@maksymshypytsia/flags-sdk 0.0.0-stage → 0.1.1
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 +173 -2
- package/dist/hashRollout.d.ts +6 -0
- package/dist/hashRollout.js +31 -0
- package/dist/index.d.ts +22 -0
- package/dist/index.js +48 -0
- package/package.json +53 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 ShipaM
|
|
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
CHANGED
|
@@ -1,3 +1,174 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @maksymshypytsia/flags-sdk
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[](https://www.npmjs.com/package/@maksymshypytsia/flags-sdk)
|
|
4
|
+
[](./LICENSE)
|
|
5
|
+
[](https://nodejs.org)
|
|
6
|
+

|
|
7
|
+
|
|
8
|
+
Tiny JavaScript/TypeScript client for [feature-flags-saas](https://github.com/ShipaM/feature-flags-saas).
|
|
9
|
+
|
|
10
|
+
- **One request.** Flags are fetched once and cached in memory.
|
|
11
|
+
- **Local evaluation.** `isEnabled()` is synchronous: no network, no waiting.
|
|
12
|
+
- **Same answer as the server.** Uses the exact same rollout hash, so a user always lands in the same bucket.
|
|
13
|
+
- **Zero runtime dependencies**, ESM, written in TypeScript (types included).
|
|
14
|
+
- No polling, no WebSocket.
|
|
15
|
+
|
|
16
|
+
## Installation
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
npm install @maksymshypytsia/flags-sdk
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
<details>
|
|
23
|
+
<summary>pnpm / yarn / bun</summary>
|
|
24
|
+
|
|
25
|
+
```bash
|
|
26
|
+
pnpm add @maksymshypytsia/flags-sdk
|
|
27
|
+
yarn add @maksymshypytsia/flags-sdk
|
|
28
|
+
bun add @maksymshypytsia/flags-sdk
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
</details>
|
|
32
|
+
|
|
33
|
+
**Requirements:** Node.js 18+ (or any modern browser) because the SDK uses the built-in `fetch`.
|
|
34
|
+
The package is **ESM only**: use `import`, not `require`.
|
|
35
|
+
|
|
36
|
+
## Quick start
|
|
37
|
+
|
|
38
|
+
```ts
|
|
39
|
+
import { getFlags } from "@maksymshypytsia/flags-sdk";
|
|
40
|
+
|
|
41
|
+
const flags = await getFlags({
|
|
42
|
+
apiKey: process.env.FLAGS_API_KEY!, // dashboard -> Project -> API keys
|
|
43
|
+
userKey: "user-42", // any stable id: user id, email, ...
|
|
44
|
+
baseUrl: "https://flags.example.com", // where the service runs
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
if (flags.isEnabled("new-checkout")) {
|
|
48
|
+
// show the new checkout
|
|
49
|
+
}
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
## How to get the values
|
|
53
|
+
|
|
54
|
+
| Option | Where to get it |
|
|
55
|
+
| --------- | -------------------------------------------------------------------- |
|
|
56
|
+
| `apiKey` | Dashboard -> your project -> **API keys**. Looks like `ffk_prod_...` |
|
|
57
|
+
| `userKey` | Your own stable user identifier (id, email). Never random per visit |
|
|
58
|
+
| `baseUrl` | The address of your feature-flags-saas deployment, no `/api` suffix |
|
|
59
|
+
|
|
60
|
+
Each API key belongs to one environment (`dev`, `staging`, `prod`), so use a separate key per environment.
|
|
61
|
+
|
|
62
|
+
## Usage
|
|
63
|
+
|
|
64
|
+
### Server (Node.js, Next.js route, Express...)
|
|
65
|
+
|
|
66
|
+
```ts
|
|
67
|
+
import { getFlags } from "@maksymshypytsia/flags-sdk";
|
|
68
|
+
|
|
69
|
+
export async function handler(userId: string) {
|
|
70
|
+
const flags = await getFlags({
|
|
71
|
+
apiKey: process.env.FLAGS_API_KEY!,
|
|
72
|
+
userKey: userId,
|
|
73
|
+
baseUrl: process.env.FLAGS_URL!,
|
|
74
|
+
});
|
|
75
|
+
return flags.isEnabled("new-checkout") ? "new" : "old";
|
|
76
|
+
}
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
Calling `getFlags` for many users is cheap: the network request happens only
|
|
80
|
+
once per `baseUrl` + `apiKey`, every other call reuses the cached data
|
|
81
|
+
(parallel calls share the same request).
|
|
82
|
+
|
|
83
|
+
### Refresh the flags
|
|
84
|
+
|
|
85
|
+
Flags are **not** refreshed automatically. When you want fresh data:
|
|
86
|
+
|
|
87
|
+
```ts
|
|
88
|
+
import { clearCache, getFlags } from "@maksymshypytsia/flags-sdk";
|
|
89
|
+
|
|
90
|
+
clearCache(); // forget what we have
|
|
91
|
+
const flags = await getFlags({ apiKey, userKey, baseUrl }); // fetches again
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
### Error handling
|
|
95
|
+
|
|
96
|
+
```ts
|
|
97
|
+
try {
|
|
98
|
+
const flags = await getFlags({ apiKey, userKey, baseUrl });
|
|
99
|
+
} catch (error) {
|
|
100
|
+
// wrong key (HTTP 401), server down, unexpected response...
|
|
101
|
+
// a failed request is never cached, the next call tries again
|
|
102
|
+
}
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
A sensible pattern is to treat "could not load flags" as "all flags off".
|
|
106
|
+
|
|
107
|
+
## API
|
|
108
|
+
|
|
109
|
+
### `getFlags(options): Promise<FlagsClient>`
|
|
110
|
+
|
|
111
|
+
| Option | Type | Description |
|
|
112
|
+
| --------- | -------- | ------------------------------------------------------ |
|
|
113
|
+
| `apiKey` | `string` | Project API key. Sent as `Authorization: Bearer <key>` |
|
|
114
|
+
| `userKey` | `string` | Stable id of the end user |
|
|
115
|
+
| `baseUrl` | `string` | Service URL. A trailing `/` is ignored |
|
|
116
|
+
|
|
117
|
+
Throws `TypeError` if an option is empty, and `Error` if the request fails
|
|
118
|
+
or the response has an unexpected shape.
|
|
119
|
+
|
|
120
|
+
### `client.isEnabled(flagKey): boolean`
|
|
121
|
+
|
|
122
|
+
`true` only if the flag exists, is enabled **and** the user falls inside the
|
|
123
|
+
flag's rollout percentage. Unknown or disabled flags return `false`.
|
|
124
|
+
Synchronous, makes no network requests, always gives the same answer for the same user and flag.
|
|
125
|
+
|
|
126
|
+
### `clearCache(): void`
|
|
127
|
+
|
|
128
|
+
Forgets cached flags; the next `getFlags()` fetches again.
|
|
129
|
+
|
|
130
|
+
### `isEnabledForUser(userKey, flagKey, rollout): boolean`
|
|
131
|
+
|
|
132
|
+
The raw rollout function the server uses. Handy for tests or for evaluating on your own server.
|
|
133
|
+
|
|
134
|
+
## How it works
|
|
135
|
+
|
|
136
|
+
1. `getFlags` sends one `GET {baseUrl}/api/v1/flags` with your API key.
|
|
137
|
+
2. The response (`{ flags: { key: { enabled, rollout } } }`) is cached in memory.
|
|
138
|
+
3. `isEnabled` computes `FNV-1a(userKey + ":" + flagKey) % 100` and compares it with the `rollout` percentage.
|
|
139
|
+
The same input always gives the same bucket, so a user does not flip between old and new.
|
|
140
|
+
|
|
141
|
+
## FAQ
|
|
142
|
+
|
|
143
|
+
**Can I use it in the browser?**
|
|
144
|
+
Yes, if the service allows your origin (CORS). Keep in mind that an API key in
|
|
145
|
+
public frontend code is visible to everyone, so do not use a key you consider secret.
|
|
146
|
+
|
|
147
|
+
**Why does `require()` fail?**
|
|
148
|
+
The package is ESM only. Use `import`, or `await import("@maksymshypytsia/flags-sdk")`.
|
|
149
|
+
|
|
150
|
+
**Why does a user get a different result than my colleague?**
|
|
151
|
+
Rollout depends on `userKey`. Make sure you pass the same stable value everywhere.
|
|
152
|
+
|
|
153
|
+
## Development
|
|
154
|
+
|
|
155
|
+
```bash
|
|
156
|
+
npm install
|
|
157
|
+
npm run typecheck # tsc --noEmit
|
|
158
|
+
npm test # vitest
|
|
159
|
+
npm run build # tsc -> dist/
|
|
160
|
+
npm pack --dry-run # see what goes into the package
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
Try an unpublished build in another project:
|
|
164
|
+
|
|
165
|
+
```bash
|
|
166
|
+
npm pack
|
|
167
|
+
cd ../some-app && npm install ../feature-flags-sdk/maksymshypytsia-flags-sdk-0.1.0.tgz
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
Release: `npm version patch && git push --follow-tags && npm publish`.
|
|
171
|
+
|
|
172
|
+
## License
|
|
173
|
+
|
|
174
|
+
MIT
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/** Fast, non-cryptographic hash. Returns a number from 0 to 2^32 - 1. */
|
|
2
|
+
export declare function fnv1a(input: string): number;
|
|
3
|
+
/** Get a user's bucket from 0 to 99 for a specific flag. */
|
|
4
|
+
export declare function getBucket(userKey: string, flagKey: string): number;
|
|
5
|
+
/** Check if a flag is enabled for a user at the given rollout percentage. */
|
|
6
|
+
export declare function isEnabledForUser(userKey: string, flagKey: string, rolloutPercentage: number): boolean;
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
// Deterministic rollout: the same user and flag always get the same result.
|
|
2
|
+
const FNV_OFFSET_BASIS = 0x811c9dc5; // Initial value for FNV-1a (32-bit).
|
|
3
|
+
const FNV_PRIME = 0x01000193; // FNV-1a multiplication constant.
|
|
4
|
+
const encoder = new TextEncoder();
|
|
5
|
+
/** Fast, non-cryptographic hash. Returns a number from 0 to 2^32 - 1. */
|
|
6
|
+
export function fnv1a(input) {
|
|
7
|
+
let hash = FNV_OFFSET_BASIS;
|
|
8
|
+
// Hash the UTF-8 bytes so different languages get the same result.
|
|
9
|
+
for (const byte of encoder.encode(input)) {
|
|
10
|
+
hash ^= byte; // Mix the byte into the hash.
|
|
11
|
+
hash = Math.imul(hash, FNV_PRIME); // Multiply using 32-bit arithmetic.
|
|
12
|
+
}
|
|
13
|
+
return hash >>> 0; // Convert the result to an unsigned 32-bit number.
|
|
14
|
+
}
|
|
15
|
+
/** Get a user's bucket from 0 to 99 for a specific flag. */
|
|
16
|
+
export function getBucket(userKey, flagKey) {
|
|
17
|
+
// Combine user and flag so each flag gets its own rollout.
|
|
18
|
+
return fnv1a(`${userKey}:${flagKey}`) % 100;
|
|
19
|
+
}
|
|
20
|
+
/** Check if a flag is enabled for a user at the given rollout percentage. */
|
|
21
|
+
export function isEnabledForUser(userKey, flagKey, rolloutPercentage) {
|
|
22
|
+
// Handle edge cases explicitly.
|
|
23
|
+
if (Number.isNaN(rolloutPercentage))
|
|
24
|
+
return false;
|
|
25
|
+
if (rolloutPercentage <= 0)
|
|
26
|
+
return false;
|
|
27
|
+
if (rolloutPercentage >= 100)
|
|
28
|
+
return true;
|
|
29
|
+
// Enable the flag if the user's bucket is inside the rollout range.
|
|
30
|
+
return getBucket(userKey, flagKey) < rolloutPercentage;
|
|
31
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { isEnabledForUser } from "./hashRollout.js";
|
|
2
|
+
export { isEnabledForUser };
|
|
3
|
+
/** One flag exactly as GET /api/v1/flags returns it. */
|
|
4
|
+
export type FlagData = {
|
|
5
|
+
enabled: boolean;
|
|
6
|
+
rollout: number;
|
|
7
|
+
};
|
|
8
|
+
export type GetFlagsOptions = {
|
|
9
|
+
/** Project API key, e.g. "ffk_prod_...". Sent as "Authorization: Bearer <key>". */
|
|
10
|
+
apiKey: string;
|
|
11
|
+
/** Any stable id of the end user (user id, email...). Decides the rollout bucket. */
|
|
12
|
+
userKey: string;
|
|
13
|
+
/** Where the feature-flags service lives, e.g. "https://flags.example.com". */
|
|
14
|
+
baseUrl: string;
|
|
15
|
+
};
|
|
16
|
+
export type FlagsClient = {
|
|
17
|
+
/** true if the flag exists, is enabled and the user is inside its rollout. */
|
|
18
|
+
isEnabled(flagKey: string): boolean;
|
|
19
|
+
};
|
|
20
|
+
/** Forget cached flags. The next getFlags() call fetches again. */
|
|
21
|
+
export declare function clearCache(): void;
|
|
22
|
+
export declare function getFlags(options: GetFlagsOptions): Promise<FlagsClient>;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { isEnabledForUser } from "./hashRollout.js";
|
|
2
|
+
// Re-exported so a server can reuse the exact same rollout logic as the SDK.
|
|
3
|
+
export { isEnabledForUser };
|
|
4
|
+
// In-memory cache: ONE network request per baseUrl + apiKey.
|
|
5
|
+
// We store the Promise, so parallel getFlags() calls share the same request.
|
|
6
|
+
const cache = new Map();
|
|
7
|
+
/** Forget cached flags. The next getFlags() call fetches again. */
|
|
8
|
+
export function clearCache() {
|
|
9
|
+
cache.clear();
|
|
10
|
+
}
|
|
11
|
+
async function fetchFlags(apiKey, baseUrl) {
|
|
12
|
+
const res = await fetch(`${baseUrl}/api/v1/flags`, {
|
|
13
|
+
headers: { Authorization: `Bearer ${apiKey}` },
|
|
14
|
+
});
|
|
15
|
+
if (!res.ok)
|
|
16
|
+
throw new Error(`Failed to load flags: HTTP ${res.status}`);
|
|
17
|
+
const body = (await res.json());
|
|
18
|
+
if (!body || typeof body.flags !== "object" || body.flags === null) {
|
|
19
|
+
throw new Error("Failed to load flags: unexpected response format");
|
|
20
|
+
}
|
|
21
|
+
return body.flags;
|
|
22
|
+
}
|
|
23
|
+
export async function getFlags(options) {
|
|
24
|
+
const { apiKey, userKey, baseUrl } = options;
|
|
25
|
+
if (!apiKey)
|
|
26
|
+
throw new TypeError("getFlags: apiKey is required");
|
|
27
|
+
if (!userKey)
|
|
28
|
+
throw new TypeError("getFlags: userKey is required");
|
|
29
|
+
if (!baseUrl)
|
|
30
|
+
throw new TypeError("getFlags: baseUrl is required");
|
|
31
|
+
const base = baseUrl.replace(/\/+$/, ""); // "https://x.com/" -> "https://x.com"
|
|
32
|
+
const cacheKey = `${base}|${apiKey}`;
|
|
33
|
+
let pending = cache.get(cacheKey);
|
|
34
|
+
if (!pending) {
|
|
35
|
+
pending = fetchFlags(apiKey, base);
|
|
36
|
+
cache.set(cacheKey, pending);
|
|
37
|
+
pending.catch(() => cache.delete(cacheKey)); // never cache a failure
|
|
38
|
+
}
|
|
39
|
+
const data = await pending;
|
|
40
|
+
return {
|
|
41
|
+
isEnabled(flagKey) {
|
|
42
|
+
const flag = data[flagKey];
|
|
43
|
+
if (!flag || !flag.enabled)
|
|
44
|
+
return false; // unknown or switched off
|
|
45
|
+
return isEnabledForUser(userKey, flagKey, flag.rollout);
|
|
46
|
+
},
|
|
47
|
+
};
|
|
48
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,55 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@maksymshypytsia/flags-sdk",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Tiny client SDK for feature-flags-saas: one fetch, local evaluation.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./dist/index.js",
|
|
7
|
+
"types": "./dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"import": "./dist/index.js"
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
"files": [
|
|
15
|
+
"dist"
|
|
16
|
+
],
|
|
17
|
+
"sideEffects": false,
|
|
18
|
+
"engines": {
|
|
19
|
+
"node": ">=18"
|
|
20
|
+
},
|
|
21
|
+
"publishConfig": {
|
|
22
|
+
"access": "public"
|
|
23
|
+
},
|
|
24
|
+
"scripts": {
|
|
25
|
+
"prebuild": "node -e \"require('fs').rmSync('dist',{recursive:true,force:true})\"",
|
|
26
|
+
"build": "tsc -p tsconfig.build.json",
|
|
27
|
+
"typecheck": "tsc --noEmit",
|
|
28
|
+
"test": "vitest run",
|
|
29
|
+
"prepare": "npm run build",
|
|
30
|
+
"prepublishOnly": "npm run typecheck && npm test"
|
|
31
|
+
},
|
|
32
|
+
"keywords": [
|
|
33
|
+
"feature-flags",
|
|
34
|
+
"feature-toggles",
|
|
35
|
+
"feature-flag",
|
|
36
|
+
"rollout",
|
|
37
|
+
"sdk",
|
|
38
|
+
"typescript"
|
|
39
|
+
],
|
|
40
|
+
"license": "MIT",
|
|
41
|
+
"repository": {
|
|
42
|
+
"type": "git",
|
|
43
|
+
"url": "git+https://github.com/ShipaM/feature-flags-sdk.git"
|
|
44
|
+
},
|
|
45
|
+
"devDependencies": {
|
|
46
|
+
"@types/node": "^22.20.5",
|
|
47
|
+
"typescript": "^5",
|
|
48
|
+
"vitest": "^5.0.5"
|
|
49
|
+
},
|
|
50
|
+
"homepage": "https://github.com/ShipaM/feature-flags-sdk#readme",
|
|
51
|
+
"bugs": {
|
|
52
|
+
"url": "https://github.com/ShipaM/feature-flags-sdk/issues"
|
|
53
|
+
},
|
|
54
|
+
"author": "Maksym Shypytsia"
|
|
55
|
+
}
|