@sessionsight/goals 1.0.0
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/LICENSE +21 -0
- package/README.md +106 -0
- package/package.json +40 -0
- package/src/client.ts +104 -0
- package/src/index.ts +42 -0
- package/src/types.ts +24 -0
- package/test/client.test.ts +198 -0
- package/tsconfig.json +13 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 SessionSight
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
# @sessionsight/goals
|
|
2
|
+
|
|
3
|
+
Server-side SDK for tracking goal progress in SessionSight.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install @sessionsight/goals
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
Or with a script tag:
|
|
12
|
+
|
|
13
|
+
```html
|
|
14
|
+
<script src="https://cdn.sessionsight.com/sessionsight-goals.js"></script>
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
## Quick Start
|
|
18
|
+
|
|
19
|
+
```typescript
|
|
20
|
+
import SessionSightGoals from '@sessionsight/goals';
|
|
21
|
+
|
|
22
|
+
// Initialize with your secret API key and property ID
|
|
23
|
+
SessionSightGoals.init({
|
|
24
|
+
secretApiKey: 'sessionsight_sec_your_secret_key',
|
|
25
|
+
propertyId: 'your-property-id',
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
// Increment a goal
|
|
29
|
+
await SessionSightGoals.increment('user-signups');
|
|
30
|
+
|
|
31
|
+
// Increment with a custom amount
|
|
32
|
+
await SessionSightGoals.increment('revenue', { amount: 49 });
|
|
33
|
+
|
|
34
|
+
// Increment with a monetary value for revenue attribution
|
|
35
|
+
await SessionSightGoals.increment('purchase', {
|
|
36
|
+
value: 49.99,
|
|
37
|
+
currency: 'USD',
|
|
38
|
+
metadata: { sku: 'widget-pro' },
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
// Increment with metadata
|
|
42
|
+
await SessionSightGoals.increment('user-signups', {
|
|
43
|
+
metadata: { plan: 'pro', source: 'landing-page' },
|
|
44
|
+
});
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
## API Reference
|
|
48
|
+
|
|
49
|
+
### `SessionSightGoals.init(config)`
|
|
50
|
+
|
|
51
|
+
Initialize the SDK. Must be called before any other method.
|
|
52
|
+
|
|
53
|
+
| Option | Type | Required | Default | Description |
|
|
54
|
+
| ------------ | -------- | -------- | -------------------------------- | ------------------------------ |
|
|
55
|
+
| `secretApiKey` | `string` | Yes | — | Your secret API key (`sessionsight_sec_...`) |
|
|
56
|
+
| `propertyId` | `string` | Yes | — | The property ID to track |
|
|
57
|
+
| `apiUrl` | `string` | No | `https://api.sessionsight.com` | Custom API endpoint |
|
|
58
|
+
|
|
59
|
+
### `SessionSightGoals.increment(goalId, options?)`
|
|
60
|
+
|
|
61
|
+
Increment a goal counter. Returns a `Promise<IncrementResult>`.
|
|
62
|
+
|
|
63
|
+
| Parameter | Type | Required | Default | Description |
|
|
64
|
+
| -------------------- | ------------------------- | -------- | ------- | ------------------------------- |
|
|
65
|
+
| `goalId` | `string` | Yes | — | The goal's slug ID |
|
|
66
|
+
| `options.amount` | `number` | No | `1` | Amount to increment by |
|
|
67
|
+
| `options.value` | `number` | No | — | Monetary value (e.g., purchase amount) |
|
|
68
|
+
| `options.currency` | `string` | No | — | ISO 4217 currency code (e.g., `'USD'`) |
|
|
69
|
+
| `options.visitorId` | `string` | No | — | SessionSight visitor ID for attribution |
|
|
70
|
+
| `options.metadata` | `Record<string, string>` | No | — | Optional context for the event |
|
|
71
|
+
|
|
72
|
+
**Returns:**
|
|
73
|
+
|
|
74
|
+
```typescript
|
|
75
|
+
interface IncrementResult {
|
|
76
|
+
success: boolean;
|
|
77
|
+
error?: string;
|
|
78
|
+
}
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
### `SessionSightGoals.decrement(goalId, options?)`
|
|
82
|
+
|
|
83
|
+
Decrement a goal counter. Returns a `Promise<IncrementResult>`.
|
|
84
|
+
|
|
85
|
+
| Parameter | Type | Required | Default | Description |
|
|
86
|
+
| -------------------- | ------------------------- | -------- | ------- | ------------------------------- |
|
|
87
|
+
| `goalId` | `string` | Yes | — | The goal's slug ID |
|
|
88
|
+
| `options.amount` | `number` | No | `1` | Amount to decrement by |
|
|
89
|
+
| `options.visitorId` | `string` | No | — | SessionSight visitor ID for attribution |
|
|
90
|
+
| `options.metadata` | `Record<string, string>` | No | — | Optional context for the event |
|
|
91
|
+
|
|
92
|
+
### `SessionSightGoals.destroy()`
|
|
93
|
+
|
|
94
|
+
Tear down the SDK instance. Call this during cleanup if needed.
|
|
95
|
+
|
|
96
|
+
## Authentication
|
|
97
|
+
|
|
98
|
+
This SDK uses your **secret API key** (`sessionsight_sec_...`), not the public key. The secret key should only be used in server-side code — never expose it in client-side JavaScript.
|
|
99
|
+
|
|
100
|
+
## Build Outputs
|
|
101
|
+
|
|
102
|
+
| File | Format | Usage |
|
|
103
|
+
| ----------------------------- | ------ | -------------------------------------------------- |
|
|
104
|
+
| `dist/index.js` | ESM | `import SessionSightGoals from '@sessionsight/goals'` |
|
|
105
|
+
| `dist/index.d.ts` | Types | TypeScript type definitions |
|
|
106
|
+
| `dist/sessionsight-goals.js` | IIFE | `<script>` tag → `window.SessionSightGoals` |
|
package/package.json
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@sessionsight/goals",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Goal and conversion tracking SDK for SessionSight.",
|
|
5
|
+
"author": "SessionSight",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"homepage": "https://sessionsight.com",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "https://github.com/SessionSight/sdks.git",
|
|
11
|
+
"directory": "packages/goals"
|
|
12
|
+
},
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/SessionSight/sdks/issues"
|
|
15
|
+
},
|
|
16
|
+
"keywords": [
|
|
17
|
+
"goals",
|
|
18
|
+
"conversion-tracking",
|
|
19
|
+
"analytics",
|
|
20
|
+
"sessionsight"
|
|
21
|
+
],
|
|
22
|
+
"type": "module",
|
|
23
|
+
"main": "./dist/index.js",
|
|
24
|
+
"types": "./dist/index.d.ts",
|
|
25
|
+
"exports": {
|
|
26
|
+
".": {
|
|
27
|
+
"import": "./dist/index.js",
|
|
28
|
+
"types": "./dist/index.d.ts"
|
|
29
|
+
}
|
|
30
|
+
},
|
|
31
|
+
"scripts": {
|
|
32
|
+
"build": "bun build src/index.ts --outdir dist --format esm && bun x tsc --emitDeclarationOnly --declaration --outDir dist"
|
|
33
|
+
},
|
|
34
|
+
"peerDependencies": {
|
|
35
|
+
"typescript": "^5"
|
|
36
|
+
},
|
|
37
|
+
"dependencies": {
|
|
38
|
+
"@sessionsight/sdk-shared": "workspace:*"
|
|
39
|
+
}
|
|
40
|
+
}
|
package/src/client.ts
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import type { GoalsConfig, IncrementOptions, DecrementOptions, IncrementResult } from './types.js';
|
|
2
|
+
import { normalizeApiUrl } from '@sessionsight/sdk-shared';
|
|
3
|
+
|
|
4
|
+
const FETCH_TIMEOUT_MS = 10_000;
|
|
5
|
+
|
|
6
|
+
function fetchWithTimeout(url: string, options: RequestInit): Promise<Response> {
|
|
7
|
+
const controller = new AbortController();
|
|
8
|
+
const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
|
|
9
|
+
return fetch(url, { ...options, signal: controller.signal }).finally(() => clearTimeout(timer));
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export class GoalsClient {
|
|
13
|
+
private apiUrl: string;
|
|
14
|
+
private secretApiKey: string;
|
|
15
|
+
private propertyId: string;
|
|
16
|
+
|
|
17
|
+
constructor(config: GoalsConfig) {
|
|
18
|
+
if (typeof window !== 'undefined' && !('process' in globalThis)) {
|
|
19
|
+
throw new Error('@sessionsight/goals is a server-side SDK and cannot be used in the browser.');
|
|
20
|
+
}
|
|
21
|
+
if (!config.secretApiKey?.trim()) throw new Error('@sessionsight/goals: secretApiKey is required.');
|
|
22
|
+
if (!config.propertyId?.trim()) throw new Error('@sessionsight/goals: propertyId is required.');
|
|
23
|
+
this.secretApiKey = config.secretApiKey;
|
|
24
|
+
this.propertyId = config.propertyId;
|
|
25
|
+
this.apiUrl = normalizeApiUrl(config.apiUrl || '');
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
async increment(goalId: string, options?: IncrementOptions): Promise<IncrementResult> {
|
|
29
|
+
const amount = options?.amount ?? 1;
|
|
30
|
+
if (!Number.isFinite(amount) || amount <= 0) {
|
|
31
|
+
return { success: false, error: 'amount must be a positive finite number' };
|
|
32
|
+
}
|
|
33
|
+
if (options?.value != null && (!Number.isFinite(options.value) || options.value < 0)) {
|
|
34
|
+
return { success: false, error: 'value must be a non-negative finite number' };
|
|
35
|
+
}
|
|
36
|
+
try {
|
|
37
|
+
const res = await fetchWithTimeout(`${this.apiUrl}/v1/goals/increment`, {
|
|
38
|
+
method: 'POST',
|
|
39
|
+
headers: {
|
|
40
|
+
'Content-Type': 'application/json',
|
|
41
|
+
'x-api-key': this.secretApiKey,
|
|
42
|
+
},
|
|
43
|
+
body: JSON.stringify({
|
|
44
|
+
goalId,
|
|
45
|
+
propertyId: this.propertyId,
|
|
46
|
+
amount: options?.amount ?? 1,
|
|
47
|
+
...(options?.value != null ? { value: options.value } : {}),
|
|
48
|
+
...(options?.currency ? { currency: options.currency } : {}),
|
|
49
|
+
...(options?.visitorId ? { visitorId: options.visitorId } : {}),
|
|
50
|
+
...(options?.metadata ? { metadata: options.metadata } : {}),
|
|
51
|
+
}),
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
if (!res.ok) {
|
|
55
|
+
const data = await res.json().catch(() => ({}));
|
|
56
|
+
return { success: false, error: (data as any).error || `HTTP ${res.status}` };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
return { success: true };
|
|
60
|
+
} catch (err) {
|
|
61
|
+
const message = err instanceof Error ? err.message : 'Unknown error';
|
|
62
|
+
console.warn('[SessionSight Goals] Failed to increment goal:', message);
|
|
63
|
+
return { success: false, error: message };
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
async decrement(goalId: string, options?: DecrementOptions): Promise<IncrementResult> {
|
|
68
|
+
const amount = options?.amount ?? 1;
|
|
69
|
+
if (!Number.isFinite(amount) || amount <= 0) {
|
|
70
|
+
return { success: false, error: 'amount must be a positive finite number' };
|
|
71
|
+
}
|
|
72
|
+
try {
|
|
73
|
+
const res = await fetchWithTimeout(`${this.apiUrl}/v1/goals/decrement`, {
|
|
74
|
+
method: 'POST',
|
|
75
|
+
headers: {
|
|
76
|
+
'Content-Type': 'application/json',
|
|
77
|
+
'x-api-key': this.secretApiKey,
|
|
78
|
+
},
|
|
79
|
+
body: JSON.stringify({
|
|
80
|
+
goalId,
|
|
81
|
+
propertyId: this.propertyId,
|
|
82
|
+
amount: options?.amount ?? 1,
|
|
83
|
+
...(options?.visitorId ? { visitorId: options.visitorId } : {}),
|
|
84
|
+
...(options?.metadata ? { metadata: options.metadata } : {}),
|
|
85
|
+
}),
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
if (!res.ok) {
|
|
89
|
+
const data = await res.json().catch(() => ({}));
|
|
90
|
+
return { success: false, error: (data as any).error || `HTTP ${res.status}` };
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
return { success: true };
|
|
94
|
+
} catch (err) {
|
|
95
|
+
const message = err instanceof Error ? err.message : 'Unknown error';
|
|
96
|
+
console.warn('[SessionSight Goals] Failed to decrement goal:', message);
|
|
97
|
+
return { success: false, error: message };
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
destroy(): void {
|
|
102
|
+
// No-op for now; reserved for future cleanup (e.g., batching, intervals)
|
|
103
|
+
}
|
|
104
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { GoalsClient } from './client.js';
|
|
2
|
+
import type { GoalsConfig, IncrementOptions, DecrementOptions, IncrementResult } from './types.js';
|
|
3
|
+
|
|
4
|
+
export { GoalsClient };
|
|
5
|
+
export type { GoalsConfig, IncrementOptions, DecrementOptions, IncrementResult } from './types.js';
|
|
6
|
+
|
|
7
|
+
let instance: GoalsClient | null = null;
|
|
8
|
+
|
|
9
|
+
const SessionSightGoals = {
|
|
10
|
+
init(config: GoalsConfig): void {
|
|
11
|
+
if (instance) {
|
|
12
|
+
console.warn('[SessionSight Goals] Already initialized. Call destroy() first.');
|
|
13
|
+
return;
|
|
14
|
+
}
|
|
15
|
+
instance = new GoalsClient(config);
|
|
16
|
+
},
|
|
17
|
+
|
|
18
|
+
async increment(goalId: string, options?: IncrementOptions): Promise<IncrementResult> {
|
|
19
|
+
if (!instance) {
|
|
20
|
+
console.warn('[SessionSight Goals] Not initialized. Call init() first.');
|
|
21
|
+
return { success: false, error: 'Not initialized' };
|
|
22
|
+
}
|
|
23
|
+
return instance.increment(goalId, options);
|
|
24
|
+
},
|
|
25
|
+
|
|
26
|
+
async decrement(goalId: string, options?: DecrementOptions): Promise<IncrementResult> {
|
|
27
|
+
if (!instance) {
|
|
28
|
+
console.warn('[SessionSight Goals] Not initialized. Call init() first.');
|
|
29
|
+
return { success: false, error: 'Not initialized' };
|
|
30
|
+
}
|
|
31
|
+
return instance.decrement(goalId, options);
|
|
32
|
+
},
|
|
33
|
+
|
|
34
|
+
destroy(): void {
|
|
35
|
+
if (instance) {
|
|
36
|
+
instance.destroy();
|
|
37
|
+
instance = null;
|
|
38
|
+
}
|
|
39
|
+
},
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
export default SessionSightGoals;
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
export interface GoalsConfig {
|
|
2
|
+
secretApiKey: string;
|
|
3
|
+
propertyId: string;
|
|
4
|
+
apiUrl?: string;
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export interface IncrementOptions {
|
|
8
|
+
amount?: number;
|
|
9
|
+
value?: number;
|
|
10
|
+
currency?: string;
|
|
11
|
+
visitorId?: string;
|
|
12
|
+
metadata?: Record<string, string>;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export interface DecrementOptions {
|
|
16
|
+
amount?: number;
|
|
17
|
+
visitorId?: string;
|
|
18
|
+
metadata?: Record<string, string>;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface IncrementResult {
|
|
22
|
+
success: boolean;
|
|
23
|
+
error?: string;
|
|
24
|
+
}
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
import { test, expect, mock, beforeEach } from 'bun:test';
|
|
2
|
+
import { GoalsClient } from '../src/client.js';
|
|
3
|
+
|
|
4
|
+
const originalFetch = globalThis.fetch;
|
|
5
|
+
|
|
6
|
+
beforeEach(() => {
|
|
7
|
+
globalThis.fetch = originalFetch;
|
|
8
|
+
});
|
|
9
|
+
|
|
10
|
+
test('increment sends correct request', async () => {
|
|
11
|
+
const mockFetch = mock(() =>
|
|
12
|
+
Promise.resolve(new Response(JSON.stringify({ success: true }), { status: 200 }))
|
|
13
|
+
);
|
|
14
|
+
globalThis.fetch = mockFetch;
|
|
15
|
+
|
|
16
|
+
const client = new GoalsClient({
|
|
17
|
+
secretApiKey: 'sk_test_123',
|
|
18
|
+
propertyId: 'prop-1',
|
|
19
|
+
apiUrl: 'https://api.example.com',
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
const result = await client.increment('user-signups');
|
|
23
|
+
|
|
24
|
+
expect(result).toEqual({ success: true });
|
|
25
|
+
expect(mockFetch).toHaveBeenCalledTimes(1);
|
|
26
|
+
|
|
27
|
+
const [url, opts] = mockFetch.mock.calls[0] as [string, RequestInit];
|
|
28
|
+
expect(url).toBe('https://api.example.com/v1/goals/increment');
|
|
29
|
+
expect(opts.method).toBe('POST');
|
|
30
|
+
expect(opts.headers).toEqual({
|
|
31
|
+
'Content-Type': 'application/json',
|
|
32
|
+
'x-api-key': 'sk_test_123',
|
|
33
|
+
});
|
|
34
|
+
const body = JSON.parse(opts.body as string);
|
|
35
|
+
expect(body.goalId).toBe('user-signups');
|
|
36
|
+
expect(body.propertyId).toBe('prop-1');
|
|
37
|
+
expect(body.amount).toBe(1);
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
test('increment sends custom amount and metadata', async () => {
|
|
41
|
+
const mockFetch = mock(() =>
|
|
42
|
+
Promise.resolve(new Response(JSON.stringify({ success: true }), { status: 200 }))
|
|
43
|
+
);
|
|
44
|
+
globalThis.fetch = mockFetch;
|
|
45
|
+
|
|
46
|
+
const client = new GoalsClient({
|
|
47
|
+
secretApiKey: 'sk_test_123',
|
|
48
|
+
propertyId: 'prop-1',
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
await client.increment('revenue', { amount: 49, metadata: { plan: 'pro' } });
|
|
52
|
+
|
|
53
|
+
const body = JSON.parse((mockFetch.mock.calls[0] as [string, RequestInit])[1].body as string);
|
|
54
|
+
expect(body.amount).toBe(49);
|
|
55
|
+
expect(body.metadata).toEqual({ plan: 'pro' });
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
test('increment returns error on non-ok response', async () => {
|
|
59
|
+
globalThis.fetch = mock(() =>
|
|
60
|
+
Promise.resolve(new Response(JSON.stringify({ error: 'Goal not found' }), { status: 404 }))
|
|
61
|
+
);
|
|
62
|
+
|
|
63
|
+
const client = new GoalsClient({
|
|
64
|
+
secretApiKey: 'sk_test_123',
|
|
65
|
+
propertyId: 'prop-1',
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
const result = await client.increment('nonexistent');
|
|
69
|
+
expect(result.success).toBe(false);
|
|
70
|
+
expect(result.error).toBe('Goal not found');
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
test('increment returns error on network failure', async () => {
|
|
74
|
+
globalThis.fetch = mock(() => Promise.reject(new Error('Network error')));
|
|
75
|
+
|
|
76
|
+
const client = new GoalsClient({
|
|
77
|
+
secretApiKey: 'sk_test_123',
|
|
78
|
+
propertyId: 'prop-1',
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
const result = await client.increment('user-signups');
|
|
82
|
+
expect(result.success).toBe(false);
|
|
83
|
+
expect(result.error).toBe('Network error');
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
test('strips trailing slash from apiUrl', async () => {
|
|
87
|
+
const mockFetch = mock(() =>
|
|
88
|
+
Promise.resolve(new Response(JSON.stringify({ success: true }), { status: 200 }))
|
|
89
|
+
);
|
|
90
|
+
globalThis.fetch = mockFetch;
|
|
91
|
+
|
|
92
|
+
const client = new GoalsClient({
|
|
93
|
+
secretApiKey: 'sk_test_123',
|
|
94
|
+
propertyId: 'prop-1',
|
|
95
|
+
apiUrl: 'https://api.example.com/',
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
await client.increment('test');
|
|
99
|
+
const url = (mockFetch.mock.calls[0] as [string, RequestInit])[0];
|
|
100
|
+
expect(url).toBe('https://api.example.com/v1/goals/increment');
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
test('increment sends value and currency for revenue attribution', async () => {
|
|
104
|
+
const mockFetch = mock(() =>
|
|
105
|
+
Promise.resolve(new Response(JSON.stringify({ success: true }), { status: 200 }))
|
|
106
|
+
);
|
|
107
|
+
globalThis.fetch = mockFetch;
|
|
108
|
+
|
|
109
|
+
const client = new GoalsClient({
|
|
110
|
+
secretApiKey: 'sk_test_123',
|
|
111
|
+
propertyId: 'prop-1',
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
await client.increment('purchase', { value: 49.99, currency: 'USD', metadata: { sku: 'widget-pro' } });
|
|
115
|
+
|
|
116
|
+
const body = JSON.parse((mockFetch.mock.calls[0] as [string, RequestInit])[1].body as string);
|
|
117
|
+
expect(body.value).toBe(49.99);
|
|
118
|
+
expect(body.currency).toBe('USD');
|
|
119
|
+
expect(body.metadata).toEqual({ sku: 'widget-pro' });
|
|
120
|
+
expect(body.amount).toBe(1);
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
test('increment omits value and currency when not provided', async () => {
|
|
124
|
+
const mockFetch = mock(() =>
|
|
125
|
+
Promise.resolve(new Response(JSON.stringify({ success: true }), { status: 200 }))
|
|
126
|
+
);
|
|
127
|
+
globalThis.fetch = mockFetch;
|
|
128
|
+
|
|
129
|
+
const client = new GoalsClient({
|
|
130
|
+
secretApiKey: 'sk_test_123',
|
|
131
|
+
propertyId: 'prop-1',
|
|
132
|
+
});
|
|
133
|
+
|
|
134
|
+
await client.increment('user-signups', { amount: 5 });
|
|
135
|
+
|
|
136
|
+
const body = JSON.parse((mockFetch.mock.calls[0] as [string, RequestInit])[1].body as string);
|
|
137
|
+
expect(body.value).toBeUndefined();
|
|
138
|
+
expect(body.currency).toBeUndefined();
|
|
139
|
+
expect(body.amount).toBe(5);
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
test('decrement sends correct request', async () => {
|
|
143
|
+
const mockFetch = mock(() =>
|
|
144
|
+
Promise.resolve(new Response(JSON.stringify({ success: true }), { status: 200 }))
|
|
145
|
+
);
|
|
146
|
+
globalThis.fetch = mockFetch;
|
|
147
|
+
|
|
148
|
+
const client = new GoalsClient({
|
|
149
|
+
secretApiKey: 'sk_test_123',
|
|
150
|
+
propertyId: 'prop-1',
|
|
151
|
+
apiUrl: 'https://api.example.com',
|
|
152
|
+
});
|
|
153
|
+
|
|
154
|
+
const result = await client.decrement('user-signups');
|
|
155
|
+
|
|
156
|
+
expect(result).toEqual({ success: true });
|
|
157
|
+
const [url, opts] = mockFetch.mock.calls[0] as [string, RequestInit];
|
|
158
|
+
expect(url).toBe('https://api.example.com/v1/goals/decrement');
|
|
159
|
+
expect(opts.method).toBe('POST');
|
|
160
|
+
const body = JSON.parse(opts.body as string);
|
|
161
|
+
expect(body.goalId).toBe('user-signups');
|
|
162
|
+
expect(body.propertyId).toBe('prop-1');
|
|
163
|
+
expect(body.amount).toBe(1);
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
test('decrement sends custom amount and metadata', async () => {
|
|
167
|
+
const mockFetch = mock(() =>
|
|
168
|
+
Promise.resolve(new Response(JSON.stringify({ success: true }), { status: 200 }))
|
|
169
|
+
);
|
|
170
|
+
globalThis.fetch = mockFetch;
|
|
171
|
+
|
|
172
|
+
const client = new GoalsClient({
|
|
173
|
+
secretApiKey: 'sk_test_123',
|
|
174
|
+
propertyId: 'prop-1',
|
|
175
|
+
});
|
|
176
|
+
|
|
177
|
+
await client.decrement('inventory', { amount: 3, metadata: { reason: 'refund' } });
|
|
178
|
+
|
|
179
|
+
const body = JSON.parse((mockFetch.mock.calls[0] as [string, RequestInit])[1].body as string);
|
|
180
|
+
expect(body.amount).toBe(3);
|
|
181
|
+
expect(body.metadata).toEqual({ reason: 'refund' });
|
|
182
|
+
});
|
|
183
|
+
|
|
184
|
+
test('uses default apiUrl when not provided', async () => {
|
|
185
|
+
const mockFetch = mock(() =>
|
|
186
|
+
Promise.resolve(new Response(JSON.stringify({ success: true }), { status: 200 }))
|
|
187
|
+
);
|
|
188
|
+
globalThis.fetch = mockFetch;
|
|
189
|
+
|
|
190
|
+
const client = new GoalsClient({
|
|
191
|
+
secretApiKey: 'sk_test_123',
|
|
192
|
+
propertyId: 'prop-1',
|
|
193
|
+
});
|
|
194
|
+
|
|
195
|
+
await client.increment('test');
|
|
196
|
+
const url = (mockFetch.mock.calls[0] as [string, RequestInit])[0];
|
|
197
|
+
expect(url).toBe('https://api.sessionsight.com/v1/goals/increment');
|
|
198
|
+
});
|
package/tsconfig.json
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
{
|
|
2
|
+
"extends": "../../tsconfig.json",
|
|
3
|
+
"compilerOptions": {
|
|
4
|
+
"outDir": "./dist",
|
|
5
|
+
"declaration": true,
|
|
6
|
+
"noEmit": false,
|
|
7
|
+
"rootDir": "./src",
|
|
8
|
+
"lib": ["ES2022", "DOM"],
|
|
9
|
+
"module": "ESNext",
|
|
10
|
+
"moduleResolution": "bundler"
|
|
11
|
+
},
|
|
12
|
+
"include": ["src/**/*.ts"]
|
|
13
|
+
}
|