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

@quickly-desk/sdk

v0.0.2

Published

SDK para integração fácil do Quickly Desk em aplicações React e React Native

Readme

Quickly Desk SDK

SDK for easy integration of Quickly Desk in React and React Native applications.

Installation

npm install @quickly-desk/sdk
# or
yarn add @quickly-desk/sdk

Usage

React (Web)

import React, { useMemo } from "react";
import {
  QuicklyDeskProvider,
  useCustomerAuth,
  useChatsWithWebSocket,
} from "@quickly-desk/sdk";

function App() {
  const config = useMemo(
    () => ({
      publicKey: "your-public-key",
      customerReference: "unique-customer-id",
      customerName: "Customer Name",
      metadata: {
        phone: "11999999999",
        // other optional metadata
      },
    }),
    []
  );

  return (
    <QuicklyDeskProvider config={config}>
      <YourApp />
    </QuicklyDeskProvider>
  );
}

function YourApp() { const { loading, error, signOut } = useCustomerAuth(); const { chats, messages, sendMessage, createChat } = useChatsWithWebSocket();

// Use the hooks as needed return ...; }


### React Native

```tsx
import React, { useMemo } from "react";
import {
  QuicklyDeskProvider,
  useCustomerAuth,
  useChatsWithWebSocket,
} from "@quickly-desk/sdk";

function App() {
  const config = useMemo(
    () => ({
      publicKey: "your-public-key",
      customerReference: "unique-customer-id",
      customerName: "Customer Name",
      metadata: {
        phone: "11999999999",
      },
    }),
    []
  );

  return (
    <QuicklyDeskProvider config={config}>
      <YourApp />
    </QuicklyDeskProvider>
  );
}

Features

  • No caching: The SDK always authenticates when the provider is executed
  • Automatic token refresh: Tokens are automatically refreshed when expired
  • Request queue: Failed requests are queued and retried after token refresh
  • WebSocket support: Real-time chat functionality with WebSocket connections

API

Hooks

useCustomerAuth()

Hook for managing customer authentication.

const { loading, error, signOut } = useCustomerAuth();
  • loading: Loading state during authentication (boolean)
  • error: Error message if authentication fails (string | null)
  • signOut(): Function to sign out manually

useChatsWithWebSocket()

Hook principal para gerenciar chats e mensagens. Gerencia automaticamente a conexão WebSocket com base no ciclo de vida do componente.

Características:

  • ✅ Conecta automaticamente ao WebSocket quando o componente monta
  • ✅ Aguarda a conexão WebSocket estar pronta antes de carregar chats
  • ✅ Chama loadChats() automaticamente após conectar
  • ✅ Desconecta automaticamente quando o componente desmonta (se for o último componente usando)
  • ✅ Usa contador de referências para manter conexão durante navegação entre telas
  • ✅ Proteção contra race conditions e múltiplas chamadas
  • ✅ Tratamento robusto de erros e timeouts
  • ✅ Pode ser usado em múltiplos componentes simultaneamente
const {
  chats,
  currentChat,
  messages,
  participants,
  ws,
  loading,
  sendMessageLoading,
  createChatLoading,
  loadChats,
  loadChatHistory,
  sendMessage,
  createChat,
} = useChatsWithWebSocket();

Propriedades retornadas:

  • chats: Lista de chats (Chat[])
  • currentChat: Chat atual selecionado (Chat | null)
  • messages: Mensagens do chat atual (ChatMessage[])
  • participants: Participantes ativos por chat ID ({ [id_chat: string]: { participants: string[]; typingStatus: { [id_user: string]: string } } })
  • ws: Conexão WebSocket (WebSocket | null)
  • loading: Estado de carregamento (boolean)
  • sendMessageLoading: Estado de envio de mensagem (boolean)
  • createChatLoading: Estado de criação de chat (boolean)
  • loadChats(): Carrega lista de chats
  • loadChatHistory(id_chat): Carrega histórico de um chat específico
  • sendMessage(id_chat, content): Envia uma mensagem
  • createChat(): Cria um novo chat

Exemplos de uso:

// Tela de listagem de chats
function ChatsListScreen() {
  const { chats, loading, loadChats, createChat } = useChatsWithWebSocket();
  
  // WebSocket conecta automaticamente ao montar
  // loadChats() é chamado automaticamente após conexão
  // WebSocket desconecta automaticamente ao desmontar
  
  const onRefresh = async () => {
    await loadChats(); // Pode ser chamado manualmente para refresh
  };
  
  return (
    <FlatList
      data={chats}
      renderItem={({ item }) => <ChatListItem chat={item} />}
      onRefresh={onRefresh}
      refreshing={loading}
    />
  );
}

// Tela de chat individual
function ChatScreen({ id_chat }: { id_chat: string }) {
  const { messages, loadChatHistory, sendMessage, loading } = useChatsWithWebSocket();
  
  // Pode usar o mesmo hook - conexão WebSocket é compartilhada
  // Não precisa gerenciar conexão manualmente
  
  useEffect(() => {
    if (id_chat) {
      loadChatHistory(id_chat);
    }
  }, [id_chat, loadChatHistory]);
  
  return (
    <View>
      <FlatList data={messages} renderItem={({ item }) => <MessageBubble message={item} />} />
      <MessageInput onSend={(content) => sendMessage(id_chat, content)} />
    </View>
  );
}

Types

interface Chat {
  id_chat: string;
  id_tenant: string;
  id_customer: string;
  created_at?: string;
  updated_at?: string;
  customer_name?: string;
  last_message?: string | null;
  last_message_time?: string | null;
  unread_count?: number;
}

interface ChatMessage {
  id_chat_message: number;
  id_chat: string;
  sender: string;
  id_sender: string;
  read: boolean;
  content: string;
  created_at?: string;
}

Configuration

SDKConfig

interface SDKConfig {
  apiUrl?: string; // API URL (optional)
  wsUrl?: string; // WebSocket URL (optional)
  publicKey: string; // Public key (required)
  customerReference: string; // Unique customer ID (required)
  customerName: string; // Customer name (required)
  metadata?: Record<string, any>; // Optional metadata
}

Authentication Flow

The SDK automatically:

  1. Authenticates when the provider is executed (calls /auth/customer)
  2. Stores the token in memory (no persistent storage)
  3. Refreshes the token automatically when it expires
  4. Queues failed requests during token refresh and retries them after refresh

Edge Cases e Comportamentos

Limites e Validações

  • Tamanho máximo de mensagem: 5000 caracteres
  • Tamanho máximo da fila de requisições: 50 requisições
  • Timeout da fila: 30 segundos
  • Timeout de conexão WebSocket: 10 segundos (padrão)
  • Máximo de tentativas de retry WebSocket: 3 tentativas
  • Máximo de mensagens processadas em memória: 100 IDs

Comportamentos Automáticos

  1. Reconexão WebSocket: O SDK reconecta automaticamente se a conexão fechar inesperadamente (code !== 1000)
  2. Prevenção de duplicatas: Mensagens duplicadas são automaticamente ignoradas usando um Set de IDs processados
  3. Validação de mensagens: Todas as mensagens WebSocket são validadas antes de serem processadas
  4. Retry automático: WebSocket tenta reconectar até 3 vezes com backoff exponencial (1s, 2s, 4s, max 10s)
  5. Limpeza de recursos: Todos os timeouts e listeners são limpos adequadamente ao desmontar componentes

Tratamento de Erros

O SDK classifica erros em tipos específicos:

  • NetworkError: Erros de conexão de rede
  • TimeoutError: Timeouts de requisição ou conexão
  • AuthenticationError: Erros de autenticação
  • ValidationError: Erros de validação de entrada

Múltiplos Componentes

Você pode usar useChatsWithWebSocket em múltiplos componentes simultaneamente:

  • A conexão WebSocket é compartilhada entre todos os componentes
  • Um contador de referências gerencia quando conectar/desconectar
  • A conexão só fecha quando o último componente se desinscreve

Navegação entre Telas

  • Ao navegar da lista de chats para um chat específico, a conexão WebSocket é mantida
  • Ao sair da tela de listagem, a conexão fecha automaticamente
  • Mensagens continuam chegando mesmo quando não está na tela de listagem (se outro componente estiver usando)

Troubleshooting

Para problemas comuns e soluções, consulte TROUBLESHOOTING.md.

License

MIT