跳到主要内容

@nudojs/service

service 包提供类型推断的主要编程 API。整合解析、指令提取与求值,产出适用于工具链(LSP、CLI、IDE 扩展)的分析结果。

analyzeFile​

analyzeFile(
filePath: string,
source: string,
activeCases?: Map<string, number>,
externalCallRecords?: CallRecord[],
loadModule?: LoadModule
): AnalysisResult

对文件运行类型推断。使用 filePath 进行模块解析和诊断。activeCases 将函数名映射到用例索引,用于诊断(如 IDE 中当前“激活”的用例)。

externalCallRecords 接收由 collectCallRecords 从使用现场文件(测试、示例、上层应用)收集的调用记录。能解析到本文件所定义函数的记录会被匹配并注入为合成的 call@L 用例——参见调用点发现指南。

没有 @nudo:case 指令的函数也不会被跳过:全程序推断会为每个观测到的调用点合成一个 call@L 用例;找不到调用点时合成参数为 any 的 entry@L 用例(并在 FunctionAnalysis 上标记 entryOnly)。入口无约束参数是 any;真 unknown 表示推导失败。

返回: AnalysisResult


analyzeFileAsync​

analyzeFileAsync(
filePath: string,
source: string,
activeCases?: Map<string, number>,
externalCallRecords?: CallRecord[],
loadModule?: LoadModule
): Promise<AnalysisResult>

analyzeFile 的异步入口:先通过动态 import 预加载基于路径的 env 文件(/// @nudo:env ./nudo-harvest-node.ts)——在 ESM 中无法同步完成——再运行同步分析,后者会从 env 加载器缓存中取用预加载的工厂。异步工具链(CLI、LSP)应使用它;当被分析文件声明了路径 env 时,同步的 analyzeFile 会降级。

返回: Promise<AnalysisResult>


collectCallRecords​

collectCallRecords(filePath: string, source: string): CallRecord[]

调用点发现的第一阶段:求值使用现场文件的顶层代码,记录其中每一次调用及其在调用点实际观测到的实参类型与结果类型。测试框架的回调(it、test、describe)会以 unknown 参数被手动执行,从而捕获测试体内的调用点——测试框架本身从不运行。该阶段不产出诊断、也不会抛出异常:使用现场文件可能依赖未 mock 的全局,收集尽力而为。

将返回的记录作为 externalCallRecords 传给 analyzeFile/analyzeFileAsync,即可注入为 call@L 用例。两阶段流程见调用点发现 — 编程 API。

返回: CallRecord[](见 CallRecord)


getTypeAtPosition​

getTypeAtPosition(
filePath: string,
source: string,
line: number,
column: number,
activeCases?: Map<string, number>
): Abs | null

返回指定源码位置(1-based 行、0-based 列)的 Abs(无损的 shape × term × pred × conf 值)。当位置位于带有用例的函数内时,按函数使用对应的激活用例索引。

返回: Abs,若无类型则返回 null。


getTypeAtPositionAsync​

getTypeAtPositionAsync(
filePath: string,
source: string,
line: number,
column: number,
activeCases?: Map<string, number>
): Promise<Abs | null>

getTypeAtPosition 的异步入口,带路径 env 预加载(见 analyzeFileAsync)。

返回: Promise<Abs | null>


getCompletionsAtPosition​

getCompletionsAtPosition(
filePath: string,
source: string,
line: number,
column: number
): CompletionItem[]

返回指定位置的补全项。支持变量补全以及 obj. 之后的属性/方法补全。

返回: CompletionItem 数组


getCasesForFile​

getCasesForFile(filePath: string, source: string): {
functionName: string;
cases: { name: string; index: number }[];
loc: SourceLocation;
}[]

列出所有带有 @nudo:case 指令的函数及其用例名称/索引。用于 IDE 中的用例切换。


isNudoTargetPath​

isNudoTargetPath(path: string): boolean

CLI 收集器、监视模式与 LSP isNudoFile 判定共享的扩展名门。纯路径规则(文件无需存在):

路径是否目标
.js / .mjs / .ts(大小写不敏感)是
.d.ts、.tsx、.jsx、.cjs、.mts、.cts 及其余扩展否
*.nudo.{js,mjs,ts} 侧车否(契约模块,非实现源码)
*.nudo.draft.{js,mjs,ts}否(draft 产物)

shouldAnalyzeFile​

shouldAnalyzeFile(
filePath: string,
source: string | undefined,
config?: AnalysisConfig,
): boolean

自动路径(LSP validate、watch、Vite 插件)是否应对该缓冲/文件跑分析。具名路径 CLI(nudo check src/lib.js)不受本门限制,直接分析所点名文件。

门禁顺序:

  1. isNudoTargetPath —— 非目标路径恒不分析
  2. nudo.analysis.exclude / include(默认 exclude:node_modules / dist / coverage)
  3. package.json#nudo.analysis.mode(出厂默认 "exports";DEFAULT_ANALYSIS_MODE):
    • "directives" —— 仅含 @nudo:* 指令的文件
    • "exports"(默认)—— 指令 或 含 export(ESM/CJS)或 同名 *.nudo.js 侧车
    • "all" —— 通过 include/exclude 的全部目标路径

默认值真源:PUBLIC_API.md §7。模式语义:共存。

相关:DEFAULT_ANALYSIS_MODE(再导出常量,"exports")、filterDiagnosticsByLevel、diagnosticsLevelForFile、sourceHasNudoDirectives。


buildSemanticTokens​

buildSemanticTokens(
filePath: string,
source: string,
opts?: { loadModule?: LoadModule; autoBind?: boolean },
): number[]

从分析结果产出 LSP 编码的语义 token(五元组:deltaLine/deltaStartChar/length/tokenType/tokenModifiers)——函数绑定标为 function,其余绑定标为 variable,参数标为 parameter。顶层 named-export 函数绑定额外带 contract 档 modifier(contract / generated / derived),与 CodeLens ● contract 经 contractTierOf 同源(A7);非导出声明只带 declaration。LSP 服务器的 semanticTokens handler 直接消费它。

配套的图例与编码器从同一模块导出,LSP 包再原样再导出(TOKEN_TYPES/TOKEN_MODIFIERS),因此 tokenType 索引不可能与提取器漂移:

SEMANTIC_TOKEN_TYPES: readonly string[] // ["function", "variable", "parameter", "property",
// "type", "keyword", "string", "number", "comment",
// "decorator", "method"]
SEMANTIC_TOKEN_MODIFIERS: readonly string[] // ["declaration", "readonly", "deprecated", "unreachable",
// "contract", "generated", "derived"]

type SemanticToken = {
line: number; char: number; length: number;
typeIndex: number; modifierBitmask: number;
};

encodeSemanticTokens(tokens: SemanticToken[]): number[];
contractTierModifierBit(src: "handwritten" | "generated" | "implicit"): number;

encodeSemanticTokens 把 { line, char, … } token 增量编码为 LSP 期望的扁平 number[]——buildSemanticTokens 已经返回编码后的输出,只有自己构造 token 时才需要它。


buildModuleGraph​

buildModuleGraph(
files: string[],
cache?: ModuleGraphCache,
): {
imports: Map<string, Set<string>>; // 文件 → 它导入的文件
dependents: Map<string, Set<string>>; // 文件 → 导入它的文件
}

type ModuleGraphCache = Map<string, { mtimeMs: number; size: number; edges: string[] }>;

静态抽取每个文件的相对导入边——增量分析的基础构件。扩展名解析规则与模块解析一致(''、.js、.ts、.mjs);裸 npm 说明符会被跳过。CLI 的 watch 模式和 LSP 的脏传播都用它在各自已知文件集上建图。

传入 cache 可跨重建保留每文件的导入边(LSP 会话以 moduleGraphCache 导出一份):文件 mtimeMs 和 size 均未变时命中——只做一次 stat,零磁盘读取、零解析;未命中则重读文件并回填条目。


computeDirtySet​

computeDirtySet(dependents: Map<string, Set<string>>, changedFile: string): string[]

返回变更文件及其全部传递依赖方(沿 dependents 反向边 BFS)。对导入环安全。


topoSortDirty​

topoSortDirty(imports: Map<string, Set<string>>, dirty: string[]): string[]

将脏文件集按依赖在前、依赖方在后的顺序拓扑排序(只统计脏集内部的导入边;容忍环——剩余文件以任意顺序追加)。按此顺序重新分析可保证依赖方先看到其依赖更新后的类型。

典型的增量分析循环:

const graph = buildModuleGraph(files);
const dirty = computeDirtySet(graph.dependents, changedFile);
for (const file of topoSortDirty(graph.imports, dirty)) {
// 重新读取并重新分析 `file`
}

absToTSType​

absToTSType(a: Abs): string

将 Abs 序列化为 TypeScript 类型语法(如 number、string | number、{ id: number; name: string })。


generateDts​

generateDts(result: AnalysisResult): string

根据分析结果生成 TypeScript 声明内容(.d.ts)。产出带真实参数名、推断返回类型和 JSDoc 注释的 declare function 签名。


generateFunctionDtsLines​

generateFunctionDtsLines(fn: FunctionAnalysis): string[]

generateDts 的按函数切片——JSDoc 加一行 export declare function。CLI 的 nudo export --format dts 与 generateDts 共用本函数,两条路径的声明输出字节级一致。无用例的函数不产出(或仅 combined 已知时产出一行 rest-args 的 (...args: unknown[]) 声明);noDeclaration 函数(CJS exports.X = fn)不产出,只留在 check/test JSON 输出中。


absToSchemaSource​

absToSchemaSource(a: Abs, opts?: { dialect?: SchemaDialect }): string
projectAbsToSchema(a: Abs, opts?: { dialect?: SchemaDialect }): {
source: string;
dialect: SchemaDialect;
dropped: string[];
}
absToSchemaNode(a: Abs): { node: SchemaNode; dropped: string[] }

Abs → dialect schema 源码(单向、有损)。中间层 SchemaNode 承载 Abs pred 可表达的 refinement(数值界、int、字符串长度)以及不可投影 pred 的 dropped 注记。默认 dialect 为 zod。

示例:

absToSchemaSource(numVar("x", gt(v("x"), lit(0))))
// → "z.number().gt(0)"

absToStandardSchema / absToStandardSchemaModule​

absToStandardSchema(a: Abs, opts?: { name?: string }): { source: string; dropped: string[] }
absToStandardSchemaModule(
exports: Record<string, Abs>,
opts?: { banner?: string },
): { source: string; dropped: string[] }
validateSchemaNode(node: SchemaNode, value: unknown): StandardSchemaResult

Abs → Standard Schema v1 运行时模块源码(~standard,vendor: "nudo")。零第三方校验库依赖。validate 与 schema dialect 投影共用同一套 SchemaNode refinement(数值界 / int / 字符串长度)。这是生态运行时路径,不能替代 nudo check。

validateSchemaNode 是可测语义核心;生成模块内联同一套检查逻辑。


generateGuardFunctionFromAbs​

generateGuardFunctionFromAbs(name: string, abs: Abs): string

生成零依赖的运行时类型守卫函数字符串。生成的函数使用 typeof、Array.isArray 和属性检查进行验证。

示例:

generateGuardFunctionFromAbs("isUser", obj({ name: str() }))
// → "function isUser(data) { ... }"

用例固化​

用例固化(case emission)这组函数把合成的 call@L 用例写回源码文本。CLI 的 nudo test --freeze[=update] 只是对它们的薄封装——工作流与合并策略见 CLI 使用指南。

serializeCaseArg​

serializeCaseArg(a: Abs): string | null

把单个 Abs 序列化为指令文法(parseCaseArgExpr)能原样读回的表达式文本。指令表达不了的形状返回 null:函数、promise(eff)与 brand 值,bigint 字面量,非有限/科学计数法数字,以及含结构字符或控制字符的字符串/对象键。

示例:

serializeCaseArg(num()) // → "number()"
serializeCaseArg(strLit("a")) // → '"a"'

buildCaseDirective​

buildCaseDirective(name: string, argsAbs: Abs[]): string | null

组装单行指令 * @nudo:case "name" (a, b)(带前导 *,无尾换行),可直接拼进 JSDoc 块。任一实参序列化失败、或名字含双引号/换行时整体返回 null。

示例:

buildCaseDirective("call@L2", [str()])
// → ' * @nudo:case "call@L2" (string())'

stripGeneratedCaseDirectives​

stripGeneratedCaseDirectives(source: string): { source: string; removed: string[] }

从源码删除所有生成的 @nudo:case 指令行(名字以保留前缀 call@ 开头);若所属 JSDoc 块因此再无其他指令或文字,则连同块首 /** 与块尾 */ 行整块删除。绝不触碰非 case 指令与普通注释。removed 按出现顺序返回被删的用例名。这是 update 模式的前半步——注意手写但以 call@… 命名的用例同样会被删除,因为该前缀是保留的。

insertGeneratedCaseDirectives​

insertGeneratedCaseDirectives(source: string, analysis: AnalysisResult): EmitResult

把分析结果中的合成用例(source === "callsite")固化进 source:指令插入在每个函数声明行的正上方——已有 JSDoc 块则插到 /** 行后,无块则新建。含手写用例或已有 call@ 指令的函数会被跳过(见 EmitResult),entry-only 函数同样跳过;序列化失败的用例按函数逐条报告。返回改写后的源码及写入/跳过报告。

unifiedDiff​

unifiedDiff(a: string, b: string, path: string): string

行级 unified diff(--- a/path 头、@@ hunk、3 行上下文),零第三方依赖;文本相同时返回 ""。--dry-run 用它预览固化结果。

EmitResult​

type EmitSkipReason =
| "hand-written" // 函数含非 call@ 命名的用例指令
| "already-generated" // 函数已有 call@ 指令(add 模式不碰)
| "entry-only" // 未找到调用点——没有可固化的内容
| "no-serializable-cases" // 没有任何用例能表达为指令文本
| "no-declaration" // CJS 绑定/赋值函数,无稳定声明
| "skipped"; // 函数本身被分析器跳过

type EmitResult = {
source: string; // 改写后的源码(无变化时与输入相同)
changed: boolean; // 是否写入了任何函数
written: Array<{ fn: string; cases: string[] }>;
skipped: Array<{ fn: string; reason: EmitSkipReason; detail?: string }>;
};

最小化的 add / update 流程:

import { analyzeFileAsync, insertGeneratedCaseDirectives, stripGeneratedCaseDirectives } from "@nudojs/service";

// add:把合成用例按原样插入源码
const result = await analyzeFileAsync(filePath, source, undefined, records);
const emitted = insertGeneratedCaseDirectives(source, result);

// update:先剥离旧的生成指令,重新分析,再插入
const stripped = stripGeneratedCaseDirectives(source);
const reanalyzed = await analyzeFileAsync(filePath, stripped.source, undefined, records);
const synced = insertGeneratedCaseDirectives(stripped.source, reanalyzed);

结果类型​

AnalysisResult​

type AnalysisResult = {
functions: FunctionAnalysis[];
diagnostics: Diagnostic[];
bindings: Map<string, BindingInfo>;
nodeAbsMap: Map<Node, Abs>;
caseHints: CaseHint[];
/** 从其他模块导入的函数,由分析本文件时观测到的
跨文件调用点合成 */
externalFunctions?: FunctionAnalysis[];
}

FunctionAnalysis​

type FunctionAnalysis = {
name: string;
loc: SourceLocation;
paramNames: string[]; // AST 中的实际参数名
cases: CaseResult[];
combinedAbs?: Abs; // 用例结果 Abs 的 join;dts 返回位来源
entryOnly?: boolean; // 合成的 entry@L 用例,未找到调用点
skipped?: boolean;
/** CJS 风格绑定/赋值函数(exports.X = fn)没有
声明级稳定的名称;.d.ts 生成会跳过它们,
但 check/test JSON 输出仍会报告 */
noDeclaration?: boolean;
/** 该函数所属导入模块的绝对路径
(仅 externalFunctions) */
fromModule?: string;
}

CaseResult​

type CaseResult = {
name: string;
argAbs: Abs[]; // 无损实参 Abs
abs: Abs; // 无损结果 Abs
throwsAbs: Abs; // 无损抛出 Abs(未抛为 never)
throwLoc?: SourceLocation;
source?: "directive" | "callsite"; // "callsite" = 由观测到的调用点合成;
// 手写用例与 entry@ 回退不设置该字段
expected?: Abs; // `@nudo:case "name" (…) => expected`——存在即标记为测试断言
aggregatedFrom?: number; // 折叠进符号化用例的额外调用点数
intension?: { // 内涵摘要(代数 generalize)
display?: string; term?: string; pred?: string; conf?: string;
abs?: string; // 无损 Abs 单行(formatAbs)
absMultiline?: string;
};
}

CallRecord​

由 collectCallRecords 在使用现场观测到的一次调用:

type CallRecord = {
fnName: string; // 调用点观测到的被调函数名
argAbs: Abs[]; // 观测到的无损实参 Abs
resultAbs: Abs; // 观测到的结果 Abs(调用抛出时为 never)
throwsAbs: Abs; // 观测到的抛出 Abs(未抛为 never)
callLoc?: { line: number; column: number }; // 调用位置;行号即 call@L 用例名中的 L
targetModule?: string; // 被调函数绑定来源的模块
targetExport?: string; // 被调函数绑定时使用的导出名
targetAliases?: string[]; // 后续再导出名(barrel、CJS 转发 shim)
fnModule?: string; // 求值时创建该函数值的模块(定义处)
}

targetModule/targetExport/fnModule 字段驱动归属守卫:一条记录只会匹配其模块真正指向的文件,因此测试文件里的同名辅助函数不会把记录涂抹到无关文件上。参见调用点发现 — 安全设计。

CaseInfo​

type CaseInfo = {
functionName: string;
caseName: string;
caseIndex: number;
}

以函数名 + 用例名 + 索引定位单个函数的单个用例。

CaseHint​

type CaseHint = {
line: number;
label: string;
ok: boolean;
}

IDE 集成在指令旁渲染的内联提示(行号、文案、通过/失败)。

Diagnostic​

type Diagnostic = {
range: SourceLocation;
severity: DiagnosticSeverity; // "error" | "warning" | "info"
message: string;
tags?: DiagnosticTag[]; // 如 ["unnecessary"]
code?: string; // 如 "nudo:unknown-recv"、"nudo:mock-invalid"、"nudo-unreachable"
suggestions?: string[];
data?: unknown; // 用于代码操作的额外上下文
/** 接收者值的来源(流入该错误的调用点实参) */
origin?: { line: number; column: number };
}

DiagnosticSeverity 为 "error" | "warning" | "info";DiagnosticTag 目前只有 "unnecessary"。

SourceLocation​

type SourceLocation = {
start: { line: number; column: number };
end: { line: number; column: number };
}

BindingInfo​

type BindingInfo = {
abs: Abs;
loc?: SourceLocation;
}

顶层绑定的类型(及可选位置),以名称为键存放在 AnalysisResult.bindings 中。

CompletionItem​

type CompletionItem = {
label: string;
kind: "property" | "method" | "variable";
detail?: string;
}

SymbolInfo / ReferenceInfo / SymbolTable​

type SymbolInfo = {
name: string;
kind: "function" | "variable" | "class" | "parameter";
loc: SourceLocation;
uri?: string;
}

type ReferenceInfo = {
name: string;
loc: SourceLocation;
uri?: string;
}

type SymbolTable = {
definitions: Map<string, SymbolInfo>;
references: ReferenceInfo[];
}

用于跳转定义 / 查找引用工具链的定义与引用信息;LSP 包在其打开的文档上构建此形状的表。

Export inventory​

由 node scripts/gen-api-docs.mjs 从包导出面(PUBLIC_API.md / src/index.ts)生成 —— 请勿手改本块(或在 pnpm run docs:gen 里一并再生)。每行名字带稳定锚点 #slug(符号名小写)。

含 @nudojs/service(src/index.ts)面与 @nudojs/service/emit 公开 emit 面。

名称种类说明签名
AbsGraphOptionstype—AbsGraphOptions = { loadModule?: AbsLoadModule; seedVars?: Record<string, Abs>; seedFns?: Record<string, { params: string[]; body: Node; ...
AbsMockSeedstype—AbsMockSeeds = { seedVars: Record<string, Abs>; seedFns: Record<string, { params: string[]; body: Node; async?: boolean; fingerprint?: st...
AbsModuleCacheEntrytype会话级依赖模块缓存条目:自身 stat 指纹 + 子树内容指纹 + 导出 + 子树装载 issue。AbsModuleCacheEntry = { mtimeMs: number; size: number; contentHash: string; depFingerprints: AbsModuleDepFingerprint[]; exports: AbsModul...
AbsModuleDepFingerprinttype单条本地依赖的内容指纹:解析后稳定路径 + 求值时源码的 hashSource (与 loadModuleDepsFingerprint 同一 hash 口径,DESIGN-002 不另起第二套)。AbsModuleDepFingerprint = { path: string; hash: string; via?: { spec: string; fromFile: string }; }
AbsModuleGraphResulttype—AbsModuleGraphResult = { modules: Record<string, AbsModuleExports>; byPath: Map<string, AbsModuleExports>; issues: AbsModuleLoadIssue[]; }
AbsModuleLoadIssuetype模块装载问题分类(求值引擎是唯一上报源;analyzer 映射诊断用)AbsModuleLoadIssue = { kind: | "cycle" | "depth" | "missing" | "missing-export" | "exports-unresolved" | "unreadable" | "json-invalid"; l...
absToSchemaNodefnAbs → SchemaNode + dropped(优先 core absToConstraint;失败则 shape 尽力)absToSchemaNode( a: Abs, opts?: { scope?: SchemaProjectionScope }, )
absToSchemaSourcefn—absToSchemaSource( a: Abs, opts?: { dialect?: SchemaDialect; scope?: SchemaProjectionScope }, ): string
absToStandardSchemaFunctionfnAbs → Standard Schema v1 函数级模块源码(入参面 + 返回面)。absToStandardSchemaFunction( spec: StandardSchemaFunctionSpec, opts?: { banner?: string; scope?: SchemaProjectionScope }, ): StandardSchemaModuleProjection
absToTSTypefnAbs → TS 类型串。有损:pred / 非 lit term 落到 shape 基类型。absToTSType(a: Abs, typeVars?: Map<string, string>): string
absToZodSchemaModulefnAbs 导出表 → 可 import 的 zod JS 模块源码。absToZodSchemaModule( exports: Record<string, Abs>, opts?: { banner?: string; scope?: SchemaProjectionScope }, ): ZodModuleProjection
AlsoSynthesizeCasestype--both-paths(nudo test):对带 @nudo:case 的函数同轮也走合成路径 (call@/entry@),directive case 与合成 case 同轮同报(教学对比面)。AlsoSynthesizeCases = boolean | readonly string[]
ambientSourcesOfSidecarfnlib.nudo.{js,mjs,ts} → candidate ambient sources next to itambientSourcesOfSidecar(sidecarPath: string): string[]
ANALYSIS_ABIconst带包版本:升级 @nudojs/* 后旧 CheckJson 不得继续命中。const ANALYSIS_ABI
analysisConfigfn归一化 nudo.analysis。默认 mode=exports(A1:无指令但有 export/侧车的文件 进 IDE 分析;all / directives 需显式配置)。analysisConfig(config: NudoConfig | null | undefined): AnalysisConfig
AnalysisConfigtype—AnalysisConfig = { include: string[]; exclude: string[]; mode: AnalysisMode; diagnostics: DiagnosticsLevel; callSiteBudget: number; evalM...
analysisFileCacheKeyfn—analysisFileCacheKey( filePath: string, source: string, activeCases?: Map<string, number>, externalCallRecords?: CallRecord[], analysisCfg?: { mode: string; evalMissingSlot: string; callSiteBudget: number; diagnostics: string; maxForks?: number; }, loadModule?: AnalyzeLoadModule, projectEnvNames?: string[], autoBind?: boolean, caseMode: DirectiveCaseMode = "all", alsoSynthesizeCases?: AlsoSynthesizeCases, )
AnalysisModetype—AnalysisMode = "directives" | "exports" | "all"
AnalysisResulttype—AnalysisResult = { functions: FunctionAnalysis[]; diagnostics: Diagnostic[]; bindings: Map<string, BindingInfo>; nodeAbsMap: Map<Node, Ab...
AnalysisSessiontype—AnalysisSession = { evictForDependents(files: string[]): void; clear(): void; reset(): void; analyze( filePath: string, source: string, a...
analyzeExportsFromSourcefn分析单文件导出 + 内涵签名(source 由 host 提供)analyzeExportsFromSource( filePath: string, source: string, ): ModuleExports
analyzeFilefn整文件分析。同 (path, source, cases, external) 命中 memo → O(1)。analyzeFile( filePath: string, source: string, activeCases?: Map<string, number>, externalCallRecords?: CallRecord[], loadModule?: AnalyzeLoadModule, caseMode: DirectiveCaseMode = "all", alsoSynthesizeCases?: AlsoSynthesizeCases, ): AnalysisResult
analyzeFileAsyncfnAsync entry to analyzeFile: preloads path-based env files (/// @nudo:env ./nudo-harvest-node.ts) via dynamic import — impossible synchronously in ESM — then runs the sync analysis, which picks the preloaded factories up from the env-loader cache.analyzeFileAsync( filePath: string, source: string, activeCases?: Map<string, number>, externalCallRecords?: CallRecord[], loadModule?: AnalyzeLoadModule, caseMode: DirectiveCaseMode = "all", alsoSynthesizeCases?: AlsoSynthesizeCases, ): Promise<AnalysisResult>
analyzeFileAsyncWithEvalFailuresfn{@link analyzeFileAsync} 的观测面版本(1145):env 预载 + 同步分析 + 按文件的引擎内部回落观测。analyzeFileAsyncWithEvalFailures( filePath: string, source: string, activeCases?: Map<string, number>, externalCallRecords?: CallRecord[], loadModule?: AnalyzeLoadModule, caseMode: DirectiveCaseMode = "all", alsoSynthesizeCases?: AlsoSynthesizeCases, ): Promise<{ analysis: AnalysisResult; evalFailures: FileEvalFailure[] }>
analyzeFileWithEvalFailuresfn分析一个文件 + 观测该文件的引擎内部回落(1145 观测面)。analyzeFileWithEvalFailures( filePath: string, source: string, activeCases?: Map<string, number>, externalCallRecords?: CallRecord[], loadModule?: AnalyzeLoadModule, caseMode: DirectiveCaseMode = "all", alsoSynthesizeCases?: AlsoSynthesizeCases, )
applyBForkBudgetFromConfigfn把 fork 预算写进 core(core 保持无 IO)。applyBForkBudgetFromConfig( config: NudoConfig | null | undefined, env: NodeJS.ProcessEnv = process.env, ): number
applyMockModuleDirectivesfnOverlay @nudo:mock-module directives onto a modules map.applyMockModuleDirectives( base: Record<string, AbsModuleExports>, fileDirectives: FileDirective[], opts: { fromFile: string; loadModule?: LoadModule }, ): MockModuleApplyResult
applyMockModuleDirectivesFromSourcefnSource string → apply mock-module (CLI / one-shot hosts).applyMockModuleDirectivesFromSource( source: string, base: Record<string, AbsModuleExports>, opts: { fromFile: string; loadModule?: LoadModule }, ): MockModuleApplyResult
applySessionCacheConfigfn接线 package.json#nudo.sessionCache(进程内 LRU 上限)并立刻 trim。applySessionCacheConfig(config: NudoConfig | null | undefined): SessionCacheLimits
applyTextEditsfn把 edits 应用到源码(按 start 从后往前)applyTextEdits(source: string, edits: TextEdit[]): string
BindingInfotype—BindingInfo = { abs: Abs; loc?: SourceLocation; }
blankGeneratedCaseDirectivesfn供分析使用的源码视图:把生成态 call@ case 指令抹成空注释行(行数 不变)。BUG-076:混合块(手写 case + 生成见证)不参与剥离,但分析若仍把 旧见证当 directive case 读到,就不再合成当前调用点证据 ⇒ 陈旧见证永远 不刷新。写盘基源仍用 stripGeneratedCaseDirectives 的结果(手写块原样)。blankGeneratedCaseDirectives(source: string): string
BodyReadFieldtype—BodyReadField = { field: string; type: string; via: string; fields?: BodyReadField[]; }
BodyReadTypestype—BodyReadTypes = Map<string, Map<string, BodyReadField[]>>
buildCaseDirectivefn组装单行 * @nudo:case "name" (a, b) 指令文本(无尾换行)。buildCaseDirective(name: string, argsAbs: Abs[]): string | null
buildEvalInjectionfn—buildEvalInjection( filePath: string, source: string, allEnvNames: string[], dirDiags: DirectiveDiag[], parseAst: (filePath: string, source: string) => ReturnType<typeof parse>, )
buildModuleGraphfnStatically extract each file's relative import edges (extension resolution identical to CLI resolveModule: ''/'.js'/'.ts'/'.mjs'; bare npm specifiers skipped).buildModuleGraph( files: string[], cache?: ModuleGraphCache, )
buildTestReportfn汇总一份 case 报告的断言结果(+ 逐函数展示行)。buildTestReport( file: string, result: AnalysisResult, opts: TestReportOptions = {}, ): TestReport
CallRecordtype——
CallsiteRecordstype采集结果:记录 + 路径错误(两者必须分开呈现)。CallsiteRecords = { records: CallRecord[]; errors: Array<{ path: string; message: string }>; }
caseExpectedSatisfiedfn实际值是否满足期望(结构面 leqAbs + 对象槽字面量严格面 + 值面谓词)。caseExpectedSatisfied(actual: Abs, expected: Abs): boolean
CaseHinttype—CaseHint = { line: number; label: string; ok: boolean; }
CaseJsontype—CaseJson = { version: 1; file: string; summary: { functions: number; externalFunctions: number; cases: number; diagnostics: number; }; fu...
CaseJsonCasetype—CaseJsonCase = { name: string; args: string[]; result: string; throws: string | null; source: string | null; aggregatedFrom?: number; arg...
CaseJsonFunctiontype—CaseJsonFunction = { name: string; loc: SourceLocation; entryOnly: boolean; noDeclaration?: boolean; cases: CaseJsonCase[]; combined?: st...
CaseResulttype—CaseResult = { name: string; argAbs: Abs[]; abs: Abs; throwsAbs: Abs; throwLoc?: SourceLocation; source?: "directive" | "callsite"; expec...
CaseTestOutcometype—CaseTestOutcome = { fn: string; caseName: string; ok: boolean; unchecked: boolean; uncheckedReason?: "no-expectation" | "inference-failed...
checkCacheKeyfncheck 报告键:abi + 相对路径 + 源码 sha + autoBind + 侧车 sha + @nudo:import / 传递契约依赖内容 sha(依赖变更必须 miss)。checkCacheKey( filePath: string, source: string, opts: { autoBind: boolean; projectDir?: string; sidecarContent?: string | null; depContents?: Array<{ path: string; content: string | null }>; projectEnvNames?: string[]; analysisCfg?: { mode?: string; evalMissingSlot?: string; callSiteBudget?: number; entryThrows?: string; ignoreThrows?: string; maxForks?: number; }; }, ): string
checkConfigfnpackage.json#nudo 键 → 执法选项checkConfig(config: NudoConfig | null | undefined): CheckConfig
CheckConfigtype—CheckConfig = { entryThrows: "error" | "warning" | "off"; ignoreThrows: string[]; }
CheckSupplementOptionstype补充诊断通道的采集选项。CheckSupplementOptions = { modules?: Record<string, unknown>; loadModule?: LoadModule; }
clearAbsModuleCachefn—clearAbsModuleCache(): void
clearAnalysisFileCachefn—clearAnalysisFileCache(): void
clearAnalysisSessionCachesfn清空全部会话级分析缓存(service + core)。clearAnalysisSessionCaches(): void
clearEnvPathDepsfn—clearEnvPathDeps(): void
clearEvalCachefn—clearEvalCache(): void
clearFnAnalysisCachefn—clearFnAnalysisCache(): void
clearPathEnvCachesfnHost cache-clear hooks (CLI watch / vite / tests) must drop path-env modules tooclearPathEnvCaches(): void
collectAbsBindingsFromGraphfn收集顶层绑定名 → Abs(含相对 import / 裸包 harvest 注入)。collectAbsBindingsFromGraph( source: string, filePath: string, opts: AbsGraphOptions = {}, ): Map<string, Abs>
collectCallRecordsfn调用点发现(阶段一):在"使用现场"文件(测试 / 上层应用)中求值 顶层代码,收集它对(外部模块导出的)函数的调用记录。每条记录带 真实的实参类型与结果类型——后续 analyzeFile 将其注入合成 case, 使被使用方从 entry-only(参数全 unknown)升级为真实调用形态。collectCallRecords(filePath: string, source: string): CallSiteRecord[]
collectCallsiteRecordsfn采集使用点记录(--from 等价通道)。collectCallsiteRecords(sites: string[]): CallsiteRecords
collectCheckSupplementIssuesfn采集三条补充诊断通道(指令文法 / mock 装载 / env 未解析)→ CheckIssue[]。collectCheckSupplementIssues( filePath: string, source: string, opts: CheckSupplementOptions = {}, ): CheckIssue[]
collectDependencySpecsconst——
collectEnvGlobalsfn—collectEnvGlobals(envNames: string[]): Record<string, Abs>
collectEnvModulesfnBug 282:env 模块是 CJS 互操作模块——Node 的 node:fs 的默认导出就是 模块对象本身(具名导出挂在它上面)⇒ ESM 默认导入 (import fs from "node:fs")必须绑到命名空间。collectEnvModules(envNames: string[]): Record<string, AbsModuleExports>
collectEnvNamesfn—collectEnvNames(filePath: string, source: string, includeProject: boolean): string[]
collectEvalDiagnosticsfn静态收集 求值引擎诊断。collectEvalDiagnostics( source: string, extraKnown?: Iterable<string>, filename?: string, ): EvalDiagnostics
collectEvalReplacementsfn收集 @nudo:replace + @nudo:as → transpile 注入表。collectEvalReplacements( source: string, opts?: { diags?: DirectiveDiag[] }, ): EvalReplacements
collectLoadDepContentsfn—collectLoadDepContents( filePath: string, source: string, loadModule: (spec: string, fromFile: string) => string | undefined, )
collectMissingExportIssuesfnnamed import / re-export 缺名 → missing-export issue。collectMissingExportIssues( source: string, modules: Record<string, AbsModuleExports>, fromFile: string, ): AbsModuleLoadIssue[]
collectParamBodyReadTypesfn收集每个函数形参成员读取 + 用法推断类型。collectParamBodyReadTypes(source: string): BodyReadTypes
collectParamContractsfn收集每个函数形参的契约证据(quickfix 侧车发射面): 数组方法接收者读 → array(元素契约)(元素 shape 由回调元素位 成员读合成);纯成员读 → shape(…);参数本体标量用法 → 叶子 DSL (number() 等)。无证据参数不进表(契约留 any 位)。collectParamContracts(source: string): ParamContracts
collectSkipReturnsfn每个带 @nudo:skip 的顶层函数 → 声明的返回 Abs;null = 未声明返回类型。collectSkipReturns(source: string): Map<string, Abs | null>
collectStaticImportsfn从入口文件沿静态相对 import/require 收集(仅类型事实,不是运行时加载器)。collectStaticImports( entryFile: string, maxDepth = 8, ): Map<string, ModuleExports>
compileAnyMatcherfnCompile a pattern list into a matcher that is true when any pattern matches.compileAnyMatcher(patterns: string[] | string): Matcher
compilePatternfn单模式编译:无通配符(* / ?)→ 字面量子串匹配;有 → 锚定正则。compilePattern(pattern: string): Matcher
CompletionItemtype—CompletionItem = { label: string; kind: "property" | "method" | "variable" | "function"; detail?: string; }
ComposedEvalModulestype模块图组装的共享产物:analyzer 与 tryRunEval 走同一序列 (evalAbsModuleGraph → collectEnvModules → mergeHarvestUnderEnv → applyMockModule*),单一事实源,不再各自漂移。ComposedEvalModules = { modules: Record<string, AbsModuleExports>; issues: AbsModuleLoadIssue[]; mockErrors: string[]; mockModuleErrors: ...
composeEvalModulesfn模块图组装单一入口:相对/harvest 模块图 → @nudo:env modules 并入 (手写 env wins,B8)→ @nudo:mock-module 覆盖。composeEvalModules( source: string, filePath: string, opts: { envNames?: string[]; seedVars?: Record<string, Abs>; seedFns?: AbsGraphOptions["seedFns"]; loadModule?: LoadModule; fileDirectives?: FileDirective[]; } = {}, ): ComposedEvalModules
computeDirtySetfnchanged plus its transitive dependents (reverse-edge BFS); cycle-safe via visited.computeDirtySet(dependents: Map<string, Set<string>>, changedFile: string): string[]
configIgnoreThrowsfnpackage.json#nudo.check.ignoreThrows 的原始值 → 与 CLI 同口径的列表 (679:配置面复用本解析器,不再走各面自己的严格 string[] 过滤—— 裸字符串 "TypeError" 曾被静默丢成空表 ⇒ 门禁假红)。configIgnoreThrows( config: { check?: unknown } | null | undefined, ): string[]
ConstraintSourceExprtype—ConstraintSourceExpr = { expr: string; importFrom?: string; importName?: string; }
contractCacheKeyfneffectiveContract 表键(L1 Phase B,design-persistent-cache)。contractCacheKey( filePath: string, source: string, opts: { autoBind: boolean; projectDir?: string; sidecarSource?: string | undefined; depContents?: Array<{ path: string; content: string | null }>; projectEnvNames?: string[]; }, ): string
contractConfigfn归一化 nudo.contract 配置段。contractConfig(config: NudoConfig | null | undefined): ContractConfig
ContractConfigtype—ContractConfig = { autoBind: boolean; emit: string[]; }
ContractDraftEntrytype—ContractDraftEntry = { fn: string; identity?: string; params: Array<{ name: string; constraint?: NudoConstraint; display: string; project...
ContractDraftOptstype—ContractDraftOpts = { fnNames?: string[]; records?: CallRecord[]; loadModule?: LoadModule; autoBind?: boolean; bodyAccesses?: boolean; so...
ContractDraftResulttype—ContractDraftResult = { file: string; entries: ContractDraftEntry[]; draftSource: string; sidecarPath: string; }
contractDslOffn契约证据 → constraint-builder DSL 文本(array(shape({ … })) 等)contractDslOf(ev: ParamContractEvidence): string
contractSurfacefn单文件 contract 表面:analyzer 推断结果给出函数清单与 implicit 展示, effectiveContract 给出契约命中(手写 > 生成段)。contractSurface( filePath: string, opts: ContractSurfaceOpts = {}, ): Promise<ContractSurfaceEntry[]>
ContractSurfaceEntrytype—ContractSurfaceEntry = { fn: string; identity?: string; kind: "export" | "local"; source: "handwritten" | "generated" | "implicit"; param...
ContractSurfaceOptstype—ContractSurfaceOpts = { autoBind?: boolean; loadModule?: LoadModule; records?: CallRecord[]; source?: string; diagnostics?: ContractFaceD...
currentBForkBudgetLimitfn当前生效 fork 上限(调试/测试;与 core getEvalForkBudgetLimit 同源)currentBForkBudgetLimit(): number
DEFAULT_ANALYSIS_MODEconst", ]; /** A1 产品默认:exports — 普通带导出的 .js 进 IDE;directives/all 需显式const DEFAULT_ANALYSIS_MODE
DEFAULT_SESSION_CACHE_LIMITSconst保守默认:多项目共存时不悄悄吃内存(大仓请显式调高)const DEFAULT_SESSION_CACHE_LIMITS
defaultAbsLoadModulefn相对说明符 → 源码(与 defaultLoadModule 同一扩展名/入口候选表)defaultAbsLoadModule(spec: string, fromFile: string): string | undefined
defaultLoadModulefn默认 loadModule:相对/绝对说明符 → 源码。defaultLoadModule( spec: string, fromFile: string, mode?: ModuleLoadMode, ): string | undefined
DepContenttype—DepContent = { path: string; content: string | null }
DerivedExporttype—DerivedExport = { file: string; fn: string; paramNames: string[]; params: DerivedParam[]; returns?: { constraint: NudoConstraint; dsl: st...
DerivedParamtype—DerivedParam = { name: string; constraint: NudoConstraint; dsl: string; prelude: string[]; imports: Array<{ name: string; from: string }>...
deriveFromRootfn入口:对 filePath 做 root 驱动下行推导。deriveFromRoot( filePath: string, opts: RootDeriveOpts = {}, ): RootDeriveResult
detectEntryVariantsFromPackageJsonfnDetect browser/node dual faces in a parsed package.json.detectEntryVariantsFromPackageJson(pkg: unknown): EntryVariantFaces | null
Diagnostictype—Diagnostic = { range: SourceLocation; severity: DiagnosticSeverity; message: string; tags?: DiagnosticTag[]; code?: string; suggestions?:...
DiagnosticSeveritytype—DiagnosticSeverity = "error" | "warning" | "info"
DiagnosticsLeveltype—DiagnosticsLevel = "off" | "errors" | "default" | "verbose"
diagnosticsLevelForFilefn—diagnosticsLevelForFile(filePath: string): DiagnosticsLevel
DiagnosticTagtype—DiagnosticTag = "unnecessary"
DirectiveCaseModetype@nudo:case 求值档: - none(默认):不跑 case;有 case 的函数也走 entry@ 出签名(check / IDE) - all:逐 case 真跑(nudo test / CaseJson / freeze) - selected:只跑 activeCases 选中的那条(LSP selectCase)DirectiveCaseMode = "none" | "all" | "selected"
directiveDiagIssuesfnD1: 指令文法诊断(nudo:directive-syntax)→ CheckIssue(warning,不挡 exit)。directiveDiagIssues( diags: Array<{ code: string; message: string; at?: { line: number; column: number }; }>, ): CheckIssue[]
DiskCachefn—DiskCache { private readonly root: string | undefined; private readonly ns: string; private readonly keyMat: Buffer | undefined; enabled ...
DiskCacheOptionstype—DiskCacheOptions = { root?: string | undefined; namespace: string; signKey?: string; }
diskCacheRootfn磁盘缓存根(B3):config.cache / NUDO_CACHE_DIR / 默认关。diskCacheRoot( config: NudoConfig | null | undefined, projectDir: string | undefined, ): string | undefined
DiskCacheSignErrorfnnudo.cache.sign 配置错误(sign: true 但 NUDO_CACHE_KEY 缺席/空, 或 sign 取值形状非法)。签名是安全旋钮 ⇒ 拒绝运行(CLI 面显式报错 退出),不静默降级到未签名缓存。DiskCacheSignError extends Error { constructor(message: string) { super(message); this.name = "DiskCacheSignError"; } }
diskCacheSignStatefn—diskCacheSignState( config: NudoConfig | null | undefined, env: NodeJS.ProcessEnv = process.env, ): DiskCacheSignState
DiskCacheSignStatetype磁盘缓存条目签名状态(B3 信任面): - { kind: "off" }:未开签名(默认)——旧未签名行为原样 - { kind: "on", key }:签名开 + NUDO_CACHE_KEY 就绪(key = 原始密钥串, HMAC 密钥材料派生见 disk-cache.ts) - { kind: "error", message }:配置错误——sign: true 但密钥缺席/空。DiskCacheSignState = | { kind: "off" } | { kind: "on"; key: string } | { kind: "error"; message: string }
domainEvidenceCasesfn产物面(dts / zod / standard / guard)的域证据 case。domainEvidenceCases(cases: readonly CaseResult[]): CaseResult[]
draftContractfn为单文件顶层导出生成 contract 草稿(不写盘)。draftContract( filePath: string, opts: ContractDraftOpts = {}, ): Promise<ContractDraftResult>
DraftEvidencetypeDraftEvidence body = 仅来自函数体对形参的成员读取(草稿建议,非义务)。DraftEvidence = "callsite" | "directive" | "symbolic" | "body" | "none"
DtsClassSurfacetype类声明面(成员面 + 导出形态)DtsClassSurface extends DtsClassMemberSurface { exportName?: string; exportNames?: string[]; isDefault: boolean; }
DtsContractFacetype契约面证据(export CLI 从 effectiveContract 取——与 check 签名面同数据源: sidecar(*.nudo.js)∪ inline @nudo:contract)。DtsContractFace { params: Array<{ name: string; abs: Abs; optional?: boolean; display?: string }>; return?: Abs; returnDisplay?: string; }
DtsFunctionProjectiontypeprojectFunctionDts 的返回面:声明行 + 主签名参数位(unknown = 无证据)DtsFunctionProjection { lines: string[]; params: Array<{ name: string; type: string }>; exportName?: string; classMember?: { className: s...
DtsModuleExtrastype模块面合成的分析面补充证据(函数入口之外的事实:模块级绑定 Abs)。DtsModuleExtras { values?: ReadonlyMap<string, Abs>; }
DtsModuleProjectiontype模块面 dts 投影结果DtsModuleProjection { lines: string[]; params: Array<{ name: string; type: string }>; }
dtsModuleSurfacefn模块导出面扫描(源文件 → 导出名表 + 类面 + 再导出语句)。dtsModuleSurface(source: string): DtsModuleSurface
DtsModuleSurfacetype模块导出面(源文件的导出面:导出名 → 本地绑定 + 类面 + 再导出 + 导入面)DtsModuleSurface { exportBindings: Map<string, string>; reexports: string[]; classes: Map<string, DtsClassSurface>; imports?: Map<string,...
DtsValueSurfacetype模块级值声明面(BUG-190):export const/let/var 与 TS enum。DtsValueSurface { kind: "const" | "let" | "var" | "enum"; enumMembers?: Array<{ name: string; init?: string }>; constEnum?: boolean; type...
emitContractfn单文件 emit:分析 → 逐目标投影/自检 → 组装侧车内容 →(非 dryRun)写盘。emitContract( filePath: string, opts: EmitContractOpts, ): Promise<EmitContractResult>
EmitContractOptstype—EmitContractOpts = { fnNames?: string[]; mode: "add" | "update"; all?: boolean; dryRun?: boolean; records?: CallRecord[]; source?: string...
EmitContractResulttype—EmitContractResult = { written: string[]; skipped: Array<{ fn: string; reason: EmitContractSkipReason }>; changed: boolean; diff?: string...
EmitContractSkipReasontype—EmitContractSkipReason = | "name-clash" | "not-projectable" | "not-an-export" | "no-change" | "emit-denied" | "multi-declarator" | "expor...
emitDerivedFromRootfn—emitDerivedFromRoot( rootFile: string, opts: { fnNames?: string[]; mode: "add" | "update"; dryRun?: boolean; loadModule?: LoadModule; autoBind?: boolean; refreshExistingOnly?: boolean; baseContent?: (sidecarPath: string) => string | undefined; skipWrite?: string[]; directSections?: Set<string>; directCreatedSections?: Set<string>; }, ): EmitDerivedResult
EmitDerivedResulttype—EmitDerivedResult = { sidecars: Array<{ file: string; sidecarPath: string; fn: string; written: boolean; writtenNames?: string[]; changed...
EmitResulttype—EmitResult = { source: string; changed: boolean; written: Array<{ fn: string; cases: string[] }>; skipped: Array<{ fn: string; reason: Em...
EmitSkipReasontype—EmitSkipReason = | "hand-written" | "already-generated" | "entry-only" | "no-serializable-cases" | "no-declaration" | "contract-violation...
ENTRY_CONTRACT_NOTEconstentry@ 回退 case × 有效契约的注解行:解释「check 全绿但 test 打 (any) => any throws」的表面矛盾——entry@ 用的是无约束入口 face, 契约作用于 check/export 面;要看到受约束的 case 就加 @nudo:case 或提供调用点。throws 显示保留(那是无约束 face 的诚实结果)。const ENTRY_CONTRACT_NOTE
EntryVariantFaceGrouptypeOne browser/node face pair, scoped to a subpath or field source.EntryVariantFaceGroup = { key: string; browser: string[]; node: string[]; }
EntryVariantFacestype—EntryVariantFaces = { kind: "exports-conditions" | "browser-field"; groups: Map<string, EntryVariantFaceGroup>; }
entryVariantForFilefnDual-entry info for an analyzed file: the owning package must declare a dual group (browser + node faces resolving to different files in the same subpath / field source) and this file must be one of that group's entry targets on exactly one face.entryVariantForFile(filePath: string): EntryVariantInfo | null
EntryVariantInfotype—EntryVariantInfo = { pkgPath: string; pkgDir: string; pkgName?: string; kind: "exports-conditions" | "browser-field"; browserPaths: strin...
EntryVariantIssuetypeHost-facing info issue (CLI check / JSON) for one analyzed entry variant.EntryVariantIssue = { severity: "info"; code: typeof DIAG.dualEntry; message: string; suggestion: string; line: number; column: number; }
entryVariantIssueForFilefn—entryVariantIssueForFile(filePath: string): EntryVariantIssue | null
ENV_UNRESOLVED_CODEconstpath env 加载失败告警码(live 瞬态:每轮 preloadPathEnvs 现场收集)。const ENV_UNRESOLVED_CODE
EnvHarvestConflicttypeConflict when handwritten env overwrote a harvest module/export (B8).EnvHarvestConflict = { module: string; exports: string[]; defaultOverwritten: boolean; }
envPathDependentsfn依赖该 env 模板的源文件列表envPathDependents(envPath: string): string[]
envUnresolvedIssuesfnpath env 未解析 → CheckIssue(warning)。envUnresolvedIssues( filePath: string, source: string, baseDir = dirname(filePath), ): CheckIssue[]
evalAbsModuleGraphfn递归求值相对依赖 + 裸包 harvest,产出入口可用的 modules 表。evalAbsModuleGraph( entrySource: string, entryFile: string, opts: AbsGraphOptions = {}, ): AbsModuleGraphResult
EvalBuiltinUnknowntype—EvalBuiltinUnknown = { name: string; range: EvalLoc }
EvalDiagnosticstype—EvalDiagnostics = { unreachable: EvalUnreachable[]; builtinUnknown: EvalBuiltinUnknown[]; capabilityDenied: EvalBuiltinUnknown[]; deniedM...
EvalRunResulttype—EvalRunResult = { exports: Record<string, unknown>; modules: Record<string, AbsModuleExports>; memberDiags?: EvalMemberDiag[]; moduleIssu...
EvalUnreachabletype—EvalUnreachable = { range: EvalLoc }
evictAbsModuleCacheFilesfn键身份统一 stablePathKey(FIX-RESIDUAL-4):跨盘符形态删除/命中一致evictAbsModuleCacheFiles(paths: string[]): void
evictAnalysisCachesForFilesfn依赖内容变更后:按入口文件定向逐出 service 层缓存。evictAnalysisCachesForFiles(files: string[]): void
evictAnalysisFileCacheForFilesfn依赖变更后:按入口文件逐出(查找与写入同走 stablePathKey)evictAnalysisFileCacheForFiles(files: string[]): number
evictEvalCacheForFilesfn依赖文件变更后:逐出以这些文件为入口的 evaluator 缓存(键走 stablePathKey;两种 mode 槽一并清)evictEvalCacheForFiles(files: string[]): number
evictFnAnalysisCacheForFilesfnDependency content changed: drop every per-fn entry for these entry files.evictFnAnalysisCacheForFiles(files: string[]): number
evictProjectConfigMemofn清空 findProjectConfig 目录链 memo(项目配置 watch 通道 / 测试隔离)。evictProjectConfigMemo(): void
extractNudoImportSpecsfn从源码提取 @nudo:import / @nudo:import * as 的 specifierextractNudoImportSpecs(source: string): string[]
FileEvalFailuretype——
filterDiagnosticsByLevelfn按 analysis.diagnostics 档过滤 evaluator/check 显示路径诊断。filterDiagnosticsByLevel<T extends { severity: string; code?: string }>( diags: T[], level: DiagnosticsLevel, ): T[]
findOwningPackagefnNearest package.json walking up from the file's directory.findOwningPackage( fromFile: string, )
findProjectConfigfn—findProjectConfig( startDir: string, )
formatContractSurfaceLinefn单条 contract 打印行(CLI runContract 与 LSP agent 面共用)formatContractSurfaceLine(e: ContractSurfaceEntry): string
formatDerivedSectionfn组装生成段(组合式 + import + prelude)。formatDerivedSection( row: DerivedExport, opts: { rootSidecarDir: string; targetSidecarDir: string; takenNames?: Iterable<string>; }, )
formatDraftModulefn草稿模块文本(人读 + 可复制到 *.nudo.js / *.nudo.ts)formatDraftModule( filePath: string, entries: ContractDraftEntry[], sidecarPath?: string, throwsHints?: readonly string[], ): string
formatDraftSummaryfn—formatDraftSummary( sourceRel: string, draftRel: string, result: ContractDraftResult, write?: WriteDraftResult, ): string[]
formatEmitSummaryfnemit 摘要行(CLI runContractEmit 与 LSP agent 面共用;路径由调用方按 展示口径传入——CLI 传 cwd 相对、agent 传绝对路径)。formatEmitSummary( sourcePath: string, sidecarRel: string, result: EmitContractResult, ): string[]
formatExpectedfn期望值的可读文本(带谓词):number (> 0) / { n: number (> 0) }。formatExpected(expected: Abs): string
formatPathErrorTextfn路径错误的非 JSON 面文案(CLI 的 usage error 面同口径): 一行原因 + 一行 fix: 提示。formatPathErrorText(errors: PathError[]): string
formatTestReportfn—formatTestReport(r: TestReport): string
FunctionAnalysistype—FunctionAnalysis = { name: string; loc: SourceLocation; paramNames: string[]; formals?: FormalParam[]; declaredReturnType?: string; thisR...
generateDtsfn—generateDts(result: AnalysisResult): string
generateFunctionDtsLinesfn—generateFunctionDtsLines( fn: FunctionAnalysis, contract?: DtsContractFace, ): string[]
generateGuardFunctionFromAbsfn守卫源码:export function <name>(value: unknown): boolean { … }。generateGuardFunctionFromAbs(name: string, abs: Abs, used?: Set<string>): string
getAbsModuleCacheSizefn测试/诊断:当前条目数(≤ ABS_MODULE_CACHE_MAX)getAbsModuleCacheSize(): number
getAnalysisFileCacheSizefn—getAnalysisFileCacheSize(): number
getAnalysisSessionfn进程内默认 AnalysisSession(LSP server / CLI watch / agent tools 共用)getAnalysisSession(): AnalysisSession
getEnvHarvestConflictCollectorfnRead-only peek for tests / nested restore.getEnvHarvestConflictCollector()
getEnvPathDepsSizefn测试/诊断:反向依赖驻留规模getEnvPathDepsSize(): number
getEvalCacheSizefn测试/诊断:当前 evaluator run 缓存条目数(≤ getSessionCacheLimits().maxEvalRuns)getEvalCacheSize(): number
getFnAnalysisCacheSizefn测试/诊断:当前条目数(≤ getSessionCacheLimits().maxFns)getFnAnalysisCacheSize(): number
getPathEnvCacheSizesfn测试/诊断:path-env 驻留规模(均 ≤ 对应上限)getPathEnvCacheSizes()
getPathEnvDepContentsfn已成功预载的 path env 文件(供 check 磁盘缓存指纹纳入 sha)。getPathEnvDepContents(baseDir?: string): Array<{ path: string; content: string | null }>
getPathEnvLoadErrorsfnpath env 加载失败诊断(check/test 打印 nudo:env-unresolved warning 用)。getPathEnvLoadErrors(baseDir?: string): Array<{ path: string; error: string; baseDir: string }>
getSessionCacheLimitsfn—getSessionCacheLimits( env: NodeJS.ProcessEnv = process.env, ): SessionCacheLimits
inferenceFailedfnBug 950 第三态:引擎未能推断实测值(⇒ 无法判定,不是「不匹配」)。inferenceFailed(actual: Abs): boolean
injectBindingsfn—injectBindings( source: string, bindings: TypeBinding[], )
InsertCaseOptionstype固化写回的宿主接线(BUG-055 / BUG-119)——全部可选: 缺省时行为与改前逐字一致(只认源码内指令契约、add 模式的整函数跳过)。InsertCaseOptions = { filePath?: string; loadModule?: (spec: string, fromFile: string) => string | undefined; autoBind?: boolean; project...
insertGeneratedCaseDirectivesfn把 analysis 中的合成 case(source === "callsite")固化为源码指令: 1.insertGeneratedCaseDirectives( source: string, analysis: AnalysisResult, opts: InsertCaseOptions = {}, ): EmitResult
isEnvTemplatePathfnwatch 门禁:env 模板变更必须可被接收(即便扩展名不进 isNudoTargetPath)isEnvTemplatePath(path: string): boolean
isNudoTargetPathfnnudo 推断目标文件判定(纯扩展名规则,路径无需存在)。isNudoTargetPath(path: string): boolean
isProjectConfigPathfn—isProjectConfigPath(path: string): boolean
isRuntimeGlobalCtorNamefnbrand 名能否用 z.instanceof(<name>) 表达(须是运行时全局构造器名)。isRuntimeGlobalCtorName(name: string): boolean
isSidecarPathfnFormal sidecar contracts only — drafts never ambient-bind and need not reanalyzeisSidecarPath(path: string): boolean
isWatchRelevantPathfnWatch accept gate: analysis targets + sidecar/config/env-template invalidatorsisWatchRelevantPath(path: string): boolean
LoadModuletype—LoadModule = (spec: string, fromFile: string) => string | undefined
locFromNodefn—locFromNode(node: Node): SourceLocation
Matchertype极简 glob → RegExp 编译器(自 vite-plugin 内联实现抽取,语义不变)。Matcher = (id: string) => boolean
matchesEmitAllowlistfn极简 glob(** / * / ?):相对 projectDir 匹配源文件绝对路径 (不是侧车路径;侧车随源文件同目录写出)。无白名单 → true。matchesEmitAllowlist( absPath: string, projectDir: string | undefined, patterns: string[], ): boolean
matchSidecarFnDeclfn定位侧车里目标契约的声明起点:export const <name> = fn( / <name> = fn(。matchSidecarFnDecl( sidecarSource: string, exportName: string, )
materializeActionfnkind → WorkspaceEdit 物化。返回 undefined = 该 action 只读(info)或缺证据。materializeAction(input: MaterializeInput): QuickfixPlan | undefined
MaterializeInputtype—MaterializeInput = { code: string; fn?: string; file: string; source: string; sidecarText?: string; sidecarPath: string; action: CheckAct...
mergeCheckIssuesfn追加 issues 并同步 summary/ok(有新 error 则 ok=false)。mergeCheckIssues<T extends Summarized>(report: T, issues: CheckIssue[]): T
MergeHarvestOptionstype—MergeHarvestOptions = { onConflict?: (c: EnvHarvestConflict) => void; }
mergeHarvestUnderEnvfnHandwritten @nudojs/env wins over harvest / graph modules on overlapping module keys and overlapping export names (docs/versioning.md B8 + website harvester API).mergeHarvestUnderEnv( harvestModules: Record<string, AbsModuleExports>, envModules: Record<string, AbsModuleExports>, opts?: MergeHarvestOptions, ): Record<string, AbsModuleExports>
mockDirectivesToAbsSeedsfn从函数上的 @nudo:mock 指令收集 Abs seedmockDirectivesToAbsSeeds( functions: Array<{ directives: FunctionWithDirectives["directives"]; name?: string }>, opts?: { fromFile?: string; loadModule?: LoadModule; }, ): AbsMockSeeds
MockFromErrortype@nudo:mock name from "path" 解析失败(缺文件/缺绑定/求值失败)。MockFromError = { name: string; fromPath: string; message: string; code?: string; }
mockFromErrorIssuesfnmock 装载失败 → CheckIssue。mockFromErrorIssues(mockFromErrors: MockFromError[]): CheckIssue[]
MockModuleApplyResulttype—MockModuleApplyResult = { modules: Record<string, AbsModuleExports>; errors: FromMockError[]; applied: boolean; }
mockSeedsForSourcefn便捷入口:源码 → @nudo:mock 的 eval 注入 Abs 绑定(checkSource 注入管线用)mockSeedsForSource( source: string, opts?: { fromFile?: string; loadModule?: LoadModule }, ): Record<string, Abs>
mockSeedsToAbsMocksfn求值引擎注入用:seedVars + seedFns 统一为 Abs 函数绑定。mockSeedsToAbsMocks(seeds: AbsMockSeeds): Record<string, Abs>
ModuleExportstype—ModuleExports = { path: string; named: Map<string, string>; defaultExport?: string; source: string; poly: Map<string, PolyFn>; }
ModuleGraphCachetypemtime 边缓存:key 为文件路径,edges 为已抽取的相对 import 边(与 buildModuleGraph 返回语义一致)。ModuleGraphCache = Map<string, { mtimeMs: number; size: number; edges: string[] }>
ModuleReadErrorfn路径 stat 或文件读失败(EACCES / EMFILE / ESTALE / EIO …)。ModuleReadError extends Error { readonly code: string; readonly path: string; constructor(path: string, cause: unknown) { const code = (c...
normalizeRealPathfn—normalizeRealPath(p: string): string
normPosixPathfnposix 化(\ → /)——等值比较前先统一分隔符normPosixPath(p: string): string
noteEnvPathDepsfn源码里的 path-based load specs 解析为绝对路径后登记反向边noteEnvPathDeps(sourcePath: string, source: string): void
NudoCacheConfigtypenudo.cache 的对象形态(CI 级信任面): - dir:根目录(true/省略 → .nudo/cache;字符串 → 自定义根;false → 关闭) - sign:条目 HMAC 签名(默认 false)。开启时必须提供 env NUDO_CACHE_KEY(非空),否则拒绝运行(显式配置错误,不静默降级)—— 伪造的结构合法 CheckJson 会造成假绿(persistent-cache.md 的 L1 关闭理由), 签名把「结构合法」升级为「本密钥签发」。NudoCacheConfig = { dir?: boolean | string; sign?: boolean; }
NudoConfigtype—NudoConfig = { env?: string[]; mocks?: Record<string, string>; contract?: { autoBind?: boolean; emit?: string[] | string; }; analysis?: {...
openDiskCachefn单源 DiskCache 构造:根目录(diskCacheRoot)+ 签名状态 (diskCacheSignState)一并解析。配置错误时 throw DiskCacheSignError (消费面:CLI check/contract/health 在 action 层预检给分面错误形态; 本函数是库面/漏检路径的 fail-closed 兜底)。openDiskCache(opts: { config: NudoConfig | null | undefined; projectDir: string | undefined; namespace: string; env?: NodeJS.ProcessEnv; }): DiskCache
ParamContractEvidencetype参数契约证据(quickfix 侧车发射面): - array:参数被当数组方法接收者调用(items.reduce(…));element 为 回调元素位合成的元素契约(无证据 → array(any())) - shape:参数被成员读取(既有 body-read 字段面) - scalar:参数本体直接用法(1 + tax → number())——多参函数只收窄 一个参数仍消不掉 L2(残余 may-throw 来自其余未约束位) 优先级:array > shape > scalar(数组方法读是最强形态证据)。ParamContractEvidence = | { kind: "array"; element?: ParamContractEvidence } | { kind: "shape"; fields: BodyReadField[] } | { kind: "scal...
ParamContractstypefnName → paramName → 契约证据(参数按声明序插入)ParamContracts = Map<string, Map<string, ParamContractEvidence>>
parseIgnoreThrowsfn--ignore-throws / package.json#nudo.check.ignoreThrows 解析的 单一实现(CLI / LSP / vite-plugin 三面共享)。parseIgnoreThrows(raw?: unknown): string[] | undefined
pathEnvPreloadFingerprintfn预载状态指纹(已驻留的 path env 文件:路径 + mtimeMs)。pathEnvPreloadFingerprint(): string
PathErrortype路径错误(--json 信封的 pathErrors 面;非 JSON 面走 usage error)。PathError = { path: string; code: PathErrorCode; message: string; suggestion: string; }
PathErrorCodetype路径错误码(与 CLI 的 PathError 码集一致)。PathErrorCode = | typeof DIAG.pathNotFound | typeof DIAG.pathEmptyDir | typeof DIAG.pathNotTarget | typeof DIAG.pathMissingCallsite | typ...
pathNotFoundErrorfn路径不存在(CLI 同口径文案)。pathNotFoundError(path: string): PathError
projectConfigMemoStatsfn诊断/测试:memo 条目数 + 实际读盘(readFileSync+JSON.parse)次数projectConfigMemoStats()
projectFunctionDtsfn为单个函数生成 .d.ts 投影(JSDoc + 单一 widen 主签名)。projectFunctionDts( fn: FunctionAnalysis, contract?: DtsContractFace, surface?: DtsModuleSurface, ): DtsFunctionProjection
projectModuleDtsfn—projectModuleDts( surface: DtsModuleSurface | undefined, entries: ReadonlyArray<{ fn: FunctionAnalysis; projection: DtsFunctionProjection; contract?: DtsContractFace; }>, extras?: DtsModuleExtras, ): DtsModuleProjection
QuickfixPlantype—QuickfixPlan = { titleKind: QuickfixTitleKind; title: string; edits: TextEdit[]; sidecar?: { path: string; newText: string }; openPath?: ...
QuickfixTitleKindtype—QuickfixTitleKind = "fix" | "silence" | "review" | "adjust" | "scaffold"
ReferenceInfotype—ReferenceInfo = { name: string; loc: SourceLocation; uri?: string; }
relativizePathfn稳定逻辑根相对化(磁盘缓存路径维):树内相对 root,树外取 node_modules/<pkg> 段、monorepo root 或 pnpm store 内容哈希; 绝对路径明文绝不进 key。relativizePath(p: string, root?: string): string
resetAllAnalysisCachesfn比 clearAnalysisSessionCaches 更彻底:再丢 AST LRU(测试 / 进程复用场景)resetAllAnalysisCaches(): void
resetSessionCacheLimitStatefn测试:清空显式 / package.json 层(env 每次调用现读,无需重置)resetSessionCacheLimitState(): void
resolveModulefn—resolveModule(source: string, fromDir: string)
resolveRelativeSpecfn相对说明符 → 相对 from 文件的规范化 posix 路径;非相对说明符 → undefinedresolveRelativeSpec(from: string, spec: string): string | undefined
RootDeriveOptstype—RootDeriveOpts = { loadModule?: LoadModule; autoBind?: boolean; fnNames?: string[]; refreshExistingOnly?: boolean; }
RootDeriveResulttype—RootDeriveResult = { roots: string[]; derived: DerivedExport[]; hasRoot: boolean; graphError?: string; }
safeLoadModulefnloadModule 容错包装:读失败当 miss,避免 I/O 错误炸穿指纹/图遍历。safeLoadModule( loadModule: (spec: string, fromFile: string) => string | undefined, spec: string, fromFile: string, ): string | undefined
SchemaDialecttype—SchemaDialect = "zod"
SchemaNodetype—SchemaNode = | { k: "lit"; value: import("@nudojs/core").LiteralValue } | { k: "prim"; type: "number" | "string" | "boolean" | "bigint" |...
SchemaProjectiontype—SchemaProjection = { source: string; dialect: SchemaDialect; dropped: string[]; }
SchemaProjectionScopetype模块面作用域(BUG-051):shadowedGlobals = 本模块里被用户绑定(类 / 导入 / 顶层声明)遮蔽掉的全局构造器名。SchemaProjectionScope = { shadowedGlobals?: ReadonlySet<string>; }
SchemaRefinementtype—SchemaRefinement = | { kind: "numBound"; op: "gt" | "ge" | "lt" | "le"; n: number } | { kind: "int" } | { kind: "strMin"; n: number } | {...
serializeCaseArgfn单个 Abs → parseCaseArgExpr 可解析回去的表达式文本;不可表达返回 nullserializeCaseArg(a: Abs): string | null
serializeCaseJsonfn—serializeCaseJson( result: AnalysisResult, file: string, ): CaseJson
SessionCacheLimitstype会话级内存 LRU 上限(进程内,非磁盘 cache)。SessionCacheLimits = { maxFiles: number; maxFns: number; maxEvalRuns: number; }
setAnalysisSessionfn测试:替换默认 session(返回旧值以便恢复)setAnalysisSession(session: AnalysisSession | undefined): AnalysisSession | undefined
setEnvHarvestConflictCollectorfnInstall conflict collector; returns the previous one so nested/concurrent analyzeFile callers can save/restore (scoped fallback: inside runWithCollectorScope each analysis gets its own slot, no cross-talk).setEnvHarvestConflictCollector( collector: ((c: EnvHarvestConflict) => void) | null, )
setSessionCacheFromProjectfnpackage.json#nudo.sessionCache 层(findProjectConfig / 宿主接线)setSessionCacheFromProject(partial: PartialLimits | null | undefined): void
setSessionCacheLimitsfn显式覆盖(宿主 / 测试)。传 null 清除显式层setSessionCacheLimits(partial: PartialLimits | null): SessionCacheLimits
sha256Hexfn—sha256Hex(data: string | Buffer): string
shapeDslFromFieldsfnshape({ type: string(), loc: shape({ start: … }) }) 文本。shapeDslFromFields(fields: BodyReadField[]): string
shouldAnalyzeFilefn是否应对该文件跑分析(自动路径,如 LSP validate)。shouldAnalyzeFile( filePath: string, source: string | undefined, config?: AnalysisConfig, ): boolean
sidecarDraftPathfnlib.js|ts → lib.nudo.draft.js|ts(不进 ambient sidecar 表)sidecarDraftPath(filePath: string): string
sourceHasNudoDirectivesfn—hasNudoDirectives(source: string): boolean
SourceLocationtype—SourceLocation = { start: { line: number; column: number }; end: { line: number; column: number }; }
stablePathKeyconst——
stablePathKeyGraphconst——
StandardSchemaFunctionSpectype标准面函数级装配描述(入参面 + 返回面)。StandardSchemaFunctionSpec = { fn: string; inputs?: ReadonlyArray<{ name: string; abs: Abs; optional?: boolean }>; formals?: ReadonlyArra...
StandardSchemaInputEntrytype标准面入参条目:整参(param)或解构形参的字段(field)。StandardSchemaInputEntry = | { kind: "param"; name: string; abs: Abs; optional?: boolean } | { kind: "field"; name: string; abs: Abs; opt...
StandardSchemaIssuetype—StandardSchemaIssue = { message: string; path?: ReadonlyArray<PropertyKey>; }
StandardSchemaModuleProjectiontype—StandardSchemaModuleProjection = { source: string; dropped: string[]; }
StandardSchemaResulttype—StandardSchemaResult = | { value: unknown; issues?: undefined } | { issues: ReadonlyArray<StandardSchemaIssue>; value?: undefined }
stripGeneratedCaseDirectivesfn从源码剥离所有本模块生成的 @nudo:case 指令(名字以 call@ 开头,整行删除)。stripGeneratedCaseDirectives(source: string)
Summarizedtypecheck 报告的最小可并入形状(CheckReport / CheckJson 都满足)。Summarized = { issues: CheckIssue[]; ok: boolean; summary: { errors: number; warnings: number; infos: number; functions: number }; }
SYMBOLIC_BUDGET_NOTEconstcall@symbolic(预算聚合见证)× actionable 提示(精度悬崖 UX):报告里出现 call@symbolic = 该函数的调用点数超过了 callSiteBudget(默认 3, package.json#nudo.analysis.callSiteBudget,1–64),超预算的调用点被折进 一条宽化聚合见证(#widened,可解释降级)。两条恢复路径,与 check 面 nudo:recursion-truncated 的建议句式同构(「事实 — 动作 A or 动作 B」): - 抬预算:package.json#nudo.analysis.callSiteBudget(1–64); - 固化精确见证:@nudo:case(limitations §3.2.2 同款口径——递归函数的 精确见证用指令固化,不要依赖 call@:预算只保住前 N 个调用点)。const SYMBOLIC_BUDGET_NOTE
SymbolInfotype—SymbolInfo = { name: string; kind: "function" | "variable" | "class" | "parameter"; loc: SourceLocation; uri?: string; }
SymbolTabletype—SymbolTable = { definitions: Map<string, SymbolInfo>; references: ReferenceInfo[]; }
targetPathErrorfn「分析目标」闸门(与 CLI resolveTargetsCollect 的文件分支同口径): 侧车契约模块(*.nudo.js / *.nudo.draft.*)、类型声明(.d.ts)、 JSX(.jsx / .tsx)不是分析目标——把它们送进分析器会得到 「0 个函数 ⇒ 0 error ⇒ 判绿」的假绿(或把契约 DSL 构造器当成真实 调用点报成 case)。targetPathError(path: string): PathError | undefined
TestReporttype—TestReport = { file: string; passed: number; failed: number; unchecked: number; outcomes: CaseTestOutcome[]; caseLines: string[]; }
TestReportOptionstype—TestReportOptions = { entryContractNotes?: ReadonlySet<string>; }
TextEdittype—TextEdit = { startLine: number; startCol: number; endLine: number; endCol: number; newText: string; }
topoSortDirtyfnTopological order with dependencies before dependents (only imports edges internal to dirty; cycles tolerated — remaining files appended in arbitrary order).topoSortDirty(imports: Map<string, Set<string>>, dirty: string[]): string[]
trimAnalysisFileCachefn立刻压到当前 maxFiles(调低上限时收内存)trimAnalysisFileCache(): void
trimEvalCachefn立刻压到当前 maxEvalRuns(调低上限时收内存)trimEvalCache(): void
trimFnAnalysisCachefn立刻压到当前 maxFns(调低上限时收内存)trimFnAnalysisCache(): void
tryEvalCallfn求值引擎求值具名导出(仅成功结果)tryEvalCall( source: string, filePath: string, fnName: string, args: Abs[], opts: { envNames?: string[]; mocks?: Record<string, Abs>; phi?: Phi; loadModule?: LoadModule; depKey?: string | null; keepNeverThrows?: boolean; } = {}, ): Abs | undefined
tryEvalCallFullfn求值引擎求值具名导出(结果 + throws);opts.collectCalls 时附带调用点记录。tryEvalCallFull( source: string, filePath: string, fnName: string, args: Abs[], opts: { collectCalls?: boolean; collectMemberDiags?: boolean; envNames?: string[]; mocks?: Record<string, Abs>; phi?: Phi; thisArg?: Abs; loadModule?: LoadModule; depKey?: string | null; } = {}, )
tryRunEvalfn模块图 + runTranspiled(默认 analyze 模式)tryRunEval( source: string, filePath: string, opts: { maxLoopIters?: number; mode?: "exec" | "analyze"; envNames?: string[]; mocks?: Record<string, Abs>; lenientGlobals?: boolean; loadModule?: LoadModule; depKey?: string | null; composed?: ComposedEvalModules; fresh?: boolean; } = {}, ): EvalRunResult | undefined
TypeBindingtype—TypeBinding = { name: string; type: string }
typeExprToDirectivefnagent 面类型表达式 → @nudo:as 文法(认不出的表达式落到 unknown)typeExprToDirective(expr: string): string
unifiedDifffn—unifiedDiff(a: string, b: string, path: string): string
writeContractDraftfn写入 *.nudo.draft.js(覆盖草稿文件本身;不碰正式 *.nudo.js)。writeContractDraft( filePath: string, draftSource: string, opts: { dryRun?: boolean; projectDir?: string; entries?: ReadonlyArray<Pick<ContractDraftEntry, "dsl" | "skipped">>; draftable?: boolean; } = {}, ): WriteDraftResult
WriteDraftResulttype—WriteDraftResult = { draftPath: string; written: boolean; changed: boolean; draftable: boolean; draftSource: string; skipped?: "hand-edit...
writeFileAtomicfntmp + rename 原子写(同目录 temp ⇒ 崩溃/磁盘满时目标要么旧要么新,不会 半截)。随机后缀用 randomBytes(不是 Math.random/Date.now):防可 预测 tmp 路径被预置符号链接劫持。writeFileAtomic(path: string, data: string): void
ZodModuleProjectiontype—ZodModuleProjection = { source: string; dialect: SchemaDialect; dropped: string[]; }