cdk-insights 1.41.1 → 1.41.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -363,9 +363,9 @@ Acknowledgements cascade to descendant constructs, so scope them as narrowly as
363
363
 
364
364
  | Plan | Price | What's Included |
365
365
  |------|-------|-----------------|
366
- | **Free** | £0 forever | Static analysis (100+ rules), JSON/Table/Markdown/SARIF output, multi-stack analysis, CLI access |
367
- | **Pro** | £9.99/mo | Everything in Free + AI analysis (Bedrock), GitHub integration, dashboard, PDF reports, 10,000 resources/mo |
368
- | **Team** | £7.99/member/mo | Everything in Pro + team management, shared configs, audit trails, 15,000 resources/member |
366
+ | **Free** | £0 forever | Static analysis (100+ rules), JSON/Table/Markdown/SARIF output, multi-stack analysis, CLI access. Sign up for a free account to add **500 AI insights/month**. |
367
+ | **Pro** | £9.99/mo | Everything in Free + AI analysis (Bedrock), GitHub integration, dashboard, PDF reports, **5,000 AI insights/month** |
368
+ | **Team** | £12.99/seat/mo (2-seat minimum) | Everything in Pro + team management, shared configs, audit trails, **10,000 AI insights per seat** |
369
369
 
370
370
  Static analysis is **free forever** — no trial, no credit card, no signup required.
371
371
 
package/dist/entry.js CHANGED
@@ -174,7 +174,7 @@ ${gt.primary.bold(`${Xt.rocket} ${s}`)}`),console.log(`${gt.comment("\u2500".rep
174
174
  ${gt.primary.bold(`${Xt.chart} Analysis Complete!`)}`),console.log(gt.comment("\u2500".repeat(50))),console.log(gt.success(`\u2705 Completed: ${n}`)),i>0&&console.log(gt.error(`\u274C Failed: ${i}`)),o>0&&console.log(gt.warning(`\u23F0 Timed out: ${o}`)),console.log(gt.comment(`\u23F1\uFE0F Total time: ${y}s`))}}}createSpinner(e){let s=Dm({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
  ${gt.primary.bold(`${Xt.chart} Analysis Summary`)}`),console.log(gt.comment("\u2500".repeat(40))),console.log(gt.text(`Completed ${e.length} step${e.length===1?"":"s"} successfully!`))}header(e){console.log(`
176
176
  ${gt.primary.bold(`${Xt.rocket} ${e}`)}`),console.log(`${gt.comment("\u2500".repeat(60))}
177
- `)}section(e,s=Xt.info){console.log(gt.primary.bold(`${s} ${e}`))}success(e,s=Xt.success){console.log(gt.success(`${s} ${e}`))}info(e,s=Xt.info){console.log(gt.info(`${s} ${e}`))}warning(e,s=Xt.warning){console.log(gt.warning(`${s} ${e}`))}error(e,s=Xt.error){console.log(gt.error(`${s} ${e}`))}comment(e,s=""){console.log(gt.comment(`${s} ${e}`))}phase1(e){console.log(gt.info(`${Xt.phase1} Phase 1: ${e}`))}phase2(e){console.log(gt.primary(`${Xt.phase2} Phase 2: ${e}`))}phase3(e){console.log(gt.secondary(`${Xt.phase3} Phase 3: ${e}`))}severityBadge(e){switch(e.toUpperCase()){case"CRITICAL":return gt.severity.critical.bold(`${Xt.critical} CRITICAL`);case"HIGH":return gt.severity.high.bold(`${Xt.high} HIGH`);case"MEDIUM":return gt.severity.medium.bold(`${Xt.medium} MEDIUM`);case"LOW":return gt.severity.low.bold(`${Xt.low} LOW`);default:return gt.comment(e)}}divider(){console.log(gt.comment("\u2500".repeat(60)))}newline(){console.log("")}clearLine(){process.stdout.write(`\r${" ".repeat(process.stdout.columns)}\r`)}},Am=_S.getInstance()});var P8,L8=D(()=>{"use strict";P8=t=>t&&(t.Name||t.ResourceName||t.FunctionName)||"Unnamed"});var TS,O8,PS,M8=D(()=>{"use strict";dt();TS=null,O8=t=>{TS=t},PS=()=>{if(TS&&!process.env.CI)try{TS.saveToDisk(),ie.info("\u{1F4BE} Cache saved to disk on exit")}catch(t){ie.warn("\u26A0\uFE0F Could not save cache on exit",{error:t instanceof Error?t.message:String(t)})}};process.on("exit",PS);process.on("SIGINT",()=>{PS(),process.exit(0)});process.on("SIGTERM",()=>{PS(),process.exit(0)})});var Dee,Aee,wm,wee,Eee,Ree,Iee,B8,N8=D(()=>{"use strict";lS();JM();sS();yl();om();s8();hS();FS();dt();Qn();L8();M8();Dee={maxConcurrent:hl.DEFAULT_MAX_CONCURRENT,retryAttempts:hl.DEFAULT_RETRY_ATTEMPTS,retryDelay:hl.DEFAULT_RETRY_DELAY_MS,timeoutMs:hl.DEFAULT_TIMEOUT_MS},Aee=t=>{if(!(t instanceof Error))return!1;let e=t.message??"";return e.startsWith("Polling timed out")||e==="Analysis timeout"||e.toLowerCase().includes("timeout")},wm=(t,e)=>{let s=t.match(/^(.+?)(\s\([^)]+\))?$/);if(!s)return t;let[,n,r=""]=s;return`${Pc(e,n)}${r}`},wee=t=>{let e=dl({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 Aee(s)?{status:"timeout",redactedId:n}:(e.set(i,o+1),o>t.retryAttempts?{status:"skipped",redactedId:n}:{status:"fail",redactedId:n,error:s})}},Eee=({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)||[],y=f[p];if(!y)return{status:"skipped",redactedId:p};let C=dS(p,y,i,o,[]),A=pS(C),w=e[p];if(!w)return{status:"skipped",redactedId:p};let N=w,L=()=>(s[N]||(s[N]={issues:[]}),s[N]),R=c.get(A);if(R){let k=(R.issues||[]).map(x=>({...x,resource:N,resourceId:N})),K=L();return K.issues.push(...na({existing:K.issues,incoming:k})),K.resourceName=R.resourceName,{status:"success",redactedId:p,resourceKey:N,remappedIssues:k,resourceName:R.resourceName}}let H=Pc(a,w),B=Pc("cdk-insights-stack",a),S=im(w,l,u),U={dependencies:S.dependencies.map(k=>wm(k,a)),dependents:S.dependents.map(k=>wm(k,a)),usageDescription:S.usageDescription};for(let k=1;k<=r.retryAttempts;k++)try{let K=await Promise.race([t(B,H,y,y.Type,i,o,h,g,U,d),new Promise((Y,J)=>setTimeout(()=>J(new Error("Analysis timeout")),r.timeoutMs))]);K.resourceId=N;let x=(K.issues||[]).map(Y=>({...Y,resource:N,resourceId:N})),v=L();return v.issues.push(...na({existing:v.issues,incoming:x})),v.resourceName=K.resourceName,c.set(A,K,C),{status:"success",redactedId:p,resourceKey:N,remappedIssues:x,resourceName:K.resourceName}}catch(K){if(k===r.retryAttempts)return n({analysisError:K,redactedId:p});await new Promise(x=>setTimeout(x,r.retryDelay*2**(k-1)))}return{status:"fail",redactedId:p,error:new Error("Max retries exceeded")}},Ree=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)},Iee=10,B8=({analyzeResource:t,analyzeResourcesBatch:e,redactResources:s,config:n=Dee})=>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:y,mapping:b}=s(i),C=r8(a,b,c),A=new Map;for(let X of C){let re=A.get(X.resourceId);re?re.push(X):A.set(X.resourceId,[X])}let w=Object.keys(y),N=w.length,L=ta(i),R=new ym({ttl:d?.ttl||6*60*60*1e3,maxSize:d?.maxSize||5e3,disabled:l||!d?.enabled});O8(R);let H=wee(n),B=Eee({analyzeResource:t,redactionMapping:b,aggregatedResult:m,errorHandler:H,config:n,authToken:o,fingerprint:u,stackName:r,analysisCache:R,originalResources:i,relationships:L,aiModelId:p}),S=Am.createSingleLineProgressTracker(N,"Analyzing resources with AI"),U=Math.min(Math.max(1,Math.floor(f??1)),Iee);if(U>1&&!!e&&e){ie.debug("Batched analysis enabled",{batchSize:U,totalResources:N});let X=Pc("cdk-insights-stack",r),re=pe=>{let Ae=im(pe,L,i);return{dependencies:Ae.dependencies.map(we=>wm(we,r)),dependents:Ae.dependents.map(we=>wm(we,r)),usageDescription:Ae.usageDescription}};for(let pe=0;pe<w.length;pe+=U){let Ae=w.slice(pe,pe+U),we=async()=>{for(let z of Ae){let ae=await B({redactedId:z,redactedResources:y,findingsByResource:A,progressTracker:S});switch(h.processedCount++,ae.status){case"success":h.successCount++;break;case"timeout":h.timeoutCount++,g.push({redactedId:z,resourceData:y[z],resourceType:y[z].Type,existingFindings:A.get(z)||[]});break;case"fail":case"skipped":h.failureCount++;break}}},ue=new Map,Re=[];for(let z of Ae){let ae=y[z],q=b[z];if(!ae||!q){h.processedCount++,h.failureCount++;continue}let _=dS(z,ae,o,u,[]),le=pS(_),F=R.get(le);if(F){let ye=(F.issues||[]).map(I=>({...I,resource:q,resourceId:q}));m[q]||(m[q]={issues:[]});let Se=m[q];Se.issues.push(...na({existing:Se.issues,incoming:ye})),Se.resourceName=F.resourceName,h.processedCount++,h.successCount++;continue}let te=Pc(r,q);ue.set(te,{redactedId:z,originalResourceId:q,cacheKey:le,cacheComponents:_}),Re.push({stableResourceId:te,resourceData:ae,resourceType:ae.Type,context:re(q),existingFindings:A.get(z)||[]})}if(Re.length!==0)try{let z=await Promise.race([e(X,Re,o,u,p),new Promise((ae,q)=>setTimeout(()=>q(new Error("Analysis timeout")),n.timeoutMs))]);for(let[ae,q]of ue){let _=z.get(ae);if(h.processedCount++,!_){ie.warn(`Batched response missing entry for resource ${q.originalResourceId}`,{stableResourceId:ae,redactedId:q.redactedId}),h.failureCount++;continue}let le=(_.issues||[]).map(te=>({...te,resource:q.originalResourceId,resourceId:q.originalResourceId}));m[q.originalResourceId]||(m[q.originalResourceId]={issues:[]});let F=m[q.originalResourceId];F.issues.push(...na({existing:F.issues,incoming:le})),F.resourceName=_.resourceName,R.set(q.cacheKey,{resourceId:q.originalResourceId,issues:_.issues||[],resourceName:_.resourceName},q.cacheComponents),h.successCount++}}catch(z){ie.warn("Batched analysis call failed \u2014 falling back to per-resource for this chunk",{error:z instanceof Error?z.message:String(z),chunkSize:Ae.length}),await we()}}}else await Ree(w,n.maxConcurrent,async X=>{ie.debug(`Starting analysis for resource ${X}`,{redactedId:X,maxConcurrent:n.maxConcurrent});let re=await B({redactedId:X,redactedResources:y,findingsByResource:A,progressTracker:S});switch(h.processedCount++,ie.debug(`Resource ${X} analysis result: ${re.status}`,{redactedId:X,status:re.status,hasProgressTracker:!!S}),re.status){case"success":h.successCount++,ie.debug(`Resource ${X} completed successfully`,{redactedId:X,resourceKey:re.resourceKey});break;case"timeout":h.timeoutCount++,ie.warn(`Resource ${X} timed out`,{redactedId:X}),g.push({redactedId:X,resourceData:y[X],resourceType:y[X].Type,existingFindings:A.get(X)||[]});break;case"fail":case"skipped":h.failureCount++,ie.warn(`Resource ${X} failed or was skipped`,{redactedId:X,status:re.status});break}});let K=Date.now()-h.startTime,x=S.getStats();if(ie.debug("Analysis completed with progress tracker stats",{progressTrackerStats:x,performanceMetrics:h,totalTime:K,totalResources:N,maxConcurrent:n.maxConcurrent}),P.analysisComplete(K,h.successCount,h.failureCount,h.timeoutCount),h.failureCount>0||h.timeoutCount>0){P.newline(),P.info("\u{1F4CA} Performance Analysis:");let X=h.successCount>0?Math.round(K/1e3/h.successCount):0;P.comment(` \u23F1\uFE0F Average completion time: ${X}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 X of g){if(P.comment(` \u274C ${X.resourceType}: ${X.redactedId}`),X.resourceData?.Properties){let pe=X.resourceData.Properties,Ae=P8(pe);P.comment(` \u{1F4DD} Name: ${Ae}`)}X.existingFindings.length>0&&P.comment(` \u{1F50D} Existing findings: ${X.existingFindings.length}`),X.resourceData?.Metadata&&P.comment(" \u{1F4CD} Has metadata: Yes"),["AWS::CloudFormation::Stack","AWS::Serverless::Application","AWS::ECS::Service"].includes(X.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)),Y=new Set(Object.values(b)),J=Array.from(Y).filter(X=>!v.has(X)||!m[X]?.issues?.length);if(J.length>0){let X=R.getCachedResultsForResources(J),re=0;for(let[pe,Ae]of Array.from(X.entries())){if(m[pe]?.issues?.length>0)continue;let we=(Ae.issues||[]).map(ue=>({...ue,resource:pe,resourceId:pe}));we.length>0&&(m[pe]||(m[pe]={issues:[]}),m[pe].issues.push(...we),m[pe].resourceName=Ae.resourceName,re+=we.length)}re>0}return m}});var W8,kee,$8,_ee,Fee,LS,Oc,Mc,j8,U8,Tee,Pee,Lee,Bc,Em=D(()=>{"use strict";W8="1.41.1",kee={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/"},$8=t=>t.toLowerCase().replace(/[^\w\s-]/g,"").trim().replace(/\s+/g,"-").replace(/-+/g,"-"),_ee=(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},Fee=t=>t?t.split(`
177
+ `)}section(e,s=Xt.info){console.log(gt.primary.bold(`${s} ${e}`))}success(e,s=Xt.success){console.log(gt.success(`${s} ${e}`))}info(e,s=Xt.info){console.log(gt.info(`${s} ${e}`))}warning(e,s=Xt.warning){console.log(gt.warning(`${s} ${e}`))}error(e,s=Xt.error){console.log(gt.error(`${s} ${e}`))}comment(e,s=""){console.log(gt.comment(`${s} ${e}`))}phase1(e){console.log(gt.info(`${Xt.phase1} Phase 1: ${e}`))}phase2(e){console.log(gt.primary(`${Xt.phase2} Phase 2: ${e}`))}phase3(e){console.log(gt.secondary(`${Xt.phase3} Phase 3: ${e}`))}severityBadge(e){switch(e.toUpperCase()){case"CRITICAL":return gt.severity.critical.bold(`${Xt.critical} CRITICAL`);case"HIGH":return gt.severity.high.bold(`${Xt.high} HIGH`);case"MEDIUM":return gt.severity.medium.bold(`${Xt.medium} MEDIUM`);case"LOW":return gt.severity.low.bold(`${Xt.low} LOW`);default:return gt.comment(e)}}divider(){console.log(gt.comment("\u2500".repeat(60)))}newline(){console.log("")}clearLine(){process.stdout.write(`\r${" ".repeat(process.stdout.columns)}\r`)}},Am=_S.getInstance()});var P8,L8=D(()=>{"use strict";P8=t=>t&&(t.Name||t.ResourceName||t.FunctionName)||"Unnamed"});var TS,O8,PS,M8=D(()=>{"use strict";dt();TS=null,O8=t=>{TS=t},PS=()=>{if(TS&&!process.env.CI)try{TS.saveToDisk(),ie.info("\u{1F4BE} Cache saved to disk on exit")}catch(t){ie.warn("\u26A0\uFE0F Could not save cache on exit",{error:t instanceof Error?t.message:String(t)})}};process.on("exit",PS);process.on("SIGINT",()=>{PS(),process.exit(0)});process.on("SIGTERM",()=>{PS(),process.exit(0)})});var Dee,Aee,wm,wee,Eee,Ree,Iee,B8,N8=D(()=>{"use strict";lS();JM();sS();yl();om();s8();hS();FS();dt();Qn();L8();M8();Dee={maxConcurrent:hl.DEFAULT_MAX_CONCURRENT,retryAttempts:hl.DEFAULT_RETRY_ATTEMPTS,retryDelay:hl.DEFAULT_RETRY_DELAY_MS,timeoutMs:hl.DEFAULT_TIMEOUT_MS},Aee=t=>{if(!(t instanceof Error))return!1;let e=t.message??"";return e.startsWith("Polling timed out")||e==="Analysis timeout"||e.toLowerCase().includes("timeout")},wm=(t,e)=>{let s=t.match(/^(.+?)(\s\([^)]+\))?$/);if(!s)return t;let[,n,r=""]=s;return`${Pc(e,n)}${r}`},wee=t=>{let e=dl({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 Aee(s)?{status:"timeout",redactedId:n}:(e.set(i,o+1),o>t.retryAttempts?{status:"skipped",redactedId:n}:{status:"fail",redactedId:n,error:s})}},Eee=({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)||[],y=f[p];if(!y)return{status:"skipped",redactedId:p};let C=dS(p,y,i,o,[]),A=pS(C),w=e[p];if(!w)return{status:"skipped",redactedId:p};let N=w,L=()=>(s[N]||(s[N]={issues:[]}),s[N]),R=c.get(A);if(R){let k=(R.issues||[]).map(x=>({...x,resource:N,resourceId:N})),K=L();return K.issues.push(...na({existing:K.issues,incoming:k})),K.resourceName=R.resourceName,{status:"success",redactedId:p,resourceKey:N,remappedIssues:k,resourceName:R.resourceName}}let H=Pc(a,w),B=Pc("cdk-insights-stack",a),S=im(w,l,u),U={dependencies:S.dependencies.map(k=>wm(k,a)),dependents:S.dependents.map(k=>wm(k,a)),usageDescription:S.usageDescription};for(let k=1;k<=r.retryAttempts;k++)try{let K=await Promise.race([t(B,H,y,y.Type,i,o,h,g,U,d),new Promise((Y,J)=>setTimeout(()=>J(new Error("Analysis timeout")),r.timeoutMs))]);K.resourceId=N;let x=(K.issues||[]).map(Y=>({...Y,resource:N,resourceId:N})),v=L();return v.issues.push(...na({existing:v.issues,incoming:x})),v.resourceName=K.resourceName,c.set(A,K,C),{status:"success",redactedId:p,resourceKey:N,remappedIssues:x,resourceName:K.resourceName}}catch(K){if(k===r.retryAttempts)return n({analysisError:K,redactedId:p});await new Promise(x=>setTimeout(x,r.retryDelay*2**(k-1)))}return{status:"fail",redactedId:p,error:new Error("Max retries exceeded")}},Ree=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)},Iee=10,B8=({analyzeResource:t,analyzeResourcesBatch:e,redactResources:s,config:n=Dee})=>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:y,mapping:b}=s(i),C=r8(a,b,c),A=new Map;for(let X of C){let re=A.get(X.resourceId);re?re.push(X):A.set(X.resourceId,[X])}let w=Object.keys(y),N=w.length,L=ta(i),R=new ym({ttl:d?.ttl||6*60*60*1e3,maxSize:d?.maxSize||5e3,disabled:l||!d?.enabled});O8(R);let H=wee(n),B=Eee({analyzeResource:t,redactionMapping:b,aggregatedResult:m,errorHandler:H,config:n,authToken:o,fingerprint:u,stackName:r,analysisCache:R,originalResources:i,relationships:L,aiModelId:p}),S=Am.createSingleLineProgressTracker(N,"Analyzing resources with AI"),U=Math.min(Math.max(1,Math.floor(f??1)),Iee);if(U>1&&!!e&&e){ie.debug("Batched analysis enabled",{batchSize:U,totalResources:N});let X=Pc("cdk-insights-stack",r),re=pe=>{let Ae=im(pe,L,i);return{dependencies:Ae.dependencies.map(we=>wm(we,r)),dependents:Ae.dependents.map(we=>wm(we,r)),usageDescription:Ae.usageDescription}};for(let pe=0;pe<w.length;pe+=U){let Ae=w.slice(pe,pe+U),we=async()=>{for(let z of Ae){let ae=await B({redactedId:z,redactedResources:y,findingsByResource:A,progressTracker:S});switch(h.processedCount++,ae.status){case"success":h.successCount++;break;case"timeout":h.timeoutCount++,g.push({redactedId:z,resourceData:y[z],resourceType:y[z].Type,existingFindings:A.get(z)||[]});break;case"fail":case"skipped":h.failureCount++;break}}},ue=new Map,Re=[];for(let z of Ae){let ae=y[z],q=b[z];if(!ae||!q){h.processedCount++,h.failureCount++;continue}let _=dS(z,ae,o,u,[]),le=pS(_),F=R.get(le);if(F){let ye=(F.issues||[]).map(I=>({...I,resource:q,resourceId:q}));m[q]||(m[q]={issues:[]});let Se=m[q];Se.issues.push(...na({existing:Se.issues,incoming:ye})),Se.resourceName=F.resourceName,h.processedCount++,h.successCount++;continue}let te=Pc(r,q);ue.set(te,{redactedId:z,originalResourceId:q,cacheKey:le,cacheComponents:_}),Re.push({stableResourceId:te,resourceData:ae,resourceType:ae.Type,context:re(q),existingFindings:A.get(z)||[]})}if(Re.length!==0)try{let z=await Promise.race([e(X,Re,o,u,p),new Promise((ae,q)=>setTimeout(()=>q(new Error("Analysis timeout")),n.timeoutMs))]);for(let[ae,q]of ue){let _=z.get(ae);if(h.processedCount++,!_){ie.warn(`Batched response missing entry for resource ${q.originalResourceId}`,{stableResourceId:ae,redactedId:q.redactedId}),h.failureCount++;continue}let le=(_.issues||[]).map(te=>({...te,resource:q.originalResourceId,resourceId:q.originalResourceId}));m[q.originalResourceId]||(m[q.originalResourceId]={issues:[]});let F=m[q.originalResourceId];F.issues.push(...na({existing:F.issues,incoming:le})),F.resourceName=_.resourceName,R.set(q.cacheKey,{resourceId:q.originalResourceId,issues:_.issues||[],resourceName:_.resourceName},q.cacheComponents),h.successCount++}}catch(z){ie.warn("Batched analysis call failed \u2014 falling back to per-resource for this chunk",{error:z instanceof Error?z.message:String(z),chunkSize:Ae.length}),await we()}}}else await Ree(w,n.maxConcurrent,async X=>{ie.debug(`Starting analysis for resource ${X}`,{redactedId:X,maxConcurrent:n.maxConcurrent});let re=await B({redactedId:X,redactedResources:y,findingsByResource:A,progressTracker:S});switch(h.processedCount++,ie.debug(`Resource ${X} analysis result: ${re.status}`,{redactedId:X,status:re.status,hasProgressTracker:!!S}),re.status){case"success":h.successCount++,ie.debug(`Resource ${X} completed successfully`,{redactedId:X,resourceKey:re.resourceKey});break;case"timeout":h.timeoutCount++,ie.warn(`Resource ${X} timed out`,{redactedId:X}),g.push({redactedId:X,resourceData:y[X],resourceType:y[X].Type,existingFindings:A.get(X)||[]});break;case"fail":case"skipped":h.failureCount++,ie.warn(`Resource ${X} failed or was skipped`,{redactedId:X,status:re.status});break}});let K=Date.now()-h.startTime,x=S.getStats();if(ie.debug("Analysis completed with progress tracker stats",{progressTrackerStats:x,performanceMetrics:h,totalTime:K,totalResources:N,maxConcurrent:n.maxConcurrent}),P.analysisComplete(K,h.successCount,h.failureCount,h.timeoutCount),h.failureCount>0||h.timeoutCount>0){P.newline(),P.info("\u{1F4CA} Performance Analysis:");let X=h.successCount>0?Math.round(K/1e3/h.successCount):0;P.comment(` \u23F1\uFE0F Average completion time: ${X}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 X of g){if(P.comment(` \u274C ${X.resourceType}: ${X.redactedId}`),X.resourceData?.Properties){let pe=X.resourceData.Properties,Ae=P8(pe);P.comment(` \u{1F4DD} Name: ${Ae}`)}X.existingFindings.length>0&&P.comment(` \u{1F50D} Existing findings: ${X.existingFindings.length}`),X.resourceData?.Metadata&&P.comment(" \u{1F4CD} Has metadata: Yes"),["AWS::CloudFormation::Stack","AWS::Serverless::Application","AWS::ECS::Service"].includes(X.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)),Y=new Set(Object.values(b)),J=Array.from(Y).filter(X=>!v.has(X)||!m[X]?.issues?.length);if(J.length>0){let X=R.getCachedResultsForResources(J),re=0;for(let[pe,Ae]of Array.from(X.entries())){if(m[pe]?.issues?.length>0)continue;let we=(Ae.issues||[]).map(ue=>({...ue,resource:pe,resourceId:pe}));we.length>0&&(m[pe]||(m[pe]={issues:[]}),m[pe].issues.push(...we),m[pe].resourceName=Ae.resourceName,re+=we.length)}re>0}return m}});var W8,kee,$8,_ee,Fee,LS,Oc,Mc,j8,U8,Tee,Pee,Lee,Bc,Em=D(()=>{"use strict";W8="1.41.2",kee={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/"},$8=t=>t.toLowerCase().replace(/[^\w\s-]/g,"").trim().replace(/\s+/g,"-").replace(/-+/g,"-"),_ee=(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},Fee=t=>t?t.split(`
178
178
  `).map(e=>e.trim()).filter(Boolean).join(`
179
179
  `):"",LS=t=>{let e=`- **Issue:** ${t.issue}`;return t.recommendation&&(e+=`
180
180
  - **Recommendation:** ${Fee(t.recommendation)}`),t.context&&(t.context.property&&(e+=`
@@ -296,7 +296,7 @@ ${o}`)}});var Z8,Y8,J8=D(()=>{"use strict";Z8=require("node:child_process"),Y8=(
296
296
  `)}catch(a){console.error("Failed to write GitHub outputs:",a)}}});var km,f4,m4=D(()=>{"use strict";dt();km=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"}},f4=(t,e)=>{Me.info(`
297
297
  \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}
298
298
  `),Me.info("Severity Breakdown:"),Me.info(` ${km("CRITICAL")} Critical: ${e.severityCounts.CRITICAL}`),Me.info(` ${km("HIGH")} High: ${e.severityCounts.HIGH}`),Me.info(` ${km("MEDIUM")} Medium: ${e.severityCounts.MEDIUM}`),Me.info(` ${km("LOW")} Low: ${e.severityCounts.LOW}
299
- `),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 Xee,ete,tte,h4,El,US=D(()=>{"use strict";Xee=u0(),ete=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"}},tte=(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}`:""},h4={CRITICAL:4,HIGH:3,MEDIUM:2,LOW:1},El=t=>{let e=new Xee({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=tte(i,n);s.push({issue:i,group:n,service:o,sourceLocation:a})}}s.sort((n,r)=>{let i=h4[n.issue.severity]||0;return(h4[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",`${ete(n.severity)} ${n.severity}`,i,n.issue,o||n.locationHint||""]);console.log(e.toString())}});var Rl=M((B_e,ste)=>{ste.exports={name:"cdk-insights",version:"1.41.1",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-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","aws-cdk-lib":"^2.190.0","cdk-nag":"^2.35.73",constructs:"^10.4.2"},peerDependenciesMeta:{"@aws-solutions-constructs/aws-apigateway-lambda":{optional:!0},"@aws-solutions-constructs/aws-lambda-stepfunctions":{optional:!0},"@aws-solutions-constructs/aws-s3-lambda":{optional:!0}}}});var y4,nte,g4,rte,x4,b4=D(()=>{"use strict";y4=oe(require("node:fs"));dt();yl();({version:nte}=Rl()),g4={CRITICAL:0,HIGH:1,MEDIUM:2,LOW:3},rte=(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)=>g4[c.severity]-g4[u.severity]),a=bm(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:nte,summary:e,recommendations:n}},x4=(t,e,s)=>{let n=rte(t,e,s),r=`${t}_analysis_report.json`;try{y4.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 ite,ote,S4,_m,ate,HS=D(()=>{"use strict";({version:ite}=Rl()),ote=t=>{switch(t){case"CRITICAL":case"HIGH":return"error";case"MEDIUM":return"warning";default:return"note"}},S4=t=>{switch(t){case"CRITICAL":return 9;case"HIGH":return 7;case"MEDIUM":return 4;case"LOW":return 2;default:return 1}},_m=(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=ate(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":S4(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:ote(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":S4(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:ite,informationUri:"https://cdkinsights.dev",rules:s}},results:n}]}},ate=t=>{let e=t.issue.toLowerCase().replace(/[^a-z0-9]+/g,"-").slice(0,50);return`CDK-${t.severity}-${e}`}});var GS,v4,C4=D(()=>{"use strict";GS=oe(require("node:fs"));dt();Em();m4();US();b4();HS();jS();v4=(t,e,s,n,r)=>{switch(Me.info(`Generating output in format: ${t}`),t){case"markdown":{let i=Bc(e,s,r,n),o=`${e}_analysis_report.md`;try{GS.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":{El(s);break}case"json":{let i=x4(e,r,s);process.stdout.write(`${JSON.stringify(i,null,2)}
299
+ `),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 Xee,ete,tte,h4,El,US=D(()=>{"use strict";Xee=u0(),ete=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"}},tte=(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}`:""},h4={CRITICAL:4,HIGH:3,MEDIUM:2,LOW:1},El=t=>{let e=new Xee({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=tte(i,n);s.push({issue:i,group:n,service:o,sourceLocation:a})}}s.sort((n,r)=>{let i=h4[n.issue.severity]||0;return(h4[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",`${ete(n.severity)} ${n.severity}`,i,n.issue,o||n.locationHint||""]);console.log(e.toString())}});var Rl=M((B_e,ste)=>{ste.exports={name:"cdk-insights",version:"1.41.2",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-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","aws-cdk-lib":"^2.190.0","cdk-nag":"^2.35.73",constructs:"^10.4.2"},peerDependenciesMeta:{"@aws-solutions-constructs/aws-apigateway-lambda":{optional:!0},"@aws-solutions-constructs/aws-lambda-stepfunctions":{optional:!0},"@aws-solutions-constructs/aws-s3-lambda":{optional:!0}}}});var y4,nte,g4,rte,x4,b4=D(()=>{"use strict";y4=oe(require("node:fs"));dt();yl();({version:nte}=Rl()),g4={CRITICAL:0,HIGH:1,MEDIUM:2,LOW:3},rte=(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)=>g4[c.severity]-g4[u.severity]),a=bm(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:nte,summary:e,recommendations:n}},x4=(t,e,s)=>{let n=rte(t,e,s),r=`${t}_analysis_report.json`;try{y4.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 ite,ote,S4,_m,ate,HS=D(()=>{"use strict";({version:ite}=Rl()),ote=t=>{switch(t){case"CRITICAL":case"HIGH":return"error";case"MEDIUM":return"warning";default:return"note"}},S4=t=>{switch(t){case"CRITICAL":return 9;case"HIGH":return 7;case"MEDIUM":return 4;case"LOW":return 2;default:return 1}},_m=(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=ate(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":S4(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:ote(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":S4(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:ite,informationUri:"https://cdkinsights.dev",rules:s}},results:n}]}},ate=t=>{let e=t.issue.toLowerCase().replace(/[^a-z0-9]+/g,"-").slice(0,50);return`CDK-${t.severity}-${e}`}});var GS,v4,C4=D(()=>{"use strict";GS=oe(require("node:fs"));dt();Em();m4();US();b4();HS();jS();v4=(t,e,s,n,r)=>{switch(Me.info(`Generating output in format: ${t}`),t){case"markdown":{let i=Bc(e,s,r,n),o=`${e}_analysis_report.md`;try{GS.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":{El(s);break}case"json":{let i=x4(e,r,s);process.stdout.write(`${JSON.stringify(i,null,2)}
300
300
  `);break}case"sarif":{let i=_m(e,s),o=`${e}_analysis_report.sarif`;try{GS.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":{Im(e,s,r.severityCounts,r.totalResources);break}default:f4(e,r);break}}});var Fm,D4=D(()=>{"use strict";Fm=(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,w4,E4=D(()=>{"use strict";A4=oe(require("node:crypto")),w4=t=>A4.createHash("sha256").update(JSON.stringify(t)).digest("hex")});var Tm,cte,ute,zS,qS=D(()=>{"use strict";Tm=(t,e)=>e.endsWith("*")?t.startsWith(e.slice(0,-1)):t===e,cte=(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},ute=(t,e,s)=>!t.ruleId||s.length===0||e.length===0?!1:s.some(n=>n.ruleId===t.ruleId&&e.some(r=>cte(r,n.constructPath))),zS=(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=>Tm(c,a)))||t.ruleId&&n.some(c=>Tm(t.ruleId,c))?!0:ute(t,e,i)}});var lte,dte,pte,fte,R4,I4=D(()=>{"use strict";lte=[/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],dte=[/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],pte=t=>lte.some(e=>e.test(t)),fte=t=>dte.some(e=>e.test(t)),R4=(t,e=!1)=>t.filter(s=>{let n=s.issue||"";return!(pte(n)||e&&fte(n))})});var k4,_4=D(()=>{"use strict";dt();yl();I4();k4=({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,y=R4(g,m.isGenerated).map(C=>{switch(C.severity||(Me.debug(`AI recommendation missing severity for resource '${f}', defaulting to MEDIUM`),C.severity="MEDIUM"),C.severity.toUpperCase()==="CRITICAL"&&(Me.debug(`Capping AI finding from CRITICAL \u2192 HIGH for resource '${f}' (AI findings are advisory)`),C.severity="HIGH"),C.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 '${C.severity}' for resource '${f}', defaulting to MEDIUM`),C.severity="MEDIUM",u++;break}return{resourceName:C.resourceName||m.resourceName,resourceId:f,friendlyName:m.friendlyName,displayName:m.displayName,locationHint:C.locationHint||m.locationHint,constructPath:m.cdkPath,githubUrl:m.githubUrl,docUrl:m.docUrl,issue:C.issue||"AI analysis issue",recommendation:C.recommendation||"No specific recommendation provided",severity:C.severity,wafPillar:(()=>{if(C.wafPillar)switch(C.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:C.codeSnippet||"",foundBy:C.foundBy??"cdkInsights"}}),b=bm(y,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 Pm,KS,mte,hte,VS=D(()=>{"use strict";Pm=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},KS=(t,e=!1)=>{if(t.length<16||mte(t)||Pm(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},mte=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!!hte(t)},hte=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 ZS,YS,gte,yte,xte,bte,F4,T4,JS,QS,XS,ev,Lm,tv,sv=D(()=>{"use strict";ZS=[/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],YS=[/^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_-]+$/],gte=[/\{\{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*:/],yte=[/^<[^>]+>$/,/^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],xte=[/^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],bte=[/(?:^|\.)Targets\[\d+\]\.Input$/,/(?:^|\.)Create$/,/(?:^|\.)Update$/,/(?:^|\.)Delete$/,/(?:^|\.)DefinitionString$/,/(?:^|\.)Code\.ZipFile$/,/(?:^|\.)Statement\[\d+\]\.Resource$/,/(?:^|\.)Statement\[\d+\]\.Resource\[\d+\]$/,/(?:^|\.)Statement\[\d+\]\.Sid$/],F4=t=>xte.some(e=>e.test(t)),T4=t=>bte.some(e=>e.test(t)),JS=t=>ZS.some(e=>e.test(t)),QS=t=>YS.some(e=>e.test(t)),XS=t=>gte.some(e=>e.test(t)),ev=t=>yte.some(e=>e.test(t)),Lm=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])},tv=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 Il,kl,nv=D(()=>{"use strict";Il=t=>{let e={api_key:`Use AWS Secrets Manager to store API keys securely:
301
301
 
302
302
  // CDK TypeScript example:
@@ -458,7 +458,7 @@ See: https://docs.aws.amazon.com/secretsmanager/latest/userguide/intro.html`},kl
458
458
  `,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 l5=M((TTe,u5)=>{"use strict";var wre=ih(),{MAX_LENGTH:o5,CHAR_BACKSLASH:Kv,CHAR_BACKTICK:Ere,CHAR_COMMA:Rre,CHAR_DOT:Ire,CHAR_LEFT_PARENTHESES:kre,CHAR_RIGHT_PARENTHESES:_re,CHAR_LEFT_CURLY_BRACE:Fre,CHAR_RIGHT_CURLY_BRACE:Tre,CHAR_LEFT_SQUARE_BRACKET:a5,CHAR_RIGHT_SQUARE_BRACKET:c5,CHAR_DOUBLE_QUOTE:Pre,CHAR_SINGLE_QUOTE:Lre,CHAR_NO_BREAK_SPACE:Ore,CHAR_ZERO_WIDTH_NOBREAK_SPACE:Mre}=i5(),Bre=(t,e={})=>{if(typeof t!="string")throw new TypeError("Expected a string");let s=e||{},n=typeof s.maxLength=="number"?Math.min(o5,s.maxLength):o5;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===Mre||p===Ore)){if(p===Kv){m({type:"text",value:(e.keepEscaping?p:"")+f()});continue}if(p===c5){m({type:"text",value:"\\"+p});continue}if(p===a5){c++;let g;for(;l<u&&(g=f());){if(p+=g,g===a5){c++;continue}if(g===Kv){p+=f();continue}if(g===c5&&(c--,c===0))break}m({type:"text",value:p});continue}if(p===kre){o=m({type:"paren",nodes:[]}),i.push(o),m({type:"text",value:p});continue}if(p===_re){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===Pre||p===Lre||p===Ere){let g=p,h;for(e.keepQuotes!==!0&&(p="");l<u&&(h=f());){if(h===Kv){p+=h+f();continue}if(h===g){e.keepQuotes===!0&&(p+=h);break}p+=h}m({type:"text",value:p});continue}if(p===Fre){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===Tre){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===Rre&&d>0){if(o.ranges>0){o.ranges=0;let g=o.nodes.shift();o.nodes=[g,{type:"text",value:wre(o)}]}m({type:"comma",value:p}),o.commas++;continue}if(p===Ire&&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(y=>{y.nodes||(y.type==="open"&&(y.isOpen=!0),y.type==="close"&&(y.isClose=!0),y.nodes||(y.type="text"),y.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};u5.exports=Bre});var f5=M((PTe,p5)=>{"use strict";var d5=ih(),Nre=e5(),$re=n5(),Wre=l5(),tn=(t,e={})=>{let s=[];if(Array.isArray(t))for(let n of t){let r=tn.create(n,e);Array.isArray(r)?s.push(...r):s.push(r)}else s=[].concat(tn.create(t,e));return e&&e.expand===!0&&e.nodupes===!0&&(s=[...new Set(s)]),s};tn.parse=(t,e={})=>Wre(t,e);tn.stringify=(t,e={})=>d5(typeof t=="string"?tn.parse(t,e):t,e);tn.compile=(t,e={})=>(typeof t=="string"&&(t=tn.parse(t,e)),Nre(t,e));tn.expand=(t,e={})=>{typeof t=="string"&&(t=tn.parse(t,e));let s=$re(t,e);return e.noempty===!0&&(s=s.filter(Boolean)),e.nodupes===!0&&(s=[...new Set(s)]),s};tn.create=(t,e={})=>t===""||t.length<3?[t]:e.expand!==!0?tn.compile(t,e):tn.expand(t,e);p5.exports=tn});var m5=M((LTe,jre)=>{jre.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 g5=M((OTe,h5)=>{h5.exports=m5()});var x5=M((MTe,y5)=>{"use strict";var Ure=require("path"),Hre=g5(),Gre=new Set(Hre);y5.exports=t=>Gre.has(Ure.extname(t).slice(1).toLowerCase())});var ch=M(Be=>{"use strict";var{sep:zre}=require("path"),{platform:Vv}=process,qre=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=`.${zre}`;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=Vv==="win32";Be.isMacos=Vv==="darwin";Be.isLinux=Vv==="linux";Be.isIBMi=qre.type()==="OS400"});var A5=M((NTe,D5)=>{"use strict";var Qr=require("fs"),ls=require("path"),{promisify:Ql}=require("util"),Kre=x5(),{isWindows:Vre,isLinux:Zre,EMPTY_FN:Yre,EMPTY_STR:Jre,KEY_LISTENERS:Uc,KEY_ERR:Zv,KEY_RAW:Zl,HANDLER_KEYS:Qre,EV_CHANGE:lh,EV_ADD:uh,EV_ADD_DIR:Xre,EV_ERROR:S5,STR_DATA:eie,STR_END:tie,BRACE_START:sie,STAR:nie}=ch(),rie="watch",iie=Ql(Qr.open),v5=Ql(Qr.stat),oie=Ql(Qr.lstat),aie=Ql(Qr.close),Yv=Ql(Qr.realpath),cie={lstat:oie,stat:v5},Qv=(t,e)=>{t instanceof Set?t.forEach(e):e(t)},Yl=(t,e,s)=>{let n=t[e];n instanceof Set||(t[e]=n=new Set([n])),n.add(s)},uie=t=>e=>{let s=t[e];s instanceof Set?s.clear():delete t[e]},Jl=(t,e,s)=>{let n=t[e];n instanceof Set?n.delete(s):n===s&&delete t[e]},C5=t=>t instanceof Set?t.size===0:!t,dh=new Map;function b5(t,e,s,n,r){let i=(o,a)=>{s(t),r(o,a,{watchedPath:t}),a&&t!==a&&ph(ls.resolve(t,a),Uc,ls.join(t,a))};try{return Qr.watch(t,e,i)}catch(o){n(o)}}var ph=(t,e,s,n,r)=>{let i=dh.get(t);i&&Qv(i[e],o=>{o(s,n,r)})},lie=(t,e,s,n)=>{let{listener:r,errHandler:i,rawEmitter:o}=n,a=dh.get(e),c;if(!s.persistent)return c=b5(t,s,r,i,o),c.close.bind(c);if(a)Yl(a,Uc,r),Yl(a,Zv,i),Yl(a,Zl,o);else{if(c=b5(t,s,ph.bind(null,e,Uc),i,ph.bind(null,e,Zl)),!c)return;c.on(S5,async u=>{let l=ph.bind(null,e,Zv);if(a.watcherUnusable=!0,Vre&&u.code==="EPERM")try{let d=await iie(t,"r");await aie(d),l(u)}catch{}else l(u)}),a={listeners:r,errHandlers:i,rawEmitters:o,watcher:c},dh.set(e,a)}return()=>{Jl(a,Uc,r),Jl(a,Zv,i),Jl(a,Zl,o),C5(a.listeners)&&(a.watcher.close(),dh.delete(e),Qre.forEach(uie(a)),a.watcher=void 0,Object.freeze(a))}},Jv=new Map,die=(t,e,s,n)=>{let{listener:r,rawEmitter:i}=n,o=Jv.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,Qr.unwatchFile(e),o=void 0),o?(Yl(o,Uc,r),Yl(o,Zl,i)):(o={listeners:r,rawEmitters:i,options:s,watcher:Qr.watchFile(e,s,(l,d)=>{Qv(o.rawEmitters,f=>{f(lh,e,{curr:l,prev:d})});let p=l.mtimeMs;(l.size!==d.size||p>d.mtimeMs||p===0)&&Qv(o.listeners,f=>f(t,l))})},Jv.set(e,o)),()=>{Jl(o,Uc,r),Jl(o,Zl,i),C5(o.listeners)&&(Jv.delete(e),Qr.unwatchFile(e),o.options=o.watcher=void 0,Object.freeze(o))}},Xv=class{constructor(e){this.fsw=e,this._boundHandleError=s=>e._handleError(s)}_watchWithNodeFs(e,s){let n=this.fsw.options,r=ls.dirname(e),i=ls.basename(e);this.fsw._getWatchedDir(r).add(i);let a=ls.resolve(e),c={persistent:n.persistent};s||(s=Yre);let u;return n.usePolling?(c.interval=n.enableBinaryInterval&&Kre(i)?n.binaryInterval:n.interval,u=die(e,a,c,{listener:s,rawEmitter:this.fsw._emitRaw})):u=lie(e,a,c,{listener:s,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw}),u}_handleFile(e,s,n){if(this.fsw.closed)return;let r=ls.dirname(e),i=ls.basename(e),o=this.fsw._getWatchedDir(r),a=s;if(o.has(i))return;let c=async(l,d)=>{if(this.fsw._throttle(rie,e,5)){if(!d||d.mtimeMs===0)try{let p=await v5(e);if(this.fsw.closed)return;let f=p.atimeMs,m=p.mtimeMs;(!f||f<=m||m!==a.mtimeMs)&&this.fsw._emit(lh,e,p),Zre&&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(lh,e,d),a=d}}},u=this._watchWithNodeFs(e,c);if(!(n&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(uh,e,0))return;this.fsw._emit(uh,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 Yv(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(lh,n,e.stats)):(o.add(r),this.fsw._symlinkPaths.set(i,a),this.fsw._emit(uh,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=ls.join(e,Jre),!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(eie,async d=>{if(this.fsw.closed){l=void 0;return}let p=d.path,f=ls.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=ls.join(i,ls.relative(i,f)),this._addToNodeFs(f,s,n,o+1))}}).on(S5,this._boundHandleError);return new Promise(d=>l.once(tie,()=>{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:ls.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(ls.dirname(e)),u=c.has(ls.basename(e));!(n&&this.fsw.options.ignoreInitial)&&!i&&!u&&(!o.hasGlob||o.globFilter(e))&&this.fsw._emit(Xre,e,s),c.add(ls.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 cie[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(nie)&&!e.includes(sie),l;if(c.isDirectory()){let d=ls.resolve(e),p=u?await Yv(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 Yv(e):e;if(this.fsw.closed)return;let p=ls.dirname(a.watchPath);if(this.fsw._getWatchedDir(p).add(a.watchPath),this.fsw._emit(uh,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(ls.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}}};D5.exports=Xv});var F5=M(($Te,aC)=>{"use strict";var iC=require("fs"),ds=require("path"),{promisify:oC}=require("util"),Hc;try{Hc=require("fsevents")}catch(t){process.env.CHOKIDAR_PRINT_FSEVENTS_REQUIRE_ERROR&&console.error(t)}if(Hc){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&&(Hc=void 0)}}var{EV_ADD:eC,EV_CHANGE:pie,EV_ADD_DIR:w5,EV_UNLINK:fh,EV_ERROR:fie,STR_DATA:mie,STR_END:hie,FSEVENT_CREATED:gie,FSEVENT_MODIFIED:yie,FSEVENT_DELETED:xie,FSEVENT_MOVED:bie,FSEVENT_UNKNOWN:Sie,FSEVENT_FLAG_MUST_SCAN_SUBDIRS:vie,FSEVENT_TYPE_FILE:Cie,FSEVENT_TYPE_DIRECTORY:Xl,FSEVENT_TYPE_SYMLINK:_5,ROOT_GLOBSTAR:E5,DIR_SUFFIX:Die,DOT_SLASH:R5,FUNCTION_TYPE:tC,EMPTY_FN:Aie,IDENTITY_FN:wie}=ch(),Eie=t=>isNaN(t)?{}:{depth:t},nC=oC(iC.stat),Rie=oC(iC.lstat),I5=oC(iC.realpath),Iie={stat:nC,lstat:Rie},aa=new Map,kie=10,_ie=new Set([69888,70400,71424,72704,73472,131328,131840,262912]),Fie=(t,e)=>({stop:Hc.watch(t,e)});function Tie(t,e,s,n){let r=ds.extname(e)?ds.dirname(e):e,i=ds.dirname(r),o=aa.get(r);Pie(i)&&(r=i);let a=ds.resolve(t),c=a!==e,u=(d,p,f)=>{c&&(d=d.replace(e,a)),(d===a||!d.indexOf(a+ds.sep))&&s(d,p,f)},l=!1;for(let d of aa.keys())if(e.indexOf(ds.resolve(d)+ds.sep)===0){r=d,o=aa.get(r),l=!0;break}return o||l?o.listeners.add(u):(o={listeners:new Set([u]),rawEmitter:n,watcher:Fie(r,(d,p)=>{if(!o.listeners.size||p&vie)return;let f=Hc.getInfo(d,p);o.listeners.forEach(m=>{m(d,p,f)}),o.rawEmitter(f.event,d,f)})},aa.set(r,o)),()=>{let d=o.listeners;if(d.delete(u),!d.size&&(aa.delete(r),o.watcher))return o.watcher.stop().then(()=>{o.rawEmitter=o.watcher=void 0,Object.freeze(o)})}}var Pie=t=>{let e=0;for(let s of aa.keys())if(s.indexOf(t)===0&&(e++,e>=kie))return!0;return!1},Lie=()=>Hc&&aa.size<128,sC=(t,e)=>{let s=0;for(;!t.indexOf(e)&&(t=ds.dirname(t))!==e;)s++;return s},k5=(t,e)=>t.type===Xl&&e.isDirectory()||t.type===_5&&e.isSymbolicLink()||t.type===Cie&&e.isFile(),rC=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+E5),!0;n.delete(e),n.delete(e+E5)}addOrChange(e,s,n,r,i,o,a,c){let u=i.has(o)?pie:eC;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 nC(e);if(this.fsw.closed)return;k5(a,u)?this.addOrChange(e,s,n,r,i,o,a,c):this.handleEvent(fh,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(fh,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===fh){let l=c.type===Xl;(l||o.has(a))&&this.fsw._remove(i,a,l)}else{if(e===eC){if(c.type===Xl&&this.fsw._getWatchedDir(s),c.type===_5&&u.followSymlinks){let d=u.depth===void 0?void 0:sC(n,r)+1;return this._addToFsEvents(s,!1,!0,d)}this.fsw._getWatchedDir(i).add(a)}let l=c.type===Xl?e+Die:e;this.fsw._emit(l,s),l===w5&&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=Tie(e,s,async(c,u,l)=>{if(this.fsw.closed||i.depth!==void 0&&sC(c,s)>i.depth)return;let d=n(ds.join(e,ds.relative(e,c)));if(r&&!r(d))return;let p=ds.dirname(d),f=ds.basename(d),m=this.fsw._getWatchedDir(l.type===Xl?d:p);if(_ie.has(u)||l.event===Sie)if(typeof i.ignored===tC){let g;try{g=await nC(d)}catch{}if(this.fsw.closed||this.checkIgnored(d,g))return;k5(l,g)?this.addOrChange(d,c,s,p,m,f,l,i):this.handleEvent(fh,d,c,s,p,m,f,l,i)}else this.checkExists(d,c,s,p,m,f,l,i);else switch(l.event){case gie:case yie:return this.addOrChange(d,c,s,p,m,f,l,i);case xie:case bie: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 I5(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!==R5?a=o.replace(i,e):o!==R5&&(a=ds.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(ds.dirname(o)),u=ds.basename(o);a&&this.fsw._getWatchedDir(o),!c.has(u)&&(c.add(u),(!r.ignoreInitial||i===!0)&&this.fsw._emit(a?w5:eC,o,s))}initWatch(e,s,n,r){if(this.fsw.closed)return;let i=this._watchWithFsEvents(n.watchPath,ds.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===tC?s:wie,a=this.fsw._getWatchHelpers(e);try{let c=await Iie[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),...Eie(i.depth-(r||0))}).on(mie,u=>{if(this.fsw.closed||u.stats.isDirectory()&&!a.filterPath(u))return;let l=ds.join(a.watchPath,u.path),{fullPath:d}=u;if(a.followSymlinks&&u.stats.isSymbolicLink()){let p=i.depth===void 0?void 0:sC(l,ds.resolve(a.watchPath))+1;this._handleFsEventsSymlink(l,d,o,p)}else this.emitAdd(l,u.stats,o,i,n)}).on(fie,Aie).on(hie,()=>{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===tC)this.initWatch(void 0,e,a,o);else{let c;try{c=await I5(a.watchPath)}catch{}this.initWatch(c,e,a,o)}}};aC.exports=rC;aC.exports.canUse=Lie});var U5=M(CC=>{"use strict";var{EventEmitter:Oie}=require("events"),SC=require("fs"),bt=require("path"),{promisify:N5}=require("util"),Mie=YB(),fC=wN().default,Bie=FN(),cC=jv(),Nie=f5(),$ie=$v(),Wie=A5(),T5=F5(),{EV_ALL:uC,EV_READY:jie,EV_ADD:mh,EV_CHANGE:ed,EV_UNLINK:P5,EV_ADD_DIR:Uie,EV_UNLINK_DIR:Hie,EV_RAW:Gie,EV_ERROR:lC,STR_CLOSE:zie,STR_END:qie,BACK_SLASH_RE:Kie,DOUBLE_SLASH_RE:L5,SLASH_OR_BACK_SLASH_RE:Vie,DOT_RE:Zie,REPLACER_RE:Yie,SLASH:dC,SLASH_SLASH:Jie,BRACE_START:Qie,BANG:mC,ONE_DOT:$5,TWO_DOTS:Xie,GLOBSTAR:eoe,SLASH_GLOBSTAR:pC,ANYMATCH_OPTS:hC,STRING_TYPE:vC,FUNCTION_TYPE:toe,EMPTY_STR:gC,EMPTY_FN:soe,isWindows:noe,isMacos:roe,isIBMi:ioe}=ch(),ooe=N5(SC.stat),aoe=N5(SC.readdir),yC=(t=[])=>Array.isArray(t)?t:[t],W5=(t,e=[])=>(t.forEach(s=>{Array.isArray(s)?W5(s,e):e.push(s)}),e),O5=t=>{let e=W5(yC(t));if(!e.every(s=>typeof s===vC))throw new TypeError(`Non-string provided as watch path: ${e}`);return e.map(j5)},M5=t=>{let e=t.replace(Kie,dC),s=!1;for(e.startsWith(Jie)&&(s=!0);e.match(L5);)e=e.replace(L5,dC);return s&&(e=dC+e),e},j5=t=>M5(bt.normalize(M5(t))),B5=(t=gC)=>e=>typeof e!==vC?e:j5(bt.isAbsolute(e)?e:bt.join(t,e)),coe=(t,e)=>bt.isAbsolute(t)?t:t.startsWith(mC)?mC+bt.join(e,t.slice(1)):bt.join(e,t),sr=(t,e)=>t[e]===void 0,xC=class{constructor(e,s){this.path=e,this._removeWatcher=s,this.items=new Set}add(e){let{items:s}=this;s&&e!==$5&&e!==Xie&&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 aoe(n)}catch{this._removeWatcher&&this._removeWatcher(bt.dirname(n),bt.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)}},uoe="stat",loe="lstat",bC=class{constructor(e,s,n,r){this.fsw=r,this.path=e=e.replace(Yie,gC),this.watchPath=s,this.fullWatchPath=bt.resolve(s),this.hasGlob=s!==e,e===gC&&(this.hasGlob=!1),this.globSymlink=this.hasGlob&&n?void 0:!1,this.globFilter=this.hasGlob?fC(e,void 0,hC):!1,this.dirParts=this.getDirParts(e),this.dirParts.forEach(i=>{i.length>1&&i.pop()}),this.followSymlinks=n,this.statMethod=n?uoe:loe}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 bt.join(this.watchPath,bt.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===toe?this.globFilter(n):!0)&&this.fsw._isntIgnored(n,s)&&this.fsw._hasReadPermissions(s)}getDirParts(e){if(!this.hasGlob)return[];let s=[];return(e.includes(Qie)?Nie.expand(e):[e]).forEach(r=>{s.push(bt.relative(this.watchPath,r).split(Vie))}),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===eoe&&(n=!0),n||!s[0][o]||fC(i,s[0][o],hC))))}return!this.unmatchedGlob&&this.fsw._isntIgnored(this.entryPath(e),e.stats)}},hh=class extends Oie{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,sr(s,"persistent")&&(s.persistent=!0),sr(s,"ignoreInitial")&&(s.ignoreInitial=!1),sr(s,"ignorePermissionErrors")&&(s.ignorePermissionErrors=!1),sr(s,"interval")&&(s.interval=100),sr(s,"binaryInterval")&&(s.binaryInterval=300),sr(s,"disableGlobbing")&&(s.disableGlobbing=!1),s.enableBinaryInterval=s.binaryInterval!==s.interval,sr(s,"useFsEvents")&&(s.useFsEvents=!s.usePolling),T5.canUse()||(s.useFsEvents=!1),sr(s,"usePolling")&&!s.useFsEvents&&(s.usePolling=roe),ioe&&(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)),sr(s,"atomic")&&(s.atomic=!s.usePolling&&!s.useFsEvents),s.atomic&&(this._pendingUnlinks=new Map),sr(s,"followSymlinks")&&(s.followSymlinks=!0),sr(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=yC(s.ignored));let a=0;this._emitReady=()=>{a++,a>=this._readyCount&&(this._emitReady=soe,this._readyEmitted=!0,process.nextTick(()=>this.emit(jie)))},this._emitRaw=(...c)=>this.emit(Gie,...c),this._readyEmitted=!1,this.options=s,s.useFsEvents?this._fsEventsHandler=new T5(this):this._nodeFsHandler=new Wie(this),Object.freeze(s)}add(e,s,n){let{cwd:r,disableGlobbing:i}=this.options;this.closed=!1;let o=O5(e);return r&&(o=o.map(a=>{let c=coe(a,r);return i||!cC(a)?c:$ie(c)})),o=o.filter(a=>a.startsWith(mC)?(this._ignoredPaths.add(a.slice(1)),!1):(this._ignoredPaths.delete(a),this._ignoredPaths.delete(a+pC),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(bt.dirname(c),bt.basename(s||c))})})),this}unwatch(e){if(this.closed)return this;let s=O5(e),{cwd:n}=this.options;return s.forEach(r=>{!bt.isAbsolute(r)&&!this._closers.has(r)&&(n&&(r=bt.join(n,r)),r=bt.resolve(r)),this._closePath(r),this._ignoredPaths.add(r),this._watched.has(r)&&this._ignoredPaths.add(r+pC),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?bt.relative(this.options.cwd,n):n;e[r||$5]=s.getChildren().sort()}),e}emitWithAll(e,s){this.emit(...s),e!==lC&&this.emit(uC,...s)}async _emit(e,s,n,r,i){if(this.closed)return;let o=this.options;noe&&(s=bt.normalize(s)),o.cwd&&(s=bt.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===P5)return this._pendingUnlinks.set(s,a),setTimeout(()=>{this._pendingUnlinks.forEach((l,d)=>{this.emit(...l),this.emit(uC,...l),this._pendingUnlinks.delete(d)})},typeof o.atomic=="number"?o.atomic:100),this;e===mh&&this._pendingUnlinks.has(s)&&(e=a[0]=ed,this._pendingUnlinks.delete(s))}if(c&&(e===mh||e===ed)&&this._readyEmitted){let l=(d,p)=>{d?(e=a[0]=lC,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===ed&&!this._throttle(ed,s,50))return this;if(o.alwaysStat&&n===void 0&&(e===mh||e===Uie||e===ed)){let l=o.cwd?bt.join(o.cwd,s):s,d;try{d=await ooe(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(lC,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&&!bt.isAbsolute(e)&&(o=bt.join(this.options.cwd,e));let a=new Date,c=u=>{SC.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&&Zie.test(e))return!0;if(!this._userIgnored){let{cwd:n}=this.options,r=this.options.ignored,i=r&&r.map(B5(n)),o=yC(i).filter(c=>typeof c===vC&&!cC(c)).map(c=>c+pC),a=this._getGlobIgnored().map(B5(n)).concat(i,o);this._userIgnored=fC(a,void 0,hC)}return this._userIgnored([e,s])}_isntIgnored(e,s){return!this._isIgnored(e,s)}_getWatchHelpers(e,s){let n=s||this.options.disableGlobbing||!cC(e)?e:Bie(e),r=this.options.followSymlinks;return new bC(e,n,r,this)}_getWatchedDir(e){this._boundRemove||(this._boundRemove=this._remove.bind(this));let s=bt.resolve(e);return this._watched.has(s)||this._watched.set(s,new xC(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=bt.join(e,s),i=bt.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=bt.relative(this.options.cwd,r)),this.options.awaitWriteFinish&&this._pendingWrites.has(l)&&this._pendingWrites.get(l).cancelWait()===mh)return;this._watched.delete(r),this._watched.delete(i);let d=n?Hie:P5;u&&!this._isIgnored(r)&&this._emit(d,r),this.options.useFsEvents||this._closePath(r)}_closePath(e){this._closeFile(e);let s=bt.dirname(e);this._getWatchedDir(s).remove(bt.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:uC,alwaysStat:!0,lstat:!0,...s},r=Mie(e,n);return this._streams.add(r),r.once(zie,()=>{r=void 0}),r.once(qie,()=>{r&&(this._streams.delete(r),r=void 0)}),r}};CC.FSWatcher=hh;var doe=(t,e)=>{let s=new hh(e);return s.add(t),s};CC.watch=doe});var G5,Sr,poe,foe,H5,moe,z5,q5=D(()=>{"use strict";G5=oe(require("node:fs")),Sr=oe(require("node:path")),poe=["**/.*","**/.*/**","**/node_modules/**"],foe="cdk.out",H5=t=>t===void 0?[]:Array.isArray(t)?t:[t],moe=t=>{try{let e=G5.readFileSync(t,"utf-8");return JSON.parse(e)??{}}catch{return{}}},z5=(t=process.cwd())=>{let e=t,s=moe(Sr.join(e,"cdk.json")),n=H5(s.watch?.include),r=H5(s.watch?.exclude),i=s.output??foe,o=n.length>0?n:[e],a=[...r,...poe],c=Sr.relative(e,Sr.resolve(e,i));return c.length>0&&!c.startsWith(`..${Sr.sep}`)&&!Sr.isAbsolute(c)&&a.push(`${c}/**`),{include:o,exclude:a,rootDir:e}}});var Z5,Y5,hoe,J5,Q5,goe,yoe,xoe,K5,V5,boe,Soe,X5,e$=D(()=>{"use strict";NS();Qn();Z5={critical:0,high:0,medium:0,low:0,total:0},Y5={counts:{...Z5},byFingerprint:new Map},hoe={CRITICAL:"critical",HIGH:"high",MEDIUM:"medium",LOW:"low"},J5=t=>{let e={counts:{...Z5},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=wl(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=hoe[r.severity];a&&(e.counts[a]+=1)}}return e},Q5=(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}},goe=t=>t==="CRITICAL"?de.severity.critical:t==="HIGH"?de.severity.high:t==="MEDIUM"?de.severity.medium:de.severity.low,yoe=(t,e=70)=>{let s=t.replace(/\s+/g," ").trim();return s.length>e?`${s.slice(0,e-1)}\u2026`:s},xoe=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},K5=(t,e)=>{let n=goe(e.issue.severity)(e.issue.severity.padEnd(8)),r=de.text(xoe(e)),i=de.comment(yoe(e.issue.issue));return` ${t==="+"?de.error("+"):de.success("-")} ${n} ${r} ${i}`},V5=8,boe=t=>t.toTimeString().slice(0,8),Soe=t=>t<1e3?`${t}ms`:`${(t/1e3).toFixed(1)}s`,X5=({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(boe(r)),de.comment(Soe(n)),de.text(`triggered: ${de.accent(s)}`)].join(de.comment(" \xB7 "));a.push(` ${u}`),a.push("");let{counts:l}=t,d=[`${de.severity.critical(`${_t.critical} CRITICAL`)} ${de.text(String(l.critical).padStart(3))}`,`${de.severity.high(`${_t.high} HIGH`)} ${de.text(String(l.high).padStart(3))}`,`${de.severity.medium(`${_t.medium} MEDIUM`)} ${de.text(String(l.medium).padStart(3))}`,`${de.severity.low(`${_t.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,V5);for(let g of f)a.push(K5("+",g));e.added.length>f.length&&a.push(de.comment(` \u2026and ${e.added.length-f.length} more added`));let m=e.removed.slice(0,V5);for(let g of m)a.push(K5("-",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(`
459
459
  `)}});var r$={};Ch(r$,{runWatchLoop:()=>Doe});var t$,s$,voe,n$,Coe,Doe,i$=D(()=>{"use strict";t$=oe(require("node:path")),s$=oe(U5());q5();Qn();e$();AC();voe=300,n$=t=>t.output!=="table"&&t.format!=="table",Coe=t=>{let e=n$(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"}},Doe=async t=>{let e=Coe(t.config),s=n$(t.config),{include:n,exclude:r,rootDir:i}=z5(),o=null,a=!1,c=!1,u=Y5,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 DC(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=J5(g?.recommendationMaps),y=l?void 0:Q5(u,h),b=X5({state:h,diff:y,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(`
460
460
  `)[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=s$.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=t$.relative(i,m)||m;d(`${f} ${g}`)},voe)}),p.on("error",f=>{P.error(`Watcher error: ${f instanceof Error?f.message:String(f)}`)}),await new Promise(f=>{let m=()=>{P.info(`
461
- \u{1F44B} Stopping watcher.`),p.close().then(()=>f())};process.once("SIGINT",m),process.once("SIGTERM",m)})}});async function woe(t,e){let s=t.all?"All stacks":t.stackName||"All stacks",n=await Ii({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 Ii({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 qy({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 DC(t,e,s,n,r,i,o,a,c,u,l,d){let{stackName:p,output:f,services:m,withIssue:g,ruleFilter:h,failOnCritical:y}=t,b=p==="All stacks"?void 0:p,{stacks:C,inlineFindings:A,pathToLogicalId:w,recommendationMapPerStack:N,assetSourcePaths:L,acknowledgementsPerStack:R,cdkVersion:H,supportsBoxTraces:B,cdkContext:S,resourceIdMetadata:U,validationReportFindings:k}=rm(b),K=Object.keys(C).length;P.success(`Synthesis complete. Found ${K} stack${K===1?"":"s"} to analyze.`),H&&!B&&P.info(`Detected aws-cdk-lib ${H}. Upgrade to >= 2.252.0 for per-property source locations on deferred values.`);let x=Object.values(C).reduce((q,_)=>{let le=Object.entries(_.Resources||{}).filter(([,F])=>!F.Type.startsWith("AWS::CDK::"));return q+le.length},0);x>0?P.info(`\u{1F50D} Preparing to analyze ${x} total resources across ${K} stacks...`):P.warning("No user resources found in stacks. Make sure your CDK app is properly configured.");let v=null,Y=!!s;if(a&&(Y=!1,P.info("\u{1F3E0} Running in local mode - static analysis only")),o&&!a){P.info("\u{1F50D} Checking license quota...");let q=n.licenseType==="FREE"||n.status==="TRIAL",_=n.totalResourcesAnalyzed||0,le=n.trialUsageLimit||n.maxUsage||200,F=Number.isNaN(_)?0:_,te=Number.isNaN(le)?200:le;if(q&&F>=te)Y=!1,v={canProceed:!0,canRunStaticAnalysis:!0,canRunAIAnalysis:!1,quota:{currentResourcesAnalyzed:F,maxResources:te,remainingResources:Math.max(0,te-F),isTrial:!0,trialExpired:!1},reason:`Trial AI credit allowance exceeded (${F}/${te} 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(v=await sB({licenseKey:o,requestedResources:x,allowOveruse:t.allowOveruse,usageData:r,licenseInfo:n}),Y=!!s&&(v?.canRunAIAnalysis??!0),v?.quota?.isTrial){let ye=v.quota.currentResourcesAnalyzed,Se=v.quota.maxResources;ye>=Se&&(v={...v,canProceed:!0,canRunStaticAnalysis:!0,canRunAIAnalysis:!1,reason:`Trial AI credit allowance exceeded (${ye}/${Se} used) \u2014 falling back to static scans only`},Y=!1)}v?.quota?.isTrial&&P.displayTrialStatus({currentResourcesAnalyzed:v.quota.currentResourcesAnalyzed,maxResources:v.quota.maxResources,remainingResources:v.quota.remainingResources,isTrial:v.quota.isTrial,trialExpired:v.quota.trialExpired,trialStart:n.trialStart,trialEnd:n.trialEnd,tier:n.tier}),!Y&&v?.quota?P.displayQuotaWarning({currentResourcesAnalyzed:v.quota.currentResourcesAnalyzed,maxResources:v.quota.maxResources,requestedResources:x,remainingResources:v.quota.remainingResources,isTrial:v.quota.isTrial}):Y&&o&&P.success("AI analysis enabled - you'll receive comprehensive recommendations")}let J=Hp(t.services),X=J.services;J.removedAllServices?ie.debug(`Services normalization: removed "All services", using: ${X.join(", ")}`):J.defaultedToAll&&ie.debug('Services normalization: defaulting to "All services"');let re=c||{},pe=t.warnSensitive||re.warnOnly||!1,Ae=(()=>{let q=S?.["cdkInsights:aiModel"];return typeof q=="string"?q:void 0})(),we=fB({flag:t.model,cdkContext:Ae,userConfig:typeof t.ai?.model=="string"?t.ai?.model:void 0,tier:n?.tier});we.downgradedFromTierGate?P.warning(`\u26A0\uFE0F Requested AI model "${we.requestedAlias}" is not available on your tier \u2014 using "${we.alias}" instead.`):we.source!=="tierDefault"&&P.comment(`\u{1F916} AI model: ${we.alias} (from ${we.source})`);let ue=t.ai?.batchSize,Re=typeof ue=="number"&&Number.isFinite(ue)?Math.max(1,Math.floor(ue)):void 0;Re&&Re>1&&P.comment(`\u{1F9FA} AI batching: ${Re} resources per call`);let z={stacks:C,inlineFindings:A,validationReportFindings:k,pathToLogicalId:w,recommendationMapPerStack:N,assetSourcePaths:L,acknowledgementsPerStack:R,output:c$(t),services:X,withIssue:t.withIssue,ruleFilter:t.ruleFilter||[],ignoreRules:t.ignoreRules||[],ignorePaths:t.ignorePaths||[],failOnCritical:t.failOnCritical,authToken:s,fingerprint:e,tier:n?.tier,quotaValidation:v||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:pe,sensitiveDataDetection:{disabled:re.enabled===!1,ignoreProperties:re.ignoreProperties||[],allowPatterns:re.allowPatterns||[],strictMode:re.strictMode||!1},cdkContext:S,resourceIdMetadata:U,aiModelId:we.bedrockModelId,aiBatchSize:Re,forceLocal:a,baselineExclude:u,collectFingerprints:l,skipRendering:d};return{...await Um(z),totalResources:x}}var o$,a$,Aoe,c$,u$,AC=D(()=>{"use strict";o$=oe(require("node:fs")),a$=oe(require("node:path"));mb();rr();pp();uF();xb();pF();vF();$b();Qa();vT();Qb();uv();tB();Xa();gy();mp();nB();vb();dt();oB();uB();mv();Qn();mB();yB();$l();Aoe=()=>{let t=a$.resolve(process.cwd(),"cdk.out");return o$.existsSync(t)},c$=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";u$={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){Km(),ie.info("\u{1F5D1}\uFE0F Cleared saved CLI preferences.");return}let s=Xu(),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 Sk(i,n,r);k?(o=k.token,a=k.usageData,c=k.licenseInfo||await Gm(i,o),k.fingerprint?n=k.fingerprint:n=Xu(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 Gm(i,void 0))}else c=await Gm(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=tr(),d=gB(l,t),p=d.ci||fp();if(p&&!d.ci){let k=YR();P.info(`Detected CI environment${k?`: ${k}`:""}`)}let f=!p&&JR();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"],K=typeof t.output=="string"?t.output:void 0,x=typeof t.format=="string"?t.format:void 0,v=K??x;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:Y}=await Promise.resolve().then(()=>(i$(),r$));await Y({config:d,fingerprint:n,authToken:o,licenseInfo:c,usageData:a,project:r,licenseKey:i});return}Aoe()||(P.info("\u26A1 No cdk.out directory found. Running cdk synth..."),xT()||(P.error("Failed to synthesize CDK stacks."),P.comment(" Make sure your CDK app compiles correctly."),process.exit(1)));let m=dF();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)&&(Ir.isFeatureEnabled("githubIntegration",c.tier)?P.success("\u{1F517} GitHub integration enabled"):(P.error("GitHub integration is not available for your current tier"),P.comment(dp("githubIntegration",c.tier,"GitHub integration")),process.exit(1))),f&&!d.yes){let k=await woe(d,g);h={...d,...k}}h.all&&(h.stackName="All stacks"),h.stackName||(h.stackName="All stacks"),f&&h.output||(h.output=c$(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 bc({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 y,b=0;if(h.diff)try{let k=gb(h.baseline);k?(y=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 C=h.writeBaseline?new Set:void 0,A=h.writeBaseline===!0,w=cB(),N=new Date,L=await DC(h,n,o,c,a,r,i,h.local,l.sensitiveDataDetection,y,C,A),R=l.telemetry?.enabled===!0&&!!i;if(h.diff&&y){let k=0,K=[];for(let x of Object.values(L.recommendationMaps||{})){if(!x?.sources)continue;let v=[...x.sources.cdkInsights?.issues??[],...x.sources.cdkNag?.issues??[]];k+=v.length,K.push(...v)}if(P.info(`\u{1F4D0} Diff result: ${k} new finding${k===1?"":"s"} (${b} existing, suppressed).`),R){let x=(()=>{try{return gb(h.baseline)}catch{return null}})();Pl({enabled:!0,licenseKey:i,authToken:o,tier:c?.tier,event:{type:"diff_run",newFindings:k,existingSuppressed:b,newSeverities:fv(K),baselineGeneratedAt:x?.generatedAt,failedOnCritical:!!L.hasCriticalIssues}})}}if(h.writeBaseline&&C){let k="1.41.1",{path:K,count:x}=cF([...C],{cliVersion:k,overridePath:h.baseline});if(P.success(`\u{1F4CC} Wrote baseline of ${x} finding${x===1?"":"s"} to ${K}.`),P.comment(" On the next run, pass --diff to see only new findings since this point."),R){let v=[],Y={},J=new Set;for(let X of Object.values(L.recommendationMaps||{})){if(!X?.sources)continue;let re=[...X.sources.cdkInsights?.issues??[],...X.sources.cdkNag?.issues??[]];v.push(...re);for(let Ae of re){let we=Ae.ruleId,ue=/^([A-Za-z][A-Za-z0-9-]+):\s/.exec(Ae.issue??""),Re=we||ue?.[1]||"unknown";Y[Re]=(Y[Re]??0)+1}let pe=X.type;pe?.startsWith("AWS::")&&J.add(pe.split("::")[1])}Pl({enabled:!0,licenseKey:i,authToken:o,tier:c?.tier,event:{type:"baseline_written",totalFindings:x,severityCounts:fv(v),ruleHistogram:Y,uniqueServices:J.size}})}return}let H=[],B=L.recommendationMaps||{},S=new Set;for(let[k,K]of Object.entries(B)){let x=K,v=k.includes(":")?k.substring(k.indexOf(":")+1):k,Y=k.includes(":")?k.substring(0,k.indexOf(":")):"";Y&&S.add(Y);let J=[...x.sources.cdkInsights?.issues??[],...x.sources.cdkNag?.issues??[],...x.sources.validationReport?.issues??[]];for(let X of J)H.push({resourceId:v,issue:X.issue,recommendation:X.recommendation,severity:X.severity,wafPillar:X.wafPillar||"Security",foundBy:X.foundBy||"cdkInsights",validationPluginName:X.validationPluginName,seenInSynth:X.seenInSynth,constructPath:X.constructPath,codeSnippet:X.codeSnippet,sourceLocation:X.sourceLocation,ruleId:X.ruleId,context:X.context,constructType:X.constructType||x.constructType})}if(h.prComment)if(Gf()){P.info("Posting analysis summary to PR...");let k=[...S],K={stackNames:k.length>0?k:[h.stackName||"Unknown"],resourceCount:L.totalResources,issues:H,reportUrl:void 0,aiEnabled:!h.local&&!!i,tier:c?.tier||"free"},x=await Cb({data:K,updateExisting:!0});x.success?P.success("PR comment posted successfully"):P.warning(`Failed to post PR comment: ${x.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.41.1",K=new Date,x=!h.local&&!!i,v=iB({scanId:w,cliVersion:k,recommendationMaps:L.recommendationMaps||{},scannedResourceIds:L.scannedResourceIds??new Set,scanStartedAt:N,scanCompletedAt:K,aiAnalysis:{ran:x}});P.info("\u{1F4E4} Uploading scan to CDK Insights...");let Y=await aB({enabled:!0,licenseKey:i,authToken:o,tier:c?.tier,report:v});if(!Y.skipped)if(Y.success)P.success(`Uploaded as scan ${Y.scanId}`),Y.viewUrl&&P.comment(` View: ${Y.viewUrl}`),Y.retentionDays&&P.comment(` Retained for ${Y.retentionDays} day${Y.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 J=Y.serverMessage??Y.reason??"unknown";P.warning(`Could not upload scan to CDK Insights (${J}). Run continues normally.`)}}if(l.feedback!==!1&&f&&o&&H.length>0)try{let k=await Ii({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 K=Kn(),v=ST({apiClient:{post:async(J,X)=>{let{data:re}=await Rt.post(`${K}${J}`,X,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","x-cdk-insights-fingerprint":n,"x-cdk-insights-client":"cli"},timeout:1e4});return re}}}),Y={};for(let[J,X]of Object.entries(L.recommendationMaps||{})){let re=X,pe=J.includes(":")?J.substring(J.indexOf(":")+1):J;re.type&&(Y[pe]=re.type)}if(k==="helpful")v.markReportAsHelpful(H,Y).catch(()=>{}),P.comment(" Thanks for your feedback!");else{let J=H.map(X=>({issue:X,rating:k,resourceType:Y[X.resourceId]}));v.submitBatchFeedback(J).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 Gc,v$,S$,Hoe,C$,D$=D(()=>{"use strict";Gc=oe(require("node:fs")),v$=oe(require("node:path")),S$="@aws-cdk/core:stackTrace",Hoe=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(`
461
+ \u{1F44B} Stopping watcher.`),p.close().then(()=>f())};process.once("SIGINT",m),process.once("SIGTERM",m)})}});async function woe(t,e){let s=t.all?"All stacks":t.stackName||"All stacks",n=await Ii({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 Ii({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 qy({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 DC(t,e,s,n,r,i,o,a,c,u,l,d){let{stackName:p,output:f,services:m,withIssue:g,ruleFilter:h,failOnCritical:y}=t,b=p==="All stacks"?void 0:p,{stacks:C,inlineFindings:A,pathToLogicalId:w,recommendationMapPerStack:N,assetSourcePaths:L,acknowledgementsPerStack:R,cdkVersion:H,supportsBoxTraces:B,cdkContext:S,resourceIdMetadata:U,validationReportFindings:k}=rm(b),K=Object.keys(C).length;P.success(`Synthesis complete. Found ${K} stack${K===1?"":"s"} to analyze.`),H&&!B&&P.info(`Detected aws-cdk-lib ${H}. Upgrade to >= 2.252.0 for per-property source locations on deferred values.`);let x=Object.values(C).reduce((q,_)=>{let le=Object.entries(_.Resources||{}).filter(([,F])=>!F.Type.startsWith("AWS::CDK::"));return q+le.length},0);x>0?P.info(`\u{1F50D} Preparing to analyze ${x} total resources across ${K} stacks...`):P.warning("No user resources found in stacks. Make sure your CDK app is properly configured.");let v=null,Y=!!s;if(a&&(Y=!1,P.info("\u{1F3E0} Running in local mode - static analysis only")),o&&!a){P.info("\u{1F50D} Checking license quota...");let q=n.licenseType==="FREE"||n.status==="TRIAL",_=n.totalResourcesAnalyzed||0,le=n.trialUsageLimit||n.maxUsage||200,F=Number.isNaN(_)?0:_,te=Number.isNaN(le)?200:le;if(q&&F>=te)Y=!1,v={canProceed:!0,canRunStaticAnalysis:!0,canRunAIAnalysis:!1,quota:{currentResourcesAnalyzed:F,maxResources:te,remainingResources:Math.max(0,te-F),isTrial:!0,trialExpired:!1},reason:`Trial AI credit allowance exceeded (${F}/${te} 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(v=await sB({licenseKey:o,requestedResources:x,allowOveruse:t.allowOveruse,usageData:r,licenseInfo:n}),Y=!!s&&(v?.canRunAIAnalysis??!0),v?.quota?.isTrial){let ye=v.quota.currentResourcesAnalyzed,Se=v.quota.maxResources;ye>=Se&&(v={...v,canProceed:!0,canRunStaticAnalysis:!0,canRunAIAnalysis:!1,reason:`Trial AI credit allowance exceeded (${ye}/${Se} used) \u2014 falling back to static scans only`},Y=!1)}v?.quota?.isTrial&&P.displayTrialStatus({currentResourcesAnalyzed:v.quota.currentResourcesAnalyzed,maxResources:v.quota.maxResources,remainingResources:v.quota.remainingResources,isTrial:v.quota.isTrial,trialExpired:v.quota.trialExpired,trialStart:n.trialStart,trialEnd:n.trialEnd,tier:n.tier}),!Y&&v?.quota?P.displayQuotaWarning({currentResourcesAnalyzed:v.quota.currentResourcesAnalyzed,maxResources:v.quota.maxResources,requestedResources:x,remainingResources:v.quota.remainingResources,isTrial:v.quota.isTrial}):Y&&o&&P.success("AI analysis enabled - you'll receive comprehensive recommendations")}let J=Hp(t.services),X=J.services;J.removedAllServices?ie.debug(`Services normalization: removed "All services", using: ${X.join(", ")}`):J.defaultedToAll&&ie.debug('Services normalization: defaulting to "All services"');let re=c||{},pe=t.warnSensitive||re.warnOnly||!1,Ae=(()=>{let q=S?.["cdkInsights:aiModel"];return typeof q=="string"?q:void 0})(),we=fB({flag:t.model,cdkContext:Ae,userConfig:typeof t.ai?.model=="string"?t.ai?.model:void 0,tier:n?.tier});we.downgradedFromTierGate?P.warning(`\u26A0\uFE0F Requested AI model "${we.requestedAlias}" is not available on your tier \u2014 using "${we.alias}" instead.`):we.source!=="tierDefault"&&P.comment(`\u{1F916} AI model: ${we.alias} (from ${we.source})`);let ue=t.ai?.batchSize,Re=typeof ue=="number"&&Number.isFinite(ue)?Math.max(1,Math.floor(ue)):void 0;Re&&Re>1&&P.comment(`\u{1F9FA} AI batching: ${Re} resources per call`);let z={stacks:C,inlineFindings:A,validationReportFindings:k,pathToLogicalId:w,recommendationMapPerStack:N,assetSourcePaths:L,acknowledgementsPerStack:R,output:c$(t),services:X,withIssue:t.withIssue,ruleFilter:t.ruleFilter||[],ignoreRules:t.ignoreRules||[],ignorePaths:t.ignorePaths||[],failOnCritical:t.failOnCritical,authToken:s,fingerprint:e,tier:n?.tier,quotaValidation:v||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:pe,sensitiveDataDetection:{disabled:re.enabled===!1,ignoreProperties:re.ignoreProperties||[],allowPatterns:re.allowPatterns||[],strictMode:re.strictMode||!1},cdkContext:S,resourceIdMetadata:U,aiModelId:we.bedrockModelId,aiBatchSize:Re,forceLocal:a,baselineExclude:u,collectFingerprints:l,skipRendering:d};return{...await Um(z),totalResources:x}}var o$,a$,Aoe,c$,u$,AC=D(()=>{"use strict";o$=oe(require("node:fs")),a$=oe(require("node:path"));mb();rr();pp();uF();xb();pF();vF();$b();Qa();vT();Qb();uv();tB();Xa();gy();mp();nB();vb();dt();oB();uB();mv();Qn();mB();yB();$l();Aoe=()=>{let t=a$.resolve(process.cwd(),"cdk.out");return o$.existsSync(t)},c$=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";u$={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){Km(),ie.info("\u{1F5D1}\uFE0F Cleared saved CLI preferences.");return}let s=Xu(),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 Sk(i,n,r);k?(o=k.token,a=k.usageData,c=k.licenseInfo||await Gm(i,o),k.fingerprint?n=k.fingerprint:n=Xu(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 Gm(i,void 0))}else c=await Gm(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=tr(),d=gB(l,t),p=d.ci||fp();if(p&&!d.ci){let k=YR();P.info(`Detected CI environment${k?`: ${k}`:""}`)}let f=!p&&JR();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"],K=typeof t.output=="string"?t.output:void 0,x=typeof t.format=="string"?t.format:void 0,v=K??x;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:Y}=await Promise.resolve().then(()=>(i$(),r$));await Y({config:d,fingerprint:n,authToken:o,licenseInfo:c,usageData:a,project:r,licenseKey:i});return}Aoe()||(P.info("\u26A1 No cdk.out directory found. Running cdk synth..."),xT()||(P.error("Failed to synthesize CDK stacks."),P.comment(" Make sure your CDK app compiles correctly."),process.exit(1)));let m=dF();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)&&(Ir.isFeatureEnabled("githubIntegration",c.tier)?P.success("\u{1F517} GitHub integration enabled"):(P.error("GitHub integration is not available for your current tier"),P.comment(dp("githubIntegration",c.tier,"GitHub integration")),process.exit(1))),f&&!d.yes){let k=await woe(d,g);h={...d,...k}}h.all&&(h.stackName="All stacks"),h.stackName||(h.stackName="All stacks"),f&&h.output||(h.output=c$(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 bc({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 y,b=0;if(h.diff)try{let k=gb(h.baseline);k?(y=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 C=h.writeBaseline?new Set:void 0,A=h.writeBaseline===!0,w=cB(),N=new Date,L=await DC(h,n,o,c,a,r,i,h.local,l.sensitiveDataDetection,y,C,A),R=l.telemetry?.enabled===!0&&!!i;if(h.diff&&y){let k=0,K=[];for(let x of Object.values(L.recommendationMaps||{})){if(!x?.sources)continue;let v=[...x.sources.cdkInsights?.issues??[],...x.sources.cdkNag?.issues??[]];k+=v.length,K.push(...v)}if(P.info(`\u{1F4D0} Diff result: ${k} new finding${k===1?"":"s"} (${b} existing, suppressed).`),R){let x=(()=>{try{return gb(h.baseline)}catch{return null}})();Pl({enabled:!0,licenseKey:i,authToken:o,tier:c?.tier,event:{type:"diff_run",newFindings:k,existingSuppressed:b,newSeverities:fv(K),baselineGeneratedAt:x?.generatedAt,failedOnCritical:!!L.hasCriticalIssues}})}}if(h.writeBaseline&&C){let k="1.41.2",{path:K,count:x}=cF([...C],{cliVersion:k,overridePath:h.baseline});if(P.success(`\u{1F4CC} Wrote baseline of ${x} finding${x===1?"":"s"} to ${K}.`),P.comment(" On the next run, pass --diff to see only new findings since this point."),R){let v=[],Y={},J=new Set;for(let X of Object.values(L.recommendationMaps||{})){if(!X?.sources)continue;let re=[...X.sources.cdkInsights?.issues??[],...X.sources.cdkNag?.issues??[]];v.push(...re);for(let Ae of re){let we=Ae.ruleId,ue=/^([A-Za-z][A-Za-z0-9-]+):\s/.exec(Ae.issue??""),Re=we||ue?.[1]||"unknown";Y[Re]=(Y[Re]??0)+1}let pe=X.type;pe?.startsWith("AWS::")&&J.add(pe.split("::")[1])}Pl({enabled:!0,licenseKey:i,authToken:o,tier:c?.tier,event:{type:"baseline_written",totalFindings:x,severityCounts:fv(v),ruleHistogram:Y,uniqueServices:J.size}})}return}let H=[],B=L.recommendationMaps||{},S=new Set;for(let[k,K]of Object.entries(B)){let x=K,v=k.includes(":")?k.substring(k.indexOf(":")+1):k,Y=k.includes(":")?k.substring(0,k.indexOf(":")):"";Y&&S.add(Y);let J=[...x.sources.cdkInsights?.issues??[],...x.sources.cdkNag?.issues??[],...x.sources.validationReport?.issues??[]];for(let X of J)H.push({resourceId:v,issue:X.issue,recommendation:X.recommendation,severity:X.severity,wafPillar:X.wafPillar||"Security",foundBy:X.foundBy||"cdkInsights",validationPluginName:X.validationPluginName,seenInSynth:X.seenInSynth,constructPath:X.constructPath,codeSnippet:X.codeSnippet,sourceLocation:X.sourceLocation,ruleId:X.ruleId,context:X.context,constructType:X.constructType||x.constructType})}if(h.prComment)if(Gf()){P.info("Posting analysis summary to PR...");let k=[...S],K={stackNames:k.length>0?k:[h.stackName||"Unknown"],resourceCount:L.totalResources,issues:H,reportUrl:void 0,aiEnabled:!h.local&&!!i,tier:c?.tier||"free"},x=await Cb({data:K,updateExisting:!0});x.success?P.success("PR comment posted successfully"):P.warning(`Failed to post PR comment: ${x.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.41.2",K=new Date,x=!h.local&&!!i,v=iB({scanId:w,cliVersion:k,recommendationMaps:L.recommendationMaps||{},scannedResourceIds:L.scannedResourceIds??new Set,scanStartedAt:N,scanCompletedAt:K,aiAnalysis:{ran:x}});P.info("\u{1F4E4} Uploading scan to CDK Insights...");let Y=await aB({enabled:!0,licenseKey:i,authToken:o,tier:c?.tier,report:v});if(!Y.skipped)if(Y.success)P.success(`Uploaded as scan ${Y.scanId}`),Y.viewUrl&&P.comment(` View: ${Y.viewUrl}`),Y.retentionDays&&P.comment(` Retained for ${Y.retentionDays} day${Y.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 J=Y.serverMessage??Y.reason??"unknown";P.warning(`Could not upload scan to CDK Insights (${J}). Run continues normally.`)}}if(l.feedback!==!1&&f&&o&&H.length>0)try{let k=await Ii({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 K=Kn(),v=ST({apiClient:{post:async(J,X)=>{let{data:re}=await Rt.post(`${K}${J}`,X,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","x-cdk-insights-fingerprint":n,"x-cdk-insights-client":"cli"},timeout:1e4});return re}}}),Y={};for(let[J,X]of Object.entries(L.recommendationMaps||{})){let re=X,pe=J.includes(":")?J.substring(J.indexOf(":")+1):J;re.type&&(Y[pe]=re.type)}if(k==="helpful")v.markReportAsHelpful(H,Y).catch(()=>{}),P.comment(" Thanks for your feedback!");else{let J=H.map(X=>({issue:X,rating:k,resourceType:Y[X.resourceId]}));v.submitBatchFeedback(J).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 Gc,v$,S$,Hoe,C$,D$=D(()=>{"use strict";Gc=oe(require("node:fs")),v$=oe(require("node:path")),S$="@aws-cdk/core:stackTrace",Hoe=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(`
462
462
  `)?`
463
463
  `:"";return{status:"added",updated:`${JSON.stringify(i,null,2)}${o}`}},C$=t=>{let e=v$.join(t,"cdk.json");if(!Gc.existsSync(e))return{status:"missing",cdkJsonPath:e};let s=Gc.readFileSync(e,"utf-8"),n=Hoe(s);return n.status==="invalid-json"?{status:"invalid-json",cdkJsonPath:e}:n.status==="already-set"?{status:"already-set",cdkJsonPath:e}:(Gc.writeFileSync(e,n.updated,"utf-8"),{status:"added",cdkJsonPath:e})}});var F$=oe(wh()),Sh=require("node:child_process"),T$=oe(require("node:path")),P$=require("node:util");rr();var L$=oe(u0());var Qd=require("assert");var aH={right:pH,center:fH},cH=0,zd=1,uH=2,qd=3,l0=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(`
464
464
  `).map(r=>r.split(" ")),n=0;return s.forEach(r=>{r.length>1&&Ks.stringWidth(r[0])>n&&(n=Math.min(Math.floor(this.width*.5),Ks.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=Ks.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(`
@@ -582,7 +582,7 @@ ${t.body.join(`
582
582
  \u2705 Configuration saved successfully!`),console.log(`
583
583
  \u{1F4CB} Your current configuration:`),console.log(JSON.stringify(t,null,2))}finally{s.close()}},Zoe=()=>{let t=tr();console.log("\u{1F4CB} Current Configuration:"),console.log(JSON.stringify(t,null,2))},Yoe=t=>{let{key:e,value:s}=t;if(t.help){nd(e);return}s||(console.log(`
584
584
  \u274C No value provided for ${e}`),nd(e),process.exit(1));let n=tr(),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{ie.error(`\u274C Invalid value for ${e}: ${s}`),nd(e),process.exit(1)}let i=IC[e];i&&(i.type==="boolean"&&typeof r!="boolean"&&(ie.error(`\u274C ${e} must be a boolean (true/false)`),nd(e),process.exit(1)),i.type==="array"&&!Array.isArray(r)&&(ie.error(`\u274C ${e} must be a comma-separated list`),nd(e),process.exit(1))),n[e]=r,Nl(n),ie.info(`\u2714\uFE0F ${e} = ${JSON.stringify(r)}`)},Joe=t=>{let{key:e}=t,s=tr();if(s[e]===void 0){ie.warn(`\u26A0\uFE0F ${e} not set`);return}delete s[e],Nl(s),ie.info(`\u2714\uFE0F Removed ${e}`)},O$=new Set(["vi","vim","nvim","nano","emacs","code","subl","atom","gedit","kate","notepad","notepad++","micro","helix","pico"]),Qoe=t=>{let e=t.split("/").pop()||t;return O$.has(e.toLowerCase())},Xoe=()=>{let t=Zp.get("EDITOR")||"vi";Qoe(t)||(ie.error(`\u274C Unsupported editor: ${t}. Allowed editors: ${Array.from(O$).join(", ")}`),process.exit(1));let e=(0,Sh.spawnSync)(t,[Koe],{stdio:"inherit"});e.error&&(ie.error("\u274C Editor error",{error:e.error.message}),process.exit(1)),ie.info("\u2714\uFE0F Config saved")},kC=t=>t.teamId||process.env.CDK_INSIGHTS_TEAM_ID||void 0,_C=()=>{let t=Zp.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}},FC=()=>Zp.get("CDK_INSIGHTS_API_URL")||"https://api.cdkinsights.dev",eae=async t=>{let e=kC(t);e||(console.error("\u274C Team ID required. Use --team-id or set CDK_INSIGHTS_TEAM_ID env var."),process.exit(1));try{console.log("\u{1F4E5} Fetching team configurations...");let n=(await Rt.get(`${FC()}/v1/teams/${e}/configs`,{headers:_C()})).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=Bl(i.configData),c={...tr(),...o};Nl(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)}},tae=async t=>{let e=kC(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=tr(),n=t.name||"CLI Config",r=t.description||"";console.log(`\u{1F4E4} Pushing local config as "${n}"...`);let o=(await Rt.post(`${FC()}/v1/teams/${e}/configs`,{configName:n,configDescription:r,configData:s},{headers:_C()})).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)}},sae=async t=>{let e=kC(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...
585
- `);let n=(await Rt.get(`${FC()}/v1/teams/${e}/configs`,{headers:_C()})).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)}},nae=async t=>{let{path:e}=t,s=(0,P$.promisify)(Sh.exec),n=e||process.cwd();ie.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&&ie.error(r)}catch(r){ie.error("\u274C Failed to synthesize stacks",{error:r instanceof Error?r.message:String(r)}),process.exit(1)}},rae=()=>{ie.info("\u{1F5D1}\uFE0F Clearing caches..."),lk(),vk();let t=ly();ie.info(`\u{1F4C1} Cache directory: ${t.cacheDir}`),ie.info(`\u{1F4CA} Cache status: ${t.cacheFileExists?"Files found":"No persistent cache files"}`)},iae=()=>{ie.info("\u{1F4CA} Cache Status:");let t=ly();if(ie.info(`\u{1F4C1} Cache directory: ${t.cacheDir}`),ie.info(`\u{1F4C2} Directory exists: ${t.cacheDirExists?"Yes":"No"}`),ie.info(`\u{1F4C4} Cache file exists: ${t.cacheFileExists?"Yes":"No"}`),t.cacheSize!==void 0){let e=(t.cacheSize/1024).toFixed(2);ie.info(`\u{1F4CF} Cache file size: ${e} KB`)}ie.info(`\u2699\uFE0F Cache enabled: ${dk()?"Yes":"No"}`),ie.info("\u2139\uFE0F Note: Current cache is in-memory and clears on process restart")},oae=()=>{let t=new L$.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()},aae={command:"config <action> [key] [value]",describe:"Manage project-level configuration",builder:t=>t.command({command:"list",describe:"Show current configuration",handler:Zoe}).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:Yoe}).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:Joe}).command({command:"edit",describe:"Open config file in your editor",handler:Xoe}).command({command:"setup",describe:"Interactive setup to configure CDK Insights",handler:Voe}).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:eae}).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:tae}).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:sae}).demandCommand(1).help(),handler:()=>{}},cae=()=>{ZR(x0(process.argv)).scriptName("cdk-insights").version("1.41.1").usage("Usage: $0 <command> [options]").command(u$).command(d$).command(x$).command(b$).command(k$).command(_$).command(aae).command("hook","Install Git pre-commit hook for CDK Insights",()=>{},()=>p$()).command("synth","Run `cdk synth` automatically before analysis",t=>t.option("path",{type:"string",describe:"Path to the CDK project (defaults to current directory)"}),nae).command("clear-cache","Clear the analysis cache",()=>{},rae).command("cache-status","Show the current cache status",()=>{},iae).demandCommand(1,"Please specify a command.").strict().help().wrap(null).epilog(oae()).parse()};cae();
585
+ `);let n=(await Rt.get(`${FC()}/v1/teams/${e}/configs`,{headers:_C()})).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)}},nae=async t=>{let{path:e}=t,s=(0,P$.promisify)(Sh.exec),n=e||process.cwd();ie.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&&ie.error(r)}catch(r){ie.error("\u274C Failed to synthesize stacks",{error:r instanceof Error?r.message:String(r)}),process.exit(1)}},rae=()=>{ie.info("\u{1F5D1}\uFE0F Clearing caches..."),lk(),vk();let t=ly();ie.info(`\u{1F4C1} Cache directory: ${t.cacheDir}`),ie.info(`\u{1F4CA} Cache status: ${t.cacheFileExists?"Files found":"No persistent cache files"}`)},iae=()=>{ie.info("\u{1F4CA} Cache Status:");let t=ly();if(ie.info(`\u{1F4C1} Cache directory: ${t.cacheDir}`),ie.info(`\u{1F4C2} Directory exists: ${t.cacheDirExists?"Yes":"No"}`),ie.info(`\u{1F4C4} Cache file exists: ${t.cacheFileExists?"Yes":"No"}`),t.cacheSize!==void 0){let e=(t.cacheSize/1024).toFixed(2);ie.info(`\u{1F4CF} Cache file size: ${e} KB`)}ie.info(`\u2699\uFE0F Cache enabled: ${dk()?"Yes":"No"}`),ie.info("\u2139\uFE0F Note: Current cache is in-memory and clears on process restart")},oae=()=>{let t=new L$.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()},aae={command:"config <action> [key] [value]",describe:"Manage project-level configuration",builder:t=>t.command({command:"list",describe:"Show current configuration",handler:Zoe}).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:Yoe}).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:Joe}).command({command:"edit",describe:"Open config file in your editor",handler:Xoe}).command({command:"setup",describe:"Interactive setup to configure CDK Insights",handler:Voe}).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:eae}).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:tae}).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:sae}).demandCommand(1).help(),handler:()=>{}},cae=()=>{ZR(x0(process.argv)).scriptName("cdk-insights").version("1.41.2").usage("Usage: $0 <command> [options]").command(u$).command(d$).command(x$).command(b$).command(k$).command(_$).command(aae).command("hook","Install Git pre-commit hook for CDK Insights",()=>{},()=>p$()).command("synth","Run `cdk synth` automatically before analysis",t=>t.option("path",{type:"string",describe:"Path to the CDK project (defaults to current directory)"}),nae).command("clear-cache","Clear the analysis cache",()=>{},rae).command("cache-status","Show the current cache status",()=>{},iae).demandCommand(1,"Please specify a command.").strict().help().wrap(null).epilog(oae()).parse()};cae();
586
586
  /*! Bundled license information:
587
587
 
588
588
  mime-db/index.js:
package/dist/index.js CHANGED
@@ -77,7 +77,7 @@ ${JSON.stringify(z)}`}).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(b_,function(o){return i.close+o+i.open}))}return t}Ae.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){Ae[s]=function(n){if(typeof e[s]=="object"){var r=n;for(var i in e[s])r=Ae[e[s][i]](r);return r}return Ae[e[s]](n)}})(t)};function x_(){var e={};return Object.keys(Tv).forEach(function(t){e[t]={get:function(){return kv([t])}}}),e}var w_=function(t,s){var n=s.split("");return n=n.map(t),n.join("")};Ae.trap=yv();Ae.zalgo=bv();Ae.maps={};Ae.maps.america=vv()(Ae);Ae.maps.zebra=Av()(Ae);Ae.maps.rainbow=wv()(Ae);Ae.maps.random=Rv()(Ae);for(Fv in Ae.maps)(function(e){Ae[e]=function(t){return w_(Ae.maps[e],t)}})(Fv);var Fv;Iv(Ae,x_())});var Ov=T((xV,_v)=>{var E_=Lv();_v.exports=E_});var Wv=T((wV,ra)=>{var{info:R_,debug:Nv}=sa(),Rt=El(),Il=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={};I_.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=Rt.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(Rt.wordWrap(this.fixedWidth,this.content,i))}return this.wrapLines(this.content.split(`
78
78
  `))}wrapLines(t){let s=Rt.colorizeLines(t);return this.href?s.map(n=>Rt.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(Mv,-1),this.height=this.heights.reduce(Mv,-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=Rt.truncate(this.content,10,this.truncate);t||R_(`${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(Rt.repeat(this.chars[this.y==0?"top":"mid"],n))},this):(s.push(this._topLeftChar(0)),s.push(Rt.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=Ov();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 fi;)d=this.cells[d.y][d.x-1];d instanceof gi||(i=this.chars.rightMid)}let o=Rt.repeat(" ",this.paddingLeft),a=s?this.chars.right:"",u=Rt.repeat(" ",this.paddingRight),c=this.lines[t],l=this.width-(this.paddingLeft+this.paddingRight);n&&(c+=this.truncate||"\u2026");let p=Rt.truncate(c,l,this.truncate);return p=Rt.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=Rt.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 fi;)o=this.cells[o.y][o.x-1];o instanceof gi||(n=this.chars.rightMid)}let r=t?this.chars.right:"",i=Rt.repeat(" ",this.width);return this.stylizeLine(n,i,r)}},fi=class{constructor(){}draw(t){return typeof t=="number"&&Nv(`${this.y}-${this.x}: 1x1 ColSpanCell`),""}init(){}mergeTableOptions(){}},gi=class{constructor(t){this.originalCell=t}init(t){let s=this.y,n=this.originalCell.y;this.cellOffset=s-n,this.offset=F_(t.rowHeights,n,this.cellOffset)}draw(t){return t=="top"?this.originalCell.draw(this.offset,this.cellOffset):t=="bottom"?this.originalCell.draw("bottom"):(Nv(`${this.y}-${this.x}: 1x${this.colSpan} RowSpanCell for ${this.originalCell.content}`),this.originalCell.draw(this.offset+1+t))}mergeTableOptions(){}};function Bv(...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]=Bv(e[r],e[s],t[r],t[s])):n[s]=Bv(e[s],t[s])}function F_(e,t,s){let n=e[t];for(let r=1;r<s;r++)n+=1+e[t+r];return n}function Mv(e,t){return e+t+1}var I_=["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=Il;ra.exports.ColSpanCell=fi;ra.exports.RowSpanCell=gi});var $v=T((EV,jv)=>{var{warn:k_,debug:T_}=sa(),kl=Wv(),{ColSpanCell:P_,RowSpanCell:L_}=kl;(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 x=b.rowSpan||1,v=b.colSpan||1;if(x>1)for(let E=0;E<v;E++)f[b.x+E]=x;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),x=!(g>b||y>h),v=m.x,E=m.x-1+(m.colSpan||1),O=f.x,M=f.x-1+(f.colSpan||1),P=!(v>M||O>E);return x&&P}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 x=m[b];for(let v=0;v<x.length;v++)if(r(y,x[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 L_(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 x=new P_;x.x=y.x+b,x.y=y.y,g.splice(h+1,0,x)}}}}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);T_(`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 x=h+1;for(;x<f&&o(m,x,b.x,b.x+b.colSpan);)b.rowSpan++,x++;let v=new kl(b);v.x=b.x,v.y=b.y,k_(`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 kl(g)})})}function d(m){let f=p(m);return t(f),l(f),a(f),u(f),f}jv.exports={makeTableLayout:d,layoutTable:t,addRowSpanCells:a,maxWidth:s,fillInTable:l,computeWidths:Uv("colSpan","desiredWidth","x",1),computeHeights:Uv("rowSpan","desiredHeight","y",1)}})();function Uv(e,t,s,n){return function(r,i){let o=[],a=[],u={};i.forEach(function(c){c.forEach(function(l){(l[e]||1)>1?a.push(l):o[l[s]]=Math.max(o[l[s]]||0,l[t]||0,n)})}),r.forEach(function(c,l){typeof c=="number"&&(o[l]=c)});for(let c=a.length-1;c>=0;c--){let l=a[c],p=l[e],d=l[s],m=o[d],f=typeof r[d]=="number"?0:1;if(typeof m=="number")for(let 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 Hv=T((RV,Gv)=>{var Ss=sa(),__=El(),Tl=$v(),ia=class extends Array{constructor(t){super();let s=__.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=Tl.makeTableLayout(t);n.forEach(function(i){i.forEach(function(o){o.mergeTableOptions(this.options,n)},this)},this),Tl.computeWidths(this.options.colWidths,n),Tl.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)&&Pl(o,"top",r);for(let u=0;u<a;u++)Pl(o,u,r);i+1==n.length&&Pl(o,"bottom",r)}return r.join(`
79
79
  `)}get width(){return this.toString().split(`
80
- `)[0].length}};ia.reset=()=>Ss.reset();function Pl(e,t,s){let n=[];e.forEach(function(i){n.push(i.draw(t))});let r=n.join("");r.length&&s.push(r)}Gv.exports=ia});var qv=T((FV,zv)=>{zv.exports=Hv()});var Ll=T((kV,N_)=>{N_.exports={name:"cdk-insights",version:"1.41.1",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-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","aws-cdk-lib":"^2.190.0","cdk-nag":"^2.35.73",constructs:"^10.4.2"},peerDependenciesMeta:{"@aws-solutions-constructs/aws-apigateway-lambda":{optional:!0},"@aws-solutions-constructs/aws-lambda-stepfunctions":{optional:!0},"@aws-solutions-constructs/aws-s3-lambda":{optional:!0}}}});var hC={};xi(hC,{STACK_TRACE_CONTEXT_KEY:()=>ga,ensureStackTraceInCdkJson:()=>yO,isStackTraceContextEnabledInCdkJson:()=>SO,patchCdkJsonForStackTrace:()=>gC});var Bs,Kl,ga,gC,yO,SO,yC=ep(()=>{"use strict";Bs=Z(require("node:fs")),Kl=Z(require("node:path")),ga="@aws-cdk/core:stackTrace",gC=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(`
80
+ `)[0].length}};ia.reset=()=>Ss.reset();function Pl(e,t,s){let n=[];e.forEach(function(i){n.push(i.draw(t))});let r=n.join("");r.length&&s.push(r)}Gv.exports=ia});var qv=T((FV,zv)=>{zv.exports=Hv()});var Ll=T((kV,N_)=>{N_.exports={name:"cdk-insights",version:"1.41.2",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-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","aws-cdk-lib":"^2.190.0","cdk-nag":"^2.35.73",constructs:"^10.4.2"},peerDependenciesMeta:{"@aws-solutions-constructs/aws-apigateway-lambda":{optional:!0},"@aws-solutions-constructs/aws-lambda-stepfunctions":{optional:!0},"@aws-solutions-constructs/aws-s3-lambda":{optional:!0}}}});var hC={};xi(hC,{STACK_TRACE_CONTEXT_KEY:()=>ga,ensureStackTraceInCdkJson:()=>yO,isStackTraceContextEnabledInCdkJson:()=>SO,patchCdkJsonForStackTrace:()=>gC});var Bs,Kl,ga,gC,yO,SO,yC=ep(()=>{"use strict";Bs=Z(require("node:fs")),Kl=Z(require("node:path")),ga="@aws-cdk/core:stackTrace",gC=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}`}},yO=e=>{let t=Kl.join(e,"cdk.json");if(!Bs.existsSync(t))return{status:"missing",cdkJsonPath:t};let s=Bs.readFileSync(t,"utf-8"),n=gC(s);return n.status==="invalid-json"?{status:"invalid-json",cdkJsonPath:t}:n.status==="already-set"?{status:"already-set",cdkJsonPath:t}:(Bs.writeFileSync(t,n.updated,"utf-8"),{status:"added",cdkJsonPath:t})},SO=e=>{try{let t=Kl.join(e,"cdk.json");if(!Bs.existsSync(t))return!1;let s=JSON.parse(Bs.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 a2={};xi(a2,{CDK_INSIGHTS_ANNOTATION_PREFIX:()=>va,CDK_INSIGHTS_METADATA_VERSION:()=>Jl,CDK_INSIGHTS_NAG_FINDING_PREFIX:()=>ya,CdkInsightsAspect:()=>Da,CdkInsightsPolicyValidationPlugin:()=>vi,ExtremelyHelpfulConsoleLogger:()=>Di,SCAN_REPORT_SCHEMA_VERSION:()=>FC,clearCaches:()=>EC,createCdkInsightsAspect:()=>wC,createCdkInsightsLogger:()=>AC,createCdkInsightsPolicyValidationPlugin:()=>WC,createExtremelyHelpfulConsoleLogger:()=>xC,getCacheStats:()=>RC,isCdkDebugEnabled:()=>Ql,runAnalysis:()=>o2});module.exports=Fa(a2);var GC=Z(require("node:fs"));function Dr(e,t){return function(){return e.apply(t,arguments)}}var{toString:QC}=Object.prototype,{getPrototypeOf:Ei}=Object,{iterator:Ri,toStringTag:rp}=Symbol,Fi=(e=>t=>{let s=QC.call(t);return e[s]||(e[s]=s.slice(8,-1).toLowerCase())})(Object.create(null)),$t=e=>(e=e.toLowerCase(),t=>Fi(t)===e),Ii=e=>t=>typeof t===e,{isArray:wn}=Array,xn=Ii("undefined");function vr(e){return e!==null&&!xn(e)&&e.constructor!==null&&!xn(e.constructor)&&ft(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var ip=$t("ArrayBuffer");function XC(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&ip(e.buffer),t}var eA=Ii("string"),ft=Ii("function"),op=Ii("number"),Cr=e=>e!==null&&typeof e=="object",tA=e=>e===!0||e===!1,wi=e=>{if(Fi(e)!=="object")return!1;let t=Ei(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(rp in e)&&!(Ri in e)},sA=e=>{if(!Cr(e)||vr(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},nA=$t("Date"),rA=$t("File"),iA=e=>!!(e&&typeof e.uri<"u"),oA=e=>e&&typeof e.getParts<"u",aA=$t("Blob"),cA=$t("FileList"),uA=e=>Cr(e)&&ft(e.pipe);function lA(){return typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{}}var sp=lA(),np=typeof sp.FormData<"u"?sp.FormData:void 0,pA=e=>{if(!e)return!1;if(np&&e instanceof np)return!0;let t=Ei(e);if(!t||t===Object.prototype||!ft(e.append))return!1;let s=Fi(e);return s==="formdata"||s==="object"&&ft(e.toString)&&e.toString()==="[object FormData]"},dA=$t("URLSearchParams"),[mA,fA,gA,hA]=["ReadableStream","Request","Response","Headers"].map($t),yA=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function Ar(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(vr(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 ap(e,t){if(vr(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,cp=e=>!xn(e)&&e!==Ws;function Ia(...e){let{caseless:t,skipUndefined:s}=cp(this)&&this||{},n={},r=(i,o)=>{if(o==="__proto__"||o==="constructor"||o==="prototype")return;let a=t&&ap(n,o)||o,u=ka(n,a)?n[a]:void 0;wi(u)&&wi(i)?n[a]=Ia(u,i):wi(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]&&Ar(e[i],r);return n}var SA=(e,t,s,{allOwnKeys:n}={})=>(Ar(t,(r,i)=>{s&&ft(r)?Object.defineProperty(e,i,{__proto__:null,value:Dr(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),bA=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)},vA=(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&&Ei(e)}while(e&&(!s||s(e,t))&&e!==Object.prototype);return t},CA=(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},AA=e=>{if(!e)return null;if(wn(e))return e;let t=e.length;if(!op(t))return null;let s=new Array(t);for(;t-- >0;)s[t]=e[t];return s},xA=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&Ei(Uint8Array)),wA=(e,t)=>{let n=(e&&e[Ri]).call(e),r;for(;(r=n.next())&&!r.done;){let i=r.value;t.call(e,i[0],i[1])}},EA=(e,t)=>{let s,n=[];for(;(s=e.exec(t))!==null;)n.push(s);return n},RA=$t("HTMLFormElement"),FA=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),IA=$t("RegExp"),up=(e,t)=>{let s=Object.getOwnPropertyDescriptors(e),n={};Ar(s,(r,i)=>{let o;(o=t(r,i,e))!==!1&&(n[i]=o||r)}),Object.defineProperties(e,n)},kA=e=>{up(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+"'")})}})},TA=(e,t)=>{let s={},n=r=>{r.forEach(i=>{s[i]=!0})};return wn(e)?n(e):n(String(e).split(t)),s},PA=()=>{},LA=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function _A(e){return!!(e&&ft(e.append)&&e[rp]==="FormData"&&e[Ri])}var OA=e=>{let t=new Array(10),s=(n,r)=>{if(Cr(n)){if(t.indexOf(n)>=0)return;if(vr(n))return n;if(!("toJSON"in n)){t[r]=n;let i=wn(n)?[]:{};return Ar(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)},BA=$t("AsyncFunction"),MA=e=>e&&(Cr(e)||ft(e))&&ft(e.then)&&ft(e.catch),lp=((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)),NA=typeof queueMicrotask<"u"?queueMicrotask.bind(Ws):typeof process<"u"&&process.nextTick||lp,WA=e=>e!=null&&ft(e[Ri]),D={isArray:wn,isArrayBuffer:ip,isBuffer:vr,isFormData:pA,isArrayBufferView:XC,isString:eA,isNumber:op,isBoolean:tA,isObject:Cr,isPlainObject:wi,isEmptyObject:sA,isReadableStream:mA,isRequest:fA,isResponse:gA,isHeaders:hA,isUndefined:xn,isDate:nA,isFile:rA,isReactNativeBlob:iA,isReactNative:oA,isBlob:aA,isRegExp:IA,isFunction:ft,isStream:uA,isURLSearchParams:dA,isTypedArray:xA,isFileList:cA,forEach:Ar,merge:Ia,extend:SA,trim:yA,stripBOM:bA,inherits:DA,toFlatObject:vA,kindOf:Fi,kindOfTest:$t,endsWith:CA,toArray:AA,forEachEntry:wA,matchAll:EA,isHTMLForm:RA,hasOwnProperty:ka,hasOwnProp:ka,reduceDescriptors:up,freezeMethods:kA,toObjectSet:TA,toCamelCase:FA,noop:PA,toFiniteNumber:LA,findKey:ap,global:Ws,isContextDefined:cp,isSpecCompliantForm:_A,toJSONObject:OA,isAsyncFn:BA,isThenable:MA,setImmediate:lp,asap:NA,isIterable:WA};var UA=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"]),pp=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]&&UA[s])&&(s==="set-cookie"?t[s]?t[s].push(n):t[s]=[n]:t[s]=t[s]?t[s]+", "+n:n)}),t};var dp=Symbol("internals"),jA=/[^\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 xr(e){return e&&String(e).trim().toLowerCase()}function GA(e){return $A(e.replace(jA,""))}function ki(e){return e===!1||e==null?e:D.isArray(e)?e.map(ki):GA(String(e))}function HA(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 zA=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 qA(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,s,n)=>s.toUpperCase()+n)}function KA(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=xr(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]=ki(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())&&!zA(t))o(pp(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=xr(t),t){let n=D.findKey(this,t);if(n){let r=this[n];if(!s)return r;if(s===!0)return HA(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=xr(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=xr(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]=ki(r),delete s[i];return}let a=t?qA(i):String(i).trim();a!==i&&delete s[i],s[a]=ki(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:")}`),W?(e.log(q.error(" \u274C Trial expire
124
124
  `)},displayQuotaWarning:_=>{let{currentResourcesAnalyzed:U,maxResources:Y,requestedResources:ae,isTrial:W}=_;if(!W)return;U+ae>Y&&(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 ${U}/${Y} AI credits`)),e.log(q.warning(` This analysis would add ${ae} more`)),e.log(q.warning(` Total would be ${U+ae}/${Y}`)),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=SL();var CD=e=>e&&(e.Name||e.ResourceName||e.FunctionName)||"Unnamed";var pl=null,AD=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 bL={maxConcurrent:ei.DEFAULT_MAX_CONCURRENT,retryAttempts:ei.DEFAULT_RETRY_ATTEMPTS,retryDelay:ei.DEFAULT_RETRY_DELAY_MS,timeoutMs:ei.DEFAULT_TIMEOUT_MS},DL=e=>{if(!(e instanceof Error))return!1;let t=e.message??"";return t.startsWith("Polling timed out")||t==="Analysis timeout"||t.toLowerCase().includes("timeout")},Qo=(e,t)=>{let s=e.match(/^(.+?)(\s\([^)]+\))?$/);if(!s)return e;let[,n,r=""]=s;return`${ur(t,n)}${r}`},vL=e=>{let t=$r({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 DL(s)?{status:"timeout",redactedId:n}:(t.set(i,o+1),o>e.retryAttempts?{status:"skipped",redactedId:n}:{status:"fail",redactedId:n,error:s})}},CL=({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 x=wu(d,y,i,o,[]),v=Eu(x),E=t[d];if(!E)return{status:"skipped",redactedId:d};let O=E,M=()=>(s[O]||(s[O]={issues:[]}),s[O]),P=u.get(v);if(P){let ie=(P.issues||[]).map(_=>({..._,resource:O,resourceId:O})),se=M();return se.issues.push(...bn({existing:se.issues,incoming:ie})),se.resourceName=P.resourceName,{status:"success",redactedId:d,resourceKey:O,remappedIssues:ie,resourceName:P.resourceName}}let X=ur(a,E),B=ur("cdk-insights-stack",a),z=eo(E,l,c),ne={dependencies:z.dependencies.map(ie=>Qo(ie,a)),dependents:z.dependents.map(ie=>Qo(ie,a)),usageDescription:z.usageDescription};for(let ie=1;ie<=r.retryAttempts;ie++)try{let se=await Promise.race([e(B,X,y,y.Type,i,o,h,g,ne,p),new Promise((Y,ae)=>setTimeout(()=>ae(new Error("Analysis timeout")),r.timeoutMs))]);se.resourceId=O;let _=(se.issues||[]).map(Y=>({...Y,resource:O,resourceId:O})),U=M();return U.issues.push(...bn({existing:U.issues,incoming:_})),U.resourceName=se.resourceName,u.set(v,se,x),{status:"success",redactedId:d,resourceKey:O,remappedIssues:_,resourceName:se.resourceName}}catch(se){if(ie===r.retryAttempts)return n({analysisError:se,redactedId:d});await new Promise(_=>setTimeout(_,r.retryDelay*2**(ie-1)))}return{status:"fail",redactedId:d,error:new Error("Max retries exceeded")}},AL=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)},xL=10,xD=({analyzeResource:e,analyzeResourcesBatch:t,redactResources:s,config:n=bL})=>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),x=pb(a,b,u),v=new Map;for(let W of x){let ee=v.get(W.resourceId);ee?ee.push(W):v.set(W.resourceId,[W])}let E=Object.keys(y),O=E.length,M=Ks(i),P=new No({ttl:p?.ttl||6*60*60*1e3,maxSize:p?.maxSize||5e3,disabled:l||!p?.enabled});AD(P);let X=vL(n),B=CL({analyzeResource:e,redactionMapping:b,aggregatedResult:f,errorHandler:X,config:n,authToken:o,fingerprint:c,stackName:r,analysisCache:P,originalResources:i,relationships:M,aiModelId:d}),z=Yo.createSingleLineProgressTracker(O,"Analyzing resources with AI"),ne=Math.min(Math.max(1,Math.floor(m??1)),xL);if(ne>1&&!!t&&t){st.debug("Batched analysis enabled",{batchSize:ne,totalResources:O});let W=ur("cdk-insights-stack",r),ee=te=>{let pe=eo(te,M,i);return{dependencies:pe.dependencies.map(ce=>Qo(ce,r)),dependents:pe.dependents.map(ce=>Qo(ce,r)),usageDescription:pe.usageDescription}};for(let te=0;te<E.length;te+=ne){let pe=E.slice(te,te+ne),ce=async()=>{for(let re of pe){let G=await B({redactedId:re,redactedResources:y,findingsByResource:v,progressTracker:z});switch(h.processedCount++,G.status){case"success":h.successCount++;break;case"timeout":h.timeoutCount++,g.push({redactedId:re,resourceData:y[re],resourceType:y[re].Type,existingFindings:v.get(re)||[]});break;case"fail":case"skipped":h.failureCount++;break}}},Le=new Map,De=[];for(let re of pe){let G=y[re],k=b[re];if(!G||!k){h.processedCount++,h.failureCount++;continue}let J=wu(re,G,o,c,[]),Se=Eu(J),K=P.get(Se);if(K){let He=(K.issues||[]).map(mt=>({...mt,resource:k,resourceId:k}));f[k]||(f[k]={issues:[]});let xe=f[k];xe.issues.push(...bn({existing:xe.issues,incoming:He})),xe.resourceName=K.resourceName,h.processedCount++,h.successCount++;continue}let he=ur(r,k);Le.set(he,{redactedId:re,originalResourceId:k,cacheKey:Se,cacheComponents:J}),De.push({stableResourceId:he,resourceData:G,resourceType:G.Type,context:ee(k),existingFindings:v.get(re)||[]})}if(De.length!==0)try{let re=await Promise.race([t(W,De,o,c,d),new Promise((G,k)=>setTimeout(()=>k(new Error("Analysis timeout")),n.timeoutMs))]);for(let[G,k]of Le){let J=re.get(G);if(h.processedCount++,!J){st.warn(`Batched response missing entry for resource ${k.originalResourceId}`,{stableResourceId:G,redactedId:k.redactedId}),h.failureCount++;continue}let Se=(J.issues||[]).map(he=>({...he,resource:k.originalResourceId,resourceId:k.originalResourceId}));f[k.originalResourceId]||(f[k.originalResourceId]={issues:[]});let K=f[k.originalResourceId];K.issues.push(...bn({existing:K.issues,incoming:Se})),K.resourceName=J.resourceName,P.set(k.cacheKey,{resourceId:k.originalResourceId,issues:J.issues||[],resourceName:J.resourceName},k.cacheComponents),h.successCount++}}catch(re){st.warn("Batched analysis call failed \u2014 falling back to per-resource for this chunk",{error:re instanceof Error?re.message:String(re),chunkSize:pe.length}),await ce()}}}else await AL(E,n.maxConcurrent,async W=>{st.debug(`Starting analysis for resource ${W}`,{redactedId:W,maxConcurrent:n.maxConcurrent});let ee=await B({redactedId:W,redactedResources:y,findingsByResource:v,progressTracker:z});switch(h.processedCount++,st.debug(`Resource ${W} analysis result: ${ee.status}`,{redactedId:W,status:ee.status,hasProgressTracker:!!z}),ee.status){case"success":h.successCount++,st.debug(`Resource ${W} completed successfully`,{redactedId:W,resourceKey:ee.resourceKey});break;case"timeout":h.timeoutCount++,st.warn(`Resource ${W} timed out`,{redactedId:W}),g.push({redactedId:W,resourceData:y[W],resourceType:y[W].Type,existingFindings:v.get(W)||[]});break;case"fail":case"skipped":h.failureCount++,st.warn(`Resource ${W} failed or was skipped`,{redactedId:W,status:ee.status});break}});let se=Date.now()-h.startTime,_=z.getStats();if(st.debug("Analysis completed with progress tracker stats",{progressTrackerStats:_,performanceMetrics:h,totalTime:se,totalResources:O,maxConcurrent:n.maxConcurrent}),V.analysisComplete(se,h.successCount,h.failureCount,h.timeoutCount),h.failureCount>0||h.timeoutCount>0){V.newline(),V.info("\u{1F4CA} Performance Analysis:");let W=h.successCount>0?Math.round(se/1e3/h.successCount):0;V.comment(` \u23F1\uFE0F Average completion time: ${W}s`),V.comment(` \u{1F4CA} Success rate: ${(h.successCount/O*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 W of g){if(V.comment(` \u274C ${W.resourceType}: ${W.redactedId}`),W.resourceData?.Properties){let te=W.resourceData.Properties,pe=CD(te);V.comment(` \u{1F4DD} Name: ${pe}`)}W.existingFindings.length>0&&V.comment(` \u{1F50D} Existing findings: ${W.existingFindings.length}`),W.resourceData?.Metadata&&V.comment(" \u{1F4CD} Has metadata: Yes"),["AWS::CloudFormation::Stack","AWS::Serverless::Application","AWS::ECS::Service"].includes(W.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 U=new Set(Object.keys(f)),Y=new Set(Object.values(b)),ae=Array.from(Y).filter(W=>!U.has(W)||!f[W]?.issues?.length);if(ae.length>0){let W=P.getCachedResultsForResources(ae),ee=0;for(let[te,pe]of Array.from(W.entries())){if(f[te]?.issues?.length>0)continue;let ce=(pe.issues||[]).map(Le=>({...Le,resource:te,resourceId:te}));ce.length>0&&(f[te]||(f[te]={issues:[]}),f[te].issues.push(...ce),f[te].resourceName=pe.resourceName,ee+=ce.length)}ee>0}return f};var fl=require("node:child_process"),nt=Z(require("node:fs")),gl=Z(require("node:os")),li=Z(require("node:path"));var ED="1.41.1",wL={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/"},wD=e=>e.toLowerCase().replace(/[^\w\s-]/g,"").trim().replace(/\s+/g,"-").replace(/-+/g,"-"),EL=(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},RL=e=>e?e.split(`
127
+ `))}}},V=SL();var CD=e=>e&&(e.Name||e.ResourceName||e.FunctionName)||"Unnamed";var pl=null,AD=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 bL={maxConcurrent:ei.DEFAULT_MAX_CONCURRENT,retryAttempts:ei.DEFAULT_RETRY_ATTEMPTS,retryDelay:ei.DEFAULT_RETRY_DELAY_MS,timeoutMs:ei.DEFAULT_TIMEOUT_MS},DL=e=>{if(!(e instanceof Error))return!1;let t=e.message??"";return t.startsWith("Polling timed out")||t==="Analysis timeout"||t.toLowerCase().includes("timeout")},Qo=(e,t)=>{let s=e.match(/^(.+?)(\s\([^)]+\))?$/);if(!s)return e;let[,n,r=""]=s;return`${ur(t,n)}${r}`},vL=e=>{let t=$r({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 DL(s)?{status:"timeout",redactedId:n}:(t.set(i,o+1),o>e.retryAttempts?{status:"skipped",redactedId:n}:{status:"fail",redactedId:n,error:s})}},CL=({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 x=wu(d,y,i,o,[]),v=Eu(x),E=t[d];if(!E)return{status:"skipped",redactedId:d};let O=E,M=()=>(s[O]||(s[O]={issues:[]}),s[O]),P=u.get(v);if(P){let ie=(P.issues||[]).map(_=>({..._,resource:O,resourceId:O})),se=M();return se.issues.push(...bn({existing:se.issues,incoming:ie})),se.resourceName=P.resourceName,{status:"success",redactedId:d,resourceKey:O,remappedIssues:ie,resourceName:P.resourceName}}let X=ur(a,E),B=ur("cdk-insights-stack",a),z=eo(E,l,c),ne={dependencies:z.dependencies.map(ie=>Qo(ie,a)),dependents:z.dependents.map(ie=>Qo(ie,a)),usageDescription:z.usageDescription};for(let ie=1;ie<=r.retryAttempts;ie++)try{let se=await Promise.race([e(B,X,y,y.Type,i,o,h,g,ne,p),new Promise((Y,ae)=>setTimeout(()=>ae(new Error("Analysis timeout")),r.timeoutMs))]);se.resourceId=O;let _=(se.issues||[]).map(Y=>({...Y,resource:O,resourceId:O})),U=M();return U.issues.push(...bn({existing:U.issues,incoming:_})),U.resourceName=se.resourceName,u.set(v,se,x),{status:"success",redactedId:d,resourceKey:O,remappedIssues:_,resourceName:se.resourceName}}catch(se){if(ie===r.retryAttempts)return n({analysisError:se,redactedId:d});await new Promise(_=>setTimeout(_,r.retryDelay*2**(ie-1)))}return{status:"fail",redactedId:d,error:new Error("Max retries exceeded")}},AL=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)},xL=10,xD=({analyzeResource:e,analyzeResourcesBatch:t,redactResources:s,config:n=bL})=>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),x=pb(a,b,u),v=new Map;for(let W of x){let ee=v.get(W.resourceId);ee?ee.push(W):v.set(W.resourceId,[W])}let E=Object.keys(y),O=E.length,M=Ks(i),P=new No({ttl:p?.ttl||6*60*60*1e3,maxSize:p?.maxSize||5e3,disabled:l||!p?.enabled});AD(P);let X=vL(n),B=CL({analyzeResource:e,redactionMapping:b,aggregatedResult:f,errorHandler:X,config:n,authToken:o,fingerprint:c,stackName:r,analysisCache:P,originalResources:i,relationships:M,aiModelId:d}),z=Yo.createSingleLineProgressTracker(O,"Analyzing resources with AI"),ne=Math.min(Math.max(1,Math.floor(m??1)),xL);if(ne>1&&!!t&&t){st.debug("Batched analysis enabled",{batchSize:ne,totalResources:O});let W=ur("cdk-insights-stack",r),ee=te=>{let pe=eo(te,M,i);return{dependencies:pe.dependencies.map(ce=>Qo(ce,r)),dependents:pe.dependents.map(ce=>Qo(ce,r)),usageDescription:pe.usageDescription}};for(let te=0;te<E.length;te+=ne){let pe=E.slice(te,te+ne),ce=async()=>{for(let re of pe){let G=await B({redactedId:re,redactedResources:y,findingsByResource:v,progressTracker:z});switch(h.processedCount++,G.status){case"success":h.successCount++;break;case"timeout":h.timeoutCount++,g.push({redactedId:re,resourceData:y[re],resourceType:y[re].Type,existingFindings:v.get(re)||[]});break;case"fail":case"skipped":h.failureCount++;break}}},Le=new Map,De=[];for(let re of pe){let G=y[re],k=b[re];if(!G||!k){h.processedCount++,h.failureCount++;continue}let J=wu(re,G,o,c,[]),Se=Eu(J),K=P.get(Se);if(K){let He=(K.issues||[]).map(mt=>({...mt,resource:k,resourceId:k}));f[k]||(f[k]={issues:[]});let xe=f[k];xe.issues.push(...bn({existing:xe.issues,incoming:He})),xe.resourceName=K.resourceName,h.processedCount++,h.successCount++;continue}let he=ur(r,k);Le.set(he,{redactedId:re,originalResourceId:k,cacheKey:Se,cacheComponents:J}),De.push({stableResourceId:he,resourceData:G,resourceType:G.Type,context:ee(k),existingFindings:v.get(re)||[]})}if(De.length!==0)try{let re=await Promise.race([t(W,De,o,c,d),new Promise((G,k)=>setTimeout(()=>k(new Error("Analysis timeout")),n.timeoutMs))]);for(let[G,k]of Le){let J=re.get(G);if(h.processedCount++,!J){st.warn(`Batched response missing entry for resource ${k.originalResourceId}`,{stableResourceId:G,redactedId:k.redactedId}),h.failureCount++;continue}let Se=(J.issues||[]).map(he=>({...he,resource:k.originalResourceId,resourceId:k.originalResourceId}));f[k.originalResourceId]||(f[k.originalResourceId]={issues:[]});let K=f[k.originalResourceId];K.issues.push(...bn({existing:K.issues,incoming:Se})),K.resourceName=J.resourceName,P.set(k.cacheKey,{resourceId:k.originalResourceId,issues:J.issues||[],resourceName:J.resourceName},k.cacheComponents),h.successCount++}}catch(re){st.warn("Batched analysis call failed \u2014 falling back to per-resource for this chunk",{error:re instanceof Error?re.message:String(re),chunkSize:pe.length}),await ce()}}}else await AL(E,n.maxConcurrent,async W=>{st.debug(`Starting analysis for resource ${W}`,{redactedId:W,maxConcurrent:n.maxConcurrent});let ee=await B({redactedId:W,redactedResources:y,findingsByResource:v,progressTracker:z});switch(h.processedCount++,st.debug(`Resource ${W} analysis result: ${ee.status}`,{redactedId:W,status:ee.status,hasProgressTracker:!!z}),ee.status){case"success":h.successCount++,st.debug(`Resource ${W} completed successfully`,{redactedId:W,resourceKey:ee.resourceKey});break;case"timeout":h.timeoutCount++,st.warn(`Resource ${W} timed out`,{redactedId:W}),g.push({redactedId:W,resourceData:y[W],resourceType:y[W].Type,existingFindings:v.get(W)||[]});break;case"fail":case"skipped":h.failureCount++,st.warn(`Resource ${W} failed or was skipped`,{redactedId:W,status:ee.status});break}});let se=Date.now()-h.startTime,_=z.getStats();if(st.debug("Analysis completed with progress tracker stats",{progressTrackerStats:_,performanceMetrics:h,totalTime:se,totalResources:O,maxConcurrent:n.maxConcurrent}),V.analysisComplete(se,h.successCount,h.failureCount,h.timeoutCount),h.failureCount>0||h.timeoutCount>0){V.newline(),V.info("\u{1F4CA} Performance Analysis:");let W=h.successCount>0?Math.round(se/1e3/h.successCount):0;V.comment(` \u23F1\uFE0F Average completion time: ${W}s`),V.comment(` \u{1F4CA} Success rate: ${(h.successCount/O*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 W of g){if(V.comment(` \u274C ${W.resourceType}: ${W.redactedId}`),W.resourceData?.Properties){let te=W.resourceData.Properties,pe=CD(te);V.comment(` \u{1F4DD} Name: ${pe}`)}W.existingFindings.length>0&&V.comment(` \u{1F50D} Existing findings: ${W.existingFindings.length}`),W.resourceData?.Metadata&&V.comment(" \u{1F4CD} Has metadata: Yes"),["AWS::CloudFormation::Stack","AWS::Serverless::Application","AWS::ECS::Service"].includes(W.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 U=new Set(Object.keys(f)),Y=new Set(Object.values(b)),ae=Array.from(Y).filter(W=>!U.has(W)||!f[W]?.issues?.length);if(ae.length>0){let W=P.getCachedResultsForResources(ae),ee=0;for(let[te,pe]of Array.from(W.entries())){if(f[te]?.issues?.length>0)continue;let ce=(pe.issues||[]).map(Le=>({...Le,resource:te,resourceId:te}));ce.length>0&&(f[te]||(f[te]={issues:[]}),f[te].issues.push(...ce),f[te].resourceName=pe.resourceName,ee+=ce.length)}ee>0}return f};var fl=require("node:child_process"),nt=Z(require("node:fs")),gl=Z(require("node:os")),li=Z(require("node:path"));var ED="1.41.2",wL={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/"},wD=e=>e.toLowerCase().replace(/[^\w\s-]/g,"").trim().replace(/\s+/g,"-").replace(/-+/g,"-"),EL=(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},RL=e=>e?e.split(`
128
128
  `).map(t=>t.trim()).filter(Boolean).join(`
129
129
  `):"",ml=e=>{let t=`- **Issue:** ${e.issue}`;return e.recommendation&&(t+=`
130
130
  - **Recommendation:** ${RL(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.41.1",
3
+ "version": "1.41.2",
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",