wanshi-kg/outlion

GitHub: wanshi-kg/outlion

基于 tree-sitter WASM 引擎的通用大纲与符号生成器,支持 45 种文件类型与 11 种输出格式,为知识图谱和文档分析提供确定性的结构化数据。

Stars: 0 | Forks: 0

# outlion **面向代码和文档的通用大纲与符号生成器。** 单一 tree-sitter (WASM) 引擎,支持 45 种文件类型,11 种输出格式,并提供确定性的符号/边 API —— 专为知识图谱、文档工具和内容分析而构建。 [![CI](https://static.pigsec.cn/wp-content/uploads/repos/2026/06/d7f0b92718003445.svg)](https://github.com/wanshi-kg/outlion/actions/workflows/ci.yml) [![npm](https://img.shields.io/npm/v/@wanshi-kg/outlion.svg)](https://www.npmjs.com/package/@wanshi-kg/outlion) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) ## 目录 - [功能](#features) - [安装](#installation) - [快速开始](#quick-start) - [支持的文件类型](#supported-file-types) - [输出格式](#output-format) - [Symbol API](#symbol-api-code) - [配置选项](#configuration-options) - [高级用法](#advanced-usage) - [开发](#development) - [贡献](#contributing) - [许可证](#license) ## 🚀 功能 - **45 种文件类型,单一引擎**:文档(Markdown、JSON、XML、YAML、HTML、CSV),代码(14 种语言),配置/数据(TOML、INI、`.properties`/`.env`)以及标记语言(RST、AsciiDoc、LaTeX、Org、Wiki) - **基于 tree-sitter 的代码分析**:每种代码语言都通过统一的 tree-sitter (WASM) 查询核心进行解析 —— 无需为每种语言单独手写解析器 - **符号与边 API**:`extractSymbols` 以确定性的、无需联网的方式枚举代码符号,并为 TS/JS/Python 提供文件内的 `calls`/`imports` 边 - **11 种输出格式**:ascii-tree、JSON、YAML、XML、CSV、SQL、DOT、Mermaid、PlantUML、HTML - **层级结构**:维护正确的父子关系 - **丰富的元数据**:行号、可见性、参数、docstring 等 - **可扩展架构**:轻松添加对新文件类型的支持 - **CLI 工具**:用于批量处理的命令行界面 - **TypeScript 优先**:完整的类型安全和 IntelliSense 支持 ## 📦 安装 ``` npm install @wanshi-kg/outlion # 或从 GitHub 安装:npm install github:wanshi-kg/outlion ``` 安装后即可使用 `outlion` CLI 二进制文件(参见 [CLI 用法](#cli-usage))。 ## 🎯 快速开始 ### 基本用法 ``` import DocumentOutlineGenerator from '@wanshi-kg/outlion'; const generator = new DocumentOutlineGenerator(); // Analyze a file const outline = await generator.generateFromFile('./example.md'); console.log(JSON.stringify(outline, null, 2)); // Or analyze content directly const inline = await generator.generateFromContent( '# Title\n## Subtitle\nContent here', 'md' ); ``` ### 使用选项 ``` const outline = await generator.generateFromFile('./src/app.ts', { includeLineNumbers: true, maxDepth: 3, includePrivate: false, includeComments: true }); ``` ### CLI 用法 ``` # 基础分析 outlion example.ts # 使用 options outlion src/app.py --line-numbers --max-depth 2 --format json # Export formats:ascii-tree(默认)、json、yaml、xml、csv、sql、dot、mermaid、plantuml、html outlion src/app.ts --format mermaid outlion data.csv --format sql --output nodes.sql # Token-lean 树(无行号 / metadata) outlion src/app.ts --format tree --compact # 保存到文件 outlion README.md --output outline.json # 列出支持的 extensions / output formats outlion list-extensions outlion list-formats ``` ## 📋 支持的文件类型 | 扩展名 | 类型 | 功能 | |-----------|------|----------| | `.md`, `.markdown` | Markdown | 标题(H1-H6),支持 frontmatter | | `.json` | JSON | Schema 分析,嵌套对象结构 | | `.xml` | XML | 元素层级,属性检测 | | `.yaml`, `.yml` | YAML | 对象结构,数组处理 | | `.html`, `.htm` | HTML | 标题,语义元素(`
`, `
` 等) | | `.csv` | CSV | 带有推断出 `dataType`(字符串/数字/日期/布尔值/电子邮件/URL)的标题列 | | `.ts`, `.tsx` | TypeScript | 类、接口、函数、类型、枚举 | | `.js`, `.jsx` | JavaScript | 类、函数、变量、方法 | | `.py` | Python | 类、函数、方法、属性、装饰器(tree-sitter) | | `.java` | Java | 类、方法、字段、构造函数 | | `.cs` | C# | 类、方法、属性、事件 | | `.cpp` | C++ | 命名空间、类、结构体、枚举、函数、方法(tree-sitter) | | `.go` | Go | 结构体、接口、函数、方法、字段、常量 | | `.rs` | Rust | 结构体、枚举、trait、impl、函数、模块 | | `.rb`, `.rake`, `.gemspec` | Ruby | 模块、类、方法、单例方法 | | `.php`, `.phtml` | PHP | 命名空间、类、接口、trait、方法、属性 | | `.kt`, `.kts` | Kotlin | 类、接口、对象、函数、属性 | | `.swift` | Swift | 类、结构体、枚举、协议、函数、属性 | | `.scala`, `.sbt` | Scala | 类、对象、trait、方法 | | `.lua` | Lua | 函数、局部函数、表函数 | | `.toml` | TOML | 表、嵌套表、数组表、键/值对 | | `.ini`, `.cfg`, `.conf` | INI | 节以及键/值对(`.conf` 尽最大努力解析) | | `.properties`, `.env` | Properties | 带有值的扁平键/值对 | | `.rst`, `.rest` | reStructuredText | 装饰符顺序的节层级、指令 | | `.adoc`, `.asciidoc` | AsciiDoc | `=` 级别标题、源码/告示块 | | `.tex`, `.latex` | LaTeX | `\section` 家族层级、选定的环境 | | `.org` | Org-mode | `*` 星号标题(TODO/优先级/标签)、`#+BEGIN` 块 | | `.wiki`, `.mediawiki` | Wiki | MediaWiki `== ==` 标题、代码块 | 所有代码语言均运行在单一的 tree-sitter (WASM) 查询引擎上。TOML 使用相同的引擎; INI/Properties 和标记格式(RST/AsciiDoc/LaTeX/Org/Wiki)使用行解析器。Protocol Buffers 和 GraphQL 被推迟支持(在锁定的运行时下没有语法 —— 参见 [TECHDEBT.md](TECHDEBT.md))。 ## 📊 输出格式 ### OutlineNode 结构 ``` interface OutlineNode { title: string; // Name/title of the item type: string; // Type: heading, function, class, etc. depth: number; // Nesting level (1 = top-level) line?: number; // Line number (1-based) column?: number; // Column number (1-based) children?: OutlineNode[]; // Child items metadata?: { // Additional information visibility?: 'public' | 'private' | 'protected'; isStatic?: boolean; isAbstract?: boolean; parameters?: Parameter[]; returnType?: string; docstring?: string; // ... more metadata based on file type }; id?: string; // Unique identifier anchor?: string; // Link anchor (for web documents) } ``` ### 示例输出 #### Markdown 文件 ``` [ { "title": "Introduction", "type": "heading", "depth": 1, "line": 1, "anchor": "introduction", "children": [ { "title": "Getting Started", "type": "heading", "depth": 2, "line": 5, "anchor": "getting-started" } ] } ] ``` #### TypeScript 类 ``` [ { "title": "UserService", "type": "class", "depth": 1, "line": 10, "children": [ { "title": "constructor", "type": "method", "depth": 2, "line": 12, "metadata": { "visibility": "public", "parameters": [ {"name": "apiKey", "type": "string"} ] } }, { "title": "getUser", "type": "method", "depth": 2, "line": 16, "metadata": { "visibility": "public", "parameters": [ {"name": "id", "type": "number"} ], "returnType": "Promise" } } ] } ] ``` ### 导出格式化器 相同的大纲可以从库中渲染为任何已注册的格式: ``` import DocumentOutlineGenerator, { formatOutline, getFormats } from '@wanshi-kg/outlion'; const generator = new DocumentOutlineGenerator(); const outline = await generator.generateFromFile('./src/app.ts'); getFormats(); // ['ascii-tree','csv','dot','html','json','mermaid','plantuml','sql','tree','xml','yaml'] const tree = formatOutline(outline, 'ascii-tree', { compact: true }); // token-lean prompt view const diagram = formatOutline(outline, 'mermaid'); // classDiagram / flowchart const rows = formatOutline(outline, 'csv'); // path,title,type,depth,line const inserts = formatOutline(outline, 'sql'); // CREATE TABLE + INSERTs ``` `ascii-tree` 是标准视图(kg-gen 将其渲染到 `{{fileOutline}}` prompt 中)。数据 导出(`json`/`yaml`/`xml`/`csv`/`sql`)适用于工具和存储;图表导出 (`mermaid`/`plantuml`/`dot`/`html`)适用于可视化。PDF 有意不在支持范围内 —— 请使用 `html` + 浏览器的打印为 PDF 功能。 ## 🧬 Symbol API (代码) 除了大纲之外,`extractSymbols` 还**以确定性的、无需联网的方式**枚举代码符号 —— 适用于在任何 LLM 过程之前就需要获取符号集的 AST 种子提取流水线。它返回 每种代码语言的定义,以及 TypeScript、JavaScript 和 Python 文件内的 `calls`/`imports` 边。 ``` import DocumentOutlineGenerator, { hashContent, SYMBOL_SCHEMA_VERSION } from '@wanshi-kg/outlion'; const generator = new DocumentOutlineGenerator(); const table = await generator.extractSymbols(source, 'ts'); // { // schemaVersion: 1, // symbols: [{ name, qualifiedName, kind, span: { startLine, endLine }, exported, signature? }], // references: [{ from, to, kind: 'calls' | 'imports', line }], // } hashContent(source); // sha256 hex — skip re-parsing unchanged files ``` `kind` 是一个小巧、稳定的 **snake_case** 枚举(`function`、`method`、`class`、`interface`、`enum`、 `enum_member`、`struct`、`trait`、`type_alias`、`field`、`property`、`constant`、`module` 等),旨在 完美融入下游的标准化词汇表中。引用**仅限在文件内**解析名称 —— 跨文件解析是消费者的任务。非代码扩展返回空表。 `SymbolTable` 的结构已进行版本控制 (`SYMBOL_SCHEMA_VERSION`),并导出了 JSON Schema (`SYMBOL_TABLE_JSON_SCHEMA`)。 CLI:`outlion symbols src/app.ts`。 ## ⚙️ 配置选项 ``` interface GeneratorOptions { includeLineNumbers?: boolean; // Include position information maxDepth?: number; // Limit nesting depth fileName?: string; // File context for better analysis includePrivate?: boolean; // Include private/internal members includeComments?: boolean; // Include documentation/comments // Custom options for specific generators [key: string]: any; } ``` ## 🔧 高级用法 ### 自定义生成器 为不支持的文件类型创建你自己的生成器: ``` import { OutlineGenerator, OutlineNode, GeneratorOptions } from '@wanshi-kg/outlion'; class SqlGenerator extends OutlineGenerator { async generate(content: string, options: GeneratorOptions = {}): Promise { const nodes: OutlineNode[] = []; // Your parsing logic here const tables = this.extractTables(content); for (const table of tables) { const node = this.createNode( table.name, 'table', 1, table.position, { columns: table.columns } ); nodes.push(node); } return nodes; } getSupportedExtensions(): string[] { return ['sql']; } private extractTables(content: string) { // Implementation here return []; } } // Register the custom generator const generator = new DocumentOutlineGenerator(); generator.registerGenerator('sql', new SqlGenerator()); ``` ### 批量处理 ``` import fs from 'fs/promises'; import path from 'path'; async function analyzeProject(projectPath: string) { const generator = new DocumentOutlineGenerator(); const results = new Map(); async function processDirectory(dir: string) { const entries = await fs.readdir(dir, { withFileTypes: true }); for (const entry of entries) { const fullPath = path.join(dir, entry.name); if (entry.isDirectory() && !entry.name.startsWith('.')) { await processDirectory(fullPath); } else if (entry.isFile()) { const ext = path.extname(entry.name).slice(1); if (generator.isSupported(ext)) { try { const outline = await generator.generateFromFile(fullPath); results.set(fullPath, outline); } catch (error) { console.warn(`Failed to process ${fullPath}:`, error); } } } } } await processDirectory(projectPath); return results; } ``` ## 🧪 开发 ### 环境配置 ``` git clone https://github.com/wanshi-kg/outlion.git cd outlion npm install ``` ### 可用脚本 ``` npm run build # Compile TypeScript npm run dev # Watch mode for development npm test # Run tests npm run test:watch # Watch mode for tests npm run lint # Run ESLint npm run lint:fix # Fix ESLint issues ``` ### 项目结构 ``` src/ ├── index.ts # DocumentOutlineGenerator: registry + outline + Symbol API ├── types.ts # OutlineNode / GeneratorOptions definitions ├── errors.ts # Typed error hierarchy ├── symbols.ts # SymbolTable contract + hashContent ├── cli.ts # CLI (`outlion`) ├── formatters/ # ascii-tree, json, yaml, xml, csv, sql, dot, mermaid, plantuml, html ├── docstrings/ # JSDoc / Javadoc / pydoc / xmldoc extractors ├── generators/ │ ├── OutlineGenerator.ts # Base generator class │ ├── MarkdownGenerator.ts, JsonGenerator.ts, XmlGenerator.ts, YamlGenerator.ts, HtmlGenerator.ts, CsvGenerator.ts │ ├── IniGenerator.ts, PropertiesGenerator.ts # config/data line parsers │ ├── MarkupGenerator.ts + Rst/Asciidoc/Latex/Org/Wiki # markup line parsers │ └── code/ │ ├── TreeSitterGenerator.ts # Shared WASM tree-sitter base (outline + extractSymbols) │ └── Generator.ts # TS, JS, Python, Java, C#, C++, Go, Rust, Ruby, │ # PHP, Kotlin, Swift, Scala, Lua, TOML └── queries//*.scm # tree-sitter outline.scm + references.scm tests/ ├── *.test.ts # main, golden, formatters, symbols, docstrings └── fixtures// # input.* + expected.json ``` ### 添加新的语言支持 对于 tree-sitter 语言(目标架构): 1. 添加一个 `src/queries//outline.scm` 查询文件 2. 为该语言继承 `TreeSitterGenerator` 子类 3. 在 `DocumentOutlineGenerator` 中注册扩展名 4. 添加一个 `tests/fixtures//` 黄金测试固件 有关共享引擎,请参见 `TreeSitterGenerator` 和 `queries/` 目录;延期支持的功能追踪于 [TECHDEBT.md](TECHDEBT.md)。 ## 📄 许可证 本项目基于 MIT 许可证授权 - 详见 [LICENSE](LICENSE) 文件。 ## 🔗 相关项目 - [markdown-toc](https://github.com/jonschlinkert/markdown-toc) - 为 Markdown 文件生成目录 - [json-schema-generator](https://github.com/krg7880/json-schema-generator) - 生成 JSON schema - [tree-sitter](https://github.com/tree-sitter/tree-sitter) - 增量解析系统 用 ❤️ 制作,以提供更好的代码分析和文档工具。
标签:AST解析, MITM代理, Tree-sitter, 代码分析, 凭证管理, 威胁情报, 开发者工具, 符号提取, 自动化攻击