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

@seedgrid/pulse-subscriber-react

v3.0.0

Published

SDK de referência (React + TypeScript) para assinar o SeedGrid Pulse: conecta no WebSocket, assina canais/grupos, recebe mensagens e envia ack. Protocolo realtime v1.

Readme

@seedgrid/pulse-subscriber-react

SDK de referência (React + TypeScript) para assinar o SeedGrid Pulse: conecta no WebSocket, assina canais/grupos, recebe mensagens em tempo real, confirma recebimento (ack) e reporta o resultado de execução (result, com DLQ/retry). Implementa o contrato PulseSubscriber do PULSE_SDK_PLAN.md sobre o protocolo realtime v1 (ver PROTOCOL.md).

Entrega dois níveis:

  • Core framework-agnóstico — PulseSubscriberClient (funciona em qualquer ambiente com WebSocket).
  • Camada React — hook usePulseSubscriber + PulseProvider opcional.

O que é

Um cliente tipado que fala exatamente o protocolo do Pulse:

handshake (account key)  →  connected  →  subscribe  →  subscribed
                                              ↓
                        message  →  ack (recebido)  →  processa  →  result (execução)
  • autenticação somente no handshake (a identidade da conexão é o account_id resolvido pela chave; o cliente nunca declara userId);
  • reconexão automática (fixa ou exponencial, com jitter);
  • replay de backlog ao reconectar (a assinatura é reenviada e o servidor reentrega o que ficou pendente);
  • ack explícito e idempotente (confirma o RECEBIMENTO);
  • reportResult para reportar o RESULTADO DE EXECUÇÃO (success / retryable / permanent) — a única via que leva a completed ou à DLQ;
  • deduplicação opcional por messageId (transactional inbox) para o at-least-once do Pulse;
  • callbacks de estado, incluindo erro de autenticação.

Quando usar

  • app React (web) que precisa reagir a eventos do Pulse em tempo real;
  • qualquer runtime JS/TS (Node, Deno, Electron, React Native) via o core — use import { PulseSubscriberClient } from "@seedgrid/pulse-subscriber-react/core".

Quando NÃO usar

  • para publicar mensagens: isso é papel do PulsePublisher (server-side, usa a chave project da conta). Este SDK só assina/consome.
  • para administrar contas/chaves: isso vive dentro do pulse / pulse-ui.
  • não embarque nenhuma chave no browser: lá a conexão é com token curto (getToken).

Instalação

npm install @seedgrid/pulse-subscriber-react
# peer deps (apenas para a camada React):
npm install react react-dom

Detalhes em INSTALLATION.md.

Quickstart (React)

import { usePulseSubscriber } from "@seedgrid/pulse-subscriber-react";

function Inbox() {
  const { messages, connectionState, ack } = usePulseSubscriber({
    // O token vem do SEU backend (que o pede ao Pulse para o usuário da sessão).
    // Nenhuma chave no front.
    getToken: async () => (await fetch("/api/realtime/connect", { method: "POST" })).json(),
    subscription: { channels: ["orders"], groups: ["tenant:15"] },
    autoAck: false,
  });

  return (
    <div>
      <span>status: {connectionState}</span>
      <ul>
        {messages.map((m) => (
          <li key={m.messageId}>
            {m.event}
            {m.requiresAck && (
              <button onClick={() => ack({ messageId: m.messageId })}>ack</button>
            )}
          </li>
        ))}
      </ul>
    </div>
  );
}

⚠️ Autenticação no browser: o servidor Pulse atual aceita a account key apenas via header Authorization: Bearer no handshake — e o WebSocket nativo do navegador não envia headers. Em produção web, coloque um reverse-proxy same-origin que injeta esse header (recomendado), ou rode o core em um runtime que suporta headers (Node ws, React Native, Electron). Veja CONFIGURATION.md e SECURITY.md.

Conceitos centrais

| Conceito | Descrição | |----------|-----------| | account key | credencial da conexão. Resolve o account_id no handshake. NÃO é credencial de publicação. | | channel | categoria funcional da mensagem (orders, finance, ...). | | group | agrupamento lógico (tenant:15) para entrega por grupo. | | ack | confirma o RECEBIMENTO de uma entrega (mensagem → delivered). | | result | reporta o RESULTADO DE EXECUÇÃO (success/retryable/permanent); leva a completed ou à DLQ. | | replay | reentrega de pendências ao (re)assinar após reconexão. | | dedup | deduplicação por messageId (transactional inbox) contra o at-least-once. |

API pública (resumo)

Core — PulseSubscriberClient

// Opcional: liga a deduplicação por messageId (transactional inbox).
new PulseSubscriberClient({ processedStore: new InMemoryProcessedStore() });

connect(input: ConnectInput): Promise<void>;
subscribe(input: SubscribeInput): Promise<void>;
ack(input: AckInput): Promise<void>;                                  // RECEBIMENTO
reportResult(messageId: string, result: ExecutionResult): Promise<void>; // EXECUÇÃO
disconnect(): Promise<void>;
onMessage(handler): Unsubscribe;
onStateChange(handler): Unsubscribe;
onError(handler): Unsubscribe;         // frames {"type":"error"}
onAcknowledged(handler): Unsubscribe;  // frames {"type":"acknowledged"}

ExecutionResult é uma união discriminada:

type ExecutionResult =
  | { outcome: "success" }
  | { outcome: "retryable"; reason?: string; retryAfterSecs?: number }
  | { outcome: "permanent"; reason: string };

Frames result emitidos na rede:

{ "type": "result", "messageId": "msg_1", "outcome": "success" }
{ "type": "result", "messageId": "msg_1", "outcome": "retryable", "reason": "db down", "retryAfterSecs": 30 }
{ "type": "result", "messageId": "msg_1", "outcome": "permanent", "reason": "invalid payload" }

React — usePulseSubscriber(options) retorna { messages, connectionState, connectionId, accountId, ack, reportResult, subscribe, connect, reconnect, disconnect, clearMessages, client }. Ligue a dedup com a opção dedup: true (store em memória) ou dedup: <ProcessedStore>.

Deduplicação (transactional inbox)

A entrega do Pulse é at-least-once: uma mensagem pode ser reentregue se o ack/result se perdeu ou após um replay de reconexão. Para aplicar o efeito de negócio uma única vez, ative a dedup:

import {
  PulseSubscriberClient,
  InMemoryProcessedStore,      // LRU em memória (efêmero)
  LocalStorageProcessedStore,  // persistente por origem no browser
  type ProcessedStore,         // implemente para IndexedDB/banco (inbox real)
} from "@seedgrid/pulse-subscriber-react/core";

const client = new PulseSubscriberClient({
  processedStore: new InMemoryProcessedStore(),
});

Com a dedup ligada: numa reentrega de um messageId já processado com sucesso, o handler da aplicação é pulado e result: success é re-reportado automaticamente; o id é registrado no store logo após um reportResult(..., { outcome: "success" }). Idealmente o efeito de negócio e o registro do id ocorrem na mesma transação persistente — para isso implemente ProcessedStore sobre seu banco/IndexedDB.

Tipos completos em CONFIGURATION.md.

Matriz de compatibilidade

| Item | Suportado | |------|-----------| | Protocolo Pulse | v1 | | React | 18+ (peer dependency) | | Node | 18+ (via core + ws) | | Módulos | ESM + CJS | | Tipos | TypeScript (declarations incluídas) | | SSR (Next.js/Remix) | sim — conexão só abre no cliente (useEffect) | | Auth no browser | via reverse-proxy que injeta Authorization (ver docs) |

Mapa de documentação

Licença

MIT.