@toyef/arise-core
v0.3.2
Published
The core analytics library that provides the fundamental communication layer with the Arise API. This package includes basic event tracking, user identification, and session management functionality with full TypeScript support.
Readme
@toyef/arise-core
The core analytics library that provides the fundamental communication layer with the Arise API. This package includes basic event tracking, user identification, and session management functionality with full TypeScript support.
Installation
npm install @toyef/arise-coreQuick Start
1. Basic Setup
import { analytics } from '@toyef/arise-core';
// Track an event
const response = await analytics.trackEvent({
name: 'button_clicked',
properties: {
button_id: 'submit',
page: '/checkout'
},
context: {
projectId: 'your-project-id',
userId: 'user123'
}
});2. Track Page Views
import { analytics } from '@toyef/arise-core';
const response = await analytics.trackPage({
url: '/products/123',
title: 'Product Details',
referrer: 'https://google.com',
context: {
projectId: 'your-project-id',
userId: 'user123'
}
});3. Identify Users
import { analytics } from '@toyef/arise-core';
const response = await analytics.identifyUser({
traits: {
email: '[email protected]',
name: 'John Doe',
plan: 'premium'
},
context: {
projectId: 'your-project-id',
userId: 'user123'
}
});API Reference
Core Analytics Class
import { AriseAnalytics } from '@toyef/arise-core';
const analytics = new AriseAnalytics();Event Tracking
trackEvent(params)
Track custom events with properties.
const response = await analytics.trackEvent({
name: 'purchase_completed',
properties: {
product_id: 'abc123',
amount: 99.99,
currency: 'USD'
},
context: {
projectId: 'your-project-id',
userId: 'user123',
device: {
os: { name: 'iOS', version: '15.0' },
client: { name: 'Safari', version: '15.0', type: 'browser' },
device: { type: 'mobile', brand: 'Apple', model: 'iPhone 13' }
}
},
options: {
sessionId: 'session123',
timestamp: Date.now(),
updateLastActivity: true
}
});Parameters:
name(string): Event nameproperties(EventData, optional): Event propertiescontext(RequestContext): Request context including project ID and user infooptions(TrackingOptions, optional): Additional tracking options
Page View Tracking
trackPage(params)
Track page views for web applications.
const response = await analytics.trackPage({
url: '/dashboard',
title: 'User Dashboard',
referrer: '/login',
context: {
projectId: 'your-project-id',
userId: 'user123',
userAgent: navigator.userAgent
},
options: {
sessionId: 'session123',
updateLastActivity: true
}
});Parameters:
url(string): Page URLtitle(string, optional): Page titlereferrer(string, optional): Referrer URLcontext(RequestContext): Request contextoptions(TrackingOptions, optional): Additional tracking options
User Identification
identifyUser(params)
Associate user traits with a user ID.
const response = await analytics.identifyUser({
traits: {
email: '[email protected]',
name: 'John Doe',
age: 30,
plan: 'premium',
signup_date: '2024-01-15'
},
context: {
projectId: 'your-project-id',
userId: 'user123'
}
});Parameters:
traits(EventData): User propertiescontext(RequestContext): Request context
Session Management
endSession(params)
End a user session with duration and exit information.
const response = await analytics.endSession({
sessionId: 'session123',
duration: 1800000, // 30 minutes in milliseconds
exitPage: '/logout',
context: {
projectId: 'your-project-id',
userId: 'user123'
}
});Parameters:
sessionId(string): Session identifierduration(number): Session duration in millisecondsexitPage(string, optional): Last page visitedcontext(RequestContext): Request context
Types and Interfaces
RequestContext
interface RequestContext {
projectId?: string;
userId?: string;
uid?: string;
userAgent?: string;
device?: Device;
}Device Information
type Device = {
os: { name: string; version: string };
client: {
name: string;
type: string;
version: string;
};
device: {
type: string;
brand: string;
model: string;
};
};Event Data
type EventData = {
[key: string]: string | number | boolean | undefined;
};Tracking Options
interface TrackingOptions {
sessionId?: string;
timestamp?: number;
updateLastActivity?: boolean;
}Response Format
interface AriseResponse {
success: boolean;
userId?: string;
sessionId?: string;
timestamp: number;
requestId: string;
}Advanced Usage
Custom HTTP Client
import { httpClient, setEndpoint } from '@toyef/arise-core';
// Set custom API endpoint
setEndpoint('https://your-custom-api.com');
// Use the HTTP client directly
const response = await httpClient.sendRequest({
path: '/custom-endpoint',
context: {
projectId: 'your-project-id',
userId: 'user123'
},
body: {
custom_data: 'value'
}
});Legacy Compatibility Functions
import { track, page, identify, end } from '@toyef/arise-core';
// These are bound to the singleton analytics instance
await track({
name: 'event_name',
properties: { key: 'value' },
context: { projectId: 'your-project-id', userId: 'user123' }
});
await page({
url: '/page',
context: { projectId: 'your-project-id', userId: 'user123' }
});
await identify({
traits: { email: '[email protected]' },
context: { projectId: 'your-project-id', userId: 'user123' }
});
await end({
sessionId: 'session123',
duration: 1000,
context: { projectId: 'your-project-id', userId: 'user123' }
});Error Handling
import { analytics } from '@toyef/arise-core';
try {
const response = await analytics.trackEvent({
name: 'test_event',
context: {
projectId: 'your-project-id',
userId: 'user123'
}
});
if (response?.success) {
console.log('Event tracked successfully');
}
} catch (error) {
console.error('Failed to track event:', error);
// The error is handled gracefully, your app continues
}Batch Operations
import { analytics } from '@toyef/arise-core';
// Track multiple events
const events = [
{
name: 'page_view',
properties: { page: '/home' },
context: { projectId: 'your-project-id', userId: 'user1' }
},
{
name: 'button_click',
properties: { button: 'signup' },
context: { projectId: 'your-project-id', userId: 'user2' }
}
];
const responses = await Promise.all(
events.map(event => analytics.trackEvent(event))
);Environment Configuration
Development vs Production
import { analytics, setEndpoint } from '@toyef/arise-core';
// Set different endpoints for different environments
if (process.env.NODE_ENV === 'development') {
setEndpoint('https://dev-api.ariseapp.com');
} else {
setEndpoint('https://api.ariseapp.com');
}
// Track with environment context
await analytics.trackEvent({
name: 'app_started',
properties: {
environment: process.env.NODE_ENV,
version: process.env.APP_VERSION
},
context: {
projectId: process.env.ARISE_PROJECT_ID,
userId: 'user123'
}
});Integration Examples
React Hook
import { useEffect } from 'react';
import { analytics } from '@toyef/arise-core';
function useAnalytics(projectId, userId) {
const track = async (eventName, properties = {}) => {
return await analytics.trackEvent({
name: eventName,
properties,
context: { projectId, userId }
});
};
const page = async (url, title) => {
return await analytics.trackPage({
url,
title,
context: { projectId, userId }
});
};
const identify = async (traits) => {
return await analytics.identifyUser({
traits,
context: { projectId, userId }
});
};
return { track, page, identify };
}Node.js Middleware
const { analytics } = require('@toyef/arise-core');
function analyticsMiddleware(projectId) {
return async (req, res, next) => {
const startTime = Date.now();
res.on('finish', async () => {
await analytics.trackEvent({
name: 'api_request',
properties: {
method: req.method,
url: req.originalUrl,
status: res.statusCode,
duration: Date.now() - startTime
},
context: {
projectId,
userId: req.user?.id,
userAgent: req.get('User-Agent')
}
});
});
next();
};
}Performance Considerations
- All API calls are asynchronous and non-blocking
- Failed requests return
nullinstead of throwing errors - Network errors are logged but don't crash your application
- Consider implementing retry logic for critical events
Security
- All requests are sent over HTTPS
- API endpoints validate request signatures
- User data is handled according to privacy regulations
- No sensitive data is logged or stored locally
Browser Support
- Modern browsers with fetch API support
- Node.js 10+
- React Native with fetch polyfill
License
MIT
Support
For issues and questions, please visit our documentation or create an issue on GitHub.
