Skip to main content

@nudojs/harvester

API reference for the Nudo declaration harvester. @nudojs/harvester converts TypeScript .d.ts declarations into Nudo env definitions — TypeScript source that rebuilds those types with Abs constructors from @nudojs/core.

It is an env-package / analysis library, not a product CLI verb. Use it when authoring @nudojs/env faces or programmatically generating a path-based /// @nudo:env module. Everyday analysis auto-fills @types through @nudojs/service without calling this package directly.

Public API​

The package exports two functions and one type from src/index.ts.

harvestDts​

harvestDts(files: string[], opts?: { maxFileBytes?: number; maxMs?: number }): HarvestedEnv

Reads the given .d.ts file paths from disk and parses them with the TypeScript compiler in two phases. opts.maxFileBytes (default 1_500_000) skips oversized files; opts.maxMs sets a deadline after which excess files count as skipped.

  1. Collect — walk every module/global declaration (declare module "...", namespaces, interfaces, classes, type aliases, function overloads, export = / export * from re-exports) into a shared symbol table.
  2. Materialize — convert the collected symbols into Abs values (see core). Because materialization runs only after the whole symbol table is populated, cross-file references resolve regardless of file order.

The result mirrors core's EnvDefinition shape ({ globals, modules }), so the emitted env plugs directly into the /// @nudo:env loading path.

type HarvestedEnv = {
globals: Record<string, Abs>;
modules: Record<string, Record<string, Abs>>;
stats: { files: number; symbols: number; skipped: number };
};
  • globals — symbols declared in the global scope (e.g. Buffer, process from @types/node)
  • modules — per-module records, keyed by both bare and prefixed names ("path" and "node:path" for the same record)
  • stats — counters for tooling: files parsed, symbols emitted, declarations skipped (unsupported syntax)

Example:

import { harvestDts } from "@nudojs/harvester";

const env = harvestDts(["node_modules/@types/node/fs.d.ts"]);
env.stats; // { files: 1, symbols: …, skipped: … }

emitEnvModule​

emitEnvModule(env: HarvestedEnv, pkgName: string): string

Renders a HarvestedEnv as importable TypeScript source exporting a single defineEnv() function:

import { emitEnvModule } from "@nudojs/harvester";

const code = emitEnvModule(env, "@types/node");

The emitted file follows this shape (module records shared under several keys — e.g. "path" aliasing "node:path" — are emitted once as a const and referenced from every key):

// Auto-generated by @nudojs/harvester — DO NOT EDIT
// Source package: @types/node
import { num, str, bool, never as absNever, unknown as absUnknown, numLit, strLit, boolLit, objOf, relationFn, abs as makeAbs } from "@nudojs/core";

export function defineEnv() {
const mod0: Record<string, unknown> = {
// …per-module symbols…
};

return {
globals: {
// …global symbols…
},
modules: {
path: mod0,
"node:path": mod0,
},
};
}

Individual symbols use the Abs constructors — e.g. these entries harvested from @types/node:

platform: relationFn([], makeAbs({ k: "sum", members: [strLit("aix"), strLit("android"), strLit("darwin"), /* … */ strLit("netbsd")] }, undefined, undefined, "exact"), { conf: "exact" }),
join: relationFn([makeAbs({ k: "arr", element: str() }, undefined, undefined, "exact")], str(), { conf: "exact" }),

Using the Harvested Env​

Add the generated file to your JavaScript source with a path-based /// @nudo:env directive (distinct from the named environments es / web / node documented in Directives):

/// @nudo:env nudo-harvest-node.ts
import { join } from "node:path";

export function buildKey(dir, name) {
const p = join(dir, name);
return p + ".md";
}

const key = buildKey("docs", "readme");

Running nudo test on this file shows the harvested signature of join flowing through the call site:

=== buildKey ===

call@L9 ("docs", "readme") => `${string}.md`

Path-based env files are loaded via dynamic import, so asynchronous consumers (nudo check/nudo test, analyzeFileAsync, the LSP validation path) preload them; the synchronous analyzeFile degrades when a file declares one. Async tooling should prefer analyzeFileAsync.

Automatic harvest path (three states)​

When analysis meets a bare import (import x from "commander"), Nudo does not invent types. The auto path follows three states:

Import targetWhat happensProduct path
JS source package ships usable .js/.mjs (e.g. commander, ms, debug)Analysis executes the source through the Abs evaluator / checkSourcenudo check / nudo test / LSP — no handwritten mock required for the zero-FP precision gate
Types package — @types/* installed or the package ships .d.tsDeclarations are harvested (harvestPackage / harvestNodeTypes / bareSpecToAbsModules → env modules)Analysis auto-fill via module-graph harvest; handwritten @nudojs/env stays primary for builtins
Neither JS analysis path nor typesAuto path yields empty modulesUse @nudo:mock, a path-based /// @nudo:env, or a sidecar hint — see the mock boundary below

Library helper vs production injection. autoHarvestModules (exported from @nudojs/harvester) is the programmatic harvest helper used by tools/tests. Production analysis injection goes through evalAbsModuleGraph → bareSpecToAbsModules (harvest-to-abs.ts), then mergeHarvestUnderEnv so handwritten @nudojs/env wins on overlap. There is not a second analysis path.

barePackageName("lodash/fp") → lodash; relative / absolute / node: specifiers are never harvest targets (builtins use handwritten env).

Performance budgets (@types/node)​

harvestNodeTypes in @nudojs/harvester is budgeted so IDE startup is not dragged down by huge .d.ts graphs:

BudgetDefaultNotes
maxFiles12Entry-priority collect under node_modules/@types/node
maxMs2500Passed to harvestDts; excess files count as stats.skipped
disableNUDO_HARVEST_NODE=offReturns { ok: false, reason: "disabled" } — explicit, not silent

Results are cached in-process and on disk (HarvestJson under ~/.cache/nudo/deps / NUDO_DEPS_CACHE_DIR) — success and terminal outcomes keyed by package root + dts content hash + budgets. disabled (NUDO_HARVEST_NODE=off) is never cached. Call clearNodeHarvestCache() after @types/node changes in watch/test paths. On harvest miss/fail the loader degrades to handwritten @nudojs/env node face (degraded: true). Handwritten @nudojs/env wins over harvest on overlapping module keys and export names — analysis injects via mergeHarvestUnderEnv in @nudojs/service (harvest only fills missing slots). Do not treat harvest output as the type-system source of truth.

Coverage baseline (resolved / leaf-clean / unknown / mock-required) is generated by pnpm run coverage:env → docs/reports/env-coverage-baseline.{json,md}. Resolution rate — and even leaf-clean ratio — is not a soundness claim.

Mock boundary (honest)​

Still recommended for handwritten mock (aligned with docs/design/limitations.md §2 call-site ceiling):

  • Native bindings (child_process.spawn, native addons) — env may hold a signature, not side effects
  • Dynamic require / computed module graphs (literal / constant-folded specs resolve; the rest stay honest unknown)
  • Stream machine callbacks (Node Transform internals driven by the runtime)
  • Dual-entry browser/node variants — call-site records do not cross files
  • Functions with no call-site usage — entry@ fallback is an honest observation with unconstrained any params; entry may-throw on that surface is still L2 (nudo:entry-may-throw), not a free pass.

See also Language Semantics — mock boundary.

Export inventory​

Generated by node scripts/gen-api-docs.mjs from package export surfaces (PUBLIC_API.md / src/index.ts) — do not edit this block (or regenerate via pnpm run docs:gen). Summaries quote the source JSDoc first sentence as-is — CJK text means the symbol's doc is not yet English, and — means no JSDoc at all. Each row's name carries a stable anchor #slug (the lowercased symbol name).

NameKindSummarySignature
absToHarvestSigfnAbs → 签名投影(丢 pred/conf;fn 只留参数名+类型面;保留泛型 α 与 lit term)absToHarvestSig(a: Abs): HarvestSig
autoHarvestModulesfn自动 harvest 源码中全部裸包(有 @types 或包内 dts 时)。autoHarvestModules( source: string, fromDir: string, ): Record
barePackageNamefn裸说明符 → 包名(含 scope);相对/绝对/node: 与裸 Node 内建返回 undefinedbarePackageName(spec: string): string | undefined
bareSpecToAbsModulesfn裸说明符 → Abs 导出表(走 harvest 缓存)bareSpecToAbsModules( spec: string, fromFile: string, ): AbsModuleExports | undefined
clearHarvestCachefn—clearHarvestCache(): void
clearNodeHarvestCachefnClear the in-process @types/node harvest cache.clearNodeHarvestCache(): void
collectBarePackagesfn—collectBarePackages(source: string): string[]
collectDtsFromEntryfn从入口 .d.ts 沿 reference path / 相对 import 做 BFS 收集。collectDtsFromEntry(entry: string, maxFiles = 200): string[]
depsCacheRootfn依赖包层缓存根(跨项目);off/0 关闭depsCacheRoot(): string | undefined
dtsClosureHashfndts 闭包内容哈希(覆盖每个实际读到的文件,不只入口);读故障语义见 dtsClosureHashDetaileddtsClosureHash(files: string[]): string
DtsContractDrafttype—DtsContractDraft = { label: string; files: string[]; exports: DtsExportDraft[]; draftSource: string; stats: { files: number; exports: num...
DtsExportDrafttype—DtsExportDraft = { name: string; dsl?: string; note?: string; kind: "function" | "value" | "class" | "other"; partial?: boolean; }
dtsPathToContractDraftfn目录/文件入口:内部解析 .d.ts 列表。dtsPathToContractDraft( path: string, label?: string, ): DtsContractDraft
dtsToContractDraftfn从 .d.ts 路径列表生成契约草稿(不写盘)。dtsToContractDraft( dtsFiles: string[], label?: string, opts?: { acceptTarget?: string }, ): DtsContractDraft
emitEnvModulefn—emitEnvModule(env: HarvestedEnv, pkgName: string): string
formatDtsContractDraftfn组装 @nudo:draft 模块(与 formatDraftModule 同纪律:不 ambient 绑定)。formatDtsContractDraft( label: string, files: string[], exports: DtsExportDraft[], acceptTarget?: string, ): string
formatHarvestSummaryfnharvest 结果 → 人类可读导出表formatHarvestSummary(h: PackageHarvest): string
getHarvestCacheSizefn测试/诊断:当前条目数(≤ HARVEST_CACHE_MAX)getHarvestCacheSize(): number
getNodeHarvestCacheSizefnNumber of cached harvest results (diagnostics / tests).getNodeHarvestCacheSize(): number
handwrittenNodeEnvfn手写 @nudojs/env node 面(B2 降级链):harvest 未命中/失败时仍给出 可分析的 Node API 声明;与 harvest 重叠处由 mergeHarvestUnderEnv 让手写 wins。handwrittenNodeEnv(): HarvestedEnv | null
HARVEST_NODE_DEFAULT_MAX_FILESconstIDE-startup budgets for @types/node harvest.const HARVEST_NODE_DEFAULT_MAX_FILES
HARVEST_NODE_DEFAULT_MAX_MSconst—const HARVEST_NODE_DEFAULT_MAX_MS
harvestCacheKeyfnL2 键:pkg + version + knobs + dtsClosureHash(相对化;content-addressable)harvestCacheKey( pkg: string, meta: { dtsHash: string; maxFiles: number; pkgVersion?: string }, ): string
harvestDtsfn—harvestDts( files: string[], opts?: { maxFileBytes?: number; maxMs?: number }, ): HarvestedEnv
HarvestedEnvtypeHarvested env:Abs 原生(与 EnvDefinition 同形)。HarvestedEnv = { globals: Record<string, Abs>; modules: Record<string, Record<string, Abs>>; stats: { files: number; symbols: number; ski...
harvestedValueToAbsfn单个 Abs 导出 → 可调用 mock(fn 槽按 relation α 替换,或返回声明返回类型)harvestedValueToAbs(a: Abs): Abs
HarvestJsontype—HarvestJson = { v: 1; pkg: string; pkgVersion?: string; knobs: { maxFiles: number; abi: string }; dtsHash: string; modules: Record<string...
HarvestNodeStatstype—HarvestNodeStats = { files: number; symbols: number; skipped: number; degraded?: number; }
harvestNodeTypesfnharvest @types/node(限制文件数 + 时间预算,避免拖垮启动)。harvestNodeTypes( fromDir?: string, maxFiles: number = HARVEST_NODE_DEFAULT_MAX_FILES, maxMs: number = HARVEST_NODE_DEFAULT_MAX_MS, ): NodeEnvResult
harvestPackagefnharvest 一个 npm 包(或 @types 包)harvestPackage( pkg: string, fromDir?: string, maxFiles = 24, ): PackageHarvest
harvestPackageCachedfn—harvestPackageCached(pkg: string, fromDir: string): PackageHarvest | null
harvestPackageWithDiskfnL2 + L0:磁盘优先(跳过 harvestDts 解析),miss 再 harvest 并写盘。harvestPackageWithDisk( pkg: string, fromDir: string, maxFiles = 24, ): PackageHarvest | null
HarvestSigtype签名投影节点(可 JSON 化;足够 mock Abs 的 shape 面)。HarvestSig = | { k: "prim"; type: string } | { k: "unknown" } | { k: "any" } | { k: "never" } | { k: "lit"; value: number | string | bool...
harvestSigToAbsfn签名投影 → mock Abs(conf 合 mock)harvestSigToAbs(sig: HarvestSig): Abs
isHarvestNodeDisabledfn—isHarvestNodeDisabled(env: NodeJS.ProcessEnv = process.env): boolean
lookupHarvestedfn取某个导出的展示串(formatShape)lookupHarvested( h: PackageHarvest, moduleName: string, exportName: string, ): string | undefined
materializeHarvestJsonfnHarvestJson → mock Abs 导出表(materialize);损坏/版本不符 → nullmaterializeHarvestJson(j: unknown): HarvestedEnv | null
NodeEnvResulttype—NodeEnvResult = | { ok: true; env: HarvestedEnv; root: string; files: number; stats: HarvestNodeStats; cached: boolean; degraded?: boolea...
PackageHarvesttype—PackageHarvest = { pkg: string; root: string; dtsFiles: string[]; env: HarvestedEnv; }
packageHarvestToAbsModulesfn把 harvest 的 modules/globals 合成 AbsModuleExports。packageHarvestToAbsModules( pkg: string, h: PackageHarvest, ): Record<string, AbsModuleExports>
readHarvestDiskfn—readHarvestDisk(root: string, key: string): HarvestJson | undefined
resolvePackageRootfn在 node_modules 中解析包根(含 @types/*)。resolvePackageRoot( pkg: string, fromDir: string = process.cwd(), ): string | undefined
serializeHarvestJsonfn—serializeHarvestJson( pkg: string, env: HarvestedEnv, meta: { dtsHash: string; maxFiles: number; pkgVersion?: string }, ): HarvestJson
writeHarvestDiskfn—writeHarvestDisk(root: string, key: string, value: HarvestJson): void