@li2/analytics 0.1.3 → 0.1.4

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.
package/README.md ADDED
@@ -0,0 +1,266 @@
1
+ # @li2/analytics
2
+
3
+ Conversion tracking SDK for Li2.ai. Track leads and sales from your marketing campaigns with automatic click ID attribution.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @li2/analytics
9
+ # or
10
+ pnpm add @li2/analytics
11
+ # or
12
+ yarn add @li2/analytics
13
+ ```
14
+
15
+ ## Client-Side SDK
16
+
17
+ The client-side SDK automatically captures click IDs from URLs (`?uid=...`) and cookies, making it easy to track conversions in the browser. You don't need to pass `clickId` manually - it's auto-detected.
18
+
19
+ > **Note:** If you need to track conversions on the server (e.g., after a webhook or server-side payment confirmation), use `getClickId()` to capture the click ID on the client and pass it to your server. See [Server-Side SDK](#server-side-sdk) for details.
20
+
21
+ ### Installation Snippet
22
+
23
+ Add this snippet to your `<head>` tag. It loads the SDK asynchronously and queues any tracking calls made before the script loads.
24
+
25
+ ```html
26
+ <script>
27
+ !(function (c, n) {
28
+ c[n] = c[n] || function () { (c[n].q = c[n].q || []).push(arguments); };
29
+ ["trackLead", "trackSale"].forEach((t) => (c[n][t] = (...a) => c[n](t, ...a)));
30
+ var s = document.createElement("script");
31
+ s.defer = 1;
32
+ s.src = "https://unpkg.com/@li2/analytics/dist/index.global.js";
33
+ s.setAttribute("data-publishable-key", "li2_pk_...");
34
+ document.head.appendChild(s);
35
+ })(window, "li2Analytics");
36
+ </script>
37
+ ```
38
+
39
+ ### Script Tag Usage
40
+
41
+ ```html
42
+ <script
43
+ src="https://unpkg.com/@li2/analytics/dist/index.global.js"
44
+ data-publishable-key="li2_pk_..."
45
+ ></script>
46
+
47
+ <script>
48
+ // Track a lead
49
+ li2Analytics.trackLead({
50
+ eventName: 'signup',
51
+ customerExternalId: 'user_123',
52
+ customerName: 'John Doe',
53
+ customerEmail: 'john@example.com',
54
+ })
55
+
56
+ // Track a sale
57
+ li2Analytics.trackSale({
58
+ customerExternalId: 'user_123',
59
+ amount: 4999, // $49.99 in cents
60
+ eventName: 'purchase',
61
+ invoiceId: 'inv_abc123',
62
+ })
63
+ </script>
64
+ ```
65
+
66
+ ### Module Import Usage
67
+
68
+ ```typescript
69
+ import { init, trackLead, trackSale } from '@li2/analytics'
70
+
71
+ // Initialize with your publishable key
72
+ init({
73
+ publishableKey: 'li2_pk_...',
74
+ debug: true, // optional: enable console logging
75
+ })
76
+
77
+ // Track a lead conversion
78
+ const leadResult = await trackLead({
79
+ eventName: 'signup',
80
+ customerExternalId: 'user_123',
81
+ customerName: 'John Doe',
82
+ customerEmail: 'john@example.com',
83
+ })
84
+
85
+ if (leadResult.success) {
86
+ console.log('Lead tracked:', leadResult.customerId)
87
+ }
88
+
89
+ // Track a sale conversion
90
+ const saleResult = await trackSale({
91
+ customerExternalId: 'user_123',
92
+ amount: 4999, // Amount in cents ($49.99)
93
+ eventName: 'purchase',
94
+ paymentProcessor: 'stripe',
95
+ invoiceId: 'inv_abc123',
96
+ currency: 'usd',
97
+ })
98
+
99
+ if (saleResult.success) {
100
+ console.log('Sale tracked:', saleResult.saleEventId)
101
+ }
102
+ ```
103
+
104
+ ### Utility Functions
105
+
106
+ ```typescript
107
+ import { isTrackingAvailable, getClickId } from '@li2/analytics'
108
+
109
+ // Check if a click ID is available for attribution
110
+ if (isTrackingAvailable()) {
111
+ console.log('Click ID:', getClickId())
112
+ }
113
+
114
+ // Use getClickId() to pass the click ID to your server for server-side tracking
115
+ const clickId = getClickId() // Returns null if no click ID is available
116
+ ```
117
+
118
+ ## Server-Side SDK
119
+
120
+ The server-side SDK is for use in Node.js, Next.js API routes, server actions, and other backend environments. It requires an API key for authentication.
121
+
122
+ ### Passing Click ID from Client to Server
123
+
124
+ Unlike the client-side SDK, the server cannot auto-detect the click ID. You need to capture it on the client and include it in your server requests:
125
+
126
+ ```typescript
127
+ // Client-side: capture the click ID
128
+ import { getClickId } from '@li2/analytics'
129
+
130
+ const clickId = getClickId()
131
+
132
+ // Include clickId when calling your server
133
+ fetch('/api/checkout', {
134
+ method: 'POST',
135
+ body: JSON.stringify({ clickId, ...otherData }),
136
+ })
137
+ ```
138
+
139
+ ### Setup
140
+
141
+ ```typescript
142
+ import { initServer } from '@li2/analytics'
143
+
144
+ const li2 = initServer({
145
+ apiKey: 'li2_sk_...', // Your secret API key
146
+ debug: true, // optional: enable console logging
147
+ })
148
+ ```
149
+
150
+ ### Track Lead (Server-Side)
151
+
152
+ ```typescript
153
+ // clickId must be captured from the client and passed to your server
154
+ const result = await li2.trackLead({
155
+ clickId: 'abc123', // Required for server-side tracking
156
+ eventName: 'signup',
157
+ customerExternalId: 'user_123',
158
+ customerName: 'John Doe',
159
+ customerEmail: 'john@example.com',
160
+ metadata: {
161
+ plan: 'pro',
162
+ source: 'landing_page',
163
+ },
164
+ })
165
+
166
+ if (result.success) {
167
+ console.log('Lead tracked:', result.customerId)
168
+ }
169
+ ```
170
+
171
+ ### Track Sale (Server-Side)
172
+
173
+ ```typescript
174
+ const result = await li2.trackSale({
175
+ clickId: 'abc123', // Required for server-side tracking
176
+ customerExternalId: 'user_123',
177
+ amount: 9900, // Amount in cents ($99.00)
178
+ eventName: 'subscription',
179
+ paymentProcessor: 'stripe',
180
+ invoiceId: 'inv_xyz789',
181
+ currency: 'usd',
182
+ metadata: {
183
+ plan: 'annual',
184
+ coupon: 'SAVE20',
185
+ },
186
+ })
187
+
188
+ if (result.success) {
189
+ console.log('Sale tracked:', result.saleEventId)
190
+ }
191
+ ```
192
+
193
+ ### Next.js Example
194
+
195
+ ```typescript
196
+ // app/api/checkout/route.ts
197
+ import { initServer } from '@li2/analytics'
198
+
199
+ const li2 = initServer({ apiKey: process.env.LI2_API_KEY! })
200
+
201
+ export async function POST(request: Request) {
202
+ const { clickId, userId, amount, invoiceId } = await request.json()
203
+
204
+ // Track the sale after successful payment
205
+ const result = await li2.trackSale({
206
+ clickId,
207
+ customerExternalId: userId,
208
+ amount,
209
+ invoiceId,
210
+ paymentProcessor: 'stripe',
211
+ })
212
+
213
+ return Response.json({ success: result.success })
214
+ }
215
+ ```
216
+
217
+ ## API Reference
218
+
219
+ ### Client-Side
220
+
221
+ | Function | Description |
222
+ | ---------------------- | ---------------------------------------- |
223
+ | `init(config)` | Initialize the SDK with configuration |
224
+ | `trackLead(params)` | Track a lead conversion event |
225
+ | `trackSale(params)` | Track a sale conversion event |
226
+ | `isTrackingAvailable()`| Check if click ID is available |
227
+ | `getClickId()` | Get the current click ID |
228
+
229
+ ### Server-Side
230
+
231
+ | Function | Description |
232
+ | ---------------------- | ---------------------------------------- |
233
+ | `initServer(config)` | Create a server-side SDK instance |
234
+ | `trackLead(params)` | Track a lead (clickId required) |
235
+ | `trackSale(params)` | Track a sale (clickId required) |
236
+
237
+ ### TrackLead Parameters
238
+
239
+ | Parameter | Type | Required | Description |
240
+ | -------------------- | -------- | -------- | ------------------------------------- |
241
+ | `clickId` | string | Server only | Click ID for attribution |
242
+ | `eventName` | string | Yes | Name of the lead event |
243
+ | `customerExternalId` | string | Yes | Your unique customer identifier |
244
+ | `customerName` | string | No | Customer's name |
245
+ | `customerEmail` | string | No | Customer's email |
246
+ | `customerAvatar` | string | No | URL to customer's avatar |
247
+ | `metadata` | object | No | Additional data (max 10,000 chars) |
248
+
249
+ ### TrackSale Parameters
250
+
251
+ | Parameter | Type | Required | Description |
252
+ | -------------------- | -------- | -------- | ------------------------------------- |
253
+ | `clickId` | string | Server only | Click ID for attribution |
254
+ | `customerExternalId` | string | Yes | Your unique customer identifier |
255
+ | `amount` | number | Yes | Amount in smallest currency unit |
256
+ | `eventName` | string | No | Name of sale event (default: "Purchase") |
257
+ | `paymentProcessor` | string | No | Payment processor (e.g., "stripe") |
258
+ | `invoiceId` | string | No | Your invoice/transaction ID |
259
+ | `currency` | string | No | Currency code (default: "usd") |
260
+ | `customerName` | string | No | Customer's name |
261
+ | `customerEmail` | string | No | Customer's email |
262
+ | `metadata` | object | No | Additional data (max 10,000 chars) |
263
+
264
+ ## License
265
+
266
+ MIT
package/dist/index.d.mts CHANGED
@@ -63,6 +63,67 @@ interface TrackSaleResponse {
63
63
  customerId?: string;
64
64
  message?: string;
65
65
  }
66
+ /**
67
+ * Configuration for the server-side Li2 Analytics SDK
68
+ */
69
+ interface Li2ServerConfig {
70
+ /** Secret API key for server-side authentication (li2_sk_...) */
71
+ apiKey: string;
72
+ /** API endpoint for tracking (default: https://api.li2.ai) */
73
+ apiUrl?: string;
74
+ /** Enable debug logging */
75
+ debug?: boolean;
76
+ }
77
+ /**
78
+ * Parameters for tracking a lead (server-side)
79
+ * Note: clickId is REQUIRED for server-side tracking
80
+ */
81
+ interface ServerTrackLeadParams {
82
+ /** The unique click ID (REQUIRED for server-side tracking) */
83
+ clickId: string;
84
+ /** The name of the lead event (required) */
85
+ eventName: string;
86
+ /** The unique customer ID in your system (required) */
87
+ customerExternalId: string;
88
+ /** The name of the customer */
89
+ customerName?: string;
90
+ /** The email address of the customer */
91
+ customerEmail?: string;
92
+ /** The avatar URL of the customer */
93
+ customerAvatar?: string;
94
+ /** Phone number (legacy, optional) */
95
+ phone?: string;
96
+ /** Additional metadata (max 10,000 characters) */
97
+ metadata?: Record<string, unknown>;
98
+ }
99
+ /**
100
+ * Parameters for tracking a sale (server-side)
101
+ * Note: clickId is REQUIRED for server-side tracking
102
+ */
103
+ interface ServerTrackSaleParams {
104
+ /** The unique click ID (REQUIRED for server-side tracking) */
105
+ clickId: string;
106
+ /** The unique customer ID in your system (required) */
107
+ customerExternalId: string;
108
+ /** The sale amount in smallest currency unit (required, e.g., 5000 cents = $50.00) */
109
+ amount: number;
110
+ /** The name of the sale event (default: "Purchase") */
111
+ eventName?: string;
112
+ /** The payment processor (default: "custom", e.g., "stripe", "paypal") */
113
+ paymentProcessor?: string;
114
+ /** The unique invoice/transaction ID in your system */
115
+ invoiceId?: string;
116
+ /** The currency code (default: "usd") */
117
+ currency?: string;
118
+ /** The name of the customer (used to auto-create customer if not found) */
119
+ customerName?: string;
120
+ /** The email of the customer (used to auto-create customer if not found) */
121
+ customerEmail?: string;
122
+ /** The avatar URL of the customer */
123
+ customerAvatar?: string;
124
+ /** Additional metadata (max 10,000 characters) */
125
+ metadata?: Record<string, unknown>;
126
+ }
66
127
  declare class Li2Analytics {
67
128
  private config;
68
129
  private clickId;
@@ -89,6 +150,25 @@ declare class Li2Analytics {
89
150
  */
90
151
  trackSale(params: TrackSaleParams): Promise<TrackSaleResponse>;
91
152
  }
153
+ /**
154
+ * Server-side Li2 Analytics SDK
155
+ * For use in Node.js, Next.js server actions, React Server Components, etc.
156
+ */
157
+ declare class Li2ServerAnalytics {
158
+ private config;
159
+ constructor(config: Li2ServerConfig);
160
+ private log;
161
+ /**
162
+ * Track a lead conversion event (server-side)
163
+ * @param params - Lead tracking parameters (clickId is REQUIRED)
164
+ */
165
+ trackLead(params: ServerTrackLeadParams): Promise<TrackLeadResponse>;
166
+ /**
167
+ * Track a sale conversion event (server-side)
168
+ * @param params - Sale tracking parameters (clickId is REQUIRED)
169
+ */
170
+ trackSale(params: ServerTrackSaleParams): Promise<TrackSaleResponse>;
171
+ }
92
172
  /**
93
173
  * Initialize the Li2 Analytics SDK
94
174
  */
@@ -118,6 +198,11 @@ declare function isTrackingAvailable(): boolean;
118
198
  */
119
199
  declare function getClickId(): string | null;
120
200
 
201
+ /**
202
+ * Initialize the server-side Li2 Analytics SDK
203
+ * For use in Node.js, Next.js server actions, React Server Components, etc.
204
+ */
205
+ declare function initServer(config: Li2ServerConfig): Li2ServerAnalytics;
121
206
  declare const _default: {
122
207
  init: typeof init;
123
208
  getInstance: typeof getInstance;
@@ -125,6 +210,7 @@ declare const _default: {
125
210
  trackSale: typeof trackSale;
126
211
  isTrackingAvailable: typeof isTrackingAvailable;
127
212
  getClickId: typeof getClickId;
213
+ initServer: typeof initServer;
128
214
  };
129
215
 
130
- export { Li2Analytics, type Li2Config, type TrackLeadParams, type TrackLeadResponse, type TrackSaleParams, type TrackSaleResponse, _default as default, getClickId, getInstance, init, isTrackingAvailable, trackLead, trackSale };
216
+ export { Li2Analytics, type Li2Config, Li2ServerAnalytics, type Li2ServerConfig, type ServerTrackLeadParams, type ServerTrackSaleParams, type TrackLeadParams, type TrackLeadResponse, type TrackSaleParams, type TrackSaleResponse, _default as default, getClickId, getInstance, init, initServer, isTrackingAvailable, trackLead, trackSale };
package/dist/index.d.ts CHANGED
@@ -63,6 +63,67 @@ interface TrackSaleResponse {
63
63
  customerId?: string;
64
64
  message?: string;
65
65
  }
66
+ /**
67
+ * Configuration for the server-side Li2 Analytics SDK
68
+ */
69
+ interface Li2ServerConfig {
70
+ /** Secret API key for server-side authentication (li2_sk_...) */
71
+ apiKey: string;
72
+ /** API endpoint for tracking (default: https://api.li2.ai) */
73
+ apiUrl?: string;
74
+ /** Enable debug logging */
75
+ debug?: boolean;
76
+ }
77
+ /**
78
+ * Parameters for tracking a lead (server-side)
79
+ * Note: clickId is REQUIRED for server-side tracking
80
+ */
81
+ interface ServerTrackLeadParams {
82
+ /** The unique click ID (REQUIRED for server-side tracking) */
83
+ clickId: string;
84
+ /** The name of the lead event (required) */
85
+ eventName: string;
86
+ /** The unique customer ID in your system (required) */
87
+ customerExternalId: string;
88
+ /** The name of the customer */
89
+ customerName?: string;
90
+ /** The email address of the customer */
91
+ customerEmail?: string;
92
+ /** The avatar URL of the customer */
93
+ customerAvatar?: string;
94
+ /** Phone number (legacy, optional) */
95
+ phone?: string;
96
+ /** Additional metadata (max 10,000 characters) */
97
+ metadata?: Record<string, unknown>;
98
+ }
99
+ /**
100
+ * Parameters for tracking a sale (server-side)
101
+ * Note: clickId is REQUIRED for server-side tracking
102
+ */
103
+ interface ServerTrackSaleParams {
104
+ /** The unique click ID (REQUIRED for server-side tracking) */
105
+ clickId: string;
106
+ /** The unique customer ID in your system (required) */
107
+ customerExternalId: string;
108
+ /** The sale amount in smallest currency unit (required, e.g., 5000 cents = $50.00) */
109
+ amount: number;
110
+ /** The name of the sale event (default: "Purchase") */
111
+ eventName?: string;
112
+ /** The payment processor (default: "custom", e.g., "stripe", "paypal") */
113
+ paymentProcessor?: string;
114
+ /** The unique invoice/transaction ID in your system */
115
+ invoiceId?: string;
116
+ /** The currency code (default: "usd") */
117
+ currency?: string;
118
+ /** The name of the customer (used to auto-create customer if not found) */
119
+ customerName?: string;
120
+ /** The email of the customer (used to auto-create customer if not found) */
121
+ customerEmail?: string;
122
+ /** The avatar URL of the customer */
123
+ customerAvatar?: string;
124
+ /** Additional metadata (max 10,000 characters) */
125
+ metadata?: Record<string, unknown>;
126
+ }
66
127
  declare class Li2Analytics {
67
128
  private config;
68
129
  private clickId;
@@ -89,6 +150,25 @@ declare class Li2Analytics {
89
150
  */
90
151
  trackSale(params: TrackSaleParams): Promise<TrackSaleResponse>;
91
152
  }
153
+ /**
154
+ * Server-side Li2 Analytics SDK
155
+ * For use in Node.js, Next.js server actions, React Server Components, etc.
156
+ */
157
+ declare class Li2ServerAnalytics {
158
+ private config;
159
+ constructor(config: Li2ServerConfig);
160
+ private log;
161
+ /**
162
+ * Track a lead conversion event (server-side)
163
+ * @param params - Lead tracking parameters (clickId is REQUIRED)
164
+ */
165
+ trackLead(params: ServerTrackLeadParams): Promise<TrackLeadResponse>;
166
+ /**
167
+ * Track a sale conversion event (server-side)
168
+ * @param params - Sale tracking parameters (clickId is REQUIRED)
169
+ */
170
+ trackSale(params: ServerTrackSaleParams): Promise<TrackSaleResponse>;
171
+ }
92
172
  /**
93
173
  * Initialize the Li2 Analytics SDK
94
174
  */
@@ -118,6 +198,11 @@ declare function isTrackingAvailable(): boolean;
118
198
  */
119
199
  declare function getClickId(): string | null;
120
200
 
201
+ /**
202
+ * Initialize the server-side Li2 Analytics SDK
203
+ * For use in Node.js, Next.js server actions, React Server Components, etc.
204
+ */
205
+ declare function initServer(config: Li2ServerConfig): Li2ServerAnalytics;
121
206
  declare const _default: {
122
207
  init: typeof init;
123
208
  getInstance: typeof getInstance;
@@ -125,6 +210,7 @@ declare const _default: {
125
210
  trackSale: typeof trackSale;
126
211
  isTrackingAvailable: typeof isTrackingAvailable;
127
212
  getClickId: typeof getClickId;
213
+ initServer: typeof initServer;
128
214
  };
129
215
 
130
- export { Li2Analytics, type Li2Config, type TrackLeadParams, type TrackLeadResponse, type TrackSaleParams, type TrackSaleResponse, _default as default, getClickId, getInstance, init, isTrackingAvailable, trackLead, trackSale };
216
+ export { Li2Analytics, type Li2Config, Li2ServerAnalytics, type Li2ServerConfig, type ServerTrackLeadParams, type ServerTrackSaleParams, type TrackLeadParams, type TrackLeadResponse, type TrackSaleParams, type TrackSaleResponse, _default as default, getClickId, getInstance, init, initServer, isTrackingAvailable, trackLead, trackSale };