Pear API Base Class (Holepunch)

1.30.0 · active · verified Tue Apr 21

The `pear-api` package provides the foundational base class for interacting with the Pear API, which is part of the Holepunch peer-to-peer (P2P) runtime and development platform. Currently at version 1.30.0, this library enables developers to build P2P applications, particularly focusing on User Interface integrations by abstracting complex underlying P2P mechanisms. The Pear ecosystem is actively maintained, with regular updates to its 1.x branch and a significant transition underway to a version 2, which introduces notable breaking changes and a shift towards modern JavaScript module standards. Key differentiators include its focus on enabling local-first, offline-first P2P applications and its design for extensibility within UI environments like Electron.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to extend the `PearAPI` base class to create a custom P2P application API, handle connection, and publish data, including error handling and simulated asynchronous operations.

import { PearAPI } from 'pear-api';

interface MyApiOptions {
  authToken: string;
  appId: string;
}

interface MyP2PData {
  id: string;
  message: string;
  timestamp: number;
}

class MyPearAppAPI extends PearAPI {
  private token: string;
  private appId: string;

  constructor(options: MyApiOptions) {
    super(); // Initialize the base PearAPI class
    this.token = options.authToken;
    this.appId = options.appId;
    console.log(`MyPearAppAPI initialized for app: ${this.appId}`);
  }

  async connect(): Promise<boolean> {
    console.log('Attempting to connect to Pear network...');
    // Simulate P2P network connection logic
    await new Promise(resolve => setTimeout(resolve, 1000));
    if (!this.token) {
      console.error('Authentication token is missing.');
      return false;
    }
    console.log('Successfully connected to Pear network.');
    return true;
  }

  async publishData(data: MyP2PData): Promise<void> {
    if (!(await this.connect())) {
      throw new Error('Failed to connect, cannot publish data.');
    }
    console.log(`Publishing data [${data.id}]: ${data.message} at ${new Date(data.timestamp).toISOString()}`);
    // Simulate data publishing to the P2P network
    await new Promise(resolve => setTimeout(resolve, 500));
    console.log('Data published.');
  }

  static async createAndRun(token: string): Promise<MyPearAppAPI> {
    const api = new MyPearAppAPI({ authToken: token, appId: 'my-p2p-app' });
    const connected = await api.connect();
    if (connected) {
      await api.publishData({ id: 'msg-1', message: 'Hello P2P world!', timestamp: Date.now() });
    }
    return api;
  }
}

// Example usage with a dummy token
MyPearAppAPI.createAndRun(process.env.PEAR_AUTH_TOKEN ?? 'dummy_auth_token_123')
  .then(() => console.log('Pear application flow completed.'))
  .catch(error => console.error('Pear application error:', error.message));

view raw JSON →