Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@openfeature/server-sdk

Package Overview
Dependencies
Maintainers
2
Versions
27
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@openfeature/server-sdk - npm Package Compare versions

Comparing version 1.14.0 to 1.15.0

390

dist/cjs/index.js
"use strict";
var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
var __export = (target, all) => {

@@ -20,2 +37,22 @@ for (var name in all)

var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var __async = (__this, __arguments, generator) => {
return new Promise((resolve, reject) => {
var fulfilled = (value) => {
try {
step(generator.next(value));
} catch (e) {
reject(e);
}
};
var rejected = (value) => {
try {
step(generator.throw(value));
} catch (e) {
reject(e);
}
};
var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
step((generator = generator.apply(__this, __arguments)).next());
});
};

@@ -43,5 +80,7 @@ // src/index.ts

var NoopFeatureProvider = class {
metadata = {
name: "No-op Provider"
};
constructor() {
this.metadata = {
name: "No-op Provider"
};
}
resolveBooleanEvaluation(_, defaultValue) {

@@ -74,3 +113,2 @@ return this.noOp(defaultValue);

var VariantFoundError = class _VariantFoundError extends import_core2.OpenFeatureError {
code;
constructor(message) {

@@ -86,10 +124,9 @@ super(message);

var InMemoryProvider = class {
events = new OpenFeatureEventEmitter();
runsOn = "server";
metadata = {
name: "in-memory"
};
_flagConfiguration;
constructor(flagConfiguration = {}) {
this._flagConfiguration = { ...flagConfiguration };
this.events = new OpenFeatureEventEmitter();
this.runsOn = "server";
this.metadata = {
name: "in-memory"
};
this._flagConfiguration = __spreadValues({}, flagConfiguration);
}

@@ -102,3 +139,3 @@ /**

const flagsChanged = Object.entries(flagConfiguration).filter(([key, value]) => this._flagConfiguration[key] !== value).map(([key]) => key);
this._flagConfiguration = { ...flagConfiguration };
this._flagConfiguration = __spreadValues({}, flagConfiguration);
this.events.emit(import_core6.ServerProviderEvents.ConfigurationChanged, { flagsChanged });

@@ -112,26 +149,33 @@ }

}
async resolveStringEvaluation(flagKey, defaultValue, context, logger) {
return this.resolveFlagWithReason(flagKey, defaultValue, context, logger);
resolveStringEvaluation(flagKey, defaultValue, context, logger) {
return __async(this, null, function* () {
return this.resolveFlagWithReason(flagKey, defaultValue, context, logger);
});
}
async resolveObjectEvaluation(flagKey, defaultValue, context, logger) {
return this.resolveFlagWithReason(flagKey, defaultValue, context, logger);
resolveObjectEvaluation(flagKey, defaultValue, context, logger) {
return __async(this, null, function* () {
return this.resolveFlagWithReason(flagKey, defaultValue, context, logger);
});
}
async resolveFlagWithReason(flagKey, defaultValue, ctx, logger) {
try {
const resolutionResult = this.lookupFlagValue(flagKey, defaultValue, ctx, logger);
if (typeof resolutionResult?.value != typeof defaultValue) {
throw new import_core3.TypeMismatchError();
resolveFlagWithReason(flagKey, defaultValue, ctx, logger) {
return __async(this, null, function* () {
try {
const resolutionResult = this.lookupFlagValue(flagKey, defaultValue, ctx, logger);
if (typeof (resolutionResult == null ? void 0 : resolutionResult.value) != typeof defaultValue) {
throw new import_core3.TypeMismatchError();
}
return resolutionResult;
} catch (error) {
if (!(error instanceof import_core3.OpenFeatureError)) {
throw new import_core3.GeneralError((error == null ? void 0 : error.message) || "unknown error");
}
throw error;
}
return resolutionResult;
} catch (error) {
if (!(error instanceof import_core3.OpenFeatureError)) {
throw new import_core3.GeneralError(error?.message || "unknown error");
}
throw error;
}
});
}
lookupFlagValue(flagKey, defaultValue, ctx, logger) {
var _a;
if (!(flagKey in this._flagConfiguration)) {
const message = `no flag found with key ${flagKey}`;
logger?.debug(message);
logger == null ? void 0 : logger.debug(message);
throw new import_core3.FlagNotFoundError(message);

@@ -143,15 +187,15 @@ }

}
const isContextEval = ctx && flagSpec?.contextEvaluator;
const variant = isContextEval ? flagSpec.contextEvaluator?.(ctx) : flagSpec.defaultVariant;
const value = variant && flagSpec?.variants[variant];
const isContextEval = ctx && (flagSpec == null ? void 0 : flagSpec.contextEvaluator);
const variant = isContextEval ? (_a = flagSpec.contextEvaluator) == null ? void 0 : _a.call(flagSpec, ctx) : flagSpec.defaultVariant;
const value = variant && (flagSpec == null ? void 0 : flagSpec.variants[variant]);
if (value === void 0) {
const message = `no value associated with variant ${variant}`;
logger?.error(message);
logger == null ? void 0 : logger.error(message);
throw new VariantFoundError(message);
}
return {
value,
...variant && { variant },
return __spreadProps(__spreadValues({
value
}, variant && { variant }), {
reason: isContextEval ? import_core3.StandardResolutionReasons.TARGETING_MATCH : import_core3.StandardResolutionReasons.STATIC
};
});
}

@@ -172,12 +216,11 @@ };

this.options = options;
this._hooks = [];
this._context = context;
}
_context;
_hooks = [];
_clientLogger;
get metadata() {
var _a, _b;
return {
// Use domain if name is not provided
name: this.options.domain ?? this.options.name,
domain: this.options.domain ?? this.options.name,
name: (_a = this.options.domain) != null ? _a : this.options.name,
domain: (_b = this.options.domain) != null ? _b : this.options.name,
version: this.options.version,

@@ -191,2 +234,3 @@ providerMetadata: this.providerAccessor().metadata

addHandler(eventType, handler) {
var _a;
this.emitterAccessor().addHandler(eventType, handler);

@@ -202,3 +246,3 @@ const shouldRunNow = (0, import_core4.statusMatchesEvent)(eventType, this._providerStatus);

} catch (err) {
this._logger?.error("Error running event handler:", err);
(_a = this._logger) == null ? void 0 : _a.error("Error running event handler:", err);
}

@@ -235,4 +279,6 @@ }

}
async getBooleanValue(flagKey, defaultValue, context, options) {
return (await this.getBooleanDetails(flagKey, defaultValue, context, options)).value;
getBooleanValue(flagKey, defaultValue, context, options) {
return __async(this, null, function* () {
return (yield this.getBooleanDetails(flagKey, defaultValue, context, options)).value;
});
}

@@ -249,4 +295,6 @@ getBooleanDetails(flagKey, defaultValue, context, options) {

}
async getStringValue(flagKey, defaultValue, context, options) {
return (await this.getStringDetails(flagKey, defaultValue, context, options)).value;
getStringValue(flagKey, defaultValue, context, options) {
return __async(this, null, function* () {
return (yield this.getStringDetails(flagKey, defaultValue, context, options)).value;
});
}

@@ -264,4 +312,6 @@ getStringDetails(flagKey, defaultValue, context, options) {

}
async getNumberValue(flagKey, defaultValue, context, options) {
return (await this.getNumberDetails(flagKey, defaultValue, context, options)).value;
getNumberValue(flagKey, defaultValue, context, options) {
return __async(this, null, function* () {
return (yield this.getNumberDetails(flagKey, defaultValue, context, options)).value;
});
}

@@ -279,4 +329,6 @@ getNumberDetails(flagKey, defaultValue, context, options) {

}
async getObjectValue(flagKey, defaultValue, context, options) {
return (await this.getObjectDetails(flagKey, defaultValue, context, options)).value;
getObjectValue(flagKey, defaultValue, context, options) {
return __async(this, null, function* () {
return (yield this.getObjectDetails(flagKey, defaultValue, context, options)).value;
});
}

@@ -286,99 +338,105 @@ getObjectDetails(flagKey, defaultValue, context, options) {

}
async evaluate(flagKey, resolver, defaultValue, flagType, invocationContext = {}, options = {}) {
const allHooks = [
...OpenFeature.getHooks(),
...this.getHooks(),
...options.hooks || [],
...this._provider.hooks || []
];
const allHooksReversed = [...allHooks].reverse();
const mergedContext = {
...OpenFeature.getContext(),
...OpenFeature.getTransactionContext(),
...this._context,
...invocationContext
};
const hookContext = {
flagKey,
defaultValue,
flagValueType: flagType,
clientMetadata: this.metadata,
providerMetadata: this._provider.metadata,
context: mergedContext,
logger: this._logger
};
try {
const frozenContext = await this.beforeHooks(allHooks, hookContext, options);
if (this.providerStatus === import_core.ServerProviderStatus.NOT_READY) {
throw new import_core4.ProviderNotReadyError("provider has not yet initialized");
} else if (this.providerStatus === import_core.ServerProviderStatus.FATAL) {
throw new import_core4.ProviderFatalError("provider is in an irrecoverable error state");
}
const resolution = await resolver.call(this._provider, flagKey, defaultValue, frozenContext, this._logger);
const evaluationDetails = {
...resolution,
flagMetadata: Object.freeze(resolution.flagMetadata ?? {}),
flagKey
evaluate(_0, _1, _2, _3) {
return __async(this, arguments, function* (flagKey, resolver, defaultValue, flagType, invocationContext = {}, options = {}) {
var _a;
const allHooks = [
...OpenFeature.getHooks(),
...this.getHooks(),
...options.hooks || [],
...this._provider.hooks || []
];
const allHooksReversed = [...allHooks].reverse();
const mergedContext = __spreadValues(__spreadValues(__spreadValues(__spreadValues({}, OpenFeature.getContext()), OpenFeature.getTransactionContext()), this._context), invocationContext);
const hookContext = {
flagKey,
defaultValue,
flagValueType: flagType,
clientMetadata: this.metadata,
providerMetadata: this._provider.metadata,
context: mergedContext,
logger: this._logger
};
if (evaluationDetails.errorCode) {
throw (0, import_core4.instantiateErrorByErrorCode)(evaluationDetails.errorCode);
try {
const frozenContext = yield this.beforeHooks(allHooks, hookContext, options);
if (this.providerStatus === import_core.ServerProviderStatus.NOT_READY) {
throw new import_core4.ProviderNotReadyError("provider has not yet initialized");
} else if (this.providerStatus === import_core.ServerProviderStatus.FATAL) {
throw new import_core4.ProviderFatalError("provider is in an irrecoverable error state");
}
const resolution = yield resolver.call(this._provider, flagKey, defaultValue, frozenContext, this._logger);
const evaluationDetails = __spreadProps(__spreadValues({}, resolution), {
flagMetadata: Object.freeze((_a = resolution.flagMetadata) != null ? _a : {}),
flagKey
});
if (evaluationDetails.errorCode) {
throw (0, import_core4.instantiateErrorByErrorCode)(evaluationDetails.errorCode);
}
yield this.afterHooks(allHooksReversed, hookContext, evaluationDetails, options);
return evaluationDetails;
} catch (err) {
const errorMessage = err == null ? void 0 : err.message;
const errorCode = (err == null ? void 0 : err.code) || import_core4.ErrorCode.GENERAL;
yield this.errorHooks(allHooksReversed, hookContext, err, options);
return {
errorCode,
errorMessage,
value: defaultValue,
reason: import_core4.StandardResolutionReasons.ERROR,
flagMetadata: Object.freeze({}),
flagKey
};
} finally {
yield this.finallyHooks(allHooksReversed, hookContext, options);
}
await this.afterHooks(allHooksReversed, hookContext, evaluationDetails, options);
return evaluationDetails;
} catch (err) {
const errorMessage = err?.message;
const errorCode = err?.code || import_core4.ErrorCode.GENERAL;
await this.errorHooks(allHooksReversed, hookContext, err, options);
return {
errorCode,
errorMessage,
value: defaultValue,
reason: import_core4.StandardResolutionReasons.ERROR,
flagMetadata: Object.freeze({}),
flagKey
};
} finally {
await this.finallyHooks(allHooksReversed, hookContext, options);
}
});
}
async beforeHooks(hooks, hookContext, options) {
for (const hook of hooks) {
Object.freeze(hookContext);
Object.assign(hookContext.context, {
...hookContext.context,
...await hook?.before?.(hookContext, Object.freeze(options.hookHints))
});
}
return Object.freeze(hookContext.context);
beforeHooks(hooks, hookContext, options) {
return __async(this, null, function* () {
var _a;
for (const hook of hooks) {
Object.freeze(hookContext);
Object.assign(hookContext.context, __spreadValues(__spreadValues({}, hookContext.context), yield (_a = hook == null ? void 0 : hook.before) == null ? void 0 : _a.call(hook, hookContext, Object.freeze(options.hookHints))));
}
return Object.freeze(hookContext.context);
});
}
async afterHooks(hooks, hookContext, evaluationDetails, options) {
for (const hook of hooks) {
await hook?.after?.(hookContext, evaluationDetails, options.hookHints);
}
afterHooks(hooks, hookContext, evaluationDetails, options) {
return __async(this, null, function* () {
var _a;
for (const hook of hooks) {
yield (_a = hook == null ? void 0 : hook.after) == null ? void 0 : _a.call(hook, hookContext, evaluationDetails, options.hookHints);
}
});
}
async errorHooks(hooks, hookContext, err, options) {
for (const hook of hooks) {
try {
await hook?.error?.(hookContext, err, options.hookHints);
} catch (err2) {
this._logger.error(`Unhandled error during 'error' hook: ${err2}`);
if (err2 instanceof Error) {
this._logger.error(err2.stack);
errorHooks(hooks, hookContext, err, options) {
return __async(this, null, function* () {
var _a;
for (const hook of hooks) {
try {
yield (_a = hook == null ? void 0 : hook.error) == null ? void 0 : _a.call(hook, hookContext, err, options.hookHints);
} catch (err2) {
this._logger.error(`Unhandled error during 'error' hook: ${err2}`);
if (err2 instanceof Error) {
this._logger.error(err2.stack);
}
this._logger.error(err2 == null ? void 0 : err2.stack);
}
this._logger.error(err2?.stack);
}
}
});
}
async finallyHooks(hooks, hookContext, options) {
for (const hook of hooks) {
try {
await hook?.finally?.(hookContext, options.hookHints);
} catch (err) {
this._logger.error(`Unhandled error during 'finally' hook: ${err}`);
if (err instanceof Error) {
this._logger.error(err.stack);
finallyHooks(hooks, hookContext, options) {
return __async(this, null, function* () {
var _a;
for (const hook of hooks) {
try {
yield (_a = hook == null ? void 0 : hook.finally) == null ? void 0 : _a.call(hook, hookContext, options.hookHints);
} catch (err) {
this._logger.error(`Unhandled error during 'finally' hook: ${err}`);
if (err instanceof Error) {
this._logger.error(err.stack);
}
this._logger.error(err == null ? void 0 : err.stack);
}
this._logger.error(err?.stack);
}
}
});
}

@@ -400,7 +458,8 @@ get _provider() {

var OpenFeatureEventEmitter = class extends import_core5.GenericEventEmitter {
eventEmitter = new import_node_events.EventEmitter({ captureRejections: true });
constructor() {
super();
this.eventEmitter = new import_node_events.EventEmitter({ captureRejections: true });
this.eventEmitter.on("error", (err) => {
this._logger?.error("Error running event handler:", err);
var _a;
(_a = this._logger) == null ? void 0 : _a.error("Error running event handler:", err);
});

@@ -427,5 +486,8 @@ }

var AsyncLocalStorageTransactionContextPropagator = class {
asyncLocalStorage = new import_async_hooks.AsyncLocalStorage();
constructor() {
this.asyncLocalStorage = new import_async_hooks.AsyncLocalStorage();
}
getTransactionContext() {
return this.asyncLocalStorage.getStore() ?? {};
var _a;
return (_a = this.asyncLocalStorage.getStore()) != null ? _a : {};
}

@@ -441,14 +503,14 @@ setTransactionContext(transactionContext, callback, ...args) {

var OpenFeatureAPI = class _OpenFeatureAPI extends import_core7.OpenFeatureCommonAPI {
_statusEnumType = import_core.ServerProviderStatus;
_apiEmitter = new OpenFeatureEventEmitter();
_defaultProvider = new import_core7.ProviderWrapper(
NOOP_PROVIDER,
import_core.ServerProviderStatus.NOT_READY,
this._statusEnumType
);
_domainScopedProviders = /* @__PURE__ */ new Map();
_createEventEmitter = () => new OpenFeatureEventEmitter();
_transactionContextPropagator = NOOP_TRANSACTION_CONTEXT_PROPAGATOR;
constructor() {
super("server");
this._statusEnumType = import_core.ServerProviderStatus;
this._apiEmitter = new OpenFeatureEventEmitter();
this._defaultProvider = new import_core7.ProviderWrapper(
NOOP_PROVIDER,
import_core.ServerProviderStatus.NOT_READY,
this._statusEnumType
);
this._domainScopedProviders = /* @__PURE__ */ new Map();
this._createEventEmitter = () => new OpenFeatureEventEmitter();
this._transactionContextPropagator = NOOP_TRANSACTION_CONTEXT_PROPAGATOR;
}

@@ -470,11 +532,14 @@ /**

getProviderStatus(domain) {
var _a, _b;
if (!domain) {
return this._defaultProvider.status;
}
return this._domainScopedProviders.get(domain)?.status ?? this._defaultProvider.status;
return (_b = (_a = this._domainScopedProviders.get(domain)) == null ? void 0 : _a.status) != null ? _b : this._defaultProvider.status;
}
async setProviderAndWait(domainOrProvider, providerOrUndefined) {
const domain = (0, import_core7.stringOrUndefined)(domainOrProvider);
const provider = domain ? (0, import_core7.objectOrUndefined)(providerOrUndefined) : (0, import_core7.objectOrUndefined)(domainOrProvider);
await this.setAwaitableProvider(domain, provider);
setProviderAndWait(domainOrProvider, providerOrUndefined) {
return __async(this, null, function* () {
const domain = (0, import_core7.stringOrUndefined)(domainOrProvider);
const provider = domain ? (0, import_core7.objectOrUndefined)(providerOrUndefined) : (0, import_core7.objectOrUndefined)(domainOrProvider);
yield this.setAwaitableProvider(domain, provider);
});
}

@@ -498,5 +563,6 @@ setProvider(clientOrProvider, providerOrUndefined) {

getClient(domainOrContext, versionOrContext, contextOrUndefined) {
var _a, _b;
const domain = (0, import_core7.stringOrUndefined)(domainOrContext);
const version = (0, import_core7.stringOrUndefined)(versionOrContext);
const context = (0, import_core7.objectOrUndefined)(domainOrContext) ?? (0, import_core7.objectOrUndefined)(versionOrContext) ?? (0, import_core7.objectOrUndefined)(contextOrUndefined);
const context = (_b = (_a = (0, import_core7.objectOrUndefined)(domainOrContext)) != null ? _a : (0, import_core7.objectOrUndefined)(versionOrContext)) != null ? _b : (0, import_core7.objectOrUndefined)(contextOrUndefined);
return new OpenFeatureClient(

@@ -520,5 +586,5 @@ () => this.getProviderForClient(domain),

const baseMessage = "Invalid TransactionContextPropagator, will not be set: ";
if (typeof transactionContextPropagator?.getTransactionContext !== "function") {
if (typeof (transactionContextPropagator == null ? void 0 : transactionContextPropagator.getTransactionContext) !== "function") {
this._logger.error(`${baseMessage}: getTransactionContext is not a function.`);
} else if (typeof transactionContextPropagator?.setTransactionContext !== "function") {
} else if (typeof (transactionContextPropagator == null ? void 0 : transactionContextPropagator.setTransactionContext) !== "function") {
this._logger.error(`${baseMessage}: setTransactionContext is not a function.`);

@@ -538,4 +604,4 @@ } else {

const error = err;
this._logger.error(`Error getting transaction context: ${error?.message}, returning empty context.`);
this._logger.error(error?.stack);
this._logger.error(`Error getting transaction context: ${error == null ? void 0 : error.message}, returning empty context.`);
this._logger.error(error == null ? void 0 : error.stack);
return {};

@@ -542,0 +608,0 @@ }

@@ -0,1 +1,41 @@

var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
var __async = (__this, __arguments, generator) => {
return new Promise((resolve, reject) => {
var fulfilled = (value) => {
try {
step(generator.next(value));
} catch (e) {
reject(e);
}
};
var rejected = (value) => {
try {
step(generator.throw(value));
} catch (e) {
reject(e);
}
};
var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
step((generator = generator.apply(__this, __arguments)).next());
});
};
// src/provider/provider.ts

@@ -7,5 +47,7 @@ import { ServerProviderStatus } from "@openfeature/core";

var NoopFeatureProvider = class {
metadata = {
name: "No-op Provider"
};
constructor() {
this.metadata = {
name: "No-op Provider"
};
}
resolveBooleanEvaluation(_, defaultValue) {

@@ -44,3 +86,2 @@ return this.noOp(defaultValue);

var VariantFoundError = class _VariantFoundError extends OpenFeatureError {
code;
constructor(message) {

@@ -56,10 +97,9 @@ super(message);

var InMemoryProvider = class {
events = new OpenFeatureEventEmitter();
runsOn = "server";
metadata = {
name: "in-memory"
};
_flagConfiguration;
constructor(flagConfiguration = {}) {
this._flagConfiguration = { ...flagConfiguration };
this.events = new OpenFeatureEventEmitter();
this.runsOn = "server";
this.metadata = {
name: "in-memory"
};
this._flagConfiguration = __spreadValues({}, flagConfiguration);
}

@@ -72,3 +112,3 @@ /**

const flagsChanged = Object.entries(flagConfiguration).filter(([key, value]) => this._flagConfiguration[key] !== value).map(([key]) => key);
this._flagConfiguration = { ...flagConfiguration };
this._flagConfiguration = __spreadValues({}, flagConfiguration);
this.events.emit(ServerProviderEvents.ConfigurationChanged, { flagsChanged });

@@ -82,26 +122,33 @@ }

}
async resolveStringEvaluation(flagKey, defaultValue, context, logger) {
return this.resolveFlagWithReason(flagKey, defaultValue, context, logger);
resolveStringEvaluation(flagKey, defaultValue, context, logger) {
return __async(this, null, function* () {
return this.resolveFlagWithReason(flagKey, defaultValue, context, logger);
});
}
async resolveObjectEvaluation(flagKey, defaultValue, context, logger) {
return this.resolveFlagWithReason(flagKey, defaultValue, context, logger);
resolveObjectEvaluation(flagKey, defaultValue, context, logger) {
return __async(this, null, function* () {
return this.resolveFlagWithReason(flagKey, defaultValue, context, logger);
});
}
async resolveFlagWithReason(flagKey, defaultValue, ctx, logger) {
try {
const resolutionResult = this.lookupFlagValue(flagKey, defaultValue, ctx, logger);
if (typeof resolutionResult?.value != typeof defaultValue) {
throw new TypeMismatchError();
resolveFlagWithReason(flagKey, defaultValue, ctx, logger) {
return __async(this, null, function* () {
try {
const resolutionResult = this.lookupFlagValue(flagKey, defaultValue, ctx, logger);
if (typeof (resolutionResult == null ? void 0 : resolutionResult.value) != typeof defaultValue) {
throw new TypeMismatchError();
}
return resolutionResult;
} catch (error) {
if (!(error instanceof OpenFeatureError2)) {
throw new GeneralError((error == null ? void 0 : error.message) || "unknown error");
}
throw error;
}
return resolutionResult;
} catch (error) {
if (!(error instanceof OpenFeatureError2)) {
throw new GeneralError(error?.message || "unknown error");
}
throw error;
}
});
}
lookupFlagValue(flagKey, defaultValue, ctx, logger) {
var _a;
if (!(flagKey in this._flagConfiguration)) {
const message = `no flag found with key ${flagKey}`;
logger?.debug(message);
logger == null ? void 0 : logger.debug(message);
throw new FlagNotFoundError(message);

@@ -113,15 +160,15 @@ }

}
const isContextEval = ctx && flagSpec?.contextEvaluator;
const variant = isContextEval ? flagSpec.contextEvaluator?.(ctx) : flagSpec.defaultVariant;
const value = variant && flagSpec?.variants[variant];
const isContextEval = ctx && (flagSpec == null ? void 0 : flagSpec.contextEvaluator);
const variant = isContextEval ? (_a = flagSpec.contextEvaluator) == null ? void 0 : _a.call(flagSpec, ctx) : flagSpec.defaultVariant;
const value = variant && (flagSpec == null ? void 0 : flagSpec.variants[variant]);
if (value === void 0) {
const message = `no value associated with variant ${variant}`;
logger?.error(message);
logger == null ? void 0 : logger.error(message);
throw new VariantFoundError(message);
}
return {
value,
...variant && { variant },
return __spreadProps(__spreadValues({
value
}, variant && { variant }), {
reason: isContextEval ? StandardResolutionReasons.TARGETING_MATCH : StandardResolutionReasons.STATIC
};
});
}

@@ -155,12 +202,11 @@ };

this.options = options;
this._hooks = [];
this._context = context;
}
_context;
_hooks = [];
_clientLogger;
get metadata() {
var _a, _b;
return {
// Use domain if name is not provided
name: this.options.domain ?? this.options.name,
domain: this.options.domain ?? this.options.name,
name: (_a = this.options.domain) != null ? _a : this.options.name,
domain: (_b = this.options.domain) != null ? _b : this.options.name,
version: this.options.version,

@@ -174,2 +220,3 @@ providerMetadata: this.providerAccessor().metadata

addHandler(eventType, handler) {
var _a;
this.emitterAccessor().addHandler(eventType, handler);

@@ -185,3 +232,3 @@ const shouldRunNow = statusMatchesEvent(eventType, this._providerStatus);

} catch (err) {
this._logger?.error("Error running event handler:", err);
(_a = this._logger) == null ? void 0 : _a.error("Error running event handler:", err);
}

@@ -218,4 +265,6 @@ }

}
async getBooleanValue(flagKey, defaultValue, context, options) {
return (await this.getBooleanDetails(flagKey, defaultValue, context, options)).value;
getBooleanValue(flagKey, defaultValue, context, options) {
return __async(this, null, function* () {
return (yield this.getBooleanDetails(flagKey, defaultValue, context, options)).value;
});
}

@@ -232,4 +281,6 @@ getBooleanDetails(flagKey, defaultValue, context, options) {

}
async getStringValue(flagKey, defaultValue, context, options) {
return (await this.getStringDetails(flagKey, defaultValue, context, options)).value;
getStringValue(flagKey, defaultValue, context, options) {
return __async(this, null, function* () {
return (yield this.getStringDetails(flagKey, defaultValue, context, options)).value;
});
}

@@ -247,4 +298,6 @@ getStringDetails(flagKey, defaultValue, context, options) {

}
async getNumberValue(flagKey, defaultValue, context, options) {
return (await this.getNumberDetails(flagKey, defaultValue, context, options)).value;
getNumberValue(flagKey, defaultValue, context, options) {
return __async(this, null, function* () {
return (yield this.getNumberDetails(flagKey, defaultValue, context, options)).value;
});
}

@@ -262,4 +315,6 @@ getNumberDetails(flagKey, defaultValue, context, options) {

}
async getObjectValue(flagKey, defaultValue, context, options) {
return (await this.getObjectDetails(flagKey, defaultValue, context, options)).value;
getObjectValue(flagKey, defaultValue, context, options) {
return __async(this, null, function* () {
return (yield this.getObjectDetails(flagKey, defaultValue, context, options)).value;
});
}

@@ -269,99 +324,105 @@ getObjectDetails(flagKey, defaultValue, context, options) {

}
async evaluate(flagKey, resolver, defaultValue, flagType, invocationContext = {}, options = {}) {
const allHooks = [
...OpenFeature.getHooks(),
...this.getHooks(),
...options.hooks || [],
...this._provider.hooks || []
];
const allHooksReversed = [...allHooks].reverse();
const mergedContext = {
...OpenFeature.getContext(),
...OpenFeature.getTransactionContext(),
...this._context,
...invocationContext
};
const hookContext = {
flagKey,
defaultValue,
flagValueType: flagType,
clientMetadata: this.metadata,
providerMetadata: this._provider.metadata,
context: mergedContext,
logger: this._logger
};
try {
const frozenContext = await this.beforeHooks(allHooks, hookContext, options);
if (this.providerStatus === ServerProviderStatus.NOT_READY) {
throw new ProviderNotReadyError("provider has not yet initialized");
} else if (this.providerStatus === ServerProviderStatus.FATAL) {
throw new ProviderFatalError("provider is in an irrecoverable error state");
}
const resolution = await resolver.call(this._provider, flagKey, defaultValue, frozenContext, this._logger);
const evaluationDetails = {
...resolution,
flagMetadata: Object.freeze(resolution.flagMetadata ?? {}),
flagKey
evaluate(_0, _1, _2, _3) {
return __async(this, arguments, function* (flagKey, resolver, defaultValue, flagType, invocationContext = {}, options = {}) {
var _a;
const allHooks = [
...OpenFeature.getHooks(),
...this.getHooks(),
...options.hooks || [],
...this._provider.hooks || []
];
const allHooksReversed = [...allHooks].reverse();
const mergedContext = __spreadValues(__spreadValues(__spreadValues(__spreadValues({}, OpenFeature.getContext()), OpenFeature.getTransactionContext()), this._context), invocationContext);
const hookContext = {
flagKey,
defaultValue,
flagValueType: flagType,
clientMetadata: this.metadata,
providerMetadata: this._provider.metadata,
context: mergedContext,
logger: this._logger
};
if (evaluationDetails.errorCode) {
throw instantiateErrorByErrorCode(evaluationDetails.errorCode);
try {
const frozenContext = yield this.beforeHooks(allHooks, hookContext, options);
if (this.providerStatus === ServerProviderStatus.NOT_READY) {
throw new ProviderNotReadyError("provider has not yet initialized");
} else if (this.providerStatus === ServerProviderStatus.FATAL) {
throw new ProviderFatalError("provider is in an irrecoverable error state");
}
const resolution = yield resolver.call(this._provider, flagKey, defaultValue, frozenContext, this._logger);
const evaluationDetails = __spreadProps(__spreadValues({}, resolution), {
flagMetadata: Object.freeze((_a = resolution.flagMetadata) != null ? _a : {}),
flagKey
});
if (evaluationDetails.errorCode) {
throw instantiateErrorByErrorCode(evaluationDetails.errorCode);
}
yield this.afterHooks(allHooksReversed, hookContext, evaluationDetails, options);
return evaluationDetails;
} catch (err) {
const errorMessage = err == null ? void 0 : err.message;
const errorCode = (err == null ? void 0 : err.code) || ErrorCode2.GENERAL;
yield this.errorHooks(allHooksReversed, hookContext, err, options);
return {
errorCode,
errorMessage,
value: defaultValue,
reason: StandardResolutionReasons2.ERROR,
flagMetadata: Object.freeze({}),
flagKey
};
} finally {
yield this.finallyHooks(allHooksReversed, hookContext, options);
}
await this.afterHooks(allHooksReversed, hookContext, evaluationDetails, options);
return evaluationDetails;
} catch (err) {
const errorMessage = err?.message;
const errorCode = err?.code || ErrorCode2.GENERAL;
await this.errorHooks(allHooksReversed, hookContext, err, options);
return {
errorCode,
errorMessage,
value: defaultValue,
reason: StandardResolutionReasons2.ERROR,
flagMetadata: Object.freeze({}),
flagKey
};
} finally {
await this.finallyHooks(allHooksReversed, hookContext, options);
}
});
}
async beforeHooks(hooks, hookContext, options) {
for (const hook of hooks) {
Object.freeze(hookContext);
Object.assign(hookContext.context, {
...hookContext.context,
...await hook?.before?.(hookContext, Object.freeze(options.hookHints))
});
}
return Object.freeze(hookContext.context);
beforeHooks(hooks, hookContext, options) {
return __async(this, null, function* () {
var _a;
for (const hook of hooks) {
Object.freeze(hookContext);
Object.assign(hookContext.context, __spreadValues(__spreadValues({}, hookContext.context), yield (_a = hook == null ? void 0 : hook.before) == null ? void 0 : _a.call(hook, hookContext, Object.freeze(options.hookHints))));
}
return Object.freeze(hookContext.context);
});
}
async afterHooks(hooks, hookContext, evaluationDetails, options) {
for (const hook of hooks) {
await hook?.after?.(hookContext, evaluationDetails, options.hookHints);
}
afterHooks(hooks, hookContext, evaluationDetails, options) {
return __async(this, null, function* () {
var _a;
for (const hook of hooks) {
yield (_a = hook == null ? void 0 : hook.after) == null ? void 0 : _a.call(hook, hookContext, evaluationDetails, options.hookHints);
}
});
}
async errorHooks(hooks, hookContext, err, options) {
for (const hook of hooks) {
try {
await hook?.error?.(hookContext, err, options.hookHints);
} catch (err2) {
this._logger.error(`Unhandled error during 'error' hook: ${err2}`);
if (err2 instanceof Error) {
this._logger.error(err2.stack);
errorHooks(hooks, hookContext, err, options) {
return __async(this, null, function* () {
var _a;
for (const hook of hooks) {
try {
yield (_a = hook == null ? void 0 : hook.error) == null ? void 0 : _a.call(hook, hookContext, err, options.hookHints);
} catch (err2) {
this._logger.error(`Unhandled error during 'error' hook: ${err2}`);
if (err2 instanceof Error) {
this._logger.error(err2.stack);
}
this._logger.error(err2 == null ? void 0 : err2.stack);
}
this._logger.error(err2?.stack);
}
}
});
}
async finallyHooks(hooks, hookContext, options) {
for (const hook of hooks) {
try {
await hook?.finally?.(hookContext, options.hookHints);
} catch (err) {
this._logger.error(`Unhandled error during 'finally' hook: ${err}`);
if (err instanceof Error) {
this._logger.error(err.stack);
finallyHooks(hooks, hookContext, options) {
return __async(this, null, function* () {
var _a;
for (const hook of hooks) {
try {
yield (_a = hook == null ? void 0 : hook.finally) == null ? void 0 : _a.call(hook, hookContext, options.hookHints);
} catch (err) {
this._logger.error(`Unhandled error during 'finally' hook: ${err}`);
if (err instanceof Error) {
this._logger.error(err.stack);
}
this._logger.error(err == null ? void 0 : err.stack);
}
this._logger.error(err?.stack);
}
}
});
}

@@ -383,7 +444,8 @@ get _provider() {

var OpenFeatureEventEmitter = class extends GenericEventEmitter {
eventEmitter = new EventEmitter({ captureRejections: true });
constructor() {
super();
this.eventEmitter = new EventEmitter({ captureRejections: true });
this.eventEmitter.on("error", (err) => {
this._logger?.error("Error running event handler:", err);
var _a;
(_a = this._logger) == null ? void 0 : _a.error("Error running event handler:", err);
});

@@ -410,5 +472,8 @@ }

var AsyncLocalStorageTransactionContextPropagator = class {
asyncLocalStorage = new AsyncLocalStorage();
constructor() {
this.asyncLocalStorage = new AsyncLocalStorage();
}
getTransactionContext() {
return this.asyncLocalStorage.getStore() ?? {};
var _a;
return (_a = this.asyncLocalStorage.getStore()) != null ? _a : {};
}

@@ -424,14 +489,14 @@ setTransactionContext(transactionContext, callback, ...args) {

var OpenFeatureAPI = class _OpenFeatureAPI extends OpenFeatureCommonAPI {
_statusEnumType = ServerProviderStatus;
_apiEmitter = new OpenFeatureEventEmitter();
_defaultProvider = new ProviderWrapper(
NOOP_PROVIDER,
ServerProviderStatus.NOT_READY,
this._statusEnumType
);
_domainScopedProviders = /* @__PURE__ */ new Map();
_createEventEmitter = () => new OpenFeatureEventEmitter();
_transactionContextPropagator = NOOP_TRANSACTION_CONTEXT_PROPAGATOR;
constructor() {
super("server");
this._statusEnumType = ServerProviderStatus;
this._apiEmitter = new OpenFeatureEventEmitter();
this._defaultProvider = new ProviderWrapper(
NOOP_PROVIDER,
ServerProviderStatus.NOT_READY,
this._statusEnumType
);
this._domainScopedProviders = /* @__PURE__ */ new Map();
this._createEventEmitter = () => new OpenFeatureEventEmitter();
this._transactionContextPropagator = NOOP_TRANSACTION_CONTEXT_PROPAGATOR;
}

@@ -453,11 +518,14 @@ /**

getProviderStatus(domain) {
var _a, _b;
if (!domain) {
return this._defaultProvider.status;
}
return this._domainScopedProviders.get(domain)?.status ?? this._defaultProvider.status;
return (_b = (_a = this._domainScopedProviders.get(domain)) == null ? void 0 : _a.status) != null ? _b : this._defaultProvider.status;
}
async setProviderAndWait(domainOrProvider, providerOrUndefined) {
const domain = stringOrUndefined(domainOrProvider);
const provider = domain ? objectOrUndefined(providerOrUndefined) : objectOrUndefined(domainOrProvider);
await this.setAwaitableProvider(domain, provider);
setProviderAndWait(domainOrProvider, providerOrUndefined) {
return __async(this, null, function* () {
const domain = stringOrUndefined(domainOrProvider);
const provider = domain ? objectOrUndefined(providerOrUndefined) : objectOrUndefined(domainOrProvider);
yield this.setAwaitableProvider(domain, provider);
});
}

@@ -481,5 +549,6 @@ setProvider(clientOrProvider, providerOrUndefined) {

getClient(domainOrContext, versionOrContext, contextOrUndefined) {
var _a, _b;
const domain = stringOrUndefined(domainOrContext);
const version = stringOrUndefined(versionOrContext);
const context = objectOrUndefined(domainOrContext) ?? objectOrUndefined(versionOrContext) ?? objectOrUndefined(contextOrUndefined);
const context = (_b = (_a = objectOrUndefined(domainOrContext)) != null ? _a : objectOrUndefined(versionOrContext)) != null ? _b : objectOrUndefined(contextOrUndefined);
return new OpenFeatureClient(

@@ -503,5 +572,5 @@ () => this.getProviderForClient(domain),

const baseMessage = "Invalid TransactionContextPropagator, will not be set: ";
if (typeof transactionContextPropagator?.getTransactionContext !== "function") {
if (typeof (transactionContextPropagator == null ? void 0 : transactionContextPropagator.getTransactionContext) !== "function") {
this._logger.error(`${baseMessage}: getTransactionContext is not a function.`);
} else if (typeof transactionContextPropagator?.setTransactionContext !== "function") {
} else if (typeof (transactionContextPropagator == null ? void 0 : transactionContextPropagator.setTransactionContext) !== "function") {
this._logger.error(`${baseMessage}: setTransactionContext is not a function.`);

@@ -521,4 +590,4 @@ } else {

const error = err;
this._logger.error(`Error getting transaction context: ${error?.message}, returning empty context.`);
this._logger.error(error?.stack);
this._logger.error(`Error getting transaction context: ${error == null ? void 0 : error.message}, returning empty context.`);
this._logger.error(error == null ? void 0 : error.stack);
return {};

@@ -525,0 +594,0 @@ }

{
"name": "@openfeature/server-sdk",
"version": "1.14.0",
"version": "1.15.0",
"description": "OpenFeature SDK for JavaScript",

@@ -20,4 +20,4 @@ "main": "./dist/cjs/index.js",

"clean": "shx rm -rf ./dist",
"build:esm": "esbuild src/index.ts --bundle --external:@openfeature/core --sourcemap --target=es2022 --platform=node --format=esm --outfile=./dist/esm/index.js --analyze",
"build:cjs": "esbuild src/index.ts --bundle --external:@openfeature/core --sourcemap --target=es2022 --platform=node --format=cjs --outfile=./dist/cjs/index.js --analyze",
"build:esm": "esbuild src/index.ts --bundle --external:@openfeature/core --sourcemap --target=es2015 --platform=node --format=esm --outfile=./dist/esm/index.js --analyze",
"build:cjs": "esbuild src/index.ts --bundle --external:@openfeature/core --sourcemap --target=es2015 --platform=node --format=cjs --outfile=./dist/cjs/index.js --analyze",
"build:rollup-types": "rollup -c ../../rollup.config.mjs",

@@ -52,7 +52,7 @@ "build": "npm run clean && npm run build:esm && npm run build:cjs && npm run build:rollup-types",

"peerDependencies": {
"@openfeature/core": "1.2.0"
"@openfeature/core": "1.3.0"
},
"devDependencies": {
"@openfeature/core": "1.2.0"
"@openfeature/core": "1.3.0"
}
}

@@ -19,4 +19,4 @@ <!-- markdownlint-disable MD033 -->

<!-- x-release-please-start-version -->
<a href="https://github.com/open-feature/js-sdk/releases/tag/server-sdk-v1.14.0">
<img alt="Release" src="https://img.shields.io/static/v1?label=release&message=v1.14.0&color=blue&style=for-the-badge" />
<a href="https://github.com/open-feature/js-sdk/releases/tag/server-sdk-v1.15.0">
<img alt="Release" src="https://img.shields.io/static/v1?label=release&message=v1.15.0&color=blue&style=for-the-badge" />
</a>

@@ -23,0 +23,0 @@ <!-- x-release-please-end -->

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc