@li2/analytics 0.1.7 → 0.1.8

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 CHANGED
@@ -1,295 +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
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
@@ -9,6 +9,8 @@ interface Li2Config {
9
9
  apiUrl?: string;
10
10
  /** Enable debug logging */
11
11
  debug?: boolean;
12
+ /** Enable outbound link tracking with array of domains to track */
13
+ outbound?: string[];
12
14
  }
13
15
  interface CookieOptions {
14
16
  /** Domain for cross-domain tracking (e.g., ".example.com") */
@@ -148,6 +150,10 @@ declare class Li2Analytics {
148
150
  private getClickIdFromUrl;
149
151
  private getCookie;
150
152
  private setCookie;
153
+ /**
154
+ * Load outbound tracking module dynamically
155
+ */
156
+ private loadOutboundModule;
151
157
  /**
152
158
  * Get the current click ID
153
159
  */
package/dist/index.d.ts CHANGED
@@ -9,6 +9,8 @@ interface Li2Config {
9
9
  apiUrl?: string;
10
10
  /** Enable debug logging */
11
11
  debug?: boolean;
12
+ /** Enable outbound link tracking with array of domains to track */
13
+ outbound?: string[];
12
14
  }
13
15
  interface CookieOptions {
14
16
  /** Domain for cross-domain tracking (e.g., ".example.com") */
@@ -148,6 +150,10 @@ declare class Li2Analytics {
148
150
  private getClickIdFromUrl;
149
151
  private getCookie;
150
152
  private setCookie;
153
+ /**
154
+ * Load outbound tracking module dynamically
155
+ */
156
+ private loadOutboundModule;
151
157
  /**
152
158
  * Get the current click ID
153
159
  */