@wtdlee/repomap 0.11.0 → 0.11.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +38 -6
- package/dist/analyzers/index.d.ts +2 -2
- package/dist/analyzers/index.js +1 -1
- package/dist/chunk-5PWKCCT7.js +3 -0
- package/dist/{chunk-54DEMJO2.js → chunk-CWAQJQVH.js} +1 -1
- package/dist/cli.js +1 -1
- package/dist/{dataflow-analyzer-DIUsRpvv.d.ts → dataflow-analyzer-Woim3nqS.d.ts} +9 -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-O2SKKQVN.js +0 -3
package/README.md
CHANGED
|
@@ -25,6 +25,36 @@ Powered by [SWC](https://swc.rs/) for blazing-fast AST parsing. Analyze large-sc
|
|
|
25
25
|
|
|
26
26
|
> 🚀 **10x faster** than ts-morph based solutions. No caching needed!
|
|
27
27
|
|
|
28
|
+
## Screenshots
|
|
29
|
+
|
|
30
|
+
### Page Map - List View
|
|
31
|
+
Browse all pages with filtering by page type, relationships, and data operations.
|
|
32
|
+
|
|
33
|
+
<p align="center">
|
|
34
|
+
<img src="./docs/images/page-map.png" alt="Page Map List View" width="800">
|
|
35
|
+
</p>
|
|
36
|
+
|
|
37
|
+
### Page Map - Detail Panel
|
|
38
|
+
View page details including file path, authentication status, data operations (queries/mutations), REST API calls, and related pages.
|
|
39
|
+
|
|
40
|
+
<p align="center">
|
|
41
|
+
<img src="./docs/images/page-map-detail-panel.png" alt="Page Map Detail Panel" width="800">
|
|
42
|
+
</p>
|
|
43
|
+
|
|
44
|
+
### Page Map - Operation Detail Modal
|
|
45
|
+
Drill down into specific GraphQL operations with full query definition and evidence chain showing how the operation connects to the page.
|
|
46
|
+
|
|
47
|
+
<p align="center">
|
|
48
|
+
<img src="./docs/images/page-map-detail-modal.png" alt="Page Map Operation Detail" width="800">
|
|
49
|
+
</p>
|
|
50
|
+
|
|
51
|
+
### Page Map - Graph View
|
|
52
|
+
Interactive force-directed graph visualization of page relationships and hierarchies.
|
|
53
|
+
|
|
54
|
+
<p align="center">
|
|
55
|
+
<img src="./docs/images/page-map-graph.png" alt="Page Map Graph View" width="800">
|
|
56
|
+
</p>
|
|
57
|
+
|
|
28
58
|
## Features
|
|
29
59
|
|
|
30
60
|
### 🗺️ Page Map
|
|
@@ -89,11 +119,11 @@ npx @wtdlee/repomap serve
|
|
|
89
119
|
|
|
90
120
|
| Command | Description |
|
|
91
121
|
|---------|-------------|
|
|
92
|
-
| `repomap serve` | Start
|
|
93
|
-
| `repomap generate` | Generate
|
|
94
|
-
| `repomap init` |
|
|
95
|
-
| `repomap rails` | Analyze Rails application and generate
|
|
96
|
-
| `repomap diff` | Show changes since last generation |
|
|
122
|
+
| `repomap serve` | Start local documentation server with live reload |
|
|
123
|
+
| `repomap generate` | Generate documentation from source code |
|
|
124
|
+
| `repomap init` | Initialize repomap configuration |
|
|
125
|
+
| `repomap rails` | Analyze a Rails application and generate interactive map |
|
|
126
|
+
| `repomap diff` | Show documentation changes since last generation |
|
|
97
127
|
|
|
98
128
|
### CLI Options
|
|
99
129
|
|
|
@@ -397,6 +427,7 @@ export default config;
|
|
|
397
427
|
- **Rails Routes**: Browse routes with response type indicators (JSON, HTML, Redirect)
|
|
398
428
|
- **Rails Screens**: View-based screen listing with template info
|
|
399
429
|
- **React Components**: React components used in Rails views with usage locations
|
|
430
|
+
- **Export CSV**: Export the currently selected page details as a human-readable CSV (includes a timestamp in the filename)
|
|
400
431
|
|
|
401
432
|
#### Route Indicators
|
|
402
433
|
| Tag | Meaning |
|
|
@@ -414,7 +445,7 @@ export default config;
|
|
|
414
445
|
- **Controllers Tab**: Controllers with actions and filters
|
|
415
446
|
- **Models Tab**: Models with associations and validations
|
|
416
447
|
- **gRPC Tab**: gRPC services with RPC methods
|
|
417
|
-
- **Diagram Tab**: Model relationships ER diagram
|
|
448
|
+
- **Diagram Tab**: Model relationships ER diagram (copy Mermaid source, download SVG/PNG)
|
|
418
449
|
|
|
419
450
|
#### Features
|
|
420
451
|
- Multi-select filters (Ctrl/Cmd + click)
|
|
@@ -426,6 +457,7 @@ export default config;
|
|
|
426
457
|
- Auto-generated markdown documentation
|
|
427
458
|
- Navigation sidebar
|
|
428
459
|
- Syntax-highlighted code blocks
|
|
460
|
+
- Mermaid diagrams: zoom, reset, fullscreen, copy Mermaid source, download SVG/PNG
|
|
429
461
|
- Coverage metrics (parse failures, codegen detection) to prevent silent omissions
|
|
430
462
|
|
|
431
463
|
## Supported Frameworks
|
|
@@ -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-Woim3nqS.js';
|
|
2
|
+
export { D as DataFlowAnalyzer, G as GraphQLAnalyzer, P as PagesAnalyzer } from '../dataflow-analyzer-Woim3nqS.js';
|
|
3
3
|
import { Module, CallExpression } from '@swc/core';
|
|
4
4
|
import { DataFetchingInfo, RepositoryConfig, AnalysisResult } from '../types.js';
|
|
5
5
|
|
package/dist/analyzers/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{f as ALL_GRAPHQL_HOOKS,a as BaseAnalyzer,B as DataFlowAnalyzer,h as GRAPHQL_INDICATORS,d as GRAPHQL_MUTATION_HOOKS,e as GRAPHQL_OTHER_HOOKS,c as GRAPHQL_QUERY_HOOKS,A as GraphQLAnalyzer,g as HOOK_TYPE_MAP,z as PagesAnalyzer,C as RestApiAnalyzer,o as cleanOperationName,s as extractGraphQLContext,x as extractGraphQLOperationsFromFile,t as extractOperationNameFromGqlCall,u as extractOperationNameFromTemplate,q as getCalleeName,y as getHookInfoString,m as getHookType,v as hasGraphQLArgument,n as hasGraphQLIndicators,l as isGraphQLHook,j as isMutationHook,i as isQueryHook,k as isSubscriptionHook,p as parseToAst,w as resolveOperationName,r as traverseAst}from'../chunk-
|
|
1
|
+
export{f as ALL_GRAPHQL_HOOKS,a as BaseAnalyzer,B as DataFlowAnalyzer,h as GRAPHQL_INDICATORS,d as GRAPHQL_MUTATION_HOOKS,e as GRAPHQL_OTHER_HOOKS,c as GRAPHQL_QUERY_HOOKS,A as GraphQLAnalyzer,g as HOOK_TYPE_MAP,z as PagesAnalyzer,C as RestApiAnalyzer,o as cleanOperationName,s as extractGraphQLContext,x as extractGraphQLOperationsFromFile,t as extractOperationNameFromGqlCall,u as extractOperationNameFromTemplate,q as getCalleeName,y as getHookInfoString,m as getHookType,v as hasGraphQLArgument,n as hasGraphQLIndicators,l as isGraphQLHook,j as isMutationHook,i as isQueryHook,k as isSubscriptionHook,p as parseToAst,w as resolveOperationName,r as traverseAst}from'../chunk-5PWKCCT7.js';
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import {parseSync}from'@swc/core';import j from'fast-glob';import*as y from'path';import*as F from'fs';import*as T from'fs/promises';import h from'typescript';import {parse,getLocation}from'graphql';var A=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}getListSetting(e,t=[]){let r=this.getSetting(e,"");return r?r.split(/[,\n]/g).map(s=>s.trim()).filter(Boolean):t}getGraphQLHookPatterns(){let e=(this.getSetting("graphqlHookPreset","auto")||"auto").trim().toLowerCase(),t=this.getListSetting("graphqlHookPatterns",[]),r=["useLazyLoadQuery","usePreloadedQuery","useQueryLoader","useMutation","useSubscription","useFragment","usePaginationFragment","useRefetchableFragment","useRelayEnvironment"],s=["useUrql*"],i=["useGql*","useGraphQL*","useGraphql*","useApiQuery*","useApiMutation*"],n=[];return e==="none"||e==="off"||e==="false"?n=[]:e==="apollo"?n=[]:e==="urql"?n=s:e==="relay"?n=r:n=[...r,...s,...i],Array.from(new Set([...n,...t]))}log(e){process.env.REPOMAP_VERBOSE==="1"&&console.log(`[${this.getName()}] ${e}`);}warn(e){console.warn(`\u26A0\uFE0F ${e}`);}error(e,t){console.error(`\u274C ${e}`,t?.message||"");}};var ee=["useQuery","useLazyQuery","useSuspenseQuery","useBackgroundQuery","useReadQuery"],te=["useMutation"],ve=["useSubscription","useFragment","useApolloClient"],W=[...ee,...te,...ve],X={useQuery:"useQuery",useSuspenseQuery:"useQuery",useBackgroundQuery:"useQuery",useReadQuery:"useQuery",useLazyQuery:"useLazyQuery",useMutation:"useMutation",useSubscription:"useSubscription"},be=["Document","useQuery","useMutation","useLazyQuery","useSuspenseQuery","useBackgroundQuery","useSubscription","Query","Mutation","gql","graphql","GET_","FETCH_","SEARCH_","CREATE_","UPDATE_","DELETE_","SUBSCRIBE_","@apollo","ApolloClient","@urql","urql","react-relay","Relay"];function Ce(p,e){if(!e)return false;if(e===p)return true;if(!e.includes("*"))return false;let t=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${t}$`).test(p)}function E(p,e){for(let t of e)if(Ce(p,t))return true;return false}function R(p,e=[]){return E(p,e)?/Query$/.test(p)||!/(Mutation|Subscription)$/.test(p):ee.includes(p)||/^use[A-Z].*Query$/.test(p)}function Q(p,e=[]){return E(p,e)?/Mutation$/.test(p)||p.toLowerCase().includes("mutation"):te.includes(p)||/^use[A-Z].*Mutation$/.test(p)}function ne(p,e=[]){return E(p,e)?/Subscription$/.test(p)||p.toLowerCase().includes("subscription"):p==="useSubscription"}function $(p,e=[]){return E(p,e)?true:W.includes(p)||R(p,e)||Q(p,e)}function q(p,e=[]){return X[p]?X[p]:p.includes("Mutation")||E(p,e)?"useMutation":p.includes("Lazy")?"useLazyQuery":p.includes("Subscription")?"useSubscription":"useQuery"}function H(p){return be.some(e=>p.includes(e))}function d(p){return p.replace(/^(GET_|FETCH_|CREATE_|UPDATE_|DELETE_)/,"").replace(/_QUERY$|_MUTATION$/,"").replace(/Document$/,"").replace(/Query$|Mutation$|Variables$|Subscription$/,"")}function Ae(p){try{return parseSync(p,{syntax:"typescript",tsx:!0,comments:!1})}catch{return null}}function v(p){return p?p.type==="Identifier"?p.value:p.type==="MemberExpression"&&p.property?.type==="Identifier"?p.property.value:null:null}function M(p,e){if(!(!p||typeof p!="object")){e(p);for(let t of Object.keys(p)){let r=p[t];if(Array.isArray(r))for(let s of r)M(s,e);else r&&typeof r=="object"&&M(r,e);}}}function V(p,e,t){let r={documentImports:new Map,variableOperations:new Map,staticPropertyOperations:new Map,codegenMap:t||new Map};return M(p,s=>{s.type==="ImportDeclaration"&&we(s,r.documentImports),s.type==="VariableDeclarator"&&Fe(s,e,r.variableOperations),s.type==="AssignmentExpression"&&Ne(s,e,r.staticPropertyOperations);}),r}function we(p,e){let t=p.source?.value||"",r=t.includes("__generated__")||t.includes("generated")||t.includes("graphql")||t.includes(".generated")||t.endsWith(".graphql");for(let s of p.specifiers||[]){let i;(s.type==="ImportSpecifier"||s.type==="ImportDefaultSpecifier")&&(i=s.local?.value),i&&((i.endsWith("Document")||r)&&e.set(i,i.replace(/Document$/,"")),(i.endsWith("Query")||i.endsWith("Mutation"))&&e.set(i,i.replace(/Query$|Mutation$/,"")));}}function Fe(p,e,t){if(p.id?.type!=="Identifier")return;let r=p.id.value,s=p.init;if(!s)return;let i=null;if(s.type==="CallExpression"){let n=v(s.callee);(n==="gql"||n==="graphql")&&(i=U(s,e));}if(s.type==="TaggedTemplateExpression"){let n=v(s.tag);(n==="gql"||n==="graphql")&&(i=P(s.template));}if(s.type==="Identifier"){let n=s.value;if(n.endsWith("Document")||n.endsWith("Query")||n.endsWith("Mutation")){t.set(r,n);return}}i&&t.set(r,i);}function Ne(p,e,t){if(p.left?.type!=="MemberExpression")return;let r=p.left.object,s=p.left.property;if(r?.type!=="Identifier"||s?.type!=="Identifier")return;let i=`${r.value}.${s.value}`,n=p.right;if(!n)return;let a=null;if(n.type==="CallExpression"){let o=v(n.callee);(o==="gql"||o==="graphql")&&(a=U(n,e));}if(n.type==="TaggedTemplateExpression"){let o=v(n.tag);(o==="gql"||o==="graphql")&&(a=P(n.template));}a&&t.set(i,a);}function U(p,e){if(!p.arguments?.length)return null;let t=p.arguments[0],r=t?.expression||t;if(r?.type==="TemplateLiteral")return P(r);if(p.span){let i=e.slice(p.span.start,p.span.end).match(/(?:query|mutation|subscription)\s+(\w+)/i);if(i)return i[1]}return null}function P(p,e){if(!p?.quasis?.[0])return null;let r=(p.quasis[0].raw||p.quasis[0].cooked||"").match(/(?:query|mutation|subscription)\s+(\w+)/i);return r?r[1]:null}function re(p,e,t){if(!p.arguments?.length)return false;let r=p.arguments[0],s=r?.expression||r;if(!s)return false;if(p.typeArguments?.params?.length>0){let n=p.typeArguments.params[0];if(n?.type==="TsTypeReference"&&n.typeName?.type==="Identifier"){let a=n.typeName.value;if(/Query$|Mutation$|Subscription$|Document$/.test(a))return true}}if(s.type==="Identifier"){let n=s.value;if(t.documentImports.has(n)||t.variableOperations.has(n)||n.endsWith("Document")||/^[A-Z][a-zA-Z0-9]*Query$/.test(n)||/^[A-Z][a-zA-Z0-9]*Mutation$/.test(n)||/^[A-Z][A-Z0-9_]*_QUERY$/.test(n)||/^[A-Z][A-Z0-9_]*_MUTATION$/.test(n))return true}if(s.type==="TaggedTemplateExpression"){let n=v(s.tag);if(n==="gql"||n==="graphql")return true}if(s.type==="CallExpression"){let n=v(s.callee);if(n==="gql"||n==="graphql")return true}if(s.type==="TemplateLiteral"&&s.quasis?.[0]?.raw){let n=s.quasis[0].raw;if(/(?:query|mutation|subscription)\s+\w+/i.test(n))return true}if(s.type==="MemberExpression"){let n=s.property?.value;if(n&&/Query$|Mutation$|Document$/.test(n))return true;let a=s.object?.type==="Identifier"?s.object.value:null;if(a&&n){let o=`${a}.${n}`;if(t.staticPropertyOperations.has(o))return true}}if(s.type==="ObjectExpression")for(let n of s.properties||[]){if(n.type!=="KeyValueProperty")continue;let a=n.key?.type==="Identifier"||n.key?.type==="StringLiteral"?n.key.value:null;if(!a||!["query","mutation","document","subscription"].includes(a))continue;let o=n.value;if(o&&K(o,e,t))return true}let i=p.span;if(i){let n=e.slice(i.start,Math.min(i.end,i.start+500));if(/\bDocument\b/.test(n)||/\bgql\s*[`(]/.test(n)||/\bgraphql\s*[`(]/.test(n)||/query\s+[A-Z]\w+\s*[({]/.test(n)||/mutation\s+[A-Z]\w+\s*[({]/.test(n))return true}return false}function Z(p,e,t){let r=Me(p,e);if(r)return r;if(p.arguments?.length>0){let s=p.arguments[0],i=s?.expression||s;if(i){let n=K(i,e,t);if(n)return n}}return null}function Me(p,e){if(p.typeArguments?.params?.length>0){let t=p.typeArguments.params[0];if(t?.type==="TsTypeReference"&&t.typeName?.type==="Identifier")return d(t.typeName.value)}if(p.callee?.span&&p.span){let t=p.callee.span.end,r=Math.min(t+150,p.span.end),i=e.slice(t,r).match(/^<\s*(\w+)(?:Query|Mutation|Variables|Subscription)?[\s,>]/);if(i)return d(i[1])}return null}function K(p,e,t){if(p.type==="Identifier")return se(p.value,t);if(p.type==="MemberExpression")return Se(p,t);if(p.type==="TaggedTemplateExpression"){let r=v(p.tag);if(r==="gql"||r==="graphql")return P(p.template)}if(p.type==="TemplateLiteral")return P(p);if(p.type==="CallExpression"){let r=v(p.callee);if(r==="gql"||r==="graphql")return U(p,e)}return p.type==="ObjectExpression"?ie(p,e,t):null}function se(p,e){let t=e.variableOperations.get(p);if(t)return e.variableOperations.has(t)?se(t,e):t.endsWith("Document")||t.endsWith("Query")||t.endsWith("Mutation")?e.documentImports.get(t)||d(t):t;let r=e.documentImports.get(p);if(r)return r;let s=e.codegenMap.get(p);return s?s.operationName:/^(Query|Mutation|QUERY|MUTATION|Document)$/i.test(p)?null:d(p)}function Se(p,e){let t=p.object?.type==="Identifier"?p.object.value:null,r=p.property?.type==="Identifier"?p.property.value:null;if(!r)return null;if(t){let s=`${t}.${r}`,i=e.staticPropertyOperations.get(s);if(i)return i}return d(r)}function ie(p,e,t){for(let r of p.properties||[])if(r.type==="KeyValueProperty"&&r.key?.type==="Identifier"&&r.key.value==="query")return K(r.value,e,t);return null}function je(p,e){let t=[],r=new Set;if(!H(p))return t;let s=Ae(p);if(!s)return t;let i=V(s,p,e);return M(s,n=>{if(n.type!=="CallExpression")return;let a=v(n.callee);if(a){if($(a)){let o=Z(n,p,i),l=q(a),u=`${l}:${o||"unknown"}`;r.has(u)||(r.add(u),t.push({operationName:o||"unknown",hookName:a,type:l}));}if((a==="query"||a==="mutate")&&n.arguments?.length>0){let o=n.arguments[0],l=o?.expression||o;if(l?.type==="ObjectExpression"){let u=ie(l,p,i),f=a==="mutate"?"useMutation":"useQuery",c=`${f}:${u||"unknown"}`;u&&!r.has(c)&&(r.add(c),t.push({operationName:u,hookName:`client.${a}`,type:f}));}}}}),t}function Ge(p){return `${{useQuery:"Query",useLazyQuery:"Query",useMutation:"Mutation",useSubscription:"Subscription"}[p.type]||"Query"}: ${p.operationName}`}async function S(p,e,t=8){let r=new Array(p.length).fill(null),s=0;async function i(){for(;s<p.length;){let a=s++;if(a<p.length)try{r[a]=await e(p[a],a);}catch{r[a]=null;}}}let n=Array(Math.min(t,p.length)).fill(null).map(()=>i());return await Promise.all(n),r.filter(a=>a!==null)}function k(p,e){let t=h.createSourceFile(e,p,h.ScriptTarget.Latest,true,h.ScriptKind.TS),r=[],s=i=>{if(h.isVariableStatement(i)&&Ie(i.modifiers))for(let n of i.declarationList.declarations){if(!h.isIdentifier(n.name))continue;let a=n.name.text;if(!a.endsWith("Document")||!n.initializer)continue;let o=Pe(n.initializer),l=Ee(o);if(!l)continue;let u=Re(l);if(!u)continue;let c=h.getLineAndCharacterOfPosition(t,n.name.getStart(t)).line+1;r.push({documentName:a,operationName:u.operationName,operationType:u.operationType,document:l,line:c});}h.forEachChild(i,s);};return s(t),r}function Ie(p){return p?p.some(e=>e.kind===h.SyntaxKind.ExportKeyword):false}function Pe(p){let e=p;for(;;){if(h.isParenthesizedExpression(e)){e=e.expression;continue}if(h.isAsExpression(e)){e=e.expression;continue}if(h.isTypeAssertionExpression(e)){e=e.expression;continue}if(h.isNonNullExpression(e)){e=e.expression;continue}break}return e}function Ee(p){if(!h.isObjectLiteralExpression(p))return null;let e=B(p);if(!e||typeof e!="object")return null;let t=e.kind,r=e.definitions;return t!=="Document"||!Array.isArray(r)?null:e}function Re(p){let e=p.definitions;if(!Array.isArray(e)||e.length===0)return null;let t=e[0];if(!t||typeof t!="object"||t.kind!=="OperationDefinition")return null;let s=t.operation,i=t.name,n=s==="mutation"||s==="subscription"?s:"query",a="";if(i&&typeof i=="object"){let o=i.value;typeof o=="string"&&(a=o);}return a?{operationName:a,operationType:n}:null}function B(p){if(h.isObjectLiteralExpression(p)){let e={};for(let t of p.properties){if(h.isPropertyAssignment(t)){let r=Qe(t.name);if(!r)continue;e[r]=B(t.initializer);continue}h.isShorthandPropertyAssignment(t);}return e}return h.isArrayLiteralExpression(p)?p.elements.map(e=>h.isExpression(e)?B(e):null):h.isStringLiteral(p)||h.isNoSubstitutionTemplateLiteral(p)?p.text:h.isNumericLiteral(p)?Number(p.text):p.kind===h.SyntaxKind.TrueKeyword?true:p.kind===h.SyntaxKind.FalseKeyword?false:(p.kind===h.SyntaxKind.NullKeyword,null)}function Qe(p){return h.isIdentifier(p)||h.isStringLiteral(p)||h.isNumericLiteral(p)?p.text:(h.isComputedPropertyName(p),null)}var O=class{repoRootAbs;knownFiles;configCache=new Map;configPathCache=new Map;constructor(e,t){this.repoRootAbs=y.resolve(e),this.knownFiles=t;}resolve(e,t){if(!t||!t.startsWith(".")&&!t.startsWith("/")&&!t.startsWith("@")&&!t.includes("/"))return null;let r=y.join(this.repoRootAbs,e),s=this.getParsedConfigForFile(r),i={fileExists:m=>F.existsSync(m),readFile:m=>{try{return F.readFileSync(m,"utf8")}catch{return}},directoryExists:m=>{try{return F.existsSync(m)&&F.statSync(m).isDirectory()}catch{return false}},getCurrentDirectory:()=>this.repoRootAbs,realpath:h.sys.realpath},n=s?.options||{moduleResolution:h.ModuleResolutionKind.NodeNext,jsx:h.JsxEmit.ReactJSX,allowJs:true},o=h.resolveModuleName(t,r,n,i).resolvedModule?.resolvedFileName;if(!o)return null;let l=this.toRepoRelative(o);if(!l)return null;let u=this.normalizeRel(l),f=this.pickKnownFile(u);if(!f)return null;let c=this.getConfigPathForFile(r),g=c&&this.toRepoRelative(c)||void 0;return {file:f,evidence:{fromFile:this.normalizeRel(e),specifier:t,resolvedFile:f,configFile:g}}}getConfigPathForFile(e){let t=y.dirname(e),r=this.configPathCache.get(t);if(r!==void 0)return r;let s=this.findNearestConfig(t);return this.configPathCache.set(t,s),s}getParsedConfigForFile(e){let t=this.getConfigPathForFile(e);if(!t)return null;let r=this.configCache.get(t);if(r!==void 0)return r;try{let s=h.readConfigFile(t,h.sys.readFile);if(s.error)return this.configCache.set(t,null),null;let i=h.parseJsonConfigFileContent(s.config,h.sys,y.dirname(t),void 0,t);return this.configCache.set(t,i),i}catch{return this.configCache.set(t,null),null}}findNearestConfig(e){let t=y.resolve(e),r=this.repoRootAbs;for(;;){let s=y.join(t,"tsconfig.json"),i=y.join(t,"jsconfig.json");if(F.existsSync(s))return s;if(F.existsSync(i))return i;if(t===r)break;let n=y.dirname(t);if(n===t||(t=n,!t.startsWith(r)))break}return null}toRepoRelative(e){let t=y.resolve(e);if(!t.startsWith(this.repoRootAbs))return null;let r=y.relative(this.repoRootAbs,t);return this.normalizeRel(r)}normalizeRel(e){return y.normalize(e).replace(/\\/g,"/")}pickKnownFile(e){if(this.knownFiles.has(e))return e;let t=e.replace(/\.(ts|tsx|js|jsx|mts|cts|mjs|cjs|d\.ts)$/,""),r=this.firstKnownByStem(t);if(r)return r;let s=this.firstKnownByStem(`${t}/index`);return s||null}firstKnownByStem(e){let t=[".ts",".tsx",".js",".jsx",".mts",".cts",".mjs",".cjs"];for(let r of t){let s=`${e}${r}`;if(this.knownFiles.has(s))return s}return null}};var oe=class extends A{codegenMap=new Map;tsResolver=null;coverage={tsFilesScanned:0,tsParseFailures:0,graphqlParseFailures:0,codegenFilesDetected:0,codegenFilesParsed:0,codegenExportsFound:0};constructor(e){super(e);}getName(){return "PagesAnalyzer"}async analyze(){this.log("Starting page analysis..."),await this.loadCodegenMapping();let e=await this.findPageFiles();this.coverage.tsFilesScanned+=e.length,this.log(`Found ${e.length} page files`);let t=50,r=new Map;for(let n=0;n<e.length;n+=t){let a=e.slice(n,n+t),o=await Promise.all(a.map(async l=>{try{let u=await T.readFile(l,"utf-8");return {filePath:l,content:u}}catch{return null}}));for(let l of o)l&&r.set(l.filePath,l.content);}let i=(await S(e,async n=>{let a=r.get(n);if(!a)return null;let o=this.detectPagesRoot(n);return this.analyzePageFile(n,a,o)},8)).filter(n=>n!==null);return this.log(`Analyzed ${i.length} pages successfully`),{pages:i,coverage:this.coverage}}async loadCodegenMapping(){let e=await j(["**/__generated__/graphql.ts","**/__generated__/gql.ts","**/generated/graphql.ts","**/generated/gql.ts","**/*.generated.ts","**/graphql.ts"],{cwd:this.basePath,ignore:["**/node_modules/**","**/.next/**","**/dist/**","**/build/**"],absolute:true});for(let t of e)try{let r=await T.readFile(t,"utf-8"),s=y.relative(this.basePath,t);if(!r.includes("Document")||!r.includes("definitions"))continue;this.coverage.codegenFilesDetected+=1;let i=k(r,s);this.coverage.codegenFilesParsed+=1,this.coverage.codegenExportsFound+=i.length;for(let n of i)this.codegenMap.set(n.documentName,{operationName:n.operationName,operationType:n.operationType});i.length>0&&this.log(`Loaded ${i.length} codegen mappings from ${s}`);}catch{}}analyzePageFile(e,t,r){try{let s=e.endsWith(".tsx")||e.endsWith(".jsx"),i=parseSync(t,{syntax:e.endsWith(".ts")||e.endsWith(".tsx")?"typescript":"ecmascript",tsx:s,jsx:s,comments:!1}),n=y.relative(r,e),a=this.filePathToRoutePath(n),o=this.findPageComponent(i,t);if(!o)return null;let l=this.extractRouteParams(a),u=this.extractImports(i),f=this.extractLayout(i,t),c=this.extractAuthRequirement(i,t,e),g=this.extractPermissions(t),m=this.extractDataFetching(i,t,u),x=this.extractLinkedPages(i,t),C=this.extractNavigation(t),I=this.extractSteps(t);return {path:a,filePath:n,component:o,params:l,layout:f,authentication:c,permissions:g,dataFetching:m,navigation:C,linkedPages:x,steps:I.length>0?I:void 0}}catch{return this.coverage.tsParseFailures+=1,null}}async findPageFiles(){let e=this.getSetting("pagesDir","src/pages"),t=[],s=[...new Set([e,"pages","src/pages","app","src/app"])];for(let n of s){if(n==="app"||n==="src/app"){let o=["controllers","models","views","helpers"],l=this.resolvePath(n);if(o.some(f=>{try{return F.existsSync(y.join(l,f))}catch{return false}}))continue}let a=this.resolvePath(n);try{let l=n==="app"||n==="src/app"||n.endsWith("/app")?["**/page.{tsx,ts,jsx,js}"]:["**/*.tsx","**/*.ts","**/*.jsx","**/*.js"],u=await j(l,{cwd:a,ignore:["_app.tsx","_app.ts","_app.jsx","_app.js","_document.tsx","_document.ts","_error.tsx","api/**","**/*.test.*","**/*.spec.*","**/node_modules/**","**/components/pages/**"],absolute:!0});t.push(...u),u.length>0&&this.log(`Found ${u.length} pages in ${n}`);}catch{}}let i=["frontend/src/**/pages","app/javascript/**/pages"];for(let n of i)try{let a=await j([`${n}/**/*.tsx`,`${n}/**/*.ts`,`${n}/**/*.jsx`,`${n}/**/*.js`],{cwd:this.basePath,ignore:["**/*.test.*","**/*.spec.*","**/node_modules/**","**/components/pages/**"],absolute:!0});t.push(...a);}catch{}if(t.length===0){let n=await this.findSPARoutes();n.length>0&&(this.log(`Found ${n.length} SPA routes from App.tsx`),t.push(...n));}return [...new Set(t)]}async findSPARoutes(){let e=[];if(!this.tsResolver)try{let r=await j(["**/*.{ts,tsx,js,jsx}"],{cwd:this.basePath,ignore:["**/node_modules/**","**/.next/**","**/dist/**","**/build/**"],absolute:!1,onlyFiles:!0,unique:!0,dot:!1});this.tsResolver=new O(this.basePath,new Set(r.map(s=>s.replace(/\\/g,"/"))));}catch{this.tsResolver=null;}let t=["src/App.tsx","src/App.jsx","src/App.js","App.tsx","App.jsx","App.js"];for(let r of t){let s=this.resolvePath(r);if(F.existsSync(s))try{let i=await T.readFile(s,"utf-8");if(!i.includes("react-router")&&!i.includes("Route"))continue;let n=parseSync(i,{syntax:"typescript",tsx:!0}),a=this.extractImports(n);this.traverseNode(n,o=>{if(o.type==="JSXOpeningElement"){let l=this.getJsxTagName(o);if(l==="Route"||l==="PrivateRoute"){let u=this.getJsxAttribute(o,"component"),f=this.getJsxAttribute(o,"element"),c=u||f,g=c?a.get(c):void 0;if(g){let m=this.resolveImportPath(s,g);m&&F.existsSync(m)&&e.push(m);}}}}),e.length>0&&e.push(s);}catch{}}return e}resolveImportPath(e,t){if(!t.startsWith(".")){let n=y.relative(this.basePath,e).replace(/\\/g,"/");if(this.tsResolver){let a=this.tsResolver.resolve(n,t);if(a)return y.join(this.basePath,a.file)}return null}let r=[".tsx",".ts",".jsx",".js","/index.tsx","/index.ts","/index.jsx","/index.js"],s=y.dirname(e),i=y.resolve(s,t);for(let n of r){let a=i+n;if(F.existsSync(a))return a}if(F.existsSync(i)&&F.statSync(i).isDirectory())for(let n of ["/index.tsx","/index.ts","/index.jsx","/index.js"]){let a=i+n;if(F.existsSync(a))return a}return null}detectPagesRoot(e){let t=["/src/pages/","/pages/","/src/app/","/app/","/frontend/src/pages/","/app/javascript/pages/"];for(let r of t){let s=e.indexOf(r);if(s!==-1)return e.substring(0,s+r.length-1)}return this.basePath}filePathToRoutePath(e){let t=e.replace(/\\/g,"/").replace(/\.(tsx?|jsx?)$/,"");return t=t.replace(/\/page$/,"").replace(/^page$/,""),t=t.replace(/\/route$/,"").replace(/^route$/,""),"/"+t.split("/").filter(Boolean).map(n=>n.replace(/^\(\.\.\.\)|^\(\.\.\)|^\(\.\)/,"")).filter(n=>!(n.startsWith("(")&&n.endsWith(")")||n.startsWith("@"))).join("/").replace(/\/index$/,"").replace(/\[\[\.\.\.(\w+)\]\]/g,"*").replace(/\[\.\.\.(\w+)\]/g,"*").replace(/\[(\w+)\]/g,":$1")}extractRouteParams(e){let t=[],r=e.match(/:(\w+)/g);if(r)for(let s of r)t.push(s.slice(1));return t}findDefaultExportName(e){for(let t of e.body){if(t.type==="ExportDefaultDeclaration"){let r=t.decl;if((r?.type==="FunctionExpression"||r?.type==="FunctionDeclaration")&&r.identifier?.value||(r?.type==="ClassDeclaration"||r?.type==="ClassExpression")&&r.identifier?.value)return r.identifier.value;if(r?.type==="Identifier")return r.value}if(t.type==="ExportDefaultExpression"){let r=t.expression;if(r?.type==="Identifier")return r.value}}return null}findPageComponent(e,t){let r=this.findDefaultExportName(e);if(r&&r!=="Page"&&r!=="default")return r;let s=this.findMainJsxComponent(e,t);if(s&&s!=="Page"&&s!=="default")return s;for(let i of e.body){if(i.type==="ExportDefaultDeclaration"){let n=i.decl;if((n?.type==="FunctionExpression"||n?.type==="FunctionDeclaration")&&n.identifier?.value){let a=n.identifier.value;if(a!=="Page")return a}if((n?.type==="ClassDeclaration"||n?.type==="ClassExpression")&&n.identifier?.value){let a=n.identifier.value;if(a!=="Page")return a}if(n?.type==="Identifier"){let a=n.value;if(a!=="Page")return a}if(n?.type==="ArrowFunctionExpression"||(n?.type==="FunctionExpression"||n?.type==="FunctionDeclaration")&&!n.identifier)return s||"default"}if(i.type==="ExportDefaultExpression"){let n=i.expression;if(n?.type==="Identifier"){let a=n.value;if(a!=="Page")return a}}}if(s)return s;for(let i of e.body)if(i.type==="VariableDeclaration"){for(let n of i.declarations)if(n.id?.type==="Identifier"&&n.id.value==="Page")return "Page"}for(let i of e.body)if(i.type==="ExportDeclaration"&&i.declaration?.type==="FunctionDeclaration"){let n=i.declaration.identifier?.value;if(n&&/^[A-Z]/.test(n))return n}for(let i of e.body){if(i.type==="FunctionDeclaration"){let n=i.identifier?.value;if(n&&/^[A-Z]/.test(n))return n}if(i.type==="VariableDeclaration"){for(let n of i.declarations)if(n.id?.type==="Identifier"){let a=n.id.value;if(a&&/^[A-Z]/.test(a)&&t.includes("return")&&t.includes("<"))return a}}}return null}isProjectImport(e){return e.startsWith("./")||e.startsWith("../")||/^[@~#]\//.test(e)?true:!(e.startsWith("@")&&!e.startsWith("@/")||/^[a-z]/.test(e))}findMainJsxComponent(e,t){let r=this.extractImports(e),s=new Set;for(let[a,o]of r)/^[A-Z]/.test(a)&&this.isProjectImport(o)&&s.add(a);let i=[];for(let a of s){let o=new RegExp(`<${a}[\\s/>]`,"g"),l;for(;(l=o.exec(t))!==null;)i.push({name:a,index:l.index});}let n=i.find(a=>a.name.includes("Container")||a.name.includes("Page")||a.name.includes("View")||a.name.includes("Screen"));return n?n.name:i.length>0?(i.sort((a,o)=>a.index-o.index),i[0].name):null}extractImports(e){let t=new Map;for(let r of e.body)if(r.type==="ImportDeclaration"){let s=r.source?.value||"";for(let i of r.specifiers||[])i.type==="ImportSpecifier"&&i.local?.value&&t.set(i.local.value,s),i.type==="ImportDefaultSpecifier"&&i.local?.value&&t.set(i.local.value,s);}return t}extractLayout(e,t){if(t.includes("getLayout")){let r=t.match(/getLayout\s*=.*?<(\w+Layout|\w+Shell)/);if(r)return r[1]}}extractAuthRequirement(e,t,r){let s=y.basename(r),a={required:!["404.tsx","permission-denied.tsx","_app.tsx","_document.tsx","_error.tsx"].some(l=>s===l)},o=["RequiredCondition","ProtectedRoute","AuthGuard","PrivateRoute","WithAuth","RequireAuth","Authenticated","Authorized"];for(let l of o)if(t.includes(`<${l}`)){a.condition="Additional permissions required";let u=this.extractRolesFromContent(t);u.length>0&&(a.roles=u);break}return a}extractRolesFromContent(e){let t=[];this.traverseNode({content:e},()=>{});let r=e.matchAll(/(\w+Role|\w+Permission)\.(\w+)/g);for(let s of r)t.push(s[2]);return [...new Set(t)]}extractPermissions(e){let t=[],r=e.matchAll(/(?:Permission|Role|isAdmin)\.\w+/g);for(let s of r)t.includes(s[0])||t.push(s[0]);return t}extractDataFetching(e,t,r){let s=[],i=new Set,n=new Map;for(let[l,u]of this.codegenMap)n.set(l,{operationName:u.operationName,type:u.operationType});let a=V(e,t,n),o=this.getGraphQLHookPatterns();if(M(e,l=>{if(l.type==="CallExpression"){let u=l,f=v(u.callee);if(!f)return;if($(f,o)&&re(u,t,a)){let c=Z(u,t,a),m={type:q(f,o),operationName:c||"unknown"},x=this.extractVariablesFromCall(u);Object.keys(x).length>0&&(m.variables=x);let C=`${m.type}:${m.operationName}`;i.has(C)||(i.add(C),s.push(m));}if(f==="query"||f==="mutate"){let c=this.analyzeClientDirectCall(u,t,a);if(c){let g=`${c.type}:${c.operationName}`;i.has(g)||(i.add(g),s.push(c));}}}}),this.extractSSRDataFetching(e,t,s,i),t.includes("getStaticProps")){let l="getStaticProps:getStaticProps";i.has(l)||(i.add(l),s.push({type:"getStaticProps",operationName:"getStaticProps"}));}return s}analyzeClientDirectCall(e,t,r){if(!e.arguments?.length)return null;let s=e.arguments[0],i=s?.expression||s;if(i?.type!=="ObjectExpression")return null;for(let n of i.properties||[])if(n.type==="KeyValueProperty"&&n.key?.type==="Identifier"&&n.key.value==="query"){let a=n.value,o=null;if(a?.type==="Identifier"){let l=a.value;o=r.variableOperations.get(l)||r.documentImports.get(l)||d(l);}if(a?.type==="MemberExpression"){let l=a.object?.type==="Identifier"?a.object.value:null,u=a.property?.type==="Identifier"?a.property.value:null;if(l&&u){let f=`${l}.${u}`;o=r.staticPropertyOperations.get(f)||d(u);}}if(o)return {type:v(e.callee)==="mutate"?"useMutation":"useQuery",operationName:o}}return null}extractDocumentImports(e){let t=new Map;for(let r of e.body)if(r.type==="ImportDeclaration"){let s=r.source?.value||"",i=s.includes("__generated__")||s.includes("generated")||s.includes("graphql")||s.includes(".generated");for(let n of r.specifiers||[]){let a=n.type==="ImportSpecifier"||n.type==="ImportDefaultSpecifier"?n.local?.value:null;if(a){if(a.endsWith("Document")||i){let o=a.replace(/Document$/,"");t.set(a,o);}(a.endsWith("Query")||a.endsWith("Mutation"))&&t.set(a,a.replace(/Query$|Mutation$/,""));}}}return t}extractVariableAssignments(e,t){let r=new Map;return this.traverseNode(e,s=>{if(s.type==="VariableDeclarator"&&s.id?.type==="Identifier"){let i=s.id.value,n=s.init;if(!n)return;if(n.type==="Identifier"){let a=n.value;(a.endsWith("Document")||a.endsWith("Query"))&&r.set(i,a);}if(n.type==="CallExpression"){let a=this.getCalleeName(n.callee);if(a==="gql"||a==="graphql"){let o=this.extractOperationNameFromGqlCall(n,t);o&&r.set(i,o);}}if(n.type==="TaggedTemplateExpression"){let a=this.getCalleeName(n.tag);if(a==="gql"||a==="graphql"){let o=n.template;if(o?.quasis?.[0]?.raw){let u=o.quasis[0].raw.match(/(?:query|mutation|subscription)\s+(\w+)/i);u&&r.set(i,u[1]);}}}}}),r}extractOperationNameFromGqlCall(e,t){if(!e.arguments?.length)return null;let r=e.arguments[0],s=r?.expression||r;if(s?.type==="TemplateLiteral"&&s.quasis?.[0]?.raw){let n=s.quasis[0].raw.match(/(?:query|mutation|subscription)\s+(\w+)/i);if(n)return n[1]}if(e.span){let n=t.slice(e.span.start,e.span.end).match(/(?:query|mutation|subscription)\s+(\w+)/i);if(n)return n[1]}return null}analyzeGraphQLHookCall(e,t,r,s){let i=this.getCalleeName(e.callee);if(!i)return null;let n=this.getGraphQLHookPatterns(),a=W.includes(i),o=R(i,n)&&!i.includes("Params"),l=Q(i,n);if(!a&&!o&&!l)return null;let u=q(i,n),f=i.replace(/^use/,"").replace(/Query$|Mutation$/,""),c=this.extractTypeGeneric(e,t);if(c&&(f=c.replace(/Query$|Mutation$|Variables$/,"")),e.arguments&&e.arguments.length>0){let m=e.arguments[0],x=m?.expression||m,C=this.extractOperationFromArgument(x,r,s);C&&(f=C);}let g=this.extractVariablesFromCall(e);return {type:u,operationName:f,variables:g}}extractTypeGeneric(e,t){if(e.typeArguments?.params?.length>0){let r=e.typeArguments.params[0];if(r?.type==="TsTypeReference"&&r.typeName?.type==="Identifier")return r.typeName.value}if(e.callee?.span){let r=e.callee.span.end,i=t.slice(r,r+100).match(/^<(\w+)(?:Query|Mutation|Variables)?[,>]/);if(i)return i[1]}return null}extractOperationFromArgument(e,t,r){if(!e)return null;if(e.type==="Identifier"){let s=e.value;if(["[","{","'",'"',"`"].some(o=>s.startsWith(o)))return null;let i=r.get(s);if(i)return !i.endsWith("Document")&&!i.endsWith("Query")?i:t.get(i)||i.replace(/Document$/,"");let n=t.get(s);if(n)return n;let a=this.codegenMap.get(s);return a?a.operationName:/^(Query|Mutation|QUERY|MUTATION)$/i.test(s)?null:s.replace(/Document$/,"").replace(/Query$|Mutation$/,"")}if(e.type==="MemberExpression"&&e.property?.type==="Identifier")return e.property.value.replace(/Document$/,"").replace(/Query$|Mutation$/,"");if(e.type==="TaggedTemplateExpression"&&e.template?.quasis?.[0]?.raw){let i=e.template.quasis[0].raw.match(/(?:query|mutation|subscription)\s+(\w+)/i);if(i)return i[1]}if(e.type==="CallExpression"){let s=this.getCalleeName(e.callee);if((s==="graphql"||s==="gql")&&e.arguments?.length>0){let i=e.arguments[0],n=i?.expression||i;if(n?.type==="TemplateLiteral"&&n.quasis?.[0]?.raw){let o=n.quasis[0].raw.match(/(?:query|mutation|subscription)\s+(\w+)/i);if(o)return o[1]}}}if(e.type==="TemplateLiteral"&&e.quasis?.[0]?.raw){let i=e.quasis[0].raw.match(/(?:query|mutation|subscription)\s+(\w+)/i);if(i)return i[1]}return null}extractVariablesFromCall(e){let t=[];if(e.arguments&&e.arguments.length>1){let r=e.arguments[1],s=r?.expression||r;if(s?.type==="ObjectExpression"){for(let i of s.properties||[])if(i.type==="KeyValueProperty"&&i.key?.type==="Identifier"&&i.key.value==="variables"&&i.value?.type==="ObjectExpression")for(let n of i.value.properties||[])n.type==="KeyValueProperty"&&n.key?.type==="Identifier"?t.push(n.key.value):n.type==="Identifier"&&t.push(n.value);}}return t}extractSSRDataFetching(e,t,r,s){let i=this.extractImports(e),n=this.extractDocumentImports(e);for(let a of e.body)if(a.type==="ExportDeclaration"){let o=a.declaration;if(o?.type==="VariableDeclaration")for(let l of o.declarations)l.id?.type==="Identifier"&&l.id.value==="getServerSideProps"&&this.extractSSRQueriesFromNode(l,t,i,n,r,s);o?.type==="FunctionDeclaration"&&o.identifier?.value==="getServerSideProps"&&this.extractSSRQueriesFromNode(o,t,i,n,r,s);}}extractSSRQueriesFromNode(e,t,r,s,i,n){M(e,a=>{if(a.type!=="CallExpression")return;let o=v(a.callee);if(o==="query"||o==="mutate"){let l=this.extractQueryFromClientCall(a,t,r,s);if(l){let u=`getServerSideProps:\u2192 ${l}`;n.has(u)||(n.add(u),i.push({type:"getServerSideProps",operationName:`\u2192 ${l}`}));}}});}extractQueryFromClientCall(e,t,r,s){if(!e.arguments?.length)return null;let i=e.arguments[0],n=i?.expression||i;if(n?.type!=="ObjectExpression")return null;for(let a of n.properties||[])if(a.type==="KeyValueProperty"&&a.key?.type==="Identifier"&&a.key.value==="query"){let o=a.value;if(o?.type==="Identifier"){let l=o.value;if(s.has(l))return s.get(l)||null;let u=this.codegenMap.get(l);return u?u.operationName:r.get(l)?d(l):d(l)}if(o?.type==="MemberExpression"){let l=o.object?.type==="Identifier"?o.object.value:null,u=o.property?.type==="Identifier"?o.property.value:null;if(l&&u)return `${l}.${u}`}}return null}extractNavigation(e){let t={visible:true,currentNavItem:null};(e.includes("hideNavigation")||e.includes("noNav"))&&(t.visible=false),(e.includes("miniNav")||e.includes("collapsedNav"))&&(t.mini=true);let r=e.match(/currentNav(?:Item)?[:\s=]+['"`]([^'"`]+)['"`]/);return r&&(t.currentNavItem=r[1]),t}extractLinkedPages(e,t){let r=[];return this.traverseNode(e,s=>{if(s.type==="JSXOpeningElement"&&this.getJsxTagName(s)==="Link"){let n=this.getJsxAttribute(s,"href");if(n&&n.startsWith("/")&&!n.includes("http")){let a=n.split("?")[0].split("#")[0];r.includes(a)||r.push(a);}}}),r}extractSteps(e){let t=[],r=e.matchAll(/(?:step|Step)\s*[:=]\s*['"`]([^'"`]+)['"`]/g),s=0;for(let i of r)t.push({id:s++,name:i[1]});return t}traverseNode(e,t){if(!(!e||typeof e!="object")){t(e);for(let r of Object.keys(e)){let s=e[r];if(Array.isArray(s))for(let i of s)this.traverseNode(i,t);else s&&typeof s=="object"&&this.traverseNode(s,t);}}}getCalleeName(e){if(e.type==="Identifier")return e.value;if(e.type==="MemberExpression"){let t=e.object,r=e.property;if(t.type==="Identifier"&&r.type==="Identifier")return `${t.value}.${r.value}`}return null}getJsxTagName(e){return e.name?.type==="Identifier"?e.name.value:null}getJsxAttribute(e,t){if(!e.attributes)return null;for(let r of e.attributes)if(r.type==="JSXAttribute"&&r.name?.value===t){if(r.value?.type==="StringLiteral")return r.value.value;if(r.value?.type==="JSXExpressionContainer"&&(r.value.expression?.type==="Identifier"||r.value.expression?.type==="StringLiteral"))return r.value.expression.value}return null}};var ue=class extends A{coverage={tsFilesScanned:0,tsParseFailures:0,graphqlParseFailures:0,codegenFilesDetected:0,codegenFilesParsed:0,codegenExportsFound:0};constructor(e){super(e);}getName(){return "GraphQLAnalyzer"}async analyze(){this.log("Starting GraphQL analysis...");let e=[];this.log("[GraphQLAnalyzer] Step 1: Analyzing .graphql files...");let t=await this.analyzeGraphQLFiles();e.push(...t),this.log(`[GraphQLAnalyzer] Step 1 done: ${t.length} from .graphql files`),this.log("[GraphQLAnalyzer] Step 2: Analyzing inline GraphQL...");let r=await this.analyzeInlineGraphQL();e.push(...r),this.log(`[GraphQLAnalyzer] Step 2 done: ${r.length} inline operations`),this.log("[GraphQLAnalyzer] Step 3: Analyzing codegen output...");let s=await this.analyzeCodegenGenerated();e.push(...s),this.log(`[GraphQLAnalyzer] Step 3 done: ${s.length} from codegen`);let i=this.deduplicateOperations(e);return this.log(`[GraphQLAnalyzer] Deduplicated: ${i.length} unique operations`),this.log("[GraphQLAnalyzer] Step 4: Finding operation usage..."),await this.findOperationUsage(i),this.log("[GraphQLAnalyzer] Step 4 done"),this.log(`Found ${i.length} GraphQL operations`),{graphqlOperations:i,coverage:this.coverage}}deduplicateOperations(e){let t=new Map;for(let r of e)if(!t.has(r.name))t.set(r.name,r);else {let s=t.get(r.name);if(s)for(let i of r.usedIn)s.usedIn.includes(i)||s.usedIn.push(i);}return Array.from(t.values())}async analyzeCodegenGenerated(){let e=[],t=await j(["**/__generated__/graphql.ts","**/__generated__/gql.ts","**/generated/graphql.ts","**/generated/gql.ts","**/*.generated.ts","**/*.generated.tsx","**/graphql/generated.ts","**/gql/generated.ts"],{cwd:this.basePath,ignore:["**/node_modules/**","**/.next/**","**/dist/**","**/build/**"],absolute:true});for(let r of t)try{let s=await T.readFile(r,"utf-8"),i=y.relative(this.basePath,r);if(!s.includes("Document")||!s.includes("definitions"))continue;this.coverage.codegenFilesDetected+=1;let n=k(s,i);this.coverage.codegenFilesParsed+=1,this.coverage.codegenExportsFound+=n.length;for(let a of n){let l=a.document?.definitions?.[0];if(!l||l.kind!=="OperationDefinition")continue;let u=(l.variableDefinitions||[]).map(f=>({name:f.variable?.name?.value||"unknown",type:this.extractTypeFromAst(f.type),required:f.type?.kind==="NonNullType"}));e.push({name:a.operationName,type:a.operationType,filePath:i,usedIn:[],variables:u,returnType:this.inferReturnTypeFromAst(l),fragments:this.extractFragmentReferencesFromAst(l),fields:this.extractFieldsFromAst(l.selectionSet),variableNames:[a.documentName]});}n.length>0&&this.log(`Found ${n.length} operations in codegen output: ${i}`);}catch(s){this.warn(`Failed to analyze codegen file ${r}: ${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 r=[];for(let s of e.selections)if(s.kind==="Field"){let i={name:s.name?.value||"unknown"};if(s.arguments?.length>0){let n=s.arguments.map(a=>a.name?.value).join(", ");i.type=`(${n})`;}s.selectionSet&&(i.fields=this.extractFieldsFromAst(s.selectionSet,t+1)),r.push(i);}else if(s.kind==="FragmentSpread")r.push({name:`...${s.name?.value}`,type:"fragment"});else if(s.kind==="InlineFragment"){let i=s.typeCondition?.name?.value||"inline";r.push({name:`... on ${i}`,type:"inline-fragment",fields:this.extractFieldsFromAst(s.selectionSet,t+1)});}return r}extractFragmentReferencesFromAst(e){let t=[],r=s=>{if(s&&(s.kind==="FragmentSpread"&&t.push(s.name?.value),s.selectionSet?.selections))for(let i of s.selectionSet.selections)r(i);};return r(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 j(["**/*.graphql"],{cwd:this.basePath,ignore:["**/node_modules/**","**/.next/**"],absolute:true});return (await S(e,async r=>{let s=await T.readFile(r,"utf-8");try{let i=parse(s);return this.extractOperationsFromDocument(i,y.relative(this.basePath,r))}catch{return this.coverage.graphqlParseFailures+=1,[]}})).flat()}async analyzeInlineGraphQL(){let e=[],t=await j(["**/*.ts","**/*.tsx","**/*.js","**/*.jsx"],{cwd:this.basePath,ignore:["**/node_modules/**","**/.next/**","**/__tests__/**","**/*.test.*","**/*.spec.*","**/__generated__/**"],absolute:true});this.coverage.tsFilesScanned+=t.length;let r=50;for(let s=0;s<t.length;s+=r){let i=t.slice(s,s+r),n=await S(i,async a=>{try{let o=await T.readFile(a,"utf-8");if(!o.includes("gql")&&!o.includes("graphql"))return [];let l=y.relative(this.basePath,a),u=a.endsWith(".tsx")||a.endsWith(".jsx"),f=parseSync(o,{syntax:a.endsWith(".ts")||a.endsWith(".tsx")?"typescript":"ecmascript",tsx:u,jsx:u});return this.analyzeModuleForGraphQL(f,o,l)}catch{return this.coverage.tsParseFailures+=1,[]}},10);e.push(...n.flat());}return e}analyzeModuleForGraphQL(e,t,r){let s=[],i=[];return this.traverseNodeWithContext(e,i,(n,a)=>{if(n.type==="TaggedTemplateExpression"){let o=n,l=this.getTagName(o.tag);if(l==="gql"||l==="graphql"){let u=this.extractTemplateContent(o.template,t);if(u)try{let f=parse(u),c=this.extractOperationsFromDocument(f,r);if(a)for(let g of c)g.variableNames=g.variableNames||[],g.variableNames.push(a),g.variableNames.push(`${g.name}Document`);s.push(...c);}catch{this.coverage.graphqlParseFailures+=1;}}}if(n.type==="CallExpression"){let o=n,l=this.getCalleeName(o.callee);if((l==="gql"||l==="graphql")&&o.arguments.length>0){let u=o.arguments[0].expression,f=this.extractGraphQLFromExpression(u,t);if(f)try{let c=parse(f),g=this.extractOperationsFromDocument(c,r);if(a)for(let m of g)m.variableNames=m.variableNames||[],m.variableNames.push(a),m.variableNames.push(`${m.name}Document`);s.push(...g);}catch{this.coverage.graphqlParseFailures+=1;}}}}),s}traverseNodeWithContext(e,t,r){if(!e||typeof e!="object")return;let s=false;e.type==="VariableDeclarator"&&e.id?.type==="Identifier"&&(t.push(e.id.value),s=true),r(e,t.length>0?t[t.length-1]:null);for(let i of Object.keys(e)){let n=e[i];if(Array.isArray(n))for(let a of n)this.traverseNodeWithContext(a,t,r);else n&&typeof n=="object"&&this.traverseNodeWithContext(n,t,r);}s&&t.pop();}getTagName(e){return e.type==="Identifier"?e.value:null}getCalleeName(e){return e.type==="Identifier"?e.value:null}extractTemplateContent(e,t){if(e.type==="TemplateLiteral"){if(e.quasis.length===1&&e.expressions.length===0)return e.quasis[0].raw;let r=e.span.start,s=e.span.end;return t.slice(r,s).slice(1,-1).replace(/\$\{[^}]*\}/g,"")}return null}extractGraphQLFromExpression(e,t){return e.type==="TemplateLiteral"?this.extractTemplateContent(e,t):e.type==="StringLiteral"?e.value:null}extractOperationsFromDocument(e,t){let r=[];for(let s of e.definitions){let i=this.extractOperation(s,t);i&&r.push(i);}return r}extractOperation(e,t){if(e.kind==="OperationDefinition"){let r=e.name?.value||"anonymous",s=e.operation,i=this.extractVariables(e),n=this.extractFragmentReferences(e),a=this.extractFields(e),o=e.loc?getLocation(e.loc.source,e.loc.start):null;return {name:r,type:s,filePath:t,line:o?.line,column:o?.column,usedIn:[],variables:i,returnType:this.inferReturnType(e),fragments:n,fields:a}}if(e.kind==="FragmentDefinition"){let r=e.loc?getLocation(e.loc.source,e.loc.start):null;return {name:e.name.value,type:"fragment",filePath:t,line:r?.line,column:r?.column,usedIn:[],variables:[],returnType:e.typeCondition.name.value,fragments:this.extractFragmentReferences(e),fields:this.extractFields(e)}}return null}extractFields(e){let t=[],r=(s,i=0)=>{if(!s||!s.selections||i>5)return [];let n=[];for(let a of s.selections)if(a.kind==="Field"){let o={name:a.name.value};if(a.arguments&&a.arguments.length>0){let l=a.arguments.map(u=>u.name.value).join(", ");o.type=`(${l})`;}a.selectionSet&&(o.fields=r(a.selectionSet,i+1)),n.push(o);}else if(a.kind==="FragmentSpread")n.push({name:`...${a.name.value}`,type:"fragment"});else if(a.kind==="InlineFragment"&&a.selectionSet){let o=a.typeCondition?.name?.value||"inline";n.push({name:`... on ${o}`,type:"inline-fragment",fields:r(a.selectionSet,i+1)});}return n};return e.selectionSet?r(e.selectionSet):t}extractVariables(e){let t=[];if(e.variableDefinitions)for(let r of e.variableDefinitions){let s=r.variable.name.value,i=this.typeNodeToString(r.type),n=r.type.kind==="NonNullType";t.push({name:s,type:i,required:n});}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=[],r=s=>{if(s&&(s.kind==="FragmentSpread"&&t.push(s.name.value),s.selectionSet))for(let i of s.selectionSet.selections)r(i);};return r(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=this.getGraphQLHookPatterns(),r=await j(["**/*.ts","**/*.tsx"],{cwd:this.basePath,ignore:["**/node_modules/**","**/.next/**","**/__generated__/**","**/dist/**","**/build/**"],absolute:true}),s=new Map,i=new Map,n=new Map,a=new Map;for(let c of e)if(s.set(c.name,c),i.set(`${c.name}Document`,c),a.set(`${c.name}Query`,c),a.set(`${c.name}Mutation`,c),a.set(`${c.name}Subscription`,c),a.set(`${c.name}QueryVariables`,c),a.set(`${c.name}MutationVariables`,c),c.variableNames)for(let g of c.variableNames)n.set(g,c);let o=new Set;for(let c of e)if(o.add(c.name),o.add(`${c.name}Document`),o.add(`${c.name}Query`),o.add(`${c.name}Mutation`),o.add(`${c.name}Subscription`),c.variableNames)for(let g of c.variableNames)o.add(g);let l=null,u=Array.from(o);if(u.length>0&&u.length<2e3){let c=u.sort((g,m)=>m.length-g.length).map(g=>g.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"));l=new RegExp(`\\b(${c.join("|")})\\b`,"g");}let f=50;for(let c=0;c<r.length;c+=f){let g=r.slice(c,c+f);await Promise.all(g.map(async m=>{try{let x=await T.readFile(m,"utf-8"),C=y.relative(this.basePath,m);if(!H(x))return;if(l){let I=new Set,Y;for(;(Y=l.exec(x))!==null;)I.add(Y[1]);l.lastIndex=0;for(let z of I){let L=i.get(z)||n.get(z)||s.get(z);L&&C!==L.filePath&&(L.usedIn.includes(C)||L.usedIn.push(C));}}await this.findUsageWithAST(x,m,C,s,a,n,t);}catch{}}));}}async findUsageWithAST(e,t,r,s,i,n,a){try{let o=t.endsWith(".tsx")||t.endsWith(".jsx"),l=parseSync(e,{syntax:t.endsWith(".ts")||t.endsWith(".tsx")?"typescript":"ecmascript",tsx:o,jsx:o,comments:!1});this.traverseNodeForUsage(l,e,u=>{if(u.type==="CallExpression"){let f=this.getCalleeNameForUsage(u.callee);if(f&&$(f,a)){let c=this.extractTypeGenericFromCall(u,e);if(c){let m=i.get(c)||s.get(c.replace(/Query$|Mutation$|Variables$/,""));m&&r!==m.filePath&&(m.usedIn.includes(r)||m.usedIn.push(r));}let g=this.extractFirstArgName(u);if(g){let m=g.replace(/Document$/,""),x=n.get(g)||n.get(m)||s.get(m)||i.get(g);x&&r!==x.filePath&&(x.usedIn.includes(r)||x.usedIn.push(r));}}}});}catch{}}traverseNodeForUsage(e,t,r){if(!(!e||typeof e!="object")){r(e);for(let s of Object.keys(e)){let i=e[s];if(Array.isArray(i))for(let n of i)this.traverseNodeForUsage(n,t,r);else i&&typeof i=="object"&&this.traverseNodeForUsage(i,t,r);}}}getCalleeNameForUsage(e){return e?e.type==="Identifier"?e.value:e.type==="MemberExpression"&&e.property?.type==="Identifier"?e.property.value:null:null}extractTypeGenericFromCall(e,t){if(e.typeArguments?.params?.length>0){let r=e.typeArguments.params[0];if(r?.type==="TsTypeReference"&&r.typeName?.type==="Identifier")return r.typeName.value}if(e.callee?.span){let r=e.callee.span.end,i=t.slice(r,r+150).match(/^<\s*(\w+)(?:Query|Mutation|Variables|Subscription)?(?:\s*,|\s*>)/);if(i)return i[1]}return null}extractFirstArgName(e){if(e.arguments?.length>0){let t=e.arguments[0].expression;if(t?.type==="Identifier")return t.value;if(t?.type==="MemberExpression"&&t.property?.type==="Identifier")return t.property.value}return null}};var fe=class extends A{componentCache=new Map;coverage={tsFilesScanned:0,tsParseFailures:0,graphqlParseFailures:0,codegenFilesDetected:0,codegenFilesParsed:0,codegenExportsFound:0};constructor(e){super(e);}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,coverage:this.coverage}}async analyzeComponents(){let e=[],t=[this.getSetting("featuresDir",""),this.getSetting("componentsDir",""),this.getSetting("pagesDir","")].filter(Boolean),r=["src/features","src/components","src/common/components","src/common","src/pages","src/app","src/modules","src/views","src/screens","components","pages","app"],i=[...new Set([...t,...r])].flatMap(o=>[`${o}/**/*.tsx`,`${o}/**/*.ts`]),n=await j(i,{cwd:this.basePath,ignore:["**/*.test.*","**/*.spec.*","**/*.stories.*","**/node_modules/**","**/__generated__/**"],absolute:true,onlyFiles:true,unique:true});this.log(`[DataFlowAnalyzer] Found ${n.length} component files to analyze`),this.coverage.tsFilesScanned+=n.length;let a=50;for(let o=0;o<n.length;o+=a){let l=n.slice(o,o+a),u=await Promise.all(l.map(async f=>{try{let c=await T.readFile(f,"utf-8");return {filePath:f,content:c}}catch{return null}}));for(let f of u)if(f)try{let c=parseSync(f.content,{syntax:"typescript",tsx:!0,comments:!1}),g=y.relative(this.basePath,f.filePath),m=this.analyzeComponentFile(c,g,f.content);e.push(...m);}catch{this.coverage.tsParseFailures+=1;}}return this.log(`[DataFlowAnalyzer] Extracted ${e.length} components`),this.buildDependencyGraph(e),e}analyzeComponentFile(e,t,r){let s=[],i=this.extractImports(e);for(let n of e.body){if(n.type==="ExportDeclaration"&&n.declaration?.type==="FunctionDeclaration"){let a=n.declaration.identifier?.value;if(a&&this.isComponentName(a)){let o=this.extractComponentInfo(a,t,r,i);s.push(o),this.componentCache.set(a,o);}}if(n.type==="FunctionDeclaration"){let a=n.identifier?.value;if(a&&this.isComponentName(a)){let o=this.extractComponentInfo(a,t,r,i);s.push(o),this.componentCache.set(a,o);}}if(n.type==="ExportDefaultDeclaration"&&n.decl?.type==="FunctionExpression"){let a=n.decl.identifier?.value;if(a&&this.isComponentName(a)){let o=this.extractComponentInfo(a,t,r,i);s.push(o),this.componentCache.set(a,o);}}if(n.type==="VariableDeclaration"){for(let a of n.declarations)if(a.id?.type==="Identifier"){let o=a.id.value;if(o&&(this.isComponentName(o)||o.startsWith("use"))&&a.init&&(a.init.type==="ArrowFunctionExpression"||a.init.type==="FunctionExpression")){let l=this.extractComponentInfo(o,t,r,i);s.push(l),this.componentCache.set(o,l);}}}if(n.type==="ExportDeclaration"&&n.declaration?.type==="VariableDeclaration"){for(let a of n.declaration.declarations)if(a.id?.type==="Identifier"){let o=a.id.value;if(o&&(this.isComponentName(o)||o.startsWith("use"))&&a.init&&(a.init.type==="ArrowFunctionExpression"||a.init.type==="FunctionExpression")){let l=this.extractComponentInfo(o,t,r,i);s.push(l),this.componentCache.set(o,l);}}}}return s}extractImports(e){let t=new Map,r=this.getListSetting("aliasPrefixes",["@/","~/","#/"]);for(let s of e.body)if(s.type==="ImportDeclaration"){let i=s.source?.value||"",n=r.some(a=>i.startsWith(a));if(i.startsWith(".")||n)for(let a of s.specifiers||[])a.type==="ImportSpecifier"&&a.local?.value&&t.set(a.local.value,i),a.type==="ImportDefaultSpecifier"&&a.local?.value&&t.set(a.local.value,i);}return t}isComponentName(e){return /^[A-Z][a-zA-Z0-9]*$/.test(e)}extractComponentInfo(e,t,r,s){let i="presentational";["/pages/","/app/","/routes/","/views/","/screens/"].some(f=>t.includes(f))?i="page":e.includes("Container")||e.includes("Provider")?i="container":e.includes("Layout")||e.includes("Shell")||e.includes("Wrapper")||e.includes("Frame")||e.includes("Scaffold")||t.includes("/layouts/")||t.includes("/layout/")?i="layout":e.startsWith("use")&&(i="hook");let a=this.extractHooksUsed(r),o=Array.from(s.keys()).filter(f=>this.isComponentName(f)||f.startsWith("use")),l=[];for(let[f,c]of s)l.push({name:f,path:c});let u=this.extractStateManagement(r);return {name:e,filePath:t,type:i,props:[],dependencies:o,dependents:[],hooks:a,stateManagement:u,imports:l}}extractHooksUsed(e){let t=[],r=new Set;if(!e.includes("use"))return t;try{let s=parseSync(e,{syntax:"typescript",tsx:!0,comments:!1}),i=this.extractDocumentImportsFromAst(s),n=this.extractVariableOperationMap(s,e);this.traverseForHooks(s,e,i,n,t,r);}catch{this.extractHooksWithRegex(e,t,r);}return t}extractDocumentImportsFromAst(e){let t=new Map;for(let r of e.body)if(r.type==="ImportDeclaration"){let s=r.source?.value||"",i=s.includes("__generated__")||s.includes("generated")||s.includes("graphql")||s.includes(".generated");for(let n of r.specifiers||[]){let a;(n.type==="ImportSpecifier"||n.type==="ImportDefaultSpecifier")&&(a=n.local?.value),a&&((a.endsWith("Document")||i)&&t.set(a,a.replace(/Document$/,"")),(a.endsWith("Query")||a.endsWith("Mutation"))&&t.set(a,a.replace(/Query$|Mutation$/,"")));}}return t}extractVariableOperationMap(e,t){let r=new Map,s=n=>{if(n.type!=="VariableDeclarator"||n.id?.type!=="Identifier")return;let a=n.id.value,o=n.init;if(o){if(o.type==="CallExpression"){let l=this.getCalleeNameFromNode(o.callee);if(l==="gql"||l==="graphql"){let u=this.extractOperationNameFromGqlCall(o,t);u&&r.set(a,u);}}if(o.type==="TaggedTemplateExpression"){let l=this.getCalleeNameFromNode(o.tag);if((l==="gql"||l==="graphql")&&o.template?.quasis?.[0]?.raw){let f=o.template.quasis[0].raw.match(/(?:query|mutation|subscription)\s+(\w+)/i);f&&r.set(a,f[1]);}}}},i=n=>{if(!(!n||typeof n!="object")){s(n);for(let a of Object.keys(n)){let o=n[a];if(Array.isArray(o))for(let l of o)i(l);else o&&typeof o=="object"&&i(o);}}};return i(e),r}extractOperationNameFromGqlCall(e,t){if(!e.arguments?.length)return null;let r=e.arguments[0],s=r?.expression||r;if(s?.type==="TemplateLiteral"&&s.quasis?.[0]?.raw){let n=s.quasis[0].raw.match(/(?:query|mutation|subscription)\s+(\w+)/i);if(n)return n[1]}if(e.span){let n=t.slice(e.span.start,e.span.end).match(/(?:query|mutation|subscription)\s+(\w+)/i);if(n)return n[1]}return null}traverseForHooks(e,t,r,s,i,n){if(!(!e||typeof e!="object")){e.type==="CallExpression"&&this.analyzeHookCall(e,t,r,s,i,n);for(let a of Object.keys(e)){let o=e[a];if(Array.isArray(o))for(let l of o)this.traverseForHooks(l,t,r,s,i,n);else o&&typeof o=="object"&&this.traverseForHooks(o,t,r,s,i,n);}}}analyzeHookCall(e,t,r,s,i,n){let a=this.getCalleeNameFromNode(e.callee);if(!a||!a.startsWith("use"))return;let o=R(a),l=Q(a),u=ne(a);if((o||l||u)&&this.hasGraphQLArgument(e,t,r,s)){let c=this.extractOperationNameFromCall(e,t,r,s),g=l?"Mutation":u?"Subscription":"Query",m=c?`${g}: ${c}`:`${g}: unknown`;n.has(m)||(n.add(m),i.push(m));return}if(a==="useContext"){let f=this.extractContextName(e);if(f){let c=`\u{1F504} Context: ${f}`;n.has(c)||(n.add(c),i.push(c));}return}n.has(a)||(n.add(a),i.push(a));}hasGraphQLArgument(e,t,r,s){if(!e.arguments?.length)return false;let i=e.arguments[0],n=i?.expression||i;if(!n)return false;if(n.type==="Identifier"){let a=n.value;if(r.has(a)||s.has(a)||a.endsWith("Document")||/[A-Z][a-z]*Query$/.test(a)||/[A-Z][a-z]*Mutation$/.test(a)||/^[A-Z][A-Z0-9_]*_QUERY$/.test(a)||/^[A-Z][A-Z0-9_]*_MUTATION$/.test(a))return true}if(n.type==="TaggedTemplateExpression"){let a=this.getCalleeNameFromNode(n.tag);if(a==="gql"||a==="graphql")return true}if(n.type==="CallExpression"){let a=this.getCalleeNameFromNode(n.callee);if(a==="gql"||a==="graphql")return true}if(n.type==="TemplateLiteral"&&n.quasis?.[0]?.raw){let a=n.quasis[0].raw;if(/(?:query|mutation|subscription)\s+\w+/i.test(a))return true}if(n.type==="MemberExpression"){let a=n.property?.value;if(a&&/Query$|Mutation$|Document$/.test(a))return true}if(e.span){let a=t.slice(e.span.start,Math.min(e.span.end,e.span.start+500));if(a.includes("Document")||/\bgql\s*[`(]/.test(a)||/\bgraphql\s*[`(]/.test(a)||/query\s+\w+\s*[({]/.test(a)||/mutation\s+\w+\s*[({]/.test(a))return true}return false}getCalleeNameFromNode(e){return e?e.type==="Identifier"?e.value:e.type==="MemberExpression"&&e.property?.type==="Identifier"?e.property.value:null:null}extractOperationNameFromCall(e,t,r,s){if(e.typeArguments?.params?.length>0){let i=e.typeArguments.params[0];if(i?.type==="TsTypeReference"&&i.typeName?.type==="Identifier"){let n=i.typeName.value;return d(n)}}if(e.callee?.span&&e.span){let i=e.callee.span.end,n=Math.min(i+150,e.span.end),o=t.slice(i,n).match(/^<\s*(\w+)(?:Query|Mutation|Variables|Subscription)?[\s,>]/);if(o)return d(o[1])}if(e.arguments?.length>0){let i=e.arguments[0],n=i?.expression||i;if(!n)return null;if(n.type==="Identifier"){let a=n.value,o=s.get(a);if(o)return o;let l=r.get(a);return l||(/^(Query|Mutation|QUERY|MUTATION)$/i.test(a)?null:d(a))}if(n.type==="MemberExpression"&&n.property?.type==="Identifier")return d(n.property.value);if(n.type==="TaggedTemplateExpression"&&n.template?.quasis?.[0]?.raw){let o=n.template.quasis[0].raw.match(/(?:query|mutation|subscription)\s+(\w+)/i);if(o)return o[1]}if(n.type==="CallExpression"){let a=this.getCalleeNameFromNode(n.callee);if((a==="graphql"||a==="gql")&&n.arguments?.length>0){let o=n.arguments[0],l=o?.expression||o;if(l?.type==="TemplateLiteral"&&l.quasis?.[0]?.raw){let f=l.quasis[0].raw.match(/(?:query|mutation|subscription)\s+(\w+)/i);if(f)return f[1]}}}if(n.type==="TemplateLiteral"&&n.quasis?.[0]?.raw){let o=n.quasis[0].raw.match(/(?:query|mutation|subscription)\s+(\w+)/i);if(o)return o[1]}}if(e.span){let i=t.slice(e.span.start,e.span.end),n=i.match(/\b([A-Z][a-zA-Z0-9]*Document)\b/);if(n)return d(n[1]);let a=i.match(/(?:query|mutation|subscription)\s+(\w+)/i);if(a)return a[1]}return null}extractContextName(e){if(e.arguments?.length>0){let t=e.arguments[0].expression;if(t?.type==="Identifier")return t.value.replace(/Context$/,"")}return null}extractHooksWithRegex(e,t,r){let s=/\b(useQuery|useMutation|useLazyQuery|useSuspenseQuery|useBackgroundQuery|useSubscription)(?:<[^>]*>)?\s*\(\s*([A-Z_][A-Za-z0-9_]*)?/gs,i;for(;(i=s.exec(e))!==null;){let o=i[1],l=i[2];if(l&&/^(Query|Mutation|QUERY|MUTATION)$/i.test(l))continue;let u=l?d(l):"unknown",c=`${o.includes("Mutation")?"Mutation":o.includes("Subscription")?"Subscription":"Query"}: ${u}`;r.has(c)||(r.add(c),t.push(c));}let n=/\b(use[A-Z][a-zA-Z0-9]*)\s*\(/g,a;for(;(a=n.exec(e))!==null;){let o=a[1];if(!["useQuery","useMutation","useLazyQuery","useSuspenseQuery","useBackgroundQuery","useSubscription"].includes(o))if(o==="useContext"){let l=e.slice(a.index).match(/useContext\s*\(\s*([A-Z][A-Za-z0-9]*)/);if(l){let f=`\u{1F504} Context: ${l[1].replace(/Context$/,"")}`;r.has(f)||(r.add(f),t.push(f));}}else r.has(o)||(r.add(o),t.push(o));}}extractStateManagement(e){let t=[];return e.includes("useState")&&t.push("useState"),e.includes("useReducer")&&t.push("useReducer"),e.includes("useContext")&&t.push("useContext"),e.includes("useQuery")&&t.push("Apollo Query"),e.includes("useMutation")&&t.push("Apollo Mutation"),e.includes("useRecoil")&&t.push("Recoil"),(e.includes("useSelector")||e.includes("useDispatch"))&&t.push("Redux"),t}buildDependencyGraph(e){let t=new Map;for(let r of e)t.set(r.name,r);for(let r of e)for(let s of r.dependencies){let i=t.get(s);i&&!i.dependents.includes(r.name)&&i.dependents.push(r.name);}}async analyzeDataFlows(e){let t=[],r=1,s=this.analyzeContextFlows(e);t.push(...s.map(a=>({...a,id:`flow-${r++}`})));let i=this.analyzeApolloFlows(e);t.push(...i.map(a=>({...a,id:`flow-${r++}`})));let n=this.analyzePropDrilling(e);return t.push(...n.map(a=>({...a,id:`flow-${r++}`}))),t}analyzeContextFlows(e){let t=[],r=e.filter(i=>i.name.includes("Provider")||i.name.includes("Context")),s=e.filter(i=>i.hooks.some(n=>n.includes("Context")));for(let i of r){let n=i.name.replace("Provider","").replace("Context","");for(let a of s){let o=a.hooks.find(l=>l.includes("Context")&&l.includes(n));(o||a.hooks.some(l=>l.includes(n)))&&t.push({name:`\u{1F504} ${n} Context`,description:`Data flows from ${i.name} to ${a.name} via Context`,source:{type:"context",name:i.name},target:{type:"component",name:a.name},via:[],operations:[o||`useContext(${n})`]});}}return t}analyzeApolloFlows(e){let t=[];for(let r of e){let s=r.hooks.filter(n=>n.includes("Query:")||n==="useQuery"||n==="useLazyQuery");for(let n of s){let a=n.includes(":")?n.split(":")[1].trim():r.name;t.push({name:`Query: ${a}`,description:`${r.name} fetches ${a} via Apollo`,source:{type:"api",name:`GraphQL: ${a}`},target:{type:"component",name:r.name},via:[{type:"cache",name:"Apollo Cache"}],operations:[n]});}let i=r.hooks.filter(n=>n.includes("Mutation:")||n==="useMutation");for(let n of i){let a=n.includes(":")?n.split(":")[1].trim():r.name;t.push({name:`Mutation: ${a}`,description:`${r.name} mutates ${a} via Apollo`,source:{type:"component",name:r.name},target:{type:"api",name:`GraphQL: ${a}`},via:[],operations:[n]});}}return t}analyzePropDrilling(e){let t=[];for(let r of e)r.props.length>5&&r.dependents.length>0&&t.push({name:`Prop Drilling through ${r.name}`,description:`${r.name} passes ${r.props.length} props to children`,source:{type:"component",name:r.name},target:{type:"component",name:r.dependents[0]},via:[],operations:["props"]});return t}};var he=class p extends A{apiCallCounter=0;constructor(e){super(e);}getName(){return "RestApiAnalyzer"}async analyze(){this.log("Starting REST API analysis...");let e=await j(["**/*.ts","**/*.tsx","**/*.js","**/*.jsx"],{cwd:this.basePath,ignore:["**/node_modules/**","**/.next/**","**/__tests__/**","**/*.test.*","**/*.spec.*","**/*.stories.*","**/__generated__/**","**/dist/**","**/build/**"],absolute:true}),t=50,r=[];for(let s=0;s<e.length;s+=t){let i=e.slice(s,s+t),n=await S(i,async a=>{try{let o=await T.readFile(a,"utf-8"),l=y.relative(this.basePath,a),u=a.endsWith(".tsx")||a.endsWith(".jsx"),f=parseSync(o,{syntax:a.endsWith(".ts")||a.endsWith(".tsx")?"typescript":"ecmascript",tsx:u,jsx:u});return this.analyzeModule(f,o,l)}catch{return []}},10);r.push(...n.flat());}return this.log(`Found ${r.length} REST API calls`),{apiCalls:r}}analyzeModule(e,t,r){let s=[],i=t.split(`
|
|
2
|
+
`);return this.traverseNode(e,n=>{if(n.type==="CallExpression"){let a=n,o=this.analyzeCallExpression(a,r,i);o&&s.push(o);}}),s}traverseNode(e,t){if(!(!e||typeof e!="object")){t(e);for(let r of Object.keys(e)){let s=e[r];if(Array.isArray(s))for(let i of s)this.traverseNode(i,t);else s&&typeof s=="object"&&this.traverseNode(s,t);}}}analyzeCallExpression(e,t,r){let s=e.callee;if(s.type==="Super"||s.type==="Import")return null;let i=this.getCalleeName(s);if(!i)return null;if(i==="fetch"||i==="window.fetch")return this.extractFetchCall(e,t,r);let n=i.match(/^axios\.(get|post|put|delete|patch)$/i);return n?this.extractAxiosMethodCall(e,t,r,n[1].toUpperCase()):i==="axios"?this.extractAxiosDirectCall(e,t,r):i==="useSWR"||i==="useSWRImmutable"?this.extractSwrCall(e,t,r):null}getCalleeName(e){if(e.type==="Identifier")return e.value;if(e.type==="MemberExpression"){let t=e.object,r=e.property;if(t.type==="Identifier"&&r.type==="Identifier")return `${t.value}.${r.value}`}return null}extractFetchCall(e,t,r){if(e.arguments.length===0)return null;let s=e.arguments[0],i=this.extractUrlFromExpression(s.expression);if(!i.url||!i.isPlaceholder&&!this.isApiUrl(i.url))return null;let n="GET",a=false;if(e.arguments.length>1){let l=e.arguments[1].expression;if(l.type==="ObjectExpression")for(let u of l.properties)u.type==="KeyValueProperty"&&u.key.type==="Identifier"&&(u.key.value==="method"&&u.value.type==="StringLiteral"&&(n=this.normalizeMethod(u.value.value)),(u.key.value==="credentials"||u.key.value==="headers")&&(a=true));}let o=this.getLineNumber(e.span.start,r);return {id:`api-${++this.apiCallCounter}`,method:n,url:i.url,callType:"fetch",filePath:t,line:o,containingFunction:"unknown",usedIn:[],requiresAuth:a,category:this.categorizeApi(i.url)}}extractAxiosMethodCall(e,t,r,s){if(e.arguments.length===0)return null;let i=e.arguments[0],n=this.extractUrlFromExpression(i.expression);if(!n.url)return null;let a=this.getLineNumber(e.span.start,r);return {id:`api-${++this.apiCallCounter}`,method:this.normalizeMethod(s),url:n.url,callType:"axios",filePath:t,line:a,containingFunction:"unknown",usedIn:[],requiresAuth:false,category:this.categorizeApi(n.url)}}extractAxiosDirectCall(e,t,r){if(e.arguments.length===0)return null;let s=e.arguments[0].expression;if(s.type!=="ObjectExpression")return null;let i=null,n="GET";for(let o of s.properties)o.type==="KeyValueProperty"&&o.key.type==="Identifier"&&(o.key.value==="url"&&o.value.type==="StringLiteral"&&(i=o.value.value),o.key.value==="method"&&o.value.type==="StringLiteral"&&(n=this.normalizeMethod(o.value.value)));if(!i)return null;let a=this.getLineNumber(e.span.start,r);return {id:`api-${++this.apiCallCounter}`,method:n,url:i,callType:"axios",filePath:t,line:a,containingFunction:"unknown",usedIn:[],requiresAuth:false,category:this.categorizeApi(i)}}extractSwrCall(e,t,r){if(e.arguments.length===0)return null;let s=e.arguments[0].expression,i=this.extractUrlFromExpression(s);if(!i.url)return null;let n=this.getLineNumber(e.span.start,r);return {id:`api-${++this.apiCallCounter}`,method:"GET",url:i.url,callType:"useSWR",filePath:t,line:n,containingFunction:"unknown",usedIn:[],requiresAuth:false,category:this.categorizeApi(i.url)}}extractUrlFromExpression(e){if(e.type==="StringLiteral")return {url:e.value,isPlaceholder:false};if(e.type==="TemplateLiteral")return e.quasis.length===1&&e.expressions.length===0?{url:e.quasis[0].raw,isPlaceholder:false}:{url:e.quasis.map(s=>s.raw).join(":param"),isPlaceholder:true};if(e.type==="Identifier")return {url:`[${e.value}]`,isPlaceholder:true};if(e.type==="MemberExpression"){let t=e.object.type==="Identifier"?e.object.value:"?",r=e.property.type==="Identifier"?e.property.value:"?";return {url:`[${t}.${r}]`,isPlaceholder:true}}if(e.type==="ConditionalExpression"){let t=this.extractUrlFromExpression(e.consequent);return t.url?t:this.extractUrlFromExpression(e.alternate)}return {url:null,isPlaceholder:false}}getLineNumber(e,t){let r=0;for(let s=0;s<t.length;s++)if(r+=t[s].length+1,r>e)return s+1;return t.length}static STATIC_FILE_EXTENSIONS=/\.(css|js|mjs|cjs|ts|tsx|jsx|png|jpg|jpeg|gif|webp|svg|ico|woff|woff2|ttf|eot|otf|mp3|mp4|webm|ogg|wav|pdf|doc|docx|xls|xlsx|ppt|pptx|zip|tar|gz|rar|html|htm|xml|txt|md|map|wasm)$/i;static NON_API_SCHEMES=/^(data:|blob:|javascript:|mailto:|tel:|file:)/;isApiUrl(e){return p.NON_API_SCHEMES.test(e)||p.STATIC_FILE_EXTENSIONS.test(e)||!e.trim()?false:!!(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://")||e.startsWith("[")||e.includes("/api/")||e.includes("/v1/")||e.includes("/v2/")||e.includes("/graphql"))}static SERVICE_PATTERNS=[{pattern:/amazonaws\.com|\.s3\./i,name:"AWS"},{pattern:/googleapis\.com|google\.com\/api/i,name:"Google API"},{pattern:/graph\.facebook\.com|facebook\.com\/v\d+/i,name:"Facebook"},{pattern:/api\.twitter\.com|twitter\.com\/\d+/i,name:"Twitter/X"},{pattern:/api\.github\.com|github\.com\/api/i,name:"GitHub API"},{pattern:/stripe\.com/i,name:"Stripe"},{pattern:/paypal\.com/i,name:"PayPal"},{pattern:/slack\.com/i,name:"Slack"},{pattern:/discord\.com|discordapp\.com/i,name:"Discord"},{pattern:/twilio\.com/i,name:"Twilio"},{pattern:/sendgrid\.(com|net)/i,name:"SendGrid"},{pattern:/mailchimp\.com/i,name:"Mailchimp"},{pattern:/hubspot\.com|hsforms\.com/i,name:"HubSpot"},{pattern:/salesforce\.com/i,name:"Salesforce"},{pattern:/zendesk\.com/i,name:"Zendesk"},{pattern:/intercom\.io/i,name:"Intercom"},{pattern:/firebase(io)?\.com|firestore\.googleapis/i,name:"Firebase"},{pattern:/supabase\.(co|com|io)/i,name:"Supabase"},{pattern:/auth0\.com/i,name:"Auth0"},{pattern:/okta\.com/i,name:"Okta"},{pattern:/clerk\.(dev|com)/i,name:"Clerk"},{pattern:/cloudflare\.com|workers\.dev/i,name:"Cloudflare"},{pattern:/vercel\.com|vercel\.app/i,name:"Vercel"},{pattern:/netlify\.com|netlify\.app/i,name:"Netlify"},{pattern:/heroku\.com|herokuapp\.com/i,name:"Heroku"},{pattern:/railway\.app/i,name:"Railway"},{pattern:/render\.com/i,name:"Render"},{pattern:/digitalocean\.com/i,name:"DigitalOcean"},{pattern:/algolia\.(com|net|io)/i,name:"Algolia"},{pattern:/elastic\.co|elasticsearch/i,name:"Elasticsearch"},{pattern:/mongodb\.com|mongodb\.net/i,name:"MongoDB"},{pattern:/planetscale\.com/i,name:"PlanetScale"},{pattern:/sentry\.io/i,name:"Sentry"},{pattern:/datadog\.com/i,name:"Datadog"},{pattern:/segment\.(com|io)/i,name:"Segment"},{pattern:/mixpanel\.com/i,name:"Mixpanel"},{pattern:/amplitude\.com/i,name:"Amplitude"},{pattern:/openai\.com/i,name:"OpenAI"},{pattern:/anthropic\.com/i,name:"Anthropic"},{pattern:/cohere\.(ai|com)/i,name:"Cohere"}];categorizeApi(e){if(e.startsWith("["))return "Dynamic URL";if(e.startsWith("/"))return e.startsWith("/api/")?"Internal API":e.includes("/graphql")?"GraphQL":"Internal Route";for(let{pattern:t,name:r}of p.SERVICE_PATTERNS)if(t.test(e))return r;try{let s=new URL(e).hostname.replace(/^(api\.|www\.)/,"").split(".");if(s.length>=2){let i=s[s.length-2];return i.charAt(0).toUpperCase()+i.slice(1)+" API"}}catch{}return "External API"}normalizeMethod(e){let t=e.toUpperCase();return ["GET","POST","PUT","DELETE","PATCH"].includes(t)?t:"unknown"}};
|
|
3
|
+
export{ue as A,fe as B,he as C,A as a,O as b,ee as c,te as d,ve as e,W as f,X as g,be as h,R as i,Q as j,ne as k,$ as l,q as m,H as n,d as o,Ae as p,v as q,M as r,V as s,U as t,P as u,re as v,Z as w,je as x,Ge as y,oe as z};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {b as b$2,a as a$2}from'./chunk-DSYVU23K.js';import {a as a$3}from'./chunk-VV3A3UE3.js';import {C,B,A as A$1,z,b as b$1}from'./chunk-O2SKKQVN.js';import {a,b}from'./chunk-QBSB6BIU.js';import {a as a$1}from'./chunk-JBPSEUZS.js';import {k}from'./chunk-H7VVRHQZ.js';import {simpleGit}from'simple-git';import*as A from'fs/promises';import*as R from'path';import {parseSync}from'@swc/core';import he from'express';import {Server}from'socket.io';import*as ye from'http';import {marked}from'marked';import*as ue from'net';var W=class{config;mermaidGenerator;markdownGenerator;constructor(o){this.config=o,this.mermaidGenerator=new a,this.markdownGenerator=new b;}async generate(){let o=[];for(let k of this.config.repositories)try{let x=await this.analyzeRepository(k);o.push(x);}catch(x){console.error(`\u274C ${k.name}: ${x.message}`);}let r=this.analyzeCrossRepo(o),e=o.map(k=>k.analysis),a=this.extractCrossRepoLinks(e),s=this.mermaidGenerator.generateAll(e,a),i={generatedAt:new Date().toISOString(),repositories:o,crossRepoAnalysis:r,diagrams:s};return await this.writeDocumentation(i),i}async analyzeRepository(o){let{version:r,commitHash:e}=await this.getRepoInfo(o),a=o.analyzers.map(b=>this.createAnalyzer(b,o)).filter(b=>b!==null),s=Date.now(),i=await Promise.all(a.map(b=>b.analyze())),k=((Date.now()-s)/1e3).toFixed(1);console.log(` Analyzed ${o.displayName} in ${k}s`);let x=this.mergeAnalysisResults(i,o.name,r,e);await this.enrichPagesWithHookGraphQL(x,o.path);let T={totalPages:x.pages.length,totalComponents:x.components.length,totalGraphQLOperations:x.graphqlOperations.length,totalDataFlows:x.dataFlows.length,authRequiredPages:x.pages.filter(b=>b.authentication.required).length,publicPages:x.pages.filter(b=>!b.authentication.required).length};return {name:o.name,displayName:o.displayName,version:r,commitHash:e,analysis:x,summary:T}}async getRepoInfo(o){try{let a=(await simpleGit(o.path).log({n:1})).latest?.hash||"unknown",s="unknown";try{let i=R.join(o.path,"package.json");s=JSON.parse(await A.readFile(i,"utf-8")).version||"unknown";}catch{}return {version:s,commitHash:a}}catch{return {version:"unknown",commitHash:"unknown"}}}createAnalyzer(o,r){switch(o){case "pages":if(r.type==="nextjs"||r.type==="rails"||r.type==="generic")return new z(r);break;case "graphql":return new A$1(r);case "dataflow":case "components":return new B(r);case "rest-api":case "api":return new C(r)}return null}mergeAnalysisResults(o,r,e,a){let s={repository:r,timestamp:new Date().toISOString(),version:e,commitHash:a,coverage:{tsFilesScanned:0,tsParseFailures:0,graphqlParseFailures:0,codegenFilesDetected:0,codegenFilesParsed:0,codegenExportsFound:0},pages:[],graphqlOperations:[],apiCalls:[],components:[],dataFlows:[],apiEndpoints:[],models:[],crossRepoLinks:[]};for(let i of o)i.coverage&&s.coverage&&(s.coverage.tsFilesScanned+=i.coverage.tsFilesScanned||0,s.coverage.tsParseFailures+=i.coverage.tsParseFailures||0,s.coverage.graphqlParseFailures+=i.coverage.graphqlParseFailures||0,s.coverage.codegenFilesDetected+=i.coverage.codegenFilesDetected||0,s.coverage.codegenFilesParsed+=i.coverage.codegenFilesParsed||0,s.coverage.codegenExportsFound+=i.coverage.codegenExportsFound||0),i.pages&&s.pages.push(...i.pages),i.graphqlOperations&&s.graphqlOperations.push(...i.graphqlOperations),i.apiCalls&&s.apiCalls.push(...i.apiCalls),i.components&&s.components.push(...i.components),i.dataFlows&&s.dataFlows.push(...i.dataFlows),i.apiEndpoints&&s.apiEndpoints.push(...i.apiEndpoints),i.models&&s.models.push(...i.models),i.crossRepoLinks&&s.crossRepoLinks.push(...i.crossRepoLinks);return s}analyzeCrossRepo(o){let r=[],e=[],a=[],s=[],i=new Map;for(let T of o)for(let b of T.analysis.graphqlOperations){let $=i.get(b.name)||[];$.push(T.name),i.set(b.name,$);}for(let[T,b]of i)b.length>1&&r.push(T);let k=o.filter(T=>T.analysis.pages.length>0),x=o.filter(T=>T.analysis.apiEndpoints.length>0);for(let T of k)for(let b of x)for(let $ of b.analysis.apiEndpoints)e.push({frontend:T.name,backend:b.name,endpoint:$.path,operations:T.analysis.graphqlOperations.filter(N=>N.usedIn.length>0).map(N=>N.name)});return {sharedTypes:r,apiConnections:e,navigationFlows:a,dataFlowAcrossRepos:s}}extractCrossRepoLinks(o){let r=[],e=new Map;for(let a of o)for(let s of a.graphqlOperations){let i=e.get(s.name)||[];i.push(a),e.set(s.name,i);}for(let[a,s]of e)s.length>1&&r.push({sourceRepo:s[0].repository,sourcePath:`graphql/${a}`,targetRepo:s[1].repository,targetPath:`graphql/${a}`,linkType:"graphql-operation",description:`Shared GraphQL operation: ${a}`});return r}async enrichPagesWithHookGraphQL(o,r){let e=o.graphqlOperations.filter(n=>n.type==="query"||n.type==="mutation"||n.type==="subscription"),a=/\.(ts|tsx|js|jsx)$/,s=n=>R.normalize(n).replace(/\\/g,"/"),i=(this.config.analysis?.include||["**/*.ts","**/*.tsx"]).map(String),k=(this.config.analysis?.exclude||[]).map(String),x=(await import('fast-glob')).default,T=await x(i,{cwd:r,ignore:["**/node_modules/**","**/.next/**","**/dist/**","**/build/**","**/coverage/**",...k],onlyFiles:true,unique:true,dot:false}),b=new Set(T.map(s)),$=new Map;for(let n of b){let t=n.replace(a,"");$.has(t)||$.set(t,n);}let N=new b$1(r,b),Z=new Set(["src/"]);for(let n of b){let t=n.indexOf("/src/");t!==-1&&Z.add(n.slice(0,t+5));}let F=n=>{let t=s(n).replace(a,""),p=$.get(t);if(p)return p;let c=$.get(t+"/index");return c||null},ve=async()=>{let n=["tsconfig.json","jsconfig.json"];for(let t of n)try{let p=await A.readFile(R.join(r,t),"utf-8"),l=JSON.parse(p)?.compilerOptions||{},d=typeof l.baseUrl=="string"?l.baseUrl:void 0,q=typeof l.paths=="object"&&l.paths?l.paths:void 0;return {baseUrl:d,paths:q}}catch{}return {}},{baseUrl:D,paths:V}=await ve(),we=n=>{if(!V)return [];let t=[];for(let[p,c]of Object.entries(V)){if(!p.includes("*")){n===p&&t.push(...c);continue}let[l,d]=p.split("*");if(!n.startsWith(l)||!n.endsWith(d))continue;let q=n.slice(l.length,n.length-d.length);for(let w of c)w.includes("*")?t.push(w.replace("*",q)):t.push(w);}return t},I=(n,t)=>{if(!t)return null;let p=N.resolve(n,t);if(p)return p.file;if(t.startsWith(".")){let l=R.dirname(n);return F(R.join(l,t))}if(t.startsWith("@/")){let l=t.replace("@/","");if(D){let d=F(R.join(D,l));if(d)return d}for(let d of Z){let q=F(d+l);if(q)return q}return null}let c=we(t);if(c.length>0)for(let l of c){let d=F(D?R.join(D,l):l);if(d)return d}if(D){let l=F(R.join(D,t));if(l)return l}return null},j=new Map,_=new Map,Q=async n=>{let t=s(n),p=_.get(t);if(p!==void 0)return p;try{let c=R.join(r,t),l=await A.readFile(c,"utf-8");return _.set(t,l),l}catch{return _.set(t,""),null}},xe=async n=>{let t=s(n),p=j.get(t);if(p)return p.map(h=>({spec:h,names:null}));let c=await Q(t);if(!c)return j.set(t,[]),[];let l;try{let h=t.endsWith(".ts")||t.endsWith(".tsx"),g=t.endsWith(".tsx")||t.endsWith(".jsx");l=parseSync(c,{syntax:h?"typescript":"ecmascript",tsx:g,jsx:g,comments:!1});}catch{return j.set(t,[]),[]}let d=new Set,q=[],w=(h,g,m)=>{typeof h!="string"||h.length===0||(d.add(h),q.push({spec:h,names:g,pos:m}));},f=h=>{if(!h||typeof h!="object")return;let g=h,m=g;if(m.type==="ImportDeclaration"){if(!m.typeOnly){let v=m.source?.value,u=[],y=m.specifiers||[];for(let E of y){let M=E,B=M.type;if(B==="ImportDefaultSpecifier"||B==="ImportNamespaceSpecifier"){u=null;break}if(B==="ImportSpecifier"){let G=M.imported?.value,P=M.local?.value,z=G||P;z&&u.push(z);}}Array.isArray(u)&&u.length===0&&(u=null),w(v,u,m.span?.start);}}else if(m.type==="ExportAllDeclaration")w(m.source?.value,null,m.span?.start);else if(m.type==="ExportNamedDeclaration"){let v=m.source?.value,u=m.specifiers||[],y=[];for(let E of u){let M=E;if(M.type==="ExportSpecifier"){let G=M.exported?.value,P=M.orig?.value,z=G||P;z&&y.push(z);}}w(v,y.length>0?y:null,m.span?.start);}else if(m.type==="CallExpression"){let v=m.callee||null;if(v?.type==="Identifier"&&v.value==="require"){let u=m.arguments?.[0]?.expression;u?.type==="StringLiteral"&&w(u.value,null,m.span?.start);}if(v?.type==="Import"){let u=m.arguments?.[0]?.expression;u?.type==="StringLiteral"&&w(u.value,null,m.span?.start);}}for(let v of Object.keys(g)){let u=g[v];if(Array.isArray(u))for(let y of u)f(y);else u&&typeof u=="object"&&f(u);}};f(l);let C=Array.from(d);return j.set(t,C),q.filter(h=>typeof h.spec=="string"&&h.spec.length>0)},be=(n,t)=>{if(t===void 0||t<0)return;let p=1;for(let c=0;c<n.length&&c<t;c++)n.charCodeAt(c)===10&&p++;return p},ke=(n,t)=>{if(t<0)return;let p=1;for(let c=0;c<n.length&&c<t;c++)n.charCodeAt(c)===10&&p++;return p},H=new Map,Y=async n=>{let t=s(n),p=H.get(t);if(p)return p;let c=await Q(t);if(!c){let h={named:new Map,stars:[],isBarrel:false};return H.set(t,h),h}let l;try{let h=t.endsWith(".ts")||t.endsWith(".tsx"),g=t.endsWith(".tsx")||t.endsWith(".jsx");l=parseSync(c,{syntax:h?"typescript":"ecmascript",tsx:g,jsx:g,comments:!1});}catch{let h={named:new Map,stars:[],isBarrel:false};return H.set(t,h),h}let d=new Map,q=[],w=true,f=l?.body;if(Array.isArray(f))for(let h of f){let g=h,m=g.type;if(m&&m!=="ImportDeclaration"){if(m==="ExportAllDeclaration"){let v=g.source?.value;typeof v=="string"&&q.push(v);continue}if(m==="ExportNamedDeclaration"){let v=g.source?.value,u=g.specifiers||[];if(typeof v=="string"&&Array.isArray(u))for(let y of u){let E=y;if(E.type!=="ExportSpecifier")continue;let B=E.exported?.value,G=E.orig?.value,P=B||G;P&&d.set(P,v);}continue}w=false;}}else w=false;let C={named:d,stars:q,isBarrel:w};return H.set(t,C),C},ee=async(n,t,p)=>{let c=s(n);if(p.has(c))return null;p.add(c);let l=await Y(c),d=l.named.get(t);if(d)return I(c,d);for(let q of l.stars){let w=I(c,q);if(!w)continue;let f=await ee(w,t,p);if(f)return f}return null},X=new Map;for(let n of e){let t=new Set;n.filePath&&t.add(n.filePath);for(let p of n.usedIn||[])t.add(p);for(let p of t){let c=X.get(p)||[];c.push({opName:n.name,opType:n.type}),X.set(p,c);}}let Me=n=>{if(!n)return null;let t=[`src/pages/${n}`,`pages/${n}`,`src/app/${n}`,`app/${n}`,`frontend/src/pages/${n}`,`frontend/src/app/${n}`,`app/javascript/pages/${n}`,`app/javascript/app/${n}`];for(let l of t){if(b.has(l))return l;let d=F(l);if(d)return d}let p=[],c=[`/pages/${n}`,`/app/${n}`,`/${n}`];for(let l of b)for(let d of c)if(l.endsWith(d)&&!(d.startsWith("/pages/")&&!l.includes("/pages/"))&&!(d.startsWith("/app/")&&!l.includes("/app/"))){p.push(l);break}return p.length===0?null:(p.sort((l,d)=>l.length-d.length),p[0])},K=new Map,U=new Map;for(let n of o.pages){let t=Me(n.filePath);if(!t)continue;let p=new Map,c=new Set,l=[{f:t,depth:0}],d=new Map,q=30,w=2e4;for(;l.length>0;){let f=l.shift();if(!f)break;if(c.has(f.f))continue;if(c.add(f.f),c.size>=w)break;let C=X.get(f.f);if(C)for(let g of C){let m=p.get(g.opName);(!m||f.depth<m.distance)&&p.set(g.opName,{opName:g.opName,opType:g.opType,sourceFile:f.f,distance:f.depth});}if(f.depth>=q)continue;let h=await xe(f.f);for(let g of h){let m=I(f.f,g.spec);if(m){if(!c.has(m)&&(l.push({f:m,depth:f.depth+1}),!d.has(m))){let v=await Q(f.f),u=v?be(v,g.pos):void 0,y=Array.isArray(g.names)&&g.names.length>0?`names:${g.names.join(",")}`:void 0;d.set(m,{from:f.f,spec:g.spec,line:u,detail:y});}if(Array.isArray(g.names)&&g.names.length>0){if((await Y(m)).isBarrel)for(let u of g.names){let y=await ee(m,u,new Set);y&&!c.has(y)&&(l.push({f:y,depth:f.depth+2}),d.has(y)||d.set(y,{from:m,spec:`re-export:${u}`,line:void 0,detail:"barrel"}));}}else if(g.names===null){let v=await Y(m);if(v.isBarrel){for(let u of v.stars){let y=I(m,u);y&&!c.has(y)&&l.push({f:y,depth:f.depth+2});}for(let u of v.named.values()){let y=I(m,u);y&&!c.has(y)&&l.push({f:y,depth:f.depth+2});}}}}}}K.set(n.path,{page:n,entryFile:t,parent:d,bestByOp:p});for(let f of c)U.set(f,(U.get(f)||0)+1);}let Re=K.size,qe=Array.from(U.values()).sort((n,t)=>n-t),Te=((n,t)=>{if(n.length===0)return 0;let p=Math.min(n.length-1,Math.max(0,Math.floor(n.length*t)));return n[p]})(qe,.9),Se=Math.max(10,Te),$e=Math.max(2,Math.floor(Re*.05));for(let{page:n,entryFile:t,parent:p,bestByOp:c}of K.values()){let l=new Set((n.dataFetching||[]).map(d=>d.operationName?.replace(/^[→\->\s]+/,"")||""));for(let{opName:d,opType:q,sourceFile:w,distance:f}of c.values()){if(l.has(d))continue;l.add(d);let C=U.get(w)||0,h;f===0?h=void 0:C>=Se?h=`common:${w}`:f<=2||C<=$e?h=`close:${w}`:h=`indirect:${w}`;let g=f===0||f<=2?"certain":h?.startsWith("common:")?"unknown":"likely",m=[];if(f>0&&w!==t){let u=[],y=w,E=new Set;for(;y!==t&&!E.has(y);){E.add(y);let M=p.get(y);if(!M)break;u.push({from:M.from,to:y,spec:M.spec,line:M.line,detail:M.detail}),y=M.from;}u.reverse();for(let M of u)m.push({kind:"import-edge",file:M.from,line:M.line,detail:`${M.spec} -> ${M.to}${M.detail?` (${M.detail})`:""}`});}let v=await Q(w);if(v){let u=v.indexOf(`${d}Document`)>=0?v.indexOf(`${d}Document`):v.indexOf(d),y=u>=0?ke(v,u):void 0;m.push({kind:"operation-reference",file:w,line:y,detail:`ref:${d}`});}else m.push({kind:"operation-reference",file:w,detail:`ref:${d}`});n.dataFetching.push({type:q==="mutation"?"useMutation":q==="subscription"?"useSubscription":"useQuery",operationName:d,source:h,confidence:g,evidence:m.length>0?m:void 0});}}}async writeDocumentation(o){let r=this.config.outputDir;await A.mkdir(r,{recursive:true});let e=this.markdownGenerator.generateDocumentation(o);for(let[s,i]of e){let k=R.join(r,s),x=R.dirname(k);await A.mkdir(x,{recursive:true}),await A.writeFile(k,i,"utf-8");}let a=R.join(r,"report.json");await A.writeFile(a,JSON.stringify(o,null,2),"utf-8");}};function Ee(L){return new Promise(o=>{let r=ue.createServer();r.once("error",e=>{e.code,o(false);}),r.once("listening",()=>{r.close(),o(true);}),r.listen(L);})}async function fe(L,o=10){for(let r=0;r<o;r++){let e=L+r;if(await Ee(e))return e}throw new Error(`No available port found between ${L} and ${L+o-1}`)}var ge=class{config;port;app;server;io;engine;currentReport=null;envResult=null;railsAnalysis=null;constructor(o,r=3030){this.config=o,this.port=r,this.app=he(),this.server=ye.createServer(this.app),this.io=new Server(this.server),this.engine=new W(o),this.setupRoutes(),this.setupSocketIO();}setupRoutes(){this.app.use("/assets",he.static(R.join(this.config.outputDir,"assets"))),this.app.get("/icons.svg",async(e,a)=>{let s=[R.join(R.dirname(new URL(import.meta.url).pathname),"generators","assets","icons.svg"),R.join(R.dirname(new URL(import.meta.url).pathname),"..","generators","assets","icons.svg"),R.join(process.cwd(),"dist","generators","assets","icons.svg"),R.join(process.cwd(),"src","generators","assets","icons.svg")];for(let i of s)try{let k=await A.readFile(i);a.type("image/svg+xml").send(k);return}catch{}a.status(404).send("icons.svg not found");}),["common.css","page-map.css","docs.css","rails-map.css"].forEach(e=>{this.app.get(`/${e}`,async(a,s)=>{let i=[R.join(R.dirname(new URL(import.meta.url).pathname),"generators","assets",e),R.join(R.dirname(new URL(import.meta.url).pathname),"..","generators","assets",e),R.join(process.cwd(),"dist","generators","assets",e),R.join(process.cwd(),"src","generators","assets",e)];for(let k of i)try{let x=await A.readFile(k,"utf-8");s.type("text/css").send(x);return}catch{}s.status(404).send("CSS not found");});}),["favicon.ico","favicon.svg","favicon-96x96.png","apple-touch-icon.png","site.webmanifest","web-app-manifest-192x192.png","web-app-manifest-512x512.png"].forEach(e=>{(e==="favicon.ico"?[`/${e}`,`/favicon/${e}`]:[`/favicon/${e}`]).forEach(s=>{this.app.get(s,async(i,k)=>{let x=[R.join(R.dirname(new URL(import.meta.url).pathname),"generators","assets","favicon",e),R.join(R.dirname(new URL(import.meta.url).pathname),"..","generators","assets","favicon",e),R.join(process.cwd(),"dist","generators","assets","favicon",e),R.join(process.cwd(),"src","generators","assets","favicon",e)];for(let T of x)try{let b=await A.readFile(T),$=e.split(".").pop(),N={ico:"image/x-icon",svg:"image/svg+xml",png:"image/png",webmanifest:"application/manifest+json"};k.type(N[$||""]||"application/octet-stream").send(b);return}catch{}k.status(404).send("File not found");});});}),this.app.get("/",(e,a)=>{a.redirect("/page-map");}),this.app.get("/page-map",(e,a)=>{if(!this.currentReport){a.status(503).send("Documentation not ready yet");return}let s=new a$1;a.send(s.generatePageMapHtml(this.currentReport,{envResult:this.envResult,railsAnalysis:this.railsAnalysis}));}),this.app.get("/rails-map",(e,a)=>{if(!this.railsAnalysis){a.status(404).send("No Rails environment detected");return}let s=new b$2;a.send(s.generateFromResult(this.railsAnalysis));}),this.app.get("/docs",async(e,a)=>{a.send(await this.renderPage("index"));}),this.app.get("/docs/*path",async(e,a)=>{let s=e.params.path,i=Array.isArray(s)?s.join("/"):s||"index";a.send(await this.renderPage(i));}),this.app.get("/api/report",(e,a)=>{a.json(this.currentReport);}),this.app.get("/api/env",(e,a)=>{a.json(this.envResult);}),this.app.get("/api/rails",(e,a)=>{this.railsAnalysis?a.json(this.railsAnalysis):a.status(404).json({error:"No Rails analysis available"});}),this.app.get("/api/diagram/:name",(e,a)=>{let s=this.currentReport?.diagrams.find(i=>i.title.toLowerCase().replace(/\s+/g,"-")===e.params.name);s?a.json(s):a.status(404).json({error:"Diagram not found"});}),this.app.post("/api/regenerate",async(e,a)=>{try{await this.regenerate(),a.json({success:!0});}catch(s){a.status(500).json({error:s.message});}});}setupSocketIO(){this.io.on("connection",o=>{o.on("disconnect",()=>{});});}async renderPage(o){let r=o.replace(/\.md$/,""),e=R.join(this.config.outputDir,`${r}.md`),a="";try{let s=await A.readFile(e,"utf-8"),i=await marked.parse(s);i=i.replace(/<pre><code class="language-mermaid">([\s\S]*?)<\/code><\/pre>/g,'<div class="mermaid">$1</div>'),i=i.replace(/<table>/g,'<div class="table-wrapper"><table>'),i=i.replace(/<\/table>/g,"</table></div>"),a=i;}catch(s){let i=s;if(i.code==="ENOENT"){let k=this.currentReport?.repositories.map(x=>x.name)||[];a=`
|
|
1
|
+
import {b as b$2,a as a$2}from'./chunk-DSYVU23K.js';import {a as a$3}from'./chunk-VV3A3UE3.js';import {C,B,A as A$1,z,b as b$1}from'./chunk-5PWKCCT7.js';import {a,b}from'./chunk-QBSB6BIU.js';import {a as a$1}from'./chunk-JBPSEUZS.js';import {k}from'./chunk-H7VVRHQZ.js';import {simpleGit}from'simple-git';import*as A from'fs/promises';import*as R from'path';import {parseSync}from'@swc/core';import he from'express';import {Server}from'socket.io';import*as ye from'http';import {marked}from'marked';import*as ue from'net';var W=class{config;mermaidGenerator;markdownGenerator;constructor(o){this.config=o,this.mermaidGenerator=new a,this.markdownGenerator=new b;}async generate(){let o=[];for(let k of this.config.repositories)try{let x=await this.analyzeRepository(k);o.push(x);}catch(x){console.error(`\u274C ${k.name}: ${x.message}`);}let r=this.analyzeCrossRepo(o),e=o.map(k=>k.analysis),a=this.extractCrossRepoLinks(e),s=this.mermaidGenerator.generateAll(e,a),i={generatedAt:new Date().toISOString(),repositories:o,crossRepoAnalysis:r,diagrams:s};return await this.writeDocumentation(i),i}async analyzeRepository(o){let{version:r,commitHash:e}=await this.getRepoInfo(o),a=o.analyzers.map(b=>this.createAnalyzer(b,o)).filter(b=>b!==null),s=Date.now(),i=await Promise.all(a.map(b=>b.analyze())),k=((Date.now()-s)/1e3).toFixed(1);console.log(` Analyzed ${o.displayName} in ${k}s`);let x=this.mergeAnalysisResults(i,o.name,r,e);await this.enrichPagesWithHookGraphQL(x,o.path);let T={totalPages:x.pages.length,totalComponents:x.components.length,totalGraphQLOperations:x.graphqlOperations.length,totalDataFlows:x.dataFlows.length,authRequiredPages:x.pages.filter(b=>b.authentication.required).length,publicPages:x.pages.filter(b=>!b.authentication.required).length};return {name:o.name,displayName:o.displayName,version:r,commitHash:e,analysis:x,summary:T}}async getRepoInfo(o){try{let a=(await simpleGit(o.path).log({n:1})).latest?.hash||"unknown",s="unknown";try{let i=R.join(o.path,"package.json");s=JSON.parse(await A.readFile(i,"utf-8")).version||"unknown";}catch{}return {version:s,commitHash:a}}catch{return {version:"unknown",commitHash:"unknown"}}}createAnalyzer(o,r){switch(o){case "pages":if(r.type==="nextjs"||r.type==="rails"||r.type==="generic")return new z(r);break;case "graphql":return new A$1(r);case "dataflow":case "components":return new B(r);case "rest-api":case "api":return new C(r)}return null}mergeAnalysisResults(o,r,e,a){let s={repository:r,timestamp:new Date().toISOString(),version:e,commitHash:a,coverage:{tsFilesScanned:0,tsParseFailures:0,graphqlParseFailures:0,codegenFilesDetected:0,codegenFilesParsed:0,codegenExportsFound:0},pages:[],graphqlOperations:[],apiCalls:[],components:[],dataFlows:[],apiEndpoints:[],models:[],crossRepoLinks:[]};for(let i of o)i.coverage&&s.coverage&&(s.coverage.tsFilesScanned+=i.coverage.tsFilesScanned||0,s.coverage.tsParseFailures+=i.coverage.tsParseFailures||0,s.coverage.graphqlParseFailures+=i.coverage.graphqlParseFailures||0,s.coverage.codegenFilesDetected+=i.coverage.codegenFilesDetected||0,s.coverage.codegenFilesParsed+=i.coverage.codegenFilesParsed||0,s.coverage.codegenExportsFound+=i.coverage.codegenExportsFound||0),i.pages&&s.pages.push(...i.pages),i.graphqlOperations&&s.graphqlOperations.push(...i.graphqlOperations),i.apiCalls&&s.apiCalls.push(...i.apiCalls),i.components&&s.components.push(...i.components),i.dataFlows&&s.dataFlows.push(...i.dataFlows),i.apiEndpoints&&s.apiEndpoints.push(...i.apiEndpoints),i.models&&s.models.push(...i.models),i.crossRepoLinks&&s.crossRepoLinks.push(...i.crossRepoLinks);return s}analyzeCrossRepo(o){let r=[],e=[],a=[],s=[],i=new Map;for(let T of o)for(let b of T.analysis.graphqlOperations){let $=i.get(b.name)||[];$.push(T.name),i.set(b.name,$);}for(let[T,b]of i)b.length>1&&r.push(T);let k=o.filter(T=>T.analysis.pages.length>0),x=o.filter(T=>T.analysis.apiEndpoints.length>0);for(let T of k)for(let b of x)for(let $ of b.analysis.apiEndpoints)e.push({frontend:T.name,backend:b.name,endpoint:$.path,operations:T.analysis.graphqlOperations.filter(N=>N.usedIn.length>0).map(N=>N.name)});return {sharedTypes:r,apiConnections:e,navigationFlows:a,dataFlowAcrossRepos:s}}extractCrossRepoLinks(o){let r=[],e=new Map;for(let a of o)for(let s of a.graphqlOperations){let i=e.get(s.name)||[];i.push(a),e.set(s.name,i);}for(let[a,s]of e)s.length>1&&r.push({sourceRepo:s[0].repository,sourcePath:`graphql/${a}`,targetRepo:s[1].repository,targetPath:`graphql/${a}`,linkType:"graphql-operation",description:`Shared GraphQL operation: ${a}`});return r}async enrichPagesWithHookGraphQL(o,r){let e=o.graphqlOperations.filter(n=>n.type==="query"||n.type==="mutation"||n.type==="subscription"),a=/\.(ts|tsx|js|jsx)$/,s=n=>R.normalize(n).replace(/\\/g,"/"),i=(this.config.analysis?.include||["**/*.ts","**/*.tsx"]).map(String),k=(this.config.analysis?.exclude||[]).map(String),x=(await import('fast-glob')).default,T=await x(i,{cwd:r,ignore:["**/node_modules/**","**/.next/**","**/dist/**","**/build/**","**/coverage/**",...k],onlyFiles:true,unique:true,dot:false}),b=new Set(T.map(s)),$=new Map;for(let n of b){let t=n.replace(a,"");$.has(t)||$.set(t,n);}let N=new b$1(r,b),Z=new Set(["src/"]);for(let n of b){let t=n.indexOf("/src/");t!==-1&&Z.add(n.slice(0,t+5));}let F=n=>{let t=s(n).replace(a,""),p=$.get(t);if(p)return p;let c=$.get(t+"/index");return c||null},ve=async()=>{let n=["tsconfig.json","jsconfig.json"];for(let t of n)try{let p=await A.readFile(R.join(r,t),"utf-8"),l=JSON.parse(p)?.compilerOptions||{},d=typeof l.baseUrl=="string"?l.baseUrl:void 0,q=typeof l.paths=="object"&&l.paths?l.paths:void 0;return {baseUrl:d,paths:q}}catch{}return {}},{baseUrl:D,paths:V}=await ve(),we=n=>{if(!V)return [];let t=[];for(let[p,c]of Object.entries(V)){if(!p.includes("*")){n===p&&t.push(...c);continue}let[l,d]=p.split("*");if(!n.startsWith(l)||!n.endsWith(d))continue;let q=n.slice(l.length,n.length-d.length);for(let w of c)w.includes("*")?t.push(w.replace("*",q)):t.push(w);}return t},I=(n,t)=>{if(!t)return null;let p=N.resolve(n,t);if(p)return p.file;if(t.startsWith(".")){let l=R.dirname(n);return F(R.join(l,t))}if(t.startsWith("@/")){let l=t.replace("@/","");if(D){let d=F(R.join(D,l));if(d)return d}for(let d of Z){let q=F(d+l);if(q)return q}return null}let c=we(t);if(c.length>0)for(let l of c){let d=F(D?R.join(D,l):l);if(d)return d}if(D){let l=F(R.join(D,t));if(l)return l}return null},j=new Map,_=new Map,Q=async n=>{let t=s(n),p=_.get(t);if(p!==void 0)return p;try{let c=R.join(r,t),l=await A.readFile(c,"utf-8");return _.set(t,l),l}catch{return _.set(t,""),null}},xe=async n=>{let t=s(n),p=j.get(t);if(p)return p.map(h=>({spec:h,names:null}));let c=await Q(t);if(!c)return j.set(t,[]),[];let l;try{let h=t.endsWith(".ts")||t.endsWith(".tsx"),g=t.endsWith(".tsx")||t.endsWith(".jsx");l=parseSync(c,{syntax:h?"typescript":"ecmascript",tsx:g,jsx:g,comments:!1});}catch{return j.set(t,[]),[]}let d=new Set,q=[],w=(h,g,m)=>{typeof h!="string"||h.length===0||(d.add(h),q.push({spec:h,names:g,pos:m}));},f=h=>{if(!h||typeof h!="object")return;let g=h,m=g;if(m.type==="ImportDeclaration"){if(!m.typeOnly){let v=m.source?.value,u=[],y=m.specifiers||[];for(let E of y){let M=E,B=M.type;if(B==="ImportDefaultSpecifier"||B==="ImportNamespaceSpecifier"){u=null;break}if(B==="ImportSpecifier"){let G=M.imported?.value,P=M.local?.value,z=G||P;z&&u.push(z);}}Array.isArray(u)&&u.length===0&&(u=null),w(v,u,m.span?.start);}}else if(m.type==="ExportAllDeclaration")w(m.source?.value,null,m.span?.start);else if(m.type==="ExportNamedDeclaration"){let v=m.source?.value,u=m.specifiers||[],y=[];for(let E of u){let M=E;if(M.type==="ExportSpecifier"){let G=M.exported?.value,P=M.orig?.value,z=G||P;z&&y.push(z);}}w(v,y.length>0?y:null,m.span?.start);}else if(m.type==="CallExpression"){let v=m.callee||null;if(v?.type==="Identifier"&&v.value==="require"){let u=m.arguments?.[0]?.expression;u?.type==="StringLiteral"&&w(u.value,null,m.span?.start);}if(v?.type==="Import"){let u=m.arguments?.[0]?.expression;u?.type==="StringLiteral"&&w(u.value,null,m.span?.start);}}for(let v of Object.keys(g)){let u=g[v];if(Array.isArray(u))for(let y of u)f(y);else u&&typeof u=="object"&&f(u);}};f(l);let C=Array.from(d);return j.set(t,C),q.filter(h=>typeof h.spec=="string"&&h.spec.length>0)},be=(n,t)=>{if(t===void 0||t<0)return;let p=1;for(let c=0;c<n.length&&c<t;c++)n.charCodeAt(c)===10&&p++;return p},ke=(n,t)=>{if(t<0)return;let p=1;for(let c=0;c<n.length&&c<t;c++)n.charCodeAt(c)===10&&p++;return p},H=new Map,Y=async n=>{let t=s(n),p=H.get(t);if(p)return p;let c=await Q(t);if(!c){let h={named:new Map,stars:[],isBarrel:false};return H.set(t,h),h}let l;try{let h=t.endsWith(".ts")||t.endsWith(".tsx"),g=t.endsWith(".tsx")||t.endsWith(".jsx");l=parseSync(c,{syntax:h?"typescript":"ecmascript",tsx:g,jsx:g,comments:!1});}catch{let h={named:new Map,stars:[],isBarrel:false};return H.set(t,h),h}let d=new Map,q=[],w=true,f=l?.body;if(Array.isArray(f))for(let h of f){let g=h,m=g.type;if(m&&m!=="ImportDeclaration"){if(m==="ExportAllDeclaration"){let v=g.source?.value;typeof v=="string"&&q.push(v);continue}if(m==="ExportNamedDeclaration"){let v=g.source?.value,u=g.specifiers||[];if(typeof v=="string"&&Array.isArray(u))for(let y of u){let E=y;if(E.type!=="ExportSpecifier")continue;let B=E.exported?.value,G=E.orig?.value,P=B||G;P&&d.set(P,v);}continue}w=false;}}else w=false;let C={named:d,stars:q,isBarrel:w};return H.set(t,C),C},ee=async(n,t,p)=>{let c=s(n);if(p.has(c))return null;p.add(c);let l=await Y(c),d=l.named.get(t);if(d)return I(c,d);for(let q of l.stars){let w=I(c,q);if(!w)continue;let f=await ee(w,t,p);if(f)return f}return null},X=new Map;for(let n of e){let t=new Set;n.filePath&&t.add(n.filePath);for(let p of n.usedIn||[])t.add(p);for(let p of t){let c=X.get(p)||[];c.push({opName:n.name,opType:n.type}),X.set(p,c);}}let Me=n=>{if(!n)return null;let t=[`src/pages/${n}`,`pages/${n}`,`src/app/${n}`,`app/${n}`,`frontend/src/pages/${n}`,`frontend/src/app/${n}`,`app/javascript/pages/${n}`,`app/javascript/app/${n}`];for(let l of t){if(b.has(l))return l;let d=F(l);if(d)return d}let p=[],c=[`/pages/${n}`,`/app/${n}`,`/${n}`];for(let l of b)for(let d of c)if(l.endsWith(d)&&!(d.startsWith("/pages/")&&!l.includes("/pages/"))&&!(d.startsWith("/app/")&&!l.includes("/app/"))){p.push(l);break}return p.length===0?null:(p.sort((l,d)=>l.length-d.length),p[0])},K=new Map,U=new Map;for(let n of o.pages){let t=Me(n.filePath);if(!t)continue;let p=new Map,c=new Set,l=[{f:t,depth:0}],d=new Map,q=30,w=2e4;for(;l.length>0;){let f=l.shift();if(!f)break;if(c.has(f.f))continue;if(c.add(f.f),c.size>=w)break;let C=X.get(f.f);if(C)for(let g of C){let m=p.get(g.opName);(!m||f.depth<m.distance)&&p.set(g.opName,{opName:g.opName,opType:g.opType,sourceFile:f.f,distance:f.depth});}if(f.depth>=q)continue;let h=await xe(f.f);for(let g of h){let m=I(f.f,g.spec);if(m){if(!c.has(m)&&(l.push({f:m,depth:f.depth+1}),!d.has(m))){let v=await Q(f.f),u=v?be(v,g.pos):void 0,y=Array.isArray(g.names)&&g.names.length>0?`names:${g.names.join(",")}`:void 0;d.set(m,{from:f.f,spec:g.spec,line:u,detail:y});}if(Array.isArray(g.names)&&g.names.length>0){if((await Y(m)).isBarrel)for(let u of g.names){let y=await ee(m,u,new Set);y&&!c.has(y)&&(l.push({f:y,depth:f.depth+2}),d.has(y)||d.set(y,{from:m,spec:`re-export:${u}`,line:void 0,detail:"barrel"}));}}else if(g.names===null){let v=await Y(m);if(v.isBarrel){for(let u of v.stars){let y=I(m,u);y&&!c.has(y)&&l.push({f:y,depth:f.depth+2});}for(let u of v.named.values()){let y=I(m,u);y&&!c.has(y)&&l.push({f:y,depth:f.depth+2});}}}}}}K.set(n.path,{page:n,entryFile:t,parent:d,bestByOp:p});for(let f of c)U.set(f,(U.get(f)||0)+1);}let Re=K.size,qe=Array.from(U.values()).sort((n,t)=>n-t),Te=((n,t)=>{if(n.length===0)return 0;let p=Math.min(n.length-1,Math.max(0,Math.floor(n.length*t)));return n[p]})(qe,.9),Se=Math.max(10,Te),$e=Math.max(2,Math.floor(Re*.05));for(let{page:n,entryFile:t,parent:p,bestByOp:c}of K.values()){let l=new Set((n.dataFetching||[]).map(d=>d.operationName?.replace(/^[→\->\s]+/,"")||""));for(let{opName:d,opType:q,sourceFile:w,distance:f}of c.values()){if(l.has(d))continue;l.add(d);let C=U.get(w)||0,h;f===0?h=void 0:C>=Se?h=`common:${w}`:f<=2||C<=$e?h=`close:${w}`:h=`indirect:${w}`;let g=f===0||f<=2?"certain":h?.startsWith("common:")?"unknown":"likely",m=[];if(f>0&&w!==t){let u=[],y=w,E=new Set;for(;y!==t&&!E.has(y);){E.add(y);let M=p.get(y);if(!M)break;u.push({from:M.from,to:y,spec:M.spec,line:M.line,detail:M.detail}),y=M.from;}u.reverse();for(let M of u)m.push({kind:"import-edge",file:M.from,line:M.line,detail:`${M.spec} -> ${M.to}${M.detail?` (${M.detail})`:""}`});}let v=await Q(w);if(v){let u=v.indexOf(`${d}Document`)>=0?v.indexOf(`${d}Document`):v.indexOf(d),y=u>=0?ke(v,u):void 0;m.push({kind:"operation-reference",file:w,line:y,detail:`ref:${d}`});}else m.push({kind:"operation-reference",file:w,detail:`ref:${d}`});n.dataFetching.push({type:q==="mutation"?"useMutation":q==="subscription"?"useSubscription":"useQuery",operationName:d,source:h,confidence:g,evidence:m.length>0?m:void 0});}}}async writeDocumentation(o){let r=this.config.outputDir;await A.mkdir(r,{recursive:true});let e=this.markdownGenerator.generateDocumentation(o);for(let[s,i]of e){let k=R.join(r,s),x=R.dirname(k);await A.mkdir(x,{recursive:true}),await A.writeFile(k,i,"utf-8");}let a=R.join(r,"report.json");await A.writeFile(a,JSON.stringify(o,null,2),"utf-8");}};function Ee(L){return new Promise(o=>{let r=ue.createServer();r.once("error",e=>{e.code,o(false);}),r.once("listening",()=>{r.close(),o(true);}),r.listen(L);})}async function fe(L,o=10){for(let r=0;r<o;r++){let e=L+r;if(await Ee(e))return e}throw new Error(`No available port found between ${L} and ${L+o-1}`)}var ge=class{config;port;app;server;io;engine;currentReport=null;envResult=null;railsAnalysis=null;constructor(o,r=3030){this.config=o,this.port=r,this.app=he(),this.server=ye.createServer(this.app),this.io=new Server(this.server),this.engine=new W(o),this.setupRoutes(),this.setupSocketIO();}setupRoutes(){this.app.use("/assets",he.static(R.join(this.config.outputDir,"assets"))),this.app.get("/icons.svg",async(e,a)=>{let s=[R.join(R.dirname(new URL(import.meta.url).pathname),"generators","assets","icons.svg"),R.join(R.dirname(new URL(import.meta.url).pathname),"..","generators","assets","icons.svg"),R.join(process.cwd(),"dist","generators","assets","icons.svg"),R.join(process.cwd(),"src","generators","assets","icons.svg")];for(let i of s)try{let k=await A.readFile(i);a.type("image/svg+xml").send(k);return}catch{}a.status(404).send("icons.svg not found");}),["common.css","page-map.css","docs.css","rails-map.css"].forEach(e=>{this.app.get(`/${e}`,async(a,s)=>{let i=[R.join(R.dirname(new URL(import.meta.url).pathname),"generators","assets",e),R.join(R.dirname(new URL(import.meta.url).pathname),"..","generators","assets",e),R.join(process.cwd(),"dist","generators","assets",e),R.join(process.cwd(),"src","generators","assets",e)];for(let k of i)try{let x=await A.readFile(k,"utf-8");s.type("text/css").send(x);return}catch{}s.status(404).send("CSS not found");});}),["favicon.ico","favicon.svg","favicon-96x96.png","apple-touch-icon.png","site.webmanifest","web-app-manifest-192x192.png","web-app-manifest-512x512.png"].forEach(e=>{(e==="favicon.ico"?[`/${e}`,`/favicon/${e}`]:[`/favicon/${e}`]).forEach(s=>{this.app.get(s,async(i,k)=>{let x=[R.join(R.dirname(new URL(import.meta.url).pathname),"generators","assets","favicon",e),R.join(R.dirname(new URL(import.meta.url).pathname),"..","generators","assets","favicon",e),R.join(process.cwd(),"dist","generators","assets","favicon",e),R.join(process.cwd(),"src","generators","assets","favicon",e)];for(let T of x)try{let b=await A.readFile(T),$=e.split(".").pop(),N={ico:"image/x-icon",svg:"image/svg+xml",png:"image/png",webmanifest:"application/manifest+json"};k.type(N[$||""]||"application/octet-stream").send(b);return}catch{}k.status(404).send("File not found");});});}),this.app.get("/",(e,a)=>{a.redirect("/page-map");}),this.app.get("/page-map",(e,a)=>{if(!this.currentReport){a.status(503).send("Documentation not ready yet");return}let s=new a$1;a.send(s.generatePageMapHtml(this.currentReport,{envResult:this.envResult,railsAnalysis:this.railsAnalysis}));}),this.app.get("/rails-map",(e,a)=>{if(!this.railsAnalysis){a.status(404).send("No Rails environment detected");return}let s=new b$2;a.send(s.generateFromResult(this.railsAnalysis));}),this.app.get("/docs",async(e,a)=>{a.send(await this.renderPage("index"));}),this.app.get("/docs/*path",async(e,a)=>{let s=e.params.path,i=Array.isArray(s)?s.join("/"):s||"index";a.send(await this.renderPage(i));}),this.app.get("/api/report",(e,a)=>{a.json(this.currentReport);}),this.app.get("/api/env",(e,a)=>{a.json(this.envResult);}),this.app.get("/api/rails",(e,a)=>{this.railsAnalysis?a.json(this.railsAnalysis):a.status(404).json({error:"No Rails analysis available"});}),this.app.get("/api/diagram/:name",(e,a)=>{let s=this.currentReport?.diagrams.find(i=>i.title.toLowerCase().replace(/\s+/g,"-")===e.params.name);s?a.json(s):a.status(404).json({error:"Diagram not found"});}),this.app.post("/api/regenerate",async(e,a)=>{try{await this.regenerate(),a.json({success:!0});}catch(s){a.status(500).json({error:s.message});}});}setupSocketIO(){this.io.on("connection",o=>{o.on("disconnect",()=>{});});}async renderPage(o){let r=o.replace(/\.md$/,""),e=R.join(this.config.outputDir,`${r}.md`),a="";try{let s=await A.readFile(e,"utf-8"),i=await marked.parse(s);i=i.replace(/<pre><code class="language-mermaid">([\s\S]*?)<\/code><\/pre>/g,'<div class="mermaid">$1</div>'),i=i.replace(/<table>/g,'<div class="table-wrapper"><table>'),i=i.replace(/<\/table>/g,"</table></div>"),a=i;}catch(s){let i=s;if(i.code==="ENOENT"){let k=this.currentReport?.repositories.map(x=>x.name)||[];a=`
|
|
2
2
|
<h1>Page not found</h1>
|
|
3
3
|
<p>The requested path <code>${r}</code> does not exist.</p>
|
|
4
4
|
${k.length>0?`
|
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-CWAQJQVH.js';import'./chunk-DSYVU23K.js';import'./chunk-VV3A3UE3.js';import'./chunk-5PWKCCT7.js';import'./chunk-QBSB6BIU.js';import'./chunk-JBPSEUZS.js';import'./chunk-H7VVRHQZ.js';import {Command}from'commander';import s from'chalk';import*as c from'path';import*as v from'fs';import*as n from'fs/promises';import*as P from'os';function x(){let e=P.tmpdir();return c.join(e,`repomap-${Date.now()}`)}function S(e){let t=async()=>{try{await n.rm(e,{recursive:!0,force:!0});}catch{}process.exit(0);};process.on("SIGINT",t),process.on("SIGTERM",t);}function E(){try{let e=new URL("../package.json",import.meta.url),t=v.readFileSync(e,"utf-8");return JSON.parse(t).version||"0.0.0"}catch{return "0.0.0"}}var h=new Command;h.name("repomap").description("Interactive documentation generator for code repositories").version(E());async function C(e){let t=c.basename(e),a=false,o=c.join(e,"Gemfile"),p=c.join(e,"config","routes.rb");try{await n.access(o),await n.access(p);let d=await n.readFile(o,"utf-8");a=d.includes("gem 'rails'")||d.includes('gem "rails"');}catch{}let r=c.join(e,"package.json"),i=false,l=false,f={};try{let d=JSON.parse(await n.readFile(r,"utf-8")),w={...d.dependencies,...d.devDependencies};i=!!w.react,l=!!w.next;let m=["src/pages","pages","app","src/app","frontend/src"];for(let u of m)try{await n.access(c.join(e,u)),f.pagesDir=u;break}catch{}let b=["src/features","features","src/modules","modules","frontend/src"];for(let u of b)try{await n.access(c.join(e,u)),f.featuresDir=u;break}catch{}let D=["src/components","components","src/common/components","frontend/src"];for(let u of D)try{await n.access(c.join(e,u)),f.componentsDir=u;break}catch{}}catch{}let g=[];(i||l)&&g.push("pages","graphql","dataflow","rest-api");let y="generic";return l?y="nextjs":a&&(y="rails"),!a&&!i&&!l?null:{name:t,displayName:t,description:a&&i?"Rails + React application":a?"Rails application":"",path:e,branch:"main",type:y,analyzers:g,settings:f}}async function N(e){let t=await C(e);if(!t)throw new Error("Could not detect project. Please create a repomap.config.ts file or run 'repomap init'.");return {outputDir:"./.repomap",site:{title:`${t.displayName} Documentation`,description:"Auto-generated documentation",baseUrl:"/docs"},repositories:[t],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 $(e,t){let a=e?[e]:["repomap.config.ts","repomap.config.js","repomap.config.mjs"];for(let o of a){let p=c.resolve(t,o);try{await n.access(p);let r=await import(p);return r.config||r.default}catch{}}return N(t)}h.command("generate").description("Generate documentation from source code").option("-c, --config <path>","Path to config file").option("-o, --output <path>","Output directory").option("--temp","Use temporary directory (no files in repository)").option("--repo <name>","Analyze specific repository only").option("--watch","Watch for changes and regenerate").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 t=e.ci||process.env.CI==="true";t||console.log(s.blue.bold(`
|
|
3
3
|
\u{1F4DA} Repomap
|
|
4
4
|
`));try{let a$1=process.cwd(),o=await $(e.config,a$1);e.temp&&(o.outputDir=x(),t||console.log(s.cyan(`\u{1F4C1} Using temp directory: ${o.outputDir}
|
|
5
5
|
`))),e.output&&(o.outputDir=e.output),e.repo&&(o.repositories=o.repositories.filter(r=>r.name===e.repo),o.repositories.length===0&&(console.error(s.red(`Repository "${e.repo}" not found in config`)),process.exit(1)));let p=new a(o);if(e.watch)console.log(s.yellow(`\u{1F440} Watch mode enabled. Press Ctrl+C to stop.
|
|
@@ -88,10 +88,19 @@ declare class PagesAnalyzer extends BaseAnalyzer {
|
|
|
88
88
|
private detectPagesRoot;
|
|
89
89
|
private filePathToRoutePath;
|
|
90
90
|
private extractRouteParams;
|
|
91
|
+
/**
|
|
92
|
+
* Find the name of the default export (function/class declaration)
|
|
93
|
+
* Returns null if the default export is anonymous or an expression
|
|
94
|
+
*/
|
|
95
|
+
private findDefaultExportName;
|
|
91
96
|
/**
|
|
92
97
|
* Find page component name from AST
|
|
93
98
|
*/
|
|
94
99
|
private findPageComponent;
|
|
100
|
+
/**
|
|
101
|
+
* Check if an import source is from the project (not an external package)
|
|
102
|
+
*/
|
|
103
|
+
private isProjectImport;
|
|
95
104
|
/**
|
|
96
105
|
* Find the main component used in the page's JSX
|
|
97
106
|
* This is more accurate than using the default export name like "Page"
|
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, CoverageMetrics, CrossRepoAnalysis, CrossRepoLink, DataFetchingInfo, DataFlow, DataFlowNode, DiagramConfig, DiagramType, GraphQLField, GraphQLOperation, ImportInfo, 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-Woim3nqS.js';
|
|
4
4
|
export { MarkdownGenerator, MermaidGenerator, PageMapGenerator, PageMapOptions } from './generators/index.js';
|
|
5
5
|
export { DocServer } 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-CWAQJQVH.js';import'./chunk-DSYVU23K.js';import'./chunk-VV3A3UE3.js';export{a as BaseAnalyzer,B as DataFlowAnalyzer,A as GraphQLAnalyzer,z as PagesAnalyzer}from'./chunk-5PWKCCT7.js';export{b as MarkdownGenerator,a as MermaidGenerator}from'./chunk-QBSB6BIU.js';export{a as PageMapGenerator}from'./chunk-JBPSEUZS.js';import'./chunk-H7VVRHQZ.js';
|
package/dist/server/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{b as DocServer}from'../chunk-
|
|
1
|
+
export{b as DocServer}from'../chunk-CWAQJQVH.js';import'../chunk-DSYVU23K.js';import'../chunk-VV3A3UE3.js';import'../chunk-5PWKCCT7.js';import'../chunk-QBSB6BIU.js';import'../chunk-JBPSEUZS.js';import'../chunk-H7VVRHQZ.js';
|
package/package.json
CHANGED
package/dist/chunk-O2SKKQVN.js
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import {parseSync}from'@swc/core';import j from'fast-glob';import*as y from'path';import*as F from'fs';import*as T from'fs/promises';import h from'typescript';import {parse,getLocation}from'graphql';var A=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}getListSetting(e,t=[]){let r=this.getSetting(e,"");return r?r.split(/[,\n]/g).map(s=>s.trim()).filter(Boolean):t}getGraphQLHookPatterns(){let e=(this.getSetting("graphqlHookPreset","auto")||"auto").trim().toLowerCase(),t=this.getListSetting("graphqlHookPatterns",[]),r=["useLazyLoadQuery","usePreloadedQuery","useQueryLoader","useMutation","useSubscription","useFragment","usePaginationFragment","useRefetchableFragment","useRelayEnvironment"],s=["useUrql*"],i=["useGql*","useGraphQL*","useGraphql*","useApiQuery*","useApiMutation*"],n=[];return e==="none"||e==="off"||e==="false"?n=[]:e==="apollo"?n=[]:e==="urql"?n=s:e==="relay"?n=r:n=[...r,...s,...i],Array.from(new Set([...n,...t]))}log(e){process.env.REPOMAP_VERBOSE==="1"&&console.log(`[${this.getName()}] ${e}`);}warn(e){console.warn(`\u26A0\uFE0F ${e}`);}error(e,t){console.error(`\u274C ${e}`,t?.message||"");}};var X=["useQuery","useLazyQuery","useSuspenseQuery","useBackgroundQuery","useReadQuery"],ee=["useMutation"],ve=["useSubscription","useFragment","useApolloClient"],z=[...X,...ee,...ve],Y={useQuery:"useQuery",useSuspenseQuery:"useQuery",useBackgroundQuery:"useQuery",useReadQuery:"useQuery",useLazyQuery:"useLazyQuery",useMutation:"useMutation",useSubscription:"useSubscription"},be=["Document","useQuery","useMutation","useLazyQuery","useSuspenseQuery","useBackgroundQuery","useSubscription","Query","Mutation","gql","graphql","GET_","FETCH_","SEARCH_","CREATE_","UPDATE_","DELETE_","SUBSCRIBE_","@apollo","ApolloClient","@urql","urql","react-relay","Relay"];function Ce(p,e){if(!e)return false;if(e===p)return true;if(!e.includes("*"))return false;let t=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${t}$`).test(p)}function E(p,e){for(let t of e)if(Ce(p,t))return true;return false}function R(p,e=[]){return E(p,e)?/Query$/.test(p)||!/(Mutation|Subscription)$/.test(p):X.includes(p)||/^use[A-Z].*Query$/.test(p)}function Q(p,e=[]){return E(p,e)?/Mutation$/.test(p)||p.toLowerCase().includes("mutation"):ee.includes(p)||/^use[A-Z].*Mutation$/.test(p)}function te(p,e=[]){return E(p,e)?/Subscription$/.test(p)||p.toLowerCase().includes("subscription"):p==="useSubscription"}function $(p,e=[]){return E(p,e)?true:z.includes(p)||R(p,e)||Q(p,e)}function D(p,e=[]){return Y[p]?Y[p]:p.includes("Mutation")||E(p,e)?"useMutation":p.includes("Lazy")?"useLazyQuery":p.includes("Subscription")?"useSubscription":"useQuery"}function W(p){return be.some(e=>p.includes(e))}function d(p){return p.replace(/^(GET_|FETCH_|CREATE_|UPDATE_|DELETE_)/,"").replace(/_QUERY$|_MUTATION$/,"").replace(/Document$/,"").replace(/Query$|Mutation$|Variables$|Subscription$/,"")}function Ae(p){try{return parseSync(p,{syntax:"typescript",tsx:!0,comments:!1})}catch{return null}}function v(p){return p?p.type==="Identifier"?p.value:p.type==="MemberExpression"&&p.property?.type==="Identifier"?p.property.value:null:null}function M(p,e){if(!(!p||typeof p!="object")){e(p);for(let t of Object.keys(p)){let r=p[t];if(Array.isArray(r))for(let s of r)M(s,e);else r&&typeof r=="object"&&M(r,e);}}}function H(p,e,t){let r={documentImports:new Map,variableOperations:new Map,staticPropertyOperations:new Map,codegenMap:t||new Map};return M(p,s=>{s.type==="ImportDeclaration"&&we(s,r.documentImports),s.type==="VariableDeclarator"&&Fe(s,e,r.variableOperations),s.type==="AssignmentExpression"&&Ne(s,e,r.staticPropertyOperations);}),r}function we(p,e){let t=p.source?.value||"",r=t.includes("__generated__")||t.includes("generated")||t.includes("graphql")||t.includes(".generated")||t.endsWith(".graphql");for(let s of p.specifiers||[]){let i;(s.type==="ImportSpecifier"||s.type==="ImportDefaultSpecifier")&&(i=s.local?.value),i&&((i.endsWith("Document")||r)&&e.set(i,i.replace(/Document$/,"")),(i.endsWith("Query")||i.endsWith("Mutation"))&&e.set(i,i.replace(/Query$|Mutation$/,"")));}}function Fe(p,e,t){if(p.id?.type!=="Identifier")return;let r=p.id.value,s=p.init;if(!s)return;let i=null;if(s.type==="CallExpression"){let n=v(s.callee);(n==="gql"||n==="graphql")&&(i=V(s,e));}if(s.type==="TaggedTemplateExpression"){let n=v(s.tag);(n==="gql"||n==="graphql")&&(i=P(s.template));}if(s.type==="Identifier"){let n=s.value;if(n.endsWith("Document")||n.endsWith("Query")||n.endsWith("Mutation")){t.set(r,n);return}}i&&t.set(r,i);}function Ne(p,e,t){if(p.left?.type!=="MemberExpression")return;let r=p.left.object,s=p.left.property;if(r?.type!=="Identifier"||s?.type!=="Identifier")return;let i=`${r.value}.${s.value}`,n=p.right;if(!n)return;let a=null;if(n.type==="CallExpression"){let o=v(n.callee);(o==="gql"||o==="graphql")&&(a=V(n,e));}if(n.type==="TaggedTemplateExpression"){let o=v(n.tag);(o==="gql"||o==="graphql")&&(a=P(n.template));}a&&t.set(i,a);}function V(p,e){if(!p.arguments?.length)return null;let t=p.arguments[0],r=t?.expression||t;if(r?.type==="TemplateLiteral")return P(r);if(p.span){let i=e.slice(p.span.start,p.span.end).match(/(?:query|mutation|subscription)\s+(\w+)/i);if(i)return i[1]}return null}function P(p,e){if(!p?.quasis?.[0])return null;let r=(p.quasis[0].raw||p.quasis[0].cooked||"").match(/(?:query|mutation|subscription)\s+(\w+)/i);return r?r[1]:null}function ne(p,e,t){if(!p.arguments?.length)return false;let r=p.arguments[0],s=r?.expression||r;if(!s)return false;if(p.typeArguments?.params?.length>0){let n=p.typeArguments.params[0];if(n?.type==="TsTypeReference"&&n.typeName?.type==="Identifier"){let a=n.typeName.value;if(/Query$|Mutation$|Subscription$|Document$/.test(a))return true}}if(s.type==="Identifier"){let n=s.value;if(t.documentImports.has(n)||t.variableOperations.has(n)||n.endsWith("Document")||/^[A-Z][a-zA-Z0-9]*Query$/.test(n)||/^[A-Z][a-zA-Z0-9]*Mutation$/.test(n)||/^[A-Z][A-Z0-9_]*_QUERY$/.test(n)||/^[A-Z][A-Z0-9_]*_MUTATION$/.test(n))return true}if(s.type==="TaggedTemplateExpression"){let n=v(s.tag);if(n==="gql"||n==="graphql")return true}if(s.type==="CallExpression"){let n=v(s.callee);if(n==="gql"||n==="graphql")return true}if(s.type==="TemplateLiteral"&&s.quasis?.[0]?.raw){let n=s.quasis[0].raw;if(/(?:query|mutation|subscription)\s+\w+/i.test(n))return true}if(s.type==="MemberExpression"){let n=s.property?.value;if(n&&/Query$|Mutation$|Document$/.test(n))return true;let a=s.object?.type==="Identifier"?s.object.value:null;if(a&&n){let o=`${a}.${n}`;if(t.staticPropertyOperations.has(o))return true}}if(s.type==="ObjectExpression")for(let n of s.properties||[]){if(n.type!=="KeyValueProperty")continue;let a=n.key?.type==="Identifier"||n.key?.type==="StringLiteral"?n.key.value:null;if(!a||!["query","mutation","document","subscription"].includes(a))continue;let o=n.value;if(o&&Z(o,e,t))return true}let i=p.span;if(i){let n=e.slice(i.start,Math.min(i.end,i.start+500));if(/\bDocument\b/.test(n)||/\bgql\s*[`(]/.test(n)||/\bgraphql\s*[`(]/.test(n)||/query\s+[A-Z]\w+\s*[({]/.test(n)||/mutation\s+[A-Z]\w+\s*[({]/.test(n))return true}return false}function U(p,e,t){let r=Me(p,e);if(r)return r;if(p.arguments?.length>0){let s=p.arguments[0],i=s?.expression||s;if(i){let n=Z(i,e,t);if(n)return n}}return null}function Me(p,e){if(p.typeArguments?.params?.length>0){let t=p.typeArguments.params[0];if(t?.type==="TsTypeReference"&&t.typeName?.type==="Identifier")return d(t.typeName.value)}if(p.callee?.span&&p.span){let t=p.callee.span.end,r=Math.min(t+150,p.span.end),i=e.slice(t,r).match(/^<\s*(\w+)(?:Query|Mutation|Variables|Subscription)?[\s,>]/);if(i)return d(i[1])}return null}function Z(p,e,t){if(p.type==="Identifier")return re(p.value,t);if(p.type==="MemberExpression")return Se(p,t);if(p.type==="TaggedTemplateExpression"){let r=v(p.tag);if(r==="gql"||r==="graphql")return P(p.template)}if(p.type==="TemplateLiteral")return P(p);if(p.type==="CallExpression"){let r=v(p.callee);if(r==="gql"||r==="graphql")return V(p,e)}return p.type==="ObjectExpression"?se(p,e,t):null}function re(p,e){let t=e.variableOperations.get(p);if(t)return e.variableOperations.has(t)?re(t,e):t.endsWith("Document")||t.endsWith("Query")||t.endsWith("Mutation")?e.documentImports.get(t)||d(t):t;let r=e.documentImports.get(p);if(r)return r;let s=e.codegenMap.get(p);return s?s.operationName:/^(Query|Mutation|QUERY|MUTATION|Document)$/i.test(p)?null:d(p)}function Se(p,e){let t=p.object?.type==="Identifier"?p.object.value:null,r=p.property?.type==="Identifier"?p.property.value:null;if(!r)return null;if(t){let s=`${t}.${r}`,i=e.staticPropertyOperations.get(s);if(i)return i}return d(r)}function se(p,e,t){for(let r of p.properties||[])if(r.type==="KeyValueProperty"&&r.key?.type==="Identifier"&&r.key.value==="query")return Z(r.value,e,t);return null}function je(p,e){let t=[],r=new Set;if(!W(p))return t;let s=Ae(p);if(!s)return t;let i=H(s,p,e);return M(s,n=>{if(n.type!=="CallExpression")return;let a=v(n.callee);if(a){if($(a)){let o=U(n,p,i),l=D(a),u=`${l}:${o||"unknown"}`;r.has(u)||(r.add(u),t.push({operationName:o||"unknown",hookName:a,type:l}));}if((a==="query"||a==="mutate")&&n.arguments?.length>0){let o=n.arguments[0],l=o?.expression||o;if(l?.type==="ObjectExpression"){let u=se(l,p,i),f=a==="mutate"?"useMutation":"useQuery",c=`${f}:${u||"unknown"}`;u&&!r.has(c)&&(r.add(c),t.push({operationName:u,hookName:`client.${a}`,type:f}));}}}}),t}function Ge(p){return `${{useQuery:"Query",useLazyQuery:"Query",useMutation:"Mutation",useSubscription:"Subscription"}[p.type]||"Query"}: ${p.operationName}`}async function S(p,e,t=8){let r=new Array(p.length).fill(null),s=0;async function i(){for(;s<p.length;){let a=s++;if(a<p.length)try{r[a]=await e(p[a],a);}catch{r[a]=null;}}}let n=Array(Math.min(t,p.length)).fill(null).map(()=>i());return await Promise.all(n),r.filter(a=>a!==null)}function k(p,e){let t=h.createSourceFile(e,p,h.ScriptTarget.Latest,true,h.ScriptKind.TS),r=[],s=i=>{if(h.isVariableStatement(i)&&Ie(i.modifiers))for(let n of i.declarationList.declarations){if(!h.isIdentifier(n.name))continue;let a=n.name.text;if(!a.endsWith("Document")||!n.initializer)continue;let o=Pe(n.initializer),l=Ee(o);if(!l)continue;let u=Re(l);if(!u)continue;let c=h.getLineAndCharacterOfPosition(t,n.name.getStart(t)).line+1;r.push({documentName:a,operationName:u.operationName,operationType:u.operationType,document:l,line:c});}h.forEachChild(i,s);};return s(t),r}function Ie(p){return p?p.some(e=>e.kind===h.SyntaxKind.ExportKeyword):false}function Pe(p){let e=p;for(;;){if(h.isParenthesizedExpression(e)){e=e.expression;continue}if(h.isAsExpression(e)){e=e.expression;continue}if(h.isTypeAssertionExpression(e)){e=e.expression;continue}if(h.isNonNullExpression(e)){e=e.expression;continue}break}return e}function Ee(p){if(!h.isObjectLiteralExpression(p))return null;let e=K(p);if(!e||typeof e!="object")return null;let t=e.kind,r=e.definitions;return t!=="Document"||!Array.isArray(r)?null:e}function Re(p){let e=p.definitions;if(!Array.isArray(e)||e.length===0)return null;let t=e[0];if(!t||typeof t!="object"||t.kind!=="OperationDefinition")return null;let s=t.operation,i=t.name,n=s==="mutation"||s==="subscription"?s:"query",a="";if(i&&typeof i=="object"){let o=i.value;typeof o=="string"&&(a=o);}return a?{operationName:a,operationType:n}:null}function K(p){if(h.isObjectLiteralExpression(p)){let e={};for(let t of p.properties){if(h.isPropertyAssignment(t)){let r=Qe(t.name);if(!r)continue;e[r]=K(t.initializer);continue}h.isShorthandPropertyAssignment(t);}return e}return h.isArrayLiteralExpression(p)?p.elements.map(e=>h.isExpression(e)?K(e):null):h.isStringLiteral(p)||h.isNoSubstitutionTemplateLiteral(p)?p.text:h.isNumericLiteral(p)?Number(p.text):p.kind===h.SyntaxKind.TrueKeyword?true:p.kind===h.SyntaxKind.FalseKeyword?false:(p.kind===h.SyntaxKind.NullKeyword,null)}function Qe(p){return h.isIdentifier(p)||h.isStringLiteral(p)||h.isNumericLiteral(p)?p.text:(h.isComputedPropertyName(p),null)}var O=class{repoRootAbs;knownFiles;configCache=new Map;configPathCache=new Map;constructor(e,t){this.repoRootAbs=y.resolve(e),this.knownFiles=t;}resolve(e,t){if(!t||!t.startsWith(".")&&!t.startsWith("/")&&!t.startsWith("@")&&!t.includes("/"))return null;let r=y.join(this.repoRootAbs,e),s=this.getParsedConfigForFile(r),i={fileExists:m=>F.existsSync(m),readFile:m=>{try{return F.readFileSync(m,"utf8")}catch{return}},directoryExists:m=>{try{return F.existsSync(m)&&F.statSync(m).isDirectory()}catch{return false}},getCurrentDirectory:()=>this.repoRootAbs,realpath:h.sys.realpath},n=s?.options||{moduleResolution:h.ModuleResolutionKind.NodeNext,jsx:h.JsxEmit.ReactJSX,allowJs:true},o=h.resolveModuleName(t,r,n,i).resolvedModule?.resolvedFileName;if(!o)return null;let l=this.toRepoRelative(o);if(!l)return null;let u=this.normalizeRel(l),f=this.pickKnownFile(u);if(!f)return null;let c=this.getConfigPathForFile(r),g=c&&this.toRepoRelative(c)||void 0;return {file:f,evidence:{fromFile:this.normalizeRel(e),specifier:t,resolvedFile:f,configFile:g}}}getConfigPathForFile(e){let t=y.dirname(e),r=this.configPathCache.get(t);if(r!==void 0)return r;let s=this.findNearestConfig(t);return this.configPathCache.set(t,s),s}getParsedConfigForFile(e){let t=this.getConfigPathForFile(e);if(!t)return null;let r=this.configCache.get(t);if(r!==void 0)return r;try{let s=h.readConfigFile(t,h.sys.readFile);if(s.error)return this.configCache.set(t,null),null;let i=h.parseJsonConfigFileContent(s.config,h.sys,y.dirname(t),void 0,t);return this.configCache.set(t,i),i}catch{return this.configCache.set(t,null),null}}findNearestConfig(e){let t=y.resolve(e),r=this.repoRootAbs;for(;;){let s=y.join(t,"tsconfig.json"),i=y.join(t,"jsconfig.json");if(F.existsSync(s))return s;if(F.existsSync(i))return i;if(t===r)break;let n=y.dirname(t);if(n===t||(t=n,!t.startsWith(r)))break}return null}toRepoRelative(e){let t=y.resolve(e);if(!t.startsWith(this.repoRootAbs))return null;let r=y.relative(this.repoRootAbs,t);return this.normalizeRel(r)}normalizeRel(e){return y.normalize(e).replace(/\\/g,"/")}pickKnownFile(e){if(this.knownFiles.has(e))return e;let t=e.replace(/\.(ts|tsx|js|jsx|mts|cts|mjs|cjs|d\.ts)$/,""),r=this.firstKnownByStem(t);if(r)return r;let s=this.firstKnownByStem(`${t}/index`);return s||null}firstKnownByStem(e){let t=[".ts",".tsx",".js",".jsx",".mts",".cts",".mjs",".cjs"];for(let r of t){let s=`${e}${r}`;if(this.knownFiles.has(s))return s}return null}};var ae=class extends A{codegenMap=new Map;tsResolver=null;coverage={tsFilesScanned:0,tsParseFailures:0,graphqlParseFailures:0,codegenFilesDetected:0,codegenFilesParsed:0,codegenExportsFound:0};constructor(e){super(e);}getName(){return "PagesAnalyzer"}async analyze(){this.log("Starting page analysis..."),await this.loadCodegenMapping();let e=await this.findPageFiles();this.coverage.tsFilesScanned+=e.length,this.log(`Found ${e.length} page files`);let t=50,r=new Map;for(let n=0;n<e.length;n+=t){let a=e.slice(n,n+t),o=await Promise.all(a.map(async l=>{try{let u=await T.readFile(l,"utf-8");return {filePath:l,content:u}}catch{return null}}));for(let l of o)l&&r.set(l.filePath,l.content);}let i=(await S(e,async n=>{let a=r.get(n);if(!a)return null;let o=this.detectPagesRoot(n);return this.analyzePageFile(n,a,o)},8)).filter(n=>n!==null);return this.log(`Analyzed ${i.length} pages successfully`),{pages:i,coverage:this.coverage}}async loadCodegenMapping(){let e=await j(["**/__generated__/graphql.ts","**/__generated__/gql.ts","**/generated/graphql.ts","**/generated/gql.ts","**/*.generated.ts","**/graphql.ts"],{cwd:this.basePath,ignore:["**/node_modules/**","**/.next/**","**/dist/**","**/build/**"],absolute:true});for(let t of e)try{let r=await T.readFile(t,"utf-8"),s=y.relative(this.basePath,t);if(!r.includes("Document")||!r.includes("definitions"))continue;this.coverage.codegenFilesDetected+=1;let i=k(r,s);this.coverage.codegenFilesParsed+=1,this.coverage.codegenExportsFound+=i.length;for(let n of i)this.codegenMap.set(n.documentName,{operationName:n.operationName,operationType:n.operationType});i.length>0&&this.log(`Loaded ${i.length} codegen mappings from ${s}`);}catch{}}analyzePageFile(e,t,r){try{let s=e.endsWith(".tsx")||e.endsWith(".jsx"),i=parseSync(t,{syntax:e.endsWith(".ts")||e.endsWith(".tsx")?"typescript":"ecmascript",tsx:s,jsx:s,comments:!1}),n=y.relative(r,e),a=this.filePathToRoutePath(n),o=this.findPageComponent(i,t);if(!o)return null;let l=this.extractRouteParams(a),u=this.extractImports(i),f=this.extractLayout(i,t),c=this.extractAuthRequirement(i,t,e),g=this.extractPermissions(t),m=this.extractDataFetching(i,t,u),x=this.extractLinkedPages(i,t),C=this.extractNavigation(t),I=this.extractSteps(t);return {path:a,filePath:n,component:o,params:l,layout:f,authentication:c,permissions:g,dataFetching:m,navigation:C,linkedPages:x,steps:I.length>0?I:void 0}}catch{return this.coverage.tsParseFailures+=1,null}}async findPageFiles(){let e=this.getSetting("pagesDir","src/pages"),t=[],s=[...new Set([e,"pages","src/pages","app","src/app"])];for(let n of s){if(n==="app"||n==="src/app"){let o=["controllers","models","views","helpers"],l=this.resolvePath(n);if(o.some(f=>{try{return F.existsSync(y.join(l,f))}catch{return false}}))continue}let a=this.resolvePath(n);try{let l=n==="app"||n==="src/app"||n.endsWith("/app")?["**/page.{tsx,ts,jsx,js}"]:["**/*.tsx","**/*.ts","**/*.jsx","**/*.js"],u=await j(l,{cwd:a,ignore:["_app.tsx","_app.ts","_app.jsx","_app.js","_document.tsx","_document.ts","_error.tsx","api/**","**/*.test.*","**/*.spec.*","**/node_modules/**","**/components/pages/**"],absolute:!0});t.push(...u),u.length>0&&this.log(`Found ${u.length} pages in ${n}`);}catch{}}let i=["frontend/src/**/pages","app/javascript/**/pages"];for(let n of i)try{let a=await j([`${n}/**/*.tsx`,`${n}/**/*.ts`,`${n}/**/*.jsx`,`${n}/**/*.js`],{cwd:this.basePath,ignore:["**/*.test.*","**/*.spec.*","**/node_modules/**","**/components/pages/**"],absolute:!0});t.push(...a);}catch{}if(t.length===0){let n=await this.findSPARoutes();n.length>0&&(this.log(`Found ${n.length} SPA routes from App.tsx`),t.push(...n));}return [...new Set(t)]}async findSPARoutes(){let e=[];if(!this.tsResolver)try{let r=await j(["**/*.{ts,tsx,js,jsx}"],{cwd:this.basePath,ignore:["**/node_modules/**","**/.next/**","**/dist/**","**/build/**"],absolute:!1,onlyFiles:!0,unique:!0,dot:!1});this.tsResolver=new O(this.basePath,new Set(r.map(s=>s.replace(/\\/g,"/"))));}catch{this.tsResolver=null;}let t=["src/App.tsx","src/App.jsx","src/App.js","App.tsx","App.jsx","App.js"];for(let r of t){let s=this.resolvePath(r);if(F.existsSync(s))try{let i=await T.readFile(s,"utf-8");if(!i.includes("react-router")&&!i.includes("Route"))continue;let n=parseSync(i,{syntax:"typescript",tsx:!0}),a=this.extractImports(n);this.traverseNode(n,o=>{if(o.type==="JSXOpeningElement"){let l=this.getJsxTagName(o);if(l==="Route"||l==="PrivateRoute"){let u=this.getJsxAttribute(o,"component"),f=this.getJsxAttribute(o,"element"),c=u||f,g=c?a.get(c):void 0;if(g){let m=this.resolveImportPath(s,g);m&&F.existsSync(m)&&e.push(m);}}}}),e.length>0&&e.push(s);}catch{}}return e}resolveImportPath(e,t){if(!t.startsWith(".")){let n=y.relative(this.basePath,e).replace(/\\/g,"/");if(this.tsResolver){let a=this.tsResolver.resolve(n,t);if(a)return y.join(this.basePath,a.file)}return null}let r=[".tsx",".ts",".jsx",".js","/index.tsx","/index.ts","/index.jsx","/index.js"],s=y.dirname(e),i=y.resolve(s,t);for(let n of r){let a=i+n;if(F.existsSync(a))return a}if(F.existsSync(i)&&F.statSync(i).isDirectory())for(let n of ["/index.tsx","/index.ts","/index.jsx","/index.js"]){let a=i+n;if(F.existsSync(a))return a}return null}detectPagesRoot(e){let t=["/src/pages/","/pages/","/src/app/","/app/","/frontend/src/pages/","/app/javascript/pages/"];for(let r of t){let s=e.indexOf(r);if(s!==-1)return e.substring(0,s+r.length-1)}return this.basePath}filePathToRoutePath(e){let t=e.replace(/\\/g,"/").replace(/\.(tsx?|jsx?)$/,"");return t=t.replace(/\/page$/,""),t=t.replace(/\/route$/,""),"/"+t.split("/").filter(Boolean).map(n=>n.replace(/^\(\.\.\.\)|^\(\.\.\)|^\(\.\)/,"")).filter(n=>!(n.startsWith("(")&&n.endsWith(")")||n.startsWith("@"))).join("/").replace(/\/index$/,"").replace(/\[\[\.\.\.(\w+)\]\]/g,"*").replace(/\[\.\.\.(\w+)\]/g,"*").replace(/\[(\w+)\]/g,":$1")}extractRouteParams(e){let t=[],r=e.match(/:(\w+)/g);if(r)for(let s of r)t.push(s.slice(1));return t}findPageComponent(e,t){let r=this.findMainJsxComponent(e,t);if(r&&r!=="Page"&&r!=="default")return r;for(let s of e.body){if(s.type==="ExportDefaultDeclaration"){let i=s.decl;if(i?.type==="FunctionExpression"&&i.identifier?.value){let n=i.identifier.value;if(n!=="Page")return n}if(i?.type==="Identifier"){let n=i.value;if(n!=="Page")return n}if(i?.type==="ArrowFunctionExpression")return r||"default"}if(s.type==="ExportDefaultExpression"){let i=s.expression;if(i?.type==="Identifier"){let n=i.value;if(n!=="Page")return n}}}if(r)return r;for(let s of e.body)if(s.type==="VariableDeclaration"){for(let i of s.declarations)if(i.id?.type==="Identifier"&&i.id.value==="Page")return "Page"}for(let s of e.body)if(s.type==="ExportDeclaration"&&s.declaration?.type==="FunctionDeclaration"){let i=s.declaration.identifier?.value;if(i&&/^[A-Z]/.test(i))return i}for(let s of e.body){if(s.type==="FunctionDeclaration"){let i=s.identifier?.value;if(i&&/^[A-Z]/.test(i))return i}if(s.type==="VariableDeclaration"){for(let i of s.declarations)if(i.id?.type==="Identifier"){let n=i.id.value;if(n&&/^[A-Z]/.test(n)&&t.includes("return")&&t.includes("<"))return n}}}return null}findMainJsxComponent(e,t){let r=this.extractImports(e),s=new Set;for(let[a,o]of r)/^[A-Z]/.test(a)&&(o.includes("features")||o.includes("components")||o.includes("containers"))&&s.add(a);let i=[];for(let a of s){let o=new RegExp(`<${a}[\\s/>]`,"g"),l;for(;(l=o.exec(t))!==null;)i.push({name:a,index:l.index});}let n=i.find(a=>a.name.includes("Container")||a.name.includes("Page")||a.name.includes("View")||a.name.includes("Screen"));return n?n.name:i.length>0?(i.sort((a,o)=>a.index-o.index),i[0].name):null}extractImports(e){let t=new Map;for(let r of e.body)if(r.type==="ImportDeclaration"){let s=r.source?.value||"";for(let i of r.specifiers||[])i.type==="ImportSpecifier"&&i.local?.value&&t.set(i.local.value,s),i.type==="ImportDefaultSpecifier"&&i.local?.value&&t.set(i.local.value,s);}return t}extractLayout(e,t){if(t.includes("getLayout")){let r=t.match(/getLayout\s*=.*?<(\w+Layout|\w+Shell)/);if(r)return r[1]}}extractAuthRequirement(e,t,r){let s=y.basename(r),a={required:!["404.tsx","permission-denied.tsx","_app.tsx","_document.tsx","_error.tsx"].some(l=>s===l)},o=["RequiredCondition","ProtectedRoute","AuthGuard","PrivateRoute","WithAuth","RequireAuth","Authenticated","Authorized"];for(let l of o)if(t.includes(`<${l}`)){a.condition="Additional permissions required";let u=this.extractRolesFromContent(t);u.length>0&&(a.roles=u);break}return a}extractRolesFromContent(e){let t=[];this.traverseNode({content:e},()=>{});let r=e.matchAll(/(\w+Role|\w+Permission)\.(\w+)/g);for(let s of r)t.push(s[2]);return [...new Set(t)]}extractPermissions(e){let t=[],r=e.matchAll(/(?:Permission|Role|isAdmin)\.\w+/g);for(let s of r)t.includes(s[0])||t.push(s[0]);return t}extractDataFetching(e,t,r){let s=[],i=new Set,n=new Map;for(let[l,u]of this.codegenMap)n.set(l,{operationName:u.operationName,type:u.operationType});let a=H(e,t,n),o=this.getGraphQLHookPatterns();if(M(e,l=>{if(l.type==="CallExpression"){let u=l,f=v(u.callee);if(!f)return;if($(f,o)&&ne(u,t,a)){let c=U(u,t,a),m={type:D(f,o),operationName:c||"unknown"},x=this.extractVariablesFromCall(u);Object.keys(x).length>0&&(m.variables=x);let C=`${m.type}:${m.operationName}`;i.has(C)||(i.add(C),s.push(m));}if(f==="query"||f==="mutate"){let c=this.analyzeClientDirectCall(u,t,a);if(c){let g=`${c.type}:${c.operationName}`;i.has(g)||(i.add(g),s.push(c));}}}}),this.extractSSRDataFetching(e,t,s,i),t.includes("getStaticProps")){let l="getStaticProps:getStaticProps";i.has(l)||(i.add(l),s.push({type:"getStaticProps",operationName:"getStaticProps"}));}return s}analyzeClientDirectCall(e,t,r){if(!e.arguments?.length)return null;let s=e.arguments[0],i=s?.expression||s;if(i?.type!=="ObjectExpression")return null;for(let n of i.properties||[])if(n.type==="KeyValueProperty"&&n.key?.type==="Identifier"&&n.key.value==="query"){let a=n.value,o=null;if(a?.type==="Identifier"){let l=a.value;o=r.variableOperations.get(l)||r.documentImports.get(l)||d(l);}if(a?.type==="MemberExpression"){let l=a.object?.type==="Identifier"?a.object.value:null,u=a.property?.type==="Identifier"?a.property.value:null;if(l&&u){let f=`${l}.${u}`;o=r.staticPropertyOperations.get(f)||d(u);}}if(o)return {type:v(e.callee)==="mutate"?"useMutation":"useQuery",operationName:o}}return null}extractDocumentImports(e){let t=new Map;for(let r of e.body)if(r.type==="ImportDeclaration"){let s=r.source?.value||"",i=s.includes("__generated__")||s.includes("generated")||s.includes("graphql")||s.includes(".generated");for(let n of r.specifiers||[]){let a=n.type==="ImportSpecifier"||n.type==="ImportDefaultSpecifier"?n.local?.value:null;if(a){if(a.endsWith("Document")||i){let o=a.replace(/Document$/,"");t.set(a,o);}(a.endsWith("Query")||a.endsWith("Mutation"))&&t.set(a,a.replace(/Query$|Mutation$/,""));}}}return t}extractVariableAssignments(e,t){let r=new Map;return this.traverseNode(e,s=>{if(s.type==="VariableDeclarator"&&s.id?.type==="Identifier"){let i=s.id.value,n=s.init;if(!n)return;if(n.type==="Identifier"){let a=n.value;(a.endsWith("Document")||a.endsWith("Query"))&&r.set(i,a);}if(n.type==="CallExpression"){let a=this.getCalleeName(n.callee);if(a==="gql"||a==="graphql"){let o=this.extractOperationNameFromGqlCall(n,t);o&&r.set(i,o);}}if(n.type==="TaggedTemplateExpression"){let a=this.getCalleeName(n.tag);if(a==="gql"||a==="graphql"){let o=n.template;if(o?.quasis?.[0]?.raw){let u=o.quasis[0].raw.match(/(?:query|mutation|subscription)\s+(\w+)/i);u&&r.set(i,u[1]);}}}}}),r}extractOperationNameFromGqlCall(e,t){if(!e.arguments?.length)return null;let r=e.arguments[0],s=r?.expression||r;if(s?.type==="TemplateLiteral"&&s.quasis?.[0]?.raw){let n=s.quasis[0].raw.match(/(?:query|mutation|subscription)\s+(\w+)/i);if(n)return n[1]}if(e.span){let n=t.slice(e.span.start,e.span.end).match(/(?:query|mutation|subscription)\s+(\w+)/i);if(n)return n[1]}return null}analyzeGraphQLHookCall(e,t,r,s){let i=this.getCalleeName(e.callee);if(!i)return null;let n=this.getGraphQLHookPatterns(),a=z.includes(i),o=R(i,n)&&!i.includes("Params"),l=Q(i,n);if(!a&&!o&&!l)return null;let u=D(i,n),f=i.replace(/^use/,"").replace(/Query$|Mutation$/,""),c=this.extractTypeGeneric(e,t);if(c&&(f=c.replace(/Query$|Mutation$|Variables$/,"")),e.arguments&&e.arguments.length>0){let m=e.arguments[0],x=m?.expression||m,C=this.extractOperationFromArgument(x,r,s);C&&(f=C);}let g=this.extractVariablesFromCall(e);return {type:u,operationName:f,variables:g}}extractTypeGeneric(e,t){if(e.typeArguments?.params?.length>0){let r=e.typeArguments.params[0];if(r?.type==="TsTypeReference"&&r.typeName?.type==="Identifier")return r.typeName.value}if(e.callee?.span){let r=e.callee.span.end,i=t.slice(r,r+100).match(/^<(\w+)(?:Query|Mutation|Variables)?[,>]/);if(i)return i[1]}return null}extractOperationFromArgument(e,t,r){if(!e)return null;if(e.type==="Identifier"){let s=e.value;if(["[","{","'",'"',"`"].some(o=>s.startsWith(o)))return null;let i=r.get(s);if(i)return !i.endsWith("Document")&&!i.endsWith("Query")?i:t.get(i)||i.replace(/Document$/,"");let n=t.get(s);if(n)return n;let a=this.codegenMap.get(s);return a?a.operationName:/^(Query|Mutation|QUERY|MUTATION)$/i.test(s)?null:s.replace(/Document$/,"").replace(/Query$|Mutation$/,"")}if(e.type==="MemberExpression"&&e.property?.type==="Identifier")return e.property.value.replace(/Document$/,"").replace(/Query$|Mutation$/,"");if(e.type==="TaggedTemplateExpression"&&e.template?.quasis?.[0]?.raw){let i=e.template.quasis[0].raw.match(/(?:query|mutation|subscription)\s+(\w+)/i);if(i)return i[1]}if(e.type==="CallExpression"){let s=this.getCalleeName(e.callee);if((s==="graphql"||s==="gql")&&e.arguments?.length>0){let i=e.arguments[0],n=i?.expression||i;if(n?.type==="TemplateLiteral"&&n.quasis?.[0]?.raw){let o=n.quasis[0].raw.match(/(?:query|mutation|subscription)\s+(\w+)/i);if(o)return o[1]}}}if(e.type==="TemplateLiteral"&&e.quasis?.[0]?.raw){let i=e.quasis[0].raw.match(/(?:query|mutation|subscription)\s+(\w+)/i);if(i)return i[1]}return null}extractVariablesFromCall(e){let t=[];if(e.arguments&&e.arguments.length>1){let r=e.arguments[1],s=r?.expression||r;if(s?.type==="ObjectExpression"){for(let i of s.properties||[])if(i.type==="KeyValueProperty"&&i.key?.type==="Identifier"&&i.key.value==="variables"&&i.value?.type==="ObjectExpression")for(let n of i.value.properties||[])n.type==="KeyValueProperty"&&n.key?.type==="Identifier"?t.push(n.key.value):n.type==="Identifier"&&t.push(n.value);}}return t}extractSSRDataFetching(e,t,r,s){let i=this.extractImports(e),n=this.extractDocumentImports(e);for(let a of e.body)if(a.type==="ExportDeclaration"){let o=a.declaration;if(o?.type==="VariableDeclaration")for(let l of o.declarations)l.id?.type==="Identifier"&&l.id.value==="getServerSideProps"&&this.extractSSRQueriesFromNode(l,t,i,n,r,s);o?.type==="FunctionDeclaration"&&o.identifier?.value==="getServerSideProps"&&this.extractSSRQueriesFromNode(o,t,i,n,r,s);}}extractSSRQueriesFromNode(e,t,r,s,i,n){M(e,a=>{if(a.type!=="CallExpression")return;let o=v(a.callee);if(o==="query"||o==="mutate"){let l=this.extractQueryFromClientCall(a,t,r,s);if(l){let u=`getServerSideProps:\u2192 ${l}`;n.has(u)||(n.add(u),i.push({type:"getServerSideProps",operationName:`\u2192 ${l}`}));}}});}extractQueryFromClientCall(e,t,r,s){if(!e.arguments?.length)return null;let i=e.arguments[0],n=i?.expression||i;if(n?.type!=="ObjectExpression")return null;for(let a of n.properties||[])if(a.type==="KeyValueProperty"&&a.key?.type==="Identifier"&&a.key.value==="query"){let o=a.value;if(o?.type==="Identifier"){let l=o.value;if(s.has(l))return s.get(l)||null;let u=this.codegenMap.get(l);return u?u.operationName:r.get(l)?d(l):d(l)}if(o?.type==="MemberExpression"){let l=o.object?.type==="Identifier"?o.object.value:null,u=o.property?.type==="Identifier"?o.property.value:null;if(l&&u)return `${l}.${u}`}}return null}extractNavigation(e){let t={visible:true,currentNavItem:null};(e.includes("hideNavigation")||e.includes("noNav"))&&(t.visible=false),(e.includes("miniNav")||e.includes("collapsedNav"))&&(t.mini=true);let r=e.match(/currentNav(?:Item)?[:\s=]+['"`]([^'"`]+)['"`]/);return r&&(t.currentNavItem=r[1]),t}extractLinkedPages(e,t){let r=[];return this.traverseNode(e,s=>{if(s.type==="JSXOpeningElement"&&this.getJsxTagName(s)==="Link"){let n=this.getJsxAttribute(s,"href");if(n&&n.startsWith("/")&&!n.includes("http")){let a=n.split("?")[0].split("#")[0];r.includes(a)||r.push(a);}}}),r}extractSteps(e){let t=[],r=e.matchAll(/(?:step|Step)\s*[:=]\s*['"`]([^'"`]+)['"`]/g),s=0;for(let i of r)t.push({id:s++,name:i[1]});return t}traverseNode(e,t){if(!(!e||typeof e!="object")){t(e);for(let r of Object.keys(e)){let s=e[r];if(Array.isArray(s))for(let i of s)this.traverseNode(i,t);else s&&typeof s=="object"&&this.traverseNode(s,t);}}}getCalleeName(e){if(e.type==="Identifier")return e.value;if(e.type==="MemberExpression"){let t=e.object,r=e.property;if(t.type==="Identifier"&&r.type==="Identifier")return `${t.value}.${r.value}`}return null}getJsxTagName(e){return e.name?.type==="Identifier"?e.name.value:null}getJsxAttribute(e,t){if(!e.attributes)return null;for(let r of e.attributes)if(r.type==="JSXAttribute"&&r.name?.value===t){if(r.value?.type==="StringLiteral")return r.value.value;if(r.value?.type==="JSXExpressionContainer"&&(r.value.expression?.type==="Identifier"||r.value.expression?.type==="StringLiteral"))return r.value.expression.value}return null}};var le=class extends A{coverage={tsFilesScanned:0,tsParseFailures:0,graphqlParseFailures:0,codegenFilesDetected:0,codegenFilesParsed:0,codegenExportsFound:0};constructor(e){super(e);}getName(){return "GraphQLAnalyzer"}async analyze(){this.log("Starting GraphQL analysis...");let e=[];this.log("[GraphQLAnalyzer] Step 1: Analyzing .graphql files...");let t=await this.analyzeGraphQLFiles();e.push(...t),this.log(`[GraphQLAnalyzer] Step 1 done: ${t.length} from .graphql files`),this.log("[GraphQLAnalyzer] Step 2: Analyzing inline GraphQL...");let r=await this.analyzeInlineGraphQL();e.push(...r),this.log(`[GraphQLAnalyzer] Step 2 done: ${r.length} inline operations`),this.log("[GraphQLAnalyzer] Step 3: Analyzing codegen output...");let s=await this.analyzeCodegenGenerated();e.push(...s),this.log(`[GraphQLAnalyzer] Step 3 done: ${s.length} from codegen`);let i=this.deduplicateOperations(e);return this.log(`[GraphQLAnalyzer] Deduplicated: ${i.length} unique operations`),this.log("[GraphQLAnalyzer] Step 4: Finding operation usage..."),await this.findOperationUsage(i),this.log("[GraphQLAnalyzer] Step 4 done"),this.log(`Found ${i.length} GraphQL operations`),{graphqlOperations:i,coverage:this.coverage}}deduplicateOperations(e){let t=new Map;for(let r of e)if(!t.has(r.name))t.set(r.name,r);else {let s=t.get(r.name);if(s)for(let i of r.usedIn)s.usedIn.includes(i)||s.usedIn.push(i);}return Array.from(t.values())}async analyzeCodegenGenerated(){let e=[],t=await j(["**/__generated__/graphql.ts","**/__generated__/gql.ts","**/generated/graphql.ts","**/generated/gql.ts","**/*.generated.ts","**/*.generated.tsx","**/graphql/generated.ts","**/gql/generated.ts"],{cwd:this.basePath,ignore:["**/node_modules/**","**/.next/**","**/dist/**","**/build/**"],absolute:true});for(let r of t)try{let s=await T.readFile(r,"utf-8"),i=y.relative(this.basePath,r);if(!s.includes("Document")||!s.includes("definitions"))continue;this.coverage.codegenFilesDetected+=1;let n=k(s,i);this.coverage.codegenFilesParsed+=1,this.coverage.codegenExportsFound+=n.length;for(let a of n){let l=a.document?.definitions?.[0];if(!l||l.kind!=="OperationDefinition")continue;let u=(l.variableDefinitions||[]).map(f=>({name:f.variable?.name?.value||"unknown",type:this.extractTypeFromAst(f.type),required:f.type?.kind==="NonNullType"}));e.push({name:a.operationName,type:a.operationType,filePath:i,usedIn:[],variables:u,returnType:this.inferReturnTypeFromAst(l),fragments:this.extractFragmentReferencesFromAst(l),fields:this.extractFieldsFromAst(l.selectionSet),variableNames:[a.documentName]});}n.length>0&&this.log(`Found ${n.length} operations in codegen output: ${i}`);}catch(s){this.warn(`Failed to analyze codegen file ${r}: ${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 r=[];for(let s of e.selections)if(s.kind==="Field"){let i={name:s.name?.value||"unknown"};if(s.arguments?.length>0){let n=s.arguments.map(a=>a.name?.value).join(", ");i.type=`(${n})`;}s.selectionSet&&(i.fields=this.extractFieldsFromAst(s.selectionSet,t+1)),r.push(i);}else if(s.kind==="FragmentSpread")r.push({name:`...${s.name?.value}`,type:"fragment"});else if(s.kind==="InlineFragment"){let i=s.typeCondition?.name?.value||"inline";r.push({name:`... on ${i}`,type:"inline-fragment",fields:this.extractFieldsFromAst(s.selectionSet,t+1)});}return r}extractFragmentReferencesFromAst(e){let t=[],r=s=>{if(s&&(s.kind==="FragmentSpread"&&t.push(s.name?.value),s.selectionSet?.selections))for(let i of s.selectionSet.selections)r(i);};return r(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 j(["**/*.graphql"],{cwd:this.basePath,ignore:["**/node_modules/**","**/.next/**"],absolute:true});return (await S(e,async r=>{let s=await T.readFile(r,"utf-8");try{let i=parse(s);return this.extractOperationsFromDocument(i,y.relative(this.basePath,r))}catch{return this.coverage.graphqlParseFailures+=1,[]}})).flat()}async analyzeInlineGraphQL(){let e=[],t=await j(["**/*.ts","**/*.tsx","**/*.js","**/*.jsx"],{cwd:this.basePath,ignore:["**/node_modules/**","**/.next/**","**/__tests__/**","**/*.test.*","**/*.spec.*","**/__generated__/**"],absolute:true});this.coverage.tsFilesScanned+=t.length;let r=50;for(let s=0;s<t.length;s+=r){let i=t.slice(s,s+r),n=await S(i,async a=>{try{let o=await T.readFile(a,"utf-8");if(!o.includes("gql")&&!o.includes("graphql"))return [];let l=y.relative(this.basePath,a),u=a.endsWith(".tsx")||a.endsWith(".jsx"),f=parseSync(o,{syntax:a.endsWith(".ts")||a.endsWith(".tsx")?"typescript":"ecmascript",tsx:u,jsx:u});return this.analyzeModuleForGraphQL(f,o,l)}catch{return this.coverage.tsParseFailures+=1,[]}},10);e.push(...n.flat());}return e}analyzeModuleForGraphQL(e,t,r){let s=[],i=[];return this.traverseNodeWithContext(e,i,(n,a)=>{if(n.type==="TaggedTemplateExpression"){let o=n,l=this.getTagName(o.tag);if(l==="gql"||l==="graphql"){let u=this.extractTemplateContent(o.template,t);if(u)try{let f=parse(u),c=this.extractOperationsFromDocument(f,r);if(a)for(let g of c)g.variableNames=g.variableNames||[],g.variableNames.push(a),g.variableNames.push(`${g.name}Document`);s.push(...c);}catch{this.coverage.graphqlParseFailures+=1;}}}if(n.type==="CallExpression"){let o=n,l=this.getCalleeName(o.callee);if((l==="gql"||l==="graphql")&&o.arguments.length>0){let u=o.arguments[0].expression,f=this.extractGraphQLFromExpression(u,t);if(f)try{let c=parse(f),g=this.extractOperationsFromDocument(c,r);if(a)for(let m of g)m.variableNames=m.variableNames||[],m.variableNames.push(a),m.variableNames.push(`${m.name}Document`);s.push(...g);}catch{this.coverage.graphqlParseFailures+=1;}}}}),s}traverseNodeWithContext(e,t,r){if(!e||typeof e!="object")return;let s=false;e.type==="VariableDeclarator"&&e.id?.type==="Identifier"&&(t.push(e.id.value),s=true),r(e,t.length>0?t[t.length-1]:null);for(let i of Object.keys(e)){let n=e[i];if(Array.isArray(n))for(let a of n)this.traverseNodeWithContext(a,t,r);else n&&typeof n=="object"&&this.traverseNodeWithContext(n,t,r);}s&&t.pop();}getTagName(e){return e.type==="Identifier"?e.value:null}getCalleeName(e){return e.type==="Identifier"?e.value:null}extractTemplateContent(e,t){if(e.type==="TemplateLiteral"){if(e.quasis.length===1&&e.expressions.length===0)return e.quasis[0].raw;let r=e.span.start,s=e.span.end;return t.slice(r,s).slice(1,-1).replace(/\$\{[^}]*\}/g,"")}return null}extractGraphQLFromExpression(e,t){return e.type==="TemplateLiteral"?this.extractTemplateContent(e,t):e.type==="StringLiteral"?e.value:null}extractOperationsFromDocument(e,t){let r=[];for(let s of e.definitions){let i=this.extractOperation(s,t);i&&r.push(i);}return r}extractOperation(e,t){if(e.kind==="OperationDefinition"){let r=e.name?.value||"anonymous",s=e.operation,i=this.extractVariables(e),n=this.extractFragmentReferences(e),a=this.extractFields(e),o=e.loc?getLocation(e.loc.source,e.loc.start):null;return {name:r,type:s,filePath:t,line:o?.line,column:o?.column,usedIn:[],variables:i,returnType:this.inferReturnType(e),fragments:n,fields:a}}if(e.kind==="FragmentDefinition"){let r=e.loc?getLocation(e.loc.source,e.loc.start):null;return {name:e.name.value,type:"fragment",filePath:t,line:r?.line,column:r?.column,usedIn:[],variables:[],returnType:e.typeCondition.name.value,fragments:this.extractFragmentReferences(e),fields:this.extractFields(e)}}return null}extractFields(e){let t=[],r=(s,i=0)=>{if(!s||!s.selections||i>5)return [];let n=[];for(let a of s.selections)if(a.kind==="Field"){let o={name:a.name.value};if(a.arguments&&a.arguments.length>0){let l=a.arguments.map(u=>u.name.value).join(", ");o.type=`(${l})`;}a.selectionSet&&(o.fields=r(a.selectionSet,i+1)),n.push(o);}else if(a.kind==="FragmentSpread")n.push({name:`...${a.name.value}`,type:"fragment"});else if(a.kind==="InlineFragment"&&a.selectionSet){let o=a.typeCondition?.name?.value||"inline";n.push({name:`... on ${o}`,type:"inline-fragment",fields:r(a.selectionSet,i+1)});}return n};return e.selectionSet?r(e.selectionSet):t}extractVariables(e){let t=[];if(e.variableDefinitions)for(let r of e.variableDefinitions){let s=r.variable.name.value,i=this.typeNodeToString(r.type),n=r.type.kind==="NonNullType";t.push({name:s,type:i,required:n});}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=[],r=s=>{if(s&&(s.kind==="FragmentSpread"&&t.push(s.name.value),s.selectionSet))for(let i of s.selectionSet.selections)r(i);};return r(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=this.getGraphQLHookPatterns(),r=await j(["**/*.ts","**/*.tsx"],{cwd:this.basePath,ignore:["**/node_modules/**","**/.next/**","**/__generated__/**","**/dist/**","**/build/**"],absolute:true}),s=new Map,i=new Map,n=new Map,a=new Map;for(let c of e)if(s.set(c.name,c),i.set(`${c.name}Document`,c),a.set(`${c.name}Query`,c),a.set(`${c.name}Mutation`,c),a.set(`${c.name}Subscription`,c),a.set(`${c.name}QueryVariables`,c),a.set(`${c.name}MutationVariables`,c),c.variableNames)for(let g of c.variableNames)n.set(g,c);let o=new Set;for(let c of e)if(o.add(c.name),o.add(`${c.name}Document`),o.add(`${c.name}Query`),o.add(`${c.name}Mutation`),o.add(`${c.name}Subscription`),c.variableNames)for(let g of c.variableNames)o.add(g);let l=null,u=Array.from(o);if(u.length>0&&u.length<2e3){let c=u.sort((g,m)=>m.length-g.length).map(g=>g.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"));l=new RegExp(`\\b(${c.join("|")})\\b`,"g");}let f=50;for(let c=0;c<r.length;c+=f){let g=r.slice(c,c+f);await Promise.all(g.map(async m=>{try{let x=await T.readFile(m,"utf-8"),C=y.relative(this.basePath,m);if(!W(x))return;if(l){let I=new Set,J;for(;(J=l.exec(x))!==null;)I.add(J[1]);l.lastIndex=0;for(let ye of I){let q=i.get(ye);q&&C!==q.filePath&&(q.usedIn.includes(C)||q.usedIn.push(C));}}await this.findUsageWithAST(x,m,C,s,a,n,t);}catch{}}));}}async findUsageWithAST(e,t,r,s,i,n,a){try{let o=t.endsWith(".tsx")||t.endsWith(".jsx"),l=parseSync(e,{syntax:t.endsWith(".ts")||t.endsWith(".tsx")?"typescript":"ecmascript",tsx:o,jsx:o,comments:!1});this.traverseNodeForUsage(l,e,u=>{if(u.type==="CallExpression"){let f=this.getCalleeNameForUsage(u.callee);if(f&&$(f,a)){let c=this.extractTypeGenericFromCall(u,e);if(c){let m=i.get(c)||s.get(c.replace(/Query$|Mutation$|Variables$/,""));m&&r!==m.filePath&&(m.usedIn.includes(r)||m.usedIn.push(r));}let g=this.extractFirstArgName(u);if(g){let m=g.replace(/Document$/,""),x=n.get(g)||n.get(m)||s.get(m)||i.get(g);x&&r!==x.filePath&&(x.usedIn.includes(r)||x.usedIn.push(r));}}}});}catch{}}traverseNodeForUsage(e,t,r){if(!(!e||typeof e!="object")){r(e);for(let s of Object.keys(e)){let i=e[s];if(Array.isArray(i))for(let n of i)this.traverseNodeForUsage(n,t,r);else i&&typeof i=="object"&&this.traverseNodeForUsage(i,t,r);}}}getCalleeNameForUsage(e){return e?e.type==="Identifier"?e.value:e.type==="MemberExpression"&&e.property?.type==="Identifier"?e.property.value:null:null}extractTypeGenericFromCall(e,t){if(e.typeArguments?.params?.length>0){let r=e.typeArguments.params[0];if(r?.type==="TsTypeReference"&&r.typeName?.type==="Identifier")return r.typeName.value}if(e.callee?.span){let r=e.callee.span.end,i=t.slice(r,r+150).match(/^<\s*(\w+)(?:Query|Mutation|Variables|Subscription)?(?:\s*,|\s*>)/);if(i)return i[1]}return null}extractFirstArgName(e){if(e.arguments?.length>0){let t=e.arguments[0].expression;if(t?.type==="Identifier")return t.value;if(t?.type==="MemberExpression"&&t.property?.type==="Identifier")return t.property.value}return null}};var ce=class extends A{componentCache=new Map;coverage={tsFilesScanned:0,tsParseFailures:0,graphqlParseFailures:0,codegenFilesDetected:0,codegenFilesParsed:0,codegenExportsFound:0};constructor(e){super(e);}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,coverage:this.coverage}}async analyzeComponents(){let e=[],t=[this.getSetting("featuresDir",""),this.getSetting("componentsDir",""),this.getSetting("pagesDir","")].filter(Boolean),r=["src/features","src/components","src/common/components","src/common","src/pages","src/app","src/modules","src/views","src/screens","components","pages","app"],i=[...new Set([...t,...r])].flatMap(o=>[`${o}/**/*.tsx`,`${o}/**/*.ts`]),n=await j(i,{cwd:this.basePath,ignore:["**/*.test.*","**/*.spec.*","**/*.stories.*","**/node_modules/**","**/__generated__/**"],absolute:true,onlyFiles:true,unique:true});this.log(`[DataFlowAnalyzer] Found ${n.length} component files to analyze`),this.coverage.tsFilesScanned+=n.length;let a=50;for(let o=0;o<n.length;o+=a){let l=n.slice(o,o+a),u=await Promise.all(l.map(async f=>{try{let c=await T.readFile(f,"utf-8");return {filePath:f,content:c}}catch{return null}}));for(let f of u)if(f)try{let c=parseSync(f.content,{syntax:"typescript",tsx:!0,comments:!1}),g=y.relative(this.basePath,f.filePath),m=this.analyzeComponentFile(c,g,f.content);e.push(...m);}catch{this.coverage.tsParseFailures+=1;}}return this.log(`[DataFlowAnalyzer] Extracted ${e.length} components`),this.buildDependencyGraph(e),e}analyzeComponentFile(e,t,r){let s=[],i=this.extractImports(e);for(let n of e.body){if(n.type==="ExportDeclaration"&&n.declaration?.type==="FunctionDeclaration"){let a=n.declaration.identifier?.value;if(a&&this.isComponentName(a)){let o=this.extractComponentInfo(a,t,r,i);s.push(o),this.componentCache.set(a,o);}}if(n.type==="FunctionDeclaration"){let a=n.identifier?.value;if(a&&this.isComponentName(a)){let o=this.extractComponentInfo(a,t,r,i);s.push(o),this.componentCache.set(a,o);}}if(n.type==="ExportDefaultDeclaration"&&n.decl?.type==="FunctionExpression"){let a=n.decl.identifier?.value;if(a&&this.isComponentName(a)){let o=this.extractComponentInfo(a,t,r,i);s.push(o),this.componentCache.set(a,o);}}if(n.type==="VariableDeclaration"){for(let a of n.declarations)if(a.id?.type==="Identifier"){let o=a.id.value;if(o&&(this.isComponentName(o)||o.startsWith("use"))&&a.init&&(a.init.type==="ArrowFunctionExpression"||a.init.type==="FunctionExpression")){let l=this.extractComponentInfo(o,t,r,i);s.push(l),this.componentCache.set(o,l);}}}if(n.type==="ExportDeclaration"&&n.declaration?.type==="VariableDeclaration"){for(let a of n.declaration.declarations)if(a.id?.type==="Identifier"){let o=a.id.value;if(o&&(this.isComponentName(o)||o.startsWith("use"))&&a.init&&(a.init.type==="ArrowFunctionExpression"||a.init.type==="FunctionExpression")){let l=this.extractComponentInfo(o,t,r,i);s.push(l),this.componentCache.set(o,l);}}}}return s}extractImports(e){let t=new Map,r=this.getListSetting("aliasPrefixes",["@/","~/","#/"]);for(let s of e.body)if(s.type==="ImportDeclaration"){let i=s.source?.value||"",n=r.some(a=>i.startsWith(a));if(i.startsWith(".")||n)for(let a of s.specifiers||[])a.type==="ImportSpecifier"&&a.local?.value&&t.set(a.local.value,i),a.type==="ImportDefaultSpecifier"&&a.local?.value&&t.set(a.local.value,i);}return t}isComponentName(e){return /^[A-Z][a-zA-Z0-9]*$/.test(e)}extractComponentInfo(e,t,r,s){let i="presentational";["/pages/","/app/","/routes/","/views/","/screens/"].some(f=>t.includes(f))?i="page":e.includes("Container")||e.includes("Provider")?i="container":e.includes("Layout")||e.includes("Shell")||e.includes("Wrapper")||e.includes("Frame")||e.includes("Scaffold")||t.includes("/layouts/")||t.includes("/layout/")?i="layout":e.startsWith("use")&&(i="hook");let a=this.extractHooksUsed(r),o=Array.from(s.keys()).filter(f=>this.isComponentName(f)||f.startsWith("use")),l=[];for(let[f,c]of s)l.push({name:f,path:c});let u=this.extractStateManagement(r);return {name:e,filePath:t,type:i,props:[],dependencies:o,dependents:[],hooks:a,stateManagement:u,imports:l}}extractHooksUsed(e){let t=[],r=new Set;if(!e.includes("use"))return t;try{let s=parseSync(e,{syntax:"typescript",tsx:!0,comments:!1}),i=this.extractDocumentImportsFromAst(s),n=this.extractVariableOperationMap(s,e);this.traverseForHooks(s,e,i,n,t,r);}catch{this.extractHooksWithRegex(e,t,r);}return t}extractDocumentImportsFromAst(e){let t=new Map;for(let r of e.body)if(r.type==="ImportDeclaration"){let s=r.source?.value||"",i=s.includes("__generated__")||s.includes("generated")||s.includes("graphql")||s.includes(".generated");for(let n of r.specifiers||[]){let a;(n.type==="ImportSpecifier"||n.type==="ImportDefaultSpecifier")&&(a=n.local?.value),a&&((a.endsWith("Document")||i)&&t.set(a,a.replace(/Document$/,"")),(a.endsWith("Query")||a.endsWith("Mutation"))&&t.set(a,a.replace(/Query$|Mutation$/,"")));}}return t}extractVariableOperationMap(e,t){let r=new Map,s=n=>{if(n.type!=="VariableDeclarator"||n.id?.type!=="Identifier")return;let a=n.id.value,o=n.init;if(o){if(o.type==="CallExpression"){let l=this.getCalleeNameFromNode(o.callee);if(l==="gql"||l==="graphql"){let u=this.extractOperationNameFromGqlCall(o,t);u&&r.set(a,u);}}if(o.type==="TaggedTemplateExpression"){let l=this.getCalleeNameFromNode(o.tag);if((l==="gql"||l==="graphql")&&o.template?.quasis?.[0]?.raw){let f=o.template.quasis[0].raw.match(/(?:query|mutation|subscription)\s+(\w+)/i);f&&r.set(a,f[1]);}}}},i=n=>{if(!(!n||typeof n!="object")){s(n);for(let a of Object.keys(n)){let o=n[a];if(Array.isArray(o))for(let l of o)i(l);else o&&typeof o=="object"&&i(o);}}};return i(e),r}extractOperationNameFromGqlCall(e,t){if(!e.arguments?.length)return null;let r=e.arguments[0],s=r?.expression||r;if(s?.type==="TemplateLiteral"&&s.quasis?.[0]?.raw){let n=s.quasis[0].raw.match(/(?:query|mutation|subscription)\s+(\w+)/i);if(n)return n[1]}if(e.span){let n=t.slice(e.span.start,e.span.end).match(/(?:query|mutation|subscription)\s+(\w+)/i);if(n)return n[1]}return null}traverseForHooks(e,t,r,s,i,n){if(!(!e||typeof e!="object")){e.type==="CallExpression"&&this.analyzeHookCall(e,t,r,s,i,n);for(let a of Object.keys(e)){let o=e[a];if(Array.isArray(o))for(let l of o)this.traverseForHooks(l,t,r,s,i,n);else o&&typeof o=="object"&&this.traverseForHooks(o,t,r,s,i,n);}}}analyzeHookCall(e,t,r,s,i,n){let a=this.getCalleeNameFromNode(e.callee);if(!a||!a.startsWith("use"))return;let o=R(a),l=Q(a),u=te(a);if((o||l||u)&&this.hasGraphQLArgument(e,t,r,s)){let c=this.extractOperationNameFromCall(e,t,r,s),g=l?"Mutation":u?"Subscription":"Query",m=c?`${g}: ${c}`:`${g}: unknown`;n.has(m)||(n.add(m),i.push(m));return}if(a==="useContext"){let f=this.extractContextName(e);if(f){let c=`\u{1F504} Context: ${f}`;n.has(c)||(n.add(c),i.push(c));}return}n.has(a)||(n.add(a),i.push(a));}hasGraphQLArgument(e,t,r,s){if(!e.arguments?.length)return false;let i=e.arguments[0],n=i?.expression||i;if(!n)return false;if(n.type==="Identifier"){let a=n.value;if(r.has(a)||s.has(a)||a.endsWith("Document")||/[A-Z][a-z]*Query$/.test(a)||/[A-Z][a-z]*Mutation$/.test(a)||/^[A-Z][A-Z0-9_]*_QUERY$/.test(a)||/^[A-Z][A-Z0-9_]*_MUTATION$/.test(a))return true}if(n.type==="TaggedTemplateExpression"){let a=this.getCalleeNameFromNode(n.tag);if(a==="gql"||a==="graphql")return true}if(n.type==="CallExpression"){let a=this.getCalleeNameFromNode(n.callee);if(a==="gql"||a==="graphql")return true}if(n.type==="TemplateLiteral"&&n.quasis?.[0]?.raw){let a=n.quasis[0].raw;if(/(?:query|mutation|subscription)\s+\w+/i.test(a))return true}if(n.type==="MemberExpression"){let a=n.property?.value;if(a&&/Query$|Mutation$|Document$/.test(a))return true}if(e.span){let a=t.slice(e.span.start,Math.min(e.span.end,e.span.start+500));if(a.includes("Document")||/\bgql\s*[`(]/.test(a)||/\bgraphql\s*[`(]/.test(a)||/query\s+\w+\s*[({]/.test(a)||/mutation\s+\w+\s*[({]/.test(a))return true}return false}getCalleeNameFromNode(e){return e?e.type==="Identifier"?e.value:e.type==="MemberExpression"&&e.property?.type==="Identifier"?e.property.value:null:null}extractOperationNameFromCall(e,t,r,s){if(e.typeArguments?.params?.length>0){let i=e.typeArguments.params[0];if(i?.type==="TsTypeReference"&&i.typeName?.type==="Identifier"){let n=i.typeName.value;return d(n)}}if(e.callee?.span&&e.span){let i=e.callee.span.end,n=Math.min(i+150,e.span.end),o=t.slice(i,n).match(/^<\s*(\w+)(?:Query|Mutation|Variables|Subscription)?[\s,>]/);if(o)return d(o[1])}if(e.arguments?.length>0){let i=e.arguments[0],n=i?.expression||i;if(!n)return null;if(n.type==="Identifier"){let a=n.value,o=s.get(a);if(o)return o;let l=r.get(a);return l||(/^(Query|Mutation|QUERY|MUTATION)$/i.test(a)?null:d(a))}if(n.type==="MemberExpression"&&n.property?.type==="Identifier")return d(n.property.value);if(n.type==="TaggedTemplateExpression"&&n.template?.quasis?.[0]?.raw){let o=n.template.quasis[0].raw.match(/(?:query|mutation|subscription)\s+(\w+)/i);if(o)return o[1]}if(n.type==="CallExpression"){let a=this.getCalleeNameFromNode(n.callee);if((a==="graphql"||a==="gql")&&n.arguments?.length>0){let o=n.arguments[0],l=o?.expression||o;if(l?.type==="TemplateLiteral"&&l.quasis?.[0]?.raw){let f=l.quasis[0].raw.match(/(?:query|mutation|subscription)\s+(\w+)/i);if(f)return f[1]}}}if(n.type==="TemplateLiteral"&&n.quasis?.[0]?.raw){let o=n.quasis[0].raw.match(/(?:query|mutation|subscription)\s+(\w+)/i);if(o)return o[1]}}if(e.span){let i=t.slice(e.span.start,e.span.end),n=i.match(/\b([A-Z][a-zA-Z0-9]*Document)\b/);if(n)return d(n[1]);let a=i.match(/(?:query|mutation|subscription)\s+(\w+)/i);if(a)return a[1]}return null}extractContextName(e){if(e.arguments?.length>0){let t=e.arguments[0].expression;if(t?.type==="Identifier")return t.value.replace(/Context$/,"")}return null}extractHooksWithRegex(e,t,r){let s=/\b(useQuery|useMutation|useLazyQuery|useSuspenseQuery|useBackgroundQuery|useSubscription)(?:<[^>]*>)?\s*\(\s*([A-Z_][A-Za-z0-9_]*)?/gs,i;for(;(i=s.exec(e))!==null;){let o=i[1],l=i[2];if(l&&/^(Query|Mutation|QUERY|MUTATION)$/i.test(l))continue;let u=l?d(l):"unknown",c=`${o.includes("Mutation")?"Mutation":o.includes("Subscription")?"Subscription":"Query"}: ${u}`;r.has(c)||(r.add(c),t.push(c));}let n=/\b(use[A-Z][a-zA-Z0-9]*)\s*\(/g,a;for(;(a=n.exec(e))!==null;){let o=a[1];if(!["useQuery","useMutation","useLazyQuery","useSuspenseQuery","useBackgroundQuery","useSubscription"].includes(o))if(o==="useContext"){let l=e.slice(a.index).match(/useContext\s*\(\s*([A-Z][A-Za-z0-9]*)/);if(l){let f=`\u{1F504} Context: ${l[1].replace(/Context$/,"")}`;r.has(f)||(r.add(f),t.push(f));}}else r.has(o)||(r.add(o),t.push(o));}}extractStateManagement(e){let t=[];return e.includes("useState")&&t.push("useState"),e.includes("useReducer")&&t.push("useReducer"),e.includes("useContext")&&t.push("useContext"),e.includes("useQuery")&&t.push("Apollo Query"),e.includes("useMutation")&&t.push("Apollo Mutation"),e.includes("useRecoil")&&t.push("Recoil"),(e.includes("useSelector")||e.includes("useDispatch"))&&t.push("Redux"),t}buildDependencyGraph(e){let t=new Map;for(let r of e)t.set(r.name,r);for(let r of e)for(let s of r.dependencies){let i=t.get(s);i&&!i.dependents.includes(r.name)&&i.dependents.push(r.name);}}async analyzeDataFlows(e){let t=[],r=1,s=this.analyzeContextFlows(e);t.push(...s.map(a=>({...a,id:`flow-${r++}`})));let i=this.analyzeApolloFlows(e);t.push(...i.map(a=>({...a,id:`flow-${r++}`})));let n=this.analyzePropDrilling(e);return t.push(...n.map(a=>({...a,id:`flow-${r++}`}))),t}analyzeContextFlows(e){let t=[],r=e.filter(i=>i.name.includes("Provider")||i.name.includes("Context")),s=e.filter(i=>i.hooks.some(n=>n.includes("Context")));for(let i of r){let n=i.name.replace("Provider","").replace("Context","");for(let a of s){let o=a.hooks.find(l=>l.includes("Context")&&l.includes(n));(o||a.hooks.some(l=>l.includes(n)))&&t.push({name:`\u{1F504} ${n} Context`,description:`Data flows from ${i.name} to ${a.name} via Context`,source:{type:"context",name:i.name},target:{type:"component",name:a.name},via:[],operations:[o||`useContext(${n})`]});}}return t}analyzeApolloFlows(e){let t=[];for(let r of e){let s=r.hooks.filter(n=>n.includes("Query:")||n==="useQuery"||n==="useLazyQuery");for(let n of s){let a=n.includes(":")?n.split(":")[1].trim():r.name;t.push({name:`Query: ${a}`,description:`${r.name} fetches ${a} via Apollo`,source:{type:"api",name:`GraphQL: ${a}`},target:{type:"component",name:r.name},via:[{type:"cache",name:"Apollo Cache"}],operations:[n]});}let i=r.hooks.filter(n=>n.includes("Mutation:")||n==="useMutation");for(let n of i){let a=n.includes(":")?n.split(":")[1].trim():r.name;t.push({name:`Mutation: ${a}`,description:`${r.name} mutates ${a} via Apollo`,source:{type:"component",name:r.name},target:{type:"api",name:`GraphQL: ${a}`},via:[],operations:[n]});}}return t}analyzePropDrilling(e){let t=[];for(let r of e)r.props.length>5&&r.dependents.length>0&&t.push({name:`Prop Drilling through ${r.name}`,description:`${r.name} passes ${r.props.length} props to children`,source:{type:"component",name:r.name},target:{type:"component",name:r.dependents[0]},via:[],operations:["props"]});return t}};var ge=class p extends A{apiCallCounter=0;constructor(e){super(e);}getName(){return "RestApiAnalyzer"}async analyze(){this.log("Starting REST API analysis...");let e=await j(["**/*.ts","**/*.tsx","**/*.js","**/*.jsx"],{cwd:this.basePath,ignore:["**/node_modules/**","**/.next/**","**/__tests__/**","**/*.test.*","**/*.spec.*","**/*.stories.*","**/__generated__/**","**/dist/**","**/build/**"],absolute:true}),t=50,r=[];for(let s=0;s<e.length;s+=t){let i=e.slice(s,s+t),n=await S(i,async a=>{try{let o=await T.readFile(a,"utf-8"),l=y.relative(this.basePath,a),u=a.endsWith(".tsx")||a.endsWith(".jsx"),f=parseSync(o,{syntax:a.endsWith(".ts")||a.endsWith(".tsx")?"typescript":"ecmascript",tsx:u,jsx:u});return this.analyzeModule(f,o,l)}catch{return []}},10);r.push(...n.flat());}return this.log(`Found ${r.length} REST API calls`),{apiCalls:r}}analyzeModule(e,t,r){let s=[],i=t.split(`
|
|
2
|
-
`);return this.traverseNode(e,n=>{if(n.type==="CallExpression"){let a=n,o=this.analyzeCallExpression(a,r,i);o&&s.push(o);}}),s}traverseNode(e,t){if(!(!e||typeof e!="object")){t(e);for(let r of Object.keys(e)){let s=e[r];if(Array.isArray(s))for(let i of s)this.traverseNode(i,t);else s&&typeof s=="object"&&this.traverseNode(s,t);}}}analyzeCallExpression(e,t,r){let s=e.callee;if(s.type==="Super"||s.type==="Import")return null;let i=this.getCalleeName(s);if(!i)return null;if(i==="fetch"||i==="window.fetch")return this.extractFetchCall(e,t,r);let n=i.match(/^axios\.(get|post|put|delete|patch)$/i);return n?this.extractAxiosMethodCall(e,t,r,n[1].toUpperCase()):i==="axios"?this.extractAxiosDirectCall(e,t,r):i==="useSWR"||i==="useSWRImmutable"?this.extractSwrCall(e,t,r):null}getCalleeName(e){if(e.type==="Identifier")return e.value;if(e.type==="MemberExpression"){let t=e.object,r=e.property;if(t.type==="Identifier"&&r.type==="Identifier")return `${t.value}.${r.value}`}return null}extractFetchCall(e,t,r){if(e.arguments.length===0)return null;let s=e.arguments[0],i=this.extractUrlFromExpression(s.expression);if(!i.url||!i.isPlaceholder&&!this.isApiUrl(i.url))return null;let n="GET",a=false;if(e.arguments.length>1){let l=e.arguments[1].expression;if(l.type==="ObjectExpression")for(let u of l.properties)u.type==="KeyValueProperty"&&u.key.type==="Identifier"&&(u.key.value==="method"&&u.value.type==="StringLiteral"&&(n=this.normalizeMethod(u.value.value)),(u.key.value==="credentials"||u.key.value==="headers")&&(a=true));}let o=this.getLineNumber(e.span.start,r);return {id:`api-${++this.apiCallCounter}`,method:n,url:i.url,callType:"fetch",filePath:t,line:o,containingFunction:"unknown",usedIn:[],requiresAuth:a,category:this.categorizeApi(i.url)}}extractAxiosMethodCall(e,t,r,s){if(e.arguments.length===0)return null;let i=e.arguments[0],n=this.extractUrlFromExpression(i.expression);if(!n.url)return null;let a=this.getLineNumber(e.span.start,r);return {id:`api-${++this.apiCallCounter}`,method:this.normalizeMethod(s),url:n.url,callType:"axios",filePath:t,line:a,containingFunction:"unknown",usedIn:[],requiresAuth:false,category:this.categorizeApi(n.url)}}extractAxiosDirectCall(e,t,r){if(e.arguments.length===0)return null;let s=e.arguments[0].expression;if(s.type!=="ObjectExpression")return null;let i=null,n="GET";for(let o of s.properties)o.type==="KeyValueProperty"&&o.key.type==="Identifier"&&(o.key.value==="url"&&o.value.type==="StringLiteral"&&(i=o.value.value),o.key.value==="method"&&o.value.type==="StringLiteral"&&(n=this.normalizeMethod(o.value.value)));if(!i)return null;let a=this.getLineNumber(e.span.start,r);return {id:`api-${++this.apiCallCounter}`,method:n,url:i,callType:"axios",filePath:t,line:a,containingFunction:"unknown",usedIn:[],requiresAuth:false,category:this.categorizeApi(i)}}extractSwrCall(e,t,r){if(e.arguments.length===0)return null;let s=e.arguments[0].expression,i=this.extractUrlFromExpression(s);if(!i.url)return null;let n=this.getLineNumber(e.span.start,r);return {id:`api-${++this.apiCallCounter}`,method:"GET",url:i.url,callType:"useSWR",filePath:t,line:n,containingFunction:"unknown",usedIn:[],requiresAuth:false,category:this.categorizeApi(i.url)}}extractUrlFromExpression(e){if(e.type==="StringLiteral")return {url:e.value,isPlaceholder:false};if(e.type==="TemplateLiteral")return e.quasis.length===1&&e.expressions.length===0?{url:e.quasis[0].raw,isPlaceholder:false}:{url:e.quasis.map(s=>s.raw).join(":param"),isPlaceholder:true};if(e.type==="Identifier")return {url:`[${e.value}]`,isPlaceholder:true};if(e.type==="MemberExpression"){let t=e.object.type==="Identifier"?e.object.value:"?",r=e.property.type==="Identifier"?e.property.value:"?";return {url:`[${t}.${r}]`,isPlaceholder:true}}if(e.type==="ConditionalExpression"){let t=this.extractUrlFromExpression(e.consequent);return t.url?t:this.extractUrlFromExpression(e.alternate)}return {url:null,isPlaceholder:false}}getLineNumber(e,t){let r=0;for(let s=0;s<t.length;s++)if(r+=t[s].length+1,r>e)return s+1;return t.length}static STATIC_FILE_EXTENSIONS=/\.(css|js|mjs|cjs|ts|tsx|jsx|png|jpg|jpeg|gif|webp|svg|ico|woff|woff2|ttf|eot|otf|mp3|mp4|webm|ogg|wav|pdf|doc|docx|xls|xlsx|ppt|pptx|zip|tar|gz|rar|html|htm|xml|txt|md|map|wasm)$/i;static NON_API_SCHEMES=/^(data:|blob:|javascript:|mailto:|tel:|file:)/;isApiUrl(e){return p.NON_API_SCHEMES.test(e)||p.STATIC_FILE_EXTENSIONS.test(e)||!e.trim()?false:!!(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://")||e.startsWith("[")||e.includes("/api/")||e.includes("/v1/")||e.includes("/v2/")||e.includes("/graphql"))}static SERVICE_PATTERNS=[{pattern:/amazonaws\.com|\.s3\./i,name:"AWS"},{pattern:/googleapis\.com|google\.com\/api/i,name:"Google API"},{pattern:/graph\.facebook\.com|facebook\.com\/v\d+/i,name:"Facebook"},{pattern:/api\.twitter\.com|twitter\.com\/\d+/i,name:"Twitter/X"},{pattern:/api\.github\.com|github\.com\/api/i,name:"GitHub API"},{pattern:/stripe\.com/i,name:"Stripe"},{pattern:/paypal\.com/i,name:"PayPal"},{pattern:/slack\.com/i,name:"Slack"},{pattern:/discord\.com|discordapp\.com/i,name:"Discord"},{pattern:/twilio\.com/i,name:"Twilio"},{pattern:/sendgrid\.(com|net)/i,name:"SendGrid"},{pattern:/mailchimp\.com/i,name:"Mailchimp"},{pattern:/hubspot\.com|hsforms\.com/i,name:"HubSpot"},{pattern:/salesforce\.com/i,name:"Salesforce"},{pattern:/zendesk\.com/i,name:"Zendesk"},{pattern:/intercom\.io/i,name:"Intercom"},{pattern:/firebase(io)?\.com|firestore\.googleapis/i,name:"Firebase"},{pattern:/supabase\.(co|com|io)/i,name:"Supabase"},{pattern:/auth0\.com/i,name:"Auth0"},{pattern:/okta\.com/i,name:"Okta"},{pattern:/clerk\.(dev|com)/i,name:"Clerk"},{pattern:/cloudflare\.com|workers\.dev/i,name:"Cloudflare"},{pattern:/vercel\.com|vercel\.app/i,name:"Vercel"},{pattern:/netlify\.com|netlify\.app/i,name:"Netlify"},{pattern:/heroku\.com|herokuapp\.com/i,name:"Heroku"},{pattern:/railway\.app/i,name:"Railway"},{pattern:/render\.com/i,name:"Render"},{pattern:/digitalocean\.com/i,name:"DigitalOcean"},{pattern:/algolia\.(com|net|io)/i,name:"Algolia"},{pattern:/elastic\.co|elasticsearch/i,name:"Elasticsearch"},{pattern:/mongodb\.com|mongodb\.net/i,name:"MongoDB"},{pattern:/planetscale\.com/i,name:"PlanetScale"},{pattern:/sentry\.io/i,name:"Sentry"},{pattern:/datadog\.com/i,name:"Datadog"},{pattern:/segment\.(com|io)/i,name:"Segment"},{pattern:/mixpanel\.com/i,name:"Mixpanel"},{pattern:/amplitude\.com/i,name:"Amplitude"},{pattern:/openai\.com/i,name:"OpenAI"},{pattern:/anthropic\.com/i,name:"Anthropic"},{pattern:/cohere\.(ai|com)/i,name:"Cohere"}];categorizeApi(e){if(e.startsWith("["))return "Dynamic URL";if(e.startsWith("/"))return e.startsWith("/api/")?"Internal API":e.includes("/graphql")?"GraphQL":"Internal Route";for(let{pattern:t,name:r}of p.SERVICE_PATTERNS)if(t.test(e))return r;try{let s=new URL(e).hostname.replace(/^(api\.|www\.)/,"").split(".");if(s.length>=2){let i=s[s.length-2];return i.charAt(0).toUpperCase()+i.slice(1)+" API"}}catch{}return "External API"}normalizeMethod(e){let t=e.toUpperCase();return ["GET","POST","PUT","DELETE","PATCH"].includes(t)?t:"unknown"}};
|
|
3
|
-
export{le as A,ce as B,ge as C,A as a,O as b,X as c,ee as d,ve as e,z as f,Y as g,be as h,R as i,Q as j,te as k,$ as l,D as m,W as n,d as o,Ae as p,v as q,M as r,H as s,V as t,P as u,ne as v,U as w,je as x,Ge as y,ae as z};
|