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

onilib

v1.0.2

Published

A modular Node.js library for real-time online integration in games and web applications

Downloads

19

Readme

ONILib (Online Integration Library)

🚀 Uma biblioteca Node.js completa para integração online em tempo real para jogos e aplicações web.

A ONILib é uma solução modular e escalável que fornece todos os recursos necessários para criar aplicações online em tempo real, incluindo autenticação, comunicação WebSocket, matchmaking, P2P WebRTC, armazenamento persistente e ferramentas de administração.

✨ Características Principais

  • 🔐 Autenticação Robusta: Suporte a JWT e API Keys com estratégias customizáveis
  • 🔄 Comunicação em Tempo Real: Servidor WebSocket com salas e middlewares
  • 🎮 Sistema de Matchmaking: Filas inteligentes com critérios de pareamento
  • 🔗 Suporte P2P: WebRTC signaling com fallback relay opcional
  • 💾 Armazenamento Flexível: Adaptadores para Memory, SQLite, PostgreSQL e Cloudflare D1/KV
  • 📊 Painel Administrativo: API REST para métricas, sessões e gerenciamento
  • 🧪 Ferramentas de Teste: Harness completo para testes P2P, latência e throughput
  • 🛠️ CLI Integrada: Comandos para scaffolding, desenvolvimento e deploy

🚀 Instalação Rápida

# Instalar globalmente
npm install -g onilib

# Criar novo projeto
onilib init meu-jogo-online
cd meu-jogo-online

# Instalar dependências
npm install

# Iniciar servidor de desenvolvimento
onilib start --dev

📋 Comandos CLI

| Comando | Descrição | |---------|----------| | onilib init [nome] | Cria scaffolding inicial do projeto | | onilib start [--dev] | Inicia servidor (--dev para hot reload) | | onilib test | Executa suíte de testes | | onilib test p2p --nodes=N --duration=Xs | Teste de stress P2P | | onilib build | Prepara projeto para produção |

🏗️ Arquitetura Modular

Core Modules

const { NodeOnlineIntegration } = require('onilib');

const noi = new NodeOnlineIntegration({
  // Configuração dos módulos
  auth: { /* configurações de autenticação */ },
  realtime: { /* configurações WebSocket */ },
  storage: { /* configurações de armazenamento */ },
  matchmaking: { /* configurações de matchmaking */ },
  p2p: { /* configurações WebRTC */ },
  admin: { /* configurações do painel admin */ }
});

await noi.start();

Módulos Disponíveis

  • core: Gerenciamento de ciclo de vida e configuração
  • auth: Autenticação JWT e API Key
  • realtime: Servidor WebSocket com salas
  • storage: Adaptadores de armazenamento
  • matchmaking: Sistema de filas e pareamento
  • p2p: Signaling WebRTC
  • admin: API REST para administração

💡 Exemplo Básico

Servidor

const { NodeOnlineIntegration } = require('onilib');

const config = {
  name: 'meu-jogo',
  port: 3000,
  
  auth: {
    jwtSecret: 'seu-secret-jwt',
    apiKeys: ['sua-api-key']
  },
  
  realtime: {
    port: 8080,
    authRequired: true
  },
  
  storage: {
    type: 'sqlite',
    path: './data/game.db'
  },
  
  matchmaking: {
    maxPlayersPerMatch: 2,
    enableSkillMatching: true
  }
};

async function main() {
  const noi = new NodeOnlineIntegration(config);
  await noi.start();
  
  // Obter referências dos módulos
  const realtime = noi.getModule('realtime');
  const matchmaking = noi.getModule('matchmaking');
  
  // Registrar handlers customizados
  realtime.registerHandler('game_action', (client, message) => {
    console.log('Ação do jogo:', message.data);
    
    // Broadcast para outros jogadores na sala
    realtime.broadcastToRoom(client.currentRoom, {
      type: 'player_action',
      data: message.data
    }, client.id);
  });
  
  // Eventos de matchmaking
  matchmaking.on('match:started', (match) => {
    console.log('Partida iniciada:', match.id);
    
    // Criar sala dedicada para a partida
    const roomId = `match_${match.id}`;
    
    for (const player of match.players) {
      realtime.joinRoom(player.client, roomId);
      realtime.sendToClient(player.client, {
        type: 'game_start',
        data: { matchId: match.id, roomId }
      });
    }
  });
}

main().catch(console.error);

🔧 Configuração

Edit noi.config.js to customize your application settings:

  • Authentication: Configure JWT secrets and API keys
  • WebSocket: Set ports and connection limits
  • Storage: Choose between memory, SQLite, or PostgreSQL
  • Matchmaking: Configure queue settings and match criteria
  • P2P: Set up WebRTC STUN/TURN servers

📡 API WebSocket

Mensagens de Autenticação

// Autenticação com API Key
{
  type: 'auth',
  data: {
    strategy: 'apikey',
    credentials: { apiKey: 'sua-api-key' }
  }
}

// Autenticação com JWT
{
  type: 'auth',
  data: {
    strategy: 'jwt',
    credentials: { token: 'seu-jwt-token' }
  }
}

Mensagens de Salas

// Entrar em sala
{
  type: 'join_room',
  data: { roomId: 'lobby' }
}

// Sair de sala
{
  type: 'leave_room',
  data: { roomId: 'lobby' }
}

Mensagens de Matchmaking

// Entrar na fila
{
  type: 'join_queue',
  data: {
    queueType: 'ranked',
    criteria: { skill: 1200, region: 'BR' }
  }
}

// Aceitar partida
{
  type: 'accept_match',
  data: { matchId: 'match-123' }
}

Admin REST API

Access the admin panel at http://localhost:3001:

  • GET /health - Health check
  • GET /api/system/stats - System statistics
  • GET /api/realtime/clients - Connected clients
  • GET /api/matchmaking/queues - Active queues
  • GET /api/p2p/rooms - P2P rooms

🧪 Testes

Executar Testes

# Todos os testes
npm test

# Testes específicos
npm test -- --testNamePattern="Auth Module"

# Testes P2P com múltiplos nós
onilib test p2p --nodes=10 --duration=60s

# Teste de carga
onilib test load --connections=100 --duration=30s

🚀 Deploy

Railway/Render

# Preparar para deploy
onilib build

# Variáveis de ambiente necessárias
export NODE_ENV=production
export JWT_SECRET=seu-secret-super-seguro
export API_KEY=sua-api-key-producao
export STORAGE_TYPE=postgres
export DATABASE_URL=sua-connection-string

Environment Variables

  • NODE_ENV - Environment (development/production)
  • PORT - HTTP server port
  • WS_PORT - WebSocket server port
  • JWT_SECRET - JWT signing secret
  • API_KEY - Default API key
  • STORAGE_TYPE - Storage adapter (memory/sqlite/postgres)
  • STORAGE_PATH - Database file path (for SQLite)

License

MIT