Commit c6c7e451 by 张立顺

feat: add miniprogram knowledge graph core

1 parent 608ebded
Showing 31 changed files with 1873 additions and 0 deletions
/**
* @file 从微信小程序源码提取可验证的结构化关系。
* 仅保存路径、符号名和规范化路由/接口路径,不保存业务字面量或源码片段。
*/
import fs from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import { parse } from '@babel/parser'
const SCHEMA_VERSION = '1.0.0'
const SOURCE_EXTENSIONS = ['.js', '.mjs', '.cjs', '.json']
const IGNORED_DIRECTORIES = new Set([
'.git',
'.svn',
'.cursor',
'.idea',
'.codex',
'.codex-tmp',
'.superpowers',
'.history',
'.vscode',
'.worktrees',
'node_modules',
'miniprogram_npm',
'outputs',
])
const IGNORED_PATH_PREFIXES = [
'docs/COMPONENT-PAGE-INDEX.md',
'docs/generated/',
'tests/.migration-readiness-',
'tests/knowledge-graph/fixtures/',
]
const ROUTE_METHODS = new Set([
'navigateTo',
'redirectTo',
'reLaunch',
'switchTab',
'go',
])
const EDGE_TYPES = new Set([
'contains',
'declares',
'usesComponent',
'imports',
'bindsEvent',
'calls',
'navigatesTo',
'definesApi',
'callsApi',
'callsEndpoint',
'readsState',
'writesState',
'coveredBy',
'documentedBy',
])
function toPosix(value) {
return value.replace(/\\/g, '/')
}
function compareText(left, right) {
return left < right ? -1 : left > right ? 1 : 0
}
function relativePath(rootDir, absolutePath) {
return toPosix(path.relative(rootDir, absolutePath))
}
function readJson(filePath) {
return JSON.parse(fs.readFileSync(filePath, 'utf8'))
}
function walkFiles(rootDir) {
const files = []
const visit = (directory) => {
for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
if (entry.isDirectory() && IGNORED_DIRECTORIES.has(entry.name)) continue
const absolutePath = path.join(directory, entry.name)
const filePath = relativePath(rootDir, absolutePath)
if (
IGNORED_PATH_PREFIXES.some(
(prefix) => filePath === prefix.slice(0, -1) || filePath.startsWith(prefix),
)
) {
continue
}
if (entry.isDirectory()) visit(absolutePath)
else if (entry.isFile()) files.push(absolutePath)
}
}
visit(rootDir)
return files.sort((left, right) =>
compareText(relativePath(rootDir, left), relativePath(rootDir, right)),
)
}
function lineColumnFor(text, needle) {
const index = Math.max(0, text.indexOf(needle))
const prefix = text.slice(0, index)
const lines = prefix.split(/\r?\n/)
return { line: lines.length, column: lines.at(-1).length }
}
function evidence(filePath, loc = {}) {
return {
path: toPosix(filePath),
line: Math.max(1, Number(loc.line || loc.start?.line || 1)),
column: Math.max(0, Number(loc.column ?? loc.start?.column ?? 0)),
}
}
function nodeLocation(node) {
return node?.loc?.start || { line: 1, column: 0 }
}
function stableCompare(left, right) {
return compareText(JSON.stringify(left), JSON.stringify(right))
}
function stripKnownExtension(filePath) {
return filePath.replace(/\.(?:js|mjs|cjs|json|wxml)$/i, '')
}
function normalizedRoute(value) {
if (typeof value !== 'string') return null
const clean = value.trim().replace(/^\/+/, '').split(/[?#]/, 1)[0]
if (!clean || clean.includes('{{')) return null
return stripKnownExtension(clean)
}
function endpointPath(value) {
if (typeof value !== 'string') return null
const trimmed = value.trim()
if (!trimmed || trimmed.includes('${') || trimmed.includes('{{')) return null
try {
if (/^https?:\/\//i.test(trimmed)) return new URL(trimmed).pathname
} catch {
return null
}
if (/^(?:[A-Za-z][\w-]*\.)+api\.[A-Za-z0-9_.-]+$/.test(trimmed)) {
return trimmed
}
if (!trimmed.startsWith('/')) return null
return trimmed.split(/[?#]/, 1)[0]
}
function isRequestCall(node) {
if (node?.type !== 'CallExpression') return false
if (node.callee?.type === 'Identifier') {
return ['fetch', 'request', 'requestApi'].includes(node.callee.name)
}
if (
node.callee?.type === 'MemberExpression' ||
node.callee?.type === 'OptionalMemberExpression'
) {
const clientName = memberChain(node.callee.object)?.split('.').at(-1)
if (!clientName || !/^(?:wx|.*(?:api|request))$/i.test(clientName)) {
return false
}
return [
'delete',
'download',
'fetch',
'get',
'patch',
'post',
'put',
'request',
'upload',
].includes(propertyName(node.callee))
}
return false
}
function parseSource(source, filePath, unresolved) {
try {
return parse(source, {
sourceType: 'unambiguous',
errorRecovery: false,
plugins: [
'asyncGenerators',
'classProperties',
'dynamicImport',
'objectRestSpread',
'optionalCatchBinding',
'optionalChaining',
'topLevelAwait',
],
})
} catch {
unresolved.push({
kind: 'parse',
path: filePath,
line: 1,
column: 0,
reason: 'babel-parser-failed',
})
return null
}
}
function walkAst(node, visitor, parent = null) {
if (!node || typeof node !== 'object') return
if (typeof node.type === 'string') visitor(node, parent)
for (const [key, value] of Object.entries(node)) {
if (['loc', 'start', 'end', 'extra', 'errors', 'comments'].includes(key)) continue
if (Array.isArray(value)) {
for (const child of value) walkAst(child, visitor, node)
} else if (value && typeof value === 'object') {
walkAst(value, visitor, node)
}
}
}
function identifierSymbols(node) {
const symbols = new Set()
walkAst(node, (child) => {
if (child.type === 'Identifier' && child.name.length >= 4) {
symbols.add(child.name)
}
})
return [...symbols].sort(compareText)
}
function staticString(node) {
if (!node) return null
if (node.type === 'StringLiteral') return node.value
if (node.type === 'TemplateLiteral' && node.expressions.length === 0) {
return node.quasis[0]?.value?.cooked || ''
}
return null
}
function propertyName(node) {
if (!node) return null
if (!node.computed && node.property?.type === 'Identifier') return node.property.name
return staticString(node.property)
}
function memberChain(node) {
if (!node) return null
if (node.type === 'Identifier') return node.name
if (node.type === 'CallExpression' && node.callee?.type === 'Identifier') {
return `${node.callee.name}()`
}
if (node.type !== 'MemberExpression' && node.type !== 'OptionalMemberExpression') {
return null
}
const object = memberChain(node.object)
const property = propertyName(node)
return object && property ? `${object}.${property}` : null
}
function functionNameFromProperty(property) {
if (!property) return null
if (property.type === 'ObjectMethod') {
return property.key?.name || staticString(property.key)
}
if (property.type === 'ObjectProperty') {
const value = property.value
if (['FunctionExpression', 'ArrowFunctionExpression'].includes(value?.type)) {
return property.key?.name || staticString(property.key)
}
}
return null
}
function functionBodyFromProperty(property) {
if (property?.type === 'ObjectMethod') return property.body
if (property?.type === 'ObjectProperty') return property.value?.body
return null
}
function resolveExistingSource(rootDir, importerPath, specifier) {
if (typeof specifier !== 'string') return null
if (/^(?:node:|[a-z][a-z0-9+.-]*:)/i.test(specifier)) return null
let candidate
if (specifier.startsWith('~/')) candidate = path.join(rootDir, specifier.slice(2))
else if (specifier.startsWith('/')) candidate = path.join(rootDir, specifier.slice(1))
else if (specifier.startsWith('.')) {
candidate = path.resolve(path.dirname(path.join(rootDir, importerPath)), specifier)
} else {
return null
}
const candidates = [candidate]
if (!path.extname(candidate)) {
for (const extension of SOURCE_EXTENSIONS) candidates.push(`${candidate}${extension}`)
for (const extension of SOURCE_EXTENSIONS) {
candidates.push(path.join(candidate, `index${extension}`))
}
}
const found = candidates.find((item) => fs.existsSync(item) && fs.statSync(item).isFile())
return found ? relativePath(rootDir, found) : null
}
function resolveComponent(rootDir, ownerBase, componentPath) {
if (typeof componentPath !== 'string' || componentPath.startsWith('@')) return null
let absoluteBase
if (componentPath.startsWith('/')) absoluteBase = path.join(rootDir, componentPath.slice(1))
else if (componentPath.startsWith('.')) {
absoluteBase = path.resolve(path.dirname(path.join(rootDir, ownerBase)), componentPath)
} else {
absoluteBase = path.join(rootDir, componentPath)
}
const normalized = stripKnownExtension(relativePath(rootDir, absoluteBase))
return fs.existsSync(path.join(rootDir, `${normalized}.json`)) ||
fs.existsSync(path.join(rootDir, `${normalized}.js`))
? normalized
: null
}
function isTestPath(filePath) {
return /\.(?:test|spec)\.[cm]?js$/i.test(filePath)
}
function isApiPath(filePath) {
return (
/(?:^|\/)api(?:\/|\.[cm]?js$)/i.test(filePath) ||
/(?:^|\/)apis\//i.test(filePath)
)
}
function loadCatalog(rootDir) {
const catalogPath = path.join(rootDir, 'docs/knowledge/domain-catalog.json')
if (!fs.existsSync(catalogPath)) return { schemaVersion: 1, domains: [] }
const catalog = readJson(catalogPath)
const gapsPath = path.join(rootDir, 'docs/knowledge/known-gaps.json')
const gaps = fs.existsSync(gapsPath) ? readJson(gapsPath).gaps || [] : []
return {
schemaVersion: catalog.schemaVersion || 1,
domains: Array.isArray(catalog.domains)
? catalog.domains.map((domain) => ({
...domain,
knownGaps: gaps
.filter((gap) => gap.domain === domain.name)
.map((gap) => ({ reason: gap.reason, nextStep: gap.nextStep }))
.sort(stableCompare),
}))
: [],
}
}
function domainForPath(filePath, domains) {
const clean = stripKnownExtension(filePath).replace(/^\/+/, '')
const matches = []
for (const domain of domains) {
for (const root of domain.roots || []) {
const normalized = String(root).replace(/^\.\//, '').replace(/\/$/, '')
if (clean === normalized || clean.startsWith(`${normalized}/`)) {
matches.push({ domain: domain.name, length: normalized.length })
}
}
}
matches.sort((left, right) => right.length - left.length || compareText(left.domain, right.domain))
return matches[0]?.domain || null
}
class GraphCollector {
constructor(domains) {
this.domains = domains
this.nodes = new Map()
this.edges = new Map()
this.unresolved = []
}
addNode(node) {
const clean = Object.fromEntries(
Object.entries(node).filter(([, value]) => value !== null && value !== undefined),
)
if (!this.nodes.has(clean.id)) this.nodes.set(clean.id, clean)
return clean.id
}
mergeNode(id, patch) {
const current = this.nodes.get(id)
if (!current) return
this.nodes.set(
id,
Object.fromEntries(
Object.entries({ ...current, ...patch }).filter(
([, value]) => value !== null && value !== undefined,
),
),
)
}
addEdge(edge) {
if (!EDGE_TYPES.has(edge.type) || !this.nodes.has(edge.from) || !this.nodes.has(edge.to)) {
return
}
const clean = {
from: edge.from,
to: edge.to,
type: edge.type,
confidence: edge.confidence ?? 1,
evidence: evidence(edge.evidence.path, edge.evidence),
}
const key = `${clean.from}|${clean.to}|${clean.type}|${clean.evidence.path}|${clean.evidence.line}|${clean.evidence.column}`
if (!this.edges.has(key)) this.edges.set(key, clean)
}
addUnresolved(item) {
this.unresolved.push({
kind: item.kind,
path: toPosix(item.path),
line: Math.max(1, item.line || 1),
column: Math.max(0, item.column || 0),
reason: item.reason,
})
}
}
function addDomainNodes(collector, catalog) {
for (const domain of catalog.domains) {
collector.addNode({
id: `domain:${domain.name}`,
type: 'domain',
name: domain.name,
aliases: [...(domain.aliases || [])].sort(compareText),
roots: [...(domain.roots || [])].sort(compareText),
entrypoints: [...(domain.entrypoints || [])].sort(compareText),
riskKeywords: [...(domain.riskKeywords || [])].sort(compareText),
knownGaps: domain.knownGaps || [],
})
}
}
function addContainedByDomain(collector, nodeId, filePath, loc = { line: 1, column: 0 }) {
const domain = domainForPath(filePath, collector.domains)
if (!domain) return null
collector.addEdge({
from: `domain:${domain}`,
to: nodeId,
type: 'contains',
confidence: 1,
evidence: { path: filePath, ...loc },
})
return domain
}
function addPage(collector, route, evidencePath, loc) {
const id = `page:${route}`
const domain = domainForPath(route, collector.domains)
collector.addNode({ id, type: 'page', name: path.posix.basename(route), path: route, domain })
addContainedByDomain(collector, id, route, loc)
return id
}
function addComponent(collector, componentPath, evidencePath, loc) {
const id = `component:${componentPath}`
const domain = domainForPath(componentPath, collector.domains)
collector.addNode({
id,
type: 'component',
name: path.posix.basename(componentPath),
path: componentPath,
domain,
})
addContainedByDomain(collector, id, componentPath, loc)
return id
}
function addModule(collector, filePath) {
const id = `module:${filePath}`
const domain = domainForPath(filePath, collector.domains)
collector.addNode({
id,
type: 'module',
name: path.posix.basename(filePath),
path: filePath,
domain,
})
addContainedByDomain(collector, id, filePath)
return id
}
function addMethod(collector, ownerId, filePath, name, loc, body) {
const id = `method:${filePath}#${name}`
const domain = domainForPath(filePath, collector.domains)
const symbols = identifierSymbols(body)
collector.addNode({
id,
type: 'method',
name,
path: filePath,
domain,
...(symbols.length ? { symbols } : {}),
})
collector.addEdge({
from: ownerId,
to: id,
type: 'declares',
confidence: 1,
evidence: { path: filePath, ...loc },
})
return id
}
function pageAndComponentFacts(rootDir, files, appConfig, collector) {
const pageIds = new Map()
const componentIds = new Map()
const mainPages = Array.isArray(appConfig.pages) ? appConfig.pages : []
const subPages = (appConfig.subpackages || appConfig.subPackages || []).flatMap((subpackage) =>
(subpackage.pages || []).map((page) => `${subpackage.root}/${page}`),
)
const appText = fs.readFileSync(path.join(rootDir, 'app.json'), 'utf8')
const tabPages = new Set((appConfig.tabBar?.list || []).map((item) => item.pagePath))
const subpackageRoots = new Set(
(appConfig.subpackages || appConfig.subPackages || []).map((item) => item.root),
)
for (const route of [...mainPages, ...subPages]) {
const loc = lineColumnFor(appText, `\"${route}\"`)
const pageId = addPage(collector, route, 'app.json', loc)
const preloads = [...(appConfig.preloadRule?.[route]?.packages || [])].sort(compareText)
collector.mergeNode(pageId, {
package: subpackageRoots.has(route.split('/')[0]) ? route.split('/')[0] : 'main',
...(tabPages.has(route) ? { tabBar: true } : {}),
...(preloads.length ? { preloads } : {}),
})
pageIds.set(route, pageId)
}
for (const file of files.filter((item) => item.endsWith('.json'))) {
const filePath = relativePath(rootDir, file)
if (filePath === 'app.json' || filePath.startsWith('docs/generated/')) continue
let config
try {
config = readJson(file)
} catch {
collector.addUnresolved({ kind: 'json', path: filePath, reason: 'invalid-json' })
continue
}
const base = stripKnownExtension(filePath)
if (config.component === true) {
componentIds.set(base, addComponent(collector, base, filePath, { line: 1, column: 0 }))
}
}
const componentConfigs = new Map()
const registerComponents = (ownerBase, ownerId, config, configPath, configText) => {
for (const [alias, rawTarget] of Object.entries(config.usingComponents || {})) {
const target = resolveComponent(rootDir, ownerBase, rawTarget)
if (!target) continue
const targetId = componentIds.get(target) || addComponent(collector, target, configPath, { line: 1, column: 0 })
componentIds.set(target, targetId)
const currentAliases = collector.nodes.get(targetId)?.aliases || []
collector.mergeNode(targetId, {
aliases: [...new Set([...currentAliases, alias])].sort(compareText),
})
const loc = lineColumnFor(configText, `\"${alias}\"`)
collector.addEdge({
from: ownerId,
to: targetId,
type: 'usesComponent',
confidence: 1,
evidence: { path: configPath, ...loc },
})
componentConfigs.set(`${ownerBase}:${alias}`, target)
}
}
for (const [route, ownerId] of pageIds) {
const jsonPath = path.join(rootDir, `${route}.json`)
if (!fs.existsSync(jsonPath)) continue
const text = fs.readFileSync(jsonPath, 'utf8')
try {
registerComponents(route, ownerId, JSON.parse(text), `${route}.json`, text)
} catch {
// Invalid JSON is already reported by the JSON pass.
}
}
for (const [componentPath, ownerId] of componentIds) {
const jsonPath = path.join(rootDir, `${componentPath}.json`)
if (!fs.existsSync(jsonPath)) continue
const text = fs.readFileSync(jsonPath, 'utf8')
try {
registerComponents(componentPath, ownerId, JSON.parse(text), `${componentPath}.json`, text)
} catch {
// Invalid JSON is already reported by the JSON pass.
}
}
const globalComponents = Object.fromEntries(
Object.entries(appConfig.usingComponents || {})
.map(([alias, target]) => [alias, resolveComponent(rootDir, 'app', target)])
.filter(([, target]) => target),
)
const applicationDomain = collector.nodes.has('domain:application')
? 'domain:application'
: collector.nodes.has('domain:main')
? 'domain:main'
: [...collector.nodes.values()].find((node) => node.type === 'domain')?.id
if (applicationDomain) {
for (const [alias, componentPath] of Object.entries(globalComponents)) {
const targetId =
componentIds.get(componentPath) ||
addComponent(collector, componentPath, 'app.json', { line: 1, column: 0 })
componentIds.set(componentPath, targetId)
const currentAliases = collector.nodes.get(targetId)?.aliases || []
collector.mergeNode(targetId, {
aliases: [...new Set([...currentAliases, alias])].sort(compareText),
})
const loc = lineColumnFor(appText, `\"${alias}\"`)
collector.addEdge({
from: applicationDomain,
to: targetId,
type: 'usesComponent',
confidence: 1,
evidence: { path: 'app.json', ...loc },
})
}
}
return {
pageIds,
componentIds,
globalComponents,
}
}
function collectApiDefinitions(record, collector) {
if (!record.ast || !isApiPath(record.path)) return
const definitions = new Map()
const addOperation = (name, body, loc) => {
if (!name || definitions.has(name)) return
const id = `apiOperation:${record.path}#${name}`
const domain = domainForPath(record.path, collector.domains)
const symbols = identifierSymbols(body)
collector.addNode({
id,
type: 'apiOperation',
name,
path: record.path,
domain,
...(symbols.length ? { symbols } : {}),
})
collector.addEdge({
from: record.nodeId,
to: id,
type: 'definesApi',
confidence: 1,
evidence: { path: record.path, ...loc },
})
definitions.set(name, { id, body, loc })
}
for (const statement of record.ast.program.body) {
const declaration = statement.type === 'ExportNamedDeclaration' ? statement.declaration : statement
if (declaration?.type === 'FunctionDeclaration') {
addOperation(declaration.id?.name, declaration.body, nodeLocation(declaration))
}
if (declaration?.type === 'VariableDeclaration') {
for (const item of declaration.declarations) {
if (
item.id?.type === 'Identifier' &&
['ArrowFunctionExpression', 'FunctionExpression'].includes(item.init?.type)
) {
addOperation(item.id.name, item.init.body, nodeLocation(item))
}
if (item.init?.type === 'ObjectExpression') {
for (const property of item.init.properties) {
addOperation(
functionNameFromProperty(property),
functionBodyFromProperty(property),
nodeLocation(property),
)
}
}
}
}
if (
statement.type === 'ExpressionStatement' &&
statement.expression?.type === 'AssignmentExpression' &&
memberChain(statement.expression.left) === 'module.exports' &&
statement.expression.right?.type === 'ObjectExpression'
) {
for (const property of statement.expression.right.properties) {
addOperation(
functionNameFromProperty(property),
functionBodyFromProperty(property),
nodeLocation(property),
)
}
}
}
record.apiOperations = definitions
}
function importBindings(record, rootDir) {
const bindings = new Map()
if (!record.ast) return bindings
for (const statement of record.ast.program.body) {
if (statement.type === 'ImportDeclaration') {
const sourcePath = resolveExistingSource(rootDir, record.path, statement.source.value)
if (!sourcePath) continue
for (const specifier of statement.specifiers) {
const imported =
specifier.type === 'ImportSpecifier'
? specifier.imported?.name || specifier.imported?.value
: specifier.type === 'ImportDefaultSpecifier'
? 'default'
: '*'
bindings.set(specifier.local.name, { sourcePath, imported })
}
}
if (statement.type !== 'VariableDeclaration') continue
for (const declaration of statement.declarations) {
const call = declaration.init
if (
call?.type !== 'CallExpression' ||
call.callee?.type !== 'Identifier' ||
call.callee.name !== 'require'
) {
continue
}
const sourcePath = resolveExistingSource(
rootDir,
record.path,
staticString(call.arguments[0]),
)
if (!sourcePath) continue
if (declaration.id.type === 'Identifier') {
bindings.set(declaration.id.name, { sourcePath, imported: '*' })
} else if (declaration.id.type === 'ObjectPattern') {
for (const property of declaration.id.properties) {
if (property.type !== 'ObjectProperty') continue
const local = property.value?.name
const imported = property.key?.name || staticString(property.key)
if (local && imported) bindings.set(local, { sourcePath, imported })
}
}
}
}
return bindings
}
function importReference(node) {
if (node.type === 'ImportDeclaration') {
return { source: node.source?.value, dynamic: false }
}
if (node.type === 'ExportNamedDeclaration' || node.type === 'ExportAllDeclaration') {
return node.source ? { source: node.source.value, dynamic: false } : null
}
if (node.type === 'ImportExpression') {
return { source: staticString(node.source), dynamic: true }
}
if (node.type !== 'CallExpression') return null
if (node.callee?.type === 'Import') {
return { source: staticString(node.arguments[0]), dynamic: true }
}
if (node.callee?.type === 'Identifier' && node.callee.name === 'require') {
return { source: staticString(node.arguments[0]), dynamic: false }
}
return null
}
function addImportEdges(record, rootDir, moduleRecords, collector) {
if (!record.ast) return
walkAst(record.ast.program, (node) => {
const reference = importReference(node)
if (!reference) return
if (reference.dynamic && !reference.source) {
collector.addUnresolved({
kind: 'import',
path: record.path,
...nodeLocation(node),
reason: 'dynamic-import-expression',
})
return
}
if (!reference.source) return
const targetPath = resolveExistingSource(rootDir, record.path, reference.source)
const target = moduleRecords.get(targetPath)
if (!target) return
collector.addEdge({
from: record.nodeId,
to: target.nodeId,
type: 'imports',
confidence: 1,
evidence: { path: record.path, ...nodeLocation(node) },
})
})
}
function isWriteReference(node, parent) {
return (
(parent?.type === 'AssignmentExpression' && parent.left === node) ||
(parent?.type === 'UpdateExpression' && parent.argument === node) ||
(parent?.type === 'UnaryExpression' && parent.operator === 'delete')
)
}
function globalStateName(node) {
const chain = memberChain(node)
if (!chain) return null
const wxMatch = chain.match(/^wx\.(\$[A-Za-z_$][\w$]*)$/)
if (wxMatch) return `wx.${wxMatch[1]}`
const globalMatch = chain.match(/(?:^|\.)globalData\.([A-Za-z_$][\w$]*)$/)
if (globalMatch) return `globalData.${globalMatch[1]}`
return null
}
function routeArgument(call) {
const first = call.arguments?.[0]
if (!first) return { value: null, node: call }
if (first.type === 'ObjectExpression') {
const routeProperty = first.properties.find(
(property) =>
property.type === 'ObjectProperty' &&
['url', 'path'].includes(property.key?.name || staticString(property.key)),
)
return { value: staticString(routeProperty?.value), node: routeProperty?.value || first }
}
return { value: staticString(first), node: first }
}
function resolveRouteTarget(value, sourcePath, pageIds) {
if (typeof value !== 'string') {
return { targetRoute: null, reason: 'dynamic-route-expression' }
}
const direct = normalizedRoute(value)
if (direct && pageIds.has(direct)) return { targetRoute: direct, reason: null }
const routeName = value.split(/[?#]/, 1)[0]
const sourceParent = stripKnownExtension(sourcePath).split('/')[0]
const [explicitParent, explicitName] = routeName.includes('.')
? routeName.split('.', 2)
: [sourceParent, routeName]
const matches = [...pageIds.keys()].filter((route) => {
const parts = route.split('/')
return parts[0] === explicitParent && parts.at(-1) === explicitName
})
if (matches.length === 1) return { targetRoute: matches[0], reason: null }
return {
targetRoute: null,
reason: matches.length > 1 ? 'ambiguous-route-alias' : 'route-target-not-found',
}
}
function scanExecutableBody({
body,
sourceId,
ownerId,
record,
bindings,
moduleRecords,
pageIds,
collector,
}) {
if (!body) return
walkAst(body, (node, parent) => {
if (node.type === 'MemberExpression' || node.type === 'OptionalMemberExpression') {
const state = globalStateName(node)
if (state) {
const stateId = `globalState:${state}`
const domain = domainForPath(record.path, collector.domains)
collector.addNode({ id: stateId, type: 'globalState', name: state, domain })
collector.addEdge({
from: sourceId,
to: stateId,
type: isWriteReference(node, parent) ? 'writesState' : 'readsState',
confidence: 1,
evidence: { path: record.path, ...nodeLocation(node) },
})
}
}
if (node.type !== 'CallExpression' && node.type !== 'OptionalCallExpression') return
const calleeName = propertyName(node.callee)
if (calleeName && ROUTE_METHODS.has(calleeName)) {
const route = routeArgument(node)
const resolvedRoute = resolveRouteTarget(route.value, record.path, pageIds)
if (resolvedRoute.targetRoute) {
collector.addEdge({
from: sourceId,
to: pageIds.get(resolvedRoute.targetRoute),
type: 'navigatesTo',
confidence: 1,
evidence: { path: record.path, ...nodeLocation(route.node) },
})
} else {
collector.addUnresolved({
kind: 'route',
path: record.path,
...nodeLocation(route.node),
reason: resolvedRoute.reason,
})
}
}
if (
node.callee?.type === 'MemberExpression' &&
node.callee.object?.type === 'ThisExpression'
) {
const called = propertyName(node.callee)
const targetId = called ? `method:${record.path}#${called}` : null
if (targetId && collector.nodes.has(targetId)) {
collector.addEdge({
from: sourceId,
to: targetId,
type: 'calls',
confidence: 1,
evidence: { path: record.path, ...nodeLocation(node) },
})
}
}
let binding = null
let operationName = null
if (node.callee?.type === 'Identifier') {
binding = bindings.get(node.callee.name)
operationName = binding?.imported === '*' ? node.callee.name : binding?.imported
} else if (
node.callee?.type === 'MemberExpression' &&
node.callee.object?.type === 'Identifier'
) {
binding = bindings.get(node.callee.object.name)
operationName = propertyName(node.callee)
}
const targetRecord = binding ? moduleRecords.get(binding.sourcePath) : null
if (targetRecord?.apiOperations?.size) {
const operation =
targetRecord.apiOperations.get(operationName) ||
(targetRecord.apiOperations.size === 1
? [...targetRecord.apiOperations.values()][0]
: null)
if (operation) {
collector.addEdge({
from: sourceId,
to: operation.id,
type: 'callsApi',
confidence: operationName === operation.id.split('#').at(-1) ? 1 : 0.8,
evidence: { path: record.path, ...nodeLocation(node) },
})
}
}
})
}
function discoverOwnerObject(record) {
let owner = null
walkAst(record.ast?.program, (node) => {
if (owner || node.type !== 'CallExpression') return
if (
node.callee?.type === 'Identifier' &&
['App', 'Page', 'Component'].includes(node.callee.name) &&
node.arguments[0]?.type === 'ObjectExpression'
) {
owner = { kind: node.callee.name, object: node.arguments[0] }
}
})
return owner
}
function ownerMethods(owner) {
if (!owner) return []
const properties =
owner.kind === 'Component'
? owner.object.properties.flatMap((property) => {
const name = property.key?.name || staticString(property.key)
return name === 'methods' && property.value?.type === 'ObjectExpression'
? property.value.properties
: [property]
})
: owner.object.properties
return properties
.map((property) => ({
name: functionNameFromProperty(property),
body: functionBodyFromProperty(property),
loc: nodeLocation(property),
}))
.filter((item) => item.name && item.body)
}
function topLevelFunctions(record) {
const definitions = new Map()
const add = (name, body, loc) => {
if (name && body && !definitions.has(name)) {
definitions.set(name, { name, body, loc })
}
}
const addObjectMethods = (object) => {
if (object?.type !== 'ObjectExpression') return
for (const property of object.properties) {
add(
functionNameFromProperty(property),
functionBodyFromProperty(property),
nodeLocation(property),
)
}
}
for (const statement of record.ast?.program.body || []) {
const declaration =
statement.type === 'ExportNamedDeclaration' ||
statement.type === 'ExportDefaultDeclaration'
? statement.declaration
: statement
if (declaration?.type === 'FunctionDeclaration') {
add(declaration.id?.name, declaration.body, nodeLocation(declaration))
}
if (declaration?.type === 'VariableDeclaration') {
for (const item of declaration.declarations) {
if (
item.id?.type === 'Identifier' &&
['ArrowFunctionExpression', 'FunctionExpression'].includes(item.init?.type)
) {
add(item.id.name, item.init.body, nodeLocation(item))
}
addObjectMethods(item.init)
}
}
addObjectMethods(
declaration?.type === 'ObjectExpression' ? declaration : null,
)
if (
statement.type === 'ExpressionStatement' &&
statement.expression?.type === 'AssignmentExpression'
) {
const assignment = statement.expression
addObjectMethods(assignment.right)
if (
['ArrowFunctionExpression', 'FunctionExpression'].includes(
assignment.right?.type,
)
) {
add(
propertyName(assignment.left),
assignment.right.body,
nodeLocation(assignment),
)
}
}
}
return [...definitions.values()]
}
function scanModuleBehavior(record, context) {
if (!record.ast) return
const owner = discoverOwnerObject(record)
const ownerBase = stripKnownExtension(record.path)
const ownerId =
context.pageIds.get(ownerBase) || context.componentIds.get(ownerBase) || record.nodeId
const bindings = importBindings(record, context.rootDir)
const methods = ownerMethods(owner)
const ownerMethodNames = new Set(methods.map((method) => method.name))
const moduleFunctions = isApiPath(record.path)
? []
: topLevelFunctions(record).filter(
(method) => !ownerMethodNames.has(method.name),
)
for (const method of methods) {
addMethod(
context.collector,
ownerId,
record.path,
method.name,
method.loc,
method.body,
)
}
for (const method of methods) {
scanExecutableBody({
body: method.body,
sourceId: `method:${record.path}#${method.name}`,
ownerId,
record,
bindings,
moduleRecords: context.moduleRecords,
pageIds: context.pageIds,
collector: context.collector,
})
}
for (const method of moduleFunctions) {
addMethod(
context.collector,
record.nodeId,
record.path,
method.name,
method.loc,
method.body,
)
scanExecutableBody({
body: method.body,
sourceId: `method:${record.path}#${method.name}`,
ownerId: record.nodeId,
record,
bindings,
moduleRecords: context.moduleRecords,
pageIds: context.pageIds,
collector: context.collector,
})
}
for (const operation of record.apiOperations?.values() || []) {
scanExecutableBody({
body: operation.body,
sourceId: operation.id,
ownerId: record.nodeId,
record,
bindings,
moduleRecords: context.moduleRecords,
pageIds: context.pageIds,
collector: context.collector,
})
walkAst(operation.body, (node) => {
if (!isRequestCall(node)) return
const candidate = node.arguments?.[0]
let value = staticString(candidate)
if (candidate?.type === 'ObjectExpression') {
const urlProperty = candidate.properties.find(
(property) =>
property.type === 'ObjectProperty' &&
['url', 'path'].includes(property.key?.name || staticString(property.key)),
)
value = staticString(urlProperty?.value)
}
if (candidate && !value) {
context.collector.addUnresolved({
kind: 'endpoint',
path: record.path,
...nodeLocation(candidate),
reason: 'dynamic-endpoint-expression',
})
return
}
const endpoint = endpointPath(value)
if (!endpoint) {
context.collector.addUnresolved({
kind: 'endpoint',
path: record.path,
...nodeLocation(candidate || node),
reason: candidate
? 'unsupported-endpoint-format'
: 'missing-endpoint-argument',
})
return
}
const endpointId = `endpoint:${endpoint}`
context.collector.addNode({
id: endpointId,
type: 'endpoint',
name: endpoint,
path: endpoint,
})
context.collector.addEdge({
from: operation.id,
to: endpointId,
type: 'callsEndpoint',
confidence: 0.95,
evidence: { path: record.path, ...nodeLocation(node) },
})
})
}
}
function scanWxml(rootDir, files, owners, collector) {
for (const file of files.filter((item) => item.endsWith('.wxml'))) {
const filePath = relativePath(rootDir, file)
const base = stripKnownExtension(filePath)
const ownerId = owners.pageIds.get(base) || owners.componentIds.get(base)
if (!ownerId) continue
const source = fs.readFileSync(file, 'utf8')
const eventPattern = /\b(?:bind|catch|mut-bind)(?::)?[\w-]*\s*=\s*["']([A-Za-z_$][\w$]*)["']/g
for (const match of source.matchAll(eventPattern)) {
const methodId = `method:${base}.js#${match[1]}`
if (!collector.nodes.has(methodId)) continue
const loc = lineColumnFor(source, match[0])
collector.addEdge({
from: ownerId,
to: methodId,
type: 'bindsEvent',
confidence: 1,
evidence: { path: filePath, ...loc },
})
}
const navigatorPattern = /<navigator\b[^>]*\burl\s*=\s*["']([^"']+)["']/gi
for (const match of source.matchAll(navigatorPattern)) {
const route = normalizedRoute(match[1])
if (!route || !owners.pageIds.has(route)) continue
const loc = lineColumnFor(source, match[0])
collector.addEdge({
from: ownerId,
to: owners.pageIds.get(route),
type: 'navigatesTo',
confidence: 1,
evidence: { path: filePath, ...loc },
})
}
for (const [alias, componentPath] of Object.entries(owners.globalComponents)) {
if (!new RegExp(`<${alias}(?:\\s|/|>)`).test(source)) continue
const componentId = owners.componentIds.get(componentPath) || addComponent(collector, componentPath, filePath, { line: 1, column: 0 })
owners.componentIds.set(componentPath, componentId)
const loc = lineColumnFor(source, `<${alias}`)
collector.addEdge({
from: ownerId,
to: componentId,
type: 'usesComponent',
confidence: 0.95,
evidence: { path: filePath, ...loc },
})
}
}
}
function scanTests(rootDir, records, moduleRecords, collector) {
for (const record of records.filter((item) => isTestPath(item.path))) {
const testId = `test:${record.path}`
const pathDomain = domainForPath(record.path, collector.domains)
collector.addNode({ id: testId, type: 'test', name: path.posix.basename(record.path), path: record.path, domain: pathDomain })
if (record.nodeId !== testId) collector.nodes.delete(record.nodeId)
record.nodeId = testId
if (pathDomain) collector.mergeNode(testId, { domain: pathDomain })
addContainedByDomain(collector, testId, record.path)
if (!record.ast) continue
const covered = new Map()
walkAst(record.ast.program, (node) => {
let source = importReference(node)?.source || null
if (
node.type === 'NewExpression' &&
node.callee?.type === 'Identifier' &&
node.callee.name === 'URL'
) {
source = staticString(node.arguments[0])
if (!source) {
collector.addUnresolved({
kind: 'testSource',
path: record.path,
...nodeLocation(node),
reason: 'dynamic-test-file-reference',
})
return
}
}
if (!source) return
const targetPath = resolveExistingSource(rootDir, record.path, source)
if (!targetPath || isTestPath(targetPath)) return
covered.set(targetPath, nodeLocation(node))
})
const coveredDomains = new Set()
for (const [sourcePath, loc] of covered) {
const sourceRecord = moduleRecords.get(sourcePath)
if (!sourceRecord) continue
const sourceDomain = collector.nodes.get(sourceRecord.nodeId)?.domain
if (sourceDomain) coveredDomains.add(sourceDomain)
collector.addEdge({
from: sourceRecord.nodeId,
to: testId,
type: 'coveredBy',
confidence: 0.9,
evidence: { path: record.path, ...loc },
})
collector.addEdge({
from: testId,
to: sourceRecord.nodeId,
type: 'imports',
confidence: 1,
evidence: { path: record.path, ...loc },
})
}
if (!pathDomain && coveredDomains.size === 1) {
const [inferredDomain] = coveredDomains
collector.mergeNode(testId, { domain: inferredDomain })
collector.addEdge({
from: `domain:${inferredDomain}`,
to: testId,
type: 'contains',
confidence: 0.9,
evidence: { path: record.path, line: 1, column: 0 },
})
}
}
}
function resolveDocumentTarget(rootDir, documentPath, value) {
if (!value || /^(?:https?:|mailto:|#)/i.test(value)) return null
const clean = value.split('#', 1)[0].replace(/^<|>$/g, '')
const absolute = clean.startsWith('/')
? path.join(rootDir, clean.slice(1))
: path.resolve(path.dirname(path.join(rootDir, documentPath)), clean)
const candidates = [absolute]
if (!path.extname(absolute)) {
for (const extension of ['.js', '.mjs', '.json', '.md']) candidates.push(`${absolute}${extension}`)
candidates.push(path.join(absolute, 'README.md'))
}
const target = candidates.find(
(candidate) => fs.existsSync(candidate) && fs.statSync(candidate).isFile(),
)
return target ? relativePath(rootDir, target) : null
}
function nodeForFilePath(filePath, collector) {
const candidates = [
`module:${filePath}`,
`test:${filePath}`,
`document:${filePath}`,
`page:${stripKnownExtension(filePath)}`,
`component:${stripKnownExtension(filePath)}`,
]
return candidates.find((id) => collector.nodes.has(id)) || null
}
function scanDocuments(rootDir, files, catalog, collector) {
for (const file of files.filter(
(item) =>
item.endsWith('.md') &&
!relativePath(rootDir, item).startsWith('docs/generated/') &&
relativePath(rootDir, item) !== 'docs/COMPONENT-PAGE-INDEX.md',
)) {
const filePath = relativePath(rootDir, file)
const id = `document:${filePath}`
const domain = domainForPath(filePath, collector.domains)
collector.addNode({ id, type: 'document', name: path.posix.basename(filePath), path: filePath, domain })
addContainedByDomain(collector, id, filePath)
const source = fs.readFileSync(file, 'utf8')
const candidates = []
for (const match of source.matchAll(/\[[^\]]*\]\(([^)]+)\)/g)) {
candidates.push({ value: match[1].trim().split(/\s+/, 1)[0], index: match.index })
}
for (const match of source.matchAll(/`([^`\r\n]+)`/g)) {
if (/[/.]/.test(match[1])) candidates.push({ value: match[1], index: match.index })
}
const seen = new Set()
for (const candidate of candidates) {
const targetPath = resolveDocumentTarget(rootDir, filePath, candidate.value)
if (!targetPath || seen.has(targetPath)) continue
const targetId = nodeForFilePath(targetPath, collector)
if (!targetId) continue
seen.add(targetPath)
const loc = lineColumnFor(source, candidate.value)
collector.addEdge({
from: targetId,
to: id,
type: 'documentedBy',
confidence: 0.9,
evidence: { path: filePath, ...loc },
})
}
}
for (const domain of catalog.domains) {
for (const documentPath of domain.documents || []) {
const documentId = `document:${documentPath}`
if (!collector.nodes.has(documentId)) continue
collector.addEdge({
from: `domain:${domain.name}`,
to: documentId,
type: 'documentedBy',
confidence: 1,
evidence: { path: 'docs/knowledge/domain-catalog.json', line: 1, column: 0 },
})
}
}
}
function graphStats(nodes, edges, unresolved) {
const nodeTypes = {}
const edgeTypes = {}
for (const node of nodes) nodeTypes[node.type] = (nodeTypes[node.type] || 0) + 1
for (const edge of edges) edgeTypes[edge.type] = (edgeTypes[edge.type] || 0) + 1
return {
nodeCount: nodes.length,
edgeCount: edges.length,
unresolvedCount: unresolved.length,
nodeTypes: Object.fromEntries(Object.entries(nodeTypes).sort()),
edgeTypes: Object.fromEntries(Object.entries(edgeTypes).sort()),
}
}
/**
* 构建项目领域知识图谱。
*
* @param {{rootDir: string}} options 项目根目录。
* @returns {Promise<object>} 固定排序且不含时间戳的图谱对象。
*/
export async function buildKnowledgeGraph({ rootDir }) {
const absoluteRoot = path.resolve(rootDir)
const appPath = path.join(absoluteRoot, 'app.json')
if (!fs.existsSync(appPath)) throw new Error(`app.json not found under ${absoluteRoot}`)
const catalog = loadCatalog(absoluteRoot)
const collector = new GraphCollector(catalog.domains)
addDomainNodes(collector, catalog)
const files = walkFiles(absoluteRoot)
const appConfig = readJson(appPath)
const owners = pageAndComponentFacts(absoluteRoot, files, appConfig, collector)
const sourceFiles = files.filter((file) => /\.[cm]?js$/i.test(file))
const records = sourceFiles.map((file) => {
const filePath = relativePath(absoluteRoot, file)
const source = fs.readFileSync(file, 'utf8')
const isTest = isTestPath(filePath)
const nodeId = isTest
? collector.addNode({ id: `test:${filePath}`, type: 'test', name: path.posix.basename(filePath), path: filePath })
: addModule(collector, filePath)
return {
path: filePath,
source,
ast: parseSource(source, filePath, collector.unresolved),
nodeId,
apiOperations: new Map(),
}
})
const moduleRecords = new Map(records.map((record) => [record.path, record]))
for (const record of records.filter((item) => !isTestPath(item.path) && item.ast)) {
const symbols = identifierSymbols(record.ast.program)
if (symbols.length) collector.mergeNode(record.nodeId, { symbols })
}
for (const record of records.filter((item) => !isTestPath(item.path))) {
const base = stripKnownExtension(record.path)
const ownerId = owners.pageIds.get(base) || owners.componentIds.get(base)
if (!ownerId) continue
collector.addEdge({
from: ownerId,
to: record.nodeId,
type: 'contains',
confidence: 1,
evidence: { path: record.path, line: 1, column: 0 },
})
}
for (const record of records) collectApiDefinitions(record, collector)
scanTests(absoluteRoot, records, moduleRecords, collector)
for (const record of records) addImportEdges(record, absoluteRoot, moduleRecords, collector)
for (const record of records.filter((item) => !isTestPath(item.path))) {
scanModuleBehavior(record, {
rootDir: absoluteRoot,
moduleRecords,
pageIds: owners.pageIds,
componentIds: owners.componentIds,
collector,
})
}
scanWxml(absoluteRoot, files, owners, collector)
scanDocuments(absoluteRoot, files, catalog, collector)
const nodes = [...collector.nodes.values()].sort((left, right) => compareText(left.id, right.id))
const edges = [...collector.edges.values()].sort(stableCompare)
const unresolved = collector.unresolved.sort(stableCompare)
return {
schemaVersion: SCHEMA_VERSION,
nodes,
edges,
unresolved,
stats: graphStats(nodes, edges, unresolved),
}
}
/**
* 将图谱序列化为可重复构建的 JSON。
*
* @param {object} graph 图谱对象。
* @returns {string} 带结尾换行的稳定 JSON。
*/
export function serializeGraph(graph) {
return `${JSON.stringify(graph, null, 2)}\n`
}
async function main() {
const rootDir = process.cwd()
const output = path.join(rootDir, 'docs/generated/knowledge-graph.json')
const graph = await buildKnowledgeGraph({ rootDir })
fs.mkdirSync(path.dirname(output), { recursive: true })
fs.writeFileSync(output, serializeGraph(graph), 'utf8')
console.log(`WROTE ${relativePath(rootDir, output)}`)
}
const isMain =
process.argv[1] &&
path.resolve(process.argv[1]) === path.resolve(fileURLToPath(import.meta.url))
if (isMain) await main()
import assert from 'node:assert/strict'
import fs from 'node:fs'
import path from 'node:path'
import test from 'node:test'
import { fileURLToPath, pathToFileURL } from 'node:url'
const projectRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..')
const fixtureRoot = path.join(
projectRoot,
'tests/knowledge-graph/fixtures/mini-program',
)
const builderPath = path.join(
projectRoot,
'scripts/knowledge-graph/build-knowledge-graph.mjs',
)
async function loadBuilder() {
assert.equal(
fs.existsSync(builderPath),
true,
'knowledge graph builder must exist',
)
return import(pathToFileURL(builderPath))
}
function findEdge(graph, type, fromIncludes, toIncludes) {
return graph.edges.find(
(edge) =>
edge.type === type &&
edge.from.includes(fromIncludes) &&
edge.to.includes(toIncludes),
)
}
test('builds the public graph contract from mini-program facts', async () => {
const { buildKnowledgeGraph } = await loadBuilder()
const graph = await buildKnowledgeGraph({ rootDir: fixtureRoot })
assert.equal(graph.schemaVersion, '1.0.0')
assert.deepEqual(Object.keys(graph), [
'schemaVersion',
'nodes',
'edges',
'unresolved',
'stats',
])
const nodeTypes = new Set(graph.nodes.map((node) => node.type))
for (const type of [
'domain',
'page',
'component',
'module',
'method',
'apiOperation',
'endpoint',
'globalState',
'test',
'document',
]) {
assert.equal(nodeTypes.has(type), true, `missing ${type} node`)
}
const homePage = graph.nodes.find((node) => node.id === 'page:pages/home/home')
assert.equal(homePage.tabBar, true)
assert.deepEqual(homePage.preloads, ['pkg'])
assert.ok(findEdge(graph, 'usesComponent', 'pages/home/home', 'components/card/card'))
assert.ok(findEdge(graph, 'imports', 'pages/home/home.js', 'api/order.js'))
assert.ok(findEdge(graph, 'imports', 'pages/home/home.js', 'utils/helper.js'))
assert.ok(findEdge(graph, 'bindsEvent', 'pages/home/home', '#loadPageData'))
assert.ok(findEdge(graph, 'bindsEvent', 'components/card/card', '#captureSelect'))
assert.ok(findEdge(graph, 'calls', '#onShow', '#loadPageData'))
assert.ok(findEdge(graph, 'navigatesTo', 'pages/home/home', 'pkg/pages/detail/detail'))
assert.ok(findEdge(graph, 'navigatesTo', 'pkg/pages/detail/detail', 'pkg/pages/confirm/confirm'))
assert.ok(findEdge(graph, 'callsApi', '#loadPageData', 'api/order.js#fetchOrder'))
assert.ok(
findEdge(
graph,
'callsApi',
'pages/home/services/order-service.js#refreshOrders',
'api/order.js#fetchOrder',
),
)
assert.equal(
graph.nodes.some(
(node) => node.id === 'endpoint:dj.api.fixture.notEndpoint',
),
false,
)
assert.ok(
graph.nodes.some(
(node) => node.id === 'endpoint:dj.pad.api.fixture.audit',
),
)
assert.ok(
graph.unresolved.some(
(item) =>
item.kind === 'endpoint' &&
item.path === 'api/order.js' &&
item.reason === 'dynamic-endpoint-expression',
),
)
assert.ok(findEdge(graph, 'callsEndpoint', 'api/order.js#fetchOrder', '/fixture/orders/list'))
assert.ok(
findEdge(
graph,
'callsEndpoint',
'api/order.js#fetchOrderDetail',
'dj.api.fixture.order.detail',
),
)
assert.ok(findEdge(graph, 'writesState', '#loadPageData', 'wx.$orderListRefresh'))
assert.ok(
findEdge(
graph,
'writesState',
'pages/home/services/order-service.js#refreshOrders',
'wx.$orderListRefresh',
),
)
assert.ok(findEdge(graph, 'readsState', '#loadPageData', 'globalData.yqMerchantId'))
assert.ok(findEdge(graph, 'coveredBy', 'pages/home/home.js', 'tests/home.test.mjs'))
assert.ok(findEdge(graph, 'coveredBy', 'utils/helper.js', 'tests/home.test.mjs'))
assert.ok(findEdge(graph, 'documentedBy', 'pages/home/home.js', 'docs/home.md'))
for (const edge of graph.edges) {
assert.equal(typeof edge.confidence, 'number')
assert.match(edge.evidence.path, /^[^\\]+/)
assert.equal(Number.isInteger(edge.evidence.line), true)
assert.equal(Number.isInteger(edge.evidence.column), true)
}
})
test('records dynamic expressions without copying source literals', async () => {
const { buildKnowledgeGraph } = await loadBuilder()
const graph = await buildKnowledgeGraph({ rootDir: fixtureRoot })
assert.ok(
graph.unresolved.some(
(item) =>
item.kind === 'route' && item.path === 'pages/home/home.js',
),
)
assert.ok(
graph.unresolved.some(
(item) =>
item.kind === 'import' && item.path === 'tests/home.test.mjs',
),
)
assert.ok(
graph.unresolved.some(
(item) =>
item.kind === 'testSource' && item.path === 'tests/home.test.mjs',
),
)
const serialized = JSON.stringify(graph)
assert.equal(serialized.includes('id=fixture'), false)
assert.equal(serialized.includes('wx.navigateTo({ url: target })'), false)
assert.equal(
graph.unresolved.some((item) => item.path.startsWith('.vscode/')),
false,
)
for (const ignoredRoot of ['.svn/', '.cursor/', '.codex-tmp/']) {
assert.equal(
graph.nodes.some((node) => node.path?.startsWith(ignoredRoot)),
false,
)
assert.equal(
graph.unresolved.some((item) => item.path.startsWith(ignoredRoot)),
false,
)
}
assert.equal(
graph.nodes.some((node) =>
node.path?.startsWith('tests/.migration-readiness-'),
),
false,
)
assert.equal(
graph.unresolved.some((item) =>
item.path.startsWith('tests/.migration-readiness-'),
),
false,
)
assert.equal(
graph.nodes.some(
(node) =>
node.type === 'document' &&
(node.path?.startsWith('docs/generated/') ||
node.path === 'docs/COMPONENT-PAGE-INDEX.md'),
),
false,
)
})
test('merges every registered alias for a shared component', async () => {
const { buildKnowledgeGraph } = await loadBuilder()
const graph = await buildKnowledgeGraph({ rootDir: fixtureRoot })
const card = graph.nodes.find(
(node) => node.id === 'component:components/card/card',
)
assert.deepEqual(card?.aliases, ['app-card', 'local-card'])
})
test('produces byte-stable output across consecutive builds', async () => {
const { buildKnowledgeGraph, serializeGraph } = await loadBuilder()
const first = serializeGraph(await buildKnowledgeGraph({ rootDir: fixtureRoot }))
const second = serializeGraph(await buildKnowledgeGraph({ rootDir: fixtureRoot }))
assert.equal(first, second)
assert.equal(first.endsWith('\n'), true)
})
{
// Editor JSONC must not enter business parsing.
"editor.formatOnSave": true
}
import request from '../utils/request.js'
export function fetchOrder() {
return request({ url: '/fixture/orders/list' })
}
export function fetchOrderDetail() {
void ['fixture'].includes('dj.api.fixture.notEndpoint')
request('dj.pad.api.fixture.audit')
return request('dj.api.fixture.order.detail')
}
export function fetchDynamicEndpoint(suffix) {
return request('dj.api.fixture.' + suffix)
}
{
"pages": ["pages/home/home"],
"subpackages": [
{
"root": "pkg",
"pages": ["pages/detail/detail", "pages/confirm/confirm"]
}
],
"tabBar": {
"list": [
{ "pagePath": "pages/home/home", "text": "首页" }
]
},
"usingComponents": {
"app-card": "/components/card/card"
},
"preloadRule": {
"pages/home/home": { "packages": ["pkg"] }
},
"resolveAlias": {
"~/*": "/*"
}
}
Component({
methods: {
select() {
this.triggerEvent('select')
},
captureSelect() {},
},
})
<button bindtap="select" capture-bind:touchstart="captureSelect">选择</button>
# Generated component index
This generated compatibility index must not be ingested as source documentation.
# Generated document
This generated file must never become an input to its own knowledge graph.
# 首页
- [首页源码](../pages/home/home.js)
- 路由:`pkg/pages/detail/detail`
{
"schemaVersion": 1,
"domains": [
{
"name": "main",
"aliases": ["首页"],
"roots": ["pages", "components", "api", "utils"],
"entrypoints": ["pages/home/home"],
"riskKeywords": ["orderListRefresh"],
"documents": ["docs/home.md"]
},
{
"name": "pkg",
"aliases": ["详情"],
"roots": ["pkg"],
"entrypoints": ["pkg/pages/detail/detail"],
"riskKeywords": [],
"documents": []
}
]
}
{
"schemaVersion": 1,
"gaps": [
{
"domain": "pkg",
"reason": "fixture business semantics are not documented",
"nextStep": "calibrate the detail flow on first change"
}
]
}
import { fetchOrder as loadOrder } from '~/api/order.js'
import { normalizeOrder } from './services/order-service.js'
const helper = require('../../utils/helper.js')
Page({
onShow() {
this.loadPageData()
},
loadPageData() {
normalizeOrder(loadOrder())
loadOrder()
helper.touch()
wx.navigateTo({ url: '/pkg/pages/detail/detail?id=fixture' })
wx.$orderListRefresh = false
wx.$orderListRefresh = true
return getApp().globalData.yqMerchantId
},
openDynamic(target) {
wx.navigateTo({ url: target })
},
})
{
"usingComponents": {
"local-card": "/components/card/card"
}
}
<view>
<local-card bind:select="loadPageData" />
<app-card />
<navigator url="/pkg/pages/detail/detail">详情</navigator>
</view>
import { fetchOrder } from '../../../api/order.js'
export function normalizeOrder(order) {
return order || null
}
export function refreshOrders() {
wx.$orderListRefresh = true
return fetchOrder()
}
Page({
onLoad() {
const shouldRefresh = wx.$orderListRefresh
if (shouldRefresh) wx.$orderListRefresh = false
wx.$router.go('confirm')
},
})
import fs from 'node:fs'
import { fetchOrder } from '../api/order.js'
fs.readFileSync(new URL('../pages/home/home.js', import.meta.url), 'utf8')
await import('../utils/helper.js')
export async function loadDynamic(target) {
return import(target)
}
export function dynamicSourceUrl(relativePath) {
return new URL(relativePath, import.meta.url)
}
void fetchOrder
import assert from 'node:assert/strict'
import test from 'node:test'
import request from '../utils/request.js'
test('keeps the owning domain suite visible to affected selection', () => {
assert.deepEqual(request({ ok: true }), { ok: true })
})
import assert from 'node:assert/strict'
import test from 'node:test'
import { normalizeOrder } from '../pages/home/services/order-service.js'
test('normalizes an empty order', () => {
assert.equal(normalizeOrder(undefined), null)
})
module.exports = {
touch() {
return true
},
}
export default function request(options) {
return options
}
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!