guideai-app 0.2.9 → 0.3.1

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.
@@ -1,4 +1,4 @@
1
- import { UserMetadata, MetadataUpdate } from '../types/metadata.types';
1
+ import { MetadataUpdate } from '../types/metadata.types';
2
2
  interface ConversationData {
3
3
  id: string;
4
4
  ephemeralToken: string;
@@ -6,7 +6,5 @@ interface ConversationData {
6
6
  }
7
7
  export declare const createNewConversation: (organizationKey: string, onError: (error: Error, context: string) => void) => Promise<ConversationData | null>;
8
8
  export declare const logMessage: (content: string, sender: "GUIDEAI" | "HUMAN", conversationId: string | null, organizationKey: string, onError: (error: Error, context: string) => void) => Promise<void>;
9
- export declare const sendUserMetadata: (metadata: UserMetadata, organizationKey: string, onError: (error: Error, context: string) => void) => Promise<boolean>;
10
9
  export declare const sendMetadataUpdates: (updates: MetadataUpdate[], organizationKey: string, onError: (error: Error, context: string) => void) => Promise<boolean>;
11
- export declare const updateUserMetadata: (userId: string, metadataUpdate: Partial<UserMetadata>, organizationKey: string, onError: (error: Error, context: string) => void) => Promise<boolean>;
12
10
  export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "guideai-app",
3
- "version": "0.2.9",
3
+ "version": "0.3.1",
4
4
  "description": "AI-powered guide component for React applications",
5
5
  "main": "dist/GuideAI.js",
6
6
  "types": "dist/GuideAI.d.ts",
@@ -1,324 +0,0 @@
1
- # User Metadata Tracking - Implementation Guide
2
-
3
- ## Overview
4
-
5
- The GuideAI package now includes comprehensive user metadata tracking capabilities designed for integration with Overproof. This system tracks the following metadata:
6
-
7
- - **User's First Visit** - Timestamp of the first time the user interacted with GuideAI
8
- - **User's Last Visit** - Timestamp of the most recent user interaction
9
- - **User Logins** - Count and timestamp of login events
10
- - **User Type** - Classification of the user (agent, admin, manager, customer, guest, etc.)
11
- - **Customer Type** - Type of customer (individual, business, enterprise, etc.)
12
- - **Customer License** - License identifier for the customer
13
-
14
- ## Basic Usage
15
-
16
- ### 1. Basic Integration
17
-
18
- ```typescript
19
- import { GuideAI } from 'guide-ai-package';
20
-
21
- function App() {
22
- return (
23
- <GuideAI
24
- organizationKey="your-org-key"
25
- metadata={{
26
- config: {
27
- trackVisits: true,
28
- trackLogins: true,
29
- syncInterval: 30000, // Sync every 30 seconds
30
- storage: 'localStorage'
31
- },
32
- initialUserData: {
33
- userType: 'agent',
34
- customerType: 'business',
35
- customerLicense: 'OVERPRF-12345'
36
- },
37
- onMetadataUpdate: (metadata) => {
38
- console.log('Metadata updated:', metadata);
39
- // Send to your analytics system
40
- }
41
- }}
42
- />
43
- );
44
- }
45
- ```
46
-
47
- ### 2. Tracking User Login Events
48
-
49
- ```typescript
50
- import { useRef } from 'react';
51
-
52
- function LoginComponent() {
53
- const guideAIRef = useRef();
54
-
55
- const handleLogin = async (userInfo) => {
56
- // Your login logic here
57
- const loginResult = await performLogin(userInfo);
58
-
59
- if (loginResult.success) {
60
- // Track the login with GuideAI
61
- guideAIRef.current?.trackLogin({
62
- userId: loginResult.userId,
63
- userType: loginResult.userType,
64
- customerType: loginResult.customerType,
65
- customerLicense: loginResult.license
66
- });
67
- }
68
- };
69
-
70
- return (
71
- <div>
72
- <GuideAI
73
- ref={guideAIRef}
74
- organizationKey="your-org-key"
75
- metadata={{
76
- config: { trackLogins: true }
77
- }}
78
- />
79
- <button onClick={handleLogin}>Login</button>
80
- </div>
81
- );
82
- }
83
- ```
84
-
85
- ### 3. Updating User Information
86
-
87
- ```typescript
88
- function UserProfileComponent() {
89
- const guideAIRef = useRef();
90
-
91
- const updateUserProfile = (newUserData) => {
92
- // Update user profile in your system
93
- saveUserProfile(newUserData);
94
-
95
- // Update GuideAI metadata
96
- guideAIRef.current?.updateUserInfo({
97
- userType: newUserData.role,
98
- customerType: newUserData.accountType,
99
- customerLicense: newUserData.license,
100
- customFields: {
101
- department: newUserData.department,
102
- region: newUserData.region
103
- }
104
- });
105
- };
106
-
107
- return (
108
- <GuideAI
109
- ref={guideAIRef}
110
- organizationKey="your-org-key"
111
- metadata={{
112
- config: {
113
- customFields: ['department', 'region'],
114
- collectBrowserInfo: true
115
- }
116
- }}
117
- />
118
- );
119
- }
120
- ```
121
-
122
- ## Configuration Options
123
-
124
- ### MetadataConfig
125
-
126
- ```typescript
127
- interface MetadataConfig {
128
- // Whether to automatically track visits (default: true)
129
- trackVisits?: boolean;
130
-
131
- // Whether to automatically track logins (default: true)
132
- trackLogins?: boolean;
133
-
134
- // How often to sync metadata to backend in milliseconds (default: 30000)
135
- syncInterval?: number;
136
-
137
- // Storage strategy (default: 'localStorage')
138
- storage?: 'localStorage' | 'sessionStorage' | 'memory';
139
-
140
- // Custom metadata fields to collect
141
- customFields?: string[];
142
-
143
- // Whether to collect browser information (default: true)
144
- collectBrowserInfo?: boolean;
145
-
146
- // Whether to collect user agent (default: true)
147
- collectUserAgent?: boolean;
148
- }
149
- ```
150
-
151
- ### UserMetadata Structure
152
-
153
- ```typescript
154
- interface UserMetadata {
155
- // Core identification
156
- userId?: string;
157
- userType?: 'agent' | 'admin' | 'manager' | 'customer' | 'guest' | string;
158
-
159
- // Customer-specific metadata
160
- customerType?: 'individual' | 'business' | 'enterprise' | string;
161
- customerLicense?: string;
162
-
163
- // Visit tracking (automatically managed)
164
- firstVisit?: number; // timestamp
165
- lastVisit?: number; // timestamp
166
- visitCount?: number;
167
-
168
- // Login tracking (requires manual tracking)
169
- loginCount?: number;
170
- lastLogin?: number; // timestamp
171
-
172
- // Session metadata (automatically managed)
173
- organizationKey: string;
174
- sessionId?: string;
175
-
176
- // Browser information (automatically collected if enabled)
177
- userAgent?: string;
178
- browserInfo?: {
179
- name?: string;
180
- version?: string;
181
- platform?: string;
182
- };
183
-
184
- // Custom fields for Overproof-specific needs
185
- customFields?: Record<string, string | number | boolean>;
186
- }
187
- ```
188
-
189
- ## API Integration
190
-
191
- The system automatically sends metadata updates to these endpoints:
192
-
193
- ### POST `/user-metadata`
194
- Sends complete user metadata object when initially collected.
195
-
196
- ### POST `/metadata-updates`
197
- Sends batched metadata updates periodically.
198
-
199
- ### PATCH `/users/{userId}/metadata`
200
- Updates specific user metadata when userId is available.
201
-
202
- ## Backend Implementation
203
-
204
- You'll need to implement these endpoints in your backend:
205
-
206
- ```typescript
207
- // Example Express.js implementation
208
- app.post('/api/user-metadata', (req, res) => {
209
- const { organizationKey, metadata, timestamp } = req.body;
210
-
211
- // Store metadata in your database
212
- await UserMetadata.upsert({
213
- organizationKey,
214
- userId: metadata.userId || 'anonymous',
215
- ...metadata,
216
- lastUpdated: new Date(timestamp)
217
- });
218
-
219
- res.json({ success: true });
220
- });
221
-
222
- app.post('/api/metadata-updates', (req, res) => {
223
- const { organizationKey, updates, batchTimestamp } = req.body;
224
-
225
- // Process batch updates
226
- for (const update of updates) {
227
- await processMetadataUpdate(organizationKey, update);
228
- }
229
-
230
- res.json({ success: true });
231
- });
232
- ```
233
-
234
- ## Privacy Considerations
235
-
236
- - **User Agent Collection**: Can be disabled via `collectUserAgent: false`
237
- - **Browser Info Collection**: Can be disabled via `collectBrowserInfo: false`
238
- - **Custom Fields**: Only fields specified in `customFields` array are collected
239
- - **Storage**: Can be set to `'memory'` for session-only storage without persistence
240
-
241
- ## Testing
242
-
243
- ```typescript
244
- // Get current metadata
245
- const metadata = guideAIRef.current?.getMetadata();
246
- console.log('Current metadata:', metadata);
247
-
248
- // Force sync metadata now
249
- await guideAIRef.current?.syncMetadata();
250
-
251
- // Track custom events
252
- guideAIRef.current?.trackCustomEvent('document_viewed', {
253
- documentType: 'policy',
254
- documentId: 'POL-12345'
255
- });
256
- ```
257
-
258
- ## Overproof Integration Example
259
-
260
- ```typescript
261
- function OverproofApp() {
262
- const guideAIRef = useRef();
263
-
264
- // Track when user logs into Overproof
265
- const handleOverproofLogin = (user) => {
266
- guideAIRef.current?.trackLogin({
267
- userId: user.id,
268
- userType: user.role, // 'agent', 'admin', etc.
269
- customerType: user.accountType,
270
- customerLicense: user.licenseNumber,
271
- customFields: {
272
- agencyId: user.agencyId,
273
- territory: user.territory,
274
- permissions: user.permissions.join(',')
275
- }
276
- });
277
- };
278
-
279
- // Track when user profile is updated
280
- const handleProfileUpdate = (updatedProfile) => {
281
- guideAIRef.current?.updateUserInfo({
282
- userType: updatedProfile.role,
283
- customerLicense: updatedProfile.licenseNumber,
284
- customFields: {
285
- agencyId: updatedProfile.agencyId,
286
- territory: updatedProfile.territory
287
- }
288
- });
289
- };
290
-
291
- return (
292
- <GuideAI
293
- ref={guideAIRef}
294
- organizationKey="overproof-org-key"
295
- metadata={{
296
- config: {
297
- trackVisits: true,
298
- trackLogins: true,
299
- syncInterval: 15000, // More frequent syncing for Overproof
300
- customFields: ['agencyId', 'territory', 'permissions'],
301
- collectBrowserInfo: true
302
- },
303
- onMetadataUpdate: (metadata) => {
304
- // Send to Overproof analytics
305
- window.OverproofAnalytics?.track('guideai_metadata_update', metadata);
306
- }
307
- }}
308
- />
309
- );
310
- }
311
- ```
312
-
313
- ## Storage and Data Persistence
314
-
315
- - **localStorage**: Persists across browser sessions (default)
316
- - **sessionStorage**: Persists only for current session
317
- - **memory**: No persistence, data lost on page refresh
318
-
319
- Metadata is automatically:
320
- - Saved locally based on storage configuration
321
- - Synced to backend at configured intervals
322
- - Restored when user returns (if using persistent storage)
323
-
324
- This implementation provides a robust foundation for tracking user metadata in the Overproof environment while maintaining flexibility for other use cases.
package/obfuscate.js DELETED
@@ -1,40 +0,0 @@
1
- const fs = require('fs');
2
- const path = require('path');
3
- const JavaScriptObfuscator = require('javascript-obfuscator');
4
-
5
- // Files to obfuscate
6
- const files = [
7
- 'dist/index.js',
8
- 'dist/index.esm.js'
9
- ];
10
-
11
- // Load obfuscator config
12
- const config = JSON.parse(fs.readFileSync(path.resolve(__dirname, 'obfuscator.json'), 'utf8'));
13
-
14
- // Process each file
15
-
16
- files.forEach(file => {
17
- const filePath = path.resolve(__dirname, file);
18
-
19
- try {
20
- // Check if file exists
21
- if (!fs.existsSync(filePath)) {
22
- console.warn(`Warning: ${file} does not exist, skipping obfuscation.`);
23
- return;
24
- }
25
-
26
-
27
- // Read the file
28
- const code = fs.readFileSync(filePath, 'utf8');
29
-
30
- // Obfuscate the code
31
- const obfuscationResult = JavaScriptObfuscator.obfuscate(code, config);
32
-
33
- // Write the obfuscated code back to the file
34
- fs.writeFileSync(filePath, obfuscationResult.getObfuscatedCode());
35
-
36
- } catch (error) {
37
- console.error(`Error obfuscating ${file}:`, error);
38
- process.exit(1);
39
- }
40
- });
@@ -1,24 +0,0 @@
1
- {
2
- "compact": true,
3
- "controlFlowFlattening": false,
4
- "controlFlowFlatteningThreshold": 0.75,
5
- "deadCodeInjection": false,
6
- "deadCodeInjectionThreshold": 0.4,
7
- "debugProtection": false,
8
- "debugProtectionInterval": 0,
9
- "disableConsoleOutput": true,
10
- "identifierNamesGenerator": "hexadecimal",
11
- "log": false,
12
- "numbersToExpressions": false,
13
- "renameGlobals": false,
14
- "rotateStringArray": false,
15
- "selfDefending": false,
16
- "shuffleStringArray": false,
17
- "splitStrings": false,
18
- "splitStringsChunkLength": 10,
19
- "stringArray": false,
20
- "stringArrayEncoding": [],
21
- "stringArrayThreshold": 0,
22
- "transformObjectKeys": false,
23
- "unicodeEscapeSequence": false
24
- }
package/structure.md DELETED
@@ -1,128 +0,0 @@
1
- # GuideAI Package Structure
2
-
3
- ## Directory Structure
4
-
5
- ```
6
- guide-ai-package/src/
7
- ├── GuideAI.tsx # Main component
8
- ├── index.ts # Package entry point
9
- ├── components/ # React components
10
- │ └── Styles.tsx # Styling for the component
11
- ├── hooks/ # React hooks
12
- │ ├── useConversation.ts # Conversation management
13
- │ └── useRecording.ts # Audio recording and WebRTC
14
- ├── types/ # TypeScript type definitions
15
- │ └── index.ts # Type definitions
16
- └── utils/ # Utility functions
17
- ├── api-services.ts # API related functions
18
- ├── dom-interaction.ts # DOM manipulation utilities
19
- ├── react-hooks.ts # React hooks utilities
20
- ├── storage.ts # Local storage utilities
21
- └── webrtc.ts # WebRTC related utilities
22
- ```
23
-
24
- ## File Descriptions
25
-
26
- ### Main Files
27
-
28
- #### `GuideAI.tsx`
29
- The main component exported by the package that provides the user interface for audio interactions.
30
-
31
- **Functions & Components:**
32
- - `GuideAI(props: GuideAIProps)`: Main component that renders the UI
33
- - Sets up conversation management
34
- - Initializes audio recording
35
- - Handles user interactions
36
-
37
- #### `index.ts`
38
- Entry point for the package, exports the GuideAI component and types.
39
-
40
- **Exports:**
41
- - `GuideAI`
42
- - `GuideAIProps` (type)
43
-
44
- ### Components
45
-
46
- #### `components/Styles.tsx`
47
- Contains the CSS styling for the GuideAI component.
48
-
49
- **Functions & Components:**
50
- - `Styles()`: Component that injects CSS styles into the page
51
-
52
- ### Hooks
53
-
54
- #### `hooks/useConversation.ts`
55
- Custom hook for managing conversation state and interaction with the API.
56
-
57
- **Functions:**
58
- - `useConversation(organizationKey, onError)`: Main hook function
59
- - `storeConversationItem(item)`: Stores a conversation item
60
- - `initializeConversation()`: Creates or restores a conversation
61
- - `logMessageToConversation(content, sender)`: Logs a message to the conversation
62
- - `addConversationHistory(sendMessageFn)`: Adds conversation history to a new session
63
- - `isConversationStale()`: Checks if conversation is more than 15 minutes old
64
-
65
- #### `hooks/useRecording.ts`
66
- Custom hook for managing audio recording, WebRTC connections, and handling responses.
67
-
68
- **Functions:**
69
- - `useRecording(organizationKey, onError, logMessageFn, addConversationHistoryFn, storeConversationItemFn, isAddingHistoryContextRef)`: Main hook function
70
- - `sendWebRTCMessage(message)`: Sends a message through WebRTC
71
- - `cleanupWebRTC()`: Cleans up WebRTC connections and media streams
72
- - `handleWebRTCMessage(message)`: Handles incoming WebRTC messages
73
- - `startRecording()`: Starts audio recording
74
- - `stopRecording()`: Stops audio recording
75
- - `toggleRecording()`: Toggles recording state
76
-
77
- ### Types
78
-
79
- #### `types/index.ts`
80
- Contains TypeScript type definitions used throughout the package.
81
-
82
- **Types:**
83
- - `ConversationItem`: Represents an item in the conversation
84
- - `RecordingStatus`: Status of the recording ('idle' | 'recording' | 'processing' | 'playing' | 'initializing')
85
- - `GuideAIProps`: Props for the GuideAI component
86
-
87
- ### Utils
88
-
89
- #### `utils/api-services.ts`
90
- Functions for interacting with external APIs.
91
-
92
- **Functions:**
93
- - `createNewConversation(organizationKey)`: Creates a new conversation
94
- - `logMessage(conversationId, content, sender)`: Logs a message to the conversation
95
- - `fetchEphemeralToken(organizationKey)`: Fetches an ephemeral token for WebRTC
96
- - `geminiFlash(prompt)`: Makes a call to the Gemini API
97
-
98
- #### `utils/dom-interaction.ts`
99
- Utilities for interacting with the DOM.
100
-
101
- **Functions:**
102
- - `highlightElement(selector, logMessageFn)`: Highlights an element on the page
103
- - DOM traversal and interaction functions
104
-
105
- #### `utils/react-hooks.ts`
106
- Utilities for React hooks to avoid duplicate React instances.
107
-
108
- **Functions:**
109
- - `getReactHooks()`: Returns React hooks from the host application or fall back to local ones
110
-
111
- #### `utils/storage.ts`
112
- Local storage utility functions.
113
-
114
- **Constants:**
115
- - `STORAGE_PREFIX`: Prefix for storage keys
116
- - `STORAGE_KEYS`: Object containing all storage keys
117
-
118
- **Functions:**
119
- - `saveToStorage(key, value)`: Saves a value to localStorage
120
- - `getFromStorage(key, defaultValue)`: Gets a value from localStorage
121
-
122
- #### `utils/webrtc.ts`
123
- WebRTC related utilities for audio streaming.
124
-
125
- **Functions:**
126
- - `initializeWebRTC(audioStream, token, audioElementRef, peerConnectionRef, dataChannelRef, handleMessageCallback)`: Sets up WebRTC connection
127
- - `sendMessage(dataChannel, message)`: Sends a message through the data channel
128
- - `orderConversationItems(items)`: Orders conversation items for replay