npm package: @pl8net/client
Description: TypeScript/Javascript client library for Playnet multiplayer framework
Author: Playnet Team
Latest version: 0.0.1

# Pl8net Client Library

[![npm version](https://img.shields.io/npm/v/@pl8net/client.svg)](https://www.npmjs.com/package/@pl8net/client)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)

A TypeScript client library for the Playnet multiplayer framework. This library provides an easy-to-use interface for connecting to Playnet servers, handling authentication, and synchronizing player positions in real-time.

## Features

- WebSocket-based communication with Playnet servers
- TypeScript types for all messages and events
- Promise-based connection handling
- Automatic reconnection with exponential backoff
- Event-based API for reacting to server messages
- Player tracking and management
- Detailed documentation and examples

## Installation

```bash
npm install @pl8net/client
```

## Usage

### Basic Example

```typescript
import PlaynetClient from '@pl8net/client';

// Create a client instance
const client = new PlaynetClient('ws://localhost:8081/ws');

// Set up event handlers
client.on('onConnect', (clientId) => {
  console.log(`Connected with client ID: ${clientId}`);
  
  // Authenticate after connection
  client.authenticate('PlayerName');
});

client.on('onAuthenticated', (playerId) => {
  console.log(`Authenticated as player: ${playerId}`);
  
  // Update position periodically
  setInterval(() => {
    client.updatePosition(
      { x: Math.random() * 10, y: 0, z: Math.random() * 10 },
      { x: 0, y: Math.random() * 360, z: 0 }
    );
  }, 1000);
});

client.on('onPlayerJoin', (player) => {
  console.log(`Player joined: ${player.username}`);
});

client.on('onPlayerLeft', (player) => {
  console.log(`Player left: ${player.username}`);
});

client.on('onStateUpdate', (players) => {
  console.log(`Received state update with ${Object.keys(players).length} players`);
});

client.on('onError', (error) => {
  console.error(`Error: ${error}`);
});

// Connect to the server
client.connect().catch(error => {
  console.error('Failed to connect:', error);
});
```

### Using with React

```typescript
import React, { useEffect, useState } from 'react';
import PlaynetClient, { Player } from '@pl8net/client';

const MultiplayerGame = () => {
  const [client] = useState(() => new PlaynetClient('ws://localhost:8081/ws'));
  const [connected, setConnected] = useState(false);
  const [authenticated, setAuthenticated] = useState(false);
  const [players, setPlayers] = useState<Player[]>([]);
  
  useEffect(() => {
    // Set up event handlers
    client.on('onConnect', () => setConnected(true));
    client.on('onDisconnect', () => {
      setConnected(false);
      setAuthenticated(false);
    });
    client.on('onAuthenticated', () => setAuthenticated(true));
    client.on('onStateUpdate', (playersMap) => {
      setPlayers(Object.values(playersMap));
    });
    
    // Connect to the server
    client.connect().catch(console.error);
    
    // Cleanup on unmount
    return () => {
      client.disconnect();
    };
  }, [client]);
  
  const handleLogin = (username: string) => {
    if (connected) {
      client.authenticate(username);
    }
  };
  
  const handleMove = (x: number, y: number, z: number) => {
    if (authenticated) {
      client.updatePosition(
        { x, y, z },
        { x: 0, y: 0, z: 0 }
      );
    }
  };
  
  return (
    <div>
      {/* Your game UI */}
    </div>
  );
};
```

## API

### `PlaynetClient`

The main class for interacting with the Playnet server.

#### Constructor

```typescript
constructor(serverUrl: string)
```

- `serverUrl`: The WebSocket URL of the Playnet server (e.g., `ws://localhost:8081/ws`)

#### Methods

- `connect(): Promise<void>` - Connects to the Playnet server
- `disconnect(): void` - Disconnects from the server
- `authenticate(username: string): boolean` - Authenticates with the given username
- `updatePosition(position: Position, rotation: Rotation): boolean` - Updates the player's position and rotation
- `isConnected(): boolean` - Checks if the client is connected
- `isAuthenticated(): boolean` - Checks if the client is authenticated
- `getClientId(): string | null` - Gets the client ID
- `getPlayerId(): string | null` - Gets the player ID
- `getPlayer(playerId: string): Player | null` - Gets a player by ID
- `getAllPlayers(): Player[]` - Gets all connected players
- `configureReconnection(enabled?: boolean, maxAttempts?: number, initialDelay?: number): void` - Configures automatic reconnection

#### Events

Subscribe to events using the `on` method:

```typescript
on<K extends keyof PlaynetCallbacks>(event: K, callback: PlaynetCallbacks[K]): void
```

Available events:

- `onConnect(clientId: string)` - Called when connected to the server
- `onDisconnect(code?: number, reason?: string)` - Called when disconnected
- `onAuthenticated(playerId: string)` - Called when authenticated
- `onPlayerJoin(player: Player)` - Called when a player joins
- `onPlayerLeft(player: Player)` - Called when a player leaves
- `onStateUpdate(players: Record<string, Player>)` - Called when a state update is received
- `onError(error: string)` - Called when an error occurs

### Types

#### `Position`

```typescript
interface Position {
  x: number;
  y: number;
  z: number;
}
```

#### `Rotation`

```typescript
interface Rotation {
  x: number;
  y: number;
  z: number;
}
```

#### `Player`

```typescript
interface Player {
  id: string;
  username: string;
  position: Position;
  rotation: Rotation;
}
```

## Message Protocol

The Playnet client uses the following message types:

### Client to Server

- `Auth` - Authentication request
- `Position` - Position update

### Server to Client

- `Connected` - Connection confirmation
- `AuthResponse` - Authentication response
- `UserJoin` - User joined notification
- `UserLeft` - User left notification
- `State` - World state update
- `Error` - Error message

For detailed information about the protocol, see the [Playnet WebSocket Protocol Documentation](https://github.com/pl8net/playnet/blob/master/docs/websocket.md) [TODO].

## Building and Testing

```bash
# Install dependencies
npm install

# Build the library
npm run build

# Run tests
npm test

# Development with auto-rebuilding
npm run dev
```

## Publishing

```bash
# Test publication (dry run)
npm run publish:dry-run

# Publish to npm registry (official release)
npm run release

# Publish a beta version
npm run publish:beta
```

## License

MIT