@clianta/sdk 1.6.0 → 1.6.2

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,5 +1,5 @@
1
1
  /*!
2
- * Clianta SDK v1.6.0
2
+ * Clianta SDK v1.6.2
3
3
  * (c) 2026 Clianta
4
4
  * Released under the MIT License.
5
5
  */
@@ -14,7 +14,7 @@
14
14
  * @see SDK_VERSION in core/config.ts
15
15
  */
16
16
  /** SDK Version */
17
- const SDK_VERSION = '1.6.0';
17
+ const SDK_VERSION = '1.6.2';
18
18
  /** Default API endpoint — reads from env or falls back to localhost */
19
19
  const getDefaultApiEndpoint = () => {
20
20
  // Build-time env var (works with Next.js, Vite, CRA, etc.)
@@ -32,7 +32,7 @@
32
32
  }
33
33
  return 'http://localhost:5000';
34
34
  };
35
- /** Core plugins enabled by default */
35
+ /** Core plugins enabled by default — all auto-track with zero config */
36
36
  const DEFAULT_PLUGINS = [
37
37
  'pageView',
38
38
  'forms',
@@ -41,13 +41,13 @@
41
41
  'engagement',
42
42
  'downloads',
43
43
  'exitIntent',
44
+ 'errors',
45
+ 'performance',
44
46
  ];
45
47
  /** Default configuration values */
46
48
  const DEFAULT_CONFIG = {
47
49
  projectId: '',
48
50
  apiEndpoint: getDefaultApiEndpoint(),
49
- authToken: '',
50
- apiKey: '',
51
51
  debug: false,
52
52
  autoPageView: true,
53
53
  plugins: DEFAULT_PLUGINS,
@@ -2513,1268 +2513,6 @@
2513
2513
  }
2514
2514
  }
2515
2515
 
2516
- /**
2517
- * Clianta SDK - Event Triggers Manager
2518
- * Manages event-driven automation and email notifications
2519
- */
2520
- /**
2521
- * Event Triggers Manager
2522
- * Handles event-driven automation based on CRM actions
2523
- *
2524
- * Similar to:
2525
- * - Salesforce: Process Builder, Flow Automation
2526
- * - HubSpot: Workflows, Email Sequences
2527
- * - Pipedrive: Workflow Automation
2528
- */
2529
- class EventTriggersManager {
2530
- constructor(apiEndpoint, workspaceId, authToken) {
2531
- this.triggers = new Map();
2532
- this.listeners = new Map();
2533
- this.apiEndpoint = apiEndpoint;
2534
- this.workspaceId = workspaceId;
2535
- this.authToken = authToken;
2536
- }
2537
- /**
2538
- * Set authentication token
2539
- */
2540
- setAuthToken(token) {
2541
- this.authToken = token;
2542
- }
2543
- /**
2544
- * Make authenticated API request
2545
- */
2546
- async request(endpoint, options = {}) {
2547
- const url = `${this.apiEndpoint}${endpoint}`;
2548
- const headers = {
2549
- 'Content-Type': 'application/json',
2550
- ...(options.headers || {}),
2551
- };
2552
- if (this.authToken) {
2553
- headers['Authorization'] = `Bearer ${this.authToken}`;
2554
- }
2555
- try {
2556
- const response = await fetch(url, {
2557
- ...options,
2558
- headers,
2559
- });
2560
- const data = await response.json();
2561
- if (!response.ok) {
2562
- return {
2563
- success: false,
2564
- error: data.message || 'Request failed',
2565
- status: response.status,
2566
- };
2567
- }
2568
- return {
2569
- success: true,
2570
- data: data.data || data,
2571
- status: response.status,
2572
- };
2573
- }
2574
- catch (error) {
2575
- return {
2576
- success: false,
2577
- error: error instanceof Error ? error.message : 'Network error',
2578
- status: 0,
2579
- };
2580
- }
2581
- }
2582
- // ============================================
2583
- // TRIGGER MANAGEMENT
2584
- // ============================================
2585
- /**
2586
- * Get all event triggers
2587
- */
2588
- async getTriggers() {
2589
- return this.request(`/api/workspaces/${this.workspaceId}/triggers`);
2590
- }
2591
- /**
2592
- * Get a single trigger by ID
2593
- */
2594
- async getTrigger(triggerId) {
2595
- return this.request(`/api/workspaces/${this.workspaceId}/triggers/${triggerId}`);
2596
- }
2597
- /**
2598
- * Create a new event trigger
2599
- */
2600
- async createTrigger(trigger) {
2601
- const result = await this.request(`/api/workspaces/${this.workspaceId}/triggers`, {
2602
- method: 'POST',
2603
- body: JSON.stringify(trigger),
2604
- });
2605
- // Cache the trigger locally if successful
2606
- if (result.success && result.data?._id) {
2607
- this.triggers.set(result.data._id, result.data);
2608
- }
2609
- return result;
2610
- }
2611
- /**
2612
- * Update an existing trigger
2613
- */
2614
- async updateTrigger(triggerId, updates) {
2615
- const result = await this.request(`/api/workspaces/${this.workspaceId}/triggers/${triggerId}`, {
2616
- method: 'PUT',
2617
- body: JSON.stringify(updates),
2618
- });
2619
- // Update cache if successful
2620
- if (result.success && result.data?._id) {
2621
- this.triggers.set(result.data._id, result.data);
2622
- }
2623
- return result;
2624
- }
2625
- /**
2626
- * Delete a trigger
2627
- */
2628
- async deleteTrigger(triggerId) {
2629
- const result = await this.request(`/api/workspaces/${this.workspaceId}/triggers/${triggerId}`, {
2630
- method: 'DELETE',
2631
- });
2632
- // Remove from cache if successful
2633
- if (result.success) {
2634
- this.triggers.delete(triggerId);
2635
- }
2636
- return result;
2637
- }
2638
- /**
2639
- * Activate a trigger
2640
- */
2641
- async activateTrigger(triggerId) {
2642
- return this.updateTrigger(triggerId, { isActive: true });
2643
- }
2644
- /**
2645
- * Deactivate a trigger
2646
- */
2647
- async deactivateTrigger(triggerId) {
2648
- return this.updateTrigger(triggerId, { isActive: false });
2649
- }
2650
- // ============================================
2651
- // EVENT HANDLING (CLIENT-SIDE)
2652
- // ============================================
2653
- /**
2654
- * Register a local event listener for client-side triggers
2655
- * This allows immediate client-side reactions to events
2656
- */
2657
- on(eventType, callback) {
2658
- if (!this.listeners.has(eventType)) {
2659
- this.listeners.set(eventType, new Set());
2660
- }
2661
- this.listeners.get(eventType).add(callback);
2662
- logger.debug(`Event listener registered: ${eventType}`);
2663
- }
2664
- /**
2665
- * Remove an event listener
2666
- */
2667
- off(eventType, callback) {
2668
- const listeners = this.listeners.get(eventType);
2669
- if (listeners) {
2670
- listeners.delete(callback);
2671
- }
2672
- }
2673
- /**
2674
- * Emit an event (client-side only)
2675
- * This will trigger any registered local listeners
2676
- */
2677
- emit(eventType, data) {
2678
- logger.debug(`Event emitted: ${eventType}`, data);
2679
- const listeners = this.listeners.get(eventType);
2680
- if (listeners) {
2681
- listeners.forEach(callback => {
2682
- try {
2683
- callback(data);
2684
- }
2685
- catch (error) {
2686
- logger.error(`Error in event listener for ${eventType}:`, error);
2687
- }
2688
- });
2689
- }
2690
- }
2691
- /**
2692
- * Check if conditions are met for a trigger
2693
- * Supports dynamic field evaluation including custom fields and nested paths
2694
- */
2695
- evaluateConditions(conditions, data) {
2696
- if (!conditions || conditions.length === 0) {
2697
- return true; // No conditions means always fire
2698
- }
2699
- return conditions.every(condition => {
2700
- // Support dot notation for nested fields (e.g., 'customFields.industry')
2701
- const fieldValue = condition.field.includes('.')
2702
- ? this.getNestedValue(data, condition.field)
2703
- : data[condition.field];
2704
- const targetValue = condition.value;
2705
- switch (condition.operator) {
2706
- case 'equals':
2707
- return fieldValue === targetValue;
2708
- case 'not_equals':
2709
- return fieldValue !== targetValue;
2710
- case 'contains':
2711
- return String(fieldValue).includes(String(targetValue));
2712
- case 'greater_than':
2713
- return Number(fieldValue) > Number(targetValue);
2714
- case 'less_than':
2715
- return Number(fieldValue) < Number(targetValue);
2716
- case 'in':
2717
- return Array.isArray(targetValue) && targetValue.includes(fieldValue);
2718
- case 'not_in':
2719
- return Array.isArray(targetValue) && !targetValue.includes(fieldValue);
2720
- default:
2721
- return false;
2722
- }
2723
- });
2724
- }
2725
- /**
2726
- * Execute actions for a triggered event (client-side preview)
2727
- * Note: Actual execution happens on the backend
2728
- */
2729
- async executeActions(trigger, data) {
2730
- logger.info(`Executing actions for trigger: ${trigger.name}`);
2731
- for (const action of trigger.actions) {
2732
- try {
2733
- await this.executeAction(action, data);
2734
- }
2735
- catch (error) {
2736
- logger.error(`Failed to execute action:`, error);
2737
- }
2738
- }
2739
- }
2740
- /**
2741
- * Execute a single action
2742
- */
2743
- async executeAction(action, data) {
2744
- switch (action.type) {
2745
- case 'send_email':
2746
- await this.executeSendEmail(action, data);
2747
- break;
2748
- case 'webhook':
2749
- await this.executeWebhook(action, data);
2750
- break;
2751
- case 'create_task':
2752
- await this.executeCreateTask(action, data);
2753
- break;
2754
- case 'update_contact':
2755
- await this.executeUpdateContact(action, data);
2756
- break;
2757
- default:
2758
- logger.warn(`Unknown action type:`, action);
2759
- }
2760
- }
2761
- /**
2762
- * Execute send email action (via backend API)
2763
- */
2764
- async executeSendEmail(action, data) {
2765
- logger.debug('Sending email:', action);
2766
- const payload = {
2767
- to: this.replaceVariables(action.to, data),
2768
- subject: action.subject ? this.replaceVariables(action.subject, data) : undefined,
2769
- body: action.body ? this.replaceVariables(action.body, data) : undefined,
2770
- templateId: action.templateId,
2771
- cc: action.cc,
2772
- bcc: action.bcc,
2773
- from: action.from,
2774
- delayMinutes: action.delayMinutes,
2775
- };
2776
- await this.request(`/api/workspaces/${this.workspaceId}/emails/send`, {
2777
- method: 'POST',
2778
- body: JSON.stringify(payload),
2779
- });
2780
- }
2781
- /**
2782
- * Execute webhook action
2783
- */
2784
- async executeWebhook(action, data) {
2785
- logger.debug('Calling webhook:', action.url);
2786
- const body = action.body ? this.replaceVariables(action.body, data) : JSON.stringify(data);
2787
- await fetch(action.url, {
2788
- method: action.method,
2789
- headers: {
2790
- 'Content-Type': 'application/json',
2791
- ...action.headers,
2792
- },
2793
- body,
2794
- });
2795
- }
2796
- /**
2797
- * Execute create task action
2798
- */
2799
- async executeCreateTask(action, data) {
2800
- logger.debug('Creating task:', action.title);
2801
- const dueDate = action.dueDays
2802
- ? new Date(Date.now() + action.dueDays * 24 * 60 * 60 * 1000).toISOString()
2803
- : undefined;
2804
- await this.request(`/api/workspaces/${this.workspaceId}/tasks`, {
2805
- method: 'POST',
2806
- body: JSON.stringify({
2807
- title: this.replaceVariables(action.title, data),
2808
- description: action.description ? this.replaceVariables(action.description, data) : undefined,
2809
- priority: action.priority,
2810
- dueDate,
2811
- assignedTo: action.assignedTo,
2812
- relatedContactId: typeof data.contactId === 'string' ? data.contactId : undefined,
2813
- }),
2814
- });
2815
- }
2816
- /**
2817
- * Execute update contact action
2818
- */
2819
- async executeUpdateContact(action, data) {
2820
- const contactId = data.contactId || data._id;
2821
- if (!contactId) {
2822
- logger.warn('Cannot update contact: no contactId in data');
2823
- return;
2824
- }
2825
- logger.debug('Updating contact:', contactId);
2826
- await this.request(`/api/workspaces/${this.workspaceId}/contacts/${contactId}`, {
2827
- method: 'PUT',
2828
- body: JSON.stringify(action.updates),
2829
- });
2830
- }
2831
- /**
2832
- * Replace variables in a string template
2833
- * Supports syntax like {{contact.email}}, {{opportunity.value}}
2834
- */
2835
- replaceVariables(template, data) {
2836
- return template.replace(/\{\{([^}]+)\}\}/g, (match, path) => {
2837
- const value = this.getNestedValue(data, path.trim());
2838
- return value !== undefined ? String(value) : match;
2839
- });
2840
- }
2841
- /**
2842
- * Get nested value from object using dot notation
2843
- * Supports dynamic field access including custom fields
2844
- */
2845
- getNestedValue(obj, path) {
2846
- return path.split('.').reduce((current, key) => {
2847
- return current !== null && current !== undefined && typeof current === 'object'
2848
- ? current[key]
2849
- : undefined;
2850
- }, obj);
2851
- }
2852
- /**
2853
- * Extract all available field paths from a data object
2854
- * Useful for dynamic field discovery based on platform-specific attributes
2855
- * @param obj - The data object to extract fields from
2856
- * @param prefix - Internal use for nested paths
2857
- * @param maxDepth - Maximum depth to traverse (default: 3)
2858
- * @returns Array of field paths (e.g., ['email', 'contact.firstName', 'customFields.industry'])
2859
- */
2860
- extractAvailableFields(obj, prefix = '', maxDepth = 3) {
2861
- if (maxDepth <= 0)
2862
- return [];
2863
- const fields = [];
2864
- for (const key in obj) {
2865
- if (!obj.hasOwnProperty(key))
2866
- continue;
2867
- const value = obj[key];
2868
- const fieldPath = prefix ? `${prefix}.${key}` : key;
2869
- fields.push(fieldPath);
2870
- // Recursively traverse nested objects
2871
- if (value !== null && typeof value === 'object' && !Array.isArray(value)) {
2872
- const nestedFields = this.extractAvailableFields(value, fieldPath, maxDepth - 1);
2873
- fields.push(...nestedFields);
2874
- }
2875
- }
2876
- return fields;
2877
- }
2878
- /**
2879
- * Get available fields from sample data
2880
- * Helps with dynamic field detection for platform-specific attributes
2881
- * @param sampleData - Sample data object to analyze
2882
- * @returns Array of available field paths
2883
- */
2884
- getAvailableFields(sampleData) {
2885
- return this.extractAvailableFields(sampleData);
2886
- }
2887
- // ============================================
2888
- // HELPER METHODS FOR COMMON PATTERNS
2889
- // ============================================
2890
- /**
2891
- * Create a simple email trigger
2892
- * Helper method for common use case
2893
- */
2894
- async createEmailTrigger(config) {
2895
- return this.createTrigger({
2896
- name: config.name,
2897
- eventType: config.eventType,
2898
- conditions: config.conditions,
2899
- actions: [
2900
- {
2901
- type: 'send_email',
2902
- to: config.to,
2903
- subject: config.subject,
2904
- body: config.body,
2905
- },
2906
- ],
2907
- isActive: true,
2908
- });
2909
- }
2910
- /**
2911
- * Create a task creation trigger
2912
- */
2913
- async createTaskTrigger(config) {
2914
- return this.createTrigger({
2915
- name: config.name,
2916
- eventType: config.eventType,
2917
- conditions: config.conditions,
2918
- actions: [
2919
- {
2920
- type: 'create_task',
2921
- title: config.taskTitle,
2922
- description: config.taskDescription,
2923
- priority: config.priority,
2924
- dueDays: config.dueDays,
2925
- },
2926
- ],
2927
- isActive: true,
2928
- });
2929
- }
2930
- /**
2931
- * Create a webhook trigger
2932
- */
2933
- async createWebhookTrigger(config) {
2934
- return this.createTrigger({
2935
- name: config.name,
2936
- eventType: config.eventType,
2937
- conditions: config.conditions,
2938
- actions: [
2939
- {
2940
- type: 'webhook',
2941
- url: config.webhookUrl,
2942
- method: config.method || 'POST',
2943
- },
2944
- ],
2945
- isActive: true,
2946
- });
2947
- }
2948
- }
2949
-
2950
- /**
2951
- * Clianta SDK - CRM API Client
2952
- * @see SDK_VERSION in core/config.ts
2953
- */
2954
- /**
2955
- * CRM API Client for managing contacts and opportunities
2956
- */
2957
- class CRMClient {
2958
- constructor(apiEndpoint, workspaceId, authToken, apiKey) {
2959
- this.apiEndpoint = apiEndpoint;
2960
- this.workspaceId = workspaceId;
2961
- this.authToken = authToken;
2962
- this.apiKey = apiKey;
2963
- this.triggers = new EventTriggersManager(apiEndpoint, workspaceId, authToken);
2964
- }
2965
- /**
2966
- * Set authentication token for API requests (user JWT)
2967
- */
2968
- setAuthToken(token) {
2969
- this.authToken = token;
2970
- this.apiKey = undefined;
2971
- this.triggers.setAuthToken(token);
2972
- }
2973
- /**
2974
- * Set workspace API key for server-to-server requests.
2975
- * Use this instead of setAuthToken when integrating from an external app.
2976
- */
2977
- setApiKey(key) {
2978
- this.apiKey = key;
2979
- this.authToken = undefined;
2980
- }
2981
- /**
2982
- * Validate required parameter exists
2983
- * @throws {Error} if value is null/undefined or empty string
2984
- */
2985
- validateRequired(param, value, methodName) {
2986
- if (value === null || value === undefined || value === '') {
2987
- throw new Error(`[CRMClient.${methodName}] ${param} is required`);
2988
- }
2989
- }
2990
- /**
2991
- * Make authenticated API request
2992
- */
2993
- async request(endpoint, options = {}) {
2994
- const url = `${this.apiEndpoint}${endpoint}`;
2995
- const headers = {
2996
- 'Content-Type': 'application/json',
2997
- ...(options.headers || {}),
2998
- };
2999
- if (this.apiKey) {
3000
- headers['X-Api-Key'] = this.apiKey;
3001
- }
3002
- else if (this.authToken) {
3003
- headers['Authorization'] = `Bearer ${this.authToken}`;
3004
- }
3005
- try {
3006
- const response = await fetch(url, {
3007
- ...options,
3008
- headers,
3009
- });
3010
- const data = await response.json();
3011
- if (!response.ok) {
3012
- return {
3013
- success: false,
3014
- error: data.message || 'Request failed',
3015
- status: response.status,
3016
- };
3017
- }
3018
- return {
3019
- success: true,
3020
- data: data.data || data,
3021
- status: response.status,
3022
- };
3023
- }
3024
- catch (error) {
3025
- return {
3026
- success: false,
3027
- error: error instanceof Error ? error.message : 'Network error',
3028
- status: 0,
3029
- };
3030
- }
3031
- }
3032
- // ============================================
3033
- // INBOUND EVENTS API (API-key authenticated)
3034
- // ============================================
3035
- /**
3036
- * Send an inbound event from an external app (e.g. user signup on client website).
3037
- * Requires the client to be initialized with an API key via setApiKey() or the constructor.
3038
- *
3039
- * The contact is upserted in the CRM and matching workflow automations fire automatically.
3040
- *
3041
- * @example
3042
- * const crm = new CRMClient('http://localhost:5000', 'WORKSPACE_ID');
3043
- * crm.setApiKey('mm_live_...');
3044
- *
3045
- * await crm.sendEvent({
3046
- * event: 'user.registered',
3047
- * contact: { email: 'alice@example.com', firstName: 'Alice' },
3048
- * data: { plan: 'free', signupSource: 'homepage' },
3049
- * });
3050
- */
3051
- async sendEvent(payload) {
3052
- const url = `${this.apiEndpoint}/api/public/events`;
3053
- const headers = { 'Content-Type': 'application/json' };
3054
- if (this.apiKey) {
3055
- headers['X-Api-Key'] = this.apiKey;
3056
- }
3057
- else if (this.authToken) {
3058
- headers['Authorization'] = `Bearer ${this.authToken}`;
3059
- }
3060
- try {
3061
- const response = await fetch(url, {
3062
- method: 'POST',
3063
- headers,
3064
- body: JSON.stringify(payload),
3065
- });
3066
- const data = await response.json();
3067
- if (!response.ok) {
3068
- return {
3069
- success: false,
3070
- contactCreated: false,
3071
- event: payload.event,
3072
- error: data.error || 'Request failed',
3073
- };
3074
- }
3075
- return {
3076
- success: data.success,
3077
- contactCreated: data.contactCreated,
3078
- contactId: data.contactId,
3079
- event: data.event,
3080
- };
3081
- }
3082
- catch (error) {
3083
- return {
3084
- success: false,
3085
- contactCreated: false,
3086
- event: payload.event,
3087
- error: error instanceof Error ? error.message : 'Network error',
3088
- };
3089
- }
3090
- }
3091
- // ============================================
3092
- // CONTACTS API
3093
- // ============================================
3094
- /**
3095
- * Get all contacts with pagination
3096
- */
3097
- async getContacts(params) {
3098
- const queryParams = new URLSearchParams();
3099
- if (params?.page)
3100
- queryParams.set('page', params.page.toString());
3101
- if (params?.limit)
3102
- queryParams.set('limit', params.limit.toString());
3103
- if (params?.search)
3104
- queryParams.set('search', params.search);
3105
- if (params?.status)
3106
- queryParams.set('status', params.status);
3107
- const query = queryParams.toString();
3108
- const endpoint = `/api/workspaces/${this.workspaceId}/contacts${query ? `?${query}` : ''}`;
3109
- return this.request(endpoint);
3110
- }
3111
- /**
3112
- * Get a single contact by ID
3113
- */
3114
- async getContact(contactId) {
3115
- this.validateRequired('contactId', contactId, 'getContact');
3116
- return this.request(`/api/workspaces/${this.workspaceId}/contacts/${contactId}`);
3117
- }
3118
- /**
3119
- * Create a new contact
3120
- */
3121
- async createContact(contact) {
3122
- return this.request(`/api/workspaces/${this.workspaceId}/contacts`, {
3123
- method: 'POST',
3124
- body: JSON.stringify(contact),
3125
- });
3126
- }
3127
- /**
3128
- * Update an existing contact
3129
- */
3130
- async updateContact(contactId, updates) {
3131
- this.validateRequired('contactId', contactId, 'updateContact');
3132
- return this.request(`/api/workspaces/${this.workspaceId}/contacts/${contactId}`, {
3133
- method: 'PUT',
3134
- body: JSON.stringify(updates),
3135
- });
3136
- }
3137
- /**
3138
- * Delete a contact
3139
- */
3140
- async deleteContact(contactId) {
3141
- this.validateRequired('contactId', contactId, 'deleteContact');
3142
- return this.request(`/api/workspaces/${this.workspaceId}/contacts/${contactId}`, {
3143
- method: 'DELETE',
3144
- });
3145
- }
3146
- // ============================================
3147
- // OPPORTUNITIES API
3148
- // ============================================
3149
- /**
3150
- * Get all opportunities with pagination
3151
- */
3152
- async getOpportunities(params) {
3153
- const queryParams = new URLSearchParams();
3154
- if (params?.page)
3155
- queryParams.set('page', params.page.toString());
3156
- if (params?.limit)
3157
- queryParams.set('limit', params.limit.toString());
3158
- if (params?.pipelineId)
3159
- queryParams.set('pipelineId', params.pipelineId);
3160
- if (params?.stageId)
3161
- queryParams.set('stageId', params.stageId);
3162
- const query = queryParams.toString();
3163
- const endpoint = `/api/workspaces/${this.workspaceId}/opportunities${query ? `?${query}` : ''}`;
3164
- return this.request(endpoint);
3165
- }
3166
- /**
3167
- * Get a single opportunity by ID
3168
- */
3169
- async getOpportunity(opportunityId) {
3170
- return this.request(`/api/workspaces/${this.workspaceId}/opportunities/${opportunityId}`);
3171
- }
3172
- /**
3173
- * Create a new opportunity
3174
- */
3175
- async createOpportunity(opportunity) {
3176
- return this.request(`/api/workspaces/${this.workspaceId}/opportunities`, {
3177
- method: 'POST',
3178
- body: JSON.stringify(opportunity),
3179
- });
3180
- }
3181
- /**
3182
- * Update an existing opportunity
3183
- */
3184
- async updateOpportunity(opportunityId, updates) {
3185
- return this.request(`/api/workspaces/${this.workspaceId}/opportunities/${opportunityId}`, {
3186
- method: 'PUT',
3187
- body: JSON.stringify(updates),
3188
- });
3189
- }
3190
- /**
3191
- * Delete an opportunity
3192
- */
3193
- async deleteOpportunity(opportunityId) {
3194
- return this.request(`/api/workspaces/${this.workspaceId}/opportunities/${opportunityId}`, {
3195
- method: 'DELETE',
3196
- });
3197
- }
3198
- /**
3199
- * Move opportunity to a different stage
3200
- */
3201
- async moveOpportunity(opportunityId, stageId) {
3202
- return this.request(`/api/workspaces/${this.workspaceId}/opportunities/${opportunityId}/move`, {
3203
- method: 'POST',
3204
- body: JSON.stringify({ stageId }),
3205
- });
3206
- }
3207
- // ============================================
3208
- // COMPANIES API
3209
- // ============================================
3210
- /**
3211
- * Get all companies with pagination
3212
- */
3213
- async getCompanies(params) {
3214
- const queryParams = new URLSearchParams();
3215
- if (params?.page)
3216
- queryParams.set('page', params.page.toString());
3217
- if (params?.limit)
3218
- queryParams.set('limit', params.limit.toString());
3219
- if (params?.search)
3220
- queryParams.set('search', params.search);
3221
- if (params?.status)
3222
- queryParams.set('status', params.status);
3223
- if (params?.industry)
3224
- queryParams.set('industry', params.industry);
3225
- const query = queryParams.toString();
3226
- const endpoint = `/api/workspaces/${this.workspaceId}/companies${query ? `?${query}` : ''}`;
3227
- return this.request(endpoint);
3228
- }
3229
- /**
3230
- * Get a single company by ID
3231
- */
3232
- async getCompany(companyId) {
3233
- return this.request(`/api/workspaces/${this.workspaceId}/companies/${companyId}`);
3234
- }
3235
- /**
3236
- * Create a new company
3237
- */
3238
- async createCompany(company) {
3239
- return this.request(`/api/workspaces/${this.workspaceId}/companies`, {
3240
- method: 'POST',
3241
- body: JSON.stringify(company),
3242
- });
3243
- }
3244
- /**
3245
- * Update an existing company
3246
- */
3247
- async updateCompany(companyId, updates) {
3248
- return this.request(`/api/workspaces/${this.workspaceId}/companies/${companyId}`, {
3249
- method: 'PUT',
3250
- body: JSON.stringify(updates),
3251
- });
3252
- }
3253
- /**
3254
- * Delete a company
3255
- */
3256
- async deleteCompany(companyId) {
3257
- return this.request(`/api/workspaces/${this.workspaceId}/companies/${companyId}`, {
3258
- method: 'DELETE',
3259
- });
3260
- }
3261
- /**
3262
- * Get contacts belonging to a company
3263
- */
3264
- async getCompanyContacts(companyId, params) {
3265
- const queryParams = new URLSearchParams();
3266
- if (params?.page)
3267
- queryParams.set('page', params.page.toString());
3268
- if (params?.limit)
3269
- queryParams.set('limit', params.limit.toString());
3270
- const query = queryParams.toString();
3271
- const endpoint = `/api/workspaces/${this.workspaceId}/companies/${companyId}/contacts${query ? `?${query}` : ''}`;
3272
- return this.request(endpoint);
3273
- }
3274
- /**
3275
- * Get deals/opportunities belonging to a company
3276
- */
3277
- async getCompanyDeals(companyId, params) {
3278
- const queryParams = new URLSearchParams();
3279
- if (params?.page)
3280
- queryParams.set('page', params.page.toString());
3281
- if (params?.limit)
3282
- queryParams.set('limit', params.limit.toString());
3283
- const query = queryParams.toString();
3284
- const endpoint = `/api/workspaces/${this.workspaceId}/companies/${companyId}/deals${query ? `?${query}` : ''}`;
3285
- return this.request(endpoint);
3286
- }
3287
- // ============================================
3288
- // PIPELINES API
3289
- // ============================================
3290
- /**
3291
- * Get all pipelines
3292
- */
3293
- async getPipelines() {
3294
- return this.request(`/api/workspaces/${this.workspaceId}/pipelines`);
3295
- }
3296
- /**
3297
- * Get a single pipeline by ID
3298
- */
3299
- async getPipeline(pipelineId) {
3300
- return this.request(`/api/workspaces/${this.workspaceId}/pipelines/${pipelineId}`);
3301
- }
3302
- /**
3303
- * Create a new pipeline
3304
- */
3305
- async createPipeline(pipeline) {
3306
- return this.request(`/api/workspaces/${this.workspaceId}/pipelines`, {
3307
- method: 'POST',
3308
- body: JSON.stringify(pipeline),
3309
- });
3310
- }
3311
- /**
3312
- * Update an existing pipeline
3313
- */
3314
- async updatePipeline(pipelineId, updates) {
3315
- return this.request(`/api/workspaces/${this.workspaceId}/pipelines/${pipelineId}`, {
3316
- method: 'PUT',
3317
- body: JSON.stringify(updates),
3318
- });
3319
- }
3320
- /**
3321
- * Delete a pipeline
3322
- */
3323
- async deletePipeline(pipelineId) {
3324
- return this.request(`/api/workspaces/${this.workspaceId}/pipelines/${pipelineId}`, {
3325
- method: 'DELETE',
3326
- });
3327
- }
3328
- // ============================================
3329
- // TASKS API
3330
- // ============================================
3331
- /**
3332
- * Get all tasks with pagination
3333
- */
3334
- async getTasks(params) {
3335
- const queryParams = new URLSearchParams();
3336
- if (params?.page)
3337
- queryParams.set('page', params.page.toString());
3338
- if (params?.limit)
3339
- queryParams.set('limit', params.limit.toString());
3340
- if (params?.status)
3341
- queryParams.set('status', params.status);
3342
- if (params?.priority)
3343
- queryParams.set('priority', params.priority);
3344
- if (params?.contactId)
3345
- queryParams.set('contactId', params.contactId);
3346
- if (params?.companyId)
3347
- queryParams.set('companyId', params.companyId);
3348
- if (params?.opportunityId)
3349
- queryParams.set('opportunityId', params.opportunityId);
3350
- const query = queryParams.toString();
3351
- const endpoint = `/api/workspaces/${this.workspaceId}/tasks${query ? `?${query}` : ''}`;
3352
- return this.request(endpoint);
3353
- }
3354
- /**
3355
- * Get a single task by ID
3356
- */
3357
- async getTask(taskId) {
3358
- return this.request(`/api/workspaces/${this.workspaceId}/tasks/${taskId}`);
3359
- }
3360
- /**
3361
- * Create a new task
3362
- */
3363
- async createTask(task) {
3364
- return this.request(`/api/workspaces/${this.workspaceId}/tasks`, {
3365
- method: 'POST',
3366
- body: JSON.stringify(task),
3367
- });
3368
- }
3369
- /**
3370
- * Update an existing task
3371
- */
3372
- async updateTask(taskId, updates) {
3373
- return this.request(`/api/workspaces/${this.workspaceId}/tasks/${taskId}`, {
3374
- method: 'PUT',
3375
- body: JSON.stringify(updates),
3376
- });
3377
- }
3378
- /**
3379
- * Mark a task as completed
3380
- */
3381
- async completeTask(taskId) {
3382
- return this.request(`/api/workspaces/${this.workspaceId}/tasks/${taskId}/complete`, {
3383
- method: 'PATCH',
3384
- });
3385
- }
3386
- /**
3387
- * Delete a task
3388
- */
3389
- async deleteTask(taskId) {
3390
- return this.request(`/api/workspaces/${this.workspaceId}/tasks/${taskId}`, {
3391
- method: 'DELETE',
3392
- });
3393
- }
3394
- // ============================================
3395
- // ACTIVITIES API
3396
- // ============================================
3397
- /**
3398
- * Get activities for a contact
3399
- */
3400
- async getContactActivities(contactId, params) {
3401
- const queryParams = new URLSearchParams();
3402
- if (params?.page)
3403
- queryParams.set('page', params.page.toString());
3404
- if (params?.limit)
3405
- queryParams.set('limit', params.limit.toString());
3406
- if (params?.type)
3407
- queryParams.set('type', params.type);
3408
- const query = queryParams.toString();
3409
- const endpoint = `/api/workspaces/${this.workspaceId}/contacts/${contactId}/activities${query ? `?${query}` : ''}`;
3410
- return this.request(endpoint);
3411
- }
3412
- /**
3413
- * Get activities for an opportunity/deal
3414
- */
3415
- async getOpportunityActivities(opportunityId, params) {
3416
- const queryParams = new URLSearchParams();
3417
- if (params?.page)
3418
- queryParams.set('page', params.page.toString());
3419
- if (params?.limit)
3420
- queryParams.set('limit', params.limit.toString());
3421
- if (params?.type)
3422
- queryParams.set('type', params.type);
3423
- const query = queryParams.toString();
3424
- const endpoint = `/api/workspaces/${this.workspaceId}/opportunities/${opportunityId}/activities${query ? `?${query}` : ''}`;
3425
- return this.request(endpoint);
3426
- }
3427
- /**
3428
- * Create a new activity
3429
- */
3430
- async createActivity(activity) {
3431
- // Determine the correct endpoint based on related entity
3432
- let endpoint;
3433
- if (activity.opportunityId) {
3434
- endpoint = `/api/workspaces/${this.workspaceId}/opportunities/${activity.opportunityId}/activities`;
3435
- }
3436
- else if (activity.contactId) {
3437
- endpoint = `/api/workspaces/${this.workspaceId}/contacts/${activity.contactId}/activities`;
3438
- }
3439
- else {
3440
- endpoint = `/api/workspaces/${this.workspaceId}/activities`;
3441
- }
3442
- return this.request(endpoint, {
3443
- method: 'POST',
3444
- body: JSON.stringify(activity),
3445
- });
3446
- }
3447
- /**
3448
- * Update an existing activity
3449
- */
3450
- async updateActivity(activityId, updates) {
3451
- return this.request(`/api/workspaces/${this.workspaceId}/activities/${activityId}`, {
3452
- method: 'PATCH',
3453
- body: JSON.stringify(updates),
3454
- });
3455
- }
3456
- /**
3457
- * Delete an activity
3458
- */
3459
- async deleteActivity(activityId) {
3460
- return this.request(`/api/workspaces/${this.workspaceId}/activities/${activityId}`, {
3461
- method: 'DELETE',
3462
- });
3463
- }
3464
- /**
3465
- * Log a call activity
3466
- */
3467
- async logCall(data) {
3468
- return this.createActivity({
3469
- type: 'call',
3470
- title: `${data.direction === 'inbound' ? 'Inbound' : 'Outbound'} Call`,
3471
- direction: data.direction,
3472
- duration: data.duration,
3473
- outcome: data.outcome,
3474
- description: data.notes,
3475
- contactId: data.contactId,
3476
- opportunityId: data.opportunityId,
3477
- });
3478
- }
3479
- /**
3480
- * Log a meeting activity
3481
- */
3482
- async logMeeting(data) {
3483
- return this.createActivity({
3484
- type: 'meeting',
3485
- title: data.title,
3486
- duration: data.duration,
3487
- outcome: data.outcome,
3488
- description: data.notes,
3489
- contactId: data.contactId,
3490
- opportunityId: data.opportunityId,
3491
- });
3492
- }
3493
- /**
3494
- * Add a note to a contact or opportunity
3495
- */
3496
- async addNote(data) {
3497
- return this.createActivity({
3498
- type: 'note',
3499
- title: 'Note',
3500
- description: data.content,
3501
- contactId: data.contactId,
3502
- opportunityId: data.opportunityId,
3503
- });
3504
- }
3505
- // ============================================
3506
- // EMAIL TEMPLATES API
3507
- // ============================================
3508
- /**
3509
- * Get all email templates
3510
- */
3511
- async getEmailTemplates(params) {
3512
- const queryParams = new URLSearchParams();
3513
- if (params?.page)
3514
- queryParams.set('page', params.page.toString());
3515
- if (params?.limit)
3516
- queryParams.set('limit', params.limit.toString());
3517
- const query = queryParams.toString();
3518
- const endpoint = `/api/workspaces/${this.workspaceId}/email-templates${query ? `?${query}` : ''}`;
3519
- return this.request(endpoint);
3520
- }
3521
- /**
3522
- * Get a single email template by ID
3523
- */
3524
- async getEmailTemplate(templateId) {
3525
- return this.request(`/api/workspaces/${this.workspaceId}/email-templates/${templateId}`);
3526
- }
3527
- /**
3528
- * Create a new email template
3529
- */
3530
- async createEmailTemplate(template) {
3531
- return this.request(`/api/workspaces/${this.workspaceId}/email-templates`, {
3532
- method: 'POST',
3533
- body: JSON.stringify(template),
3534
- });
3535
- }
3536
- /**
3537
- * Update an email template
3538
- */
3539
- async updateEmailTemplate(templateId, updates) {
3540
- return this.request(`/api/workspaces/${this.workspaceId}/email-templates/${templateId}`, {
3541
- method: 'PUT',
3542
- body: JSON.stringify(updates),
3543
- });
3544
- }
3545
- /**
3546
- * Delete an email template
3547
- */
3548
- async deleteEmailTemplate(templateId) {
3549
- return this.request(`/api/workspaces/${this.workspaceId}/email-templates/${templateId}`, {
3550
- method: 'DELETE',
3551
- });
3552
- }
3553
- /**
3554
- * Send an email using a template
3555
- */
3556
- async sendEmail(data) {
3557
- return this.request(`/api/workspaces/${this.workspaceId}/emails/send`, {
3558
- method: 'POST',
3559
- body: JSON.stringify(data),
3560
- });
3561
- }
3562
- // ============================================
3563
- // READ-BACK / DATA RETRIEVAL API
3564
- // ============================================
3565
- /**
3566
- * Get a contact by email address.
3567
- * Returns the first matching contact from a search query.
3568
- */
3569
- async getContactByEmail(email) {
3570
- this.validateRequired('email', email, 'getContactByEmail');
3571
- const queryParams = new URLSearchParams({ search: email, limit: '1' });
3572
- return this.request(`/api/workspaces/${this.workspaceId}/contacts?${queryParams.toString()}`);
3573
- }
3574
- /**
3575
- * Get activity timeline for a contact
3576
- */
3577
- async getContactActivity(contactId, params) {
3578
- this.validateRequired('contactId', contactId, 'getContactActivity');
3579
- const queryParams = new URLSearchParams();
3580
- if (params?.page)
3581
- queryParams.set('page', params.page.toString());
3582
- if (params?.limit)
3583
- queryParams.set('limit', params.limit.toString());
3584
- if (params?.type)
3585
- queryParams.set('type', params.type);
3586
- if (params?.startDate)
3587
- queryParams.set('startDate', params.startDate);
3588
- if (params?.endDate)
3589
- queryParams.set('endDate', params.endDate);
3590
- const query = queryParams.toString();
3591
- const endpoint = `/api/workspaces/${this.workspaceId}/contacts/${contactId}/activities${query ? `?${query}` : ''}`;
3592
- return this.request(endpoint);
3593
- }
3594
- /**
3595
- * Get engagement metrics for a contact (via their linked visitor data)
3596
- */
3597
- async getContactEngagement(contactId) {
3598
- this.validateRequired('contactId', contactId, 'getContactEngagement');
3599
- return this.request(`/api/workspaces/${this.workspaceId}/contacts/${contactId}/engagement`);
3600
- }
3601
- /**
3602
- * Get a full timeline for a contact including events, activities, and opportunities
3603
- */
3604
- async getContactTimeline(contactId, params) {
3605
- this.validateRequired('contactId', contactId, 'getContactTimeline');
3606
- const queryParams = new URLSearchParams();
3607
- if (params?.page)
3608
- queryParams.set('page', params.page.toString());
3609
- if (params?.limit)
3610
- queryParams.set('limit', params.limit.toString());
3611
- const query = queryParams.toString();
3612
- const endpoint = `/api/workspaces/${this.workspaceId}/contacts/${contactId}/timeline${query ? `?${query}` : ''}`;
3613
- return this.request(endpoint);
3614
- }
3615
- /**
3616
- * Search contacts with advanced filters
3617
- */
3618
- async searchContacts(query, filters) {
3619
- const queryParams = new URLSearchParams();
3620
- queryParams.set('search', query);
3621
- if (filters?.status)
3622
- queryParams.set('status', filters.status);
3623
- if (filters?.lifecycleStage)
3624
- queryParams.set('lifecycleStage', filters.lifecycleStage);
3625
- if (filters?.source)
3626
- queryParams.set('source', filters.source);
3627
- if (filters?.tags)
3628
- queryParams.set('tags', filters.tags.join(','));
3629
- if (filters?.page)
3630
- queryParams.set('page', filters.page.toString());
3631
- if (filters?.limit)
3632
- queryParams.set('limit', filters.limit.toString());
3633
- const qs = queryParams.toString();
3634
- const endpoint = `/api/workspaces/${this.workspaceId}/contacts${qs ? `?${qs}` : ''}`;
3635
- return this.request(endpoint);
3636
- }
3637
- // ============================================
3638
- // WEBHOOK MANAGEMENT API
3639
- // ============================================
3640
- /**
3641
- * List all webhook subscriptions
3642
- */
3643
- async listWebhooks(params) {
3644
- const queryParams = new URLSearchParams();
3645
- if (params?.page)
3646
- queryParams.set('page', params.page.toString());
3647
- if (params?.limit)
3648
- queryParams.set('limit', params.limit.toString());
3649
- const query = queryParams.toString();
3650
- return this.request(`/api/workspaces/${this.workspaceId}/webhooks${query ? `?${query}` : ''}`);
3651
- }
3652
- /**
3653
- * Create a new webhook subscription
3654
- */
3655
- async createWebhook(data) {
3656
- return this.request(`/api/workspaces/${this.workspaceId}/webhooks`, {
3657
- method: 'POST',
3658
- body: JSON.stringify(data),
3659
- });
3660
- }
3661
- /**
3662
- * Delete a webhook subscription
3663
- */
3664
- async deleteWebhook(webhookId) {
3665
- this.validateRequired('webhookId', webhookId, 'deleteWebhook');
3666
- return this.request(`/api/workspaces/${this.workspaceId}/webhooks/${webhookId}`, {
3667
- method: 'DELETE',
3668
- });
3669
- }
3670
- // ============================================
3671
- // EVENT TRIGGERS API (delegated to triggers manager)
3672
- // ============================================
3673
- /**
3674
- * Get all event triggers
3675
- */
3676
- async getEventTriggers() {
3677
- return this.triggers.getTriggers();
3678
- }
3679
- /**
3680
- * Create a new event trigger
3681
- */
3682
- async createEventTrigger(trigger) {
3683
- return this.triggers.createTrigger(trigger);
3684
- }
3685
- /**
3686
- * Update an event trigger
3687
- */
3688
- async updateEventTrigger(triggerId, updates) {
3689
- return this.triggers.updateTrigger(triggerId, updates);
3690
- }
3691
- /**
3692
- * Delete an event trigger
3693
- */
3694
- async deleteEventTrigger(triggerId) {
3695
- return this.triggers.deleteTrigger(triggerId);
3696
- }
3697
- }
3698
-
3699
- /**
3700
- * Privacy-safe visitor API client.
3701
- * All methods return data for the current visitor only (no cross-visitor access).
3702
- */
3703
- class VisitorClient {
3704
- constructor(transport, workspaceId, visitorId) {
3705
- this.transport = transport;
3706
- this.workspaceId = workspaceId;
3707
- this.visitorId = visitorId;
3708
- }
3709
- /** Update visitorId (e.g. after reset) */
3710
- setVisitorId(id) {
3711
- this.visitorId = id;
3712
- }
3713
- basePath() {
3714
- return `/api/public/track/visitor/${this.workspaceId}/${this.visitorId}`;
3715
- }
3716
- /**
3717
- * Get the current visitor's profile from the CRM.
3718
- * Returns visitor data and linked contact info if identified.
3719
- */
3720
- async getProfile() {
3721
- const result = await this.transport.fetchData(`${this.basePath()}/profile`);
3722
- if (result.success && result.data) {
3723
- logger.debug('Visitor profile fetched:', result.data);
3724
- return result.data;
3725
- }
3726
- logger.warn('Failed to fetch visitor profile:', result.error);
3727
- return null;
3728
- }
3729
- /**
3730
- * Get the current visitor's recent activity/events.
3731
- * Returns paginated list of tracking events.
3732
- */
3733
- async getActivity(options) {
3734
- const params = {};
3735
- if (options?.page)
3736
- params.page = options.page.toString();
3737
- if (options?.limit)
3738
- params.limit = options.limit.toString();
3739
- if (options?.eventType)
3740
- params.eventType = options.eventType;
3741
- if (options?.startDate)
3742
- params.startDate = options.startDate;
3743
- if (options?.endDate)
3744
- params.endDate = options.endDate;
3745
- const result = await this.transport.fetchData(`${this.basePath()}/activity`, params);
3746
- if (result.success && result.data) {
3747
- return result.data;
3748
- }
3749
- logger.warn('Failed to fetch visitor activity:', result.error);
3750
- return null;
3751
- }
3752
- /**
3753
- * Get a summarized journey timeline for the current visitor.
3754
- * Includes top pages, sessions, time spent, and recent activities.
3755
- */
3756
- async getTimeline() {
3757
- const result = await this.transport.fetchData(`${this.basePath()}/timeline`);
3758
- if (result.success && result.data) {
3759
- return result.data;
3760
- }
3761
- logger.warn('Failed to fetch visitor timeline:', result.error);
3762
- return null;
3763
- }
3764
- /**
3765
- * Get engagement metrics for the current visitor.
3766
- * Includes time on site, page views, bounce rate, and engagement score.
3767
- */
3768
- async getEngagement() {
3769
- const result = await this.transport.fetchData(`${this.basePath()}/engagement`);
3770
- if (result.success && result.data) {
3771
- return result.data;
3772
- }
3773
- logger.warn('Failed to fetch visitor engagement:', result.error);
3774
- return null;
3775
- }
3776
- }
3777
-
3778
2516
  /**
3779
2517
  * Clianta SDK - Main Tracker Class
3780
2518
  * @see SDK_VERSION in core/config.ts
@@ -3823,17 +2561,12 @@
3823
2561
  this.visitorId = this.createVisitorId();
3824
2562
  this.sessionId = this.createSessionId();
3825
2563
  logger.debug('IDs created', { visitorId: this.visitorId, sessionId: this.sessionId });
3826
- // Initialize visitor API client
3827
- this.visitor = new VisitorClient(this.transport, this.workspaceId, this.visitorId);
3828
2564
  // Security warnings
3829
2565
  if (this.config.apiEndpoint.startsWith('http://') &&
3830
2566
  typeof window !== 'undefined' &&
3831
2567
  !window.location.hostname.includes('localhost') &&
3832
2568
  !window.location.hostname.includes('127.0.0.1')) {
3833
- logger.warn('apiEndpoint uses HTTP — events and visitor data will be sent unencrypted. Use HTTPS in production.');
3834
- }
3835
- if (this.config.apiKey && typeof window !== 'undefined') {
3836
- logger.warn('API key is exposed in client-side code. Use API keys only in server-side (Node.js) environments.');
2569
+ logger.warn('apiEndpoint uses HTTP — events will be sent unencrypted. Use HTTPS in production.');
3837
2570
  }
3838
2571
  // Initialize plugins
3839
2572
  this.initPlugins();
@@ -4029,63 +2762,6 @@
4029
2762
  return null;
4030
2763
  }
4031
2764
  }
4032
- /**
4033
- * Send a server-side inbound event via the API key endpoint.
4034
- * Convenience proxy to CRMClient.sendEvent() — requires apiKey in config.
4035
- */
4036
- async sendEvent(payload) {
4037
- const apiKey = this.config.apiKey;
4038
- if (!apiKey) {
4039
- logger.error('sendEvent() requires an apiKey in the SDK config');
4040
- return { success: false, contactCreated: false, event: payload.event, error: 'No API key configured' };
4041
- }
4042
- const client = new CRMClient(this.config.apiEndpoint, this.workspaceId, undefined, apiKey);
4043
- return client.sendEvent(payload);
4044
- }
4045
- /**
4046
- * Get the current visitor's profile from the CRM.
4047
- * @deprecated Use `tracker.visitor.getProfile()` instead.
4048
- */
4049
- async getVisitorProfile() {
4050
- if (!this.isInitialized) {
4051
- logger.warn('SDK not initialized');
4052
- return null;
4053
- }
4054
- return this.visitor.getProfile();
4055
- }
4056
- /**
4057
- * Get the current visitor's recent activity/events.
4058
- * @deprecated Use `tracker.visitor.getActivity()` instead.
4059
- */
4060
- async getVisitorActivity(options) {
4061
- if (!this.isInitialized) {
4062
- logger.warn('SDK not initialized');
4063
- return null;
4064
- }
4065
- return this.visitor.getActivity(options);
4066
- }
4067
- /**
4068
- * Get a summarized journey timeline for the current visitor.
4069
- * @deprecated Use `tracker.visitor.getTimeline()` instead.
4070
- */
4071
- async getVisitorTimeline() {
4072
- if (!this.isInitialized) {
4073
- logger.warn('SDK not initialized');
4074
- return null;
4075
- }
4076
- return this.visitor.getTimeline();
4077
- }
4078
- /**
4079
- * Get engagement metrics for the current visitor.
4080
- * @deprecated Use `tracker.visitor.getEngagement()` instead.
4081
- */
4082
- async getVisitorEngagement() {
4083
- if (!this.isInitialized) {
4084
- logger.warn('SDK not initialized');
4085
- return null;
4086
- }
4087
- return this.visitor.getEngagement();
4088
- }
4089
2765
  /**
4090
2766
  * Retry pending identify call
4091
2767
  */
@@ -4495,7 +3171,12 @@
4495
3171
 
4496
3172
  /**
4497
3173
  * Clianta SDK
4498
- * Professional CRM and tracking SDK for lead generation
3174
+ * Client-side tracking SDK for CRM — tracks visitors, identifies contacts,
3175
+ * captures forms, and writes CRM data from client websites.
3176
+ *
3177
+ * This SDK is designed to run on CLIENT WEBSITES (React, Next.js, Vue, etc.)
3178
+ * It only SENDS data to your CRM — it never reads CRM data back.
3179
+ *
4499
3180
  * @see SDK_VERSION in core/config.ts
4500
3181
  */
4501
3182
  // Global instance cache
@@ -4537,21 +3218,43 @@
4537
3218
  globalInstance = new Tracker(workspaceId, config);
4538
3219
  return globalInstance;
4539
3220
  }
4540
- // Attach to window for <script> usage
3221
+ // Attach to window for <script> tag usage + AUTO-INIT
4541
3222
  if (typeof window !== 'undefined') {
4542
3223
  window.clianta = clianta;
4543
3224
  window.Clianta = {
4544
3225
  clianta,
4545
3226
  Tracker,
4546
- CRMClient,
4547
3227
  ConsentManager,
4548
- EventTriggersManager,
4549
3228
  };
3229
+ // ============================================
3230
+ // AUTO-INIT FROM SCRIPT TAG
3231
+ // ============================================
3232
+ // Enables true plug-and-play:
3233
+ // <script src="clianta.min.js" data-project-id="YOUR_ID"></script>
3234
+ // That's it — everything auto-tracks.
3235
+ const autoInit = () => {
3236
+ const scripts = document.querySelectorAll('script[data-project-id]');
3237
+ const script = scripts[scripts.length - 1]; // last matching script
3238
+ if (!script)
3239
+ return;
3240
+ const projectId = script.getAttribute('data-project-id');
3241
+ if (!projectId)
3242
+ return;
3243
+ const debug = script.hasAttribute('data-debug');
3244
+ const instance = clianta(projectId, { debug });
3245
+ // Expose the auto-initialized instance globally
3246
+ window.__clianta = instance;
3247
+ };
3248
+ // Run after DOM is ready
3249
+ if (document.readyState === 'loading') {
3250
+ document.addEventListener('DOMContentLoaded', autoInit);
3251
+ }
3252
+ else {
3253
+ autoInit();
3254
+ }
4550
3255
  }
4551
3256
 
4552
- exports.CRMClient = CRMClient;
4553
3257
  exports.ConsentManager = ConsentManager;
4554
- exports.EventTriggersManager = EventTriggersManager;
4555
3258
  exports.SDK_VERSION = SDK_VERSION;
4556
3259
  exports.Tracker = Tracker;
4557
3260
  exports.clianta = clianta;