From 06a04c22360c6d9b647b501a7d5e12e3b9478314 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sat, 15 Aug 2026 21:12:24 +0000 Subject: [PATCH 1/5] Add AWS AppConfig flag provider Land @pegma/flags-aws-appconfig as a thin FlagProvider that translates a host-injected reader. Map already-evaluated values and unconditional feature-flag documents; reject enabled multi-variant rules so this package does not become a second targeting engine. Co-authored-by: Fly Over Coder --- AGENTS.md | 8 +- README.md | 5 +- docs/PROJECT_PLAN.md | 29 +- docs/RELEASING.md | 7 +- packages/flags-aws-appconfig/LICENSE | 21 + packages/flags-aws-appconfig/README.md | 63 +++ packages/flags-aws-appconfig/package.json | 39 ++ .../flags-aws-appconfig/src/index.test.ts | 494 ++++++++++++++++++ packages/flags-aws-appconfig/src/index.ts | 349 +++++++++++++ packages/flags-aws-appconfig/tsconfig.json | 12 + pnpm-lock.yaml | 6 + scripts/release-packages.mjs | 4 + tests/aws-appconfig-conformance.test.ts | 111 ++++ tests/release-packages.test.ts | 1 + tsconfig.json | 1 + 15 files changed, 1127 insertions(+), 23 deletions(-) create mode 100644 packages/flags-aws-appconfig/LICENSE create mode 100644 packages/flags-aws-appconfig/README.md create mode 100644 packages/flags-aws-appconfig/package.json create mode 100644 packages/flags-aws-appconfig/src/index.test.ts create mode 100644 packages/flags-aws-appconfig/src/index.ts create mode 100644 packages/flags-aws-appconfig/tsconfig.json create mode 100644 tests/aws-appconfig-conformance.test.ts diff --git a/AGENTS.md b/AGENTS.md index 3f1d23d..4b1ce02 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -77,10 +77,10 @@ scaffold. ## Where things stand -Phase 3 lands `@pegma/flags-launchdarkly` beside the Phase 1 packages -and `@pegma/flags-azure-appconfig` at `0.1.0` (unpublished). Remaining -vendor adapters (AWS AppConfig, Cloudflare Flagship, flagd) are still -later. +Phase 3 lands `@pegma/flags-launchdarkly` and +`@pegma/flags-aws-appconfig` beside the Phase 1 packages and +`@pegma/flags-azure-appconfig` at `0.1.0` (unpublished). Remaining +vendor adapters (Cloudflare Flagship, flagd) are still later. Siblings: [spine](https://github.com/pegma-dev/spine), [health](https://github.com/pegma-dev/health), diff --git a/README.md b/README.md index e8ff787..57c71b1 100644 --- a/README.md +++ b/README.md @@ -81,10 +81,11 @@ const detail = await client.evaluate("checkoutEnabled", { | `@pegma/flags-core` | Schema, client, cache, timeout, health helper | | `@pegma/flags-static` | In-memory provider for tests and local development | | `@pegma/flags-azure-appconfig` | Azure App Configuration provider | +| `@pegma/flags-aws-appconfig` | AWS AppConfig provider | | `@pegma/flags-launchdarkly` | LaunchDarkly provider | -Remaining vendor adapters (AWS AppConfig, Cloudflare Flagship, flagd) -are named in [the plan](docs/PROJECT_PLAN.md) and stay later. +Remaining vendor adapters (Cloudflare Flagship, flagd) are named in +[the plan](docs/PROJECT_PLAN.md) and stay later. ## Development diff --git a/docs/PROJECT_PLAN.md b/docs/PROJECT_PLAN.md index 5f9cdfb..69cee5a 100644 --- a/docs/PROJECT_PLAN.md +++ b/docs/PROJECT_PLAN.md @@ -2,12 +2,11 @@ ## Status -**Stage:** Phase 3 LaunchDarkly adapter implemented in-tree; unpublished. -Public API unstable (`0.x`). +**Stage:** Phase 3 LaunchDarkly and AWS AppConfig adapters implemented +in-tree; unpublished. Public API unstable (`0.x`). **First named consumers:** RetireGolden.org (Azure App Configuration). -Remaining vendor adapters (AWS AppConfig, Cloudflare Flagship, flagd) -are still later. +Remaining vendor adapters (Cloudflare Flagship, flagd) are still later. **License:** MIT @@ -105,8 +104,7 @@ 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. -- AWS AppConfig, Cloudflare Flagship, or flagd adapter packages in this - phase. +- Cloudflare Flagship or flagd adapter packages in this phase. - Metrics, experiment assignment, or percentage math in the core. ## Package architecture @@ -118,14 +116,15 @@ package here would invite the wrong extractions. | `@pegma/flags-static` | Zero-dep in-memory provider | 1 | | `@pegma/flags-launchdarkly` | LaunchDarkly adapter | 3 | | `@pegma/flags-azure-appconfig` | Azure App Configuration adapter | 2 | -| `@pegma/flags-aws-appconfig` | AWS AppConfig adapter | later | +| `@pegma/flags-aws-appconfig` | AWS AppConfig adapter | 3 | | `@pegma/flags-cloudflare-flagship` | Cloudflare Flagship adapter | later | | `@pegma/flags-flagd` | flagd / OpenFeature adapter | later | Dependencies: `@pegma/spine` pinned exactly. `@pegma/flags-static`, -`@pegma/flags-azure-appconfig`, 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-azure-appconfig`, `@pegma/flags-aws-appconfig`, and +`@pegma/flags-launchdarkly` depend only on `@pegma/flags-contracts` (no +vendor SDK). Adapters pin contracts (and spine, if they need `Logger` / +`Clock`) exactly. ## Delivery phases @@ -147,10 +146,12 @@ still carries those rules. Do not pre-build the other vendors. ### Phase 3 — remaining adapters -`@pegma/flags-launchdarkly` is in-tree. It translates an injected -LaunchDarkly `variationDetail` result and must pass the Phase 1 -conformance suite. It does not import the LaunchDarkly SDK or evaluate -targeting rules. AWS AppConfig, Cloudflare Flagship, and flagd remain +`@pegma/flags-launchdarkly` and `@pegma/flags-aws-appconfig` are +in-tree. Each translates an injected reader result and must pass the +Phase 1 conformance suite. Neither imports a vendor SDK nor evaluates +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. Cloudflare Flagship and flagd remain later, each as its own package. ### Phase 4 — publish diff --git a/docs/RELEASING.md b/docs/RELEASING.md index 60a45eb..b5f4580 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -1,7 +1,8 @@ # Release operations `@pegma/flags-contracts`, `@pegma/flags-core`, `@pegma/flags-static`, -`@pegma/flags-azure-appconfig`, and `@pegma/flags-launchdarkly` publish +`@pegma/flags-azure-appconfig`, `@pegma/flags-aws-appconfig`, 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 fallback. Phase 3 does not publish; this runbook exists so the first @@ -12,8 +13,8 @@ release does not invent a lane. Before the first release through this workflow: - configure `@pegma/flags-contracts`, `@pegma/flags-core`, - `@pegma/flags-static`, `@pegma/flags-azure-appconfig`, and - `@pegma/flags-launchdarkly` on npm with + `@pegma/flags-static`, `@pegma/flags-azure-appconfig`, + `@pegma/flags-aws-appconfig`, 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-aws-appconfig/LICENSE b/packages/flags-aws-appconfig/LICENSE new file mode 100644 index 0000000..897032a --- /dev/null +++ b/packages/flags-aws-appconfig/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-aws-appconfig/README.md b/packages/flags-aws-appconfig/README.md new file mode 100644 index 0000000..4ca59d6 --- /dev/null +++ b/packages/flags-aws-appconfig/README.md @@ -0,0 +1,63 @@ +# `@pegma/flags-aws-appconfig` + +AWS AppConfig `FlagProvider` for Pegma hosts. + +> [!IMPORTANT] +> Pegma is in early `0.x` development. This package's public API is unstable. + +The host constructs and injects an AppConfig reader. This package never +imports the AWS SDK, never owns a client singleton, and does not evaluate +multi-variant rules or percentage splits. It translates an already-evaluated +value — or a setting this package can map without becoming a second targeting +engine — into a `FlagResolution`. + +Prefer a reader that returns a value AppConfig already evaluated (the +AppConfig Agent `?flag=` response, or `GetLatestConfiguration` after the +host applied context). This package can also map: + +- ordinary typed values (string as-is; boolean, number, and json via JSON) +- an unconditional feature-flag object with a boolean `enabled` field +- a stored default variant that has no `rule` + +An enabled document that still carries `_variants` with a `rule` is +rejected. Wrap AppConfig evaluation in the injected reader if the host +needs those rules. + +```ts +import { + awsAppConfigFlagValue, + createAwsAppConfigFlagProvider, +} from "@pegma/flags-aws-appconfig"; +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 = createAwsAppConfigFlagProvider({ + reader: { + async getConfiguration({ key }) { + const document = await appConfig.getLatestConfiguration(); + const value = awsAppConfigFlagValue(document, key); + if (value === undefined) { + return undefined; + } + return { key, value }; + }, + }, +}); + +const client = createFlagsClient({ schema, logger, provider }); +``` + +Import `awsAppConfigFlagValue` when the host fetched a whole +`AWS.AppConfig.FeatureFlags` document or a retrieved flag map and needs +the stored object for one key. A missing key is `DEFAULT_FALLBACK`. A +feature flag with `enabled: false` is `DISABLED`. diff --git a/packages/flags-aws-appconfig/package.json b/packages/flags-aws-appconfig/package.json new file mode 100644 index 0000000..baf22be --- /dev/null +++ b/packages/flags-aws-appconfig/package.json @@ -0,0 +1,39 @@ +{ + "name": "@pegma/flags-aws-appconfig", + "version": "0.1.0", + "description": "AWS AppConfig 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-aws-appconfig" + }, + "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-aws-appconfig/src/index.test.ts b/packages/flags-aws-appconfig/src/index.test.ts new file mode 100644 index 0000000..0cf2c3c --- /dev/null +++ b/packages/flags-aws-appconfig/src/index.test.ts @@ -0,0 +1,494 @@ +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 { + AWS_APPCONFIG_FEATURE_FLAGS_TYPE, + awsAppConfigFlagValue, + createAwsAppConfigFlagProvider, + type AwsAppConfigConfiguration, + type AwsAppConfigGetRequest, + type AwsAppConfigReader, +} from "./index.js"; + +const context: EvaluationContext = { targetingKey: "user-1" }; + +function request( + extras: Partial & + Pick, +): FlagResolutionRequest { + return { + context, + ...extras, + }; +} + +function configuration( + key: string, + value: unknown, + extras: Omit = {}, +): AwsAppConfigConfiguration { + return { + key, + value, + ...extras, + }; +} + +function memoryReader( + configurations: readonly AwsAppConfigConfiguration[], + extras: { + readonly delayMs?: number; + readonly error?: unknown; + readonly onGet?: (request: AwsAppConfigGetRequest) => void; + } = {}, +): AwsAppConfigReader { + return { + async getConfiguration(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; + } + return configurations.find((entry) => entry.key === getRequest.key); + }, + }; +} + +describe("awsAppConfigFlagValue", () => { + it("reads a flag from an AWS.AppConfig.FeatureFlags document", () => { + expect(AWS_APPCONFIG_FEATURE_FLAGS_TYPE).toBe("AWS.AppConfig.FeatureFlags"); + expect( + awsAppConfigFlagValue( + { + version: "1", + flags: { checkoutEnabled: { name: "checkoutEnabled" } }, + values: { checkoutEnabled: { enabled: true } }, + }, + "checkoutEnabled", + ), + ).toEqual({ enabled: true }); + }); + + it("reads a flag from a retrieved flag map", () => { + expect( + awsAppConfigFlagValue( + { checkoutEnabled: { enabled: false } }, + "checkoutEnabled", + ), + ).toEqual({ enabled: false }); + }); + + it("returns undefined for a missing key", () => { + expect(awsAppConfigFlagValue({ version: "1", values: {} }, "theme")).toBe( + undefined, + ); + }); +}); + +describe("createAwsAppConfigFlagProvider", () => { + it("requires an injected reader", () => { + expect(() => + createAwsAppConfigFlagProvider({} as { reader: AwsAppConfigReader }), + ).toThrow("injected AWS AppConfig reader"); + }); + + it("returns DEFAULT_FALLBACK for a missing key", async () => { + const provider = createAwsAppConfigFlagProvider({ + reader: memoryReader([]), + }); + await expect( + provider.resolve( + request({ + flagKey: "theme", + kind: "string", + defaultValue: "light", + }), + ), + ).resolves.toEqual({ + value: "light", + reason: "DEFAULT_FALLBACK", + }); + }); + + it("looks up the flag key as an already-evaluated value by default", async () => { + const seen: AwsAppConfigGetRequest[] = []; + const provider = createAwsAppConfigFlagProvider({ + reader: memoryReader([configuration("theme", "dark")], { + onGet(getRequest) { + seen.push(getRequest); + }, + }), + }); + const resolution = await provider.resolve( + request({ flagKey: "theme", kind: "string", defaultValue: "light" }), + ); + expect(resolution).toEqual({ value: "dark", reason: "TARGETING_MATCH" }); + expect(seen[0]?.key).toBe("theme"); + }); + + it("parses boolean, number, and json ordinary values", async () => { + const provider = createAwsAppConfigFlagProvider({ + reader: memoryReader([ + configuration("checkoutEnabled", "true"), + configuration("maxItems", "25"), + configuration("payload", '{"experiment":"on"}'), + ]), + }); + await expect( + provider.resolve( + request({ + flagKey: "checkoutEnabled", + kind: "boolean", + defaultValue: false, + }), + ), + ).resolves.toEqual({ value: true, reason: "TARGETING_MATCH" }); + 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", + }); + }); + + it("does not JSON-parse ordinary string values", async () => { + const provider = createAwsAppConfigFlagProvider({ + reader: memoryReader([configuration("theme", "dark")]), + }); + await expect( + provider.resolve( + request({ flagKey: "theme", kind: "string", defaultValue: "light" }), + ), + ).resolves.toEqual({ value: "dark", reason: "TARGETING_MATCH" }); + }); + + it("translates an already-evaluated boolean without a document", async () => { + const provider = createAwsAppConfigFlagProvider({ + reader: memoryReader([configuration("checkoutEnabled", true)]), + }); + await expect( + provider.resolve( + request({ + flagKey: "checkoutEnabled", + kind: "boolean", + defaultValue: false, + }), + ), + ).resolves.toEqual({ value: true, reason: "TARGETING_MATCH" }); + }); + + it("translates an enabled feature flag with no targeting rules", async () => { + const provider = createAwsAppConfigFlagProvider({ + reader: memoryReader([ + configuration("checkoutEnabled", { enabled: true }), + ]), + }); + await expect( + provider.resolve( + request({ + flagKey: "checkoutEnabled", + kind: "boolean", + defaultValue: false, + }), + ), + ).resolves.toEqual({ value: true, reason: "TARGETING_MATCH" }); + }); + + it("does not treat a multi-variant rule as an unconditional match", async () => { + const provider = createAwsAppConfigFlagProvider({ + reader: memoryReader([ + configuration("checkoutEnabled", { + enabled: true, + _variants: [ + { + name: "beta", + enabled: true, + rule: 'splits(["$userId"], {"seed":"checkout"}) < 25', + }, + { name: "default", enabled: false }, + ], + }), + ]), + }); + await expect( + provider.resolve( + request({ + flagKey: "checkoutEnabled", + kind: "boolean", + defaultValue: false, + }), + ), + ).rejects.toThrow("does not evaluate"); + }); + + it("does not treat a percentage split as a stored default match", async () => { + const provider = createAwsAppConfigFlagProvider({ + reader: memoryReader([ + configuration("checkoutEnabled", { + _variants: [ + { + name: "on", + enabled: true, + rule: "percent(50)", + }, + { name: "default", enabled: false }, + ], + }), + ]), + }); + await expect( + provider.resolve( + request({ + flagKey: "checkoutEnabled", + kind: "boolean", + defaultValue: false, + }), + ), + ).rejects.toThrow("does not evaluate"); + }); + + it("keeps a disabled feature flag DISABLED even when leftover rules exist", async () => { + const provider = createAwsAppConfigFlagProvider({ + reader: memoryReader([ + configuration("checkoutEnabled", { + enabled: false, + _variants: [ + { + name: "beta", + enabled: true, + rule: "percent(100)", + }, + { name: "default", enabled: false }, + ], + }), + ]), + }); + await expect( + provider.resolve( + request({ + flagKey: "checkoutEnabled", + kind: "boolean", + defaultValue: true, + }), + ), + ).resolves.toEqual({ + value: false, + reason: "DISABLED", + variant: "default", + }); + }); + + it("translates a disabled feature flag as DISABLED", async () => { + const provider = createAwsAppConfigFlagProvider({ + reader: memoryReader([ + configuration("checkoutEnabled", { enabled: false }), + ]), + }); + await expect( + provider.resolve( + request({ + flagKey: "checkoutEnabled", + kind: "boolean", + defaultValue: true, + }), + ), + ).resolves.toEqual({ value: false, reason: "DISABLED" }); + }); + + it("reads a default variant without a rule as stored data, not a rollout", async () => { + const provider = createAwsAppConfigFlagProvider({ + reader: memoryReader([ + configuration("checkoutEnabled", { + enabled: false, + _variants: [{ name: "stored", enabled: true }], + }), + ]), + }); + await expect( + provider.resolve( + request({ + flagKey: "checkoutEnabled", + kind: "boolean", + defaultValue: false, + }), + ), + ).resolves.toEqual({ + value: true, + reason: "DISABLED", + variant: "stored", + }); + }); + + it("extracts a flag from a retrieved flag map", async () => { + const provider = createAwsAppConfigFlagProvider({ + reader: memoryReader([ + configuration("checkoutEnabled", { + checkoutEnabled: { enabled: true }, + theme: { enabled: false }, + }), + ]), + }); + await expect( + provider.resolve( + request({ + flagKey: "checkoutEnabled", + kind: "boolean", + defaultValue: false, + }), + ), + ).resolves.toEqual({ value: true, reason: "TARGETING_MATCH" }); + }); + + it("extracts a flag from an AWS.AppConfig.FeatureFlags document", async () => { + const provider = createAwsAppConfigFlagProvider({ + reader: memoryReader([ + configuration( + "checkoutEnabled", + { + version: "1", + flags: { checkoutEnabled: { name: "checkoutEnabled" } }, + values: { checkoutEnabled: { enabled: true } }, + }, + { type: AWS_APPCONFIG_FEATURE_FLAGS_TYPE }, + ), + ]), + }); + await expect( + provider.resolve( + request({ + flagKey: "checkoutEnabled", + kind: "boolean", + defaultValue: false, + }), + ), + ).resolves.toEqual({ value: true, reason: "TARGETING_MATCH" }); + }); + + it("forwards the targeting key to the reader", async () => { + const seen: AwsAppConfigGetRequest[] = []; + const provider = createAwsAppConfigFlagProvider({ + reader: memoryReader([configuration("theme", "dark")], { + 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"); + }); + + it("applies host keyOf without inventing a layout", async () => { + const seen: AwsAppConfigGetRequest[] = []; + const provider = createAwsAppConfigFlagProvider({ + keyOf: (flagKey) => `app/${flagKey}`, + reader: memoryReader( + [configuration("app/checkoutEnabled", { enabled: true })], + { + 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]?.key).toBe("app/checkoutEnabled"); + }); + + it("throws when a typed ordinary value is not JSON", async () => { + const provider = createAwsAppConfigFlagProvider({ + reader: memoryReader([configuration("maxItems", "twenty-five")]), + }); + await expect( + provider.resolve( + request({ flagKey: "maxItems", kind: "number", defaultValue: 10 }), + ), + ).rejects.toThrow("not valid JSON"); + }); + + it("throws when a feature flag document is malformed", async () => { + const provider = createAwsAppConfigFlagProvider({ + reader: memoryReader([ + configuration( + "checkoutEnabled", + {}, + { type: AWS_APPCONFIG_FEATURE_FLAGS_TYPE }, + ), + ]), + }); + await expect( + provider.resolve( + request({ + flagKey: "checkoutEnabled", + kind: "boolean", + defaultValue: false, + }), + ), + ).rejects.toThrow("boolean enabled field"); + }); + + it("propagates reader failures", async () => { + const provider = createAwsAppConfigFlagProvider({ + reader: memoryReader([], { error: new Error("appconfig unavailable") }), + }); + await expect( + provider.resolve( + request({ + flagKey: "checkoutEnabled", + kind: "boolean", + defaultValue: false, + }), + ), + ).rejects.toThrow("appconfig unavailable"); + }); + + it("closes the injected reader", async () => { + const close = vi.fn(); + const provider = createAwsAppConfigFlagProvider({ + reader: { ...memoryReader([]), close }, + }); + await provider.close?.(); + expect(close).toHaveBeenCalledOnce(); + }); + + it("does not import an AWS SDK or call Date.now on the production path", () => { + const source = readFileSync(join(import.meta.dirname, "index.ts"), "utf8"); + expect(source).not.toMatch(/@aws-sdk\//u); + expect(source).not.toMatch(/aws-sdk/u); + expect(source).not.toMatch(/Date\.now\(/u); + }); +}); diff --git a/packages/flags-aws-appconfig/src/index.ts b/packages/flags-aws-appconfig/src/index.ts new file mode 100644 index 0000000..3a680f4 --- /dev/null +++ b/packages/flags-aws-appconfig/src/index.ts @@ -0,0 +1,349 @@ +import type { + EvaluationContext, + FlagProvider, + FlagProviderCapabilities, + FlagResolution, + FlagResolutionRequest, + FlagValueKind, +} from "@pegma/flags-contracts"; + +/** + * AWS AppConfig hosted feature-flag configuration type. + * + * @see https://docs.aws.amazon.com/appconfig/latest/userguide/appconfig-type-reference-feature-flags.html + */ +export const AWS_APPCONFIG_FEATURE_FLAGS_TYPE = "AWS.AppConfig.FeatureFlags"; + +/** Narrow configuration the injected reader returns. Matches AppConfig. */ +export interface AwsAppConfigConfiguration { + readonly key: string; + readonly value?: unknown; + readonly contentType?: string; + readonly type?: string; +} + +export interface AwsAppConfigGetRequest { + readonly key: string; + readonly context: EvaluationContext; +} + +/** + * Host-injected AppConfig lookup. Typically a thin wrapper around the + * AppConfig Agent `?flag=` response or `GetLatestConfiguration` that maps + * a missing flag to `undefined`. This package never imports the AWS SDK. + */ +export interface AwsAppConfigReader { + getConfiguration( + request: AwsAppConfigGetRequest, + ): Promise; + close?(): void | Promise; +} + +export interface AwsAppConfigFlagProviderOptions { + readonly reader: AwsAppConfigReader; + 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; +} + +function isPlainObject(value: unknown): value is object { + return value !== null && typeof value === "object" && !Array.isArray(value); +} + +function parseJson(raw: string, what: string): unknown { + try { + return JSON.parse(raw); + } catch { + throw new Error(`AWS AppConfig ${what} is not valid JSON`); + } +} + +function isFeatureFlagsType(configuration: AwsAppConfigConfiguration): boolean { + return configuration.type === AWS_APPCONFIG_FEATURE_FLAGS_TYPE; +} + +function isFeatureFlagEntry(value: unknown): value is object { + if (!isPlainObject(value)) { + return false; + } + return ( + typeof own(value, "enabled") === "boolean" || + Array.isArray(own(value, "_variants")) + ); +} + +function isFlagSetDocument(value: unknown): value is object { + return ( + isPlainObject(value) && + typeof own(value, "version") === "string" && + isPlainObject(own(value, "values")) + ); +} + +/** + * Reads the stored flag object from an `AWS.AppConfig.FeatureFlags` + * document or a retrieved flag map. Does not evaluate variants. + */ +export function awsAppConfigFlagValue( + document: unknown, + flagKey: string, +): unknown { + if (!isPlainObject(document)) { + return undefined; + } + const values = own(document, "values"); + if (isPlainObject(values) && Object.hasOwn(values, flagKey)) { + return own(values, flagKey); + } + if (Object.hasOwn(document, flagKey)) { + return own(document, flagKey); + } + return undefined; +} + +function variantRule(entry: object): string | undefined { + const rule = own(entry, "rule"); + if (rule === undefined) { + return undefined; + } + if (typeof rule !== "string") { + throw new Error("AWS AppConfig feature flag variant rule must be a string"); + } + return rule === "" ? undefined : rule; +} + +function hasUnevaluatedTargeting(document: object): boolean { + const variants = own(document, "_variants"); + if (variants === undefined) { + return false; + } + if (!Array.isArray(variants)) { + return true; + } + for (const entry of variants) { + if (!isPlainObject(entry)) { + continue; + } + if (variantRule(entry) !== undefined) { + return true; + } + } + return false; +} + +function refuseUnevaluatedTargeting(document: object, flagKey: string): void { + if (hasUnevaluatedTargeting(document)) { + throw new Error( + `AWS AppConfig feature flag ${flagKey} has targeting rules or a percentage rollout that this adapter does not evaluate`, + ); + } +} + +function defaultVariant( + document: object, +): { readonly enabled: boolean; readonly variant: string } | undefined { + const variants = own(document, "_variants"); + if (!Array.isArray(variants) || variants.length === 0) { + return undefined; + } + for (let index = variants.length - 1; index >= 0; index -= 1) { + const entry = variants[index]; + if (!isPlainObject(entry)) { + continue; + } + if (variantRule(entry) !== undefined) { + continue; + } + const name = own(entry, "name"); + const enabled = own(entry, "enabled"); + if (typeof name !== "string" || name === "") { + throw new Error( + "AWS AppConfig feature flag default variant is missing a name", + ); + } + if (typeof enabled !== "boolean") { + throw new Error( + "AWS AppConfig feature flag default variant is missing a boolean enabled field", + ); + } + return { enabled, variant: name }; + } + return undefined; +} + +function booleanFromFeatureFlag( + request: FlagResolutionRequest, + enabled: boolean, + reason: "TARGETING_MATCH" | "DISABLED", + variant?: string, +): FlagResolution { + if (request.kind !== "boolean") { + throw new Error( + `AWS AppConfig feature flag ${request.flagKey} has no stored ${request.kind} value`, + ); + } + return { + value: enabled, + reason, + ...(variant === undefined ? {} : { variant }), + }; +} + +function resolveFeatureFlag( + request: FlagResolutionRequest, + document: object, +): FlagResolution { + const enabled = own(document, "enabled"); + if (enabled !== undefined && typeof enabled !== "boolean") { + throw new Error( + "AWS AppConfig feature flag document is missing a boolean enabled field", + ); + } + + if (enabled === false) { + const stored = defaultVariant(document); + if (stored !== undefined) { + return booleanFromFeatureFlag( + request, + stored.enabled, + "DISABLED", + stored.variant, + ); + } + return booleanFromFeatureFlag(request, false, "DISABLED"); + } + + refuseUnevaluatedTargeting(document, request.flagKey); + + const stored = defaultVariant(document); + if (stored !== undefined) { + return booleanFromFeatureFlag( + request, + stored.enabled, + "TARGETING_MATCH", + stored.variant, + ); + } + if (enabled !== true) { + throw new Error( + "AWS AppConfig feature flag document is missing a boolean enabled field", + ); + } + return booleanFromFeatureFlag(request, true, "TARGETING_MATCH"); +} + +function unwrapFlagEntry(value: unknown, key: string): unknown { + if (isFlagSetDocument(value)) { + return awsAppConfigFlagValue(value, key); + } + if ( + isPlainObject(value) && + Object.hasOwn(value, key) && + isFeatureFlagEntry(own(value, key)) + ) { + return own(value, key); + } + return value; +} + +function parseTypedValue(kind: FlagValueKind, raw: string): unknown { + if (kind === "string") { + return raw; + } + return parseJson(raw, `${kind} value`); +} + +function resolveValue( + request: FlagResolutionRequest, + configuration: AwsAppConfigConfiguration, + value: unknown, +): FlagResolution { + if (isFeatureFlagEntry(value) || isFeatureFlagsType(configuration)) { + if (!isPlainObject(value)) { + throw new Error( + "AWS AppConfig feature flag document must be a JSON object", + ); + } + return resolveFeatureFlag(request, value); + } + if (typeof value === "string") { + return { + value: parseTypedValue(request.kind, value), + reason: "TARGETING_MATCH", + }; + } + return { value, reason: "TARGETING_MATCH" }; +} + +function resolveConfiguration( + request: FlagResolutionRequest, + configuration: AwsAppConfigConfiguration, +): FlagResolution { + if (configuration.value === undefined) { + throw new Error( + `AWS AppConfig configuration ${configuration.key} has no value`, + ); + } + let value = configuration.value; + if (typeof value === "string" && isFeatureFlagsType(configuration)) { + value = parseJson(value, "feature flag"); + } + const unwrapped = unwrapFlagEntry(value, configuration.key); + if (unwrapped === undefined) { + return { value: request.defaultValue, reason: "DEFAULT_FALLBACK" }; + } + return resolveValue(request, configuration, unwrapped); +} + +/** + * Translates AWS AppConfig configurations into {@link FlagProvider} + * resolutions. Multi-variant rules and percentage splits are not evaluated + * here. An enabled document that still carries those rules is rejected so + * this adapter cannot report a targeting match it did not compute. The + * injected reader must return an already-evaluated value when the host + * needs AppConfig variant evaluation. + */ +export function createAwsAppConfigFlagProvider( + options: AwsAppConfigFlagProviderOptions, +): FlagProvider { + if ( + options.reader === undefined || + typeof options.reader.getConfiguration !== "function" + ) { + throw new Error( + "createAwsAppConfigFlagProvider requires an injected AWS AppConfig reader", + ); + } + const name = options.name ?? "aws-appconfig"; + const capabilities: FlagProviderCapabilities = { + static: false, + streaming: false, + targeting: true, + }; + + return { + name, + capabilities() { + return capabilities; + }, + async resolve(request) { + const key = options.keyOf?.(request.flagKey) ?? request.flagKey; + const configuration = await options.reader.getConfiguration({ + key, + context: request.context, + }); + if (configuration === undefined) { + return { value: request.defaultValue, reason: "DEFAULT_FALLBACK" }; + } + return resolveConfiguration(request, configuration); + }, + async close() { + await options.reader.close?.(); + }, + }; +} diff --git a/packages/flags-aws-appconfig/tsconfig.json b/packages/flags-aws-appconfig/tsconfig.json new file mode 100644 index 0000000..bc330dd --- /dev/null +++ b/packages/flags-aws-appconfig/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 1dfeb59..5682ade 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -21,6 +21,12 @@ importers: specifier: ^4.1.10 version: 4.1.10(@types/node@26.2.0)(vite@8.2.1(@types/node@26.2.0)) + packages/flags-aws-appconfig: + dependencies: + '@pegma/flags-contracts': + specifier: 0.1.0 + version: link:../flags-contracts + packages/flags-azure-appconfig: dependencies: '@pegma/flags-contracts': diff --git a/scripts/release-packages.mjs b/scripts/release-packages.mjs index 9ad348d..ca9d72c 100644 --- a/scripts/release-packages.mjs +++ b/scripts/release-packages.mjs @@ -43,6 +43,10 @@ export const RELEASE_PACKAGES = [ directory: "flags-azure-appconfig", name: "@pegma/flags-azure-appconfig", }, + { + directory: "flags-aws-appconfig", + name: "@pegma/flags-aws-appconfig", + }, { directory: "flags-launchdarkly", name: "@pegma/flags-launchdarkly", diff --git a/tests/aws-appconfig-conformance.test.ts b/tests/aws-appconfig-conformance.test.ts new file mode 100644 index 0000000..6680245 --- /dev/null +++ b/tests/aws-appconfig-conformance.test.ts @@ -0,0 +1,111 @@ +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 { + createAwsAppConfigFlagProvider, + type AwsAppConfigConfiguration, + type AwsAppConfigReader, +} from "../packages/flags-aws-appconfig/src/index.js"; + +function wait(delayMs: number): Promise { + return new Promise((resolve) => { + setTimeout(resolve, delayMs); + }); +} + +function configurationsFromFlags( + flags: Readonly>, +): AwsAppConfigConfiguration[] { + return Object.entries(flags).map(([flagKey, value]) => ({ + key: flagKey, + value, + })); +} + +function memoryReader(options: { + readonly configurations?: readonly AwsAppConfigConfiguration[]; + readonly configurationsForContext?: ( + context: EvaluationContext, + ) => readonly AwsAppConfigConfiguration[]; + readonly delayMs?: number; + readonly error?: unknown; +}): AwsAppConfigReader { + return { + async getConfiguration(request) { + if (options.delayMs !== undefined && options.delayMs > 0) { + await wait(options.delayMs); + } + if (options.error !== undefined) { + throw options.error; + } + const configurations = + options.configurationsForContext?.(request.context) ?? + options.configurations ?? + []; + return configurations.find( + (configuration) => configuration.key === request.key, + ); + }, + }; +} + +const cases = flagConformanceCases((scenario) => { + switch (scenario.type) { + case "values": + return createAwsAppConfigFlagProvider({ + reader: memoryReader({ + configurations: configurationsFromFlags(scenario.flags), + }), + }); + case "empty": + return createAwsAppConfigFlagProvider({ + reader: memoryReader({ configurations: [] }), + }); + case "targeted": + return createAwsAppConfigFlagProvider({ + reader: memoryReader({ + configurationsForContext(context) { + return context.targetingKey === scenario.targetingKey + ? configurationsFromFlags(scenario.flags) + : []; + }, + }), + }); + case "timeout": + return createAwsAppConfigFlagProvider({ + reader: memoryReader({ delayMs: scenario.delayMs }), + }); + case "error": + return createAwsAppConfigFlagProvider({ + reader: memoryReader({ error: scenario.error }), + }); + case "disabled": + return createAwsAppConfigFlagProvider({ + reader: memoryReader({ + configurations: [ + { + key: scenario.flagKey, + value: { + enabled: false, + _variants: [ + { + name: "stored", + enabled: scenario.value, + }, + ], + }, + }, + ], + }), + }); + } +}); + +describe("AWS AppConfig 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 05337e9..c0102c3 100644 --- a/tests/release-packages.test.ts +++ b/tests/release-packages.test.ts @@ -46,6 +46,7 @@ describe("release package metadata", () => { "@pegma/flags-core", "@pegma/flags-static", "@pegma/flags-azure-appconfig", + "@pegma/flags-aws-appconfig", "@pegma/flags-launchdarkly", ]); }); diff --git a/tsconfig.json b/tsconfig.json index 2c3ea5b..0fafba7 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -5,6 +5,7 @@ { "path": "./packages/flags-core" }, { "path": "./packages/flags-static" }, { "path": "./packages/flags-azure-appconfig" }, + { "path": "./packages/flags-aws-appconfig" }, { "path": "./packages/flags-launchdarkly" } ] } From f14fe85d7675a73d0e6c7382e7fb4cbe1c32ac0e Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sat, 15 Aug 2026 21:13:01 +0000 Subject: [PATCH 2/5] Fix AppConfig parse assignment under unknown narrowing Keep the configuration payload typed as unknown after JSON parse so tsc does not treat the narrowed string as the only writable type. Co-authored-by: Fly Over Coder --- packages/flags-aws-appconfig/src/index.ts | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/packages/flags-aws-appconfig/src/index.ts b/packages/flags-aws-appconfig/src/index.ts index 3a680f4..bbe5644 100644 --- a/packages/flags-aws-appconfig/src/index.ts +++ b/packages/flags-aws-appconfig/src/index.ts @@ -289,11 +289,12 @@ function resolveConfiguration( `AWS AppConfig configuration ${configuration.key} has no value`, ); } - let value = configuration.value; - if (typeof value === "string" && isFeatureFlagsType(configuration)) { - value = parseJson(value, "feature flag"); - } - const unwrapped = unwrapFlagEntry(value, configuration.key); + const raw = configuration.value; + const parsed = + typeof raw === "string" && isFeatureFlagsType(configuration) + ? parseJson(raw, "feature flag") + : raw; + const unwrapped = unwrapFlagEntry(parsed, configuration.key); if (unwrapped === undefined) { return { value: request.defaultValue, reason: "DEFAULT_FALLBACK" }; } From 37a366c37613bc4a33912b0f6324f732d60a21f8 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sat, 15 Aug 2026 21:22:24 +0000 Subject: [PATCH 3/5] Require AppConfig metadata before feature-flag mapping Do not treat a JSON object as a feature-flag document just because it has a boolean enabled field. Walk FeatureFlags maps and version/values documents only when the host marked the type, and return DEFAULT_FALLBACK for a missing key instead of throwing. Co-authored-by: Fly Over Coder --- packages/flags-aws-appconfig/README.md | 11 ++- .../flags-aws-appconfig/src/index.test.ts | 96 ++++++++++++++++--- packages/flags-aws-appconfig/src/index.ts | 51 +++++++--- 3 files changed, 125 insertions(+), 33 deletions(-) diff --git a/packages/flags-aws-appconfig/README.md b/packages/flags-aws-appconfig/README.md index 4ca59d6..f59ed5e 100644 --- a/packages/flags-aws-appconfig/README.md +++ b/packages/flags-aws-appconfig/README.md @@ -16,15 +16,20 @@ AppConfig Agent `?flag=` response, or `GetLatestConfiguration` after the host applied context). This package can also map: - ordinary typed values (string as-is; boolean, number, and json via JSON) -- an unconditional feature-flag object with a boolean `enabled` field +- a feature-flag document marked `type: AWS.AppConfig.FeatureFlags`, or + one that carries AWS `_variants` metadata - a stored default variant that has no `rule` -An enabled document that still carries `_variants` with a `rule` is +A JSON object that happens to include `enabled` is a payload, not a +feature-flag document. Set `type: AWS.AppConfig.FeatureFlags` when the +reader returns AppConfig feature-flag data or a retrieved flag map. An +enabled document that still carries `_variants` with a `rule` is rejected. Wrap AppConfig evaluation in the injected reader if the host needs those rules. ```ts import { + AWS_APPCONFIG_FEATURE_FLAGS_TYPE, awsAppConfigFlagValue, createAwsAppConfigFlagProvider, } from "@pegma/flags-aws-appconfig"; @@ -49,7 +54,7 @@ const provider = createAwsAppConfigFlagProvider({ if (value === undefined) { return undefined; } - return { key, value }; + return { key, value, type: AWS_APPCONFIG_FEATURE_FLAGS_TYPE }; }, }, }); diff --git a/packages/flags-aws-appconfig/src/index.test.ts b/packages/flags-aws-appconfig/src/index.test.ts index 0cf2c3c..272c345 100644 --- a/packages/flags-aws-appconfig/src/index.test.ts +++ b/packages/flags-aws-appconfig/src/index.test.ts @@ -40,6 +40,10 @@ function configuration( }; } +function featureFlag(key: string, value: unknown): AwsAppConfigConfiguration { + return configuration(key, value, { type: AWS_APPCONFIG_FEATURE_FLAGS_TYPE }); +} + function memoryReader( configurations: readonly AwsAppConfigConfiguration[], extras: { @@ -92,6 +96,9 @@ describe("awsAppConfigFlagValue", () => { expect(awsAppConfigFlagValue({ version: "1", values: {} }, "theme")).toBe( undefined, ); + expect( + awsAppConfigFlagValue({ checkoutEnabled: { enabled: true } }, "theme"), + ).toBe(undefined); }); }); @@ -200,9 +207,7 @@ describe("createAwsAppConfigFlagProvider", () => { it("translates an enabled feature flag with no targeting rules", async () => { const provider = createAwsAppConfigFlagProvider({ - reader: memoryReader([ - configuration("checkoutEnabled", { enabled: true }), - ]), + reader: memoryReader([featureFlag("checkoutEnabled", { enabled: true })]), }); await expect( provider.resolve( @@ -218,7 +223,7 @@ describe("createAwsAppConfigFlagProvider", () => { it("does not treat a multi-variant rule as an unconditional match", async () => { const provider = createAwsAppConfigFlagProvider({ reader: memoryReader([ - configuration("checkoutEnabled", { + featureFlag("checkoutEnabled", { enabled: true, _variants: [ { @@ -245,7 +250,7 @@ describe("createAwsAppConfigFlagProvider", () => { it("does not treat a percentage split as a stored default match", async () => { const provider = createAwsAppConfigFlagProvider({ reader: memoryReader([ - configuration("checkoutEnabled", { + featureFlag("checkoutEnabled", { _variants: [ { name: "on", @@ -271,7 +276,7 @@ describe("createAwsAppConfigFlagProvider", () => { it("keeps a disabled feature flag DISABLED even when leftover rules exist", async () => { const provider = createAwsAppConfigFlagProvider({ reader: memoryReader([ - configuration("checkoutEnabled", { + featureFlag("checkoutEnabled", { enabled: false, _variants: [ { @@ -302,7 +307,7 @@ describe("createAwsAppConfigFlagProvider", () => { it("translates a disabled feature flag as DISABLED", async () => { const provider = createAwsAppConfigFlagProvider({ reader: memoryReader([ - configuration("checkoutEnabled", { enabled: false }), + featureFlag("checkoutEnabled", { enabled: false }), ]), }); await expect( @@ -319,7 +324,7 @@ describe("createAwsAppConfigFlagProvider", () => { it("reads a default variant without a rule as stored data, not a rollout", async () => { const provider = createAwsAppConfigFlagProvider({ reader: memoryReader([ - configuration("checkoutEnabled", { + featureFlag("checkoutEnabled", { enabled: false, _variants: [{ name: "stored", enabled: true }], }), @@ -343,7 +348,7 @@ describe("createAwsAppConfigFlagProvider", () => { it("extracts a flag from a retrieved flag map", async () => { const provider = createAwsAppConfigFlagProvider({ reader: memoryReader([ - configuration("checkoutEnabled", { + featureFlag("checkoutEnabled", { checkoutEnabled: { enabled: true }, theme: { enabled: false }, }), @@ -410,7 +415,7 @@ describe("createAwsAppConfigFlagProvider", () => { const provider = createAwsAppConfigFlagProvider({ keyOf: (flagKey) => `app/${flagKey}`, reader: memoryReader( - [configuration("app/checkoutEnabled", { enabled: true })], + [featureFlag("app/checkoutEnabled", { enabled: true })], { onGet(getRequest) { seen.push(getRequest); @@ -440,14 +445,75 @@ describe("createAwsAppConfigFlagProvider", () => { ).rejects.toThrow("not valid JSON"); }); + it("returns an ordinary JSON object that contains enabled", async () => { + const payload = { enabled: true, mode: "dark" }; + const provider = createAwsAppConfigFlagProvider({ + reader: memoryReader([configuration("payload", payload)]), + }); + await expect( + provider.resolve( + request({ + flagKey: "payload", + kind: "json", + defaultValue: { enabled: false, mode: "light" }, + }), + ), + ).resolves.toEqual({ + value: payload, + reason: "TARGETING_MATCH", + }); + }); + + it("returns DEFAULT_FALLBACK for a missing key in a feature-flag document", async () => { + const provider = createAwsAppConfigFlagProvider({ + reader: memoryReader([ + featureFlag("theme", { + version: "1", + flags: { checkoutEnabled: { name: "checkoutEnabled" } }, + values: { checkoutEnabled: { enabled: true } }, + }), + ]), + }); + await expect( + provider.resolve( + request({ + flagKey: "theme", + kind: "string", + defaultValue: "light", + }), + ), + ).resolves.toEqual({ + value: "light", + reason: "DEFAULT_FALLBACK", + }); + }); + + it("returns DEFAULT_FALLBACK for a missing key in a feature-flag map", async () => { + const provider = createAwsAppConfigFlagProvider({ + reader: memoryReader([ + featureFlag("theme", { + checkoutEnabled: { enabled: true }, + }), + ]), + }); + await expect( + provider.resolve( + request({ + flagKey: "theme", + kind: "string", + defaultValue: "light", + }), + ), + ).resolves.toEqual({ + value: "light", + reason: "DEFAULT_FALLBACK", + }); + }); + it("throws when a feature flag document is malformed", async () => { const provider = createAwsAppConfigFlagProvider({ reader: memoryReader([ - configuration( - "checkoutEnabled", - {}, - { type: AWS_APPCONFIG_FEATURE_FLAGS_TYPE }, - ), + featureFlag("checkoutEnabled", { enabled: "yes" }), ]), }); await expect( diff --git a/packages/flags-aws-appconfig/src/index.ts b/packages/flags-aws-appconfig/src/index.ts index bbe5644..98a5d24 100644 --- a/packages/flags-aws-appconfig/src/index.ts +++ b/packages/flags-aws-appconfig/src/index.ts @@ -67,16 +67,28 @@ function isFeatureFlagsType(configuration: AwsAppConfigConfiguration): boolean { return configuration.type === AWS_APPCONFIG_FEATURE_FLAGS_TYPE; } -function isFeatureFlagEntry(value: unknown): value is object { - if (!isPlainObject(value)) { - return false; - } +function hasVariants(value: unknown): boolean { + return isPlainObject(value) && Array.isArray(own(value, "_variants")); +} + +function isSingleFeatureFlagEntry(value: unknown): value is object { return ( - typeof own(value, "enabled") === "boolean" || - Array.isArray(own(value, "_variants")) + isPlainObject(value) && + (Object.hasOwn(value, "enabled") || hasVariants(value)) ); } +/** + * Feature-flag documents need AWS metadata. A boolean `enabled` field + * alone is a valid JSON payload and is not enough. + */ +function isFeatureFlagDocument( + configuration: AwsAppConfigConfiguration, + value: unknown, +): boolean { + return isFeatureFlagsType(configuration) || hasVariants(value); +} + function isFlagSetDocument(value: unknown): value is object { return ( isPlainObject(value) && @@ -237,18 +249,27 @@ function resolveFeatureFlag( return booleanFromFeatureFlag(request, true, "TARGETING_MATCH"); } -function unwrapFlagEntry(value: unknown, key: string): unknown { +function unwrapFlagEntry( + value: unknown, + key: string, + configuration: AwsAppConfigConfiguration, +): unknown { if (isFlagSetDocument(value)) { + if (!isFeatureFlagsType(configuration)) { + return value; + } return awsAppConfigFlagValue(value, key); } - if ( - isPlainObject(value) && - Object.hasOwn(value, key) && - isFeatureFlagEntry(own(value, key)) - ) { + if (!isFeatureFlagsType(configuration) || !isPlainObject(value)) { + return value; + } + if (Object.hasOwn(value, key)) { return own(value, key); } - return value; + if (isSingleFeatureFlagEntry(value)) { + return value; + } + return undefined; } function parseTypedValue(kind: FlagValueKind, raw: string): unknown { @@ -263,7 +284,7 @@ function resolveValue( configuration: AwsAppConfigConfiguration, value: unknown, ): FlagResolution { - if (isFeatureFlagEntry(value) || isFeatureFlagsType(configuration)) { + if (isFeatureFlagDocument(configuration, value)) { if (!isPlainObject(value)) { throw new Error( "AWS AppConfig feature flag document must be a JSON object", @@ -294,7 +315,7 @@ function resolveConfiguration( typeof raw === "string" && isFeatureFlagsType(configuration) ? parseJson(raw, "feature flag") : raw; - const unwrapped = unwrapFlagEntry(parsed, configuration.key); + const unwrapped = unwrapFlagEntry(parsed, configuration.key, configuration); if (unwrapped === undefined) { return { value: request.defaultValue, reason: "DEFAULT_FALLBACK" }; } From a3d0160fa169991165f3060aed96887c8c1e661f Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sat, 15 Aug 2026 21:27:27 +0000 Subject: [PATCH 4/5] Keep leaf feature flags when an attribute matches the key Detect a single feature-flag entry before looking up a nested map key so an attribute named like the flag is not unwrapped in place of enabled or _variants. Co-authored-by: Fly Over Coder --- .../flags-aws-appconfig/src/index.test.ts | 20 +++++++++++++++++++ packages/flags-aws-appconfig/src/index.ts | 6 +++--- 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/packages/flags-aws-appconfig/src/index.test.ts b/packages/flags-aws-appconfig/src/index.test.ts index 272c345..c980d24 100644 --- a/packages/flags-aws-appconfig/src/index.test.ts +++ b/packages/flags-aws-appconfig/src/index.test.ts @@ -345,6 +345,26 @@ describe("createAwsAppConfigFlagProvider", () => { }); }); + it("does not unwrap an attribute that shares the flag key", async () => { + const provider = createAwsAppConfigFlagProvider({ + reader: memoryReader([ + featureFlag("checkoutEnabled", { + enabled: true, + checkoutEnabled: "dark", + }), + ]), + }); + await expect( + provider.resolve( + request({ + flagKey: "checkoutEnabled", + kind: "boolean", + defaultValue: false, + }), + ), + ).resolves.toEqual({ value: true, reason: "TARGETING_MATCH" }); + }); + it("extracts a flag from a retrieved flag map", async () => { const provider = createAwsAppConfigFlagProvider({ reader: memoryReader([ diff --git a/packages/flags-aws-appconfig/src/index.ts b/packages/flags-aws-appconfig/src/index.ts index 98a5d24..65743de 100644 --- a/packages/flags-aws-appconfig/src/index.ts +++ b/packages/flags-aws-appconfig/src/index.ts @@ -263,12 +263,12 @@ function unwrapFlagEntry( if (!isFeatureFlagsType(configuration) || !isPlainObject(value)) { return value; } - if (Object.hasOwn(value, key)) { - return own(value, key); - } if (isSingleFeatureFlagEntry(value)) { return value; } + if (Object.hasOwn(value, key)) { + return own(value, key); + } return undefined; } From 12ffba799e505459b79393f619f4824961023944 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sat, 15 Aug 2026 21:32:02 +0000 Subject: [PATCH 5/5] Unwrap FeatureFlags maps that include a flag named enabled Detect a retrieved flag map by flag-shaped children, not by an own enabled property, so other keys still extract while a leaf entry with a colliding attribute keeps reading enabled. Co-authored-by: Fly Over Coder --- .../flags-aws-appconfig/src/index.test.ts | 20 ++++++++++++++++++ packages/flags-aws-appconfig/src/index.ts | 21 ++++++++++++++++--- 2 files changed, 38 insertions(+), 3 deletions(-) diff --git a/packages/flags-aws-appconfig/src/index.test.ts b/packages/flags-aws-appconfig/src/index.test.ts index c980d24..306cac2 100644 --- a/packages/flags-aws-appconfig/src/index.test.ts +++ b/packages/flags-aws-appconfig/src/index.test.ts @@ -365,6 +365,26 @@ describe("createAwsAppConfigFlagProvider", () => { ).resolves.toEqual({ value: true, reason: "TARGETING_MATCH" }); }); + it("unwraps other keys from a map that includes a flag named enabled", async () => { + const provider = createAwsAppConfigFlagProvider({ + reader: memoryReader([ + featureFlag("checkoutEnabled", { + enabled: { enabled: false }, + checkoutEnabled: { enabled: true }, + }), + ]), + }); + await expect( + provider.resolve( + request({ + flagKey: "checkoutEnabled", + kind: "boolean", + defaultValue: false, + }), + ), + ).resolves.toEqual({ value: true, reason: "TARGETING_MATCH" }); + }); + it("extracts a flag from a retrieved flag map", async () => { const provider = createAwsAppConfigFlagProvider({ reader: memoryReader([ diff --git a/packages/flags-aws-appconfig/src/index.ts b/packages/flags-aws-appconfig/src/index.ts index 65743de..336a3da 100644 --- a/packages/flags-aws-appconfig/src/index.ts +++ b/packages/flags-aws-appconfig/src/index.ts @@ -71,13 +71,25 @@ function hasVariants(value: unknown): boolean { return isPlainObject(value) && Array.isArray(own(value, "_variants")); } -function isSingleFeatureFlagEntry(value: unknown): value is object { +function isFlagEntry(value: unknown): value is object { return ( isPlainObject(value) && - (Object.hasOwn(value, "enabled") || hasVariants(value)) + (typeof own(value, "enabled") === "boolean" || hasVariants(value)) ); } +function isFeatureFlagMap(value: unknown): value is object { + if (!isPlainObject(value)) { + return false; + } + for (const childKey of Object.keys(value)) { + if (isFlagEntry(own(value, childKey))) { + return true; + } + } + return false; +} + /** * Feature-flag documents need AWS metadata. A boolean `enabled` field * alone is a valid JSON payload and is not enough. @@ -263,7 +275,10 @@ function unwrapFlagEntry( if (!isFeatureFlagsType(configuration) || !isPlainObject(value)) { return value; } - if (isSingleFeatureFlagEntry(value)) { + if (isFeatureFlagMap(value)) { + return Object.hasOwn(value, key) ? own(value, key) : undefined; + } + if (isFlagEntry(value) || Object.hasOwn(value, "enabled")) { return value; } if (Object.hasOwn(value, key)) {