TwirpScript

0.0.72 · active · verified Sun Apr 19

TwirpScript is a Protocol Buffers (Protobuf) RPC framework designed for JavaScript and TypeScript environments. It automates the generation of both client and server code from `.proto` service definitions, facilitating type-safe communication in both browser and Node.js runtimes. The package is currently at version 0.0.72 and maintains an active release cadence with frequent minor updates addressing bug fixes and improvements. A key differentiator is its adherence to the Twirp Wire Protocol (v7) and its focus on minimizing bundle sizes, especially through tree-shaking and a lightweight runtime (2KB for TwirpScript, 37KB for the underlying ProtoScript serialization runtime). This makes it an efficient alternative to larger RPC frameworks, particularly for web applications requiring lean client bundles and strict type enforcement.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to create and use a TwirpScript client to interact with a generated Protobuf RPC service, such as a 'Haberdasher' service.

// haberdasher.proto (example service definition)
// syntax = "proto3";
// package twirp.example;

// message Hat {
//   int32 inches = 1;
//   string color = 2;
//   string name = 3;
// }

// message Size {
//   int32 inches = 1;
// }

// service Haberdasher {
//   rpc MakeHat(Size) returns (Hat);
// }

// After running TwirpScript compiler (e.g., twirpscript --proto_path=. haberdasher.proto),
// this would generate `haberdasher.pb.ts` and `haberdasher.twirp.ts`.

// client.ts
import { createTwirpClient } from 'twirpscript';
import { Haberdasher } from './haberdasher.twirp'; // Generated Twirp service client
import { Size } from './haberdasher.pb'; // Generated Protobuf message type

const BASE_URL = 'http://localhost:8080/twirp'; // Replace with your Twirp server URL

async function runClient() {
  // Create a Twirp client for the Haberdasher service
  const client = createTwirpClient(Haberdasher, BASE_URL);

  try {
    // Define the request message for MakeHat
    const size: Size = { inches: 12 };
    
    // Call the RPC method
    const hat = await client.MakeHat(size);
    
    console.log(`Successfully made a hat: ${hat.name} (${hat.color}, ${hat.inches} inches)`);
  } catch (error) {
    console.error('Error making hat:', error);
  }
}

runClient();

view raw JSON →