diff --git a/packages/browser-sdk/README.md b/packages/browser-sdk/README.md index 10c44a2a..8474499a 100644 --- a/packages/browser-sdk/README.md +++ b/packages/browser-sdk/README.md @@ -1,8 +1,6 @@ # Reflag Browser SDK v2 -Client-side feature flags and JSON values for [Reflag](https://reflag.com). - -> This is a breaking v2 prerelease. It requires the v2 evaluated-flags/check protocol on the server. Do not switch existing v1 applications or bootstrap consumers without coordinating that upgrade. Nothing in this branch publishes or deploys the SDK/server. +Client-side feature flags for [Reflag](https://reflag.com). ## Get started @@ -28,32 +26,27 @@ if (enabled) { Use only a **publishable** key in a browser. Secret keys belong on your server. -## Direct-value reads +## Read flags ```ts -reflag.getFlag("release"); // boolean; missing/mismatched -> false +reflag.getFlag("huddles"); // true or false reflag.getFlag("model", "quick"); // string reflag.getFlag("limit", 10); // number -reflag.getFlag("settings", { model: "quick" }); -reflag.getFlag("nullable-settings", null); // FlagValue (arbitrary JSON) +reflag.getFlag("settings", { model: "quick" }); // { model: string } +reflag.getFlag("anything", null); // any JSON value ``` -- Defaults are positional JSON values; generation is not required for useful types. Primitive literals widen, and readonly defaults are accepted. -- A non-null default accepts only the same **top-level JSON category**: Boolean, number, string, array or object. A mismatch warns without logging the payload and returns the default. A bare read can never return a truthy object. -- Explicit `null` accepts any JSON value, including authored null. Missing values return null. -- Falsy selected values (`false`, `0`, `""`, null) are preserved when accepted by the requested category. -- Object fields and array elements are **not schema-validated**. Validate untrusted/nested payloads in your application. -- Values and defaults are returned as independent mutable copies. There are no reserved JSON property names. +Without a default, a read expects a Boolean and returns `false` if the flag is missing or isn't a Boolean. With a default, the read returns the default while flags load, or if the flag is missing or has a different JSON type. Pass `null` to accept any JSON value, then check its type before using it. -`getFlags()` returns a direct-value record (entries may be undefined) and registers checks for its returned roots. `getFlagResults()` returns owned evaluated diagnostics **without checks**; it is intended for tooling, not ordinary application reads. `getFlagsForBootstrap()` serializes protocol-v2 evaluated state without checks. +The SDK doesn't check object fields or fill in missing fields from your default. -## Checks and delivery +`getFlags()` returns all flag values as an object. -Calling a getter registers a requested-root check immediately, even if its return value is ignored. There are no `.isEnabled`, `.config`, `.value` or flag `.track()` wrappers. Delivery remains buffered through `/bulk` and identity-aware rate-limited. +## Checks -A selected check carries the authored selected key as `evalResult`, its `sourceVersionId` and the available snapshot `flagStateVersion`. Payload equality is not identity: equal-valued selections or segment-only snapshot changes remain distinguishable on subsequent reads. Defaults, category mismatches, local overrides and static fallback values do not fabricate authored selections. Diagnostics and bootstrap serialization generate no checks. The server evaluates dependencies; fetching their results does not itself register reads. +Each read records a check. Reflag uses checks for exposure counts, and they show up in the Event Log, which helps with debugging. `getFlags()` records a check for every flag it returns. -`enableTracking: false` disables checks and user/company/usage tracking. `offline: true` skips HTTP and tracking. `await reflag.stop()` flushes buffered events and closes the client's background transports. +Set `enableTracking: false` to stop sending checks and events, or `offline: true` to skip all requests. `await reflag.stop()` sends pending events and closes the client's connections. ## Context, refresh and cache @@ -68,47 +61,44 @@ await reflag.setContext({ await reflag.refresh(); ``` -`setContext()` replaces the context; update methods shallow-merge their section. User/company sections require IDs, including valid numeric zero. Context supports nested JSON and arrays. A context change clears the old context's values while fetching; stale/in-flight responses cannot replace a newer context or snapshot. - -Values come from `GET /flags/evaluated`, not legacy `/features/evaluated`. Server evaluation retains the complete internal graph and authorized public roots. The Browser SDK does not cache dependency evaluations of its own. +`setContext()` replaces the whole context. The update methods merge new attributes into the user, company or other context. Users and companies need an `id`. While flags for a new context load, reads return their defaults. Constructor options include: -| Option | Behavior | -| ------------------------------- | --------------------------------------------------------------------------- | -| `apiBaseUrl`, `appBaseUrl` | API origin and toolbar/feedback links | -| `credentials` | Fetch credentials mode; `include` also enables default SSE credentials | -| `timeoutMs` | Flag request timeout; default 5,000 ms | -| `staleTimeMs` | Fresh-cache duration; default 0 | -| `staleWhileRevalidate` | Serve stale cached state while revalidating; default false | -| `expireTimeMs` | Cache expiry; default 30 days | -| `storage` | Optional async storage adapter | -| `fallbackFlags` | Value record or array of enabled Boolean keys, without authored provenance | -| `enableLiveFlagUpdates` | Refresh after SSE publications; default false in Browser, true in React/Vue | -| `eventSourceFactory` | Optional EventSource-compatible transport | -| `trackingQueue` | Buffered-delivery `flushDelayMs` and `maxSize` | -| `logger`, `toolbar`, `feedback` | Logging, Boolean override toolbar and feedback options | - -Evaluated cache and override storage use isolated v2 keys. V1 cache entries are never interpreted as v2 values. Malformed refreshes leave known-good state intact. Valid saved v2 selections retain their real provenance on restore. There is no automatic periodic HTTP fallback after an SSE failure; manual refresh/context updates remain available. +| Option | Behavior | +| ------------------------------- | -------------------------------------------------------------------------------------------------- | +| `apiBaseUrl`, `appBaseUrl` | API origin and toolbar/feedback links | +| `credentials` | Fetch credentials mode | +| `timeoutMs` | Flag request timeout; default 5,000 ms | +| `staleTimeMs` | Fresh-cache duration; default 0 | +| `staleWhileRevalidate` | Serve stale cached state while revalidating; default false | +| `expireTimeMs` | Cache expiry; default 30 days | +| `storage` | Optional async storage adapter | +| `enableLiveFlagUpdates` | Update flags as soon as they change in Reflag; default `false` in Browser, `true` in React and Vue | +| `eventSourceFactory` | Custom EventSource implementation for live updates | +| `trackingQueue` | How long to batch events (`flushDelayMs`) and the batch size (`maxSize`) | +| `logger`, `toolbar`, `feedback` | Logging, toolbar and feedback options | + +Flags are cached in the browser. If a refresh fails, the client keeps the last values it received. ## Overrides and toolbar ```ts reflag.setFlagOverride("release", true); reflag.setFlagOverride("settings", { model: "local" }); -reflag.setFlagOverride("nullable-settings", null); // a real null override -reflag.setFlagOverride("release", undefined); // clear the override +reflag.setFlagOverride("nullable-settings", null); // override with null +reflag.setFlagOverride("release", undefined); // remove the override ``` -Overrides apply after server evaluation and do not rewrite authored dependency results. The built-in toolbar appears on localhost by default and offers Boolean overrides only. It uses diagnostic access, so opening it does not register application checks. +Overrides apply on top of the values from Reflag and are saved in the browser. The toolbar appears on localhost by default and lets you override Boolean flags. Opening it doesn't record checks. ## Server bootstrap -Generate the full payload with **Node SDK v2** on your server: +Get the bootstrap data from the Node.js SDK on your server: ```ts const bootstrappedState = serverClient.getFlagsForBootstrap(context); -// Send via your framework's safe JSON/hydration mechanism. +// Serialize this into the page with your framework's usual mechanism. ``` ```ts @@ -117,7 +107,7 @@ await reflag.initialize(); const enabled = reflag.getFlag("release"); ``` -The payload includes `protocolVersion: 2`, context, evaluated diagnostics/selections and an optional snapshot version. V1 payloads and the old `bootstrappedFlags` option are rejected. Preserve the entire envelope; do not pass just its `flags` property. A version is required for bootstrapped live updates. Never embed secrets or server-only context in public bootstrap data. Later refreshes use browser-visible context and can differ from server-only evaluation; disable live updates when that is inappropriate. Requesting missing opt-in metadata still makes a browser-side request even when live updates are disabled. +Pass the whole object, not just its `flags`. Flags are then available immediately, without a network request. With live updates on, later refreshes evaluate flags using the browser's context, so values that depend on server-only attributes can change. Set `enableLiveFlagUpdates: false` if they must not. ## End-user opt-in @@ -132,21 +122,23 @@ try { } ``` -The list contains presentation/membership metadata (`key`, `name`, `description`, `isEnabled`, `userOptedIn`, `companyOptedIn`, `isOptedIn`); this is not the ordinary flag getter API. User/company grants remain independent. The selected scope requires its ID. Successful mutations wait for versioned evaluation and membership confirmation. - -Metadata arrives with ordinary `/flags/evaluated` responses and is cached with the evaluated snapshot. Bootstrapped clients whose snapshot lacks metadata fetch it on demand from the same v2 endpoint, without replacing server-derived values or provenance with browser-context evaluations. Loading settles on success or failure, including an empty list. Opt-in mutations confirm values and membership together in one versioned refresh. `optInFlagsLoadingUpdated` and `flagsUpdated` support UI subscriptions. Failed metadata requests settle loading without exposing an error; call `reflag.refresh()` to retry. Check the mutation's returned `Response.ok` and catch promise rejections: HTTP failures return a readable non-OK response without refreshing, skipped calls return undefined, and confirmation can fail after membership changed remotely. +Each entry includes the flag's `key`, `name`, `description` and whether the user or company has opted in. User and company opt-ins are independent, and the user or company you opt in must have an `id`. `setOptIn()` resolves once the new flag values have loaded. Check `response.ok` and catch errors, as in the example. If the list fails to load, it stays empty; call `reflag.refresh()` to retry. ## Tracking, feedback and events Use `track(eventName, attributes?)`, `feedback(payload)` and `requestFeedback({ flagKey, ... })` on the client. See [FEEDBACK.md](./FEEDBACK.md) for the feedback UI and prompting configuration. -`on(event, handler)` returns an unsubscribe function. Events include `stateUpdated`, `flagsUpdated` (evaluated diagnostics), `check`, `track`, `user`, `company` and `optInFlagsLoadingUpdated`. +`on(event, handler)` returns an unsubscribe function. Events include `stateUpdated`, `flagsUpdated`, `check`, `track`, `user`, `company` and `optInFlagsLoadingUpdated`. + +## Migrating from v1 -## Migration from v1 +- `getFlag()` returns the flag's value: replace `getFlag(key).isEnabled` with `getFlag(key)`. +- Move remote config to a multivariate flag and read it with a default, such as `getFlag("model", "quick")`. Existing remote config isn't converted automatically. +- Use the client's `track()` and `requestFeedback()` instead of the flag's. +- `setFlagOverride(key, value)` takes the value directly; pass `undefined` to remove an override. +- `getFlags()` returns all flag values and records a check for each. +- Remove `fallbackFlags` and pass a default to each read instead, such as `getFlag("huddles", true)`. +- If you bootstrap from the server, upgrade the Node SDK that produces the bootstrap data to v2 at the same time. +- If you generate type declarations, regenerate them with the v2 CLI. -- Replace `getFlag(key).isEnabled` with `getFlag(key)`. -- Replace legacy remote config access with a separately authored multivariate flag and a positional default. Legacy config is **not** automatically converted into v2 values. -- Move flag `.track()` / `.requestFeedback()` calls to ordinary client methods. -- Replace wrapper overrides with `setFlagOverride(key, value)`; undefined clears, null is a value. -- `getFlags()` now returns values and registers checks. Tooling should use `getFlagResults()`. -- Upgrade both ends of bootstrap to v2. Old Browser/framework clients remain incompatible with v2 bootstrap. +See the [migration guide](https://docs.reflag.com/supported-languages/migrating-from-v1) for the full steps. diff --git a/packages/react-native-sdk/README.md b/packages/react-native-sdk/README.md index 35429a2d..2c6374e2 100644 --- a/packages/react-native-sdk/README.md +++ b/packages/react-native-sdk/README.md @@ -2,15 +2,15 @@ React Native providers and hooks for Boolean and multivariate flags. Built on the matching React v2 SDK, with AsyncStorage persistence and a native SSE transport included. -This branch targets the v2 toolchain; it does not publish packages. Upgrade Node/bootstrap producers and Native consumers together. The [React SDK README](../react-sdk/README.md) covers the shared API. +The [React SDK README](../react-sdk/README.md) covers the shared API. ## Install and initialize ```sh -npm install @reflag/react-native-sdk@2 +npm install @reflag/react-native-sdk ``` -Requires React 17 or later (the modern JSX runtime) and a React version supported by your React Native app. Wrap your app with the Native provider, which supplies the platform adapters: +Requires React 17 or later (the modern JSX runtime) and a React version supported by your React Native app. Wrap your app with the React Native provider, which supplies the platform adapters: ```tsx import { ReflagProvider } from "@reflag/react-native-sdk"; @@ -26,11 +26,11 @@ import { ReflagProvider } from "@reflag/react-native-sdk"; ; ``` -Use only publishable keys in the app, never server secret keys. Native providers default live updates on, persistence to AsyncStorage, and SSE to `react-native-sse` with transport polling disabled. `storage`, `eventSourceFactory`, and `enableLiveFlagUpdates` remain configurable. +Use only publishable keys in the app, never server secret keys. React Native providers default live updates on, persistence to AsyncStorage, and SSE to `react-native-sse` with transport polling disabled. `storage`, `eventSourceFactory`, and `enableLiveFlagUpdates` remain configurable. ## Read flags and track usage -`useFlag(key)` returns a **Boolean**, with false while initializing or when missing. A positional JSON default requests a matching top-level value category: +Pass a flag key to check whether it's enabled, or add a default to read another value: ```tsx import { Button } from "react-native"; @@ -50,13 +50,15 @@ function StartHuddleButton() { } ``` -Defaults infer widened direct-value types without generated declarations. Accepted false, zero, empty strings and null are not replaced by truthy fallbacks. Explicit `null` requests arbitrary JSON; `undefined` retains the Boolean-first behavior. Returned JSON values are independent copies. Defaults check top-level categories, not nested runtime schemas. +Without a default, a read expects a Boolean and returns `false` if the flag is missing or isn't a Boolean. With a default, the read returns the default while flags load, or if the flag is missing or has a different JSON type. Pass `null` to accept any JSON value, then check its type before using it. -Reading registers root checks immediately; application usage remains separate through `useTrack()`. `useClient().getFlags()` also returns direct values, not v1 flag wrappers. `useIsLoading()` reports readiness separately. +The SDK doesn't check object fields or fill in missing fields from your default. + +Each read records a check. Reflag uses checks for exposure counts, and they show up in the Event Log, which helps with debugging. Track usage with `useTrack()`. `useIsLoading()` returns whether flags are still loading. ## Suspense -Ordinary `useFlag` never suspends, even inside a provider with `suspense` enabled. Use `useFlagSuspense` to wait for initialization: +`useFlag()` never suspends. To wait for flags with Suspense, use `useFlagSuspense()`: ```tsx import { Suspense } from "react"; @@ -73,11 +75,11 @@ function Huddles() { ; ``` -A missing flag uses its default after initialization rather than suspending forever. Provider `suspense` and `useOptInFlags({ suspense: true })` control opt-in metadata loading, not ordinary flag reads. An object passed as `useFlag`'s second argument is a JSON default, not loading options. +If a flag is missing once flags have loaded, it returns the default. The provider's `suspense` prop applies only to `useOptInFlags()`. -## Bootstrap from Node v2 +## Bootstrap from the server -Produce the envelope on your server using Node SDK v2: +Get the bootstrap data from the Node.js SDK on your server: ```ts const flags = serverClient.getFlagsForBootstrap({ @@ -86,7 +88,7 @@ const flags = serverClient.getFlagsForBootstrap({ }); ``` -Pass the complete serialized envelope to Native: +Pass the whole object to `ReflagBootstrappedProvider`: ```tsx import { ReflagBootstrappedProvider } from "@reflag/react-native-sdk"; @@ -99,21 +101,21 @@ import { ReflagBootstrappedProvider } from "@reflag/react-native-sdk"; ; ``` -The envelope contains `protocolVersion: 2`, context, evaluated flags and an optional snapshot version. Legacy v1 bootstrap is rejected. Live updates require a snapshot version. Never expose secret keys or server-only attributes in bootstrap data: later refreshes use app-visible context and may differ from server evaluation. Disable live updates when later client evaluation must not replace the server result. Requesting missing opt-in metadata still makes a client-side request even with live updates disabled. +Flags are then available immediately, without a network request. With live updates on, later refreshes evaluate flags using the app's context, so values that depend on server-only attributes can change. Set `enableLiveFlagUpdates={false}` if they must not. -`ReflagClientProvider` accepts an externally initialized matching v2 client. Its lifecycle and platform-adapter configuration belong to your application; the Native convenience providers do not configure an external client. +To use a client you create yourself, pass it to `ReflagClientProvider`. Your app is then responsible for initializing and stopping it, and for configuring its storage and live updates. ## Opt-in and feedback -`useOptInFlags()` returns metadata and loading state; `useSetOptIn()` changes membership. Metadata arrives with ordinary `/flags/evaluated` responses, or on demand after bootstrap without replacing server-derived values. User/company grants stay independent. Successful mutations confirm versioned evaluation and membership in one refresh. Check the returned `Response.ok` and catch rejections: confirmation can fail after membership changed remotely, and skipped calls return undefined. Failed metadata loading settles without exposing an error; use `useClient().refresh()` to retry. +`useOptInFlags()` returns the flags users can opt in to, and `useSetOptIn()` changes an opt-in. Each entry includes the flag's `key`, `name`, `description` and whether the user or company has opted in. User and company opt-ins are independent, and the user or company you opt in must have an `id`. `setOptIn()` resolves once the new flag values have loaded. Check `response.ok` and catch errors, as in the example. If the list fails to load, it stays empty; call `useClient().refresh()` to retry. -The toolbar and built-in feedback UI are web-only and disabled by default. Use your own Native feedback UI with `useSendFeedback()` or `client.feedback()`; enabling a web UI option does not make it Native-compatible. +The toolbar and built-in feedback UI are web-only and disabled by default. Collect feedback with your own UI and send it with `useSendFeedback()`. -`enableTracking: false` disables checks and ordinary tracking. Offline mode skips HTTP/tracking; use direct-value fallbacks such as `fallbackFlags={{ huddle: true, settings: { mode: "offline" } }}`. +Set `enableTracking: false` to stop sending checks and events, or `offline` to skip all requests, and reads return their defaults. ## Optional key registration -Native reexports React's hooks and **shares React's `Flags` registry**. Register direct-value schemas in `@reflag/react-sdk`, not a separate Native registry: +The React Native SDK reexports React's hooks and **shares React's `Flags` registry**. Register flag types in `@reflag/react-sdk`, not a separate React Native registry: ```ts import "@reflag/react-native-sdk"; @@ -126,7 +128,7 @@ declare module "@reflag/react-sdk" { } ``` -Registration constrains keys and checks non-null positional defaults, including required and nested fields. Named-interface and readonly defaults work. It does not restore wrappers or validate nested runtime payloads. The Native package reexports the same registry/types; v2 CLI React-format declarations target this shared interface. Regenerate legacy wrapper declarations before use; CLI v2 is a separate release dependency. +Registered flags get autocompletion for their keys and type checks for the defaults you pass. The checks happen at compile time only. To generate the declarations, run `npx reflag flags types` with the `react` format. ## Refresh when returning to the foreground @@ -154,14 +156,18 @@ function AppStateListener() { } ``` -Mount this listener under a Native provider. Context prop changes and `useUpdateUser`/`useUpdateCompany`/`useUpdateOtherContext` also update evaluation context. +Mount this listener under a React Native provider. Context prop changes and `useUpdateUser`/`useUpdateCompany`/`useUpdateOtherContext` also update evaluation context. ## Migrating from v1 -- Replace `const { isEnabled, track } = useFlag(key)` with `const enabled = useFlag(key)` and a separate `useTrack()` call. -- Replace remote-config wrappers with authored multivariate flags and positional JSON defaults. -- Use `useFlagSuspense`, not `useFlag(key, { suspense: true })`, for readiness-waiting reads. -- Use direct-value fallback maps for multivariate flags; Boolean string-array shorthand remains supported. Migrate both ends of bootstrap to protocol v2. -- Rebuild against matching Native/React/Browser v2 packages and regenerate legacy declarations. +- `useFlag()` returns the flag's value: replace `const { isEnabled } = useFlag(key)` with `const enabled = useFlag(key)`. +- Move remote config to a multivariate flag and read it with a default, such as `useFlag("model", "quick")`. Existing remote config isn't converted automatically. +- Use `useTrack()` instead of the flag's `track()`, and send feedback with `useSendFeedback()`. +- Replace `useFlag(key, { suspense: true })` with `useFlagSuspense(key)`, and the flag's loading property with `useIsLoading()`. +- Remove `fallbackFlags` and pass a default to each read instead, such as `useFlag("huddles", true)`. +- If you bootstrap from the server, upgrade the Node SDK that produces the bootstrap data to v2 at the same time. +- If you generate type declarations, regenerate them with the v2 CLI. + +The [Expo](https://github.com/reflagcom/javascript/tree/main/packages/react-native-sdk/dev/expo) and [bare React Native](https://github.com/reflagcom/javascript/tree/main/packages/react-native-sdk/dev/bare-rn) examples use the v2 React Native APIs. The OpenFeature providers still use SDK v1. -The [Expo](https://github.com/reflagcom/javascript/tree/main/packages/react-native-sdk/dev/expo) and [bare React Native](https://github.com/reflagcom/javascript/tree/main/packages/react-native-sdk/dev/bare-rn) examples use the v2 Native APIs. OpenFeature providers are separate integrations and do not gain v2 support from this migration. +See the [migration guide](https://docs.reflag.com/supported-languages/migrating-from-v1) for the full steps. diff --git a/packages/react-sdk/README.md b/packages/react-sdk/README.md index a451cb99..b716cfa9 100644 --- a/packages/react-sdk/README.md +++ b/packages/react-sdk/README.md @@ -1,8 +1,6 @@ # Reflag React SDK v2 -Direct-value feature flags for React, backed by [Browser SDK v2](../browser-sdk/README.md). - -> Breaking prerelease: requires compatible v2 server endpoints and **Node SDK v2** for bootstrap. The v2 CLI generates direct-value declarations; regenerate legacy wrapper-shaped output when migrating. Useful default-based inference does not require generated declarations. React Native remains on published React/Browser v1 in this repository. +Feature flags for React, built on the [Browser SDK](../browser-sdk/README.md). ## Setup @@ -20,7 +18,7 @@ import { ReflagProvider } from "@reflag/react-sdk"; ; ``` -Provider options forward Browser SDK settings, including `logger`, `debug`, `enableTracking`, `offline`, cache/fallback options, `toolbar`, `feedback`, `credentials` and API origins. A custom logger takes precedence over debug logging. Live updates default to true; set `enableLiveFlagUpdates={false}` to disable them. +Provider options forward Browser SDK settings, including `logger`, `debug`, `enableTracking`, `offline`, cache options, `toolbar`, `feedback`, `credentials` and API origins. A custom logger takes precedence over debug logging. Live updates default to true; set `enableLiveFlagUpdates={false}` to disable them. ## `useFlag(key, defaultValue?)` @@ -28,7 +26,7 @@ Provider options forward Browser SDK settings, including `logger`, `debug`, `ena import { useFlag, useTrack } from "@reflag/react-sdk"; function Huddles() { - const enabled = useFlag("huddles"); // boolean, implicit false + const enabled = useFlag("huddles"); // true or false const settings = useFlag("huddle-settings", { maxParticipants: 10 }); const track = useTrack(); if (!enabled) return null; @@ -40,18 +38,20 @@ function Huddles() { } ``` -Bare reads return Boolean/false, including while initial data is unavailable. A positional default infers widened direct types, even without generated declarations: +Pass a default to read other values. The default sets the return type: ```ts useFlag("model", "quick"); // string useFlag("limit", 10); // number useFlag("settings", { model: "quick" }); // { model: string } -useFlag("nullable-settings", null); // FlagValue: arbitrary JSON +useFlag("anything", null); // any JSON value ``` -Non-null defaults enforce only the top-level JSON category (Boolean/number/string/array/object). Mismatches return the default and warn without logging the payload. Explicit null accepts authored null and all other JSON; missing values return null. Accepted false, zero and empty strings are preserved. Nested fields/elements are not schema-validated. Values/defaults are independent mutable copies; readonly defaults are accepted. +Without a default, a read expects a Boolean and returns `false` if the flag is missing or isn't a Boolean. With a default, the read returns the default while flags load, or if the flag is missing or has a different JSON type. Pass `null` to accept any JSON value, then check its type before using it. + +The SDK doesn't check object fields or fill in missing fields from your default. -`useFlag` never suspends. Its second argument is **payload data**, not `{ suspense: ... }` options; ordinary JSON has no reserved keys. Use the dedicated hook below for suspension. Use `useIsLoading()` or the provider's `loadingComponent` when you need an explicit loading UI. +`useFlag()` never suspends. To wait for flags with Suspense, use `useFlagSuspense()`. For a loading UI, use `useIsLoading()` or the provider's `loadingComponent`. ## `useFlagSuspense(key, defaultValue?)` @@ -69,15 +69,15 @@ function Model() { ; ``` -This hook has the same Boolean/default-based return types. It waits for initialization before reading. Once initialization settles, missing flags return their default rather than suspending forever. Bootstrap values can render immediately. Suspended attempts do not register a root read before data is ready. +It takes the same arguments as `useFlag()` and suspends until flags have loaded. If a flag is missing once they have, it returns the default. -The provider's existing `suspense` prop continues to configure **`useOptInFlags` only**. It does not change `useFlag`; `useFlagSuspense` is explicit. +The provider's `suspense` prop applies only to `useOptInFlags()`. ## Checks and usage tracking -A completed getter/hook read registers its requested-root check immediately, even if the value is ignored. Actual delivery remains buffered and identity-aware rate-limited by the Browser SDK. Checks contain selected variant/source/snapshot identity, not payloads. Defaults, category mismatches and local overrides never invent authored selections. Diagnostic/bootstrap inspection registers no checks. +Each read records a check. Reflag uses checks for exposure counts, and they show up in the Event Log, which helps with debugging. -Application usage and feedback remain separate hooks: +Track usage and collect feedback with separate hooks: ```ts const track = useTrack(); @@ -102,17 +102,17 @@ declare module "@reflag/react-sdk" { } ``` -Registration constrains keys and checks non-null defaults against the registered value schema, including required and nested properties. Named-interface and readonly defaults are supported. Explicit `null` remains an arbitrary-JSON request; bare/`undefined` reads remain Boolean. The positional default still determines the widened return type, and generated declarations do not add nested runtime validation. The same rules apply to `useFlagSuspense`. The v2 CLI generates direct-value declarations from current production-environment variants; regenerate legacy wrapper declarations when migrating. +Registered flags get autocompletion for their keys and type checks for the defaults you pass, in both `useFlag()` and `useFlagSuspense()`. The checks happen at compile time only. To generate the declarations, run `npx reflag flags types` with the `react` format. ## Bootstrap and SSR -On the server, use Node SDK v2: +Get the bootstrap data from the Node.js SDK on your server: ```ts const flags = serverClient.getFlagsForBootstrap(context); ``` -Pass the **entire** safe, serialized envelope to the client provider: +Pass the whole object to `ReflagBootstrappedProvider`: ```tsx import { ReflagBootstrappedProvider } from "@reflag/react-sdk"; @@ -122,16 +122,16 @@ import { ReflagBootstrappedProvider } from "@reflag/react-sdk"; ; ``` -The envelope includes `protocolVersion: 2`, context, evaluated flag results and optional `flagStateVersion`. V1 bootstrap is rejected. Use a snapshot version for live updates; later refreshes use browser-visible context. Do not send secrets/server-only attributes to the browser. Disable live updates if later browser evaluation must not replace server-only results. Requesting missing opt-in metadata still makes a browser-side request even when live updates are disabled. +Flags are then available immediately, without a network request. With live updates on, later refreshes evaluate flags using the browser's context, so values that depend on server-only attributes can change. Set `enableLiveFlagUpdates={false}` if they must not. -For a pre-existing Browser v2 client, use ``. The provider does not own its lifecycle; initialize/stop externally, except that a suspending read can start on-demand initialization. +To use a client you create yourself, pass it to `ReflagClientProvider`. Your app is then responsible for initializing and stopping it. ## Context, loading and events -- `useUpdateUser()`, `useUpdateCompany()` and `useUpdateOtherContext()` return async shallow-update functions. `useClient().setContext(context)` replaces the whole context. -- Context changes clear old-context values while fetching. Stale/in-flight responses cannot replace a newer context/snapshot. -- `useIsLoading()` returns provider loading state. `loadingComponent` and `initialLoading` configure initial presentation; they are not getter arguments. -- `useClient()` returns the underlying Browser client. Its `getFlags()` returns direct values/checks; `getFlagResults()` is diagnostic-only. +- `useUpdateUser()`, `useUpdateCompany()` and `useUpdateOtherContext()` return functions that merge new attributes into the current context. `useClient().setContext(context)` replaces the whole context. +- While flags for a new context load, reads return their defaults. +- `useIsLoading()` returns provider loading state. Use `loadingComponent` or `initialLoading` to control what renders while flags load. +- `useClient()` returns the underlying Browser client. - `useOnEvent(type, handler, client?)` subscribes and unsubscribes on unmount. A supplied external client works without a provider. ## Opt-in hooks @@ -147,10 +147,18 @@ try { } ``` -Metadata arrives with the initial v2 evaluation for regular providers. Bootstrapped providers fetch missing metadata on demand from `/flags/evaluated` without replacing server-derived values. `isLoading` covers initialization and metadata retrieval; it settles on success or failure. Metadata presentation includes `isEnabled` and membership fields, separately from direct flag reads. User/company grants remain independent. Mutations confirm versioned evaluation and membership in a single refresh. Check the returned `Response.ok` and catch rejections; a confirmation failure can occur after membership changed remotely, and skipped calls return undefined. Failed metadata requests settle loading without exposing an error; use `useClient().refresh()` to retry. +Each entry includes the flag's `key`, `name`, `description` and whether the user or company has opted in. User and company opt-ins are independent, and the user or company you opt in must have an `id`. `setOptIn()` resolves once the new flag values have loaded. Check `response.ok` and catch errors, as in the example. If the list fails to load, it stays empty; call `useClient().refresh()` to retry. + +Pass `{ suspense: true }` to `useOptInFlags()` to suspend until the list loads. It defaults to the provider's `suspense` prop. -`useOptInFlags({ suspense: true | false })` retains its own per-hook loading options and may inherit provider `suspense`. These options are unrelated to the positional payload defaults used by `useFlag` / `useFlagSuspense`. +## Migrating from v1 -## Migration from v1 +- `useFlag()` returns the flag's value: replace `const { isEnabled } = useFlag(key)` with `const enabled = useFlag(key)`. +- Move remote config to a multivariate flag and read it with a default, such as `useFlag("model", "quick")`. Existing remote config isn't converted automatically. +- Use `useTrack()` and `useRequestFeedback()` instead of the flag's `track()` and `requestFeedback()`. +- Replace `useFlag(key, { suspense: true })` with `useFlagSuspense(key)`, and the flag's loading property with `useIsLoading()`. +- Remove `fallbackFlags` and pass a default to each read instead, such as `useFlag("huddles", true)`. +- If you bootstrap from the server, upgrade the Node SDK that produces the bootstrap data to v2 at the same time. +- If you generate type declarations, regenerate them with the v2 CLI. -Use `const enabled = useFlag(key)` instead of destructuring `.isEnabled`. Replace wrapper config access with an authored multivariate flag and positional default. Move `.track()` and `.requestFeedback()` to separate hooks. Replace `useFlag(key, { suspense: true })` with `useFlagSuspense(key)`, and use `useIsLoading()` instead of a flag wrapper's loading property. Upgrade Browser/server bootstrap together. Nothing here publishes the prerelease or deploys its required server changes. +See the [migration guide](https://docs.reflag.com/supported-languages/migrating-from-v1) for the full steps. diff --git a/packages/vue-sdk/README.md b/packages/vue-sdk/README.md index 2dee709e..e429d260 100644 --- a/packages/vue-sdk/README.md +++ b/packages/vue-sdk/README.md @@ -1,8 +1,6 @@ # Reflag Vue SDK v2 -Reactive direct-value flags for Vue 3, backed by [Browser SDK v2](../browser-sdk/README.md). - -> Breaking prerelease: requires the compatible v2 server protocol. Bootstrap must come from **Node SDK v2**, not v1. Generated declarations are optional; the v2 CLI supports `--format vue` and direct-value schemas. Regenerate legacy wrapper-shaped declarations when migrating. +Feature flags for Vue 3, built on the [Browser SDK](../browser-sdk/README.md). ## Setup @@ -25,7 +23,7 @@ import { ReflagProvider } from "@reflag/vue-sdk"; ``` -Provider options forward Browser settings, including cache/storage, fallback values, offline/tracking, feedback, toolbar, credentials and API origins. `logger` takes precedence over `debug`. Live updates default to true; disable with `:enable-live-flag-updates="false"`. For an ordinary client-only Nuxt provider, wrap it in ``. +Provider options forward Browser settings, including cache/storage, offline/tracking, feedback, toolbar, credentials and API origins. `logger` takes precedence over `debug`. Live updates default to true; disable with `:enable-live-flag-updates="false"`. For an ordinary client-only Nuxt provider, wrap it in ``. ## `useFlag(key, defaultValue?)` @@ -33,7 +31,7 @@ Provider options forward Browser settings, including cache/storage, fallback val