humanbehavior-js 0.2.7 → 0.2.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -213,8 +213,9 @@ declare class HumanBehaviorTracker {
213
213
  */
214
214
  private deleteCookie;
215
215
  /**
216
- * Log out the current user by clearing all user-related data
217
- * This will delete the user ID cookie, clear localStorage, and reset user properties
216
+ * Clear user data and reset session when user signs out of the site
217
+ * This should be called when a user logs out of your application to prevent
218
+ * data contamination between different users
218
219
  */
219
220
  logout(): void;
220
221
  /**
@@ -309,6 +310,25 @@ declare class HumanBehaviorAPI {
309
310
  }>): Promise<any>;
310
311
  }
311
312
 
313
+ /**
314
+ * Server-side utilities for HumanBehavior SDK
315
+ */
316
+ interface ServerSideUserData {
317
+ email: string;
318
+ name?: string;
319
+ image?: string;
320
+ provider?: string;
321
+ [key: string]: any;
322
+ }
323
+ /**
324
+ * Identify user from server-side (NextAuth, Firebase, etc.)
325
+ * Use this in your auth events to track users immediately on sign-in
326
+ */
327
+ declare function identifyUser(userData: ServerSideUserData, apiKey: string): Promise<{
328
+ success: boolean;
329
+ error?: string;
330
+ }>;
331
+
312
332
  declare enum LogLevel {
313
333
  NONE = 0,
314
334
  ERROR = 1,
@@ -342,5 +362,5 @@ declare const logWarn: (message: string, ...args: any[]) => void;
342
362
  declare const logInfo: (message: string, ...args: any[]) => void;
343
363
  declare const logDebug: (message: string, ...args: any[]) => void;
344
364
 
345
- export { HumanBehaviorAPI, HumanBehaviorTracker, LogLevel, MAX_CHUNK_SIZE_BYTES, RedactionManager, HumanBehaviorTracker as default, isChunkSizeExceeded, logDebug, logError, logInfo, logWarn, logger, redactionManager, splitLargeEvent, validateSingleEventSize };
346
- export type { LoggerConfig, RedactionOptions };
365
+ export { HumanBehaviorAPI, HumanBehaviorTracker, LogLevel, MAX_CHUNK_SIZE_BYTES, RedactionManager, HumanBehaviorTracker as default, identifyUser, isChunkSizeExceeded, logDebug, logError, logInfo, logWarn, logger, redactionManager, splitLargeEvent, validateSingleEventSize };
366
+ export type { LoggerConfig, RedactionOptions, ServerSideUserData };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "humanbehavior-js",
3
- "version": "0.2.7",
3
+ "version": "0.2.9",
4
4
  "description": "SDK for HumanBehavior session and event recording",
5
5
  "type": "module",
6
6
  "main": "./dist/cjs/index.js",
package/src/index.ts CHANGED
@@ -13,6 +13,9 @@ export * from './api';
13
13
  // Export redaction functionality
14
14
  export * from './redact';
15
15
 
16
+ // Export server-side utilities
17
+ export * from './server';
18
+
16
19
  // Export logger functionality
17
20
  export * from './utils/logger';
18
21
 
@@ -11,6 +11,7 @@ interface HumanBehaviorInterface {
11
11
  addUserInfo: ({ userId, userProperties }: { userId?: string, userProperties: Record<string, any> }) => Promise<string>;
12
12
  start: () => void;
13
13
  stop: () => void;
14
+ logout: () => void;
14
15
  viewLogs: () => void;
15
16
  }
16
17
 
@@ -173,6 +174,7 @@ const defaultImplementation: HumanBehaviorInterface = {
173
174
  },
174
175
  start: () => {},
175
176
  stop: () => {},
177
+ logout: () => {},
176
178
  viewLogs: () => {},
177
179
  };
178
180
 
@@ -195,6 +197,9 @@ const createQueuingImplementation = (queueEvent: (event: any) => void): HumanBeh
195
197
  stop: () => {
196
198
  // Stop is a no-op when not initialized
197
199
  },
200
+ logout: () => {
201
+ // Logout is a no-op when not initialized
202
+ },
198
203
  viewLogs: () => {
199
204
  logWarn('Logs are not available until HumanBehaviorTracker is initialized');
200
205
  }
package/src/server.ts ADDED
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Server-side utilities for HumanBehavior SDK
3
+ */
4
+
5
+ export interface ServerSideUserData {
6
+ email: string;
7
+ name?: string;
8
+ image?: string;
9
+ provider?: string;
10
+ [key: string]: any; // Allow additional properties
11
+ }
12
+
13
+ /**
14
+ * Identify user from server-side (NextAuth, Firebase, etc.)
15
+ * Use this in your auth events to track users immediately on sign-in
16
+ */
17
+ export async function identifyUser(
18
+ userData: ServerSideUserData,
19
+ apiKey: string
20
+ ): Promise<{ success: boolean; error?: string }> {
21
+ try {
22
+ const response = await fetch('https://ingest.humanbehavior.co/api/ingestion/user', {
23
+ method: 'POST',
24
+ headers: {
25
+ 'Content-Type': 'application/json',
26
+ 'Authorization': `Bearer ${apiKey}`
27
+ },
28
+ body: JSON.stringify({
29
+ userId: userData.email,
30
+ userAttributes: userData,
31
+ posthogName: userData.email || userData.name || null // Update posthogName with email
32
+ })
33
+ });
34
+
35
+ if (!response.ok) {
36
+ const errorText = await response.text();
37
+ return {
38
+ success: false,
39
+ error: `Failed to identify user: ${response.status} ${response.statusText} - ${errorText}`
40
+ };
41
+ }
42
+
43
+ return { success: true };
44
+ } catch (error) {
45
+ return {
46
+ success: false,
47
+ error: error instanceof Error ? error.message : 'Unknown error'
48
+ };
49
+ }
50
+ }
package/src/tracker.ts CHANGED
@@ -1008,8 +1008,9 @@ export class HumanBehaviorTracker {
1008
1008
  }
1009
1009
 
1010
1010
  /**
1011
- * Log out the current user by clearing all user-related data
1012
- * This will delete the user ID cookie, clear localStorage, and reset user properties
1011
+ * Clear user data and reset session when user signs out of the site
1012
+ * This should be called when a user logs out of your application to prevent
1013
+ * data contamination between different users
1013
1014
  */
1014
1015
  public logout(): void {
1015
1016
  if (!isBrowser) return;
@@ -1027,7 +1028,14 @@ export class HumanBehaviorTracker {
1027
1028
  this.endUserId = null;
1028
1029
  this.userProperties = {};
1029
1030
 
1030
- logInfo('User logged out - cleared all user data and cookies');
1031
+ // Generate a new session ID for the next user
1032
+ this.sessionId = uuidv1();
1033
+ if (isBrowser) {
1034
+ localStorage.setItem('human_behavior_session_id', this.sessionId);
1035
+ localStorage.setItem('human_behavior_last_activity', Date.now().toString());
1036
+ }
1037
+
1038
+ logInfo('User logged out - cleared all user data and started fresh session');
1031
1039
  } catch (error) {
1032
1040
  logError('Error during logout:', error);
1033
1041
  }