From 512f03b2e2884bd5c112b3c01a469502bd0a6e1f Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sat, 15 Aug 2026 21:48:49 +0000 Subject: [PATCH 1/2] Add flagd / OpenFeature flag provider Land the last Phase 3 vendor adapter as a thin FlagProvider that translates injected OpenFeature evaluation details. Targeting and percentage rollouts stay in flagd. Co-authored-by: Fly Over Coder --- AGENTS.md | 8 +- README.md | 4 +- docs/PROJECT_PLAN.md | 35 +- docs/RELEASING.md | 5 +- packages/flags-flagd/LICENSE | 21 ++ packages/flags-flagd/README.md | 82 +++++ packages/flags-flagd/package.json | 39 +++ packages/flags-flagd/src/index.test.ts | 461 +++++++++++++++++++++++++ packages/flags-flagd/src/index.ts | 229 ++++++++++++ packages/flags-flagd/tsconfig.json | 12 + pnpm-lock.yaml | 6 + scripts/release-packages.mjs | 4 + tests/flagd-conformance.test.ts | 110 ++++++ tests/release-packages.test.ts | 1 + tsconfig.json | 1 + 15 files changed, 993 insertions(+), 25 deletions(-) create mode 100644 packages/flags-flagd/LICENSE create mode 100644 packages/flags-flagd/README.md create mode 100644 packages/flags-flagd/package.json create mode 100644 packages/flags-flagd/src/index.test.ts create mode 100644 packages/flags-flagd/src/index.ts create mode 100644 packages/flags-flagd/tsconfig.json create mode 100644 tests/flagd-conformance.test.ts diff --git a/AGENTS.md b/AGENTS.md index c9de492..45d96a8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -78,10 +78,10 @@ scaffold. ## Where things stand Phase 3 lands `@pegma/flags-launchdarkly`, -`@pegma/flags-aws-appconfig`, and `@pegma/flags-cloudflare-flagship` -beside the Phase 1 packages and `@pegma/flags-azure-appconfig` at -`0.1.0` (unpublished). Remaining vendor adapters (flagd) are still -later. +`@pegma/flags-aws-appconfig`, `@pegma/flags-cloudflare-flagship`, and +`@pegma/flags-flagd` beside the Phase 1 packages and +`@pegma/flags-azure-appconfig` at `0.1.0` (unpublished). Phase 3 vendor +adapters are complete. Siblings: [spine](https://github.com/pegma-dev/spine), [health](https://github.com/pegma-dev/health), diff --git a/README.md b/README.md index f29850f..83de225 100644 --- a/README.md +++ b/README.md @@ -83,11 +83,9 @@ const detail = await client.evaluate("checkoutEnabled", { | `@pegma/flags-azure-appconfig` | Azure App Configuration provider | | `@pegma/flags-aws-appconfig` | AWS AppConfig provider | | `@pegma/flags-cloudflare-flagship` | Cloudflare Flagship provider | +| `@pegma/flags-flagd` | flagd / OpenFeature provider | | `@pegma/flags-launchdarkly` | LaunchDarkly provider | -Remaining vendor adapters (flagd) are named in -[the plan](docs/PROJECT_PLAN.md) and stay later. - ## Development Requires Node.js 22 or 24. diff --git a/docs/PROJECT_PLAN.md b/docs/PROJECT_PLAN.md index 7dc0cd0..9286631 100644 --- a/docs/PROJECT_PLAN.md +++ b/docs/PROJECT_PLAN.md @@ -2,11 +2,12 @@ ## Status -**Stage:** Phase 3 LaunchDarkly, AWS AppConfig, and Cloudflare Flagship -adapters implemented in-tree; unpublished. Public API unstable (`0.x`). +**Stage:** Phase 3 vendor adapters implemented in-tree; unpublished. +Public API unstable (`0.x`). **First named consumers:** RetireGolden.org (Azure App Configuration). -Remaining vendor adapters (flagd) are still later. +Phase 3 vendor adapters (LaunchDarkly, AWS AppConfig, Cloudflare +Flagship, flagd) are complete. **License:** MIT @@ -104,7 +105,6 @@ package here would invite the wrong extractions. - Flag authoring, admin UI, or a Pegma-owned flag store. - A custom expression / rule language or AppConfig document evaluator. -- flagd adapter packages in this phase. - Metrics, experiment assignment, or percentage math in the core. ## Package architecture @@ -118,13 +118,14 @@ package here would invite the wrong extractions. | `@pegma/flags-azure-appconfig` | Azure App Configuration adapter | 2 | | `@pegma/flags-aws-appconfig` | AWS AppConfig adapter | 3 | | `@pegma/flags-cloudflare-flagship` | Cloudflare Flagship adapter | 3 | -| `@pegma/flags-flagd` | flagd / OpenFeature adapter | later | +| `@pegma/flags-flagd` | flagd / OpenFeature adapter | 3 | Dependencies: `@pegma/spine` pinned exactly. `@pegma/flags-static`, `@pegma/flags-azure-appconfig`, `@pegma/flags-aws-appconfig`, -`@pegma/flags-cloudflare-flagship`, and `@pegma/flags-launchdarkly` -depend only on `@pegma/flags-contracts` (no vendor SDK). Adapters pin -contracts (and spine, if they need `Logger` / `Clock`) exactly. +`@pegma/flags-cloudflare-flagship`, `@pegma/flags-launchdarkly`, and +`@pegma/flags-flagd` depend only on `@pegma/flags-contracts` (no vendor +SDK). Adapters pin contracts (and spine, if they need `Logger` / `Clock`) +exactly. ## Delivery phases @@ -146,14 +147,16 @@ still carries those rules. Do not pre-build the other vendors. ### Phase 3 — remaining adapters -`@pegma/flags-launchdarkly`, `@pegma/flags-aws-appconfig`, and -`@pegma/flags-cloudflare-flagship` are in-tree. Each translates an -injected reader result and must pass the Phase 1 conformance suite. -None import a vendor SDK or evaluate targeting rules. The AWS adapter -maps an already-evaluated value or an unconditional feature-flag -setting and rejects an enabled document that still carries -multi-variant rules. The Flagship adapter translates an already-evaluated -`*Details` result. flagd remains later as its own package. +`@pegma/flags-launchdarkly`, `@pegma/flags-aws-appconfig`, +`@pegma/flags-cloudflare-flagship`, and `@pegma/flags-flagd` are +in-tree. Each translates an injected reader result and must pass the +Phase 1 conformance suite. None import a vendor SDK or evaluate +targeting rules. The AWS adapter maps an already-evaluated value or an +unconditional feature-flag setting and rejects an enabled document that +still carries multi-variant rules. The Flagship adapter translates an +already-evaluated `*Details` result. The flagd adapter translates an +already-evaluated OpenFeature detail. Phase 3 vendor adapters are +complete. ### Phase 4 — publish diff --git a/docs/RELEASING.md b/docs/RELEASING.md index db47097..09f3a35 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -2,7 +2,8 @@ `@pegma/flags-contracts`, `@pegma/flags-core`, `@pegma/flags-static`, `@pegma/flags-azure-appconfig`, `@pegma/flags-aws-appconfig`, -`@pegma/flags-cloudflare-flagship`, and `@pegma/flags-launchdarkly` +`@pegma/flags-cloudflare-flagship`, `@pegma/flags-flagd`, and +`@pegma/flags-launchdarkly` publish only from a stable GitHub release. Merging a pull request never publishes, and the workflow has no manual-dispatch or npm-token @@ -16,7 +17,7 @@ Before the first release through this workflow: - configure `@pegma/flags-contracts`, `@pegma/flags-core`, `@pegma/flags-static`, `@pegma/flags-azure-appconfig`, `@pegma/flags-aws-appconfig`, `@pegma/flags-cloudflare-flagship`, - and `@pegma/flags-launchdarkly` on npm with + `@pegma/flags-flagd`, and `@pegma/flags-launchdarkly` on npm with the GitHub Actions trusted publisher `pegma-dev/flags-core`, workflow `publish.yml`, environment `npm-publish`, and allowed action `npm publish`; diff --git a/packages/flags-flagd/LICENSE b/packages/flags-flagd/LICENSE new file mode 100644 index 0000000..897032a --- /dev/null +++ b/packages/flags-flagd/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 RetireGolden, LLC + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/flags-flagd/README.md b/packages/flags-flagd/README.md new file mode 100644 index 0000000..07912cb --- /dev/null +++ b/packages/flags-flagd/README.md @@ -0,0 +1,82 @@ +# `@pegma/flags-flagd` + +flagd / OpenFeature `FlagProvider` for Pegma hosts. + +> [!IMPORTANT] +> Pegma is in early `0.x` development. This package's public API is unstable. + +The host constructs and injects a flagd / OpenFeature reader. This package +never imports the OpenFeature SDK or a flagd provider, never owns a client +singleton, and does not evaluate targeting rules or percentage rollouts. It +translates an already-evaluated OpenFeature detail into a `FlagResolution`. + +```ts +import { + createFlagdFlagProvider, + flagdEvaluationContext, +} from "@pegma/flags-flagd"; +import { createFlagsClient, declareFlags, flag } from "@pegma/flags-core"; +import type { Logger } from "@pegma/spine"; + +const schema = declareFlags({ + checkoutEnabled: flag.boolean({ defaultValue: false }), +}); + +const logger: Logger = { + log(level, message, fields) { + console.log(level, message, fields); + }, +}; + +const provider = createFlagdFlagProvider({ + reader: { + async getDetails({ flagKey, context, defaultValue, kind }) { + const evaluationContext = flagdEvaluationContext(context); + switch (kind) { + case "boolean": + return client.getBooleanDetails( + flagKey, + defaultValue, + evaluationContext, + ); + case "string": + return client.getStringDetails( + flagKey, + defaultValue, + evaluationContext, + ); + case "number": + return client.getNumberDetails( + flagKey, + defaultValue, + evaluationContext, + ); + case "json": + return client.getObjectDetails( + flagKey, + defaultValue, + evaluationContext, + ); + } + }, + close() { + return client.close?.(); + }, + }, +}); + +const flags = createFlagsClient({ schema, logger, provider }); +``` + +`client` is the host's OpenFeature client configured with a flagd +provider. Import `flagdEvaluationContext` when the host wants the +documented OpenFeature context (`targetingKey` plus attributes). Hosts +that need a different context shape can map `EvaluationContext` +themselves inside the reader. + +A missing flag (`undefined` from the reader, or OpenFeature +`FLAG_NOT_FOUND`) is `DEFAULT_FALLBACK`. `DISABLED` is `DISABLED`. +`TARGETING_MATCH`, `SPLIT`, `DEFAULT`, `STATIC`, `CACHED`, and `STALE` +are `TARGETING_MATCH` — flagd already evaluated those rules. Other +OpenFeature `ERROR` codes propagate so the flags client can record +`ERROR`. diff --git a/packages/flags-flagd/package.json b/packages/flags-flagd/package.json new file mode 100644 index 0000000..e3d150b --- /dev/null +++ b/packages/flags-flagd/package.json @@ -0,0 +1,39 @@ +{ + "name": "@pegma/flags-flagd", + "version": "0.1.0", + "description": "flagd / OpenFeature FlagProvider for Pegma hosts.", + "license": "MIT", + "type": "module", + "sideEffects": false, + "publishConfig": { + "access": "public" + }, + "files": [ + "dist/**/*.d.ts", + "dist/**/*.d.ts.map", + "dist/**/*.js", + "dist/**/*.js.map" + ], + "exports": { + ".": { + "types": "./dist/index.d.ts", + "import": "./dist/index.js" + } + }, + "engines": { + "node": ">=22" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/pegma-dev/flags-core.git", + "directory": "packages/flags-flagd" + }, + "dependencies": { + "@pegma/flags-contracts": "0.1.0" + }, + "scripts": { + "build": "tsc -p tsconfig.json", + "check": "tsc -p tsconfig.json --noEmit", + "prepack": "pnpm run build" + } +} diff --git a/packages/flags-flagd/src/index.test.ts b/packages/flags-flagd/src/index.test.ts new file mode 100644 index 0000000..4cbafed --- /dev/null +++ b/packages/flags-flagd/src/index.test.ts @@ -0,0 +1,461 @@ +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import { describe, expect, it, vi } from "vitest"; + +import type { + EvaluationContext, + FlagResolutionRequest, +} from "@pegma/flags-contracts"; + +import { + FLAGD_ERROR_FLAG_NOT_FOUND, + FLAGD_REASON_CACHED, + FLAGD_REASON_DEFAULT, + FLAGD_REASON_DISABLED, + FLAGD_REASON_ERROR, + FLAGD_REASON_SPLIT, + FLAGD_REASON_STALE, + FLAGD_REASON_STATIC, + FLAGD_REASON_TARGETING_MATCH, + createFlagdFlagProvider, + flagdEvaluationContext, + type FlagdDetailsRequest, + type FlagdEvaluationDetails, + type FlagdReader, +} from "./index.js"; + +const context: EvaluationContext = { targetingKey: "user-1" }; + +function request( + extras: Partial & + Pick, +): FlagResolutionRequest { + return { + context, + ...extras, + }; +} + +function detail( + value: unknown, + reason: string, + extras: { + readonly errorCode?: string; + readonly variant?: string; + } = {}, +): FlagdEvaluationDetails { + return { + value, + reason, + ...(extras.errorCode === undefined ? {} : { errorCode: extras.errorCode }), + ...(extras.variant === undefined ? {} : { variant: extras.variant }), + }; +} + +function memoryReader( + details: Readonly>, + extras: { + readonly delayMs?: number; + readonly error?: unknown; + readonly onGet?: (request: FlagdDetailsRequest) => void; + readonly detailsForContext?: ( + context: EvaluationContext, + ) => Readonly>; + } = {}, +): FlagdReader { + return { + async getDetails(getRequest) { + extras.onGet?.(getRequest); + if (extras.delayMs !== undefined && extras.delayMs > 0) { + await new Promise((resolve) => { + setTimeout(resolve, extras.delayMs); + }); + } + if (extras.error !== undefined) { + throw extras.error; + } + const table = extras.detailsForContext?.(getRequest.context) ?? details; + return Object.hasOwn(table, getRequest.flagKey) + ? table[getRequest.flagKey] + : undefined; + }, + }; +} + +describe("flagdEvaluationContext", () => { + it("maps targeting key and JSON-compatible attributes", () => { + expect( + flagdEvaluationContext({ + targetingKey: "user-1", + tenant: "acme", + environment: "prod", + principalId: "principal-1" as NonNullable< + EvaluationContext["principalId"] + >, + attributes: { + plan: "pro", + seats: 3, + beta: true, + targetingKey: "should-not-win", + tags: ["beta", "internal"], + nested: { region: "us" }, + }, + }), + ).toEqual({ + targetingKey: "user-1", + tenant: "acme", + environment: "prod", + principalId: "principal-1", + plan: "pro", + seats: 3, + beta: true, + tags: ["beta", "internal"], + nested: { region: "us" }, + }); + }); +}); + +describe("createFlagdFlagProvider", () => { + it("requires an injected reader", () => { + expect(() => + createFlagdFlagProvider({} as { reader: FlagdReader }), + ).toThrow("injected flagd reader"); + }); + + it("returns DEFAULT_FALLBACK for a missing key", async () => { + const provider = createFlagdFlagProvider({ + reader: memoryReader({}), + }); + await expect( + provider.resolve( + request({ + flagKey: "theme", + kind: "string", + defaultValue: "light", + }), + ), + ).resolves.toEqual({ + value: "light", + reason: "DEFAULT_FALLBACK", + }); + }); + + it("returns DEFAULT_FALLBACK for OpenFeature FLAG_NOT_FOUND", async () => { + const provider = createFlagdFlagProvider({ + reader: memoryReader({ + theme: detail("light", FLAGD_REASON_ERROR, { + errorCode: FLAGD_ERROR_FLAG_NOT_FOUND, + }), + }), + }); + await expect( + provider.resolve( + request({ flagKey: "theme", kind: "string", defaultValue: "light" }), + ), + ).resolves.toEqual({ + value: "light", + reason: "DEFAULT_FALLBACK", + }); + }); + + it("translates TARGETING_MATCH, SPLIT, DEFAULT, STATIC, CACHED, and STALE as targeting matches", async () => { + const provider = createFlagdFlagProvider({ + reader: memoryReader({ + checkoutEnabled: detail(true, FLAGD_REASON_TARGETING_MATCH, { + variant: "on", + }), + theme: detail("dark", FLAGD_REASON_SPLIT, { + variant: "dark", + }), + maxItems: detail(25, FLAGD_REASON_DEFAULT), + payload: detail({ experiment: "on" }, FLAGD_REASON_STATIC), + cached: detail("warm", FLAGD_REASON_CACHED), + stale: detail("old", FLAGD_REASON_STALE), + }), + }); + await expect( + provider.resolve( + request({ + flagKey: "checkoutEnabled", + kind: "boolean", + defaultValue: false, + }), + ), + ).resolves.toEqual({ + value: true, + reason: "TARGETING_MATCH", + variant: "on", + }); + await expect( + provider.resolve( + request({ flagKey: "theme", kind: "string", defaultValue: "light" }), + ), + ).resolves.toEqual({ + value: "dark", + reason: "TARGETING_MATCH", + variant: "dark", + }); + await expect( + provider.resolve( + request({ flagKey: "maxItems", kind: "number", defaultValue: 10 }), + ), + ).resolves.toEqual({ value: 25, reason: "TARGETING_MATCH" }); + await expect( + provider.resolve( + request({ + flagKey: "payload", + kind: "json", + defaultValue: { experiment: "off" }, + }), + ), + ).resolves.toEqual({ + value: { experiment: "on" }, + reason: "TARGETING_MATCH", + }); + await expect( + provider.resolve( + request({ flagKey: "cached", kind: "string", defaultValue: "cold" }), + ), + ).resolves.toEqual({ value: "warm", reason: "TARGETING_MATCH" }); + await expect( + provider.resolve( + request({ flagKey: "stale", kind: "string", defaultValue: "fresh" }), + ), + ).resolves.toEqual({ value: "old", reason: "TARGETING_MATCH" }); + }); + + it("omits variant when flagd returns an empty variant", async () => { + const provider = createFlagdFlagProvider({ + reader: memoryReader({ + theme: detail("dark", FLAGD_REASON_TARGETING_MATCH, { + variant: "", + }), + }), + }); + await expect( + provider.resolve( + request({ flagKey: "theme", kind: "string", defaultValue: "light" }), + ), + ).resolves.toEqual({ + value: "dark", + reason: "TARGETING_MATCH", + }); + }); + + it("translates DISABLED as DISABLED", async () => { + const provider = createFlagdFlagProvider({ + reader: memoryReader({ + checkoutEnabled: detail(false, FLAGD_REASON_DISABLED, { + variant: "off", + }), + }), + }); + await expect( + provider.resolve( + request({ + flagKey: "checkoutEnabled", + kind: "boolean", + defaultValue: true, + }), + ), + ).resolves.toEqual({ + value: false, + reason: "DISABLED", + variant: "off", + }); + }); + + it("does not treat an unknown reason as a targeting match", async () => { + const provider = createFlagdFlagProvider({ + reader: memoryReader({ + checkoutEnabled: detail(true, "PERCENTILE_ROLLOUT"), + }), + }); + await expect( + provider.resolve( + request({ + flagKey: "checkoutEnabled", + kind: "boolean", + defaultValue: false, + }), + ), + ).rejects.toThrow("is not translated"); + }); + + it("does not treat UNKNOWN as a targeting match", async () => { + const provider = createFlagdFlagProvider({ + reader: memoryReader({ + checkoutEnabled: detail(true, "UNKNOWN"), + }), + }); + await expect( + provider.resolve( + request({ + flagKey: "checkoutEnabled", + kind: "boolean", + defaultValue: false, + }), + ), + ).rejects.toThrow("is not translated"); + }); + + it("propagates flagd evaluation errors without an errorCode", async () => { + const provider = createFlagdFlagProvider({ + reader: memoryReader({ + checkoutEnabled: detail(false, FLAGD_REASON_ERROR), + }), + }); + await expect( + provider.resolve( + request({ + flagKey: "checkoutEnabled", + kind: "boolean", + defaultValue: false, + }), + ), + ).rejects.toThrow("flagd evaluation failed for checkoutEnabled"); + }); + + it("propagates OpenFeature evaluation errors other than FLAG_NOT_FOUND", async () => { + const provider = createFlagdFlagProvider({ + reader: memoryReader({ + checkoutEnabled: detail(false, FLAGD_REASON_ERROR, { + errorCode: "TYPE_MISMATCH", + }), + }), + }); + await expect( + provider.resolve( + request({ + flagKey: "checkoutEnabled", + kind: "boolean", + defaultValue: false, + }), + ), + ).rejects.toThrow("TYPE_MISMATCH"); + }); + + it("does not treat an errorCode on a match as a targeting match", async () => { + const provider = createFlagdFlagProvider({ + reader: memoryReader({ + checkoutEnabled: detail(true, FLAGD_REASON_TARGETING_MATCH, { + errorCode: "GENERAL", + }), + }), + }); + await expect( + provider.resolve( + request({ + flagKey: "checkoutEnabled", + kind: "boolean", + defaultValue: false, + }), + ), + ).rejects.toThrow("GENERAL"); + }); + + it("forwards the targeting key and kind to the reader", async () => { + const seen: FlagdDetailsRequest[] = []; + const provider = createFlagdFlagProvider({ + reader: memoryReader( + { + theme: detail("dark", FLAGD_REASON_TARGETING_MATCH), + }, + { + onGet(getRequest) { + seen.push(getRequest); + }, + }, + ), + }); + await provider.resolve( + request({ + flagKey: "theme", + kind: "string", + defaultValue: "light", + context: { targetingKey: "user-1" }, + }), + ); + expect(seen[0]?.context.targetingKey).toBe("user-1"); + expect(seen[0]?.defaultValue).toBe("light"); + expect(seen[0]?.kind).toBe("string"); + }); + + it("applies host keyOf without inventing a layout", async () => { + const seen: FlagdDetailsRequest[] = []; + const provider = createFlagdFlagProvider({ + keyOf: (flagKey) => `app.${flagKey}`, + reader: memoryReader( + { + "app.checkoutEnabled": detail(true, FLAGD_REASON_TARGETING_MATCH), + }, + { + onGet(getRequest) { + seen.push(getRequest); + }, + }, + ), + }); + const resolution = await provider.resolve( + request({ + flagKey: "checkoutEnabled", + kind: "boolean", + defaultValue: false, + }), + ); + expect(resolution.reason).toBe("TARGETING_MATCH"); + expect(seen[0]?.flagKey).toBe("app.checkoutEnabled"); + }); + + it("throws when a detail is missing a reason", async () => { + const provider = createFlagdFlagProvider({ + reader: memoryReader({ + checkoutEnabled: { + value: true, + reason: "", + }, + }), + }); + await expect( + provider.resolve( + request({ + flagKey: "checkoutEnabled", + kind: "boolean", + defaultValue: false, + }), + ), + ).rejects.toThrow("reason"); + }); + + it("propagates reader failures", async () => { + const provider = createFlagdFlagProvider({ + reader: memoryReader({}, { error: new Error("flagd unavailable") }), + }); + await expect( + provider.resolve( + request({ + flagKey: "checkoutEnabled", + kind: "boolean", + defaultValue: false, + }), + ), + ).rejects.toThrow("flagd unavailable"); + }); + + it("closes the injected reader", async () => { + const close = vi.fn(); + const provider = createFlagdFlagProvider({ + reader: { ...memoryReader({}), close }, + }); + await provider.close?.(); + expect(close).toHaveBeenCalledOnce(); + }); + + it("does not import an OpenFeature or flagd SDK or call Date.now on the production path", () => { + const source = readFileSync(join(import.meta.dirname, "index.ts"), "utf8"); + expect(source).not.toMatch(/@openfeature\//u); + expect(source).not.toMatch(/@flagd\//u); + expect(source).not.toMatch(/flagd-provider/u); + expect(source).not.toMatch(/Date\.now\(/u); + }); +}); diff --git a/packages/flags-flagd/src/index.ts b/packages/flags-flagd/src/index.ts new file mode 100644 index 0000000..5081121 --- /dev/null +++ b/packages/flags-flagd/src/index.ts @@ -0,0 +1,229 @@ +import type { + EvaluationContext, + FlagProvider, + FlagProviderCapabilities, + FlagResolution, + FlagResolutionRequest, + FlagValueKind, + JsonValue, +} from "@pegma/flags-contracts"; + +/** + * OpenFeature evaluation reasons this adapter translates. + * + * @see https://openfeature.dev/specification/types#evaluation-reason + */ +export const FLAGD_REASON_TARGETING_MATCH = "TARGETING_MATCH"; +export const FLAGD_REASON_SPLIT = "SPLIT"; +export const FLAGD_REASON_DEFAULT = "DEFAULT"; +export const FLAGD_REASON_STATIC = "STATIC"; +export const FLAGD_REASON_CACHED = "CACHED"; +export const FLAGD_REASON_STALE = "STALE"; +export const FLAGD_REASON_DISABLED = "DISABLED"; +export const FLAGD_REASON_ERROR = "ERROR"; + +/** OpenFeature `errorCode` for a flag the provider does not define. */ +export const FLAGD_ERROR_FLAG_NOT_FOUND = "FLAG_NOT_FOUND"; + +/** JSON-compatible OpenFeature targeting attributes. */ +export type FlagdAttributeValue = JsonValue; + +/** + * Flat OpenFeature evaluation context. `targetingKey` is the primary + * identifier. Additional attributes keep their JSON-compatible values. + * + * @see https://openfeature.dev/specification/types#evaluation-context + */ +export interface FlagdEvaluationContext { + readonly targetingKey: string; + readonly [attribute: string]: FlagdAttributeValue | undefined; +} + +/** + * Narrow detail the injected reader returns. Matches OpenFeature + * evaluation details from a flagd-backed client. + */ +export interface FlagdEvaluationDetails { + readonly value: unknown; + readonly variant?: string; + readonly reason?: string; + readonly errorCode?: string; + readonly flagKey?: string; +} + +export interface FlagdDetailsRequest { + readonly flagKey: string; + readonly context: EvaluationContext; + readonly defaultValue: unknown; + readonly kind: FlagValueKind; +} + +/** + * Host-injected flagd / OpenFeature lookup. Typically a thin wrapper + * around `client.get*Details` that maps a missing flag to `undefined` + * or returns OpenFeature's `FLAG_NOT_FOUND` detail. This package never + * imports the OpenFeature SDK or a flagd provider. + */ +export interface FlagdReader { + getDetails( + request: FlagdDetailsRequest, + ): Promise; + close?(): void | Promise; +} + +export interface FlagdFlagProviderOptions { + readonly reader: FlagdReader; + readonly name?: string; + readonly keyOf?: (flagKey: string) => string; +} + +function own(record: object, key: string): unknown { + return Object.hasOwn(record, key) + ? (record as Record)[key] + : undefined; +} + +/** + * Builds the documented OpenFeature evaluation context for `context`. + * `targetingKey` is the primary identifier. Optional tenant, environment, + * principal, and host attributes are copied as attributes. Hosts that + * need a different context shape should map it themselves in the + * injected reader. + */ +export function flagdEvaluationContext( + context: EvaluationContext, +): FlagdEvaluationContext { + const attributes: Record = { + ...(context.attributes ?? {}), + }; + if (typeof context.principalId === "string") { + attributes.principalId = context.principalId; + } + if (context.tenant !== undefined) { + attributes.tenant = context.tenant; + } + if (context.environment !== undefined) { + attributes.environment = context.environment; + } + return { + ...attributes, + targetingKey: context.targetingKey, + }; +} + +function variantOf( + detail: FlagdEvaluationDetails, +): { readonly variant: string } | Record { + if (typeof detail.variant !== "string" || detail.variant === "") { + return {}; + } + return { variant: detail.variant }; +} + +function requireReasonKind(detail: FlagdEvaluationDetails): string { + const reason = own(detail, "reason"); + if (typeof reason !== "string" || reason === "") { + throw new Error("flagd evaluation detail is missing a reason"); + } + return reason; +} + +function requireErrorCode(detail: FlagdEvaluationDetails): string | undefined { + const errorCode = own(detail, "errorCode"); + if (errorCode === undefined) { + return undefined; + } + if (typeof errorCode !== "string") { + throw new Error("flagd evaluation detail has a non-string errorCode"); + } + return errorCode === "" ? undefined : errorCode; +} + +function resolveDetail( + request: FlagResolutionRequest, + detail: FlagdEvaluationDetails, +): FlagResolution { + const reason = requireReasonKind(detail); + const errorCode = requireErrorCode(detail); + if (errorCode === FLAGD_ERROR_FLAG_NOT_FOUND) { + return { value: request.defaultValue, reason: "DEFAULT_FALLBACK" }; + } + if (reason === FLAGD_REASON_ERROR || errorCode !== undefined) { + throw new Error( + errorCode === undefined + ? `flagd evaluation failed for ${request.flagKey}` + : `flagd evaluation failed for ${request.flagKey}: ${errorCode}`, + ); + } + switch (reason) { + case FLAGD_REASON_TARGETING_MATCH: + case FLAGD_REASON_SPLIT: + case FLAGD_REASON_DEFAULT: + case FLAGD_REASON_STATIC: + case FLAGD_REASON_CACHED: + case FLAGD_REASON_STALE: + return { + value: detail.value, + reason: "TARGETING_MATCH", + ...variantOf(detail), + }; + case FLAGD_REASON_DISABLED: + return { + value: detail.value, + reason: "DISABLED", + ...variantOf(detail), + }; + default: + throw new Error( + `flagd evaluation reason ${reason} is not translated by this adapter`, + ); + } +} + +/** + * Translates OpenFeature evaluation details into {@link FlagProvider} + * resolutions. Targeting rules and percentage rollouts are not evaluated + * here — flagd already did that. The injected reader must return an + * already-evaluated detail. + */ +export function createFlagdFlagProvider( + options: FlagdFlagProviderOptions, +): FlagProvider { + if ( + options.reader === undefined || + typeof options.reader.getDetails !== "function" + ) { + throw new Error( + "createFlagdFlagProvider requires an injected flagd reader", + ); + } + const name = options.name ?? "flagd"; + const capabilities: FlagProviderCapabilities = { + static: false, + streaming: false, + targeting: true, + }; + + return { + name, + capabilities() { + return capabilities; + }, + async resolve(request) { + const flagKey = options.keyOf?.(request.flagKey) ?? request.flagKey; + const detail = await options.reader.getDetails({ + flagKey, + context: request.context, + defaultValue: request.defaultValue, + kind: request.kind, + }); + if (detail === undefined) { + return { value: request.defaultValue, reason: "DEFAULT_FALLBACK" }; + } + return resolveDetail(request, detail); + }, + async close() { + await options.reader.close?.(); + }, + }; +} diff --git a/packages/flags-flagd/tsconfig.json b/packages/flags-flagd/tsconfig.json new file mode 100644 index 0000000..bc330dd --- /dev/null +++ b/packages/flags-flagd/tsconfig.json @@ -0,0 +1,12 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "outDir": "dist", + "rootDir": "src", + "tsBuildInfoFile": "tsconfig.tsbuildinfo", + "types": ["node"] + }, + "include": ["src/**/*.ts"], + "exclude": ["src/**/*.test.ts"], + "references": [{ "path": "../flags-contracts" }] +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index fd5cf73..5174a57 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -54,6 +54,12 @@ importers: specifier: 0.1.2 version: 0.1.2 + packages/flags-flagd: + dependencies: + '@pegma/flags-contracts': + specifier: 0.1.0 + version: link:../flags-contracts + packages/flags-launchdarkly: dependencies: '@pegma/flags-contracts': diff --git a/scripts/release-packages.mjs b/scripts/release-packages.mjs index d549739..04e7aa1 100644 --- a/scripts/release-packages.mjs +++ b/scripts/release-packages.mjs @@ -51,6 +51,10 @@ export const RELEASE_PACKAGES = [ directory: "flags-cloudflare-flagship", name: "@pegma/flags-cloudflare-flagship", }, + { + directory: "flags-flagd", + name: "@pegma/flags-flagd", + }, { directory: "flags-launchdarkly", name: "@pegma/flags-launchdarkly", diff --git a/tests/flagd-conformance.test.ts b/tests/flagd-conformance.test.ts new file mode 100644 index 0000000..6e19bb9 --- /dev/null +++ b/tests/flagd-conformance.test.ts @@ -0,0 +1,110 @@ +import { describe, it } from "vitest"; + +import type { EvaluationContext } from "../packages/flags-contracts/src/index.js"; +import { flagConformanceCases } from "../packages/flags-core/src/conformance.js"; +import { + FLAGD_REASON_DISABLED, + FLAGD_REASON_TARGETING_MATCH, + createFlagdFlagProvider, + type FlagdEvaluationDetails, + type FlagdReader, +} from "../packages/flags-flagd/src/index.js"; + +function wait(delayMs: number): Promise { + return new Promise((resolve) => { + setTimeout(resolve, delayMs); + }); +} + +function detailFor(value: unknown): FlagdEvaluationDetails { + return { + value, + reason: FLAGD_REASON_TARGETING_MATCH, + }; +} + +function detailsFromFlags( + flags: Readonly>, +): Record { + return Object.fromEntries( + Object.entries(flags).map(([flagKey, value]) => [ + flagKey, + detailFor(value), + ]), + ); +} + +function memoryReader(options: { + readonly details?: Readonly>; + readonly detailsForContext?: ( + context: EvaluationContext, + ) => Readonly>; + readonly delayMs?: number; + readonly error?: unknown; +}): FlagdReader { + return { + async getDetails(request) { + if (options.delayMs !== undefined && options.delayMs > 0) { + await wait(options.delayMs); + } + if (options.error !== undefined) { + throw options.error; + } + const details = + options.detailsForContext?.(request.context) ?? options.details ?? {}; + return Object.hasOwn(details, request.flagKey) + ? details[request.flagKey] + : undefined; + }, + }; +} + +const cases = flagConformanceCases((scenario) => { + switch (scenario.type) { + case "values": + return createFlagdFlagProvider({ + reader: memoryReader({ details: detailsFromFlags(scenario.flags) }), + }); + case "empty": + return createFlagdFlagProvider({ + reader: memoryReader({ details: {} }), + }); + case "targeted": + return createFlagdFlagProvider({ + reader: memoryReader({ + detailsForContext(context) { + return context.targetingKey === scenario.targetingKey + ? detailsFromFlags(scenario.flags) + : {}; + }, + }), + }); + case "timeout": + return createFlagdFlagProvider({ + reader: memoryReader({ delayMs: scenario.delayMs }), + }); + case "error": + return createFlagdFlagProvider({ + reader: memoryReader({ error: scenario.error }), + }); + case "disabled": + return createFlagdFlagProvider({ + reader: memoryReader({ + details: { + [scenario.flagKey]: { + value: scenario.value, + reason: FLAGD_REASON_DISABLED, + }, + }, + }), + }); + } +}); + +describe("flagd provider conformance", () => { + for (const testCase of cases) { + it(testCase.name, async () => { + await testCase.run(); + }); + } +}); diff --git a/tests/release-packages.test.ts b/tests/release-packages.test.ts index 0b57692..3b25c6e 100644 --- a/tests/release-packages.test.ts +++ b/tests/release-packages.test.ts @@ -48,6 +48,7 @@ describe("release package metadata", () => { "@pegma/flags-azure-appconfig", "@pegma/flags-aws-appconfig", "@pegma/flags-cloudflare-flagship", + "@pegma/flags-flagd", "@pegma/flags-launchdarkly", ]); }); diff --git a/tsconfig.json b/tsconfig.json index c7dd4b0..20cd70a 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -7,6 +7,7 @@ { "path": "./packages/flags-azure-appconfig" }, { "path": "./packages/flags-aws-appconfig" }, { "path": "./packages/flags-cloudflare-flagship" }, + { "path": "./packages/flags-flagd" }, { "path": "./packages/flags-launchdarkly" } ] } From 974f181aaebed0593a279e2c43f9da404ecf390a Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sat, 15 Aug 2026 21:54:14 +0000 Subject: [PATCH 2/2] Map flagd STALE to STALE_CACHE OpenFeature STALE is a stale provider result, not a fresh targeting match. Return STALE_CACHE so the client emits fallback telemetry. Co-authored-by: Fly Over Coder --- packages/flags-flagd/README.md | 9 +++--- packages/flags-flagd/src/index.test.ts | 19 +++++++++--- packages/flags-flagd/src/index.ts | 7 ++++- tests/flagd-conformance.test.ts | 43 +++++++++++++++++++++++++- 4 files changed, 68 insertions(+), 10 deletions(-) diff --git a/packages/flags-flagd/README.md b/packages/flags-flagd/README.md index 07912cb..9269f59 100644 --- a/packages/flags-flagd/README.md +++ b/packages/flags-flagd/README.md @@ -76,7 +76,8 @@ themselves inside the reader. A missing flag (`undefined` from the reader, or OpenFeature `FLAG_NOT_FOUND`) is `DEFAULT_FALLBACK`. `DISABLED` is `DISABLED`. -`TARGETING_MATCH`, `SPLIT`, `DEFAULT`, `STATIC`, `CACHED`, and `STALE` -are `TARGETING_MATCH` — flagd already evaluated those rules. Other -OpenFeature `ERROR` codes propagate so the flags client can record -`ERROR`. +`STALE` is `STALE_CACHE` so the flags client records the stale reason +and emits fallback telemetry. `TARGETING_MATCH`, `SPLIT`, `DEFAULT`, +`STATIC`, and `CACHED` are `TARGETING_MATCH` — flagd already evaluated +those rules. Other OpenFeature `ERROR` codes propagate so the flags +client can record `ERROR`. diff --git a/packages/flags-flagd/src/index.test.ts b/packages/flags-flagd/src/index.test.ts index 4cbafed..7cc46cd 100644 --- a/packages/flags-flagd/src/index.test.ts +++ b/packages/flags-flagd/src/index.test.ts @@ -158,7 +158,7 @@ describe("createFlagdFlagProvider", () => { }); }); - it("translates TARGETING_MATCH, SPLIT, DEFAULT, STATIC, CACHED, and STALE as targeting matches", async () => { + it("translates TARGETING_MATCH, SPLIT, DEFAULT, STATIC, and CACHED as targeting matches", async () => { const provider = createFlagdFlagProvider({ reader: memoryReader({ checkoutEnabled: detail(true, FLAGD_REASON_TARGETING_MATCH, { @@ -170,7 +170,6 @@ describe("createFlagdFlagProvider", () => { maxItems: detail(25, FLAGD_REASON_DEFAULT), payload: detail({ experiment: "on" }, FLAGD_REASON_STATIC), cached: detail("warm", FLAGD_REASON_CACHED), - stale: detail("old", FLAGD_REASON_STALE), }), }); await expect( @@ -217,11 +216,23 @@ describe("createFlagdFlagProvider", () => { request({ flagKey: "cached", kind: "string", defaultValue: "cold" }), ), ).resolves.toEqual({ value: "warm", reason: "TARGETING_MATCH" }); + }); + + it("translates STALE as STALE_CACHE", async () => { + const provider = createFlagdFlagProvider({ + reader: memoryReader({ + theme: detail("old", FLAGD_REASON_STALE, { variant: "cached" }), + }), + }); await expect( provider.resolve( - request({ flagKey: "stale", kind: "string", defaultValue: "fresh" }), + request({ flagKey: "theme", kind: "string", defaultValue: "fresh" }), ), - ).resolves.toEqual({ value: "old", reason: "TARGETING_MATCH" }); + ).resolves.toEqual({ + value: "old", + reason: "STALE_CACHE", + variant: "cached", + }); }); it("omits variant when flagd returns an empty variant", async () => { diff --git a/packages/flags-flagd/src/index.ts b/packages/flags-flagd/src/index.ts index 5081121..3518743 100644 --- a/packages/flags-flagd/src/index.ts +++ b/packages/flags-flagd/src/index.ts @@ -161,12 +161,17 @@ function resolveDetail( case FLAGD_REASON_DEFAULT: case FLAGD_REASON_STATIC: case FLAGD_REASON_CACHED: - case FLAGD_REASON_STALE: return { value: detail.value, reason: "TARGETING_MATCH", ...variantOf(detail), }; + case FLAGD_REASON_STALE: + return { + value: detail.value, + reason: "STALE_CACHE", + ...variantOf(detail), + }; case FLAGD_REASON_DISABLED: return { value: detail.value, diff --git a/tests/flagd-conformance.test.ts b/tests/flagd-conformance.test.ts index 6e19bb9..68c8f58 100644 --- a/tests/flagd-conformance.test.ts +++ b/tests/flagd-conformance.test.ts @@ -1,9 +1,12 @@ -import { describe, it } from "vitest"; +import { describe, expect, it } from "vitest"; import type { EvaluationContext } from "../packages/flags-contracts/src/index.js"; +import { createFlagsClient } from "../packages/flags-core/src/client.js"; import { flagConformanceCases } from "../packages/flags-core/src/conformance.js"; +import { declareFlags, flag } from "../packages/flags-core/src/schema.js"; import { FLAGD_REASON_DISABLED, + FLAGD_REASON_STALE, FLAGD_REASON_TARGETING_MATCH, createFlagdFlagProvider, type FlagdEvaluationDetails, @@ -107,4 +110,42 @@ describe("flagd provider conformance", () => { await testCase.run(); }); } + + it("maps STALE through the client as STALE_CACHE with fallback telemetry", async () => { + const events: Array<{ + readonly level: string; + readonly message: string; + readonly fields?: Readonly>; + }> = []; + const client = createFlagsClient({ + schema: declareFlags({ + theme: flag.string({ defaultValue: "light" }), + }), + logger: { + log(level, message, fields) { + events.push({ + level, + message, + ...(fields === undefined ? {} : { fields }), + }); + }, + }, + provider: createFlagdFlagProvider({ + reader: memoryReader({ + details: { + theme: { value: "old", reason: FLAGD_REASON_STALE }, + }, + }), + }), + }); + const detail = await client.evaluate("theme", { targetingKey: "user-1" }); + expect(detail).toMatchObject({ + value: "old", + reason: "STALE_CACHE", + }); + expect(events.some((event) => event.message === "flags.fallback")).toBe( + true, + ); + expect(events[0]?.fields?.reason).toBe("STALE_CACHE"); + }); });