All files / src utils.ts

97.93% Statements 95/97
95.34% Branches 41/43
100% Functions 27/27
97.82% Lines 90/92

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 2081x 1x 1x 1x 1x 1x     1x 308x 308x   6x       1x 280x 280x   149x       1x 39x 37x   101x 101x   2x     1x             139x 139x       138x   1x       1x 58x 58x 58x 58x   1x       1x 1602x 188x 12x   176x   1414x     1x 2788x     1x 6x       6x                   6x 119x 95x   95x 44x 11x 11x 11x         6x     1x 73x                             1x 96x 1x   95x                     95x   95x     247x     95x 855x     95x     1x 118x   118x 463x   463x 118x             1x 19x 6x       1x 6x 6x         1x 13x   13x 50x   4x       13x     1x 31x 31x 26x   5x       1x 20x 20x 17x    
import fs from 'fs-extra';
import path from 'path';
import sanitizeName from 'sanitize-filename';
import dotProp from 'dot-prop';
import { loadFileAndReplaceKeywords, Auth0 } from './tools';
import log from './logger';
import { Asset, Assets, Config, KeywordMappings } from './types';
 
export function isDirectory(filePath: string): boolean {
  try {
    return fs.statSync(path.resolve(filePath)).isDirectory();
  } catch (err) {
    return false;
  }
}
 
export function isFile(filePath: string): boolean {
  try {
    return fs.statSync(path.resolve(filePath)).isFile();
  } catch (err) {
    return false;
  }
}
 
export function getFiles(folder: string, exts: string[]): string[] {
  if (isDirectory(folder)) {
    return fs
      .readdirSync(folder)
      .map((f) => path.join(folder, f))
      .filter((f) => isFile(f) && exts.includes(path.extname(f)));
  }
  return [];
}
 
export function loadJSON(
  file: string,
  opts: { disableKeywordReplacement: boolean; mappings: KeywordMappings } = {
    disableKeywordReplacement: false,
    mappings: {},
  }
): any {
  try {
    const content = loadFileAndReplaceKeywords(file, {
      mappings: opts.mappings,
      disableKeywordReplacement: opts.disableKeywordReplacement,
    });
    return JSON.parse(content);
  } catch (e) {
    throw new Error(`Error parsing JSON from metadata file: ${file}, because: ${e.message}`);
  }
}
 
export function dumpJSON(file: string, mappings: { [key: string]: any }): void {
  try {
    log.info(`Writing ${file}`);
    const jsonBody = JSON.stringify(mappings, null, 2);
    fs.writeFileSync(file, jsonBody.endsWith('\n') ? jsonBody : `${jsonBody}\n`);
  } catch (e) {
    throw new Error(`Error writing JSON to metadata file: ${file}, because: ${e.message}`);
  }
}
 
export function existsMustBeDir(folder: string): boolean {
  if (fs.existsSync(folder)) {
    if (!isDirectory(folder)) {
      throw new Error(`Expected ${folder} to be a folder but got a file?`);
    }
    return true;
  }
  return false;
}
 
export function toConfigFn(data: Config): (arg0: keyof Config) => any {
  return (key) => data[key];
}
 
export function stripIdentifiers(auth0: Auth0, assets: Assets) {
  const updated = { ...assets };
 
  // Some of the object identifiers are required to perform updates.
  // Don't strip these object id's
  const ignore = [
    'actions',
    'rulesConfigs',
    'emailTemplates',
    'guardianFactors',
    'guardianFactorProviders',
    'guardianFactorTemplates',
  ];
 
  // Optionally Strip identifiers
  auth0.handlers.forEach((h) => {
    if (ignore.includes(h.type)) return;
    const exist = updated[h.type];
    // All objects with the identifier field is an array. This could change in future.
    if (Array.isArray(exist)) {
      updated[h.type] = exist.map((o) => {
        const newObj = { ...o };
        delete newObj[h.id];
        return newObj;
      });
    }
  });
 
  return updated;
}
 
export function sanitize(str: string): string {
  return sanitizeName(str, { replacement: '-' });
}
 
type ImportantFields = {
  name: string | null;
  client_id: string | null;
  audience: string | null;
  template: string | null;
  identifier: string | null;
  strategy: string | null;
  script: string | null;
  stage: string | null;
  id: string | null;
};
 
export function formatResults(item: any): Partial<ImportantFields> {
  if (!item || typeof item !== 'object') {
    return item;
  }
  const importantFields: ImportantFields = {
    name: null,
    client_id: null,
    audience: null,
    template: null,
    identifier: null,
    strategy: null,
    script: null,
    stage: null,
    id: null,
  };
  const result = { ...importantFields };
 
  Object.entries(item)
    .sort()
    .forEach(([key, value]) => {
      result[key] = value;
    });
 
  Object.keys(importantFields).forEach((key) => {
    if (result[key] === null) delete result[key];
  });
 
  return result;
}
 
export function recordsSorter(a: Partial<ImportantFields>, b: Partial<ImportantFields>): number {
  const importantFields = ['name', 'key', 'client_id', 'template'];
 
  for (let i = 0; i < importantFields.length; i += 1) {
    const key = importantFields[i];
 
    if (a[key] && b[key]) {
      return a[key] > b[key] ? 1 : -1;
    }
  }
 
  return 0;
}
 
export function clearTenantFlags(tenant: Asset): void {
  if (tenant.flags && !Object.keys(tenant.flags).length) {
    delete tenant.flags;
  }
}
 
export function ensureProp(obj: Asset, props: string): void {
  const value = '';
  Iif (!dotProp.has(obj, props)) {
    dotProp.set(obj, props, value);
  }
}
 
export function clearClientArrays(client: Asset): Asset {
  const propsToClear = ['allowed_clients', 'allowed_logout_urls', 'allowed_origins', 'callbacks'];
  //If designated properties are null, set them as empty arrays instead
  Object.keys(client).forEach((prop) => {
    if (propsToClear.indexOf(prop) >= 0 && !client[prop]) {
      //TODO: understand why setting as empty array instead of deleting null prop. Ex: `delete client[prop]`
      client[prop] = [];
    }
  });
 
  return client;
}
 
export function convertClientIdToName(clientId: string, knownClients: Asset[] = []): string {
  try {
    const found = knownClients.find((c) => c.client_id === clientId);
    return (found && found.name) || clientId;
  } catch (e) {
    return clientId;
  }
}
 
export function mapClientID2NameSorted(enabledClients: string[], knownClients: Asset[]): string[] {
  return [
    ...(enabledClients || []).map((clientId) => convertClientIdToName(clientId, knownClients)),
  ].sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()));
}