knowledge-artifacts.mjs 10.3 KB
/**
 * @file 将知识图谱渲染为面向开发者的 Markdown 视图,并执行漂移检查。
 */

import fs from 'node:fs'
import path from 'node:path'
import { serializeGraph } from './build-knowledge-graph.mjs'

function compareText(left, right) {
  return left < right ? -1 : left > right ? 1 : 0
}

function sortById(items) {
  return [...items].sort((left, right) => compareText(left.id, right.id))
}

function displayPath(node) {
  return node.path || node.name || node.id
}

function sortedUnique(items) {
  return [...new Set(items.filter(Boolean))].sort(compareText)
}

function markdownTable(headers, rows) {
  const heading = `| ${headers.join(' | ')} |`
  const divider = `| ${headers.map(() => '---').join(' | ')} |`
  if (!rows.length) return `${heading}\n${divider}\n| ${headers.map((_, index) => (index === 0 ? '暂无' : '')).join(' | ')} |`
  return [
    heading,
    divider,
    ...rows.map((row) => `| ${row.map((cell) => String(cell).replace(/\|/g, '\\|')).join(' | ')} |`),
  ].join('\n')
}

function generatedNotice() {
  return '> 此文件由 `npm run knowledge:build` 生成。代码事实请勿手工修改;业务语义维护在 `docs/knowledge/`。'
}

function projectSummary(graph) {
  const typeRows = Object.entries(graph.stats.nodeTypes).map(([type, count]) => [type, count])
  const edgeRows = Object.entries(graph.stats.edgeTypes).map(([type, count]) => [type, count])
  return `# 项目知识图谱概览

${generatedNotice()}

## 规模

- 节点:${graph.stats.nodeCount}
- 关系:${graph.stats.edgeCount}
- 未解析:${graph.stats.unresolvedCount}

## 节点类型

${markdownTable(['类型', '数量'], typeRows)}

## 关系类型

${markdownTable(['类型', '数量'], edgeRows)}

## 使用入口

- 更新事实:\`npm run knowledge:build\`
- 检查漂移:\`npm run knowledge:check\`
- 查询影响:\`npm run impact -- --keyword <关键词> --depth 2 --direction both --format json\`
`
}

function domainView(graph, domain) {
  const nodeById = new Map(graph.nodes.map((node) => [node.id, node]))
  const linkedDocuments = graph.edges
    .filter(
      (edge) =>
        edge.from === domain.id && edge.type === 'documentedBy',
    )
    .map((edge) => nodeById.get(edge.to))
    .filter((node) => node?.type === 'document')
  const nodes = [
    ...new Map(
      [
        ...graph.nodes.filter((node) => node.domain === domain.name),
        ...linkedDocuments,
      ].map((node) => [node.id, node]),
    ).values(),
  ]
  const rows = ['page', 'component', 'apiOperation', 'globalState', 'test', 'document'].map((type) => [
    type,
    nodes.filter((node) => node.type === type).length,
  ])
  const entrypoints = domain.entrypoints || []
  const nodeRows = sortById(nodes)
    .filter((node) => ['page', 'component', 'apiOperation', 'globalState', 'test', 'document'].includes(node.type))
    .map((node) => [
      node.type,
      `\`${
        node.type === 'apiOperation'
          ? `${node.path}#${node.name}`
          : displayPath(node)
      }\``,
    ])
  const gapRows = (domain.knownGaps || []).map((gap) => [gap.reason, gap.nextStep])
  return `# ${domain.name} 领域索引

${generatedNotice()}

## 人工语义

- 别名:${(domain.aliases || []).join('、') || '未维护'}
- 根目录:${(domain.roots || []).map((item) => `\`${item}\``).join('、') || '未维护'}
- 核心入口:${entrypoints.map((item) => `\`${item}\``).join('、') || '未维护'}
- 风险关键词:${(domain.riskKeywords || []).map((item) => `\`${item}\``).join('、') || '未维护'}

## 已知文档缺口

${markdownTable(['缺口', '补齐时机'], gapRows)}

## 机器事实统计

${markdownTable(['类型', '数量'], rows)}

## 可定位实体

${markdownTable(['类型', '路径/符号'], nodeRows)}
`
}

function apiCallerIndex(graph) {
  const nodeById = new Map(graph.nodes.map((node) => [node.id, node]))
  const operations = sortById(graph.nodes.filter((node) => node.type === 'apiOperation'))
  const rows = operations.map((operation) => {
    const callers = sortedUnique(
      graph.edges
        .filter((edge) => edge.type === 'callsApi' && edge.to === operation.id)
        .map((edge) => displayPath(nodeById.get(edge.from))),
    )
    const endpoints = sortedUnique(
      graph.edges
        .filter((edge) => edge.type === 'callsEndpoint' && edge.from === operation.id)
        .map((edge) => displayPath(nodeById.get(edge.to))),
    )
    return [
      `\`${operation.path}#${operation.name}\``,
      callers.map((item) => `\`${item}\``).join('<br>') || '—',
      endpoints.map((item) => `\`${item}\``).join('<br>') || '—',
    ]
  })
  return `# API 调用方索引

${generatedNotice()}

${markdownTable(['API 操作', '调用方', '后端路径'], rows)}
`
}

function routeIndex(graph) {
  const nodeById = new Map(graph.nodes.map((node) => [node.id, node]))
  const rows = graph.edges
    .filter((edge) => edge.type === 'navigatesTo')
    .map((edge) => [
      `\`${displayPath(nodeById.get(edge.from))}\``,
      `\`${displayPath(nodeById.get(edge.to))}\``,
      `\`${edge.evidence.path}:${edge.evidence.line}\``,
    ])
  return `# 路由索引

${generatedNotice()}

${markdownTable(['来源', '目标页面', '证据'], rows)}
`
}

function globalStateIndex(graph) {
  const nodeById = new Map(graph.nodes.map((node) => [node.id, node]))
  const states = sortById(graph.nodes.filter((node) => node.type === 'globalState'))
  const rows = states.map((state) => {
    const readers = sortedUnique(
      graph.edges
        .filter((edge) => edge.type === 'readsState' && edge.to === state.id)
        .map((edge) => displayPath(nodeById.get(edge.from))),
    )
    const writers = sortedUnique(
      graph.edges
        .filter((edge) => edge.type === 'writesState' && edge.to === state.id)
        .map((edge) => displayPath(nodeById.get(edge.from))),
    )
    return [
      `\`${state.name}\``,
      readers.map((item) => `\`${item}\``).join('<br>') || '—',
      writers.map((item) => `\`${item}\``).join('<br>') || '—',
    ]
  })
  return `# 全局状态索引

${generatedNotice()}

${markdownTable(['状态', '读取方', '写入方'], rows)}
`
}

function componentPageIndex(graph) {
  const nodeById = new Map(graph.nodes.map((node) => [node.id, node]))
  const components = sortById(graph.nodes.filter((node) => node.type === 'component'))
  const rows = components.map((component) => {
    const edges = graph.edges.filter(
      (edge) => edge.type === 'usesComponent' && edge.to === component.id,
    )
    const consumers = sortedUnique(
      edges.map((edge) => {
        const owner = nodeById.get(edge.from)
        return edge.evidence.path === 'app.json'
          ? 'app.json (global)'
          : displayPath(owner)
      }),
    )
    const highRisk =
      consumers.length >= 5 ||
      /Merchant-Seles|Coupon|Popup/i.test(component.path || component.name)
    return [
      highRisk ? '**高**' : '',
      `\`${component.path}\``,
      consumers.length,
      consumers.map((item) => `\`${item}\``).join('<br>') || '—',
    ]
  })
  return `# 组件 → 页面反向索引(usingComponents)

${generatedNotice()}

> 边界:本地组件注册来自 JSON,应用级组件同时结合 WXML 实际标签;第三方组件不进入业务图谱。

高风险:引用数 ≥ 5,或命中 Merchant-Seles / Coupon / Popup 等治理名单。

${markdownTable(['风险', '组件路径', '引用数', '引用方'], rows)}
`
}

/**
 * 生成全部受管产物的内存内容。
 *
 * @param {object} graph 知识图谱。
 * @returns {Map<string, string>} 相对路径到稳定文本的映射。
 */
export function createKnowledgeArtifactContents(graph) {
  const contents = new Map()
  contents.set('docs/COMPONENT-PAGE-INDEX.md', componentPageIndex(graph))
  contents.set('docs/generated/API-CALLER-INDEX.md', apiCallerIndex(graph))
  contents.set('docs/generated/GLOBAL-STATE-INDEX.md', globalStateIndex(graph))
  contents.set('docs/generated/PROJECT-SUMMARY.md', projectSummary(graph))
  contents.set('docs/generated/ROUTE-PAGE-INDEX.md', routeIndex(graph))
  for (const domain of sortById(
    graph.nodes.filter((node) => node.type === 'domain'),
  )) {
    contents.set(`docs/generated/domains/${domain.name}.md`, domainView(graph, domain))
  }
  contents.set('docs/generated/knowledge-graph.json', serializeGraph(graph))
  return new Map([...contents].sort(([left], [right]) => compareText(left, right)))
}

function obsoleteDomainArtifacts(contents, rootDir) {
  const relativeDirectory = 'docs/generated/domains'
  const directory = path.join(rootDir, relativeDirectory)
  if (!fs.existsSync(directory)) return []
  const expected = new Set(
    [...contents.keys()].filter((item) =>
      item.startsWith(`${relativeDirectory}/`),
    ),
  )
  return fs
    .readdirSync(directory, { withFileTypes: true })
    .filter((entry) => entry.isFile() && entry.name.endsWith('.md'))
    .map((entry) => `${relativeDirectory}/${entry.name}`)
    .filter((item) => !expected.has(item))
    .sort(compareText)
}

/**
 * 写入知识图谱及 Markdown 视图。
 *
 * @param {{graph: object, rootDir: string}} options 图谱与目标项目根目录。
 * @returns {string[]} 已写入的相对路径。
 */
export function writeKnowledgeArtifacts({ graph, rootDir }) {
  const contents = createKnowledgeArtifactContents(graph)
  for (const relativePath of obsoleteDomainArtifacts(contents, rootDir)) {
    fs.rmSync(path.join(rootDir, relativePath))
  }
  for (const [relativePath, content] of contents) {
    const outputPath = path.join(rootDir, relativePath)
    fs.mkdirSync(path.dirname(outputPath), { recursive: true })
    fs.writeFileSync(outputPath, content.endsWith('\n') ? content : `${content}\n`, 'utf8')
  }
  return [...contents.keys()]
}

/**
 * 比较磁盘产物与当前图谱,返回缺失或漂移文件。
 *
 * @param {{graph: object, rootDir: string}} options 图谱与项目根目录。
 * @returns {string[]} 漂移的相对路径。
 */
export function checkKnowledgeArtifacts({ graph, rootDir }) {
  const contents = createKnowledgeArtifactContents(graph)
  const drift = []
  for (const [relativePath, rawContent] of contents) {
    const expected = rawContent.endsWith('\n') ? rawContent : `${rawContent}\n`
    const absolutePath = path.join(rootDir, relativePath)
    if (!fs.existsSync(absolutePath) || fs.readFileSync(absolutePath, 'utf8') !== expected) {
      drift.push(relativePath)
    }
  }
  return [...drift, ...obsoleteDomainArtifacts(contents, rootDir)].sort(compareText)
}