@didnhdj/fnmap 0.1.9 → 0.1.10

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.
Files changed (2) hide show
  1. package/dist/index.js +17 -17
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const A=require("fs"),E=require("path"),Re=require("commander"),k=require("child_process"),Fe=require("@babel/parser"),B=require("@babel/traverse"),b={FILE_NOT_FOUND:"FILE_NOT_FOUND",FILE_READ_ERROR:"FILE_READ_ERROR",PARSE_ERROR:"PARSE_ERROR",CONFIG_ERROR:"CONFIG_ERROR",VALIDATION_ERROR:"VALIDATION_ERROR",PERMISSION_ERROR:"PERMISSION_ERROR",FILE_TOO_LARGE:"FILE_TOO_LARGE"};function oe(e){return"parseError"in e}function Ie(e){return e.success===!0}function Ce(e){return e.success===!1}function Ae(e){return e.valid===!0}function ve(e){return e.valid===!1}const v={reset:"\x1B[0m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",gray:"\x1B[90m",bold:"\x1B[1m"},X=10*1024*1024,H=50,z=[".js",".ts",".jsx",".tsx",".mjs"],K=["node_modules",".git","dist","build",".next","coverage","__pycache__",".cache"],Q={enable:!0,include:["**/*.js","**/*.ts","**/*.jsx","**/*.tsx","**/*.mjs"],exclude:[]};function ie(e){if(!e||typeof e!="string")return{valid:!1,error:"File path is required and must be a string / 文件路径必须是字符串",errorType:b.VALIDATION_ERROR};if(!A.existsSync(e))return{valid:!1,error:`File not found: ${e} / 文件不存在: ${e}`,errorType:b.FILE_NOT_FOUND};try{const o=A.statSync(e);if(!o.isFile())return{valid:!1,error:`Path is not a file: ${e} / 路径不是文件: ${e}`,errorType:b.VALIDATION_ERROR};if(o.size>X)return{valid:!1,error:`File too large (${(o.size/1024/1024).toFixed(2)}MB > ${X/1024/1024}MB): ${e} / 文件过大`,errorType:b.FILE_TOO_LARGE}}catch(o){return{valid:!1,error:`Cannot access file: ${e}. Reason: ${o.message} / 无法访问文件`,errorType:b.PERMISSION_ERROR}}return{valid:!0}}function Z(e){if(!e||typeof e!="object")return{valid:!1,error:"Config must be an object / 配置必须是对象"};const o=e;return o.enable!==void 0&&typeof o.enable!="boolean"?{valid:!1,error:"Config.enable must be a boolean / enable 字段必须是布尔值"}:o.include!==void 0&&!Array.isArray(o.include)?{valid:!1,error:"Config.include must be an array / include 字段必须是数组"}:o.exclude!==void 0&&!Array.isArray(o.exclude)?{valid:!1,error:"Config.exclude must be an array / exclude 字段必须是数组"}:{valid:!0}}function U(e,o,s={}){const t=[o];return s.file&&t.push(`File: ${s.file}`),s.line!==void 0&&s.column!==void 0&&t.push(`Location: Line ${s.line}, Column ${s.column}`),s.suggestion&&t.push(`Suggestion: ${s.suggestion}`),t.join(`
3
- `)}let L=!1,q=null;const S={error:e=>{L||console.error(`${v.red}✗${v.reset} ${e}`)},success:e=>{L||console.log(`${v.green}✓${v.reset} ${e}`)},info:e=>{L||console.log(e)},warn:e=>{L||console.warn(`${v.yellow}!${v.reset} ${e}`)},title:e=>{L||console.log(`${v.bold}${e}${v.reset}`)}};function ae(e){L=e}function be(){return L}function ce(){try{return require("../../package.json").version}catch{return"0.1.0"}}function Y(){return q=new Re.Command,q.name("fnmap").description("AI code indexing tool - Analyzes JS/TS code structure and generates structured code maps").version(ce(),"-v, --version","Show version number").option("-f, --files <files>","Process specified files (comma-separated)",e=>e.split(",").map(o=>o.trim()).filter(Boolean)).option("-d, --dir <dir>","Process all code files in directory").option("-p, --project <dir>","Specify project root directory",process.env.CLAUDE_PROJECT_DIR??process.cwd()).option("-c, --changed","Process only git changed files (staged + modified + untracked)").option("-s, --staged","Process only git staged files (for pre-commit hook)").option("-m, --mermaid [mode]","Generate Mermaid call graph (file=file-level, project=project-level)").option("-q, --quiet","Quiet mode").option("--init","Create default config file .fnmaprc").argument("[files...]","Directly specify file paths").allowUnknownOption(!1).addHelpText("after",`
2
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const x=require("fs"),E=require("path"),Re=require("commander"),P=require("child_process"),Fe=require("@babel/parser"),B=require("@babel/traverse"),C={FILE_NOT_FOUND:"FILE_NOT_FOUND",FILE_READ_ERROR:"FILE_READ_ERROR",PARSE_ERROR:"PARSE_ERROR",CONFIG_ERROR:"CONFIG_ERROR",VALIDATION_ERROR:"VALIDATION_ERROR",PERMISSION_ERROR:"PERMISSION_ERROR",FILE_TOO_LARGE:"FILE_TOO_LARGE"};function ie(e){return"parseError"in e}function be(e){return e.success===!0}function xe(e){return e.success===!1}function Ae(e){return e.valid===!0}function Ce(e){return e.valid===!1}const A={reset:"\x1B[0m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",gray:"\x1B[90m",bold:"\x1B[1m"},K=10*1024*1024,X=50,z=[".js",".ts",".jsx",".tsx",".mjs"],Z=["node_modules",".git","dist","build",".next","coverage","__pycache__",".cache"],H={enable:!0,include:["**/*.js","**/*.ts","**/*.jsx","**/*.tsx","**/*.mjs"],exclude:[]};function ae(e){if(!e||typeof e!="string")return{valid:!1,error:"File path is required and must be a string / 文件路径必须是字符串",errorType:C.VALIDATION_ERROR};if(!x.existsSync(e))return{valid:!1,error:`File not found: ${e} / 文件不存在: ${e}`,errorType:C.FILE_NOT_FOUND};try{const s=x.statSync(e);if(!s.isFile())return{valid:!1,error:`Path is not a file: ${e} / 路径不是文件: ${e}`,errorType:C.VALIDATION_ERROR};if(s.size>K)return{valid:!1,error:`File too large (${(s.size/1024/1024).toFixed(2)}MB > ${K/1024/1024}MB): ${e} / 文件过大`,errorType:C.FILE_TOO_LARGE}}catch(s){return{valid:!1,error:`Cannot access file: ${e}. Reason: ${s.message} / 无法访问文件`,errorType:C.PERMISSION_ERROR}}return{valid:!0}}function Q(e){if(!e||typeof e!="object")return{valid:!1,error:"Config must be an object / 配置必须是对象"};const s=e;return s.enable!==void 0&&typeof s.enable!="boolean"?{valid:!1,error:"Config.enable must be a boolean / enable 字段必须是布尔值"}:s.include!==void 0&&!Array.isArray(s.include)?{valid:!1,error:"Config.include must be an array / include 字段必须是数组"}:s.exclude!==void 0&&!Array.isArray(s.exclude)?{valid:!1,error:"Config.exclude must be an array / exclude 字段必须是数组"}:{valid:!0}}function V(e,s,r={}){const n=[s];return r.file&&n.push(`File: ${r.file}`),r.line!==void 0&&r.column!==void 0&&n.push(`Location: Line ${r.line}, Column ${r.column}`),r.suggestion&&n.push(`Suggestion: ${r.suggestion}`),n.join(`
3
+ `)}let T=!1,q=null;const $={error:e=>{T||console.error(`${A.red}✗${A.reset} ${e}`)},success:e=>{T||console.log(`${A.green}✓${A.reset} ${e}`)},info:e=>{T||console.log(e)},warn:e=>{T||console.warn(`${A.yellow}!${A.reset} ${e}`)},title:e=>{T||console.log(`${A.bold}${e}${A.reset}`)}};function ce(e){T=e}function ve(){return T}function le(){try{return require("../../package.json").version}catch{return"0.1.0"}}function Y(){return q=new Re.Command,q.name("fnmap").description("AI code indexing tool - Analyzes JS/TS code structure and generates structured code maps").version(le(),"-v, --version","Show version number").option("-f, --files <files>","Process specified files (comma-separated)",e=>e.split(",").map(s=>s.trim()).filter(Boolean)).option("-d, --dir <dir>","Process all code files in directory").option("-p, --project <dir>","Specify project root directory",process.env.CLAUDE_PROJECT_DIR??process.cwd()).option("-c, --changed","Process only git changed files (staged + modified + untracked)").option("-s, --staged","Process only git staged files (for pre-commit hook)").option("-m, --mermaid [mode]","Generate Mermaid call graph (file=file-level, project=project-level)").option("-q, --quiet","Quiet mode").option("--init","Create default config file .fnmaprc").argument("[files...]","Directly specify file paths").allowUnknownOption(!1).addHelpText("after",`
4
4
  Configuration files (by priority):
5
5
  .fnmaprc JSON config file
6
6
  .fnmaprc.json JSON config file
@@ -19,16 +19,16 @@ Examples:
19
19
  $ fnmap --mermaid file --dir src Generate file-level call graphs
20
20
  $ fnmap --mermaid project Generate project-level call graph
21
21
  $ fnmap --init Create config file
22
- `),q}function P(){return q||Y()}const _e={get opts(){return P().opts.bind(P())},get args(){return P().args},get parse(){return P().parse.bind(P())}};function le(e){const o=[".fnmaprc",".fnmaprc.json"];for(const t of o){const a=E.join(e,t);if(A.existsSync(a))try{const l=A.readFileSync(a,"utf-8");if(!l.trim()){S.warn(`Config file is empty: ${t}. Using default config / 配置文件为空,使用默认配置`);continue}let g;try{g=JSON.parse(l)}catch(u){const i=u,r=U(b.CONFIG_ERROR,`Failed to parse config file: ${t} / 配置文件解析失败`,{file:a,line:i.lineNumber,column:i.columnNumber,suggestion:"Check JSON syntax, ensure proper quotes and commas / 检查 JSON 语法,确保引号和逗号正确"});S.warn(r);continue}const p=Z(g);if(!p.valid){S.warn(`Invalid config in ${t}: ${p.error}`);continue}return{config:g,source:t}}catch(l){const g=l,p=U(b.FILE_READ_ERROR,`Failed to read config file: ${t} / 配置文件读取失败`,{file:a,suggestion:g.message});S.warn(p)}}const s=E.join(e,"package.json");if(A.existsSync(s))try{const t=JSON.parse(A.readFileSync(s,"utf-8"));if(t.fnmap){const a=Z(t.fnmap);if(!a.valid)S.warn(`Invalid fnmap config in package.json: ${a.error}`);else return{config:t.fnmap,source:"package.json#fnmap"}}}catch{}return{config:null,source:null}}function fe(e){return e?{...Q,...e,exclude:[...e.exclude??[]]}:Q}function xe(e){try{return k.execSync("git rev-parse --show-toplevel",{cwd:e,encoding:"utf-8"}).trim()}catch{return null}}function de(e,o=!1){const s=[];try{const t=xe(e);if(!t)return[];let a;if(o)a=k.execSync("git diff --cached --name-only --diff-filter=ACMR",{cwd:e,encoding:"utf-8"});else{const p=k.execSync("git diff --cached --name-only --diff-filter=ACMR",{cwd:e,encoding:"utf-8"}),u=k.execSync("git diff --name-only --diff-filter=ACMR",{cwd:e,encoding:"utf-8"}),i=k.execSync("git ls-files --others --exclude-standard",{cwd:e,encoding:"utf-8"});a=`${p}
23
- ${u}
24
- ${i}`}const l=a.split(`
25
- `).map(p=>p.trim()).filter(Boolean).filter(p=>{const u=E.extname(p);return z.includes(u)}),g=[...new Set(l)];for(const p of g){const u=E.resolve(t,p);A.existsSync(u)&&u.startsWith(E.resolve(e))&&s.push(u)}}catch{return[]}return s}function Ne(e){const o=[];if(!A.existsSync(e))return o;try{const s=A.readdirSync(e,{withFileTypes:!0});for(const t of s)if(t.isFile()){const a=E.extname(t.name);z.includes(a)&&o.push(E.join(e,t.name))}}catch{return o}return o}function W(e,o=e,s=K,t=0,a=new Set){const l=[];if(!A.existsSync(e))return S.warn(`Directory does not exist: ${e} / 目录不存在`),l;if(t>H)return S.warn(`Max directory depth (${H}) exceeded: ${e} / 超过最大目录深度`),l;let g;try{g=A.realpathSync(e)}catch(u){const i=u;return S.warn(`Cannot resolve real path: ${e}. Reason: ${i.message} / 无法解析真实路径`),l}if(a.has(g))return S.warn(`Circular reference detected, skipping: ${e} / 检测到循环引用`),l;a.add(g);let p;try{p=A.readdirSync(e,{withFileTypes:!0})}catch(u){const i=u;return i.code==="EACCES"||i.code==="EPERM"?S.warn(`Permission denied: ${e} / 权限不足`):S.warn(`Failed to read directory: ${e}. Reason: ${i.message} / 读取目录失败`),l}for(const u of p)try{const i=E.join(e,u.name);if(u.isDirectory())s.includes(u.name)||l.push(...W(i,o,s,t+1,a));else if(u.isFile()){const r=E.extname(u.name);z.includes(r)&&l.push(E.relative(o,i))}}catch(i){const r=i;S.warn(`Error processing entry: ${u.name}. Reason: ${r.message} / 处理条目出错`)}return l}function G(e){if(!e)return"";const s=e.value.split(`
26
- `).map(t=>t.replace(/^\s*\*\s?/,"").trim());for(const t of s)if(t.startsWith("@description "))return t.slice(13).trim().slice(0,60);for(const t of s)if(t&&!t.startsWith("@")&&!t.startsWith("/"))return t.slice(0,60);return""}const J=typeof B=="function"?B:B.default;function ue(e,o){var m,F;if(e==null)return{parseError:"Code content is null or undefined / 代码内容为空",errorType:b.VALIDATION_ERROR};if(typeof e!="string")return{parseError:"Code must be a string / 代码必须是字符串类型",errorType:b.VALIDATION_ERROR};if(!e.trim())return{description:"",imports:[],functions:[],classes:[],constants:[],callGraph:{}};const s={description:"",imports:[],functions:[],classes:[],constants:[],callGraph:{}},t=e.match(/^\/\*\*[\s\S]*?\*\//);if(t){const n=t[0].split(`
27
- `).map(c=>c.replace(/^\s*\*\s?/,"").trim()).filter(c=>c&&!c.startsWith("/")&&!c.startsWith("@ai"));for(const c of n)if(c.startsWith("@description ")){s.description=c.slice(13).trim();break}if(!s.description&&n.length>0){const c=n.find(h=>!h.startsWith("@"));c&&(s.description=c)}}let a;try{const f=o&&(o.endsWith(".ts")||o.endsWith(".tsx"));a=Fe.parse(e,{sourceType:"unambiguous",plugins:["jsx","classPrivateProperties","classPrivateMethods",...f?["typescript"]:[]]})}catch(f){const n=f;return{parseError:U(b.PARSE_ERROR,`Syntax error: ${n.message} / 语法错误`,{file:o??void 0,line:(m=n.loc)==null?void 0:m.line,column:(F=n.loc)==null?void 0:F.column,suggestion:"Check syntax errors in the file / 检查文件中的语法错误"}),loc:n.loc,errorType:b.PARSE_ERROR}}const l=new Map,g=new Map,p=new Map;function u(f){var c,h,I;let n=f;for(;n;){if(n.node.type==="FunctionDeclaration"){const y=n.node;if(y.id)return y.id.name}if(n.node.type==="ClassMethod"){const y=n.node,R=(c=n.parentPath)==null?void 0:c.parentPath,$=R==null?void 0:R.node,C=((h=$==null?void 0:$.id)==null?void 0:h.name)??"",_=((I=y.key)==null?void 0:I.name)??"";return C?`${C}.${_}`:_}if(n.node.type==="ArrowFunctionExpression"||n.node.type==="FunctionExpression"){const y=n.parent;if((y==null?void 0:y.type)==="VariableDeclarator"){const $=y.id;if($!=null&&$.name)return $.name}}n=n.parentPath}return null}J(a,{VariableDeclarator(f){var c,h,I,y;const n=f.node;if(((c=n.init)==null?void 0:c.type)==="CallExpression"&&((h=n.init.callee)==null?void 0:h.type)==="Identifier"&&n.init.callee.name==="require"&&((y=(I=n.init.arguments)==null?void 0:I[0])==null?void 0:y.type)==="StringLiteral"){const R=n.init.arguments[0].value;if(l.has(R)||l.set(R,new Set),n.id.type==="Identifier"){const $=n.id.name;l.get(R).add($),g.set($,R),p.set($,new Set)}else if(n.id.type==="ObjectPattern"){for(const $ of n.id.properties)if($.type==="ObjectProperty"&&$.key.type==="Identifier"){const C=$.value.type==="Identifier"?$.value.name:$.key.name;l.get(R).add($.key.name),g.set(C,R),p.set(C,new Set)}}}},CallExpression(f){var c,h,I,y,R,$;const n=f.node;if(((c=n.callee)==null?void 0:c.type)==="Identifier"&&n.callee.name==="require"&&((I=(h=n.arguments)==null?void 0:h[0])==null?void 0:I.type)==="StringLiteral"){const C=f.parent;if((C==null?void 0:C.type)==="MemberExpression"&&((y=C.property)==null?void 0:y.type)==="Identifier"){const _=n.arguments[0].value;l.has(_)||l.set(_,new Set),l.get(_).add(C.property.name);const N=(R=f.parentPath)==null?void 0:R.parent;if((N==null?void 0:N.type)==="VariableDeclarator"){const O=N;(($=O.id)==null?void 0:$.type)==="Identifier"&&(g.set(O.id.name,_),p.set(O.id.name,new Set))}}}},ImportDeclaration(f){const n=f.node,c=n.source.value;l.has(c)||l.set(c,new Set);for(const h of n.specifiers){let I,y;if(h.type==="ImportDefaultSpecifier")I="default",y=h.local.name;else if(h.type==="ImportNamespaceSpecifier")I="*",y=h.local.name;else if(h.type==="ImportSpecifier"){const R=h.imported;I=R.type==="Identifier"?R.name:R.value,y=h.local.name}I&&y&&(l.get(c).add(I),g.set(y,c),p.set(y,new Set))}}}),J(a,{Identifier(f){const n=f.node.name;if(p.has(n)){const c=f.parent;if((c==null?void 0:c.type)==="VariableDeclarator"&&c.id===f.node||(c==null?void 0:c.type)==="ImportSpecifier"||(c==null?void 0:c.type)==="ImportDefaultSpecifier")return;const h=u(f);h&&p.get(n).add(h)}},FunctionDeclaration(f){var C,_,N,O,j;const n=f.node,c=((C=n.id)==null?void 0:C.name)??"[anonymous]",h=n.params.map(x=>{var M,T;return x.type==="Identifier"?x.name:x.type==="AssignmentPattern"&&((M=x.left)==null?void 0:M.type)==="Identifier"?x.left.name+"?":x.type==="RestElement"&&((T=x.argument)==null?void 0:T.type)==="Identifier"?"..."+x.argument.name:"?"}),I=((N=(_=n.loc)==null?void 0:_.start)==null?void 0:N.line)??0,y=((j=(O=n.loc)==null?void 0:O.end)==null?void 0:j.line)??0;let R="";const $=n.leadingComments;$&&$.length>0&&(R=G($[$.length-1])),s.functions.push({name:c,params:h.join(","),startLine:I,endLine:y,description:R})},ClassDeclaration(f){var _,N,O,j,x,M,T,ee,ne,te;const n=f.node,c=((_=n.id)==null?void 0:_.name)??"[anonymous]",h=((O=(N=n.loc)==null?void 0:N.start)==null?void 0:O.line)??0,I=((x=(j=n.loc)==null?void 0:j.end)==null?void 0:x.line)??0,y=((M=n.superClass)==null?void 0:M.type)==="Identifier"?n.superClass.name:null;let R="";const $=n.leadingComments;$&&$.length>0&&(R=G($[$.length-1]));const C=[];if((T=n.body)!=null&&T.body){for(const w of n.body.body)if(w.type==="ClassMethod"){const $e=((ee=w.key)==null?void 0:ee.type)==="Identifier"?w.key.name:"[computed]",Se=w.params.map(D=>{var se;return D.type==="Identifier"?D.name:D.type==="AssignmentPattern"&&((se=D.left)==null?void 0:se.type)==="Identifier"?D.left.name+"?":"?"}),Ee=((te=(ne=w.loc)==null?void 0:ne.start)==null?void 0:te.line)??0;let re="";const V=w.leadingComments;V&&V.length>0&&(re=G(V[V.length-1])),C.push({name:$e,params:Se.join(","),line:Ee,static:w.static,kind:w.kind,description:re})}}s.classes.push({name:c,superClass:y,startLine:h,endLine:I,methods:C,description:R})},VariableDeclaration(f){var c,h,I;if(f.parent.type!=="Program")return;const n=f.node;if(n.kind==="const"){let y="";const R=n.leadingComments;R&&R.length>0&&(y=G(R[R.length-1]));for(const $ of n.declarations){const C=((c=$.id)==null?void 0:c.type)==="Identifier"?$.id.name:void 0;if(C&&C===C.toUpperCase()&&C.length>2){const _=((I=(h=n.loc)==null?void 0:h.start)==null?void 0:I.line)??0;s.constants.push({name:C,line:_,description:y})}}}}});for(const[f,n]of l){const c=new Set;for(const h of g.keys())if(g.get(h)===f&&p.has(h))for(const I of p.get(h))c.add(I);s.imports.push({module:f,members:Array.from(n),usedIn:Array.from(c)})}const i=new Set;for(const f of s.functions)i.add(f.name);for(const f of s.classes)for(const n of f.methods)i.add(n.name),i.add(`${f.name}.${n.name}`);const r=new Set(g.keys()),d=new Map;J(a,{CallExpression(f){var h,I;const n=f.node;let c=null;if(n.callee.type==="Identifier")c=n.callee.name;else if(n.callee.type==="MemberExpression"&&((h=n.callee.property)==null?void 0:h.type)==="Identifier"){const y=((I=n.callee.object)==null?void 0:I.type)==="Identifier"?n.callee.object.name:void 0,R=n.callee.property.name;y&&r.has(y)?c=`${y}.${R}`:c=R}if(c){const y=u(f);if(y&&y!==c){const R=i.has(c),$=r.has(c)||c.includes(".")&&r.has(c.split(".")[0]);(R||$)&&(d.has(y)||d.set(y,new Set),d.get(y).add(c))}}}}),s.callGraph={};for(const[f,n]of d)s.callGraph[f]=Array.from(n);return s}function Oe(e,o){const s=[];let t=`/*@AI ${o}`;e.description&&(t+=` - ${e.description.slice(0,50)}`),s.push(t);for(const a of e.imports){const l=Array.isArray(a.members)?a.members.join(","):"";let g=`<${a.module}:${l}`;Array.isArray(a.usedIn)&&a.usedIn.length>0&&(g+=` ->${a.usedIn.join(",")}`),s.push(g)}for(const a of e.classes){let l=a.name;a.superClass&&(l+=`:${a.superClass}`),l+=` ${a.startLine}-${a.endLine}`,a.description&&(l+=` ${a.description}`),s.push(l);for(const g of a.methods){const p=g.static?" +":" .",u=g.kind==="get"?"get:":g.kind==="set"?"set:":"";let i=`${p}${u}${g.name}(${g.params}) ${g.line}`;g.description&&(i+=` ${g.description}`),s.push(i)}}for(const a of e.functions){let l=`${a.name}(${a.params}) ${a.startLine}-${a.endLine}`;a.description&&(l+=` ${a.description}`),s.push(l)}for(const a of e.constants){let l=`${a.name} ${a.line}`;a.description&&(l+=` ${a.description}`),s.push(l)}return s.push("@AI*/"),s.join(`
28
- `)}function we(e){let o=e;return o=o.replace(/\/\*@AI[\s\S]*?@AI\*\/\s*/g,""),o=o.replace(/\/\*\*[\s\S]*?@ai-context-end[\s\S]*?\*\/\s*/g,""),o=o.replace(/^\/\*\*[\s\S]*?\*\/\s*\n?/,""),o}function me(e,o){var t,a,l;const s=[`@FNMAP ${E.basename(e)}/`];for(const{relativePath:g,info:p}of o){let i=`#${E.basename(g)}`;p.description&&(i+=` ${p.description.slice(0,50)}`),s.push(i);for(const r of p.imports){const d=Array.isArray(r.members)?r.members.join(","):"";s.push(` <${r.module}:${d}`)}for(const r of p.classes){let d=` ${r.name}`;r.superClass&&(d+=`:${r.superClass}`),d+=` ${r.startLine}-${r.endLine}`,r.description&&(d+=` ${r.description}`),s.push(d);for(const m of r.methods){const F=m.static?" +":" .",f=m.kind==="get"?"get:":m.kind==="set"?"set:":"";let n=`${F}${f}${m.name}(${m.params}) ${m.line}`;m.description&&(n+=` ${m.description}`);const c=`${r.name}.${m.name}`,h=((t=p.callGraph)==null?void 0:t[c])??((a=p.callGraph)==null?void 0:a[m.name]);Array.isArray(h)&&h.length>0&&(n+=` →${h.join(",")}`),s.push(n)}}for(const r of p.functions){let d=` ${r.name}(${r.params}) ${r.startLine}-${r.endLine}`;r.description&&(d+=` ${r.description}`);const m=(l=p.callGraph)==null?void 0:l[r.name];Array.isArray(m)&&m.length>0&&(d+=` →${m.join(",")}`),s.push(d)}for(const r of p.constants){let d=` ${r.name} ${r.line}`;r.description&&(d+=` ${r.description}`),s.push(d)}}return s.push("@FNMAP"),s.join(`
29
- `)}function pe(e,o){const s=["flowchart TD"],t=r=>"id_"+r.replace(/[^a-zA-Z0-9]/g,d=>`_${d.charCodeAt(0)}_`),a=r=>r.replace(/"/g,"#quot;"),l=o.functions.map(r=>r.name),g=[];for(const r of o.classes)for(const d of r.methods)g.push(`${r.name}.${d.name}`);const p=[...l,...g];if(p.length===0)return null;const u=E.basename(e,E.extname(e));s.push(` subgraph ${t(u)}["${u}"]`);for(const r of p)s.push(` ${t(r)}["${a(r)}"]`);s.push(" end");const i=o.callGraph??{};for(const[r,d]of Object.entries(i))if(Array.isArray(d)){for(const m of d)if(p.includes(m)||m.includes(".")){const F=p.includes(m)?m:m.split(".").pop();(p.includes(m)||p.some(f=>f.endsWith(F)))&&s.push(` ${t(r)} --> ${t(m)}`)}}return s.join(`
30
- `)}function ge(e,o){const s=["flowchart TD"],t=u=>"id_"+u.replace(/[^a-zA-Z0-9]/g,i=>`_${i.charCodeAt(0)}_`),a=u=>u.replace(/"/g,"#quot;"),l=new Map,g=[];for(const{relativePath:u,info:i}of o){const r=E.basename(u,E.extname(u)),d=i.functions.map(n=>n.name),m=[];for(const n of i.classes)for(const c of n.methods)m.push(`${n.name}.${c.name}`);const F=[...d,...m];l.set(u,{fileName:r,functions:F});const f=i.callGraph??{};for(const[n,c]of Object.entries(f))if(Array.isArray(c))for(const h of c)g.push({file:u,fileName:r,caller:n,callee:h})}for(const[,{fileName:u,functions:i}]of l)if(i.length!==0){s.push(` subgraph ${t(u)}["${a(u)}"]`);for(const r of i)s.push(` ${t(u)}_${t(r)}["${a(r)}"]`);s.push(" end")}const p=new Set;for(const{fileName:u,caller:i,callee:r}of g){const d=`${t(u)}_${t(i)}`;let m=null;for(const[,{fileName:F,functions:f}]of l)if(f.includes(r)){m=`${t(F)}_${t(r)}`;break}if(!m){const F=[...l.keys()].find(f=>{var n;return((n=l.get(f))==null?void 0:n.fileName)===u});if(F){const f=l.get(F);f!=null&&f.functions.includes(r)&&(m=`${t(u)}_${t(r)}`)}}if(m){const F=`${d}-->${m}`;p.has(F)||(s.push(` ${d} --> ${m}`),p.add(F))}}return s.join(`
31
- `)}function he(e){const o=ie(e);if(!o.valid)return{success:!1,error:o.error,errorType:o.errorType??b.VALIDATION_ERROR};try{const s=A.readFileSync(e,"utf-8"),t=ue(s,e);return t?oe(t)?{success:!1,error:t.parseError,errorType:t.errorType,loc:t.loc}:{success:!0,info:t}:{success:!1,error:"Analysis returned null / 分析返回空值",errorType:b.PARSE_ERROR}}catch(s){const t=s;return{success:!1,error:U(b.FILE_READ_ERROR,"Failed to read or process file / 读取或处理文件失败",{file:e,suggestion:t.message}),errorType:b.FILE_READ_ERROR}}}const Le=`
22
+ `),q}function k(){return q||Y()}const _e={get opts(){return k().opts.bind(k())},get args(){return k().args},get parse(){return k().parse.bind(k())}};function fe(e){const s=[".fnmaprc",".fnmaprc.json"];for(const n of s){const i=E.join(e,n);if(x.existsSync(i))try{const l=x.readFileSync(i,"utf-8");if(!l.trim()){$.warn(`Config file is empty: ${n}. Using default config / 配置文件为空,使用默认配置`);continue}let g;try{g=JSON.parse(l)}catch(d){const a=d,o=V(C.CONFIG_ERROR,`Failed to parse config file: ${n} / 配置文件解析失败`,{file:i,line:a.lineNumber,column:a.columnNumber,suggestion:"Check JSON syntax, ensure proper quotes and commas / 检查 JSON 语法,确保引号和逗号正确"});$.warn(o);continue}const m=Q(g);if(!m.valid){$.warn(`Invalid config in ${n}: ${m.error}`);continue}return{config:g,source:n}}catch(l){const g=l,m=V(C.FILE_READ_ERROR,`Failed to read config file: ${n} / 配置文件读取失败`,{file:i,suggestion:g.message});$.warn(m)}}const r=E.join(e,"package.json");if(x.existsSync(r))try{const n=JSON.parse(x.readFileSync(r,"utf-8"));if(n.fnmap){const i=Q(n.fnmap);if(!i.valid)$.warn(`Invalid fnmap config in package.json: ${i.error}`);else return{config:n.fnmap,source:"package.json#fnmap"}}}catch{}return{config:null,source:null}}function de(e){return e?{...H,...e,exclude:[...e.exclude??[]]}:H}function ee(e){return e.endsWith(".d.ts")||e.endsWith(".d.tsx")||e.endsWith(".d.mts")}function Ne(e){try{return P.execSync("git rev-parse --show-toplevel",{cwd:e,encoding:"utf-8"}).trim()}catch{return null}}function pe(e,s=!1){const r=[];try{const n=Ne(e);if(!n)return[];let i;if(s)i=P.execSync("git diff --cached --name-only --diff-filter=ACMR",{cwd:e,encoding:"utf-8"});else{const m=P.execSync("git diff --cached --name-only --diff-filter=ACMR",{cwd:e,encoding:"utf-8"}),d=P.execSync("git diff --name-only --diff-filter=ACMR",{cwd:e,encoding:"utf-8"}),a=P.execSync("git ls-files --others --exclude-standard",{cwd:e,encoding:"utf-8"});i=`${m}
23
+ ${d}
24
+ ${a}`}const l=i.split(`
25
+ `).map(m=>m.trim()).filter(Boolean).filter(m=>{const d=E.extname(m);return z.includes(d)&&!ee(m)}),g=[...new Set(l)];for(const m of g){const d=E.resolve(n,m);x.existsSync(d)&&d.startsWith(E.resolve(e))&&r.push(d)}}catch{return[]}return r}function Oe(e){const s=[];if(!x.existsSync(e))return s;try{const r=x.readdirSync(e,{withFileTypes:!0});for(const n of r)if(n.isFile()){const i=E.extname(n.name);z.includes(i)&&!ee(n.name)&&s.push(E.join(e,n.name))}}catch{return s}return s}function W(e,s=e,r=Z,n=0,i=new Set){const l=[];if(!x.existsSync(e))return $.warn(`Directory does not exist: ${e} / 目录不存在`),l;if(n>X)return $.warn(`Max directory depth (${X}) exceeded: ${e} / 超过最大目录深度`),l;let g;try{g=x.realpathSync(e)}catch(d){const a=d;return $.warn(`Cannot resolve real path: ${e}. Reason: ${a.message} / 无法解析真实路径`),l}if(i.has(g))return $.warn(`Circular reference detected, skipping: ${e} / 检测到循环引用`),l;i.add(g);let m;try{m=x.readdirSync(e,{withFileTypes:!0})}catch(d){const a=d;return a.code==="EACCES"||a.code==="EPERM"?$.warn(`Permission denied: ${e} / 权限不足`):$.warn(`Failed to read directory: ${e}. Reason: ${a.message} / 读取目录失败`),l}for(const d of m)try{const a=E.join(e,d.name);if(d.isDirectory())r.includes(d.name)||l.push(...W(a,s,r,n+1,i));else if(d.isFile()){const o=E.extname(d.name);z.includes(o)&&!ee(d.name)&&l.push(E.relative(s,a))}}catch(a){const o=a;$.warn(`Error processing entry: ${d.name}. Reason: ${o.message} / 处理条目出错`)}return l}function G(e){if(!e)return"";const r=e.value.split(`
26
+ `).map(n=>n.replace(/^\s*\*\s?/,"").trim());for(const n of r)if(n.startsWith("@description "))return n.slice(13).trim().slice(0,60);for(const n of r)if(n&&!n.startsWith("@")&&!n.startsWith("/"))return n.slice(0,60);return""}const J=typeof B=="function"?B:B.default;function ue(e,s){var u,R;if(e==null)return{parseError:"Code content is null or undefined / 代码内容为空",errorType:C.VALIDATION_ERROR};if(typeof e!="string")return{parseError:"Code must be a string / 代码必须是字符串类型",errorType:C.VALIDATION_ERROR};if(!e.trim())return{description:"",imports:[],functions:[],classes:[],constants:[],callGraph:{}};const r={description:"",imports:[],functions:[],classes:[],constants:[],callGraph:{}},n=e.match(/^\/\*\*[\s\S]*?\*\//);if(n){const t=n[0].split(`
27
+ `).map(c=>c.replace(/^\s*\*\s?/,"").trim()).filter(c=>c&&!c.startsWith("/")&&!c.startsWith("@ai"));for(const c of t)if(c.startsWith("@description ")){r.description=c.slice(13).trim();break}if(!r.description&&t.length>0){const c=t.find(y=>!y.startsWith("@"));c&&(r.description=c)}}let i;try{const f=s&&(s.endsWith(".ts")||s.endsWith(".tsx"));i=Fe.parse(e,{sourceType:"unambiguous",plugins:["jsx","classPrivateProperties","classPrivateMethods",...f?["typescript"]:[]]})}catch(f){const t=f;return{parseError:V(C.PARSE_ERROR,`Syntax error: ${t.message} / 语法错误`,{file:s??void 0,line:(u=t.loc)==null?void 0:u.line,column:(R=t.loc)==null?void 0:R.column,suggestion:"Check syntax errors in the file / 检查文件中的语法错误"}),loc:t.loc,errorType:C.PARSE_ERROR}}const l=new Map,g=new Map,m=new Map;function d(f){var c,y,F;let t=f;for(;t;){if(t.node.type==="FunctionDeclaration"){const h=t.node;if(h.id)return h.id.name}if(t.node.type==="ClassMethod"){const h=t.node,I=(c=t.parentPath)==null?void 0:c.parentPath,S=I==null?void 0:I.node,b=((y=S==null?void 0:S.id)==null?void 0:y.name)??"",v=((F=h.key)==null?void 0:F.name)??"";return b?`${b}.${v}`:v}if(t.node.type==="ArrowFunctionExpression"||t.node.type==="FunctionExpression"){const h=t.parent;if((h==null?void 0:h.type)==="VariableDeclarator"){const S=h.id;if(S!=null&&S.name)return S.name}}t=t.parentPath}return null}J(i,{VariableDeclarator(f){var c,y,F,h;const t=f.node;if(((c=t.init)==null?void 0:c.type)==="CallExpression"&&((y=t.init.callee)==null?void 0:y.type)==="Identifier"&&t.init.callee.name==="require"&&((h=(F=t.init.arguments)==null?void 0:F[0])==null?void 0:h.type)==="StringLiteral"){const I=t.init.arguments[0].value;if(l.has(I)||l.set(I,new Set),t.id.type==="Identifier"){const S=t.id.name;l.get(I).add(S),g.set(S,I),m.set(S,new Set)}else if(t.id.type==="ObjectPattern"){for(const S of t.id.properties)if(S.type==="ObjectProperty"&&S.key.type==="Identifier"){const b=S.value.type==="Identifier"?S.value.name:S.key.name;l.get(I).add(S.key.name),g.set(b,I),m.set(b,new Set)}}}},CallExpression(f){var c,y,F,h,I,S;const t=f.node;if(((c=t.callee)==null?void 0:c.type)==="Identifier"&&t.callee.name==="require"&&((F=(y=t.arguments)==null?void 0:y[0])==null?void 0:F.type)==="StringLiteral"){const b=f.parent;if((b==null?void 0:b.type)==="MemberExpression"&&((h=b.property)==null?void 0:h.type)==="Identifier"){const v=t.arguments[0].value;l.has(v)||l.set(v,new Set),l.get(v).add(b.property.name);const N=(I=f.parentPath)==null?void 0:I.parent;if((N==null?void 0:N.type)==="VariableDeclarator"){const O=N;((S=O.id)==null?void 0:S.type)==="Identifier"&&(g.set(O.id.name,v),m.set(O.id.name,new Set))}}}},ImportDeclaration(f){const t=f.node,c=t.source.value;l.has(c)||l.set(c,new Set);for(const y of t.specifiers){let F,h;if(y.type==="ImportDefaultSpecifier")F="default",h=y.local.name;else if(y.type==="ImportNamespaceSpecifier")F="*",h=y.local.name;else if(y.type==="ImportSpecifier"){const I=y.imported;F=I.type==="Identifier"?I.name:I.value,h=y.local.name}F&&h&&(l.get(c).add(F),g.set(h,c),m.set(h,new Set))}}}),J(i,{Identifier(f){const t=f.node.name;if(m.has(t)){const c=f.parent;if((c==null?void 0:c.type)==="VariableDeclarator"&&c.id===f.node||(c==null?void 0:c.type)==="ImportSpecifier"||(c==null?void 0:c.type)==="ImportDefaultSpecifier")return;const y=d(f);y&&m.get(t).add(y)}},FunctionDeclaration(f){var b,v,N,O,L;const t=f.node,c=((b=t.id)==null?void 0:b.name)??"[anonymous]",y=t.params.map(_=>{var D,j;return _.type==="Identifier"?_.name:_.type==="AssignmentPattern"&&((D=_.left)==null?void 0:D.type)==="Identifier"?_.left.name+"?":_.type==="RestElement"&&((j=_.argument)==null?void 0:j.type)==="Identifier"?"..."+_.argument.name:"?"}),F=((N=(v=t.loc)==null?void 0:v.start)==null?void 0:N.line)??0,h=((L=(O=t.loc)==null?void 0:O.end)==null?void 0:L.line)??0;let I="";const S=t.leadingComments;S&&S.length>0&&(I=G(S[S.length-1])),r.functions.push({name:c,params:y.join(","),startLine:F,endLine:h,description:I})},ClassDeclaration(f){var v,N,O,L,_,D,j,ne,te,re;const t=f.node,c=((v=t.id)==null?void 0:v.name)??"[anonymous]",y=((O=(N=t.loc)==null?void 0:N.start)==null?void 0:O.line)??0,F=((_=(L=t.loc)==null?void 0:L.end)==null?void 0:_.line)??0,h=((D=t.superClass)==null?void 0:D.type)==="Identifier"?t.superClass.name:null;let I="";const S=t.leadingComments;S&&S.length>0&&(I=G(S[S.length-1]));const b=[];if((j=t.body)!=null&&j.body){for(const w of t.body.body)if(w.type==="ClassMethod"){const Se=((ne=w.key)==null?void 0:ne.type)==="Identifier"?w.key.name:"[computed]",Ee=w.params.map(M=>{var oe;return M.type==="Identifier"?M.name:M.type==="AssignmentPattern"&&((oe=M.left)==null?void 0:oe.type)==="Identifier"?M.left.name+"?":"?"}),Ie=((re=(te=w.loc)==null?void 0:te.start)==null?void 0:re.line)??0;let se="";const U=w.leadingComments;U&&U.length>0&&(se=G(U[U.length-1])),b.push({name:Se,params:Ee.join(","),line:Ie,static:w.static,kind:w.kind,description:se})}}r.classes.push({name:c,superClass:h,startLine:y,endLine:F,methods:b,description:I})},VariableDeclaration(f){var c,y,F;if(f.parent.type!=="Program")return;const t=f.node;if(t.kind==="const"){let h="";const I=t.leadingComments;I&&I.length>0&&(h=G(I[I.length-1]));for(const S of t.declarations){const b=((c=S.id)==null?void 0:c.type)==="Identifier"?S.id.name:void 0;if(b&&b===b.toUpperCase()&&b.length>2){const v=((F=(y=t.loc)==null?void 0:y.start)==null?void 0:F.line)??0;r.constants.push({name:b,line:v,description:h})}}}}});for(const[f,t]of l){const c=new Set;for(const y of g.keys())if(g.get(y)===f&&m.has(y))for(const F of m.get(y))c.add(F);r.imports.push({module:f,members:Array.from(t),usedIn:Array.from(c)})}const a=new Set;for(const f of r.functions)a.add(f.name);for(const f of r.classes)for(const t of f.methods)a.add(t.name),a.add(`${f.name}.${t.name}`);const o=new Set(g.keys()),p=new Map;J(i,{CallExpression(f){var y,F;const t=f.node;let c=null;if(t.callee.type==="Identifier")c=t.callee.name;else if(t.callee.type==="MemberExpression"&&((y=t.callee.property)==null?void 0:y.type)==="Identifier"){const h=((F=t.callee.object)==null?void 0:F.type)==="Identifier"?t.callee.object.name:void 0,I=t.callee.property.name;h&&o.has(h)?c=`${h}.${I}`:c=I}if(c){const h=d(f);if(h&&h!==c){const I=a.has(c),S=o.has(c)||c.includes(".")&&o.has(c.split(".")[0]);(I||S)&&(p.has(h)||p.set(h,new Set),p.get(h).add(c))}}}}),r.callGraph={};for(const[f,t]of p)r.callGraph[f]=Array.from(t);return r.isPureType=we(i),r}function we(e){let s=!1;for(const r of e.program.body){switch(r.type){case"TSTypeAliasDeclaration":case"TSInterfaceDeclaration":case"TSEnumDeclaration":break;case"ImportDeclaration":r.importKind!=="type"&&r.specifiers.some(i=>i.type==="ImportSpecifier"?i.importKind!=="type":!0)&&r.specifiers.length>0&&(s=!0);break;case"ExportNamedDeclaration":if(r.exportKind==="type")break;if(r.declaration){const n=r.declaration.type;n!=="TSTypeAliasDeclaration"&&n!=="TSInterfaceDeclaration"&&(s=!0)}else r.specifiers&&r.specifiers.length>0&&r.specifiers.some(i=>i.type==="ExportSpecifier"?i.exportKind!=="type":!0)&&(s=!0);break;case"ExportDefaultDeclaration":s=!0;break;case"ExportAllDeclaration":r.exportKind!=="type"&&(s=!0);break;default:s=!0;break}if(s)break}return!s}function Te(e,s){const r=[];let n=`/*@AI ${s}`;e.description&&(n+=` - ${e.description.slice(0,50)}`),r.push(n);for(const i of e.imports){const l=Array.isArray(i.members)?i.members.join(","):"";let g=`<${i.module}:${l}`;Array.isArray(i.usedIn)&&i.usedIn.length>0&&(g+=` ->${i.usedIn.join(",")}`),r.push(g)}for(const i of e.classes){let l=i.name;i.superClass&&(l+=`:${i.superClass}`),l+=` ${i.startLine}-${i.endLine}`,i.description&&(l+=` ${i.description}`),r.push(l);for(const g of i.methods){const m=g.static?" +":" .",d=g.kind==="get"?"get:":g.kind==="set"?"set:":"";let a=`${m}${d}${g.name}(${g.params}) ${g.line}`;g.description&&(a+=` ${g.description}`),r.push(a)}}for(const i of e.functions){let l=`${i.name}(${i.params}) ${i.startLine}-${i.endLine}`;i.description&&(l+=` ${i.description}`),r.push(l)}for(const i of e.constants){let l=`${i.name} ${i.line}`;i.description&&(l+=` ${i.description}`),r.push(l)}return r.push("@AI*/"),r.join(`
28
+ `)}function Le(e){let s=e;return s=s.replace(/\/\*@AI[\s\S]*?@AI\*\/\s*/g,""),s=s.replace(/\/\*\*[\s\S]*?@ai-context-end[\s\S]*?\*\/\s*/g,""),s=s.replace(/^\/\*\*[\s\S]*?\*\/\s*\n?/,""),s}function me(e,s){var n,i,l;const r=[`@FNMAP ${E.basename(e)}/`];for(const{relativePath:g,info:m}of s){let a=`#${E.basename(g)}`;m.description&&(a+=` ${m.description.slice(0,50)}`),r.push(a);for(const o of m.imports){const p=Array.isArray(o.members)?o.members.join(","):"";r.push(` <${o.module}:${p}`)}for(const o of m.classes){let p=` ${o.name}`;o.superClass&&(p+=`:${o.superClass}`),p+=` ${o.startLine}-${o.endLine}`,o.description&&(p+=` ${o.description}`),r.push(p);for(const u of o.methods){const R=u.static?" +":" .",f=u.kind==="get"?"get:":u.kind==="set"?"set:":"";let t=`${R}${f}${u.name}(${u.params}) ${u.line}`;u.description&&(t+=` ${u.description}`);const c=`${o.name}.${u.name}`,y=((n=m.callGraph)==null?void 0:n[c])??((i=m.callGraph)==null?void 0:i[u.name]);Array.isArray(y)&&y.length>0&&(t+=` →${y.join(",")}`),r.push(t)}}for(const o of m.functions){let p=` ${o.name}(${o.params}) ${o.startLine}-${o.endLine}`;o.description&&(p+=` ${o.description}`);const u=(l=m.callGraph)==null?void 0:l[o.name];Array.isArray(u)&&u.length>0&&(p+=` →${u.join(",")}`),r.push(p)}for(const o of m.constants){let p=` ${o.name} ${o.line}`;o.description&&(p+=` ${o.description}`),r.push(p)}}return r.push("@FNMAP"),r.join(`
29
+ `)}function ge(e,s){const r=["flowchart TD"],n=o=>"id_"+o.replace(/[^a-zA-Z0-9]/g,p=>`_${p.charCodeAt(0)}_`),i=o=>o.replace(/"/g,"#quot;"),l=s.functions.map(o=>o.name),g=[];for(const o of s.classes)for(const p of o.methods)g.push(`${o.name}.${p.name}`);const m=[...l,...g];if(m.length===0)return null;const d=E.basename(e,E.extname(e));r.push(` subgraph ${n(d)}["${d}"]`);for(const o of m)r.push(` ${n(o)}["${i(o)}"]`);r.push(" end");const a=s.callGraph??{};for(const[o,p]of Object.entries(a))if(Array.isArray(p)){for(const u of p)if(m.includes(u)||u.includes(".")){const R=m.includes(u)?u:u.split(".").pop();(m.includes(u)||m.some(f=>f.endsWith(R)))&&r.push(` ${n(o)} --> ${n(u)}`)}}return r.join(`
30
+ `)}function ye(e,s){const r=["flowchart TD"],n=d=>"id_"+d.replace(/[^a-zA-Z0-9]/g,a=>`_${a.charCodeAt(0)}_`),i=d=>d.replace(/"/g,"#quot;"),l=new Map,g=[];for(const{relativePath:d,info:a}of s){const o=E.basename(d,E.extname(d)),p=a.functions.map(t=>t.name),u=[];for(const t of a.classes)for(const c of t.methods)u.push(`${t.name}.${c.name}`);const R=[...p,...u];l.set(d,{fileName:o,functions:R});const f=a.callGraph??{};for(const[t,c]of Object.entries(f))if(Array.isArray(c))for(const y of c)g.push({file:d,fileName:o,caller:t,callee:y})}for(const[,{fileName:d,functions:a}]of l)if(a.length!==0){r.push(` subgraph ${n(d)}["${i(d)}"]`);for(const o of a)r.push(` ${n(d)}_${n(o)}["${i(o)}"]`);r.push(" end")}const m=new Set;for(const{fileName:d,caller:a,callee:o}of g){const p=`${n(d)}_${n(a)}`;let u=null;for(const[,{fileName:R,functions:f}]of l)if(f.includes(o)){u=`${n(R)}_${n(o)}`;break}if(!u){const R=[...l.keys()].find(f=>{var t;return((t=l.get(f))==null?void 0:t.fileName)===d});if(R){const f=l.get(R);f!=null&&f.functions.includes(o)&&(u=`${n(d)}_${n(o)}`)}}if(u){const R=`${p}-->${u}`;m.has(R)||(r.push(` ${p} --> ${u}`),m.add(R))}}return r.join(`
31
+ `)}function he(e){const s=ae(e);if(!s.valid)return{success:!1,error:s.error,errorType:s.errorType??C.VALIDATION_ERROR};try{const r=x.readFileSync(e,"utf-8"),n=ue(r,e);return n?ie(n)?{success:!1,error:n.parseError,errorType:n.errorType,loc:n.loc}:{success:!0,info:n}:{success:!1,error:"Analysis returned null / 分析返回空值",errorType:C.PARSE_ERROR}}catch(r){const n=r;return{success:!1,error:V(C.FILE_READ_ERROR,"Failed to read or process file / 读取或处理文件失败",{file:e,suggestion:n.message}),errorType:C.FILE_READ_ERROR}}}const De=`
32
32
 
33
33
  ## .fnmap Code Index Format
34
34
 
@@ -53,8 +53,8 @@ The \`.fnmap\` file provides a structured code index for quick navigation. Read
53
53
  1. Every global variable, function, class, and file module must have a **concise comment describing its purpose or functionality** - avoid describing anything else
54
54
  2. When updating code, always update related comments to reflect the changes
55
55
  3. Prefer encapsulating logic in functions rather than writing flat, sequential code
56
- `;function je(e){const o=["CLAUDE.md","AGENTS.md"],s=A.readdirSync(e);for(const t of o){const a=s.find(l=>l.toLowerCase()===t.toLowerCase());if(a){const l=E.join(e,a);if(A.readFileSync(l,"utf-8").includes(".fnmap Code Index Format")){console.log(`${v.yellow}!${v.reset} ${a} already contains fnmap documentation`);continue}A.appendFileSync(l,Le),console.log(`${v.green}✓${v.reset} Appended fnmap documentation to ${a}`)}}}function ye(){const e=Y();e.parse(process.argv);const o=e.opts(),s=e.args;o.quiet&&ae(!0);const t=E.resolve(o.project);if(o.init){const i=E.join(t,".fnmaprc");if(A.existsSync(i))console.log(`${v.yellow}!${v.reset} Config file already exists: .fnmaprc`);else{const r={enable:!0,include:["src/**/*.js","src/**/*.ts","src/**/*.jsx","src/**/*.tsx"],exclude:["node_modules","dist","build",".next","coverage","__pycache__",".cache"]};A.writeFileSync(i,JSON.stringify(r,null,2)),console.log(`${v.green}✓${v.reset} Created config file: .fnmaprc`)}je(t);return}const a=[...o.files??[],...s].filter(i=>A.existsSync(i));let l=[];if(o.changed||o.staged){const i=de(t,o.staged);if(i.length===0){S.info("No git changed code files detected");return}const r=new Set;for(const d of i)r.add(E.dirname(d));for(const d of r){const m=Ne(d);l.push(...m)}}else if(a.length>0)l=a.map(i=>E.isAbsolute(i)?i:E.resolve(t,i));else if(o.dir){const i=E.resolve(t,o.dir);l=W(i,t).map(d=>E.join(t,d))}else{const{config:i,source:r}=le(t);if(i){if(S.info(`Using config: ${r}`),i.enable===!1){S.info("Config file has enable set to false, skipping processing");return}const d=fe(i),m=[...K,...d.exclude];if(d.include)for(const F of d.include){const f=F.replace(/\/\*\*\/.*$/,"").replace(/\*\*\/.*$/,""),n=f?E.resolve(t,f):t;if(A.existsSync(n)){const c=W(n,t,m);l.push(...c.map(h=>E.join(t,h)))}}}else{S.warn("No config file found. Use fnmap init to create config, or use --dir/--files to specify scope"),S.info(""),S.info("Supported config files: .fnmaprc, .fnmaprc.json, package.json#fnmap");return}}if(l.length===0){S.info("No files found to process");return}l=[...new Set(l)],S.info("=".repeat(50)),S.title("fnmap - AI Code Indexing Tool"),S.info("=".repeat(50));let g=0,p=0;const u=new Map;for(const i of l){const r=E.relative(t,i);S.info(`
57
- Analyzing: ${r}`);const d=he(i);if(d.success){g++;const m=d.info;S.success(`Imports: ${m.imports.length}, Functions: ${m.functions.length}, Classes: ${m.classes.length}, Constants: ${m.constants.length}`);const F=E.dirname(i);u.has(F)||u.set(F,[]),u.get(F).push({relativePath:r,info:m})}else p++,S.error(d.error)}if(u.size>0){S.info(`
58
- Generating .fnmap index...`);for(const[i,r]of u)try{const d=me(i,r),m=E.join(i,".fnmap");A.writeFileSync(m,d),S.success(E.relative(t,m))}catch(d){const m=d;S.error(`Failed to generate .fnmap for ${E.relative(t,i)}: ${m.message}`)}}if(o.mermaid&&u.size>0){if(S.info(`
59
- Generating Mermaid call graphs...`),o.mermaid==="file"||o.mermaid===!0)for(const[i,r]of u)for(const{relativePath:d,info:m}of r)try{const F=pe(d,m);if(F){const f=E.basename(d,E.extname(d)),n=E.join(i,`${f}.mermaid`);A.writeFileSync(n,F),S.success(E.relative(t,n))}}catch(F){const f=F;S.error(`Failed to generate mermaid for ${d}: ${f.message}`)}else if(o.mermaid==="project")try{const i=[];for(const[,m]of u)i.push(...m);const r=ge(t,i),d=E.join(t,".fnmap.mermaid");A.writeFileSync(d,r),S.success(E.relative(t,d))}catch(i){const r=i;S.error(`Failed to generate project mermaid: ${r.message}`)}}S.info(`
60
- `+"=".repeat(50)),S.info(`Complete! Analyzed: ${v.green}${g}${v.reset}, Failed: ${p>0?v.red:""}${p}${v.reset}`),S.info("=".repeat(50))}require.main===module&&ye();exports.COLORS=v;exports.DEFAULT_CONFIG=Q;exports.DEFAULT_EXCLUDES=K;exports.ErrorTypes=b;exports.MAX_DIR_DEPTH=H;exports.MAX_FILE_SIZE=X;exports.SUPPORTED_EXTENSIONS=z;exports.analyzeFile=ue;exports.extractJSDocDescription=G;exports.formatError=U;exports.generateAiMap=me;exports.generateFileMermaid=pe;exports.generateHeader=Oe;exports.generateProjectMermaid=ge;exports.getGitChangedFiles=de;exports.getVersion=ce;exports.isParseError=oe;exports.isProcessFailure=Ce;exports.isProcessSuccess=Ie;exports.isQuietMode=be;exports.isValidationFailure=ve;exports.isValidationSuccess=Ae;exports.loadConfig=le;exports.logger=S;exports.main=ye;exports.mergeConfig=fe;exports.processFile=he;exports.program=_e;exports.removeExistingHeaders=we;exports.scanDirectory=W;exports.setQuietMode=ae;exports.setupCLI=Y;exports.validateConfig=Z;exports.validateFilePath=ie;
56
+ `;function je(e){const s=["CLAUDE.md","AGENTS.md"],r=x.readdirSync(e);for(const n of s){const i=r.find(l=>l.toLowerCase()===n.toLowerCase());if(i){const l=E.join(e,i);if(x.readFileSync(l,"utf-8").includes(".fnmap Code Index Format")){console.log(`${A.yellow}!${A.reset} ${i} already contains fnmap documentation`);continue}x.appendFileSync(l,De),console.log(`${A.green}✓${A.reset} Appended fnmap documentation to ${i}`)}}}function $e(){const e=Y();e.parse(process.argv);const s=e.opts(),r=e.args;s.quiet&&ce(!0);const n=E.resolve(s.project);if(s.init){const a=E.join(n,".fnmaprc");if(x.existsSync(a))console.log(`${A.yellow}!${A.reset} Config file already exists: .fnmaprc`);else{const o={enable:!0,include:["src/**/*.js","src/**/*.ts","src/**/*.jsx","src/**/*.tsx"],exclude:["node_modules","dist","build",".next","coverage","__pycache__",".cache"]};x.writeFileSync(a,JSON.stringify(o,null,2)),console.log(`${A.green}✓${A.reset} Created config file: .fnmaprc`)}je(n);return}const i=[...s.files??[],...r].filter(a=>x.existsSync(a));let l=[];if(s.changed||s.staged){const a=pe(n,s.staged);if(a.length===0){$.info("No git changed code files detected");return}const o=new Set;for(const p of a)o.add(E.dirname(p));for(const p of o){const u=Oe(p);l.push(...u)}}else if(i.length>0)l=i.map(a=>E.isAbsolute(a)?a:E.resolve(n,a));else if(s.dir){const a=E.resolve(n,s.dir);l=W(a,n).map(p=>E.join(n,p))}else{const{config:a,source:o}=fe(n);if(a){if($.info(`Using config: ${o}`),a.enable===!1){$.info("Config file has enable set to false, skipping processing");return}const p=de(a),u=[...Z,...p.exclude];if(p.include)for(const R of p.include){const f=R.replace(/\/\*\*\/.*$/,"").replace(/\*\*\/.*$/,""),t=f?E.resolve(n,f):n;if(x.existsSync(t)){const c=W(t,n,u);l.push(...c.map(y=>E.join(n,y)))}}}else{$.warn("No config file found. Use fnmap init to create config, or use --dir/--files to specify scope"),$.info(""),$.info("Supported config files: .fnmaprc, .fnmaprc.json, package.json#fnmap");return}}if(l.length===0){$.info("No files found to process");return}l=[...new Set(l)],$.info("=".repeat(50)),$.title("fnmap - AI Code Indexing Tool"),$.info("=".repeat(50));let g=0,m=0;const d=new Map;for(const a of l){const o=E.relative(n,a);$.info(`
57
+ Analyzing: ${o}`);const p=he(a);if(p.success){g++;const u=p.info;if(u.isPureType){$.info("Skipped (pure type file) / 跳过纯类型文件");continue}$.success(`Imports: ${u.imports.length}, Functions: ${u.functions.length}, Classes: ${u.classes.length}, Constants: ${u.constants.length}`);const R=E.dirname(a);d.has(R)||d.set(R,[]),d.get(R).push({relativePath:o,info:u})}else m++,$.error(p.error)}if(d.size>0){$.info(`
58
+ Generating .fnmap index...`);for(const[a,o]of d)try{const p=me(a,o),u=E.join(a,".fnmap");x.writeFileSync(u,p),$.success(E.relative(n,u))}catch(p){const u=p;$.error(`Failed to generate .fnmap for ${E.relative(n,a)}: ${u.message}`)}}if(s.mermaid&&d.size>0){if($.info(`
59
+ Generating Mermaid call graphs...`),s.mermaid==="file"||s.mermaid===!0)for(const[a,o]of d)for(const{relativePath:p,info:u}of o)try{const R=ge(p,u);if(R){const f=E.basename(p,E.extname(p)),t=E.join(a,`${f}.mermaid`);x.writeFileSync(t,R),$.success(E.relative(n,t))}}catch(R){const f=R;$.error(`Failed to generate mermaid for ${p}: ${f.message}`)}else if(s.mermaid==="project")try{const a=[];for(const[,u]of d)a.push(...u);const o=ye(n,a),p=E.join(n,".fnmap.mermaid");x.writeFileSync(p,o),$.success(E.relative(n,p))}catch(a){const o=a;$.error(`Failed to generate project mermaid: ${o.message}`)}}$.info(`
60
+ `+"=".repeat(50)),$.info(`Complete! Analyzed: ${A.green}${g}${A.reset}, Failed: ${m>0?A.red:""}${m}${A.reset}`),$.info("=".repeat(50))}require.main===module&&$e();exports.COLORS=A;exports.DEFAULT_CONFIG=H;exports.DEFAULT_EXCLUDES=Z;exports.ErrorTypes=C;exports.MAX_DIR_DEPTH=X;exports.MAX_FILE_SIZE=K;exports.SUPPORTED_EXTENSIONS=z;exports.analyzeFile=ue;exports.extractJSDocDescription=G;exports.formatError=V;exports.generateAiMap=me;exports.generateFileMermaid=ge;exports.generateHeader=Te;exports.generateProjectMermaid=ye;exports.getGitChangedFiles=pe;exports.getVersion=le;exports.isParseError=ie;exports.isProcessFailure=xe;exports.isProcessSuccess=be;exports.isQuietMode=ve;exports.isValidationFailure=Ce;exports.isValidationSuccess=Ae;exports.loadConfig=fe;exports.logger=$;exports.main=$e;exports.mergeConfig=de;exports.processFile=he;exports.program=_e;exports.removeExistingHeaders=Le;exports.scanDirectory=W;exports.setQuietMode=ce;exports.setupCLI=Y;exports.validateConfig=Q;exports.validateFilePath=ae;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@didnhdj/fnmap",
3
- "version": "0.1.9",
3
+ "version": "0.1.10",
4
4
  "description": "AI code indexing tool for analyzing JS/TS code structure and generating structured code maps to help AI understand code quickly",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",