From ee5a583a5540cb33f423069de73ece385f579991 Mon Sep 17 00:00:00 2001 From: Ron Cohen Date: Tue, 1 Dec 2026 14:37:18 +0000 Subject: [PATCH] fix: return minimal JSON-safe bootstrap snapshots --- .changeset/slim-bootstrap-snapshots.md | 7 +++ packages/browser-sdk/src/client.ts | 39 ++++++++++++-- packages/browser-sdk/src/flag/flags.ts | 11 ++-- packages/browser-sdk/test/client.test.ts | 53 +++++++++++++++++++ packages/node-sdk/README.md | 6 ++- packages/node-sdk/src/client.ts | 19 +++++-- packages/node-sdk/src/types.ts | 10 +++- .../node-sdk/test/bootstrap-secrecy.test.ts | 34 +++++++++++- packages/react-sdk/src/index.tsx | 4 +- 9 files changed, 165 insertions(+), 18 deletions(-) create mode 100644 .changeset/slim-bootstrap-snapshots.md diff --git a/.changeset/slim-bootstrap-snapshots.md b/.changeset/slim-bootstrap-snapshots.md new file mode 100644 index 000000000..cefe15947 --- /dev/null +++ b/.changeset/slim-bootstrap-snapshots.md @@ -0,0 +1,7 @@ +--- +"@reflag/node-sdk": patch +"@reflag/browser-sdk": patch +"@reflag/react-sdk": patch +--- + +Return smaller, JSON-safe bootstrap snapshots. They retain flag values and the metadata needed for checks and refreshes, but omit unused evaluation details and properties with `undefined` values. Existing v2 clients can still read the snapshots at runtime. TypeScript apps passing Node bootstrap data directly to an older client SDK may need to update the client SDK to accept an omitted flag value. diff --git a/packages/browser-sdk/src/client.ts b/packages/browser-sdk/src/client.ts index cc5eb707b..c70ec7077 100644 --- a/packages/browser-sdk/src/client.ts +++ b/packages/browser-sdk/src/client.ts @@ -13,7 +13,13 @@ import { } from "./feedback/feedback"; import * as feedbackLib from "./feedback/ui"; import { isValidBootstrapSnapshot } from "./flag/bootstrap"; -import { CheckEvent, FlagsClient, OptInFlag, RawFlags } from "./flag/flags"; +import { + type BootstrappedFlags, + CheckEvent, + FlagsClient, + OptInFlag, + RawFlags, +} from "./flag/flags"; import { isValidFlagStateVersion } from "./flag/flagStateVersion"; import { FlagDefaultValue, @@ -226,7 +232,7 @@ export type FlagDefinitions = Readonly>; export type BootstrappedState = { protocolVersion: 2; context: ReflagContext; - flags: RawFlags; + flags: BootstrappedFlags; flagStateVersion?: number; }; @@ -1150,11 +1156,36 @@ export class ReflagClient { } getFlagsForBootstrap(): BootstrappedState { + const flagStateVersion = this.flagsClient.getFlagStateVersion(); + const flags = Object.fromEntries( + Object.entries(this.getFlagResults()).map(([key, flag]) => [ + key, + { + resolved: flag.resolved, + ...(flag.value === undefined ? {} : { value: flag.value }), + ...(flag.variantKey === undefined || + flag.sourceVersionId === undefined + ? {} + : { + variantKey: flag.variantKey, + sourceVersionId: flag.sourceVersionId, + }), + ruleResults: flag.ruleResults.map(({ ruleId, matched }) => ({ + ruleId, + matched, + })), + errors: flag.errors, + ...(flag.optInEnabled === undefined + ? {} + : { optInEnabled: flag.optInEnabled, optIn: flag.optIn }), + }, + ]), + ); return { protocolVersion: 2, context: this.getContext(), - flags: this.getFlagResults(), - flagStateVersion: this.flagsClient.getFlagStateVersion(), + flags, + ...(flagStateVersion === undefined ? {} : { flagStateVersion }), }; } diff --git a/packages/browser-sdk/src/flag/flags.ts b/packages/browser-sdk/src/flag/flags.ts index fdca62959..456159ead 100644 --- a/packages/browser-sdk/src/flag/flags.ts +++ b/packages/browser-sdk/src/flag/flags.ts @@ -179,9 +179,14 @@ const REFRESH_LIMIT_WINDOW_MS = 60 * 1000; export type FlagOverrides = Record; +type BootstrappedFlag = Omit & { + value?: RawFlag["value"]; +}; +export type BootstrappedFlags = Record; + type BootstrappedState = { protocolVersion: 2; - flags: RawFlags; + flags: BootstrappedFlags; flagStateVersion?: number; }; @@ -476,7 +481,7 @@ export class FlagsClient { } setFetchedFlags( - fetchedFlags: RawFlags, + fetchedFlags: BootstrappedFlags, triggerEvent = true, flagStateVersion?: number, ) { @@ -495,7 +500,7 @@ export class FlagsClient { // A newly accepted snapshot supersedes any metadata-only request in flight. this.optInMetadataFetchVersion++; this.setOptInMetadata(validated, flagStateVersion); - this.warnMissingFlagContextFields(fetchedFlags); + this.warnMissingFlagContextFields(validated); this.updateFlags(triggerEvent); } diff --git a/packages/browser-sdk/test/client.test.ts b/packages/browser-sdk/test/client.test.ts index 7cabaed00..b6b77759d 100644 --- a/packages/browser-sdk/test/client.test.ts +++ b/packages/browser-sdk/test/client.test.ts @@ -112,6 +112,59 @@ describe("direct values and root checks", () => { expect(checks()[0].evalErrors).toEqual([error]); }); + test("reserializes only bootstrap fields without losing check metadata", async () => { + const client = create({ + bootstrappedState: { + protocolVersion: 2, + context: { user: { id: "alice" } }, + flags: { + flagA: { + ...selectedFlag(null, "none"), + matchedRuleId: "split", + allocationIndex: 0, + ruleResults: [ + { ruleId: "skipped", matched: false }, + { + ruleId: "split", + matched: true, + allocationIndex: 0, + destination: { type: "variant", variantKey: "none" }, + }, + ], + }, + unresolved: { resolved: false, ruleResults: [], errors: [] }, + }, + }, + }); + expect(client.getFlagResults().flagA.allocationIndex).toBe(0); + const state = client.getFlagsForBootstrap(); + expect(state).toStrictEqual(JSON.parse(JSON.stringify(state))); + expect(state).not.toHaveProperty("flagStateVersion"); + expect(state.flags.flagA).toStrictEqual({ + value: null, + resolved: true, + variantKey: "none", + sourceVersionId: "version-1", + ruleResults: [ + { ruleId: "skipped", matched: false }, + { ruleId: "split", matched: true }, + ], + errors: [], + }); + expect(state.flags.unresolved).not.toHaveProperty("value"); + + const restored = create({ bootstrappedState: state }); + expect(restored.getFlag("flagA", null)).toBeNull(); + expect(restored.getFlag("unresolved", "fallback")).toBe("fallback"); + await restored.stop(); + expect(checks()[0]).toMatchObject({ + key: "flagA", + evalResult: "none", + sourceVersionId: "version-1", + evalRuleResults: [false, true], + }); + }); + test("registers an ignored root read immediately, but diagnostics/bootstrap register none; delivery stays buffered", async () => { const client = create(); const check = vi.fn(); diff --git a/packages/node-sdk/README.md b/packages/node-sdk/README.md index d0d07a465..3536cc03c 100644 --- a/packages/node-sdk/README.md +++ b/packages/node-sdk/README.md @@ -422,8 +422,10 @@ console.log(bootstrappedState); // "huddle-settings": { // "value": { "maxParticipants": 50, "videoQuality": "hd" }, // "variantKey": "enhanced", +// "sourceVersionId": "example-version", // "resolved": true, -// ... +// "ruleResults": [{ "ruleId": "example-rule", "matched": true }], +// "errors": [] // } // }, // flagStateVersion: 42 @@ -447,7 +449,7 @@ const bootstrappedState = boundClient.getFlagsForBootstrap(); ### Key differences from `getFlags()` -- **Raw data**: Returns the evaluated raw flags, including their values and evaluation details, as JSON serializable objects +- **Bootstrap data**: Returns JSON-safe flag values and the metadata needed to record checks in the client, without the full evaluation trace - **Public flags only**: Leaves out flags that aren't marked `secret: false` - **No checks**: Doesn't record `check` events - **Context included**: Returns both the evaluated flags and the context used for evaluation diff --git a/packages/node-sdk/src/client.ts b/packages/node-sdk/src/client.ts index a7e8b438a..285d31738 100644 --- a/packages/node-sdk/src/client.ts +++ b/packages/node-sdk/src/client.ts @@ -522,9 +522,22 @@ export class ReflagClient { .map(([key, result]) => [ key, { - ...result, - // Match publishable-key HTTP evaluation: dependency origins can name - // private flags or segments, even when the requested root is public. + resolved: result.resolved, + ...(result.value === undefined ? {} : { value: result.value }), + ...(result.resolved && + result.variantKey !== undefined && + result.sourceVersionId !== undefined + ? { + variantKey: result.variantKey, + sourceVersionId: result.sourceVersionId, + } + : {}), + // v2 readers require rule IDs, even though checks only send match booleans. + ruleResults: result.ruleResults.map(({ ruleId, matched }) => ({ + ruleId, + matched, + })), + // Dependency origins can name private flags or segments. errors: result.errors.map(({ source: _source, ...error }) => error), }, ]), diff --git a/packages/node-sdk/src/types.ts b/packages/node-sdk/src/types.ts index 917105166..7a5435da1 100644 --- a/packages/node-sdk/src/types.ts +++ b/packages/node-sdk/src/types.ts @@ -102,10 +102,18 @@ export type RawFlag = Omit< resolved: boolean; }; export type RawFlags = Record; +type BootstrappedFlag = Pick< + RawFlag, + "resolved" | "variantKey" | "sourceVersionId" +> & { + value?: FlagValue; + ruleResults: Pick[]; + errors: (EvaluationError & { source?: never })[]; +}; export type BootstrappedFlags = { protocolVersion: 2; context: Context; - flags: RawFlags; + flags: Record; flagStateVersion?: number; }; export type EvaluatedFlagsAPIResponse = { diff --git a/packages/node-sdk/test/bootstrap-secrecy.test.ts b/packages/node-sdk/test/bootstrap-secrecy.test.ts index 1bfd74aad..ea5a2fe98 100644 --- a/packages/node-sdk/test/bootstrap-secrecy.test.ts +++ b/packages/node-sdk/test/bootstrap-secrecy.test.ts @@ -117,13 +117,13 @@ describe("bootstrap visibility boundary", () => { resolved: true, variantKey: "on", sourceVersionId: "version:public", - matchedRuleId: "public-target", ruleResults: [{ ruleId: "public-target", matched: true }], errors: [{ code: "MISSING_CONTEXT_FIELD", field: "user.plan" }], }, }, }); const serialized = JSON.stringify(bootstrap); + expect(bootstrap).toStrictEqual(JSON.parse(serialized)); for (const privateData of [ privatePayload, "private-dependency", @@ -154,6 +154,37 @@ describe("bootstrap visibility boundary", () => { }, ); + it("keeps only the fields needed to bootstrap a percentage rollout", async () => { + const flag = definition("rollout", null); + flag.rules.unshift({ + id: "rollout-rule", + filter: { type: "constant", value: true }, + result: { + type: "percentageDistribution", + key: "rollout", + attribute: "company.id", + allocations: [ + { + percentage: 100, + destination: { type: "variant", variantKey: "default" }, + }, + ], + }, + }); + const h = harness(snapshot([flag])); + await h.client.initialize(); + expect(h.client.getFlagsForBootstrap(context).flags).toStrictEqual({ + rollout: { + value: null, + resolved: true, + variantKey: "default", + sourceVersionId: "version:rollout", + ruleResults: [{ ruleId: "rollout-rule", matched: true }], + errors: [], + }, + }); + }); + it.each([undefined, null, "false", 0, {}, true])( "does not treat visibility %j as an explicit public declaration", async (secret) => { @@ -187,7 +218,6 @@ describe("bootstrap visibility boundary", () => { const bootstrap = h.client.getFlagsForBootstrap(context); expect(bootstrap.flags).toEqual({ public: { - flagKey: "public", value: { nested: [false] }, resolved: false, ruleResults: [], diff --git a/packages/react-sdk/src/index.tsx b/packages/react-sdk/src/index.tsx index abd073cf1..256713f52 100644 --- a/packages/react-sdk/src/index.tsx +++ b/packages/react-sdk/src/index.tsx @@ -78,9 +78,7 @@ export type OptInFlag = Omit & { */ export type RawFlags = BrowserRawFlags; -export type BootstrappedFlags = BrowserBootstrappedState & { - flags: BrowserRawFlags; -}; +export type BootstrappedFlags = BrowserBootstrappedState; const SDK_VERSION = `react-sdk/${version}`;