# @brightsy/client 中文文档

规范地址：https://npmcn.com/package/%40brightsy/client/

版本：1\.0\.34
npm 元数据更新时间：2026-10-26T01:01:37.404Z
中文译文更新时间：2026-11-08T15:47:21.549Z
软件包许可：MIT

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

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

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

- 包体积（解压后）：891 kB，81 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- 运行依赖：2 个
- 首次发布：2025-12-02T17:22:50.459Z
- 最新版本发布：2026-10-26T01:01:37.167Z
- 近 30 天下载量：1850（2026-10-09 至 2026-11-07，npm 官方下载统计）
- 已发布版本数：19（近 12 个月 19 个）

## 中文简介

布莱特西CMS和代理公司的统一客户端 SDK

## 安装

```sh
npm install @brightsy/client
```

也可以使用：`pnpm add @brightsy/client`、`yarn add @brightsy/client`、`bun add @brightsy/client`

## README

# 亮度客户端

Brightsy API的官方TypeScript/JavaScript客户端.

## 安装

```bash
npm install @brightsy/client
```

## 快速启动

```typescript
import { BrightsyClient } from '@brightsy/client';

const client = new BrightsyClient({
  api_key: 'bsy_your_api_key',
  account_id: 'your_account_id',
  endpoint: 'https://brightsy.ai' // optional
});
```

## API 参考

### 内容管理

#### CMA - 内容管理 API

包含完整 CRUD 操作的访问草稿内容 :

```typescript
// List records
const posts = await client.cma()
  .recordType('blog-post')
  .where('status', 'eq', 'draft')
  .pageSize(10)
  .get();

// Create a record
const newPost = await client.cma()
  .recordType('blog-post')
  .create({
    title: 'My Post',
    content: '...'
  });

// Update a record
await client.cma()
  .recordType('blog-post')
  .id('record-id')
  .update({ title: 'Updated Title' });

// Delete a record
await client.cma()
  .recordType('blog-post')
  .id('record-id')
  .delete();
```

#### CDA - 内容交付 API

访问已发布的内容( 只读) :

```typescript
const posts = await client.cda()
  .recordType('blog-post')
  .where('published', 'eq', true)
  .get();
```

#### CPA - 内容预览 API

访问草稿内容( 只读) :

```typescript
const drafts = await client.cpa()
  .recordType('blog-post')
  .get();
```

### 探员

管理和与AI代理交互:

```typescript
// List agents
const agents = await client.agents().list({ search: 'customer' });

// Create an agent
const agent = await client.agents().create({
  name: 'Customer Support',
  description: 'Handles customer inquiries',
  system_instruction: '...'
});

// Get agent details
const agent = await client.agents().get('agent-id');

// Update an agent
await client.agents().update('agent-id', {
  name: 'Updated Name'
});

// Delete an agent
await client.agents().delete('agent-id');

// Chat with an agent (execution)
const response = await client.agent('agent-id').chat({
  message: 'Hello!',
  chat_id: client.createChatId()
});
```

### 假设

管理自动化方案:

```typescript
// List scenarios
const scenarios = await client.scenarios().list();

// Create a scenario
const scenario = await client.scenarios().create({
  name: 'Welcome Email',
  description: '...',
  trigger_type: 'webhook',
  run_as_user_id: 'user-uuid' // Optional user context for webhook/signature runs
});

// Get, update, delete
await client.scenarios().get('scenario-id');
await client.scenarios().update('scenario-id', { run_as_user_id: 'user-uuid' });
await client.scenarios().delete('scenario-id');

// Trigger a scenario (legacy method)
await client.scenario('scenario-id').trigger({ data: '...' });
```

### 时间表

管理计划任务 :

```typescript
// List schedules
const schedules = await client.schedules().list();

// Create a schedule
const schedule = await client.schedules().create({
  name: 'Daily Backup',
  cron: '0 0 * * *',
  scenario_id: 'scenario-id'
});

// Get, update, delete
await client.schedules().get('schedule-id');
await client.schedules().update('schedule-id', { /* ... */ });
await client.schedules().delete('schedule-id');
```

### 网络呼号

管理事件 Webhoks :

```typescript
// List webhooks
const webhooks = await client.webhooks().list();

// Create a webhook
const webhook = await client.webhooks().create({
  name: 'Content Published',
  webhook_type: 'http',
  endpoint_url: 'https://example.com/webhook',
  triggers: {
    cms: {
      'blog-post': {
        publish: true
      }
    }
  }
});

// Get, update, delete
await client.webhooks().get('webhook-id');
await client.webhooks().update('webhook-id', { /* ... */ });
await client.webhooks().delete('webhook-id');

// Test a webhook
await client.webhooks().test('webhook-id');
```

### 应用程序

访问连接的应用程序/集成 :

```typescript
// List connected apps
const apps = await client.apps().list();

// Get app details
const app = await client.apps().get('app-id');
```

### 文件

管理账户存储中的文件和文件夹 :

```typescript
// List files
const files = await client.files().list({ 
  path: 'public/images',
  search: 'logo' 
});

// Create folder
await client.files().createFolder({
  path: 'public',
  folderName: 'images'
});

// Upload file
await client.files().upload({
  path: 'public',
  filename: 'image.jpg',
  file: fileBlob
});

// Get signed URL for private file
const { signedUrl } = await client.files().signedUrl({
  path: 'public/image.jpg',
  expiresIn: 3600
});

// Move/rename file
await client.files().move('old/path.jpg', 'new/path.jpg');

// Delete file
await client.files().delete('path/to/file.jpg');
```

### AI 图像

AI 驱动图像操作 :

```typescript
// Analyze an image
const analysis = await client.images().analyze({
  imageUrl: 'https://example.com/image.jpg',
  prompt: 'What objects are in this image?', // optional
  model: 'gemini_2_5_flash_preview_09_2025' // optional
});
console.log(analysis.data.response);

// Get improvement suggestions
const suggestions = await client.images().suggestEdits({
  imageUrl: 'https://example.com/image.jpg',
  model: 'gemini_2_5_flash_preview_09_2025' // optional
});
console.log(suggestions.data.suggestions);
// Returns structured suggestions with category, title, description, priority

// Generate a new image
const generation = await client.images().generate({
  prompt: 'A beautiful sunset over mountains',
  width: 1024,  // optional, default: 1024
  height: 768,  // optional, default: 768
  model: 'gemini_nano_banana_2_1' // optional; catalog key or OpenRouter id
});
console.log(generation.data.imageUrl);
```

**图像分析** 双子座2.5 用于图像的AI视觉分析的闪光. 您可以询问有关图像的具体问题或获得一般描述.

**图像建议** 返回关于改善图像的结构化建议,包括组成、颜色、亮度、技术和创造性建议.

**图像生成** 使用 Flux 1. 1 Pro 从文本提示创建新图像 。 生成的图像 URL 是临时的, 如果您需要坚持, 应该下载 .

```typescript
// List files
const files = await client.files().list({
  path: 'documents',
  search: 'invoice'
});

// Create a folder
await client.files().createFolder({
  path: 'documents',
  folderName: '2024'
});

// Option 1: Direct upload (convenience method)
const { fileUrl, path } = await client.files().upload({
  path: 'documents',
  filename: 'report.pdf',
  file: fileData // File, Blob, or Buffer
});

// Option 2: Manual two-step upload
const { uploadUrl, fileUrl } = await client.files().uploadUrl({
  path: 'documents',
  filename: 'report.pdf'
});

await fetch(uploadUrl, {
  method: 'PUT',
  body: fileData
});

// Get signed download URL
const { signedUrl } = await client.files().signedUrl({
  path: 'documents/report.pdf',
  expiresIn: 3600
});

// Delete a file
await client.files().delete('documents/report.pdf');

// Move/rename a file
await client.files().move('old-path.pdf', 'new-path.pdf');
```

### API 密钥

管理团队 API 密钥 :

```typescript
// List API keys
const keys = await client.apikeys().list();

// Create an API key
const newKey = await client.apikeys().create({
  name: 'Production Key',
  permissions: {
    cms: {
      'blog-post': {
        read: true,
        create: true
      }
    }
  }
});

// Get, update, delete
await client.apikeys().get('key-id');
await client.apikeys().update('key-id', { name: 'Updated' });
await client.apikeys().delete('key-id');

// Rotate an API key
const { key } = await client.apikeys().rotate('key-id');
```

## 高级使用

### 文件上传示例

#### 浏览器( 有文件输入)

```typescript
// From file input
const fileInput = document.getElementById('fileInput') as HTMLInputElement;
const file = fileInput.files[0];

const { fileUrl } = await client.files().upload({
  path: 'uploads',
  filename: file.name,
  file: file
});

console.log('File uploaded to:', fileUrl);
```

#### 节点.js(带有fs)

```typescript
import fs from 'fs';

const fileBuffer = fs.readFileSync('./report.pdf');

const { fileUrl } = await client.files().upload({
  path: 'documents',
  filename: 'report.pdf',
  file: fileBuffer
});
```

#### 带有 Blob/ ArrayBaffer 的文件

```typescript
const blob = new Blob(['Hello, world!'], { type: 'text/plain' });

const { fileUrl } = await client.files().upload({
  path: 'notes',
  filename: 'hello.txt',
  file: blob
});
```

### 过滤和铺放

```typescript
const results = await client.cma()
  .recordType('blog-post')
  .where('status', 'eq', 'published')
  .where('views', 'gt', 1000)
  .orderBy('created_at', 'desc')
  .page(1)
  .pageSize(20)
  .select('title', 'slug', 'created_at')
  .get();
```

### 处理错误

```typescript
try {
  const agent = await client.agents().get('invalid-id');
} catch (error) {
  console.error('Error:', error.message);
}
```

### 流程代理回复

```typescript
await client.agent('agent-id').chat({
  message: 'Tell me a story',
  stream: true,
  onChunk: (chunk) => {
    console.log(chunk);
  }
});
```

## 开发和测试

### 运行测试

```bash
# Run all unit tests
pnpm test

# Run tests in watch mode
pnpm test:watch

# Run API integration tests (with MSW mocks)
pnpm test:api

# Run E2E tests against REAL API
# Option 1: Use CLI login (recommended)
brightsy login  # Run once to authenticate
pnpm test:e2e

# Option 2: Use environment variables
BRIGHTSY_API_KEY=bsy_xxx BRIGHTSY_ACCOUNT_ID=xxx pnpm test:e2e

# Run tests with coverage
pnpm test:coverage
```

### 测试结构

测试套房包括:

-   **单位测试** (单位:千美元)`src/*.test.ts`(中文(简体) )
    
    -   `Client.test.ts` - 亮相类和生成UUID
    -   `oauth.test.ts` - OAuth PKCE公用事业和OAuthClient
    -   `stream-utils.test.ts` - 信息格式化和JSON分析
-   **API 集成测试** (单位:千美元)`src/api.test.ts`(中文(简体) )
    
    -   对代理、情景、CMS、文件的测试
    -   使用 MSW (Mock Service Worker) 来模拟 API
-   **E2E 测试** (单位:千美元)`src/e2e.test.ts`(中文(简体) )
    
    -   针对真实的亮光API的测试
    -   要求数 `BRIGHTSY_API_KEY` 财务报告和审定财务报表 `BRIGHTSY_ACCOUNT_ID` 环境 vars
    -   使用测试账户避免修改生产数据

### 大楼

```bash
pnpm build
```

## 认证

客户端支持带颗粒权限的团队API密钥. 从Brightsy仪表板取出你的API钥匙.

## 支助

-   联合国 [https://docs.brights.ai (英语)](https://docs.brightsy.ai/)
-   GitHub : (中文(简体) ) [https://github.com/brightsy/brightsy (中文(简体) )](https://github.com/brightsy/brightsy)
-   电子邮件 : [支持@brightsy.ai](mailto:support@brightsy.ai)

## 许可证

麻省理工学院

## 常见问题

### @brightsy/client 是什么？

布莱特西CMS和代理公司的统一客户端 SDK

### 如何安装 @brightsy/client？

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

### @brightsy/client 支持 TypeScript 吗？

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

### @brightsy/client 支持 ESM 还是 CommonJS？

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

### @brightsy/client 可以商用吗？

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

### @brightsy/client 的下载量有多少？

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

### @brightsy/client 还在维护吗？

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

