npm package: @fict/json-rpc
Description: JSON-RPC V3.0 package
Author: Gopalakrishna Palem
Latest version: 0.1.8

# @fict/json-rpc

A lightweight, type-safe TypeScript implementation of the [JSON-RPC V3.0](https://github.com/KrishnaPG/json-rpc-v3.0) protocol, supporting versions 2.0 and 3.0, with additional `streaming capabilities`. This package provides utilities to create and handle JSON-RPC requests, responses, errors, and streams, suitable for client-server communication in enterprise applications.

## Features
- **Type-Safe**: Built with TypeScript for robust type checking and IntelliSense support.
- **JSON-RPC 2.0 & 3.0**: Supports both JSON-RPC 2.0 and 3.0 specifications.
- **Streaming Support**: Enables streaming requests and responses for real-time data.
- **Comprehensive Error Handling**: Includes standardized error codes and customizable error messages.
- **Extensible**: Modular design for easy integration and extension.
- **Lightweight**: Minimal dependencies for fast installation and execution.

## Installation

Install the package via npm:

```bash
npm install @fict/json-rpc
```

## Usage

### Basic Request and Response

Create a JSON-RPC request and handle a success response:

```typescript
import { RPCRequest, RPCResponse } from '@fict/json-rpc';

// Create a request
const request = RPCRequest('getUser', { id: 123 }, 'req1');
// { jsonrpc: "3.0", method: "getUser", params: { id: 123 }, id: "req1" }

// Create a success response
const response = RPCResponse({ name: "Alice" }, 'req1');
// { jsonrpc: "3.0", id: "req1", result: { name: "Alice" } }
```

### Streaming Request and Response

Handle streaming requests and responses:

```typescript
import {RPCStreamRequest, RPCStreamResponse, RPCStreamDone} from '@fict/json-rpc';

// Create a streaming request
const streamRequest = JsonRpc.RPCStreamRequest('getDataStream', { query: "latest" }, 'stream1');
// { jsonrpc: "3.0", method: "getDataStream", params: { query: "latest" }, id: "stream1", options: { stream: true } }

// Create a streaming data response
const streamData = JsonRpc.RPCStreamResponse({ chunk: [1, 2, 3] }, 'stream1');
// { jsonrpc: "3.0", stream: { id: "stream1", data: { chunk: [1, 2, 3] } } }

// Signal stream completion
const streamDone = JsonRpc.RPCStreamDone({ total: 100 }, 'stream1');
// { jsonrpc: "3.0", stream: { id: "stream1" }, result: { total: 100 } }
```

### Error Handling

Handle errors with standardized codes:

```typescript
import { RPCError, ErrorCode } from '@fict/json-rpc';

// Create an error response
const errorResponse = RPCError(
  { code: ErrorCode.RPC_MethodNotFound, message: "Method not found" },
  'req1'
);
// { jsonrpc: "3.0", id: "req1", error: { code: -32601, title: "NotFound", message: "Method not found" } }
```

### Message Discrimination

Process incoming JSON-RPC messages:

```typescript
import { JsonRpcMessage } from '@fict/json-rpc';

function handleRpcMessage(msg: JsonRpcMessage) {
  if ("method" in msg && !("options" in msg)) {
    console.log("Regular Request:", msg);
  } else if ("options" in msg && msg.options?.stream) {
    console.log("Stream Request:", msg);
  } else if ("stream" in msg) {
    if ("data" in msg.stream) {
      console.log("Stream Data:", msg.stream.data);
    } else if ("result" in msg) {
      console.log("Stream Done:", msg.result);
    } else if ("error" in msg) {
      console.error("Stream Error:", msg.error);
    }
  } else if ("result" in msg) {
    console.log("Success Response:", msg.result);
  } else if ("error" in msg) {
    console.error("Error Response:", msg.error);
  } else if ("ack" in msg) {
    console.log("Ack Response for request:", msg.id);
  }
}
```

## API Reference

### Enums
- **`JsonRpcVersion`**: Defines supported JSON-RPC versions.
  - `V2_0 = "2.0"`
  - `V3_0 = "3.0"`
- **`ErrorCode`**: Standard and JSON-RPC-specific error codes (e.g., `BadRequest`, `RPC_InvalidRequest`, `RPC_MethodNotFound`).

### Interfaces
- **`BaseJsonRpcRequest<TParams>`**: Base request with `jsonrpc`, `method`, `params`, and `id`.
- **`JsonRpcRequestV3<TParams, TOptions>`**: Extends base request with `options` for version 3.0.
- **`JsonRpcStreamRequest<TParams>`**: Streaming request with `options.stream`.
- **`JsonRpcSuccessResponse<TResult>`**: Success response with `result`.
- **`JsonRpcErrorResponse`**: Error response with `error` context.
- **`JsonRpcAck<TAck>`**: Acknowledgment response with `ack`.
- **`JsonRpcStreamData<TData>`**: Streaming data response with `stream.id` and `stream.data`.
- **`JsonRpcStreamDone<TResult>`**: Streaming done response with final `result`.
- **`JsonRpcStreamError`**: Streaming error response with `error`.

### Helper Functions
- **`JsonRpc.RPCRequest(method, params?, id?)`**: Creates a standard JSON-RPC request.
- **`JsonRpc.RPCStreamRequest(method, params, id)`**: Creates a streaming request.
- **`JsonRpc.RPCResponse(result, id?)`**: Creates a success response.
- **`JsonRpc.RPCAck(id, ack?)`**: Creates an acknowledgment response.
- **`JsonRpc.RPCStreamResponse(data, id)`**: Creates a streaming data response.
- **`JsonRpc.RPCStreamDone(result, id)`**: Creates a streaming done response.
- **`JsonRpc.RPCStreamAbort(id)`**: Creates a streaming abort response.
- **`JsonRpc.RPCStreamError(err, id)`**: Creates a streaming error response.
- **`JsonRpc.RPCError(err, id?)`**: Creates a standard error response.
- **`JsonRpc.ErrorFmt`**: Provides utilities to format error contexts (e.g., `clientCancelled`, `notFound`, `timeout`).

## Error Codes
The package includes a comprehensive set of error codes:
- **HTTP-like**: `BadRequest (400)`, `UnAuthenticated (401)`, `NotFound (404)`, etc.
- **JSON-RPC Specific**: `RPC_InvalidRequest (-32600)`, `RPC_MethodNotFound (-32601)`, etc.
- **Enhanced Codes**: `RPC_Unauthenticated (-32001)`, `RPC_TooManyRequests (-32029)`, etc.

## Requirements
- **Node.js**: v22 or higher
- **TypeScript**: v5.8 or higher (for type safety)

## Development
To contribute or test locally:

1. Clone the repository:
   ```bash
   git clone https://github.com/your-org/json-rpc.git
   cd json-rpc
   ```
2. Install dependencies:
   ```bash
   npm install
   ```
3. Build the package:
   ```bash
   npm run build
   ```
4. Run tests:
   ```bash
   npm test
   ```

## License
Copyright © 2025 [Gopalakrishna Palem](https://gk.palem.in/). Licensed under the MIT License.