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

@agenus-io/pixel

v0.0.8

Published

Pixel Tracker para Facebook e Google Analytics - Envia eventos para sua API do Agenus

Downloads

308

Readme

GomarkePixel

SDK de tracking para web com arquitetura modular, cobrindo:

  • Core/Tracker: visitante, sessão, pageview e fila de envio.
  • Behavior: sinais comportamentais (scroll, click, idle, visibility, exit intent, viewport e engagement).
  • Conversion (tracker manual): eventos de conversão/e-commerce por invocação.
  • AutoTracks: detecção automática por seletores e data-attributes.
  • AutoTrack Engine: regras leves por seletor/texto/URL (autoTrack).

Instalação

NPM / PNPM / Yarn

npm install @agenus-io/pixel
# ou
pnpm add @agenus-io/pixel
# ou
yarn add @agenus-io/pixel

CDN (global)

<script src="https://unpkg.com/@agenus-io/pixel@latest/dist/index.global.js"></script>

Modos de uso

1) Script tag com auto-init (HTML puro)

Quando o script possui data-pixel, o pacote faz bootstrap automático e expõe window.gomarkePixel.

<script
  src="../dist/index.global.js"
  data-pixel="pix_123"
  data-api-endpoint="https://seu-endpoint"
  data-debug="true"
  data-timeout="5000"
  data-project-id="projeto_abc"
  data-page-id="home"
></script>

data-attributes de bootstrap aceitos no script:

  • data-pixel (obrigatório para auto-init)
  • data-api-endpoint
  • data-debug
  • data-timeout
  • data-project-id
  • data-page-id

2) Import por módulo (invocação manual e automática)

import GomarkePixel from '@agenus-io/pixel';

const pixel = new GomarkePixel({
  pixel: 'pix_123',
  apiEndpoint: 'https://seu-endpoint',
  debug: true,
});

Configuração completa (GomarkePixelConfig)

type SelectorType =
  | 'class'
  | 'id'
  | 'attribute'
  | 'tag'
  | 'text'
  | 'url'
  | 'data-attribute'
  | 'custom'
  | 'automatic';

interface GomarkePixelConfig {
  pixel: string;
  apiEndpoint: string;
  apiEndpointEvent?: string;
  projectId?: string;
  pageId?: string;
  apiKey?: string;
  debug?: boolean;
  version?: string;
  timeout?: number;
  pixelMeta?: Array<{ title?: string; externalId?: string; token?: string }>;

  behavior?: {
    enabled?: boolean;
    idleThresholdMs?: number;
    rageClickThreshold?: number;
    rageClickWindowMs?: number;
    scrollWeights?: { scroll: number; click: number; time: number };
    engagementThresholds?: { low: number; medium: number };
    viewport?: {
      enabled?: boolean;
      selector: string;
      selectorType:
        | 'class'
        | 'id'
        | 'attribute'
        | 'data-attribute'
        | 'tag'
        | 'custom';
      trackElementVisibility?: boolean;
      trackElementIntersection?: boolean;
      visibilityThreshold?: number;
      intersectionThreshold?: number;
      trackElementClicks?: boolean;
      trackElementHovers?: boolean;
      maxTrackingElements?: number;
    };
  };

  autoTracks?: {
    addToCart?: {
      enabled?: boolean;
      selector?: string;
      selectorType?: SelectorType;
      productDataSelectors?: {
        id?: string;
        name?: string;
        price?: string;
        category?: string;
        image?: string;
        currency?: string;
      };
      customDataExtractor?: (element: Element) => Record<string, unknown>;
    };
    removeToCart?: {
      enabled?: boolean;
      selector?: string;
      selectorType?: SelectorType;
      productDataSelectors?: {
        id?: string;
        name?: string;
        price?: string;
        category?: string;
        image?: string;
      };
      customDataExtractor?: (element: Element) => Record<string, unknown>;
    };
    initiateCheckout?: {
      enabled?: boolean;
      selector?: string;
      selectorType?: SelectorType;
      trackOnNavigation?: boolean;
      navigationSelectors?: string[];
      cartDataSelectors?: { total?: string; currency?: string; items?: string };
      customCartExtractor?: (element: Element) => Record<string, unknown>;
    };
    lead?: {
      enabled?: boolean;
      selector?: string;
      selectorType?: SelectorType;
      trackOnFieldFocus?: boolean;
      trackOnFieldBlur?: boolean;
      trackOnFieldChange?: boolean;
      requiredFields?: string[];
      validationRules?: { email?: RegExp; phone?: RegExp; minLength?: number };
      formFieldSelectors?: {
        email?: string;
        name?: string;
        phone?: string;
        message?: string;
      };
      customFormExtractor?: (form: HTMLFormElement) => Record<string, unknown>;
    };
    scroll?: {
      enabled?: boolean;
      scrollThresholds?: number[];
      trackScrollDepth?: boolean;
      trackTimeOnPage?: boolean;
      debounceMs?: number;
    };
    viewport?: {
      enabled?: boolean;
      selector?: string;
      selectorType?:
        | 'class'
        | 'id'
        | 'attribute'
        | 'tag'
        | 'text'
        | 'url'
        | 'data-attribute'
        | 'custom';
      trackElementIntersection?: boolean;
      trackElementClicks?: boolean;
      trackElementHovers?: boolean;
      visibilityThreshold?: number;
      maxTrackingElements?: number;
    };
    viewContent?: {
      enabled?: boolean;
      selector?: string;
      selectorType?: SelectorType;
      customDataExtractor?: (element: Element) => Record<string, unknown>;
    };
  };

  autoTrack?: {
    selectors?: Array<{
      selector: string;
      eventType:
        | 'pageView'
        | 'purchase'
        | 'lead'
        | 'addToCart'
        | 'initiateCheckout'
        | 'removeToCart'
        | 'search'
        | 'viewContent';
      dataAttribute?: string;
    }>;
    texts?: Array<{
      text: string | RegExp;
      eventType:
        | 'pageView'
        | 'purchase'
        | 'lead'
        | 'addToCart'
        | 'initiateCheckout'
        | 'removeToCart'
        | 'search'
        | 'viewContent';
    }>;
    urlPatterns?: Array<{
      pattern: string | RegExp;
      eventType:
        | 'pageView'
        | 'purchase'
        | 'lead'
        | 'addToCart'
        | 'initiateCheckout'
        | 'removeToCart'
        | 'search'
        | 'viewContent';
    }>;
  };
}

Módulo Tracker (conversão manual por invocação)

Métodos públicos de GomarkePixel:

  • trackPageView()
  • trackPurchase({ value, currency, transactionId?, items? })
  • trackAddToCart({ itemId, itemName, value?, currency?, category?, quantity? })
  • trackRemoveToCart({ itemId, itemName, value?, currency? })
  • trackInitiateCheckout({ value?, currency?, items? })
  • trackLead({ ...campos })
  • trackSearch({ searchTerm, category?, resultsCount?, filters? })
  • trackViewContent({ content_id?, content_name?, content_type?, content_category?, value?, ...extra })

Exemplo manual:

await pixel.trackPurchase({
  value: 199.9,
  currency: 'BRL',
  transactionId: 'txn_001',
  items: [
    {
      item_id: 'sku_001',
      item_name: 'Produto Teste',
      category: 'Categoria Teste',
      quantity: 1,
      price: 199.9,
    },
  ],
});

Módulo AutoTracker (autoTracks)

data-attributes padrão (sem customização)

Se você ativar os autoTracks com selectorType: 'attribute', os defaults são:

  • Lead: data-lead
  • Add to cart: data-add-to-cart
  • Remove to cart: data-remove-to-cart
  • Checkout: data-checkout
  • View content: data-view-content
  • Viewport (behavior): pode usar data-viewport-key no módulo behavior

Atributos de dados para e-commerce:

  • Produto: data-product-id, data-product-name, data-product-price, data-product-category, data-product-image, data-product-currency
  • Carrinho: data-cart-total, data-cart-currency, data-cart-items

Exemplo em HTML puro com data-attributes

<button
  data-add-to-cart="true"
  data-product-id="sku_001"
  data-product-name="Produto Teste"
  data-product-price="199.9"
  data-product-category="Categoria Teste"
  data-product-currency="BRL"
>
  Add to Cart
</button>

<button
  data-checkout="true"
  data-cart-total="199.9"
  data-cart-currency="BRL"
  data-cart-items='[{"item_id":"sku_001","item_name":"Produto Teste","quantity":1,"price":199.9}]'
>
  Checkout
</button>

<form data-lead="true">
  <input name="email" />
  <input name="name" />
  <button type="submit">Enviar lead</button>
</form>

Exemplo de config autoTracks

const pixel = new GomarkePixel({
  pixel: 'pix_123',
  apiEndpoint: 'https://seu-endpoint',
  debug: true,
  autoTracks: {
    addToCart: { enabled: true, selector: 'data-add-to-cart', selectorType: 'attribute' },
    removeToCart: { enabled: true, selector: 'data-remove-to-cart', selectorType: 'attribute' },
    initiateCheckout: { enabled: true, selector: 'data-checkout', selectorType: 'attribute' },
    lead: { enabled: true, selector: 'data-lead', selectorType: 'attribute', requiredFields: ['email', 'name'] },
    viewContent: { enabled: true, selector: 'data-view-content', selectorType: 'attribute' },
    scroll: { enabled: true, scrollThresholds: [25, 50, 75, 90], trackTimeOnPage: true },
  },
});

Também é possível configurar por método:

  • setupAutoAddToCart(config)
  • setupAutoRemoveToCart(config)
  • setupAutoInitiateCheckout(config)
  • setupAutoLead(config)
  • setupAutoViewContent(config)

Módulo Behavior

O engine de behavior coleta sinais para enriquecer contexto comportamental:

  • scroll
  • click e rage click
  • idle/active
  • visibility (hidden/visible)
  • exit intent
  • viewport (elementos visíveis, interseção, clique, hover)
  • score de engagement (low | medium | high)

Métodos úteis no GomarkePixel:

  • getBehaviorState()
  • getBehaviorPhase()
  • getViewportState()
  • enqueueBehaviorSnapshot()
  • getBehaviorBufferStats()
  • getBehaviorBatchPayload()
  • resetForNewPage() (SPA)

Módulo AutoTrack Engine (autoTrack)

Além dos autoTrackers, existe um motor leve por regras:

  • selectors: dispara por seletor CSS clicado.
  • texts: dispara por texto em a, button ou [role="button"].
  • urlPatterns: dispara por padrão de URL/path (inclui SPA via pushState/replaceState).

Exemplo:

const pixel = new GomarkePixel({
  pixel: 'pix_123',
  apiEndpoint: 'https://seu-endpoint',
  autoTrack: {
    selectors: [{ selector: '[data-track="purchase"]', eventType: 'purchase' }],
    texts: [{ text: /finalizar compra/i, eventType: 'initiateCheckout' }],
    urlPatterns: [{ pattern: 'obrigado', eventType: 'purchase' }],
  },
});

Uso com React

import { useEffect, useMemo } from 'react';
import GomarkePixel from '@agenus-io/pixel';

export function App() {
  const pixel = useMemo(
    () =>
      new GomarkePixel({
        pixel: 'pix_123',
        apiEndpoint: 'https://seu-endpoint',
        debug: true,
        autoTracks: {
          addToCart: { enabled: true, selector: 'data-add-to-cart', selectorType: 'attribute' },
          lead: { enabled: true, selector: 'data-lead', selectorType: 'attribute' },
        },
      }),
    []
  );

  useEffect(() => {
    pixel.trackPageView();
  }, [pixel]);

  return (
    <button
      data-add-to-cart="true"
      data-product-id="sku_001"
      data-product-name="Produto Teste"
      data-product-price="199.9"
    >
      Adicionar ao carrinho
    </button>
  );
}

Uso com Next.js

App Router (app/layout.tsx) com script global

import Script from 'next/script';

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="pt-BR">
      <body>
        {children}
        <Script
          src="https://unpkg.com/@agenus-io/pixel@latest/dist/index.global.js"
          strategy="afterInteractive"
          data-pixel="pix_123"
          data-api-endpoint="https://seu-endpoint"
          data-debug="true"
        />
      </body>
    </html>
  );
}

App Router por módulo (client component)

'use client';

import { useEffect } from 'react';
import GomarkePixel from '@agenus-io/pixel';

const pixel = new GomarkePixel({
  pixel: 'pix_123',
  apiEndpoint: 'https://seu-endpoint',
  debug: true,
});

export function PixelBootstrap() {
  useEffect(() => {
    pixel.trackPageView();
  }, []);

  return null;
}

Métodos utilitários e operação

  • Sessão/visitante:
    • getSessionId()
    • getVisitorId()
    • getSessionData()
    • isSessionActive()
    • updateSessionActivity()
    • renewSession()
    • clearSession()
    • exportSessionData()
  • Fila e debug:
    • getQueueLength()
    • flushQueue()
  • Tracker factory:
    • getTrackerFactory()
    • getTrackerStats()
    • clearTrackers()
  • AutoTracker factory:
    • getAutoTrackerFactory()
    • getAutoTrackerStats()
    • stopAllAutoTrackers()
    • rebuildAllAutoTrackers()

Scripts de desenvolvimento

pnpm dev
pnpm build
pnpm test
pnpm test:watch
pnpm lint
pnpm lint:fix
pnpm format
pnpm type-check

Estrutura de módulos (atual)

src/
  core/        # visitor, session, pageview, queue, consent
  behavior/    # scroll, click, idle, visibility, exit intent, viewport, engagement
  conversion/  # engine, tracks manuais e autoTracks
  utils/       # sessão, envio, device, fingerprint, getSetting, etc.
  pixel.ts     # classe principal GomarkePixel
  index.ts     # exports públicos + autoInitFromScriptTag()

Licença

MIT