@wtdlee/repomap 0.3.3 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/analyzers/index.d.ts +2 -2
- package/dist/analyzers/index.js +1 -1
- package/dist/{chunk-53ANJE42.js → chunk-EYHNEFTO.js} +18 -18
- package/dist/chunk-PSM6AV63.js +2 -0
- package/dist/cli.js +1 -1
- package/dist/{dataflow-analyzer-BfAiqVUp.d.ts → dataflow-analyzer-LeE44O3x.d.ts} +25 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/server/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-J2CM7T7U.js +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { B as BaseAnalyzer } from '../dataflow-analyzer-
|
|
2
|
-
export { D as DataFlowAnalyzer, G as GraphQLAnalyzer, P as PagesAnalyzer } from '../dataflow-analyzer-
|
|
1
|
+
import { B as BaseAnalyzer } from '../dataflow-analyzer-LeE44O3x.js';
|
|
2
|
+
export { D as DataFlowAnalyzer, G as GraphQLAnalyzer, P as PagesAnalyzer } from '../dataflow-analyzer-LeE44O3x.js';
|
|
3
3
|
import { RepositoryConfig, AnalysisResult } from '../types.js';
|
|
4
4
|
|
|
5
5
|
/**
|
package/dist/analyzers/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{a as BaseAnalyzer,d as DataFlowAnalyzer,c as GraphQLAnalyzer,b as PagesAnalyzer,e as RestApiAnalyzer}from'../chunk-
|
|
1
|
+
export{a as BaseAnalyzer,d as DataFlowAnalyzer,c as GraphQLAnalyzer,b as PagesAnalyzer,e as RestApiAnalyzer}from'../chunk-PSM6AV63.js';
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import {a as a$2}from'./chunk-H4YGP3GL.js';import {a as a$3}from'./chunk-VV3A3UE3.js';import {e,d,c,b as b$2}from'./chunk-
|
|
2
|
-
`);let
|
|
3
|
-
\u{1F4E6} Analyzing ${i.displayName}...`);let r=await this.analyzeRepository(i);
|
|
4
|
-
\u{1F517} Running cross-repository analysis...`);let
|
|
5
|
-
\u{1F4CA} Generating diagrams...`);let e=
|
|
6
|
-
\u{1F4DD} Writing documentation...`),await this.writeDocumentation(
|
|
7
|
-
\u2728 Documentation generation complete!`),console.log(`\u{1F4C1} Output: ${this.config.outputDir}`),
|
|
1
|
+
import {a as a$2}from'./chunk-H4YGP3GL.js';import {a as a$3}from'./chunk-VV3A3UE3.js';import {e,d as d$1,c,b as b$2}from'./chunk-PSM6AV63.js';import {a,b as b$1}from'./chunk-XWZH2RDG.js';import {a as a$1}from'./chunk-MOEA75XK.js';import {k}from'./chunk-PTR5IROV.js';import {simpleGit}from'simple-git';import*as d from'fs/promises';import*as m from'path';import H from'fast-glob';import*as w from'crypto';import F from'express';import {Server}from'socket.io';import*as z from'http';import {marked}from'marked';import*as P from'net';var C="1.1",x=class{cacheDir;manifest;manifestPath;dirty=false;constructor(a){this.cacheDir=m.join(a,".repomap-cache"),this.manifestPath=m.join(this.cacheDir,"manifest.json"),this.manifest={version:C,entries:{}};}async init(){try{await d.mkdir(this.cacheDir,{recursive:!0});}catch(a){console.warn(` Warning: Could not create cache directory: ${a.message}`);return}try{let a=await d.readFile(this.manifestPath,"utf-8"),t=JSON.parse(a);t.version===C?this.manifest=t:(console.log(" Cache version mismatch, clearing cache..."),await this.clear());}catch{}}async computeFileHash(a){try{let t=await d.readFile(a,"utf-8");return w.createHash("md5").update(t).digest("hex")}catch{return ""}}async computeFilesHash(a){let t=[...a].sort(),e=50,o;t.length<=e*2?o=t:o=[...t.slice(0,e),...t.slice(-e)];let s=await Promise.all(o.map(i=>this.computeFileHash(i))),n=w.createHash("md5").update(String(t.length)).digest("hex");return w.createHash("md5").update(s.join("")+n).digest("hex")}get(a,t){let e=this.manifest.entries[a];return e&&e.hash===t?e.data:null}set(a,t,e){this.manifest.entries[a]={hash:t,timestamp:Date.now(),data:e},this.dirty=true;}async save(){if(this.dirty)try{await d.mkdir(this.cacheDir,{recursive:!0}),await d.writeFile(this.manifestPath,JSON.stringify(this.manifest,null,2)),this.dirty=!1;}catch(a){console.warn(" Warning: Failed to save cache:",a.message);}}async clear(){this.manifest={version:C,entries:{}},this.dirty=true;try{await d.rm(this.cacheDir,{recursive:!0,force:!0}),await d.mkdir(this.cacheDir,{recursive:!0});}catch{}}getStats(){let a=Object.keys(this.manifest.entries).length,t=JSON.stringify(this.manifest).length;return {entries:a,size:t>1024*1024?`${(t/1024/1024).toFixed(1)}MB`:`${(t/1024).toFixed(1)}KB`}}};var b=class{config;mermaidGenerator;markdownGenerator;noCache;constructor(a$1,t){this.config=a$1,this.mermaidGenerator=new a,this.markdownGenerator=new b$1,this.noCache=t?.noCache??false;}async generate(){console.log(`\u{1F680} Starting documentation generation...
|
|
2
|
+
`);let a=[];for(let i of this.config.repositories)try{console.log(`
|
|
3
|
+
\u{1F4E6} Analyzing ${i.displayName}...`);let r=await this.analyzeRepository(i);a.push(r),console.log(`\u2705 Completed ${i.displayName}`);}catch(r){console.error(`\u274C Failed to analyze ${i.name}:`,r.message);}console.log(`
|
|
4
|
+
\u{1F517} Running cross-repository analysis...`);let t=this.analyzeCrossRepo(a);console.log(`
|
|
5
|
+
\u{1F4CA} Generating diagrams...`);let e=a.map(i=>i.analysis),o=this.extractCrossRepoLinks(e),s=this.mermaidGenerator.generateAll(e,o),n={generatedAt:new Date().toISOString(),repositories:a,crossRepoAnalysis:t,diagrams:s};return console.log(`
|
|
6
|
+
\u{1F4DD} Writing documentation...`),await this.writeDocumentation(n),console.log(`
|
|
7
|
+
\u2728 Documentation generation complete!`),console.log(`\u{1F4C1} Output: ${this.config.outputDir}`),n}async analyzeRepository(a){let t=new x(a.path);await t.init();let{version:e,commitHash:o}=await this.getRepoInfo(a),s=await H(["**/*.{ts,tsx,graphql}"],{cwd:a.path,ignore:["**/node_modules/**","**/.next/**","**/dist/**","**/build/**"],absolute:true}),n=await t.computeFilesHash(s),i=`analysis_v${e}_${a.name}_${o}`;this.noCache&&console.log(" \u{1F504} Cache disabled, analyzing from scratch...");let r=this.noCache?null:t.get(i,n);if(r){console.log(` \u26A1 Using cached analysis (hash: ${n.slice(0,8)}...)`);let c={totalPages:r.pages.length,totalComponents:r.components.length,totalGraphQLOperations:r.graphqlOperations.length,totalDataFlows:r.dataFlows.length,authRequiredPages:r.pages.filter(q=>q.authentication.required).length,publicPages:r.pages.filter(q=>!q.authentication.required).length};return {name:a.name,displayName:a.displayName,version:e,commitHash:o,analysis:r,summary:c}}let l=a.analyzers.map(c=>this.createAnalyzer(c,a)).filter(c=>c!==null);console.log(` Running ${l.length} analyzers in parallel...`);let h=Date.now(),g=await Promise.all(l.map(c=>c.analyze()));console.log(` Analysis completed in ${((Date.now()-h)/1e3).toFixed(1)}s`);let p=this.mergeAnalysisResults(g,a.name,e,o);t.set(i,n,p),await t.save(),console.log(` \u{1F4BE} Analysis cached (hash: ${n.slice(0,8)}...)`);let B={totalPages:p.pages.length,totalComponents:p.components.length,totalGraphQLOperations:p.graphqlOperations.length,totalDataFlows:p.dataFlows.length,authRequiredPages:p.pages.filter(c=>c.authentication.required).length,publicPages:p.pages.filter(c=>!c.authentication.required).length};return {name:a.name,displayName:a.displayName,version:e,commitHash:o,analysis:p,summary:B}}async getRepoInfo(a){try{let o=(await simpleGit(a.path).log({n:1})).latest?.hash||"unknown",s="unknown";try{let n=m.join(a.path,"package.json");s=JSON.parse(await d.readFile(n,"utf-8")).version||"unknown";}catch{}return {version:s,commitHash:o}}catch{return {version:"unknown",commitHash:"unknown"}}}createAnalyzer(a,t){switch(a){case "pages":if(t.type==="nextjs"||t.type==="rails"||t.type==="generic")return new b$2(t);break;case "graphql":return new c(t);case "dataflow":case "components":return new d$1(t);case "rest-api":case "api":return new e(t)}return null}mergeAnalysisResults(a,t,e,o){let s={repository:t,timestamp:new Date().toISOString(),version:e,commitHash:o,pages:[],graphqlOperations:[],apiCalls:[],components:[],dataFlows:[],apiEndpoints:[],models:[],crossRepoLinks:[]};for(let n of a)n.pages&&s.pages.push(...n.pages),n.graphqlOperations&&s.graphqlOperations.push(...n.graphqlOperations),n.apiCalls&&s.apiCalls.push(...n.apiCalls),n.components&&s.components.push(...n.components),n.dataFlows&&s.dataFlows.push(...n.dataFlows),n.apiEndpoints&&s.apiEndpoints.push(...n.apiEndpoints),n.models&&s.models.push(...n.models),n.crossRepoLinks&&s.crossRepoLinks.push(...n.crossRepoLinks);return s}analyzeCrossRepo(a){let t=[],e=[],o=[],s=[],n=new Map;for(let l of a)for(let h of l.analysis.graphqlOperations){let g=n.get(h.name)||[];g.push(l.name),n.set(h.name,g);}for(let[l,h]of n)h.length>1&&t.push(l);let i=a.filter(l=>l.analysis.pages.length>0),r=a.filter(l=>l.analysis.apiEndpoints.length>0);for(let l of i)for(let h of r)for(let g of h.analysis.apiEndpoints)e.push({frontend:l.name,backend:h.name,endpoint:g.path,operations:l.analysis.graphqlOperations.filter(p=>p.usedIn.length>0).map(p=>p.name)});return {sharedTypes:t,apiConnections:e,navigationFlows:o,dataFlowAcrossRepos:s}}extractCrossRepoLinks(a){let t=[],e=new Map;for(let o of a)for(let s of o.graphqlOperations){let n=e.get(s.name)||[];n.push(o),e.set(s.name,n);}for(let[o,s]of e)s.length>1&&t.push({sourceRepo:s[0].repository,sourcePath:`graphql/${o}`,targetRepo:s[1].repository,targetPath:`graphql/${o}`,linkType:"graphql-operation",description:`Shared GraphQL operation: ${o}`});return t}async writeDocumentation(a){let t=this.config.outputDir;await d.mkdir(t,{recursive:true});let e=this.markdownGenerator.generateDocumentation(a);for(let[s,n]of e){let i=m.join(t,s),r=m.dirname(i);await d.mkdir(r,{recursive:true}),await d.writeFile(i,n,"utf-8"),console.log(` \u{1F4C4} ${s}`);}let o=m.join(t,"report.json");await d.writeFile(o,JSON.stringify(a,null,2),"utf-8"),console.log(" \u{1F4CB} report.json");}};function Q(u){return new Promise(a=>{let t=P.createServer();t.once("error",e=>{e.code,a(false);}),t.once("listening",()=>{t.close(),a(true);}),t.listen(u);})}async function O(u,a=10){for(let t=0;t<a;t++){let e=u+t;if(await Q(e))return e}throw new Error(`No available port found between ${u} and ${u+a-1}`)}var I=class{config;port;app;server;io;engine;currentReport=null;envResult=null;railsAnalysis=null;constructor(a,t=3030,e){this.config=a,this.port=t,this.app=F(),this.server=z.createServer(this.app),this.io=new Server(this.server),this.engine=new b(a,{noCache:e?.noCache}),this.setupRoutes(),this.setupSocketIO();}setupRoutes(){this.app.use("/assets",F.static(m.join(this.config.outputDir,"assets"))),["common.css","page-map.css","docs.css","rails-map.css"].forEach(t=>{this.app.get(`/${t}`,async(e,o)=>{let s=[m.join(m.dirname(new URL(import.meta.url).pathname),"generators","assets",t),m.join(m.dirname(new URL(import.meta.url).pathname),"..","generators","assets",t),m.join(process.cwd(),"dist","generators","assets",t),m.join(process.cwd(),"src","generators","assets",t)];for(let n of s)try{let i=await d.readFile(n,"utf-8");o.type("text/css").send(i);return}catch{}o.status(404).send("CSS not found");});}),this.app.get("/",(t,e)=>{e.redirect("/page-map");}),this.app.get("/page-map",(t,e)=>{if(!this.currentReport){e.status(503).send("Documentation not ready yet");return}let o=new a$1;e.send(o.generatePageMapHtml(this.currentReport,{envResult:this.envResult,railsAnalysis:this.railsAnalysis}));}),this.app.get("/rails-map",(t,e)=>{if(!this.railsAnalysis){e.status(404).send("No Rails environment detected");return}let o=new a$2;e.send(o.generateFromResult(this.railsAnalysis));}),this.app.get("/docs",async(t,e)=>{e.send(await this.renderPage("index"));}),this.app.get("/docs/*path",async(t,e)=>{let o=t.params.path,s=Array.isArray(o)?o.join("/"):o||"index";e.send(await this.renderPage(s));}),this.app.get("/api/report",(t,e)=>{e.json(this.currentReport);}),this.app.get("/api/env",(t,e)=>{e.json(this.envResult);}),this.app.get("/api/rails",(t,e)=>{this.railsAnalysis?e.json(this.railsAnalysis):e.status(404).json({error:"No Rails analysis available"});}),this.app.get("/api/diagram/:name",(t,e)=>{let o=this.currentReport?.diagrams.find(s=>s.title.toLowerCase().replace(/\s+/g,"-")===t.params.name);o?e.json(o):e.status(404).json({error:"Diagram not found"});}),this.app.post("/api/regenerate",async(t,e)=>{try{await this.regenerate(),e.json({success:!0});}catch(o){e.status(500).json({error:o.message});}});}setupSocketIO(){this.io.on("connection",a=>{console.log("Client connected"),a.on("disconnect",()=>{console.log("Client disconnected");});});}async renderPage(a){let t=a.replace(/\.md$/,""),e=m.join(this.config.outputDir,`${t}.md`),o="";try{let s=await d.readFile(e,"utf-8"),n=await marked.parse(s);n=n.replace(/<pre><code class="language-mermaid">([\s\S]*?)<\/code><\/pre>/g,'<div class="mermaid">$1</div>'),n=n.replace(/<table>/g,'<div class="table-wrapper"><table>'),n=n.replace(/<\/table>/g,"</table></div>"),o=n;}catch(s){console.error(`Failed to render page: ${e}`,s),o=`<h1>Page not found</h1><p>Path: ${t}</p>`;}return this.getHtmlTemplate(o)}getGraphQLData(){if(!this.currentReport)return "[]";let a=[];for(let t of this.currentReport.repositories)for(let e of t.analysis?.graphqlOperations||[])a.push({name:e.name,type:e.type,returnType:e.returnType,variables:e.variables,fields:e.fields,usedIn:e.usedIn});return JSON.stringify(a)}getApiCallsData(){if(!this.currentReport)return "[]";let a=[];for(let t of this.currentReport.repositories)for(let e of t.analysis?.apiCalls||[])a.push({id:e.id,method:e.method,url:e.url,callType:e.callType,filePath:e.filePath,line:e.line,containingFunction:e.containingFunction,requiresAuth:e.requiresAuth});return JSON.stringify(a)}getHtmlTemplate(a){let t=this.getGraphQLData(),e=this.getApiCallsData();return `<!DOCTYPE html>
|
|
8
8
|
<html lang="ja">
|
|
9
9
|
<head>
|
|
10
10
|
<meta charset="UTF-8">
|
|
@@ -13,7 +13,7 @@ import {a as a$2}from'./chunk-H4YGP3GL.js';import {a as a$3}from'./chunk-VV3A3UE
|
|
|
13
13
|
<script src="https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js"></script>
|
|
14
14
|
<script src="/socket.io/socket.io.js"></script>
|
|
15
15
|
<script>
|
|
16
|
-
window.graphqlOps = ${
|
|
16
|
+
window.graphqlOps = ${t};
|
|
17
17
|
window.apiCalls = ${e};
|
|
18
18
|
// Create multiple lookup maps for different naming conventions
|
|
19
19
|
window.gqlMap = new Map();
|
|
@@ -97,11 +97,11 @@ import {a as a$2}from'./chunk-H4YGP3GL.js';import {a as a$3}from'./chunk-VV3A3UE
|
|
|
97
97
|
<div class="nav-group">
|
|
98
98
|
<span class="nav-group-title">Documentation</span>
|
|
99
99
|
<div class="nav-subitems">
|
|
100
|
-
${this.config.repositories.map(
|
|
101
|
-
<a href="/docs/repos/${
|
|
102
|
-
<a href="/docs/repos/${
|
|
103
|
-
<a href="/docs/repos/${
|
|
104
|
-
<a href="/docs/repos/${
|
|
100
|
+
${this.config.repositories.map(o=>`
|
|
101
|
+
<a href="/docs/repos/${o.name}/pages">Pages</a>
|
|
102
|
+
<a href="/docs/repos/${o.name}/components">Components</a>
|
|
103
|
+
<a href="/docs/repos/${o.name}/graphql">GraphQL</a>
|
|
104
|
+
<a href="/docs/repos/${o.name}/dataflow">Data Flow</a>
|
|
105
105
|
`).join("")}
|
|
106
106
|
</div>
|
|
107
107
|
</div>
|
|
@@ -117,7 +117,7 @@ import {a as a$2}from'./chunk-H4YGP3GL.js';import {a as a$3}from'./chunk-VV3A3UE
|
|
|
117
117
|
</aside>
|
|
118
118
|
<div class="content-area">
|
|
119
119
|
<div class="content">
|
|
120
|
-
${
|
|
120
|
+
${a}
|
|
121
121
|
</div>
|
|
122
122
|
</div>
|
|
123
123
|
</div>
|
|
@@ -946,12 +946,12 @@ import {a as a$2}from'./chunk-H4YGP3GL.js';import {a as a$3}from'./chunk-VV3A3UE
|
|
|
946
946
|
}
|
|
947
947
|
</script>
|
|
948
948
|
</body>
|
|
949
|
-
</html>`}async start(
|
|
949
|
+
</html>`}async start(a=true){let t=this.config.repositories[0]?.path||process.cwd();if(console.log("\u{1F50D} Detecting project environments..."),this.envResult=await a$3(t),this.envResult.environments.length>0){console.log(` Found: ${this.envResult.environments.map(e=>e.type).join(", ")}`);for(let e of this.envResult.environments)e.features.length>0&&console.log(` ${e.type} features: ${e.features.join(", ")}`);}if(console.log(`
|
|
950
950
|
\u{1F4DA} Generating documentation...`),this.currentReport=await this.engine.generate(),this.envResult.hasRails){console.log(`
|
|
951
|
-
\u{1F6E4}\uFE0F Analyzing Rails application...`);try{this.railsAnalysis=await k(
|
|
951
|
+
\u{1F6E4}\uFE0F Analyzing Rails application...`);try{this.railsAnalysis=await k(t),console.log(" \u2705 Rails analysis complete");}catch(e){console.error(" \u26A0\uFE0F Rails analysis failed:",e.message);}}try{let e=await O(this.port);e!==this.port&&console.log(`
|
|
952
952
|
\u26A0\uFE0F Port ${this.port} is in use, using port ${e} instead`),this.port=e;}catch(e){console.error(`
|
|
953
953
|
\u274C Failed to find available port: ${e.message}`),process.exit(1);}if(this.server.listen(this.port,()=>{console.log(`
|
|
954
954
|
\u{1F310} Documentation server running at http://localhost:${this.port}`),this.envResult?.hasRails&&this.envResult?.hasNextjs&&console.log(" \u{1F4CA} Multiple environments detected - use tabs to switch views"),console.log(` Press Ctrl+C to stop
|
|
955
|
-
`);}),
|
|
956
|
-
\u{1F504} Regenerating documentation...`),this.currentReport=await this.engine.generate(),this.envResult?.hasRails){let
|
|
955
|
+
`);}),a){let e=(await import('open')).default;await e(`http://localhost:${this.port}`);}this.config.watch.enabled&&this.watchForChanges();}async regenerate(){if(console.log(`
|
|
956
|
+
\u{1F504} Regenerating documentation...`),this.currentReport=await this.engine.generate(),this.envResult?.hasRails){let a=this.config.repositories[0]?.path||process.cwd();try{this.railsAnalysis=await k(a);}catch(t){console.error("\u26A0\uFE0F Rails re-analysis failed:",t.message);}}this.io.emit("reload"),console.log("\u2705 Documentation regenerated");}async watchForChanges(){let a=this.config.repositories.map(e=>e.path),t=null;for(let e of a)try{let o=d.watch(e,{recursive:!0});(async()=>{for await(let s of o)s.filename&&(s.filename.endsWith(".ts")||s.filename.endsWith(".tsx"))&&(t&&clearTimeout(t),t=setTimeout(async()=>{await this.regenerate();},this.config.watch.debounce));})();}catch(o){console.warn(`Warning: Could not watch directory ${e}:`,o.message);}}stop(){this.server.close(),console.log(`
|
|
957
957
|
\u{1F44B} Server stopped`);}};export{b as a,I as b};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {Project,Node,SyntaxKind}from'ts-morph';import z from'fast-glob';import*as F from'path';import*as W from'fs';import*as O from'fs/promises';import {parse}from'graphql';var D=class{config;basePath;constructor(e){this.config=e,this.basePath=e.path;}resolvePath(e){return `${this.basePath}/${e}`}getSetting(e,t=""){return this.config.settings[e]??t}log(e){console.log(`[${this.getName()}] ${e}`);}warn(e){console.warn(`[${this.getName()}] \u26A0\uFE0F ${e}`);}error(e,t){console.error(`[${this.getName()}] \u274C ${e}`,t?.message||"");}};async function E(T,e,t=8){let n=new Array(T.length).fill(null),s=0;async function i(){for(;s<T.length;){let o=s++;if(o<T.length)try{n[o]=await e(T[o],o);}catch{n[o]=null;}}}let a=Array(Math.min(t,T.length)).fill(null).map(()=>i());return await Promise.all(a),n.filter(o=>o!==null)}var q=class extends D{project;codegenMap=new Map;constructor(e){super(e),this.project=new Project({tsConfigFilePath:this.resolvePath("tsconfig.json"),skipAddingFilesFromTsConfig:true});}extractOperationNameFromGql(e){let t=e.match(/(?:query|mutation|subscription)\s+(\w+)/);if(t&&t[1])return t[1];let n=e.match(/`\s*(?:query|mutation|subscription)\s+(\w+)/);if(n&&n[1])return n[1];let s=e.match(/GraphQL[^`]*`\s*(?:\n\s*)?(?:query|mutation|subscription)\s+(\w+)/);return s&&s[1]?s[1]:null}findOperationNameFromVariable(e,t){let n=e.getVariableDeclaration(t);if(!n){let o=e.getExportedDeclarations().get(t);if(o&&o.length>0){let r=o[0];Node.isVariableDeclaration(r)&&(n=r);}}if(n||(n=e.getVariableDeclarations().find(o=>o.getName()===t)),!n){let a=e.getFullText(),o=[new RegExp(`(?:const|let|var)\\s+${t}\\s*=\\s*gql\\s*\\(\\s*/\\*[^*]*\\*/\\s*\`\\s*(?:query|mutation|subscription)\\s+(\\w+)`,"s"),new RegExp(`(?:const|let|var)\\s+${t}\\s*=\\s*gql\`\\s*(?:query|mutation|subscription)\\s+(\\w+)`,"s"),new RegExp(`(?:const|let|var)\\s+${t}\\s*=\\s*gql\\s*\\(\`\\s*(?:query|mutation|subscription)\\s+(\\w+)`,"s"),new RegExp(`(?:const|let|var)\\s+${t}\\s*=\\s*graphql\\s*\\(\`\\s*(?:query|mutation|subscription)\\s+(\\w+)`,"s")];for(let r of o){let c=a.match(r);if(c&&c[1])return c[1]}return null}let s=n.getInitializer();if(!s)return null;let i=s.getText();return this.extractOperationNameFromGql(i)}getName(){return "PagesAnalyzer"}async analyze(){this.log("Starting page analysis..."),await this.loadCodegenMapping(),await this.analyzeAppFile();let e=await this.findPageFiles();this.log(`Found ${e.length} page files`);for(let s of e)try{this.project.addSourceFileAtPath(s);}catch{}let n=(await E(e,async s=>{let i=this.detectPagesRoot(s);return this.analyzePageFile(s,i)},4)).filter(s=>s!==null);return this.log(`Analyzed ${n.length} pages successfully`),{pages:n}}async analyzePageFile(e,t){let n=this.project.getSourceFile(e);if(!n)return null;let s=F.relative(t,e),i=this.filePathToRoutePath(s),a=this.findPageComponent(n);if(!a)return null;let o=this.extractRouteParams(i),r=this.extractLayout(n),c=this.extractAuthRequirement(n),l=this.extractPermissions(n),g=this.extractDataFetching(n),u=this.extractNavigation(n),d=this.extractLinkedPages(n),S=this.extractSteps(n);return {path:i,filePath:s,component:a,params:o,layout:r,authentication:c,permissions:l,dataFetching:g,navigation:u,linkedPages:d,steps:S.length>0?S:void 0}}detectPagesRoot(e){let t=["/src/pages/","/pages/","/src/app/","/app/","/frontend/src/pages/","/app/javascript/pages/"];for(let n of t){let s=e.indexOf(n);if(s!==-1)return e.substring(0,s+n.length-1)}return this.basePath}filePathToRoutePath(e){return "/"+e.replace(/\.tsx?$/,"").replace(/\/index$/,"").replace(/\[\.\.\.(\w+)\]/g,"*").replace(/\[(\w+)\]/g,":$1")}extractRouteParams(e){let t=[],n=/:(\w+)/g,s;for(;(s=n.exec(e))!==null;)t.push(s[1]);return t}findPageComponent(e){let t=e.getDefaultExportSymbol();if(t){let o=t.getName();if(o!=="default")return o}let n=e.getExportAssignment(o=>!o.isExportEquals());if(n){let o=n.getExpression();if(o){let r=o.getText();if(/^[A-Z][a-zA-Z0-9]*$/.test(r))return r;if(Node.isFunctionExpression(o)||Node.isArrowFunction(o))return "default"}}let s=e.getFunctions();for(let o of s)if(o.isDefaultExport())return o.getName()||"default";if(e.getVariableDeclaration("Page"))return "Page";let a=e.getVariableDeclarations();for(let o of a){let r=o.getTypeNode();if(r){let c=r.getText();if(c.includes("NextPage")||c.includes("FC")||c.includes("React.FC"))return o.getName()}}for(let o of a){let r=o.getName();if(/^[A-Z][a-zA-Z0-9]*$/.test(r)){let c=o.getInitializer();if(c&&(Node.isArrowFunction(c)||Node.isFunctionExpression(c))){let l=c.getText();if(l.includes("return")&&(l.includes("<")||l.includes("jsx")))return r}}}return null}extractLayout(e){let t=e.getDescendantsOfKind(SyntaxKind.PropertyAccessExpression).find(n=>n.getName()==="getLayout");if(t){let n=t.getParent();if(Node.isBinaryExpression(n)){let i=n.getRight().getDescendantsOfKind(SyntaxKind.JsxOpeningElement);if(i.length>0)return i[0].getTagNameNode().getText()}}}extractAuthRequirement(e){let n=e.getFilePath().split("/").pop()||"",a={required:!["404.tsx","permission-denied.tsx","_app.tsx","_document.tsx","_error.tsx"].some(o=>n===o)};try{let o=["RequiredCondition","ProtectedRoute","AuthGuard","PrivateRoute","WithAuth","RequireAuth","Authenticated","Authorized"],r=e.getDescendantsOfKind(SyntaxKind.JsxOpeningElement).find(c=>{let l=c.getTagNameNode().getText();return o.some(g=>l.includes(g))});if(r){a.condition="Additional permissions required";let c=r.getAttributes();for(let l of c)if(l.isKind(SyntaxKind.JsxAttribute))try{let g=l.getNameNode().getText();if(["condition","roles","permissions","requiredRoles","allowedRoles"].includes(g)){let u=l.getInitializer();if(u){a.condition=u.getText();let d=this.extractRolesFromCondition(u.getText());d.length>0&&(a.roles=d);}}}catch{}}}catch{}return a}extractRolesFromCondition(e){let t=[],n=/(\w+Role|\w+Permission)\.(\w+)/g,s;for(;(s=n.exec(e))!==null;)t.push(s[2]);let i=/['"]([a-zA-Z_-]+)['"]/g;for(;(s=i.exec(e))!==null;){let o=s[1];/admin|user|owner|member|guest|manager|editor|viewer/i.test(o)&&t.push(o);}let a=/\b(ROLE_\w+|[A-Z]+_ROLE)\b/g;for(;(s=a.exec(e))!==null;)t.push(s[1]);return [...new Set(t)]}extractPermissions(e){let t=[],n=e.getDescendantsOfKind(SyntaxKind.PropertyAccessExpression).filter(s=>{let i=s.getText();return i.includes("Permission")||i.includes("Role")||i.includes("isAdmin")});for(let s of n){let i=s.getText();t.includes(i)||t.push(i);}return t}extractDataFetching(e){let t=[],n=new Map,s=["useQuery","useMutation","useLazyQuery","useSubscription"];for(let h of e.getImportDeclarations()){let p=h.getModuleSpecifierValue();if(p.includes("@apollo/client")||p.includes("apollo"))for(let f of h.getNamedImports()){let y=f.getName(),m=f.getAliasNode()?.getText()||y;s.includes(y)&&n.set(m,y);}}let i=n.size>0||e.getImportDeclarations().some(h=>{let p=h.getModuleSpecifierValue();return p.includes("@apollo/client")||p.includes("apollo")}),a=e.getDescendantsOfKind(SyntaxKind.CallExpression).filter(h=>{let p=h.getExpression().getText();return !!(n.has(p)||s.includes(p)||/^use[A-Z].*Query$/.test(p)&&!p.includes("Params")&&!p.includes("String")||/^use[A-Z].*Mutation$/.test(p))});for(let h of a){let p=h.getExpression().getText(),f;n.has(p)?f=n.get(p):p.includes("Mutation")?f="useMutation":p.includes("Lazy")?f="useLazyQuery":f="useQuery";let y=h.getArguments();if(y.length===0){if(/^use[A-Z]/.test(p)){let N=p.replace(/^use/,"").replace(/Query$|Mutation$/,"");t.push({type:f,operationName:N,variables:[]});}continue}let x=y[0].getText();if(x.startsWith("[")||x.startsWith("{")||x.startsWith("'")||x.startsWith('"')||x.startsWith("`")||!(i||x.endsWith("Document")||x.endsWith("Query")||x.endsWith("Mutation")||x.includes("gql")||/^[A-Z_]+$/.test(x)))continue;let P=x.replace(/Document$/,"").replace(/Query$|Mutation$/,""),C=[];if(y.length>1){let w=y[1].getDescendantsOfKind(SyntaxKind.PropertyAssignment).find(b=>{try{return b.getName()==="variables"}catch{return false}});if(w){let b=w.getInitializer();if(b){let k=b.getDescendantsOfKind(SyntaxKind.PropertyAssignment);for(let Z of k)try{C.push(Z.getName());}catch{}}}}t.push({type:f,operationName:P,variables:C});}let o=e.getVariableDeclaration("getServerSideProps"),r=e.getFunction("getServerSideProps"),c=o||r;if(c){let h=e.getImportDeclarations();for(let y of h){let m=y.getNamedImports();for(let x of m){let A=x.getName();if(A.endsWith("Document")&&e.getDescendantsOfKind(SyntaxKind.Identifier).filter(C=>C.getText()===A).length>0){let C=A.replace(/Document$/,"");t.push({type:"getServerSideProps",operationName:`\u2192 ${C}`});}}}let f=c.getText().match(/query:\s*(\w+)/g);if(f)for(let y of f){let m=y.replace(/query:\s*/,"");t.some(x=>x.operationName?.includes(m.replace(/Document$/,"")))||t.push({type:"getServerSideProps",operationName:`\u2192 ${m.replace(/Document$/,"")}`});}}let l=e.getVariableDeclaration("getStaticProps"),g=e.getFunction("getStaticProps");(l||g)&&t.push({type:"getStaticProps",operationName:"getStaticProps"});let u=e.getImportDeclarations(),d=e.getFilePath(),S=F.dirname(d);for(let h of u){let p=h.getModuleSpecifierValue(),f=p.startsWith(".")||p.startsWith("/"),y=!p.includes("node_modules")&&!p.startsWith("@types/")&&p.startsWith("@")===false;if(f||y){if(p.includes("__generated__")||p.includes("/generated/"))continue;let m=[],x=h.getNamedImports();for(let P of x){let C=P.getName();this.isComponentName(C)&&m.push(C);}let A=h.getDefaultImport();if(A){let P=A.getText();this.isComponentName(P)&&m.push(P);}for(let P of m){let C=this.analyzeImportedComponent(S,p,P);if(C.length>0)for(let N of C)t.push({type:N.type,operationName:N.operationName.startsWith("\u2192")?`\u2192 ${N.operationName} (${P})`:`\u2192 ${N.operationName} (${P})`,variables:N.variables});else t.push({type:"component",operationName:P,variables:[]});}}}return t}symbolTraceCache=new Map;analyzeImportedComponent(e,t,n,s=new Set,i=0){if(i>10)return [];let o=[];try{let r=F.resolve(e,t),c=`${r}:${n}`;if(s.has(c))return [];s.add(c);let l=this.symbolTraceCache.get(c);if(l!==void 0)return l;let g=[`${r}.tsx`,`${r}.ts`,`${r}/index.tsx`,`${r}/index.ts`,`${r}/${n}.tsx`,`${r}/${n}.ts`],u,d;for(let p of g)try{if(u=this.project.addSourceFileAtPath(p),u){d=p;break}}catch{}if(!u||!d)return o;if(d.endsWith("index.tsx")||d.endsWith("index.ts")){let p=this.followReExport(u,n,F.dirname(d));p&&(u=p);}let S=u.getImportDeclarations().some(p=>{let f=p.getModuleSpecifierValue();return f.includes("@apollo/client")||f.includes("apollo")||f.includes("gql")||f.includes("graphql")||f.includes("__generated__")}),h=u.getImportDeclarations().filter(p=>{let f=p.getModuleSpecifierValue();return f.startsWith("./")||f.startsWith("../")});for(let p of h){let f=p.getModuleSpecifierValue(),y=p.getNamedImports().map(m=>m.getName()).filter(m=>/^use[A-Z]/.test(m));for(let m of y){let x=this.analyzeCustomHook(F.dirname(u.getFilePath()),f,m,s,i+1);o.push(...x);}}for(let p of h){let f=p.getModuleSpecifierValue(),y=p.getNamedImports().map(A=>A.getName()),m=p.getDefaultImport()?.getText(),x=y.filter(A=>/^[A-Z]/.test(A)&&this.isComponentName(A));for(let A of x){let P=this.analyzeImportedComponent(F.dirname(u.getFilePath()),f,A,s,i+1);o.push(...P);}if(m&&/^[A-Z]/.test(m)&&this.isComponentName(m)){let A=this.analyzeImportedComponent(F.dirname(u.getFilePath()),f,m,s,i+1);o.push(...A);}}if(S){let p=u.getDescendantsOfKind(SyntaxKind.CallExpression).filter(f=>{let y=f.getExpression().getText();return ["useQuery","useMutation","useLazyQuery","useSubscription"].includes(y)});for(let f of p){let y=f.getExpression().getText(),m=f.getArguments();if(m.length===0)continue;let A=m[0].getText(),P=A,C=null,N=this.resolveDocumentName(A);if(N)P=N.operationName,C=N.operationType;else if(A.endsWith("Document"))P=A.replace(/Document$/,"");else if(/^[A-Za-z]/.test(A)){let b=this.findOperationNameFromVariable(u,A);if(b&&(P=b),P===A&&A!=="Query"&&A!=="Mutation"){let k=A.match(/^(.+?)(Query|Mutation|Subscription)$/);k&&(P=k[1]);}}P!=="Query"&&P!=="Mutation"&&(P=P.replace(/Document$/,"").replace(/Query$|Mutation$/,"")||P),(P==="Query"||P==="Mutation"||P==="")&&P===""&&(P=A||"Unknown");let w=C?C==="mutation"?"useMutation":C==="subscription"?"useSubscription":y.includes("Lazy")?"useLazyQuery":"useQuery":y.includes("Mutation")?"useMutation":y.includes("Lazy")?"useLazyQuery":"useQuery";o.push({type:w,operationName:P,variables:[]});}}this.symbolTraceCache.set(c,o);}catch{}return o}analyzeCustomHook(e,t,n,s=new Set,i=0){if(i>10)return [];let o=[];try{let r=F.resolve(e,t),c=`hook:${r}:${n}`;if(s.has(c))return [];s.add(c);let l=this.symbolTraceCache.get(c);if(l!==void 0)return l;let g=[`${r}.tsx`,`${r}.ts`,`${r}/${n}.tsx`,`${r}/${n}.ts`,`${r}/index.tsx`,`${r}/index.ts`],u;for(let p of g)try{if(u=this.project.addSourceFileAtPath(p),u)break}catch{}if(!u)return o;let d=u.getImportDeclarations().some(p=>{let f=p.getModuleSpecifierValue();return f.includes("@apollo/client")||f.includes("apollo")||f.includes("graphql")||f.includes("__generated__")}),S=u.getImportDeclarations().filter(p=>{let f=p.getModuleSpecifierValue();return f.startsWith("./")||f.startsWith("../")});for(let p of S){let f=p.getModuleSpecifierValue(),y=p.getNamedImports().map(m=>m.getName()).filter(m=>/^use[A-Z]/.test(m));for(let m of y){let x=this.analyzeCustomHook(F.dirname(u.getFilePath()),f,m,s,i+1);o.push(...x);}}if(!d&&o.length===0)return o;let h=u.getDescendantsOfKind(SyntaxKind.CallExpression).filter(p=>{let f=p.getExpression().getText();return ["useQuery","useMutation","useLazyQuery","useSubscription"].includes(f)});for(let p of h){let f=p.getExpression().getText(),y=p.getArguments();if(y.length===0)continue;let m=y[0].getText(),x=m,A=null,P=this.resolveDocumentName(m);if(P)x=P.operationName,A=P.operationType;else if(m.endsWith("Document"))x=m.replace(/Document$/,"");else if(/^[A-Za-z]/.test(m)){let N=this.findOperationNameFromVariable(u,m);if(N&&(x=N),x===m&&m!=="Query"&&m!=="Mutation"){let w=m.match(/^(.+?)(Query|Mutation|Subscription)$/);w&&(x=w[1]);}}x!=="Query"&&x!=="Mutation"&&(x=x.replace(/Document$/,"").replace(/Query$|Mutation$/,"")||x),x===""&&(x=m||"Unknown");let C=A?A==="mutation"?"useMutation":A==="subscription"?"useSubscription":f.includes("Lazy")?"useLazyQuery":"useQuery":f.includes("Mutation")?"useMutation":f.includes("Lazy")?"useLazyQuery":"useQuery";o.push({type:C,operationName:`\u2192 ${x} (via ${n})`,variables:[]});}this.symbolTraceCache.set(c,o);}catch{}return o}globalContextQueries=[];async findPageFiles(){let e=this.getSetting("pagesDir","src/pages"),t=[],s=[...new Set([e,"pages","src/pages","app","src/app"])];for(let o of s){if(o==="app"||o==="src/app"){let c=["controllers","models","views","helpers"],l=this.resolvePath(o);if(c.some(u=>{try{return W.existsSync(F.join(l,u))}catch{return false}}))continue}let r=this.resolvePath(o);try{let c=await z(["**/*.tsx","**/*.ts","**/*.jsx","**/*.js"],{cwd:r,ignore:["_app.tsx","_app.ts","_app.jsx","_app.js","_document.tsx","_document.ts","_document.jsx","_document.js","_error.tsx","_error.ts","_error.jsx","_error.js","api/**","**/*.test.*","**/*.spec.*","**/node_modules/**","**/components/pages/**"],absolute:!0});t.push(...c),c.length>0&&this.log(`Found ${c.length} pages in ${o}`);}catch{}}let i=["frontend/src/**/pages","app/javascript/**/pages"];for(let o of i)try{let r=await z([`${o}/**/*.tsx`,`${o}/**/*.ts`,`${o}/**/*.jsx`,`${o}/**/*.js`],{cwd:this.basePath,ignore:["**/*.test.*","**/*.spec.*","**/node_modules/**","**/vendor/**","**/components/pages/**","**/stories/**"],absolute:!0});t.push(...r),r.length>0&&this.log(`Found ${r.length} React pages in ${o}`);}catch{}let a=["frontend/src/**/index.tsx","frontend/src/**/App.tsx","app/javascript/packs/*.tsx","app/javascript/packs/*.jsx"];for(let o of a)try{let r=await z([o],{cwd:this.basePath,ignore:["**/node_modules/**","**/vendor/**"],absolute:!0});for(let c of r)t.includes(c)||t.push(c);}catch{}return [...new Set(t)]}async analyzeAppFile(){let e=this.getSetting("pagesDir","src/pages"),t=[this.resolvePath(`${e}/_app.tsx`),this.resolvePath(`${e}/_app.ts`)];for(let n of t)try{let s=this.project.addSourceFileAtPath(n);if(!s)continue;let i=s.getDescendantsOfKind(SyntaxKind.JsxElement),a=s.getDescendantsOfKind(SyntaxKind.JsxSelfClosingElement),o=new Set;for(let r of [...i,...a]){let c=r.getFirstDescendantByKind(SyntaxKind.Identifier)?.getText();c&&(c.includes("Provider")||c.includes("Context"))&&o.add(c);}for(let r of s.getImportDeclarations()){let c=r.getModuleSpecifierValue();if(!c.startsWith("./")&&!c.startsWith("../"))continue;let l=r.getNamedImports().map(u=>u.getName()),g=r.getDefaultImport()?.getText();for(let u of o)if(l.includes(u)||g===u){let d=this.analyzeImportedComponent(F.dirname(n),c,u,new Set,0);for(let S of d)this.globalContextQueries.push({...S,operationName:`[Global] ${S.operationName}`});}}this.globalContextQueries.length>0&&this.log(`Found ${this.globalContextQueries.length} global context queries from _app`);return}catch{}}async loadCodegenMapping(){let e=["__generated__","src/__generated__","src/__generated__/gql-graphql-gateway","generated","src/generated"];for(let t of e){let n=this.resolvePath(t);try{let s=await z(["**/*.ts","**/*.tsx"],{cwd:n,absolute:!0,onlyFiles:!0});for(let i of s)try{let a=this.project.addSourceFileAtPath(i),o=a.getVariableDeclarations();for(let c of o){let l=c.getName();if(l.endsWith("Document")){let g=c.getInitializer()?.getText()??"",u=g.match(/(?:query|mutation|subscription)\s+(\w+)/),d=g.match(/(query|mutation|subscription)\s+/);u&&this.codegenMap.set(l,{operationName:u[1],operationType:d?d[1]:"query"});}}let r=a.getTypeAliases();for(let c of r){let l=c.getName();if((l.endsWith("Query")||l.endsWith("Mutation")||l.endsWith("Subscription"))&&!l.endsWith("Variables")){let g=l+"Document";if(!this.codegenMap.has(g)){let u=l.endsWith("Mutation")?"mutation":l.endsWith("Subscription")?"subscription":"query";this.codegenMap.set(g,{operationName:l,operationType:u});}}}}catch{}if(this.codegenMap.size>0){this.log(`Loaded ${this.codegenMap.size} codegen mappings from ${t}`);return}}catch{}}}resolveDocumentName(e){if(new Set(["Query","Mutation","Subscription"]).has(e))return null;let n=this.codegenMap.get(e);if(n!==void 0)return n;let s=e.endsWith("Document")?e:e+"Document",i=this.codegenMap.get(s);return i!==void 0?i:null}followReExport(e,t,n){try{let s=e.getExportDeclarations(),i=null;for(let a of s){let o=a.getNamedExports();for(let r of o){let c=a.getModuleSpecifierValue();if(!c)continue;let l=F.resolve(n,c),g=[`${l}.tsx`,`${l}.ts`,`${l}/index.tsx`,`${l}/index.ts`],u;for(let d of g)try{if(u=this.project.addSourceFileAtPath(d),u)break}catch{}if(u&&(i||(i=u),r.getName()===t||r.getAliasNode()?.getText()===t))return u}}if(i)return i;for(let a of e.getExportDeclarations())if(a.isNamespaceExport()){let o=a.getModuleSpecifierValue();if(o){let r=F.resolve(n,o),c=[`${r}.tsx`,`${r}.ts`];for(let l of c)try{let g=this.project.addSourceFileAtPath(l);if(g&&g.getExportedDeclarations().has(t))return g}catch{}}}}catch{}return null}isComponentName(e){return !/^[A-Z]/.test(e)||e.endsWith("Query")||e.endsWith("Mutation")||e.endsWith("Subscription")||e.endsWith("Fragment")||e.endsWith("Document")||e.endsWith("Variables")||e==="Query"||e==="Mutation"||e==="Subscription"||new Set(["NextPage","NextPageContext","NextApiRequest","NextApiResponse","GetServerSideProps","GetStaticProps","GetStaticPaths","InferGetServerSidePropsType","InferGetStaticPropsType","FC","FunctionComponent","VFC","Component","PureComponent","ReactNode","ReactElement","PropsWithChildren","ComponentProps","ComponentType","ElementType","RefObject","MutableRefObject","Dispatch","SetStateAction","ChangeEvent","MouseEvent","KeyboardEvent","FormEvent","SyntheticEvent"]).has(e)?false:!!(["Container","Page","Screen","View","Form","Modal","Dialog","Panel","Root","Provider","Wrapper"].some(s=>e.endsWith(s))||/Page[A-Z]?\w*$/.test(e)||/Container[A-Z]?\w*$/.test(e)||/^[A-Z][a-z]+[A-Z][a-z]+/.test(e))}extractNavigation(e){let t={visible:true,currentNavItem:null};try{let n=e.getDescendantsOfKind(SyntaxKind.PropertyAccessExpression).find(s=>{try{return s.getName()==="globalNavigationStyle"}catch{return !1}});if(n){let s=n.getParent();if(Node.isBinaryExpression(s)){let i=s.getRight(),a=i.getDescendantsOfKind(SyntaxKind.PropertyAssignment).find(c=>{try{return c.getName()==="visible"}catch{return !1}});a&&(t.visible=a.getInitializer()?.getText()==="true");let o=i.getDescendantsOfKind(SyntaxKind.PropertyAssignment).find(c=>{try{return c.getName()==="currentNavItem"}catch{return !1}});if(o){let c=o.getInitializer()?.getText();t.currentNavItem=c&&c!=="null"?c.replace(/['"]/g,""):null;}let r=i.getDescendantsOfKind(SyntaxKind.PropertyAssignment).find(c=>{try{return c.getName()==="mini"}catch{return !1}});r&&(t.mini=r.getInitializer()?.getText()==="true");}}}catch{}return t}extractSteps(e){let t=[],n=e.getDescendantsOfKind(SyntaxKind.CallExpression).filter(a=>a.getExpression().getText()==="useState");for(let a of n){let o=a.getParent();if(!o)continue;let c=o.getText().match(/\[\s*(step|currentStep|activeStep|page|currentPage|phase|stage)\s*,/i);if(c){let l=c[1],g=e.getDescendantsOfKind(SyntaxKind.SwitchStatement);for(let d of g)d.getExpression().getText().includes(l)&&d.getClauses().forEach((p,f)=>{if(p.isKind(SyntaxKind.CaseClause)){let y=p.getExpression()?.getText()||String(f),m=p.getDescendantsOfKind(SyntaxKind.JsxOpeningElement),x=m.length>0?m[0].getTagNameNode().getText():void 0;t.push({id:y.replace(/['"]/g,""),name:`Step ${y.replace(/['"]/g,"")}`,component:x});}});let u=e.getDescendantsOfKind(SyntaxKind.ArrayLiteralExpression);for(let d of u){let S=d.getParent();S&&S.getText().match(/steps|pages|screens|views|components/i)&&d.getElements().forEach((p,f)=>{let y=p.getText();if(y.startsWith("{")){let m=y.match(/(?:name|label|title)\s*:\s*['"]([^'"]+)['"]/),x=y.match(/(?:component|content)\s*:\s*<?\s*(\w+)/);t.push({id:f+1,name:m?m[1]:`Step ${f+1}`,component:x?x[1]:void 0});}else /^[A-Z]/.test(y)&&t.push({id:f+1,name:y,component:y});});}}}let s=e.getDescendantsOfKind(SyntaxKind.JsxOpeningElement);for(let a of s)if(a.getTagNameNode().getText().match(/Stepper|Wizard|Steps|TabPanel|FormStep/i)){let r=a.getParent();r&&r.isKind(SyntaxKind.JsxElement)&&r.getJsxChildren().forEach((l,g)=>{if(l.isKind(SyntaxKind.JsxElement)||l.isKind(SyntaxKind.JsxSelfClosingElement)){let u=l.isKind(SyntaxKind.JsxElement)?l.getOpeningElement().getTagNameNode().getText():l.getTagNameNode().getText(),d=l.isKind(SyntaxKind.JsxElement)?l.getOpeningElement().getAttributes():l.getAttributes(),S=u;for(let h of d)if(h.isKind(SyntaxKind.JsxAttribute)){let p=h.getNameNode().getText();if(p==="label"||p==="title"||p==="name"){let f=h.getInitializer()?.getText();if(f){S=f.replace(/['"{}]/g,"");break}}}t.push({id:g+1,name:S,component:u});}});}let i=e.getDescendantsOfKind(SyntaxKind.ConditionalExpression);for(let a of i){let o=a.getCondition().getText();if(o.match(/step\s*===?\s*\d+|currentStep|activeStep/i)){let r=a.getWhenTrue(),c=o.match(/===?\s*(\d+)/);if(c&&t.length===0){let l=r.getDescendantsOfKind(SyntaxKind.JsxOpeningElement);l.length>0&&t.push({id:parseInt(c[1]),component:l[0].getTagNameNode().getText()});}}}return t}extractLinkedPages(e){let t=[],n=e.getDescendantsOfKind(SyntaxKind.CallExpression).filter(i=>{let a=i.getExpression().getText();return a.includes("router.push")||a.includes("router.replace")||a.includes("Link")});for(let i of n){let a=i.getArguments();if(a.length>0){let r=a[0].getText().match(/['"`]([^'"`]+)['"`]/);r&&!t.includes(r[1])&&t.push(r[1]);}}let s=e.getDescendantsOfKind(SyntaxKind.JsxOpeningElement).filter(i=>i.getTagNameNode().getText()==="Link");for(let i of s)try{let a=i.getAttributes();for(let o of a)if(o.isKind(SyntaxKind.JsxAttribute)&&o.getNameNode().getText()==="href"){let l=o.getInitializer()?.getText();if(l){let g=l.match(/['"`]([^'"`]+)['"`]/);g&&!t.includes(g[1])&&t.push(g[1]);}}}catch{}return t}};var G=class extends D{project;constructor(e){super(e),this.project=new Project({tsConfigFilePath:this.resolvePath("tsconfig.json"),skipAddingFilesFromTsConfig:true});}getName(){return "GraphQLAnalyzer"}async analyze(){this.log("Starting GraphQL analysis...");let e=[],t=await this.analyzeGraphQLFiles();e.push(...t);let n=await this.analyzeInlineGraphQL();e.push(...n);let s=await this.analyzeCodegenGenerated();e.push(...s);let i=this.deduplicateOperations(e);return await this.findOperationUsage(i),this.log(`Found ${i.length} GraphQL operations`),{graphqlOperations:i}}deduplicateOperations(e){let t=new Map;for(let n of e)if(!t.has(n.name))t.set(n.name,n);else {let s=t.get(n.name);if(s)for(let i of n.usedIn)s.usedIn.includes(i)||s.usedIn.push(i);}return Array.from(t.values())}async analyzeCodegenGenerated(){let e=[],t=await z(["**/__generated__/graphql.ts","**/__generated__/gql.ts","**/generated/graphql.ts"],{cwd:this.basePath,ignore:["**/node_modules/**","**/.next/**"],absolute:true});for(let n of t)try{let s=await O.readFile(n,"utf-8"),i=F.relative(this.basePath,n),a=s.split(`
|
|
2
|
+
`);for(let o of a){if(!o.includes("Document =")||!o.includes("DocumentNode"))continue;let r=o.match(/export\s+const\s+(\w+Document)\s*=\s*(\{"kind":"Document".+\})\s*as\s+unknown\s+as\s+DocumentNode/);if(!r)continue;let c=r[1],l=r[2];try{let g=JSON.parse(l);if(g.kind==="Document"&&g.definitions){let u=g.definitions[0];if(u?.kind==="OperationDefinition"){let d=u.name?.value||c.replace(/Document$/,""),S=u.operation,h=(u.variableDefinitions||[]).map(p=>({name:p.variable?.name?.value||"unknown",type:this.extractTypeFromAst(p.type),required:p.type?.kind==="NonNullType"}));e.push({name:d,type:S,filePath:i,usedIn:[],variables:h,returnType:this.inferReturnTypeFromAst(u),fragments:[],fields:[]});}}}catch{}}this.log(`Found ${e.length} operations in codegen output: ${i}`);}catch(s){this.warn(`Failed to analyze codegen file ${n}: ${s.message}`);}return e}extractTypeFromAst(e){return e?e.kind==="NonNullType"?`${this.extractTypeFromAst(e.type)}!`:e.kind==="ListType"?`[${this.extractTypeFromAst(e.type)}]`:e.kind==="NamedType"&&e.name?.value||"unknown":"unknown"}extractFieldsFromAst(e,t=0){if(!e?.selections||t>5)return [];let n=[];for(let s of e.selections)if(s.kind==="Field"){let i={name:s.name?.value||"unknown"};if(s.arguments?.length>0){let a=s.arguments.map(o=>o.name?.value).join(", ");i.type=`(${a})`;}s.selectionSet&&(i.fields=this.extractFieldsFromAst(s.selectionSet,t+1)),n.push(i);}else if(s.kind==="FragmentSpread")n.push({name:`...${s.name?.value}`,type:"fragment"});else if(s.kind==="InlineFragment"){let i=s.typeCondition?.name?.value||"inline";n.push({name:`... on ${i}`,type:"inline-fragment",fields:this.extractFieldsFromAst(s.selectionSet,t+1)});}return n}extractFragmentReferencesFromAst(e){let t=[],n=s=>{if(s&&(s.kind==="FragmentSpread"&&t.push(s.name?.value),s.selectionSet?.selections))for(let i of s.selectionSet.selections)n(i);};return n(e),t.filter(Boolean)}inferReturnTypeFromAst(e){if(e.selectionSet?.selections?.length>0){let t=e.selectionSet.selections[0];if(t.kind==="Field")return t.name?.value||"unknown"}return "unknown"}async analyzeGraphQLFiles(){let e=await z(["**/*.graphql"],{cwd:this.basePath,ignore:["**/node_modules/**","**/.next/**"],absolute:true});return (await E(e,async n=>{let s=await O.readFile(n,"utf-8"),i=parse(s);return this.extractOperationsFromDocument(i,F.relative(this.basePath,n))})).flat()}async analyzeInlineGraphQL(){let e=[],t=await z(["**/*.ts","**/*.tsx"],{cwd:this.basePath,ignore:["**/node_modules/**","**/.next/**","**/__tests__/**","**/*.test.*","**/*.spec.*"],absolute:true});for(let n of t)try{let s=this.project.addSourceFileAtPath(n),i=F.relative(this.basePath,n),a=s.getImportDeclarations().some(c=>{let l=c.getModuleSpecifierValue(),g=c.getNamedImports().map(d=>d.getName()),u=c.getDefaultImport()?.getText();return (g.includes("gql")||g.includes("graphql")||u==="gql")&&(l.includes("graphql")||l.includes("apollo")||l.includes("gql")||l.includes("__generated__"))}),o=s.getDescendantsOfKind(SyntaxKind.TaggedTemplateExpression);for(let c of o){let l=c.getTag().getText();if(l==="gql"||l==="graphql")try{let g=c.getTemplate(),u="";if(g.isKind(SyntaxKind.NoSubstitutionTemplateLiteral)?u=g.getLiteralValue():g.isKind(SyntaxKind.TemplateExpression)&&(u=g.getText().slice(1,-1).replace(/\$\{[^}]*\}/g,"")),u&&u.trim())try{let d=parse(u),S=this.extractOperationsFromDocument(d,i);e.push(...S);}catch{}}catch{}}let r=s.getDescendantsOfKind(SyntaxKind.CallExpression);for(let c of r)try{let g=c.getExpression().getText();if(g==="gql"||g==="graphql"){let u=c.getArguments();if(u.length>0){let d=u[0],S="";if(d.isKind(SyntaxKind.NoSubstitutionTemplateLiteral))S=d.getLiteralValue();else if(d.isKind(SyntaxKind.TemplateExpression))S=d.getText().slice(1,-1).replace(/\$\{[^}]*\}/g,"");else {let h=d.getText();if(h.includes("`")){let p=h.match(/\/\*\s*GraphQL\s*\*\/\s*`([^`]*)`/);if(p)S=p[1];else {let f=h.match(/`([^`]*)`/);f&&(S=f[1]);}}}if(S&&S.trim())try{let h=parse(S),p=this.extractOperationsFromDocument(h,i);e.push(...p);}catch{}}}}catch{}if(a){let c=s.getVariableDeclarations();for(let l of c){let g=l.getName();if(g.includes("QUERY")||g.includes("MUTATION")||g.includes("FRAGMENT")||g.includes("Query")||g.includes("Mutation")||g.includes("Subscription")||/^[A-Z_]+_(QUERY|MUTATION|FRAGMENT|SUBSCRIPTION)$/.test(g)||/Query$|Mutation$|Fragment$|Subscription$/.test(g)){let d=l.getInitializer();d&&d.isKind(SyntaxKind.CallExpression);}}}}catch(s){this.warn(`Failed to analyze ${n}: ${s.message}`);}return e}extractOperationsFromDocument(e,t){let n=[];for(let s of e.definitions){let i=this.extractOperation(s,t);i&&n.push(i);}return n}extractOperation(e,t){if(e.kind==="OperationDefinition"){let n=e.name?.value||"anonymous",s=e.operation,i=this.extractVariables(e),a=this.extractFragmentReferences(e),o=this.extractFields(e);return {name:n,type:s,filePath:t,usedIn:[],variables:i,returnType:this.inferReturnType(e),fragments:a,fields:o}}return e.kind==="FragmentDefinition"?{name:e.name.value,type:"fragment",filePath:t,usedIn:[],variables:[],returnType:e.typeCondition.name.value,fragments:this.extractFragmentReferences(e),fields:this.extractFields(e)}:null}extractFields(e){let t=[],n=(s,i=0)=>{if(!s||!s.selections||i>5)return [];let a=[];for(let o of s.selections)if(o.kind==="Field"){let r={name:o.name.value};if(o.arguments&&o.arguments.length>0){let c=o.arguments.map(l=>l.name.value).join(", ");r.type=`(${c})`;}o.selectionSet&&(r.fields=n(o.selectionSet,i+1)),a.push(r);}else if(o.kind==="FragmentSpread")a.push({name:`...${o.name.value}`,type:"fragment"});else if(o.kind==="InlineFragment"&&o.selectionSet){let r=o.typeCondition?.name?.value||"inline";a.push({name:`... on ${r}`,type:"inline-fragment",fields:n(o.selectionSet,i+1)});}return a};return e.selectionSet?n(e.selectionSet):t}extractVariables(e){let t=[];if(e.variableDefinitions)for(let n of e.variableDefinitions){let s=n.variable.name.value,i=this.typeNodeToString(n.type),a=n.type.kind==="NonNullType";t.push({name:s,type:i,required:a});}return t}typeNodeToString(e){return e.kind==="NonNullType"?`${this.typeNodeToString(e.type)}!`:e.kind==="ListType"?`[${this.typeNodeToString(e.type)}]`:e.kind==="NamedType"?e.name.value:"unknown"}extractFragmentReferences(e){let t=[],n=s=>{if(s&&(s.kind==="FragmentSpread"&&t.push(s.name.value),s.selectionSet))for(let i of s.selectionSet.selections)n(i);};return n(e),t}inferReturnType(e){if(e.selectionSet&&e.selectionSet.selections.length>0){let t=e.selectionSet.selections[0];if(t.kind==="Field")return t.name.value}return "unknown"}async findOperationUsage(e){if(e.length===0)return;let t=await z(["**/*.ts","**/*.tsx"],{cwd:this.basePath,ignore:["**/node_modules/**","**/.next/**","**/__generated__/**"],absolute:true}),n=new Map,s=new Map;for(let r of e)n.set(r.name,r),s.set(`${r.name}Document`,r);let i=e.map(r=>`${r.name}Document`),a=new RegExp(`\\b(${i.join("|")})\\b`,"g"),o=50;for(let r=0;r<t.length;r+=o){let c=t.slice(r,r+o);await Promise.all(c.map(async l=>{try{let g=await O.readFile(l,"utf-8"),u=F.relative(this.basePath,l);if(!g.includes("Document")&&!g.includes("useQuery")&&!g.includes("useMutation")&&!g.includes("Query")&&!g.includes("Mutation"))return;let d=new Set,S;for(;(S=a.exec(g))!==null;)d.add(S[1]);a.lastIndex=0;for(let h of d){let p=s.get(h);p&&u!==p.filePath&&(p.usedIn.includes(u)||p.usedIn.push(u));}for(let[h,p]of n)u!==p.filePath&&(p.usedIn.includes(u)||(g.includes(`useQuery<${h}`)||g.includes(`useMutation<${h}`)||g.includes(`useLazyQuery<${h}`)||g.includes(`useSubscription<${h}`)||g.includes(`${h}Query`)||g.includes(`${h}Mutation`))&&p.usedIn.push(u));}catch{}}));}}};var K=class extends D{project;componentCache=new Map;constructor(e){super(e),this.project=new Project({tsConfigFilePath:this.resolvePath("tsconfig.json"),skipAddingFilesFromTsConfig:true});}getName(){return "DataFlowAnalyzer"}async analyze(){this.log("Starting data flow analysis...");let e=await this.analyzeComponents(),t=await this.analyzeDataFlows(e);return this.log(`Analyzed ${e.length} components and ${t.length} data flows`),{components:e,dataFlows:t}}async analyzeComponents(){let e=[],t=[this.getSetting("featuresDir",""),this.getSetting("componentsDir",""),this.getSetting("pagesDir","")].filter(Boolean),n=["src/features","src/components","src/common/components","src/common","src/pages","src/app","src/modules","src/views","src/screens","components","pages","app"],s=[...new Set([...t,...n])];for(let i of s){let a=await z(["**/*.tsx"],{cwd:this.resolvePath(i),ignore:["**/*.test.*","**/*.spec.*","**/*.stories.*"],absolute:true});for(let o of a)try{let r=this.project.addSourceFileAtPath(o),c=F.relative(this.basePath,o),l=this.analyzeComponentFile(r,c);e.push(...l);}catch(r){this.warn(`Failed to analyze ${o}: ${r.message}`);}}return this.buildDependencyGraph(e),e}analyzeComponentFile(e,t){let n=[],s=e.getFunctions();for(let o of s){let r=o.getName();if(r&&this.isComponentName(r)){let c=this.extractComponentInfo(o,r,t);n.push(c),this.componentCache.set(r,c);}}let i=e.getVariableDeclarations();for(let o of i){let r=o.getName();if(this.isComponentName(r)){let c=o.getInitializer();if(c&&(c.isKind(SyntaxKind.ArrowFunction)||c.isKind(SyntaxKind.FunctionExpression))){let l=this.extractComponentInfo(c,r,t);n.push(l),this.componentCache.set(r,l);}}}let a=e.getFunctions().filter(o=>{let r=o.getName();return r&&r.startsWith("use")});for(let o of a){let r=o.getName()??"",c=this.extractHookInfo(o,r,t);n.push(c),this.componentCache.set(r,c);}return n}isComponentName(e){return /^[A-Z][a-zA-Z0-9]*$/.test(e)}extractComponentInfo(e,t,n){let s=e.getSourceFile(),i="presentational";["/pages/","/app/","/routes/","/views/","/screens/"].some(g=>n.includes(g))?i="page":t.includes("Container")||t.includes("Provider")?i="container":(t.includes("Layout")||t.includes("Shell")||t.includes("Wrapper")||t.includes("Frame")||t.includes("Scaffold")||n.includes("/layouts/")||n.includes("/layout/"))&&(i="layout");let o=this.extractProps(e),r=this.extractHooksUsed(e),c=this.extractDependencies(s),l=this.extractStateManagement(e);return {name:t,filePath:n,type:i,props:o,dependencies:c,dependents:[],hooks:r,stateManagement:l}}extractHookInfo(e,t,n){let s=e.getSourceFile(),i=this.extractProps(e),a=this.extractHooksUsed(e),o=this.extractDependencies(s),r=this.extractStateManagement(e);return {name:t,filePath:n,type:"hook",props:i,dependencies:o,dependents:[],hooks:a,stateManagement:r}}extractProps(e){let t=[],n=e.getParameters?.()||[];if(n.length>0){let i=n[0].getTypeNode?.();if(i){let a=i.getDescendantsOfKind?.(SyntaxKind.PropertySignature)||[];for(let o of a)t.push({name:o.getName(),type:o.getType().getText(),required:!o.hasQuestionToken()});}}return t}extractHooksUsed(e){let t=[],n=e.getDescendantsOfKind?.(SyntaxKind.CallExpression)||[];for(let s of n)try{let i=s.getExpression().getText();if(i.startsWith("use"))if(i==="useQuery"||i==="useMutation"||i==="useLazyQuery"){let a=this.extractOperationName(s,i);t.includes(a)||t.push(a);}else if(i==="useContext"){let a=this.extractContextName(s);t.includes(a)||t.push(a);}else t.includes(i)||t.push(i);}catch{}return t}extractOperationName(e,t){try{let n=e.getArguments?.()||[];if(n.length>0){let i=n[0].getText().replace(/^(GET_|FETCH_|CREATE_|UPDATE_|DELETE_)/,"").replace(/_QUERY$|_MUTATION$/,"").replace(/Document$/,"").replace(/Query$|Mutation$/,"");return `${t==="useMutation"?"\u270F\uFE0F":"\u{1F4E1}"} ${t==="useMutation"?"Mutation":"Query"}: ${i}`}}catch{}return t}extractContextName(e){try{let t=e.getArguments?.()||[];if(t.length>0)return `\u{1F504} Context: ${t[0].getText().replace(/Context$/,"").replace(/^Session|^Token|^Apollo/,s=>s)}`}catch{}return "useContext"}extractDependencies(e){let t=[],n=e.getImportDeclarations();for(let s of n){let i=s.getModuleSpecifierValue();if(i.startsWith(".")||i.startsWith("@/")){let a=s.getNamedImports();for(let r of a){let c=r.getName();(this.isComponentName(c)||c.startsWith("use"))&&t.push(c);}let o=s.getDefaultImport();if(o){let r=o.getText();this.isComponentName(r)&&t.push(r);}}}return t}extractStateManagement(e){let t=[],n=e.getText?.()||"";return n.includes("useState")&&t.push("useState"),n.includes("useReducer")&&t.push("useReducer"),n.includes("useContext")&&t.push("useContext"),n.includes("useQuery")&&t.push("Apollo Query"),n.includes("useMutation")&&t.push("Apollo Mutation"),n.includes("useRecoil")&&t.push("Recoil"),(n.includes("useSelector")||n.includes("useDispatch"))&&t.push("Redux"),t}buildDependencyGraph(e){let t=new Map;for(let n of e)t.set(n.name,n);for(let n of e)for(let s of n.dependencies){let i=t.get(s);i&&!i.dependents.includes(n.name)&&i.dependents.push(n.name);}}async analyzeDataFlows(e){let t=[],n=1,s=this.analyzeContextFlows(e);t.push(...s.map(o=>({...o,id:`flow-${n++}`})));let i=this.analyzeApolloFlows(e);t.push(...i.map(o=>({...o,id:`flow-${n++}`})));let a=this.analyzePropDrilling(e);return t.push(...a.map(o=>({...o,id:`flow-${n++}`}))),t}analyzeContextFlows(e){let t=[],n=e.filter(i=>i.name.includes("Provider")||i.name.includes("Context")),s=e.filter(i=>i.hooks.some(a=>a.includes("Context")));for(let i of n){let a=i.name.replace("Provider","").replace("Context","");for(let o of s){let r=o.hooks.find(c=>c.includes("Context")&&c.includes(a));(r||o.hooks.some(c=>c.includes(a)))&&t.push({name:`\u{1F504} ${a} Context`,description:`Data flows from ${i.name} to ${o.name} via Context`,source:{type:"context",name:i.name},target:{type:"component",name:o.name},via:[],operations:[r||`useContext(${a})`]});}}return t}analyzeApolloFlows(e){let t=[];for(let n of e){let s=n.hooks.filter(a=>a.includes("Query:")||a==="useQuery"||a==="useLazyQuery");for(let a of s){let o=a.includes(":")?a.split(":")[1].trim():n.name;t.push({name:`\u{1F4E1} ${o}`,description:`${n.name} fetches ${o} via Apollo`,source:{type:"api",name:`GraphQL: ${o}`},target:{type:"component",name:n.name},via:[{type:"cache",name:"Apollo Cache"}],operations:[a]});}let i=n.hooks.filter(a=>a.includes("Mutation:")||a==="useMutation");for(let a of i){let o=a.includes(":")?a.split(":")[1].trim():n.name;t.push({name:`\u270F\uFE0F ${o}`,description:`${n.name} mutates ${o} via Apollo`,source:{type:"component",name:n.name},target:{type:"api",name:`GraphQL: ${o}`},via:[],operations:[a]});}}return t}analyzePropDrilling(e){let t=[];for(let n of e)n.props.length>5&&n.dependents.length>0&&t.push({name:`Prop Drilling through ${n.name}`,description:`${n.name} passes ${n.props.length} props to children`,source:{type:"component",name:n.name},target:{type:"component",name:n.dependents[0]},via:[],operations:["props"]});return t}};var H=class extends D{project;apiCallCounter=0;constructor(e){super(e),this.project=new Project({tsConfigFilePath:this.resolvePath("tsconfig.json"),skipAddingFilesFromTsConfig:true});}getName(){return "RestApiAnalyzer"}async analyze(){this.log("Starting REST API analysis...");let e=await z(["**/*.ts","**/*.tsx"],{cwd:this.basePath,ignore:["**/node_modules/**","**/.next/**","**/__tests__/**","**/*.test.*","**/*.spec.*","**/*.stories.*","**/__generated__/**","**/dist/**","**/build/**"],absolute:true}),t=new Map;for(let i of e)try{t.set(i,this.project.addSourceFileAtPath(i));}catch{}let s=(await E(Array.from(t.entries()),async([i,a])=>{let o=F.relative(this.basePath,i),r=[];return r.push(...this.findFetchCalls(a,o)),r.push(...this.findAxiosCalls(a,o)),r.push(...this.findSwrCalls(a,o)),r},8)).flat();return this.log(`Found ${s.length} REST API calls`),{apiCalls:s}}findFetchCalls(e,t){let n=[],s=e.getDescendantsOfKind(SyntaxKind.CallExpression);for(let i of s)try{let o=i.getExpression().getText();if(o==="fetch"||o==="window.fetch"){let r=this.extractFetchCall(i,t);r&&n.push(r);}}catch{}return n}findAxiosCalls(e,t){let n=[],s=e.getDescendantsOfKind(SyntaxKind.CallExpression);for(let i of s)try{let o=i.getExpression().getText(),r=o.match(/^axios\.(get|post|put|delete|patch)$/i);if(r){let c=this.extractAxiosCall(i,t,r[1].toUpperCase());c&&n.push(c);}if(o==="axios"){let c=this.extractAxiosDirectCall(i,t);c&&n.push(c);}}catch{}return n}findSwrCalls(e,t){let n=[],s=e.getDescendantsOfKind(SyntaxKind.CallExpression);for(let i of s)try{let o=i.getExpression().getText();if(o==="useSWR"||o==="useSWRImmutable"){let r=this.extractSwrCall(i,t);r&&n.push(r);}}catch{}return n}extractFetchCall(e,t){let n=e.getArguments();if(n.length===0)return null;let s=n[0].getText(),i=this.extractUrlFromArg(s);if(!i.url||!i.isPlaceholder&&!this.isApiUrl(i.url))return null;let a="GET",o=false;if(n.length>1){let l=n[1].getText(),g=l.match(/method:\s*["'](\w+)["']/i);g&&(a=this.normalizeMethod(g[1])),o=l.includes("credentials")||l.includes("Authorization")||l.includes("withCredentials");}let r=this.getContainingFunctionName(e),c=e.getStartLineNumber();return {id:`api-${++this.apiCallCounter}`,method:a,url:i.url,callType:"fetch",filePath:t,line:c,containingFunction:r,usedIn:[],requiresAuth:o,category:this.categorizeApi(i.url)}}extractAxiosCall(e,t,n){let s=e.getArguments();if(s.length===0)return null;let i=s[0].getText(),a=this.extractUrlFromArg(i);if(!a.url)return null;let o=false;if(s.length>1){let l=s[s.length-1].getText();o=l.includes("withCredentials")||l.includes("Authorization");}let r=this.getContainingFunctionName(e),c=e.getStartLineNumber();return {id:`api-${++this.apiCallCounter}`,method:this.normalizeMethod(n),url:a.url,callType:"axios",filePath:t,line:c,containingFunction:r,usedIn:[],requiresAuth:o,category:this.categorizeApi(a.url)}}extractAxiosDirectCall(e,t){let n=e.getArguments();if(n.length===0)return null;let s=n[0].getText(),i=s.match(/url:\s*["'`]([^"'`]+)["'`]/),a=s.match(/method:\s*["'](\w+)["']/i);if(!i)return null;let o=i[1],r=a?this.normalizeMethod(a[1]):"GET",c=s.includes("withCredentials")||s.includes("Authorization"),l=this.getContainingFunctionName(e),g=e.getStartLineNumber();return {id:`api-${++this.apiCallCounter}`,method:r,url:o,callType:"axios",filePath:t,line:g,containingFunction:l,usedIn:[],requiresAuth:c,category:this.categorizeApi(o)}}extractSwrCall(e,t){let n=e.getArguments();if(n.length===0)return null;let s=n[0].getText(),i=null;if(s.startsWith('"')||s.startsWith("'")||s.startsWith("`"))i=this.cleanStringLiteral(s);else if(s.includes("?")&&s.includes(":")){let r=s.match(/\?\s*["'`]([^"'`]+)["'`]/);r?i=r[1]:(r=s.match(/:\s*["'`]([^"'`]+)["'`]/),r&&(i=r[1])),i||(r=s.match(/\?\s*`([^`]+)`/),r&&(i=r[1].replace(/\$\{[^}]+\}/g,":param")));}else {let r=this.extractUrlFromArg(s);r.url&&!s.includes("null")&&!s.includes("undefined")&&(i=r.url);}if(!i)return null;let a=this.getContainingFunctionName(e),o=e.getStartLineNumber();return {id:`api-${++this.apiCallCounter}`,method:"GET",url:i,callType:"useSWR",filePath:t,line:o,containingFunction:a,usedIn:[],requiresAuth:false,category:this.categorizeApi(i)}}getContainingFunctionName(e){let t=e;for(;t;){if(Node.isFunctionDeclaration(t))return t.getName()||"anonymous";if(Node.isVariableDeclaration(t)||Node.isMethodDeclaration(t))return t.getName();if(Node.isArrowFunction(t)){let n=t.getParent();if(n&&Node.isVariableDeclaration(n))return n.getName()}t=t.getParent();}return "unknown"}extractUrlFromArg(e){if(/^["'`]/.test(e))return {url:this.cleanStringLiteral(e),isPlaceholder:false};let t=e.match(/^(\w+)\s*\(\s*["'`]([^"'`]+)["'`]/);if(t)return {url:`[${t[1]}] ${t[2]}`,isPlaceholder:true};let n=e.match(/^(\w+)\s*\(\s*`([^`]+)`/);if(n){let s=n[2].replace(/\$\{[^}]+\}/g,":param");return {url:`[${n[1]}] ${s}`,isPlaceholder:true}}return /^\w+(\.\w+)*$/.test(e)?{url:`[${e}]`,isPlaceholder:true}:e.includes(".")?{url:`[${e}]`,isPlaceholder:true}:{url:null,isPlaceholder:false}}cleanStringLiteral(e){let t=e.replace(/^["'`]|["'`]$/g,"").trim();return t.includes("${")?t.replace(/\$\{[^}]+\}/g,":param"):t||null}isApiUrl(e){return e.startsWith("data:")||e.startsWith("blob:")||/\.(css|js|png|jpg|jpeg|gif|svg|ico|woff|woff2|ttf|eot|html)$/i.test(e)?false:e.startsWith("/")||e.startsWith("http")||e.includes("/api/")||e.includes(".json")||e.includes("api.")||e.includes("github.io")||e.includes("hsforms.com")||e.includes("hubspot")||e.includes("amazonaws.com")||e.includes("s3.")||e.includes("googleapis.com")||e.includes("stripe.com")||e.includes("graph.facebook.com")||e.includes("api.twitter.com")||e.includes("slack.com")||e.includes("discord.com")||e.includes("sendgrid.com")||e.includes("twilio.com")||e.includes("firebase")||e.includes("supabase")||e.includes("auth0.com")||e.includes("okta.com")||e.includes("cloudflare.com")||e.includes("vercel.com")||e.includes("netlify.com")}categorizeApi(e){if(e.includes("hsforms.com")||e.includes("hubspot"))return "HubSpot";if(e.includes("amazonaws.com")||e.includes("s3."))return "AWS S3";if(e.includes("googleapis.com"))return "Google API";if(e.includes("stripe.com"))return "Stripe";if(e.includes("graph.facebook.com"))return "Facebook";if(e.includes("api.twitter.com"))return "Twitter";if(e.includes("slack.com"))return "Slack";if(e.includes("discord.com"))return "Discord";if(e.includes("sendgrid.com"))return "SendGrid";if(e.includes("twilio.com"))return "Twilio";if(e.includes("firebase"))return "Firebase";if(e.includes("supabase"))return "Supabase";if(e.includes("auth0.com"))return "Auth0";if(e.includes("okta.com"))return "Okta";if(e.includes("github.io"))return "GitHub Pages API";if(e.startsWith("/api/"))return "Internal API";if(e.startsWith("/"))return "Internal Route";if(e.startsWith("["))return "Dynamic URL"}normalizeMethod(e){let t=e.toUpperCase();return ["GET","POST","PUT","DELETE","PATCH"].includes(t)?t:"unknown"}};export{D as a,q as b,G as c,K as d,H as e};
|
package/dist/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {a,b}from'./chunk-
|
|
2
|
+
import {a,b}from'./chunk-EYHNEFTO.js';import'./chunk-H4YGP3GL.js';import'./chunk-VV3A3UE3.js';import'./chunk-PSM6AV63.js';import'./chunk-XWZH2RDG.js';import'./chunk-MOEA75XK.js';import'./chunk-PTR5IROV.js';import {Command}from'commander';import n from'chalk';import*as p from'path';import*as s from'fs/promises';var d=new Command;d.name("repomap").description("Interactive documentation generator for code repositories").version("0.1.0");async function $(e){let o=p.basename(e),a=false,t=p.join(e,"Gemfile"),c=p.join(e,"config","routes.rb");try{await s.access(t),await s.access(c);let u=await s.readFile(t,"utf-8");a=u.includes("gem 'rails'")||u.includes('gem "rails"');}catch{}let r=p.join(e,"package.json"),i=false,l=false,m={};try{let u=JSON.parse(await s.readFile(r,"utf-8")),w={...u.dependencies,...u.devDependencies};i=!!w.react,l=!!w.next;let f=["src/pages","pages","app","src/app","frontend/src"];for(let g of f)try{await s.access(p.join(e,g)),m.pagesDir=g;break}catch{}let b=["src/features","features","src/modules","modules","frontend/src"];for(let g of b)try{await s.access(p.join(e,g)),m.featuresDir=g;break}catch{}let D=["src/components","components","src/common/components","frontend/src"];for(let g of D)try{await s.access(p.join(e,g)),m.componentsDir=g;break}catch{}}catch{}let h=[];(i||l)&&h.push("pages","graphql","dataflow","rest-api");let y="generic";return l?y="nextjs":a&&(y="rails"),!a&&!i&&!l?null:{name:o,displayName:o,description:a&&i?"Rails + React application":a?"Rails application":"",path:e,branch:"main",type:y,analyzers:h,settings:m}}async function x(e){let o=await $(e);if(!o)throw new Error("Could not detect project. Please create a repomap.config.ts file or run 'repomap init'.");return {outputDir:"./.repomap",site:{title:`${o.displayName} Documentation`,description:"Auto-generated documentation",baseUrl:"/docs"},repositories:[o],analysis:{include:["**/*.tsx","**/*.ts"],exclude:["**/node_modules/**","**/__tests__/**","**/*.test.*","**/*.spec.*","**/dist/**","**/.next/**"],maxDepth:5},diagrams:{enabled:true,types:["flowchart","sequence"],theme:"default"},watch:{enabled:false,debounce:1e3},integrations:{github:{enabled:false,organization:""},slack:{enabled:false}}}}async function P(e,o){let a=e?[e]:["repomap.config.ts","repomap.config.js","repomap.config.mjs"];for(let t of a){let c=p.resolve(o,t);try{await s.access(c),console.log(n.gray(`Loading config from: ${c}`));let r=await import(c);return r.config||r.default}catch{}}return console.log(n.gray("No config file found, auto-detecting project...")),x(o)}d.command("generate").description("Generate documentation from source code").option("-c, --config <path>","Path to config file").option("-o, --output <path>","Output directory").option("--repo <name>","Analyze specific repository only").option("--watch","Watch for changes and regenerate").option("--no-cache","Disable caching (always analyze from scratch)").option("--format <type>","Output format: json, html, markdown (default: all)","all").option("--ci","CI mode: minimal output, exit codes for errors").option("--static","Generate standalone HTML files (for GitHub Pages)").action(async e=>{let o=e.ci||process.env.CI==="true";o||console.log(n.blue.bold(`
|
|
3
3
|
\u{1F4DA} Repomap - Documentation Generator
|
|
4
4
|
`));try{let a$1=process.cwd(),t=await P(e.config,a$1);e.output&&(t.outputDir=e.output),e.repo&&(t.repositories=t.repositories.filter(r=>r.name===e.repo),t.repositories.length===0&&(console.error(n.red(`Repository "${e.repo}" not found in config`)),process.exit(1)));let c=new a(t,{noCache:!e.cache});if(e.watch)console.log(n.yellow(`
|
|
5
5
|
\u{1F440} Watch mode enabled. Press Ctrl+C to stop.
|
|
@@ -137,6 +137,31 @@ declare class GraphQLAnalyzer extends BaseAnalyzer {
|
|
|
137
137
|
constructor(config: RepositoryConfig);
|
|
138
138
|
getName(): string;
|
|
139
139
|
analyze(): Promise<Partial<AnalysisResult>>;
|
|
140
|
+
/**
|
|
141
|
+
* Deduplicate operations by name, keeping the first occurrence
|
|
142
|
+
*/
|
|
143
|
+
private deduplicateOperations;
|
|
144
|
+
/**
|
|
145
|
+
* Analyze GraphQL Code Generator output files
|
|
146
|
+
* Supports client preset pattern: __generated__/graphql.ts
|
|
147
|
+
*/
|
|
148
|
+
private analyzeCodegenGenerated;
|
|
149
|
+
/**
|
|
150
|
+
* Extract type string from AST type node
|
|
151
|
+
*/
|
|
152
|
+
private extractTypeFromAst;
|
|
153
|
+
/**
|
|
154
|
+
* Extract fields from AST selection set
|
|
155
|
+
*/
|
|
156
|
+
private extractFieldsFromAst;
|
|
157
|
+
/**
|
|
158
|
+
* Extract fragment references from AST
|
|
159
|
+
*/
|
|
160
|
+
private extractFragmentReferencesFromAst;
|
|
161
|
+
/**
|
|
162
|
+
* Infer return type from AST definition
|
|
163
|
+
*/
|
|
164
|
+
private inferReturnTypeFromAst;
|
|
140
165
|
private analyzeGraphQLFiles;
|
|
141
166
|
private analyzeInlineGraphQL;
|
|
142
167
|
private extractOperationsFromDocument;
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { DocGeneratorConfig, DocumentationReport } from './types.js';
|
|
2
2
|
export { APICall, APIConnection, APIEndpoint, AnalysisConfig, AnalysisResult, AnalyzerType, AssociationInfo, AttributeInfo, AuthRequirement, ComponentInfo, CrossRepoAnalysis, CrossRepoLink, DataFetchingInfo, DataFlow, DataFlowNode, DiagramConfig, DiagramType, GraphQLField, GraphQLOperation, IntegrationsConfig, MermaidDiagram, ModelInfo, NavigationFlow, NavigationInfo, PageInfo, ParameterInfo, PropInfo, RepositoryConfig, RepositoryReport, RepositorySummary, ResponseInfo, SiteConfig, StepInfo, VariableInfo, WatchConfig } from './types.js';
|
|
3
|
-
export { B as BaseAnalyzer, D as DataFlowAnalyzer, G as GraphQLAnalyzer, P as PagesAnalyzer } from './dataflow-analyzer-
|
|
3
|
+
export { B as BaseAnalyzer, D as DataFlowAnalyzer, G as GraphQLAnalyzer, P as PagesAnalyzer } from './dataflow-analyzer-LeE44O3x.js';
|
|
4
4
|
export { MarkdownGenerator, MermaidGenerator, PageMapGenerator, PageMapOptions } from './generators/index.js';
|
|
5
5
|
export { DocServer, DocServerOptions } from './server/index.js';
|
|
6
6
|
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import'./chunk-6F4PWJZI.js';export{a as DocGeneratorEngine,b as DocServer}from'./chunk-
|
|
1
|
+
import'./chunk-6F4PWJZI.js';export{a as DocGeneratorEngine,b as DocServer}from'./chunk-EYHNEFTO.js';import'./chunk-H4YGP3GL.js';import'./chunk-VV3A3UE3.js';export{a as BaseAnalyzer,d as DataFlowAnalyzer,c as GraphQLAnalyzer,b as PagesAnalyzer}from'./chunk-PSM6AV63.js';export{b as MarkdownGenerator,a as MermaidGenerator}from'./chunk-XWZH2RDG.js';export{a as PageMapGenerator}from'./chunk-MOEA75XK.js';import'./chunk-PTR5IROV.js';
|
package/dist/server/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{b as DocServer}from'../chunk-
|
|
1
|
+
export{b as DocServer}from'../chunk-EYHNEFTO.js';import'../chunk-H4YGP3GL.js';import'../chunk-VV3A3UE3.js';import'../chunk-PSM6AV63.js';import'../chunk-XWZH2RDG.js';import'../chunk-MOEA75XK.js';import'../chunk-PTR5IROV.js';
|
package/package.json
CHANGED
package/dist/chunk-J2CM7T7U.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import {Project,Node,SyntaxKind}from'ts-morph';import z from'fast-glob';import*as N from'path';import*as W from'fs';import*as L from'fs/promises';import {parse}from'graphql';var F=class{config;basePath;constructor(e){this.config=e,this.basePath=e.path;}resolvePath(e){return `${this.basePath}/${e}`}getSetting(e,t=""){return this.config.settings[e]??t}log(e){console.log(`[${this.getName()}] ${e}`);}warn(e){console.warn(`[${this.getName()}] \u26A0\uFE0F ${e}`);}error(e,t){console.error(`[${this.getName()}] \u274C ${e}`,t?.message||"");}};async function E(D,e,t=8){let n=new Array(D.length).fill(null),o=0;async function i(){for(;o<D.length;){let s=o++;if(s<D.length)try{n[s]=await e(D[s],s);}catch{n[s]=null;}}}let a=Array(Math.min(t,D.length)).fill(null).map(()=>i());return await Promise.all(a),n.filter(s=>s!==null)}var q=class extends F{project;codegenMap=new Map;constructor(e){super(e),this.project=new Project({tsConfigFilePath:this.resolvePath("tsconfig.json"),skipAddingFilesFromTsConfig:true});}extractOperationNameFromGql(e){let t=e.match(/(?:query|mutation|subscription)\s+(\w+)/);if(t&&t[1])return t[1];let n=e.match(/`\s*(?:query|mutation|subscription)\s+(\w+)/);if(n&&n[1])return n[1];let o=e.match(/GraphQL[^`]*`\s*(?:\n\s*)?(?:query|mutation|subscription)\s+(\w+)/);return o&&o[1]?o[1]:null}findOperationNameFromVariable(e,t){let n=e.getVariableDeclaration(t);if(!n){let s=e.getExportedDeclarations().get(t);if(s&&s.length>0){let r=s[0];Node.isVariableDeclaration(r)&&(n=r);}}if(n||(n=e.getVariableDeclarations().find(s=>s.getName()===t)),!n){let a=e.getFullText(),s=[new RegExp(`(?:const|let|var)\\s+${t}\\s*=\\s*gql\\s*\\(\\s*/\\*[^*]*\\*/\\s*\`\\s*(?:query|mutation|subscription)\\s+(\\w+)`,"s"),new RegExp(`(?:const|let|var)\\s+${t}\\s*=\\s*gql\`\\s*(?:query|mutation|subscription)\\s+(\\w+)`,"s"),new RegExp(`(?:const|let|var)\\s+${t}\\s*=\\s*gql\\s*\\(\`\\s*(?:query|mutation|subscription)\\s+(\\w+)`,"s"),new RegExp(`(?:const|let|var)\\s+${t}\\s*=\\s*graphql\\s*\\(\`\\s*(?:query|mutation|subscription)\\s+(\\w+)`,"s")];for(let r of s){let c=a.match(r);if(c&&c[1])return c[1]}return null}let o=n.getInitializer();if(!o)return null;let i=o.getText();return this.extractOperationNameFromGql(i)}getName(){return "PagesAnalyzer"}async analyze(){this.log("Starting page analysis..."),await this.loadCodegenMapping(),await this.analyzeAppFile();let e=await this.findPageFiles();this.log(`Found ${e.length} page files`);for(let o of e)try{this.project.addSourceFileAtPath(o);}catch{}let n=(await E(e,async o=>{let i=this.detectPagesRoot(o);return this.analyzePageFile(o,i)},4)).filter(o=>o!==null);return this.log(`Analyzed ${n.length} pages successfully`),{pages:n}}async analyzePageFile(e,t){let n=this.project.getSourceFile(e);if(!n)return null;let o=N.relative(t,e),i=this.filePathToRoutePath(o),a=this.findPageComponent(n);if(!a)return null;let s=this.extractRouteParams(i),r=this.extractLayout(n),c=this.extractAuthRequirement(n),l=this.extractPermissions(n),g=this.extractDataFetching(n),u=this.extractNavigation(n),d=this.extractLinkedPages(n),C=this.extractSteps(n);return {path:i,filePath:o,component:a,params:s,layout:r,authentication:c,permissions:l,dataFetching:g,navigation:u,linkedPages:d,steps:C.length>0?C:void 0}}detectPagesRoot(e){let t=["/src/pages/","/pages/","/src/app/","/app/","/frontend/src/pages/","/app/javascript/pages/"];for(let n of t){let o=e.indexOf(n);if(o!==-1)return e.substring(0,o+n.length-1)}return this.basePath}filePathToRoutePath(e){return "/"+e.replace(/\.tsx?$/,"").replace(/\/index$/,"").replace(/\[\.\.\.(\w+)\]/g,"*").replace(/\[(\w+)\]/g,":$1")}extractRouteParams(e){let t=[],n=/:(\w+)/g,o;for(;(o=n.exec(e))!==null;)t.push(o[1]);return t}findPageComponent(e){let t=e.getDefaultExportSymbol();if(t){let s=t.getName();if(s!=="default")return s}let n=e.getExportAssignment(s=>!s.isExportEquals());if(n){let s=n.getExpression();if(s){let r=s.getText();if(/^[A-Z][a-zA-Z0-9]*$/.test(r))return r;if(Node.isFunctionExpression(s)||Node.isArrowFunction(s))return "default"}}let o=e.getFunctions();for(let s of o)if(s.isDefaultExport())return s.getName()||"default";if(e.getVariableDeclaration("Page"))return "Page";let a=e.getVariableDeclarations();for(let s of a){let r=s.getTypeNode();if(r){let c=r.getText();if(c.includes("NextPage")||c.includes("FC")||c.includes("React.FC"))return s.getName()}}for(let s of a){let r=s.getName();if(/^[A-Z][a-zA-Z0-9]*$/.test(r)){let c=s.getInitializer();if(c&&(Node.isArrowFunction(c)||Node.isFunctionExpression(c))){let l=c.getText();if(l.includes("return")&&(l.includes("<")||l.includes("jsx")))return r}}}return null}extractLayout(e){let t=e.getDescendantsOfKind(SyntaxKind.PropertyAccessExpression).find(n=>n.getName()==="getLayout");if(t){let n=t.getParent();if(Node.isBinaryExpression(n)){let i=n.getRight().getDescendantsOfKind(SyntaxKind.JsxOpeningElement);if(i.length>0)return i[0].getTagNameNode().getText()}}}extractAuthRequirement(e){let n=e.getFilePath().split("/").pop()||"",a={required:!["404.tsx","permission-denied.tsx","_app.tsx","_document.tsx","_error.tsx"].some(s=>n===s)};try{let s=["RequiredCondition","ProtectedRoute","AuthGuard","PrivateRoute","WithAuth","RequireAuth","Authenticated","Authorized"],r=e.getDescendantsOfKind(SyntaxKind.JsxOpeningElement).find(c=>{let l=c.getTagNameNode().getText();return s.some(g=>l.includes(g))});if(r){a.condition="Additional permissions required";let c=r.getAttributes();for(let l of c)if(l.isKind(SyntaxKind.JsxAttribute))try{let g=l.getNameNode().getText();if(["condition","roles","permissions","requiredRoles","allowedRoles"].includes(g)){let u=l.getInitializer();if(u){a.condition=u.getText();let d=this.extractRolesFromCondition(u.getText());d.length>0&&(a.roles=d);}}}catch{}}}catch{}return a}extractRolesFromCondition(e){let t=[],n=/(\w+Role|\w+Permission)\.(\w+)/g,o;for(;(o=n.exec(e))!==null;)t.push(o[2]);let i=/['"]([a-zA-Z_-]+)['"]/g;for(;(o=i.exec(e))!==null;){let s=o[1];/admin|user|owner|member|guest|manager|editor|viewer/i.test(s)&&t.push(s);}let a=/\b(ROLE_\w+|[A-Z]+_ROLE)\b/g;for(;(o=a.exec(e))!==null;)t.push(o[1]);return [...new Set(t)]}extractPermissions(e){let t=[],n=e.getDescendantsOfKind(SyntaxKind.PropertyAccessExpression).filter(o=>{let i=o.getText();return i.includes("Permission")||i.includes("Role")||i.includes("isAdmin")});for(let o of n){let i=o.getText();t.includes(i)||t.push(i);}return t}extractDataFetching(e){let t=[],n=new Map,o=["useQuery","useMutation","useLazyQuery","useSubscription"];for(let S of e.getImportDeclarations()){let p=S.getModuleSpecifierValue();if(p.includes("@apollo/client")||p.includes("apollo"))for(let f of S.getNamedImports()){let x=f.getName(),m=f.getAliasNode()?.getText()||x;o.includes(x)&&n.set(m,x);}}let i=n.size>0||e.getImportDeclarations().some(S=>{let p=S.getModuleSpecifierValue();return p.includes("@apollo/client")||p.includes("apollo")}),a=e.getDescendantsOfKind(SyntaxKind.CallExpression).filter(S=>{let p=S.getExpression().getText();return !!(n.has(p)||o.includes(p)||/^use[A-Z].*Query$/.test(p)&&!p.includes("Params")&&!p.includes("String")||/^use[A-Z].*Mutation$/.test(p))});for(let S of a){let p=S.getExpression().getText(),f;n.has(p)?f=n.get(p):p.includes("Mutation")?f="useMutation":p.includes("Lazy")?f="useLazyQuery":f="useQuery";let x=S.getArguments();if(x.length===0){if(/^use[A-Z]/.test(p)){let T=p.replace(/^use/,"").replace(/Query$|Mutation$/,"");t.push({type:f,operationName:T,variables:[]});}continue}let h=x[0].getText();if(h.startsWith("[")||h.startsWith("{")||h.startsWith("'")||h.startsWith('"')||h.startsWith("`")||!(i||h.endsWith("Document")||h.endsWith("Query")||h.endsWith("Mutation")||h.includes("gql")||/^[A-Z_]+$/.test(h)))continue;let y=h.replace(/Document$/,"").replace(/Query$|Mutation$/,""),A=[];if(x.length>1){let w=x[1].getDescendantsOfKind(SyntaxKind.PropertyAssignment).find(b=>{try{return b.getName()==="variables"}catch{return false}});if(w){let b=w.getInitializer();if(b){let R=b.getDescendantsOfKind(SyntaxKind.PropertyAssignment);for(let Z of R)try{A.push(Z.getName());}catch{}}}}t.push({type:f,operationName:y,variables:A});}let s=e.getVariableDeclaration("getServerSideProps"),r=e.getFunction("getServerSideProps"),c=s||r;if(c){let S=e.getImportDeclarations();for(let x of S){let m=x.getNamedImports();for(let h of m){let v=h.getName();if(v.endsWith("Document")&&e.getDescendantsOfKind(SyntaxKind.Identifier).filter(A=>A.getText()===v).length>0){let A=v.replace(/Document$/,"");t.push({type:"getServerSideProps",operationName:`\u2192 ${A}`});}}}let f=c.getText().match(/query:\s*(\w+)/g);if(f)for(let x of f){let m=x.replace(/query:\s*/,"");t.some(h=>h.operationName?.includes(m.replace(/Document$/,"")))||t.push({type:"getServerSideProps",operationName:`\u2192 ${m.replace(/Document$/,"")}`});}}let l=e.getVariableDeclaration("getStaticProps"),g=e.getFunction("getStaticProps");(l||g)&&t.push({type:"getStaticProps",operationName:"getStaticProps"});let u=e.getImportDeclarations(),d=e.getFilePath(),C=N.dirname(d);for(let S of u){let p=S.getModuleSpecifierValue(),f=p.startsWith(".")||p.startsWith("/"),x=!p.includes("node_modules")&&!p.startsWith("@types/")&&p.startsWith("@")===false;if(f||x){if(p.includes("__generated__")||p.includes("/generated/"))continue;let m=[],h=S.getNamedImports();for(let y of h){let A=y.getName();this.isComponentName(A)&&m.push(A);}let v=S.getDefaultImport();if(v){let y=v.getText();this.isComponentName(y)&&m.push(y);}for(let y of m){let A=this.analyzeImportedComponent(C,p,y);if(A.length>0)for(let T of A)t.push({type:T.type,operationName:T.operationName.startsWith("\u2192")?`\u2192 ${T.operationName} (${y})`:`\u2192 ${T.operationName} (${y})`,variables:T.variables});else t.push({type:"component",operationName:y,variables:[]});}}}return t}symbolTraceCache=new Map;analyzeImportedComponent(e,t,n,o=new Set,i=0){if(i>10)return [];let s=[];try{let r=N.resolve(e,t),c=`${r}:${n}`;if(o.has(c))return [];o.add(c);let l=this.symbolTraceCache.get(c);if(l!==void 0)return l;let g=[`${r}.tsx`,`${r}.ts`,`${r}/index.tsx`,`${r}/index.ts`,`${r}/${n}.tsx`,`${r}/${n}.ts`],u,d;for(let p of g)try{if(u=this.project.addSourceFileAtPath(p),u){d=p;break}}catch{}if(!u||!d)return s;if(d.endsWith("index.tsx")||d.endsWith("index.ts")){let p=this.followReExport(u,n,N.dirname(d));p&&(u=p);}let C=u.getImportDeclarations().some(p=>{let f=p.getModuleSpecifierValue();return f.includes("@apollo/client")||f.includes("apollo")||f.includes("gql")||f.includes("graphql")||f.includes("__generated__")}),S=u.getImportDeclarations().filter(p=>{let f=p.getModuleSpecifierValue();return f.startsWith("./")||f.startsWith("../")});for(let p of S){let f=p.getModuleSpecifierValue(),x=p.getNamedImports().map(m=>m.getName()).filter(m=>/^use[A-Z]/.test(m));for(let m of x){let h=this.analyzeCustomHook(N.dirname(u.getFilePath()),f,m,o,i+1);s.push(...h);}}for(let p of S){let f=p.getModuleSpecifierValue(),x=p.getNamedImports().map(v=>v.getName()),m=p.getDefaultImport()?.getText(),h=x.filter(v=>/^[A-Z]/.test(v)&&this.isComponentName(v));for(let v of h){let y=this.analyzeImportedComponent(N.dirname(u.getFilePath()),f,v,o,i+1);s.push(...y);}if(m&&/^[A-Z]/.test(m)&&this.isComponentName(m)){let v=this.analyzeImportedComponent(N.dirname(u.getFilePath()),f,m,o,i+1);s.push(...v);}}if(C){let p=u.getDescendantsOfKind(SyntaxKind.CallExpression).filter(f=>{let x=f.getExpression().getText();return ["useQuery","useMutation","useLazyQuery","useSubscription"].includes(x)});for(let f of p){let x=f.getExpression().getText(),m=f.getArguments();if(m.length===0)continue;let v=m[0].getText(),y=v,A=null,T=this.resolveDocumentName(v);if(T)y=T.operationName,A=T.operationType;else if(v.endsWith("Document"))y=v.replace(/Document$/,"");else if(/^[A-Za-z]/.test(v)){let b=this.findOperationNameFromVariable(u,v);if(b&&(y=b),y===v&&v!=="Query"&&v!=="Mutation"){let R=v.match(/^(.+?)(Query|Mutation|Subscription)$/);R&&(y=R[1]);}}y!=="Query"&&y!=="Mutation"&&(y=y.replace(/Document$/,"").replace(/Query$|Mutation$/,"")||y),(y==="Query"||y==="Mutation"||y==="")&&y===""&&(y=v||"Unknown");let w=A?A==="mutation"?"useMutation":A==="subscription"?"useSubscription":x.includes("Lazy")?"useLazyQuery":"useQuery":x.includes("Mutation")?"useMutation":x.includes("Lazy")?"useLazyQuery":"useQuery";s.push({type:w,operationName:y,variables:[]});}}this.symbolTraceCache.set(c,s);}catch{}return s}analyzeCustomHook(e,t,n,o=new Set,i=0){if(i>10)return [];let s=[];try{let r=N.resolve(e,t),c=`hook:${r}:${n}`;if(o.has(c))return [];o.add(c);let l=this.symbolTraceCache.get(c);if(l!==void 0)return l;let g=[`${r}.tsx`,`${r}.ts`,`${r}/${n}.tsx`,`${r}/${n}.ts`,`${r}/index.tsx`,`${r}/index.ts`],u;for(let p of g)try{if(u=this.project.addSourceFileAtPath(p),u)break}catch{}if(!u)return s;let d=u.getImportDeclarations().some(p=>{let f=p.getModuleSpecifierValue();return f.includes("@apollo/client")||f.includes("apollo")||f.includes("graphql")||f.includes("__generated__")}),C=u.getImportDeclarations().filter(p=>{let f=p.getModuleSpecifierValue();return f.startsWith("./")||f.startsWith("../")});for(let p of C){let f=p.getModuleSpecifierValue(),x=p.getNamedImports().map(m=>m.getName()).filter(m=>/^use[A-Z]/.test(m));for(let m of x){let h=this.analyzeCustomHook(N.dirname(u.getFilePath()),f,m,o,i+1);s.push(...h);}}if(!d&&s.length===0)return s;let S=u.getDescendantsOfKind(SyntaxKind.CallExpression).filter(p=>{let f=p.getExpression().getText();return ["useQuery","useMutation","useLazyQuery","useSubscription"].includes(f)});for(let p of S){let f=p.getExpression().getText(),x=p.getArguments();if(x.length===0)continue;let m=x[0].getText(),h=m,v=null,y=this.resolveDocumentName(m);if(y)h=y.operationName,v=y.operationType;else if(m.endsWith("Document"))h=m.replace(/Document$/,"");else if(/^[A-Za-z]/.test(m)){let T=this.findOperationNameFromVariable(u,m);if(T&&(h=T),h===m&&m!=="Query"&&m!=="Mutation"){let w=m.match(/^(.+?)(Query|Mutation|Subscription)$/);w&&(h=w[1]);}}h!=="Query"&&h!=="Mutation"&&(h=h.replace(/Document$/,"").replace(/Query$|Mutation$/,"")||h),h===""&&(h=m||"Unknown");let A=v?v==="mutation"?"useMutation":v==="subscription"?"useSubscription":f.includes("Lazy")?"useLazyQuery":"useQuery":f.includes("Mutation")?"useMutation":f.includes("Lazy")?"useLazyQuery":"useQuery";s.push({type:A,operationName:`\u2192 ${h} (via ${n})`,variables:[]});}this.symbolTraceCache.set(c,s);}catch{}return s}globalContextQueries=[];async findPageFiles(){let e=this.getSetting("pagesDir","src/pages"),t=[],o=[...new Set([e,"pages","src/pages","app","src/app"])];for(let s of o){if(s==="app"||s==="src/app"){let c=["controllers","models","views","helpers"],l=this.resolvePath(s);if(c.some(u=>{try{return W.existsSync(N.join(l,u))}catch{return false}}))continue}let r=this.resolvePath(s);try{let c=await z(["**/*.tsx","**/*.ts","**/*.jsx","**/*.js"],{cwd:r,ignore:["_app.tsx","_app.ts","_app.jsx","_app.js","_document.tsx","_document.ts","_document.jsx","_document.js","_error.tsx","_error.ts","_error.jsx","_error.js","api/**","**/*.test.*","**/*.spec.*","**/node_modules/**","**/components/pages/**"],absolute:!0});t.push(...c),c.length>0&&this.log(`Found ${c.length} pages in ${s}`);}catch{}}let i=["frontend/src/**/pages","app/javascript/**/pages"];for(let s of i)try{let r=await z([`${s}/**/*.tsx`,`${s}/**/*.ts`,`${s}/**/*.jsx`,`${s}/**/*.js`],{cwd:this.basePath,ignore:["**/*.test.*","**/*.spec.*","**/node_modules/**","**/vendor/**","**/components/pages/**","**/stories/**"],absolute:!0});t.push(...r),r.length>0&&this.log(`Found ${r.length} React pages in ${s}`);}catch{}let a=["frontend/src/**/index.tsx","frontend/src/**/App.tsx","app/javascript/packs/*.tsx","app/javascript/packs/*.jsx"];for(let s of a)try{let r=await z([s],{cwd:this.basePath,ignore:["**/node_modules/**","**/vendor/**"],absolute:!0});for(let c of r)t.includes(c)||t.push(c);}catch{}return [...new Set(t)]}async analyzeAppFile(){let e=this.getSetting("pagesDir","src/pages"),t=[this.resolvePath(`${e}/_app.tsx`),this.resolvePath(`${e}/_app.ts`)];for(let n of t)try{let o=this.project.addSourceFileAtPath(n);if(!o)continue;let i=o.getDescendantsOfKind(SyntaxKind.JsxElement),a=o.getDescendantsOfKind(SyntaxKind.JsxSelfClosingElement),s=new Set;for(let r of [...i,...a]){let c=r.getFirstDescendantByKind(SyntaxKind.Identifier)?.getText();c&&(c.includes("Provider")||c.includes("Context"))&&s.add(c);}for(let r of o.getImportDeclarations()){let c=r.getModuleSpecifierValue();if(!c.startsWith("./")&&!c.startsWith("../"))continue;let l=r.getNamedImports().map(u=>u.getName()),g=r.getDefaultImport()?.getText();for(let u of s)if(l.includes(u)||g===u){let d=this.analyzeImportedComponent(N.dirname(n),c,u,new Set,0);for(let C of d)this.globalContextQueries.push({...C,operationName:`[Global] ${C.operationName}`});}}this.globalContextQueries.length>0&&this.log(`Found ${this.globalContextQueries.length} global context queries from _app`);return}catch{}}async loadCodegenMapping(){let e=["__generated__","src/__generated__","src/__generated__/gql-graphql-gateway","generated","src/generated"];for(let t of e){let n=this.resolvePath(t);try{let o=await z(["**/*.ts","**/*.tsx"],{cwd:n,absolute:!0,onlyFiles:!0});for(let i of o)try{let a=this.project.addSourceFileAtPath(i),s=a.getVariableDeclarations();for(let c of s){let l=c.getName();if(l.endsWith("Document")){let g=c.getInitializer()?.getText()??"",u=g.match(/(?:query|mutation|subscription)\s+(\w+)/),d=g.match(/(query|mutation|subscription)\s+/);u&&this.codegenMap.set(l,{operationName:u[1],operationType:d?d[1]:"query"});}}let r=a.getTypeAliases();for(let c of r){let l=c.getName();if((l.endsWith("Query")||l.endsWith("Mutation")||l.endsWith("Subscription"))&&!l.endsWith("Variables")){let g=l+"Document";if(!this.codegenMap.has(g)){let u=l.endsWith("Mutation")?"mutation":l.endsWith("Subscription")?"subscription":"query";this.codegenMap.set(g,{operationName:l,operationType:u});}}}}catch{}if(this.codegenMap.size>0){this.log(`Loaded ${this.codegenMap.size} codegen mappings from ${t}`);return}}catch{}}}resolveDocumentName(e){if(new Set(["Query","Mutation","Subscription"]).has(e))return null;let n=this.codegenMap.get(e);if(n!==void 0)return n;let o=e.endsWith("Document")?e:e+"Document",i=this.codegenMap.get(o);return i!==void 0?i:null}followReExport(e,t,n){try{let o=e.getExportDeclarations(),i=null;for(let a of o){let s=a.getNamedExports();for(let r of s){let c=a.getModuleSpecifierValue();if(!c)continue;let l=N.resolve(n,c),g=[`${l}.tsx`,`${l}.ts`,`${l}/index.tsx`,`${l}/index.ts`],u;for(let d of g)try{if(u=this.project.addSourceFileAtPath(d),u)break}catch{}if(u&&(i||(i=u),r.getName()===t||r.getAliasNode()?.getText()===t))return u}}if(i)return i;for(let a of e.getExportDeclarations())if(a.isNamespaceExport()){let s=a.getModuleSpecifierValue();if(s){let r=N.resolve(n,s),c=[`${r}.tsx`,`${r}.ts`];for(let l of c)try{let g=this.project.addSourceFileAtPath(l);if(g&&g.getExportedDeclarations().has(t))return g}catch{}}}}catch{}return null}isComponentName(e){return !/^[A-Z]/.test(e)||e.endsWith("Query")||e.endsWith("Mutation")||e.endsWith("Subscription")||e.endsWith("Fragment")||e.endsWith("Document")||e.endsWith("Variables")||e==="Query"||e==="Mutation"||e==="Subscription"||new Set(["NextPage","NextPageContext","NextApiRequest","NextApiResponse","GetServerSideProps","GetStaticProps","GetStaticPaths","InferGetServerSidePropsType","InferGetStaticPropsType","FC","FunctionComponent","VFC","Component","PureComponent","ReactNode","ReactElement","PropsWithChildren","ComponentProps","ComponentType","ElementType","RefObject","MutableRefObject","Dispatch","SetStateAction","ChangeEvent","MouseEvent","KeyboardEvent","FormEvent","SyntheticEvent"]).has(e)?false:!!(["Container","Page","Screen","View","Form","Modal","Dialog","Panel","Root","Provider","Wrapper"].some(o=>e.endsWith(o))||/Page[A-Z]?\w*$/.test(e)||/Container[A-Z]?\w*$/.test(e)||/^[A-Z][a-z]+[A-Z][a-z]+/.test(e))}extractNavigation(e){let t={visible:true,currentNavItem:null};try{let n=e.getDescendantsOfKind(SyntaxKind.PropertyAccessExpression).find(o=>{try{return o.getName()==="globalNavigationStyle"}catch{return !1}});if(n){let o=n.getParent();if(Node.isBinaryExpression(o)){let i=o.getRight(),a=i.getDescendantsOfKind(SyntaxKind.PropertyAssignment).find(c=>{try{return c.getName()==="visible"}catch{return !1}});a&&(t.visible=a.getInitializer()?.getText()==="true");let s=i.getDescendantsOfKind(SyntaxKind.PropertyAssignment).find(c=>{try{return c.getName()==="currentNavItem"}catch{return !1}});if(s){let c=s.getInitializer()?.getText();t.currentNavItem=c&&c!=="null"?c.replace(/['"]/g,""):null;}let r=i.getDescendantsOfKind(SyntaxKind.PropertyAssignment).find(c=>{try{return c.getName()==="mini"}catch{return !1}});r&&(t.mini=r.getInitializer()?.getText()==="true");}}}catch{}return t}extractSteps(e){let t=[],n=e.getDescendantsOfKind(SyntaxKind.CallExpression).filter(a=>a.getExpression().getText()==="useState");for(let a of n){let s=a.getParent();if(!s)continue;let c=s.getText().match(/\[\s*(step|currentStep|activeStep|page|currentPage|phase|stage)\s*,/i);if(c){let l=c[1],g=e.getDescendantsOfKind(SyntaxKind.SwitchStatement);for(let d of g)d.getExpression().getText().includes(l)&&d.getClauses().forEach((p,f)=>{if(p.isKind(SyntaxKind.CaseClause)){let x=p.getExpression()?.getText()||String(f),m=p.getDescendantsOfKind(SyntaxKind.JsxOpeningElement),h=m.length>0?m[0].getTagNameNode().getText():void 0;t.push({id:x.replace(/['"]/g,""),name:`Step ${x.replace(/['"]/g,"")}`,component:h});}});let u=e.getDescendantsOfKind(SyntaxKind.ArrayLiteralExpression);for(let d of u){let C=d.getParent();C&&C.getText().match(/steps|pages|screens|views|components/i)&&d.getElements().forEach((p,f)=>{let x=p.getText();if(x.startsWith("{")){let m=x.match(/(?:name|label|title)\s*:\s*['"]([^'"]+)['"]/),h=x.match(/(?:component|content)\s*:\s*<?\s*(\w+)/);t.push({id:f+1,name:m?m[1]:`Step ${f+1}`,component:h?h[1]:void 0});}else /^[A-Z]/.test(x)&&t.push({id:f+1,name:x,component:x});});}}}let o=e.getDescendantsOfKind(SyntaxKind.JsxOpeningElement);for(let a of o)if(a.getTagNameNode().getText().match(/Stepper|Wizard|Steps|TabPanel|FormStep/i)){let r=a.getParent();r&&r.isKind(SyntaxKind.JsxElement)&&r.getJsxChildren().forEach((l,g)=>{if(l.isKind(SyntaxKind.JsxElement)||l.isKind(SyntaxKind.JsxSelfClosingElement)){let u=l.isKind(SyntaxKind.JsxElement)?l.getOpeningElement().getTagNameNode().getText():l.getTagNameNode().getText(),d=l.isKind(SyntaxKind.JsxElement)?l.getOpeningElement().getAttributes():l.getAttributes(),C=u;for(let S of d)if(S.isKind(SyntaxKind.JsxAttribute)){let p=S.getNameNode().getText();if(p==="label"||p==="title"||p==="name"){let f=S.getInitializer()?.getText();if(f){C=f.replace(/['"{}]/g,"");break}}}t.push({id:g+1,name:C,component:u});}});}let i=e.getDescendantsOfKind(SyntaxKind.ConditionalExpression);for(let a of i){let s=a.getCondition().getText();if(s.match(/step\s*===?\s*\d+|currentStep|activeStep/i)){let r=a.getWhenTrue(),c=s.match(/===?\s*(\d+)/);if(c&&t.length===0){let l=r.getDescendantsOfKind(SyntaxKind.JsxOpeningElement);l.length>0&&t.push({id:parseInt(c[1]),component:l[0].getTagNameNode().getText()});}}}return t}extractLinkedPages(e){let t=[],n=e.getDescendantsOfKind(SyntaxKind.CallExpression).filter(i=>{let a=i.getExpression().getText();return a.includes("router.push")||a.includes("router.replace")||a.includes("Link")});for(let i of n){let a=i.getArguments();if(a.length>0){let r=a[0].getText().match(/['"`]([^'"`]+)['"`]/);r&&!t.includes(r[1])&&t.push(r[1]);}}let o=e.getDescendantsOfKind(SyntaxKind.JsxOpeningElement).filter(i=>i.getTagNameNode().getText()==="Link");for(let i of o)try{let a=i.getAttributes();for(let s of a)if(s.isKind(SyntaxKind.JsxAttribute)&&s.getNameNode().getText()==="href"){let l=s.getInitializer()?.getText();if(l){let g=l.match(/['"`]([^'"`]+)['"`]/);g&&!t.includes(g[1])&&t.push(g[1]);}}}catch{}return t}};var K=class extends F{project;constructor(e){super(e),this.project=new Project({tsConfigFilePath:this.resolvePath("tsconfig.json"),skipAddingFilesFromTsConfig:true});}getName(){return "GraphQLAnalyzer"}async analyze(){this.log("Starting GraphQL analysis...");let e=[],t=await this.analyzeGraphQLFiles();e.push(...t);let n=await this.analyzeInlineGraphQL();return e.push(...n),await this.findOperationUsage(e),this.log(`Found ${e.length} GraphQL operations`),{graphqlOperations:e}}async analyzeGraphQLFiles(){let e=await z(["**/*.graphql"],{cwd:this.basePath,ignore:["**/node_modules/**","**/.next/**"],absolute:true});return (await E(e,async n=>{let o=await L.readFile(n,"utf-8"),i=parse(o);return this.extractOperationsFromDocument(i,N.relative(this.basePath,n))})).flat()}async analyzeInlineGraphQL(){let e=[],t=await z(["**/*.ts","**/*.tsx"],{cwd:this.basePath,ignore:["**/node_modules/**","**/.next/**","**/__tests__/**","**/*.test.*","**/*.spec.*"],absolute:true});for(let n of t)try{let o=this.project.addSourceFileAtPath(n),i=N.relative(this.basePath,n),a=o.getImportDeclarations().some(c=>{let l=c.getModuleSpecifierValue(),g=c.getNamedImports().map(d=>d.getName()),u=c.getDefaultImport()?.getText();return (g.includes("gql")||g.includes("graphql")||u==="gql")&&(l.includes("graphql")||l.includes("apollo")||l.includes("gql")||l.includes("__generated__"))}),s=o.getDescendantsOfKind(SyntaxKind.TaggedTemplateExpression);for(let c of s){let l=c.getTag().getText();if(l==="gql"||l==="graphql")try{let g=c.getTemplate(),u="";if(g.isKind(SyntaxKind.NoSubstitutionTemplateLiteral)?u=g.getLiteralValue():g.isKind(SyntaxKind.TemplateExpression)&&(u=g.getText().slice(1,-1).replace(/\$\{[^}]*\}/g,"")),u&&u.trim())try{let d=parse(u),C=this.extractOperationsFromDocument(d,i);e.push(...C);}catch{}}catch{}}let r=o.getDescendantsOfKind(SyntaxKind.CallExpression);for(let c of r)try{let g=c.getExpression().getText();if(g==="gql"||g==="graphql"){let u=c.getArguments();if(u.length>0){let d=u[0],C="";if(d.isKind(SyntaxKind.NoSubstitutionTemplateLiteral))C=d.getLiteralValue();else if(d.isKind(SyntaxKind.TemplateExpression))C=d.getText().slice(1,-1).replace(/\$\{[^}]*\}/g,"");else {let S=d.getText();if(S.includes("`")){let p=S.match(/\/\*\s*GraphQL\s*\*\/\s*`([^`]*)`/);if(p)C=p[1];else {let f=S.match(/`([^`]*)`/);f&&(C=f[1]);}}}if(C&&C.trim())try{let S=parse(C),p=this.extractOperationsFromDocument(S,i);e.push(...p);}catch{}}}}catch{}if(a){let c=o.getVariableDeclarations();for(let l of c){let g=l.getName();if(g.includes("QUERY")||g.includes("MUTATION")||g.includes("FRAGMENT")||g.includes("Query")||g.includes("Mutation")||g.includes("Subscription")||/^[A-Z_]+_(QUERY|MUTATION|FRAGMENT|SUBSCRIPTION)$/.test(g)||/Query$|Mutation$|Fragment$|Subscription$/.test(g)){let d=l.getInitializer();d&&d.isKind(SyntaxKind.CallExpression);}}}}catch(o){this.warn(`Failed to analyze ${n}: ${o.message}`);}return e}extractOperationsFromDocument(e,t){let n=[];for(let o of e.definitions){let i=this.extractOperation(o,t);i&&n.push(i);}return n}extractOperation(e,t){if(e.kind==="OperationDefinition"){let n=e.name?.value||"anonymous",o=e.operation,i=this.extractVariables(e),a=this.extractFragmentReferences(e),s=this.extractFields(e);return {name:n,type:o,filePath:t,usedIn:[],variables:i,returnType:this.inferReturnType(e),fragments:a,fields:s}}return e.kind==="FragmentDefinition"?{name:e.name.value,type:"fragment",filePath:t,usedIn:[],variables:[],returnType:e.typeCondition.name.value,fragments:this.extractFragmentReferences(e),fields:this.extractFields(e)}:null}extractFields(e){let t=[],n=(o,i=0)=>{if(!o||!o.selections||i>5)return [];let a=[];for(let s of o.selections)if(s.kind==="Field"){let r={name:s.name.value};if(s.arguments&&s.arguments.length>0){let c=s.arguments.map(l=>l.name.value).join(", ");r.type=`(${c})`;}s.selectionSet&&(r.fields=n(s.selectionSet,i+1)),a.push(r);}else if(s.kind==="FragmentSpread")a.push({name:`...${s.name.value}`,type:"fragment"});else if(s.kind==="InlineFragment"&&s.selectionSet){let r=s.typeCondition?.name?.value||"inline";a.push({name:`... on ${r}`,type:"inline-fragment",fields:n(s.selectionSet,i+1)});}return a};return e.selectionSet?n(e.selectionSet):t}extractVariables(e){let t=[];if(e.variableDefinitions)for(let n of e.variableDefinitions){let o=n.variable.name.value,i=this.typeNodeToString(n.type),a=n.type.kind==="NonNullType";t.push({name:o,type:i,required:a});}return t}typeNodeToString(e){return e.kind==="NonNullType"?`${this.typeNodeToString(e.type)}!`:e.kind==="ListType"?`[${this.typeNodeToString(e.type)}]`:e.kind==="NamedType"?e.name.value:"unknown"}extractFragmentReferences(e){let t=[],n=o=>{if(o&&(o.kind==="FragmentSpread"&&t.push(o.name.value),o.selectionSet))for(let i of o.selectionSet.selections)n(i);};return n(e),t}inferReturnType(e){if(e.selectionSet&&e.selectionSet.selections.length>0){let t=e.selectionSet.selections[0];if(t.kind==="Field")return t.name.value}return "unknown"}async findOperationUsage(e){let t=await z(["**/*.ts","**/*.tsx"],{cwd:this.basePath,ignore:["**/node_modules/**","**/.next/**"],absolute:true}),n=new Map;for(let o of e)n.set(o.name,o);for(let o of t)try{let i=await L.readFile(o,"utf-8"),a=N.relative(this.basePath,o);for(let[s,r]of n)(i.includes(`useQuery<${s}`)||i.includes(`useMutation<${s}`)||i.includes(`useLazyQuery<${s}`)||i.includes(`${s}Query`)||i.includes(`${s}Mutation`)||i.includes(`${s}Variables`))&&(r.usedIn.includes(a)||r.usedIn.push(a));}catch{}}};var G=class extends F{project;componentCache=new Map;constructor(e){super(e),this.project=new Project({tsConfigFilePath:this.resolvePath("tsconfig.json"),skipAddingFilesFromTsConfig:true});}getName(){return "DataFlowAnalyzer"}async analyze(){this.log("Starting data flow analysis...");let e=await this.analyzeComponents(),t=await this.analyzeDataFlows(e);return this.log(`Analyzed ${e.length} components and ${t.length} data flows`),{components:e,dataFlows:t}}async analyzeComponents(){let e=[],t=[this.getSetting("featuresDir",""),this.getSetting("componentsDir",""),this.getSetting("pagesDir","")].filter(Boolean),n=["src/features","src/components","src/common/components","src/common","src/pages","src/app","src/modules","src/views","src/screens","components","pages","app"],o=[...new Set([...t,...n])];for(let i of o){let a=await z(["**/*.tsx"],{cwd:this.resolvePath(i),ignore:["**/*.test.*","**/*.spec.*","**/*.stories.*"],absolute:true});for(let s of a)try{let r=this.project.addSourceFileAtPath(s),c=N.relative(this.basePath,s),l=this.analyzeComponentFile(r,c);e.push(...l);}catch(r){this.warn(`Failed to analyze ${s}: ${r.message}`);}}return this.buildDependencyGraph(e),e}analyzeComponentFile(e,t){let n=[],o=e.getFunctions();for(let s of o){let r=s.getName();if(r&&this.isComponentName(r)){let c=this.extractComponentInfo(s,r,t);n.push(c),this.componentCache.set(r,c);}}let i=e.getVariableDeclarations();for(let s of i){let r=s.getName();if(this.isComponentName(r)){let c=s.getInitializer();if(c&&(c.isKind(SyntaxKind.ArrowFunction)||c.isKind(SyntaxKind.FunctionExpression))){let l=this.extractComponentInfo(c,r,t);n.push(l),this.componentCache.set(r,l);}}}let a=e.getFunctions().filter(s=>{let r=s.getName();return r&&r.startsWith("use")});for(let s of a){let r=s.getName()??"",c=this.extractHookInfo(s,r,t);n.push(c),this.componentCache.set(r,c);}return n}isComponentName(e){return /^[A-Z][a-zA-Z0-9]*$/.test(e)}extractComponentInfo(e,t,n){let o=e.getSourceFile(),i="presentational";["/pages/","/app/","/routes/","/views/","/screens/"].some(g=>n.includes(g))?i="page":t.includes("Container")||t.includes("Provider")?i="container":(t.includes("Layout")||t.includes("Shell")||t.includes("Wrapper")||t.includes("Frame")||t.includes("Scaffold")||n.includes("/layouts/")||n.includes("/layout/"))&&(i="layout");let s=this.extractProps(e),r=this.extractHooksUsed(e),c=this.extractDependencies(o),l=this.extractStateManagement(e);return {name:t,filePath:n,type:i,props:s,dependencies:c,dependents:[],hooks:r,stateManagement:l}}extractHookInfo(e,t,n){let o=e.getSourceFile(),i=this.extractProps(e),a=this.extractHooksUsed(e),s=this.extractDependencies(o),r=this.extractStateManagement(e);return {name:t,filePath:n,type:"hook",props:i,dependencies:s,dependents:[],hooks:a,stateManagement:r}}extractProps(e){let t=[],n=e.getParameters?.()||[];if(n.length>0){let i=n[0].getTypeNode?.();if(i){let a=i.getDescendantsOfKind?.(SyntaxKind.PropertySignature)||[];for(let s of a)t.push({name:s.getName(),type:s.getType().getText(),required:!s.hasQuestionToken()});}}return t}extractHooksUsed(e){let t=[],n=e.getDescendantsOfKind?.(SyntaxKind.CallExpression)||[];for(let o of n)try{let i=o.getExpression().getText();if(i.startsWith("use"))if(i==="useQuery"||i==="useMutation"||i==="useLazyQuery"){let a=this.extractOperationName(o,i);t.includes(a)||t.push(a);}else if(i==="useContext"){let a=this.extractContextName(o);t.includes(a)||t.push(a);}else t.includes(i)||t.push(i);}catch{}return t}extractOperationName(e,t){try{let n=e.getArguments?.()||[];if(n.length>0){let i=n[0].getText().replace(/^(GET_|FETCH_|CREATE_|UPDATE_|DELETE_)/,"").replace(/_QUERY$|_MUTATION$/,"").replace(/Document$/,"").replace(/Query$|Mutation$/,"");return `${t==="useMutation"?"\u270F\uFE0F":"\u{1F4E1}"} ${t==="useMutation"?"Mutation":"Query"}: ${i}`}}catch{}return t}extractContextName(e){try{let t=e.getArguments?.()||[];if(t.length>0)return `\u{1F504} Context: ${t[0].getText().replace(/Context$/,"").replace(/^Session|^Token|^Apollo/,o=>o)}`}catch{}return "useContext"}extractDependencies(e){let t=[],n=e.getImportDeclarations();for(let o of n){let i=o.getModuleSpecifierValue();if(i.startsWith(".")||i.startsWith("@/")){let a=o.getNamedImports();for(let r of a){let c=r.getName();(this.isComponentName(c)||c.startsWith("use"))&&t.push(c);}let s=o.getDefaultImport();if(s){let r=s.getText();this.isComponentName(r)&&t.push(r);}}}return t}extractStateManagement(e){let t=[],n=e.getText?.()||"";return n.includes("useState")&&t.push("useState"),n.includes("useReducer")&&t.push("useReducer"),n.includes("useContext")&&t.push("useContext"),n.includes("useQuery")&&t.push("Apollo Query"),n.includes("useMutation")&&t.push("Apollo Mutation"),n.includes("useRecoil")&&t.push("Recoil"),(n.includes("useSelector")||n.includes("useDispatch"))&&t.push("Redux"),t}buildDependencyGraph(e){let t=new Map;for(let n of e)t.set(n.name,n);for(let n of e)for(let o of n.dependencies){let i=t.get(o);i&&!i.dependents.includes(n.name)&&i.dependents.push(n.name);}}async analyzeDataFlows(e){let t=[],n=1,o=this.analyzeContextFlows(e);t.push(...o.map(s=>({...s,id:`flow-${n++}`})));let i=this.analyzeApolloFlows(e);t.push(...i.map(s=>({...s,id:`flow-${n++}`})));let a=this.analyzePropDrilling(e);return t.push(...a.map(s=>({...s,id:`flow-${n++}`}))),t}analyzeContextFlows(e){let t=[],n=e.filter(i=>i.name.includes("Provider")||i.name.includes("Context")),o=e.filter(i=>i.hooks.some(a=>a.includes("Context")));for(let i of n){let a=i.name.replace("Provider","").replace("Context","");for(let s of o){let r=s.hooks.find(c=>c.includes("Context")&&c.includes(a));(r||s.hooks.some(c=>c.includes(a)))&&t.push({name:`\u{1F504} ${a} Context`,description:`Data flows from ${i.name} to ${s.name} via Context`,source:{type:"context",name:i.name},target:{type:"component",name:s.name},via:[],operations:[r||`useContext(${a})`]});}}return t}analyzeApolloFlows(e){let t=[];for(let n of e){let o=n.hooks.filter(a=>a.includes("Query:")||a==="useQuery"||a==="useLazyQuery");for(let a of o){let s=a.includes(":")?a.split(":")[1].trim():n.name;t.push({name:`\u{1F4E1} ${s}`,description:`${n.name} fetches ${s} via Apollo`,source:{type:"api",name:`GraphQL: ${s}`},target:{type:"component",name:n.name},via:[{type:"cache",name:"Apollo Cache"}],operations:[a]});}let i=n.hooks.filter(a=>a.includes("Mutation:")||a==="useMutation");for(let a of i){let s=a.includes(":")?a.split(":")[1].trim():n.name;t.push({name:`\u270F\uFE0F ${s}`,description:`${n.name} mutates ${s} via Apollo`,source:{type:"component",name:n.name},target:{type:"api",name:`GraphQL: ${s}`},via:[],operations:[a]});}}return t}analyzePropDrilling(e){let t=[];for(let n of e)n.props.length>5&&n.dependents.length>0&&t.push({name:`Prop Drilling through ${n.name}`,description:`${n.name} passes ${n.props.length} props to children`,source:{type:"component",name:n.name},target:{type:"component",name:n.dependents[0]},via:[],operations:["props"]});return t}};var H=class extends F{project;apiCallCounter=0;constructor(e){super(e),this.project=new Project({tsConfigFilePath:this.resolvePath("tsconfig.json"),skipAddingFilesFromTsConfig:true});}getName(){return "RestApiAnalyzer"}async analyze(){this.log("Starting REST API analysis...");let e=await z(["**/*.ts","**/*.tsx"],{cwd:this.basePath,ignore:["**/node_modules/**","**/.next/**","**/__tests__/**","**/*.test.*","**/*.spec.*","**/*.stories.*","**/__generated__/**","**/dist/**","**/build/**"],absolute:true}),t=new Map;for(let i of e)try{t.set(i,this.project.addSourceFileAtPath(i));}catch{}let o=(await E(Array.from(t.entries()),async([i,a])=>{let s=N.relative(this.basePath,i),r=[];return r.push(...this.findFetchCalls(a,s)),r.push(...this.findAxiosCalls(a,s)),r.push(...this.findSwrCalls(a,s)),r},8)).flat();return this.log(`Found ${o.length} REST API calls`),{apiCalls:o}}findFetchCalls(e,t){let n=[],o=e.getDescendantsOfKind(SyntaxKind.CallExpression);for(let i of o)try{let s=i.getExpression().getText();if(s==="fetch"||s==="window.fetch"){let r=this.extractFetchCall(i,t);r&&n.push(r);}}catch{}return n}findAxiosCalls(e,t){let n=[],o=e.getDescendantsOfKind(SyntaxKind.CallExpression);for(let i of o)try{let s=i.getExpression().getText(),r=s.match(/^axios\.(get|post|put|delete|patch)$/i);if(r){let c=this.extractAxiosCall(i,t,r[1].toUpperCase());c&&n.push(c);}if(s==="axios"){let c=this.extractAxiosDirectCall(i,t);c&&n.push(c);}}catch{}return n}findSwrCalls(e,t){let n=[],o=e.getDescendantsOfKind(SyntaxKind.CallExpression);for(let i of o)try{let s=i.getExpression().getText();if(s==="useSWR"||s==="useSWRImmutable"){let r=this.extractSwrCall(i,t);r&&n.push(r);}}catch{}return n}extractFetchCall(e,t){let n=e.getArguments();if(n.length===0)return null;let o=n[0].getText(),i=this.extractUrlFromArg(o);if(!i.url||!i.isPlaceholder&&!this.isApiUrl(i.url))return null;let a="GET",s=false;if(n.length>1){let l=n[1].getText(),g=l.match(/method:\s*["'](\w+)["']/i);g&&(a=this.normalizeMethod(g[1])),s=l.includes("credentials")||l.includes("Authorization")||l.includes("withCredentials");}let r=this.getContainingFunctionName(e),c=e.getStartLineNumber();return {id:`api-${++this.apiCallCounter}`,method:a,url:i.url,callType:"fetch",filePath:t,line:c,containingFunction:r,usedIn:[],requiresAuth:s,category:this.categorizeApi(i.url)}}extractAxiosCall(e,t,n){let o=e.getArguments();if(o.length===0)return null;let i=o[0].getText(),a=this.extractUrlFromArg(i);if(!a.url)return null;let s=false;if(o.length>1){let l=o[o.length-1].getText();s=l.includes("withCredentials")||l.includes("Authorization");}let r=this.getContainingFunctionName(e),c=e.getStartLineNumber();return {id:`api-${++this.apiCallCounter}`,method:this.normalizeMethod(n),url:a.url,callType:"axios",filePath:t,line:c,containingFunction:r,usedIn:[],requiresAuth:s,category:this.categorizeApi(a.url)}}extractAxiosDirectCall(e,t){let n=e.getArguments();if(n.length===0)return null;let o=n[0].getText(),i=o.match(/url:\s*["'`]([^"'`]+)["'`]/),a=o.match(/method:\s*["'](\w+)["']/i);if(!i)return null;let s=i[1],r=a?this.normalizeMethod(a[1]):"GET",c=o.includes("withCredentials")||o.includes("Authorization"),l=this.getContainingFunctionName(e),g=e.getStartLineNumber();return {id:`api-${++this.apiCallCounter}`,method:r,url:s,callType:"axios",filePath:t,line:g,containingFunction:l,usedIn:[],requiresAuth:c,category:this.categorizeApi(s)}}extractSwrCall(e,t){let n=e.getArguments();if(n.length===0)return null;let o=n[0].getText(),i=null;if(o.startsWith('"')||o.startsWith("'")||o.startsWith("`"))i=this.cleanStringLiteral(o);else if(o.includes("?")&&o.includes(":")){let r=o.match(/\?\s*["'`]([^"'`]+)["'`]/);r?i=r[1]:(r=o.match(/:\s*["'`]([^"'`]+)["'`]/),r&&(i=r[1])),i||(r=o.match(/\?\s*`([^`]+)`/),r&&(i=r[1].replace(/\$\{[^}]+\}/g,":param")));}else {let r=this.extractUrlFromArg(o);r.url&&!o.includes("null")&&!o.includes("undefined")&&(i=r.url);}if(!i)return null;let a=this.getContainingFunctionName(e),s=e.getStartLineNumber();return {id:`api-${++this.apiCallCounter}`,method:"GET",url:i,callType:"useSWR",filePath:t,line:s,containingFunction:a,usedIn:[],requiresAuth:false,category:this.categorizeApi(i)}}getContainingFunctionName(e){let t=e;for(;t;){if(Node.isFunctionDeclaration(t))return t.getName()||"anonymous";if(Node.isVariableDeclaration(t)||Node.isMethodDeclaration(t))return t.getName();if(Node.isArrowFunction(t)){let n=t.getParent();if(n&&Node.isVariableDeclaration(n))return n.getName()}t=t.getParent();}return "unknown"}extractUrlFromArg(e){if(/^["'`]/.test(e))return {url:this.cleanStringLiteral(e),isPlaceholder:false};let t=e.match(/^(\w+)\s*\(\s*["'`]([^"'`]+)["'`]/);if(t)return {url:`[${t[1]}] ${t[2]}`,isPlaceholder:true};let n=e.match(/^(\w+)\s*\(\s*`([^`]+)`/);if(n){let o=n[2].replace(/\$\{[^}]+\}/g,":param");return {url:`[${n[1]}] ${o}`,isPlaceholder:true}}return /^\w+(\.\w+)*$/.test(e)?{url:`[${e}]`,isPlaceholder:true}:e.includes(".")?{url:`[${e}]`,isPlaceholder:true}:{url:null,isPlaceholder:false}}cleanStringLiteral(e){let t=e.replace(/^["'`]|["'`]$/g,"").trim();return t.includes("${")?t.replace(/\$\{[^}]+\}/g,":param"):t||null}isApiUrl(e){return e.startsWith("data:")||e.startsWith("blob:")||/\.(css|js|png|jpg|jpeg|gif|svg|ico|woff|woff2|ttf|eot|html)$/i.test(e)?false:e.startsWith("/")||e.startsWith("http")||e.includes("/api/")||e.includes(".json")||e.includes("api.")||e.includes("github.io")||e.includes("hsforms.com")||e.includes("hubspot")||e.includes("amazonaws.com")||e.includes("s3.")||e.includes("googleapis.com")||e.includes("stripe.com")||e.includes("graph.facebook.com")||e.includes("api.twitter.com")||e.includes("slack.com")||e.includes("discord.com")||e.includes("sendgrid.com")||e.includes("twilio.com")||e.includes("firebase")||e.includes("supabase")||e.includes("auth0.com")||e.includes("okta.com")||e.includes("cloudflare.com")||e.includes("vercel.com")||e.includes("netlify.com")}categorizeApi(e){if(e.includes("hsforms.com")||e.includes("hubspot"))return "HubSpot";if(e.includes("amazonaws.com")||e.includes("s3."))return "AWS S3";if(e.includes("googleapis.com"))return "Google API";if(e.includes("stripe.com"))return "Stripe";if(e.includes("graph.facebook.com"))return "Facebook";if(e.includes("api.twitter.com"))return "Twitter";if(e.includes("slack.com"))return "Slack";if(e.includes("discord.com"))return "Discord";if(e.includes("sendgrid.com"))return "SendGrid";if(e.includes("twilio.com"))return "Twilio";if(e.includes("firebase"))return "Firebase";if(e.includes("supabase"))return "Supabase";if(e.includes("auth0.com"))return "Auth0";if(e.includes("okta.com"))return "Okta";if(e.includes("github.io"))return "GitHub Pages API";if(e.startsWith("/api/"))return "Internal API";if(e.startsWith("/"))return "Internal Route";if(e.startsWith("["))return "Dynamic URL"}normalizeMethod(e){let t=e.toUpperCase();return ["GET","POST","PUT","DELETE","PATCH"].includes(t)?t:"unknown"}};export{F as a,q as b,K as c,G as d,H as e};
|