@autonomys/rpc

中文文档
1.7.0发布于 2026/11/04TypeScriptCommonJS构建来源已验证近 30 天下载 2284

This package intends to ease the implementation of custom RPC protocols through the following features:

原始使用文档
文档目录5 节
  1. Type-Safe RPC APIs
  2. Define Server RPC Handlers
  3. Use Type-Safe RPC Client
  4. Set Up the RPC Server (w/o type safety)
  5. Set Up the RPC Client (w/o type safety)

@autonomys/rpc

This package intends to ease the implementation of custom RPC protocols through the following features:

  • Robust connection controller (e.g reconnection handles).
  • Built-in RPC protocol.
  • Creation of api definition for having type safety.

Type-Safe RPC APIs

One of the objectives of this package is to achieve type safety when implementing an RPC server and ease the creation of the RPC client.

For solving this problem we should create an ApiDefinition that basically consists of the definition of RPC methods with their input or outputs.

Example:

const apiDefinition = createApiDefinition({
  test: {
    params: z.object({ name: z.string() }),
    returns: z.object({ name: z.string() }),
  },
})

The object from above defines a RPC server with the single test method that receives as params { name: string } and returns the same.

Usually, we'd want to validate that the input and the output are correctly being constructed respecting the defined types. For this reason type definitions accept any Standard Schema (e.g. zod, Valibot or ArkType). Validation with zod needs zod >= 3.24: older versions don't implement Standard Schema, so their schemas fail to type-check. However, if for some reason you don't want to implement validators you can use the method defineUnvalidatedType<T>():

type TypeWithNoValidation = string // Any type could be used here

const apiDefinition = createApiDefinition({
  test: {
    params: z.object({ name: z.string() }),
    returns: defineUnvalidatedType<TypeWithNoValidation>(),
  },
})

Params and results are sent as JSON and parsed on the other side, so a schema with transforms or defaults has two types. Clients send the schema input of params and handlers get the parsed output, while handlers return the schema input of returns and clients get the parsed output. For example, with returns: z.string().transform((s) => new Date(s)) the handler returns the string and the client gets a Date. Some schemas have unknown as input, like z.coerce.number() in zod 4 or z.preprocess(...), so the client accepts any value there and only the server rejects it. In zod 4, z.coerce.number<number>() sets the input type again.

Define Server RPC Handlers

Once our API interface is defined the server RPC handlers ought to be defined:

const apiDefinition = createApiDefinition({
  test: {
    params: z.object({ name: z.string() }),
    returns: defineUnvalidatedType<TypeWithNoValidation>(),
  },
})

const server = apiDefinition.createServer({
  test: (params) => {
    return {
      name: params.name,
    }
  },
})

server.listen(8080)

You can also pass an existing HTTP server, Express application, or port:

const server = apiDefinition.createServer(
  {
    test: (params) => ({ name: params.name }),
  },
  {
    httpServer: app, // Express app or http.Server instance
    port: 8080,
  },
)

Use Type-Safe RPC Client

Once the server is running, using the same API definition the client could be simply built by:

const apiDefinition = createApiDefinition({
  test: {
    params: z.object({ name: z.string() }),
    returns: defineUnvalidatedType<TypeWithNoValidation>(),
  },
})

const client = apiDefinition.createClient({
  endpoint: `<ws-server-endpoint>`,
  callbacks: {},
})

client
  .test({
    name: 'log',
  })
  .then((e) => console.log(e)) /// { name: "xyz" }

Set Up the RPC Server (w/o type safety)

You can create an RPC server by using the createRpcServer function with an optional list of initial handlers. You can listen directly on a port or attach to an existing HTTP server / Express app:

import { createRpcServer } from '@autonomys/rpc'

const rpcServer = createRpcServer({
  initialHandlers: [
    {
      method: 'test',
      handler: () => ({
        jsonrpc: '2.0',
        result: 'success',
        id: 1,
      }),
    },
  ],
})

rpcServer.listen(8080)

Or pass port or an Express app directly:

const rpcServer = createRpcServer({
  httpServer: app, // optional: Express application or http.Server
  port: 8080,      // optional: auto-starts listening on port
  initialHandlers: [...],
})

Set Up the RPC Client (w/o type safety)

You can create an RPC client by using the createRpcClient function. This function requires a WS(S) endpoint and to setup callbacks for certain events. Here’s an example of how to set it up:

import { createRpcClient } from '../../src'

const setupRpcClient = async () => {
  const rpcClient = createRpcClient({
    endpoint: `ws://localhost:8080`,
    callbacks: {},
  })

  return rpcClient
}

// Example usage
const rpcClient = await setupRpcClient()

const response = await rpcClient.send({
  jsonrpc: '2.0',
  method: 'test',
  id: 1,
  params: {},
})

console.log(response)

版本与发布记录

@autonomys/rpc 共发布 79 个版本,首次发布于 2025/03/26;过去 12 个月发布了 24 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
1.7.0latest2026/11/043 天前
1.6.162026/10/2019 天前
1.6.152026/10/011 个月前
1.6.142026/06/045 个月前
1.6.132026/05/295 个月前
1.6.122026/05/295 个月前

其他发布通道:beta → 1.6.4-beta.1。

关于 @autonomys/rpc 的常见问题

@autonomys/rpc 是什么?

This package intends to ease the implementation of custom RPC protocols through the following features:

如何安装 @autonomys/rpc?

在项目目录运行 npm install @autonomys/rpc,或使用 pnpm add / yarn add / bun add。

@autonomys/rpc 支持 TypeScript 吗?

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

@autonomys/rpc 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@autonomys/rpc 可以商用吗?

@autonomys/rpc 使用 未声明 许可。package.json 没有声明许可证。没有许可证的代码默认保留全部权利,商用前请联系作者或查看仓库中的 LICENSE 文件。以上为概括,不构成法律意见,请以许可原文为准。

@autonomys/rpc 的下载量有多少?

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

@autonomys/rpc 还在维护吗?

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