JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 81
  • Score
    100M100P100Q97574F
  • License MIT

GetuAI Attribution V2 SDK for client-side tracking

Package Exports

  • getu-attribution-v2-sdk
  • getu-attribution-v2-sdk/browser

Readme

GetuAI Attribution SDK

A JavaScript SDK for tracking user attribution and conversion events in web applications.

Table of Contents


Features

Feature Description
๐ŸŽฏ UTM Tracking Automatic capture and storage of UTM parameters from URLs
๐Ÿ”— Cross-Domain UTM Automatic UTM parameter passing to external links
๐Ÿ“ฆ Event Batching Efficient batch processing of events with configurable intervals
๐Ÿ“ด Offline Support Queue events locally when offline, sync when connection restores
๐Ÿ”„ SPA Support Automatic page view tracking for Single Page Applications
โšก Immediate Events Critical events (purchase, login, signup, audit approved) sent immediately
๐Ÿ• Session Management Tracks user sessions with configurable timeout
๐Ÿงน Auto Clean UTM Removes UTM parameters from URL after capture
๐Ÿ“„ Page View Debounce Prevents duplicate page view events within configurable interval
๐Ÿ“ TypeScript Full TypeScript support with type definitions

Installation

<script
  src="https://unpkg.com/getu-attribution-v2-sdk/dist/getuai-attribution.min.js"
  data-api-key="your_api_key_here"
></script>

Via NPM

npm install getu-attribution-v2-sdk

Quick Start

Automatic Initialization (CDN)

The SDK auto-initializes when loaded with a data-api-key attribute:

<script
  src="https://unpkg.com/getu-attribution-v2-sdk/dist/getuai-attribution.min.js"
  data-api-key="your_api_key_here"
  data-auto-track-page-view="true"
  data-debug="true"
></script>

Manual Initialization (NPM)

import { init, trackPageView, EventType } from "getu-attribution-v2-sdk";

// Initialize SDK
await init({
  apiKey: "your_api_key_here",
  autoTrackPageView: true,
  enableDebug: true,
});

// Track custom event
await trackPageView({ category: "homepage" });

Configuration

Script Tag Attributes

Attribute Type Default Description
data-api-key string required Your GetuAI API key
data-api-endpoint string https://attribution.getu.ai/attribution/api API endpoint URL
data-debug boolean false Enable debug logging
data-auto-track boolean false Enable auto-tracking (forms, links)
data-auto-track-page-view boolean false Enable auto page view tracking (includes SPA)
data-batch-size number 100 Number of events per batch
data-batch-interval number 2000 Batch interval in milliseconds
data-auto-clean-utm boolean true Remove UTM params from URL after capture
data-user-id string - Initial user ID
data-domain string auto-detected Cookie domain for cross-subdomain sharing (e.g. .example.com). See Cross-Subdomain Tracking

Configuration Object

interface SDKConfig {
  // Required
  apiKey: string;

  // API Settings
  apiEndpoint?: string; // Default: "https://attribution.getu.ai/attribution/api"

  // Batch Settings
  batchSize?: number; // Default: 100
  batchInterval?: number; // Default: 2000 (ms)
  maxRetries?: number; // Default: 3
  retryDelay?: number; // Default: 1000 (ms)

  // Auto-Tracking
  autoTrack?: boolean; // Default: false - Enable form/link tracking
  autoTrackPageView?: boolean; // Default: false - Enable page view + SPA tracking

  // Session
  sessionTimeout?: number; // Default: 1800000 (30 minutes in ms)

  // Cross-Domain UTM
  enableCrossDomainUTM?: boolean; // Default: true
  crossDomainUTMParams?: string[]; // Default: ["utm_source", "utm_medium", "utm_campaign", "utm_term", "utm_content"]
  excludeDomains?: string[]; // Default: [] - Domains to exclude from UTM passing

  // URL Management
  autoCleanUTM?: boolean; // Default: true - Remove UTM from URL after capture

  // Page View
  pageViewDebounceInterval?: number; // Default: 5000 (ms) - Debounce interval for same page

  // User ID
  userId?: string; // Initial user ID to set on initialization

  // Cross-Subdomain (see Cross-Subdomain Tracking section)
  domain?: string; // Cookie domain override, e.g. ".example.com". Default: auto-detected eTLD+1

  // Debug
  enableDebug?: boolean; // Default: false
}

Full Configuration Example

await init({
  apiKey: "your_api_key_here",
  apiEndpoint: "https://your-api.com/attribution/api",
  batchSize: 50,
  batchInterval: 3000,
  maxRetries: 5,
  retryDelay: 2000,
  autoTrack: true,
  autoTrackPageView: true,
  sessionTimeout: 60 * 60 * 1000, // 1 hour
  enableCrossDomainUTM: true,
  crossDomainUTMParams: ["utm_source", "utm_medium", "utm_campaign"],
  excludeDomains: ["google.com", "facebook.com"],
  autoCleanUTM: true,
  pageViewDebounceInterval: 3000,
  userId: "user_123", // Optional: Set initial user ID
  enableDebug: true,
});

User ID Management

The SDK automatically manages user IDs and includes them in all tracked events.

Setting User ID

During Initialization

You can set the user ID when initializing the SDK:

// Via script tag
<script
  src="https://unpkg.com/getu-attribution-v2-sdk/dist/getuai-attribution.min.js"
  data-api-key="your_api_key_here"
  data-user-id="user_123"
></script>;

// Via configuration object
await init({
  apiKey: "your_api_key_here",
  userId: "user_123",
});

Programmatically Set User ID

You can set or update the user ID at any time:

import { setUserId } from "getu-attribution-v2-sdk";

// Set user ID (e.g., after user login)
setUserId("user_123");

Getting User ID

import { getUserId } from "getu-attribution-v2-sdk";

const userId = getUserId();
console.log("Current user ID:", userId); // "user_123" or null

Removing User ID

import { removeUserId } from "getu-attribution-v2-sdk";

// Remove user ID (e.g., after user logout)
removeUserId();

Automatic Inclusion in Events

Once a user ID is set, it will automatically be included in all tracked events, even if you don't explicitly pass it:

// User ID is already set via setUserId("user_123")

// This will automatically include user_123 in the event
await trackPageView({ category: "homepage" });

// Explicit user ID parameter will override the stored one
await trackPageView({ category: "homepage" }, "different_user_456");

Event Tracking

Event Types

enum EventType {
  // Pre-conversion signals
  PAGE_VIEW = "page_view",
  PAGE_CLICK = "page_click",
  BUTTON_CLICK = "button_click",
  VIDEO_PLAY = "video_play",

  // Registration funnel
  FORM_SUBMIT = "form_submit",
  EMAIL_VERIFICATION = "email_verification",

  // Login flow
  LOGIN = "login",

  // Signup flow
  SIGNUP = "signup",

  // Purchase funnel
  PRODUCT_VIEW = "product_view",
  ADD_TO_CART = "add_to_cart",
  PURCHASE = "purchase",

  // Post-conversion / back-office conversion
  AUDIT_APPROVED = "audit_approved",

  // User-defined custom events
  CUSTOM = "custom",
}

Immediate Events

These events are sent immediately (not batched):

  • PURCHASE
  • LOGIN
  • SIGNUP
  • FORM_SUBMIT
  • EMAIL_VERIFICATION
  • AUDIT_APPROVED

Track Page View

// Basic
await trackPageView();

// With custom data
await trackPageView({
  category: "product",
  section: "electronics",
});

// With user ID
await trackPageView({ category: "dashboard" }, "user_123");

Track Page Click

// Basic
await trackPageClick();

// With click context
await trackPageClick("user_123", {
  element_id: "btn_signup",
  element_type: "button",
  element_text: "Sign Up",
  position: { x: 120, y: 360 },
});

Track Button Click

// Basic - button name only
await trackButtonClick("Sign Up");

// With user ID
await trackButtonClick("Buy Now", "user_123");

// With extra data
await trackButtonClick("Download Report", "user_123", {
  section: "hero",
  page: "/pricing",
  variant: "primary",
});

// Without button name (anonymous click)
await trackButtonClick();

The event will be sent with event_data.button_name set to the provided name.

Track Purchase

Method 1: Traditional format (user_id required)

await trackPurchase(
  "user_123", // tracking_user_id (required)
  99.99, // revenue
  Currency.USD, // currency (optional, default: USD)
  {
    // purchaseData (optional)
    product_id: "prod_123",
    product_name: "Premium Plan",
    quantity: 1,
  }
);

Method 2: Auto user ID format (object parameter, user_id optional)

// Auto-use stored user ID
await trackPurchaseAuto({
  revenue: 99.99,
  currency: Currency.USD, // optional
  purchaseData: {
    product_id: "prod_123",
    product_name: "Premium Plan",
    quantity: 1,
  },
  // tracking_user_id is optional - will use stored user ID if not provided
});

// Or explicitly provide user ID
await trackPurchaseAuto({
  revenue: 99.99,
  tracking_user_id: "user_123", // optional, will use stored if not provided
  purchaseData: { product_id: "prod_123" },
});

Track Login

Method 1: Traditional format (user_id required)

await trackLogin("user_123", {
  method: "email",
  provider: "google",
});

Method 2: Auto user ID format (object parameter, user_id optional)

// Auto-use stored user ID
await trackLoginAuto({
  loginData: {
    method: "email",
    provider: "google",
  },
  // tracking_user_id is optional - will use stored user ID if not provided
});

// Or explicitly provide user ID
await trackLoginAuto({
  tracking_user_id: "user_123", // optional
  loginData: { method: "email" },
});

Track Signup

Method 1: Traditional format (user_id required)

await trackSignup("user_123", {
  method: "email",
  referral_code: "REF123",
});

Method 2: Auto user ID format (object parameter, user_id optional)

// Auto-use stored user ID
await trackSignupAuto({
  signupData: {
    method: "email",
    referral_code: "REF123",
  },
  // tracking_user_id is optional - will use stored user ID if not provided
});

// Or explicitly provide user ID
await trackSignupAuto({
  tracking_user_id: "user_123", // optional
  signupData: { method: "email" },
});

Track Form Submit

await trackFormSubmit("user_123", {
  form_id: "contact_form",
  form_type: "contact",
});

Track Video Play

// Basic
await trackVideoPlay();

// With user ID
await trackVideoPlay("user_123");

// With custom data
await trackVideoPlay("user_123", {
  video_id: "video_123",
  video_title: "Introduction Video",
  duration: 120,
  position: 30,
});

Track Email Verification

Method 1: Traditional format (user_id required)

await trackEmailVerification("user_123", {
  email: "user@example.com",
  verification_method: "email_link",
});

Method 2: Auto user ID format (object parameter, user_id optional)

// Auto-use stored user ID
await trackEmailVerificationAuto({
  verificationData: {
    email: "user@example.com",
    verification_method: "email_link",
  },
  // tracking_user_id is optional - will use stored user ID if not provided
});

// Or explicitly provide user ID
await trackEmailVerificationAuto({
  tracking_user_id: "user_123", // optional
  verificationData: { email: "user@example.com" },
});

Track Audit Approved

Track an audit approval conversion event. Sent immediately.

import { trackAuditApproved } from "getu-attribution-v2-sdk";

await trackAuditApproved("user_123", {
  audit_id: "audit_987",
  reviewer: "ops_team",
});

Auto User ID Functions Summary

The following functions support auto user ID with object parameter format:

  • trackPurchaseAuto(options) - Purchase tracking with optional user ID
  • trackLoginAuto(options) - Login tracking with optional user ID
  • trackSignupAuto(options) - Signup tracking with optional user ID
  • trackEmailVerificationAuto(options) - Email verification tracking with optional user ID

Important Notes:

  • If tracking_user_id is not provided in options and no user ID is stored, these functions will log an error and return without tracking the event
  • Always set user ID using setUserId() before calling these functions, or provide tracking_user_id in the options
  • The traditional functions (trackPurchase, trackLogin, etc.) still require tracking_user_id as the first parameter

Track Product View

// Basic
await trackProductView();

// With user ID
await trackProductView("user_123");

// With product data
await trackProductView("user_123", {
  product_id: "prod_123",
  product_name: "Widget",
  category: "electronics",
  price: 29.99,
});

Track Add to Cart

// Basic
await trackAddToCart();

// With user ID
await trackAddToCart("user_123");

// With cart data
await trackAddToCart("user_123", {
  product_id: "prod_123",
  product_name: "Widget",
  quantity: 2,
  price: 29.99,
});

Track Custom Event

Use trackCustomEvent to track any user-defined event with a custom name. The event name is required and must be non-empty.

// Basic - event name only
await trackCustomEvent("webinar_registered");

// With custom data
await trackCustomEvent("webinar_registered", {
  webinar_id: "webinar_123",
  webinar_title: "Advanced Analytics",
});

// With user ID and revenue
await trackCustomEvent(
  "subscription_upgraded",
  { plan: "pro", billing_cycle: "annual" },
  "user_123", // tracking_user_id (optional)
  299.00,     // revenue (optional)
  Currency.USD // currency (optional, default: USD)
);

Custom events are batched (not sent immediately). Use flush() to force-send pending events.

Validation: An empty or whitespace-only event name will be rejected client-side with a console error.


Auto-Tracking

General Auto-Tracking (autoTrack)

When autoTrack: true, the SDK automatically tracks:

Form Submissions

  • Captures all form field values (with password masking)
  • Includes form metadata (id, action, method)
  • Handles checkboxes, radio buttons, multi-select, file inputs
  • Fallback field collection: For form fields without name attribute, SDK will use fallback keys:
    • Priority: name attribute
    • Fallback 1: id_{id} (if field has id)
    • Fallback 2: aria_{aria-label} (if field has aria-label)
    • Fallback 3: ph_{placeholder}_{index} (if field has placeholder)
    • Fallback 4: field_{index} (as last resort)
  • Adds UTM parameters to external links
  • Respects excludeDomains configuration

Page View Auto-Tracking (autoTrackPageView)

When autoTrackPageView: true, the SDK:

  1. Initial Page View: Tracks page view on SDK initialization
  2. SPA Route Changes: Automatically tracks navigation via:
    • history.pushState()
    • history.replaceState()
    • Browser back/forward (popstate)
  3. Debouncing: Prevents duplicate tracking within pageViewDebounceInterval

SPA Support

Single Page Application support is automatically enabled when autoTrackPageView: true.

How It Works

User visits /home
  โ””โ”€โ”€ SDK tracks PAGE_VIEW for /home

User clicks link to /products
  โ””โ”€โ”€ React Router calls history.pushState()
  โ””โ”€โ”€ SDK detects route change
  โ””โ”€โ”€ SDK tracks PAGE_VIEW for /products (after 100ms delay for title update)

User clicks browser back button
  โ””โ”€โ”€ Browser fires popstate event
  โ””โ”€โ”€ SDK detects route change
  โ””โ”€โ”€ SDK tracks PAGE_VIEW for /home

Route Change Detection

The SDK intercepts:

  • history.pushState() - Standard navigation
  • history.replaceState() - URL replacement
  • popstate event - Browser back/forward

Path Comparison

Only tracks when pathname + search actually changes:

// These are considered different paths:
"/products"
"/products?category=electronics"
"/products/123"

// These are considered the same (no duplicate tracking):
"/products" -> "/products"

Cross-Domain UTM

Automatic UTM Passing

When users click external links, UTM parameters are automatically appended:

User visits your site with ?utm_source=google&utm_medium=cpc
  โ””โ”€โ”€ UTM params stored in localStorage

User clicks link to https://partner-site.com/page
  โ””โ”€โ”€ SDK modifies link to:
      https://partner-site.com/page?utm_source=google&utm_medium=cpc

Configuration

await init({
  apiKey: "your_api_key",
  enableCrossDomainUTM: true, // Default: true
  crossDomainUTMParams: [
    // Which params to pass
    "utm_source",
    "utm_medium",
    "utm_campaign",
  ],
  excludeDomains: [
    // Don't pass UTM to these domains
    "google.com",
    "facebook.com",
    "twitter.com",
  ],
});

Manual UTM Enhancement

// Add UTM to any URL
const enhancedURL = addUTMToURL("https://example.com/page");
// Result: "https://example.com/page?utm_source=google&utm_medium=cpc"

// Get current UTM parameters
const utmParams = getCurrentUTMParams();
// Result: { utm_source: "google", utm_medium: "cpc", utm_campaign: "summer" }

Cross-Subdomain Tracking

When a visitor moves between subdomains on the same root (e.g. example.com โ†’ app.example.com for signup), the SDK keeps session_id, user_id, and first-touch attribution continuous. Users are never split into two journeys.

How It Works

On initialization, the SDK auto-detects the broadest cookie domain it can write to by probing parent-most hostnames. Once resolved:

  • Session, user ID, and attribution data are stored in cookies scoped to domain=.example.com (the detected root).
  • All subdomains read back the same values โ€” session stays alive across navigation.
  • Legacy localStorage data from earlier SDK versions is automatically migrated to cookies on first load.

No code change required for standard deployments (example.com, example.com, shop.acme.co, etc.).

When You Need Explicit domain Config

Auto-detection works by asking the browser to accept a probe cookie at each candidate domain. Some deployments require you to set domain yourself:

Scenario Why auto-detect can't handle it What to set
Hosted on a public suffix (*.github.io, *.vercel.app, *.netlify.app, *.pages.dev) These are registered as public suffixes โ€” the browser rejects domain=.github.io. Each subdomain is isolated by design. Leave unset โ€” each subdomain is its own scope. If you have your own domain, point it at the app and use that instead.
Multi-tenant platform sharing a parent domain (e.g. tenant-a.app.com + tenant-b.app.com, tenants must NOT share state) Auto-detect would pick .app.com and leak sessions between tenants. Set domain to the tenant hostname, e.g. tenant-a.app.com.
Staging vs prod on the same root (staging.example.com + shop.example.com, should stay separate) Auto-detect picks .example.com and bridges envs. Set domain to the environment hostname.
Custom enterprise setup where auto-detect returns null (air-gapped, odd DNS, cookie-restricted environments) No candidate domain accepted. Provide the exact domain you want.

Usage

Via script tag:

<script
  src="https://unpkg.com/getu-attribution-v2-sdk/dist/getuai-attribution.min.js"
  data-api-key="your_api_key"
  data-domain=".example.com"
></script>

Via config object:

await init({
  apiKey: "your_api_key",
  domain: ".example.com", // leading dot optional โ€” ".example.com" and "example.com" behave the same
});

Verification

Open DevTools โ†’ Application โ†’ Cookies on any page after SDK init. You should see:

Cookie Domain Purpose
_getuai_session .example.com Session id + last activity
_getuai_attrib .example.com First/last-touch UTM data
getuai_user_id .example.com User identifier (after setUserId)

If the Domain column shows the full hostname instead of the dotted parent (e.g. shop.example.com rather than .example.com), cross-subdomain sharing is NOT active โ€” check the When You Need Explicit domain Config table and pass domain explicitly.

Fallback Behavior

  • Cookie write blocked (incognito mode with cookies disabled, sandboxed iframe): SDK falls back to localStorage. Single-site tracking still works; cross-subdomain continuity does not.
  • localhost / IP literals: Cookie domain detection returns null; cookies are written as host-only. Use nip.io subdomains for local cross-subdomain testing (e.g. a.127.0.0.1.nip.io).

Session Ownership & Rotation

The SDK binds each session_id to the user who identified during it, so two different users on a shared device never share one session.

Transition Session behavior Reason
Anonymous โ†’ setUserId("A") Keep same session_id Backend backfill attaches prior anonymous events to user A
setUserId("A") โ†’ setUserId("A") again Keep same session_id No-op
setUserId("A") โ†’ setUserId("B") New session_id Different user โ€” distinct journey
setUserId("A") โ†’ removeUserId() โ†’ setUserId("B") New session_id Logout alone doesn't rotate; the subsequent user change does
setUserId("A") โ†’ removeUserId() โ†’ setUserId("A") Keep same session_id Same user re-authenticated
sessionTimeout elapsed since last activity New session_id Normal inactivity-based rotation (default 30 min)

Note: removeUserId() (logout) by itself does not rotate the session. The session still "remembers" its last owner, so a subsequent setUserId() can detect a mismatch and rotate correctly. This preserves the common "log out then log back in as yourself" case.


Attribution Data

Data Structure

interface AttributionData {
  firstTouch: UTMData; // First attribution touchpoint
  lastTouch: UTMData; // Most recent touchpoint
  touchpoints: UTMData[]; // All touchpoints history
  expiresAt: number; // Expiration timestamp
}

interface UTMData {
  utm_source?: string;
  utm_medium?: string;
  utm_campaign?: string;
  utm_term?: string;
  utm_content?: string;
  timestamp: number;
}

Accessing Attribution Data

const attribution = getAttributionData();

if (attribution) {
  console.log("First Touch:", attribution.firstTouch);
  console.log("Last Touch:", attribution.lastTouch);
  console.log("All Touchpoints:", attribution.touchpoints);
}

Touchpoint Recording

A new touchpoint is recorded when:

  • utm_source changes, OR
  • utm_campaign changes

Storage

LocalStorage

Key Content Retention
attribution_utm_data UTM attribution data 30 days
attribution_session Session information Session-based

IndexedDB

Store Content Retention
events Event queue 7 days (auto cleanup)

Automatic Cleanup

  • UTM Data: Expired data removed on next access
  • Events: Old events (>7 days) cleaned up periodically
  • Quota Exceeded: Oldest 20% of data removed automatically

Offline Support

How It Works

User goes offline
  โ””โ”€โ”€ Events queued in IndexedDB

User tracks events
  โ””โ”€โ”€ Events stored locally

User goes online
  โ””โ”€โ”€ SDK detects connection restore
  โ””โ”€โ”€ Queued events sent to server

Page unload
  โ””โ”€โ”€ SDK attempts to flush pending events

Retry Strategy

  • Failed requests retry with exponential backoff
  • Default: 3 retries with 1s base delay
  • Delay: baseDelay * 2^attemptNumber

API Reference

Core Functions

init(config: SDKConfig): Promise<AttributionSDK>

Initialize the SDK with configuration.

const sdk = await init({ apiKey: "your_key" });

getSDK(): AttributionSDK | null

Get the current SDK instance.

const sdk = getSDK();
if (sdk) {
  // SDK is initialized
}

waitForSDK(): Promise<AttributionSDK>

Wait for SDK initialization (useful with auto-init).

const sdk = await waitForSDK();

Event Functions

trackEvent(eventType, eventData?, tracking_user_id?, revenue?, currency?): Promise<void>

Track a custom event.

trackPageView(pageData?, tracking_user_id?): Promise<void>

Track a page view event.

trackPurchase(tracking_user_id, revenue, currency?, purchaseData?): Promise<void>

Track a purchase event (sent immediately).

trackLogin(tracking_user_id, loginData?): Promise<void>

Track a login event (sent immediately).

trackSignup(tracking_user_id, signupData?): Promise<void>

Track a signup event (sent immediately).

trackFormSubmit(tracking_user_id?, formData?): Promise<void>

Track a form submission event (sent immediately).

trackVideoPlay(tracking_user_id?, videoData?): Promise<void>

Track a video play event.

await trackVideoPlay("user_123", {
  video_id: "video_123",
  video_title: "Introduction Video",
  duration: 120,
});

trackEmailVerification(tracking_user_id, verificationData?): Promise<void>

Track an email verification event (sent immediately).

await trackEmailVerification("user_123", {
  email: "user@example.com",
  verification_method: "email_link",
});

trackProductView(tracking_user_id?, productData?): Promise<void>

Track a product view event.

await trackProductView("user_123", {
  product_id: "prod_123",
  product_name: "Widget",
  category: "electronics",
});

trackAddToCart(tracking_user_id?, cartData?): Promise<void>

Track an add to cart event.

await trackAddToCart("user_123", {
  product_id: "prod_123",
  product_name: "Widget",
  quantity: 2,
  price: 29.99,
});

trackCustomEvent(customEventName, eventData?, tracking_user_id?, revenue?, currency?): Promise<void>

Track a user-defined custom event. The customEventName is required and must be a non-empty string.

Parameter Type Required Description
customEventName string Yes Event name (e.g. "webinar_registered")
eventData object No Arbitrary key-value payload
tracking_user_id string No User identifier; falls back to stored user ID
revenue number No Revenue amount
currency Currency No Currency code (default: Currency.USD)
await trackCustomEvent("feature_used", {
  feature: "export_csv",
  records_count: 500,
});

Custom events are batched. Call flush() to force immediate delivery.

Attribution Functions

getAttributionData(): AttributionData | null

Get current attribution data.

addUTMToURL(url: string): string

Add current UTM parameters to a URL.

getCurrentUTMParams(): Record<string, string>

Get current UTM parameters as object.

Utility Functions

flush(): Promise<void>

Flush all pending events to the server.

getStatus(): SDKStatus | null

Get SDK status including initialization state, session info, queue size, and SPA tracking status.

const status = getStatus();
// {
//   initialized: true,
//   session: { sessionId: "...", startTime: ..., lastActivity: ..., pageViews: 0 },
//   queueSize: 5,
//   online: true,
//   crossDomainUTM: {
//     enabled: true,
//     currentParams: { utm_source: "google" }
//   },
//   spaTracking: {
//     enabled: true,
//     currentPath: "/products"
//   }
// }

destroy(): void

Destroy SDK instance and clean up resources.


Usage Patterns

Global Window Object (CDN)

// Access via window.getuaiSDK namespace
await window.getuaiSDK.init({ apiKey: "your_key" });
await window.getuaiSDK.trackPageView();
await window.getuaiSDK.trackPurchase("user_123", 99.99);

// Access enums
const eventType = window.getuaiSDK.EventType.PURCHASE;
const currency = window.getuaiSDK.Currency.USD;

Static Methods (Advanced)

import { AttributionSDK, EventType } from "getu-attribution-v2-sdk";

// Use static methods
await AttributionSDK.init({ apiKey: "your_key" });
await AttributionSDK.trackEvent(EventType.PAGE_VIEW);
await AttributionSDK.trackPurchase("user_123", 99.99);

const attribution = AttributionSDK.getAttributionData();
const status = AttributionSDK.getStatus();

Custom Instance

import { AttributionSDK } from "getu-attribution-v2-sdk";

const sdk = new AttributionSDK({
  apiKey: "your_key",
  enableDebug: true,
});

await sdk.init();
await sdk.trackPageView();

Event Listeners

// Listen for SDK ready
window.addEventListener("getuaiSDKReady", (event) => {
  console.log("SDK initialized:", event.detail.sdk);
});

// Listen for SDK errors
window.addEventListener("getuaiSDKError", (event) => {
  console.error("SDK error:", event.detail.error);
});

TypeScript Support

import {
  init,
  trackEvent,
  EventType,
  Currency,
  type SDKConfig,
  type EventData,
  type AttributionData,
} from "getu-attribution-v2-sdk";

const config: SDKConfig = {
  apiKey: "your_api_key_here",
  enableDebug: true,
  autoTrackPageView: true,
};

await init(config);

// Type-safe event tracking
await trackEvent(
  EventType.PURCHASE,
  { product_id: "123" },
  "user_123",
  99.99,
  Currency.USD
);

// Type-safe attribution data
const attribution: AttributionData | null = getAttributionData();

Browser Support

Browser Minimum Version
Chrome 50+
Firefox 50+
Safari 10+
Edge 79+

Required APIs

  • localStorage
  • IndexedDB
  • history.pushState/replaceState
  • fetch
  • Promise

Debug Mode

Enable debug logging to see detailed SDK activity:

<!-- Via script tag -->
<script src="..." data-api-key="your_key" data-debug="true"></script>
// Via config
await init({
  apiKey: "your_key",
  enableDebug: true,
});

Console Output Examples

[GetuAI Info] ๐Ÿš€ GetuAI Attribution SDK initialized successfully
[GetuAI Info] ๐Ÿ“„ Auto track page view enabled (including SPA route tracking)
[GetuAI Debug] ๐Ÿ”„ [SPA] Route change detected (pushState): /home -> /products
[GetuAI Debug] โœ… [SPA] Page view tracked for: /products
[GetuAI Info] UTM data extracted and stored successfully

Error Handling

try {
  await trackPurchase("user_123", 99.99, Currency.USD, {
    product_id: "prod_123",
  });
} catch (error) {
  console.error("Failed to track purchase:", error);
  // Event will be queued for retry automatically
}

Events that fail to send are:

  1. Stored in IndexedDB
  2. Retried with exponential backoff
  3. Sent when connection restores

License

MIT