npm.io
0.2.4 • Published yesterday

@pyrx/synapse-browser

Licence
MIT
Version
0.2.4
Deps
0
Size
240 kB
Vulns
0
Weekly
274

Synapse CEP — JavaScript Tracking + Web Push SDK

Lightweight client-side SDK for tracking user events and (Phase 9.1+) subscribing browsers to Web Push notifications in the Synapse Customer Engagement Platform.

Size: ~22 KB minified (event tracking + Web Push surface)

Browser support (Web Push, Phase 9.1): Chrome ≥ 50, Firefox ≥ 44, Edge ≥ 17, Safari macOS ≥ 16. iOS Safari requires a PWA install + iOS 16.4+ — verification deferred to a 9.1.x follow-up.

Installation

<!-- Synapse Tracking SDK -->
<script>
  !function(){var s=window.synapse=window.synapse||function(){
    (s.q=s.q||[]).push(arguments)};
    var e=document.createElement("script");
    e.type="text/javascript";e.async=true;
    e.src="https://synapse-events.pyrx.tech/sdk/v1/synapse.min.js";
    var x=document.getElementsByTagName("script")[0];
    x.parentNode.insertBefore(e,x);
  }();

  synapse('init', { apiKey: 'psk_prod_YOUR_API_KEY' });
  synapse('page');
</script>
npm (for bundlers)
pnpm add @pyrx-crm/sdk
import { synapse } from '@pyrx-crm/sdk';

synapse('init', { apiKey: 'psk_prod_YOUR_API_KEY' });

Usage

Identify Users

Call after login to associate events with a known user:

synapse('identify', 'user-123', {
  email: 'jane@example.com',
  first_name: 'Jane',
  last_name: 'Doe',
  plan: 'pro'
});
Track Events
synapse('track', 'cart.abandoned', {
  product: 'Widget',
  price: 29.99,
  currency: 'USD'
});

synapse('track', 'feature.used', {
  feature: 'export_csv',
  rows: 1500
});
Page Views
// Automatically captures URL, path, title, referrer
synapse('page');

// With custom properties
synapse('page', { section: 'pricing' });
Reset (on logout)
synapse('reset');

Web Push (Phase 9.1)

Five new commands on the same facade subscribe a browser to Web Push and manage the subscription. The full setup guide ships in PR-3 — what follows is the SDK-side API surface.

Prerequisites
  1. Generate a VAPID credential in Dashboard → Settings → Push Credentials → VAPID (PR-3 surface). Copy the public key.
  2. Copy node_modules/@pyrx/synapse-browser/dist/synapse-sw.js to your site's public directory (PR-3 ships the file). Add to postinstall if you want automatic updates:
    { "scripts": { "postinstall": "cp node_modules/@pyrx/synapse-browser/dist/synapse-sw.js public/synapse-sw.js" } }
  3. Call synapse('identify', userId) before subscribing — Web Push requires an identified user so the backend can associate the device with a contact.
enablePush — register the SW + prepare state

Safe to call from any lifecycle hook (no user gesture required):

synapse('enablePush', {
  vapidPublicKey: 'BPV9...',           // from the dashboard
  serviceWorkerPath: '/synapse-sw.js', // default
  serviceWorkerScope: '/',             // default
});

On browsers without Service Worker / PushManager / Notification support (e.g. private windows, Safari iOS without PWA install), the call logs a one-line warning and resolves cleanly — your code never crashes.

requestPermission — show the permission prompt + subscribe

Must be called from a user gesture handler (click, tap). Browsers silently deny otherwise.

button.addEventListener('click', async () => {
  try {
    const subscription = await synapse('requestPermission');
    console.log('Subscribed:', subscription.endpoint);
  } catch (err) {
    if (err.code === 'permission_denied') {
      // User said no — show your own UI rationale.
    }
  }
});
disablePush — unsubscribe + delete device server-side
synapse('disablePush');

Idempotent. Always succeeds locally even if the backend DELETE fails.

getSubscription — inspect current state
const sub = await synapse('getSubscription');
// → { endpoint, p256dh, auth, permission, deviceId } | null
setPushPreferences — per-device preferences
synapse('setPushPreferences', { quiet_hours: '22:00-07:00', mute_channels: ['promo'] });

Stored on the backend devices.metadata JSONB column — schema is tenant-defined.

Error types (TypeScript)
import {
  SynapsePushUnsupportedError,
  SynapsePermissionDeniedError,
  SynapsePushNotEnabledError,
  SynapseUserNotIdentifiedError,
  SynapseServiceWorkerError,
  SynapseDeviceRegistrationError,
} from '@pyrx/synapse-browser';

Every push error has a stable .code string (push_unsupported, permission_denied, etc.) safe to switch on.

Configuration

synapse('init', {
  apiKey: 'psk_prod_xxx',                              // Required
  endpoint: 'https://synapse-events.pyrx.tech',        // Default
  flushInterval: 5000,                                  // ms between flushes (default: 5s)
  flushSize: 10,                                        // events before auto-flush (default: 10)
  debug: false,                                         // Console logging (default: false)
});

How It Works

  1. Events are queued in memory and persisted to localStorage
  2. Queue flushes every 5 seconds or when 10 events accumulate
  3. Events are sent as a batch to POST /v1/events/batch
  4. On page unload, sendBeacon ensures delivery
  5. Failed flushes retry with exponential backoff (1s, 2s, 4s)
  6. Queue survives page refreshes via localStorage

Keywords