@quonfig/openfeature-node 1.0.2 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +22 -0
- package/dist/index.cjs +45 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +17 -0
- package/dist/index.d.ts +17 -0
- package/dist/index.js +45 -1
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -113,3 +113,25 @@ OpenFeature.addHandler(ProviderEvents.ConfigurationChanged, () => {
|
|
|
113
113
|
console.log("Configs updated!");
|
|
114
114
|
});
|
|
115
115
|
```
|
|
116
|
+
|
|
117
|
+
## Init failure and provider status
|
|
118
|
+
|
|
119
|
+
Pass `onInitFailure` (`"fail"` | `"wait"` | `"continue"`, default `"fail"`) and `initTimeout` (ms,
|
|
120
|
+
default 10000) in the provider options; they go straight to the wrapped `@quonfig/node` client. When
|
|
121
|
+
no config has loaded by `initTimeout`, the provider status follows the mode:
|
|
122
|
+
|
|
123
|
+
| `onInitFailure` | `setProviderAndWait` | Provider status | When the client heals |
|
|
124
|
+
| ---------------- | ------------------------------------------- | --------------- | --------------------- |
|
|
125
|
+
| `fail` (default) | rejects with the SDK's `QuonfigInitError` | `ERROR` | `PROVIDER_READY` |
|
|
126
|
+
| `wait` | blocks until config loads | `NOT_READY` | resolves, `READY` |
|
|
127
|
+
| `continue` | resolves, then `PROVIDER_ERROR` (non-fatal) | `ERROR` | `PROVIDER_READY` |
|
|
128
|
+
|
|
129
|
+
In every mode the client keeps retrying in the background, so a caught `fail` does not leave a dead
|
|
130
|
+
provider. While the provider is `ERROR`, evaluations still run and return your default with
|
|
131
|
+
`errorCode: PROVIDER_NOT_READY`.
|
|
132
|
+
|
|
133
|
+
```typescript
|
|
134
|
+
const provider = new QuonfigProvider({ sdkKey, onInitFailure: "continue", initTimeout: 5000 });
|
|
135
|
+
await OpenFeature.setProviderAndWait(provider);
|
|
136
|
+
OpenFeature.addHandler(ProviderEvents.Ready, () => console.log("Quonfig config loaded"));
|
|
137
|
+
```
|
package/dist/index.cjs
CHANGED
|
@@ -64,6 +64,7 @@ var QuonfigProvider = class {
|
|
|
64
64
|
this.metadata = { name: "quonfig" };
|
|
65
65
|
this.events = new import_server_sdk.OpenFeatureEventEmitter();
|
|
66
66
|
this.hooks = [];
|
|
67
|
+
this.closed = false;
|
|
67
68
|
this.targetingKeyMapping = options.targetingKeyMapping ?? "user.id";
|
|
68
69
|
this.client = new import_node.Quonfig({
|
|
69
70
|
...options,
|
|
@@ -72,10 +73,51 @@ var QuonfigProvider = class {
|
|
|
72
73
|
}
|
|
73
74
|
});
|
|
74
75
|
}
|
|
76
|
+
/**
|
|
77
|
+
* Initialize the wrapped client. Status follows the client's `onInitFailure`
|
|
78
|
+
* (design B.5), which you pass in the provider options with `initTimeout`:
|
|
79
|
+
*
|
|
80
|
+
* - `"fail"` (default): `init()` rejects, so this throws and the provider is
|
|
81
|
+
* ERROR. The client is kept alive and retries in the background; on heal the
|
|
82
|
+
* provider emits PROVIDER_READY.
|
|
83
|
+
* - `"wait"`: blocks until the first config, so the provider is NOT_READY
|
|
84
|
+
* throughout and READY when it resolves.
|
|
85
|
+
* - `"continue"`: resolves on code defaults, then emits a non-fatal
|
|
86
|
+
* PROVIDER_ERROR so the status is ERROR (evaluations still run and return
|
|
87
|
+
* the caller default). On heal the provider emits PROVIDER_READY.
|
|
88
|
+
*/
|
|
75
89
|
async initialize(_context) {
|
|
76
|
-
|
|
90
|
+
try {
|
|
91
|
+
await this.client.init();
|
|
92
|
+
} catch (err) {
|
|
93
|
+
this.emitReadyOnHeal();
|
|
94
|
+
throw err;
|
|
95
|
+
}
|
|
96
|
+
if (!this.client.isReady()) {
|
|
97
|
+
this.initErrorTimer = setTimeout(() => {
|
|
98
|
+
if (this.closed || this.client.isReady()) return;
|
|
99
|
+
this.events.emit(import_server_sdk.ProviderEvents.Error, {
|
|
100
|
+
message: "[quonfig] no config loaded (onInitFailure=continue): serving code defaults",
|
|
101
|
+
errorCode: import_server_sdk.ErrorCode.PROVIDER_NOT_READY
|
|
102
|
+
});
|
|
103
|
+
}, 0);
|
|
104
|
+
this.emitReadyOnHeal();
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
/** Emit PROVIDER_READY once the client's background retry loads config. */
|
|
108
|
+
emitReadyOnHeal() {
|
|
109
|
+
this.client.waitForReady().then(
|
|
110
|
+
() => {
|
|
111
|
+
if (!this.closed) this.events.emit(import_server_sdk.ProviderEvents.Ready);
|
|
112
|
+
},
|
|
113
|
+
() => {
|
|
114
|
+
}
|
|
115
|
+
// closed before healing
|
|
116
|
+
);
|
|
77
117
|
}
|
|
78
118
|
async shutdown() {
|
|
119
|
+
this.closed = true;
|
|
120
|
+
clearTimeout(this.initErrorTimer);
|
|
79
121
|
await this.client.close();
|
|
80
122
|
}
|
|
81
123
|
async resolveBooleanEvaluation(flagKey, defaultValue, context, _logger) {
|
|
@@ -159,6 +201,8 @@ function toOFErrorCode(code) {
|
|
|
159
201
|
return import_server_sdk.ErrorCode.FLAG_NOT_FOUND;
|
|
160
202
|
case "TYPE_MISMATCH":
|
|
161
203
|
return import_server_sdk.ErrorCode.TYPE_MISMATCH;
|
|
204
|
+
case "PROVIDER_NOT_READY":
|
|
205
|
+
return import_server_sdk.ErrorCode.PROVIDER_NOT_READY;
|
|
162
206
|
case "GENERAL":
|
|
163
207
|
default:
|
|
164
208
|
return import_server_sdk.ErrorCode.GENERAL;
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/provider.ts","../src/context.ts","../src/errors.ts"],"sourcesContent":["export { QuonfigProvider } from \"./provider.js\";\nexport type { QuonfigProviderOptions } from \"./provider.js\";\nexport { mapContext } from \"./context.js\";\nexport { toErrorCode } from \"./errors.js\";\n","import {\n ErrorCode,\n EvaluationContext,\n JsonValue,\n Logger,\n OpenFeatureEventEmitter,\n Provider,\n ProviderEvents,\n ResolutionDetails,\n StandardResolutionReasons,\n} from \"@openfeature/server-sdk\";\nimport { EvaluationDetails, Quonfig, QuonfigOptions } from \"@quonfig/node\";\nimport { mapContext } from \"./context.js\";\n\nexport interface QuonfigProviderOptions extends Omit<QuonfigOptions, \"onConfigUpdate\"> {\n /**\n * Dot-notation path to map OpenFeature's `targetingKey` into Quonfig's nested context.\n * Defaults to \"user.id\".\n */\n targetingKeyMapping?: string;\n}\n\n/**\n * QuonfigProvider wraps the @quonfig/node native SDK and implements the\n * OpenFeature server-side Provider interface.\n *\n * Usage:\n * ```typescript\n * import { QuonfigProvider } from \"@quonfig/openfeature-node\";\n * import { OpenFeature } from \"@openfeature/server-sdk\";\n *\n * const provider = new QuonfigProvider({ sdkKey: \"qf_sk_...\" });\n * await OpenFeature.setProviderAndWait(provider);\n * const client = OpenFeature.getClient();\n * const enabled = await client.getBooleanValue(\"my-flag\", false);\n * ```\n */\nexport class QuonfigProvider implements Provider {\n readonly metadata = { name: \"quonfig\" } as const;\n readonly events = new OpenFeatureEventEmitter();\n readonly hooks = [];\n\n private readonly client: Quonfig;\n private readonly targetingKeyMapping: string;\n\n constructor(options: QuonfigProviderOptions) {\n this.targetingKeyMapping = options.targetingKeyMapping ?? \"user.id\";\n this.client = new Quonfig({\n ...options,\n onConfigUpdate: () => {\n this.events.emit(ProviderEvents.ConfigurationChanged, { flagsChanged: [] });\n },\n });\n }\n\n async initialize(_context?: EvaluationContext): Promise<void> {\n await this.client.init();\n }\n\n async shutdown(): Promise<void> {\n await this.client.close();\n }\n\n async resolveBooleanEvaluation(\n flagKey: string,\n defaultValue: boolean,\n context: EvaluationContext,\n _logger: Logger\n ): Promise<ResolutionDetails<boolean>> {\n const mappedCtx = mapContext(context, this.targetingKeyMapping);\n const details = this.client.getBoolDetails(flagKey, mappedCtx);\n return toResolutionDetails(details, defaultValue);\n }\n\n async resolveStringEvaluation(\n flagKey: string,\n defaultValue: string,\n context: EvaluationContext,\n _logger: Logger\n ): Promise<ResolutionDetails<string>> {\n const mappedCtx = mapContext(context, this.targetingKeyMapping);\n const details = this.client.getStringDetails(flagKey, mappedCtx);\n return toResolutionDetails(details, defaultValue);\n }\n\n async resolveNumberEvaluation(\n flagKey: string,\n defaultValue: number,\n context: EvaluationContext,\n _logger: Logger\n ): Promise<ResolutionDetails<number>> {\n const mappedCtx = mapContext(context, this.targetingKeyMapping);\n const details = this.client.getNumberDetails(flagKey, mappedCtx);\n return toResolutionDetails(details, defaultValue);\n }\n\n async resolveObjectEvaluation<T extends JsonValue>(\n flagKey: string,\n defaultValue: T,\n context: EvaluationContext,\n _logger: Logger\n ): Promise<ResolutionDetails<T>> {\n const mappedCtx = mapContext(context, this.targetingKeyMapping);\n // Try string_list first (returns string[]), fall back to JSON.\n const listDetails = this.client.getStringListDetails(flagKey, mappedCtx);\n if (\n listDetails.reason === \"STATIC\" ||\n listDetails.reason === \"TARGETING_MATCH\" ||\n listDetails.reason === \"SPLIT\"\n ) {\n return toResolutionDetails(\n listDetails as EvaluationDetails<unknown> as EvaluationDetails<T>,\n defaultValue\n );\n }\n const jsonDetails = this.client.getJSONDetails(flagKey, mappedCtx);\n return toResolutionDetails(jsonDetails as EvaluationDetails<T>, defaultValue);\n }\n\n /**\n * Escape hatch: access the underlying @quonfig/node client for native-only features\n * (shouldLog, keys, rawConfig, etc.)\n */\n getClient(): Quonfig {\n return this.client;\n }\n}\n\n/**\n * Translate a Quonfig EvaluationDetails<T> into an OpenFeature ResolutionDetails<T>.\n *\n * Reason mapping (from the brief):\n * STATIC → StandardResolutionReasons.STATIC\n * TARGETING_MATCH → StandardResolutionReasons.TARGETING_MATCH\n * SPLIT → StandardResolutionReasons.SPLIT\n * DEFAULT → defaultValue + StandardResolutionReasons.DEFAULT\n * ERROR → defaultValue + ERROR + errorCode (FLAG_NOT_FOUND / TYPE_MISMATCH / GENERAL)\n */\nfunction toResolutionDetails<T>(\n details: EvaluationDetails<T>,\n defaultValue: T\n): ResolutionDetails<T> {\n const common = {\n variant: details.variant,\n flagMetadata: details.flagMetadata as ResolutionDetails<T>[\"flagMetadata\"],\n };\n switch (details.reason) {\n case \"STATIC\":\n return {\n value: details.value as T,\n reason: StandardResolutionReasons.STATIC,\n ...common,\n };\n case \"TARGETING_MATCH\":\n return {\n value: details.value as T,\n reason: StandardResolutionReasons.TARGETING_MATCH,\n ...common,\n };\n case \"SPLIT\":\n return {\n value: details.value as T,\n reason: StandardResolutionReasons.SPLIT,\n ...common,\n };\n case \"DEFAULT\":\n return {\n value: defaultValue,\n reason: StandardResolutionReasons.DEFAULT,\n ...common,\n };\n case \"ERROR\":\n return {\n value: defaultValue,\n reason: StandardResolutionReasons.ERROR,\n errorCode: toOFErrorCode(details.errorCode),\n errorMessage: details.errorMessage,\n ...common,\n };\n }\n}\n\nfunction toOFErrorCode(code: EvaluationDetails<unknown>[\"errorCode\"]): ErrorCode {\n switch (code) {\n case \"FLAG_NOT_FOUND\":\n return ErrorCode.FLAG_NOT_FOUND;\n case \"TYPE_MISMATCH\":\n return ErrorCode.TYPE_MISMATCH;\n case \"GENERAL\":\n default:\n return ErrorCode.GENERAL;\n }\n}\n","import type { EvaluationContext } from \"@openfeature/server-sdk\";\nimport type { Contexts, ContextValue } from \"@quonfig/node\";\n\n/**\n * Maps an OpenFeature flat EvaluationContext to Quonfig's nested Contexts format.\n *\n * Rules:\n * - `targetingKey` maps to the namespace+property specified by `targetingKeyMapping` (default: \"user.id\")\n * - Keys with a dot are split on the first dot: \"user.email\" -> namespace \"user\", key \"email\"\n * - Keys without a dot go to the default (empty-string) namespace: \"country\" -> { \"\": { country: ... } }\n * - Multi-dot keys split on first dot only: \"user.ip.address\" -> { user: { \"ip.address\": ... } }\n */\nexport function mapContext(\n ofContext: EvaluationContext,\n targetingKeyMapping = \"user.id\"\n): Contexts {\n const result: Record<string, Record<string, ContextValue>> = {};\n\n for (const [key, value] of Object.entries(ofContext)) {\n if (value === undefined) continue;\n\n // Cast to ContextValue -- OpenFeature allows arbitrary nesting but Quonfig\n // contexts accept primitives and string arrays. Callers should pass only\n // primitive or string[] values for keys they want evaluated.\n const ctxValue = value as ContextValue;\n\n if (key === \"targetingKey\") {\n const dotIdx = targetingKeyMapping.indexOf(\".\");\n const ns = dotIdx === -1 ? \"\" : targetingKeyMapping.slice(0, dotIdx);\n const prop = dotIdx === -1 ? targetingKeyMapping : targetingKeyMapping.slice(dotIdx + 1);\n result[ns] ??= {};\n result[ns][prop] = ctxValue;\n continue;\n }\n\n const dotIdx = key.indexOf(\".\");\n if (dotIdx === -1) {\n result[\"\"] ??= {};\n result[\"\"][key] = ctxValue;\n } else {\n const ns = key.slice(0, dotIdx);\n const prop = key.slice(dotIdx + 1);\n result[ns] ??= {};\n result[ns][prop] = ctxValue;\n }\n }\n\n return result;\n}\n","import { ErrorCode } from \"@openfeature/server-sdk\";\n\n/**\n * Maps a native SDK error to an OpenFeature ErrorCode.\n *\n * The native SDK throws Error instances with message strings. We map by inspecting\n * the lowercased message.\n */\nexport function toErrorCode(err: unknown): ErrorCode {\n const msg = err instanceof Error ? err.message.toLowerCase() : String(err).toLowerCase();\n\n if (\n msg.includes(\"not found\") ||\n msg.includes(\"flag not found\") ||\n msg.includes(\"no value found\") ||\n msg.includes(\"value found for key\")\n ) {\n return ErrorCode.FLAG_NOT_FOUND;\n }\n if (msg.includes(\"type mismatch\")) {\n return ErrorCode.TYPE_MISMATCH;\n }\n if (msg.includes(\"not initialized\") || msg.includes(\"provider not ready\")) {\n return ErrorCode.PROVIDER_NOT_READY;\n }\n return ErrorCode.GENERAL;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,wBAUO;AACP,kBAA2D;;;ACCpD,SAAS,WACd,WACA,sBAAsB,WACZ;AACV,QAAM,SAAuD,CAAC;AAE9D,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,SAAS,GAAG;AACpD,QAAI,UAAU,OAAW;AAKzB,UAAM,WAAW;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AAAA,QAClC,GAAG;AAAA,MACL;AAAA,IACF,KAAK;AACH,aAAO;AAAA,QACL,OAAO,QAAQ;AAAA,QACf,QAAQ,4CAA0B;AAAA,QAClC,GAAG;AAAA,MACL;AAAA,IACF,KAAK;AACH,aAAO;AAAA,QACL,OAAO;AAAA,QACP,QAAQ,4CAA0B;AAAA,QAClC,GAAG;AAAA,MACL;AAAA,IACF,KAAK;AACH,aAAO;AAAA,QACL,OAAO;AAAA,QACP,QAAQ,4CAA0B;AAAA,QAClC,WAAW,cAAc,QAAQ,SAAS;AAAA,QAC1C,cAAc,QAAQ;AAAA,QACtB,GAAG;AAAA,MACL;AAAA,EACJ;AACF;AAEA,SAAS,cAAc,MAA0D;AAC/E,UAAQ,MAAM;AAAA,IACZ,KAAK;AACH,aAAO,4BAAU;AAAA,IACnB,KAAK;AACH,aAAO,4BAAU;AAAA,IACnB,KAAK;AAAA,IACL;AACE,aAAO,4BAAU;AAAA,EACrB;AACF;;;AEhMA,IAAAC,qBAA0B;AAQnB,SAAS,YAAY,KAAyB;AACnD,QAAM,MAAM,eAAe,QAAQ,IAAI,QAAQ,YAAY,IAAI,OAAO,GAAG,EAAE,YAAY;AAEvF,MACE,IAAI,SAAS,WAAW,KACxB,IAAI,SAAS,gBAAgB,KAC7B,IAAI,SAAS,gBAAgB,KAC7B,IAAI,SAAS,qBAAqB,GAClC;AACA,WAAO,6BAAU;AAAA,EACnB;AACA,MAAI,IAAI,SAAS,eAAe,GAAG;AACjC,WAAO,6BAAU;AAAA,EACnB;AACA,MAAI,IAAI,SAAS,iBAAiB,KAAK,IAAI,SAAS,oBAAoB,GAAG;AACzE,WAAO,6BAAU;AAAA,EACnB;AACA,SAAO,6BAAU;AACnB;","names":["dotIdx","import_server_sdk"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/provider.ts","../src/context.ts","../src/errors.ts"],"sourcesContent":["export { QuonfigProvider } from \"./provider.js\";\nexport type { QuonfigProviderOptions } from \"./provider.js\";\nexport { mapContext } from \"./context.js\";\nexport { toErrorCode } from \"./errors.js\";\n","import {\n ErrorCode,\n EvaluationContext,\n JsonValue,\n Logger,\n OpenFeatureEventEmitter,\n Provider,\n ProviderEvents,\n ResolutionDetails,\n StandardResolutionReasons,\n} from \"@openfeature/server-sdk\";\nimport { EvaluationDetails, Quonfig, QuonfigOptions } from \"@quonfig/node\";\nimport { mapContext } from \"./context.js\";\n\nexport interface QuonfigProviderOptions extends Omit<QuonfigOptions, \"onConfigUpdate\"> {\n /**\n * Dot-notation path to map OpenFeature's `targetingKey` into Quonfig's nested context.\n * Defaults to \"user.id\".\n */\n targetingKeyMapping?: string;\n}\n\n/**\n * QuonfigProvider wraps the @quonfig/node native SDK and implements the\n * OpenFeature server-side Provider interface.\n *\n * Usage:\n * ```typescript\n * import { QuonfigProvider } from \"@quonfig/openfeature-node\";\n * import { OpenFeature } from \"@openfeature/server-sdk\";\n *\n * const provider = new QuonfigProvider({ sdkKey: \"qf_sk_...\" });\n * await OpenFeature.setProviderAndWait(provider);\n * const client = OpenFeature.getClient();\n * const enabled = await client.getBooleanValue(\"my-flag\", false);\n * ```\n */\nexport class QuonfigProvider implements Provider {\n readonly metadata = { name: \"quonfig\" } as const;\n readonly events = new OpenFeatureEventEmitter();\n readonly hooks = [];\n\n private readonly client: Quonfig;\n private readonly targetingKeyMapping: string;\n private closed = false;\n private initErrorTimer?: ReturnType<typeof setTimeout>;\n\n constructor(options: QuonfigProviderOptions) {\n this.targetingKeyMapping = options.targetingKeyMapping ?? \"user.id\";\n this.client = new Quonfig({\n ...options,\n onConfigUpdate: () => {\n this.events.emit(ProviderEvents.ConfigurationChanged, { flagsChanged: [] });\n },\n });\n }\n\n /**\n * Initialize the wrapped client. Status follows the client's `onInitFailure`\n * (design B.5), which you pass in the provider options with `initTimeout`:\n *\n * - `\"fail\"` (default): `init()` rejects, so this throws and the provider is\n * ERROR. The client is kept alive and retries in the background; on heal the\n * provider emits PROVIDER_READY.\n * - `\"wait\"`: blocks until the first config, so the provider is NOT_READY\n * throughout and READY when it resolves.\n * - `\"continue\"`: resolves on code defaults, then emits a non-fatal\n * PROVIDER_ERROR so the status is ERROR (evaluations still run and return\n * the caller default). On heal the provider emits PROVIDER_READY.\n */\n async initialize(_context?: EvaluationContext): Promise<void> {\n try {\n await this.client.init();\n } catch (err) {\n this.emitReadyOnHeal();\n throw err;\n }\n if (!this.client.isReady()) {\n // OpenFeature marks the provider READY once initialize() resolves, so\n // report the error after that has happened.\n this.initErrorTimer = setTimeout(() => {\n if (this.closed || this.client.isReady()) return;\n this.events.emit(ProviderEvents.Error, {\n message: \"[quonfig] no config loaded (onInitFailure=continue): serving code defaults\",\n errorCode: ErrorCode.PROVIDER_NOT_READY,\n });\n }, 0);\n this.emitReadyOnHeal();\n }\n }\n\n /** Emit PROVIDER_READY once the client's background retry loads config. */\n private emitReadyOnHeal(): void {\n this.client.waitForReady().then(\n () => {\n if (!this.closed) this.events.emit(ProviderEvents.Ready);\n },\n () => {} // closed before healing\n );\n }\n\n async shutdown(): Promise<void> {\n this.closed = true;\n clearTimeout(this.initErrorTimer);\n await this.client.close();\n }\n\n async resolveBooleanEvaluation(\n flagKey: string,\n defaultValue: boolean,\n context: EvaluationContext,\n _logger: Logger\n ): Promise<ResolutionDetails<boolean>> {\n const mappedCtx = mapContext(context, this.targetingKeyMapping);\n const details = this.client.getBoolDetails(flagKey, mappedCtx);\n return toResolutionDetails(details, defaultValue);\n }\n\n async resolveStringEvaluation(\n flagKey: string,\n defaultValue: string,\n context: EvaluationContext,\n _logger: Logger\n ): Promise<ResolutionDetails<string>> {\n const mappedCtx = mapContext(context, this.targetingKeyMapping);\n const details = this.client.getStringDetails(flagKey, mappedCtx);\n return toResolutionDetails(details, defaultValue);\n }\n\n async resolveNumberEvaluation(\n flagKey: string,\n defaultValue: number,\n context: EvaluationContext,\n _logger: Logger\n ): Promise<ResolutionDetails<number>> {\n const mappedCtx = mapContext(context, this.targetingKeyMapping);\n const details = this.client.getNumberDetails(flagKey, mappedCtx);\n return toResolutionDetails(details, defaultValue);\n }\n\n async resolveObjectEvaluation<T extends JsonValue>(\n flagKey: string,\n defaultValue: T,\n context: EvaluationContext,\n _logger: Logger\n ): Promise<ResolutionDetails<T>> {\n const mappedCtx = mapContext(context, this.targetingKeyMapping);\n // Try string_list first (returns string[]), fall back to JSON.\n const listDetails = this.client.getStringListDetails(flagKey, mappedCtx);\n if (\n listDetails.reason === \"STATIC\" ||\n listDetails.reason === \"TARGETING_MATCH\" ||\n listDetails.reason === \"SPLIT\"\n ) {\n return toResolutionDetails(\n listDetails as EvaluationDetails<unknown> as EvaluationDetails<T>,\n defaultValue\n );\n }\n const jsonDetails = this.client.getJSONDetails(flagKey, mappedCtx);\n return toResolutionDetails(jsonDetails as EvaluationDetails<T>, defaultValue);\n }\n\n /**\n * Escape hatch: access the underlying @quonfig/node client for native-only features\n * (shouldLog, keys, rawConfig, etc.)\n */\n getClient(): Quonfig {\n return this.client;\n }\n}\n\n/**\n * Translate a Quonfig EvaluationDetails<T> into an OpenFeature ResolutionDetails<T>.\n *\n * Reason mapping (from the brief):\n * STATIC → StandardResolutionReasons.STATIC\n * TARGETING_MATCH → StandardResolutionReasons.TARGETING_MATCH\n * SPLIT → StandardResolutionReasons.SPLIT\n * DEFAULT → defaultValue + StandardResolutionReasons.DEFAULT\n * ERROR → defaultValue + ERROR + errorCode (FLAG_NOT_FOUND / TYPE_MISMATCH /\n * PROVIDER_NOT_READY / GENERAL)\n */\nfunction toResolutionDetails<T>(\n details: EvaluationDetails<T>,\n defaultValue: T\n): ResolutionDetails<T> {\n const common = {\n variant: details.variant,\n flagMetadata: details.flagMetadata as ResolutionDetails<T>[\"flagMetadata\"],\n };\n switch (details.reason) {\n case \"STATIC\":\n return {\n value: details.value as T,\n reason: StandardResolutionReasons.STATIC,\n ...common,\n };\n case \"TARGETING_MATCH\":\n return {\n value: details.value as T,\n reason: StandardResolutionReasons.TARGETING_MATCH,\n ...common,\n };\n case \"SPLIT\":\n return {\n value: details.value as T,\n reason: StandardResolutionReasons.SPLIT,\n ...common,\n };\n case \"DEFAULT\":\n return {\n value: defaultValue,\n reason: StandardResolutionReasons.DEFAULT,\n ...common,\n };\n case \"ERROR\":\n return {\n value: defaultValue,\n reason: StandardResolutionReasons.ERROR,\n errorCode: toOFErrorCode(details.errorCode),\n errorMessage: details.errorMessage,\n ...common,\n };\n }\n}\n\nfunction toOFErrorCode(code: EvaluationDetails<unknown>[\"errorCode\"]): ErrorCode {\n switch (code) {\n case \"FLAG_NOT_FOUND\":\n return ErrorCode.FLAG_NOT_FOUND;\n case \"TYPE_MISMATCH\":\n return ErrorCode.TYPE_MISMATCH;\n case \"PROVIDER_NOT_READY\":\n return ErrorCode.PROVIDER_NOT_READY;\n case \"GENERAL\":\n default:\n return ErrorCode.GENERAL;\n }\n}\n","import type { EvaluationContext } from \"@openfeature/server-sdk\";\nimport type { Contexts, ContextValue } from \"@quonfig/node\";\n\n/**\n * Maps an OpenFeature flat EvaluationContext to Quonfig's nested Contexts format.\n *\n * Rules:\n * - `targetingKey` maps to the namespace+property specified by `targetingKeyMapping` (default: \"user.id\")\n * - Keys with a dot are split on the first dot: \"user.email\" -> namespace \"user\", key \"email\"\n * - Keys without a dot go to the default (empty-string) namespace: \"country\" -> { \"\": { country: ... } }\n * - Multi-dot keys split on first dot only: \"user.ip.address\" -> { user: { \"ip.address\": ... } }\n */\nexport function mapContext(\n ofContext: EvaluationContext,\n targetingKeyMapping = \"user.id\"\n): Contexts {\n const result: Record<string, Record<string, ContextValue>> = {};\n\n for (const [key, value] of Object.entries(ofContext)) {\n if (value === undefined) continue;\n\n // Cast to ContextValue -- OpenFeature allows arbitrary nesting but Quonfig\n // contexts accept primitives and string arrays. Callers should pass only\n // primitive or string[] values for keys they want evaluated.\n const ctxValue = value as ContextValue;\n\n if (key === \"targetingKey\") {\n const dotIdx = targetingKeyMapping.indexOf(\".\");\n const ns = dotIdx === -1 ? \"\" : targetingKeyMapping.slice(0, dotIdx);\n const prop = dotIdx === -1 ? targetingKeyMapping : targetingKeyMapping.slice(dotIdx + 1);\n result[ns] ??= {};\n result[ns][prop] = ctxValue;\n continue;\n }\n\n const dotIdx = key.indexOf(\".\");\n if (dotIdx === -1) {\n result[\"\"] ??= {};\n result[\"\"][key] = ctxValue;\n } else {\n const ns = key.slice(0, dotIdx);\n const prop = key.slice(dotIdx + 1);\n result[ns] ??= {};\n result[ns][prop] = ctxValue;\n }\n }\n\n return result;\n}\n","import { ErrorCode } from \"@openfeature/server-sdk\";\n\n/**\n * Maps a native SDK error to an OpenFeature ErrorCode.\n *\n * The native SDK throws Error instances with message strings. We map by inspecting\n * the lowercased message.\n */\nexport function toErrorCode(err: unknown): ErrorCode {\n const msg = err instanceof Error ? err.message.toLowerCase() : String(err).toLowerCase();\n\n if (\n msg.includes(\"not found\") ||\n msg.includes(\"flag not found\") ||\n msg.includes(\"no value found\") ||\n msg.includes(\"value found for key\")\n ) {\n return ErrorCode.FLAG_NOT_FOUND;\n }\n if (msg.includes(\"type mismatch\")) {\n return ErrorCode.TYPE_MISMATCH;\n }\n if (msg.includes(\"not initialized\") || msg.includes(\"provider not ready\")) {\n return ErrorCode.PROVIDER_NOT_READY;\n }\n return ErrorCode.GENERAL;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,wBAUO;AACP,kBAA2D;;;ACCpD,SAAS,WACd,WACA,sBAAsB,WACZ;AACV,QAAM,SAAuD,CAAC;AAE9D,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,SAAS,GAAG;AACpD,QAAI,UAAU,OAAW;AAKzB,UAAM,WAAW;AAEjB,QAAI,QAAQ,gBAAgB;AAC1B,YAAMA,UAAS,oBAAoB,QAAQ,GAAG;AAC9C,YAAM,KAAKA,YAAW,KAAK,KAAK,oBAAoB,MAAM,GAAGA,OAAM;AACnE,YAAM,OAAOA,YAAW,KAAK,sBAAsB,oBAAoB,MAAMA,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,QAAQ,YAAY,IAAI,OAAO,GAAG,EAAE,YAAY;AAEvF,MACE,IAAI,SAAS,WAAW,KACxB,IAAI,SAAS,gBAAgB,KAC7B,IAAI,SAAS,gBAAgB,KAC7B,IAAI,SAAS,qBAAqB,GAClC;AACA,WAAO,6BAAU;AAAA,EACnB;AACA,MAAI,IAAI,SAAS,eAAe,GAAG;AACjC,WAAO,6BAAU;AAAA,EACnB;AACA,MAAI,IAAI,SAAS,iBAAiB,KAAK,IAAI,SAAS,oBAAoB,GAAG;AACzE,WAAO,6BAAU;AAAA,EACnB;AACA,SAAO,6BAAU;AACnB;","names":["dotIdx","import_server_sdk"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -31,8 +31,25 @@ declare class QuonfigProvider implements Provider {
|
|
|
31
31
|
readonly hooks: never[];
|
|
32
32
|
private readonly client;
|
|
33
33
|
private readonly targetingKeyMapping;
|
|
34
|
+
private closed;
|
|
35
|
+
private initErrorTimer?;
|
|
34
36
|
constructor(options: QuonfigProviderOptions);
|
|
37
|
+
/**
|
|
38
|
+
* Initialize the wrapped client. Status follows the client's `onInitFailure`
|
|
39
|
+
* (design B.5), which you pass in the provider options with `initTimeout`:
|
|
40
|
+
*
|
|
41
|
+
* - `"fail"` (default): `init()` rejects, so this throws and the provider is
|
|
42
|
+
* ERROR. The client is kept alive and retries in the background; on heal the
|
|
43
|
+
* provider emits PROVIDER_READY.
|
|
44
|
+
* - `"wait"`: blocks until the first config, so the provider is NOT_READY
|
|
45
|
+
* throughout and READY when it resolves.
|
|
46
|
+
* - `"continue"`: resolves on code defaults, then emits a non-fatal
|
|
47
|
+
* PROVIDER_ERROR so the status is ERROR (evaluations still run and return
|
|
48
|
+
* the caller default). On heal the provider emits PROVIDER_READY.
|
|
49
|
+
*/
|
|
35
50
|
initialize(_context?: EvaluationContext): Promise<void>;
|
|
51
|
+
/** Emit PROVIDER_READY once the client's background retry loads config. */
|
|
52
|
+
private emitReadyOnHeal;
|
|
36
53
|
shutdown(): Promise<void>;
|
|
37
54
|
resolveBooleanEvaluation(flagKey: string, defaultValue: boolean, context: EvaluationContext, _logger: Logger): Promise<ResolutionDetails<boolean>>;
|
|
38
55
|
resolveStringEvaluation(flagKey: string, defaultValue: string, context: EvaluationContext, _logger: Logger): Promise<ResolutionDetails<string>>;
|
package/dist/index.d.ts
CHANGED
|
@@ -31,8 +31,25 @@ declare class QuonfigProvider implements Provider {
|
|
|
31
31
|
readonly hooks: never[];
|
|
32
32
|
private readonly client;
|
|
33
33
|
private readonly targetingKeyMapping;
|
|
34
|
+
private closed;
|
|
35
|
+
private initErrorTimer?;
|
|
34
36
|
constructor(options: QuonfigProviderOptions);
|
|
37
|
+
/**
|
|
38
|
+
* Initialize the wrapped client. Status follows the client's `onInitFailure`
|
|
39
|
+
* (design B.5), which you pass in the provider options with `initTimeout`:
|
|
40
|
+
*
|
|
41
|
+
* - `"fail"` (default): `init()` rejects, so this throws and the provider is
|
|
42
|
+
* ERROR. The client is kept alive and retries in the background; on heal the
|
|
43
|
+
* provider emits PROVIDER_READY.
|
|
44
|
+
* - `"wait"`: blocks until the first config, so the provider is NOT_READY
|
|
45
|
+
* throughout and READY when it resolves.
|
|
46
|
+
* - `"continue"`: resolves on code defaults, then emits a non-fatal
|
|
47
|
+
* PROVIDER_ERROR so the status is ERROR (evaluations still run and return
|
|
48
|
+
* the caller default). On heal the provider emits PROVIDER_READY.
|
|
49
|
+
*/
|
|
35
50
|
initialize(_context?: EvaluationContext): Promise<void>;
|
|
51
|
+
/** Emit PROVIDER_READY once the client's background retry loads config. */
|
|
52
|
+
private emitReadyOnHeal;
|
|
36
53
|
shutdown(): Promise<void>;
|
|
37
54
|
resolveBooleanEvaluation(flagKey: string, defaultValue: boolean, context: EvaluationContext, _logger: Logger): Promise<ResolutionDetails<boolean>>;
|
|
38
55
|
resolveStringEvaluation(flagKey: string, defaultValue: string, context: EvaluationContext, _logger: Logger): Promise<ResolutionDetails<string>>;
|
package/dist/index.js
CHANGED
|
@@ -41,6 +41,7 @@ var QuonfigProvider = class {
|
|
|
41
41
|
this.metadata = { name: "quonfig" };
|
|
42
42
|
this.events = new OpenFeatureEventEmitter();
|
|
43
43
|
this.hooks = [];
|
|
44
|
+
this.closed = false;
|
|
44
45
|
this.targetingKeyMapping = options.targetingKeyMapping ?? "user.id";
|
|
45
46
|
this.client = new Quonfig({
|
|
46
47
|
...options,
|
|
@@ -49,10 +50,51 @@ var QuonfigProvider = class {
|
|
|
49
50
|
}
|
|
50
51
|
});
|
|
51
52
|
}
|
|
53
|
+
/**
|
|
54
|
+
* Initialize the wrapped client. Status follows the client's `onInitFailure`
|
|
55
|
+
* (design B.5), which you pass in the provider options with `initTimeout`:
|
|
56
|
+
*
|
|
57
|
+
* - `"fail"` (default): `init()` rejects, so this throws and the provider is
|
|
58
|
+
* ERROR. The client is kept alive and retries in the background; on heal the
|
|
59
|
+
* provider emits PROVIDER_READY.
|
|
60
|
+
* - `"wait"`: blocks until the first config, so the provider is NOT_READY
|
|
61
|
+
* throughout and READY when it resolves.
|
|
62
|
+
* - `"continue"`: resolves on code defaults, then emits a non-fatal
|
|
63
|
+
* PROVIDER_ERROR so the status is ERROR (evaluations still run and return
|
|
64
|
+
* the caller default). On heal the provider emits PROVIDER_READY.
|
|
65
|
+
*/
|
|
52
66
|
async initialize(_context) {
|
|
53
|
-
|
|
67
|
+
try {
|
|
68
|
+
await this.client.init();
|
|
69
|
+
} catch (err) {
|
|
70
|
+
this.emitReadyOnHeal();
|
|
71
|
+
throw err;
|
|
72
|
+
}
|
|
73
|
+
if (!this.client.isReady()) {
|
|
74
|
+
this.initErrorTimer = setTimeout(() => {
|
|
75
|
+
if (this.closed || this.client.isReady()) return;
|
|
76
|
+
this.events.emit(ProviderEvents.Error, {
|
|
77
|
+
message: "[quonfig] no config loaded (onInitFailure=continue): serving code defaults",
|
|
78
|
+
errorCode: ErrorCode.PROVIDER_NOT_READY
|
|
79
|
+
});
|
|
80
|
+
}, 0);
|
|
81
|
+
this.emitReadyOnHeal();
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
/** Emit PROVIDER_READY once the client's background retry loads config. */
|
|
85
|
+
emitReadyOnHeal() {
|
|
86
|
+
this.client.waitForReady().then(
|
|
87
|
+
() => {
|
|
88
|
+
if (!this.closed) this.events.emit(ProviderEvents.Ready);
|
|
89
|
+
},
|
|
90
|
+
() => {
|
|
91
|
+
}
|
|
92
|
+
// closed before healing
|
|
93
|
+
);
|
|
54
94
|
}
|
|
55
95
|
async shutdown() {
|
|
96
|
+
this.closed = true;
|
|
97
|
+
clearTimeout(this.initErrorTimer);
|
|
56
98
|
await this.client.close();
|
|
57
99
|
}
|
|
58
100
|
async resolveBooleanEvaluation(flagKey, defaultValue, context, _logger) {
|
|
@@ -136,6 +178,8 @@ function toOFErrorCode(code) {
|
|
|
136
178
|
return ErrorCode.FLAG_NOT_FOUND;
|
|
137
179
|
case "TYPE_MISMATCH":
|
|
138
180
|
return ErrorCode.TYPE_MISMATCH;
|
|
181
|
+
case "PROVIDER_NOT_READY":
|
|
182
|
+
return ErrorCode.PROVIDER_NOT_READY;
|
|
139
183
|
case "GENERAL":
|
|
140
184
|
default:
|
|
141
185
|
return ErrorCode.GENERAL;
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/provider.ts","../src/context.ts","../src/errors.ts"],"sourcesContent":["import {\n ErrorCode,\n EvaluationContext,\n JsonValue,\n Logger,\n OpenFeatureEventEmitter,\n Provider,\n ProviderEvents,\n ResolutionDetails,\n StandardResolutionReasons,\n} from \"@openfeature/server-sdk\";\nimport { EvaluationDetails, Quonfig, QuonfigOptions } from \"@quonfig/node\";\nimport { mapContext } from \"./context.js\";\n\nexport interface QuonfigProviderOptions extends Omit<QuonfigOptions, \"onConfigUpdate\"> {\n /**\n * Dot-notation path to map OpenFeature's `targetingKey` into Quonfig's nested context.\n * Defaults to \"user.id\".\n */\n targetingKeyMapping?: string;\n}\n\n/**\n * QuonfigProvider wraps the @quonfig/node native SDK and implements the\n * OpenFeature server-side Provider interface.\n *\n * Usage:\n * ```typescript\n * import { QuonfigProvider } from \"@quonfig/openfeature-node\";\n * import { OpenFeature } from \"@openfeature/server-sdk\";\n *\n * const provider = new QuonfigProvider({ sdkKey: \"qf_sk_...\" });\n * await OpenFeature.setProviderAndWait(provider);\n * const client = OpenFeature.getClient();\n * const enabled = await client.getBooleanValue(\"my-flag\", false);\n * ```\n */\nexport class QuonfigProvider implements Provider {\n readonly metadata = { name: \"quonfig\" } as const;\n readonly events = new OpenFeatureEventEmitter();\n readonly hooks = [];\n\n private readonly client: Quonfig;\n private readonly targetingKeyMapping: string;\n\n constructor(options: QuonfigProviderOptions) {\n this.targetingKeyMapping = options.targetingKeyMapping ?? \"user.id\";\n this.client = new Quonfig({\n ...options,\n onConfigUpdate: () => {\n this.events.emit(ProviderEvents.ConfigurationChanged, { flagsChanged: [] });\n },\n });\n }\n\n async initialize(_context?: EvaluationContext): Promise<void> {\n await this.client.init();\n }\n\n async shutdown(): Promise<void> {\n await this.client.close();\n }\n\n async resolveBooleanEvaluation(\n flagKey: string,\n defaultValue: boolean,\n context: EvaluationContext,\n _logger: Logger\n ): Promise<ResolutionDetails<boolean>> {\n const mappedCtx = mapContext(context, this.targetingKeyMapping);\n const details = this.client.getBoolDetails(flagKey, mappedCtx);\n return toResolutionDetails(details, defaultValue);\n }\n\n async resolveStringEvaluation(\n flagKey: string,\n defaultValue: string,\n context: EvaluationContext,\n _logger: Logger\n ): Promise<ResolutionDetails<string>> {\n const mappedCtx = mapContext(context, this.targetingKeyMapping);\n const details = this.client.getStringDetails(flagKey, mappedCtx);\n return toResolutionDetails(details, defaultValue);\n }\n\n async resolveNumberEvaluation(\n flagKey: string,\n defaultValue: number,\n context: EvaluationContext,\n _logger: Logger\n ): Promise<ResolutionDetails<number>> {\n const mappedCtx = mapContext(context, this.targetingKeyMapping);\n const details = this.client.getNumberDetails(flagKey, mappedCtx);\n return toResolutionDetails(details, defaultValue);\n }\n\n async resolveObjectEvaluation<T extends JsonValue>(\n flagKey: string,\n defaultValue: T,\n context: EvaluationContext,\n _logger: Logger\n ): Promise<ResolutionDetails<T>> {\n const mappedCtx = mapContext(context, this.targetingKeyMapping);\n // Try string_list first (returns string[]), fall back to JSON.\n const listDetails = this.client.getStringListDetails(flagKey, mappedCtx);\n if (\n listDetails.reason === \"STATIC\" ||\n listDetails.reason === \"TARGETING_MATCH\" ||\n listDetails.reason === \"SPLIT\"\n ) {\n return toResolutionDetails(\n listDetails as EvaluationDetails<unknown> as EvaluationDetails<T>,\n defaultValue\n );\n }\n const jsonDetails = this.client.getJSONDetails(flagKey, mappedCtx);\n return toResolutionDetails(jsonDetails as EvaluationDetails<T>, defaultValue);\n }\n\n /**\n * Escape hatch: access the underlying @quonfig/node client for native-only features\n * (shouldLog, keys, rawConfig, etc.)\n */\n getClient(): Quonfig {\n return this.client;\n }\n}\n\n/**\n * Translate a Quonfig EvaluationDetails<T> into an OpenFeature ResolutionDetails<T>.\n *\n * Reason mapping (from the brief):\n * STATIC → StandardResolutionReasons.STATIC\n * TARGETING_MATCH → StandardResolutionReasons.TARGETING_MATCH\n * SPLIT → StandardResolutionReasons.SPLIT\n * DEFAULT → defaultValue + StandardResolutionReasons.DEFAULT\n * ERROR → defaultValue + ERROR + errorCode (FLAG_NOT_FOUND / TYPE_MISMATCH / GENERAL)\n */\nfunction toResolutionDetails<T>(\n details: EvaluationDetails<T>,\n defaultValue: T\n): ResolutionDetails<T> {\n const common = {\n variant: details.variant,\n flagMetadata: details.flagMetadata as ResolutionDetails<T>[\"flagMetadata\"],\n };\n switch (details.reason) {\n case \"STATIC\":\n return {\n value: details.value as T,\n reason: StandardResolutionReasons.STATIC,\n ...common,\n };\n case \"TARGETING_MATCH\":\n return {\n value: details.value as T,\n reason: StandardResolutionReasons.TARGETING_MATCH,\n ...common,\n };\n case \"SPLIT\":\n return {\n value: details.value as T,\n reason: StandardResolutionReasons.SPLIT,\n ...common,\n };\n case \"DEFAULT\":\n return {\n value: defaultValue,\n reason: StandardResolutionReasons.DEFAULT,\n ...common,\n };\n case \"ERROR\":\n return {\n value: defaultValue,\n reason: StandardResolutionReasons.ERROR,\n errorCode: toOFErrorCode(details.errorCode),\n errorMessage: details.errorMessage,\n ...common,\n };\n }\n}\n\nfunction toOFErrorCode(code: EvaluationDetails<unknown>[\"errorCode\"]): ErrorCode {\n switch (code) {\n case \"FLAG_NOT_FOUND\":\n return ErrorCode.FLAG_NOT_FOUND;\n case \"TYPE_MISMATCH\":\n return ErrorCode.TYPE_MISMATCH;\n case \"GENERAL\":\n default:\n return ErrorCode.GENERAL;\n }\n}\n","import type { EvaluationContext } from \"@openfeature/server-sdk\";\nimport type { Contexts, ContextValue } from \"@quonfig/node\";\n\n/**\n * Maps an OpenFeature flat EvaluationContext to Quonfig's nested Contexts format.\n *\n * Rules:\n * - `targetingKey` maps to the namespace+property specified by `targetingKeyMapping` (default: \"user.id\")\n * - Keys with a dot are split on the first dot: \"user.email\" -> namespace \"user\", key \"email\"\n * - Keys without a dot go to the default (empty-string) namespace: \"country\" -> { \"\": { country: ... } }\n * - Multi-dot keys split on first dot only: \"user.ip.address\" -> { user: { \"ip.address\": ... } }\n */\nexport function mapContext(\n ofContext: EvaluationContext,\n targetingKeyMapping = \"user.id\"\n): Contexts {\n const result: Record<string, Record<string, ContextValue>> = {};\n\n for (const [key, value] of Object.entries(ofContext)) {\n if (value === undefined) continue;\n\n // Cast to ContextValue -- OpenFeature allows arbitrary nesting but Quonfig\n // contexts accept primitives and string arrays. Callers should pass only\n // primitive or string[] values for keys they want evaluated.\n const ctxValue = value as ContextValue;\n\n if (key === \"targetingKey\") {\n const dotIdx = targetingKeyMapping.indexOf(\".\");\n const ns = dotIdx === -1 ? \"\" : targetingKeyMapping.slice(0, dotIdx);\n const prop = dotIdx === -1 ? targetingKeyMapping : targetingKeyMapping.slice(dotIdx + 1);\n result[ns] ??= {};\n result[ns][prop] = ctxValue;\n continue;\n }\n\n const dotIdx = key.indexOf(\".\");\n if (dotIdx === -1) {\n result[\"\"] ??= {};\n result[\"\"][key] = ctxValue;\n } else {\n const ns = key.slice(0, dotIdx);\n const prop = key.slice(dotIdx + 1);\n result[ns] ??= {};\n result[ns][prop] = ctxValue;\n }\n }\n\n return result;\n}\n","import { ErrorCode } from \"@openfeature/server-sdk\";\n\n/**\n * Maps a native SDK error to an OpenFeature ErrorCode.\n *\n * The native SDK throws Error instances with message strings. We map by inspecting\n * the lowercased message.\n */\nexport function toErrorCode(err: unknown): ErrorCode {\n const msg = err instanceof Error ? err.message.toLowerCase() : String(err).toLowerCase();\n\n if (\n msg.includes(\"not found\") ||\n msg.includes(\"flag not found\") ||\n msg.includes(\"no value found\") ||\n msg.includes(\"value found for key\")\n ) {\n return ErrorCode.FLAG_NOT_FOUND;\n }\n if (msg.includes(\"type mismatch\")) {\n return ErrorCode.TYPE_MISMATCH;\n }\n if (msg.includes(\"not initialized\") || msg.includes(\"provider not ready\")) {\n return ErrorCode.PROVIDER_NOT_READY;\n }\n return ErrorCode.GENERAL;\n}\n"],"mappings":";AAAA;AAAA,EACE;AAAA,EAIA;AAAA,EAEA;AAAA,EAEA;AAAA,OACK;AACP,SAA4B,eAA+B;;;ACCpD,SAAS,WACd,WACA,sBAAsB,WACZ;AACV,QAAM,SAAuD,CAAC;AAE9D,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,SAAS,GAAG;AACpD,QAAI,UAAU,OAAW;AAKzB,UAAM,WAAW;AAEjB,QAAI,QAAQ,gBAAgB;AAC1B,YAAMA,UAAS,oBAAoB,QAAQ,GAAG;AAC9C,YAAM,KAAKA,YAAW,KAAK,KAAK,oBAAoB,MAAM,GAAGA,OAAM;AACnE,YAAM,OAAOA,YAAW,KAAK,sBAAsB,oBAAoB,MAAMA,UAAS,CAAC;AACvF,aAAO,EAAE,MAAM,CAAC;AAChB,aAAO,EAAE,EAAE,IAAI,IAAI;AACnB;AAAA,IACF;AAEA,UAAM,SAAS,IAAI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QAClC,WAAW,cAAc,QAAQ,SAAS;AAAA,QAC1C,cAAc,QAAQ;AAAA,QACtB,GAAG;AAAA,MACL;AAAA,EACJ;AACF;AAEA,SAAS,cAAc,MAA0D;AAC/E,UAAQ,MAAM;AAAA,IACZ,KAAK;AACH,aAAO,UAAU;AAAA,IACnB,KAAK;AACH,aAAO,UAAU;AAAA,IACnB,KAAK;AAAA,IACL;AACE,aAAO,UAAU;AAAA,EACrB;AACF;;;AEhMA,SAAS,aAAAC,kBAAiB;AAQnB,SAAS,YAAY,KAAyB;AACnD,QAAM,MAAM,eAAe,QAAQ,IAAI,QAAQ,YAAY,IAAI,OAAO,GAAG,EAAE,YAAY;AAEvF,MACE,IAAI,SAAS,WAAW,KACxB,IAAI,SAAS,gBAAgB,KAC7B,IAAI,SAAS,gBAAgB,KAC7B,IAAI,SAAS,qBAAqB,GAClC;AACA,WAAOA,WAAU;AAAA,EACnB;AACA,MAAI,IAAI,SAAS,eAAe,GAAG;AACjC,WAAOA,WAAU;AAAA,EACnB;AACA,MAAI,IAAI,SAAS,iBAAiB,KAAK,IAAI,SAAS,oBAAoB,GAAG;AACzE,WAAOA,WAAU;AAAA,EACnB;AACA,SAAOA,WAAU;AACnB;","names":["dotIdx","ErrorCode"]}
|
|
1
|
+
{"version":3,"sources":["../src/provider.ts","../src/context.ts","../src/errors.ts"],"sourcesContent":["import {\n ErrorCode,\n EvaluationContext,\n JsonValue,\n Logger,\n OpenFeatureEventEmitter,\n Provider,\n ProviderEvents,\n ResolutionDetails,\n StandardResolutionReasons,\n} from \"@openfeature/server-sdk\";\nimport { EvaluationDetails, Quonfig, QuonfigOptions } from \"@quonfig/node\";\nimport { mapContext } from \"./context.js\";\n\nexport interface QuonfigProviderOptions extends Omit<QuonfigOptions, \"onConfigUpdate\"> {\n /**\n * Dot-notation path to map OpenFeature's `targetingKey` into Quonfig's nested context.\n * Defaults to \"user.id\".\n */\n targetingKeyMapping?: string;\n}\n\n/**\n * QuonfigProvider wraps the @quonfig/node native SDK and implements the\n * OpenFeature server-side Provider interface.\n *\n * Usage:\n * ```typescript\n * import { QuonfigProvider } from \"@quonfig/openfeature-node\";\n * import { OpenFeature } from \"@openfeature/server-sdk\";\n *\n * const provider = new QuonfigProvider({ sdkKey: \"qf_sk_...\" });\n * await OpenFeature.setProviderAndWait(provider);\n * const client = OpenFeature.getClient();\n * const enabled = await client.getBooleanValue(\"my-flag\", false);\n * ```\n */\nexport class QuonfigProvider implements Provider {\n readonly metadata = { name: \"quonfig\" } as const;\n readonly events = new OpenFeatureEventEmitter();\n readonly hooks = [];\n\n private readonly client: Quonfig;\n private readonly targetingKeyMapping: string;\n private closed = false;\n private initErrorTimer?: ReturnType<typeof setTimeout>;\n\n constructor(options: QuonfigProviderOptions) {\n this.targetingKeyMapping = options.targetingKeyMapping ?? \"user.id\";\n this.client = new Quonfig({\n ...options,\n onConfigUpdate: () => {\n this.events.emit(ProviderEvents.ConfigurationChanged, { flagsChanged: [] });\n },\n });\n }\n\n /**\n * Initialize the wrapped client. Status follows the client's `onInitFailure`\n * (design B.5), which you pass in the provider options with `initTimeout`:\n *\n * - `\"fail\"` (default): `init()` rejects, so this throws and the provider is\n * ERROR. The client is kept alive and retries in the background; on heal the\n * provider emits PROVIDER_READY.\n * - `\"wait\"`: blocks until the first config, so the provider is NOT_READY\n * throughout and READY when it resolves.\n * - `\"continue\"`: resolves on code defaults, then emits a non-fatal\n * PROVIDER_ERROR so the status is ERROR (evaluations still run and return\n * the caller default). On heal the provider emits PROVIDER_READY.\n */\n async initialize(_context?: EvaluationContext): Promise<void> {\n try {\n await this.client.init();\n } catch (err) {\n this.emitReadyOnHeal();\n throw err;\n }\n if (!this.client.isReady()) {\n // OpenFeature marks the provider READY once initialize() resolves, so\n // report the error after that has happened.\n this.initErrorTimer = setTimeout(() => {\n if (this.closed || this.client.isReady()) return;\n this.events.emit(ProviderEvents.Error, {\n message: \"[quonfig] no config loaded (onInitFailure=continue): serving code defaults\",\n errorCode: ErrorCode.PROVIDER_NOT_READY,\n });\n }, 0);\n this.emitReadyOnHeal();\n }\n }\n\n /** Emit PROVIDER_READY once the client's background retry loads config. */\n private emitReadyOnHeal(): void {\n this.client.waitForReady().then(\n () => {\n if (!this.closed) this.events.emit(ProviderEvents.Ready);\n },\n () => {} // closed before healing\n );\n }\n\n async shutdown(): Promise<void> {\n this.closed = true;\n clearTimeout(this.initErrorTimer);\n await this.client.close();\n }\n\n async resolveBooleanEvaluation(\n flagKey: string,\n defaultValue: boolean,\n context: EvaluationContext,\n _logger: Logger\n ): Promise<ResolutionDetails<boolean>> {\n const mappedCtx = mapContext(context, this.targetingKeyMapping);\n const details = this.client.getBoolDetails(flagKey, mappedCtx);\n return toResolutionDetails(details, defaultValue);\n }\n\n async resolveStringEvaluation(\n flagKey: string,\n defaultValue: string,\n context: EvaluationContext,\n _logger: Logger\n ): Promise<ResolutionDetails<string>> {\n const mappedCtx = mapContext(context, this.targetingKeyMapping);\n const details = this.client.getStringDetails(flagKey, mappedCtx);\n return toResolutionDetails(details, defaultValue);\n }\n\n async resolveNumberEvaluation(\n flagKey: string,\n defaultValue: number,\n context: EvaluationContext,\n _logger: Logger\n ): Promise<ResolutionDetails<number>> {\n const mappedCtx = mapContext(context, this.targetingKeyMapping);\n const details = this.client.getNumberDetails(flagKey, mappedCtx);\n return toResolutionDetails(details, defaultValue);\n }\n\n async resolveObjectEvaluation<T extends JsonValue>(\n flagKey: string,\n defaultValue: T,\n context: EvaluationContext,\n _logger: Logger\n ): Promise<ResolutionDetails<T>> {\n const mappedCtx = mapContext(context, this.targetingKeyMapping);\n // Try string_list first (returns string[]), fall back to JSON.\n const listDetails = this.client.getStringListDetails(flagKey, mappedCtx);\n if (\n listDetails.reason === \"STATIC\" ||\n listDetails.reason === \"TARGETING_MATCH\" ||\n listDetails.reason === \"SPLIT\"\n ) {\n return toResolutionDetails(\n listDetails as EvaluationDetails<unknown> as EvaluationDetails<T>,\n defaultValue\n );\n }\n const jsonDetails = this.client.getJSONDetails(flagKey, mappedCtx);\n return toResolutionDetails(jsonDetails as EvaluationDetails<T>, defaultValue);\n }\n\n /**\n * Escape hatch: access the underlying @quonfig/node client for native-only features\n * (shouldLog, keys, rawConfig, etc.)\n */\n getClient(): Quonfig {\n return this.client;\n }\n}\n\n/**\n * Translate a Quonfig EvaluationDetails<T> into an OpenFeature ResolutionDetails<T>.\n *\n * Reason mapping (from the brief):\n * STATIC → StandardResolutionReasons.STATIC\n * TARGETING_MATCH → StandardResolutionReasons.TARGETING_MATCH\n * SPLIT → StandardResolutionReasons.SPLIT\n * DEFAULT → defaultValue + StandardResolutionReasons.DEFAULT\n * ERROR → defaultValue + ERROR + errorCode (FLAG_NOT_FOUND / TYPE_MISMATCH /\n * PROVIDER_NOT_READY / GENERAL)\n */\nfunction toResolutionDetails<T>(\n details: EvaluationDetails<T>,\n defaultValue: T\n): ResolutionDetails<T> {\n const common = {\n variant: details.variant,\n flagMetadata: details.flagMetadata as ResolutionDetails<T>[\"flagMetadata\"],\n };\n switch (details.reason) {\n case \"STATIC\":\n return {\n value: details.value as T,\n reason: StandardResolutionReasons.STATIC,\n ...common,\n };\n case \"TARGETING_MATCH\":\n return {\n value: details.value as T,\n reason: StandardResolutionReasons.TARGETING_MATCH,\n ...common,\n };\n case \"SPLIT\":\n return {\n value: details.value as T,\n reason: StandardResolutionReasons.SPLIT,\n ...common,\n };\n case \"DEFAULT\":\n return {\n value: defaultValue,\n reason: StandardResolutionReasons.DEFAULT,\n ...common,\n };\n case \"ERROR\":\n return {\n value: defaultValue,\n reason: StandardResolutionReasons.ERROR,\n errorCode: toOFErrorCode(details.errorCode),\n errorMessage: details.errorMessage,\n ...common,\n };\n }\n}\n\nfunction toOFErrorCode(code: EvaluationDetails<unknown>[\"errorCode\"]): ErrorCode {\n switch (code) {\n case \"FLAG_NOT_FOUND\":\n return ErrorCode.FLAG_NOT_FOUND;\n case \"TYPE_MISMATCH\":\n return ErrorCode.TYPE_MISMATCH;\n case \"PROVIDER_NOT_READY\":\n return ErrorCode.PROVIDER_NOT_READY;\n case \"GENERAL\":\n default:\n return ErrorCode.GENERAL;\n }\n}\n","import type { EvaluationContext } from \"@openfeature/server-sdk\";\nimport type { Contexts, ContextValue } from \"@quonfig/node\";\n\n/**\n * Maps an OpenFeature flat EvaluationContext to Quonfig's nested Contexts format.\n *\n * Rules:\n * - `targetingKey` maps to the namespace+property specified by `targetingKeyMapping` (default: \"user.id\")\n * - Keys with a dot are split on the first dot: \"user.email\" -> namespace \"user\", key \"email\"\n * - Keys without a dot go to the default (empty-string) namespace: \"country\" -> { \"\": { country: ... } }\n * - Multi-dot keys split on first dot only: \"user.ip.address\" -> { user: { \"ip.address\": ... } }\n */\nexport function mapContext(\n ofContext: EvaluationContext,\n targetingKeyMapping = \"user.id\"\n): Contexts {\n const result: Record<string, Record<string, ContextValue>> = {};\n\n for (const [key, value] of Object.entries(ofContext)) {\n if (value === undefined) continue;\n\n // Cast to ContextValue -- OpenFeature allows arbitrary nesting but Quonfig\n // contexts accept primitives and string arrays. Callers should pass only\n // primitive or string[] values for keys they want evaluated.\n const ctxValue = value as ContextValue;\n\n if (key === \"targetingKey\") {\n const dotIdx = targetingKeyMapping.indexOf(\".\");\n const ns = dotIdx === -1 ? \"\" : targetingKeyMapping.slice(0, dotIdx);\n const prop = dotIdx === -1 ? targetingKeyMapping : targetingKeyMapping.slice(dotIdx + 1);\n result[ns] ??= {};\n result[ns][prop] = ctxValue;\n continue;\n }\n\n const dotIdx = key.indexOf(\".\");\n if (dotIdx === -1) {\n result[\"\"] ??= {};\n result[\"\"][key] = ctxValue;\n } else {\n const ns = key.slice(0, dotIdx);\n const prop = key.slice(dotIdx + 1);\n result[ns] ??= {};\n result[ns][prop] = ctxValue;\n }\n }\n\n return result;\n}\n","import { ErrorCode } from \"@openfeature/server-sdk\";\n\n/**\n * Maps a native SDK error to an OpenFeature ErrorCode.\n *\n * The native SDK throws Error instances with message strings. We map by inspecting\n * the lowercased message.\n */\nexport function toErrorCode(err: unknown): ErrorCode {\n const msg = err instanceof Error ? err.message.toLowerCase() : String(err).toLowerCase();\n\n if (\n msg.includes(\"not found\") ||\n msg.includes(\"flag not found\") ||\n msg.includes(\"no value found\") ||\n msg.includes(\"value found for key\")\n ) {\n return ErrorCode.FLAG_NOT_FOUND;\n }\n if (msg.includes(\"type mismatch\")) {\n return ErrorCode.TYPE_MISMATCH;\n }\n if (msg.includes(\"not initialized\") || msg.includes(\"provider not ready\")) {\n return ErrorCode.PROVIDER_NOT_READY;\n }\n return ErrorCode.GENERAL;\n}\n"],"mappings":";AAAA;AAAA,EACE;AAAA,EAIA;AAAA,EAEA;AAAA,EAEA;AAAA,OACK;AACP,SAA4B,eAA+B;;;ACCpD,SAAS,WACd,WACA,sBAAsB,WACZ;AACV,QAAM,SAAuD,CAAC;AAE9D,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,SAAS,GAAG;AACpD,QAAI,UAAU,OAAW;AAKzB,UAAM,WAAW;AAEjB,QAAI,QAAQ,gBAAgB;AAC1B,YAAMA,UAAS,oBAAoB,QAAQ,GAAG;AAC9C,YAAM,KAAKA,YAAW,KAAK,KAAK,oBAAoB,MAAM,GAAGA,OAAM;AACnE,YAAM,OAAOA,YAAW,KAAK,sBAAsB,oBAAoB,MAAMA,UAAS,CAAC;AACvF,aAAO,EAAE,MAAM,CAAC;AAChB,aAAO,EAAE,EAAE,IAAI,IAAI;AACnB;AAAA,IACF;AAEA,UAAM,SAAS,IAAI,QAAQ,GAAG;AAC9B,QAAI,WAAW,IAAI;AACjB,aAAO,EAAE,MAAM,CAAC;AAChB,aAAO,EAAE,EAAE,GAAG,IAAI;AAAA,IACpB,OAAO;AACL,YAAM,KAAK,IAAI,MAAM,GAAG,MAAM;AAC9B,YAAM,OAAO,IAAI,MAAM,SAAS,CAAC;AACjC,aAAO,EAAE,MAAM,CAAC;AAChB,aAAO,EAAE,EAAE,IAAI,IAAI;AAAA,IACrB;AAAA,EACF;AAEA,SAAO;AACT;;;ADXO,IAA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
1
|
{
|
|
2
2
|
"name": "@quonfig/openfeature-node",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "2.0.0",
|
|
4
4
|
"description": "OpenFeature provider for Quonfig -- Node.js",
|
|
5
5
|
"main": "dist/index.cjs",
|
|
6
6
|
"module": "dist/index.js",
|
|
@@ -25,11 +25,11 @@
|
|
|
25
25
|
"version": "prettier --write CHANGELOG.md README.md && git add CHANGELOG.md README.md"
|
|
26
26
|
},
|
|
27
27
|
"peerDependencies": {
|
|
28
|
-
"@quonfig/node": ">=1.
|
|
28
|
+
"@quonfig/node": ">=1.9.0",
|
|
29
29
|
"@openfeature/server-sdk": ">=1.0.0"
|
|
30
30
|
},
|
|
31
31
|
"devDependencies": {
|
|
32
|
-
"@quonfig/node": "^1.
|
|
32
|
+
"@quonfig/node": "^1.9.0",
|
|
33
33
|
"@openfeature/server-sdk": "^1.7.0",
|
|
34
34
|
"@types/node": "^26.6.5",
|
|
35
35
|
"prettier": "^3.0.0",
|