# @agentuity/schema 中文文档

规范地址：https://npmcn.com/package/%40agentuity/schema/

版本：3\.1\.18
npm 元数据更新时间：2026-08-01T00:43:33.272Z
中文译文更新时间：2026-11-08T14:40:19.384Z
软件包许可：Apache-2\.0

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

原始 npm 页面：https://www.npmjs.com/package/%40agentuity/schema
原文对照：https://npmcn.com/package/%40agentuity/schema/?lang=original
源码仓库：https://github.com/agentuity/sdk

弃用说明：Use a standard schema library like Zod or Valibot directly\. @agentuity/schema will be removed in a future release\.

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

- 包体积（解压后）：252 kB，108 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- 运行依赖：1 个
- 首次发布：2025-12-04T05:25:25.439Z
- 最新版本发布：2026-08-01T00:43:33.104Z
- 近 30 天下载量：1780（2026-10-05 至 2026-11-03，npm 官方下载统计）
- 已发布版本数：233（近 12 个月 233 个）

## 中文简介

暂无中文简介

## 安装

```sh
npm install @agentuity/schema
```

也可以使用：`pnpm add @agentuity/schema`、`yarn add @agentuity/schema`、`bun add @agentuity/schema`

## README

# @ agentuity/schema (英语)

用于Agentuity平台的轻量级,型式安全的Schema验证库. 支持 [标准计划](https://standardschema.dev/) 规格.

## 特征

-   QQ 类型安全计划验证
-   零运行时间依赖的轻量级
-   符合标准Schema v1
-   在浏览器和服务器环境中工作(Node.js, Bun)
-   简单而流利的API

## 安装

```bash
bun add @agentuity/schema
```

## 使用量

```typescript
import { s, ValidationError } from '@agentuity/schema';

// Define a schema
const userSchema = s.object({
    name: s.string(),
    age: s.number(),
    email: s.string(),
    isActive: s.boolean(),
});

// Extract the inferred type (like zod's z.infer)
type User = s.infer<typeof userSchema>;

// Parse with validation (throws on error)
try {
    const user: User = userSchema.parse({
        name: 'John',
        age: 30,
        email: 'john@example.com',
        isActive: true,
    });
    console.log('Valid user:', user);
} catch (error) {
    if (error instanceof ValidationError) {
        console.error('Validation failed:', error.message);
        console.error('Issues:', error.issues);
    }
}

// Safe parse (returns result object)
const result = userSchema.safeParse(data);
if (result.success) {
    console.log('Valid data:', result.data);
} else {
    console.error('Validation failed:', result.error.message);
}

// Optional and nullable
const optionalSchema = s.object({
    name: s.string(),
    nickname: s.optional(s.string()),
    age: s.nullable(s.number()),
});

// Arrays
const stringArraySchema = s.array(s.string());
const userArraySchema = s.array(userSchema);

// Unions
const statusSchema = s.union(s.literal('active'), s.literal('inactive'), s.literal('pending'));

// Enums (shorthand for union of literals)
const roleSchema = s.enum(['admin', 'user', 'guest']);
const prioritySchema = s.enum([1, 2, 3, 4, 5]);

// Literal values
const roleSchema = s.literal('admin');
```

## API 密码

### 基本类型

-   `s.string()` - 字符串验证
-   `s.number()` - 数量验证
-   `s.boolean()` - 布尔验证
-   `s.null()` - 无效验证
-   `s.undefined()` - 未定义的验证

### 复杂类型

-   `s.object(shape)` - 有打字属性的物件验证
-   `s.array(schema)` - 有输入元素的矩阵验证

### 工具类型

-   `s.optional(schema)` - 做一个可以选择的策略
-   `s.nullable(schema)` - 使计划无效
-   `s.union(...schemas)` - 多种计划的联合
-   `s.literal(value)` - 精确值匹配
-   `s.enum([...values])` - Enum类型(文字结合)

```typescript
// Enum (shorthand for union of literals)
const roleSchema = s.enum(['admin', 'user', 'guest']);
const role = roleSchema.parse('admin'); // 'admin'

// Equivalent to:
const roleSchema2 = s.union(s.literal('admin'), s.literal('user'), s.literal('guest'));
```

### 胁迫

自动将值转换为正确的类型( 如 zod.coerce) :

-   `s.coerce.string()` - 强迫使用字符串 `String(value)`
-   `s.coerce.number()` - 强迫使用数字 `Number(value)`
-   `s.coerce.boolean()` - 强迫布尔使用 `Boolean(value)`
-   `s.coerce.date()` - 使用强迫至今 `new Date(value)`

```typescript
// Parse form data where everything is a string
const formSchema = s.object({
    name: s.string(),
    age: s.coerce.number(), // "30" → 30
    newsletter: s.coerce.boolean(), // "on" → true
    createdAt: s.coerce.date(), // "2025-01-01" → Date
});

const formData = formSchema.parse({
    name: 'John',
    age: '30', // String coerced to number
    newsletter: 'on', // String coerced to boolean
    createdAt: '2025-01-01', // String coerced to Date
});

// Query parameters (always strings)
const querySchema = s.object({
    page: s.coerce.number(),
    limit: s.coerce.number(),
});

const params = querySchema.parse({
    page: '1', // "1" → 1
    limit: '20', // "20" → 20
});
```

### 文档

所有计划都支持a `.describe(description: string)` 添加文档的方法:

```typescript
const userSchema = s
    .object({
        id: s.string().describe('The unique identifier'),
        name: s.string().describe('The user full name'),
        age: s.number().describe('Age in years'),
    })
    .describe('User profile');
```

### JSON Schema 转换

将计划转换为 JSON Schema 格式 :

```typescript
const schema = s.object({
    name: s.string().describe('User name'),
    age: s.number().describe('User age'),
});

const jsonSchema = s.toJSONSchema(schema);
// {
//   "type": "object",
//   "properties": {
//     "name": { "type": "string", "description": "User name" },
//     "age": { "type": "number", "description": "User age" }
//   },
//   "required": ["name", "age"]
// }
```

将 JSON Schema 转换为计划 :

```typescript
const jsonSchema = {
    type: 'object',
    properties: {
        firstName: {
            type: 'string',
            description: 'First name',
        },
        lastName: {
            type: 'string',
            description: 'Last name',
        },
        age: {
            type: 'number',
            description: 'Age',
        },
        hobbies: {
            type: 'array',
            items: { type: 'string' },
        },
    },
    required: ['firstName', 'lastName', 'age', 'hobbies'],
};

const schema = s.fromJSONSchema(jsonSchema);
// Now you can use schema for validation
const result = schema['~standard'].validate(data);
```

支持圆通转换 :

```typescript
const original = s.object({ name: s.string() });
const json = s.toJSONSchema(original);
const reconstructed = s.fromJSONSchema(json);
// reconstructed works exactly like original
```

### 分析与验证

#### `.parse(value)` - 抛出验证错误

```typescript
try {
    const user = userSchema.parse(data);
    // user is typed and validated
} catch (error) {
    if (error instanceof ValidationError) {
        console.error(error.message); // Human-readable error
        console.error(error.issues); // Detailed issue array with paths
    }
}
```

#### `.safeParse(value)` - 返回结果对象

```typescript
const result = userSchema.safeParse(data);

if (result.success) {
    console.log(result.data); // Typed data
} else {
    console.error(result.error); // ValidationError instance
}
```

### 类型推论

使用 `s.infer` 从图中提取类型( 如 Zod ) `z.infer`:

```typescript
import { s } from '@agentuity/schema';

const Player = s.object({
    username: s.string(),
    xp: s.number(),
    inventory: s.array(s.string()),
});

// Extract the inferred type (like zod's z.infer)
type Player = s.infer<typeof Player>;
// { username: string; xp: number; inventory: string[] }

const player: Player = Player.parse(data);
```

您也可以导入 `Infer` 如果选中的话, 直接键入 :

```typescript
import { s, type Infer } from '@agentuity/schema';

type Player = Infer<typeof Player>; // Alternative syntax
```

### 处理错误

校验错误结构化, 包括失败字段的路径 :

```typescript
const profileSchema = s.object({
    user: s.object({
        name: s.string(),
        age: s.number(),
    }),
});

try {
    profileSchema.parse({ user: { name: 'John', age: 'thirty' } });
} catch (error) {
    if (error instanceof ValidationError) {
        console.log(error.message);
        // "[user.age]: Expected number, got string"

        console.log(error.issues);
        // [{ message: "Expected number, got string", path: ["user", "age"] }]
    }
}
```

## 标准计划支持

所有计划执行标准Schema v1接口:

```typescript
interface StandardSchemaV1<Input, Output> {
    readonly '~standard': {
        readonly version: 1;
        readonly vendor: string;
        readonly validate: (value: unknown) => Result<Output>;
        readonly types?: { input: Input; output: Output };
    };
}
```

## 许可证

阿帕奇 - 2.0

## 常见问题

### 如何安装 @agentuity/schema？

在项目目录运行 npm install @agentuity/schema，或使用 pnpm add / yarn add / bun add。

### @agentuity/schema 支持 TypeScript 吗？

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

### @agentuity/schema 支持 ESM 还是 CommonJS？

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

### @agentuity/schema 可以商用吗？

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

### @agentuity/schema 的下载量有多少？

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

### @agentuity/schema 还在维护吗？

最新版本 3\.1\.18 发布于 2026/08/01（3 个月前）；至今共发布 233 个版本，其中过去 12 个月发布了 233 个；首次发布于 2025/12/04。作者已将其标记为弃用，新项目建议寻找替代方案。

