obsidianlab-sdk
v1.0.0
Published
Official JavaScript/TypeScript SDK for ObsidianLab Feature Flag Management
Downloads
52
Maintainers
Readme
ObsidianLab SDK
Official JavaScript/TypeScript SDK for ObsidianLab - Feature Flag Management System.
Features
- Type-safe - Full TypeScript support
- Fast - Local evaluation with caching
- Targeting - Advanced user targeting with 9+ operators
- Rollout - Percentage-based rollouts with consistent hashing
- React Hooks - Built-in React support
- Auto-refresh - Optional polling for flag updates
- Lightweight - Zero dependencies (except crypto)
Installation
npm install obsidianlab-sdkQuick Start
Node.js / Express
const { ObsidianLabClient } = require("obsidianlab-sdk");
// Initialize client
const client = new ObsidianLabClient({
sdkKey: "pk_prod_your_sdk_key_here",
apiUrl: "https://api.obsidianlab.io/api",
});
await client.initialize();
// Check flag
const isEnabled = await client.isEnabled("new-feature", {
userId: "user_123",
userType: "premium",
});
if (isEnabled) {
// Show new feature
}React
import { ObsidianLabProvider, useFlag } from "obsidianlab-sdk";
function App() {
return (
<ObsidianLabProvider config={{ sdkKey: "pk_prod_xxx" }}>
<Dashboard />
</ObsidianLabProvider>
);
}
function Dashboard() {
const { isEnabled } = useFlag("new-feature", { userId: "user_123" });
return <div>{isEnabled && <NewFeature />}</div>;
}API Reference
ObsidianLabClient
Constructor
new ObsidianLabClient(config: ObsidianLabConfig)Config Options:
| Option | Type | Default | Description |
| ----------------- | ---------- | --------------------------- | ------------------------------------ |
| sdkKey | string | required | Your project SDK key |
| apiUrl | string | http://localhost:8000/api | ObsidianLab API URL |
| enableCache | boolean | true | Enable local caching |
| cacheTTL | number | 60000 | Cache TTL in ms |
| pollingInterval | number | 0 | Auto-refresh interval (0 = disabled) |
| onError | function | console.error | Error handler |
| onFlagsUpdated | function | undefined | Callback when flags update |
Methods
initialize()
Fetches all flags from the API. Must be called before evaluating flags.
await client.initialize();isEnabled(flagKey, context)
Check if a flag is enabled (returns boolean).
const isEnabled = await client.isEnabled("new-checkout", {
userId: "user_123",
userType: "premium",
country: "IT",
});Parameters:
flagKey(string) - Flag key to evaluatecontext(object) - User context for targeting
Returns: Promise<boolean>
evaluate(flagKey, context)
Evaluate a flag with detailed result.
const result = await client.evaluate("new-checkout", {
userId: "user_123",
});
console.log(result);
// {
// flagKey: 'new-checkout',
// value: true,
// reason: 'RULE_MATCHED',
// ruleId: 'rule_abc'
// }Returns: Promise<EvaluationResult>
getAllFlags()
Get all cached flags.
const flags = client.getAllFlags();Returns: Flag[]
getFlag(flagKey)
Get a specific flag.
const flag = client.getFlag("new-checkout");Returns: Flag | undefined
refresh()
Manually refresh flags from API.
await client.refresh();destroy()
Cleanup and stop polling.
client.destroy();React Hooks
ObsidianLabProvider
Wrap your app to provide ObsidianLab context.
<ObsidianLabProvider config={{ sdkKey: "pk_prod_xxx" }}>
<App />
</ObsidianLabProvider>useFlag(flagKey, context)
Check if a flag is enabled.
function MyComponent() {
const { isEnabled, loading } = useFlag("new-feature", {
userId: "user_123",
});
if (loading) return <Spinner />;
return <div>{isEnabled && <NewFeature />}</div>;
}useFlagValue(flagKey, context)
Get detailed evaluation result.
function MyComponent() {
const { result, loading } = useFlagValue("new-feature", {
userId: "user_123",
});
console.log(result?.reason); // 'RULE_MATCHED'
}useObsidianLab()
Access SDK client directly.
function MyComponent() {
const { client, loading, error, flags } = useObsidianLab();
if (loading) return <Spinner />;
if (error) return <Error message={error.message} />;
return <div>Total flags: {flags.length}</div>;
}Targeting & Rules
Context Attributes
Pass any custom attributes for targeting:
const context = {
userId: "user_123", // For rollout percentage
email: "[email protected]", // Custom attribute
userType: "premium", // Custom attribute
country: "IT", // Custom attribute
age: 25, // Custom attribute
plan: "enterprise", // Custom attribute
};
const isEnabled = await client.isEnabled("feature", context);Operators
ObsidianLab supports 9 targeting operators:
| Operator | Description | Example |
| ------------- | ------------------ | ------------------------------- |
| equals | Exact match | userType === 'premium' |
| notEquals | Not equal | userType !== 'free' |
| in | In array | country in ['IT', 'US'] |
| notIn | Not in array | country not in ['CN'] |
| contains | String contains | email contains '@company.com' |
| startsWith | String starts with | email starts with 'admin' |
| endsWith | String ends with | email ends with '.edu' |
| greaterThan | Number > | age > 18 |
| lessThan | Number < | age < 65 |
Rollout Percentage
Use userId in context for consistent rollout:
// 20% rollout (same user always gets same result)
const isEnabled = await client.isEnabled("gradual-rollout", {
userId: "user_123", // Required for consistent hashing
userType: "premium",
});Examples
A/B Testing
const variant = await client.isEnabled("ab-test-variant-a", {
userId: user.id,
});
if (variant) {
showVariantA();
} else {
showVariantB();
}Canary Deployment
// Enable for 10% of premium users
const useNewAPI = await client.isEnabled("new-api", {
userId: user.id,
userType: "premium",
});
const apiUrl = useNewAPI ? "/api/v2" : "/api/v1";Kill Switch
// Instantly disable feature if issues
const featureEnabled = await client.isEnabled("risky-feature", {
userId: user.id,
});
if (featureEnabled) {
// Execute risky code
}Developer Logs
const enableLogs = await client.isEnabled("debug-logs", {
email: user.email, // Rule: email in ['[email protected]']
});
if (enableLogs) {
console.log("Debug info...");
}Advanced Usage
Auto-refresh
const client = new ObsidianLabClient({
sdkKey: "pk_prod_xxx",
pollingInterval: 300000, // Refresh every 5 minutes
onFlagsUpdated: (flags) => {
console.log("Flags updated!", flags.length);
},
});Error Handling
const client = new ObsidianLabClient({
sdkKey: "pk_prod_xxx",
onError: (error) => {
console.error("ObsidianLab Error:", error);
// Send to error tracking (Sentry, etc.)
},
});Custom Cache TTL
const client = new ObsidianLabClient({
sdkKey: "pk_prod_xxx",
cacheTTL: 30000, // Refresh every 30 seconds
});TypeScript
Full TypeScript support with types included.
import {
ObsidianLabClient,
ObsidianLabConfig,
EvaluationContext,
EvaluationResult,
} from "obsidianlab-sdk";
const config: ObsidianLabConfig = {
sdkKey: "pk_prod_xxx",
};
const client = new ObsidianLabClient(config);
const context: EvaluationContext = {
userId: "user_123",
userType: "premium",
};
const result: EvaluationResult = await client.evaluate("flag", context);Links
LICENSE (MIT)
MIT License
Copyright (c) 2025 Davide Faggionato
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
