All files / src/context/directory/handlers hooks.ts

96.77% Statements 30/31
75% Branches 6/8
100% Functions 4/4
100% Lines 29/29

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 691x 1x 1x   1x 1x               62x 62x   2x   2x 4x           4x 4x     4x   4x     2x           2x   2x     2x 2x 2x     3x 3x 3x 3x 3x     3x 3x       1x         1x  
import fs from 'fs-extra';
import path from 'path';
import { constants } from '../../../tools';
 
import { getFiles, existsMustBeDir, dumpJSON, loadJSON, sanitize } from '../../../utils';
import log from '../../../logger';
import { DirectoryHandler } from '.';
import DirectoryContext from '..';
import { Asset, ParsedAsset } from '../../../types';
 
type ParsedHooks = ParsedAsset<'hooks', Asset[]>;
 
function parse(context: DirectoryContext): ParsedHooks {
  const hooksFolder = path.join(context.filePath, constants.HOOKS_DIRECTORY);
  if (!existsMustBeDir(hooksFolder)) return { hooks: null }; // Skip
 
  const files = getFiles(hooksFolder, ['.json']);
 
  const hooks = files.map((f) => {
    const hook = {
      ...loadJSON(f, {
        mappings: context.mappings,
        disableKeywordReplacement: context.disableKeywordReplacement,
      }),
    };
    Eif (hook.script) {
      hook.script = context.loadFile(hook.script, constants.HOOKS_DIRECTORY);
    }
 
    hook.name = hook.name.toLowerCase().replace(/\s/g, '-');
 
    return hook;
  });
 
  return {
    hooks,
  };
}
 
async function dump(context: DirectoryContext): Promise<void> {
  const hooks = context.assets.hooks;
 
  Iif (!hooks) return;
 
  // Create Hooks folder
  const hooksFolder = path.join(context.filePath, constants.HOOKS_DIRECTORY);
  fs.ensureDirSync(hooksFolder);
  hooks.forEach((hook) => {
    // Dump script to file
    // For cases when hook does not have `meta['hook-name']`
    hook.name = hook.name || hook.id;
    const name = sanitize(hook.name);
    const hookCode = path.join(hooksFolder, `${name}.js`);
    log.info(`Writing ${hookCode}`);
    fs.writeFileSync(hookCode, hook.script);
 
    // Dump template metadata
    const hookFile = path.join(hooksFolder, `${name}.json`);
    dumpJSON(hookFile, { ...hook, script: `./${name}.js` });
  });
}
 
const hooksHandler: DirectoryHandler<ParsedHooks> = {
  parse,
  dump,
};
 
export default hooksHandler;