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

@flowaitec/corex-js

v0.0.1

Published

A biblioteca Corex é um cliente Node.js para comunicação com servidores Corex através de conexões TCP, oferecendo funcionalidades de mensageria, canais, serviços e eventos em tempo real.

Readme

Documentação da Biblioteca Corex

Visão Geral

A biblioteca Corex é um cliente Node.js para comunicação com servidores Corex através de conexões TCP, oferecendo funcionalidades de mensageria, canais, serviços e eventos em tempo real.

Instalação e Importação

import { Corex, flowaitec } from '@flowaitec/corex-js';

// Ou criar uma nova instância
const client = Corex();

Classe Principal: Corex

Conectando ao Servidor

// URL de conexão: fxp://username:password@host:port
await client.connect('fxp://user:pass@localhost:4222');

// Eventos de conexão
client.on('connected', () => {
  console.log('Conectado ao servidor');
});

client.on('error', (err) => {
  console.error('Erro de conexão:', err);
});

client.on('close', () => {
  console.log('Conexão fechada');
});

Métodos Principais

connect(url: string): Promise<void>

Estabelece conexão com o servidor Corex.

channel(name: string): CorexChannel

Cria e retorna um canal com o nome especificado.

team(name: string): CorexTeam

Cria e retorna um time/grupo.

close(): void

Fecha a conexão com o servidor.

Propriedades

  • id: string - ID do cliente atribuído pelo servidor
  • connected: boolean - Status da conexão

Classe CorexChannel

Gerenciamento de Canais

const channel = client.channel('meu-canal');

// Criar canal
await channel.create('Descrição do canal');

// Editar canal
await channel.edit('Nova descrição');

// Remover canal
await channel.remove();

// Obter informações
const info = await channel.info();

Publicação e Assinatura

Publicar Mensagens

await channel.publish('meu-topico', Buffer.from('Mensagem de exemplo'));

Assinar Tópicos

await channel.subscribe('meu-topico', (topic, message) => {
  console.log(`Mensagem recebida no tópico ${topic}:`, message.toString());
});

Serviços e Requisições

Criar Serviço

await channel.service('meu-servico', (message, reply) => {
  // Processar requisição
  const response = Buffer.from('Resposta do serviço');
  reply(null, response); // Sem erro
  // ou: reply(new Error('Erro no serviço'));
});

Fazer Requisição

try {
  const response = await channel.request(
    'meu-servico', 
    Buffer.from('Dados da requisição'),
    5000 // timeout em ms
  );
  console.log('Resposta:', response.toString());
} catch (error) {
  console.error('Erro na requisição:', error);
}

Métodos de Consulta

// Listar serviços disponíveis
const services = await channel.getServices();

// Listar eventos
const events = await channel.getEvents();

// Listar canais
const channels = await channel.list();

Sub-canais Especializados

// WebSocket
channel.ws().emit('evento', Buffer.from('dados'));

// MQTT
channel.mqtt().publish('topico', Buffer.from('mensagem'));

// Redis
channel.redis().set('chave', Buffer.from('valor'));

// Dispositivos
channel.device();

// Aplicativos
channel.app();

// Scripts
channel.script();

Classe CorexTeam

Gerenciamento de Times

const team = client.team('meu-time');

// Criar time
await team.create();

// Editar time
await team.edit();

// Listar times
await team.list();

// Remover time
await team.remove();

Gerenciamento de Membros

const member = team.member();

// Adicionar membro
await member.create();

// Editar membro
await member.edit();

// Listar membros
await member.list();

// Remover membro
await member.remove();

Gerenciamento de Canais do Time

const teamChannel = team.channel();

// Conectar canal ao time
await teamChannel.connect('nome-canal');

// Desconectar canal
await teamChannel.disconnect('nome-canal');

// Listar canais conectados
await teamChannel.list();

Tratamento de Mensagens do Servidor

Tipos de Comandos Suportados

  • INFO: Informações do servidor e identificação do cliente
  • MSG: Mensagens publicadas em tópicos
  • CH_REQ: Requisições para serviços de canal
  • RES/AUTH/CH_RES: Respostas para requisições
  • OK: Confirmação de operação
  • ERROR: Erros do servidor
  • PING/PONG: Manutenção da conexão

Exemplo Completo de Uso

import { Corex } from '@flowaitec/corex-js';

async function exemplo() {
  const client = Corex();
  
  try {
    // Conectar
    await client.connect('fxp://usuario:senha@localhost:4222');
    
    // Criar canal
    const canal = client.channel('canal-exemplo');
    await canal.create('Canal de exemplo');
    
    // Assinar tópico
    await canal.subscribe('notificacoes', (topico, mensagem) => {
      console.log(`Notificação: ${mensagem.toString()}`);
    });
    
    // Criar serviço
    await canal.service('calculadora', (dados, responder) => {
      const numero = parseInt(dados.toString());
      const resultado = numero * 2;
      responder(null, Buffer.from(resultado.toString()));
    });
    
    // Publicar mensagem
    await canal.publish('notificacoes', Buffer.from('Olá mundo!'));
    
    // Fazer requisição
    const resposta = await canal.request('calculadora', Buffer.from('5'), 3000);
    console.log(`Resultado: ${resposta.toString()}`); // "10"
    
  } catch (error) {
    console.error('Erro:', error);
  } finally {
    client.close();
  }
}

exemplo();

Tratamento de Erros

A biblioteca utiliza Promises e callbacks com tratamento de erro consistente:

try {
  await channel.publish('topico', dados);
} catch (error) {
  console.error('Falha ao publicar:', error.message);
}

// Em callbacks de serviço
channel.service('servico', (mensagem, reply) => {
  try {
    // Processamento
    reply(null, resultado);
  } catch (error) {
    reply(error); // Envia erro para o cliente
  }
});

Timeouts

Todas as operações de requisição suportam timeout:

// Timeout de 5 segundos
const resposta = await channel.request('servico', dados, 5000);

Buffer como Formato de Dados

Todos os dados são transmitidos como Buffers, permitindo flexibilidade no formato:

// Texto
Buffer.from('Texto simples', 'utf8');

// JSON
Buffer.from(JSON.stringify({ chave: 'valor' }));

// Dados binários
Buffer.from(arrayBuffer);

Esta documentação cobre os principais aspectos da biblioteca Corex para implementação de clientes robustos de mensageria em tempo real.