import path from 'path' ; import { deepMerge } from '@empathyco/x-deep-merge' ; import { exportToFile , getParams , getSourcePaths , loadFile } from './utils' ; import { JSON } from './types' ; if ( require . main === module ) { getCSVTranslations ( ) ; } param json returns function getColumnNames ( json ) { return Object . keys ( json ) ; } param sourcePath returns function generateCSVFile ( sourcePath ) { const json = loadFile ( sourcePath ) as JSON ; const csv = transformToCSV ( json ) ; const outputFile = path . basename ( sourcePath ) . replace ( /\.[^.]+$/ , '.csv' ) ; exportToFile ( outputFile , csv ) ; return csv ; } param columnNames param source returns function getTranslations ( columnNames , source ) { return columnNames . reduce ( ( translations , column ) => deepMerge ( translations , getTranslation ( source [ column ] as JSON , column ) ) , { } ) ; } param source param column returns example function getTranslation ( source , column ) { return Object . entries ( source ) . reduce ( ( translation , [ key , value ] ) => { if ( typeof value === 'object' ) { const flatObject = getTranslation ( value as JSON , column ) ; Object . entries ( flatObject ) . forEach ( ( [ subKey , subValue ] ) => { translation [ key + '.' + subKey ] = subValue ; } ) ; } else { if ( ! ( key in translation ) ) { translation [ key ] = { } ; } ( translation [ key ] as JSON ) [ column ] = value ; } return translation ; } , { } ) ; } param sourceJson returns function transformToCSV ( sourceJson ) { const columnNames = getColumnNames ( sourceJson ) ; const translations = getTranslations ( columnNames , sourceJson ) ; const delimiter = ';' ; let csv = [ 'key' , ... columnNames ] . join ( delimiter ) + '\n' ; Object . entries ( translations ) . forEach ( ( [ key , value ] ) => { const line = [ key ] ; columnNames . forEach ( columnName => { line . push ( `${ ( ( value as JSON ) [ columnName ] as string ) ?? '' }` ) ; } ) ; csv += line . join ( delimiter ) + '\n' ; } ) ; return csv ; } returns export function getCSVTranslations ( ) { const { sourcePath } = getParams ( ) ; return getSourcePaths ( sourcePath , 'json' ) . map ( generateCSVFile ) ; }