@desplega.ai/business-use

中文文档
0.4.3发布于 2026/03/27MITTypeScriptESM + CJS近 30 天下载 3.3万

轻量级 JavaScript/ TypeScript SDK 用于商业用途事件跟踪和断言

中文使用文档
文档目录22 节
  1. 特征
  2. 安装
  3. 快速启动
  4. API 参考
  5. initialize(options?)
  6. ensure(options)
  7. act(options)
  8. assert(options)
  9. shutdown(timeout?)
  10. 环境变量
  11. 配置
  12. 批处理
  13. 队列管理
  14. 处理错误
  15. 类型脚本支持
  16. 类型安全特征
  17. 背景结构
  18. 建筑
  19. 发展
  20. 许可证
  21. 捐款
  22. 支助

业务使用 JavaScript SDK

Format & Lint Checks

一个轻量级的JavaScript/TypeScript SDK,用于跟踪生产应用中的商务事件和断言.

特征

  • 零用户失败: SDK 错误从不崩溃或屏蔽代码
  • 最低间接费用:同步批量防止阻塞 I/ 欧
  • 简单 API: 主要职能 ensure() 有方便帮助者 act() 财务报告和审定财务报表 assert()
  • 类型安全: 包含全面类型定义的完整类型脚本支持
  • 了解背景: 过滤器和验证器可以访问上游依赖性数据
  • 最小依赖性: 仅 Zod 用于计划验证

安装

# Using pnpm
pnpm add @desplega.ai/business-use

# Using npm
npm install @desplega.ai/business-use

# Using yarn
yarn add @desplega.ai/business-use

快速启动

import { initialize, ensure } from '@desplega.ai/business-use';

// Initialize the SDK (call once at app startup)
initialize({ apiKey: 'your-api-key' });

// Track a business action (no validator)
ensure({
  id: 'payment_processed',
  flow: 'checkout',
  runId: 'run_12345',
  data: { amount: 100, currency: 'USD' },
  description: 'Payment processed successfully'
});

// Track a business assertion (with validator)
function validateOrderTotal(data: Record<string, any>, ctx: { deps: Array<{ flow: string; id: string; data: Record<string, any> }> }): boolean {
  // ctx.deps contains upstream dependency events
  const hasCart = ctx.deps.some((dep) => dep.id === 'cart_created');
  return data.total > 0 && hasCart;
}

ensure({
  id: 'order_total_valid',
  flow: 'checkout',
  runId: 'run_12345',
  data: { total: 150 },
  depIds: ['cart_created'],
  validator: validateOrderTotal, // Creates "assert" node
  description: 'Order total validation'
});

// Convenience wrappers (optional)
import { act, assert } from '@desplega.ai/business-use';

// act() is ensure() without validator
act({ id: 'user_signup', flow: 'onboarding', runId: 'u123', data: {...} });

// assert() is ensure() with validator
assert({ id: 'validation', flow: 'checkout', runId: 'o123', data: {...}, validator: fn });

API 参考

initialize(options?)

初始化商业用途 SDK. 使用前必须调用 ensure()。 。 。 .

选项 :

  • apiKey?: string - 用于认证的 API 密钥( 默认: 从 BUSINESS_USE_API_KEY (原始内容存档于2019-09-21) (英语). env var
  • url?: string - 后端 API URL( 默认: 从 BUSINESS_USE_URL 环境 var 或 http://localhost:13370(中文(简体) )
  • batchSize?: number - 每批事件数量(默认:100起)
  • batchInterval?: number - 以毫秒计的平流间隔( 默认: 5000)
  • maxQueueSize?: number - 最大队列大小( 默认 ): batchSize * 10(中文(简体) )

示例

initialize({
  apiKey: 'your-api-key',
  url: 'https://api.example.com',
  batchSize: 50,
  batchInterval: 3000,
});

ensure(options)

主要职能 追踪商业事件 类型由存在自动决定 validator。 。 。 .

选项 :

  • id: string - 独特的事件标识符(例如, "payment_processed"(中文(简体) )
  • flow: string - 流动标识符(例如, "checkout"(中文(简体) )
  • runId: string | (() => string) - 运行标识符(字符串或函数)
  • data: Record<string, any> - 事件数据有效载荷
  • filter?: (data, ctx) => boolean - 后端评价的可选过滤功能
  • depIds?: string[] | (() => string[]) - 可选的依赖性节点ID
  • validator?: (data, ctx) => boolean - 在后端执行可选验证功能
  • description?: string - 可选人可读描述

类型确定 :

  • 若为 validator 提供 − 创建 "生还" 节点
  • 若为 validator 实值 undefined * 创建一个 动作 节点

示例

// Action node (no validator)
ensure({
  id: 'payment_processed',
  flow: 'checkout',
  runId: 'run_12345',
  data: { amount: 100, currency: 'USD' },
  depIds: ['cart_created'],
  description: 'Payment processed successfully',
});

// Assertion node (with validator)
function validateTotal(data: Record<string, any>, ctx: { deps: DepData[] }): boolean {
  const itemsTotal = ctx.deps.reduce((sum, dep) => sum + dep.data.price, 0);
  return data.total === itemsTotal;
}

ensure({
  id: 'order_total_valid',
  flow: 'checkout',
  runId: 'run_12345',
  data: { total: 150 },
  depIds: ['item_added'],
  validator: validateTotal,
  description: 'Order total validation',
});

act(options)

方便包装器 周围 ensure() 没有验证符。 创建一个"act"节点.

选项 :

  • id: string - 独特的事件标识符(例如, "payment_processed"(中文(简体) )
  • flow: string - 流动标识符(例如, "checkout"(中文(简体) )
  • runId: string | (() => string) - 运行标识符(字符串或函数)
  • data: Record<string, any> - 事件数据有效载荷
  • filter?: (data, ctx) => boolean - 后端评价的可选过滤功能
  • depIds?: string[] | (() => string[]) - 可选的依赖性节点ID
  • description?: string - 可选人可读描述

过滤函数签名 :

function myFilter(
  data: Record<string, any>,
  ctx: { deps: Array<{ flow: string; id: string; data: Record<string, any> }> }
): boolean {
  // Return true to include event, false to filter it out
  // ctx.deps contains all upstream dependency events
  return true;
}

示例

act({
  id: 'user_signup',
  flow: 'onboarding',
  runId: 'run_001',
  data: { email: '[email protected]', plan: 'premium' },
  depIds: ['landing_page_visit'],
  description: 'User signed up for premium plan'
});

// Using functions for dynamic values
act({
  id: 'order_completed',
  flow: 'checkout',
  runId: () => getCurrentRunId(),
  data: { orderId: order.id },
  depIds: () => getDependencies(),
});

// With filter based on upstream dependencies
function checkPrerequisites(
  data: Record<string, any>,
  ctx: { deps: Array<{ flow: string; id: string; data: Record<string, any> }> }
): boolean {
  // Only process if all upstream tasks are approved
  return ctx.deps.every((dep) => dep.data.status === 'approved');
}

act({
  id: 'order_finalized',
  flow: 'checkout',
  runId: 'run_12345',
  data: { orderId: 'ord_123' },
  depIds: ['payment_processed', 'inventory_reserved'],
  filter: checkPrerequisites, // Evaluated on backend with ctx
  description: 'Order finalized after all prerequisites',
});

assert(options)

方便包装器 周围 ensure() 使用验证器。 创建"surt"节点.

选项 :

  • id: string - 独特的断言标识符(例如, "order_total_valid"(中文(简体) )
  • flow: string - 流动标识符(例如, "checkout"(中文(简体) )
  • runId: string | (() => string) - 运行标识符(字符串或函数)
  • data: Record<string, any> - 事件数据有效载荷
  • filter?: (data, ctx) => boolean - 后端评价的可选过滤功能
  • depIds?: string[] | (() => string[]) - 可选的依赖性节点ID
  • validator?: (data, ctx) => boolean - 在后端执行可选验证功能
  • description?: string - 可选人可读描述

校验函数签名 :

function myValidator(
  data: Record<string, any>,
  ctx: { deps: Array<{ flow: string; id: string; data: Record<string, any> }> }
): boolean {
  // Return true if validation passes, false if it fails
  // ctx.deps contains all upstream dependency events
  return true;
}

示例

// Validator accessing upstream dependencies
function validateOrderTotal(
  data: Record<string, any>,
  ctx: { deps: Array<{ flow: string; id: string; data: Record<string, any> }> }
): boolean {
  // Calculate total from upstream item_added events
  const itemsTotal = ctx.deps
    .filter((dep) => dep.id === 'item_added')
    .reduce((sum, dep) => sum + dep.data.price, 0);

  // Verify order total matches
  return data.total === itemsTotal;
}

assert({
  id: 'order_total_matches',
  flow: 'checkout',
  runId: 'run_12345',
  data: { total: 150 },
  depIds: ['item_added'], // Multiple item_added events
  validator: validateOrderTotal,
  description: 'Order total matches sum of item prices',
});

// Validator with complex logic
function validatePaymentAndInventory(
  data: Record<string, any>,
  ctx: { deps: Array<{ flow: string; id: string; data: Record<string, any> }> }
): boolean {
  const paymentApproved = ctx.deps.some(
    (dep) => dep.id === 'payment_processed' && dep.data.status === 'approved'
  );
  const inventoryReserved = ctx.deps.some(
    (dep) => dep.id === 'inventory_reserved' && dep.data.reserved === true
  );
  return paymentApproved && inventoryReserved && data.readyToShip;
}

assert({
  id: 'order_ready',
  flow: 'checkout',
  runId: 'run_12345',
  data: { readyToShip: true },
  depIds: ['payment_processed', 'inventory_reserved'],
  validator: validatePaymentAndInventory,
});

shutdown(timeout?)

光荣地关闭SDK。 试图冲刷所有剩余的事件.

参数:

  • timeout?: number - 最多等待时间以毫秒( 默认: 5000)

回返情况: Promise<void>

示例

// At application shutdown
await shutdown(5000);

环境变量

SDK 通过环境变量支持配置 :

  • BUSINESS_USE_API_KEY - 用于认证的 API 密钥
  • BUSINESS_USE_URL - 后端 API URL

示例

export BUSINESS_USE_API_KEY="your-api-key"
export BUSINESS_USE_URL="https://api.example.com"
// Will use environment variables
initialize();

配置

批处理

当任一条件得到满足时,事件被分批发送到后端:

  1. 大小触发: 队列包含 {} batchSize 事件( 默认: 100)
  2. 时间触发数字 : batchInterval 自上次冲出( 默认值: 5000 秒) 后已过毫秒

队列管理

  • 最大队列大小数字 : batchSize * 10 (默认: 1000起事件)
  • 流出战略: 放弃最古老的事件(FIFO驱逐)
  • 线索安全: 已建于 JavaScript 事件回路( 固有单行)

处理错误

SDK的设计 申请从不失败数字 :

  • 所有网络出错都在内部记录
  • 无效的配置导致警告无效行为
  • 队列无声地溢出最古老的事件
  • 没有向用户代码扔出例外

类型脚本支持

SDK是用 TypeScript 编写的,并提供了完整的类型定义 类型安全过滤和验证功能数字 :

import { initialize, act, assert, type Ctx, type DepData } from '@desplega.ai/business-use';

// Type inference - both data and ctx are automatically typed!
act({
  id: 'payment_processed',
  flow: 'checkout',
  runId: 'run_123',
  data: { amount: 100, currency: 'USD' },
  depIds: ['cart_created'],
  filter: (data, ctx) => {
    // data.amount is known to exist!
    // ctx.deps gives you access to upstream dependencies
    return data.amount > 0 && ctx.deps.length > 0;
  },
});

// Explicit types for even better type safety
interface OrderData {
  orderId: string;
  total: number;
}

interface ItemData {
  id: string;
  price: number;
}

assert<OrderData>({
  id: 'order_validation',
  flow: 'checkout',
  runId: 'run_456',
  data: { orderId: '12345', total: 200 },
  depIds: ['item_added'],
  validator: (data, ctx) => {
    // Full autocomplete and type checking for data!
    // ctx.deps contains all upstream item_added events
    const calculatedTotal = ctx.deps
      .filter((dep) => dep.id === 'item_added')
      .reduce((sum, dep) => sum + (dep.data as ItemData).price, 0);
    return data.total === calculatedTotal;
  },
});

类型安全特征

  • 自动类型推断双 data 财务报告和审定财务报表 ctx 参数 filter 财务报告和审定财务报表 validator 函数自动输入
  • 明确类型参数: 使用通用类型参数(act<T>, (中文(简体) ), assert<T>更严格的类型检查
  • 背景打字数字 : ctx 有类型 Ctx 与 deps: DepData[] 获取上游依赖
  • 嵌入对象支持: 复杂嵌入式数据结构的完整类型安全
  • IDE 自动完成: 在 VS 代码和其他 TypeScript-aware 编辑器中获取完整的 IntelliSense/自动完成

背景结构

两者 filter 财务报告和审定财务报表 validator 函数收到 a ctx 有上游依赖性数据的参数:

interface DepData {
  flow: string;    // Flow identifier
  id: string;      // Node/event identifier
  data: Record<string, any>; // Event data payload
}

interface Ctx {
  deps: DepData[]; // All upstream dependency events
}

建筑

SDK遵循OpenTeleometter, Sentry, and DataDog所启发的行业最佳做法:

  • 基于矩阵的队列 可配置大小限制
  • 递归设置 Timeout 用于可靠计时器管理的(未设置Interval)
  • 基于承诺的关闭 有超时保护
  • 后端过滤器评价 与上游依赖性的联系 ctx
  • 函数序列化 用于后端执行过滤器和验证器
  • 了解背景的执行 - 过滤器和验证器都接收上游依赖性数据

发展

# Install dependencies
pnpm install

# Build the SDK
pnpm build

# Run tests
pnpm test

# Run tests with UI
pnpm test:ui

# Run example
pnpm example

# Type check
pnpm typecheck

许可证

麻省理工学院

捐款

欢迎捐款! 请打开一个问题或提交拉动请求.

支助

关于议题和问题清单:

版本与发布记录

@desplega.ai/business-use 共发布 10 个版本,首次发布于 2025/10/22;过去 12 个月发布了 1 个版本。

版本发布日期距今
0.4.3latest2026/03/277 个月前
0.4.22025/10/241 年前
0.4.12025/10/241.1 年前
0.4.02025/10/231.1 年前
0.3.32025/10/231.1 年前
0.3.22025/10/231.1 年前

关于 @desplega.ai/business-use 的常见问题

@desplega.ai/business-use 是什么?

轻量级 JavaScript/ TypeScript SDK 用于商业用途事件跟踪和断言

如何安装 @desplega.ai/business-use?

在项目目录运行 npm install @desplega.ai/business-use,或使用 pnpm add / yarn add / bun add。

@desplega.ai/business-use 支持 TypeScript 吗?

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

@desplega.ai/business-use 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@desplega.ai/business-use 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=18.0.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@desplega.ai/business-use 可以商用吗?

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

@desplega.ai/business-use 的下载量有多少?

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

@desplega.ai/business-use 还在维护吗?

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