# @astrale-os/codegraph 中文文档

规范地址：https://npmcn.com/package/%40astrale-os/codegraph/

版本：0\.1\.6
npm 元数据更新时间：2026-10-10T03:04:45.381Z
中文译文更新时间：2026-11-07T01:26:47.796Z
软件包许可：Apache-2\.0

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40astrale-os/codegraph
原文对照：https://npmcn.com/package/%40astrale-os/codegraph/?lang=original
项目主页：https://github.com/astrale-os/exp-codegraph#readme
源码仓库：https://github.com/astrale-os/exp-codegraph

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：2.9 MB，740 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- Node.js 要求：\>=22\.13 \<23 \|\| \>=24 \<25 \|\| \>=26 \<27
- 运行依赖：10 个
- 首次发布：2026-10-08T22:27:23.116Z
- 最新版本发布：2026-10-10T03:04:45.043Z
- 近 30 天下载量：2571（2026-10-07 至 2026-11-05，npm 官方下载统计）
- 已发布版本数：8（近 12 个月 8 个）

## 中文简介

无头类型Script 代码图,规格相匹配引擎,以及开发者工具

## 安装

```sh
npm install @astrale-os/codegraph
```

也可以使用：`pnpm add @astrale-os/codegraph`、`yarn add @astrale-os/codegraph`、`bun add @astrale-os/codegraph`

## README

# 代码

**检查类型Script项目. 核查模块合同.**

[检查一个项目](https://npmcn.com/package/%40astrale-os/codegraph/#readme-inspect-a-project) • 妇女 [探索 API](https://npmcn.com/package/%40astrale-os/codegraph/#readme-explore-the-api) • 妇女 [模块合同](https://npmcn.com/package/%40astrale-os/codegraph/#readme-verify-module-contracts)

## 检查一个项目

使用已有的 `tsconfig.json`。无 `.spec/` 所需经费。 安装方式 `pnpm add @astrale-os/codegraph`。 。 。 .

```ts
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`。 。 。 .

导航符号, 查找用法和模块依赖性而不提取正文

```ts
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 }))
```

```text
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`;计算的请求不确定. [结构检查、位置语义和跟踪再利用](https://npmcn.com/package/%40astrale-os/codegraph/docs/typescript-structure.md)。 。 。 .

### 通过帮助和关闭跟踪值

使用图书馆的项目,例如 `@acme/http`数字 :

```ts
// src/routes.ts
import { route } from '@acme/http'

const health = (status: number) => ({
  path: '/health',
  handler: () => ({ status }),
})

route(health(200))
```

继续同样的快照 :

```ts
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被分析而未执行. [图书馆规则还确立了被调用人的身份](https://npmcn.com/package/%40astrale-os/codegraph/docs/typescript-values.md#model-a-library-boundary);声明来源选择要检查的呼叫.

### 通过编辑保持工程开放

```ts
// 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`。 。 。 .

```ts
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'] })
```

报告在所观察到的投入仍然存在时,包括在不相关的编辑过程中,可以重复使用。 返回纯数据; 回调读取器和值计划在结算后会过期. [价值、预算和再利用](https://npmcn.com/package/%40astrale-os/codegraph/docs/typescript-values.md#reuse-a-semantic-computation)。 。 。 .

价值、图书馆模式和评价预算

```text
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)
```

模型可以描述一个库边界,同时保留约束,关闭和证明依赖. 模式操作在主动呼叫中同步解决. [完整指南](https://npmcn.com/package/%40astrale-os/codegraph/docs/typescript-values.md#model-a-library-boundary) • 妇女 [接口](https://npmcn.com/package/%40astrale-os/codegraph/analysis/typescript/value/model.ts)。 。 。 .

事实、类型、依赖性和控制流动

```text
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`;逻辑模块表面,依赖性和类型使用模块边界描述符.

[项目选项](https://npmcn.com/package/%40astrale-os/codegraph/analysis/typescript/project/model.ts) • 妇女 [事实阅读器和有效载荷](https://npmcn.com/package/%40astrale-os/codegraph/analysis/typescript/facts/model.ts) • 妇女 [电话和机关](https://npmcn.com/package/%40astrale-os/codegraph/analysis/typescript/body/types.ts) • 妇女 [模块描述符](https://npmcn.com/package/%40astrale-os/codegraph/analysis/protocol/model.ts)。 。 。 .

储存、储存工具和自定义分析

```text
@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? })
```

默认使用内存; 提供自定义保留或持久性的调用者拥有的商店 。 仓库工具盘点,分类,分组和计量文件. 本地决策会支持专门的工具整合. [所有出口,包括类型](https://npmcn.com/package/%40astrale-os/codegraph/docs/public-api.md)。 。 。 .

抓取的读者重新使用本地会话的编译器和事实所有者. 它们的默认能力是源和体的需求;结构读取需要明确的能力. [抓取邮票和租赁阅读器](https://npmcn.com/package/%40astrale-os/codegraph/docs/typescript-values.md#read-an-existing-native-capture)。 。 。 .

## 探索 API

导入任务的切入点 。 根包曝光模块-合同应用服务.

| 任务 | `@astrale-os/codegraph` 切入点 |
| --- | --- |
| 检查类型Script、 解析值、 重用观测 | `/analysis/typescript` |
| 编写通行证和政策;储存/清点事实 | `/analysis` |
| SQLite 中的顽固事实 | `/analysis/sqlite` |
| 整合本土决策会议 | `/analysis/native` |
| 库存库、计量来源、读取证据 | `/repository` |
| 作者能力、法律、国家和其他合同 | `/authoring` |
| 汇编规格并获得能力状态 | `/specification` |
| 编写合同合规情况简介 | `/conformance` |
| 验证计划和数据 | `/schema` |
| 更新和检查模块合同应用程序 | 根号 |
| 坚持工作空间检查站 | `/workspace` |

[完整的出口库存](https://npmcn.com/package/%40astrale-os/codegraph/docs/public-api.md) ——每个函数,类,常数和类型,都有与精确接口的链接.

## 核查模块合同

可选和独立于检查工作流程。 合规将作者合同与执行分析联系起来.

```sh
cg init modules/payments
```

```ts
// modules/payments/.spec/api.d.ts
export interface Payment { id: string; amount: number }
export declare function charge(amount: number): Promise<Payment>
```

```sh
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` 检查执行情况是否符合要求。 合同在执行前可能存在. [合同参考](https://npmcn.com/package/%40astrale-os/codegraph/docs/module-contracts.md)。 。 。 .

将现有执行与合同挂钩

出口合同所属类型并执行申报的API:

```ts
// 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 }
}
```

```ts
// 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` 单检查不符合要求. [执行发现和约束](https://npmcn.com/package/%40astrale-os/codegraph/docs/module-contracts.md#implementation-conformance)。 。 。 .

每日CLI:选择,更改模块,证据和活的校验

```sh
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` 检查/更改/测试/演示.

[精确命令和闸门语义](https://npmcn.com/package/%40astrale-os/codegraph/docs/module-contracts.md#commands)。 。 。 .

仅视需要增加合同内容

```text
.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
```

```text
defineCapability · defineLaw · defineState
transition · statesOf · eventsOf · transitionsOf · illegalTransitionsOf
defineCode · defineLayout · definePackage · definePackagePattern · defineBenchmark
```

[正在编写 API](https://npmcn.com/package/%40astrale-os/codegraph/docs/public-api.md#astrale-oscodegraphauthoring) • 妇女 [所有权、语法和实例](https://npmcn.com/package/%40astrale-os/codegraph/docs/module-contracts.md)。试验在外进行 `.spec/`· ; `.history/` 具有解释性、非规范性背景.

建立合同申请、编制简介并坚持设立检查站

```text
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
```

[应用程序接口](https://npmcn.com/package/%40astrale-os/codegraph/application/model.ts) • 妇女 [完整 API](https://npmcn.com/package/%40astrale-os/codegraph/docs/public-api.md)。 。 。 .

节点22 (≥22.13),24或26. 1 npm 包; 本地二进制和初用时的取景器下载, 并有经过验证的离线缓存. [预装和分发](https://npmcn.com/package/%40astrale-os/codegraph/docs/npm-distribution.md) • 妇女 [合格文物](https://npmcn.com/package/%40astrale-os/codegraph/docs/github-artifacts.md)。 。 。 .

## 常见问题

### @astrale-os/codegraph 是什么？

无头类型Script 代码图,规格相匹配引擎,以及开发者工具

### 如何安装 @astrale-os/codegraph？

在项目目录运行 npm install @astrale-os/codegraph，或使用 pnpm add / yarn add / bun add。它还提供命令行工具 cg，可以用 npx cg 直接运行。

### @astrale-os/codegraph 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @astrale-os/codegraph 支持 ESM 还是 CommonJS？

以 ES Module 形式发布，推荐使用 import 引入。在 CommonJS 项目中，Node\.js 20\.19\+ / 22\.12\+ 可以直接 require\(\) 不含顶层 await 的 ES Module，更早的版本需要改用动态 import\(\)。

### @astrale-os/codegraph 需要什么版本的 Node\.js？

package\.json 的 engines 字段要求 Node\.js \>=22\.13 \<23 \|\| \>=24 \<25 \|\| \>=26 \<27。版本不符时 npm 默认只给出警告，开启 engine-strict 后会拒绝安装。

### @astrale-os/codegraph 可以商用吗？

@astrale-os/codegraph 使用 Apache-2\.0 许可。宽松许可：允许商业使用、修改和再分发，并附带明确的专利授权；分发时需保留许可与 NOTICE 文件，修改过的文件要注明改动。以上为概括，不构成法律意见，请以许可原文为准。

### @astrale-os/codegraph 的下载量有多少？

根据 npm 官方下载统计，@astrale-os/codegraph 在 2026/10/07 – 2026/11/05 这 30 天内被下载 2,571 次，日均约 86 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @astrale-os/codegraph 还在维护吗？

最新版本 0\.1\.6 发布于 2026/10/10（28 天前）；至今共发布 8 个版本，其中过去 12 个月发布了 8 个；首次发布于 2026/10/09。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

