All files / utils validation.ts

96.7% Statements 88/91
92.85% Branches 39/42
100% Functions 17/17
96.34% Lines 79/82

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        94x   94x       94x 94x 94x                     94x         88x 88x 79x   9x 9x                                                 94x         4318x   3481x                                           94x       19x   4x                             94x 310x                                     94x 532x                                   94x       569x                     94x         7x   5x       5x                                         94x       18x                           94x         21x   21x 15x 15x 15x 3x     12x     6x         94x   4337x 2858x 1479x   1479x 461x 1018x 11x   1007x     4337x 3524x       94x         320x 228x     92x 92x 10x     82x     94x         532x 480x     52x 52x 3x         49x                                         4060x 487x     3573x 15x 3558x 49x     3509x     94x           18x 7x     11x 11x 7x     4x 1x         3x    
/**
 * @module Utils
 */
 
import * as MH from "@lisn/globals/minification-helpers";
 
import { LisnUsageError } from "@lisn/globals/errors";
 
import { CommaSeparatedStr, RawOrRelativeNumber } from "@lisn/globals/types";
 
import { toNum, toRawNum } from "@lisn/utils/math";
import { toBoolean } from "@lisn/utils/misc";
import { splitOn } from "@lisn/utils/text";
 
/**
 * Returns true if the input is a string array or comma-separated string, whose
 * elements are valid according to the `validator` function.
 *
 * @param allowEmpty If `false`, then input without any entries is
 * considered _invalid_.
 *
 * @category Validation
 */
export const isValidStrList = <T extends string = string>(
  value: unknown,
  checkFn: (value: string) => value is T,
  allowEmpty = true,
): value is CommaSeparatedStr<T> | T[] => {
  try {
    const res = validateStrList("", value, checkFn);
    return allowEmpty || !MH.isNullish(res);
  } catch (err) {
    if (MH.isInstanceOf(err, LisnUsageError)) {
      return false;
    }
    throw err;
  }
};
 
/**
 * Returns an array of strings from the given list (array or comma-separated
 * string) while validating each one using the `checkFn` function.
 *
 * If it returns without throwing, the input is necessarily valid.
 * If the result is an empty array, it will return `null`.
 *
 * @throws {@link Errors.LisnUsageError | LisnUsageError}
 *                If the input is not a string or array of strings, or if any
 *                entries do not pass `checkFn`.
 *
 * @param key Used in the error message thrown
 *
 * @returns `undefined` if the input contains no non-empty values (after
 * trimming whitespace on left/right from each), otherwise a non-empty array of
 * values.
 *
 * @category Validation
 */
export const validateStrList = <T extends string = string>(
  key: string,
  value: unknown,
  checkFn?: (value: string) => value is T,
): T[] | undefined =>
  MH.filterBlank(
    toArray(value)?.map((v) =>
      _validateString(key, v, checkFn, "a string or a string array"),
    ),
  );
 
/**
 * Returns an array of numbers from the given list.
 *
 * If it returns without throwing, the input is necessarily valid.
 * If the result is an empty array, it will return `null`.
 *
 * @throws {@link Errors.LisnUsageError | LisnUsageError}
 *                If the input is not a number or array of numbers. Numerical
 *                strings are accepted.
 *
 * @param key Used in the error message thrown
 *
 * @returns `undefined` if the input contains no non-empty values (after
 * trimming whitespace on left/right from each), otherwise a non-empty array of
 * values.
 *
 * @category Validation
 */
export const validateNumList = (
  key: string,
  value: unknown,
): number[] | undefined =>
  MH.filterBlank(
    toArray(value)?.map((v) =>
      _validateNumber(key, v, "a number or a number array"),
    ),
  );
 
/**
 * Returns a number corresponding to the supplied value, ensuring the supplied
 * value is a valid number or a string containing only a number.
 *
 * @throws {@link Errors.LisnUsageError | LisnUsageError}
 *                If the value is invalid.
 *
 * @returns `undefined` if the input is nullish.
 *
 * @category Validation
 */
export const validateNumber = (key: string, value: unknown) =>
  _validateNumber(key, value);
 
/**
 * Returns a boolean corresponding to the given value as follows:
 *
 * - `null` and `undefined` result in `undefined`
 * - `false` and `"false"` result in `false`
 * - `""`, `true` and `"true"` result in `true`
 * - other values throw an error error
 *
 * Note that an empty string is treated as `true`.
 *
 * @throws {@link Errors.LisnUsageError | LisnUsageError}
 *                If the value is not a valid boolean or boolean string.
 *
 * @returns `undefined` if the input is nullish.
 *
 * @category Validation
 */
export const validateBoolean = (key: string, value: unknown) =>
  _validateBoolean(key, value);
 
/**
 * Returns a valid string from the supplied value, ensuring the supplied value
 * is a string that conforms to the given `checkFn`.
 *
 * @throws {@link Errors.LisnUsageError | LisnUsageError}
 *                If the value is invalid.
 *
 * @param checkFn If given and the supplied value is a string, then it is
 *                called with the value as a single argument. It must return
 *                true if the value is valid and false otherwise. If it is not
 *                given, then any literal string is accepted.
 *
 * @returns `undefined` if the input is nullish.
 *
 * @category Validation
 */
export const validateString = <T extends string = string>(
  key: string,
  value: unknown,
  checkFn?: (value: string) => value is T,
) => _validateString(key, value, checkFn);
 
/**
 * Like {@link validateString} except it requires input to be given and
 * non-empty.
 *
 * @throws {@link Errors.LisnUsageError | LisnUsageError}
 *                If the value is invalid or empty.
 *
 * @category Validation
 */
export const validateStringRequired = <T extends string = string>(
  key: string,
  value: unknown,
  checkFn?: (value: string) => value is T,
): T => {
  const result = _validateString(key, value, checkFn);
 
  Iif (MH.isEmpty(result)) {
    throw MH.usageError(`'${key}' is required`);
  }
 
  return result;
};
 
/**
 * Returns a valid boolean or a string from the supplied value, ensuring the
 * supplied value is either a boolean or boolean string (see
 * {@link validateBoolean}), or a string that conforms to the given `checkFn`.
 *
 * @throws {@link Errors.LisnUsageError | LisnUsageError}
 *                If the value is invalid.
 *
 * @param stringCheckFn If given and the supplied value is a string _other than
 *                      a boolean string_, then it is called with the value as
 *                      a single argument. It must return true if the value is
 *                      valid and false otherwise. If it is not given, then any
 *                      literal string is accepted.
 *
 * @returns `undefined` if the input is nullish.
 *
 * @category Validation
 */
export const validateBooleanOrString = <T extends string = string>(
  key: string,
  value: unknown,
  stringCheckFn?: (value: string) => value is T,
) => _validateBooleanOrString(key, value, stringCheckFn);
 
/**
 * Returns an {@link RawOrRelativeNumber} corresponding to the supplied
 * value.
 *
 * @param key Used in the error message thrown
 *
 * @returns `undefined` if the input is nullish.
 *
 * @since v1.3.0
 *
 * @category Validation
 */
export const validateRawOrRelativeNumber = (
  key: string,
  value: unknown,
): RawOrRelativeNumber | undefined => {
  const typeDescription =
    "numerical with an optional prefix of + or -, or suffix of %";
 
  if (MH.isString(value)) {
    const isRaw = toRawNum(value, NaN, false) !== false; // reference was not used
    const raw = toRawNum(value, 1, false);
    if (raw === false) {
      throw MH.usageError(`'${key}' must be ${typeDescription}`);
    }
 
    return isRaw ? raw : (value as RawOrRelativeNumber);
  }
 
  return _validateNumber(key, value, typeDescription);
};
 
// --------------------
 
const toArray = (value: unknown): unknown[] | undefined => {
  let result: unknown[] | null;
  if (MH.isArray(value)) {
    result = value;
  } else Iif (MH.isIterableObject(value)) {
    result = MH.arrayFrom(value);
  } else if (MH.isLiteralString(value)) {
    result = splitOn(value, ",");
  } else if (!MH.isNullish(value)) {
    result = [value];
  } else {
    result = null;
  }
 
  return result
    ? MH.filterBlank(result.map((v) => (MH.isLiteralString(v) ? v.trim() : v)))
    : undefined;
};
 
const _validateNumber = (
  key: string,
  value: unknown,
  typeDescription?: string,
) => {
  if (MH.isNullish(value)) {
    return;
  }
 
  const numVal = toNum(value, null);
  if (numVal === null) {
    throw MH.usageError(`'${key}' must be ${typeDescription ?? "a number"}`);
  }
 
  return numVal;
};
 
const _validateBoolean = (
  key: string,
  value: unknown,
  typeDescription?: string,
) => {
  if (MH.isNullish(value)) {
    return;
  }
 
  const boolVal = toBoolean(value);
  if (boolVal === null) {
    throw MH.usageError(
      `'${key}' must be ${typeDescription ?? '"true" or "false"'}`,
    );
  }
 
  return boolVal;
};
 
function _validateString<T extends string = string>(
  key: string,
  value: unknown,
  checkFn?: (value: string) => value is T,
  typeDescription?: string,
): T;
function _validateString(
  key: string,
  value: unknown,
  checkFn: null,
  typeDescription: string,
): string;
function _validateString(
  key: string,
  value: unknown,
  checkFn?: null | ((value: string) => boolean),
  typeDescription?: string,
) {
  if (MH.isNullish(value)) {
    return;
  }
 
  if (!MH.isLiteralString(value)) {
    throw MH.usageError(`'${key}' must be ${typeDescription ?? "a string"}`);
  } else if (checkFn && !checkFn(value)) {
    throw MH.usageError(`Invalid value for '${key}'`);
  }
 
  return value;
}
 
const _validateBooleanOrString = <T extends string = string>(
  key: string,
  value: unknown,
  stringCheckFn?: (value: string) => value is T,
  typeDescription?: string,
) => {
  if (MH.isNullish(value)) {
    return;
  }
 
  const boolVal = toBoolean(value);
  if (boolVal !== null) {
    return boolVal;
  }
 
  if (!MH.isLiteralString(value)) {
    throw MH.usageError(
      `'${key}' must be ${typeDescription ?? "a boolean or string"}`,
    );
  }
 
  return _validateString(key, value, stringCheckFn);
};