diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 000ca82a..574dc79f 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -451,24 +451,20 @@ jobs:
severity: 'CRITICAL'
# Credentials preflight (workflow_dispatch only). Proves, without
- # publishing, what the tag run will need: an npm identity that can publish
- # in the @checkgate scope, parseable pub.dev credentials, and a PyPI trusted
- # publisher matching this workflow and environment. Prints no secret.
+ # publishing, what the tag run will need from npm and pub.dev: an npm
+ # identity with read-write access in the @checkgate scope and parseable
+ # pub.dev credentials. Prints no secret.
#
- # The PyPI check exchanges this job's OIDC token for a short-lived upload
- # token (discarded unused), exactly as publish-pypi will. If the publisher
- # is still *pending* (project not yet on PyPI), that exchange creates the
- # empty project `checkgate` under the account that registered it.
+ # PyPI cannot be checked here: the `pypi` environment only admits version
+ # tags, and the trusted publisher is bound to that environment. Instead,
+ # publish-pypi runs first in the tag run and every other publish job needs
+ # it, so a PyPI failure stops the release before anything is published.
preflight-credentials:
name: Preflight — publishing credentials
if: github.event_name == 'workflow_dispatch'
runs-on: ubuntu-latest
- environment:
- name: pypi
- url: https://pypi.org/project/checkgate/
permissions:
contents: read
- id-token: write
steps:
- uses: actions/setup-node@v5
with:
@@ -521,22 +517,6 @@ jobs:
console.log("pub.dev credentials: refresh token present");
});'
- - name: PyPI — trusted publisher accepts this workflow
- run: |
- set -euo pipefail
- AUD="$(curl -fsS https://pypi.org/_/oidc/audience | node -p 'JSON.parse(require("fs").readFileSync(0)).audience')"
- OIDC="$(curl -fsS -H "Authorization: bearer $ACTIONS_ID_TOKEN_REQUEST_TOKEN" "$ACTIONS_ID_TOKEN_REQUEST_URL&audience=$AUD" | node -p 'JSON.parse(require("fs").readFileSync(0)).value')"
- echo "::add-mask::$OIDC"
- RESP="$(curl -sS -X POST https://pypi.org/_/oidc/mint-token -H 'Content-Type: application/json' -d "{\"token\":\"$OIDC\"}")"
- printf '%s' "$RESP" | node -e '
- const r = JSON.parse(require("fs").readFileSync(0));
- if (r.success && r.token) { console.log("PyPI trusted publishing: accepted (upload token minted and discarded)"); process.exit(0); }
- console.error("Error: PyPI refused the trusted-publishing exchange:");
- console.error(JSON.stringify({ message: r.message, errors: (r.errors || []).map((e) => e.code + ": " + e.description) }, null, 2));
- process.exit(1);
- '
- echo "PyPI project page: $(curl -s -o /dev/null -w '%{http_code}' https://pypi.org/pypi/checkgate/json)"
-
# ===========================================================================
# PHASE 2 — PUBLISH. Every job below waits for *all* of phase 1.
# ===========================================================================
@@ -544,7 +524,7 @@ jobs:
publish-node:
name: Publish — @checkgate/node
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v')
- needs: [verify-js, build-native, build-web, verify-flutter, verify-python, build-docker]
+ needs: [verify-js, build-native, build-web, verify-flutter, verify-python, build-docker, publish-pypi]
runs-on: ubuntu-latest
permissions:
contents: read
@@ -614,7 +594,7 @@ jobs:
publish-web:
name: Publish — @checkgate/web
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v')
- needs: [verify-js, build-native, build-web, verify-flutter, verify-python, build-docker]
+ needs: [verify-js, build-native, build-web, verify-flutter, verify-python, build-docker, publish-pypi]
runs-on: ubuntu-latest
permissions:
contents: read
@@ -661,7 +641,7 @@ jobs:
publish-cli:
name: Publish — @checkgate/cli
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v')
- needs: [verify-js, build-native, build-web, verify-flutter, verify-python, build-docker]
+ needs: [verify-js, build-native, build-web, verify-flutter, verify-python, build-docker, publish-pypi]
runs-on: ubuntu-latest
permissions:
contents: read
@@ -689,7 +669,7 @@ jobs:
publish-edge:
name: Publish — @checkgate/edge
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v')
- needs: [verify-js, build-native, build-web, verify-flutter, verify-python, build-docker]
+ needs: [verify-js, build-native, build-web, verify-flutter, verify-python, build-docker, publish-pypi]
runs-on: ubuntu-latest
permissions:
contents: read
@@ -717,7 +697,7 @@ jobs:
publish-ssr:
name: Publish — @checkgate/ssr
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v')
- needs: [verify-js, build-native, build-web, verify-flutter, verify-python, build-docker]
+ needs: [verify-js, build-native, build-web, verify-flutter, verify-python, build-docker, publish-pypi]
runs-on: ubuntu-latest
permissions:
contents: read
@@ -745,7 +725,7 @@ jobs:
publish-openfeature:
name: Publish — @checkgate/openfeature-provider
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v')
- needs: [verify-js, build-native, build-web, verify-flutter, verify-python, build-docker]
+ needs: [verify-js, build-native, build-web, verify-flutter, verify-python, build-docker, publish-pypi]
runs-on: ubuntu-latest
permissions:
contents: read
@@ -773,7 +753,7 @@ jobs:
publish-node-integrations:
name: Publish — @checkgate/node-integrations
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v')
- needs: [verify-js, build-native, build-web, verify-flutter, verify-python, build-docker]
+ needs: [verify-js, build-native, build-web, verify-flutter, verify-python, build-docker, publish-pypi]
runs-on: ubuntu-latest
permissions:
contents: read
@@ -801,7 +781,7 @@ jobs:
publish-mcp-server:
name: Publish — @checkgate/mcp-server
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v')
- needs: [verify-js, build-native, build-web, verify-flutter, verify-python, build-docker]
+ needs: [verify-js, build-native, build-web, verify-flutter, verify-python, build-docker, publish-pypi]
runs-on: ubuntu-latest
permissions:
contents: read
@@ -829,7 +809,7 @@ jobs:
publish-react-native:
name: Publish — @checkgate/react-native
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v')
- needs: [verify-js, build-native, build-web, verify-flutter, verify-python, build-docker]
+ needs: [verify-js, build-native, build-web, verify-flutter, verify-python, build-docker, publish-pypi]
runs-on: ubuntu-latest
permissions:
contents: read
@@ -861,7 +841,7 @@ jobs:
publish-flutter:
name: Publish — checkgate_flutter (pub.dev)
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v')
- needs: [verify-js, build-native, build-web, verify-flutter, verify-python, build-docker]
+ needs: [verify-js, build-native, build-web, verify-flutter, verify-python, build-docker, publish-pypi]
runs-on: ubuntu-latest
permissions:
id-token: write
@@ -902,7 +882,7 @@ jobs:
publish-docker:
name: Publish — Docker image
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v')
- needs: [verify-js, build-native, build-web, verify-flutter, verify-python, build-docker]
+ needs: [verify-js, build-native, build-web, verify-flutter, verify-python, build-docker, publish-pypi]
runs-on: ubuntu-latest
permissions:
contents: read
@@ -954,6 +934,8 @@ jobs:
run: |
cosign sign --yes ${{ env.IMAGE_NAME }}@${{ steps.build-push.outputs.digest }}
+ # Runs before every other publish job (they all need it): it is the one
+ # credential the dispatch preflight cannot check (see preflight-credentials).
# PyPI trusted publishing (OIDC): no stored token. Needs, once, on PyPI: a
# publisher for project `checkgate`, owner checkgate-sh, repository
# checkgate, workflow release.yml, environment `pypi`. The action attaches
diff --git a/README.md b/README.md
index bb4d4c43..fae3d41d 100644
--- a/README.md
+++ b/README.md
@@ -32,12 +32,9 @@ request. One Server-Sent Events connection per SDK delivers changes as they happ
reconnects, a polling fallback and the last known flags if the server is unreachable. You run the
server, PostgreSQL and Redis on your own infrastructure.
-> [!NOTE]
-> **0.2.0 is in development and not yet released.** The latest release is
-> [v0.1.31](https://github.com/checkgate-sh/checkgate/releases/latest). Items marked
-> *0.2.0* below are in this source tree but not yet published to npm, PyPI or the container
-> registry. Upgrading an existing server to 0.2.0 has
-> [rules to read first](docs/operations/upgrading-to-0-2-0.md) (two migrations, no rolling upgrade; back up the database first).
+> [!IMPORTANT]
+> Upgrading a 0.1.31 server to 0.2.0? Read [Upgrading to 0.2.0](docs/operations/upgrading-to-0-2-0.md)
+> first: two database migrations, no rolling upgrade, back up the database before you start.
## How it works
@@ -106,20 +103,20 @@ client.isEnabled('new-checkout', 'user-123', { plan: 'pro' }) // local: no netwo
| Runtime | Package | Status |
|---|---|---|
-| Node.js | [`@checkgate/node`](docs/sdks/nodejs.md) (NAPI) | npm 0.1.31 |
-| Browser | [`@checkgate/web`](docs/sdks/web.md) (WebAssembly) | npm 0.1.31 |
-| React Native | [`@checkgate/react-native`](docs/sdks/react-native.md) (JSI) | npm 0.1.31 · Android build verified in CI; iOS not certified |
-| Flutter | [`checkgate_flutter`](docs/sdks/flutter.md) (FFI) | pub.dev 0.1.31 · bundles no engine: you build and link it |
-| Python | [`checkgate`](docs/sdks/python.md) (PyO3) | *0.2.0* · build from source; **not on PyPI yet** |
-| OpenFeature | [`@checkgate/openfeature-provider`](docs/sdks/openfeature.md) (Node.js server) | *0.2.0* · not yet on npm |
-| Express · Fastify · NestJS | [`@checkgate/node-integrations`](docs/sdks/node-frameworks.md) | *0.2.0* · not yet on npm |
-| SSR / edge | [`@checkgate/ssr`](docs/ecosystem/ssr.md), [`@checkgate/edge`](docs/ecosystem/edge.md) | npm 0.1.31 |
-| Typed flags | [`@checkgate/cli`](docs/ecosystem/cli.md) | npm 0.1.31 |
-| AI agents | [`@checkgate/mcp-server`](docs/ecosystem/mcp.md) | *0.2.0* · not yet on npm · read-only by default; can propose, never apply or approve |
+| Node.js | [`@checkgate/node`](docs/sdks/nodejs.md) (NAPI) | npm 0.2.0 |
+| Browser | [`@checkgate/web`](docs/sdks/web.md) (WebAssembly) | npm 0.2.0 |
+| React Native | [`@checkgate/react-native`](docs/sdks/react-native.md) (JSI) | npm 0.2.0 · Android build verified in CI; iOS not certified |
+| Flutter | [`checkgate_flutter`](docs/sdks/flutter.md) (FFI) | pub.dev 0.2.0 · bundles no engine: you build and link it |
+| Python | [`checkgate`](docs/sdks/python.md) (PyO3) | PyPI 0.2.0 · new in 0.2.0; CPython 3.11+ |
+| OpenFeature | [`@checkgate/openfeature-provider`](docs/sdks/openfeature.md) (Node.js server) | npm 0.2.0 · new in 0.2.0 |
+| Express · Fastify · NestJS | [`@checkgate/node-integrations`](docs/sdks/node-frameworks.md) | npm 0.2.0 · new in 0.2.0 |
+| SSR / edge | [`@checkgate/ssr`](docs/ecosystem/ssr.md), [`@checkgate/edge`](docs/ecosystem/edge.md) | npm 0.2.0 |
+| Typed flags | [`@checkgate/cli`](docs/ecosystem/cli.md) | npm 0.2.0 |
+| AI agents | [`@checkgate/mcp-server`](docs/ecosystem/mcp.md) | npm 0.2.0 · new in 0.2.0 · read-only by default; can propose, never apply or approve |
| Infrastructure as code | [Terraform / OpenTofu provider](docs/ecosystem/terraform.md), [Kubernetes operator](docs/ecosystem/kubernetes.md) | build from source |
Every SDK runs the same evaluation engine and checks the same shared test vectors. Also new in
-*0.2.0*: the [evaluation playground](docs/guide/playground.md) (what an SDK would answer for a user,
+0.2.0: the [evaluation playground](docs/guide/playground.md) (what an SDK would answer for a user,
and why) and [SDK diagnostics](docs/operations/sdk-diagnostics.md). Which packages your stack needs:
[Which SDK do I need?](docs/sdks/index.md)
diff --git a/docs/.vitepress/data/release.ts b/docs/.vitepress/data/release.ts
index ac31d551..3e0b12d0 100644
--- a/docs/.vitepress/data/release.ts
+++ b/docs/.vitepress/data/release.ts
@@ -1,16 +1,16 @@
// Release status for the docs site, in one place.
//
// Pages never hard-code "unreleased" or "not on npm": they use ,
-// and , which read this file. When 0.2.0 is
-// published, set `latest` to '0.2.0', `next` to null, and update each
-// package's `registry` to what the registries actually serve (check with
-// `npm view`, PyPI and pub.dev; never assume a publish succeeded).
+// and , which read this file. For a release, set
+// `latest` to its version, `next` to null (or the version in development),
+// and each package's `registry` to what the registries serve (check with
+// `npm view`, PyPI and pub.dev after publishing).
export const release = {
/** Newest version published to npm, pub.dev, ghcr.io and GitHub Releases. */
- latest: '0.1.31',
+ latest: '0.2.0',
/** The version in development on `dev`, or null when nothing is pending. */
- next: '0.2.0' as string | null,
+ next: null as string | null,
repo: 'https://github.com/checkgate-sh/checkgate',
}
@@ -50,34 +50,34 @@ export interface Package {
export const packages: Package[] = [
{ id: 'node', name: '@checkgate/node', platform: 'Node.js', binding: 'NAPI', doc: '/sdks/nodejs', since: '0.1.0',
- registry: { kind: 'npm', version: '0.1.31' }, install: 'npm install @checkgate/node', group: 'sdk',
- limits: 'Node.js runtime only (not edge runtimes). getDetails(), getHealth() and onStatusChange() arrive in 0.2.0.' },
+ registry: { kind: 'npm', version: '0.2.0' }, install: 'npm install @checkgate/node', group: 'sdk',
+ limits: 'Node.js runtime only (not edge runtimes). getDetails(), getHealth() and onStatusChange() since 0.2.0.' },
{ id: 'python', name: 'checkgate', platform: 'Python', binding: 'PyO3', doc: '/sdks/python', since: '0.2.0',
- registry: { kind: 'source', note: 'Not on PyPI yet: build from the repository (needs Rust). Do not install a package named checkgate from PyPI until the project announces it.' },
+ registry: { kind: 'pypi', version: '0.2.0' }, install: 'pip install checkgate',
group: 'sdk', limits: 'CPython 3.11+. No impression reporting or track() yet.' },
{ id: 'web', name: '@checkgate/web', platform: 'Browser', binding: 'WebAssembly', doc: '/sdks/web', since: '0.1.0',
- registry: { kind: 'npm', version: '0.1.31' }, install: 'npm install @checkgate/web', group: 'sdk' },
+ registry: { kind: 'npm', version: '0.2.0' }, install: 'npm install @checkgate/web', group: 'sdk' },
{ id: 'react-native', name: '@checkgate/react-native', platform: 'React Native', binding: 'JSI', doc: '/sdks/react-native', since: '0.1.0',
- registry: { kind: 'npm', version: '0.1.31' }, install: 'npm install @checkgate/react-native', group: 'sdk',
+ registry: { kind: 'npm', version: '0.2.0' }, install: 'npm install @checkgate/react-native', group: 'sdk',
limits: 'Android native build verified in CI; iOS not certified. Builds the Rust engine in your app build.' },
{ id: 'flutter', name: 'checkgate_flutter', platform: 'Flutter', binding: 'Dart FFI', doc: '/sdks/flutter', since: '0.1.0',
- registry: { kind: 'pub', version: '0.1.31' }, install: 'flutter pub add checkgate_flutter', group: 'sdk',
+ registry: { kind: 'pub', version: '0.2.0' }, install: 'flutter pub add checkgate_flutter', group: 'sdk',
limits: 'Bundles no compiled engine: you build and link the Rust engine yourself.' },
{ id: 'openfeature', name: '@checkgate/openfeature-provider', platform: 'OpenFeature (Node.js server)', binding: 'over @checkgate/node', doc: '/sdks/openfeature', since: '0.2.0',
- registry: { kind: 'unpublished', note: 'Publishes to npm with 0.2.0; it needs @checkgate/node 0.2.' },
+ registry: { kind: 'npm', version: '0.2.0' },
install: 'npm install @checkgate/openfeature-provider @openfeature/server-sdk', group: 'framework' },
{ id: 'node-integrations', name: '@checkgate/node-integrations', platform: 'Express · Fastify · NestJS', binding: 'over @checkgate/node', doc: '/sdks/node-frameworks', since: '0.2.0',
- registry: { kind: 'unpublished', note: 'Publishes to npm with 0.2.0.' },
+ registry: { kind: 'npm', version: '0.2.0' },
install: 'npm install @checkgate/node @checkgate/node-integrations', group: 'framework',
limits: 'Node.js 22.12+; Express 5, Fastify 5, NestJS 12.' },
{ id: 'ssr', name: '@checkgate/ssr', platform: 'SSR / bootstrap', binding: 'with @checkgate/web', doc: '/ecosystem/ssr', since: '0.1.0',
- registry: { kind: 'npm', version: '0.1.31' }, install: 'npm install @checkgate/web @checkgate/ssr', group: 'framework' },
+ registry: { kind: 'npm', version: '0.2.0' }, install: 'npm install @checkgate/web @checkgate/ssr', group: 'framework' },
{ id: 'edge', name: '@checkgate/edge', platform: 'Edge runtimes', binding: 'with @checkgate/web', doc: '/ecosystem/edge', since: '0.1.0',
- registry: { kind: 'npm', version: '0.1.31' }, install: 'npm install @checkgate/edge @checkgate/web', group: 'framework' },
+ registry: { kind: 'npm', version: '0.2.0' }, install: 'npm install @checkgate/edge @checkgate/web', group: 'framework' },
{ id: 'cli', name: '@checkgate/cli', platform: 'Typed flag accessors', binding: 'dev dependency', doc: '/ecosystem/cli', since: '0.1.0',
- registry: { kind: 'npm', version: '0.1.31' }, install: 'npm install -D @checkgate/cli', group: 'tooling' },
+ registry: { kind: 'npm', version: '0.2.0' }, install: 'npm install -D @checkgate/cli', group: 'tooling' },
{ id: 'mcp', name: '@checkgate/mcp-server', platform: 'AI agents (MCP)', binding: 'stdio', doc: '/ecosystem/mcp', since: '0.2.0',
- registry: { kind: 'unpublished', note: 'Publishes to npm with 0.2.0; needs a 0.2.0 server.' }, group: 'tooling',
+ registry: { kind: 'npm', version: '0.2.0' }, install: 'npx -y @checkgate/mcp-server@0.2.0', group: 'tooling',
limits: 'Read-only by default; can propose changes, never create, apply or approve.' },
{ id: 'terraform', name: 'terraform-provider-checkgate', platform: 'Terraform / OpenTofu', binding: 'Go', doc: '/ecosystem/terraform', since: '0.1.0',
registry: { kind: 'source', note: 'Not on the Terraform Registry: build from source.' }, group: 'tooling' },
diff --git a/docs/ecosystem/mcp.md b/docs/ecosystem/mcp.md
index ad7c7223..a9bf281e 100644
--- a/docs/ecosystem/mcp.md
+++ b/docs/ecosystem/mcp.md
@@ -78,9 +78,9 @@ your email. Someone else must approve them.
## 2. Configure your MCP client
-The package needs Node.js 22 or later (CI tests it on 22). Until it is published to npm, run it from a checkout of the
-repository (`cd integrations/mcp-server && npm ci`) and point `command`/`args` at
-`integrations/mcp-server/bin/checkgate-mcp.js`.
+The client starts the server with `npx`, so there is nothing to install beforehand. It needs
+Node.js 20 or later (CI tests it on 22). To run it from a checkout instead, use `node` with
+`integrations/mcp-server/bin/checkgate-mcp.js` as `command`/`args` after `npm ci` in that directory.
**Claude Desktop** (`claude_desktop_config.json`):
@@ -88,8 +88,8 @@ repository (`cd integrations/mcp-server && npm ci`) and point `command`/`args` a
{
"mcpServers": {
"checkgate": {
- "command": "node",
- "args": ["/path/to/checkgate/integrations/mcp-server/bin/checkgate-mcp.js"],
+ "command": "npx",
+ "args": ["-y", "@checkgate/mcp-server@0.2.0"],
"env": {
"CHECKGATE_URL": "https://flags.example.com",
"CHECKGATE_TOKEN": "pat_your_propose_token",
@@ -107,7 +107,7 @@ claude mcp add --transport stdio checkgate \
--env CHECKGATE_URL=https://flags.example.com \
--env CHECKGATE_TOKEN=pat_your_propose_token \
--env CHECKGATE_MCP_WRITE=1 \
- -- node /path/to/checkgate/integrations/mcp-server/bin/checkgate-mcp.js
+ -- npx -y @checkgate/mcp-server@0.2.0
```
Leave out `CHECKGATE_MCP_WRITE` for a read-only assistant.
diff --git a/docs/ecosystem/ssr.md b/docs/ecosystem/ssr.md
index bfdaba53..612a7658 100644
--- a/docs/ecosystem/ssr.md
+++ b/docs/ecosystem/ssr.md
@@ -27,32 +27,23 @@ npm install @checkgate/ssr @checkgate/edge @checkgate/web
### 1. Server — build the payload
-```ts
-// lib/checkgate-server.ts
+```js
+// lib/checkgate-server.js
import { CheckgateEdge } from '@checkgate/edge'
import { buildBootstrap } from '@checkgate/ssr'
import { createWasmCore } from '@checkgate/web/core'
-let edge: CheckgateEdge | null = null
+let edge = null
-export async function getBootstrap(userKey: string, keys: string[]) {
- if (!edge) {
- edge = new CheckgateEdge({
- serverUrl: process.env.CHECKGATE_URL!,
- sdkKey: process.env.CHECKGATE_SDK_KEY!,
- core: await createWasmCore(),
- ttlSeconds: 30,
- })
- }
- await edge.ensureFresh()
- // buildBootstrap re-loads the snapshot into a core and resolves `keys` for the
- // user; pass the same snapshot the edge client is holding.
- return buildBootstrap({
+export async function getBootstrap(userKey, attributes, keys) {
+ edge ??= new CheckgateEdge({
+ serverUrl: process.env.CHECKGATE_URL,
+ sdkKey: process.env.CHECKGATE_SDK_KEY,
core: await createWasmCore(),
- snapshot: edge.snapshotFlags(),
- userKey,
- keys,
+ ttlSeconds: 30,
})
+ await edge.ensureFresh()
+ return buildBootstrap({ core: await createWasmCore(), snapshot: edge.snapshotFlags(), userKey, attributes, keys })
}
```
@@ -63,15 +54,15 @@ render and the first client render then read the same values (no hydration
mismatch). Keep the user's attributes next to it so the live client evaluates
with the same inputs as the server.
-```tsx
-// app/layout.tsx (Server Component)
-import { getBootstrap } from '@/lib/checkgate-server'
+```jsx
+// app/layout.jsx (Server Component)
+import { getBootstrap } from '../lib/checkgate-server'
import { FlagsProvider } from './flags-provider'
export default async function RootLayout({ children }) {
- const userKey = /* cookie/session id */ 'anonymous'
- const attributes = { plan: 'free' } // the same attributes passed to buildBootstrap
- const payload = await getBootstrap(userKey, ['new-homepage', 'checkout-color'])
+ const userKey = 'anonymous' // from your session or cookie
+ const attributes = { plan: 'free' } // the same attributes for server and client
+ const payload = await getBootstrap(userKey, attributes, ['new-homepage', 'checkout-color'])
return (
@@ -90,25 +81,25 @@ Outside React (or with a streaming template), embed it instead with
One `CheckgateWeb` client for the whole app, seeded from the same payload:
-```tsx
+```jsx
+// app/flags-provider.jsx
'use client'
import { createContext, useContext, useEffect, useMemo, useState } from 'react'
import { BootstrapValues } from '@checkgate/ssr'
import { CheckgateWeb } from '@checkgate/web'
-type Read = (key: string) => boolean
-const FlagsContext = createContext(() => false)
+const FlagsContext = createContext(() => false)
export function FlagsProvider({ payload, attributes = {}, children }) {
const initial = useMemo(() => new BootstrapValues(payload), [payload])
- const [client, setClient] = useState(null)
+ const [client, setClient] = useState(null)
const [, setVersion] = useState(0)
useEffect(() => {
const live = new CheckgateWeb({
- serverUrl: process.env.NEXT_PUBLIC_CHECKGATE_URL!,
- sdkKey: process.env.NEXT_PUBLIC_CHECKGATE_SDK_KEY!,
- bootstrap: payload, // live-ready without waiting for SSE
+ serverUrl: process.env.NEXT_PUBLIC_CHECKGATE_URL,
+ sdkKey: process.env.NEXT_PUBLIC_CHECKGATE_SDK_KEY,
+ bootstrap: payload,
})
const off = live.onChange(() => setVersion((v) => v + 1))
live.connect().then(() => setClient(live)).catch(() => {})
@@ -116,14 +107,12 @@ export function FlagsProvider({ payload, attributes = {}, children }) {
}, [payload])
// Server-resolved values until the live client is ready, then live ones.
- const read: Read = (key) =>
- client && initial.userKey
- ? client.isEnabled(key, initial.userKey, attributes)
- : initial.isEnabled(key)
+ const read = (key) =>
+ client && initial.userKey ? client.isEnabled(key, initial.userKey, attributes) : initial.isEnabled(key)
return {children}
}
-export const useFlag = (key: string) => useContext(FlagsContext)(key)
+export const useFlag = (key) => useContext(FlagsContext)(key)
```
**Remix / SvelteKit** follow the same three steps — build the payload in the `loader` / `+page.server`, inject the script into the document template, and read it in a client component or store.
diff --git a/docs/guide/quickstart.md b/docs/guide/quickstart.md
index d39dd771..e1c318bf 100644
--- a/docs/guide/quickstart.md
+++ b/docs/guide/quickstart.md
@@ -52,19 +52,19 @@ node --env-file=../.env index.mjs
**Python**
-The Python package is not on PyPI yet, so build it from this checkout (needs Rust). Use a Python
-3.11+ interpreter: if `python3 --version` prints an older one, write `python3.11` (or newer)
-instead of `python3` below.
+Use a Python 3.11+ interpreter: if `python3 --version` prints an older one, write `python3.11`
+(or newer) instead of `python3` below.
```bash
-cd sdks/python
-python3 -m venv .venv && .venv/bin/pip install "maturin>=1.9.4,<2"
-VIRTUAL_ENV=$PWD/.venv .venv/bin/maturin develop --release
-cd ../../quickstart/python
+cd quickstart/python
+python3 -m venv .venv && .venv/bin/pip install "checkgate==0.2.0"
set -a && . ../.env && set +a
-../../sdks/python/.venv/bin/python main.py
+.venv/bin/python main.py
```
+To run against SDK changes in this checkout instead, build the package from source (needs Rust):
+see [Python SDK: build from source](/sdks/python#build-from-source).
+
Both print the flag for two users (`new-checkout: user-pro=true user-free=false`; Python writes
`True`/`False`): the flag is evaluated in your process by the Checkgate engine, with no network
call per evaluation.
@@ -99,7 +99,7 @@ restart. With a 0.2.0 server , open **Playground** in the sid
| Setup fails with `HTTP 409` or `403` | The instance was already set up. `./quickstart/start.sh --down` starts over. |
| The SDK logs `rejected the SDK key (HTTP 401)` | `CHECKGATE_SDK_KEY` is missing or from an older run: re-run with `--seed` after `--down`, or create a key in project settings. |
| The SDK keeps logging `reconnecting` | The server is not reachable at `http://localhost:$CHECKGATE_PORT`; check `docker compose -f quickstart/compose.yml ps`. |
-| `pip install checkgate` finds nothing, or something unexpected | The Python package is **not on PyPI yet** — do not install a `checkgate` package from PyPI until the project announces it. Build it from the checkout: `cd sdks/python && python3 -m venv .venv && .venv/bin/pip install maturin && .venv/bin/maturin develop --release`, then run `main.py` with `sdks/python/.venv/bin/python`. |
+| `pip install checkgate` finds no matching distribution | No wheel for your platform or Python: wheels are for CPython 3.11+ on Linux (glibc) x86_64/aarch64, macOS x86_64/arm64 and Windows x86_64. Elsewhere (for example Alpine/musl), [build from source](/sdks/python#build-from-source). |
## What the script does not do
diff --git a/docs/index.md b/docs/index.md
index 3ac599bd..ead16dff 100644
--- a/docs/index.md
+++ b/docs/index.md
@@ -71,7 +71,7 @@ const enabled = client.isEnabled('new-checkout', 'user-123', { plan: 'pro' })
```python
-# Not on PyPI yet: build from the repository (see the Python SDK docs)
+# pip install checkgate
import os
from checkgate import CheckgateClient
diff --git a/docs/roadmap.md b/docs/roadmap.md
index 921edc96..e59e4418 100644
--- a/docs/roadmap.md
+++ b/docs/roadmap.md
@@ -18,7 +18,7 @@ This document outlines the vision and future development priorities for Checkgat
Every new SDK wraps the **same shared Rust evaluation core** in [`core/`](https://github.com/checkgate-sh/checkgate/tree/main/core) — exactly how the existing Node.js (NAPI), Web (WASM), React Native (JSI), and Flutter (FFI) SDKs do — so local, in-process evaluation and flag semantics (rules, rollouts, segments, prerequisites, weighted variants) stay **identical across every language**. Each also inherits the shared resilience layer: SSE streaming with backoff, offline persistence, and the `/flags/snapshot` poll fallback.
**Server-side languages** (backend/local evaluation)
-- [x] **Python SDK** *(implemented for 0.2.0, not yet released; not on PyPI)*: PyO3 bindings to the core — Django / FastAPI / Flask apps and data/ML services. See [Python SDK](/sdks/python).
+- [x] **Python SDK** *(released in 0.2.0, on PyPI)*: PyO3 bindings to the core — Django / FastAPI / Flask apps and data/ML services. See [Python SDK](/sdks/python).
- [ ] **Go SDK**: A cgo-FFI **local-evaluation** SDK, complementing the existing [`checkgate-go`](https://github.com/checkgate-sh/checkgate/tree/main/integrations/checkgate-go) *management* client that already backs the Terraform provider and Kubernetes operator.
- [ ] **Java / Kotlin (JVM) SDK**: JNI bindings — Spring Boot and other JVM backends.
- [ ] **Ruby SDK**: Rails apps and Sidekiq workers.
@@ -31,7 +31,7 @@ Every new SDK wraps the **same shared Rust evaluation core** in [`core/`](https:
- [ ] **Kotlin Multiplatform / Android SDK**: JNI over the core, sharing logic with the JVM SDK for Android apps.
**Standards & interop**
-- [ ] **OpenFeature providers**: Official [OpenFeature](https://openfeature.dev) provider(s) so Checkgate drops into any OpenFeature-instrumented app. High leverage — implement one spec, plug into many language ecosystems at once. The Node.js server provider is implemented for 0.2.0 (not yet released; [docs](/sdks/openfeature)); other languages are planned.
+- [ ] **OpenFeature providers**: Official [OpenFeature](https://openfeature.dev) provider(s) so Checkgate drops into any OpenFeature-instrumented app. High leverage — implement one spec, plug into many language ecosystems at once. The Node.js server provider shipped in 0.2.0 ([docs](/sdks/openfeature)); other languages are planned.
---
diff --git a/docs/sdks/flutter.md b/docs/sdks/flutter.md
index 10c8df5f..36a8466a 100644
--- a/docs/sdks/flutter.md
+++ b/docs/sdks/flutter.md
@@ -13,7 +13,7 @@ Add to your `pubspec.yaml`:
```yaml
dependencies:
- checkgate_flutter: ^0.1.31
+ checkgate_flutter: ^0.2.0
```
Then run:
diff --git a/docs/sdks/index.md b/docs/sdks/index.md
index 66ce38b5..b9d6f598 100644
--- a/docs/sdks/index.md
+++ b/docs/sdks/index.md
@@ -23,7 +23,7 @@ Find your stack below — each section lists what's **required**, what's
| **React Native** | `@checkgate/react-native` | `@checkgate/cli` |
| **Flutter** | `checkgate_flutter` | `@checkgate/cli` |
| **Node.js server** — Express, Fastify, NestJS | `@checkgate/node` | `@checkgate/node-integrations`, `@checkgate/cli` |
-| **Python server** — FastAPI, Django, Flask | `checkgate` (0.2.0; build from source, not on PyPI yet) | — |
+| **Python server** — FastAPI, Django, Flask | `checkgate` (PyPI) | — |
| **Edge** — Cloudflare Workers, Vercel Edge, middleware | `@checkgate/edge` + `@checkgate/web` | `@checkgate/cli` |
`@checkgate/cli` is optional everywhere — it's a dev-time tool that generates
@@ -147,9 +147,8 @@ See the [Flutter SDK reference](/sdks/flutter).
### Python
**One package**, `checkgate`: the Python client with the same Rust core compiled
-in through PyO3 (abi3, CPython 3.11+). It is **not on PyPI yet** — build it from
-the repository ([how](/sdks/python#installation)) and do not install a `checkgate`
-package from PyPI until the project announces it. Evaluation is synchronous and
+in through PyO3 (abi3, CPython 3.11+): `pip install checkgate`
+([installation](/sdks/python#installation)). Evaluation is synchronous and
thread-safe; syncing runs on a background thread, so it works the same under
WSGI and ASGI servers. Create one client per worker process.
diff --git a/docs/sdks/node-frameworks.md b/docs/sdks/node-frameworks.md
index 12f2d670..c3427b37 100644
--- a/docs/sdks/node-frameworks.md
+++ b/docs/sdks/node-frameworks.md
@@ -147,11 +147,11 @@ TypeScript: importing the module adds `checkgate: RequestFlags` to Express's
```js
import Fastify from 'fastify'
-import checkgate from '@checkgate/node-integrations/fastify'
+import { checkgatePlugin } from '@checkgate/node-integrations/fastify'
const app = Fastify()
-await app.register(checkgate, {
+await app.register(checkgatePlugin, {
clientOptions: { serverUrl: process.env.CHECKGATE_URL, sdkKey: process.env.CHECKGATE_SDK_KEY },
context: (request) => (request.user ? { key: request.user.id, attributes: { plan: request.user.plan } } : null),
readyTimeoutMs: 5000,
diff --git a/docs/sdks/openfeature.md b/docs/sdks/openfeature.md
index 2d30d496..9515f6c0 100644
--- a/docs/sdks/openfeature.md
+++ b/docs/sdks/openfeature.md
@@ -19,8 +19,7 @@ npm install @checkgate/openfeature-provider @checkgate/node @openfeature/server-
```
Requires Node.js 22 or later (CI tests 22, 24 and 26), `@openfeature/server-sdk` 1.17 or later
-(tested with 1.23) and `@checkgate/node` 0.2. Until 0.2.0 is published, install both Checkgate
-packages from a checkout of the repository.
+(tested with 1.23) and `@checkgate/node` 0.2.
## Quick start
diff --git a/docs/sdks/python.md b/docs/sdks/python.md
index 14869de0..4ad07a27 100644
--- a/docs/sdks/python.md
+++ b/docs/sdks/python.md
@@ -15,17 +15,22 @@ standard library — there is no asyncio inside the client, so it never blocks
your event loop.
::: tip New in 0.2.0
-The release workflow builds wheels for Linux x86_64 and aarch64 (manylinux), macOS x86_64 and
-arm64, and Windows x86_64, for CPython 3.11 and newer (one abi3 wheel per platform). They are
-not published anywhere yet. See [Platform support](#platform-support) for what is tested.
+Wheels on PyPI for Linux x86_64 and aarch64 (manylinux), macOS x86_64 and arm64, and Windows
+x86_64, for CPython 3.11 and newer (one abi3 wheel per platform). See
+[Platform support](#platform-support) for what is tested.
:::
## Installation
-The package (`checkgate`, Python 3.11+) is **not on PyPI yet**: until the release announces it,
-do not install a `checkgate` package from PyPI. Build it from a checkout of the repository. You need Rust and a Python 3.11+
-interpreter; if `python3 --version` prints an older one, use `python3.11` (or newer) below.
-Publishing to PyPI is planned; no release job publishes the wheels yet.
+```bash
+pip install checkgate==0.2.0 # Python 3.11 or newer
+```
+
+### Build from source
+
+For a platform without a wheel (for example Alpine/musl), or to test changes in a checkout. You
+need Rust and a Python 3.11+ interpreter; if `python3 --version` prints an older one, use
+`python3.11` (or newer) below.
```bash
cd sdks/python
@@ -34,12 +39,6 @@ python3 -m venv .venv # Python 3.11 or newer
VIRTUAL_ENV=$PWD/.venv .venv/bin/maturin develop --release # installs checkgate into .venv
```
-Once it is published (not yet):
-
-```bash
-pip install checkgate
-```
-
## Quick Start
```python
diff --git a/docs/sdks/react-native.md b/docs/sdks/react-native.md
index b3f9e7c0..dd320559 100644
--- a/docs/sdks/react-native.md
+++ b/docs/sdks/react-native.md
@@ -206,7 +206,7 @@ from [Native setup](#native-setup-rust-toolchain).
## Platform Support
-| Platform | Architecture | Status in 0.1.31 |
+| Platform | Architecture | Status in 0.2.0 |
|----------|-------------|--------|
| Android | arm64-v8a, armeabi-v7a, x86_64, x86 | Native build and link verified in CI; not tested on a device or emulator for this release |
| iOS | arm64 | **Not certified**: the iOS app build was not run for this release |
diff --git a/docs/sdks/web.md b/docs/sdks/web.md
index 8478b46b..702fac46 100644
--- a/docs/sdks/web.md
+++ b/docs/sdks/web.md
@@ -108,61 +108,60 @@ Closes the SSE connection.
## Usage with React
-```tsx
-// hooks/useFlag.ts
-import { useEffect, useState } from 'react'
-import { flags } from '../lib/flags' // shared client instance
-
-export function useFlag(
- key: string,
- userId: string,
- attributes: Record = {}
-): boolean {
- const [enabled, setEnabled] = useState(() =>
- flags.isEnabled(key, userId, attributes)
- )
+There is no separate React package. Create one client for the app, and re-render when
+`connect()` settles and on `onChange` (`onChange` does not fire for the initial load):
- useEffect(() => {
- // Re-evaluate when flags update
- const unsubscribe = flags.onChange(() => {
- setEnabled(flags.isEnabled(key, userId, attributes))
- })
- return unsubscribe
- }, [key, userId])
+```js
+// lib/flags.js — one shared client
+import { CheckgateWeb } from '@checkgate/web'
- return enabled
+export const flags = new CheckgateWeb({ serverUrl: 'https://flags.example.com', sdkKey: 'sk_live_...' })
+export const flagsReady = flags.connect()
+```
+
+```jsx
+// hooks/useFlag.js
+import { useEffect, useReducer } from 'react'
+import { flags, flagsReady } from '../lib/flags'
+
+export function useFlag(flagKey, userKey, attributes) {
+ const [, rerender] = useReducer((n) => n + 1, 0)
+ useEffect(() => {
+ let active = true
+ const update = () => { if (active) rerender() }
+ flagsReady.then(update, update)
+ const off = flags.onChange(update)
+ return () => { active = false; off() }
+ }, [])
+ return flags.isEnabled(flagKey, userKey, attributes)
}
// Usage in a component
function CheckoutButton({ user }) {
- const newCheckout = useFlag('new-checkout-flow', user.id, {
- plan: user.plan,
- })
-
+ const newCheckout = useFlag('new-checkout-flow', user.id, { plan: user.plan })
return newCheckout ? :
}
```
+For server-rendered React (Next.js and others), use [`@checkgate/ssr`](/ecosystem/ssr) so the first
+paint matches the server render.
+
## Usage with Vue
-```typescript
-// composables/useFlag.ts
+```js
+// composables/useFlag.js
import { ref, onMounted, onUnmounted } from 'vue'
-import { flags } from '../lib/flags'
-
-export function useFlag(key: string, userId: string, attributes = {}) {
- const enabled = ref(flags.isEnabled(key, userId, attributes))
-
- let unsubscribe: (() => void) | null = null
+import { flags, flagsReady } from '../lib/flags'
+export function useFlag(flagKey, userKey, attributes = {}) {
+ const enabled = ref(flags.isEnabled(flagKey, userKey, attributes))
+ const update = () => { enabled.value = flags.isEnabled(flagKey, userKey, attributes) }
+ let off = null
onMounted(() => {
- unsubscribe = flags.onChange(() => {
- enabled.value = flags.isEnabled(key, userId, attributes)
- })
+ flagsReady.then(update, update)
+ off = flags.onChange(update)
})
-
- onUnmounted(() => unsubscribe?.())
-
+ onUnmounted(() => off?.())
return enabled
}
```
diff --git a/edge/README.md b/edge/README.md
index ad3f2a0a..205fa93d 100644
--- a/edge/README.md
+++ b/edge/README.md
@@ -1,80 +1,181 @@
-
-

-
@checkgate/edge
-
Evaluate Checkgate feature flags at the edge — Cloudflare Workers, Deno Deploy, Fastly, Vercel Edge, Fly.io.
-
+
+
+
-A tiny, **runtime-agnostic** edge evaluator. It owns the edge concern — pull a
-flag snapshot from your Checkgate server, cache it with a TTL and optional
-stale-while-revalidate, survive origin outages by keeping the last-known-good
-snapshot — and delegates the actual evaluation to an injected engine. In
-production that engine is the shared `@checkgate/web` WebAssembly core, so edge
-evaluation is **identical to every other Checkgate SDK**. No re-implemented
-rule / rollout / segment / prerequisite logic to drift.
+# @checkgate/edge
-Zero dependencies. Works anywhere `fetch` exists.
+Edge and server evaluator for [Checkgate](https://github.com/checkgate-sh/checkgate),
+the self-hosted feature-flag platform: fetches a flag snapshot, caches it with a
+TTL and optional stale-while-revalidate, and evaluates locally with the
+Checkgate engine.
-## Install
+**Current release: 0.2.0.** No API changes since 0.1.31; the package is
+versioned with the platform release. See the
+[changelog](https://github.com/checkgate-sh/checkgate/blob/main/CHANGELOG.md).
+
+## What it does
+
+- Fetches `GET /flags/snapshot` from your Checkgate server with the SDK key as
+ a Bearer token and loads every flag into an evaluation engine you inject.
+- Serves evaluations from memory: no network request per evaluation. Within the
+ TTL nothing is fetched; within the stale-while-revalidate window the old
+ snapshot is served while a refresh runs in the background.
+- Fails open: once a snapshot has loaded, a failed refresh keeps serving it.
+- Does not evaluate flags itself. In production the engine is
+ `@checkgate/web/core`, the same WebAssembly build of the Rust engine the
+ browser SDK uses, so results match the other SDKs.
+
+It polls; it does not hold a stream. A flag change becomes visible at the next
+refresh, so at most `ttlSeconds` (plus the stale window) after the change. It
+does not report impressions or events.
+
+## Installation
```bash
-npm install @checkgate/edge
+npm install @checkgate/edge @checkgate/web
```
-## Use
+`@checkgate/edge` has no dependencies. `@checkgate/web` provides the engine
+(`@checkgate/web/core`); any object with the same methods works (see `core`
+below).
+
+## Quick start
-```javascript
+Node.js (or any runtime where `createWasmCore()` can load the `.wasm` itself):
+
+```js
import { CheckgateEdge } from '@checkgate/edge'
import { createWasmCore } from '@checkgate/web/core'
-// Wrangler compiles a .wasm import into a WebAssembly.Module. On Node (Next.js
-// server) and in the browser, call createWasmCore() with no argument instead.
-import wasmModule from '@checkgate/web/dist/checkgate_bg.wasm'
const edge = new CheckgateEdge({
- serverUrl: 'https://flags.your-domain.com',
- sdkKey: env.CHECKGATE_SDK_KEY, // environment-scoped SDK key (Bearer)
- core: await createWasmCore(wasmModule), // the WASM evaluation engine
- ttlSeconds: 30, // re-fetch the snapshot at most this often
- staleWhileRevalidateSeconds: 60, // serve stale + refresh in background
+ serverUrl: 'https://flags.example.com',
+ sdkKey: process.env.CHECKGATE_SDK_KEY,
+ core: await createWasmCore(),
+ ttlSeconds: 30,
+ staleWhileRevalidateSeconds: 60,
})
-// On each request (fast: in-memory on a warm isolate):
-await edge.ensureFresh({ waitUntil: (p) => ctx.waitUntil(p) })
-const showIt = edge.isEnabled('new-homepage', userKey)
-const color = edge.getValue('checkout-color', userKey, {}, 'blue')
+// Per request:
+await edge.ensureFresh()
+const showIt = edge.isEnabled('new-homepage', userKey, { plan: 'pro' })
+const color = edge.getValue('checkout-color', userKey, {}, 'blue')
+```
+
+Cloudflare Workers: Wrangler compiles a `.wasm` import into a
+`WebAssembly.Module`, which `createWasmCore()` accepts. Keep the instance in a
+module global so a warm isolate reuses it, and hand background refreshes to
+`ctx.waitUntil`:
+
+```js
+import { CheckgateEdge } from '@checkgate/edge'
+import { createWasmCore } from '@checkgate/web/core'
+import wasmModule from '@checkgate/web/dist/checkgate_bg.wasm'
+
+let edge = null
+
+export default {
+ async fetch(request, env, ctx) {
+ edge ??= new CheckgateEdge({
+ serverUrl: env.CHECKGATE_URL,
+ sdkKey: env.CHECKGATE_SDK_KEY,
+ core: await createWasmCore(wasmModule),
+ staleWhileRevalidateSeconds: 60,
+ })
+ await edge.ensureFresh({ waitUntil: (p) => ctx.waitUntil(p) })
+ const userKey = request.headers.get('x-user-id') ?? 'anonymous'
+ return Response.json({ newHomepage: edge.isEnabled('new-homepage', userKey) })
+ },
+}
```
+A complete Worker with a Cron Trigger that keeps the snapshot warm is in
+[`examples/cloudflare-worker`](https://github.com/checkgate-sh/checkgate/tree/main/edge/examples/cloudflare-worker).
+
+## Configuration
+
+`new CheckgateEdge(options)`:
+
+| Option | Type | Default | Description |
+|---|---|---|---|
+| `serverUrl` | `string` | required | Checkgate server base URL. Trailing slashes are removed. |
+| `sdkKey` | `string` | required | SDK key of the environment, sent as `Authorization: Bearer`. |
+| `core` | object | required | Evaluation engine with `upsertFlag(json)`, `clear()`, `isEnabled()`, `getValue()`, `getVariant()`; normally `await createWasmCore()` from `@checkgate/web/core`. |
+| `ttlSeconds` | `number` | `30` | How long a loaded snapshot is fresh. |
+| `staleWhileRevalidateSeconds` | `number` | `0` | Extra window after the TTL in which the stale snapshot is served and refreshed in the background. |
+| `fetchImpl` | `fetch`-compatible function | `globalThis.fetch` | HTTP client. Use it to add a timeout (see below). |
+| `now` | `() => number` | `Date.now` | Clock in ms (for tests). |
+| `snapshotPath` | `string` | `/flags/snapshot` | Path appended to `serverUrl`. |
+
## API
| Member | Description |
|---|---|
-| `new CheckgateEdge({ serverUrl, sdkKey, core, ttlSeconds?, staleWhileRevalidateSeconds?, fetchImpl?, now?, snapshotPath? })` | Construct. `core` is the injected engine. |
-| `refresh()` | Fetch the snapshot and load it into the core. Concurrent calls are de-duplicated. Fails open to last-known-good. |
-| `ensureFresh({ waitUntil? })` | Load if never loaded; serve from cache within the TTL; serve stale + background-refresh within the SWR window; block-refresh beyond it. |
-| `isEnabled(key, userKey, attrs?)` / `getValue(key, userKey, attrs?, default?)` / `getVariant(key, userKey, attrs?)` | Delegate to the core. |
-| `isLoaded` / `flagCount` / `lastLoadedAt` / `ageMs()` | Introspection. |
-
-## Design
-
-- **Fail-open.** If a refresh can't reach origin, the previous snapshot keeps
- serving — an origin blip never takes your flags down. The *first* load has
- nothing to fall back to, so it surfaces the error. Two consequences: an HTTP
- error after the first load (including `401`/`403` for a revoked key) is
- ignored and the old snapshot keeps serving; and once a snapshot is older than
- TTL + stale-while-revalidate, a request waits for the refresh, which has no
- timeout of its own — pass a `fetch` that sets one (e.g. `AbortSignal.timeout`).
-- **De-duplicated refresh.** A burst of concurrent `ensureFresh()` calls triggers
- at most one snapshot fetch.
-- **Injected `core`, `fetch`, and clock.** That's what makes it dependency-free
- and fully unit-tested in plain Node (`npm test`) — no WASM build or edge runtime
- required to verify the caching/resilience logic.
-
-## Examples
-
-- [`examples/cloudflare-worker`](examples/cloudflare-worker) — per-request edge
- evaluation on Cloudflare Workers, with a Cron Trigger keeping the snapshot warm.
-- [`examples/fly`](examples/fly) — deploy the full Checkgate server multi-region
- on Fly.io.
-
----
-
-Part of [Checkgate](https://github.com/checkgate-sh/checkgate) — the self-hosted feature-flag platform.
+| `ensureFresh({ waitUntil }?)` | Never loaded: wait for a refresh. Within the TTL: nothing. Within TTL + stale window: start a background refresh (passed to `waitUntil` if given) and return. Beyond: wait for a refresh, keeping the old snapshot if it fails. |
+| `refresh()` | Fetch and load the snapshot now. Concurrent calls share one request. Resolves to `{ count, refreshed, status?, error? }`. |
+| `isEnabled(key, userKey, attrs?)` | Delegates to the core. |
+| `getValue(key, userKey, attrs?, defaultValue = null)` | Delegates to the core. |
+| `getVariant(key, userKey, attrs?)` | Delegates to the core: `{ enabled, value }` or `null`. |
+| `snapshotFlags()` | Copy of the raw flag array last loaded (empty before the first load); pass it to `@checkgate/ssr`'s `buildBootstrap()`. |
+| `isLoaded`, `flagCount`, `lastLoadedAt` | Whether a snapshot has loaded, its flag count, and when (ms, or `null`). |
+| `ageMs()` | Age of the loaded snapshot in ms (`Infinity` before the first load). |
+
+## Errors and lifecycle
+
+- The constructor throws if `serverUrl`, `sdkKey` or a usable `core` is missing,
+ or no `fetch` is available.
+- The **first** load has nothing to fall back to: `refresh()` and
+ `ensureFresh()` reject on a network error, a non-2xx status or a body that is
+ not a JSON array of flags.
+- After the first load, `ensureFresh()` never throws and the previous snapshot
+ keeps serving. `refresh()` resolves with `refreshed: false` for a network
+ error (`error`), a non-2xx status (`status`) or a body that is not an array; it
+ rejects only if the body is not valid JSON. This includes 401 and 403: a
+ revoked key keeps serving the last snapshot. Watch `ageMs()` if you need to
+ detect that.
+- Requests beyond TTL + stale window wait for the refresh, and the package sets
+ no timeout of its own. Pass a `fetchImpl` that does:
+
+ ```js
+ fetchImpl: (url, init) => fetch(url, { ...init, signal: AbortSignal.timeout(2000) }),
+ ```
+
+- Before the first load the core is empty: `isEnabled()` returns `false`,
+ `getVariant()` `null`. Call `ensureFresh()` first.
+- Each refresh replaces the whole flag set in the core.
+
+## Security considerations
+
+- Keep the SDK key in a secret binding or environment variable (for example
+ `wrangler secret put CHECKGATE_SDK_KEY`). Checkgate SDK keys are public by
+ design and limited to their environment's SDK endpoints (stream, snapshot,
+ flag reads, impressions and events; everything else is 403), but there is no
+ reason to expose one you only use server-side.
+- The snapshot contains every flag of the environment, including targeting rule
+ values and segment contents. It stays in memory unless you return it (for
+ example through `snapshotFlags()` into an HTML payload).
+- User attributes passed to evaluation are not sent anywhere.
+
+## Compatibility
+
+- ES module, no dependencies, no TypeScript declarations; `engines`:
+ Node.js >= 18. Needs a global `fetch` or `fetchImpl`.
+- Tested in CI: the unit suite (caching, stale-while-revalidate, fail-open,
+ de-duplication) on Node.js 22 with a fake core.
+- The Cloudflare Workers example is provided but not run in CI. Other edge
+ runtimes (Deno Deploy, Fastly, Vercel Edge) need only `fetch` and a way to load
+ the `.wasm` for `createWasmCore()`, and are untested.
+- Works with servers older than 0.1.31: it requests the snapshot without
+ `?v=2`, which every server answers with a plain array.
+
+## Documentation
+
+- [Edge evaluation guide](https://checkgate-sh.github.io/checkgate/ecosystem/edge)
+- [SSR and bootstrap](https://checkgate-sh.github.io/checkgate/ecosystem/ssr) (`@checkgate/ssr`)
+- [Web SDK and the shared engine](https://checkgate-sh.github.io/checkgate/sdks/web) (`@checkgate/web`)
+- [Flags snapshot endpoint](https://checkgate-sh.github.io/checkgate/api-reference#flags-snapshot-poll-fallback)
+- [Fly.io multi-region server example](https://github.com/checkgate-sh/checkgate/tree/main/edge/examples/fly)
+- [Changelog](https://github.com/checkgate-sh/checkgate/blob/main/CHANGELOG.md)
+
+## License
+
+Apache-2.0
diff --git a/edge/examples/cloudflare-worker/package.json b/edge/examples/cloudflare-worker/package.json
index b0093ad3..1d4fc2f9 100644
--- a/edge/examples/cloudflare-worker/package.json
+++ b/edge/examples/cloudflare-worker/package.json
@@ -9,8 +9,8 @@
"deploy": "wrangler deploy"
},
"dependencies": {
- "@checkgate/edge": "^0.1.20",
- "@checkgate/web": "^0.1.20"
+ "@checkgate/edge": "^0.2.0",
+ "@checkgate/web": "^0.2.0"
},
"devDependencies": {
"wrangler": "^4.0.0"
diff --git a/integrations/mcp-server/README.md b/integrations/mcp-server/README.md
index 4f9e82e0..86e1ab66 100644
--- a/integrations/mcp-server/README.md
+++ b/integrations/mcp-server/README.md
@@ -3,7 +3,7 @@
A [Model Context Protocol](https://modelcontextprotocol.io) server (stdio) that lets AI agents
read Checkgate feature flags and **propose** changes that a person approves.
-**Current version: 0.2.0.** This is the package's first release; it publishes to npm together with
+**Current version: 0.2.0.** This is the package's first release, shipped with
Checkgate 0.2.0. It needs a **Checkgate 0.2.0 server**: the `propose` token scope it relies on does
not exist on 0.1.x. What changed: [CHANGELOG](https://github.com/checkgate-sh/checkgate/blob/main/CHANGELOG.md).
diff --git a/quickstart/seed.mjs b/quickstart/seed.mjs
index bb851c2c..dd745ea7 100644
--- a/quickstart/seed.mjs
+++ b/quickstart/seed.mjs
@@ -49,5 +49,5 @@ Setup complete (development only).
Next:
(cd quickstart/node && npm install && node --env-file=../.env index.mjs)
- Python (not on PyPI yet; builds from this checkout): see docs/guide/quickstart.md
+ Python: see docs/guide/quickstart.md (pip install checkgate)
`);
diff --git a/sdks/flutter/README.md b/sdks/flutter/README.md
index fbbb4793..3b153a29 100644
--- a/sdks/flutter/README.md
+++ b/sdks/flutter/README.md
@@ -2,84 +2,21 @@
-# checkgate_flutter
-
-**Checkgate Flutter SDK (FFI)** — The official high-performance Dart client for Checkgate.
-Built fundamentally on top of Dart FFI (Foreign Function Interface), this SDK bypasses traditional asynchronous platform channels to access the Rust core evaluated completely synchronously in Dart memory.
-
-## Installation
-
-```bash
-flutter pub add checkgate_flutter
-```
-
-The package does not bundle a compiled engine: build it and link it into
-your app as described in [Linking the native engine](https://checkgate-sh.github.io/checkgate/sdks/flutter#linking-the-native-engine).
-
-## Quick Start
-
-Initialize the `CheckgateClient` instance inside your main Dart entrypoint:
-
-```dart
-import 'package:checkgate_flutter/checkgate_flutter.dart';
-
-void main() async {
- // Ensure Flutter engine is fully initialized natively
- WidgetsFlutterBinding.ensureInitialized();
-
- final checkgate = CheckgateClient(
- serverUrl: 'https://checkgate.your-company.com',
- sdkKey: 'sk_live_xxxxxx',
- );
-
- // Bind to the Checkgate SSE stream to subscribe to global flag updates
- await checkgate.connect();
-
- runApp(MyApp(checkgate: checkgate));
-}
-
-class MyApp extends StatelessWidget {
- final CheckgateClient checkgate;
-
- const MyApp({Key? key, required this.checkgate}) : super(key: key);
-
- @override
- Widget build(BuildContext context) {
- // Synchronously evaluate flag targeting parameters locally!
- final showMaterial3 = checkgate.isEnabled('material-3-design', 'user-12345', {
- 'plan': 'pro',
- });
-
- return MaterialApp(
- theme: showMaterial3 ? ThemeData.useMaterial3() : ThemeData.light(),
- home: Scaffold(...)
- );
- }
-}
-```
-
-## A/B testing: track conversions
-
-Record goal events with `track()` to measure how each flag variant converts. Pair
-a flag with a goal event in an **Experiment** in the dashboard to see per-variant
-conversion rates and statistical significance.
-
-```dart
-final variant = checkgate.getVariant('checkout-button-color', 'user_123');
-
-// …later, when the user converts:
-checkgate.track('checkout_complete', 'user_123', value: 49.99);
-```
-
-Events are buffered and reported asynchronously (best-effort), just like impressions.
-Use the **same `userKey`** you pass to `getVariant()`/`isEnabled()` so conversions
-attribute to the right variant.
-
-## Why Checkgate FFI?
-* **Synchronous FFI Evaluation:** You do not need to `await` flag resolution ever. The evaluation runs in Rust natively, avoiding Dart async blocking limits.
-* **Real-Time Propagation:** the client keeps an SSE stream open (in Dart) and applies flag changes as they arrive, falling back to polling if the stream cannot be established.
-
-The package bundles no compiled engine: build and link the Rust engine as described in
-[`dart/README.md`](dart/README.md) and the [Flutter SDK docs](https://checkgate-sh.github.io/checkgate/sdks/flutter).
-
-Review advanced patterns inside the [official Checkgate documentation](https://checkgate-sh.github.io/checkgate).
+# Checkgate Flutter SDK
+
+This directory holds the Flutter SDK, published to pub.dev as
+[`checkgate_flutter`](https://pub.dev/packages/checkgate_flutter). Flags are
+evaluated in-process by the Rust engine through Dart FFI and kept current over
+Server-Sent Events.
+
+The package bundles no compiled engine: you build the Rust engine and link it
+into your app yourself.
+
+- [`dart/README.md`](dart/README.md): the package README (installation,
+ usage, configuration, linking the engine, platform status). It is also the
+ pub.dev page, so it is the only copy.
+- [`dart/lib/`](dart/lib): the Dart client and FFI bindings.
+- [`dart/rust/`](dart/rust): the engine's C ABI, built as `libflutter`.
+- [`dart/test/`](dart/test): Dart unit tests (`flutter test`, no engine
+ needed).
+- Guide: https://checkgate-sh.github.io/checkgate/sdks/flutter
diff --git a/sdks/flutter/dart/README.md b/sdks/flutter/dart/README.md
index 0df20bb2..4779099f 100644
--- a/sdks/flutter/dart/README.md
+++ b/sdks/flutter/dart/README.md
@@ -1,48 +1,206 @@
# checkgate_flutter
-Flutter SDK for [Checkgate](https://github.com/checkgate-sh/checkgate) — local feature-flag evaluation via Rust FFI.
-
-Flags are evaluated **in-process** (no network round-trip). The SDK opens a persistent SSE stream to your Checkgate server and keeps the local flag store up to date in real time.
+Flutter and Dart client for [Checkgate](https://github.com/checkgate-sh/checkgate)
+feature flags. Flags are evaluated in-process by Checkgate's Rust engine,
+called through Dart FFI; the client keeps them current over Server-Sent Events.
+
+Current version: **0.2.0**
+([changelog](https://github.com/checkgate-sh/checkgate/blob/main/CHANGELOG.md)).
+The Dart API is the same as in 0.1.31.
+
+> **The package does not bundle a compiled engine.** It contains the Dart
+> client and the engine's Rust source, but no prebuilt library and no Flutter
+> plugin that builds one. You build the Rust engine and link it into your app
+> yourself; see "Linking the native engine" below.
+
+## What it does
+
+- Evaluates flags synchronously in the Rust engine: no `await` and no network
+ request per evaluation.
+- Opens an SSE stream (`GET /stream`) in Dart, applies each full flag set as a
+ whole on the server's `ready` event, and ignores late, duplicated or
+ reordered changes by revision.
+- Reconnects with exponential backoff and jitter, falls back to polling
+ `GET /flags/snapshot` while the stream keeps failing, and replaces a stream
+ that goes silent.
+- Optionally persists the last flag set through a storage adapter you provide.
+- Reports evaluation impressions (on by default) and goal events from
+ `track()` for experiments.
## Installation
```yaml
dependencies:
- checkgate_flutter: ^0.1.31
+ checkgate_flutter: ^0.2.0
```
-The package does not bundle a compiled engine: build it and link it into your
-app as described in [Linking the native engine](https://checkgate-sh.github.io/checkgate/sdks/flutter#linking-the-native-engine).
+```bash
+flutter pub get
+```
-## Usage
+Then build and link the engine as described below: without it, `connect()` fails because the engine library cannot be
+loaded.
-```dart
-import 'package:checkgate_flutter/checkgate_flutter.dart';
+## Minimal example
-final client = CheckgateClient(
- serverUrl: 'https://flags.example.com',
- sdkKey: 'your-sdk-key',
-);
+```dart
+import 'dart:async';
-await client.connect();
+import 'package:flutter/material.dart';
+import 'package:checkgate_flutter/checkgate_flutter.dart';
-final enabled = client.isEnabled('dark_mode', userId, {'country': 'US'});
+Future main() async {
+ WidgetsFlutterBinding.ensureInitialized();
+
+ final flags = CheckgateClient(
+ serverUrl: 'https://flags.example.com',
+ sdkKey: 'sk_live_your_key',
+ );
+ // Completes once the server has sent the full flag set. It keeps retrying
+ // while the server is unreachable, so bound the wait.
+ try {
+ await flags.connect().timeout(const Duration(seconds: 10));
+ } on TimeoutException {
+ // Evaluations return false / null until the flags arrive.
+ }
+
+ runApp(MyApp(flags: flags));
+}
+
+class MyApp extends StatelessWidget {
+ const MyApp({super.key, required this.flags});
+
+ final CheckgateClient flags;
+
+ @override
+ Widget build(BuildContext context) {
+ final newCheckout = flags.isEnabled('new-checkout', 'user-123', {'plan': 'pro'});
+ return MaterialApp(
+ home: Text(newCheckout ? 'New checkout' : 'Classic checkout'),
+ );
+ }
+}
```
-### API
-
-| Method | Description |
-|--------|-------------|
-| `connect()` | Opens the SSE stream and starts receiving flag updates. |
-| `isEnabled(flagKey, userKey, [attributes])` | Evaluates a flag locally. Returns `false` if not initialised. |
-| `close()` | Cancels the SSE subscription and frees resources. |
+## Configuration
+
+`CheckgateClient({...})` takes named parameters:
+
+| Parameter | Default | Description |
+|---|---|---|
+| `serverUrl` | required | Base URL of the Checkgate server |
+| `sdkKey` | required | SDK key of the environment |
+| `reconnectBaseDelay` | `Duration(seconds: 2)` | First reconnect delay; doubles per failed attempt, plus up to 30 % jitter |
+| `maxReconnectDelay` | `Duration(seconds: 30)` | Cap of the reconnect delay |
+| `pollFallbackThreshold` | `3` | Failed stream attempts before the client also polls `GET /flags/snapshot` |
+| `pollInterval` | `Duration(seconds: 30)` | Poll interval while polling |
+| `connectTimeout` | `Duration(seconds: 30)` | A stream attempt without the server's `connected` event in this time is abandoned and retried |
+| `streamIdleTimeout` | `null` | A connected stream that receives no complete frame for this long is reconnected. `null`: 3 × the heartbeat the server announces; servers before 0.1.31 announce none and send a keep-alive comment every 15 s, so 45 s. `Duration.zero` disables |
+| `storage` | `null` | A `CheckgateStorage` (`read(key)`, `write(key, value)`) that persists the last flag set |
+| `reportImpressions` | `true` | Report evaluations (flag key, user key, value, time) to the server |
+| `impressionBatchSize` | `50` | Flush buffered impressions and events once this many are queued |
+| `impressionFlushInterval` | `Duration(seconds: 10)` | Periodic flush interval |
+| `sendEvaluationContext` | `false` | Include user attributes in reported impressions |
+
+## API overview
+
+| Member | Description |
+|---|---|
+| `Future connect()` | Loads the engine, hydrates from `storage`, opens the stream; completes after the full flag set. Returns at once if already connected |
+| `bool isEnabled(flagKey, userKey, [attributes])` | Whether the flag is on; `false` for an unknown flag or before flags are loaded |
+| `Map? getVariant(flagKey, userKey, [attributes])` | `{'enabled': bool, 'value': ...}`, or `null` for an unknown flag or before flags are loaded |
+| `dynamic getValue(flagKey, userKey, [attributes, defaultValue])` | The resolved value, or `defaultValue` |
+| `void track(eventKey, userKey, {num? value, Map? context})` | Queues a goal event for experiments |
+| `void Function() onChange(callback)` | Calls `callback(flagKey)` after a flag is created, updated or deleted (not for the initial load); returns an unsubscribe function |
+| `bool isReady` | Whether a full flag set from the server has been applied |
+| `bool isPolling` | Whether the poll fallback is active |
+| `CheckgateStatus status` | `state` (`CheckgateConnectionState`: `idle`, `connecting`, `streaming`, `reconnecting`, `polling`, `authFailed`, `closed`), `lastSyncAt`, `error` |
+| `void close()` | Ends the stream and polling, hands queued impressions and events to a final best-effort send, and closes the HTTP client |
+
+`attributes` is a `Map` used by targeting rules, for example
+`{'plan': 'pro', 'country': 'US'}`.
+
+For experiments, pass the same `userKey` to `track()` as to the evaluation, so
+a conversion is attributed to the variant the user saw:
-## How it works
+```dart
+final variant = flags.getVariant('checkout-button-color', 'user-123');
+// later, when the user converts:
+flags.track('checkout_complete', 'user-123', value: 49.99);
+```
-1. On `connect()`, the SDK connects to `/stream` via SSE.
-2. The server sends a full flag snapshot on connect, then incremental `update` events.
-3. Each update is applied to the Rust-backed in-memory store via FFI.
-4. `isEnabled` evaluates the flag entirely in Rust — no async, no network.
+## Error handling and lifecycle
+
+- `connect()` completes with a `CheckgateAuthException` (its `statusCode` is
+ 401 or 403; the message contains no key) when the server rejects the SDK
+ key. Retries stop, flags already loaded keep being served, and calling
+ `connect()` again retries.
+- `connect()` completes with a `StateError` if `close()` is called before it
+ completes.
+- While the server is unreachable, `connect()` does not fail: it keeps
+ retrying. Use `.timeout(...)` if the caller cannot wait.
+- Evaluations never throw for an unknown flag or a missing connection; they
+ return `false`, `null` or `defaultValue`.
+- Network, parse and storage errors, failed impression or event reports, and
+ exceptions from `onChange` callbacks are swallowed; they never reach the
+ caller.
+- `close()` resets readiness: evaluations return `false` / `null` until the
+ next `connect()`, which reconnects the same client.
+- Impressions and `track()` events are only queued after the stream's
+ `connected` event has named the environment; earlier ones are dropped.
+ Reports are best-effort, at most 500 per request, and at most 10,000 are
+ buffered (the newest are kept).
+
+## Linking the native engine
+
+The Dart side opens the engine like this:
+
+| Platform | How the engine is found | Verified for 0.1.31 |
+|---|---|---|
+| iOS (device, simulator) | static library linked into the app (`DynamicLibrary.process()`) | iOS 17 simulator, x86_64: end to end |
+| macOS | static library linked into the app, as on iOS | no |
+| Android (arm64-v8a, armeabi-v7a, x86_64) | `libcheckgate_flutter.so` bundled in `jniLibs//` | no |
+| Linux | `libcheckgate_flutter.so` bundled with the app | no |
+| Windows | `checkgate_flutter.dll` bundled with the app | no |
+
+Build the engine from `sdks/flutter/dart/rust` in a clone of the repository
+checked out at the tag of your package version (the crate inherits workspace
+settings, so it does not build on its own from the pub cache). Cargo names the
+outputs `libflutter.a`, `libflutter.so` and `flutter.dll`; rename the shared
+library to the name in the table. For iOS, link the static library in whole
+(`-force_load`). The step-by-step commands are in the
+[Flutter SDK guide](https://checkgate-sh.github.io/checkgate/sdks/flutter#linking-the-native-engine).
+
+Verification in a Flutter app is recorded for 0.1.31 only, as in the table.
+For 0.2.0, CI runs the Dart unit tests without the engine, and the shared SSE
+fault-injection suite against the Dart client with the engine built as a
+Linux shared library and loaded by the Dart VM.
+
+## Platform compatibility
+
+- Dart SDK `>=3.0.0 <4.0.0`, Flutter `>=3.10.0`.
+- Flutter web is not supported: the client uses `dart:ffi`.
+- Mobile and desktop platforms: see the table above; only the iOS simulator
+ was verified end to end (for 0.1.31).
+
+## Security considerations
+
+- The SDK key ships inside your app, so treat it as visible to its users. It
+ only reaches the SDK endpoints of its environment (stream, flag reads,
+ impression and event reports). Use an `https://` server URL; the key is
+ sent as an `Authorization: Bearer` header.
+- Impressions contain the flag key, the user key you pass, the resolved value
+ and the evaluation time. Attributes are sent only with
+ `sendEvaluationContext: true`. Set `reportImpressions: false` to send none.
+- A `storage` adapter receives the raw flag configuration (rules, values),
+ under the key `checkgate:flags:`. Choose storage accordingly.
+
+## Documentation
+
+- Flutter SDK guide: https://checkgate-sh.github.io/checkgate/sdks/flutter
+- All SDKs: https://checkgate-sh.github.io/checkgate/sdks/
+- Changelog: https://github.com/checkgate-sh/checkgate/blob/main/CHANGELOG.md
+- Source: https://github.com/checkgate-sh/checkgate/tree/main/sdks/flutter/dart
## License
diff --git a/sdks/flutter/dart/lib/checkgate_bindings.dart b/sdks/flutter/dart/lib/checkgate_bindings.dart
index eaf0867c..53e6b5f4 100644
--- a/sdks/flutter/dart/lib/checkgate_bindings.dart
+++ b/sdks/flutter/dart/lib/checkgate_bindings.dart
@@ -1,8 +1,8 @@
// ignore_for_file: non_constant_identifier_names, camel_case_types
/// Raw Dart FFI bindings to libcheckgate_flutter.
///
-/// These typedefs mirror the C signatures in sdks/flutter/src/lib.rs exactly.
-/// Do not call these directly — use [CheckgateFlutterClient] instead.
+/// These typedefs mirror the C signatures in sdks/flutter/dart/rust/src/lib.rs exactly.
+/// Do not call these directly — use [CheckgateClient] instead.
library checkgate_bindings;
import 'dart:ffi';
diff --git a/sdks/node-integrations/README.md b/sdks/node-integrations/README.md
index 5035d4de..af966be4 100644
--- a/sdks/node-integrations/README.md
+++ b/sdks/node-integrations/README.md
@@ -1,96 +1,301 @@
-
+
# @checkgate/node-integrations
-Express, Fastify and NestJS integrations for [`@checkgate/node`](../nodejs/README.md):
+Express, Fastify and NestJS integrations for the Checkgate Node.js SDK
+([`@checkgate/node`](https://www.npmjs.com/package/@checkgate/node)): flags
+bound to each request's user, and the client's startup and shutdown.
-- **Flags bound to each request's user**: `req.checkgate.isEnabled('new-ui')`,
- from one shared client, with no network call per request or per evaluation.
-- **Startup that does not hang**: waits at most `readyTimeoutMs` for flags, then
- continues (cached or default values, still syncing) or fails. An SDK key
- rejected within that time fails startup.
-- **Graceful shutdown**: the client disconnects exactly once.
+**Current release: 0.2.0**, the first release of this package (new in Checkgate
+0.2.0). Changes are listed in the
+[changelog](https://github.com/checkgate-sh/checkgate/blob/main/CHANGELOG.md).
+
+## What it does
+
+- **One shared client, one evaluator per request.** Every request gets a
+ `RequestFlags` object bound to that request's user:
+ `req.checkgate.isEnabled('new-checkout')`. Evaluations are synchronous calls
+ into the client's in-memory flags: no network request per request or per
+ evaluation.
+- **Startup that does not hang.** The client's `connect()` keeps retrying while
+ the server is unreachable; the integrations wait at most `readyTimeoutMs` for
+ the first flag set, then continue (cached or default values, still syncing)
+ or fail, as you choose. An SDK key rejected within that time fails startup.
+- **Graceful shutdown.** The client is disconnected exactly once, however many
+ times close runs.
+- **Evaluations never throw.** A failure is reported to `onError` and the
+ evaluation returns its default.
+
+## Installation
```bash
npm install @checkgate/node @checkgate/node-integrations
```
-| Supported | |
+Install the framework you use as well (`express`, `fastify`, or `@nestjs/common`
+and `@nestjs/core`); each is an optional peer dependency.
+
+| Import | For |
|---|---|
-| Node.js | 22.12+ (CI: 22, 24, 26) |
-| `@checkgate/node` | `>=0.1.31 <0.3.0` |
-| `express` | 5.x |
-| `fastify` | 5.x |
-| `@nestjs/common`, `@nestjs/core` | 12.x (Express or Fastify platform) |
+| `@checkgate/node-integrations/express` | Express (any `(req, res, next)` stack) |
+| `@checkgate/node-integrations/fastify` | Fastify |
+| `@checkgate/node-integrations/nestjs` | NestJS |
+| `@checkgate/node-integrations` | the framework-independent core and `createTestClient()` |
## Express
```js
-const { checkgateMiddleware, listenWithCheckgate } = require('@checkgate/node-integrations/express')
+import express from 'express'
+import { CheckgateClient } from '@checkgate/node'
+import { checkgateMiddleware, listenWithCheckgate } from '@checkgate/node-integrations/express'
+// One client for the whole process.
+const client = new CheckgateClient({
+ serverUrl: process.env.CHECKGATE_URL,
+ sdkKey: process.env.CHECKGATE_SDK_KEY,
+})
+
+const app = express()
app.use(checkgateMiddleware({
- client, // one CheckgateClient for the process
+ client,
+ // req.user is set by your authentication (before or after this middleware).
context: (req) => (req.user ? { key: req.user.id, attributes: { plan: req.user.plan } } : null),
}))
-app.get('/', (req, res) => res.json({ v2: req.checkgate.isEnabled('new-ui') }))
-const { close } = await listenWithCheckgate(app, { client, port: 8080, readyTimeoutMs: 5000, onTimeout: 'continue' })
+app.get('/', (req, res) => {
+ res.json({
+ newCheckout: req.checkgate.isEnabled('new-checkout'),
+ theme: req.checkgate.getValue('checkout-theme', 'light'),
+ })
+})
+
+// Waits up to 5 s for flags, then listens either way.
+const { server, close } = await listenWithCheckgate(app, { client, port: 8080, readyTimeoutMs: 5000 })
+console.log(`listening on port ${server.address().port}`)
+
+// Stop accepting connections, finish requests in flight, then disconnect.
process.once('SIGTERM', () => close().then(() => process.exit(0)))
```
+`listenWithCheckgate()` installs no signal handlers. If you create the HTTP
+server yourself, call `startCheckgate(client, options)` before `listen()` and
+`stopCheckgate(client)` after `server.close()` (same import). In TypeScript,
+importing the module adds `checkgate: RequestFlags` to Express's `Request`.
+
## Fastify
```js
-await fastify.register(require('@checkgate/node-integrations/fastify'), {
+import Fastify from 'fastify'
+import { checkgatePlugin } from '@checkgate/node-integrations/fastify'
+
+const app = Fastify()
+
+// Creates the client, connects while the plugin loads, disconnects on close.
+await app.register(checkgatePlugin, {
clientOptions: { serverUrl: process.env.CHECKGATE_URL, sdkKey: process.env.CHECKGATE_SDK_KEY },
- context: (request) => (request.user ? { key: request.user.id } : null),
+ context: (request) => (request.user ? { key: request.user.id, attributes: { plan: request.user.plan } } : null),
+ readyTimeoutMs: 5000,
})
-fastify.get('/', async (request) => ({ v2: request.checkgate.isEnabled('new-ui') }))
+
+app.get('/', async (request) => ({ newCheckout: request.checkgate.isEnabled('new-checkout') }))
+
+const address = await app.listen({ port: 8080 })
+console.log(`listening on ${address}`)
+process.once('SIGTERM', () => app.close().then(() => process.exit(0)))
```
+Pass `clientOptions` to let the plugin build the client, or `client` to use
+one you built; either way it is disconnected in `onClose`. `fastify.checkgate`
+is the shared client and `request.checkgate` the request's evaluator. The
+plugin is not encapsulated, so routes in every child plugin see both.
+`readyTimeoutMs` must be below Fastify's `pluginTimeout` (10 s by default),
+otherwise registration fails.
+
## NestJS
```ts
-@Module({ imports: [CheckgateModule.forRoot({ clientOptions: { serverUrl, sdkKey }, context: (req) => req.user?.id })] })
+import 'reflect-metadata'
+import { Controller, Get, Module } from '@nestjs/common'
+import { NestFactory } from '@nestjs/core'
+import { Checkgate, CheckgateModule, RequireFlag, type RequestFlags } from '@checkgate/node-integrations/nestjs'
+
+@Controller()
+class AppController {
+ @Get()
+ home(@Checkgate() flags: RequestFlags) {
+ return { newCheckout: flags.isEnabled('new-checkout') }
+ }
+
+ @Get('beta')
+ @RequireFlag('beta') // 404 unless 'beta' is on for this request's user
+ beta() {
+ return { beta: true }
+ }
+}
+
+@Module({
+ imports: [
+ CheckgateModule.forRoot({
+ clientOptions: { serverUrl: process.env.CHECKGATE_URL!, sdkKey: process.env.CHECKGATE_SDK_KEY },
+ context: (req) => (req.user ? { key: req.user.id, attributes: { plan: req.user.plan } } : null),
+ readyTimeoutMs: 5000,
+ }),
+ ],
+ controllers: [AppController],
+})
class AppModule {}
-@Get() page(@Checkgate() flags: RequestFlags) { return { v2: flags.isEnabled('new-ui') } }
-@Get('beta') @RequireFlag('beta') beta() { /* 404 unless on for this user */ }
+async function bootstrap() {
+ const app = await NestFactory.create(AppModule)
+ app.enableShutdownHooks() // SIGTERM/SIGINT run onApplicationShutdown: the client disconnects
+ await app.listen(8080)
+ console.log('listening on port 8080')
+}
+void bootstrap()
```
-`forRootAsync()`, `CheckgateService`, `forTesting()` and the guard-ordering
-rules are in the docs.
+Compile with `"experimentalDecorators": true` (Nest's decorators). The module
+is global by default (`isGlobal: true`): import it once, in the root module.
+`CheckgateService` connects the client in `onApplicationBootstrap` (so
+`app.listen()` waits, within `readyTimeoutMs`) and disconnects it in
+`onApplicationShutdown`, which runs on `app.close()` and, with
+`enableShutdownHooks()`, on SIGTERM/SIGINT.
+
+`@RequireFlag()` evaluates in a guard, and Nest runs guards global, then
+controller, then method. Put authentication at the global or controller level
+(or list `@RequireFlag()` above `@UseGuards(AuthGuard)` on the method) so that
+`req.user` is set when the flag is evaluated.
-## Notes
+## Configuration
+| Option | Where | Default | Description |
+|---|---|---|---|
+| `client` | all | none | The one `CheckgateClient` shared by the app (required for Express). |
+| `clientOptions` | Fastify, NestJS | none | [`CheckgateClient` options](https://checkgate-sh.github.io/checkgate/sdks/nodejs#new-checkgateclient-options) to build the client; pass this or `client`, not both. |
+| `context` | all | `{ key: req.user.id }` when there is a `req.user`, else anonymous | `(req) => ({ key, attributes })`, a bare key, or `null` for anonymous. |
+| `defaultKey` | all | `'anonymous'` | User key when the context has none (missing or empty). |
+| `onError` | all | logs to `console.error` | `(err, info)`, called when an evaluation, the `context` function or `track()` fails. |
+| `readyTimeoutMs` | all | `5000` | How long startup waits for the first flag set (0 to 2^31 - 1 ms). |
+| `onTimeout` | all | `'continue'` | `'continue'`: start with cached or default values and keep syncing. `'fail'`: disconnect and reject with `CheckgateStartupTimeoutError`. |
+| `logger` | Express `listenWithCheckgate()`, NestJS | `console` | Receives the timeout warning (Fastify uses `fastify.log`). |
+| `port`, `host` | Express `listenWithCheckgate()` | `0` (any free port), all interfaces | Where to listen. |
+| `isGlobal` | NestJS | `true` | Register the module globally. |
+
+## API overview
+
+- **`RequestFlags`** (`req.checkgate`, `request.checkgate`, `@Checkgate()`):
+ `isEnabled(flag)` (`false` if off, missing or on error), `getVariant(flag)`
+ (`{ enabled, value }` or `null`), `getValue(flag, default)`,
+ `track(eventKey, { value?, context? })`, and `context` (the normalized
+ `{ key, attributes }`).
+- **Lifecycle:** `startCheckgate(client, { readyTimeoutMs, onTimeout, logger })`
+ resolves `{ ready, timedOut }`; `stopCheckgate(client)` disconnects once and
+ returns whether this call did. Exported from every entry point.
+- **Express:** `checkgateMiddleware(options)`,
+ `listenWithCheckgate(app, options)` resolving `{ server, startup, close }`.
+- **Fastify:** `checkgatePlugin`, also the default export. From TypeScript
+ ES modules, use the named import: the default import does not type-check
+ there.
+- **NestJS:** `CheckgateModule.forRoot(options)`,
+ `forRootAsync({ imports, inject, useFactory })`, `forTesting(flags)`;
+ `CheckgateService` (`client`, `startup`, `forRequest(req)`,
+ `forContext({ key, attributes })` for jobs and consumers); `@Checkgate()`;
+ `@RequireFlag(flag, { status: 404 | 403 })`; the `CHECKGATE_CLIENT` and
+ `CHECKGATE_OPTIONS` injection tokens.
+- **Core:** `createRequestFlags()`, `normalizeAttributes()`,
+ `normalizeContext()`, `defaultContext()`, `CheckgateStartupTimeoutError`.
+- **Testing:** `createTestClient(flags)`, an in-memory client with no server
+ and no native addon, usable as the `client` of any adapter:
+
+ ```js
+ import { createTestClient } from '@checkgate/node-integrations'
+
+ const client = createTestClient({
+ 'new-checkout': true, // on
+ 'checkout-theme': 'dark', // on, serving 'dark'
+ beta: ({ key }) => key === 'alice', // per user
+ })
+ client.setFlag('new-checkout', false) // change a flag mid-test
+ ```
+
+ `null` means off and an unlisted key is a missing flag; `disconnectCalls`
+ and `tracked` record what the app did.
+
+TypeScript declarations are included for every entry point.
+
+## Request context and isolation
+
+- Nothing about a request is stored on the shared client. Each request gets
+ its own `RequestFlags`; in NestJS it is cached on the request object, so a
+ guard and a handler parameter share one context. No NestJS provider is
+ REQUEST-scoped, so controllers and services are not rebuilt per request.
- `context(req)` is called once per request, on the first evaluation, so it
- can read `req.user` set by auth middleware that runs later.
-- Attributes are coerced for the evaluation core: finite numbers, bigints and
- booleans become strings; `null`, `undefined`, objects, arrays, dates and other
- values are dropped. Nothing a request supplies can make an evaluation throw.
-- `createTestClient(flags)` (from the package root) is an in-memory client for
- tests: no server, no native addon.
+ sees `req.user` even when authentication runs after the Checkgate
+ middleware. A `context` function that throws is reported to `onError` and the
+ request is treated as anonymous.
+- Attributes are converted before they reach the engine, which only accepts
+ strings: strings are kept; finite numbers, bigints and booleans become
+ strings (`30` becomes `"30"`, so numeric operators work); `null`,
+ `undefined`, `NaN`, `Infinity`, objects, arrays, dates, symbols and functions
+ are dropped (a rule on them behaves as if the attribute were missing).
+ Convert dates yourself, for example with `toISOString()`.
-Full guide: [Express, Fastify and NestJS](https://checkgate-sh.github.io/checkgate/sdks/node-frameworks).
+## Errors and lifecycle
-## Examples
+| | The server answers in time | It does not | It rejects the SDK key (401/403) |
+|---|---|---|---|
+| `onTimeout: 'continue'` (default) | starts with live flags | starts, logs a warning, serves the client's offline cache (if its `storage` has one) or defaults, and keeps syncing | startup fails with `CheckgateAuthError` if the rejection arrives within `readyTimeoutMs` |
+| `onTimeout: 'fail'` | starts with live flags | startup fails with `CheckgateStartupTimeoutError` (`timeoutMs`, `state`); the client is disconnected | startup fails with `CheckgateAuthError` |
-Runnable apps in [`examples/`](examples), reading `CHECKGATE_URL` and
-`CHECKGATE_SDK_KEY` from the environment:
+A key rejected after startup does not stop the app; watch
+`client.getStatus()` or `client.getHealth()` to detect it. On shutdown each
+adapter calls `client.disconnect()` exactly once.
-```bash
-npm ci
-CHECKGATE_URL=http://localhost:3000 CHECKGATE_SDK_KEY= node examples/express/server.mjs
-CHECKGATE_URL=http://localhost:3000 CHECKGATE_SDK_KEY= node examples/fastify/server.mjs
-npx tsc -p examples/nestjs && CHECKGATE_URL=http://localhost:3000 CHECKGATE_SDK_KEY= node examples/nestjs/dist/main.js
-```
+## Compatibility
+
+| | Supported |
+|---|---|
+| Node.js | 22.12 or later (`engines: ">=22.12.0"`); CI tests 22, 24 and 26 |
+| `@checkgate/node` | `>=0.1.31 <0.3.0` |
+| `express` | 5.x |
+| `fastify` | 5.x (`fastify-plugin` is a dependency of this package) |
+| `@nestjs/common`, `@nestjs/core` | 12.x, on the Express or Fastify platform |
+
+This package is CommonJS and loads NestJS 12 (published as ES modules only)
+with `require()`, which Node.js supports from 22.12. Your application can be
+CommonJS or ES modules. Express 4, Fastify 4 and NestJS 11 are not tested and
+not declared as supported peers. The adapters cover HTTP; for other Nest
+transports use `CheckgateService.forContext()`.
+
+## Security considerations
+
+- Targeting attributes are evaluated in the process. They are sent to the
+ Checkgate server only if the client is created with
+ `sendEvaluationContext: true`; the user key is sent with impressions and
+ goal events unless `reportImpressions` is off.
+- Nothing a request supplies can make an evaluation throw: attribute values
+ are coerced or dropped, `__proto__` keys are ignored, and errors go to
+ `onError`.
+- Keep the SDK key in configuration or a secret store, and use an `https://`
+ `serverUrl` outside local development.
+- `@RequireFlag()` answers 404 by default, so a disabled route looks like a
+ missing one; use `{ status: 403 }` to say it exists.
+
+## Documentation
+
+- [Express, Fastify and NestJS guide](https://checkgate-sh.github.io/checkgate/sdks/node-frameworks)
+- [Node.js SDK](https://checkgate-sh.github.io/checkgate/sdks/nodejs)
+- [SDK diagnostics](https://checkgate-sh.github.io/checkgate/operations/sdk-diagnostics)
+- [Changelog](https://github.com/checkgate-sh/checkgate/blob/main/CHANGELOG.md)
+- Runnable example apps: [`examples/`](https://github.com/checkgate-sh/checkgate/tree/main/sdks/node-integrations/examples) in the repository
## Development
-The tests run the real `@checkgate/node` client and native addon against the
-fake Checkgate server in `sdks/conformance/fault-server.mjs`:
+From `sdks/node-integrations` in a checkout of the repository. The tests run
+the real `@checkgate/node` client and native addon against the fake Checkgate
+server in `sdks/conformance/fault-server.mjs`:
```bash
(cd ../nodejs && npm ci && npm run build:debug) # needs a Rust toolchain
@@ -98,3 +303,7 @@ npm ci
npm run typecheck
npm test
```
+
+## License
+
+Apache-2.0
diff --git a/sdks/node-integrations/examples/fastify/server.mjs b/sdks/node-integrations/examples/fastify/server.mjs
index f1ce388f..1e655139 100644
--- a/sdks/node-integrations/examples/fastify/server.mjs
+++ b/sdks/node-integrations/examples/fastify/server.mjs
@@ -4,7 +4,7 @@
// curl -H 'x-user-id: alice' -H 'x-plan: pro' http://localhost:8080/
import Fastify from 'fastify'
-import checkgate from '@checkgate/node-integrations/fastify'
+import { checkgatePlugin } from '@checkgate/node-integrations/fastify'
const app = Fastify({ logger: { level: 'warn' } })
@@ -17,7 +17,7 @@ app.addHook('onRequest', async (request) => {
// The plugin builds the client, connects while loading (up to 5 s; then the
// app starts with cached or default values) and disconnects on close.
-await app.register(checkgate, {
+await app.register(checkgatePlugin, {
clientOptions: {
serverUrl: process.env.CHECKGATE_URL ?? 'http://localhost:3000',
sdkKey: process.env.CHECKGATE_SDK_KEY,
diff --git a/sdks/nodejs/README.md b/sdks/nodejs/README.md
index eb9ba721..08e8fbd9 100644
--- a/sdks/nodejs/README.md
+++ b/sdks/nodejs/README.md
@@ -1,79 +1,226 @@
-
+
# @checkgate/node
-**Checkgate Node.js SDK (NAPI)** — The official high-performance, native Node.js client for Checkgate.
-This SDK is built on top of the Rust native codebase, powered by NAPI-RS for in-process feature flag evaluation directly in your server.
+Checkgate feature-flag SDK for Node.js servers. Flags are evaluated locally by
+the Checkgate Rust engine, loaded as a native addon.
+
+**Current release: 0.2.0.** Changes are listed in the
+[changelog](https://github.com/checkgate-sh/checkgate/blob/main/CHANGELOG.md).
+
+## What it does
+
+- Connects once to your Checkgate server over Server-Sent Events (`GET /stream`),
+ receives the full flag set, then applies live updates as flags change.
+- Evaluates flags in process, synchronously: `isEnabled()`, `getVariant()`,
+ `getValue()` and `getDetails()` make no network request per evaluation.
+- Reconnects with exponential backoff and jitter. If the stream cannot be
+ established repeatedly (for example, a proxy that blocks long-lived
+ connections), it falls back to polling `GET /flags/snapshot` and switches
+ back to the stream when it recovers.
+- Keeps serving the last known flags while disconnected, and can persist them
+ through an optional `storage` adapter so a restarted process evaluates before
+ it reconnects.
+- Reports evaluation impressions and `track()` goal events in batches, in the
+ background (for experiments). User attributes are not sent unless you opt in.
## Installation
```bash
npm install @checkgate/node
-# or
-pnpm add @checkgate/node
-# or
-yarn add @checkgate/node
```
-## Quick Start
+The package ships prebuilt native binaries (see [Compatibility](#compatibility));
+nothing is compiled on install.
-Initialize the Checkgate client with your unique server URL and SDK key:
+## Minimal example
-```typescript
+```js
import { CheckgateClient } from '@checkgate/node'
-const checkgate = new CheckgateClient({
- serverUrl: 'http://localhost:3000', // Your self-hosted Checkgate server URL
- sdkKey: 'sk_live_xxxxxxxx', // Your secure server-side SDK Key
+// One client per process, created at startup and shared.
+const client = new CheckgateClient({
+ serverUrl: process.env.CHECKGATE_URL, // e.g. http://localhost:3000
+ sdkKey: process.env.CHECKGATE_SDK_KEY,
})
-async function run() {
- // Connect via SSE to instantly stream flag rules
- await checkgate.connect()
+await client.connect() // resolves once the full flag set has arrived
- // Evaluate features locally (no network call)
- const showFeature = checkgate.isEnabled('new-dashboard', 'user_123', {
- email: 'user@example.com'
- })
+// Synchronous, in memory: no network request per evaluation.
+const attributes = { plan: 'pro' }
+console.log(client.isEnabled('new-checkout', 'user-123', attributes)) // true / false
+console.log(client.getValue('checkout-theme', 'user-123', attributes, 'light')) // the variant, or 'light' if the flag is missing
+console.log(client.getDetails('new-checkout', 'user-123', attributes)) // { enabled, value, reason, ... }
- if (showFeature) {
- console.log("Welcome to the new dashboard!")
- }
-}
-
-run()
+client.disconnect() // on shutdown
```
-## Connection health
-
-A stream that goes silent for 3 server heartbeats (45 s by default) is dropped
-and reconnected. A rejected SDK key (HTTP 401/403) is not retried: `connect()`
-rejects with `CheckgateAuthError` and the last known flags keep being served.
-`client.getStatus()` returns `{ state, lastSyncAt, error }` so you can tell how
-fresh the flags are. See the [SDK docs](https://checkgate-sh.github.io/checkgate/sdks/).
-
-## A/B testing: track conversions
+CommonJS works the same way: `const { CheckgateClient } = require('@checkgate/node')`.
+
+Create **one client per process** and share it (a module-level singleton). Each
+client holds one stream to the server and a copy of the flags; creating one per
+request opens a connection per request.
+
+## Configuration
+
+`new CheckgateClient(options)`:
+
+| Option | Type | Default | Description |
+|---|---|---|---|
+| `serverUrl` | `string` | (required) | Base URL of your Checkgate server. |
+| `sdkKey` | `string` | none | SDK key of the environment, sent as `Authorization: Bearer`. Leave unset only for a server in open (development) mode. |
+| `reconnectDelayMs` | `number` | `3000` | Base reconnect delay; grows exponentially, with up to 30% jitter. |
+| `maxReconnectDelayMs` | `number` | `30000` | Upper bound of the reconnect delay. |
+| `pollFallbackThreshold` | `number` | `3` | Consecutive failed stream reconnects before polling `/flags/snapshot`. `Infinity` disables polling. |
+| `pollIntervalMs` | `number` | `30000` | Poll interval while in poll fallback. |
+| `connectTimeoutMs` | `number` | `30000` | A stream attempt without the server's `connected` event within this time is abandoned and retried. |
+| `streamIdleTimeoutMs` | `number` | 3 × the server's heartbeat interval (45 s by default) | A connected stream with no event (heartbeats included) for this long is reconnected. No idle timeout against servers older than 0.1.31, which announce no heartbeat. `0` disables it. |
+| `reportImpressions` | `boolean` | `true` | Report evaluation events for analytics and experiments. |
+| `impressionBatchSize` | `number` | `50` | Flush buffered impressions once this many have accumulated. |
+| `impressionFlushIntervalMs` | `number` | `10000` | Periodic flush interval for impressions and `track()` events. |
+| `sendEvaluationContext` | `boolean` | `false` | Include user attributes in reported impressions. Off by default, so attributes never leave the process. |
+| `storage` | `{ getItem(key), setItem(key, value) }` | none | Optional persistence adapter (sync or async). The last flag set is saved and loaded on the next start, so flags evaluate before or without a connection. |
+
+## API overview
+
+| Method | Returns | Description |
+|---|---|---|
+| `connect()` | `Promise` | Opens the stream and resolves once the first complete flag set has arrived (from the stream, or from a poll in poll fallback). Call once at startup; calling it again while connecting returns the same promise. |
+| `isEnabled(flagKey, userKey, attributes?)` | `boolean` | `false` if the flag does not exist. |
+| `getVariant(flagKey, userKey, attributes?)` | `{ enabled, value } \| null` | `value` is a boolean, string, number or JSON value; `null` if the flag does not exist. |
+| `getValue(flagKey, userKey, attributes?, defaultValue = null)` | `FlagValue` | The resolved value, or `defaultValue` if the flag does not exist. |
+| `getDetails(flagKey, userKey, attributes?)` | `EvaluationDetails \| null` | New in 0.2.0. The same evaluation plus `reason` (`DISABLED`, `PREREQUISITE_FAILED`, `TARGETING_MATCH`, `ROLLOUT_EXCLUDED`, `SPLIT`, `DEFAULT`, `STATIC`) and, when they apply, `ruleIndex`, `rolloutBucket`, `variantIndex` and `prerequisites`. |
+| `track(eventKey, userKey, { value?, context? }?)` | `void` | Records a goal event for experiments; buffered and sent in the background. Use the same `userKey` as for evaluations. |
+| `onChange(callback)` | unsubscribe function | Called with the key of each flag that changes after the initial bootstrap. |
+| `getStatus()` | `{ state, lastSyncAt, error }` | Connection state: `idle`, `connecting`, `streaming`, `reconnecting`, `polling`, `auth_failed` or `closed`. |
+| `onStatusChange(callback)` | unsubscribe function | New in 0.2.0. Called with `getStatus()` whenever the state changes, and after each poll while in poll fallback. |
+| `getHealth()` | `CheckgateHealth` | New in 0.2.0. Diagnostics (schema 1): `ready`, `source`, `flagCount`, `configAgeMs`, revisions, reconnect and poll counters, `lastError`, `offlineCache`. Local state only. |
+| `isReady()` / `isPolling()` | `boolean` | Whether the bootstrap has completed; whether poll fallback is active. |
+| `disconnect()` | `void` | Closes the stream, stops polling, flushes buffered impressions and events. |
+
+`userKey` is a stable user identifier; percentage rollouts and weighted
+variants hash it. `attributes` is a `Record` read by targeting
+rules. TypeScript declarations are included (`index.d.ts`).
+
+## Initialization, health and shutdown
+
+```js
+import { CheckgateClient, CheckgateAuthError } from '@checkgate/node'
+
+const client = new CheckgateClient({
+ serverUrl: process.env.CHECKGATE_URL,
+ sdkKey: process.env.CHECKGATE_SDK_KEY,
+})
-Record goal events with `track()` to measure how each flag variant converts. Pair
-a flag with a goal event in an **Experiment** in the dashboard to see per-variant
-conversion rates and statistical significance.
+client.onStatusChange(({ state, error }) => console.log('checkgate:', state, error?.message ?? ''))
+
+// connect() keeps retrying while the server is unreachable, so bound the wait.
+let timer
+const timeout = new Promise((resolve) => { timer = setTimeout(resolve, 5000, false) })
+try {
+ const ready = await Promise.race([client.connect().then(() => true), timeout])
+ if (!ready) console.warn('Flags not loaded yet: serving defaults, still connecting')
+} catch (err) {
+ if (!(err instanceof CheckgateAuthError)) throw err
+ console.error(`SDK key rejected (HTTP ${err.status})`) // not retried
+} finally {
+ clearTimeout(timer)
+}
-```typescript
-const variant = checkgate.getVariant('checkout-button-color', 'user_123')
+// e.g. behind a readiness probe
+const health = client.getHealth()
+const fresh = health.ready && health.configAgeMs !== null && health.configAgeMs < 5 * 60_000
+console.log({ fresh, state: health.state, source: health.source, flagCount: health.flagCount })
-// …later, when the user converts:
-checkgate.track('checkout_complete', 'user_123', { value: 49.99 })
+process.once('SIGTERM', () => client.disconnect())
```
-Events are buffered and reported asynchronously (best-effort), just like impressions.
-Use the **same `userKey`** you pass to `getVariant()`/`isEnabled()` so conversions
-attribute to the right variant.
-
-## Why Checkgate?
-* **In-Process Evaluation:** Flags are evaluated in memory via Rust native bindings, in a few microseconds per call.
-* **Instant Propagation:** Leverages SSE (Server Sent Events) to distribute flag toggles, typically within tens of milliseconds, without polling.
-* **Self-Hosted Privacy:** Keep your user data strictly within your own infrastructure bounds.
-
-For more information and detailed architecture designs, check out the [official Checkgate documentation](https://checkgate-sh.github.io/checkgate).
+## Error handling and lifecycle
+
+- **`connect()` rejects** with `CheckgateAuthError` (`err.status` is 401 or
+ 403) when the server rejects the SDK key, and with an `Error` if
+ `disconnect()` is called before it completes. While the server is unreachable
+ it does not reject; it keeps retrying. A caller that does not await it gets
+ no unhandled rejection.
+- **A rejected key is not retried.** The state becomes `auth_failed`, the flags
+ already loaded keep being served, and calling `connect()` again retries.
+- **Before the first flag set** (and without a hydrated `storage` snapshot),
+ evaluations return `false` / `null` / `defaultValue` and log a warning.
+- **While disconnected**, evaluations answer from the last known flags.
+ `Date.now() - getStatus().lastSyncAt` is how old they may be; `getHealth()`
+ has `configAgeMs` and `lastError` (`{ message, kind, at }`, not cleared by a
+ later success).
+- **Attribute values must be strings.** A non-string value for an attribute
+ that a rule reads makes `isEnabled()` throw and `getVariant()`,
+ `getValue()` and `getDetails()` answer as if the flag were missing.
+ Attributes no rule reads are not checked.
+- **Listeners** passed to `onChange()` and `onStatusChange()` that throw are
+ logged and do not affect the client.
+- **Shutdown:** call `disconnect()` once on graceful shutdown. It flushes
+ buffered impressions and events (best effort, not awaited) and sets the
+ state to `closed`. A later `connect()` starts again.
+- Impression and event reporting is best effort: a batch that fails to send
+ is dropped, not retried, and the buffers keep at most the newest 10,000
+ entries.
+
+## Compatibility
+
+- **Node.js:** the package declares no `engines` range. CI tests the SDK with
+ its native addon on Node.js 22, 24 and 26. Node.js 20 reached end of life on
+ 2026-04-30 and is not tested.
+- **Prebuilt binaries** (one package, no install script):
+
+ | Platform | Binary |
+ |---|---|
+ | Linux x64, glibc | `checkgate.linux-x64-gnu.node` |
+ | Linux arm64, glibc | `checkgate.linux-arm64-gnu.node` |
+ | Linux x64, musl (Alpine) | `checkgate.linux-x64-musl.node` |
+ | macOS x64 | `checkgate.darwin-x64.node` |
+ | macOS arm64 (Apple Silicon) | `checkgate.darwin-arm64.node` |
+ | Windows x64 | `checkgate.win32-x64-msvc.node` |
+
+ Other platforms (for example Linux arm64 with musl, or Windows arm64) have
+ no binary, and loading the package fails there.
+- **Server-only.** It is a native addon for Node.js; it does not run in
+ browsers or edge runtimes. In Next.js, keep it out of the server bundle with
+ `serverExternalPackages: ['@checkgate/node']`.
+- **Servers:** the SDK protocol is unchanged in 0.2.0, so this SDK works with
+ 0.1.31 and 0.2.0 servers. Against servers older than 0.1.31, polls replace the
+ whole flag set (no per-flag revision ordering) and there is no stream idle
+ timeout.
+
+Related packages: `@checkgate/openfeature-provider` (OpenFeature server
+provider) and `@checkgate/node-integrations` (Express, Fastify, NestJS), both
+new in 0.2.0.
+
+## Security considerations
+
+- SDK keys are tied to one environment and can only reach the SDK endpoints
+ (stream, snapshot, reading flags, reporting impressions and events). Still,
+ keep the key in configuration or a secret store rather than in source.
+- The key travels in the `Authorization` header: use an `https://` `serverUrl`
+ outside local development.
+- Targeting attributes stay in the process unless you set
+ `sendEvaluationContext: true`. User keys are sent with impressions and
+ `track()` events; set `reportImpressions: false` to stop impressions.
+- `getHealth()` and `CheckgateAuthError` messages never contain the SDK key,
+ user keys or attributes.
+- With `storage`, the persisted flag set is stored under a key namespaced by
+ the server URL and a SHA-256 digest of the SDK key (not the key itself). The
+ flag rules themselves are stored as plain JSON; protect the storage
+ accordingly.
+
+## Documentation
+
+- [Node.js SDK guide](https://checkgate-sh.github.io/checkgate/sdks/nodejs)
+- [SDK diagnostics](https://checkgate-sh.github.io/checkgate/operations/sdk-diagnostics) (`getHealth()`, `onStatusChange()`)
+- [Upgrading to 0.2.0](https://checkgate-sh.github.io/checkgate/operations/upgrading-to-0-2-0)
+- [OpenFeature provider](https://checkgate-sh.github.io/checkgate/sdks/openfeature) and [Express, Fastify and NestJS](https://checkgate-sh.github.io/checkgate/sdks/node-frameworks)
+- [Changelog](https://github.com/checkgate-sh/checkgate/blob/main/CHANGELOG.md)
+- [Source and issues](https://github.com/checkgate-sh/checkgate)
+
+## License
+
+Apache-2.0
diff --git a/sdks/nodejs/index.d.ts b/sdks/nodejs/index.d.ts
index 04495657..cbfe0205 100644
--- a/sdks/nodejs/index.d.ts
+++ b/sdks/nodejs/index.d.ts
@@ -51,7 +51,7 @@ export interface EvaluationDetails extends FlagEvaluation {
export interface CheckgateClientOptions {
/** Base URL of your Checkgate server. */
serverUrl: string;
- /** SDK key for authentication. Leave unset for open (dev-only) mode. */
+ /** SDK key for authentication. Required: the server has no unauthenticated mode. */
sdkKey?: string;
/** Base SSE reconnect delay in milliseconds; grows exponentially. Default: 3000. */
reconnectDelayMs?: number;
diff --git a/sdks/openfeature-provider/README.md b/sdks/openfeature-provider/README.md
index 4172dba1..e7403ccb 100644
--- a/sdks/openfeature-provider/README.md
+++ b/sdks/openfeature-provider/README.md
@@ -1,51 +1,207 @@
# @checkgate/openfeature-provider
-[OpenFeature](https://openfeature.dev) provider for [Checkgate](https://github.com/checkgate-sh/checkgate)
-(Node.js, server paradigm). Flags are evaluated in-process by the Checkgate Rust engine that
-powers [`@checkgate/node`](https://www.npmjs.com/package/@checkgate/node): no network request
-per evaluation, the same results as calling the SDK directly.
+[OpenFeature](https://openfeature.dev) provider for Checkgate (Node.js, server
+paradigm). Flags are evaluated locally by the Checkgate Rust engine in
+[`@checkgate/node`](https://www.npmjs.com/package/@checkgate/node): no network
+request per evaluation.
+
+**Current release: 0.2.0**, the first release of this package (new in Checkgate
+0.2.0). Changes are listed in the
+[changelog](https://github.com/checkgate-sh/checkgate/blob/main/CHANGELOG.md).
+
+## What it does
+
+- Implements the OpenFeature server `Provider` interface on top of a
+ `CheckgateClient`. Code written against the OpenFeature API keeps working.
+- Answers every evaluation with the client's `getDetails()`: the same engine,
+ the same results as calling `@checkgate/node` directly, with Checkgate's
+ reason mapped to OpenFeature's.
+- Maps the client's connection state onto the provider lifecycle (`READY`,
+ `STALE`, `ERROR`, `FATAL`) and flag changes onto
+ `PROVIDER_CONFIGURATION_CHANGED`.
+- Forwards OpenFeature `track()` calls as Checkgate goal events.
+
+## Installation
```bash
npm install @checkgate/openfeature-provider @checkgate/node @openfeature/server-sdk
```
+`@checkgate/node` (the engine, `>=0.2.0 <1`) and `@openfeature/server-sdk`
+(`^1.17.0`) are peer dependencies, so your application installs them once.
+
+## Minimal example
+
```typescript
import { OpenFeature } from '@openfeature/server-sdk'
import { CheckgateProvider } from '@checkgate/openfeature-provider'
const provider = new CheckgateProvider({
- serverUrl: process.env.CHECKGATE_URL!,
+ serverUrl: process.env.CHECKGATE_URL!, // e.g. http://localhost:3000
sdkKey: process.env.CHECKGATE_SDK_KEY!,
+ initTimeoutMs: 5000,
})
-await OpenFeature.setProviderAndWait(provider)
+await OpenFeature.setProviderAndWait(provider) // resolves when the first flag set has arrived
const client = OpenFeature.getClient()
-const enabled = await client.getBooleanValue('new-checkout', false, {
- targetingKey: 'user-123',
- plan: 'pro',
-})
+const context = { targetingKey: 'user-123', plan: 'pro' }
+const enabled = await client.getBooleanValue('new-checkout', false, context)
+const theme = await client.getStringDetails('checkout-theme', 'light', context)
+console.log(enabled, theme.value, theme.reason, theme.flagMetadata)
+
+await OpenFeature.close() // on shutdown: disconnects the client the provider created
+```
+
+Register the provider once per process, at startup. Use
+`OpenFeature.setProviderAndWait(domain, provider)` to bind it to a domain
+instead of the default provider.
+
+To use the same connection directly as well, create the client yourself and
+pass it in; the provider then never disconnects it:
+
+```typescript
+import { OpenFeature } from '@openfeature/server-sdk'
+import { CheckgateClient } from '@checkgate/node'
+import { CheckgateProvider } from '@checkgate/openfeature-provider'
+
+const checkgate = new CheckgateClient({ serverUrl: process.env.CHECKGATE_URL!, sdkKey: process.env.CHECKGATE_SDK_KEY })
+await OpenFeature.setProviderAndWait(new CheckgateProvider({ client: checkgate }))
+
+checkgate.isEnabled('new-checkout', 'user-123', { plan: 'pro' }) // same flags, direct call
```
-- `targetingKey` is the user key; other context fields are targeting attributes (numbers,
- booleans and dates are converted to strings; objects and arrays are left out).
-- Reasons: `DISABLED`, `TARGETING_MATCH`, `SPLIT`, `DEFAULT`, `STATIC`, and the custom
- `PREREQUISITE_FAILED`. `flagMetadata` carries `checkgateReason`, `ruleIndex`,
- `variantIndex` and `rolloutBucket` when they apply.
-- Lifecycle: `READY` after the first flag set, `STALE` while reconnecting (last known flags
- are still served), `FATAL` if the SDK key is rejected at startup. `initTimeoutMs` bounds the
- startup wait.
-- `new CheckgateProvider({ client })` shares an existing `CheckgateClient`; the provider never
- disconnects a client it did not create.
+## Configuration
+
+| Option | Default | Description |
+|---|---|---|
+| `client` | none | An existing `CheckgateClient`. The provider connects it if needed and never disconnects it. |
+| `serverUrl`, `sdkKey`, ... | none | Without `client`: any [`CheckgateClient` option](https://checkgate-sh.github.io/checkgate/sdks/nodejs#new-checkgateclient-options); the provider creates, connects and on close disconnects its own client. `serverUrl` is then required. |
+| `initTimeoutMs` | no limit | Stop waiting for the first flag set after this many milliseconds: `initialize()` fails (provider `ERROR`), the client keeps connecting in the background, and the provider turns `READY` when it succeeds. |
+| `requireTargetingKey` | `true` | Resolve `TARGETING_KEY_MISSING` when the context has no `targetingKey`. With `false`, a missing key is evaluated as the empty string (fine for flags without percentage rollouts or weighted variants). |
+
+## Evaluation context
+
+| OpenFeature context field | Checkgate |
+|---|---|
+| `targetingKey` | the user key (percentage rollouts and weighted variants hash it) |
+| string | attribute, unchanged |
+| finite number, boolean | attribute, converted to a string (`30` becomes `"30"`; numeric operators still compare numerically) |
+| `Date` | attribute, as an ISO-8601 string |
+| object, array, `null`, `NaN`, `Infinity` | left out |
+
+The mapping is exported as `toAttributes(context)`.
+
+## Value types
-Full documentation: [OpenFeature provider](https://checkgate-sh.github.io/checkgate/sdks/openfeature).
+| OpenFeature call | Checkgate flag type |
+|---|---|
+| `getBooleanValue` / `getBooleanDetails` | boolean |
+| `getStringValue` / `getStringDetails` | string |
+| `getNumberValue` / `getNumberDetails` | integer |
+| `getObjectValue` / `getObjectDetails` | JSON (object or array) |
+
+A flag whose value has another type resolves `TYPE_MISMATCH`. A flag that is
+off (or on with no value configured) and has no value of the requested type
+returns your default without an error. `variant` is the resolved value as a
+string for boolean, string and number flags.
+
+## Reasons and errors
+
+| Checkgate result | OpenFeature `reason` |
+|---|---|
+| `DISABLED` (flag switched off) | `DISABLED` |
+| `PREREQUISITE_FAILED` | `PREREQUISITE_FAILED` (custom reason) |
+| `TARGETING_MATCH` (a rule matched) | `TARGETING_MATCH` |
+| `SPLIT` and `ROLLOUT_EXCLUDED` (percentage rollout or weighted variant, in or out) | `SPLIT` |
+| `DEFAULT` (rules present, none matched) | `DEFAULT` |
+| `STATIC` (no rules, rollout or variants) | `STATIC` |
+
+`flagMetadata.checkgateReason` carries the exact Checkgate reason, plus
+`ruleIndex`, `variantIndex` and `rolloutBucket` when they apply. The mapping is
+exported as `REASONS`.
+
+On an error, OpenFeature returns your default value with `reason: 'ERROR'` and
+one of these `errorCode`s:
+
+| `errorCode` | When |
+|---|---|
+| `FLAG_NOT_FOUND` | The flag does not exist in the environment. |
+| `TYPE_MISMATCH` | The flag resolved to a value of another type (see above). |
+| `TARGETING_KEY_MISSING` | No `targetingKey` in the context and `requireTargetingKey` is `true`. |
+| `PROVIDER_NOT_READY` | The provider has not finished initializing (also after an `initTimeoutMs` timeout, until the first flag set arrives). |
+| `PROVIDER_FATAL` | The SDK key was rejected before the first flag set. |
+
+## Provider lifecycle
+
+| Checkgate client | Provider status / event |
+|---|---|
+| first flag set received | `READY` |
+| stream lost, reconnecting (last known flags still served) | `STALE` |
+| poll fallback with polls failing (flags still served) | `STALE` |
+| stream back, or polls succeeding again | `READY` |
+| `initTimeoutMs` elapsed before the first flag set | `ERROR`, then `READY` when it arrives |
+| `initTimeoutMs` elapsed, flags loaded from the client's `storage` cache | `READY`, then `STALE` until the server is reached |
+| SDK key rejected before the first flag set | `FATAL` (`setProviderAndWait` rejects) |
+| SDK key rejected later | `ERROR` (held flags keep being served) |
+
+A flag change emits `PROVIDER_CONFIGURATION_CHANGED` with `flagsChanged`; the
+flags of one snapshot are reported in one event. `OpenFeature.close()` calls
+the provider's `onClose()`, which unsubscribes from the client and disconnects
+it only if the provider created it.
+
+## Tracking
+
+`client.track('checkout', { targetingKey: 'user-123' }, { value: 49.99 })`
+records a Checkgate goal event for experiments: a numeric `value` becomes the
+event value and the remaining details its context. Calls without a
+`targetingKey` are ignored.
+
+## Local evaluation
+
+Evaluations never reach the network: the client holds the flags in memory,
+kept current by one stream (or poll fallback) per client. While disconnected,
+evaluations keep answering from the last known flags and the provider reports
+`STALE`. Impressions are reported in the background as configured on the
+client (`reportImpressions`, `sendEvaluationContext`).
+
+## Compatibility
+
+- Node.js: the package declares `engines: { node: ">=20" }`; CI tests it on
+ Node.js 22, 24 and 26 (Node.js 20 reached end of life on 2026-04-30).
+- `@openfeature/server-sdk` `^1.17.0` (CI tests 1.23.0), server paradigm only.
+- `@checkgate/node` `>=0.2.0 <1`, which also sets the supported platforms
+ (prebuilt native binaries for Linux, macOS and Windows; see its README).
+- CommonJS package with TypeScript declarations; `import` from ES modules works.
+
+## Security considerations
+
+- The SDK key and `serverUrl` are passed to `@checkgate/node`; keep the key in
+ configuration or a secret store and use an `https://` server URL outside
+ local development.
+- Context attributes are used for local evaluation only. They leave the process
+ only if the client is created with `sendEvaluationContext: true`; the
+ `targetingKey` is sent as the user id of impressions and tracked events.
+- Error messages from a rejected SDK key do not contain the key.
+
+## Documentation
+
+- [OpenFeature provider guide](https://checkgate-sh.github.io/checkgate/sdks/openfeature)
+- [Node.js SDK](https://checkgate-sh.github.io/checkgate/sdks/nodejs) (client options, `getDetails()`)
+- [SDK diagnostics](https://checkgate-sh.github.io/checkgate/operations/sdk-diagnostics)
+- [Changelog](https://github.com/checkgate-sh/checkgate/blob/main/CHANGELOG.md)
+- [Source and issues](https://github.com/checkgate-sh/checkgate)
## Development
+From `sdks/openfeature-provider` in a checkout of the repository:
+
```bash
(cd ../nodejs && npm ci && npm run build) # the native engine
npm ci && npm run typecheck && npm test
node bench/overhead.mjs # provider overhead vs. direct SDK calls
```
+## License
+
Apache-2.0
diff --git a/sdks/python/README.md b/sdks/python/README.md
index 6003bb18..004fa6ef 100644
--- a/sdks/python/README.md
+++ b/sdks/python/README.md
@@ -1,26 +1,57 @@
-# Checkgate Python SDK
+# checkgate (Python SDK)
-Feature flags for Python services, evaluated **locally** by Checkgate's Rust
-engine (the same code the server and every other Checkgate SDK run) and kept
-current over Server-Sent Events, with a polling fallback.
+Feature flags for Python services. Flags are evaluated locally by
+[Checkgate](https://github.com/checkgate-sh/checkgate)'s Rust engine, the same
+code the server and the other Checkgate SDKs run, and kept current over
+Server-Sent Events with a polling fallback.
-- Evaluation is a synchronous, in-process call: no network round trip and no
- `await`. It is safe to call from any number of threads.
-- Sync runs on one background daemon thread using only the standard library
- (`http.client`, `threading`): no asyncio inside the client, so it never
- blocks or depends on your event loop.
-- CPython 3.11+ (abi3 wheels). The only runtime dependency is the bundled
- extension module.
+Current version: **0.2.0**, the first release of the Python SDK
+([changelog](https://github.com/checkgate-sh/checkgate/blob/main/CHANGELOG.md)).
-> Status: new in 0.2.0. Wheels are built for Linux x86_64/aarch64 (manylinux),
-> macOS x86_64/arm64 and Windows x86_64; see [Platform support](#platform-support)
-> for which of them are tested.
+## What it does
-## Install
+- Evaluates flags in-process: an evaluation is a synchronous function call
+ with no network request and no `await`, safe to call from any number of
+ threads.
+- Syncs on one background daemon thread that uses only the standard library
+ (`http.client`, `threading`). There is no asyncio inside the client, so it
+ does not depend on or block your event loop.
+- Applies each full flag set as a whole and ignores late, duplicated or
+ reordered change events by revision, so an evaluation never sees a
+ half-applied update.
+- Reconnects with exponential backoff, falls back to polling while the stream
+ keeps failing, and can persist the last flag set for offline starts.
+- Has no runtime dependencies besides its bundled extension module.
-**Not on PyPI yet.** Do not install a `checkgate` package from PyPI until the project announces
-it. Build from a checkout instead (needs Rust and Python 3.11+; see [Development](#development)).
-Once published, it will install with `pip install checkgate`.
+## Installation
+
+```bash
+pip install checkgate==0.2.0
+```
+
+Wheels are published for the platforms under "Platform compatibility" below;
+0.2.0 is the package's first release. To build a wheel from source instead
+(for example on a platform without a wheel), you need CPython 3.11 or newer
+and a Rust toolchain (with rustup, the version pinned in the repository's
+`rust-toolchain.toml` is installed automatically):
+
+```bash
+git clone --branch v0.2.0 https://github.com/checkgate-sh/checkgate.git
+cd checkgate
+python3 -m venv .venv
+.venv/bin/pip install "maturin>=1.9.4,<2"
+.venv/bin/maturin build --release --manifest-path sdks/python/Cargo.toml --out dist
+.venv/bin/pip install dist/checkgate-0.2.0-*.whl
+```
+
+The last command installs into the clone's `.venv`; run the same
+`pip install dist/...whl` with your application's interpreter to install it
+there. On Windows, use `.venv\Scripts\` instead of `.venv/bin/`.
+
+The release workflow builds wheels for the platforms listed under
+"Platform compatibility" below and no source distribution,
+so pip finds nothing to install on other platforms. Building from source there
+is untested.
## Quick start
@@ -29,170 +60,356 @@ from checkgate import CheckgateClient, CheckgateTimeoutError
client = CheckgateClient("https://flags.example.com", sdk_key="sk_live_your_key")
try:
- client.connect(timeout=10) # waits for the full flag set
+ client.connect(timeout=10) # waits for the full flag set
except CheckgateTimeoutError:
- pass # serve defaults; keeps connecting in the background
+ pass # evaluations return defaults; the client keeps connecting in the background
+user_id = "user-123"
if client.is_enabled("new-checkout", user_id, {"plan": "pro"}):
- ...
+ print("new checkout")
color = client.get_value("button-color", user_id, default="blue")
client.close()
```
-asyncio code waits without blocking the loop:
+In asyncio code, `await client.connect_async(timeout=10)` waits without
+blocking the event loop. Evaluation stays synchronous everywhere; call it
+directly from async handlers.
-```python
-await client.connect_async(timeout=10)
-```
+## Configuration
-Framework examples: [`examples/`](examples) (FastAPI lifespan, Flask app
-factory, Django `AppConfig.ready()`, gunicorn `post_fork`).
+`CheckgateClient(server_url, sdk_key=None, *, ...)`. `server_url` must be an
+`http://` or `https://` URL. All options are keyword-only:
-## API
+| Option | Default | Description |
+|---|---|---|
+| `reconnect_delay_ms` | `3000` | Base stream reconnect delay; doubles per failed attempt, plus up to 30 % jitter |
+| `max_reconnect_delay_ms` | `30000` | Cap of the reconnect delay (before jitter) |
+| `poll_fallback_threshold` | `3` | Failed stream attempts before the client also polls `GET /flags/snapshot`; `None` disables polling |
+| `poll_interval_ms` | `30000` | Poll interval while polling |
+| `connect_timeout_ms` | `30000` | A stream that has not sent `connected` within this time is abandoned and retried |
+| `stream_idle_timeout_ms` | `None` | A connected stream silent this long is replaced. `None`: 3 × the heartbeat interval the server announces (no idle timeout against servers older than 0.1.31, which announce none); `0` disables |
+| `request_timeout_ms` | `30000` | Socket timeout of a poll request |
+| `storage` | `None` | Offline cache: `FileStorage(directory)`, `MemoryStorage()`, or any object with `get_item(key)` and `set_item(key, value)` |
-### `CheckgateClient(server_url, sdk_key=None, *, ...)`
+Invalid values raise `ValueError` (or `TypeError` for a `storage` without
+those two methods) from the constructor.
-| Option | Default | |
-|---|---|---|
-| `reconnect_delay_ms` | 3000 | base stream reconnect delay; doubles per failed attempt |
-| `max_reconnect_delay_ms` | 30000 | cap of the delay (plus 0–30 % jitter) |
-| `poll_fallback_threshold` | 3 | failed stream attempts before also polling `GET /flags/snapshot`; `None` disables |
-| `poll_interval_ms` | 30000 | poll interval while polling |
-| `connect_timeout_ms` | 30000 | a stream that has not sent `connected` within this is abandoned and retried |
-| `stream_idle_timeout_ms` | 3 × server heartbeat | a silent connected stream is treated as dead; `0` disables; none against servers before 0.1.31 |
-| `request_timeout_ms` | 30000 | socket timeout of a poll request |
-| `storage` | `None` | offline persistence (`FileStorage(dir)`, `MemoryStorage()`, or any object with `get_item`/`set_item`) |
+## API overview
### Evaluation
| Method | Returns |
|---|---|
-| `is_enabled(flag, user_id, attributes=None)` | `bool`; `False` for an unknown flag |
-| `get_value(flag, user_id, attributes=None, default=None)` | the resolved value (`bool`, `str`, `int`, `float`, `dict`, `list`, `None`), or `default` for an unknown flag |
-| `get_variant(flag, user_id, attributes=None)` | `Variant(enabled, value)` or `None` |
-| `get_details(flag, user_id, attributes=None, default=None)` | `EvaluationDetails`: value, `reason`, `rule_index`, `rollout_bucket`, `variant_index`, prerequisite trace, `error_code` |
-
-`attributes` is a mapping of strings. **Values that are not strings are
-skipped** (attribute rules compare strings), exactly as the web, React
-Native and Flutter SDKs do; the Node SDK raises instead. Pass
+| `is_enabled(flag_key, user_id, attributes=None)` | `bool`; `False` for an unknown flag |
+| `get_value(flag_key, user_id, attributes=None, default=None)` | the resolved value (`bool`, `str`, `int`, `float`, `dict`, `list` or `None`), or `default` for an unknown flag |
+| `get_variant(flag_key, user_id, attributes=None)` | `Variant(enabled, value)`, or `None` for an unknown flag |
+| `get_details(flag_key, user_id, attributes=None, default=None)` | `EvaluationDetails`: `flag_key`, `value`, `enabled`, `reason`, `checkgate_reason`, `rule_index`, `rollout_bucket`, `variant_index`, `prerequisites`, `error_code`, `error_message` |
+
+`attributes` is a mapping of attribute names to strings. Values that are not
+strings are skipped, because attribute rules compare strings (the Web, React
+Native and Flutter SDKs do the same; the Node SDK raises instead). Pass
`str(value)` to target on a number.
-Before the first flag set has arrived (and with no offline cache) every
-evaluation returns its default, and `get_details` reports `PROVIDER_NOT_READY`.
-
-`get_details().reason` follows OpenFeature: `STATIC`, `DEFAULT`,
-`TARGETING_MATCH`, `SPLIT`, `DISABLED`, `PREREQUISITE_FAILED`, or `ERROR`
-(with `error_code` `FLAG_NOT_FOUND` or `PROVIDER_NOT_READY`).
-`checkgate_reason` keeps the engine's own reason, which also distinguishes
-`ROLLOUT_EXCLUDED` (mapped to `SPLIT`).
+`get_details().reason` uses the OpenFeature vocabulary: `STATIC`, `DEFAULT`,
+`TARGETING_MATCH`, `SPLIT`, `DISABLED`, `PREREQUISITE_FAILED`, or `ERROR` with
+`error_code` `FLAG_NOT_FOUND` or `PROVIDER_NOT_READY`. `checkgate_reason` is
+the engine's own reason, which also distinguishes `ROLLOUT_EXCLUDED` (reported
+as `SPLIT`).
### Lifecycle and status
-| | |
+| Method | Description |
|---|---|
-| `connect(timeout=None)` | blocks until the full flag set is applied. Raises `CheckgateAuthError` (key rejected, HTTP 401/403: not retried), `CheckgateTimeoutError` (also a `TimeoutError`; keeps connecting in the background) or `CheckgateClosedError` |
-| `await connect_async(timeout=None)` | the same, without blocking the event loop or an executor thread |
-| `close(timeout=2.0)` | stops syncing and releases the connection; idempotent. Also `with CheckgateClient(...) as client:` |
-| `on_change(callback) -> unsubscribe` | `callback(flag_key)` after a flag is created, updated or deleted (not for the initial bootstrap). Runs on the sync thread: keep it short, do not call `connect()` from it |
-| `get_status()` | `{"state", "last_sync_at_ms", "error"}`; `state` is `idle`, `connecting`, `streaming`, `reconnecting`, `polling`, `auth_failed` or `closed` |
-| `get_health()` | sync diagnostics (schema 1): state, readiness, source (`none`/`offline_cache`/`server`), flag count, config age, revisions, stale events ignored, reconnects, polling, last error, offline cache. Contains no SDK key, user id or attribute |
-
-After `close()`: `connect()` raises `CheckgateClosedError`; evaluations keep
-answering from the last flags held (requests still in flight during shutdown
-are not disrupted) but never change again; `on_change` registers nothing.
-
-## How syncing works
-
-The client opens `GET /stream`. On every (re)connect the server replays the
-full flag set and sends `ready`; the replay is staged and swapped in whole,
-so evaluations never see a half-applied set. Afterwards each change arrives as
-a revisioned delta; an event that is not newer than what the client holds
-(late, duplicated, reordered) is ignored. A stream that goes silent for 3
-heartbeats is replaced; reconnects back off exponentially with jitter, and
-after 3 failed attempts the client also polls `/flags/snapshot?v=2`, merging
-per flag by revision so a delayed replay cannot roll back newer polled state.
-HTTP 401/403 stops all retries (`auth_failed`) and keeps the last flags.
-
-The flag set is swapped atomically in the engine: a flag and its
-prerequisites always come from the same version, even while another thread
-applies an update.
-
-## Workers, `fork()` and preloading
-
-A client must be created **in the process that uses it**. A client created
-before `os.fork()` raises `CheckgateForkError` when used in the child: the
-child inherits the client's memory but not its sync thread, and possibly a
-lock that some parent thread held at the instant of the fork (which would
-deadlock the child). The client detects the fork (`os.register_at_fork`) and
-refuses instead of silently serving flags that never update.
-
-- **gunicorn without `--preload`, uvicorn `--workers`, Django runserver**: each
- worker imports your app, so creating the client at startup just works (one
- stream per worker).
-- **gunicorn `--preload` / `preload_app = True`**: create the client in
- `post_fork` (see [`examples/gunicorn.conf.py`](examples/gunicorn.conf.py)) or
- lazily on first use (see [`examples/flask_app.py`](examples/flask_app.py)).
-- **uWSGI**: its default (`lazy-apps = false`) loads the app in the master
- and forks; set `lazy-apps = true` or create the client in a
- `@postfork` function.
-- **multiprocessing with the `fork` start method**: create the client in the
- worker function.
-
-Each worker holds its own stream connection and flag set. Point several
-workers at one `FileStorage` directory if you like: writes are atomic renames
-(last writer wins).
+| `connect(timeout=None)` | Blocks until the full flag set is applied (`timeout` in seconds; `None` waits indefinitely). Returns at once if already in sync |
+| `await connect_async(timeout=None)` | The same for asyncio, without blocking the event loop or an executor thread |
+| `close(timeout=2.0)` | Stops syncing and releases the connection; waits up to `timeout` seconds for the background threads. Idempotent |
+| `on_change(callback)` | Calls `callback(flag_key)` after a flag is created, updated or deleted (not for the initial load). Returns an unsubscribe function |
+| `is_ready()` | Whether a complete flag set from the server has been applied |
+| `is_polling()` | Whether the poll fallback is active |
+| `get_status()` | `{"state", "last_sync_at_ms", "error"}`; `state` is one of `idle`, `connecting`, `streaming`, `reconnecting`, `polling`, `auth_failed`, `closed` |
+| `get_health()` | Sync diagnostics (schema 1): state, readiness, source (`none`, `offline_cache`, `server`), flag count, config age, revisions, stale events ignored, reconnects, polling, last error, offline cache |
+
+The client is also a context manager: `with CheckgateClient(...) as client:`
+and `async with CheckgateClient(...) as client:` close it on exit.
+
+## Error handling
+
+All exceptions derive from `CheckgateError`:
+
+| Exception | Raised by | Meaning |
+|---|---|---|
+| `CheckgateAuthError` | `connect()`, `connect_async()` | The server rejected the SDK key (HTTP 401/403; `.status` holds the code). Not retried; flags already loaded keep being served. Call `connect()` again to retry |
+| `CheckgateTimeoutError` | `connect()`, `connect_async()` | Not connected within `timeout`. Also a `TimeoutError`. The client keeps connecting in the background |
+| `CheckgateClosedError` | `connect()`, `connect_async()` | The client was closed, before or while connecting |
+| `CheckgateForkError` | evaluations, `connect()`, `connect_async()`, `on_change()`, `get_status()`, `get_health()` | The client was created before `os.fork()` and used in the child; see "Threads, workers and fork" below |
+
+Evaluations do not raise for an unknown flag or a missing connection:
+
+- Before the first flag set has arrived (and with no offline cache), every
+ evaluation returns its default, `get_details()` reports `PROVIDER_NOT_READY`,
+ and the client logs one warning.
+- A flag this SDK version cannot parse is not served (it evaluates as
+ unknown) and a warning is logged.
+- Network errors and unusable responses are retried, logged on the
+ `checkgate` logger and recorded in `get_health()["last_error"]`. An
+ exception raised by an `on_change` callback is logged. None of these reach
+ the caller.
+
+## Threads, workers and fork
+
+Evaluations run on the caller's thread and never wait for the sync thread.
+`on_change` callbacks run on the sync thread: keep them short, and do not call
+`connect()` from one (it raises `RuntimeError`).
+
+`close()` is terminal for syncing: `connect()` afterwards raises
+`CheckgateClosedError`, and `on_change` registers nothing. Evaluations keep
+answering from the last flags held, so requests still in flight during
+shutdown are not disrupted, but the flags no longer change.
+
+Create the client **in the process that uses it**. A client created before
+`os.fork()` raises `CheckgateForkError` when used in the child: the child
+inherits the client's memory but not its sync thread, and possibly a lock a
+parent thread held at the moment of the fork, which would deadlock it. The
+client detects the fork (`os.register_at_fork`) and refuses instead of
+serving flags that never update.
+
+- **gunicorn without `--preload`, `uvicorn --workers`, Django `runserver`**:
+ each worker imports the app, so creating the client at app startup works
+ (one stream per worker).
+- **gunicorn `--preload` / `preload_app = True`**: the app is imported in the
+ master before the fork. Create the client in gunicorn's `post_fork` hook, or
+ lazily on first use (as the Flask example below does), and do not also
+ create it in code that runs in the master.
+- **uWSGI**: the default `lazy-apps = false` loads the app in the master and
+ forks. Set `lazy-apps = true`, or create the client in a `@postfork`
+ function.
+- **`multiprocessing` with the `fork` start method**: create the client in
+ the worker function.
+
+Each worker process holds its own stream connection and flag set.
+
+## Framework examples
+
+Complete versions are in
+[`sdks/python/examples`](https://github.com/checkgate-sh/checkgate/tree/main/sdks/python/examples).
+They read `CHECKGATE_URL` and `CHECKGATE_SDK_KEY` from the environment
+(Django from settings).
+
+### FastAPI
+
+The lifespan runs in every uvicorn worker, so each worker gets its own client.
+
+```python
+import os
+from contextlib import asynccontextmanager
+
+from fastapi import FastAPI, Request
+
+from checkgate import CheckgateClient, CheckgateTimeoutError
+
+
+@asynccontextmanager
+async def lifespan(app: FastAPI):
+ client = CheckgateClient(os.environ["CHECKGATE_URL"], os.environ["CHECKGATE_SDK_KEY"])
+ try:
+ await client.connect_async(timeout=10)
+ except CheckgateTimeoutError:
+ pass # start anyway: defaults until the flags arrive
+ app.state.flags = client
+ yield
+ client.close()
+
+
+app = FastAPI(lifespan=lifespan)
+
+
+@app.get("/checkout")
+def checkout(request: Request, user_id: str, plan: str = "free"):
+ flags: CheckgateClient = request.app.state.flags
+ return {"checkout": "v2" if flags.is_enabled("new-checkout", user_id, {"plan": plan}) else "v1"}
+```
+
+### Django
+
+Create the client in `AppConfig.ready()` and close it at exit:
+
+```python
+# myapp/flags.py
+import atexit
+from typing import Optional
+
+from django.conf import settings
+
+from checkgate import CheckgateClient, CheckgateTimeoutError
+
+client: Optional[CheckgateClient] = None
+
+
+def start() -> CheckgateClient:
+ global client
+ if client is None:
+ client = CheckgateClient(settings.CHECKGATE_URL, settings.CHECKGATE_SDK_KEY)
+ try:
+ client.connect(timeout=5)
+ except CheckgateTimeoutError:
+ pass
+ atexit.register(client.close)
+ return client
+
+
+# myapp/apps.py
+from django.apps import AppConfig
+
+
+class MyAppConfig(AppConfig):
+ name = "myapp"
+
+ def ready(self) -> None:
+ from . import flags
+
+ flags.start()
+```
+
+In views, use `flags.client.is_enabled(...)`. With gunicorn `--preload` or
+uWSGI's default `lazy-apps = false`, `ready()` runs in the master: call
+`flags.start()` from a post-fork hook instead of from `ready()`.
+
+### Flask
+
+Flask's `teardown_appcontext` runs after every request, so close the client at
+process exit. Creating it lazily on first use works with or without gunicorn
+`--preload`:
+
+```python
+import atexit
+import os
+import threading
+
+from flask import Flask, current_app, request
+
+from checkgate import CheckgateClient, CheckgateTimeoutError
+
+_lock = threading.Lock()
+
+
+def get_flags() -> CheckgateClient:
+ """The process's client, created on first use (after any fork)."""
+ client = current_app.extensions.get("checkgate")
+ if client is None:
+ with _lock:
+ client = current_app.extensions.get("checkgate")
+ if client is None:
+ config = current_app.config
+ client = CheckgateClient(config["CHECKGATE_URL"], config["CHECKGATE_SDK_KEY"])
+ try:
+ client.connect(timeout=5)
+ except CheckgateTimeoutError:
+ pass
+ atexit.register(client.close)
+ current_app.extensions["checkgate"] = client
+ return client
+
+
+def create_app() -> Flask:
+ app = Flask(__name__)
+ app.config["CHECKGATE_URL"] = os.environ["CHECKGATE_URL"]
+ app.config["CHECKGATE_SDK_KEY"] = os.environ["CHECKGATE_SDK_KEY"]
+
+ @app.get("/")
+ def index():
+ enabled = get_flags().is_enabled("new-homepage", request.args.get("user", "anonymous"))
+ return {"homepage": "new" if enabled else "classic"}
+
+ return app
+```
## Offline cache
```python
from checkgate import CheckgateClient, FileStorage
-client = CheckgateClient(url, key, storage=FileStorage("/var/cache/myapp/checkgate"))
+client = CheckgateClient(
+ "https://flags.example.com",
+ sdk_key="sk_live_your_key",
+ storage=FileStorage("/var/cache/myapp/checkgate"),
+)
```
The last complete flag set is saved after every change and loaded on the next
-start, before connecting, so a restart while the server is unreachable serves
-the last known flags instead of defaults (`get_health()["source"] ==
-"offline_cache"`). Files are named by a hash and hold flag configuration only.
-
-## Limitations
+`connect()`, before the stream opens, so a restart while the server is
+unreachable serves the last known flags instead of defaults
+(`get_health()["source"] == "offline_cache"`). Writes are atomic renames, so
+several workers may share one directory (the last writer wins). Storage errors
+are logged and ignored.
-- **No impression reporting or `track()`** in this release: the Python SDK
- sends nothing but its stream and poll requests. Experiment analytics need
- another SDK or the HTTP API.
-- **No HTTP proxy support** (`HTTP(S)_PROXY` is not read: `http.client` does
- not support it). TLS uses the system's default trust store.
-- **CPython only**, 3.11 or newer. The abi3 wheel does not load on
- free-threaded (`3.13t`) builds.
-- Evaluations are synchronous and take microseconds; the GIL is released
- inside the engine, but the attribute conversion runs with it held.
+## Platform compatibility
-## Platform support
+CPython 3.11 or newer, one abi3 wheel per platform. The abi3 wheel does not
+load on free-threaded builds (`3.13t`, `3.14t`); other interpreters such as
+PyPy are not supported.
-| Platform | Wheel built by | Test suite run by |
+| Platform | Release wheel | Tested on that platform |
|---|---|---|
-| Linux x86_64 (manylinux) | release workflow, CI | CI `sdk-python` (Python 3.11 and 3.13), release workflow |
-| Linux aarch64 (manylinux) | release workflow (cross) | python-wheels workflow, on a native build (Python 3.11) |
-| macOS arm64 | release workflow | release workflow |
-| macOS x86_64 | release workflow (cross) | python-wheels workflow, on a native build (Python 3.11) |
-| Windows x86_64 | release workflow | release workflow (fork tests skip) |
+| Linux x86_64 (manylinux) | built on x86_64 | the release wheel (3.11); CI and python-wheels workflow (3.11, 3.13) |
+| Linux aarch64 (manylinux) | cross-built on x86_64 | python-wheels workflow on an arm64 runner (3.11), including a wheel built the way the release builds it; the release wheel itself is not run |
+| macOS arm64 | built on arm64 | the release wheel (3.11); python-wheels workflow (3.11, 3.13) |
+| macOS x86_64 | cross-built on arm64 | python-wheels workflow on an Intel runner (3.11), with a natively built wheel; the release wheel itself is not run |
+| Windows x86_64 | built on x64 | the release wheel (3.11); python-wheels workflow (3.11). The fork tests are skipped |
+
+The release workflow runs the test suite against the wheels it publishes on
+Linux x86_64, macOS arm64 and Windows x86_64. The python-wheels workflow
+builds and tests wheels natively on every listed platform for pull requests
+that change the engine or this SDK. There are no wheels for musllinux
+(Alpine), 32-bit platforms or Windows on Arm.
+
+## Limitations
-The python-wheels workflow builds and tests a wheel natively on each platform for pull requests
-that touch the engine or this SDK. No workflow publishes wheels yet: the release workflow builds
-them but neither uploads them to PyPI nor attaches them to the GitHub release.
+- No impression reporting and no `track()`: the client sends nothing but its
+ stream and poll requests. Experiment analytics need another SDK or the HTTP
+ API.
+- No HTTP proxy support: `HTTP_PROXY` / `HTTPS_PROXY` are not read
+ (`http.client` does not support them).
+
+## Security considerations
+
+- Use an `https://` server URL in production: the SDK key is sent as an
+ `Authorization: Bearer` header on every stream and poll request. TLS
+ certificates and host names are verified with Python's default SSL context
+ (the system trust store).
+- An SDK key only reaches the SDK endpoints of its environment. Keep it in
+ configuration or a secret store, not in source code.
+- User ids and attributes stay in the process: nothing about an evaluation is
+ sent to the server.
+- `get_health()` and `get_status()` contain no SDK key, user id or attribute;
+ `CheckgateAuthError` carries only the HTTP status. `get_health()` is
+ suitable for an internal health endpoint.
+- `FileStorage` holds flag configuration only. Files are named by a hash (no
+ server URL or key in the name) and created readable by the owner only.
+
+## Documentation
+
+- Python SDK guide: https://checkgate-sh.github.io/checkgate/sdks/python
+- All SDKs: https://checkgate-sh.github.io/checkgate/sdks/
+- Changelog: https://github.com/checkgate-sh/checkgate/blob/main/CHANGELOG.md
+- Source: https://github.com/checkgate-sh/checkgate/tree/main/sdks/python
## Development
+From `sdks/python` in a clone of the repository (Rust toolchain and Node.js
+needed):
+
```bash
-cd sdks/python
-python3.11 -m venv .venv
+python3 -m venv .venv
.venv/bin/pip install "maturin>=1.9.4,<2" pytest
VIRTUAL_ENV=$PWD/.venv .venv/bin/maturin develop --release
.venv/bin/python -m pytest tests -q
node --test --test-concurrency=1 ../conformance/python.mjs # SSE fault-injection suite
-.venv/bin/python tool/bench.py # evaluation latency
```
`src/lib.rs` is the extension module (`checkgate._core`, evaluation only);
`python/checkgate/` is the client.
+
+## License
+
+Apache-2.0
diff --git a/sdks/python/pyproject.toml b/sdks/python/pyproject.toml
index 9f066c97..e58fe5e3 100644
--- a/sdks/python/pyproject.toml
+++ b/sdks/python/pyproject.toml
@@ -28,7 +28,7 @@ dependencies = []
[project.urls]
Homepage = "https://github.com/checkgate-sh/checkgate"
-Documentation = "https://github.com/checkgate-sh/checkgate/blob/main/docs/sdks/python.md"
+Documentation = "https://checkgate-sh.github.io/checkgate/sdks/python"
Repository = "https://github.com/checkgate-sh/checkgate"
[tool.maturin]
diff --git a/sdks/react-native/README.md b/sdks/react-native/README.md
index 37606223..c0b43eb8 100644
--- a/sdks/react-native/README.md
+++ b/sdks/react-native/README.md
@@ -1,47 +1,54 @@
-
+
# @checkgate/react-native
-**Checkgate React Native SDK (JSI)** — The official high-performance mobile client for Checkgate.
-Powered by a direct JSI (JavaScript Interface) natively bridging to Rust, this SDK completely avoids strictly serialized asynchronous React Native bridge delays, allowing synchronous, in-process feature toggle evaluations on device.
+React Native SDK for [Checkgate](https://github.com/checkgate-sh/checkgate), the
+self-hosted feature-flag platform. Flags are evaluated on the device by the
+Checkgate Rust engine, called synchronously through JSI.
-## Installation
+**Current release: 0.2.0.** No API changes since 0.1.31; the package is
+versioned with the platform release. See the
+[changelog](https://github.com/checkgate-sh/checkgate/blob/main/CHANGELOG.md).
-```bash
-npm install @checkgate/react-native
-# iOS requires pod installation
-cd ios && pod install
-```
+## What it does
-### Server-Sent Events polyfill
+- A native `Checkgate` module installs a JSI host object backed by the Rust
+ engine. `isEnabled()` and `getVariant()` call it synchronously on the JS
+ thread: no bridge round trip and no network request per evaluation. User
+ attributes stay on the device.
+- Opens one Server-Sent Events (SSE) stream (through an `EventSource` polyfill
+ you install). On every connect the server sends the complete current flag set
+ of the SDK key's environment, then each change. A user who opens the app long
+ after a flag was changed receives the flag as it is now.
+- Keeps the flag set current: live updates, reconnection with backoff, and a
+ polling fallback when the stream cannot be established.
+- Optionally persists the last flag set through a storage adapter you pass (for
+ example AsyncStorage), so a cold start can evaluate before the stream is up.
+- Reports impressions and `track()` conversion events, batched and best-effort.
-React Native has no built-in `EventSource`. Install one that accepts request
-headers (the SDK authenticates the stream with an `Authorization` header) and
-assign it to the global before calling `connect()`:
+The engine ships as Rust source and is compiled when you build the app.
-```bash
-npm install react-native-sse
-```
+## Installation
-```typescript
-import EventSource from 'react-native-sse';
-(global as any).EventSource = EventSource;
+```bash
+npm install @checkgate/react-native react-native-sse
+cd ios && pod install
```
-Without it the SDK logs an error and keeps flags current by polling
-`/flags/snapshot` every `pollIntervalMs` instead of streaming changes.
+Peer dependencies: `react` >= 18 and `react-native` >= 0.71. iOS deployment
+target 13.4 or later; Android `minSdkVersion` 23 by default (read from your
+project's `minSdkVersion`).
-### Native setup
+### Rust toolchain (build machine)
-The evaluation engine is Rust, shipped as source in the package and compiled
-when you build the app, so the build machine needs a Rust toolchain
-([rustup](https://rustup.rs)):
+Every machine that builds the app, including CI and cloud builders, needs
+[rustup](https://rustup.rs):
- **Android:** the Android targets and [cargo-ndk](https://github.com/bbqsrc/cargo-ndk).
- Gradle runs `cargo ndk` for the ABIs you build (`reactNativeArchitectures`)
- and links the result into `libcheckgate.so`.
+ Gradle runs `cargo ndk` for the ABIs you build (`reactNativeArchitectures`) and
+ links the result into `libcheckgate.so`.
```bash
rustup target add aarch64-linux-android armv7-linux-androideabi x86_64-linux-android i686-linux-android
@@ -55,61 +62,178 @@ when you build the app, so the build machine needs a Rust toolchain
rustup target add aarch64-apple-ios aarch64-apple-ios-sim x86_64-apple-ios
```
-Autolinking registers the native `Checkgate` module; there is nothing to add to
-`MainApplication` or `AppDelegate`. The client installs its JSI bindings the
-first time it is constructed. If `connect()` rejects with *Native module not
-found*, rebuild the app (and re-run `pod install` on iOS).
+Autolinking registers the native module; there is nothing to add to
+`MainApplication` or `AppDelegate`. The client installs its JSI bindings when it
+is constructed.
-## Quick Start
+### SSE polyfill (required for streaming)
-Create one `CheckgateNativeClient` for your app and evaluate flags synchronously through JSI.
+React Native has no built-in `EventSource`. The SDK needs one that accepts
+request headers, because it authenticates the stream with an `Authorization`
+header. Assign it before calling `connect()`:
-```javascript
-import { CheckgateNativeClient } from '@checkgate/react-native'
+```js
+import EventSource from 'react-native-sse'
-const client = new CheckgateNativeClient({
- serverUrl: 'https://checkgate.your-company.com',
- sdkKey: 'sk_live_xxxxxx'
-})
-
-// Run this during app initialization
-client.connect()
-
-// Later natively inside your RN component lifecycle
-function CheckoutScreen({ user }) {
- const showApplePay = client.isEnabled('apple-pay-checkout', user.id, { plan: user.plan })
-
- return showApplePay ? :
-}
+global.EventSource = EventSource
```
-## Connection health
+Without a global `EventSource` the SDK logs an error and keeps flags current by
+polling `GET /flags/snapshot` every `pollIntervalMs` instead of streaming.
-A stream that goes silent for 3 server heartbeats (45 s by default) is dropped
-and reconnected. A rejected SDK key (HTTP 401/403) is not retried: `connect()`
-rejects with `CheckgateAuthError` and the last known flags keep being served.
-`client.getStatus()` returns `{ state, lastSyncAt, error }` so you can tell how
-fresh the flags are. See the [SDK docs](https://checkgate-sh.github.io/checkgate/sdks/).
+## Quick start
-## A/B testing: track conversions
+```js
+import EventSource from 'react-native-sse'
+import { CheckgateNativeClient } from '@checkgate/react-native'
-Record goal events with `track()` to measure how each flag variant converts. Pair
-a flag with a goal event in an **Experiment** in the dashboard to see per-variant
-conversion rates and statistical significance.
+global.EventSource = EventSource
-```javascript
-const variant = client.getVariant('checkout-button-color', user.id)
+export const flags = new CheckgateNativeClient({
+ serverUrl: 'https://flags.example.com', // no trailing slash
+ sdkKey: 'sk_live_...', // the environment's SDK key (public, see Security)
+})
+export const flagsReady = flags.connect()
-// …later, when the user converts:
-client.track('checkout_complete', user.id, { value: 49.99 })
+// Anywhere, synchronously:
+const showNewOnboarding = flags.isEnabled('new-onboarding', user.id, { plan: user.plan })
```
-Events are buffered and reported asynchronously (best-effort), just like impressions.
-Use the **same `userKey`** you pass to `getVariant()`/`isEnabled()` so conversions
-attribute to the right variant.
-
-## Why Checkgate JSI?
-* **Synchronous Native Bridge:** Unlike standard HTTP wrappers, Checkgate's JSI evaluates flag arrays in memory avoiding async JS bridge loading.
-* **Bandwidth Conscious:** Streamlined SSE prevents apps from polling the network heavily on metered mobile plans.
+### Re-rendering components
+
+There are no React bindings in the package. `onChange` reports changes after
+the initial load, so also re-render when `connect()` settles:
+
+```js
+import { useEffect, useReducer } from 'react'
+import { flags, flagsReady } from './flags'
+
+export function useFlag(flagKey, userKey, attributes) {
+ const [, rerender] = useReducer((n) => n + 1, 0)
+ useEffect(() => {
+ let active = true
+ const update = () => { if (active) rerender() }
+ flagsReady.then(update, update)
+ const off = flags.onChange(update)
+ return () => { active = false; off() }
+ }, [])
+ return flags.isEnabled(flagKey, userKey, attributes)
+}
+```
-Browse the [official Checkgate documentation](https://checkgate-sh.github.io/checkgate) for architecture schemas and more.
+## Configuration
+
+`new CheckgateNativeClient(options)`:
+
+| Option | Type | Default | Description |
+|---|---|---|---|
+| `serverUrl` | `string` | required | Base URL of the Checkgate server. |
+| `sdkKey` | `string` | none | SDK key of the environment, sent as `Authorization: Bearer`. The server rejects requests without a valid key. |
+| `reconnectDelayMs` | `number` | `5000` | Base reconnect delay; doubles per failed attempt. |
+| `maxReconnectDelayMs` | `number` | `30000` | Upper bound of the reconnect delay (before jitter). |
+| `pollFallbackThreshold` | `number` | `3` | Consecutive failed stream attempts before polling `GET /flags/snapshot`. `Infinity` disables polling. |
+| `pollIntervalMs` | `number` | `30000` | Poll interval while polling. |
+| `connectTimeoutMs` | `number` | `30000` | A stream attempt without the server's `connected` event within this time is abandoned and retried. |
+| `streamIdleTimeoutMs` | `number` | 3 x server heartbeat | A connected stream with no event (heartbeats included) for this long is treated as dead and reconnected (45 s with the server's default 15 s heartbeat). `0` disables. No idle timeout against servers older than 0.1.31, which announce no heartbeat. |
+| `reportImpressions` | `boolean` | `true` | Report each evaluation (flag key, user key, result) for analytics. |
+| `impressionBatchSize` | `number` | `50` | Flush impressions (and events) once this many are buffered. |
+| `impressionFlushIntervalMs` | `number` | `10000` | Periodic flush interval for impressions and events. |
+| `sendEvaluationContext` | `boolean` | `false` | Include user attributes as `context` in impressions. Off, attributes never leave the device. |
+| `storage` | `{ getItem, setItem }` or `null` | `null` | Adapter for persisting the last flag set (sync or async, for example `@react-native-async-storage/async-storage`). `null` persists nothing. |
+
+The persisted entry is one JSON object of flag definitions keyed by flag key,
+stored under `checkgate:flags:v2::`. It is
+written after the initial flag set, each live change and each poll that changed
+something, and read once per `connect()`; stored flags are evaluated until the
+server's current set replaces them.
+
+## API
+
+| Member | Description |
+|---|---|
+| `connect(): Promise` | Restores stored flags (if `storage` is set), opens the stream, resolves once the full flag set has been received (or a poll succeeded). Calling it again while pending returns the same promise. |
+| `isEnabled(flagKey, userKey, attributes?): boolean` | Synchronous evaluation. `false` for unknown flags and before any flags are loaded. Attributes that are not strings are ignored. |
+| `getVariant(flagKey, userKey, attributes?)` | `{ enabled, value }` for multi-variant flags, or `null` if the flag does not exist or nothing is loaded. |
+| `getValue(flagKey, userKey, attributes?, defaultValue = null)` | The resolved value, or `defaultValue` when `getVariant()` would return `null`. |
+| `onChange(cb): () => void` | `cb(flagKey)` for each flag created, updated or deleted after the initial load; after a reconnect, only for flags that changed meanwhile. Returns an unsubscribe function. |
+| `track(eventKey, userKey, { value?, context? }?)` | Records a conversion event for experiments. Use the same `userKey` as for evaluation. |
+| `getStatus()` | `{ state, lastSyncAt, error }`. `state`: `idle`, `connecting`, `streaming`, `reconnecting`, `polling`, `auth_failed` or `closed`. |
+| `isReady()` / `isPolling()` | Whether the full flag set has been received / whether the client is polling. |
+| `disconnect(): void` | Closes the stream, stops polling and timers, flushes pending impressions and events. |
+| `CheckgateAuthError` | Error class (`name`, `status` 401 or 403) for a rejected SDK key. |
+
+The package ships no TypeScript declarations.
+
+## Reconnection
+
+A stream error, connect timeout or idle stream closes the stream and the SDK
+reconnects after `reconnectDelayMs x 2^attempt`, capped at
+`maxReconnectDelayMs`, plus up to 30% jitter. After `pollFallbackThreshold`
+consecutive failures it also polls `GET /flags/snapshot` while still retrying
+the stream; a successful connection stops polling. Each reconnect receives the
+full current flag set, staged and swapped in whole when complete. Change events
+carry revisions; late or duplicate ones are ignored.
+
+## Errors and lifecycle
+
+- `connect()` rejects with `Native module not found` when the JSI bindings are
+ not installed: the app was not rebuilt after installing the package (run
+ `pod install` on iOS), or it runs in a host without the native module, such as
+ Expo Go. Expo apps need a development build (`npx expo prebuild`), whose build
+ machine needs the Rust toolchain above; Expo is not tested in CI.
+- `connect()` rejects with `CheckgateAuthError` when the server answers 401 or
+ 403 (on the stream as reported by the polyfill, or on a poll). The client stops
+ retrying, keeps serving the flags it has, and `getStatus()` reports
+ `auth_failed`. Call `connect()` again to retry.
+- `connect()` rejects with an `Error` if `disconnect()` is called first. It does
+ **not** reject while the server is unreachable; it keeps retrying. Calling it
+ without awaiting never produces an unhandled rejection.
+- Once flags are loaded, `isEnabled()` throws if `flagKey` or `userKey` is not
+ a string; `getVariant()` logs the error and returns `null`.
+- Listener exceptions are caught and logged; storage errors are logged and
+ ignored. Impressions and events are buffered (at most 10,000 each), sent in
+ batches of up to 500 and not retried; `track()` before the stream has connected
+ drops the event with a warning.
+- Create one client per app. Call `disconnect()` when you no longer need it
+ (for example in a root component's cleanup).
+
+## Security considerations
+
+- **The SDK key ships in your app bundle and is public.** Checkgate has one kind
+ of SDK key, bound to one environment. It can only open the stream, read the
+ flags snapshot and flag definitions of its environment, and submit impressions
+ and events for it. It cannot create or change flags, read other environments,
+ or call any other API (403). Use a separate key per app so you can revoke it
+ alone; a revoked key gets 401.
+- **Flag definitions reach the device.** Every flag of the environment,
+ including targeting rule values and segment contents, is sent to the app, and
+ stored as plain JSON by the `storage` adapter if you pass one. Do not put
+ secrets or personal data you would not publish into flags of an environment
+ whose key ships in an app.
+- **Client-side flags are not access control.** Enforce authorization on your
+ server.
+
+## Platform support
+
+| Platform | Status in 0.2.0 |
+|---|---|
+| Android (arm64-v8a, armeabi-v7a, x86, x86_64) | The packed npm package's Rust engine and JSI host are built and linked into `libcheckgate.so` in CI for every ABI. Not tested on a device or emulator. |
+| iOS (device and simulator) | **Not certified.** No iOS build runs in CI. |
+
+The JavaScript client (streaming, polling, reconnection, auth failures) is
+covered in CI by unit tests, the shared SSE fault-injection suite, and a live
+end-to-end run against a real server with `react-native-sse`, on Node.js with the
+engine compiled to WebAssembly standing in for JSI.
+
+## Documentation
+
+- [React Native SDK guide](https://checkgate-sh.github.io/checkgate/sdks/react-native)
+- [SDK keys and authentication](https://checkgate-sh.github.io/checkgate/api-reference#authentication)
+- [SSE stream protocol](https://checkgate-sh.github.io/checkgate/api-reference#sse-stream)
+- [Reliability and sync](https://checkgate-sh.github.io/checkgate/operations/reliability)
+- [SDK diagnostics](https://checkgate-sh.github.io/checkgate/operations/sdk-diagnostics)
+- [Changelog](https://github.com/checkgate-sh/checkgate/blob/main/CHANGELOG.md)
+
+## License
+
+Apache-2.0
diff --git a/sdks/web/README.md b/sdks/web/README.md
index 1acc4ce7..e2ba356f 100644
--- a/sdks/web/README.md
+++ b/sdks/web/README.md
@@ -1,78 +1,288 @@
-
+
# @checkgate/web
-**Checkgate Web SDK (WebAssembly)** — The official frictionless frontend client for Checkgate.
-This SDK leverages a lightning-fast Rust WebAssembly (WASM) payload to evaluate feature flags completely locally within the user's browser, bypassing standard frontend HTTP polling loops.
+Browser SDK for [Checkgate](https://github.com/checkgate-sh/checkgate), the
+self-hosted feature-flag platform. Flags are evaluated locally in the browser by
+the Checkgate Rust engine compiled to WebAssembly.
+
+**Current release: 0.2.0.** No API changes since 0.1.31; the package is
+versioned with the platform release. See the
+[changelog](https://github.com/checkgate-sh/checkgate/blob/main/CHANGELOG.md).
+
+## What it does
+
+- Opens one Server-Sent Events (SSE) stream to your Checkgate server. On every
+ connect the server sends the complete current flag set of the SDK key's
+ environment, then each change as it happens.
+- Evaluates flags synchronously in WebAssembly: no network request per
+ evaluation. User attributes stay in the browser.
+- Keeps the flag set current: live updates, reconnection with backoff, and a
+ polling fallback when the stream cannot be established.
+- Persists the last flag set (in `localStorage` by default) so the next page
+ load can evaluate before the stream is up, and accepts a server-rendered
+ `bootstrap` payload from [`@checkgate/ssr`](https://www.npmjs.com/package/@checkgate/ssr).
+- Reports impressions (flag key, user key, result) and `track()` conversion
+ events for experiments, batched and best-effort.
+- Exports the same engine for server and edge runtimes as `@checkgate/web/core`
+ (used by `@checkgate/ssr` and `@checkgate/edge`).
## Installation
```bash
npm install @checkgate/web
-# or
-pnpm add @checkgate/web
-# or
-yarn add @checkgate/web
```
-## Quick Start
+The package ships the compiled `.wasm` and TypeScript declarations; no Rust
+toolchain is needed.
-Create the client with your Checkgate server URL and an SDK key (SDK keys are
-public by design; the stream sends it as a `?sdk_key=` query parameter):
+## Quick start
-```typescript
+```js
import { CheckgateWeb } from '@checkgate/web'
const checkgate = new CheckgateWeb({
- serverUrl: 'https://checkgate.your-company.com',
- sdkKey: 'sk_live_xxxxxxxx',
+ serverUrl: 'https://flags.example.com', // no trailing slash
+ sdkKey: 'sk_live_...', // the environment's SDK key (public, see Security)
})
-// Loads the WebAssembly core and the flag set over SSE.
+// Loads the WebAssembly engine, opens the stream and resolves once the full
+// flag set has arrived.
await checkgate.connect()
-// Evaluated in the browser: flag key, a stable user key, string attributes.
-if (checkgate.isEnabled('beta-feature', 'user-12345', { plan: 'enterprise' })) {
- // Render the new beta UI…
+// Flag key, a stable user key, string attributes for targeting rules.
+if (checkgate.isEnabled('new-checkout', 'user-123', { plan: 'pro' })) {
+ // render the new checkout
}
+
+const color = checkgate.getValue('checkout-color', 'user-123', {}, 'blue')
+
+checkgate.onChange((flagKey) => {
+ // a flag changed after the initial load: re-render
+})
+```
+
+### A new user gets the current configuration
+
+The server builds the initial flag set for each stream from its database at the
+moment the client connects; it does not replay a history of change events. A
+user who opens your page a minute or a month after a flag was changed receives
+the flag as it is now, the same as users who were connected when it changed.
+Nobody has to be online when you change a flag.
+
+Flags restored from `localStorage` or passed as `bootstrap` are used only until
+that initial set arrives (the `ready` event). The set then replaces them,
+including removing flags that were deleted on the server.
+
+## Configuration
+
+`new CheckgateWeb(options)`:
+
+| Option | Type | Default | Description |
+|---|---|---|---|
+| `serverUrl` | `string` | required | Base URL of the Checkgate server. |
+| `sdkKey` | `string` | none | SDK key of the environment. The stream sends it as `?sdk_key=` (`EventSource` cannot set headers); polls and reports send `Authorization: Bearer`. The server rejects requests without a valid key. |
+| `reconnectDelayMs` | `number` | `3000` | Base reconnect delay; doubles per failed attempt. |
+| `maxReconnectDelayMs` | `number` | `30000` | Upper bound of the reconnect delay (before jitter). |
+| `pollFallbackThreshold` | `number` | `3` | Consecutive failed stream attempts before polling `GET /flags/snapshot`. `Infinity` disables polling. |
+| `pollIntervalMs` | `number` | `30000` | Poll interval while polling. |
+| `connectTimeoutMs` | `number` | `30000` | A stream attempt without the server's `connected` event within this time is abandoned and retried. |
+| `streamIdleTimeoutMs` | `number` | 3 x server heartbeat | A connected stream with no event (heartbeats included) for this long is treated as dead and reconnected. The server announces its heartbeat interval (15 s by default, so 45 s). `0` disables. Servers older than 0.1.31 announce none, so no idle timeout applies to them. |
+| `reportImpressions` | `boolean` | `true` | Report each evaluation (flag key, user key, result) for analytics. |
+| `impressionBatchSize` | `number` | `50` | Flush impressions (and events) once this many are buffered. |
+| `impressionFlushIntervalMs` | `number` | `10000` | Periodic flush interval for impressions and events. |
+| `sendEvaluationContext` | `boolean` | `false` | Include user attributes as `context` in impressions. Off, attributes never leave the browser. |
+| `storage` | `{ getItem, setItem }` or `null` | `localStorage` when available | Where the last flag set is persisted. Sync or async adapters both work. `null` persists nothing. |
+| `bootstrap` | flag array, `{ flags }` or `null` | `null` | A flag set loaded by `connect()` before the stream is established, typically the payload from `@checkgate/ssr`. When given, `storage` is not read. |
+
+## API
+
+| Member | Description |
+|---|---|
+| `connect(): Promise` | Loads the WASM engine, restores `bootstrap` or stored flags, opens the stream. Resolves when the full flag set has been received (stream) or a poll succeeded. Calling it again while pending returns the same promise. |
+| `isEnabled(flagKey, userKey, attributes?): boolean` | Synchronous evaluation. `false` for unknown flags and before any flags are loaded. Attributes that are not strings are ignored. |
+| `getVariant(flagKey, userKey, attributes?)` | `{ enabled, value }` for multi-variant flags, or `null` if the flag does not exist or nothing is loaded. |
+| `getValue(flagKey, userKey, attributes?, defaultValue = null)` | The resolved value, or `defaultValue` when `getVariant()` would return `null`. |
+| `onChange(cb): () => void` | `cb(flagKey)` for each flag created, updated or deleted after the initial load. Not called for the initial load; after a reconnect, only for flags that changed meanwhile. Returns an unsubscribe function. |
+| `track(eventKey, userKey, { value?, context? }?)` | Records a conversion event for experiments. Use the same `userKey` as for evaluation. |
+| `getStatus()` | `{ state, lastSyncAt, error }`, see below. |
+| `isReady(): boolean` | Whether the full flag set has been received from the server. |
+| `isPolling(): boolean` | Whether the client is currently polling instead of streaming. |
+| `disconnect(): void` | Closes the stream, stops polling and timers, flushes pending impressions and events. |
+| `CheckgateAuthError` | Error class (`name`, `status` 401 or 403) for a rejected SDK key. |
+
+`getStatus().state` is one of `idle` (before `connect()`), `connecting`,
+`streaming` (flags current), `reconnecting`, `polling`, `auth_failed` or
+`closed`. `lastSyncAt` is when the client last confirmed its flags were current
+(initial set, successful poll, or any stream event including heartbeats), in ms
+since the epoch, or `null`. Flags are served from the last known set in every
+state; `Date.now() - lastSyncAt` is how old they may be.
+
+### Server-side core (`@checkgate/web/core`)
+
+```js
+import { createWasmCore } from '@checkgate/web/core'
+
+const core = await createWasmCore() // Node and browser: no argument
+core.upsertFlag(JSON.stringify(flag)) // flags as served by GET /flags/snapshot
+core.isEnabled('new-checkout', 'user-123', { plan: 'pro' })
+core.getValue(key, userKey, attrs, defaultValue)
+core.getVariant(key, userKey, attrs)
+core.clear()
```
-TypeScript declarations are included. Until flags are loaded (by `connect()`,
-the default `localStorage` cache, or a `bootstrap` payload from
-`@checkgate/ssr`), `isEnabled()` returns `false`. Impressions (flag key, user
-key, result) are reported by default; pass `reportImpressions: false` to turn
-them off.
+`createWasmCore(wasmInput?)` accepts a `WebAssembly.Module`, bytes, `Response`
+or `URL` for runtimes that load `.wasm` themselves (on Cloudflare Workers, import
+`@checkgate/web/dist/checkgate_bg.wasm` and pass it). Each call returns an
+independent flag store. This is the engine `@checkgate/ssr` and
+`@checkgate/edge` use.
-## Connection health
+## Using it with React
-A stream that goes silent for 3 server heartbeats (45 s by default) is dropped
-and reconnected. A rejected SDK key (HTTP 401/403) is not retried: `connect()`
-rejects with `CheckgateAuthError` and the last known flags keep being served.
-`client.getStatus()` returns `{ state, lastSyncAt, error }` so you can tell how
-fresh the flags are. See the [SDK docs](https://checkgate-sh.github.io/checkgate/sdks/).
+There is no separate React package and this package has no React bindings.
+Create one client for the app and re-render from `onChange` and from
+`connect()` settling (`onChange` does not fire for the initial load):
-## A/B testing: track conversions
+```js
+// flags.js
+import { CheckgateWeb } from '@checkgate/web'
-Record goal events with `track()` to measure how each flag variant converts. Pair
-a flag with a goal event in an **Experiment** in the dashboard to see per-variant
-conversion rates and statistical significance.
+export const flags = new CheckgateWeb({ serverUrl: 'https://flags.example.com', sdkKey: 'sk_live_...' })
+export const flagsReady = flags.connect()
+```
-```javascript
-const variant = checkgate.getVariant('checkout-button-color', 'user_123')
+```js
+// use-flag.js
+import { useEffect, useReducer } from 'react'
+import { flags, flagsReady } from './flags'
-// …later, when the user converts:
-checkgate.track('checkout_complete', 'user_123', { value: 49.99 })
+export function useFlag(flagKey, userKey, attributes) {
+ const [, rerender] = useReducer((n) => n + 1, 0)
+ useEffect(() => {
+ let active = true
+ const update = () => { if (active) rerender() }
+ flagsReady.then(update, update)
+ const off = flags.onChange(update)
+ return () => { active = false; off() }
+ }, [])
+ return flags.isEnabled(flagKey, userKey, attributes)
+}
```
-Events are buffered and reported asynchronously (best-effort), just like impressions.
-Use the **same `userKey`** you pass to `getVariant()`/`isEnabled()` so conversions
-attribute to the right variant.
+For server-rendered React (Next.js and others) use `@checkgate/ssr`: it
+evaluates on the server, embeds the result in the HTML, and seeds this client
+through the `bootstrap` option so the first paint matches the server render.
+
+## Local storage
+
+- **What is stored:** the flag definitions the client holds, as one JSON object
+ keyed by flag key, exactly as the server sent them (state, rollout, targeting
+ rules with their values, segments expanded into rules, variants). No user
+ keys, attributes, evaluation results or the SDK key.
+- **Key:** `checkgate:flags:v2::`, where `` is the
+ SHA-256 hex of the SDK key (of `session` when there is none). Different
+ servers and keys do not share an entry, and the raw key is not in the storage
+ key.
+- **Written** after the initial flag set arrives, after each live change, and
+ after each poll that changed something.
+- **Read** once per `connect()`, after the WASM engine loads, and only when no
+ `bootstrap` flags were passed. Stored flags are evaluated at once (before
+ `connect()` resolves; `isReady()` is still `false`) until the server's flag set
+ replaces them.
+- There is no expiry. Storage errors are logged with `console.warn` and
+ otherwise ignored. Pass `storage: null` to keep flag definitions out of
+ browser storage, or any `{ getItem, setItem }` adapter (for example
+ `sessionStorage`).
+
+## Reconnection
+
+- A stream error, a connect timeout (`connectTimeoutMs`) or an idle stream
+ (`streamIdleTimeoutMs`) closes the stream; the SDK reconnects itself (not with
+ the browser's built-in `EventSource` retry) after
+ `reconnectDelayMs x 2^attempt`, capped at `maxReconnectDelayMs`, plus up to 30%
+ random jitter.
+- After `pollFallbackThreshold` consecutive failures it also polls
+ `GET /flags/snapshot` every `pollIntervalMs` while still retrying the stream.
+ A successful stream connection stops polling and resets the backoff.
+- Every reconnect receives the full current flag set again. It is staged and
+ swapped in whole when complete, so evaluations keep using the previous set
+ meanwhile and a replay cut short never goes live. Change events carry
+ revisions; late or duplicate ones are ignored.
+- A browser does not expose the HTTP status of a failed `EventSource`. After an
+ attempt that never connected, the SDK asks `GET /flags/snapshot` with the same
+ key (at most once per attempt); a 401 or 403 stops all retries.
+
+## Errors and lifecycle
+
+- `connect()` rejects with `CheckgateAuthError` when the server rejects the key
+ (401/403). The client stops retrying, keeps serving the flags it has, and
+ `getStatus()` reports `auth_failed`. Call `connect()` again to retry.
+- `connect()` rejects with an `Error` if `disconnect()` is called first, or if
+ the WASM engine fails to load. It does **not** reject while the server is
+ unreachable; it keeps retrying. Race it with a timeout if your startup cannot
+ wait, and evaluate meanwhile (stored or bootstrap flags, else defaults).
+- Calling `connect()` without awaiting it never produces an unhandled
+ rejection.
+- Before any flags are loaded, `isEnabled()` returns `false` and `getVariant()`
+ returns `null` (with a `console.warn`).
+- An exception thrown by an `onChange` listener is caught and logged.
+- Impressions and events are buffered (at most 10,000 each, oldest dropped),
+ sent in batches of up to 500 with `fetch(..., { keepalive: true })`, and not
+ retried on failure. `track()` before the stream has connected drops the event
+ with a warning, because the environment is not known yet.
+- `disconnect()` flushes pending reports and closes everything. Flags already
+ loaded stay available for evaluation; a later `connect()` opens a new stream
+ and receives the current set.
+
+## Security considerations
+
+- **The SDK key is visible to anyone who loads your page.** Checkgate has one
+ kind of SDK key, bound to one environment, and treats it as public. It can only:
+ open the stream and read the flags snapshot of its environment, read that
+ environment's flag definitions, and submit impressions and events for it. It
+ cannot create or change flags, read other environments, or call any other
+ API; those requests get 403. Use a separate key per app so you can revoke one
+ without affecting others; a revoked key gets 401 and its open streams close.
+- **Flag definitions reach the browser.** Every flag of the environment,
+ including targeting rule values and segment contents, is sent to the client
+ and (by default) stored in `localStorage`. Do not put secrets or personal data
+ you would not publish into flags of an environment whose key ships to
+ browsers.
+- **The key appears in stream URLs** (`?sdk_key=`), so it can show up in proxy
+ and server access logs. Other requests use the `Authorization` header.
+- **Client-side flags are not access control.** A user can change what the
+ browser evaluates. Enforce authorization on your server.
+- Your Content Security Policy must allow the Checkgate server origin in
+ `connect-src`.
+
+## Compatibility
+
+- ES module package with TypeScript declarations; no CommonJS build.
+- Needs `WebAssembly`, `EventSource` and `fetch`. In the browser, the engine
+ fetches `checkgate_bg.wasm` relative to the module
+ (`new URL('checkgate_bg.wasm', import.meta.url)`), so your bundler or server
+ must serve that file next to the SDK's JavaScript.
+- `@checkgate/web/core` also runs on Node.js (it reads the `.wasm` from the
+ package) and on runtimes that accept a `WebAssembly.Module`.
+- Tested in CI: unit and fault-injection suites on Node.js 22 with a stubbed
+ engine, and a live end-to-end run of the real client and WASM engine against a
+ real server, in Node.js with an `EventSource` polyfill. It is not tested in a
+ real browser in CI.
+- Works with servers older than 0.1.31 (no heartbeat idle timeout, polls without
+ revisions).
+
+## Documentation
+
+- [Web SDK guide](https://checkgate-sh.github.io/checkgate/sdks/web)
+- [SSR and bootstrap](https://checkgate-sh.github.io/checkgate/ecosystem/ssr)
+- [SDK keys and authentication](https://checkgate-sh.github.io/checkgate/api-reference#authentication)
+- [SSE stream protocol](https://checkgate-sh.github.io/checkgate/api-reference#sse-stream)
+- [Reliability and sync](https://checkgate-sh.github.io/checkgate/operations/reliability)
+- [SDK diagnostics](https://checkgate-sh.github.io/checkgate/operations/sdk-diagnostics)
+- [Changelog](https://github.com/checkgate-sh/checkgate/blob/main/CHANGELOG.md)
-## Why Checkgate WebAssembly?
-* **Synchronous evaluation:** once flags are loaded, every check is a local WASM call, with no request per decision. Seed it from `@checkgate/ssr` or the local cache to avoid a loading state on first paint.
-* **Live SSE:** toggling a flag in the dashboard updates the page without a reload.
-* **Open Source Alternative:** Stop paying premium per-seat pricing for basic feature gates.
+## License
-Learn more natively in the [official Checkgate documentation](https://checkgate-sh.github.io/checkgate).
+Apache-2.0
diff --git a/sdks/web/index.d.ts b/sdks/web/index.d.ts
index 7e475577..eebbcc23 100644
--- a/sdks/web/index.d.ts
+++ b/sdks/web/index.d.ts
@@ -27,7 +27,7 @@ export interface CheckgateWebOptions {
/**
* SDK key. Browsers cannot set headers on `EventSource`, so the stream sends
* it as a `?sdk_key=` query parameter; polls send it as `Authorization: Bearer`.
- * SDK keys are public by design. Leave unset for open (dev-only) mode.
+ * SDK keys are public by design. Required: the server has no unauthenticated mode.
*/
sdkKey?: string;
/** Base SSE reconnect delay in milliseconds; grows exponentially. Default: 3000. */
diff --git a/ssr/README.md b/ssr/README.md
index 82507898..d86dfd8c 100644
--- a/ssr/README.md
+++ b/ssr/README.md
@@ -1,81 +1,162 @@
-
-

-
@checkgate/ssr
-
Server-render initial flag state and hydrate the client with zero flag flicker — Next.js, Remix, SvelteKit, or any SSR framework.
-
+
+
+
-Without SSR, a client-side flag SDK shows default values until its stream
-bootstraps — so the "old" UI paints first and snaps to the "new" one a moment
-later. `@checkgate/ssr` removes that flash:
+# @checkgate/ssr
-1. **On the server**, evaluate the flags a page needs for the current user and
- build a serializable **bootstrap payload** (it embeds the flag snapshot for the live client unless `includeSnapshot: false`).
-2. **Embed** it in the HTML (a single ``
+}
+```
+
+Browser (`/app.js`):
+
+```js
+import { readBootstrap, BootstrapValues } from '@checkgate/ssr'
+import { CheckgateWeb } from '@checkgate/web'
+
+const payload = readBootstrap()
+const initial = new BootstrapValues(payload)
+initial.isEnabled('new-homepage') // the value the server rendered with
+
+const flags = new CheckgateWeb({
+ serverUrl: 'https://flags.example.com',
+ sdkKey: 'sk_live_...',
+ bootstrap: payload, // evaluates from the embedded snapshot, then follows the stream
+})
+await flags.connect()
+flags.isEnabled('new-homepage', initial.userKey, attributes) // live; same user key and attributes as the server
+```
+
+Use the same user key and attributes on both sides, or the live client can
+resolve differently from the server.
+
+## Configuration
+
+`buildBootstrap(options)`:
+
+| Option | Type | Default | Description |
+|---|---|---|---|
+| `core` | object | required | Engine with `clear()`, `upsertFlag(json)`, `getVariant()`; normally `await createWasmCore()` from `@checkgate/web/core`. `buildBootstrap()` clears it and loads `snapshot`. |
+| `snapshot` | `object[]` | required | Array of flags as `GET /flags/snapshot` returns them (or `CheckgateEdge#snapshotFlags()`). |
+| `userKey` | `string` | required | Stable user identifier used for evaluation. |
+| `keys` | `string[]` | all flags | Flag keys to resolve. Omitted or empty: every flag in the snapshot. |
+| `attributes` | `object` | `{}` | Targeting attributes of the user. |
+| `includeSnapshot` | `boolean` | `true` | Embed the snapshot as `flags`, so `CheckgateWeb` can evaluate before its stream is up. |
+| `now` | `() => number` | `Date.now` | Clock for `generatedAt` (for tests). |
+
+`bootstrapScriptTag(payload, { varName, nonce })`: `varName` defaults to
+`__CHECKGATE_BOOTSTRAP__` (exported as `DEFAULT_VAR_NAME`); `nonce` adds a CSP
+`nonce` attribute.
+
+## API
+
+| Export | Side | Description |
+|---|---|---|
+| `buildBootstrap(options)` | server | Returns `{ v, userKey, generatedAt, values, flags? }`; `values` maps each resolved key to `{ enabled, value }`. Keys not in the snapshot are left out. |
+| `serializeBootstrap(payload)` | server | JSON with `<`, `>`, `&`, U+2028 and U+2029 escaped, safe inside ``. |
+| `readBootstrap(varName?, win?)` | client | The embedded payload, or `null` if absent (`win` defaults to `globalThis`). |
+| `new BootstrapValues(payload)` | client | `.isEnabled(key)`, `.getValue(key, defaultValue)`, `.getVariant(key)`, `.has(key)`, plus `.userKey`, `.flags`, `.valid`. |
+| `BOOTSTRAP_VERSION`, `DEFAULT_VAR_NAME` | both | Payload schema version (`1`) and the default global name. |
## The flow (Next.js App Router)
-### 1. Server — build the payload
+The server builds the payload and passes it to a client provider as a prop, so
+the server render and the first client render read the same values.
-```ts
-// lib/checkgate-server.ts
+```js
+// lib/checkgate-server.js
import { CheckgateEdge } from '@checkgate/edge'
import { buildBootstrap } from '@checkgate/ssr'
import { createWasmCore } from '@checkgate/web/core'
-let edge: CheckgateEdge | null = null
+let edge = null
-export async function getBootstrap(userKey: string, keys: string[]) {
- if (!edge) {
- edge = new CheckgateEdge({
- serverUrl: process.env.CHECKGATE_URL!,
- sdkKey: process.env.CHECKGATE_SDK_KEY!,
- core: await createWasmCore(),
- ttlSeconds: 30,
- })
- }
- await edge.ensureFresh()
- // buildBootstrap re-loads the snapshot into a core and resolves `keys` for the
- // user; pass the same snapshot the edge client is holding.
- return buildBootstrap({
+export async function getBootstrap(userKey, attributes, keys) {
+ edge ??= new CheckgateEdge({
+ serverUrl: process.env.CHECKGATE_URL,
+ sdkKey: process.env.CHECKGATE_SDK_KEY,
core: await createWasmCore(),
- snapshot: edge.snapshotFlags(), // your app can also fetch /flags/snapshot directly
- userKey,
- keys,
+ ttlSeconds: 30,
})
+ await edge.ensureFresh()
+ return buildBootstrap({ core: await createWasmCore(), snapshot: edge.snapshotFlags(), userKey, attributes, keys })
}
```
-### 2. Pass it to the client
-
-In the App Router, hand the payload to a client provider as a prop. The server
-render and the first client render then read the same values (no hydration
-mismatch). Keep the user's attributes next to it so the live client evaluates
-with the same inputs as the server.
-
-```tsx
-// app/layout.tsx (Server Component)
-import { getBootstrap } from '@/lib/checkgate-server'
+```jsx
+// app/layout.jsx (Server Component)
+import { getBootstrap } from '../lib/checkgate-server'
import { FlagsProvider } from './flags-provider'
export default async function RootLayout({ children }) {
- const userKey = /* cookie/session id */ 'anonymous'
- const attributes = { plan: 'free' } // the same attributes passed to buildBootstrap
- const payload = await getBootstrap(userKey, ['new-homepage', 'checkout-color'])
+ const userKey = 'anonymous' // from your session or cookie
+ const attributes = { plan: 'free' } // the same attributes for server and client
+ const payload = await getBootstrap(userKey, attributes, ['new-homepage', 'checkout-color'])
return (
@@ -86,33 +167,25 @@ export default async function RootLayout({ children }) {
}
```
-Outside React (or with a streaming template), embed it instead with
-`bootstrapScriptTag(payload)` and read it on the client with `readBootstrap()`;
-`readBootstrap()` returns `null` on the server, so call it only in the browser.
-
-### 3. Go live on the client
-
-One `CheckgateWeb` client for the whole app, seeded from the same payload:
-
-```tsx
+```jsx
+// app/flags-provider.jsx
'use client'
import { createContext, useContext, useEffect, useMemo, useState } from 'react'
import { BootstrapValues } from '@checkgate/ssr'
import { CheckgateWeb } from '@checkgate/web'
-type Read = (key: string) => boolean
-const FlagsContext = createContext(() => false)
+const FlagsContext = createContext(() => false)
export function FlagsProvider({ payload, attributes = {}, children }) {
const initial = useMemo(() => new BootstrapValues(payload), [payload])
- const [client, setClient] = useState(null)
+ const [client, setClient] = useState(null)
const [, setVersion] = useState(0)
useEffect(() => {
const live = new CheckgateWeb({
- serverUrl: process.env.NEXT_PUBLIC_CHECKGATE_URL!,
- sdkKey: process.env.NEXT_PUBLIC_CHECKGATE_SDK_KEY!,
- bootstrap: payload, // live-ready without waiting for SSE
+ serverUrl: process.env.NEXT_PUBLIC_CHECKGATE_URL,
+ sdkKey: process.env.NEXT_PUBLIC_CHECKGATE_SDK_KEY,
+ bootstrap: payload,
})
const off = live.onChange(() => setVersion((v) => v + 1))
live.connect().then(() => setClient(live)).catch(() => {})
@@ -120,39 +193,71 @@ export function FlagsProvider({ payload, attributes = {}, children }) {
}, [payload])
// Server-resolved values until the live client is ready, then live ones.
- const read: Read = (key) =>
- client && initial.userKey
- ? client.isEnabled(key, initial.userKey, attributes)
- : initial.isEnabled(key)
+ const read = (key) =>
+ client && initial.userKey ? client.isEnabled(key, initial.userKey, attributes) : initial.isEnabled(key)
return {children}
}
-export const useFlag = (key: string) => useContext(FlagsContext)(key)
+export const useFlag = (key) => useContext(FlagsContext)(key)
```
-**Remix / SvelteKit** follow the same three steps — build the payload in the
-`loader` / `+page.server`, inject the script into the document template, and read
-it in a client component/store.
+Outside React, embed with `bootstrapScriptTag(payload)` and read with
+`readBootstrap()` as in the minimal example. Remix and SvelteKit follow the
+same steps: build the payload in the loader or `+page.server`, embed it in the
+document, read it on the client.
-## API
+## Errors and lifecycle
-| Export | Side | Description |
-|---|---|---|
-| `buildBootstrap({ core, snapshot, userKey, keys?, attributes?, includeSnapshot? })` | server | Evaluate flags for a user, return a serializable payload. |
-| `serializeBootstrap(payload)` | server | JSON, escaped for safe inlining in `` cannot end the tag. The `nonce` is inserted as
+ given: pass only a nonce your server generated.
+- The SDK key used on the server is the same kind of key the browser uses:
+ public by design and limited to its environment's SDK endpoints (stream,
+ snapshot, flag reads, impressions and events). Keep it in server-side
+ configuration anyway.
+
+## Compatibility
+
+- ES module, no dependencies, no TypeScript declarations (the examples are
+ JavaScript); `engines`: Node.js >= 18. The server helpers run
+ wherever the engine (`@checkgate/web/core`) runs; the client helpers are
+ plain JavaScript for the browser.
+- Tested in CI: the unit suite (payload building, escaping, script tag,
+ round-trip, schema checks) on Node.js 22 with a fake engine. The Next.js,
+ Remix and SvelteKit flows are documentation and are not run in CI.
-## Safety
+## Documentation
-- The payload is serialized with `<`, `>`, `&`, and the U+2028/U+2029 line
- separators escaped, so a flag key or value containing `` can't break
- out of the tag. `bootstrapScriptTag` accepts a `nonce` for strict CSPs.
-- `BootstrapValues` is null-safe and version-checked: a missing or stale-schema
- payload degrades to defaults rather than throwing, so a bad embed never breaks
- a render.
+- [SSR and bootstrap guide](https://checkgate-sh.github.io/checkgate/ecosystem/ssr)
+- [Web SDK](https://checkgate-sh.github.io/checkgate/sdks/web) (`@checkgate/web`, the `bootstrap` option)
+- [Edge evaluation](https://checkgate-sh.github.io/checkgate/ecosystem/edge) (`@checkgate/edge`)
+- [Flags snapshot endpoint](https://checkgate-sh.github.io/checkgate/api-reference#flags-snapshot-poll-fallback)
+- [Changelog](https://github.com/checkgate-sh/checkgate/blob/main/CHANGELOG.md)
----
+## License
-Part of [Checkgate](https://github.com/checkgate-sh/checkgate) — the self-hosted feature-flag platform.
+Apache-2.0