New Research: Supply Chain Attack on Axios Pulls Malicious Dependency from npm.Details
Socket
Book a DemoSign in
Socket

@loopkit/javascript

Package Overview
Dependencies
Maintainers
1
Versions
13
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@loopkit/javascript - npm Package Compare versions

Comparing version
1.0.6
to
1.1.0
+70
dist/core/BrowserFeatures.d.ts
import type { LoopKitConfig, IBrowserFeatures } from '../types/index.js';
import type { Logger } from '../utils/Logger.js';
import type { EventTracker } from './EventTracker.js';
import type { SessionManager } from './SessionManager.js';
import type { QueueManager } from './QueueManager.js';
import type { INetworkManager } from '../types/index.js';
/**
* Browser features for auto-tracking and browser-specific functionality
*/
export declare class BrowserFeatures implements IBrowserFeatures {
private config;
private logger;
private eventTracker;
private sessionManager;
private queueManager;
private networkManager?;
private clickHandler?;
private errorHandler?;
private unloadHandler?;
constructor(config: LoopKitConfig, logger: Logger, eventTracker: EventTracker, sessionManager: SessionManager, queueManager: QueueManager);
/**
* Setup all browser features based on configuration
*/
setupFeatures(): void;
/**
* Setup automatic click tracking
*/
setupAutoClickTracking(): void;
/**
* Setup automatic page view tracking
*/
setupAutoPageViews(): void;
/**
* Setup error tracking
*/
setupErrorTracking(): void;
/**
* Setup page unload handling
*/
setupPageUnloadHandling(): void;
/**
* Update configuration
*/
updateConfig(config: LoopKitConfig): void;
/**
* Set network manager
*/
setNetworkManager(networkManager: INetworkManager): void;
/**
* Track a page view
*/
private trackPageView;
/**
* Find clickable element by walking up the DOM
*/
private findClickableElement;
/**
* Extract click properties from element
*/
private extractClickProperties;
/**
* Get element type for analytics
*/
private getElementType;
/**
* Get readable text from element
*/
private getElementText;
}
//# sourceMappingURL=BrowserFeatures.d.ts.map
{"version":3,"file":"BrowserFeatures.d.ts","sourceRoot":"","sources":["../../src/core/BrowserFeatures.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AACzE,O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AAc;IAYtB;;OAEG;IACH,OAAO,CAAC,cAAc;CAYvB"}
import type { LoopKitConfig, TrackOptions } from '../types/index.js';
import type { Logger } from '../utils/Logger.js';
import type { QueueManager } from './QueueManager.js';
import type { SessionManager } from './SessionManager.js';
import type { IdGenerator } from '../utils/IdGenerator.js';
/**
* Event tracker for handling all event types
*/
export declare class EventTracker {
private config;
private logger;
private queueManager;
private sessionManager;
private idGenerator;
constructor(config: LoopKitConfig, logger: Logger, queueManager: QueueManager, sessionManager: SessionManager, idGenerator: IdGenerator);
/**
* Track an event
*/
track(eventName: string, properties?: Record<string, any>, options?: TrackOptions, context?: any): void;
/**
* Identify a user
*/
identify(userId: string, properties?: Record<string, any>): void;
/**
* Associate user with a group
*/
group(groupId: string, properties?: Record<string, any>, groupType?: string, context?: any): void;
/**
* Update configuration
*/
updateConfig(config: LoopKitConfig): void;
/**
* Create base event structure
*/
private createBaseEvent;
/**
* Create system information
*/
private createSystemInfo;
}
//# sourceMappingURL=EventTracker.d.ts.map
{"version":3,"file":"EventTracker.d.ts","sourceRoot":"","sources":["../../src/core/EventTracker.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,aAAa,EACb,YAAY,EAMb,MAAM,mBAAmB,CAAC;AAC3B,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AACjD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAC1D,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAC;AAK3D;;GAEG;AACH,qBAAa,YAAY;IACvB,OAAO,CAAC,MAAM,CAAgB;IAC9B,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,YAAY,CAAe;IACnC,OAAO,CAAC,cAAc,CAAiB;IACvC,OAAO,CAAC,WAAW,CAAc;gBAG/B,MAAM,EAAE,aAAa,EACrB,MAAM,EAAE,MAAM,EACd,YAAY,EAAE,YAAY,EAC1B,cAAc,EAAE,cAAc,EAC9B,WAAW,EAAE,WAAW;IAS1B;;OAEG;IACH,KAAK,CACH,SAAS,EAAE,MAAM,EACjB,UAAU,GAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAM,EACpC,OAAO,GAAE,YAAiB,EAC1B,OAAO,GAAE,GAAQ,GAChB,IAAI;IA8CP;;OAEG;IACH,QAAQ,CAAC,MAAM,EAAE,MAAM,EAAE,UAAU,GAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAM,GAAG,IAAI;IAkCpE;;OAEG;IACH,KAAK,CACH,OAAO,EAAE,MAAM,EACf,UAAU,GAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAM,EACpC,SAAS,GAAE,MAAuB,EAClC,OAAO,GAAE,GAAQ,GAChB,IAAI;IAkCP;;OAEG;IACH,YAAY,CAAC,MAAM,EAAE,aAAa,GAAG,IAAI;IAIzC;;OAEG;IACH,OAAO,CAAC,eAAe;IAUvB;;OAEG;IACH,OAAO,CAAC,gBAAgB;CAiCzB"}
import type { LoopKitConfig, ILoopKit, TrackOptions, BatchEventInput } from '../types';
import { Logger } from '../utils/Logger';
import { IdGenerator } from '../utils/IdGenerator';
import { StorageManager } from './StorageManager';
import { SessionManager } from './SessionManager';
import { QueueManager } from './QueueManager';
import { EventTracker } from './EventTracker';
import { NetworkManager } from './NetworkManager';
import { BrowserFeatures } from './BrowserFeatures';
/**
* Main LoopKit SDK class
*/
export declare class LoopKit implements ILoopKit {
readonly version: string;
config: LoopKitConfig;
initialized: boolean;
userId: string | null;
userProperties: Record<string, any>;
groupId: string | null;
groupProperties: Record<string, any>;
logger: Logger;
idGenerator: IdGenerator;
storageManager: StorageManager;
sessionManager: SessionManager;
queueManager: QueueManager;
eventTracker: EventTracker;
networkManager: NetworkManager;
browserFeatures?: BrowserFeatures;
constructor();
/**
* Initialize LoopKit with API key and configuration
*/
init(apiKey: string, config?: Partial<LoopKitConfig>): LoopKit;
/**
* Update configuration
*/
configure(config: Partial<LoopKitConfig>): LoopKit;
/**
* Get current configuration
*/
getConfig(): LoopKitConfig;
/**
* Track an event
*/
track(eventName: string, properties?: Record<string, any>, options?: TrackOptions): LoopKit;
/**
* Track multiple events in batch
*/
trackBatch(events: BatchEventInput[]): LoopKit;
/**
* Identify a user
*/
identify(userId: string, properties?: Record<string, any>): LoopKit;
/**
* Associate user with a group
*/
group(groupId: string, properties?: Record<string, any>, groupType?: string): LoopKit;
/**
* Manually flush queued events
*/
flush(): Promise<void>;
/**
* Get current queue size
*/
getQueueSize(): number;
/**
* Reset SDK state
*/
reset(): void;
/**
* Reset for testing (internal method)
*/
resetForTesting(): void;
}
//# sourceMappingURL=LoopKit.d.ts.map
{"version":3,"file":"LoopKit.d.ts","sourceRoot":"","sources":["../../src/core/LoopKit.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,aAAa,EACb,QAAQ,EACR,YAAY,EACZ,eAAe,EAChB,MAAM,UAAU,CAAC;AAElB,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AACzC,OAAO,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AACnD,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9C,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9C,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAIpD;;GAEG;AACH,qBAAa,OAAQ,YAAW,QAAQ;IAEtC,SAAgB,OAAO,EAAE,MAAM,CAC8B;IAGtD,MAAM,EAAE,aAAa,CAmB1B;IAGK,WAAW,EAAE,OAAO,CAAS;IAG7B,MAAM,EAAE,MAAM,GAAG,IAAI,CAAQ;IAC7B,cAAc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AEG;IACH,eAAe,IAAI,IAAI;CAoCxB"}
import type { LoopKitConfig, INetworkManager } from '../types/index.js';
import type { Logger } from '../utils/Logger.js';
/**
* Network manager for handling API communication
*/
export declare class NetworkManager implements INetworkManager {
private config;
private logger;
constructor(config: LoopKitConfig, logger: Logger);
/**
* Send events to API with retry logic
*/
sendEvents(endpoint: string, payload: any, retryCount?: number): Promise<any>;
/**
* Send beacon for page unload (fallback for critical events)
*/
sendBeacon(endpoint: string, payload: any): boolean;
/**
* Update configuration
*/
updateConfig(config: LoopKitConfig): void;
/**
* Calculate retry delay based on backoff strategy
*/
private calculateRetryDelay;
/**
* Sleep utility for retry delays
*/
private sleep;
/**
* Get event count from payload for logging
*/
private getEventCountFromPayload;
}
//# sourceMappingURL=NetworkManager.d.ts.map
{"version":3,"file":"NetworkManager.d.ts","sourceRoot":"","sources":["../../src/core/NetworkManager.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AACxE,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAEjD;;GAEG;AACH,qBAAa,cAAe,YAAW,eAAe;IACpD,OAAO,CAAC,MAAM,CAAgB;IAC9B,OAAO,CAAC,MAAM,CAAS;gBAEX,MAAM,EAAE,aAAa,EAAE,MAAM,EAAE,MAAM;IAKjD;;OAEG;IACG,UAAU,CACd,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE,GAAG,EACZ,UAAU,GAAE,MAAU,GACrB,OAAO,CAAC,GAAG,CAAC;IA8Hf;;OAEG;IACH,UAAU,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,GAAG,GAAG,OAAO;IAiCnD;;OAEG;IACH,YAAY,CAAC,MAAM,EAAE,aAAa,GAAG,IAAI;IAIzC;;OAEG;IACH,OAAO,CAAC,mBAAmB;IAW3B;;OAEG;IACH,OAAO,CAAC,KAAK;IAIb;;OAEG;IACH,OAAO,CAAC,wBAAwB;CAmBjC"}
import type { LoopKitConfig, IQueueManager, INetworkManager, TrackEvent, IdentifyEvent, GroupEvent } from '../types/index.js';
import type { Logger } from '../utils/Logger.js';
import type { StorageManager } from './StorageManager.js';
interface QueuedEvent {
type: 'track' | 'identify' | 'group';
event: TrackEvent | IdentifyEvent | GroupEvent;
}
/**
* Queue manager for handling event batching and flushing
*/
export declare class QueueManager implements IQueueManager {
private config;
private logger;
private storageManager;
private networkManager?;
eventQueue: QueuedEvent[];
private flushTimer?;
private isInitialized;
constructor(config: LoopKitConfig, logger: Logger, storageManager: StorageManager);
/**
* Add event to queue
*/
enqueueEvent(event: TrackEvent | IdentifyEvent | GroupEvent): void;
/**
* Flush events to API
*/
flush(networkManager: INetworkManager): Promise<void>;
/**
* Get current queue
*/
getQueue(): QueuedEvent[];
/**
* Get queue size
*/
getQueueSize(): number;
/**
* Clear queue
*/
clearQueue(): void;
/**
* Reset queue state
*/
reset(): void;
/**
* Update configuration
*/
updateConfig(config: LoopKitConfig): void;
/**
* Set network manager
*/
setNetworkManager(networkManager: INetworkManager): void;
/**
* Schedule auto-flush
*/
scheduleFlush(): void;
/**
* Restart auto-flush with new config
*/
restartAutoFlush(): void;
/**
* Stop auto-flush timer
*/
private stopAutoFlush;
/**
* Persist queue to storage
*/
private persistQueue;
/**
* Load persisted queue from storage
*/
private loadPersistedQueue;
}
export {};
//# sourceMappingURL=QueueManager.d.ts.map
{"version":3,"file":"QueueManager.d.ts","sourceRoot":"","sources":["../../src/core/QueueManager.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,aAAa,EACb,aAAa,EACb,eAAe,EACf,UAAU,EACV,aAAa,EACb,UAAU,EACX,MAAM,mBAAmB,CAAC;AAC3B,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AACjD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAE1D,UAAU,WAAW;IACnB,IAAI,EAAE,OAAO,GAAG,UAAU,GAAG,OAAO,CAAC;IACrC,KAAK,EAAE,UAAU,GAAG,aAAa,GAAG,UAAU,CAAC;CAChD;AAED;;GAEG;AACH,qBAAa,YAAa,YAAW,aAAa;IAChD,OAAO,CAAC,MAAM,CAAgB;IAC9B,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,cAAc,CAAiB;IACvC,OAAO,CAAC,cAAc,CAAC,CAAkB;IAElC,UAAU,EAAE,WAAW,EAAE,CAAM;IACtC,OAAO,CAAC,UAAU,CAAC,CAAiB;IACpC,OAAO,CAAC,aAAa,CAAS;gBAG5B,MAAM,EAAE,aAAa,EACrB,MAAM,EAAE,MAAM,EACd,cAAc,EAAE,cAAc;IAUhC;;OAEG;IACH,YAAY,CAAC,KAAK,EAAE,UAAU,GAAG,aAAa,GAAG,UAAU,GAAG,IAAI;IA0ClE;;OAEG;IACG,KAAK,CAAC,cAAc,EAAE,eAAe,GAAG,OAAO,CAAC,IAAI,CAAC;IA6F3D;;OAEG;IACH,QAAQ,IAAI,WAAW,EAAE;IAIzB;;OAEG;IACH,YAAY,IAAI,MAAM;IAItB;;OAEG;IACH,UAAU,IAAI,IAAI;IAMlB;;OAEG;IACH,KAAK,IAAI,IAAI;IAMb;;OAEG;IACH,YAAY,CAAC,MAAM,EAAE,aAAa,GAAG,IAAI;IAIzC;;OAEG;IACH,iBAAiB,CAAC,cAAc,EAAE,eAAe,GAAG,IAAI;IAIxD;;OAEG;IACH,aAAa,IAAI,IAAI;IAWrB;;OAEG;IACH,gBAAgB,IAAI,IAAI;IAKxB;;OAEG;IACH,OAAO,CAAC,aAAa;IAOrB;;OAEG;IACH,OAAO,CAAC,YAAY;IAUpB;;OAEG;IACH,OAAO,CAAC,kBAAkB;CAe3B"}
import type { LoopKitConfig, ISessionManager } from '../types/index.js';
import type { Logger } from '../utils/Logger.js';
import type { IdGenerator } from '../utils/IdGenerator.js';
import type { StorageManager } from './StorageManager.js';
/**
* Session manager for handling user sessions and anonymous IDs
*/
export declare class SessionManager implements ISessionManager {
private config;
private logger;
private idGenerator;
private storageManager;
private sessionId;
private anonymousId;
private lastActivityTime;
constructor(config: LoopKitConfig, logger: Logger, idGenerator: IdGenerator, storageManager: StorageManager);
/**
* Get current session ID
*/
getSessionId(): string;
/**
* Get anonymous ID
*/
getAnonymousId(): string;
/**
* Start new session
*/
startSession(): void;
/**
* End current session
*/
endSession(): void;
/**
* Check if session is active
*/
isSessionActive(): boolean;
/**
* Update activity timestamp
*/
updateActivity(): void;
/**
* Update configuration
*/
updateConfig(config: LoopKitConfig): void;
/**
* Reset session state
*/
reset(): void;
/**
* Load existing anonymous ID or create new one
*/
private loadOrCreateAnonymousId;
}
//# sourceMappingURL=SessionManager.d.ts.map
{"version":3,"file":"SessionManager.d.ts","sourceRoot":"","sources":["../../src/core/SessionManager.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AACxE,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AACjD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAC;AAC3D,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAE1D;;GAEG;AACH,qBAAa,cAAe,YAAW,eAAe;IACpD,OAAO,CAAC,MAAM,CAAgB;IAC9B,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,WAAW,CAAc;IACjC,OAAO,CAAC,cAAc,CAAiB;IAEvC,OAAO,CAAC,SAAS,CAAS;IAC1B,OAAO,CAAC,WAAW,CAAS;IAC5B,OAAO,CAAC,gBAAgB,CAAS;gBAG/B,MAAM,EAAE,aAAa,EACrB,MAAM,EAAE,MAAM,EACd,WAAW,EAAE,WAAW,EACxB,cAAc,EAAE,cAAc;IAsBhC;;OAEG;IACH,YAAY,IAAI,MAAM;IAKtB;;OAEG;IACH,cAAc,IAAI,MAAM;IAKxB;;OAEG;IACH,YAAY,IAAI,IAAI;IAMpB;;OAEG;IACH,UAAU,IAAI,IAAI;IAMlB;;OAEG;IACH,eAAe,IAAI,OAAO;IAW1B;;OAEG;IACH,cAAc,IAAI,IAAI;IAiBtB;;OAEG;IACH,YAAY,CAAC,MAAM,EAAE,aAAa,GAAG,IAAI;IAIzC;;OAEG;IACH,KAAK,IAAI,IAAI;IAMb;;OAEG;IACH,OAAO,CAAC,uBAAuB;CAahC"}
import type { LoopKitConfig, IStorageManager } from '../types/index.js';
import type { Logger } from '../utils/Logger.js';
/**
* Storage manager for localStorage operations
*/
export declare class StorageManager implements IStorageManager {
private config;
private logger;
constructor(config: LoopKitConfig, logger: Logger);
/**
* Update configuration
*/
updateConfig(config: LoopKitConfig): void;
/**
* Get localStorage instance with fallback
*/
private getStorage;
/**
* Persist event queue to localStorage with version tracking
*/
persistQueue(queue: any[]): void;
/**
* Load persisted queue from localStorage with version checking
*/
loadQueue(): any[];
/**
* Clear persisted queue from localStorage
*/
clearQueue(): void;
/**
* Load anonymous ID from localStorage
*/
loadAnonymousId(): string | null;
/**
* Save anonymous ID to localStorage
*/
saveAnonymousId(anonymousId: string): void;
/**
* Clear anonymous ID from localStorage
*/
clearAnonymousId(): void;
/**
* Clear all LoopKit data from localStorage
*/
clearAll(): void;
}
//# sourceMappingURL=StorageManager.d.ts.map
{"version":3,"file":"StorageManager.d.ts","sourceRoot":"","sources":["../../src/core/StorageManager.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AACxE,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAUjD;;GAEG;AACH,qBAAa,cAAe,YAAW,eAAe;IACpD,OAAO,CAAC,MAAM,CAAgB;IAC9B,OAAO,CAAC,MAAM,CAAS;gBAEX,MAAM,EAAE,aAAa,EAAE,MAAM,EAAE,MAAM;IAKjD;;OAEG;IACH,YAAY,CAAC,MAAM,EAAE,aAAa,GAAG,IAAI;IAIzC;;OAEG;IACH,OAAO,CAAC,UAAU;IAUlB;;OAEG;IACH,YAAY,CAAC,KAAK,EAAE,GAAG,EAAE,GAAG,IAAI;IAoBhC;;OAEG;IACH,SAAS,IAAI,GAAG,EAAE;IAiElB;;OAEG;IACH,UAAU,IAAI,IAAI;IAelB;;OAEG;IACH,eAAe,IAAI,MAAM,GAAG,IAAI;IAmBhC;;OAEG;IACH,eAAe,CAAC,WAAW,EAAE,MAAM,GAAG,IAAI;IAe1C;;OAEG;IACH,gBAAgB,IAAI,IAAI;IAexB;;OAEG;IACH,QAAQ,IAAI,IAAI;CAIjB"}
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,OAAO,EAAE,MAAM,mBAAmB,CAAC;AAG5C,QAAA,MAAM,OAAO,SAAgB,CAAC;AAG9B,eAAe,OAAO,CAAC;AAGvB,OAAO,EAAE,OAAO,EAAE,CAAC;AAGnB,YAAY,EACV,aAAa,EACb,QAAQ,EACR,YAAY,EACZ,SAAS,EACT,UAAU,EACV,aAAa,EACb,UAAU,EACV,UAAU,EACV,WAAW,EACX,oBAAoB,EACpB,eAAe,EACf,YAAY,EACZ,WAAW,EACX,UAAU,EACV,QAAQ,EACR,eAAe,EACf,eAAe,EACf,aAAa,EACb,eAAe,EACf,gBAAgB,EAEhB,MAAM,EACN,KAAK,EACL,UAAU,EACV,UAAU,EACV,OAAO,GACR,MAAM,kBAAkB,CAAC"}
/**
* Configuration options for LoopKit SDK
*/
export interface LoopKitConfig {
/** API key for authentication */
apiKey: string;
/** Base URL for the LoopKit API */
baseURL?: string;
/** Number of events to batch before auto-flushing */
batchSize?: number;
/** Interval in seconds to auto-flush events */
flushInterval?: number;
/** Maximum number of events to store in queue */
maxQueueSize?: number;
/** Enable gzip compression for requests */
enableCompression?: boolean;
/** Request timeout in milliseconds */
requestTimeout?: number;
/** Enable debug logging */
debug?: boolean;
/** Logging level */
logLevel?: LogLevel;
/** Enable automatic event capture */
enableAutoCapture?: boolean;
/** Enable automatic click tracking */
enableAutoClickTracking?: boolean;
/** Enable automatic error tracking */
enableErrorTracking?: boolean;
/** Enable session tracking */
enableSessionTracking?: boolean;
/** Session timeout in seconds */
sessionTimeout?: number;
/** Respect Do Not Track browser setting */
respectDoNotTrack?: boolean;
/** Enable localStorage for event persistence */
enableLocalStorage?: boolean;
/** Maximum number of retry attempts */
maxRetries?: number;
/** Retry backoff strategy */
retryBackoff?: RetryBackoff;
/** Callback before tracking events */
onBeforeTrack?: (event: TrackEvent) => TrackEvent | void;
/** Callback after successfully flushing events */
onAfterTrack?: (event: TrackEvent, success: boolean) => void;
/** Error callback */
onError?: (error: Error) => void;
}
/**
* Logging levels
*/
export type LogLevel = 'error' | 'warn' | 'info' | 'debug';
/**
* Retry backoff strategies
*/
export type RetryBackoff = 'exponential' | 'linear';
/**
* Base event properties
*/
export interface BaseEvent {
/** Unique anonymous identifier */
anonymousId: string;
/** ISO 8601 timestamp */
timestamp: string;
/** User ID (if identified) */
userId?: string | null;
/** System information */
system: SystemInfo;
}
/**
* Track event for analytics
*/
export interface TrackEvent extends BaseEvent {
/** Event name */
name: string;
/** Event properties */
properties?: Record<string, any>;
}
/**
* Identify event for user identification
*/
export interface IdentifyEvent extends BaseEvent {
/** User ID */
userId: string;
/** User properties */
properties?: Record<string, any>;
}
/**
* Group event for user-group association
*/
export interface GroupEvent extends BaseEvent {
/** User ID */
userId: string;
/** Group ID */
groupId: string;
/** Group type */
groupType: string;
/** Group properties */
properties?: Record<string, any>;
}
/**
* System information included with events
*/
export interface SystemInfo {
/** SDK information */
sdk: {
name: string;
version: string;
};
/** Session ID */
sessionId: string;
/** Browser/environment context */
context?: ContextInfo;
}
/**
* Browser and environment context
*/
export interface ContextInfo {
/** Page information */
page: {
url: string;
path: string;
search: string;
title: string;
referrer: string;
};
/** User agent string */
userAgent: string;
/** Screen dimensions */
screen: {
width: number;
height: number;
};
/** Viewport dimensions */
viewport: {
width: number;
height: number;
};
}
/**
* Click tracking event properties
*/
export interface ClickEventProperties {
/** Type of element clicked */
element_type: string;
/** Text content of element */
element_text: string;
/** Element ID */
element_id: string | null;
/** Element CSS classes */
element_class: string | null;
/** Element tag name */
element_tag: string;
/** Page where click occurred */
page: string;
/** Page title */
page_title: string;
/** Page URL */
page_url: string;
/** Click position */
position: {
x: number;
y: number;
};
/** Element href (for links) */
element_href?: string;
/** Element aria-label */
element_aria_label?: string;
/** DOM traversal depth to find clickable element */
traversal_depth?: number;
/** Original clicked element tag */
original_target_tag?: string;
}
/**
* Batch event input for trackBatch method
*/
export interface BatchEventInput {
/** Event name */
name: string;
/** Event properties */
properties?: Record<string, any>;
/** Event options */
options?: TrackOptions;
}
/**
* Options for tracking events
*/
export interface TrackOptions {
/** Override timestamp */
timestamp?: string;
/** Additional context */
context?: Record<string, any>;
}
/**
* API response structure
*/
export interface ApiResponse {
/** Response success status */
success: boolean;
/** Error message if failed */
message?: string;
/** Additional response data */
data?: any;
}
/**
* Network request payload structure
*/
export interface ApiPayload {
/** Track events */
tracks?: TrackEvent[];
/** Identify events */
identifies?: IdentifyEvent[];
/** Group events */
groups?: GroupEvent[];
}
/**
* Main LoopKit SDK interface
*/
export interface ILoopKit {
/** SDK version */
readonly version: string;
/** Initialize the SDK */
init(apiKey: string, config?: Partial<LoopKitConfig>): ILoopKit;
/** Configure the SDK */
configure(config: Partial<LoopKitConfig>): ILoopKit;
/** Get current configuration */
getConfig(): LoopKitConfig;
/** Track an event */
track(eventName: string, properties?: Record<string, any>, options?: TrackOptions): ILoopKit;
/** Track multiple events in batch */
trackBatch(events: BatchEventInput[]): ILoopKit;
/** Identify a user */
identify(userId: string, properties?: Record<string, any>): ILoopKit;
/** Associate user with a group */
group(groupId: string, properties?: Record<string, any>, groupType?: string): ILoopKit;
/** Manually flush queued events */
flush(): Promise<void>;
/** Get current queue size */
getQueueSize(): number;
/** Reset SDK state */
reset(): void;
/** Reset for testing (internal) */
resetForTesting(): void;
}
/**
* Storage interface for localStorage operations
*/
export interface IStorageManager {
/** Persist event queue */
persistQueue(queue: any[]): void;
/** Load persisted queue */
loadQueue(): any[];
/** Clear persisted queue */
clearQueue(): void;
/** Load anonymous ID */
loadAnonymousId(): string | null;
/** Save anonymous ID */
saveAnonymousId(anonymousId: string): void;
/** Clear anonymous ID */
clearAnonymousId(): void;
/** Clear all data */
clearAll(): void;
}
/**
* Session management interface
*/
export interface ISessionManager {
/** Get current session ID */
getSessionId(): string;
/** Get anonymous ID */
getAnonymousId(): string;
/** Start new session */
startSession(): void;
/** End current session */
endSession(): void;
/** Check if session is active */
isSessionActive(): boolean;
/** Update activity timestamp */
updateActivity(): void;
}
/**
* Event queue management interface
*/
export interface IQueueManager {
/** Add event to queue */
enqueueEvent(event: any): void;
/** Flush events to API */
flush(networkManager: INetworkManager): Promise<void>;
/** Get current queue */
getQueue(): any[];
/** Get queue size */
getQueueSize(): number;
/** Clear queue */
clearQueue(): void;
/** Reset queue state */
reset(): void;
}
/**
* Network communication interface
*/
export interface INetworkManager {
/** Send events to API */
sendEvents(endpoint: string, payload: any, retryCount?: number): Promise<any>;
/** Send beacon for page unload */
sendBeacon(endpoint: string, payload: any): boolean;
/** Update SDK configuration */
updateConfig(config: LoopKitConfig): void;
}
/**
* Browser features interface
*/
export interface IBrowserFeatures {
/** Setup all browser features */
setupFeatures(): void;
/** Setup click tracking */
setupAutoClickTracking(): void;
/** Setup page view tracking */
setupAutoPageViews(): void;
/** Setup error tracking */
setupErrorTracking(): void;
/** Setup page unload handling */
setupPageUnloadHandling(): void;
}
export type { LoopKitConfig as Config, TrackEvent as Event, ClickEventProperties as ClickEvent, BatchEventInput as BatchEvent, TrackOptions as Options, ILoopKit as LoopKit, };
//# sourceMappingURL=index.d.ts.map
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/types/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,WAAW,aAAa;IAC5B,iCAAiC;IACjC,MAAM,EAAE,MAAM,CAA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,EAClC,eAAe,IAAI,UAAU,EAC7B,YAAY,IAAI,OAAO,EACvB,QAAQ,IAAI,OAAO,GACpB,CAAC"}
import type { LoopKitConfig } from '../types/index.js';
/**
* Configuration validation utilities
*/
export declare class ConfigValidator {
/**
* Validate LoopKit configuration
*/
static validate(config: Partial<LoopKitConfig>): void;
}
//# sourceMappingURL=ConfigValidator.d.ts.map
{"version":3,"file":"ConfigValidator.d.ts","sourceRoot":"","sources":["../../src/utils/ConfigValidator.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAEvD;;GAEG;AACH,qBAAa,eAAe;IAC1B;;OAEG;IACH,MAAM,CAAC,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC,aAAa,CAAC,GAAG,IAAI;CAyBtD"}
/**
* ID generation utilities
*/
export declare class IdGenerator {
/**
* Generate a unique session ID
*/
generateSessionId(): string;
/**
* Generate a unique anonymous ID
*/
generateAnonymousId(): string;
/**
* Generate a unique event ID
*/
generateEventId(): string;
}
//# sourceMappingURL=IdGenerator.d.ts.map
{"version":3,"file":"IdGenerator.d.ts","sourceRoot":"","sources":["../../src/utils/IdGenerator.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,qBAAa,WAAW;IACtB;;OAEG;IACH,iBAAiB,IAAI,MAAM;IAI3B;;OAEG;IACH,mBAAmB,IAAI,MAAM;IAI7B;;OAEG;IACH,eAAe,IAAI,MAAM;CAG1B"}
import type { LoopKitConfig } from '../types/index.js';
/**
* Logging utility for LoopKit SDK
*/
export declare class Logger {
private config;
constructor(config: LoopKitConfig);
/**
* Update configuration
*/
updateConfig(config: LoopKitConfig): void;
/**
* Log an error message
*/
error(message: string, data?: Record<string, any>): void;
/**
* Log a warning message
*/
warn(message: string, data?: Record<string, any>): void;
/**
* Log an info message
*/
info(message: string, data?: Record<string, any>): void;
/**
* Log a debug message
*/
debug(message: string, data?: Record<string, any>): void;
/**
* Internal logging method
*/
private log;
/**
* Check if we should log at the given level
*/
private shouldLog;
}
//# sourceMappingURL=Logger.d.ts.map
{"version":3,"file":"Logger.d.ts","sourceRoot":"","sources":["../../src/utils/Logger.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAY,MAAM,mBAAmB,CAAC;AAIjE;;GAEG;AACH,qBAAa,MAAM;IACjB,OAAO,CAAC,MAAM,CAAgB;gBAElB,MAAM,EAAE,aAAa;IAIjC;;OAEG;IACH,YAAY,CAAC,MAAM,EAAE,aAAa,GAAG,IAAI;IAIzC;;OAEG;IACH,KAAK,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,IAAI;IAIxD;;OAEG;IACH,IAAI,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,IAAI;IAIvD;;OAEG;IACH,IAAI,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,IAAI;IAIvD;;OAEG;IACH,KAAK,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,IAAI;IAIxD;;OAEG;IACH,OAAO,CAAC,GAAG;IAkCX;;OAEG;IACH,OAAO,CAAC,SAAS;CAYlB"}
/**
* Privacy utilities for handling user preferences
*/
export declare class PrivacyUtils {
/**
* Check if Do Not Track is enabled in the browser
*/
static isDoNotTrackEnabled(): boolean;
}
//# sourceMappingURL=PrivacyUtils.d.ts.map
{"version":3,"file":"PrivacyUtils.d.ts","sourceRoot":"","sources":["../../src/utils/PrivacyUtils.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,qBAAa,YAAY;IACvB;;OAEG;IACH,MAAM,CAAC,mBAAmB,IAAI,OAAO;CAatC"}
+12
-130

@@ -1,130 +0,12 @@

export interface LoopKitConfig {
// API Settings
apiKey?: string;
baseURL?: string;
// Batching
batchSize?: number;
flushInterval?: number;
maxQueueSize?: number;
// Performance
enableCompression?: boolean;
requestTimeout?: number;
// Debugging
debug?: boolean;
logLevel?: 'error' | 'warn' | 'info' | 'debug';
// Auto-capture
enableAutoCapture?: boolean;
enableErrorTracking?: boolean;
// Privacy
respectDoNotTrack?: boolean;
enableLocalStorage?: boolean;
// Retry Logic
maxRetries?: number;
retryBackoff?: 'exponential' | 'linear';
// Callbacks
onBeforeTrack?: (event: LoopKitEvent) => LoopKitEvent | null;
onAfterTrack?: (event: LoopKitEvent, success: boolean) => void;
onError?: (error: Error) => void;
}
export interface LoopKitEvent {
type: 'track' | 'identify' | 'group';
timestamp: string;
sessionId: string;
name?: string;
properties?: Record<string, any>;
userId?: string;
userProperties?: Record<string, any>;
groupId?: string;
groupProperties?: Record<string, any>;
context?: {
page?: {
url: string;
path: string;
search: string;
title: string;
referrer: string;
};
userAgent?: string;
screen?: {
width: number;
height: number;
};
viewport?: {
width: number;
height: number;
};
};
}
export interface BatchEvent {
name: string;
properties?: Record<string, any>;
}
export interface LoopKitSDK {
/**
* Initialize LoopKit with API key
*/
init(apiKey: string, options?: LoopKitConfig): LoopKitSDK;
/**
* Configure LoopKit settings
*/
configure(options: LoopKitConfig): LoopKitSDK;
/**
* Track an event
*/
track(
eventName: string,
properties?: Record<string, any>,
options?: Record<string, any>
): LoopKitSDK;
/**
* Identify a user
*/
identify(userId: string, properties?: Record<string, any>): LoopKitSDK;
/**
* Associate user with a group
*/
group(groupId: string, properties?: Record<string, any>): LoopKitSDK;
/**
* Track multiple events in a batch
*/
trackBatch(events: BatchEvent[]): LoopKitSDK;
/**
* Manually flush the event queue
*/
flush(): Promise<void>;
/**
* Get current queue size
*/
getQueueSize(): number;
/**
* Get current configuration
*/
getConfig(): LoopKitConfig;
/**
* Reset the SDK state
*/
reset(): LoopKitSDK;
}
declare const LoopKit: LoopKitSDK;
export default LoopKit;
/**
* LoopKit JavaScript SDK
*
* A complete analytics SDK for tracking events, user identification,
* and behavioral analytics in web applications.
*/
import { LoopKit } from './core/LoopKit.js';
declare const loopkit: LoopKit;
export default loopkit;
export { LoopKit };
export type { LoopKitConfig, LogLevel, RetryBackoff, BaseEvent, TrackEvent, IdentifyEvent, GroupEvent, SystemInfo, ContextInfo, ClickEventProperties, BatchEventInput, TrackOptions, ApiResponse, ApiPayload, ILoopKit, IStorageManager, ISessionManager, IQueueManager, INetworkManager, IBrowserFeatures, Config, Event, ClickEvent, BatchEvent, Options, } from './types/index.js';
//# sourceMappingURL=index.d.ts.map

@@ -1,6 +0,1 @@

/*!
* LoopKit JavaScript SDK v1.0.6
* (c) 2025 LoopKit
* Released under the MIT License
*/
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).LoopKit=t()}(this,(function(){"use strict";function e(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,i=Array(t);n<t;n++)i[n]=e[n];return i}function t(e,t,n,i,r,o,s){try{var a=e[o](s),u=a.value}catch(e){return void n(e)}a.done?t(u):Promise.resolve(u).then(i,r)}function n(e){return function(){var n=this,i=arguments;return new Promise((function(r,o){var s=e.apply(n,i);function a(e){t(s,r,o,a,u,"next",e)}function u(e){t(s,r,o,a,u,"throw",e)}a(void 0)}))}}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function r(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,h(i.key),i)}}function o(e,t,n){return t&&r(e.prototype,t),n&&r(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e}function s(e,t,n){return(t=h(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function u(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?a(Object(n),!0).forEach((function(t){s(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):a(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function c(){var e,t,n="function"==typeof Symbol?Symbol:{},i=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function o(n,i,r,o){var u=i&&i.prototype instanceof a?i:a,c=Object.create(u.prototype);return l(c,"_invoke",function(n,i,r){var o,a,u,c=0,l=r||[],g=!1,h={p:0,n:0,v:e,a:f,f:f.bind(e,4),d:function(t,n){return o=t,a=0,u=e,h.n=n,s}};function f(n,i){for(a=n,u=i,t=0;!g&&c&&!r&&t<l.length;t++){var r,o=l[t],f=h.p,d=o[2];n>3?(r=d===i)&&(u=o[(a=o[4])?5:(a=3,3)],o[4]=o[5]=e):o[0]<=f&&((r=n<2&&f<o[1])?(a=0,h.v=i,h.n=o[1]):f<d&&(r=n<3||o[0]>i||i>d)&&(o[4]=n,o[5]=i,h.n=d,a=0))}if(r||n>1)return s;throw g=!0,i}return function(r,l,d){if(c>1)throw TypeError("Generator is already running");for(g&&1===l&&f(l,d),a=l,u=d;(t=a<2?e:u)||!g;){o||(a?a<3?(a>1&&(h.n=-1),f(a,u)):h.n=u:h.v=u);try{if(c=2,o){if(a||(r="next"),t=o[r]){if(!(t=t.call(o,u)))throw TypeError("iterator result is not an object");if(!t.done)return t;u=t.value,a<2&&(a=0)}else 1===a&&(t=o.return)&&t.call(o),a<2&&(u=TypeError("The iterator does not provide a '"+r+"' method"),a=1);o=e}else if((t=(g=h.n<0)?u:n.call(i,h))!==s)break}catch(t){o=e,a=1,u=t}finally{c=1}}return{value:t,done:g}}}(n,r,o),!0),c}var s={};function a(){}function u(){}function g(){}t=Object.getPrototypeOf;var h=[][i]?t(t([][i]())):(l(t={},i,(function(){return this})),t),f=g.prototype=a.prototype=Object.create(h);function d(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,g):(e.__proto__=g,l(e,r,"GeneratorFunction")),e.prototype=Object.create(f),e}return u.prototype=g,l(f,"constructor",g),l(g,"constructor",u),u.displayName="GeneratorFunction",l(g,r,"GeneratorFunction"),l(f),l(f,r,"Generator"),l(f,i,(function(){return this})),l(f,"toString",(function(){return"[object Generator]"})),(c=function(){return{w:o,m:d}})()}function l(e,t,n,i){var r=Object.defineProperty;try{r({},"",{})}catch(e){r=0}l=function(e,t,n,i){if(t)r?r(e,t,{value:n,enumerable:!i,configurable:!i,writable:!i}):e[t]=n;else{function o(t,n){l(e,t,(function(e){return this._invoke(t,n,e)}))}o("next",0),o("throw",1),o("return",2)}},l(e,t,n,i)}function g(t){return function(t){if(Array.isArray(t))return e(t)}(t)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(t)||function(t,n){if(t){if("string"==typeof t)return e(t,n);var i={}.toString.call(t).slice(8,-1);return"Object"===i&&t.constructor&&(i=t.constructor.name),"Map"===i||"Set"===i?Array.from(t):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?e(t,n):void 0}}(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function h(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var i=n.call(e,t);if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e,"string");return"symbol"==typeof t?t:t+""}function f(e){return f="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},f(e)}var d=function(){return o((function e(){i(this,e)}),null,[{key:"isDoNotTrackEnabled",value:function(){return"undefined"!=typeof navigator&&"undefined"!=typeof window&&("1"===navigator.doNotTrack||"1"===window.doNotTrack||"1"===navigator.msDoNotTrack)}}])}(),p=function(){return o((function e(t,n,r,o,s){i(this,e),this.config=t,this.logger=n,this.queueManager=r,this.sessionManager=o,this.idGenerator=s}),[{key:"updateConfig",value:function(e){this.config=e}},{key:"track",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};if(e&&"string"==typeof e){if(!this.config.respectDoNotTrack||!d.isDoNotTrackEnabled()){var r=this.createEvent("track",u({name:e,properties:u({},t)},n),i),o=r;if(this.config.onBeforeTrack&&"function"==typeof this.config.onBeforeTrack)try{o=this.config.onBeforeTrack(r)||r}catch(e){this.logger.error("Error in onBeforeTrack callback",e)}return this.queueManager.enqueueEvent(o),this.logger.debug("Event tracked",{name:e,properties:t}),this}this.logger.info("Tracking disabled due to Do Not Track")}else this.logger.error("Event name is required and must be a string")}},{key:"identify",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=this.createEvent("identify",{userId:e,properties:u({},t)});return this.queueManager.enqueueEvent(n),this}},{key:"group",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"organization",i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},r=this.createEvent("group",{groupId:e,groupType:n,properties:u({},t)},i);return this.queueManager.enqueueEvent(r),this}},{key:"createEvent",value:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i={anonymousId:this.sessionManager.getAnonymousId(),timestamp:(new Date).toISOString()},r={sdk:{name:"@loopkit/javascript",version:"1.0.6"},sessionId:this.sessionManager.getSessionId()};return"undefined"!=typeof window&&(r.context={page:{url:window.location.href,path:window.location.pathname,search:window.location.search,title:document.title,referrer:document.referrer},userAgent:navigator.userAgent,screen:{width:window.screen.width,height:window.screen.height},viewport:{width:window.innerWidth,height:window.innerHeight}}),"track"===e?u(u({},i),{},{userId:n.userId,name:t.name,properties:t.properties,system:r}):"identify"===e?u(u({},i),{},{userId:t.userId,properties:t.properties,system:r}):"group"===e?u(u({},i),{},{userId:n.userId,groupId:t.groupId,groupType:t.groupType,properties:t.properties,system:r}):u(u(u({},i),{},{type:e},t),{},{system:r})}}])}(),v=function(){return o((function e(t,n,r){i(this,e),this.config=t,this.logger=n,this.storageManager=r,this.eventQueue=[],this.flushTimer=null,this.flushTimerStartTime=null,this.networkManager=null}),[{key:"updateConfig",value:function(e){this.config=e}},{key:"setNetworkManager",value:function(e){this.networkManager=e}},{key:"getQueueSize",value:function(){return this.eventQueue.length}},{key:"enqueueEvent",value:function(e){var t=this;if(this.eventQueue.length>=this.config.maxQueueSize&&(this.logger.warn("Event queue full, dropping oldest event"),this.eventQueue.shift()),this.eventQueue.push(e),this.config.debug){var n=this.eventQueue.length,i=n>=this.config.batchSize,r=null;if(!i&&this.config.flushInterval>0){var o=Date.now();if(this.flushTimerStartTime){var s=o-this.flushTimerStartTime,a=1e3*this.config.flushInterval;r=Math.max(0,a-s%a)}else r=1e3*this.config.flushInterval}var u={eventType:e.name?"track":e.userId&&!e.groupId?"identify":"group",eventName:e.name||(e.userId&&!e.groupId?"identify":"group"),queueSize:n,batchSize:this.config.batchSize,willAutoFlush:i,timeUntilNextFlushMs:r,timeUntilNextFlushSeconds:r?Math.round(r/1e3):null};this.logger.debug("Event added to queue".concat(i?" - triggering immediate flush":""),u)}this.config.enableLocalStorage&&this.storageManager.persistQueue(this.eventQueue),this.eventQueue.length>=this.config.batchSize&&this.flush(this.networkManager).catch((function(e){t.logger.error("Auto-flush failed",e)}))}},{key:"flush",value:(e=n(c().m((function e(t){var n,i,r,o,s,a,u,l,h=this;return c().w((function(e){for(;;)switch(e.n){case 0:if(0!==this.eventQueue.length){e.n=1;break}return this.logger.debug("No events to flush"),e.a(2);case 1:return n=g(this.eventQueue),this.eventQueue=[],i=Date.now(),this.logger.debug("Starting flush of ".concat(n.length," events")),r={tracks:[],identifies:[],groups:[]},n.forEach((function(e){void 0!==e.name?r.tracks.push(e):e.userId&&void 0===e.groupId?r.identifies.push(e):e.groupId&&r.groups.push(e)})),this.config.debug&&this.logger.debug("Events grouped for batch sending",{tracksCount:r.tracks.length,identifiesCount:r.identifies.length,groupsCount:r.groups.length,totalEvents:n.length}),e.p=2,o=[],r.tracks.length>0&&o.push(t.sendEvents("tracks",r.tracks)),r.identifies.length>0&&o.push(t.sendEvents("identifies",r.identifies)),r.groups.length>0&&o.push(t.sendEvents("groups",r.groups)),e.n=3,Promise.all(o);case 3:s=Date.now()-i,this.config.debug&&this.logger.debug("Batch flush completed successfully",{eventsCount:n.length,tracksCount:r.tracks.length,identifiesCount:r.identifies.length,groupsCount:r.groups.length,flushDurationMs:s,endpointsSent:o.length,queueSizeAfterFlush:this.eventQueue.length}),this.config.enableLocalStorage&&this.storageManager.clearQueue(),this.config.onAfterTrack&&"function"==typeof this.config.onAfterTrack&&n.forEach((function(e){try{h.config.onAfterTrack(e,!0)}catch(e){h.logger.error("Error in onAfterTrack callback",e)}})),e.n=5;break;case 4:if(e.p=4,l=e.v,u=Date.now()-i,this.config.debug?this.logger.error("Batch flush failed",{eventsCount:n.length,tracksCount:r.tracks.length,identifiesCount:r.identifies.length,groupsCount:r.groups.length,flushDurationMs:u,errorMessage:l.message,errorType:l.constructor.name,queueSizeAfterRequeue:this.eventQueue.length+n.length}):this.logger.error("Failed to flush events",l),(a=this.eventQueue).unshift.apply(a,g(n)),this.config.onAfterTrack&&"function"==typeof this.config.onAfterTrack&&n.forEach((function(e){try{h.config.onAfterTrack(e,!1)}catch(e){h.logger.error("Error in onAfterTrack callback",e)}})),this.config.onError&&"function"==typeof this.config.onError)try{this.config.onError(l)}catch(e){this.logger.error("Error in onError callback",e)}throw l;case 5:return e.a(2)}}),e,this,[[2,4]])}))),function(t){return e.apply(this,arguments)})},{key:"scheduleFlush",value:function(){var e=this;this.config.flushInterval>0&&!this.flushTimer&&(this.flushTimerStartTime=Date.now(),this.flushTimer=setTimeout((function(){e.eventQueue.length>0&&e.flush(e.networkManager).catch((function(t){e.logger.error("Scheduled flush failed",t)}))}),1e3*this.config.flushInterval))}},{key:"loadPersistedQueue",value:function(){var e,t=this.storageManager.loadQueue();t&&Array.isArray(t)&&((e=this.eventQueue).push.apply(e,g(t)),this.logger.debug("Loaded ".concat(t.length," events from storage")))}},{key:"clearFlushTimer",value:function(){this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null,this.flushTimerStartTime=null)}},{key:"reset",value:function(){this.eventQueue=[],this.clearFlushTimer()}},{key:"restartAutoFlush",value:function(){this.clearFlushTimer(),this.scheduleFlush()}}]);var e}(),y=function(){return o((function e(t,n){i(this,e),this.config=t,this.logger=n}),[{key:"updateConfig",value:function(e){this.config=e}},{key:"sendEvents",value:(e=n(c().m((function e(t,n){var i,r,o,s,a,u,l,g,h,f,d,p,v,y,m=arguments;return c().w((function(e){for(;;)switch(e.n){case 0:if(i=m.length>2&&void 0!==m[2]?m[2]:0,r="".concat(this.config.baseURL,"/").concat(t,"?apiKey=").concat(encodeURIComponent(this.config.apiKey)),o=Date.now(),"tracks"!==t){e.n=1;break}s={tracks:n},e.n=4;break;case 1:if("identifies"!==t){e.n=2;break}s={identifies:n},e.n=4;break;case 2:if("groups"!==t){e.n=3;break}s={groups:n},e.n=4;break;case 3:throw new Error("Invalid endpoint: ".concat(t));case 4:return a={"Content-Type":"application/json"},this.config.debug&&this.logger.debug("Sending ".concat(n.length," events to ").concat(t," endpoint").concat(i>0?" (retry ".concat(i,")"):""),{endpoint:t,eventsCount:n.length,retryAttempt:i,url:r.replace(/apiKey=[^&]+/,"apiKey=***"),payloadSize:JSON.stringify(s).length}),e.p=5,u=new AbortController,l=setTimeout((function(){return u.abort()}),this.config.requestTimeout),e.n=6,fetch(r,{method:"POST",headers:a,body:JSON.stringify(s),signal:u.signal});case 6:if(g=e.v,clearTimeout(l),h=Date.now()-o,g&&g.ok){e.n=7;break}throw f=g?g.statusText:"Network error",d=g?g.status:0,new Error(d?"HTTP ".concat(d,": ").concat(f):f);case 7:this.config.debug?this.logger.debug("Successfully sent ".concat(n.length," ").concat(t," events"),{endpoint:t,eventsCount:n.length,sendDurationMs:h,responseStatus:g.status,retryAttempt:i}):this.logger.debug("Successfully sent ".concat(n.length," ").concat(t," events")),e.n=11;break;case 8:if(e.p=8,y=e.v,p=Date.now()-o,this.config.debug?this.logger.error("Failed to send ".concat(t," events (attempt ").concat(i+1,")"),{endpoint:t,eventsCount:n.length,sendDurationMs:p,retryAttempt:i+1,maxRetries:this.config.maxRetries,errorMessage:y.message,errorType:y.constructor.name}):this.logger.error("Failed to send ".concat(t," events (attempt ").concat(i+1,")"),y),!(i<this.config.maxRetries)){e.n=10;break}return v=this.calculateRetryDelay(i),this.config.debug?this.logger.debug("Retrying ".concat(t," endpoint in ").concat(v,"ms"),{endpoint:t,retryDelay:v,nextRetryAttempt:i+2,maxRetries:this.config.maxRetries}):this.logger.debug("Retrying in ".concat(v,"ms")),e.n=9,new Promise((function(e){return setTimeout(e,v)}));case 9:return e.a(2,this.sendEvents(t,n,i+1));case 10:throw y;case 11:return e.a(2)}}),e,this,[[5,8]])}))),function(t,n){return e.apply(this,arguments)})},{key:"calculateRetryDelay",value:function(e){return"exponential"===this.config.retryBackoff?Math.min(1e3*Math.pow(2,e),3e4):1e3*(e+1)}},{key:"sendBeacon",value:function(e){if(!navigator.sendBeacon||0===e.length)return!1;var t={tracks:[],identifies:[],groups:[]};e.forEach((function(e){void 0!==e.name?t.tracks.push(e):e.userId&&void 0===e.groupId?t.identifies.push(e):e.groupId&&t.groups.push(e)}));var n=0;if(t.tracks.length>0){var i="".concat(this.config.baseURL,"/tracks?apiKey=").concat(encodeURIComponent(this.config.apiKey)),r={tracks:t.tracks};navigator.sendBeacon(i,JSON.stringify(r))&&n++}if(t.identifies.length>0){var o="".concat(this.config.baseURL,"/identifies?apiKey=").concat(encodeURIComponent(this.config.apiKey)),s={identifies:t.identifies};navigator.sendBeacon(o,JSON.stringify(s))&&n++}if(t.groups.length>0){var a="".concat(this.config.baseURL,"/groups?apiKey=").concat(encodeURIComponent(this.config.apiKey)),u={groups:t.groups};navigator.sendBeacon(a,JSON.stringify(u))&&n++}return n>0&&(this.logger.debug("Events sent via beacon to ".concat(n," endpoints")),!0)}}]);var e}(),m=function(){return o((function e(t,n,r,o,s){i(this,e),this.config=t,this.logger=n,this.eventTracker=r,this.sessionManager=o,this.queueManager=s,this.networkManager=null}),[{key:"updateConfig",value:function(e){this.config=e}},{key:"setNetworkManager",value:function(e){this.networkManager=e}},{key:"setupFeatures",value:function(){this.config.enableAutoCapture&&this.setupAutoPageViews(),this.config.enableAutoClickTracking&&this.setupAutoClickTracking(),this.config.enableErrorTracking&&this.setupErrorTracking(),this.setupPageUnloadHandling(),this.logger.debug("Browser features setup completed")}},{key:"setupAutoPageViews",value:function(){var e=this;window.addEventListener("load",(function(){e.eventTracker.track("page_view",{page:window.location.pathname,title:document.title,referrer:document.referrer})})),window.addEventListener("popstate",(function(){e.eventTracker.track("page_view",{page:window.location.pathname,title:document.title})})),this.logger.debug("Auto page view tracking enabled")}},{key:"setupAutoClickTracking",value:function(){var e=this;if("undefined"!=typeof document){var t={pathname:window.location.pathname,title:document.title,href:window.location.href},n=function(){t={pathname:window.location.pathname,title:document.title,href:window.location.href}};window.addEventListener("popstate",n),window.addEventListener("pushstate",n),window.addEventListener("replacestate",n),document.addEventListener("click",(function(i){try{var r=t.pathname,o=t.title,s=t.href;n();for(var a=i.target,u=null,c=0;a&&a.tagName&&c<5&&!(u=e.getClickableElementInfo(a));)a=a.parentElement,c++;if(u){var l={element_type:u.type,element_text:u.text,element_id:u.id,element_class:u.className,element_tag:u.tag,page:r,page_title:o,page_url:s,position:{x:i.clientX,y:i.clientY}};u.href&&(l.element_href=u.href),u.ariaLabel&&(l.element_aria_label=u.ariaLabel),e.config.debug&&c>0&&(l.traversal_depth=c,l.original_target_tag=i.target.tagName.toLowerCase()),e.eventTracker.track("element_click",l)}}catch(t){e.logger.warn("Error in auto click tracking",t)}}),{capture:!0,passive:!0}),this.logger.debug("Auto click tracking enabled with capture phase")}}},{key:"getClickableElementInfo",value:function(e){if(!e||!e.tagName)return null;var t=e.tagName.toLowerCase();if(!this.isClickableElement(e))return null;var n="";e.innerText?n=e.innerText.trim():e.textContent?n=e.textContent.trim():e.value?n=e.value.trim():e.alt?n=e.alt.trim():e.title&&(n=e.title.trim()),n.length>100&&(n=n.substring(0,97)+"...");var i=t;"input"===t?i=e.type||"input":"button"===t?i="submit"===e.type?"submit_button":"button":"a"===t&&(i="link");var r=null;e.href?r=e.href:e.getAttribute&&e.getAttribute("href")&&(r=e.getAttribute("href"));var o=null;e.getAttribute&&e.getAttribute("aria-label")&&(o=e.getAttribute("aria-label").trim());var s={type:i,text:n,id:e.id||null,className:e.className||null,tag:t};return r&&(s.href=r),o&&(s.ariaLabel=o),s}},{key:"isClickableElement",value:function(e){var t=e.tagName.toLowerCase();if(["button","a","input","select","textarea"].includes(t))return!0;if(e.onclick||"button"===e.getAttribute("role")||"link"===e.getAttribute("role")||null!==e.getAttribute("tabindex")||"pointer"===e.style.cursor)return!0;var n=e.className||"";return!!["btn","button","link","clickable","interactive"].some((function(e){return n.toLowerCase().includes(e)}))||!!(e.hasAttribute("data-click")||e.hasAttribute("data-action")||e.hasAttribute("ng-click")||e.hasAttribute("@click")||e.hasAttribute("v-on:click"))}},{key:"setupErrorTracking",value:function(){var e=this;window.addEventListener("error",(function(t){var n;e.eventTracker.track("javascript_error",{message:t.message,filename:t.filename,line:t.lineno,column:t.colno,stack:null===(n=t.error)||void 0===n?void 0:n.stack})})),window.addEventListener("unhandledrejection",(function(t){var n,i;e.eventTracker.track("promise_rejection",{reason:null===(n=t.reason)||void 0===n?void 0:n.toString(),stack:null===(i=t.reason)||void 0===i?void 0:i.stack})})),this.logger.debug("Auto error tracking enabled")}},{key:"setupPageUnloadHandling",value:function(){var e=this;window.addEventListener("beforeunload",(function(){e.config.enableSessionTracking&&e.sessionManager.endSession(),e.queueManager.getQueueSize()>0&&e.sendBeacon()})),document.addEventListener("visibilitychange",(function(){"hidden"===document.visibilityState&&e.queueManager.getQueueSize()>0&&e.sendBeacon()})),this.logger.debug("Page unload handling enabled")}},{key:"sendBeacon",value:function(){if(this.networkManager&&this.queueManager.getQueueSize()>0){var e=g(this.queueManager.eventQueue);this.networkManager.sendBeacon(e)&&(this.queueManager.eventQueue=[])}}}])}(),k=function(){return o((function e(t,n){i(this,e),this.config=t,this.logger=n}),[{key:"updateConfig",value:function(e){this.config=e}},{key:"getStorage",value:function(){return"undefined"!=typeof global&&global.localStorage?global.localStorage:"undefined"!=typeof localStorage?localStorage:null}},{key:"persistQueue",value:function(e){if(this.config.enableLocalStorage){var t=this.getStorage();if(t)try{var n={version:"1.0.6",events:e,timestamp:Date.now()};t.setItem("loopkit_queue",JSON.stringify(n))}catch(e){this.logger.warn("Failed to persist queue",e)}}}},{key:"loadQueue",value:function(){if(!this.config.enableLocalStorage)return[];var e=this.getStorage();if(e)try{var t=e.getItem("loopkit_queue");if(t){var n=JSON.parse(t);if(Array.isArray(n))return this.logger.debug("Legacy event format detected, clearing queue"),this.clearQueue(),[];if(n&&"object"===f(n)&&n.version&&n.events){var i="1.0.6";if(n.version!==i)return this.logger.debug("Version mismatch detected (stored: ".concat(n.version,", current: ").concat(i,"), clearing queue")),this.clearQueue(),[];if(Array.isArray(n.events))return this.logger.debug("Loaded ".concat(n.events.length," events from storage (version: ").concat(n.version,")")),n.events}}}catch(e){this.logger.warn("Failed to load persisted queue, clearing corrupted data",e),this.clearQueue()}return[]}},{key:"clearQueue",value:function(){if(this.config.enableLocalStorage){var e=this.getStorage();if(e)try{e.removeItem("loopkit_queue")}catch(e){this.logger.warn("Failed to clear persisted queue",e)}}}},{key:"loadAnonymousId",value:function(){if(!this.config.enableLocalStorage)return null;var e=this.getStorage();if(e)try{var t=e.getItem("loopkit_anonymousId");if(t)return t}catch(e){this.logger.warn("Failed to load anonymous ID",e)}return null}},{key:"saveAnonymousId",value:function(e){if(this.config.enableLocalStorage){var t=this.getStorage();if(t)try{t.setItem("loopkit_anonymousId",e)}catch(e){this.logger.warn("Failed to save anonymous ID",e)}}}},{key:"clearAnonymousId",value:function(){if(this.config.enableLocalStorage){var e=this.getStorage();if(e)try{e.removeItem("loopkit_anonymousId")}catch(e){this.logger.warn("Failed to clear anonymous ID",e)}}}},{key:"clearAll",value:function(){this.clearQueue(),this.clearAnonymousId()}}])}(),b=function(){return o((function e(t,n,r,o){i(this,e),this.config=t,this.logger=n,this.idGenerator=r,this.storageManager=o,this.sessionId=this.idGenerator.generateSessionId(),this.anonymousId=this.loadOrGenerateAnonymousId(),this.sessionStarted=!1,this.lastActivityTime=Date.now(),this.sessionTimer=null}),[{key:"updateConfig",value:function(e){this.config=e}},{key:"getSessionId",value:function(){return this.sessionId}},{key:"getAnonymousId",value:function(){return this.anonymousId}},{key:"loadOrGenerateAnonymousId",value:function(){if(this.storageManager){var e=this.storageManager.loadAnonymousId();if(e)return e}var t=this.idGenerator.generateAnonymousId();return this.storageManager&&this.storageManager.saveAnonymousId(t),t}},{key:"startSession",value:function(){this.sessionStarted||(this.sessionStarted=!0,this.lastActivityTime=Date.now(),this.setupActivityTracking(),this.logger.debug("Session started",{sessionId:this.sessionId}))}},{key:"endSession",value:function(){if(this.sessionStarted){var e=Math.round((Date.now()-this.lastActivityTime)/1e3);this.sessionStarted=!1,this.sessionTimer&&(clearTimeout(this.sessionTimer),this.sessionTimer=null),this.logger.debug("Session ended",{sessionId:this.sessionId,duration:e})}}},{key:"updateActivity",value:function(){var e=this;this.lastActivityTime=Date.now(),this.sessionTimer&&clearTimeout(this.sessionTimer),this.sessionTimer=setTimeout((function(){e.endSession()}),1e3*this.config.sessionTimeout)}},{key:"setupActivityTracking",value:function(){var e=this;if("undefined"!=typeof window){var t=this.throttle((function(){e.updateActivity()}),5e3);["mousedown","mousemove","keypress","scroll","touchstart","click"].forEach((function(e){window.addEventListener(e,t,{passive:!0})})),this.updateActivity()}}},{key:"throttle",value:function(e,t){var n;return function(){var i=arguments;n||(e.apply(this,i),n=!0,setTimeout((function(){return n=!1}),t))}}},{key:"reset",value:function(){this.sessionTimer&&(clearTimeout(this.sessionTimer),this.sessionTimer=null),this.sessionId=this.idGenerator.generateSessionId(),this.anonymousId=this.loadOrGenerateAnonymousId(),this.sessionStarted=!1,this.lastActivityTime=Date.now()}}])}(),w=function(){return o((function e(t){i(this,e),this.config=t}),[{key:"updateConfig",value:function(e){this.config=e}},{key:"log",value:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;if(this.config.debug){var i=["error","warn","info","debug"],r=i.indexOf(this.config.logLevel);if(i.indexOf(e)<=r){var o=new Date,s="".concat(o.toLocaleDateString()," ").concat(o.toLocaleTimeString(),".").concat(o.getMilliseconds().toString().padStart(3,"0")),a=u(u({},n),{},{timestamp:s,version:"1.0.6"}),c="[LoopKit] ".concat(t);n?console[e](c,a):console[e](c,{timestamp:s,version:"1.0.6"})}}}},{key:"error",value:function(e,t){this.log("error",e,t)}},{key:"warn",value:function(e,t){this.log("warn",e,t)}},{key:"info",value:function(e,t){this.log("info",e,t)}},{key:"debug",value:function(e,t){this.log("debug",e,t)}}])}(),T=function(){return o((function e(){i(this,e)}),[{key:"validate",value:function(e){if(e.batchSize<=0)throw new Error("batchSize must be greater than 0");if(e.flushInterval<0)throw new Error("flushInterval must be >= 0");if(e.maxQueueSize<=0)throw new Error("maxQueueSize must be greater than 0");if(e.requestTimeout<=0)throw new Error("requestTimeout must be greater than 0");if(e.maxRetries<0)throw new Error("maxRetries must be >= 0");if(e.sessionTimeout<=0)throw new Error("sessionTimeout must be greater than 0")}}])}(),S=function(){return o((function e(){i(this,e)}),[{key:"generateSessionId",value:function(){return"sess_"+Math.random().toString(36).substr(2,9)+"_"+Date.now()}},{key:"generateAnonymousId",value:function(){return"anon_"+Math.random().toString(36).substr(2,9)+"_"+Date.now()}},{key:"generateEventId",value:function(){return"evt_"+Math.random().toString(36).substr(2,9)+"_"+Date.now()}}])}(),I=function(){return o((function e(){i(this,e),this.version="1.0.6",this.config={apiKey:null,baseURL:"https://drain.loopkit.ai/v1",batchSize:50,flushInterval:30,maxQueueSize:1e3,enableCompression:!0,requestTimeout:1e4,debug:!1,logLevel:"debug",enableAutoCapture:!0,enableAutoClickTracking:!0,enableErrorTracking:!0,enableSessionTracking:!0,sessionTimeout:1800,respectDoNotTrack:!0,enableLocalStorage:!0,maxRetries:3,retryBackoff:"exponential",onBeforeTrack:null,onAfterTrack:null,onError:null},this.initialized=!1,this.userId=null,this.userProperties={},this.groupId=null,this.groupProperties={},this.logger=new w(this.config),this.configValidator=new T,this.idGenerator=new S,this.storageManager=new k(this.config,this.logger),this.queueManager=new v(this.config,this.logger,this.storageManager),this.networkManager=new y(this.config,this.logger),this.sessionManager=new b(this.config,this.logger,this.idGenerator,this.storageManager),this.eventTracker=new p(this.config,this.logger,this.queueManager,this.sessionManager,this.idGenerator),"undefined"!=typeof window&&(this.browserFeatures=new m(this.config,this.logger,this.eventTracker,this.sessionManager,this.queueManager)),this.track=this.track.bind(this),this.identify=this.identify.bind(this),this.group=this.group.bind(this),this.trackBatch=this.trackBatch.bind(this),this.flush=this.flush.bind(this)}),[{key:"init",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!e||"string"!=typeof e)throw new Error("LoopKit: API key is required and must be a string");return this.initialized&&this.queueManager.stopAutoFlush(),this.config.apiKey=e,this.configure(t),this.initialized=!0,this.updateModuleConfigs(),this.logger.info("LoopKit initialized",{apiKey:e.substring(0,8)+"...",version:this.version}),this.queueManager.setNetworkManager(this.networkManager),this.queueManager.scheduleFlush(),this.config.enableLocalStorage&&this.queueManager.loadPersistedQueue(),this.config.enableSessionTracking&&this.sessionManager.startSession(),this.browserFeatures&&(this.browserFeatures.setNetworkManager(this.networkManager),this.browserFeatures.setupFeatures()),this}},{key:"configure",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=this.config.flushInterval;return this.config=u(u({},this.config),e),this.configValidator.validate(this.config),this.updateModuleConfigs(),this.logger.debug("LoopKit configured",this.config),this.initialized&&void 0!==e.flushInterval&&t!==this.config.flushInterval&&this.queueManager.restartAutoFlush(),this}},{key:"track",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return this.initialized?(this.eventTracker.track(e,t,n,{userId:this.userId,userProperties:this.userProperties,groupId:this.groupId,groupProperties:this.groupProperties}),this):(this.logger.warn("LoopKit not initialized. Call init() first."),this)}},{key:"identify",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this.initialized?e&&"string"==typeof e?(this.userId=e,this.userProperties=u(u({},this.userProperties),t),this.eventTracker.identify(e,t),this.logger.debug("User identified",{userId:e,properties:t}),this):(this.logger.error("User ID is required and must be a string"),this):(this.logger.warn("LoopKit not initialized. Call init() first."),this)}},{key:"group",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"organization";return this.initialized?e&&"string"==typeof e?n&&"string"==typeof n?(this.groupId=e,this.groupProperties=u(u({},this.groupProperties),t),this.eventTracker.group(e,t,n,{userId:this.userId}),this.logger.debug("User grouped",{groupId:e,groupType:n,properties:t}),this):(this.logger.error("Group type is required and must be a string"),this):(this.logger.error("Group ID is required and must be a string"),this):(this.logger.warn("LoopKit not initialized. Call init() first."),this)}},{key:"trackBatch",value:function(e){var t=this;return this.initialized?Array.isArray(e)?(e.forEach((function(e){e.name&&e.properties?t.track(e.name,e.properties):t.logger.warn("Invalid event in batch",e)})),this):(this.logger.error("Events must be an array"),this):(this.logger.warn("LoopKit not initialized. Call init() first."),this)}},{key:"flush",value:(e=n(c().m((function e(){return c().w((function(e){for(;;)switch(e.n){case 0:if(this.initialized){e.n=1;break}return this.logger.warn("LoopKit not initialized. Call init() first."),e.a(2);case 1:return e.a(2,this.queueManager.flush(this.networkManager))}}),e,this)}))),function(){return e.apply(this,arguments)})},{key:"getQueueSize",value:function(){return this.queueManager.getQueueSize()}},{key:"getConfig",value:function(){return u({},this.config)}},{key:"getVersion",value:function(){return this.version}},{key:"reset",value:function(){return this.userId=null,this.userProperties={},this.groupId=null,this.groupProperties={},this.queueManager.reset(),this.sessionManager.reset(),this.storageManager.clearAll(),this.initialized=!1,this.logger.debug("SDK state reset"),this}},{key:"resetForTesting",value:function(){return this.reset(),this.config={apiKey:null,baseURL:"https://drain.loopkit.ai/v1",batchSize:50,flushInterval:30,maxQueueSize:1e3,enableCompression:!0,requestTimeout:1e4,debug:!1,logLevel:"debug",enableAutoCapture:!1,enableAutoClickTracking:!1,enableErrorTracking:!1,enableSessionTracking:!0,sessionTimeout:1800,respectDoNotTrack:!0,enableLocalStorage:!0,maxRetries:3,retryBackoff:"exponential",onBeforeTrack:null,onAfterTrack:null,onError:null},this.updateModuleConfigs(),this.logger.debug("SDK state reset for testing"),this}},{key:"updateModuleConfigs",value:function(){this.logger.updateConfig(this.config),this.storageManager.updateConfig(this.config),this.queueManager.updateConfig(this.config),this.networkManager.updateConfig(this.config),this.sessionManager.updateConfig(this.config),this.eventTracker.updateConfig(this.config),this.browserFeatures&&this.browserFeatures.updateConfig(this.config)}}]);var e}(),A=new I;return"undefined"!=typeof module&&module.exports?module.exports=A:"undefined"!=typeof window&&(window.LoopKit=A),A}));
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).LoopKit={})}(this,(function(e){"use strict";function t(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function r(e,t,r,n,i,o,a){try{var s=e[o](a),u=s.value}catch(e){return void r(e)}s.done?t(u):Promise.resolve(u).then(n,i)}function n(e){return function(){var t=this,n=arguments;return new Promise((function(i,o){var a=e.apply(t,n);function s(e){r(a,i,o,s,u,"next",e)}function u(e){r(a,i,o,s,u,"throw",e)}s(void 0)}))}}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,f(n.key),n)}}function a(e,t,r){return t&&o(e.prototype,t),r&&o(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function s(e,t,r){return(t=f(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function u(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function c(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?u(Object(r),!0).forEach((function(t){s(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):u(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function l(){var e,t,r="function"==typeof Symbol?Symbol:{},n=r.iterator||"@@iterator",i=r.toStringTag||"@@toStringTag";function o(r,n,i,o){var u=n&&n.prototype instanceof s?n:s,c=Object.create(u.prototype);return g(c,"_invoke",function(r,n,i){var o,s,u,c=0,l=i||[],g=!1,h={p:0,n:0,v:e,a:f,f:f.bind(e,4),d:function(t,r){return o=t,s=0,u=e,h.n=r,a}};function f(r,n){for(s=r,u=n,t=0;!g&&c&&!i&&t<l.length;t++){var i,o=l[t],f=h.p,d=o[2];r>3?(i=d===n)&&(u=o[(s=o[4])?5:(s=3,3)],o[4]=o[5]=e):o[0]<=f&&((i=r<2&&f<o[1])?(s=0,h.v=n,h.n=o[1]):f<d&&(i=r<3||o[0]>n||n>d)&&(o[4]=r,o[5]=n,h.n=d,s=0))}if(i||r>1)return a;throw g=!0,n}return function(i,l,d){if(c>1)throw TypeError("Generator is already running");for(g&&1===l&&f(l,d),s=l,u=d;(t=s<2?e:u)||!g;){o||(s?s<3?(s>1&&(h.n=-1),f(s,u)):h.n=u:h.v=u);try{if(c=2,o){if(s||(i="next"),t=o[i]){if(!(t=t.call(o,u)))throw TypeError("iterator result is not an object");if(!t.done)return t;u=t.value,s<2&&(s=0)}else 1===s&&(t=o.return)&&t.call(o),s<2&&(u=TypeError("The iterator does not provide a '"+i+"' method"),s=1);o=e}else if((t=(g=h.n<0)?u:r.call(n,h))!==a)break}catch(t){o=e,s=1,u=t}finally{c=1}}return{value:t,done:g}}}(r,i,o),!0),c}var a={};function s(){}function u(){}function c(){}t=Object.getPrototypeOf;var h=[][n]?t(t([][n]())):(g(t={},n,(function(){return this})),t),f=c.prototype=s.prototype=Object.create(h);function d(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,c):(e.__proto__=c,g(e,i,"GeneratorFunction")),e.prototype=Object.create(f),e}return u.prototype=c,g(f,"constructor",c),g(c,"constructor",u),u.displayName="GeneratorFunction",g(c,i,"GeneratorFunction"),g(f),g(f,i,"Generator"),g(f,n,(function(){return this})),g(f,"toString",(function(){return"[object Generator]"})),(l=function(){return{w:o,m:d}})()}function g(e,t,r,n){var i=Object.defineProperty;try{i({},"",{})}catch(e){i=0}g=function(e,t,r,n){if(t)i?i(e,t,{value:r,enumerable:!n,configurable:!n,writable:!n}):e[t]=r;else{function o(t,r){g(e,t,(function(e){return this._invoke(t,r,e)}))}o("next",0),o("throw",1),o("return",2)}},g(e,t,r,n)}function h(e){return function(e){if(Array.isArray(e))return t(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||function(e,r){if(e){if("string"==typeof e)return t(e,r);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?t(e,r):void 0}}(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function f(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,t);if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e,"string");return"symbol"==typeof t?t:t+""}function d(e){return d="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},d(e)}var v=function(){return a((function e(){i(this,e)}),null,[{key:"validate",value:function(e){if(void 0!==e.batchSize&&e.batchSize<=0)throw new Error("batchSize must be greater than 0");if(void 0!==e.flushInterval&&e.flushInterval<0)throw new Error("flushInterval must be >= 0");if(void 0!==e.maxQueueSize&&e.maxQueueSize<=0)throw new Error("maxQueueSize must be greater than 0");if(void 0!==e.requestTimeout&&e.requestTimeout<=0)throw new Error("requestTimeout must be greater than 0");if(void 0!==e.maxRetries&&e.maxRetries<0)throw new Error("maxRetries must be >= 0");if(void 0!==e.sessionTimeout&&e.sessionTimeout<=0)throw new Error("sessionTimeout must be greater than 0")}}])}(),p=function(){return a((function e(t){i(this,e),this.config=t}),[{key:"updateConfig",value:function(e){this.config=e}},{key:"error",value:function(e,t){this.log("error",e,t)}},{key:"warn",value:function(e,t){this.log("warn",e,t)}},{key:"info",value:function(e,t){this.log("info",e,t)}},{key:"debug",value:function(e,t){this.log("debug",e,t)}},{key:"log",value:function(e,t,r){if(this.shouldLog(e)){var n=new Date,i=n.toLocaleDateString("en-US")+" "+n.toLocaleTimeString("en-US")+"."+n.getMilliseconds();if(r){var o=c(c({},r),{},{timestamp:i,version:"1.1.0"}),a="[LoopKit] ".concat(t);console[e](a,o)}else console[e]("[LoopKit] ".concat(t),{timestamp:i,version:"1.1.0"})}}},{key:"shouldLog",value:function(e){if(!this.config.debug)return!1;var t=["error","warn","info","debug"],r=this.config.logLevel||"debug",n=t.indexOf(r);return t.indexOf(e)<=n}}])}(),y=function(){return a((function e(){i(this,e)}),[{key:"generateSessionId",value:function(){return"sess_"+Math.random().toString(36).substr(2,9)+"_"+Date.now()}},{key:"generateAnonymousId",value:function(){return"anon_"+Math.random().toString(36).substr(2,9)+"_"+Date.now()}},{key:"generateEventId",value:function(){return"evt_"+Math.random().toString(36).substr(2,9)+"_"+Date.now()}}])}(),k=function(){return a((function e(t,r){i(this,e),this.config=t,this.logger=r}),[{key:"updateConfig",value:function(e){this.config=e}},{key:"getStorage",value:function(){return"undefined"!=typeof global&&global.localStorage?global.localStorage:"undefined"!=typeof localStorage?localStorage:null}},{key:"persistQueue",value:function(e){if(this.config.enableLocalStorage){var t=this.getStorage();if(t)try{var r={version:"1.1.0",events:e,timestamp:Date.now()};t.setItem("loopkit_queue",JSON.stringify(r))}catch(e){this.logger.warn("Failed to persist queue",{error:e})}}}},{key:"loadQueue",value:function(){if(!this.config.enableLocalStorage)return[];var e=this.getStorage();if(e)try{var t=e.getItem("loopkit_queue");if(t){var r=JSON.parse(t);if(Array.isArray(r)){if(this.logger.debug("Legacy event format detected, clearing queue"),e)try{e.removeItem("loopkit_queue")}catch(e){this.logger.warn("Failed to clear persisted queue",{error:e})}return[]}if(r&&"object"===d(r)&&r.version&&r.events){var n="1.1.0";if(r.version!==n){if(this.logger.debug("Version mismatch detected (stored: ".concat(r.version,", current: ").concat(n,"), clearing queue")),e)try{e.removeItem("loopkit_queue")}catch(e){this.logger.warn("Failed to clear persisted queue",{error:e})}return[]}if(Array.isArray(r.events))return this.logger.debug("Loaded ".concat(r.events.length," events from storage (version: ").concat(r.version,")")),r.events}}}catch(e){this.logger.warn("Failed to load persisted queue, clearing corrupted data",{error:e}),this.clearQueue()}return[]}},{key:"clearQueue",value:function(){if(this.config.enableLocalStorage){var e=this.getStorage();if(e)try{e.removeItem("loopkit_queue")}catch(e){this.logger.warn("Failed to clear persisted queue",{error:e})}}}},{key:"loadAnonymousId",value:function(){if(!this.config.enableLocalStorage)return null;var e=this.getStorage();if(e)try{var t=e.getItem("loopkit_anonymousId");if(t)return t}catch(e){this.logger.warn("Failed to load anonymous ID",{error:e})}return null}},{key:"saveAnonymousId",value:function(e){if(this.config.enableLocalStorage){var t=this.getStorage();if(t)try{t.setItem("loopkit_anonymousId",e)}catch(e){this.logger.warn("Failed to save anonymous ID",{error:e})}}}},{key:"clearAnonymousId",value:function(){if(this.config.enableLocalStorage){var e=this.getStorage();if(e)try{e.removeItem("loopkit_anonymousId")}catch(e){this.logger.warn("Failed to clear anonymous ID",{error:e})}}}},{key:"clearAll",value:function(){this.clearQueue(),this.clearAnonymousId()}}])}(),m=function(){return a((function e(t,r,n,o){i(this,e),this.config=t,this.logger=r,this.idGenerator=n,this.storageManager=o,this.lastActivityTime=Date.now(),this.anonymousId=this.loadOrCreateAnonymousId(),this.sessionId=this.idGenerator.generateSessionId(),this.startSession(),this.logger.debug("Session initialized",{sessionId:this.sessionId,anonymousId:this.anonymousId})}),[{key:"getSessionId",value:function(){return this.updateActivity(),this.sessionId}},{key:"getAnonymousId",value:function(){return this.updateActivity(),this.anonymousId}},{key:"startSession",value:function(){this.sessionId=this.idGenerator.generateSessionId(),this.lastActivityTime=Date.now(),this.logger.debug("New session started: ".concat(this.sessionId))}},{key:"endSession",value:function(){this.logger.debug("Session ended: ".concat(this.sessionId)),this.sessionId=this.idGenerator.generateSessionId(),this.lastActivityTime=Date.now()}},{key:"isSessionActive",value:function(){return!this.config.enableSessionTracking||Date.now()-this.lastActivityTime<1e3*this.config.sessionTimeout}},{key:"updateActivity",value:function(){var e=Date.now(),t=e-this.lastActivityTime,r=1e3*this.config.sessionTimeout;this.config.enableSessionTracking&&t>=r?(this.logger.debug("Session timeout detected, starting new session"),this.startSession()):this.lastActivityTime=e}},{key:"updateConfig",value:function(e){this.config=e}},{key:"reset",value:function(){this.logger.debug("Resetting session manager"),this.startSession()}},{key:"loadOrCreateAnonymousId",value:function(){var e=this.storageManager.loadAnonymousId();return e?this.logger.debug("Loaded existing anonymous ID: ".concat(e)):(e=this.idGenerator.generateAnonymousId(),this.storageManager.saveAnonymousId(e),this.logger.debug("Generated new anonymous ID: ".concat(e))),e}}])}(),b=function(){return a((function e(t,r,n){i(this,e),this.eventQueue=[],this.isInitialized=!1,this.config=t,this.logger=r,this.storageManager=n,this.loadPersistedQueue(),this.isInitialized=!0}),[{key:"enqueueEvent",value:function(e){if(this.isInitialized){var t={type:"name"in e?"track":"groupId"in e?"group":"identify",event:e};this.eventQueue.length>=this.config.maxQueueSize&&(this.logger.warn("Queue size limit reached (".concat(this.config.maxQueueSize,"), dropping oldest event")),this.eventQueue.shift()),this.eventQueue.push(t),this.logger.debug("Event queued. Queue size: ".concat(this.eventQueue.length)),this.persistQueue(),this.eventQueue.length>=this.config.batchSize&&(this.logger.debug("Batch size reached (".concat(this.config.batchSize,"), auto-flushing")),this.flush(this.networkManager))}else this.logger.warn("QueueManager not initialized")}},{key:"flush",value:(e=n(l().m((function e(t){var r,n,i,o,a,s,u,c,g,f,d,v,p=this;return l().w((function(e){for(;;)switch(e.n){case 0:if(t){e.n=1;break}return this.logger.warn("NetworkManager not set, cannot flush"),e.a(2);case 1:if(0!==this.eventQueue.length){e.n=2;break}return this.logger.debug("No events to flush"),e.a(2);case 2:return r=h(this.eventQueue),this.eventQueue=[],this.persistQueue(),e.p=3,n=[],i=[],o=[],r.forEach((function(e){var t=e.type,r=e.event;switch(t){case"track":n.push(r);break;case"identify":i.push(r);break;case"group":o.push(r)}})),a=[],n.length>0&&(s="".concat(this.config.baseURL,"/tracks"),u={tracks:n},a.push(t.sendEvents(s,u))),i.length>0&&(c="".concat(this.config.baseURL,"/identities"),g={identifies:i},a.push(t.sendEvents(c,g))),o.length>0&&(f="".concat(this.config.baseURL,"/groups"),d={groups:o},a.push(t.sendEvents(f,d))),e.n=4,Promise.all(a);case 4:this.logger.debug("Successfully flushed ".concat(r.length," events")),this.config.onAfterTrack&&r.forEach((function(e){var t=e.type,r=e.event;"track"===t&&p.config.onAfterTrack(r,!0)})),e.n=6;break;case 5:throw e.p=5,v=e.v,this.logger.error("Failed to flush events",{error:v}),this.eventQueue=[].concat(h(r),h(this.eventQueue)),this.persistQueue(),this.config.onAfterTrack&&r.forEach((function(e){var t=e.type,r=e.event;"track"===t&&p.config.onAfterTrack(r,!1)})),this.config.onError&&this.config.onError(v),v;case 6:return e.a(2)}}),e,this,[[3,5]])}))),function(t){return e.apply(this,arguments)})},{key:"getQueue",value:function(){return h(this.eventQueue)}},{key:"getQueueSize",value:function(){return this.eventQueue.length}},{key:"clearQueue",value:function(){this.eventQueue=[],this.persistQueue(),this.logger.debug("Queue cleared")}},{key:"reset",value:function(){this.clearQueue(),this.stopAutoFlush(),this.storageManager.clearQueue()}},{key:"updateConfig",value:function(e){this.config=e}},{key:"setNetworkManager",value:function(e){this.networkManager=e}},{key:"scheduleFlush",value:function(){var e=this;this.config.flushInterval>0&&(this.flushTimer=setInterval((function(){e.eventQueue.length>0&&e.networkManager&&(e.logger.debug("Auto-flush triggered"),e.flush(e.networkManager))}),1e3*this.config.flushInterval))}},{key:"restartAutoFlush",value:function(){this.stopAutoFlush(),this.scheduleFlush()}},{key:"stopAutoFlush",value:function(){this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=void 0)}},{key:"persistQueue",value:function(){if(this.config.enableLocalStorage)try{this.storageManager.persistQueue(this.eventQueue)}catch(e){this.logger.warn("Failed to persist queue",{error:e})}}},{key:"loadPersistedQueue",value:function(){if(this.config.enableLocalStorage)try{var e=this.storageManager.loadQueue();Array.isArray(e)&&e.length>0&&(this.eventQueue=e,this.logger.debug("Loaded ".concat(this.eventQueue.length," persisted events")))}catch(e){this.logger.warn("Failed to load persisted queue",{error:e})}}}]);var e}(),w=function(){return a((function e(){i(this,e)}),null,[{key:"isDoNotTrackEnabled",value:function(){if("undefined"==typeof navigator)return!1;var e=navigator.doNotTrack||window.doNotTrack||navigator.msDoNotTrack;return"1"===e||"yes"===e||!0===e}}])}(),S=function(){return a((function e(t,r,n,o,a){i(this,e),this.config=t,this.logger=r,this.queueManager=n,this.sessionManager=o,this.idGenerator=a}),[{key:"track",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};if(e&&"string"==typeof e)if(this.config.respectDoNotTrack&&w.isDoNotTrackEnabled())this.logger.debug("Do Not Track is enabled, skipping event tracking");else try{var i=c(c({},this.createBaseEvent(r.timestamp)),{},{name:e,properties:c({},t)},n.userId&&{userId:n.userId}),o=i;if(this.config.onBeforeTrack)try{var a=this.config.onBeforeTrack(i);a&&(o=a)}catch(e){this.logger.error("Error in onBeforeTrack callback",{error:e})}this.queueManager.enqueueEvent(o),this.logger.debug("Tracked event: ".concat(e),o)}catch(t){this.logger.error("Failed to track event",{eventName:e,error:t}),this.config.onError&&this.config.onError(t)}else this.logger.warn("Event name is required and must be a string")}},{key:"identify",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(e&&"string"==typeof e)if(this.config.respectDoNotTrack&&w.isDoNotTrackEnabled())this.logger.debug("Do Not Track is enabled, skipping user identification");else try{var r=c(c({},this.createBaseEvent()),{},{userId:e,properties:c({},t)});this.queueManager.enqueueEvent(r),this.logger.debug("Identified user: ".concat(e),r)}catch(t){this.logger.error("Failed to identify user",{userId:e,error:t}),this.config.onError&&this.config.onError(t)}else this.logger.warn("User ID is required and must be a string")}},{key:"group",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"organization",n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};if(e&&"string"==typeof e)if(this.config.respectDoNotTrack&&w.isDoNotTrackEnabled())this.logger.debug("Do Not Track is enabled, skipping group association");else try{var i=c(c({},this.createBaseEvent()),{},{groupId:e,groupType:r,properties:c({},t)},n.userId&&{userId:n.userId});this.queueManager.enqueueEvent(i),this.logger.debug("Associated with group: ".concat(e),i)}catch(t){this.logger.error("Failed to associate with group",{groupId:e,error:t}),this.config.onError&&this.config.onError(t)}else this.logger.warn("Group ID is required and must be a string")}},{key:"updateConfig",value:function(e){this.config=e}},{key:"createBaseEvent",value:function(e){var t=e||(new Date).toISOString();return{anonymousId:this.sessionManager.getAnonymousId(),timestamp:t,system:this.createSystemInfo()}}},{key:"createSystemInfo",value:function(){var e={sdk:{name:"@loopkit/javascript",version:"1.1.0"},sessionId:this.sessionManager.getSessionId()};return"undefined"!=typeof window&&(e.context={page:{url:window.location.href,path:window.location.pathname,search:window.location.search,title:document.title,referrer:document.referrer},userAgent:navigator.userAgent,screen:{width:window.screen.width,height:window.screen.height},viewport:{width:window.innerWidth,height:window.innerHeight}}),e}}])}(),T=function(){return a((function e(t,r){i(this,e),this.config=t,this.logger=r}),[{key:"sendEvents",value:(e=n(l().m((function e(t,r){var n,i,o,a,s,u,c,g,h,f,d,v,p,y,k,m,b=arguments;return l().w((function(e){for(;;)switch(e.n){case 0:return n=b.length>2&&void 0!==b[2]?b[2]:0,e.p=1,i={"Content-Type":"application/json","User-Agent":"@loopkit/javascript"},this.config.enableCompression&&(i["Accept-Encoding"]="gzip, deflate"),(o=new URL(t)).searchParams.set("apiKey",this.config.apiKey),a=o.toString(),s={method:"POST",headers:i,body:JSON.stringify(r)},this.config.requestTimeout&&this.config.requestTimeout>0&&(u=new AbortController,s.signal=u.signal,setTimeout((function(){return u.abort()}),this.config.requestTimeout)),c=this.getEventCountFromPayload(r),this.logger.debug("Sending ".concat(c," event(s) to ").concat(a),{retryCount:n,payload:r}),g=null,e.p=2,e.n=3,fetch(a,s);case 3:g=e.v,e.n=7;break;case 4:if(e.p=4,k=e.v,this.logger.error("Network error during sendEvents (attempt ".concat(n+1,")"),{endpoint:t,error:k instanceof Error?k.message:k,retryCount:n}),!(n<this.config.maxRetries)){e.n=6;break}return h=this.calculateRetryDelay(n),this.logger.debug("Retrying in ".concat(h,"ms (attempt ").concat(n+2,")")),e.n=5,this.sleep(h);case 5:return e.a(2,this.sendEvents(t,r,n+1));case 6:throw k;case 7:if(g&&g.ok){e.n=10;break}if(f=(null==g?void 0:g.status)||"unknown",d=(null==g?void 0:g.statusText)||"unknown error",v=new Error("HTTP ".concat(f,": ").concat(d)),this.logger.error("HTTP error during sendEvents (attempt ".concat(n+1,")"),{endpoint:t,status:f,statusText:d,retryCount:n}),!(n<this.config.maxRetries)){e.n=9;break}return p=this.calculateRetryDelay(n),this.logger.debug("Retrying in ".concat(p,"ms (attempt ").concat(n+2,")")),e.n=8,this.sleep(p);case 8:return e.a(2,this.sendEvents(t,r,n+1));case 9:throw v;case 10:return e.p=10,e.n=11,g.json();case 11:y=e.v,e.n=13;break;case 12:e.p=12,e.v,y={};case 13:return this.logger.debug("Events sent successfully",{result:y}),e.a(2,y);case 14:throw e.p=14,m=e.v,this.logger.error("Unexpected error in sendEvents",{endpoint:t,error:m instanceof Error?m.message:m,retryCount:n}),m;case 15:return e.a(2)}}),e,this,[[10,12],[2,4],[1,14]])}))),function(t,r){return e.apply(this,arguments)})},{key:"sendBeacon",value:function(e,t){if("undefined"==typeof navigator||!navigator.sendBeacon)return this.logger.warn("sendBeacon not available"),!1;try{var r=new URL(e);r.searchParams.set("apiKey",this.config.apiKey);var n=r.toString(),i=JSON.stringify(t),o=new Blob([i],{type:"application/json"}),a=navigator.sendBeacon(n,o);return a?this.logger.debug("Beacon sent successfully",{endpoint:n,payload:t}):this.logger.warn("Beacon failed to send",{endpoint:n}),a}catch(e){return this.logger.error("Beacon send error",{error:e}),!1}}},{key:"updateConfig",value:function(e){this.config=e}},{key:"calculateRetryDelay",value:function(e){return"linear"===this.config.retryBackoff?1e3*(e+1):1e3*Math.pow(2,e)}},{key:"sleep",value:function(e){return new Promise((function(t){return setTimeout(t,e)}))}},{key:"getEventCountFromPayload",value:function(e){return e&&"object"===d(e)?e.tracks&&Array.isArray(e.tracks)?e.tracks.length:e.identifies&&Array.isArray(e.identifies)?e.identifies.length:e.groups&&Array.isArray(e.groups)?e.groups.length:1:0}}]);var e}(),I=function(){return a((function e(t,r,n,o,a){i(this,e),this.config=t,this.logger=r,this.eventTracker=n,this.sessionManager=o,this.queueManager=a}),[{key:"setupFeatures",value:function(){"undefined"!=typeof window?(this.config.enableAutoClickTracking&&this.setupAutoClickTracking(),this.config.enableAutoCapture&&this.setupAutoPageViews(),this.config.enableErrorTracking&&this.setupErrorTracking(),this.setupPageUnloadHandling(),this.logger.debug("Browser features setup complete")):this.logger.debug("Not in browser environment, skipping browser features")}},{key:"setupAutoClickTracking",value:function(){var e=this;"undefined"!=typeof document&&(this.clickHandler=function(t){try{var r=t.target;if(!r)return;var n=e.findClickableElement(r);if(!n)return;var i=e.extractClickProperties(n,t);e.eventTracker.track("click",i)}catch(t){e.logger.error("Error in click tracking",{error:t})}},document.addEventListener("click",this.clickHandler,{capture:!0}),this.logger.debug("Auto-click tracking enabled"))}},{key:"setupAutoPageViews",value:function(){var e=this;if("undefined"!=typeof window){this.trackPageView();var t=history.pushState,r=history.replaceState;history.pushState=function(){for(var r=arguments.length,n=new Array(r),i=0;i<r;i++)n[i]=arguments[i];t.apply(history,n),setTimeout((function(){return e.trackPageView()}),0)},history.replaceState=function(){for(var t=arguments.length,n=new Array(t),i=0;i<t;i++)n[i]=arguments[i];r.apply(history,n),setTimeout((function(){return e.trackPageView()}),0)},window.addEventListener("popstate",(function(){setTimeout((function(){return e.trackPageView()}),0)})),this.logger.debug("Auto page view tracking enabled")}}},{key:"setupErrorTracking",value:function(){var e=this;"undefined"!=typeof window&&(this.errorHandler=function(t){var r;try{e.eventTracker.track("error",{message:t.message,filename:t.filename,lineno:t.lineno,colno:t.colno,stack:null===(r=t.error)||void 0===r?void 0:r.stack,timestamp:(new Date).toISOString()})}catch(t){e.logger.error("Error in error tracking",{error:t})}},window.addEventListener("error",this.errorHandler),this.logger.debug("Error tracking enabled"))}},{key:"setupPageUnloadHandling",value:function(){var e=this;"undefined"!=typeof window&&(this.unloadHandler=function(){try{if(e.queueManager.getQueueSize()>0&&e.networkManager){var t=e.queueManager.getQueue();if(t.length>0){var r=[],n=[],i=[];if(t.forEach((function(e){var t=e.type,o=e.event;switch(t){case"track":r.push(o);break;case"identify":n.push(o);break;case"group":i.push(o)}})),r.length>0){var o="".concat(e.config.baseURL,"/tracks"),a={tracks:r};e.networkManager.sendBeacon(o,a)}if(n.length>0){var s="".concat(e.config.baseURL,"/identities"),u={identifies:n};e.networkManager.sendBeacon(s,u)}if(i.length>0){var c="".concat(e.config.baseURL,"/groups"),l={groups:i};e.networkManager.sendBeacon(c,l)}}}}catch(t){e.logger.error("Error in unload handler",{error:t})}},window.addEventListener("beforeunload",this.unloadHandler),this.logger.debug("Page unload handling enabled"))}},{key:"updateConfig",value:function(e){this.config=e}},{key:"setNetworkManager",value:function(e){this.networkManager=e}},{key:"trackPageView",value:function(){this.eventTracker.track("page_view",{url:window.location.href,path:window.location.pathname,search:window.location.search,title:document.title,referrer:document.referrer})}},{key:"findClickableElement",value:function(e){for(var t=e,r=0;t&&r<5;){var n=t.tagName.toLowerCase();if("a"===n||"button"===n||"button"===t.getAttribute("role")||t.onclick||"pointer"===t.style.cursor)return t;t=t.parentElement,r++}return e}},{key:"extractClickProperties",value:function(e,t){return e.getBoundingClientRect(),{element_type:this.getElementType(e),element_text:this.getElementText(e),element_id:e.id||null,element_class:e.className||null,element_tag:e.tagName.toLowerCase(),element_href:e.href||void 0,element_aria_label:e.getAttribute("aria-label")||void 0,page:window.location.pathname,page_title:document.title,page_url:window.location.href,position:{x:Math.round(t.clientX),y:Math.round(t.clientY)}}}},{key:"getElementType",value:function(e){var t=e.tagName.toLowerCase();return"a"===t?"link":"button"===t||"button"===e.getAttribute("role")?"button":"input"===t?"input":"form"===t?"form":"element"}},{key:"getElementText",value:function(e){return(e.innerText||e.textContent||e.getAttribute("aria-label")||e.getAttribute("title")||e.getAttribute("alt")||"").trim().substring(0,255)}}])}(),A=function(){return a((function e(){i(this,e),this.version="1.1.0",this.config={apiKey:"",baseURL:"https://drain.loopkit.ai/v1",batchSize:50,flushInterval:30,maxQueueSize:1e3,enableCompression:!0,requestTimeout:1e4,debug:!1,logLevel:"debug",enableAutoCapture:!0,enableAutoClickTracking:!0,enableErrorTracking:!0,enableSessionTracking:!0,sessionTimeout:1800,respectDoNotTrack:!0,enableLocalStorage:!0,maxRetries:3,retryBackoff:"exponential"},this.initialized=!1,this.userId=null,this.userProperties={},this.groupId=null,this.groupProperties={}}),[{key:"init",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!e||"string"!=typeof e)throw new Error("LoopKit: API key is required and must be a string");return this.config=c(c(c({},this.config),t),{},{apiKey:e}),v.validate(this.config),this.logger=new p(this.config),this.idGenerator=new y,this.storageManager=new k(this.config,this.logger),this.sessionManager=new m(this.config,this.logger,this.idGenerator,this.storageManager),this.queueManager=new b(this.config,this.logger,this.storageManager),this.eventTracker=new S(this.config,this.logger,this.queueManager,this.sessionManager,this.idGenerator),this.networkManager=new T(this.config,this.logger),"undefined"!=typeof window&&(this.browserFeatures=new I(this.config,this.logger,this.eventTracker,this.sessionManager,this.queueManager)),this.queueManager.setNetworkManager(this.networkManager),this.queueManager.scheduleFlush(),this.browserFeatures&&(this.browserFeatures.setNetworkManager(this.networkManager),this.browserFeatures.setupFeatures()),this.initialized=!0,this.logger.debug("LoopKit configured",this.config),this.logger.info("LoopKit initialized",{apiKey:this.config.apiKey.substring(0,8)+"...",version:this.version}),this}},{key:"configure",value:function(e){var t,r,n,i,o,a,s,u;return v.validate(e),this.config=c(c({},this.config),e),this.initialized&&(null===(t=this.logger)||void 0===t||t.updateConfig(this.config),null===(r=this.storageManager)||void 0===r||r.updateConfig(this.config),null===(n=this.sessionManager)||void 0===n||n.updateConfig(this.config),null===(i=this.queueManager)||void 0===i||i.updateConfig(this.config),null===(o=this.eventTracker)||void 0===o||o.updateConfig(this.config),null===(a=this.networkManager)||void 0===a||a.updateConfig(this.config),null===(s=this.browserFeatures)||void 0===s||s.updateConfig(this.config),null===(u=this.queueManager)||void 0===u||u.restartAutoFlush()),this}},{key:"getConfig",value:function(){return c({},this.config)}},{key:"track",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return this.initialized?e&&"string"==typeof e?(this.eventTracker.track(e,t,r,{userId:this.userId,userProperties:this.userProperties,groupId:this.groupId,groupProperties:this.groupProperties}),this):(this.logger.warn("Event name is required and must be a string"),this):(this.logger.warn("LoopKit not initialized. Call init() first."),this)}},{key:"trackBatch",value:function(e){var t=this;return this.initialized?Array.isArray(e)?(e.forEach((function(e){e&&"object"===d(e)&&e.name&&t.track(e.name,e.properties||{},e.options||{})})),this):(this.logger.error("trackBatch expects an array of events"),this):(this.logger.warn("LoopKit not initialized. Call init() first."),this)}},{key:"identify",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this.initialized?e&&"string"==typeof e?(this.userId=e,this.userProperties=c(c({},this.userProperties),t),this.eventTracker.identify(e,t),this):(this.logger.error("User ID is required and must be a string"),this):(this.logger.warn("LoopKit not initialized. Call init() first."),this)}},{key:"group",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"organization";return this.initialized?e&&"string"==typeof e?(this.groupId=e,this.groupProperties=c(c({},this.groupProperties),t),this.eventTracker.group(e,t,r,{userId:this.userId}),this):(this.logger.error("Group ID is required and must be a string"),this):(this.logger.warn("LoopKit not initialized. Call init() first."),this)}},{key:"flush",value:(e=n(l().m((function e(){return l().w((function(e){for(;;)switch(e.n){case 0:if(this.initialized){e.n=1;break}return this.logger.warn("LoopKit not initialized. Call init() first."),e.a(2);case 1:return e.a(2,this.queueManager.flush(this.networkManager))}}),e,this)}))),function(){return e.apply(this,arguments)})},{key:"getQueueSize",value:function(){return this.initialized?this.queueManager.getQueueSize():0}},{key:"reset",value:function(){var e,t,r;this.initialized&&(this.userId=null,this.userProperties={},this.groupId=null,this.groupProperties={},null===(e=this.queueManager)||void 0===e||e.reset(),null===(t=this.storageManager)||void 0===t||t.clearAll(),null===(r=this.sessionManager)||void 0===r||r.reset(),this.logger.debug("SDK state reset"))}},{key:"resetForTesting",value:function(){var e,t,r;this.initialized&&(null===(e=this.queueManager)||void 0===e||e.reset(),null===(t=this.storageManager)||void 0===t||t.clearAll(),null===(r=this.sessionManager)||void 0===r||r.reset()),this.initialized=!1,this.userId=null,this.userProperties={},this.groupId=null,this.groupProperties={},this.config={apiKey:"",baseURL:"https://drain.loopkit.ai/v1",batchSize:50,flushInterval:30,maxQueueSize:1e3,enableCompression:!0,requestTimeout:1e4,debug:!1,logLevel:"debug",enableAutoCapture:!0,enableAutoClickTracking:!0,enableErrorTracking:!0,enableSessionTracking:!0,sessionTimeout:1800,respectDoNotTrack:!0,enableLocalStorage:!0,maxRetries:3,retryBackoff:"exponential"}}}]);var e}(),E=new A;"undefined"!=typeof module&&module.exports?module.exports=E:"undefined"!=typeof window&&(window.LoopKit=E),e.LoopKit=A,e.default=E,Object.defineProperty(e,"__esModule",{value:!0})}));
{
"name": "@loopkit/javascript",
"version": "1.0.6",
"description": "LoopKit JavaScript SDK for tracking events and user analytics",
"main": "dist/loopkit.js",
"version": "1.1.0",
"description": "JavaScript SDK for LoopKit analytics platform",
"type": "module",
"main": "dist/loopkit.cjs.js",
"module": "dist/loopkit.esm.js",
"browser": "dist/loopkit.js",
"unpkg": "dist/loopkit.min.js",
"types": "dist/index.d.ts",
"files": [
"dist",
"README.md"
"dist/",
"README.md",
"LICENSE"
],
"scripts": {
"build": "rollup -c",
"build:watch": "rollup -c -w",
"build": "npm run clean && npm run build:ts && npm run build:rollup",
"build:ts": "tsc",
"build:rollup": "rollup -c",
"deploy:cdn": "npm run build && ./deploy.sh",
"clean": "rm -rf dist/",
"dev": "rollup -c -w",
"test": "jest",
"test:watch": "jest --watch",
"lint": "eslint src/**/*.js",
"format": "prettier --write src/**/*.js",
"prepare": "npm run build",
"deploy:cdn": "./deploy.sh"
"test:coverage": "jest --coverage",
"lint": "eslint src/**/*.ts",
"lint:fix": "eslint src/**/*.ts --fix",
"format": "prettier --write src/**/*.ts",
"type-check": "tsc --noEmit"
},

@@ -25,8 +34,8 @@ "keywords": [

"tracking",
"events",
"loopkit",
"javascript",
"typescript",
"sdk"
],
"author": "LoopKit",
"author": "LoopKit Team",
"license": "MIT",

@@ -36,21 +45,28 @@ "devDependencies": {

"@babel/preset-env": "^7.23.0",
"@rollup/plugin-babel": "^6.0.0",
"@rollup/plugin-commonjs": "^25.0.0",
"@rollup/plugin-node-resolve": "^15.2.0",
"@rollup/plugin-replace": "^6.0.2",
"@rollup/plugin-terser": "^0.4.0",
"eslint": "^8.50.0",
"@rollup/plugin-babel": "^6.0.4",
"@rollup/plugin-node-resolve": "^15.2.3",
"@rollup/plugin-replace": "^5.0.5",
"@rollup/plugin-terser": "^0.4.4",
"@rollup/plugin-typescript": "^11.1.5",
"@types/jest": "^29.5.8",
"@types/node": "^20.9.2",
"@typescript-eslint/eslint-plugin": "^6.12.0",
"@typescript-eslint/parser": "^6.12.0",
"eslint": "^8.54.0",
"jest": "^29.7.0",
"jest-environment-jsdom": "^29.7.0",
"prettier": "^3.0.0",
"rollup": "^4.0.0"
"prettier": "^3.0.3",
"rollup": "^4.3.0",
"ts-jest": "^29.1.1",
"tslib": "^2.6.2",
"typescript": "^5.3.2"
},
"repository": {
"type": "git",
"url": "git+https://github.com/loopkitai/javascript-sdk.git"
"url": "https://github.com/loopkit/javascript-sdk.git"
},
"bugs": {
"url": "https://github.com/loopkitai/javascript-sdk/issues"
"url": "https://github.com/loopkit/javascript-sdk/issues"
},
"homepage": "https://github.com/loopkitai/javascript-sdk#readme"
"homepage": "https://github.com/loopkit/javascript-sdk#readme"
}
+171
-9
# LoopKit JavaScript SDK
A JavaScript SDK for LoopKit analytics that works in both browser and Node.js environments.
A complete analytics SDK for tracking events, user identification, and behavioral analytics in web applications. Now built with **TypeScript** for better developer experience and type safety.
## Features
- **🔧 TypeScript Support**: Full TypeScript support with comprehensive type definitions
- **📊 Event Tracking**: Track custom events with properties
- **👤 User Identification**: Identify users and track their journey
- **👥 Group Analytics**: Associate users with organizations/groups
- **🔄 Zero-Config Auto Tracking**: Automatic page views, clicks, and error tracking (enabled by default)
- **💾 Local Storage**: Persist events offline with automatic retry
- **🌐 Cross-Platform**: Works in browsers, Node.js, and React applications
- **📦 Multiple Formats**: ES modules, CommonJS, UMD builds available
## 📖 Complete Documentation

@@ -28,6 +39,7 @@

// Initialize
// Initialize - auto tracking starts immediately!
LoopKit.init('your-api-key-here');
// ✅ automatically tracking page views, clicks, and errors
// Track an event
// Track custom events manually
LoopKit.track('button_clicked', {

@@ -64,7 +76,145 @@ button_name: 'signup',

## Auto Tracking Features (Enabled by Default)
LoopKit automatically tracks common user interactions and events out of the box. **All auto tracking features are enabled by default** for zero-configuration setup:
### 📋 Quick Reference
| Feature | Default | Event Type | Description |
| ------------------------- | --------- | ----------- | -------------------------------- |
| `enableAutoCapture` | ✅ `true` | `page_view` | Page loads and navigation |
| `enableAutoClickTracking` | ✅ `true` | `click` | Button, link, and element clicks |
| `enableErrorTracking` | ✅ `true` | `error` | JavaScript errors and exceptions |
### 📊 **Page View Tracking** (`enableAutoCapture: true`)
- **What it tracks**: Automatically captures page views on initial load and navigation
- **Events generated**: `page_view` events with URL, path, title, and referrer
- **When it triggers**:
- Initial page load
- Browser navigation (back/forward buttons)
- Single Page App (SPA) route changes
- **Event properties**: `url`, `path`, `search`, `title`, `referrer`
### 🖱️ **Click Tracking** (`enableAutoClickTracking: true`)
- **What it tracks**: Automatically captures clicks on interactive elements
- **Events generated**: `click` events with element details and page context
- **Elements tracked**: Buttons, links, form inputs, and clickable elements
- **Event properties**: `element_type`, `element_text`, `element_id`, `element_class`, `element_tag`, `element_href`, `page`, `page_title`, `page_url`, `position`
### 🚨 **Error Tracking** (`enableErrorTracking: true`)
- **What it tracks**: Automatically captures JavaScript errors and exceptions
- **Events generated**: `error` events with error details and stack traces
- **Error types**: Runtime errors, syntax errors, and unhandled promise rejections
- **Event properties**: `message`, `filename`, `lineno`, `colno`, `stack`, `timestamp`
### Zero-Config Example
```javascript
// Just initialize with your API key - auto tracking starts immediately!
LoopKit.init('your-api-key');
// The SDK will now automatically track:
// ✅ Page views when users navigate
// ✅ Clicks on buttons, links, etc.
// ✅ JavaScript errors that occur
// ✅ Session management
```
### Customizing Auto Tracking
You can disable specific auto tracking features if needed:
```javascript
LoopKit.init('your-api-key', {
enableAutoCapture: false, // Disable page view tracking
enableAutoClickTracking: false, // Disable click tracking
enableErrorTracking: false, // Disable error tracking
});
```
## TypeScript Support
The SDK is built with TypeScript and exports comprehensive type definitions:
### Core Types
```typescript
import type {
// Configuration
LoopKitConfig,
LogLevel,
RetryBackoff,
// Events
TrackEvent,
IdentifyEvent,
GroupEvent,
ClickEventProperties,
BatchEventInput,
TrackOptions,
// Interfaces
ILoopKit,
IStorageManager,
ISessionManager,
IQueueManager,
INetworkManager,
// Convenience aliases
Config,
Event,
Options,
} from '@loopkit/javascript';
```
### Configuration Types
```typescript
const config: LoopKitConfig = {
apiKey: 'your-key',
baseURL: 'https://api.example.com',
batchSize: 50,
flushInterval: 30,
debug: true,
logLevel: 'info',
// Auto tracking (all enabled by default)
enableAutoCapture: true, // Page view tracking
enableAutoClickTracking: true, // Click tracking
enableErrorTracking: true, // Error tracking
respectDoNotTrack: true,
onBeforeTrack: (event) => {
// Modify event before tracking
return { ...event, timestamp: new Date().toISOString() };
},
onAfterTrack: (event, success) => {
if (!success) {
console.warn('Failed to track event:', event);
}
},
onError: (error) => {
console.error('LoopKit error:', error);
},
};
```
## API Reference
### API Endpoints
The SDK sends events to separate, dedicated endpoints:
- **Track Events**: `POST /tracks` with payload `{ tracks: [...] }`
- **User Identification**: `POST /identities` with payload `{ identifies: [...] }`
- **Group Association**: `POST /groups` with payload `{ groups: [...] }`
Each endpoint receives an array of the respective event type wrapped in a named property. This allows for better API performance and easier backend processing.
### Initialization
#### `LoopKit.init(apiKey, options?)`
#### `LoopKit.init(apiKey, config?)`

@@ -78,4 +228,7 @@ Initialize the SDK with your API key and optional configuration.

flushInterval: 30,
enableAutoCapture: false,
enableErrorTracking: false,
// Auto tracking features (enabled by default - shown here for reference)
enableAutoCapture: true, // Auto page view tracking
enableAutoClickTracking: true, // Auto click tracking
enableErrorTracking: true, // Auto error tracking
});

@@ -160,2 +313,10 @@ ```

### LoopKit.reset()
Reset the SDK state (useful for logout).
```javascript
LoopKit.reset();
```
## Configuration Options

@@ -181,5 +342,6 @@

// Auto-capture (Browser only)
enableAutoCapture: false, // Auto-track page views
enableErrorTracking: false, // Auto-track JS errors
// Auto-capture (Browser only) - All enabled by default for zero-config setup
enableAutoCapture: true, // Auto-track page views
enableAutoClickTracking: true, // Auto-track click events
enableErrorTracking: true, // Auto-track JS errors

@@ -186,0 +348,0 @@ // Privacy

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display