@tranthor/sdk-node
Version:
Tranthor's node sdk for customer engagement.
284 lines • 9.09 kB
JavaScript
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.TranthorSdk = void 0;
const sdk_core_library_1 = require("@tranthor/sdk-core-library");
const cross_fetch_1 = __importDefault(require("cross-fetch"));
const uuid_1 = require("uuid");
__exportStar(require("@tranthor/sdk-core-library"), exports);
/**
* Tranthor Node.js SDK. Use it to send events to Tranthor, a
* customer engagement on autopilot.
* @class
*
* @example
* ```typescript
* import { TranthorSdk } from '@tranthor/sdk-node';
*
* // Initialize with workspace credentials
* await TranthorSdk.init({
* writeKey: 'Basic your-write-key-here',
* host: 'https://app.tranthor.com' // Optional custom endpoint
* });
*
* // Identify user with events and record attributes about them. Save user id and an identify user and add attributes about them.
* // This is how you can add optional attributes like email, name, etc.
* TranthorSdk.identify({
* userId: 'user_123',
* traits: {
* email: 'marc@legend.com',
* firstName: 'Marc',
* lastName: 'Legend',
* plan: 'premium'
* }
* });
*
* // Track custom events with properties where you record actions your users perform and any properties about the action.
* TranthorSdk.track({
* userId: 'user_123',
* event: 'purchase_completed',
* properties: {
* amount: 49.99,
* currency: 'USD'
* }
* });
*
* // Here you can record specific screen engagement on the mobile devices.
* // along with any properties about the screen.
* TranthorSdk.screen({
* userId: 'user_123',
* name: 'restaurant_screen',
* properties: {
* order_id: '1234567890',
* restaurant_name: 'The best restaurant',
* items: ['burger', 'fries', 'soda']
* }
* });
*
* // Flush pending events to Tranthor. This is important for async events to ensure they are sent synchronously.
* await TranthorSdk.flush();
* ```
*/
class TranthorSdk {
static createBaseSdk(initParams) {
return new sdk_core_library_1.TranthorSdkBase(Object.assign({ uuid: () => (0, uuid_1.v4)(), issueRequest: (data_1, _a) => __awaiter(this, [data_1, _a], void 0, function* (data, { host = "https://tranthor.com", writeKey }) {
const url = `${host}/api/public/apps/batch`;
const headers = {
authorization: writeKey,
"Content-Type": "application/json",
};
const response = yield (0, cross_fetch_1.default)(url, {
method: "POST",
headers: headers,
body: JSON.stringify(data),
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
}), setTimeout,
clearTimeout }, initParams));
}
/**
* Initialize singleton SDK instance
* @param initParams - Configuration parameters
* @returns Promise resolving to initialized SDK instance
*
* @example
* ```typescript
* // Basic initialization
* const sdk = await TranthorSdk.init({
* writeKey: 'Basic your-key-here'
* });
* ```
*/
static init(initParams) {
return __awaiter(this, void 0, void 0, function* () {
if (!TranthorSdk.instance) {
const baseSdk = this.createBaseSdk(initParams);
TranthorSdk.instance = new TranthorSdk(baseSdk);
}
return TranthorSdk.instance;
});
}
/**
* Create new SDK instance (non-singleton)
* @param initParams - Configuration parameters
* @returns Promise resolving to new SDK instance
*
* @example
* ```typescript
* // Multi-instance scenario
* const adminSdk = await TranthorSdk.initNew({
* writeKey: 'admin-key'
* });
*
* const clientSdk = await TranthorSdk.initNew({
* writeKey: 'client-key'
* });
* ```
*/
static initNew(initParams) {
return __awaiter(this, void 0, void 0, function* () {
const baseSdk = this.createBaseSdk(initParams);
return new TranthorSdk(baseSdk);
});
}
constructor(baseSdk) {
this.baseSdk = baseSdk;
}
/**
* Record user identity and attributes. This is how you can add optional attributes like email, name, etc.
* @param params - Identification payload
* @returns
* @example
* ```typescript
* // Basic user identification
* TranthorSdk.identify({
* userId: '123',
* traits: {
* name: 'Alice Smith',
* accountStatus: 'active'
* }
* });
* ```
*/
static identify(params) {
if (!this.instance) {
return;
}
return this.instance.identify(params);
}
identify(params) {
return this.baseSdk.identify(params);
}
/**
* Track custom event with properties where you record actions your users perform and any properties about the action.
* @param params - Event tracking payload
* @returns
*
* @example
* ```typescript
* // Track subscription event
* TranthorSdk.track({
* userId: '123',
* event: 'subscription_created',
* properties: {
* plan: 'pro',
* trial_days: 14
* }
* });
* ```
*/
static track(params) {
if (!this.instance) {
return;
}
return this.instance.track(params);
}
track(params) {
return this.baseSdk.track(params);
}
/**
* Record page view with metadata about the page. This is how you can record page views on the web.
* @param params - Page view payload
* @returns
* @example
* ```typescript
* // Track dashboard page view
* TranthorSdk.page({
* userId: '123',
* name: 'Dashboard',
* properties: {
* tab: 'analytics',
* referrer: 'https://search.example.com'
* }
* });
* ```
*/
static page(params) {
if (!this.instance) {
return;
}
return this.instance.page(params);
}
page(params) {
return this.baseSdk.page(params);
}
/**
* Record mobile screen view with context about the screen. This is how you can record screen views on the mobile devices.
* @param params - Screen view payload
* @returns
*
* @example
* ```typescript
* // Track mobile settings screen
* TranthorSdk.screen({
* userId: '123',
* name: 'Settings',
* properties: {
* section: 'notifications',
* os_version: '14.4.1'
* }
* });
* ```
*/
static screen(params) {
if (!this.instance) {
return;
}
return this.instance.screen(params);
}
screen(params) {
return this.baseSdk.screen(params);
}
/**
* Immediately send all queued events
* @returns Promise resolving when flush completes
* @returns
* @example
* ```typescript
* // Flush before application exit
* process.on('SIGTERM', async () => {
* await TranthorSdk.flush();
* process.exit(0);
* });
* ```
*/
static flush() {
if (!this.instance) {
return;
}
return this.instance.flush();
}
flush() {
return this.baseSdk.flush();
}
}
exports.TranthorSdk = TranthorSdk;
TranthorSdk.instance = null;
//# sourceMappingURL=index.js.map
;