@cartai2025/sdk
v1.0.2
Published
Comprehensive CartAI SDK with device fingerprinting, browser event tracking, and Socket.IO integration
Maintainers
Readme
CartAI SDK
Comprehensive JavaScript SDK for device fingerprinting, browser event tracking, and real-time analytics with Socket.IO integration.
🚀 Features
Core Functionality
- Device Fingerprinting: Advanced browser identification with fallback support
- Socket.IO Integration: Real-time communication with CartAI backend
- Browser Event Tracking: Comprehensive user behavior analytics
- Auto-Detection: Email and phone number capture from form inputs
- Session Management: Cross-session user tracking and analytics
- TypeScript Support: Full type definitions included
Browser Events Tracking
- URL Changes: Page navigation and time spent tracking
- Form Inputs: Email/phone capture with automatic visitor linking
- Click Events: User interaction monitoring with element details
- Scroll Events: Engagement tracking and scroll behavior analysis
- Payment Events: Transaction status and payment method tracking
- Sales Events: Product views, cart actions, and purchase funnel analysis
- Custom Events: Track any custom user interactions
Advanced Features
- Automatic Event Batching: Efficient event sending with configurable batch sizes
- Fallback Fingerprinting: Works even without CartAI Device SDK
- Real-time Analytics: Live updates and behavior insights
- Cross-Device Tracking: Enhanced visitor identification
- Debug Mode: Comprehensive logging for development
- Multi-Format Builds: IIFE, UMD, CJS, and ESM support
📦 Installation
NPM/Yarn
npm install @cartai2025/sdk socket.io-client
# or
yarn add @cartai2025/sdk socket.io-clientCDN (Browser)
<!-- Minified version -->
<script src="https://d24lz8mxe7yhfu.cloudfront.net/cartai-sdk/cartai-sdk.min.js"></script>
<!-- Development version -->
<script src="https://d24lz8mxe7yhfu.cloudfront.net/cartai-sdk/cartai-sdk.js"></script>🎯 Quick Start
Basic Setup
import { createCartAI } from '@cartai2025/sdk'
// Initialize the SDK
const cartai = await createCartAI({
serverUrl: 'http://localhost:8000',
apiKey: 'cartai_sk_4f8b5e9a2c1d3f6e8b7a9c2e4f1b8d5a3e7c9f2b4e6a8c1d3f5e7b9a2c4e6f8b1',
debug: true,
enableEventTracking: true
})
// Send fingerprint data
await cartai.sendFingerprint()
// Set user information
cartai.setUserInfo({
email: '[email protected]',
phone: '+1234567890'
})
// Track custom events
cartai.trackEvent({
type: 'custom',
data: {
action: 'button_click',
element: 'cta-button'
}
})Browser (IIFE)
<!DOCTYPE html>
<html>
<head>
<script src="./dist/cartai-sdk.min.js"></script>
</head>
<body>
<script>
// CartAI SDK is available as CartAISDK global
CartAISDK.createCartAI({
serverUrl: 'http://localhost:8000',
apiKey: 'your-api-key',
debug: true
}).then(async (cartai) => {
console.log('CartAI SDK initialized')
// Send fingerprint
await cartai.sendFingerprint()
// Track custom event
cartai.trackSales({
eventType: 'purchase',
productId: 'prod_123',
productName: 'Demo Product',
category: 'electronics',
value: 99.99
})
})
</script>
</body>
</html>🔧 Configuration
CartAIConfig Options
interface CartAIConfig {
serverUrl: string // Socket.IO server URL
apiKey: string // Authentication API key
loadOptions?: any // Device SDK options
autoConnect?: boolean // Auto-connect on init (default: true)
debug?: boolean // Debug logging (default: false)
enableEventTracking?: boolean // Auto event tracking (default: true)
customVisitorId?: string // Custom visitor ID
eventBatchSize?: number // Events per batch (default: 10)
eventSendInterval?: number // Batch send interval ms (default: 10000)
}📊 Event Tracking
Automatic Event Tracking
When enableEventTracking is true, the SDK automatically tracks:
- URL Changes: Page navigation with time spent
- Clicks: All click events with element details
- Scrolling: Scroll behavior and engagement
- Form Inputs: Input events with email/phone detection
- Page Visibility: Tab switching and focus changes
Manual Event Tracking
Form Input Events
cartai.trackFormInput({
inputType: 'email',
fieldName: 'signup-email',
value: '[email protected]',
isEmail: true,
fieldId: 'email-field'
})Payment Events
cartai.trackPayment({
status: 'completed',
amount: 99.99,
currency: 'USD',
transactionId: 'txn_123456',
paymentMethod: 'credit_card',
salesAttributes: {
productId: 'prod_123',
orderId: 'order_789'
}
})Sales Events
cartai.trackSales({
eventType: 'purchase',
productId: 'prod_123',
productName: 'Demo Product',
category: 'electronics',
value: 99.99,
salesAttributes: {
orderId: 'order_789',
couponCode: 'SAVE10'
}
})Custom Events
cartai.trackEvent({
type: 'custom',
data: {
eventType: 'video_play',
videoId: 'demo_video',
duration: 120
}
})🔗 Socket.IO Integration
Server Events Sent
fingerprint-data: Device fingerprint databrowser-events: Batched browser eventsget-visitor-data: Request visitor informationget-stats: Request analytics
Server Events Received
fingerprint-stored: Fingerprint confirmationbrowser-events-processed: Events processed confirmationnew-browser-activity: Real-time activity updateserror: Error messages
🎮 API Reference
Main Methods
createCartAI(config: CartAIConfig): Promise<CartAI>
Factory function to create and initialize the SDK.
initialize(): Promise<void>
Initialize the SDK (called automatically by createCartAI).
connect(): Promise<void>
Connect to Socket.IO server.
disconnect(): void
Disconnect from server and cleanup.
getFingerprint(): Promise<FingerprintResult>
Get device fingerprint data.
sendFingerprint(customData?: Record<string, any>): Promise<void>
Send fingerprint to server.
User & Location Data
setUserInfo(userInfo: UserInfo): void
Set user information for enhanced tracking.
setLocationData(locationData: LocationData): void
Set location data for user tracking.
Event Tracking Methods
trackEvent(event: BrowserEvent): void
Track a custom browser event.
trackFormInput(data: FormInputData): void
Track form input with auto email/phone detection.
trackPayment(data: PaymentData): void
Track payment events.
trackSales(data: SalesData): void
Track sales events.
sendBrowserEvents(events?: BrowserEvent[]): Promise<void>
Send browser events to server.
Utility Methods
getSessionInfo(): SessionInfo
Get current session information.
getQueuedEvents(): BrowserEvent[]
Get queued events.
clearQueuedEvents(): void
Clear queued events.
🏗️ Build & Development
Build Commands
# Install dependencies
npm install
# Build all formats
npm run build
# Build with watch mode
npm run dev
# Lint code
npm run lint
# Fix lint issues
npm run lint:fixOutput Formats
cartai-sdk.js- IIFE for direct browser usecartai-sdk.min.js- Minified IIFEcartai-sdk.umd.js- UMD for universal usagecartai-sdk.umd.min.js- Minified UMDcartai-sdk.cjs.js- CommonJS for Node.jscartai-sdk.esm.js- ES modules for bundlerscartai-sdk.d.ts- TypeScript definitions
🔒 Security & Privacy
- API Key Authentication: Secure Socket.IO connections
- Password Field Exclusion: Passwords are never tracked
- Data Truncation: Form values limited to prevent large data
- Debug Mode Control: Sensitive data logging controlled by debug flag
🌐 Browser Compatibility
- Modern Browsers: Chrome 60+, Firefox 60+, Safari 12+, Edge 79+
- Legacy Support: Graceful degradation for older browsers
- Mobile Support: iOS Safari 12+, Android Chrome 60+
🤝 Integration with CartAI Device SDK
The SDK works seamlessly with @cartai2025/device-sdk:
<!-- Include both SDKs -->
<script src="./path-to/cartai.min.js"></script>
<script src="./path-to/cartai-sdk.min.js"></script>
<script>
// CartAI Device SDK will be detected automatically
CartAISDK.createCartAI({
serverUrl: 'http://localhost:8000',
apiKey: 'your-api-key'
}).then(cartai => {
// Full fingerprinting + event tracking ready
})
</script>📈 Example Use Cases
E-commerce Tracking
// Track product views
cartai.trackSales({
eventType: 'product_view',
productId: 'prod_123',
productName: 'Wireless Headphones',
category: 'electronics',
value: 199.99
})
// Track add to cart
cartai.trackEvent({
type: 'custom',
data: {
action: 'add_to_cart',
productId: 'prod_123',
quantity: 1
}
})
// Track purchase
cartai.trackPayment({
status: 'completed',
amount: 199.99,
currency: 'USD',
transactionId: 'txn_abc123',
paymentMethod: 'credit_card'
})Lead Generation
// Form completion tracking
cartai.trackFormInput({
inputType: 'email',
fieldName: 'newsletter-signup',
value: '[email protected]',
isEmail: true
})
// Custom lead scoring
cartai.trackEvent({
type: 'custom',
data: {
action: 'whitepaper_download',
leadScore: 25,
category: 'high-intent'
}
})Content Analytics
// Article engagement
cartai.trackEvent({
type: 'custom',
data: {
action: 'article_read',
articleId: 'art_456',
readingTime: 180,
completion: 75
}
})
// Video engagement
cartai.trackEvent({
type: 'custom',
data: {
action: 'video_engagement',
videoId: 'vid_789',
watchTime: 120,
completion: 50
}
})🛠️ Troubleshooting
Common Issues
Connection Issues
// Check connection status
const sessionInfo = cartai.getSessionInfo()
console.log('Connected:', sessionInfo.isConnected)
// Manual reconnection
if (!sessionInfo.isConnected) {
await cartai.connect()
}Event Queue Management
// Check queued events
const queuedEvents = cartai.getQueuedEvents()
console.log(`${queuedEvents.length} events queued`)
// Force send events
await cartai.sendBrowserEvents()
// Clear queue if needed
cartai.clearQueuedEvents()Debug Mode
// Enable debug logging
const cartai = await createCartAI({
serverUrl: 'http://localhost:8000',
apiKey: 'your-api-key',
debug: true // Enable detailed logging
})📚 TypeScript Support
Full TypeScript definitions included:
import { CartAI, CartAIConfig, BrowserEvent, UserInfo } from '@cartai2025/sdk'
const config: CartAIConfig = {
serverUrl: 'http://localhost:8000',
apiKey: 'your-api-key',
debug: true
}
const cartai: CartAI = await createCartAI(config)
const userInfo: UserInfo = {
email: '[email protected]',
phone: '+1234567890',
userId: 'user_123'
}
cartai.setUserInfo(userInfo)🚀 Getting Started Checklist
- [ ] Install the SDK via npm or include via CDN
- [ ] Configure your CartAI backend server with Socket.IO
- [ ] Initialize the SDK with your server URL and API key
- [ ] Enable debug mode for development
- [ ] Test fingerprint collection and event tracking
- [ ] Set up user information and location data
- [ ] Implement custom event tracking for your use case
- [ ] Monitor real-time analytics in your backend
- [ ] Deploy to production with proper API keys
Need help? Check the troubleshooting section above or create an issue in the repository.
CartAI SDK - Powering comprehensive user analytics with device fingerprinting and real-time event tracking
