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

@torchwood/sdk

v0.7.0

Published

Torchwood Client API and Server API TypeScript SDK

Downloads

936

Readme

@torchwood/sdk

Torchwood 的官方 TypeScript SDK,封装 Client API(用户 JWT)与 Server API(scoped API Key + X-Torchwood-Project),以类型安全的方式调用 Torchwood 后端——适合前端应用、自动化脚本与 LLM Agent 集成。

安装

npm install @torchwood/sdk

要求 Node.js >= 18(ESM-only)。

快速开始

import { Torchwood } from "@torchwood/sdk";

// Server API:管理面操作(scoped API Key)
const admin = Torchwood.withApiKey("http://localhost:9080", "default", apiKey);
await admin.server.health.check();

// Client API:终端用户身份流(注册后自动保存 access token)
const client = Torchwood.create({ endpoint: "http://localhost:9080", projectId: "default" });
await client.account.signUp({ email: "[email protected]", password: "Pass@123", name: "User" });
await client.databases.createDocument("app", "notes", { data: { title: "Hi" } });

已有 access token 时也可以用 Torchwood.withAccessToken(endpoint, projectId, accessToken) 直接实例化。

函数内使用(execution 身份)

在 Torchwood Functions 的函数代码里,用 Torchwood.fromExecution() 直接获得带函数执行身份的 client(Authorization: Bearer <executionToken>,项目绑定在 token 内,无需 projectId / API Key)。方法面 = Server API 服务类全量(databases / users / assets / functions ...),权限由函数的 declared_scopes 约束(fail-closed):

import { Torchwood } from "@torchwood/sdk";

export async function main(ctx) {
  const tw = Torchwood.fromExecution(ctx.apiBaseUrl); // token 取自 TW_EXECUTION_TOKEN
  await tw.server.databases.createDocument("app", "audit", {
    data: { at: new Date().toISOString() },
  });
}

execution token 来源优先级:opts.executionToken 显式参数 > 环境变量 TW_EXECUTION_TOKEN(runner 在函数执行期注入)。并发(concurrency > 1)函数请走 ctx / 参数通道,不要读 process.env.TW_EXECUTION_TOKEN——async 恢复后可能读到其他请求的 token(凭证串号窗口,见 functions-v3.md 安全声明 §1)。

本地调试可用 Torchwood.fromExecution("http://127.0.0.1:9080", { executionToken: "..." }) 显式传入;或配合 torchwood functions dev --token <execution-token> 起本地 runner。

发布形态说明:函数内 SDK 与主包同源(同一个 @torchwood/sdk),暂不拆分独立 npm 包——避免 monorepo 双包构建(对 functions-v3.md §5.1 的一处已知偏离,拆包后置)。

OAuth2 浏览器流

浏览器中的 OAuth2 登录(Google / GitHub 等)走网关的 302 发起端点,整页跳转而非 fetch——发起时网关在 API 域种回调 nonce cookie,跨源 fetch 会把它丢掉导致回调必败:

// 1. 发起:同步拼出 authorize 地址,整页跳转(网关种 nonce cookie 后 302 到 provider 授权页)
window.location.href = client.account.buildOAuth2AuthorizeURL({
  provider: "github",
  success: "https://app.example.com/oauth/callback", // 回调落地点,需在项目回跳白名单内
  failure: "https://app.example.com/login?error=oauth_failed",
});

// 2. 回调页:解析重定向 fragment(#access_token=…&userId=…)建立本地会话
const parsed = parseOAuth2CallbackFragment(window.location.hash);
if (parsed?.type === "signed_in") {
  client.setAccessToken(parsed.accessToken);
  window.history.replaceState(null, "", "/oauth/callback"); // 清掉 fragment,避免 token 留在历史
} else if (parsed?.type === "mfa_required") {
  // 账号启用了 MFA:携带 parsed.challengeToken 走 createMFASession 二次认证
}

fragment 刻意不含 refresh_token(安全加固);OAuth 会话的 access_token 过期请引导用户重新登录。

createOAuth2Session / createOAuth2LinkSession 已标记 @deprecated(保留但不再适用于浏览器流,原因见方法注释);createOAuth2TokenSession 仅适用于 state 未被网关 GET 回调消费的定制流程。

API surface

Client API(Bearer JWT):account(注册/登录/会话/偏好)、databases(文档 CRUD + count)、groups / memberships、realtime(WebSocket 订阅)、assetspaymentssubscriptionsfunctionsinvokeFunction)、leaderboards(提交/me/top)、analyticsingest;包根另有 AnalyticsEventBuffer 批量缓冲器)。

Server API(API Key):healthprojectsusersgroupsdatabases(库/集合/属性/索引/文档/Bulk)、apiKeysstorage(Bucket/File)、functionsoauthProvidersoutboxauditLogsassetspaymentssubscriptionsbillingleaderboards(提交/条目/top/结算查询)、analytics(ingest + 固定形状查询)。

Agent 工具目录

SDK 内置 18 个 Agent 默认工具映射(动词 → Server RPC),供 LLM Agent / MCP Tool Server 使用:

import { agentTools, lookupAgentTool } from "@torchwood/sdk";

const tool = lookupAgentTool("list_users"); // { name, description, method, schema }

完整工具清单见 docs/developer/14-agent-tools.md

更多文档

License

MIT