import { join , dirname } from 'path' ; import { readJsonSync , readFileSync , existsSync } from 'fs-extra' ; import traverse from 'traverse' ; import dirTree from 'directory-tree' ; import { TemplateManifest , MetaFileTraverse , MetaFile } from '../../types' ; /**
 * Parses templates folder and files
 */ export const createManifest = ( path ) : TemplateManifest [ ] => { let manifest = [ ] ; if ( ! existsSync ( path ) ) return manifest ; const list = findMetaFiles ( path ) ; list . forEach ( file => { const item = createManifestItem ( file ) ; if ( item ) manifest . push ( item ) ; } ) ; return manifest ; } ; /**
 * Searches for all metadata files and flattens into a collection
 */ export const findMetaFiles = ( path ) : MetaFileTraverse [ ] => traverse ( dirTree ( path ) ) . reduce ( ( acc , file ) => { if ( file . name === 'meta.json' ) acc . push ( file ) ; return acc ; } , [ ] ) ; /**
 * Gathers the template's content and metadata based on the metadata file location
 */ export const createManifestItem = ( file ) : MetaFile | null => { const { path } = file ; const rootPath = dirname ( path ) ; const htmlPath = join ( rootPath , 'content.html' ) ; const textPath = join ( rootPath , 'content.txt' ) ; if ( existsSync ( path ) ) { const metaFile = readJsonSync ( path ) ; const htmlFile = existsSync ( htmlPath ) ? readFileSync ( htmlPath , 'utf-8' ) : '' ; const textFile = existsSync ( textPath ) ? readFileSync ( textPath , 'utf-8' ) : '' ; return { HtmlBody : htmlFile , TextBody : textFile , ... metaFile , } ; } return null ; } ;