@botfather/units

中文文档
2.0.1发布于 2026/06/23MITTypeScriptES Module零依赖构建来源已验证近 30 天下载 1919

Lightweight DSL for building interactive UIs.

原始使用文档
文档目录17 节
  1. What is it?
  2. Installation
  3. The .ui syntax
  4. API
  5. Parsing
  6. Formatting
  7. React renderer
  8. Custom (non-React) renderer
  9. Expression evaluator
  10. Incremental parsing
  11. Tree IR adapters
  12. Transform programs
  13. Reward + verifier
  14. Verified library + synthesis
  15. TypeScript types for Vite imports
  16. Package exports
  17. License

@botfather/units

The core library for the Units DSL — a lightweight, dependency-free declarative language for describing UI trees in .ui files.

What is it?

Units provides a minimal syntax for authoring UIs that is significantly terser than JSX, making it well-suited for code generation (e.g. LLM output) and human editing alike. A .ui file is parsed into a plain JSON AST, which can then be rendered by the included React renderer or any custom host framework via the custom renderer API.

Key characteristics:

  • O(n) single-pass parser — no external parsing dependencies
  • Render-agnostic — React is opt-in; plug in any framework
  • Canonical formatter for consistent diffs
  • Incremental parsing helpers for editor integrations

Installation

npm install @botfather/units
# react is a peer dependency for the React renderer
npm install react

The .ui syntax

TagName (prop:'value', expr=@scopeVar, visible?=@bool) {
  text 'Literal @{interpolated}'
  @rawExpr
  #if (@cond) { ... }
  #for (item, i in @list) {
    #key (@item.id)
    ChildTag (...)
  }
  #slot (slotName)
}
SyntaxMeaning
Tag (props) { children }Element node
key:'string' / key:123 / key:trueStatic prop value
key=@exprDynamic expression prop
key?=@exprConditional boolean prop (only set when truthy)
!click { handler(@event) }Event handler shorthand
on:click={ handler(@event) }Event handler long form
text 'literal'Text node (supports @{...} interpolation)
@exprInline expression node
#if (@cond) { }Conditional directive
#for (item, i in @list) { }Loop with index
#for item in @list { }Compact loop
#slot (name)Named slot
#key (@expr)Key directive for the next tag
// commentLine comment

API

Parsing

import { parseUnits } from "@botfather/units/parser";

const ast = parseUnits(`
  Button (variant:'primary') {
    text 'Click me'
  }
`);
// → { type: 'document', body: [...] }

Throws a descriptive error with source offset and snippet on syntax errors.

Formatting

import { formatUnits } from "@botfather/units/print";

const canonical = formatUnits(source);

Line width defaults to 100. Override with the UNITS_PRINT_WIDTH environment variable.

React renderer

import { renderUnits } from "@botfather/units/runtime";
import uiAst from "./app.ui"; // via vite-plugin-units

const element = renderUnits(uiAst, scope, {
  components: { Button: MyButtonComponent },
  slots: { default: <span>content</span> },
  set: (key, value) => setState(s => ({ ...s, [key]: value })),
});
OptionTypeDescription
componentsRecord<string, Component>Tag name → React component mapping
slotsRecord<string, ReactNode | fn>Named slot content
set(key, value) => voidMutation handler for set() expressions
evalExpr(expr, scope) => anyCustom expression evaluator

Custom (non-React) renderer

import { createUnitsRenderer } from "@botfather/units/custom-renderer";

const renderer = createUnitsRenderer({
  element(name, props, events, children) { /* create node */ },
  text(value) { /* create text node */ },
  fragment(children) { /* group children */ },
});

const node = renderer.render(ast, scope, options);

Custom renderer directive behavior mirrors runtime semantics for #if/#elif/#else and #for/#key.

Expression evaluator

import { createUnitsEvaluator } from "@botfather/units/runtime";

const evalExpr = createUnitsEvaluator();
const result = evalExpr("@items.length > 0", scope);

Expressions use @ as the scope accessor prefix. The evaluator caches compiled Function objects per expression string, and scope-prefix normalization preserves literal @ characters inside quoted strings.

Incremental parsing

import {
  findChangedRange,
  findSmallestEnclosingNode,
  incrementalParse,
} from "@botfather/units/incremental";

const range = findChangedRange(prevSource, nextSource);
const node = findSmallestEnclosingNode(ast, range.start, range.endPrev);
const newAst = incrementalParse(prevAst, prevSource, nextSource);

Useful for editor integrations. incrementalParse attempts append-only and smallest-enclosing-node reparses first, then safely falls back to a full re-parse when needed.

Tree IR adapters

import {
  normalizeDomTree,
  normalizeA11yTree,
  serializeAgentTree,
} from "@botfather/units/tree-ir";

const domIr = normalizeDomTree(rawDomLikeTree);
const a11yIr = normalizeA11yTree(rawAccessibilityTree);
const compact = serializeAgentTree(domIr);

serializeAgentTree applies token-oriented defaults (dedupes redundant name/text pairs, omits role-implicit actions like click on buttons, prunes empty text leaves, and omits text-node ids). Pass options such as includeRedundantNameText: true, includeImplicitActions: true, or includeTextIds: true to keep those fields.

Transform programs

import {
  compileTransformProgram,
  runTransformProgram,
} from "@botfather/units/transform";

const program = compileTransformProgram(programSource);
const result = runTransformProgram(program, irTree, { task: "summarize" });

Transform programs use .ui syntax with a Program (kind:'transform') root and reserved transform tags (Rule, Filter, Merge, Pass) in transform mode.

Reward + verifier

import { scoreProgram, verifyProgram } from "@botfather/units/reward";

const score = scoreProgram({ inputTree, outputTree, expectations });
const verification = verifyProgram(score, {
  action_recall: 1,
  name_recall: 0.98,
  text_f1: 0.95,
});

Verified library + synthesis

import {
  createVerifiedProgramMetadata,
  writeVerifiedProgram,
} from "@botfather/units/library";
import { runSynthesisLoop } from "@botfather/units/synthesis";

TypeScript types for Vite imports

Add /// <reference types="@botfather/units/ui" /> (or import from @botfather/units/ui) to get types for .ui file imports:

import { ast, source } from "./app.ui";
import formatted from "./app.ui?format";
import tokens from "./app.ui?tokens";
import html from "./app.ui?highlight";

Package exports

Export pathDescription
@botfather/unitsRe-exports everything
@botfather/units/parserparseUnits
@botfather/units/printformatUnits
@botfather/units/runtimerenderUnits, createUnitsEvaluator
@botfather/units/custom-renderercreateUnitsRenderer
@botfather/units/incrementalIncremental parse helpers
@botfather/units/tree-irDOM/AX normalization + compact serialization
@botfather/units/transformTransform program compiler + runtime
@botfather/units/rewardReward scoring + verifier gates
@botfather/units/libraryVerified program library helpers
@botfather/units/synthesisIterative synthesis loop helpers
@botfather/units/uiType declarations for .ui file imports

License

MIT

版本与发布记录

@botfather/units 共发布 3 个版本,首次发布于 2026/03/02;过去 12 个月发布了 3 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
2.0.1latest2026/06/234 个月前
2.0.02026/03/028 个月前
1.0.02026/03/028 个月前

关于 @botfather/units 的常见问题

@botfather/units 是什么?

Lightweight DSL for building interactive UIs.

如何安装 @botfather/units?

在项目目录运行 npm install @botfather/units,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:react(>=18)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@botfather/units 支持 TypeScript 吗?

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

@botfather/units 支持 ESM 还是 CommonJS?

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

@botfather/units 可以商用吗?

@botfather/units 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@botfather/units 的下载量有多少?

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

@botfather/units 还在维护吗?

最新版本 2.0.1 发布于 2026/06/23(4 个月前);至今共发布 3 个版本,其中过去 12 个月发布了 3 个;首次发布于 2026/03/02。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。