All files / common/util validations.ts

100% Statements 46/46
87.5% Branches 7/8
100% Functions 10/10
100% Lines 40/40

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 18219x 19x 19x   19x   19x   19x 19x         19x   8x         19x 22x         19x               19x                             19x                   19x                                                                                                                   19x 2x   2x           19x           238x   237x 36x         201x           19x 36x   36x 43x 43x   43x   43x 4x 4x     43x   43x 6x     37x             19x 43x 40x     43x    
import {ZodIssue, ZodIssueCode, ZodSchema, z} from 'zod';
import {AGGREGATION_METHODS} from '@grnsft/if-core/consts';
import {ERRORS} from '@grnsft/if-core/utils';
 
import {STRINGS} from '../../if-run/config';
 
import {AGGREGATION_TYPES} from '../../if-run/types/aggregation';
 
const {ManifestValidationError, InputValidationError} = ERRORS;
const {VALIDATING_MANIFEST} = STRINGS;
 
/**
 * At least one property defined handler.
 */
export const atLeastOneDefined = (
  obj: Record<string | number | symbol, unknown>
) => Object.values(obj).some(v => v !== undefined);
 
/**
 * All properties are defined handler.
 */
export const allDefined = (obj: Record<string | number | symbol, unknown>) =>
  Object.values(obj).every(v => v !== undefined);
 
/**
 * Reusabe aggregation method schema for parameter metadata.
 */
const aggregationMethodSchema = z.object({
  time: z.enum(AGGREGATION_METHODS),
  component: z.enum(AGGREGATION_METHODS),
});
 
/**
 * Reusable metadata schema.
 */
const metadataSchema = z
  .record(
    z.string(),
    z.object({
      unit: z.string(),
      description: z.string(),
      'aggregation-method': aggregationMethodSchema,
    })
  )
  .optional()
  .nullable();
 
/**
 * Reusable parameter metadata schema.
 */
const parameterMetadataSchema = z
  .object({
    inputs: metadataSchema,
    outputs: metadataSchema,
  })
  .optional();
 
/**
 * Validation schema for manifests.
 */
export const manifestSchema = z.object({
  name: z.string(),
  description: z.string().optional().nullable(),
  tags: z
    .object({
      kind: z.string().optional().nullable(),
      complexity: z.string().optional().nullable(),
      category: z.string().optional().nullable(),
    })
    .optional()
    .nullable(),
  explainer: z.boolean().optional(),
  explain: z.record(z.string(), z.any()).optional(),
  aggregation: z
    .object({
      metrics: z.array(z.string()),
      type: z.enum(AGGREGATION_TYPES),
      'skip-components': z.array(z.string()).optional(),
    })
    .optional()
    .nullable(),
  initialize: z.object({
    plugins: z.record(
      z.string(),
      z
        .object({
          path: z.string(),
          method: z.string(),
          mapping: z.record(z.string(), z.string()).optional(),
          config: z.record(z.string(), z.any()).optional(),
          'parameter-metadata': parameterMetadataSchema,
        })
        .optional()
    ),
  }),
  execution: z
    .object({
      command: z.string().optional(),
      environment: z
        .object({
          'if-version': z.string(),
          os: z.string(),
          'os-version': z.string(),
          'node-version': z.string(),
          'date-time': z.string(),
          dependencies: z.array(z.string()),
        })
        .optional(),
      status: z.string(),
      error: z.string().optional(),
    })
    .optional(),
  tree: z.record(z.string(), z.any()),
});
 
/**
 * Validates given `manifest` object to match pattern.
 */
export const validateManifest = (manifest: any) => {
  console.debug(VALIDATING_MANIFEST);
 
  return validate(manifestSchema, manifest, undefined, ManifestValidationError);
};
 
/**
 * Validates given `object` with given `schema`.
 */
export const validate = <T>(
  schema: ZodSchema<T>,
  object: any,
  index?: number,
  errorConstructor: ErrorConstructor = InputValidationError
) => {
  const validationResult = schema.safeParse(object);
 
  if (!validationResult.success) {
    throw new errorConstructor(
      prettifyErrorMessage(validationResult.error.message, index)
    );
  }
 
  return validationResult.data;
};
 
/**
 * Error message formatter for zod issues.
 */
const prettifyErrorMessage = (issues: string, index?: number) => {
  const issuesArray = JSON.parse(issues);
 
  return issuesArray.map((issue: ZodIssue) => {
    const code = issue.code;
    let {path, message} = issue;
 
    const indexErrorMessage = index !== undefined ? ` at index ${index}` : '';
 
    if (issue.code === ZodIssueCode.invalid_union) {
      message = issue.unionErrors[0].issues[0].message;
      path = issue.unionErrors[0].issues[0].path;
    }
 
    const fullPath = flattenPath(path);
 
    if (!fullPath) {
      return message;
    }
 
    return `"${fullPath}" parameter is ${message.toLowerCase()}${indexErrorMessage}. Error code: ${code}.`;
  });
};
 
/**
 * Flattens an array representing a nested path into a string.
 */
const flattenPath = (path: (string | number)[]): string => {
  const flattenPath = path.map(part =>
    typeof part === 'number' ? `[${part}]` : part
  );
 
  return flattenPath.join('.');
};