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 🙏

© 2026 – Pkg Stats / Ryan Hefner

@sitio-io/berrante

v0.1.0

Published

Lightweight JavaScript library for sending system notifications directly to Telegram. No servers, no dashboards, just alerts.

Readme

Berrante 🛠️ Instrumento | Telegram Telemetry

Lightweight JavaScript library for sending system notifications directly to Telegram. No servers, no dashboards, just alerts.

Quick Start

npm install @sitio-io/berrante
import { berrante } from '@sitio-io/berrante';

berrante.init({
  botToken: process.env.BERRANTE_BOT_TOKEN,
  chatId: process.env.BERRANTE_CHAT_ID,
});

berrante.info('Hello from Berrante!');

O que é?

Biblioteca JavaScript zero-dependency que envia notificações do seu código diretamente para um chat do Telegram via Bot API. Ideal para projetos pequenos que precisam de telemetria imediata sem infraestrutura complexa.

Use cases:

  • Erros em workers/background jobs
  • Alertas de falha em rotas críticas
  • Notificações de "processo iniciou/finalizou"
  • Debugging em produção (sem acesso ao terminal)

Instalação

npm install @sitio-io/berrante

Configuração

Crie seu bot no @BotFather, copie o token, e descubra seu chat_id (envie /start para o bot e acesse https://api.telegram.org/bot<TOKEN>/getUpdates).

import { berrante } from '@sitio-io/berrante';

berrante.init({
  botToken: process.env.BERRANTE_BOT_TOKEN,
  chatId: process.env.BERRANTE_CHAT_ID,
  project: 'minha-api', // opcional: aparece em todas mensagens
  disabled: process.env.NODE_ENV === 'test' // opcional: silencia em testes
});

API

berrante.init(config)

Configuração global. Chame uma vez no entrypoint da aplicação.

| Parâmetro | Tipo | Obrigatório | Descrição | |-----------|------|-------------|-----------| | botToken | string | Sim | Token do BotFather | | chatId | string | Sim | ID do chat/grupo (ex: -100123456 ou 123456789) | | project | string | Não | Prefixo nas mensagens (ex: [minha-api]) | | disabled | boolean | Não | Desativa envios (default: false) | | timeout | number | Não | Timeout do fetch em ms (default: 5000) | | debug | boolean | Não | Loga no console quando enviar/receber erro (default: false) |

berrante.error(message, meta?)

Envia notificação de erro crítico. 🔴

berrante.error('Falha na conexão com DB', {
  error: err.message,
  stack: err.stack
});

berrante.warn(message, meta?)

Envia alerta de atenção. 🟡

berrante.warn('Job demorou mais que o esperado', {
  duration: 45000
});

berrante.info(message, meta?)

Envia notificação informativa. 🔵

berrante.info('Webhook recebido da Stripe', {
  eventId: evt.id
});

berrante.success(message, meta?)

Envia notificação de sucesso. 🟢

berrante.success('Deploy finalizado', {
  commit: 'a1b2c3d'
});

berrante.send(level, message, meta?)

Método avançado para quando o nível precisa ser dinâmico.

const level = severity > 5 ? 'error' : 'warn';
berrante.send(level, 'Anomalia detectada', { severity });

Parâmetros:

  • level: 'error' | 'warn' | 'info' | 'success' — define o emoji (🔴 🟡 🔵 🟢)
  • message: string — texto principal (limite 4096 chars)
  • meta: object — dados extras (serão formatados como <pre>JSON</pre> no Telegram)

berrante.silence()

Desabilita envios temporariamente (útil para manutenção).

berrante.wake()

Reativa os envios.

Uso Prático

1. Capturando erros em Workers/Queues

async function processPayment(job) {
  try {
    await executePayment(job.data);
    berrante.success('Pagamento processado', { id: job.id });
  } catch (error) {
    berrante.error('Falha no worker de pagamento', {
      jobId: job.id,
      error: error.message,
      attempts: job.attemptsMade
    });
    throw error; // rethrow para retry
  }
}

2. Monitorando rotas específicas (Express)

import express from 'express';

// Middleware de erro global
app.use((err, req, res, next) => {
  berrante.error(`Erro em ${req.method} ${req.path}`, {
    error: err.message,
    user: req.user?.id,
    body: req.body
  });

  res.status(500).send('Internal Server Error');
});

// Notificação de rota crítica chamada
app.post('/webhook/payment', async (req, res) => {
  berrante.info('Webhook de pagamento recebido', {
    provider: req.body.provider,
    amount: req.body.amount
  });

  await processWebhook(req.body);
  res.json({ received: true });
});

3. Alerta de falha em cron jobs

import cron from 'node-cron';

cron.schedule('0 9 * * *', async () => {
  try {
    await generateDailyReport();
    berrante.success('Relatório diário gerado');
  } catch (error) {
    berrante.error('Falha no job diário', { error: error.message });
  }
});

4. Com Async Context (sem poluir o código principal)

// Em um arquivo de config
export const telemetry = berrante;

// Em qualquer lugar do código
import { telemetry } from './config';

function criticalFunction() {
  // ... lógica ...
  telemetry.info('Processo X executado');
}

Tratamento de Erros

A lib nunca lança exceções para não quebrar sua aplicação. Se o Telegram estiver fora do ar, o erro é logado no console (stderr) mas silenciado.

Para debug, habilite modo verbose:

berrante.init({
  botToken: 'xxx',
  chatId: 'xxx',
  debug: true // loga no console quando enviar/receber erro
});

Limitações

  • Rate limit: Respeita automaticamente 1 msg/segundo (burst) e 20 msgs/minuto (Telegram flood control). Mensagens excedentes são enfileiradas e enviadas gradualmente.
  • Tamanho: Mensagens > 4096 caracteres são truncadas.
  • Síncrono: Os métodos são async mas não bloqueantes (fire-and-forget). Se precisar confirmar envio: await berrante.error(...).

Do Campo

"O berrante serve para avisar, não para fazer barulho o dia todo."

Use error para o que quebra, warn para o que desperta preocupação, e info com moderação para não silenciar o que é importante.


Publicação

npm

  1. Certifique-se de estar logado: npm login
  2. Publique: npm publish --access public

GitHub Packages

Para publicar no GitHub Packages, configure o campo publishConfig no seu package.json para apontar para o seu registry do GitHub e siga as instruções da documentação do GitHub para autenticação via ~/.npmrc.