New Research: Supply Chain Attack on Axios Pulls Malicious Dependency from npm.Details →
Socket
Book a DemoSign in
Socket

@shopkit/events

Package Overview
Dependencies
Maintainers
1
Versions
8
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@shopkit/events

Event-driven analytics system for OpenStore storefronts

latest
npmnpm
Version
0.9.0
Version published
Maintainers
1
Created
Source

@shopkit/events

Event-driven analytics system for e-commerce storefronts.

Features

  • 20 standardized events aligned with GA4 enhanced e-commerce
  • Type-safe EventBus with middleware pipeline and ring buffer
  • 5-stage middleware — schema validation, deduplication, user enrichment, dev logging, server relay
  • Cart integration via onCartEvent callback (zero changes to @shopkit/cart)
  • Automatic page views with page type detection
  • Product view tracking with 20s engagement timer
  • Data mappers for cart, product, and order data (with priceDivisor for paise→rupees conversion)
  • sendBeacon batching with fetch keepalive fallback
  • PII hashing via Web Crypto API (deferred, non-blocking)
  • Performance budget of 3.2ms per event end-to-end

Installation

npm install @shopkit/events
# or
bun add @shopkit/events

Peer dependencies: react, zod, next (optional), zustand (optional)

Quick Start

1. Add EventProvider in your root layout

// app/layout.tsx
'use client';

import { EventProvider } from '@shopkit/events/react';
import { usePathname, useSearchParams } from 'next/navigation';

function EventProviderWrapper({ children }: { children: React.ReactNode }) {
  const pathname = usePathname();
  const searchParams = useSearchParams()?.toString();

  return (
    <EventProvider pathname={pathname} searchParams={searchParams}>
      {children}
    </EventProvider>
  );
}

export default function RootLayout({ children }) {
  return (
    <html>
      <body>
        <EventProviderWrapper>{children}</EventProviderWrapper>
      </body>
    </html>
  );
}

2. Wire cart events

// bootstrap/cart.ts
import { eventBus } from '@shopkit/events';
import { createCartMapper } from '@shopkit/events/mappers';
import { createCartEventHandler } from '@shopkit/events/emitters';
import { configureCart } from '@shopkit/cart';

// priceDivisor: 100 converts paise (35500) to rupees (355.00)
const mapper = createCartMapper('INR', 100);
const handleCartEvent = createCartEventHandler(eventBus, mapper);

configureCart({
  // ...existing config...
  onCartEvent: handleCartEvent,
});

3. Track product views

// components/ProductPage.tsx
import { useProductViewEmitter } from '@shopkit/events/emitters';
import { useEventBus } from '@shopkit/events/react';

function ProductPage({ product }) {
  const bus = useEventBus();
  const standardItem = {
    item_id: product.id,
    item_name: product.title,
    item_brand: product.vendor,
    item_category: product.productType,
    price: product.price,
    quantity: 1,
    currency: 'INR',
  };

  useProductViewEmitter(bus, standardItem);

  return <div>{/* product UI */}</div>;
}

4. Emit events manually

import { useTrackEvent } from '@shopkit/events/react';
import { OpenStoreEventType } from '@shopkit/events';

function SearchResults({ term, count }) {
  const emit = useTrackEvent();

  useEffect(() => {
    emit(OpenStoreEventType.SEARCH, {
      search_term: term,
      results_count: count,
    });
  }, [term, count]);

  return <div>{/* results */}</div>;
}

API Reference

Core

eventBus

Singleton EventBus instance. The single point through which all analytics events flow.

MethodSignatureDescription
subscribe(type: OpenStoreEventType, handler) => UnsubscribeSubscribe to a specific event type
subscribeAll(handler) => UnsubscribeSubscribe to all events
emit(type, data, overrides?) => OpenStoreEvent | nullEmit an event (null if blocked by middleware)
use(middleware: Middleware) => voidRegister middleware
getEventLog() => ReadonlyArray<OpenStoreEvent>Get ring buffer of last 100 events
reset() => voidClear all state (testing only)

Event Types

import { OpenStoreEventType } from '@shopkit/events';

// 16 client-side events
OpenStoreEventType.PAGE_VIEW
OpenStoreEventType.VIEW_PRODUCT
OpenStoreEventType.ENGAGE_CONTENT
OpenStoreEventType.ADD_TO_CART
OpenStoreEventType.REMOVE_FROM_CART
OpenStoreEventType.VIEW_CART
OpenStoreEventType.BEGIN_CHECKOUT
OpenStoreEventType.ADD_PAYMENT_INFO
OpenStoreEventType.ADD_SHIPPING_INFO
OpenStoreEventType.PURCHASE
OpenStoreEventType.SEARCH
OpenStoreEventType.ADD_TO_WISHLIST
OpenStoreEventType.KWIKPASS_LOGIN_ATTEMPTED
OpenStoreEventType.KWIKPASS_LOGIN_COMPLETED
OpenStoreEventType.VIEW_PROMO
OpenStoreEventType.AB_TEST_VIEWED

// 4 server-side events
OpenStoreEventType.ORDER_FULFILLED
OpenStoreEventType.ORDER_SHIPPED
OpenStoreEventType.ORDER_DELIVERED
OpenStoreEventType.ORDER_CANCELLED

Middleware (@shopkit/events/middleware)

MiddlewareFactoryDescription
schemaValidatorMiddlewarecreateSchemaValidatorMiddleware()Validates payloads against Zod schemas
deduplicatorMiddlewarecreateDeduplicatorMiddleware(windowMs?)Blocks duplicate events within 2s window
userEnricherMiddlewarecreateUserEnricherMiddleware()Enriches with cookies, affiliate data, PII hashes
devLoggerMiddlewarecreateDevLoggerMiddleware(options?)Console logging (dev default, env/console toggle)
serverRelayMiddlewarecreateServerRelayMiddleware(config?)Batches and sends via sendBeacon

Dev Logger Config

interface DevLoggerOptions {
  enabled?: boolean; // Explicitly enable/disable. Default: auto (dev mode only)
}

Logging is active when ANY of these is true:

  • enabled: true (e.g., process.env.NEXT_PUBLIC_EVENT_DEBUG === "true")
  • NODE_ENV === "development" (default, unless enabled: false)
  • window.__shopkit_debug = true (ad-hoc toggle from browser console — works in production)

Server Relay Config

interface ServerRelayConfig {
  ingestUrl?: string;        // Default: /api/events/ingest
  flushIntervalMs?: number;  // Default: 5000
  maxBatchSize?: number;     // Default: 10
}

Emitters (@shopkit/events/emitters)

createCartEventHandler(bus, mapper, options?)

Creates a handler for @shopkit/cart's onCartEvent callback.

interface CartEmitterOptions {
  getCartItems?: () => CartItemLike[];
  productIdentifier?: ProductIdentifier; // Override bus.productIdentifier
}

The handler normalizes raw cart store items (snake_case fields, price as number) automatically. productIdentifier is read lazily from bus.productIdentifier at event-fire time, so it respects config set by EventProvider even if the cart is bootstrapped first.

<PageEmitter bus={bus} pathname={pathname} searchParams={searchParams} />

React component that emits page_view on route changes. Rendered automatically by EventProvider.

useProductViewEmitter(bus, product, options?)

Hook that emits view_product on mount and engage_content after 20s dwell time.

Mappers (@shopkit/events/mappers)

MapperFactoryDescription
CartMappercreateCartMapper(currency?, priceDivisor?)CartItem to ProductFields. priceDivisor converts raw price units (e.g. 100 for paise→rupees)
ShopifyProductMappercreateShopifyProductMapper(currency?)Product GraphQL to StandardItem
ShopifyOrderMappercreateShopifyOrderMapper(currency?)Order to PurchasePayload

Note: ShopifyCartMapper and createShopifyCartMapper are deprecated aliases for CartMapper and createCartMapper.

React (@shopkit/events/react)

<EventProvider config? pathname? searchParams?>

Root provider. Initializes EventBus with middleware pipeline and renders PageEmitter.

interface EventProviderConfig {
  enableDevTools?: boolean;
  ingestUrl?: string;
  disablePageView?: boolean;
  disableServerRelay?: boolean;
  productIdentifier?: ProductIdentifier; // "product_id" | "sku" | "variant_id"
  bus?: EventBus;  // For testing
}

Hooks

HookReturn TypeDescription
useEventBus()EventBusAccess EventBus from context
useTrackEvent()(type, data) => OpenStoreEvent | nullStable emit function
useEventSubscribe(type, handler)voidSubscribe with auto-cleanup
useEventSubscribeAll(handler)voidSubscribe to all events
useEventLog()ReadonlyArray<OpenStoreEvent>Access event ring buffer

Schemas (@shopkit/events/schemas)

Zod validation schemas for all 20 events plus shared data shapes.

ExportDescription
StandardItemSchema15-field GA4-aligned item schema
StandardUserDataSchemaPII hashed user data schema
StandardCookiesSchemaPlatform tracking cookies schema
eventPayloadSchemasRecord mapping event type to Zod schema
OpenStoreEventEnvelopeSchemaFull event envelope structural schema

Sub-path Exports

import { eventBus, OpenStoreEventType } from '@shopkit/events';
import { schemaValidatorMiddleware } from '@shopkit/events/middleware';
import { createCartEventHandler } from '@shopkit/events/emitters';
import { createCartMapper } from '@shopkit/events/mappers';
import { EventProvider, useTrackEvent } from '@shopkit/events/react';
import { eventPayloadSchemas } from '@shopkit/events/schemas';

License

MIT

Keywords

events

FAQs

Package last updated on 31 Mar 2026

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts