All files / Rindu/utils/configuration schema.ts

93.33% Statements 14/15
100% Branches 7/7
100% Functions 6/6
100% Lines 12/12

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    140x           66x   45x     25x     32x     28x     34x       85x       51x     18x 18x   18x          
import type { Configuration, Validators } from "types/configuration";
 
export const DEFAULT_CONFIG: Configuration = {
  isDocPipEnabled: true,
  theme: "system",
  volume: 1,
};
 
export const CONFIGURATION_STORAGE_KEY = "app_config";
 
export const validators: Validators = {
  isDocPipEnabled: (
    value: unknown
  ): value is Configuration["isDocPipEnabled"] => typeof value === "boolean",
 
  theme: (value: unknown): value is Configuration["theme"] =>
    typeof value === "string" && ["light", "dark", "system"].includes(value),
 
  volume: (value: unknown): value is Configuration["volume"] =>
    typeof value === "number" && value >= 0 && value <= 1,
};
 
export function isValidValue<K extends keyof Configuration>(
  key: K,
  value: unknown
): value is Configuration[K] {
  return validators[key](value);
}
 
function isValidConfigEntry([key, value]: [string, unknown]): boolean {
  return key in validators && isValidValue(key as keyof Configuration, value);
}
 
export function validateConfig(config: Partial<Configuration>): Configuration {
  const validatedEntries = Object.entries(config).filter(isValidConfigEntry);
 
  return {
    ...DEFAULT_CONFIG,
    ...Object.fromEntries(validatedEntries),
  };
}