npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

api2key-base-sdk

v0.1.10

Published

TypeScript SDK for consuming the Api2Key API stable APIs

Readme

api2key-base-sdk

api2key-base-sdk 是当前唯一保留的 SDK 入口,统一承载基础平台能力、项目运行时能力和后台管理客户端。

适合放进所有新项目作为默认基础依赖。

当前边界

当前统一暴露:

  1. auth
  2. credits
  3. apiKeys
  4. settings
  5. projects
  6. orders
  7. payment
  8. ai
  9. speech
  10. admin

安装原则:

  1. 所有新项目默认只安装 api2key-base-sdk
  2. 后台项目也只安装 api2key-base-sdk
  3. 单项目私有逻辑优先留在本地 facade,而不是再拆新的 SDK 包

暴露的客户端

当前 api2key-base-sdk 暴露以下客户端:

  1. auth
  2. credits
  3. apiKeys
  4. settings
  5. projects
  6. orders
  7. payment
  8. ai
  9. speech
  10. admin

1. auth

负责稳定的用户认证能力。

当前主要方法:

  1. login(input)
  2. register(input)
  3. verifyEmail(input)
  4. resendVerification(input)
  5. forgotPassword(input)
  6. resetPassword(input)
  7. sendChangePasswordCode(accessToken?)
  8. changePassword(input, accessToken?)
  9. me(accessToken?)
  10. logout(accessToken?)

2. credits

负责稳定的积分账户读取与扣减能力。

推荐拆成两类理解:

  1. 用户态读取与扣减:默认跟随当前登录 token 或 API Key 的项目上下文
  2. 服务态写入:仍保留显式 projectId + X-Service-Secret 的内部接口

当前主要方法包括:

  1. getBalance(accessToken?)
  2. getLedger(input)
  3. deduct(input)
  4. spend(input)
  5. reserve(input)
  6. confirm(id)
  7. cancel(id)

3. apiKeys

负责用户 API Key 生命周期管理。

当前推荐约定:

  1. 用户登录后创建 API Key 时,不再要求前端额外显式传项目
  2. 默认使用当前 JWT 中的 projectId
  3. 如仍传 projectId,它只能作为一致性校验,不能覆盖当前 token 项目

4. settings

负责用户级设置的读取与更新。

5. projects / orders / payment / ai / speech

负责项目商品、会员、订单、支付、AI 以及语音运行时能力。

其中 speech 对齐当前 api2key-base-api 的内置语音接口:

  1. listVoices(...)
  2. synthesize(...)
  3. transcribe(...)
  4. transcribeSrt(...)
  5. getAsrTask(...)
  6. downloadAudio(...)

6. admin

负责项目管理、产品管理、用户管理、会员管理、模型管理、后台积分操作等控制面能力。

适合哪些项目

适合:

  1. 所有新项目
  2. 只需要登录、积分、用户设置、API Key 的项目
  3. 需要一个长期稳定基础依赖的项目

安装

npm install api2key-base-sdk

使用示例

import { createBasePlatformClient } from 'api2key-base-sdk';
import {
  createAdminPlatformClient,
  createProjectPlatformClient,
} from 'api2key-base-sdk';

const baseClient = createBasePlatformClient({
  baseUrl: process.env.API2KEY_BASE_URL!,
  getAccessToken: () => process.env.ACCESS_TOKEN,
  getServiceSecret: () => process.env.SERVICE_SECRET,
});

const me = await baseClient.auth.me();
const credits = await baseClient.credits.getBalance();
const apiKey = await baseClient.apiKeys.create({
  name: 'workflow',
});

await baseClient.auth.verifyEmail({
  email: '[email protected]',
  code: '123456',
});

const projectClient = createProjectPlatformClient({
  baseUrl: process.env.API2KEY_BASE_URL!,
  getAccessToken: () => process.env.ACCESS_TOKEN,
  getApiKey: () => process.env.API_KEY,
  getProjectId: () => process.env.PROJECT_ID,
});

const adminClient = createAdminPlatformClient({
  baseUrl: process.env.API2KEY_BASE_URL!,
  getAccessToken: () => process.env.ADMIN_ACCESS_TOKEN,
});

const products = await projectClient.projects.getCatalogProducts(process.env.PROJECT_ID!);
const aiModels = await projectClient.ai.getModels({ projectId: process.env.PROJECT_ID! });
const aiBalance = await projectClient.ai.getBalance({ projectId: process.env.PROJECT_ID! });

for (const model of aiModels.models) {
  console.log(model.key, model.inputPricing, model.outputPricing);
}

const directPayment = await projectClient.payment.createDirectUnified({
  subject: 'Workflow credits top-up',
  amount: 29.9,
});
const voices = await projectClient.speech.listVoices({
  provider: 'azure',
  locale: 'zh-CN',
});
const projects = await adminClient.admin.listProjects();

推荐调用方式

用户态:

  1. 登录 / 注册阶段可以显式指定项目,也可以省略,让后端回落当前项目、绑定项目或默认项目
  2. 登录完成后,auth.me()credits.getBalance()apiKeys.create() 默认依赖当前 token 项目
  3. 前端不要在每个用户态接口上重复显式传 projectId
  4. auth.me()credits.getBalance() 不再接受显式 projectId 覆盖
  5. credits.deduct() 支持 accessTokenapiKey,不依赖 service secret

服务态:

  1. credits.spend()credits.reserve() 继续显式传 projectId
  2. 这类接口本质上是内部服务接口,走 X-Service-Secret

说明:

  1. SDK 仍然接收单一 baseUrl
  2. /api/v1/* 接口继续基于 baseUrl 访问
  3. speech 客户端会自动基于同一域名访问根路径下的 /api/* 语音接口,无需额外配置第二个 URL
  4. 用户侧 auth.mecredits.getBalance()apiKeys.create() 默认优先使用当前登录 token 中的 projectId,无需再显式传项目
  5. 内部服务侧积分扣减 / 预扣仍需显式传 projectId,因为它们走的是 X-Service-Secret,不是用户 JWT
  6. payment.createDirectUnified() 对齐后端直付充值接口,不依赖商品或订单,只需要 subject + amountprojectId 仅在你要锁定充值目标项目时才需要显式传入
  7. AI 模型价格语义以 inputPricing / outputPricing 为准;creditCostPerRequest 仅保留为兼容旧服务端的可选字段

最小用户态示例

const authClient = createBasePlatformClient({
  baseUrl: process.env.API2KEY_BASE_URL!,
  getProjectId: () => process.env.PROJECT_ID,
});

const session = await authClient.auth.login({
  email: '[email protected]',
  password: 'password',
  projectId: process.env.PROJECT_ID!,
});

const userClient = createBasePlatformClient({
  baseUrl: process.env.API2KEY_BASE_URL!,
  getAccessToken: () => session.accessToken,
});

const meAfterLogin = await userClient.auth.me();
const balanceAfterLogin = await userClient.credits.getBalance();
const newApiKey = await userClient.apiKeys.create({ name: 'default' });

上面这组调用的重点是:

  1. 只在需要锁定项目时才在登录阶段显式指定项目
  2. 登录后用户态接口自动跟随 token 项目
  3. 不再把默认项目重复塞到每次请求里
  4. /auth/me/credits/balance 已彻底收口,不再允许用户态通过 query 或 SDK 参数切项目

直接充值积分

直充积分走 payment.createDirectUnified(),不依赖产品,不需要先创建商品订单。

最小调用只需要:

  1. 登录态 accessToken
  2. subject
  3. amount
const paymentClient = createProjectPlatformClient({
  baseUrl: process.env.API2KEY_BASE_URL!,
  getAccessToken: () => process.env.ACCESS_TOKEN,
});

const directPayment = await paymentClient.payment.createDirectUnified({
  subject: 'Account credits top-up',
  amount: 9.9,
});

console.log(directPayment.id);
console.log(directPayment.orderNo);
console.log(directPayment.data?.qrCode);

如果你明确要把充值锁定到某个项目,再额外传 projectId

await paymentClient.payment.createDirectUnified({
  subject: 'Project credits top-up',
  amount: 29.9,
  projectId: process.env.PROJECT_ID,
});

最小服务态示例

const serviceClient = createBasePlatformClient({
  baseUrl: process.env.API2KEY_BASE_URL!,
  getServiceSecret: () => process.env.SERVICE_SECRET,
});

await serviceClient.credits.spend({
  userId: 'user-id',
  projectId: process.env.PROJECT_ID!,
  amount: 10,
  service: 'ai_chat',
  taskId: 'task-001',
});

Speech 示例

推荐在项目级客户端上使用:

import { createProjectPlatformClient } from 'api2key-base-sdk';

const client = createProjectPlatformClient({
  baseUrl: process.env.API2KEY_BASE_URL!,
  getAccessToken: () => process.env.ACCESS_TOKEN,
  getApiKey: () => process.env.API_KEY,
  getProjectId: () => process.env.PROJECT_ID,
});

1. 获取声音列表

const voices = await client.speech.listVoices({
  provider: 'azure',
  locale: 'zh-CN',
});

console.log(voices.provider);
console.log(voices.total);
console.log(voices.voices[0]?.shortName);

2. 文本转音频

const synthesized = await client.speech.synthesize({
  provider: 'azure',
  text: '你好,欢迎使用 api2key speech client。',
  locale: 'zh-CN',
  voice: 'zh-CN-XiaoxiaoNeural',
  format: 'audio-24khz-96kbitrate-mono-mp3',
  rate: 1,
  volume: 100,
  pitch: 0,
});

console.log(synthesized.contentType);
console.log(synthesized.creditsCharged);
console.log(synthesized.storageKey);
console.log(synthesized.downloadUrl);
console.log(synthesized.audio.byteLength);

如果你要把返回音频写入文件,在 Node.js 中可以这样处理:

import { writeFile } from 'node:fs/promises';

await writeFile('speech.mp3', Buffer.from(synthesized.audio));

3. 简洁音频转文本

import { readFile } from 'node:fs/promises';

const audioBytes = await readFile('./sample.mp3');
const audioBlob = new Blob([audioBytes], { type: 'audio/mpeg' });

const transcript = await client.speech.transcribe({
  provider: 'groq',
  file: audioBlob,
  fileName: 'sample.mp3',
});

console.log(transcript.language);
console.log(transcript.full_text);
console.log(transcript.segments.length);

也可以直接传远程地址:

const transcript = await client.speech.transcribe({
  provider: 'groq',
  audioUrl: 'https://example.com/sample.mp3',
});

4. 音频转 SRT

同步模式:

const srtResult = await client.speech.transcribeSrt({
  provider: 'tencent',
  file: audioBlob,
  fileName: 'sample.mp3',
  async: false,
});

if ('srt' in srtResult) {
  console.log(srtResult.text);
  console.log(srtResult.srt);
}

异步模式:

const submitted = await client.speech.transcribeSrt({
  provider: 'tencent',
  file: audioBlob,
  fileName: 'sample.mp3',
  async: true,
});

if ('taskId' in submitted && !('srt' in submitted)) {
  console.log(submitted.taskId);
  console.log(submitted.statusStr);
}

5. 查询异步字幕任务

const task = await client.speech.getAsrTask({
  provider: 'tencent',
  taskId: 123456,
});

console.log(task.status);
console.log(task.statusStr);
console.log(task.retryAfterSeconds);
console.log(task.srt);

6. 通过存储 key 下载合成音频

const downloaded = await client.speech.downloadAudio({
  key: synthesized.storageKey!,
});

console.log(downloaded.contentType);
console.log(downloaded.fileName);
console.log(downloaded.audio.byteLength);

7. 鉴权建议

推荐方式:

  1. 服务端项目调用时,通过 getApiKey() 提供 sk-...
  2. 用户登录态场景,通过 getAccessToken() 提供 JWT
  3. 大多数项目建议同时提供 getProjectId(),保持语音接口和项目上下文一致

8. 路径说明

你只需要传一个 baseUrl,例如:

baseUrl: 'https://open.api2key.com/api/v1'

SDK 会自动处理:

  1. 普通平台接口继续访问 /api/v1/*
  2. speech client 自动访问同域名下的 /api/*

设计原则

  1. 新项目默认只依赖这个包
  2. 共享客户端统一收敛在一个包里
  3. api2key-base-api 可以继续保持清晰的路由分层,而不需要在消费侧安装多个 SDK

Agent 约定

后续 agent 在处理需求时,默认把这个包视为“稳定基础层”。

规则:

  1. 如果需求属于共享客户端能力,优先在这里找
  2. 后端路由边界仍按 base/project/admin 区分,不要因为 SDK 合并而改乱 API 归属
  3. 如果新需求只服务单个项目,优先留在项目本地 facade

兼容说明

当前仍保留 createPlatformAClient 作为过渡别名,它返回基础能力客户端。

建议新代码统一使用:

  • createBasePlatformClient
  • createProjectPlatformClient
  • createAdminPlatformClient