@li2/analytics 0.1.3 → 0.1.5

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,295 @@
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
+ ### Script Tag Attributes
67
+
68
+ | Attribute | Description |
69
+ | --------- | ----------- |
70
+ | `data-publishable-key` | Your publishable API key (`li2_pk_...`) |
71
+ | `data-api-url` | Custom API endpoint (default: `https://api.li2.ai`) |
72
+ | `data-debug` | Enable debug logging (presence enables, no value needed) |
73
+ | `data-cookie-options` | JSON object for cookie customization (see below) |
74
+
75
+ ### Cookie Options
76
+
77
+ By default, the SDK stores the click ID in a cookie scoped to the current domain with a 30-day expiration. Use `data-cookie-options` for cross-domain tracking or custom expiration.
78
+
79
+ ```html
80
+ <script
81
+ src="https://unpkg.com/@li2/analytics/dist/index.global.js"
82
+ data-publishable-key="li2_pk_..."
83
+ data-cookie-options='{"domain":".example.com","expiresInDays":60}'
84
+ ></script>
85
+ ```
86
+
87
+ | Property | Type | Default | Description |
88
+ | -------- | ---- | ------- | ----------- |
89
+ | `domain` | string | (current domain) | Cookie domain for cross-subdomain tracking (e.g., `.example.com`) |
90
+ | `expiresInDays` | number | `30` | Days until the cookie expires |
91
+ | `path` | string | `"/"` | Cookie path |
92
+
93
+ **Cross-domain tracking example:** If users land on `www.example.com` but convert on `app.example.com`, set `domain` to `.example.com` to share the click ID across subdomains.
94
+
95
+ ### Module Import Usage
96
+
97
+ ```typescript
98
+ import { init, trackLead, trackSale } from '@li2/analytics'
99
+
100
+ // Initialize with your publishable key
101
+ init({
102
+ publishableKey: 'li2_pk_...',
103
+ debug: true, // optional: enable console logging
104
+ })
105
+
106
+ // Track a lead conversion
107
+ const leadResult = await trackLead({
108
+ eventName: 'signup',
109
+ customerExternalId: 'user_123',
110
+ customerName: 'John Doe',
111
+ customerEmail: 'john@example.com',
112
+ })
113
+
114
+ if (leadResult.success) {
115
+ console.log('Lead tracked:', leadResult.customerId)
116
+ }
117
+
118
+ // Track a sale conversion
119
+ const saleResult = await trackSale({
120
+ customerExternalId: 'user_123',
121
+ amount: 4999, // Amount in cents ($49.99)
122
+ eventName: 'purchase',
123
+ paymentProcessor: 'stripe',
124
+ invoiceId: 'inv_abc123',
125
+ currency: 'usd',
126
+ })
127
+
128
+ if (saleResult.success) {
129
+ console.log('Sale tracked:', saleResult.saleEventId)
130
+ }
131
+ ```
132
+
133
+ ### Utility Functions
134
+
135
+ ```typescript
136
+ import { isTrackingAvailable, getClickId } from '@li2/analytics'
137
+
138
+ // Check if a click ID is available for attribution
139
+ if (isTrackingAvailable()) {
140
+ console.log('Click ID:', getClickId())
141
+ }
142
+
143
+ // Use getClickId() to pass the click ID to your server for server-side tracking
144
+ const clickId = getClickId() // Returns null if no click ID is available
145
+ ```
146
+
147
+ ## Server-Side SDK
148
+
149
+ 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.
150
+
151
+ ### Passing Click ID from Client to Server
152
+
153
+ 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:
154
+
155
+ ```typescript
156
+ // Client-side: capture the click ID
157
+ import { getClickId } from '@li2/analytics'
158
+
159
+ const clickId = getClickId()
160
+
161
+ // Include clickId when calling your server
162
+ fetch('/api/checkout', {
163
+ method: 'POST',
164
+ body: JSON.stringify({ clickId, ...otherData }),
165
+ })
166
+ ```
167
+
168
+ ### Setup
169
+
170
+ ```typescript
171
+ import { initServer } from '@li2/analytics'
172
+
173
+ const li2 = initServer({
174
+ apiKey: 'li2_sk_...', // Your secret API key
175
+ debug: true, // optional: enable console logging
176
+ })
177
+ ```
178
+
179
+ ### Track Lead (Server-Side)
180
+
181
+ ```typescript
182
+ // clickId must be captured from the client and passed to your server
183
+ const result = await li2.trackLead({
184
+ clickId: 'abc123', // Required for server-side tracking
185
+ eventName: 'signup',
186
+ customerExternalId: 'user_123',
187
+ customerName: 'John Doe',
188
+ customerEmail: 'john@example.com',
189
+ metadata: {
190
+ plan: 'pro',
191
+ source: 'landing_page',
192
+ },
193
+ })
194
+
195
+ if (result.success) {
196
+ console.log('Lead tracked:', result.customerId)
197
+ }
198
+ ```
199
+
200
+ ### Track Sale (Server-Side)
201
+
202
+ ```typescript
203
+ const result = await li2.trackSale({
204
+ clickId: 'abc123', // Required for server-side tracking
205
+ customerExternalId: 'user_123',
206
+ amount: 9900, // Amount in cents ($99.00)
207
+ eventName: 'subscription',
208
+ paymentProcessor: 'stripe',
209
+ invoiceId: 'inv_xyz789',
210
+ currency: 'usd',
211
+ metadata: {
212
+ plan: 'annual',
213
+ coupon: 'SAVE20',
214
+ },
215
+ })
216
+
217
+ if (result.success) {
218
+ console.log('Sale tracked:', result.saleEventId)
219
+ }
220
+ ```
221
+
222
+ ### Next.js Example
223
+
224
+ ```typescript
225
+ // app/api/checkout/route.ts
226
+ import { initServer } from '@li2/analytics'
227
+
228
+ const li2 = initServer({ apiKey: process.env.LI2_API_KEY! })
229
+
230
+ export async function POST(request: Request) {
231
+ const { clickId, userId, amount, invoiceId } = await request.json()
232
+
233
+ // Track the sale after successful payment
234
+ const result = await li2.trackSale({
235
+ clickId,
236
+ customerExternalId: userId,
237
+ amount,
238
+ invoiceId,
239
+ paymentProcessor: 'stripe',
240
+ })
241
+
242
+ return Response.json({ success: result.success })
243
+ }
244
+ ```
245
+
246
+ ## API Reference
247
+
248
+ ### Client-Side
249
+
250
+ | Function | Description |
251
+ | ---------------------- | ---------------------------------------- |
252
+ | `init(config)` | Initialize the SDK with configuration |
253
+ | `trackLead(params)` | Track a lead conversion event |
254
+ | `trackSale(params)` | Track a sale conversion event |
255
+ | `isTrackingAvailable()`| Check if click ID is available |
256
+ | `getClickId()` | Get the current click ID |
257
+
258
+ ### Server-Side
259
+
260
+ | Function | Description |
261
+ | ---------------------- | ---------------------------------------- |
262
+ | `initServer(config)` | Create a server-side SDK instance |
263
+ | `trackLead(params)` | Track a lead (clickId required) |
264
+ | `trackSale(params)` | Track a sale (clickId required) |
265
+
266
+ ### TrackLead Parameters
267
+
268
+ | Parameter | Type | Required | Description |
269
+ | -------------------- | -------- | -------- | ------------------------------------- |
270
+ | `clickId` | string | Server only | Click ID for attribution |
271
+ | `eventName` | string | Yes | Name of the lead event |
272
+ | `customerExternalId` | string | Yes | Your unique customer identifier |
273
+ | `customerName` | string | No | Customer's name |
274
+ | `customerEmail` | string | No | Customer's email |
275
+ | `customerAvatar` | string | No | URL to customer's avatar |
276
+ | `metadata` | object | No | Additional data (max 10,000 chars) |
277
+
278
+ ### TrackSale Parameters
279
+
280
+ | Parameter | Type | Required | Description |
281
+ | -------------------- | -------- | -------- | ------------------------------------- |
282
+ | `clickId` | string | Server only | Click ID for attribution |
283
+ | `customerExternalId` | string | Yes | Your unique customer identifier |
284
+ | `amount` | number | Yes | Amount in smallest currency unit |
285
+ | `eventName` | string | No | Name of sale event (default: "Purchase") |
286
+ | `paymentProcessor` | string | No | Payment processor (e.g., "stripe") |
287
+ | `invoiceId` | string | No | Your invoice/transaction ID |
288
+ | `currency` | string | No | Currency code (default: "usd") |
289
+ | `customerName` | string | No | Customer's name |
290
+ | `customerEmail` | string | No | Customer's email |
291
+ | `metadata` | object | No | Additional data (max 10,000 chars) |
292
+
293
+ ## License
294
+
295
+ MIT
package/dist/index.d.mts CHANGED
@@ -10,6 +10,14 @@ interface Li2Config {
10
10
  /** Enable debug logging */
11
11
  debug?: boolean;
12
12
  }
13
+ interface CookieOptions {
14
+ /** Domain for cross-domain tracking (e.g., ".example.com") */
15
+ domain?: string;
16
+ /** Days until cookie expires (default: 30) */
17
+ expiresInDays?: number;
18
+ /** Cookie path (default: "/") */
19
+ path?: string;
20
+ }
13
21
  interface TrackLeadParams {
14
22
  /** The unique click ID (auto-populated from cookie/URL if not provided) */
15
23
  clickId?: string;
@@ -63,11 +71,77 @@ interface TrackSaleResponse {
63
71
  customerId?: string;
64
72
  message?: string;
65
73
  }
74
+ /**
75
+ * Configuration for the server-side Li2 Analytics SDK
76
+ */
77
+ interface Li2ServerConfig {
78
+ /** Secret API key for server-side authentication (li2_sk_...) */
79
+ apiKey: string;
80
+ /** API endpoint for tracking (default: https://api.li2.ai) */
81
+ apiUrl?: string;
82
+ /** Enable debug logging */
83
+ debug?: boolean;
84
+ }
85
+ /**
86
+ * Parameters for tracking a lead (server-side)
87
+ * Note: clickId is REQUIRED for server-side tracking
88
+ */
89
+ interface ServerTrackLeadParams {
90
+ /** The unique click ID (REQUIRED for server-side tracking) */
91
+ clickId: string;
92
+ /** The name of the lead event (required) */
93
+ eventName: string;
94
+ /** The unique customer ID in your system (required) */
95
+ customerExternalId: string;
96
+ /** The name of the customer */
97
+ customerName?: string;
98
+ /** The email address of the customer */
99
+ customerEmail?: string;
100
+ /** The avatar URL of the customer */
101
+ customerAvatar?: string;
102
+ /** Phone number (legacy, optional) */
103
+ phone?: string;
104
+ /** Additional metadata (max 10,000 characters) */
105
+ metadata?: Record<string, unknown>;
106
+ }
107
+ /**
108
+ * Parameters for tracking a sale (server-side)
109
+ * Note: clickId is REQUIRED for server-side tracking
110
+ */
111
+ interface ServerTrackSaleParams {
112
+ /** The unique click ID (REQUIRED for server-side tracking) */
113
+ clickId: string;
114
+ /** The unique customer ID in your system (required) */
115
+ customerExternalId: string;
116
+ /** The sale amount in smallest currency unit (required, e.g., 5000 cents = $50.00) */
117
+ amount: number;
118
+ /** The name of the sale event (default: "Purchase") */
119
+ eventName?: string;
120
+ /** The payment processor (default: "custom", e.g., "stripe", "paypal") */
121
+ paymentProcessor?: string;
122
+ /** The unique invoice/transaction ID in your system */
123
+ invoiceId?: string;
124
+ /** The currency code (default: "usd") */
125
+ currency?: string;
126
+ /** The name of the customer (used to auto-create customer if not found) */
127
+ customerName?: string;
128
+ /** The email of the customer (used to auto-create customer if not found) */
129
+ customerEmail?: string;
130
+ /** The avatar URL of the customer */
131
+ customerAvatar?: string;
132
+ /** Additional metadata (max 10,000 characters) */
133
+ metadata?: Record<string, unknown>;
134
+ }
66
135
  declare class Li2Analytics {
67
136
  private config;
68
137
  private clickId;
138
+ private cookieOptions;
69
139
  constructor(config?: Li2Config);
70
140
  private log;
141
+ /**
142
+ * Set cookie options for customizing cookie behavior
143
+ */
144
+ setCookieOptions(options: CookieOptions): void;
71
145
  private init;
72
146
  private getClickIdFromUrl;
73
147
  private getCookie;
@@ -89,6 +163,25 @@ declare class Li2Analytics {
89
163
  */
90
164
  trackSale(params: TrackSaleParams): Promise<TrackSaleResponse>;
91
165
  }
166
+ /**
167
+ * Server-side Li2 Analytics SDK
168
+ * For use in Node.js, Next.js server actions, React Server Components, etc.
169
+ */
170
+ declare class Li2ServerAnalytics {
171
+ private config;
172
+ constructor(config: Li2ServerConfig);
173
+ private log;
174
+ /**
175
+ * Track a lead conversion event (server-side)
176
+ * @param params - Lead tracking parameters (clickId is REQUIRED)
177
+ */
178
+ trackLead(params: ServerTrackLeadParams): Promise<TrackLeadResponse>;
179
+ /**
180
+ * Track a sale conversion event (server-side)
181
+ * @param params - Sale tracking parameters (clickId is REQUIRED)
182
+ */
183
+ trackSale(params: ServerTrackSaleParams): Promise<TrackSaleResponse>;
184
+ }
92
185
  /**
93
186
  * Initialize the Li2 Analytics SDK
94
187
  */
@@ -118,6 +211,11 @@ declare function isTrackingAvailable(): boolean;
118
211
  */
119
212
  declare function getClickId(): string | null;
120
213
 
214
+ /**
215
+ * Initialize the server-side Li2 Analytics SDK
216
+ * For use in Node.js, Next.js server actions, React Server Components, etc.
217
+ */
218
+ declare function initServer(config: Li2ServerConfig): Li2ServerAnalytics;
121
219
  declare const _default: {
122
220
  init: typeof init;
123
221
  getInstance: typeof getInstance;
@@ -125,6 +223,7 @@ declare const _default: {
125
223
  trackSale: typeof trackSale;
126
224
  isTrackingAvailable: typeof isTrackingAvailable;
127
225
  getClickId: typeof getClickId;
226
+ initServer: typeof initServer;
128
227
  };
129
228
 
130
- export { Li2Analytics, type Li2Config, type TrackLeadParams, type TrackLeadResponse, type TrackSaleParams, type TrackSaleResponse, _default as default, getClickId, getInstance, init, isTrackingAvailable, trackLead, trackSale };
229
+ export { type CookieOptions, 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
@@ -10,6 +10,14 @@ interface Li2Config {
10
10
  /** Enable debug logging */
11
11
  debug?: boolean;
12
12
  }
13
+ interface CookieOptions {
14
+ /** Domain for cross-domain tracking (e.g., ".example.com") */
15
+ domain?: string;
16
+ /** Days until cookie expires (default: 30) */
17
+ expiresInDays?: number;
18
+ /** Cookie path (default: "/") */
19
+ path?: string;
20
+ }
13
21
  interface TrackLeadParams {
14
22
  /** The unique click ID (auto-populated from cookie/URL if not provided) */
15
23
  clickId?: string;
@@ -63,11 +71,77 @@ interface TrackSaleResponse {
63
71
  customerId?: string;
64
72
  message?: string;
65
73
  }
74
+ /**
75
+ * Configuration for the server-side Li2 Analytics SDK
76
+ */
77
+ interface Li2ServerConfig {
78
+ /** Secret API key for server-side authentication (li2_sk_...) */
79
+ apiKey: string;
80
+ /** API endpoint for tracking (default: https://api.li2.ai) */
81
+ apiUrl?: string;
82
+ /** Enable debug logging */
83
+ debug?: boolean;
84
+ }
85
+ /**
86
+ * Parameters for tracking a lead (server-side)
87
+ * Note: clickId is REQUIRED for server-side tracking
88
+ */
89
+ interface ServerTrackLeadParams {
90
+ /** The unique click ID (REQUIRED for server-side tracking) */
91
+ clickId: string;
92
+ /** The name of the lead event (required) */
93
+ eventName: string;
94
+ /** The unique customer ID in your system (required) */
95
+ customerExternalId: string;
96
+ /** The name of the customer */
97
+ customerName?: string;
98
+ /** The email address of the customer */
99
+ customerEmail?: string;
100
+ /** The avatar URL of the customer */
101
+ customerAvatar?: string;
102
+ /** Phone number (legacy, optional) */
103
+ phone?: string;
104
+ /** Additional metadata (max 10,000 characters) */
105
+ metadata?: Record<string, unknown>;
106
+ }
107
+ /**
108
+ * Parameters for tracking a sale (server-side)
109
+ * Note: clickId is REQUIRED for server-side tracking
110
+ */
111
+ interface ServerTrackSaleParams {
112
+ /** The unique click ID (REQUIRED for server-side tracking) */
113
+ clickId: string;
114
+ /** The unique customer ID in your system (required) */
115
+ customerExternalId: string;
116
+ /** The sale amount in smallest currency unit (required, e.g., 5000 cents = $50.00) */
117
+ amount: number;
118
+ /** The name of the sale event (default: "Purchase") */
119
+ eventName?: string;
120
+ /** The payment processor (default: "custom", e.g., "stripe", "paypal") */
121
+ paymentProcessor?: string;
122
+ /** The unique invoice/transaction ID in your system */
123
+ invoiceId?: string;
124
+ /** The currency code (default: "usd") */
125
+ currency?: string;
126
+ /** The name of the customer (used to auto-create customer if not found) */
127
+ customerName?: string;
128
+ /** The email of the customer (used to auto-create customer if not found) */
129
+ customerEmail?: string;
130
+ /** The avatar URL of the customer */
131
+ customerAvatar?: string;
132
+ /** Additional metadata (max 10,000 characters) */
133
+ metadata?: Record<string, unknown>;
134
+ }
66
135
  declare class Li2Analytics {
67
136
  private config;
68
137
  private clickId;
138
+ private cookieOptions;
69
139
  constructor(config?: Li2Config);
70
140
  private log;
141
+ /**
142
+ * Set cookie options for customizing cookie behavior
143
+ */
144
+ setCookieOptions(options: CookieOptions): void;
71
145
  private init;
72
146
  private getClickIdFromUrl;
73
147
  private getCookie;
@@ -89,6 +163,25 @@ declare class Li2Analytics {
89
163
  */
90
164
  trackSale(params: TrackSaleParams): Promise<TrackSaleResponse>;
91
165
  }
166
+ /**
167
+ * Server-side Li2 Analytics SDK
168
+ * For use in Node.js, Next.js server actions, React Server Components, etc.
169
+ */
170
+ declare class Li2ServerAnalytics {
171
+ private config;
172
+ constructor(config: Li2ServerConfig);
173
+ private log;
174
+ /**
175
+ * Track a lead conversion event (server-side)
176
+ * @param params - Lead tracking parameters (clickId is REQUIRED)
177
+ */
178
+ trackLead(params: ServerTrackLeadParams): Promise<TrackLeadResponse>;
179
+ /**
180
+ * Track a sale conversion event (server-side)
181
+ * @param params - Sale tracking parameters (clickId is REQUIRED)
182
+ */
183
+ trackSale(params: ServerTrackSaleParams): Promise<TrackSaleResponse>;
184
+ }
92
185
  /**
93
186
  * Initialize the Li2 Analytics SDK
94
187
  */
@@ -118,6 +211,11 @@ declare function isTrackingAvailable(): boolean;
118
211
  */
119
212
  declare function getClickId(): string | null;
120
213
 
214
+ /**
215
+ * Initialize the server-side Li2 Analytics SDK
216
+ * For use in Node.js, Next.js server actions, React Server Components, etc.
217
+ */
218
+ declare function initServer(config: Li2ServerConfig): Li2ServerAnalytics;
121
219
  declare const _default: {
122
220
  init: typeof init;
123
221
  getInstance: typeof getInstance;
@@ -125,6 +223,7 @@ declare const _default: {
125
223
  trackSale: typeof trackSale;
126
224
  isTrackingAvailable: typeof isTrackingAvailable;
127
225
  getClickId: typeof getClickId;
226
+ initServer: typeof initServer;
128
227
  };
129
228
 
130
- export { Li2Analytics, type Li2Config, type TrackLeadParams, type TrackLeadResponse, type TrackSaleParams, type TrackSaleResponse, _default as default, getClickId, getInstance, init, isTrackingAvailable, trackLead, trackSale };
229
+ export { type CookieOptions, 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 };