返回知识库
0

第十二章:Typert 类型图系统

本章目标:帮助你理解 Typert 类型图的生成原理、运行时类型注册表、跨仓库类型发现、以及如何为新能力添加类型声明。阅读本章后,你应该能回答"Typert 如何在运行时管理类型信息"以及"如何扩展类型图"。


12.1 Typert 概述

Typert 是 dsh 的类型图系统,负责:

  1. 类型生成:从 TypeScript 源码生成类型图

  2. 运行时注册:在运行时注册和查询类型信息

  3. 跨仓库发现:发现和链接其他仓库的类型

预览
源码

消费者

typert/ 能力

typert-protocol/ (协议定义)

typert-registry/ (运行时注册表)

typert-generator/ (类型图生成器)

api/gateway

sdk/server

extensions/tool-cordis

graph TB
    subgraph "typert/ 能力"
        A["typert-protocol/ (协议定义)"]
        B["typert-registry/ (运行时注册表)"]
        C["typert-generator/ (类型图生成器)"]
    end

    subgraph "消费者"
        D["api/gateway"]
        E["sdk/server"]
        F["extensions/tool-cordis"]
    end

    A --> B
    B --> C
    D --> B
    E --> B
    F --> B

12.2 类型图生成

12.2.1 生成流程

预览
源码
类型图文件FaceModelEmitterWorkspaceTypertGeneratorWorkspaceAnalyzerTypeScript 源码类型图文件FaceModelEmitterWorkspaceTypertGeneratorWorkspaceAnalyzerTypeScript 源码analyze()解析类型引用构建类型图类型图数据验证导出验证后的类型图渲染 .d.ts 文件类型声明文件
sequenceDiagram
    participant Source as TypeScript 源码
    participant Analyzer as WorkspaceAnalyzer
    participant Generator as WorkspaceTypertGenerator
    participant Emitter as FaceModelEmitter
    participant Output as 类型图文件

    Source->>Analyzer: analyze()
    Analyzer->>Analyzer: 解析类型引用
    Analyzer->>Analyzer: 构建类型图
    Analyzer-->>Generator: 类型图数据
    Generator->>Generator: 验证导出
    Generator-->>Emitter: 验证后的类型图
    Emitter->>Emitter: 渲染 .d.ts 文件
    Emitter-->>Output: 类型声明文件

12.2.2 WorkspaceAnalyzer

// 来自 packages/typert/generator/src/analyzer.ts
class WorkspaceAnalyzer {
  /** 分析工作区 */
  async analyze(): Promise<TypeGraph> {
    // 1. 扫描 TypeScript 文件
    const files = await this.scanFiles()
    
    // 2. 解析类型引用
    const references = await this.resolveReferences(files)
    
    // 3. 构建类型图
    const graph = this.buildGraph(references)
    
    // 4. 批量分析
    await this.analyzeInBatches(graph)
    
    return graph
  }
  
  /** 批量分析 */
  private async analyzeInBatches(graph: TypeGraph): Promise<void> {
    const batchSize = 100
    const batches = chunk(graph.nodes, batchSize)
    
    for (const batch of batches) {
      await Promise.all(batch.map(node => this.analyzeNode(node)))
    }
  }
}

12.2.3 类型图结构

interface TypeGraph {
  /** 类型节点 */
  nodes: TypeNode[]
  /** 类型关系 */
  edges: TypeEdge[]
  /** 元数据 */
  metadata: GraphMetadata
}

interface TypeNode {
  /** 节点 ID */
  id: string
  /** 类型名称 */
  name: string
  /** 类型种类 */
  kind: 'interface' | 'type' | 'class' | 'enum' | 'function'
  /** 文件路径 */
  filePath: string
  /** 行号 */
  line: number
}

interface TypeEdge {
  /** 源节点 */
  source: string
  /** 目标节点 */
  target: string
  /** 关系类型 */
  type: 'extends' | 'implements' | 'imports' | 'calls'
}

12.3 运行时类型注册表

12.3.1 TypertRegistry

// 来自 packages/typert/registry/src/service.ts
class TypertRegistry {
  /** 注册类型 */
  register(type: TypeRegistration): Disposable {
    const entry = {
      id: type.id,
      name: type.name,
      kind: type.kind,
      definition: type.definition,
      timestamp: Date.now()
    }
    
    this.types.set(type.id, entry)
    
    // 发送注册事件
    this.ctx.emit('typert/registered', entry)
    
    return () => {
      this.types.delete(type.id)
      this.ctx.emit('typert/unregistered', entry)
    }
  }
  
  /** 查询类型 */
  get(id: string): TypeRegistration | undefined {
    return this.types.get(id)
  }
  
  /** 列出所有类型 */
  list(): TypeRegistration[] {
    return Array.from(this.types.values())
  }
}

12.3.2 类型注册

interface TypeRegistration {
  /** 类型 ID */
  id: string
  /** 类型名称 */
  name: string
  /** 类型种类 */
  kind: 'service' | 'event' | 'tool' | 'config'
  /** 类型定义 */
  definition: TypeDefinition
  /** 注册时间 */
  timestamp: number
}

interface TypeDefinition {
  /** 类型 schema */
  schema: ZodType
  /** 类型描述 */
  description: string
  /** 类型示例 */
  example?: unknown
}

12.4 跨仓库类型发现

12.4.1 概念

Typert 支持跨仓库发现类型,允许不同仓库的类型相互引用。

预览
源码

仓库 B

仓库 A

引用

引用

类型 A

类型 B

类型 C

类型 D

graph TB
    subgraph "仓库 A"
        A1[类型 A]
        A2[类型 B]
    end

    subgraph "仓库 B"
        B1[类型 C]
        B2[类型 D]
    end

    A1 -->|"引用"| B1
    B2 -->|"引用"| A2

12.4.2 LookupStore

// 来自 packages/typert/registry/src/service.ts
class LookupStore {
  /** 获取类型 */
  get(id: string): TypeRegistration | undefined {
    // 1. 本地查找
    const local = this.localTypes.get(id)
    if (local) return local
    
    // 2. 远程查找
    const remote = this.remoteTypes.get(id)
    if (remote) return remote
    
    return undefined
  }
  
  /** 获取类型定义 */
  definitions(id: string): TypeDefinition[] {
    const results: TypeDefinition[] = []
    
    // 收集所有定义
    for (const store of [this.localTypes, ...this.remoteStores]) {
      const type = store.get(id)
      if (type) {
        results.push(type.definition)
      }
    }
    
    return results
  }
}

12.5 扩展类型图

12.5.1 添加新类型

// 1. 定义类型
interface MyCustomType {
  /** 自定义属性 */
  customProperty: string
}

// 2. 注册到 Typert
ctx.typert.register({
  id: 'my-custom-type',
  name: 'MyCustomType',
  kind: 'interface',
  definition: {
    schema: zod.object({
      customProperty: zod.string()
    }),
    description: 'My custom type description'
  }
})

// 3. 在工具中使用
ctx.tools.register({
  name: 'my_tool',
  parameters: {
    type: 'object',
    properties: {
      input: { $ref: '#/definitions/MyCustomType' }
    }
  },
  async execute(input) {
    // input 被类型安全地验证
  }
})

12.5.2 类型图验证

// 来自 packages/typert/generator/src/workspace.ts
class WorkspaceTypertGenerator {
  /** 验证导出 */
  validateExport(exportName: string, exportType: TypeNode): ValidationResult {
    // 检查类型是否符合规范
    const errors: string[] = []
    
    // 检查必须的字段
    if (!exportType.name) {
      errors.push('Type must have a name')
    }
    
    // 检查文件路径
    if (!exportType.filePath) {
      errors.push('Type must have a file path')
    }
    
    return {
      valid: errors.length === 0,
      errors
    }
  }
}

12.6 配置

12.6.1 Typert 配置

# cordis.patch.yml
- id: typert-registry
  config:
    # 类型图文件路径
    graphPath: '${DSH_HOME}/typert/graph.json'
    
    # 远程仓库
    remotes:
      - name: 'deepseek-harness'
        url: 'https://github.com/deepseek-harness/deepseek-harness'
        branch: 'main'
    
    # 缓存配置
    cache:
      enabled: true
      ttl: 3600000  # 1 小时

12.7 小结

概念一句话解释
TypeGraph类型关系图
WorkspaceAnalyzer分析 TypeScript 源码生成类型图
TypertRegistry运行时类型注册表
LookupStore跨仓库类型查找
TypeRegistration类型注册信息

下一步第十三章:Web Client 架构——深入理解 React 组件体系、Slot 机制和前端渲染。

DeepSeek-Harness / 12-Typert 类型图系统 0 0 iliuqi
2026-09-04T07:48:53.382213331Z 2026-09-04T07:58:06.078452005Z