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

@growflowstudio/shopbrain-chat-widget

v1.0.0

Published

Widget chat embeddabile per e-commerce. Si integra nei siti dei clienti tramite un semplice tag script e si connette al backend per fornire assistenza AI ai visitatori.

Readme

ShopBrain Widget

Widget chat embeddabile per e-commerce. Si integra nei siti dei clienti tramite un semplice tag script e si connette al backend per fornire assistenza AI ai visitatori.

Tech Stack

| Tecnologia | Versione | Utilizzo | |------------|----------|----------| | React | 18 | UI Framework | | TypeScript | 5.x | Type Safety | | Vite | 5.x | Build Tool | | Tailwind CSS | 3.x | Styling |

Architettura

packages/widget/
├── src/
│   ├── main.tsx                   # Entry point, window.ShopBrain.init()
│   │
│   ├── core/
│   │   └── Widget.tsx             # Main widget component
│   │
│   ├── components/
│   │   ├── ChatWindow.tsx         # Chat container
│   │   ├── MessageList.tsx        # Messages display
│   │   ├── MessageBubble.tsx      # Single message
│   │   ├── ChatInput.tsx          # Input + send button
│   │   └── TypingIndicator.tsx    # "sta scrivendo..."
│   │
│   ├── hooks/
│   │   ├── useChat.ts             # Chat state management
│   │   ├── useConfig.ts           # Config loading from API
│   │   └── useWebSocket.ts        # Real-time connection
│   │
│   ├── styles/
│   │   └── index.css              # Base styles
│   │
│   └── types/
│       └── index.ts               # TypeScript interfaces
│
├── public/
├── Dockerfile
├── package.json
├── tailwind.config.js
├── tsconfig.json
└── vite.config.ts

Come Funziona

1. Embedding nel Sito E-commerce

Il widget viene caricato tramite un tag script:

<!-- Codice da inserire nel sito del cliente -->
<script src="https://widget.shopbrain.dev/widget.js"></script>
<script>
  ShopBrain.init({
    chatbotId: 'abc123-def456',          // ID chatbot dalla dashboard
    apiUrl: 'https://api.shopbrain.dev' // URL backend (opzionale)
  });
</script>

2. Inizializzazione

Quando lo script viene caricato:

  1. Crea un container <div id="shopbrain-widget-root"> nel body
  2. Renderizza il widget React
  3. Mostra il floating action button (FAB)

3. Apertura Chat

Quando l'utente clicca il FAB:

  1. Apre la finestra di chat
  2. Carica la configurazione del chatbot dall'API
  3. Mostra il messaggio di benvenuto
  4. Inizializza la connessione WebSocket (se disponibile)

4. Conversazione

  1. L'utente scrive un messaggio
  2. Il widget invia al backend via API/WebSocket
  3. Il backend processa con RAG + LLM
  4. La risposta viene streamata in real-time
  5. Se necessario, vengono mostrati prodotti/ordini via componenti custom

Componenti Principali

Widget.tsx

interface WidgetProps {
  chatbotId: string;
  apiUrl?: string;
}

export function Widget({ chatbotId, apiUrl }: WidgetProps) {
  const [isOpen, setIsOpen] = useState(false);

  return (
    <div className="shopbrain-widget">
      {/* Floating Action Button */}
      <button onClick={() => setIsOpen(!isOpen)}>
        {isOpen ? '✕' : '💬'}
      </button>

      {/* Chat Window */}
      {isOpen && <ChatWindow chatbotId={chatbotId} />}
    </div>
  );
}

Flow di Autenticazione Customer

┌──────────────┐     ┌──────────────┐     ┌──────────────┐
│   Customer   │     │    Widget    │     │   Backend    │
└──────┬───────┘     └──────┬───────┘     └──────┬───────┘
       │                    │                    │
       │  Apre chat         │                    │
       │───────────────────►│                    │
       │                    │                    │
       │                    │  GET /config       │
       │                    │───────────────────►│
       │                    │                    │
       │                    │  auth_required:true│
       │                    │◄───────────────────│
       │                    │                    │
       │  Mostra form email │                    │
       │◄───────────────────│                    │
       │                    │                    │
       │  Inserisce email   │                    │
       │───────────────────►│                    │
       │                    │                    │
       │                    │  POST /auth/verify │
       │                    │───────────────────►│
       │                    │                    │
       │                    │  (valida su WooCommerce/Shopify)
       │                    │                    │
       │                    │  ✓ session token   │
       │                    │◄───────────────────│
       │                    │                    │
       │  Chat abilitata    │                    │
       │◄───────────────────│                    │

Avvio

Con Docker (consigliato)

# Dalla root del progetto
make dev

# Solo widget
docker compose up widget

# Rebuild
docker compose up widget --build

Il widget sarà disponibile su http://localhost:5173

Sviluppo Locale

cd packages/widget

# Installa dipendenze
pnpm install

# Avvia dev server
pnpm dev

Dev server su http://localhost:5173 (Vite)

In modalità development, il widget si auto-inizializza con:

  • chatbotId: 'dev-chatbot'
  • apiUrl: 'http://localhost:8000'

Environment Variables

# .env (nella root del progetto)
VITE_API_URL=http://localhost:8000
WIDGET_PORT=5173

Build

Development

pnpm dev

Production

pnpm build

Output in dist/:

  • widget.js - Bundle principale (IIFE)
  • widget.css - Styles

Build Configuration (vite.config.ts)

export default defineConfig({
  build: {
    lib: {
      entry: 'src/main.tsx',
      name: 'ShopBrain',
      fileName: 'widget',
      formats: ['iife'],  // Single file per embedding
    },
    rollupOptions: {
      output: {
        // Inlined CSS nel JS
        assetFileNames: 'widget.[ext]',
      },
    },
  },
});

Personalizzazione Tema

Il widget supporta temi personalizzabili per chatbot:

interface ThemeConfig {
  colors: {
    primary: string;      // Colore principale
    background: string;   // Sfondo chat
    userBubble: string;   // Bubble utente
    botBubble: string;    // Bubble assistente
    text: string;         // Testo
  };
  borderRadius: 'none' | 'sm' | 'md' | 'lg' | 'full';
  position: 'bottom-right' | 'bottom-left';
}

Il tema viene caricato dall'API insieme alla configurazione del chatbot.

CSS Isolation

Il widget usa classi con prefisso shopbrain- per evitare conflitti con il CSS del sito host:

.shopbrain-widget { ... }
.shopbrain-fab { ... }
.shopbrain-chat-window { ... }
.shopbrain-chat-header { ... }
.shopbrain-chat-messages { ... }
.shopbrain-chat-input { ... }

API Endpoints Utilizzati

| Endpoint | Metodo | Descrizione | |----------|--------|-------------| | /api/chatbots/{id}/config | GET | Configurazione chatbot | | /api/chat/message | POST | Invia messaggio | | /api/chat/stream/{id} | SSE | Stream risposta | | /api/auth/verify | POST | Verifica email customer | | /ws/chat/{conversation_id} | WebSocket | Real-time (opzionale) |

Docker

Development (hot-reload)

FROM node:20-alpine AS development
WORKDIR /app
RUN npm install -g pnpm
COPY package.json pnpm-lock.yaml ./
RUN pnpm install
COPY . .
EXPOSE 5173
CMD ["pnpm", "dev", "--host", "0.0.0.0"]

Production

FROM node:20-alpine AS builder
WORKDIR /app
RUN npm install -g pnpm
COPY package.json pnpm-lock.yaml ./
RUN pnpm install
COPY . .
RUN pnpm build

FROM nginx:alpine AS production
COPY --from=builder /app/dist /usr/share/nginx/html
# CORS headers per embedding cross-origin
COPY nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 80

Comandi Make Utili

make widget-logs      # Logs del container
make widget-shell     # Shell nel container
make widget-restart   # Riavvia il container

Testing Locale

  1. Avvia il backend: make dev
  2. Apri http://localhost:5173
  3. Il widget appare automaticamente in basso a destra
  4. Clicca per aprire la chat

Roadmap Componenti Custom

Componenti che verranno lazy-loaded in base alla configurazione del chatbot:

  • ProductCarousel - Carousel prodotti suggeriti
  • ProductCard - Card singolo prodotto
  • OrderTracker - Tracking ordine
  • SizeGuide - Guida taglie modal
  • AddToCartButton - Aggiungi al carrello
  • WishlistButton - Aggiungi a wishlist