diff --git a/packages/browser-sdk/README.md b/packages/browser-sdk/README.md index 10c44a2a..68ad060b 100644 --- a/packages/browser-sdk/README.md +++ b/packages/browser-sdk/README.md @@ -1,11 +1,19 @@ -# Reflag Browser SDK v2 +# Reflag Browser SDK -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. +Feature flags, remote configuration, usage tracking and feedback for browser applications. ## Get started +### 1. Create a client + +Install the SDK: + +```sh +npm install @reflag/browser-sdk +``` + +Create a client with your **publishable** key and the signed-in user's context: + ```ts import { ReflagClient } from "@reflag/browser-sdk"; @@ -15,138 +23,154 @@ const reflag = new ReflagClient({ company: { id: "acme", plan: "enterprise" }, }); await reflag.initialize(); +``` + +Publishable keys are safe to ship to the browser. Keep secret keys on your server. + +### 2. Create a flag -const enabled = reflag.getFlag("huddles"); // boolean, implicit false -const settings = reflag.getFlag("assistant-settings", { model: "quick" }); -// settings: { model: string } +Create a flag with the key `huddles` in the Reflag app. -if (enabled) { - // Application usage tracking is separate from reading the flag. +### 3. Read the flag + +```ts +if (reflag.getFlag("huddles")) { await reflag.track("Started huddle"); } ``` -Use only a **publishable** key in a browser. Secret keys belong on your server. +## Read flags -## Direct-value reads +Pass a flag key to check whether the flag is enabled: ```ts -reflag.getFlag("release"); // boolean; missing/mismatched -> false -reflag.getFlag("model", "quick"); // string -reflag.getFlag("limit", 10); // number -reflag.getFlag("settings", { model: "quick" }); -reflag.getFlag("nullable-settings", null); // FlagValue (arbitrary JSON) +const enabled = reflag.getFlag("huddles"); // true or false ``` -- 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. +Pass a default as the second argument to read a configuration value. The default sets the expected JSON type: -`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. +```ts +const model = reflag.getFlag("model", "quick"); // string +const settings = reflag.getFlag("assistant-settings", { model: "quick" }); // { model: string } +``` + +If the flag is missing or has a different JSON type, such as a string instead of a number, the SDK returns your default. Without a default, it expects a Boolean and falls back to `false`. Pass `null` to allow 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. + +`getFlags()` returns an object mapping flag keys to values. -## Checks and delivery +Each read records a check, which Reflag uses for launch monitoring. -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. +## Track usage and feedback -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. +```ts +await reflag.track("Started huddle", { button: "cta" }); +reflag.requestFeedback({ flagKey: "huddles", title: "How did it go?" }); +await reflag.feedback({ flagKey: "huddles", score: 5 }); +``` + +`requestFeedback()` opens the feedback form. `feedback()` sends feedback you collected yourself. -`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. +Configure your flag's adoption rules to match the event names you send. See [FEEDBACK.md](./FEEDBACK.md) to configure feedback prompts and the feedback UI. -## Context, refresh and cache +## Update context ```ts await reflag.updateUser({ role: "admin" }); await reflag.updateCompany({ plan: "enterprise" }); await reflag.updateOtherContext({ region: "eu" }); + +// Replace the whole context, for example after the user switches company: await reflag.setContext({ user: { id: "bob" }, company: { id: "other-company" }, }); -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. +The update methods merge into their section of the context, while `setContext()` replaces all of it. User and company sections need an `id`. Flag values are refetched for the new context. -Constructor options include: +## Bootstrap from the server -| 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 | +To render flags immediately, without waiting for a network request, evaluate them on your server with the **Node.js SDK** and pass the result to the browser: -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. - -## Overrides and toolbar +```ts +// On the server +const bootstrappedState = serverClient.getFlagsForBootstrap(context); +``` ```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 +// In the browser +const reflag = new ReflagClient({ publishableKey, bootstrappedState }); +await reflag.initialize(); ``` -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. +Pass the whole object returned by `getFlagsForBootstrap()`, serialized with your framework's usual mechanism. Leave secrets and server-only attributes out of the context you bootstrap, because the browser can read it. -## Server bootstrap +Later refreshes evaluate flags using the browser's context. If values that depend on server-only attributes must not change, leave `enableLiveFlagUpdates` off (the default). -Generate the full payload with **Node SDK v2** on your server: +## Let users opt in to flags ```ts -const bootstrappedState = serverClient.getFlagsForBootstrap(context); -// Send via your framework's safe JSON/hydration mechanism. +const optInFlags = reflag.getOptInFlags(); +await reflag.setOptIn("huddles", { optedIn: true }); +await reflag.setOptIn("huddles", { optedIn: false, scope: "company" }); ``` +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. Use `getIsLoadingOptInFlags()` and the `optInFlagsLoadingUpdated` event to show a loading state. + +## Overrides and toolbar + +Override flags locally while developing or testing: + ```ts -const reflag = new ReflagClient({ publishableKey, bootstrappedState }); -await reflag.initialize(); -const enabled = reflag.getFlag("release"); +reflag.setFlagOverride("huddles", true); +reflag.setFlagOverride("assistant-settings", { model: "local" }); +reflag.setFlagOverride("huddles", undefined); // remove the override ``` -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. - -## End-user opt-in +The toolbar shows on `localhost` by default and lets you toggle Boolean flags for yourself. Use the `toolbar` option to show it elsewhere, for example to internal users in production: ```ts -const options = reflag.getOptInFlags(); -const loading = reflag.getIsLoadingOptInFlags(); -try { - const response = await reflag.setOptIn("huddles", { optedIn: true }); - if (!response?.ok) console.error("Could not update opt-in"); -} catch (error) { - console.error("Could not update opt-in", error); -} +const reflag = new ReflagClient({ + publishableKey, + toolbar: user.isInternal, // show the toolbar to internal users +}); ``` -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. +## Events + +`on(event, handler)` subscribes to client events and returns an unsubscribe function. Events include `stateUpdated`, `flagsUpdated`, `check`, `track`, `user`, `company` and `optInFlagsLoadingUpdated`. + +## Configuration -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. +| Option | Description | +| -------------------------- | --------------------------------------------------------------- | +| `fallbackFlags` | Values to use if flags can't be fetched | +| `enableLiveFlagUpdates` | Update flags when they change in Reflag; default `false` | +| `staleTimeMs` | How long cached flags count as fresh; default `0` | +| `staleWhileRevalidate` | Use stale cached flags while fetching new ones; default `false` | +| `expireTimeMs` | How long cached flags are kept; default 30 days | +| `timeoutMs` | Flag request timeout; default 5,000 ms | +| `enableTracking` | Set to `false` to stop sending checks and usage events | +| `offline` | Make no network requests, for example in tests | +| `toolbar`, `feedback` | Toolbar and feedback UI options | +| `logger` | Custom logger | +| `apiBaseUrl`, `appBaseUrl` | Override the API and app URLs | +| `credentials` | Fetch credentials mode | +| `storage` | Custom async storage for the flag cache | +| `eventSourceFactory` | Custom EventSource implementation for runtimes without one | +| `trackingQueue` | Event batching: `flushDelayMs` and `maxSize` | -## Tracking, feedback and events +## Shut down -Use `track(eventName, attributes?)`, `feedback(payload)` and `requestFeedback({ flagKey, ... })` on the client. See [FEEDBACK.md](./FEEDBACK.md) for the feedback UI and prompting configuration. +Call `await reflag.stop()` to send buffered events and close the client, for example when the user signs out. -`on(event, handler)` returns an unsubscribe function. Events include `stateUpdated`, `flagsUpdated` (evaluated diagnostics), `check`, `track`, `user`, `company` and `optInFlagsLoadingUpdated`. +## Content Security Policy (CSP) -## Migration from v1 +If your site uses a strict Content Security Policy, allow: -- 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. +| Directive | Value | Reason | +| ------------- | -------------------------- | ---------------------------------- | +| `connect-src` | `https://front.reflag.com` | API requests and live updates | +| `style-src` | `'unsafe-inline'` | The feedback UI uses inline styles | diff --git a/packages/react-native-sdk/README.md b/packages/react-native-sdk/README.md index 35429a2d..6bc9bce2 100644 --- a/packages/react-native-sdk/README.md +++ b/packages/react-native-sdk/README.md @@ -1,62 +1,81 @@ -# Reflag React Native SDK v2 +# Reflag React Native SDK -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. +Feature flags, remote configuration and usage tracking for React Native apps. Built on the [React SDK](../react-sdk/README.md), with flag caching and live updates set up for React Native. -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. +## Get started -## Install and initialize +### 1. Add the provider + +Install the SDK: ```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: +It requires React 17 or later. Wrap your app in `ReflagProvider` with your **publishable** key and the signed-in user's context: ```tsx 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. +Publishable keys are safe to ship in your app. Keep secret keys on your server. + +### 2. Create a flag + +Create a flag with the key `huddles` in the Reflag app. -## Read flags and track usage +### 3. Read the flag -`useFlag(key)` returns a **Boolean**, with false while initializing or when missing. A positional JSON default requests a matching top-level value category: +Use `useFlag()` in any component: ```tsx import { Button } from "react-native"; import { useFlag, useTrack } from "@reflag/react-native-sdk"; function StartHuddleButton() { - const enabled = useFlag("huddle"); - const settings = useFlag("huddle-settings", { maxParticipants: 10 }); + const enabled = useFlag("huddles"); const track = useTrack(); if (!enabled) return null; return ( - - ); + return ; } ``` -Bare reads return Boolean/false, including while initial data is unavailable. A positional default infers widened direct types, even without generated declarations: +## Read flags -```ts -useFlag("model", "quick"); // string -useFlag("limit", 10); // number -useFlag("settings", { model: "quick" }); // { model: string } -useFlag("nullable-settings", null); // FlagValue: arbitrary JSON +Pass a flag key to check whether the flag is enabled: + +```tsx +const enabled = useFlag("huddles"); // true or false ``` -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. +Pass a default as the second argument to read a configuration value. The default sets the expected JSON type: + +```tsx +const model = useFlag("model", "quick"); // string +const settings = useFlag("huddle-settings", { maxParticipants: 10 }); // { maxParticipants: number } +``` -`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. +While flags load, or if the flag is missing or has a different JSON type, `useFlag()` returns your default. Without a default, it expects a Boolean and falls back to `false`. Pass `null` to allow any JSON value, then check its type before using it. -## `useFlagSuspense(key, defaultValue?)` +The SDK doesn't check object fields or fill in missing fields from your default. + +Each read records a check, which Reflag uses for launch monitoring. + +## Loading states and Suspense + +`useFlag()` returns immediately and never suspends. To show a loading UI, use `useIsLoading()` or the provider's `loadingComponent` prop: + +```tsx +} +> + + +``` + +To wait for flags with React Suspense, use `useFlagSuspense()`. It takes the same arguments as `useFlag()`: ```tsx import { Suspense } from "react"; @@ -69,50 +105,34 @@ 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. - -The provider's existing `suspense` prop continues to configure **`useOptInFlags` only**. It does not change `useFlag`; `useFlagSuspense` is explicit. - -## Checks and usage tracking +## Track usage and feedback -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. - -Application usage and feedback remain separate hooks: - -```ts +```tsx const track = useTrack(); await track("Started huddle", { button: "cta" }); + const requestFeedback = useRequestFeedback(); requestFeedback({ flagKey: "huddles", title: "How did it go?" }); + const sendFeedback = useSendFeedback(); await sendFeedback({ flagKey: "huddles", score: 5 }); ``` -See [Browser feedback documentation](../browser-sdk/FEEDBACK.md) for UI/prompt configuration. +Configure your flag's adoption rules to match the event names you send. See the [Browser feedback documentation](../browser-sdk/FEEDBACK.md) to configure feedback prompts and the feedback UI. -## Optional key registration +## Update context -```ts -import "@reflag/react-sdk"; -declare module "@reflag/react-sdk" { - interface Flags { - huddles: boolean; - "huddle-settings": { maxParticipants: number }; - } -} -``` - -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. +`useUpdateUser()`, `useUpdateCompany()` and `useUpdateOtherContext()` return functions that merge new attributes into the current context. To replace the whole context, call `useClient().setContext(context)`. Flag values are refetched for the new context. -## Bootstrap and SSR +## Bootstrap from the server -On the server, use Node SDK v2: +To render flags immediately, without waiting for a network request, evaluate them on your server with the **Node.js SDK**: ```ts const flags = serverClient.getFlagsForBootstrap(context); ``` -Pass the **entire** safe, serialized envelope to the client provider: +Then pass the whole result to `ReflagBootstrappedProvider`, serialized with your framework's usual mechanism: ```tsx import { ReflagBootstrappedProvider } from "@reflag/react-sdk"; @@ -122,35 +142,63 @@ 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. +Leave secrets and server-only attributes out of the context you bootstrap, because the browser can read it. Later refreshes evaluate flags using the browser's context. If values that depend on server-only attributes must not change, set `enableLiveFlagUpdates={false}`. + +## Let users opt in to flags + +```tsx +const { flags, isLoading } = useOptInFlags(); +const setOptIn = useSetOptIn(); -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. +await setOptIn("huddles", { optedIn: true }); +await setOptIn("huddles", { optedIn: false, scope: "company" }); +``` -## Context, loading and events +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. Check `isLoading` before rendering an empty state. The provider's `suspense` prop, or `useOptInFlags({ suspense: true })`, makes this hook suspend instead. See [Beta feature opt-in](https://docs.reflag.com/guides/self-opt-in) for a complete example. -- `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. -- `useOnEvent(type, handler, client?)` subscribes and unsubscribes on unmount. A supplied external client works without a provider. +## Overrides and toolbar -## Opt-in hooks +The toolbar shows on `localhost` by default and lets you toggle Boolean flags for yourself. Use the `toolbar` prop to show it elsewhere, for example to internal users in production: ```tsx -const { flags, isLoading } = useOptInFlags(); -const setOptIn = useSetOptIn(); -try { - const response = await setOptIn("huddles", { optedIn: true }); - if (!response?.ok) console.error("Could not update opt-in"); -} catch (error) { - console.error("Could not update opt-in", error); + + + +``` + +To override a flag from code, call `useClient().setFlagOverride(key, value)`. Pass `undefined` to remove the override. + +## Type safety + +Declaring your flags gives you autocompletion for keys and type checks for defaults. If you created a flag with `npx reflag new`, the declarations are already generated; run `npx reflag flags types` again when your flags change. A declaration looks like this: + +```ts +import "@reflag/react-sdk"; + +declare module "@reflag/react-sdk" { + interface Flags { + huddles: boolean; + "huddle-settings": { maxParticipants: number }; + } } ``` -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. +Declarations are checked at compile time only. See the [Reflag CLI](https://docs.reflag.com/api/cli) for more options. + +## Use an existing client + +`useClient()` returns the underlying Browser SDK client. If you already create a Browser SDK client yourself, pass it to ``; your application is then responsible for initializing and stopping it. + +## Events + +`useOnEvent(type, handler)` subscribes to [client events](../browser-sdk/README.md) and unsubscribes when the component unmounts. -`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`. +## Configuration -## Migration from v1 +The provider accepts the Browser SDK's configuration options, such as `fallbackFlags`, `enableTracking`, `offline`, `feedback` and `logger`, as props. Live updates are on by default in React; set `enableLiveFlagUpdates={false}` to turn them off. Set `debug` to log to the console. -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. +For Content Security Policy requirements and the full list of options, see the [Browser SDK](../browser-sdk/README.md). diff --git a/packages/vue-sdk/README.md b/packages/vue-sdk/README.md index 2dee709e..32f6ba14 100644 --- a/packages/vue-sdk/README.md +++ b/packages/vue-sdk/README.md @@ -1,10 +1,18 @@ -# Reflag Vue SDK v2 +# Reflag Vue SDK -Reactive direct-value flags for Vue 3, backed by [Browser SDK v2](../browser-sdk/README.md). +Feature flags, remote configuration, usage tracking and feedback for Vue 3 applications. Built on the [Browser SDK](../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. +## Get started -## Setup +### 1. Add the provider + +Install the SDK: + +```sh +npm install @reflag/vue-sdk +``` + +Wrap your application in `ReflagProvider` with your **publishable** key and the signed-in user's context: ```vue ``` -Vue unwraps refs in templates; use `.value` in script. This is a **Vue ref**, not a flag wrapper. There are no `.isEnabled`, `.config`, flag `.track()` or flag loading fields. +## Read flags + +`useFlag()` returns a ref that updates when the flag changes. Vue unwraps refs in templates; use `.value` in script. + +Pass a flag key to check whether the flag is enabled: ```ts -useFlag("release"); // ShallowRef -useFlag("model", "quick"); // ShallowRef -useFlag("limit", 10); // ShallowRef -useFlag("settings", { model: "quick" }); // ShallowRef<{ model: string }> -useFlag("nullable-settings", null); // ShallowRef +const enabled = useFlag("huddles"); // ref of true or false ``` -Defaults are positional JSON; literals widen without generated types. Non-null defaults require the same top-level category (Boolean/number/string/array/object), otherwise the default is returned with a payload-safe warning. Null explicitly accepts arbitrary JSON, including authored null; missing returns null. Valid false/zero/empty strings are preserved. Nested payload schemas are not validated by the SDK. Returned values/defaults are independent copies; readonly defaults are accepted. +Pass a default as the second argument to read a configuration value. The default sets the expected JSON type: + +```ts +const model = useFlag("model", "quick"); // ref of string +const settings = useFlag("huddle-settings", { maxParticipants: 10 }); // ref of { maxParticipants: number } +``` -The ref updates when evaluated flags change. A composable read registers the requested root through the Browser SDK, even if its result is ignored; refresh-driven rereads are identity-aware rate-limited and delivered in batches. Diagnostics/bootstrap inspection register none. Checks carry genuine selected key/source/snapshot identity, never payloads or invented selections for defaults/overrides. +While flags load, or if the flag is missing or has a different JSON type, the ref holds your default. Without a default, it expects a Boolean and falls back to `false`. Pass `null` to allow any JSON value, then check its type before using it. -## Loading, context and client access +The SDK doesn't check object fields or fill in missing fields from your default. -- `useIsLoading()` returns a Boolean ref for provider loading; the `#loading` slot and `initialLoading` control initial presentation. -- `useUpdateUser()`, `useUpdateCompany()` and `useUpdateOtherContext()` return async shallow-update functions. -- `useClient()` exposes the Browser client, including `setContext(context)`, `refresh()` and `setFlagOverride(key, value)`. Undefined clears an override; null is a JSON override. -- `getFlags()` returns direct values and registers returned-root checks. Use `getFlagResults()` for tooling without checks. -- `useOnEvent(type, handler, client?)` subscribes on mount and unsubscribes on unmount. An external client may be supplied explicitly. +Each read records a check, which Reflag uses for launch monitoring. -A context change clears old values while fetching. Late responses for previous contexts or lower snapshot versions cannot replace accepted state. V2 cache/override storage is isolated from v1. Browser fetching uses `/flags/evaluated` and never re-evaluates/caches dependencies locally. +## Loading states -## Bootstrap +`useIsLoading()` returns a Boolean ref that is `true` while the provider loads flags. You can also put loading content in the provider's `#loading` slot, as in the example above. -On the server, use Node SDK v2 and your framework's safe serialization mechanism: +## Track usage and feedback + +```ts +const track = useTrack(); +await track("Started huddle", { button: "cta" }); + +const requestFeedback = useRequestFeedback(); +requestFeedback({ flagKey: "huddles", title: "How did it go?" }); + +const sendFeedback = useSendFeedback(); +await sendFeedback({ flagKey: "huddles", score: 5 }); +``` + +Configure your flag's adoption rules to match the event names you send. See the [Browser feedback documentation](../browser-sdk/FEEDBACK.md) to configure feedback prompts and the feedback UI. + +## Update context + +`useUpdateUser()`, `useUpdateCompany()` and `useUpdateOtherContext()` return functions that merge new attributes into the current context. To replace the whole context, call `useClient().setContext(context)`. Flag values are refetched for the new context. + +## Bootstrap from the server + +To render flags immediately, without waiting for a network request, evaluate them on your server with the **Node.js SDK**: ```ts const flags = serverClient.getFlagsForBootstrap(context); ``` +Then pass the whole result to `ReflagBootstrappedProvider`, serialized with your framework's usual mechanism: + ```vue ``` -Pass the entire envelope (`protocolVersion: 2`, context, evaluated flags and optional snapshot version). Legacy v1 bootstrap is rejected. A snapshot version is required for live updates. Never expose secret keys/server-only attributes in bootstrap data; later refreshes use browser-visible context, so disable live updates when they must not replace server-only evaluations. Requesting missing opt-in metadata still makes a browser-side request even when live updates are disabled. +Leave secrets and server-only attributes out of the context you bootstrap, because the browser can read it. Later refreshes evaluate flags using the browser's context. If values that depend on server-only attributes must not change, set `:enable-live-flag-updates="false"`. -`ReflagClientProvider` accepts an externally initialized Browser v2 client. Its lifecycle belongs to the application. - -## Opt-in, tracking and feedback +## Let users opt in to flags ```ts -const { flags, isLoading } = useOptInFlags(); // refs to metadata/list loading +const { flags, isLoading } = useOptInFlags(); const setOptIn = useSetOptIn(); -try { - const response = await setOptIn("huddles", { optedIn: true }); - if (!response?.ok) console.error("Could not update opt-in"); -} catch (error) { - console.error("Could not update opt-in", error); -} -const track = useTrack(); -await track("Started huddle", { button: "cta" }); -const requestFeedback = useRequestFeedback(); -requestFeedback({ flagKey: "huddles", title: "How did it go?" }); -const sendFeedback = useSendFeedback(); -await sendFeedback({ flagKey: "huddles", score: 5 }); +await setOptIn("huddles", { optedIn: true }); +await setOptIn("huddles", { optedIn: false, scope: "company" }); ``` -Opt-in metadata arrives with ordinary `/flags/evaluated` responses. Bootstrapped providers fetch missing metadata on demand from the same v2 endpoint without replacing server-derived values or provenance; loading settles on success or failure. User/company grants remain independent; successful mutations confirm versioned evaluation and membership in a single refresh. The metadata list retains presentation/membership fields such as `isEnabled`; ordinary reads remain direct values. 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. Check `isLoading` before rendering an empty state. -`enableTracking: false` disables checks and ordinary tracking. Offline mode skips HTTP/tracking. See [Browser feedback documentation](../browser-sdk/FEEDBACK.md) for prompting/UI options. +## Overrides and toolbar -## Optional key registration and migration +The toolbar shows on `localhost` by default and lets you toggle Boolean flags for yourself. Use the `toolbar` prop to show it elsewhere, for example to internal users in production: -```ts -import "@reflag/vue-sdk"; -declare module "@reflag/vue-sdk" { - interface Flags { - huddles: boolean; - "huddle-settings": { maxParticipants: number }; - } -} +```vue + + + ``` -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 refs. Positional defaults still determine widened direct-value types, and generated declarations do not add nested runtime validation. The v2 CLI generates these schemas from current production-environment variants with `--format vue`; regenerate old wrapper declarations when migrating. +To override a flag from code, call `useClient().setFlagOverride(key, value)`. Pass `undefined` to remove the override. + +## Use an existing client + +`useClient()` returns the underlying Browser SDK client. If you already create a Browser SDK client yourself, pass it to `ReflagClientProvider`; your application is then responsible for initializing and stopping it. + +## Events + +`useOnEvent(type, handler)` subscribes to [client events](../browser-sdk/README.md) and unsubscribes when the component unmounts. + +## Configuration + +The provider accepts the Browser SDK's configuration options, such as `fallbackFlags`, `enableTracking`, `offline`, `feedback` and `logger`, as props. Live updates are on by default in Vue; set `:enable-live-flag-updates="false"` to turn them off. Set `debug` to log to the console. -Replace `const { isEnabled } = useFlag(key)` with `const enabled = useFlag(key)` (then `enabled.value` in script). Replace remote-config wrappers with separately authored multivariate flags and positional defaults, and move usage/feedback into their separate composables. Bootstrap both ends with v2. This branch does not publish SDKs or deploy the required server changes. +For Content Security Policy requirements and the full list of options, see the [Browser SDK](../browser-sdk/README.md).