@sessionsight/flags 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 +109 -0
- package/package.json +49 -0
- package/src/client.ts +118 -0
- package/src/index.ts +51 -0
- package/src/types.ts +36 -0
- package/test/client.test.ts +215 -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,109 @@
|
|
|
1
|
+
# @sessionsight/flags
|
|
2
|
+
|
|
3
|
+
Server-side SDK for evaluating feature flags with segment-based targeting in SessionSight.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install @sessionsight/flags
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Quick Start
|
|
12
|
+
|
|
13
|
+
```typescript
|
|
14
|
+
import FeatureFlags from '@sessionsight/flags';
|
|
15
|
+
|
|
16
|
+
await FeatureFlags.init({
|
|
17
|
+
secretApiKey: 'sessionsight_sec_your_secret_key',
|
|
18
|
+
propertyId: 'your-property-id',
|
|
19
|
+
environment: 'production',
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
// Boolean flag
|
|
23
|
+
const showBeta = FeatureFlags.getBooleanFlag('beta-ui', false);
|
|
24
|
+
|
|
25
|
+
// String flag
|
|
26
|
+
const bannerText = FeatureFlags.getStringFlag('banner-message', 'Welcome!');
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
## API Reference
|
|
30
|
+
|
|
31
|
+
### `FeatureFlags.init(config, context?)`
|
|
32
|
+
|
|
33
|
+
Initialize the SDK. Fetches flag configuration and evaluates flags. Returns a Promise that must be awaited before calling other methods.
|
|
34
|
+
|
|
35
|
+
| Option | Type | Required | Default | Description |
|
|
36
|
+
| --- | --- | --- | --- | --- |
|
|
37
|
+
| `secretApiKey` | `string` | Yes | - | Your secret API key (`sessionsight_sec_...`) |
|
|
38
|
+
| `propertyId` | `string` | Yes | - | The property ID to evaluate flags for |
|
|
39
|
+
| `environment` | `string` | Yes | - | Environment name (e.g., `production`, `staging`) |
|
|
40
|
+
| `apiUrl` | `string` | No | `https://api.sessionsight.com` | Custom API endpoint |
|
|
41
|
+
|
|
42
|
+
The optional `context` parameter allows passing an evaluation context on init:
|
|
43
|
+
|
|
44
|
+
| Property | Type | Description |
|
|
45
|
+
| --- | --- | --- |
|
|
46
|
+
| `userId` | `string` | Your user's ID. Used for percentage rollouts and user targeting. |
|
|
47
|
+
| `visitorId` | `string` | SessionSight visitor ID. Enables segment-based targeting via `segment_match` rules. |
|
|
48
|
+
| Custom properties | `string \| number \| boolean` | Any additional properties for targeting rules. |
|
|
49
|
+
|
|
50
|
+
### `FeatureFlags.getBooleanFlag(key, defaultValue)`
|
|
51
|
+
|
|
52
|
+
Get a boolean flag value. Returns `defaultValue` if the flag doesn't exist, is disabled, or hasn't been initialized.
|
|
53
|
+
|
|
54
|
+
```typescript
|
|
55
|
+
const showFeature = FeatureFlags.getBooleanFlag('new-feature', false);
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
### `FeatureFlags.getStringFlag(key, defaultValue)`
|
|
59
|
+
|
|
60
|
+
Get a string flag value. Returns `defaultValue` if the flag doesn't exist, is disabled, or hasn't been initialized.
|
|
61
|
+
|
|
62
|
+
```typescript
|
|
63
|
+
const theme = FeatureFlags.getStringFlag('theme', 'light');
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
### `FeatureFlags.refresh(context?)`
|
|
67
|
+
|
|
68
|
+
Re-evaluate flags with a new context. Use this for per-request targeting with visitor or user attributes.
|
|
69
|
+
|
|
70
|
+
```typescript
|
|
71
|
+
await FeatureFlags.refresh({
|
|
72
|
+
visitorId: 'visitor-uuid',
|
|
73
|
+
userId: 'user-123',
|
|
74
|
+
plan: 'enterprise',
|
|
75
|
+
});
|
|
76
|
+
const hasAccess = FeatureFlags.getBooleanFlag('advanced-analytics', false);
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
### `FeatureFlags.destroy()`
|
|
80
|
+
|
|
81
|
+
Tear down the SDK instance. Call this during cleanup if needed.
|
|
82
|
+
|
|
83
|
+
## Per-Request Targeting
|
|
84
|
+
|
|
85
|
+
For web applications serving multiple users, call `refresh()` with the current user's context on each request:
|
|
86
|
+
|
|
87
|
+
```typescript
|
|
88
|
+
// Express middleware example
|
|
89
|
+
app.use(async (req, res, next) => {
|
|
90
|
+
await FeatureFlags.refresh({
|
|
91
|
+
visitorId: req.cookies.ss_vid,
|
|
92
|
+
userId: req.user?.id,
|
|
93
|
+
});
|
|
94
|
+
next();
|
|
95
|
+
});
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
The `visitorId` comes from the `ss_vid` cookie set by the Insights SDK on the frontend. Pass it to enable segment-based targeting rules configured in the SessionSight dashboard.
|
|
99
|
+
|
|
100
|
+
## Authentication
|
|
101
|
+
|
|
102
|
+
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.
|
|
103
|
+
|
|
104
|
+
## Build Outputs
|
|
105
|
+
|
|
106
|
+
| File | Format | Usage |
|
|
107
|
+
| --- | --- | --- |
|
|
108
|
+
| `dist/index.js` | ESM | `import FeatureFlags from '@sessionsight/flags'` |
|
|
109
|
+
| `dist/index.d.ts` | Types | TypeScript type definitions |
|
package/package.json
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@sessionsight/flags",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Feature flags 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/flags"
|
|
12
|
+
},
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/SessionSight/sdks/issues"
|
|
15
|
+
},
|
|
16
|
+
"keywords": [
|
|
17
|
+
"feature-flags",
|
|
18
|
+
"feature-toggles",
|
|
19
|
+
"sessionsight"
|
|
20
|
+
],
|
|
21
|
+
"type": "module",
|
|
22
|
+
"main": "./src/index.ts",
|
|
23
|
+
"types": "./src/index.ts",
|
|
24
|
+
"exports": {
|
|
25
|
+
".": {
|
|
26
|
+
"import": "./src/index.ts",
|
|
27
|
+
"types": "./src/index.ts"
|
|
28
|
+
}
|
|
29
|
+
},
|
|
30
|
+
"publishConfig": {
|
|
31
|
+
"main": "./dist/index.js",
|
|
32
|
+
"types": "./dist/index.d.ts",
|
|
33
|
+
"exports": {
|
|
34
|
+
".": {
|
|
35
|
+
"import": "./dist/index.js",
|
|
36
|
+
"types": "./dist/index.d.ts"
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
},
|
|
40
|
+
"scripts": {
|
|
41
|
+
"build": "bun build src/index.ts --outdir dist --format esm && bun x tsc --emitDeclarationOnly --declaration --outDir dist"
|
|
42
|
+
},
|
|
43
|
+
"peerDependencies": {
|
|
44
|
+
"typescript": "^5"
|
|
45
|
+
},
|
|
46
|
+
"dependencies": {
|
|
47
|
+
"@sessionsight/sdk-shared": "workspace:*"
|
|
48
|
+
}
|
|
49
|
+
}
|
package/src/client.ts
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import type { FeatureFlagConfig, FlagEvaluationContext, EvaluatedFlags, FlagListResult } from './types.js';
|
|
2
|
+
import { normalizeApiUrl, setRegistryValue } 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 FeatureFlagClient {
|
|
13
|
+
private apiUrl: string;
|
|
14
|
+
private secretApiKey: string;
|
|
15
|
+
private propertyId: string;
|
|
16
|
+
private environment: string;
|
|
17
|
+
private flags: EvaluatedFlags = {};
|
|
18
|
+
private context: FlagEvaluationContext = {};
|
|
19
|
+
private initialized = false;
|
|
20
|
+
|
|
21
|
+
constructor(config: FeatureFlagConfig) {
|
|
22
|
+
if (typeof window !== 'undefined' && !('process' in globalThis)) {
|
|
23
|
+
throw new Error('@sessionsight/flags is a server-side SDK and cannot be used in the browser.');
|
|
24
|
+
}
|
|
25
|
+
if (!config.secretApiKey?.trim()) throw new Error('@sessionsight/flags: secretApiKey is required.');
|
|
26
|
+
if (!config.propertyId?.trim()) throw new Error('@sessionsight/flags: propertyId is required.');
|
|
27
|
+
if (!config.environment?.trim()) throw new Error('@sessionsight/flags: environment is required.');
|
|
28
|
+
this.secretApiKey = config.secretApiKey;
|
|
29
|
+
this.propertyId = config.propertyId;
|
|
30
|
+
this.environment = config.environment;
|
|
31
|
+
this.apiUrl = normalizeApiUrl(config.apiUrl || '');
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
async init(context?: FlagEvaluationContext): Promise<void> {
|
|
35
|
+
if (context) this.context = context;
|
|
36
|
+
await this.fetchFlags();
|
|
37
|
+
this.initialized = true;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
getBooleanFlag(key: string, defaultValue: boolean): boolean {
|
|
41
|
+
const flag = this.flags[key];
|
|
42
|
+
if (!flag || flag.type !== 'boolean') return defaultValue;
|
|
43
|
+
return typeof flag.value === 'boolean' ? flag.value : defaultValue;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
getStringFlag(key: string, defaultValue: string): string {
|
|
47
|
+
const flag = this.flags[key];
|
|
48
|
+
if (!flag || flag.type !== 'string') return defaultValue;
|
|
49
|
+
return typeof flag.value === 'string' ? flag.value : defaultValue;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
async refresh(context?: FlagEvaluationContext): Promise<void> {
|
|
53
|
+
if (context) this.context = { ...this.context, ...context };
|
|
54
|
+
await this.fetchFlags();
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
async getFlags(): Promise<FlagListResult> {
|
|
58
|
+
try {
|
|
59
|
+
const res = await fetchWithTimeout(`${this.apiUrl}/v1/flags/list?propertyId=${encodeURIComponent(this.propertyId)}`, {
|
|
60
|
+
method: 'GET',
|
|
61
|
+
headers: { 'x-api-key': this.secretApiKey },
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
if (!res.ok) {
|
|
65
|
+
console.warn(`[SessionSight Flags] Failed to list flags: ${res.status}`);
|
|
66
|
+
return { flags: [] };
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const data = await res.json();
|
|
70
|
+
return { flags: data.flags || [] };
|
|
71
|
+
} catch (err) {
|
|
72
|
+
console.warn('[SessionSight Flags] Failed to list flags:', err);
|
|
73
|
+
return { flags: [] };
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
destroy(): void {
|
|
78
|
+
this.flags = {};
|
|
79
|
+
this.context = {};
|
|
80
|
+
this.initialized = false;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
isInitialized(): boolean {
|
|
84
|
+
return this.initialized;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
private async fetchFlags(): Promise<void> {
|
|
88
|
+
try {
|
|
89
|
+
const res = await fetchWithTimeout(`${this.apiUrl}/v1/flags/evaluate`, {
|
|
90
|
+
method: 'POST',
|
|
91
|
+
headers: {
|
|
92
|
+
'Content-Type': 'application/json',
|
|
93
|
+
'x-api-key': this.secretApiKey,
|
|
94
|
+
},
|
|
95
|
+
body: JSON.stringify({
|
|
96
|
+
propertyId: this.propertyId,
|
|
97
|
+
environment: this.environment,
|
|
98
|
+
context: this.context,
|
|
99
|
+
}),
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
if (!res.ok) {
|
|
103
|
+
console.warn(`[SessionSight Flags] Failed to fetch flags: ${res.status}`);
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
const data = await res.json();
|
|
108
|
+
this.flags = data.flags || {};
|
|
109
|
+
|
|
110
|
+
// Write opaque evaluation token to cross-SDK registry for insights SDK to pick up
|
|
111
|
+
if (data.evaluationToken) {
|
|
112
|
+
setRegistryValue('flagEvaluationToken', data.evaluationToken);
|
|
113
|
+
}
|
|
114
|
+
} catch (err) {
|
|
115
|
+
console.warn('[SessionSight Flags] Failed to fetch flags:', err);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { FeatureFlagClient } from './client.js';
|
|
2
|
+
import type { FeatureFlagConfig, FlagEvaluationContext } from './types.js';
|
|
3
|
+
|
|
4
|
+
export { FeatureFlagClient };
|
|
5
|
+
export type { FeatureFlagConfig, FlagEvaluationContext, EvaluatedFlag, EvaluatedFlags } from './types.js';
|
|
6
|
+
|
|
7
|
+
let instance: FeatureFlagClient | null = null;
|
|
8
|
+
|
|
9
|
+
const FeatureFlags = {
|
|
10
|
+
async init(config: FeatureFlagConfig, context?: FlagEvaluationContext): Promise<void> {
|
|
11
|
+
if (instance) {
|
|
12
|
+
console.warn('[SessionSight Flags] Already initialized. Call destroy() first.');
|
|
13
|
+
return;
|
|
14
|
+
}
|
|
15
|
+
instance = new FeatureFlagClient(config);
|
|
16
|
+
await instance.init(context);
|
|
17
|
+
},
|
|
18
|
+
|
|
19
|
+
getBooleanFlag(key: string, defaultValue: boolean): boolean {
|
|
20
|
+
if (!instance) {
|
|
21
|
+
console.warn('[SessionSight Flags] Not initialized. Call init() first.');
|
|
22
|
+
return defaultValue;
|
|
23
|
+
}
|
|
24
|
+
return instance.getBooleanFlag(key, defaultValue);
|
|
25
|
+
},
|
|
26
|
+
|
|
27
|
+
getStringFlag(key: string, defaultValue: string): string {
|
|
28
|
+
if (!instance) {
|
|
29
|
+
console.warn('[SessionSight Flags] Not initialized. Call init() first.');
|
|
30
|
+
return defaultValue;
|
|
31
|
+
}
|
|
32
|
+
return instance.getStringFlag(key, defaultValue);
|
|
33
|
+
},
|
|
34
|
+
|
|
35
|
+
async refresh(context?: FlagEvaluationContext): Promise<void> {
|
|
36
|
+
if (!instance) {
|
|
37
|
+
console.warn('[SessionSight Flags] Not initialized. Call init() first.');
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
await instance.refresh(context);
|
|
41
|
+
},
|
|
42
|
+
|
|
43
|
+
destroy(): void {
|
|
44
|
+
if (instance) {
|
|
45
|
+
instance.destroy();
|
|
46
|
+
instance = null;
|
|
47
|
+
}
|
|
48
|
+
},
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
export default FeatureFlags;
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
export interface FeatureFlagConfig {
|
|
2
|
+
secretApiKey: string;
|
|
3
|
+
propertyId: string;
|
|
4
|
+
environment: string;
|
|
5
|
+
apiUrl?: string;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export interface FlagEvaluationContext {
|
|
9
|
+
userId?: string;
|
|
10
|
+
/** Set visitorId to enable segment-based targeting via segment_match rules */
|
|
11
|
+
visitorId?: string;
|
|
12
|
+
[key: string]: string | number | boolean | undefined;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export interface EvaluatedFlag {
|
|
16
|
+
value: string | boolean;
|
|
17
|
+
type: 'boolean' | 'string';
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface EvaluatedFlags {
|
|
21
|
+
[flagKey: string]: EvaluatedFlag;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface FlagDefinition {
|
|
25
|
+
id: string;
|
|
26
|
+
key: string;
|
|
27
|
+
name: string;
|
|
28
|
+
description?: string;
|
|
29
|
+
type: 'boolean' | 'string';
|
|
30
|
+
defaultValue: string | boolean;
|
|
31
|
+
createdAt: number;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface FlagListResult {
|
|
35
|
+
flags: FlagDefinition[];
|
|
36
|
+
}
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
import { test, expect, describe, beforeEach, mock } from 'bun:test';
|
|
2
|
+
import { FeatureFlagClient } from '../src/client';
|
|
3
|
+
|
|
4
|
+
// Mock global fetch
|
|
5
|
+
const mockFetch = mock(() => Promise.resolve(new Response()));
|
|
6
|
+
|
|
7
|
+
globalThis.fetch = mockFetch as any;
|
|
8
|
+
|
|
9
|
+
function mockFetchResponse(data: any, status = 200) {
|
|
10
|
+
mockFetch.mockResolvedValue(new Response(JSON.stringify(data), {
|
|
11
|
+
status,
|
|
12
|
+
headers: { 'Content-Type': 'application/json' },
|
|
13
|
+
}));
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
describe('FeatureFlagClient', () => {
|
|
17
|
+
beforeEach(() => {
|
|
18
|
+
mockFetch.mockReset();
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
test('init fetches flags and marks as initialized', async () => {
|
|
22
|
+
mockFetchResponse({
|
|
23
|
+
flags: {
|
|
24
|
+
'dark-mode': { value: true, type: 'boolean' },
|
|
25
|
+
'variant': { value: 'b', type: 'string' },
|
|
26
|
+
},
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
const client = new FeatureFlagClient({
|
|
30
|
+
secretApiKey: 'test-key',
|
|
31
|
+
environment: 'production',
|
|
32
|
+
propertyId: 'test-prop',
|
|
33
|
+
apiUrl: 'http://localhost:3001',
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
expect(client.isInitialized()).toBe(false);
|
|
37
|
+
await client.init({ userId: 'u1' });
|
|
38
|
+
expect(client.isInitialized()).toBe(true);
|
|
39
|
+
|
|
40
|
+
// Verify fetch was called correctly
|
|
41
|
+
expect(mockFetch).toHaveBeenCalledTimes(1);
|
|
42
|
+
const [url, opts] = mockFetch.mock.calls[0] as any[];
|
|
43
|
+
expect(url).toBe('http://localhost:3001/v1/flags/evaluate');
|
|
44
|
+
expect(opts.method).toBe('POST');
|
|
45
|
+
expect(opts.headers['x-api-key']).toBe('test-key');
|
|
46
|
+
const body = JSON.parse(opts.body);
|
|
47
|
+
expect(body.environment).toBe('production');
|
|
48
|
+
expect(body.context.userId).toBe('u1');
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
test('getBooleanFlag returns value when type matches', async () => {
|
|
52
|
+
mockFetchResponse({
|
|
53
|
+
flags: { 'dark-mode': { value: true, type: 'boolean' } },
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
const client = new FeatureFlagClient({ secretApiKey: 'k', environment: 'prod', propertyId: 'test-prop', apiUrl: 'http://localhost:3001' });
|
|
57
|
+
await client.init();
|
|
58
|
+
|
|
59
|
+
expect(client.getBooleanFlag('dark-mode', false)).toBe(true);
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
test('getBooleanFlag returns default when flag missing', async () => {
|
|
63
|
+
mockFetchResponse({ flags: {} });
|
|
64
|
+
|
|
65
|
+
const client = new FeatureFlagClient({ secretApiKey: 'k', environment: 'prod', propertyId: 'test-prop', apiUrl: 'http://localhost:3001' });
|
|
66
|
+
await client.init();
|
|
67
|
+
|
|
68
|
+
expect(client.getBooleanFlag('missing', false)).toBe(false);
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
test('getBooleanFlag returns default when type is string', async () => {
|
|
72
|
+
mockFetchResponse({
|
|
73
|
+
flags: { 'variant': { value: 'a', type: 'string' } },
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
const client = new FeatureFlagClient({ secretApiKey: 'k', environment: 'prod', propertyId: 'test-prop', apiUrl: 'http://localhost:3001' });
|
|
77
|
+
await client.init();
|
|
78
|
+
|
|
79
|
+
expect(client.getBooleanFlag('variant', false)).toBe(false);
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
test('getStringFlag returns value when type matches', async () => {
|
|
83
|
+
mockFetchResponse({
|
|
84
|
+
flags: { 'variant': { value: 'checkout-b', type: 'string' } },
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
const client = new FeatureFlagClient({ secretApiKey: 'k', environment: 'prod', propertyId: 'test-prop', apiUrl: 'http://localhost:3001' });
|
|
88
|
+
await client.init();
|
|
89
|
+
|
|
90
|
+
expect(client.getStringFlag('variant', 'control')).toBe('checkout-b');
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
test('getStringFlag returns default when flag missing', async () => {
|
|
94
|
+
mockFetchResponse({ flags: {} });
|
|
95
|
+
|
|
96
|
+
const client = new FeatureFlagClient({ secretApiKey: 'k', environment: 'prod', propertyId: 'test-prop', apiUrl: 'http://localhost:3001' });
|
|
97
|
+
await client.init();
|
|
98
|
+
|
|
99
|
+
expect(client.getStringFlag('missing', 'default')).toBe('default');
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
test('getStringFlag returns default when type is boolean', async () => {
|
|
103
|
+
mockFetchResponse({
|
|
104
|
+
flags: { 'toggle': { value: true, type: 'boolean' } },
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
const client = new FeatureFlagClient({ secretApiKey: 'k', environment: 'prod', propertyId: 'test-prop', apiUrl: 'http://localhost:3001' });
|
|
108
|
+
await client.init();
|
|
109
|
+
|
|
110
|
+
expect(client.getStringFlag('toggle', 'fallback')).toBe('fallback');
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
test('refresh re-fetches flags with updated context', async () => {
|
|
114
|
+
mockFetchResponse({ flags: { 'f': { value: false, type: 'boolean' } } });
|
|
115
|
+
|
|
116
|
+
const client = new FeatureFlagClient({ secretApiKey: 'k', environment: 'prod', propertyId: 'test-prop', apiUrl: 'http://localhost:3001' });
|
|
117
|
+
await client.init({ userId: 'u1' });
|
|
118
|
+
|
|
119
|
+
mockFetchResponse({ flags: { 'f': { value: true, type: 'boolean' } } });
|
|
120
|
+
await client.refresh({ userId: 'u2' });
|
|
121
|
+
|
|
122
|
+
expect(mockFetch).toHaveBeenCalledTimes(2);
|
|
123
|
+
expect(client.getBooleanFlag('f', false)).toBe(true);
|
|
124
|
+
|
|
125
|
+
// Verify second call has updated context
|
|
126
|
+
const [, opts] = mockFetch.mock.calls[1] as any[];
|
|
127
|
+
const body = JSON.parse(opts.body);
|
|
128
|
+
expect(body.context.userId).toBe('u2');
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
test('destroy clears state', async () => {
|
|
132
|
+
mockFetchResponse({ flags: { 'f': { value: true, type: 'boolean' } } });
|
|
133
|
+
|
|
134
|
+
const client = new FeatureFlagClient({ secretApiKey: 'k', environment: 'prod', propertyId: 'test-prop', apiUrl: 'http://localhost:3001' });
|
|
135
|
+
await client.init();
|
|
136
|
+
|
|
137
|
+
expect(client.getBooleanFlag('f', false)).toBe(true);
|
|
138
|
+
expect(client.isInitialized()).toBe(true);
|
|
139
|
+
|
|
140
|
+
client.destroy();
|
|
141
|
+
|
|
142
|
+
expect(client.isInitialized()).toBe(false);
|
|
143
|
+
expect(client.getBooleanFlag('f', false)).toBe(false);
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
test('handles fetch failure gracefully', async () => {
|
|
147
|
+
mockFetch.mockRejectedValue(new Error('network error'));
|
|
148
|
+
|
|
149
|
+
const client = new FeatureFlagClient({ secretApiKey: 'k', environment: 'prod', propertyId: 'test-prop', apiUrl: 'http://localhost:3001' });
|
|
150
|
+
await client.init(); // should not throw
|
|
151
|
+
|
|
152
|
+
// Returns defaults since no flags were loaded
|
|
153
|
+
expect(client.getBooleanFlag('anything', true)).toBe(true);
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
test('handles non-ok response gracefully', async () => {
|
|
157
|
+
mockFetch.mockResolvedValue(new Response('', { status: 500 }));
|
|
158
|
+
|
|
159
|
+
const client = new FeatureFlagClient({ secretApiKey: 'k', environment: 'prod', propertyId: 'test-prop', apiUrl: 'http://localhost:3001' });
|
|
160
|
+
await client.init(); // should not throw
|
|
161
|
+
|
|
162
|
+
expect(client.getStringFlag('anything', 'default')).toBe('default');
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
test('strips trailing slash from apiUrl', async () => {
|
|
166
|
+
mockFetchResponse({ flags: {} });
|
|
167
|
+
|
|
168
|
+
const client = new FeatureFlagClient({ secretApiKey: 'k', environment: 'prod', propertyId: 'test-prop', apiUrl: 'http://localhost:3001/' });
|
|
169
|
+
await client.init();
|
|
170
|
+
|
|
171
|
+
const [url] = mockFetch.mock.calls[0] as any[];
|
|
172
|
+
expect(url).toBe('http://localhost:3001/v1/flags/evaluate');
|
|
173
|
+
});
|
|
174
|
+
|
|
175
|
+
test('getFlags returns flag definitions', async () => {
|
|
176
|
+
const flagsData = {
|
|
177
|
+
flags: [
|
|
178
|
+
{ id: 'f1', key: 'dark-mode', name: 'Dark Mode', type: 'boolean', defaultValue: false, createdAt: 1000 },
|
|
179
|
+
{ id: 'f2', key: 'cta-color', name: 'CTA Color', type: 'string', defaultValue: 'blue', createdAt: 2000 },
|
|
180
|
+
],
|
|
181
|
+
};
|
|
182
|
+
mockFetchResponse(flagsData);
|
|
183
|
+
|
|
184
|
+
const client = new FeatureFlagClient({ secretApiKey: 'test-key', environment: 'prod', propertyId: 'prop-1', apiUrl: 'http://localhost:3001' });
|
|
185
|
+
const result = await client.getFlags();
|
|
186
|
+
|
|
187
|
+
expect(result.flags).toHaveLength(2);
|
|
188
|
+
expect(result.flags[0].key).toBe('dark-mode');
|
|
189
|
+
expect(result.flags[1].key).toBe('cta-color');
|
|
190
|
+
|
|
191
|
+
const [url, opts] = mockFetch.mock.calls[0] as any[];
|
|
192
|
+
expect(url).toBe('http://localhost:3001/v1/flags/list?propertyId=prop-1');
|
|
193
|
+
expect(opts.method).toBe('GET');
|
|
194
|
+
expect(opts.headers['x-api-key']).toBe('test-key');
|
|
195
|
+
});
|
|
196
|
+
|
|
197
|
+
test('getFlags returns empty array on failure', async () => {
|
|
198
|
+
mockFetch.mockRejectedValue(new Error('network error'));
|
|
199
|
+
|
|
200
|
+
const client = new FeatureFlagClient({ secretApiKey: 'k', environment: 'prod', propertyId: 'p1', apiUrl: 'http://localhost:3001' });
|
|
201
|
+
const result = await client.getFlags();
|
|
202
|
+
|
|
203
|
+
expect(result.flags).toEqual([]);
|
|
204
|
+
});
|
|
205
|
+
|
|
206
|
+
test('defaults apiUrl to production', async () => {
|
|
207
|
+
mockFetchResponse({ flags: {} });
|
|
208
|
+
|
|
209
|
+
const client = new FeatureFlagClient({ secretApiKey: 'k', environment: 'prod', propertyId: 'test-prop' });
|
|
210
|
+
await client.init();
|
|
211
|
+
|
|
212
|
+
const [url] = mockFetch.mock.calls[0] as any[];
|
|
213
|
+
expect(url).toBe('https://api.sessionsight.com/v1/flags/evaluate');
|
|
214
|
+
});
|
|
215
|
+
});
|
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
|
+
}
|