npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@sofya-sdk/react

v1.1.0

Published

React hooks for Sofya SDK

Downloads

16

Readme

@sofya-sdk/react

React hooks for Sofya SDK - Plug-and-play integration for real-time EventRooms messaging.

Installation

pnpm add @sofya-sdk/react
# or
npm install @sofya-sdk/react
# or
yarn add @sofya-sdk/react

Hooks

useCanal()

Creates a canal (room) via the backend API. Used by the receptor (desktop) side.

import { useCanal } from '@sofya-sdk/react';

function Receptor() {
  const { canalId, qrCodeUrl, qrCodeBucketLink, loading, error } = useCanal({
    backendUrl: 'https://api.sofya.app',
    apiKey: process.env.REACT_APP_API_KEY || 'your-api-key',
    autoCreate: true, // Auto-create on mount (default: true)
  });

  if (loading) return <div>Creating canal...</div>;
  if (error) return <div>Error: {error.message}</div>;

  return <QRCode value={qrCodeUrl} />;
}

Options:

  • backendUrl (string, required) - Backend API base URL
  • apiKey (string, required) - API key for authentication (x-api-key header)
  • autoCreate (boolean, optional) - Auto-create canal on mount (default: true)

Returns:

  • canalId - Canal ID
  • qrCodeUrl - PWA URL with canal parameter
  • qrCodeBucketLink - QR code image URL from bucket
  • messagingEndpoint - Messaging WebSocket endpoint derived from the backend contract
  • contract - Normalized backend contract (STT, QR code assets, EventRooms)
  • loading - Loading state
  • error - Error if any
  • createCanal() - Manually create canal
  • reset() - Reset state

Tip: combine the returned contract with buildEventRoomsConnection from @sofya-sdk/qr to build the WebSocket connection parameters automatically.


useCanalConfig()

Fetches canal configuration from the backend. Used by the emissor (mic) side after scanning QR code.

import { useCanalConfig } from '@sofya-sdk/react';
import { parseCanalFromQR } from '@sofya-sdk/qr';

function Emissor() {
  const canalId = parseCanalFromQR(window.location.href);

  const { config, loading, error } = useCanalConfig({
    canalId,
    backendUrl: 'https://api.sofya.app',
  });

  if (loading) return <div>Loading config...</div>;
  if (error) return <div>Error: {error.message}</div>;

  return <div>STT: {config?.sttEndpoint}</div>;
}

Options:

  • canalId (string | null, required) - Canal ID from QR code
  • backendUrl (string, required) - Backend API base URL
  • authToken (string, optional) - Authentication token
  • autoFetch (boolean, optional) - Auto-fetch on mount (default: true)

Returns:

  • config - Canal configuration (sttEndpoint, messagingEndpoint, canalId, contract)
  • loading - Loading state
  • error - Error if any
  • fetchConfig() - Manually fetch config
  • reset() - Reset state

The returned config.contract mirrors the backend contract and can also be passed to buildEventRoomsConnection for the emissor role.


useEventRooms()

Main hook for EventRooms WebSocket connection. Works for both receptor and emissor roles.

import { useEventRooms, useRoomEvent } from '@sofya-sdk/react';

function MyComponent() {
  const {
    connectionState,
    connected,
    client,
    presence,
    error,
    sendEvent,
    connect,
    disconnect,
  } = useEventRooms({
    url: 'wss://messaging.sofya.app/ws',
    canalId: 'CANAL123',
    role: 'desktop', // or 'mic'
    autoConnect: true,
    autoReconnect: true,
    maxReconnectAttempts: 5,
  });

  // Listen to specific events
  useRoomEvent(client, 'transcription', (payload) => {
    console.log('Transcription:', payload);
  });

  // Send event
  const handleClick = () => {
    sendEvent('transcription', { text: 'Hello', partial: false });
  };

  return (
    <div>
      <p>Status: {connectionState}</p>
      <button onClick={handleClick}>Send Event</button>
      <p>Clients in room: {presence?.clientsLocal || 0}</p>
    </div>
  );
}

Options:

  • url (string, required) - WebSocket URL
  • canalId (string | null, required) - Canal (room) ID
  • role ('desktop' | 'mic', required) - Client role
  • autoConnect (boolean, optional) - Auto-connect on mount (default: true)
  • autoReconnect (boolean, optional) - Auto-reconnect on disconnect (default: true)
  • maxReconnectAttempts (number, optional) - Maximum reconnection attempts (default: 5)

Returns:

  • connectionState - Current connection state ('disconnected' | 'connecting' | 'connected' | 'reconnecting' | 'failed')
  • connected - Boolean flag for connected state
  • presence - Latest presence information
  • error - Latest error message
  • client - EventRooms client instance (for use with useRoomEvent)
  • sendEvent(event, payload) - Send event to room
  • connect() - Manually connect
  • disconnect() - Manually disconnect

useRoomEvent()

Listen to specific events from EventRooms. Must be used with an EventRooms client instance.

import { useRoomEvent } from '@sofya-sdk/react';

function MyComponent({ client }) {
  useRoomEvent(client, 'transcription', (payload) => {
    console.log('Transcription:', payload);
  });

  return <div>Listening to transcription events...</div>;
}

Complete Examples

Receptor (Desktop) - Full Flow

import { useCanal, useEventRooms, useRoomEvent } from '@sofya-sdk/react';
import { generateQRCode } from '@sofya-sdk/qr';
import { useEffect, useState } from 'react';

function Receptor() {
  const [qrDataUrl, setQrDataUrl] = useState<string>('');
  const [transcriptions, setTranscriptions] = useState<string[]>([]);

  // 1. Create canal
  const { canalId, qrCodeUrl, messagingEndpoint, loading: canalLoading } = useCanal({
    backendUrl: 'https://api.sofya.app',
    apiKey: process.env.REACT_APP_API_KEY || 'your-api-key',
  });

  // 2. Generate QR code
  useEffect(() => {
    if (qrCodeUrl) {
      generateQRCode(qrCodeUrl).then(setQrDataUrl);
    }
  }, [qrCodeUrl]);

  // 3. Connect to EventRooms
  const { connected, client, presence } = useEventRooms({
    url: messagingEndpoint || 'wss://messaging.sofya.app/ws',
    canalId,
    role: 'desktop',
  });

  // 4. Listen to transcription events
  useRoomEvent(client, 'transcription', (payload: any) => {
    setTranscriptions((prev) => [...prev, payload.text]);
  });

  if (canalLoading) return <div>Creating canal...</div>;

  return (
    <div>
      <h1>Receptor</h1>

      {/* QR Code */}
      {qrDataUrl && <img src={qrDataUrl} alt="QR Code" />}

      {/* Status */}
      <p>Canal: {canalId}</p>
      <p>Status: {connected ? 'Connected' : 'Disconnected'}</p>
      <p>Clients: {presence?.clientsLocal || 0}</p>

      {/* Transcriptions */}
      <div>
        <h2>Transcriptions</h2>
        {transcriptions.map((text, i) => (
          <div key={i}>{text}</div>
        ))}
      </div>
    </div>
  );
}

Emissor (PWA) - Full Flow

import { useCanalConfig, useEventRooms } from '@sofya-sdk/react';
import { parseCanalFromQR } from '@sofya-sdk/qr';

function Emissor() {
  // 1. Parse canal from URL
  const canalId = parseCanalFromQR(window.location.href);

  // 2. Fetch configuration
  const { config, loading: configLoading } = useCanalConfig({
    canalId,
    backendUrl: 'https://api.sofya.app',
  });

  // 3. Connect to EventRooms
  const { connected, sendEvent } = useEventRooms({
    url: config?.messagingEndpoint || '',
    canalId,
    role: 'mic',
  });

  const handleSendTranscription = () => {
    sendEvent('transcription', {
      text: 'Hello from emissor',
      partial: false,
    });
  };

  if (configLoading) return <div>Loading configuration...</div>;
  if (!config) return <div>Invalid canal</div>;

  return (
    <div>
      <h1>Emissor</h1>
      <p>Canal: {canalId}</p>
      <p>Status: {connected ? 'Connected' : 'Disconnected'}</p>
      <button onClick={handleSendTranscription} disabled={!connected}>
        Send Transcription
      </button>
    </div>
  );
}

TypeScript

All hooks are fully typed. Import types from the package:

import type {
  UseCanalResult,
  UseCanalConfigResult,
  UseEventRoomsResult,
  EventMessage,
  ConnectionState,
} from '@sofya-sdk/react';

License

ISC