All files instance.ts

82.73% Statements 139/168
55.07% Branches 38/69
82.05% Functions 32/39
83.23% Lines 139/167

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589                          1x 1x 1x   1x                               1x                                           1x                           5x 5x                 1x 12x 12x       12x   4x   1x   1x   3x   1x   1x     1x             1x                                                       23x 23x 23x 23x 23x 23x 23x 23x 23x 23x     23x 23x           23x 3x     23x 1x     23x 1x     23x 1x       23x 23x 23x   23x 23x 23x   23x     23x 4x   4x   4x   4x 4x   4x 1x           19x 19x 19x   19x 8x                           2x 2x 1x     1x 1x   1x     1x         28x 28x                 1x       1x                         5x             1x   1x       1x       1x   1x   1x 1x 1x   1x 1x   1x   1x 1x     1x                 1x       1x       1x       1x 1x         1x       1x             18x                                         18x 18x   18x                       24x                                               23x 23x   23x 3x     20x 15x     5x                       1x 1x 1x       1x       1x   1x   1x       1x           1x                 1x                               28x                                                   28x 28x   28x 25x         2x     23x     3x                         3x   3x               4x   4x               1x   1x               1x   1x               1x   1x               1x   1x               1x   1x       1x 23x    
import {
  Context,
  DatafileContent,
  Feature,
  FeatureKey,
  InitialFeatures,
  StickyFeatures,
  VariableType,
  VariableValue,
  VariationValue,
  VariableKey,
} from "@featurevisor/types";
 
import { createLogger, Logger, LogLevel } from "./logger";
import { DatafileReader } from "./datafileReader";
import { Emitter } from "./emitter";
import { ConfigureBucketKey, ConfigureBucketValue } from "./bucket";
import { Evaluation, evaluate } from "./evaluate";
 
export type ReadyCallback = () => void;
 
export type ActivationCallback = (
  featureName: string,
  variation: VariationValue,
  context: Context,
  captureContext: Context,
) => void;
 
export interface Statuses {
  ready: boolean;
  refreshInProgress: boolean;
}
 
const DEFAULT_BUCKET_KEY_SEPARATOR = ".";
 
export type InterceptContext = (context: Context) => Context;
 
export interface InstanceOptions {
  bucketKeySeparator?: string;
  configureBucketKey?: ConfigureBucketKey;
  configureBucketValue?: ConfigureBucketValue;
  datafile?: DatafileContent | string;
  datafileUrl?: string;
  handleDatafileFetch?: (datafileUrl: string) => Promise<DatafileContent>;
  initialFeatures?: InitialFeatures;
  interceptContext?: InterceptContext;
  logger?: Logger;
  onActivation?: ActivationCallback;
  onReady?: ReadyCallback;
  onRefresh?: () => void;
  onUpdate?: () => void;
  refreshInterval?: number; // seconds
  stickyFeatures?: StickyFeatures;
}
 
const emptyDatafile: DatafileContent = {
  schemaVersion: "1",
  revision: "unknown",
  attributes: [],
  segments: [],
  features: [],
};
 
export type DatafileFetchHandler = (datafileUrl: string) => Promise<DatafileContent>;
 
function fetchDatafileContent(
  datafileUrl,
  handleDatafileFetch?: DatafileFetchHandler,
): Promise<DatafileContent> {
  if (handleDatafileFetch) {
    return handleDatafileFetch(datafileUrl);
  }
 
  return fetch(datafileUrl).then((res) => res.json());
}
 
type FieldType = string | VariableType;
type ValueType = VariableValue;
 
export function getValueByType(value: ValueType, fieldType: FieldType): ValueType {
  try {
    Iif (value === undefined) {
      return undefined;
    }
 
    switch (fieldType) {
      case "string":
        return typeof value === "string" ? value : undefined;
      case "integer":
        return parseInt(value as string, 10);
      case "double":
        return parseFloat(value as string);
      case "boolean":
        return value === true;
      case "array":
        return Array.isArray(value) ? value : undefined;
      case "object":
        return typeof value === "object" ? value : undefined;
      // @NOTE: `json` is not handled here intentionally
      default:
        return value;
    }
  } catch (e) {
    return undefined;
  }
}
 
export class FeaturevisorInstance {
  // from options
  private bucketKeySeparator: string;
  private configureBucketKey?: ConfigureBucketKey;
  private configureBucketValue?: ConfigureBucketValue;
  private datafileUrl?: string;
  private handleDatafileFetch?: DatafileFetchHandler;
  private initialFeatures?: InitialFeatures;
  private interceptContext?: InterceptContext;
  private logger: Logger;
  private refreshInterval?: number; // seconds
  private stickyFeatures?: StickyFeatures;
 
  // internally created
  private datafileReader: DatafileReader;
  private emitter: Emitter;
  private statuses: Statuses;
  private intervalId?: ReturnType<typeof setInterval>;
 
  // exposed from emitter
  public on: Emitter["addListener"];
  public addListener: Emitter["addListener"];
  public off: Emitter["removeListener"];
  public removeListener: Emitter["removeListener"];
  public removeAllListeners: Emitter["removeAllListeners"];
 
  constructor(options: InstanceOptions) {
    // from options
    this.bucketKeySeparator = options.bucketKeySeparator || DEFAULT_BUCKET_KEY_SEPARATOR;
    this.configureBucketKey = options.configureBucketKey;
    this.configureBucketValue = options.configureBucketValue;
    this.datafileUrl = options.datafileUrl;
    this.handleDatafileFetch = options.handleDatafileFetch;
    this.initialFeatures = options.initialFeatures;
    this.interceptContext = options.interceptContext;
    this.logger = options.logger || createLogger();
    this.refreshInterval = options.refreshInterval;
    this.stickyFeatures = options.stickyFeatures;
 
    // internal
    this.emitter = new Emitter();
    this.statuses = {
      ready: false,
      refreshInProgress: false,
    };
 
    // register events
    if (options.onReady) {
      this.emitter.addListener("ready", options.onReady);
    }
 
    if (options.onRefresh) {
      this.emitter.addListener("refresh", options.onRefresh);
    }
 
    if (options.onUpdate) {
      this.emitter.addListener("update", options.onUpdate);
    }
 
    if (options.onActivation) {
      this.emitter.addListener("activation", options.onActivation);
    }
 
    // expose emitter methods
    const on = this.emitter.addListener.bind(this.emitter);
    this.on = on;
    this.addListener = on;
 
    const off = this.emitter.removeListener.bind(this.emitter);
    this.off = off;
    this.removeListener = off;
 
    this.removeAllListeners = this.emitter.removeAllListeners.bind(this.emitter);
 
    // datafile
    if (options.datafileUrl) {
      this.setDatafile(options.datafile || emptyDatafile);
 
      fetchDatafileContent(options.datafileUrl, options.handleDatafileFetch)
        .then((datafile) => {
          this.setDatafile(datafile);
 
          this.statuses.ready = true;
          this.emitter.emit("ready");
 
          if (this.refreshInterval) {
            this.startRefreshing();
          }
        })
        .catch((e) => {
          this.logger.error("failed to fetch datafile", { error: e });
        });
    } else if (options.datafile) {
      this.setDatafile(options.datafile);
      this.statuses.ready = true;
 
      setTimeout(() => {
        this.emitter.emit("ready");
      }, 0);
    } else E{
      throw new Error(
        "Featurevisor SDK instance cannot be created without both `datafile` and `datafileUrl` options",
      );
    }
  }
 
  setLogLevels(levels: LogLevel[]) {
    this.logger.setLevels(levels);
  }
 
  onReady(): Promise<FeaturevisorInstance> {
    return new Promise((resolve) => {
      if (this.statuses.ready) {
        return resolve(this);
      }
 
      const cb = () => {
        this.emitter.removeListener("ready", cb);
 
        resolve(this);
      };
 
      this.emitter.addListener("ready", cb);
    });
  }
 
  setDatafile(datafile: DatafileContent | string) {
    try {
      this.datafileReader = new DatafileReader(
        typeof datafile === "string" ? JSON.parse(datafile) : datafile,
      );
    } catch (e) {
      this.logger.error("could not parse datafile", { error: e });
    }
  }
 
  setStickyFeatures(stickyFeatures: StickyFeatures | undefined) {
    this.stickyFeatures = stickyFeatures;
  }
 
  getRevision(): string {
    return this.datafileReader.getRevision();
  }
 
  getFeature(featureKey: string | Feature): Feature | undefined {
    return typeof featureKey === "string"
      ? this.datafileReader.getFeature(featureKey) // only key provided
      : featureKey; // full feature provided
  }
 
  /**
   * Statuses
   */
  isReady(): boolean {
    return this.statuses.ready;
  }
 
  /**
   * Refresh
   */
  refresh() {
    this.logger.debug("refreshing datafile");
 
    Iif (this.statuses.refreshInProgress) {
      return this.logger.warn("refresh in progress, skipping");
    }
 
    Iif (!this.datafileUrl) {
      return this.logger.error("cannot refresh since `datafileUrl` is not provided");
    }
 
    this.statuses.refreshInProgress = true;
 
    fetchDatafileContent(this.datafileUrl, this.handleDatafileFetch)
      .then((datafile) => {
        const currentRevision = this.getRevision();
        const newRevision = datafile.revision;
        const isNotSameRevision = currentRevision !== newRevision;
 
        this.setDatafile(datafile);
        this.logger.info("refreshed datafile");
 
        this.emitter.emit("refresh");
 
        if (isNotSameRevision) {
          this.emitter.emit("update");
        }
 
        this.statuses.refreshInProgress = false;
      })
      .catch((e) => {
        this.logger.error("failed to refresh datafile", { error: e });
        this.statuses.refreshInProgress = false;
      });
  }
 
  startRefreshing() {
    Iif (!this.datafileUrl) {
      return this.logger.error("cannot start refreshing since `datafileUrl` is not provided");
    }
 
    Iif (this.intervalId) {
      return this.logger.warn("refreshing has already started");
    }
 
    Iif (!this.refreshInterval) {
      return this.logger.warn("no `refreshInterval` option provided");
    }
 
    this.intervalId = setInterval(() => {
      this.refresh();
    }, this.refreshInterval * 1000);
  }
 
  stopRefreshing() {
    Iif (!this.intervalId) {
      return this.logger.warn("refreshing has not started yet");
    }
 
    clearInterval(this.intervalId);
  }
 
  /**
   * Flag
   */
  evaluateFlag(featureKey: FeatureKey | Feature, context: Context = {}): Evaluation {
    return evaluate({
      type: "flag",
 
      featureKey,
      context,
 
      logger: this.logger,
      datafileReader: this.datafileReader,
      statuses: this.statuses,
      interceptContext: this.interceptContext,
 
      stickyFeatures: this.stickyFeatures,
      initialFeatures: this.initialFeatures,
 
      bucketKeySeparator: this.bucketKeySeparator,
      configureBucketKey: this.configureBucketKey,
      configureBucketValue: this.configureBucketValue,
    });
  }
 
  isEnabled(featureKey: FeatureKey | Feature, context: Context = {}): boolean {
    try {
      const evaluation = this.evaluateFlag(featureKey, context);
 
      return evaluation.enabled === true;
    } catch (e) {
      this.logger.error("isEnabled", { featureKey, error: e });
 
      return false;
    }
  }
 
  /**
   * Variation
   */
  evaluateVariation(featureKey: FeatureKey | Feature, context: Context = {}): Evaluation {
    return evaluate({
      type: "variation",
 
      featureKey,
      context,
 
      logger: this.logger,
      datafileReader: this.datafileReader,
      statuses: this.statuses,
      interceptContext: this.interceptContext,
 
      stickyFeatures: this.stickyFeatures,
      initialFeatures: this.initialFeatures,
 
      bucketKeySeparator: this.bucketKeySeparator,
      configureBucketKey: this.configureBucketKey,
      configureBucketValue: this.configureBucketValue,
    });
  }
 
  getVariation(
    featureKey: FeatureKey | Feature,
    context: Context = {},
  ): VariationValue | undefined {
    try {
      const evaluation = this.evaluateVariation(featureKey, context);
 
      if (typeof evaluation.variationValue !== "undefined") {
        return evaluation.variationValue;
      }
 
      if (evaluation.variation) {
        return evaluation.variation.value;
      }
 
      return undefined;
    } catch (e) {
      this.logger.error("getVariation", { featureKey, error: e });
 
      return undefined;
    }
  }
 
  /**
   * Activate
   */
  activate(featureKey: FeatureKey, context: Context = {}): VariationValue | undefined {
    try {
      const evaluation = this.evaluateVariation(featureKey, context);
      const variationValue = evaluation.variation
        ? evaluation.variation.value
        : evaluation.variationValue;
 
      Iif (typeof variationValue === "undefined") {
        return undefined;
      }
 
      const finalContext = this.interceptContext ? this.interceptContext(context) : context;
 
      const captureContext: Context = {};
 
      const attributesForCapturing = this.datafileReader
        .getAllAttributes()
        .filter((a) => a.capture === true);
 
      attributesForCapturing.forEach((a) => {
        Iif (typeof finalContext[a.key] !== "undefined") {
          captureContext[a.key] = context[a.key];
        }
      });
 
      this.emitter.emit(
        "activation",
        featureKey,
        variationValue,
        finalContext,
        captureContext,
        evaluation,
      );
 
      return variationValue;
    } catch (e) {
      this.logger.error("activate", { featureKey, error: e });
 
      return undefined;
    }
  }
 
  /**
   * Variable
   */
  evaluateVariable(
    featureKey: FeatureKey | Feature,
    variableKey: VariableKey,
    context: Context = {},
  ): Evaluation {
    return evaluate({
      type: "variable",
 
      featureKey,
      variableKey,
      context,
 
      logger: this.logger,
      datafileReader: this.datafileReader,
      statuses: this.statuses,
      interceptContext: this.interceptContext,
 
      stickyFeatures: this.stickyFeatures,
      initialFeatures: this.initialFeatures,
 
      bucketKeySeparator: this.bucketKeySeparator,
      configureBucketKey: this.configureBucketKey,
      configureBucketValue: this.configureBucketValue,
    });
  }
 
  getVariable(
    featureKey: FeatureKey | Feature,
    variableKey: string,
    context: Context = {},
  ): VariableValue | undefined {
    try {
      const evaluation = this.evaluateVariable(featureKey, variableKey, context);
 
      if (typeof evaluation.variableValue !== "undefined") {
        if (
          evaluation.variableSchema &&
          evaluation.variableSchema.type === "json" &&
          typeof evaluation.variableValue === "string"
        ) {
          return JSON.parse(evaluation.variableValue);
        }
 
        return evaluation.variableValue;
      }
 
      return undefined;
    } catch (e) {
      this.logger.error("getVariable", { featureKey, variableKey, error: e });
 
      return undefined;
    }
  }
 
  getVariableBoolean(
    featureKey: FeatureKey | Feature,
    variableKey: string,
    context: Context = {},
  ): boolean | undefined {
    const variableValue = this.getVariable(featureKey, variableKey, context);
 
    return getValueByType(variableValue, "boolean") as boolean | undefined;
  }
 
  getVariableString(
    featureKey: FeatureKey | Feature,
    variableKey: string,
    context: Context = {},
  ): string | undefined {
    const variableValue = this.getVariable(featureKey, variableKey, context);
 
    return getValueByType(variableValue, "string") as string | undefined;
  }
 
  getVariableInteger(
    featureKey: FeatureKey | Feature,
    variableKey: string,
    context: Context = {},
  ): number | undefined {
    const variableValue = this.getVariable(featureKey, variableKey, context);
 
    return getValueByType(variableValue, "integer") as number | undefined;
  }
 
  getVariableDouble(
    featureKey: FeatureKey | Feature,
    variableKey: string,
    context: Context = {},
  ): number | undefined {
    const variableValue = this.getVariable(featureKey, variableKey, context);
 
    return getValueByType(variableValue, "double") as number | undefined;
  }
 
  getVariableArray(
    featureKey: FeatureKey | Feature,
    variableKey: string,
    context: Context = {},
  ): string[] | undefined {
    const variableValue = this.getVariable(featureKey, variableKey, context);
 
    return getValueByType(variableValue, "array") as string[] | undefined;
  }
 
  getVariableObject<T>(
    featureKey: FeatureKey | Feature,
    variableKey: string,
    context: Context = {},
  ): T | undefined {
    const variableValue = this.getVariable(featureKey, variableKey, context);
 
    return getValueByType(variableValue, "object") as T | undefined;
  }
 
  getVariableJSON<T>(
    featureKey: FeatureKey | Feature,
    variableKey: string,
    context: Context = {},
  ): T | undefined {
    const variableValue = this.getVariable(featureKey, variableKey, context);
 
    return getValueByType(variableValue, "json") as T | undefined;
  }
}
 
export function createInstance(options: InstanceOptions): FeaturevisorInstance {
  return new FeaturevisorInstance(options);
}