代码
检查类型Script项目. 核查模块合同.
检查一个项目
使用已有的 tsconfig.json。无 .spec/ 所需经费。 安装方式 pnpm add @astrale-os/codegraph。 。 。 .
import { openTypeScriptProject } from '@astrale-os/codegraph/analysis/typescript'
await using project = await openTypeScriptProject({ root: '.' })
await project.refresh()
await using code = await project.open()
const calls = await code.calls({ paths: ['src/routes.ts'] })
console.log({
completeness: calls.completeness,
calls: calls.sites.map(({ path, occurrence, call }) => ({
path,
span: occurrence.span,
origin: call.targetOrigin,
arguments: call.arguments,
dynamic: call.dynamic,
})),
})
电话包括未解决的站点。 覆盖范围是 complete, (中文(简体) ), partial 或者说 unavailable。 。 。 .
导航符号, 查找用法和模块依赖性而不提取正文
await using navigation = await openTypeScriptProject({
root: '.', capabilities: ['typescript.source', 'typescript.structure'],
})
await navigation.refresh()
await using snapshot = await navigation.open()
const structure = await snapshot.structure()
// A cursor or diagnostic provides the file and its UTF-16 offset.
const selected = await structure.symbolAt({ path: 'src/routes.ts', offset: 120 })
console.log(selected.target, selected.symbols) // Canonical symbols + declaration files/spans.
console.log(await structure.references({ target: { path: 'src/routes.ts', offset: 120 } }))
console.log(await structure.references({
target: { path: 'src/api.ts', name: 'route' },
}))
console.log(await structure.dependents({ path: 'src/api.ts', transitive: true }))
structure.symbolAt({ path, offset, revision?, signal? })
structure.exports({ path })
structure.references({ target, paths?, includeDeclarations?, signal? })
structure.dependencies({ paths?, signal? })
structure.dependents({ path, transitive?, signal? })
target: { path, offset, revision? } · { path, name } · { symbol } · { origin }
异域解析到它们的编译符符号;位置也选择本地和私人绑定. 结果保留了具体的修订地点,提供了事实和明确的覆盖面。 一个预期 revision 拒绝陈旧光标。 范围为装填的项目自有来源,不包括 .d.ts;计算的请求不确定. 结构检查、位置语义和跟踪再利用。 。 。 .
通过帮助和关闭跟踪值
使用图书馆的项目,例如 @acme/http数字 :
// src/routes.ts
import { route } from '@acme/http'
const health = (status: number) => ({
path: '/health',
handler: () => ({ status }),
})
route(health(200))
继续同样的快照 :
import { mapValueResult } from '@astrale-os/codegraph/analysis/typescript'
const values = await code.values()
for (const { call } of calls.sites) {
if (call.targetOrigin?.package !== '@acme/http'
|| call.targetOrigin.path.join('.') !== 'route') continue
const argument = call.arguments[0]
if (argument === undefined) continue
const status = await values.value(argument)
.property('handler').invoke().property('status').resolve()
console.log(mapValueResult(status, value =>
value.kind === 'literal' ? value.value : null))
// { kind: 'known', value: 200, evidence: [...] }
}
保留价值 known, (中文(简体) ), unknown, (中文(简体) ), ambiguous 财务报告和审定财务报表 unsupported 成果及其证据。 未知值或不完整的空盘不能证明不存在。 被授权的JavaScript被分析而未执行. 图书馆规则还确立了被调用人的身份;声明来源选择要检查的呼叫.
通过编辑保持工程开放
// After the file watcher reports an edit:
const update = await project.refresh({ changed: ['src/routes.ts'] })
await using current = await project.open()
console.log(update.durationMs, await current.calls({ paths: ['src/routes.ts'] }))
// Or let the compiler discover source, config and resolution changes:
await project.refresh({ discover: true })
刷新后打开新快照 。 更早的读者仍然坚持自己的版本. 初载后,赤出 refresh() 不扫描文件系统.
在编辑中重新使用语义计算
保持调用的稳定; 通过变量参数 input。 。 。 .
import type { TypeScriptSemanticReader } from '@astrale-os/codegraph/analysis/typescript'
async function inspectCalls(read: TypeScriptSemanticReader, input: { paths: string[] }) {
const calls = await read.calls({ paths: input.paths })
return {
completeness: calls.completeness,
calls: calls.sites.map(({ path, occurrence, call }) => ({
path, span: occurrence.span, origin: call.targetOrigin, dynamic: call.dynamic,
})),
}
}
const report = await current.compute(inspectCalls, { paths: ['src/routes.ts'] })
报告在所观察到的投入仍然存在时,包括在不相关的编辑过程中,可以重复使用。 返回纯数据; 回调读取器和值计划在结算后会过期. 价值、预算和再利用。 。 。 .
价值、图书馆模式和评价预算
snapshot.values({ call, limits })
values.value(occurrence).property(name).invoke().resolve({ limits, signal })
values.evaluate(occurrence, { signal? })
values.canReuse(proof)
mapValueResult(result, project, { equals })
limits: maximumDepth · maximumSteps · maximumAlternatives
results: known · unknown · ambiguous · unsupported
call(context)
context.callee() · context.receiver() · context.argument(index)
context.propertyName
operand.property(name) · operand.invoke() · operand.resolve()
model result: atom · unknown · transferred operand · undefined (ordinary evaluation)
模型可以描述一个库边界,同时保留约束,关闭和证明依赖. 模式操作在主动呼叫中同步解决. 完整指南 • 妇女 接口。 。 。 .
事实、类型、依赖性和控制流动
snapshot.facts.facts(kind, filter?, page?)
snapshot.facts.factsById(kind, ids)
snapshot.facts.export(kind, filter?)
snapshot.facts.exportAll(filter?)
fact kinds: project · diagnostic · source · symbol · occurrence · structure · body
body-demand · module · declaration
body: occurrences · relations · blocks · edges · definitions · calls · summary
call: target · targetOrigin · signature · receiver · typeArguments
arguments · bindings · callbacks · dynamic
源,符号,发生和体能默认启用. 其他事实需要明确的能力。 结构参考和文件依赖性使用 typescript.structure;逻辑模块表面,依赖性和类型使用模块边界描述符.
项目选项 • 妇女 事实阅读器和有效载荷 • 妇女 电话和机关 • 妇女 模块描述符。 。 。 .
储存、储存工具和自定义分析
@astrale-os/codegraph/analysis
createMemoryAnalysisStore · selectAnalysisStore
planPasses · runPortablePasses · runAnalysisPolicies
createNodeSourceTextReader · readVerifiedSourceText
createProcessNativeAnalysisSessionFactory
@astrale-os/codegraph/analysis/sqlite
createSQLiteAnalysisStore
@astrale-os/codegraph/repository
createNodeRepositoryScanner · inventoryRepository · repositoryFacts
analyzeRepositoryStatistics · refreshRepositoryStatistics
createRepositoryPathOwnershipGrouping · createRepositorySourceService
@astrale-os/codegraph/analysis/native
openNativeDecisionSession · resolvePackagedNativeAnalysis · resolvePackagedNativeOxlint
preloadNativeArtifacts({ generic?, signal? })
@astrale-os/codegraph/analysis/typescript
openCapturedTypeScriptReader(source, capture, { capabilities?, signal? })
默认使用内存; 提供自定义保留或持久性的调用者拥有的商店 。 仓库工具盘点,分类,分组和计量文件. 本地决策会支持专门的工具整合. 所有出口,包括类型。 。 。 .
抓取的读者重新使用本地会话的编译器和事实所有者. 它们的默认能力是源和体的需求;结构读取需要明确的能力. 抓取邮票和租赁阅读器。 。 。 .
探索 API
导入任务的切入点 。 根包曝光模块-合同应用服务.
| 任务 | @astrale-os/codegraph 切入点 |
|---|---|
| 检查类型Script、 解析值、 重用观测 | /analysis/typescript |
| 编写通行证和政策;储存/清点事实 | /analysis |
| SQLite 中的顽固事实 | /analysis/sqlite |
| 整合本土决策会议 | /analysis/native |
| 库存库、计量来源、读取证据 | /repository |
| 作者能力、法律、国家和其他合同 | /authoring |
| 汇编规格并获得能力状态 | /specification |
| 编写合同合规情况简介 | /conformance |
| 验证计划和数据 | /schema |
| 更新和检查模块合同应用程序 | 根号 |
| 坚持工作空间检查站 | /workspace |
完整的出口库存 ——每个函数,类,常数和类型,都有与精确接口的链接.
核查模块合同
可选和独立于检查工作流程。 合规将作者合同与执行分析联系起来.
cg init modules/payments
// modules/payments/.spec/api.d.ts
export interface Payment { id: string; amount: number }
export declare function charge(amount: number): Promise<Payment>
cg check . # Validate contracts and composition
cg verify . --require-pass # Once the implementation is bound to its contract
cg dev . --open # Browse contracts, source and diagnostics
cg check 检查规格有效性; cg verify 检查执行情况是否符合要求。 合同在执行前可能存在. 合同参考。 。 。 .
将现有执行与合同挂钩
出口合同所属类型并执行申报的API:
// modules/payments/index.ts
import type { Payment } from './.spec/api.js'
export type { Payment } from './.spec/api.js'
export async function charge(amount: number): Promise<Payment> {
return { id: 'receipt', amount }
}
// modules/payments/implementation.contract.ts
import type * as contract from './.spec/api.js'
import * as implementation from './index.js'
implementation satisfies typeof contract
将这两个文件保存在拥有的 TypeScript 项目中. verify 并检查两个方向的公共表面 satisfies 单检查不符合要求. 执行发现和约束。 。 。 .
每日CLI:选择,更改模块,证据和活的校验
cg --version
cg preload --viewer # Prepare native analysis + viewer for offline use
cg check . --select modules/payments --exclude generated --format json
cg check . --require-complete-layout --require-exact-layout --require-law-evidence
cg changed . origin/main
cg changed . origin/main --scope-only
cg test modules/payments --root .
cg test changed origin/main --root .
cg verify . --select modules/payments --schema-root schemas --require-pass --details
cg dev . --port 5173 --open --verify
changed 是一种有针对性的咨询检查; 使用完整的 check 作为全球之门. test 通过项目运行所附证据 test:file 剧本. --quiet 可在检查/更改/测试/核查中查阅; --no-cache 检查/更改/测试/演示.
精确命令和闸门语义。 。 。 .
仅视需要增加合同内容
.spec/
api.d.ts public contract
code.ts shared private entrypoints
internal.d.ts internal vocabulary
ports/**/*.d.ts required provider interfaces
capabilities/**/*.ts independently meaningful abilities
laws/**/*.ts falsifiable semantic truths
states/**/*.ts lifecycle transitions
flows/**/*.ts semantic orchestration
schemas/*.schema.json portable value representations
layout.ts physical paths and observation policy
limits.ts measured budgets
packages/*.ts reasons for external dependencies
examples/**/*.ts canonical public-API usage
benchmarks/**/*.ts workloads and metrics
architecture.md rationale and diagrams
icon.svg visual identity
defineCapability · defineLaw · defineState
transition · statesOf · eventsOf · transitionsOf · illegalTransitionsOf
defineCode · defineLayout · definePackage · definePackagePattern · defineBenchmark
正在编写 API • 妇女 所有权、语法和实例。试验在外进行 .spec/· ; .history/ 具有解释性、非规范性背景.
建立合同申请、编制简介并坚持设立检查站
createTypeSpecApplicationService(options)
service.refresh(options?) · service.current() · service.open(snapshot?)
service.settle() · service.dispose()
reader.query(universe) · reader.source(request) · reader.dispose()
compileSpecificationSnapshot · qualifySpecification · planConformance
createTypeSpecConformanceProfiles · createModuleConformanceProfiles
loadSchema · validateData · validateSchemaFile · validateModuleSchemaCatalog
createFileWorkspaceCheckpointStore
encodeWorkspaceCheckpointJson · decodeWorkspaceCheckpointJson
节点22 (≥22.13),24或26. 1 npm 包; 本地二进制和初用时的取景器下载, 并有经过验证的离线缓存. 预装和分发 • 妇女 合格文物。 。 。 .