UNPKG

@vendure/ngx-translate-extract

Version:
38 lines (37 loc) 1.38 kB
import { TranslationCollection } from '../utils/translation.collection.js'; import { stripBOM } from '../utils/utils.js'; import { flatten } from 'flat'; export class JsonCompiler { indentation = '\t'; trailingNewline = false; extension = 'json'; constructor(options) { if (options && typeof options.indentation !== 'undefined') { this.indentation = options.indentation; } if (options && typeof options.trailingNewline !== 'undefined') { this.trailingNewline = options.trailingNewline; } } compile(collection) { return JSON.stringify(collection.toKeyValueObject(), null, this.indentation) + (this.trailingNewline ? '\n' : ''); } parse(contents) { let values = JSON.parse(stripBOM(contents)); if (this.isNamespacedJsonFormat(values)) { values = flatten(values); } const newValues = {}; Object.entries(values).forEach(([key, value]) => newValues[key] = { value: value, sourceFiles: [] }); return new TranslationCollection(newValues); } isNamespacedJsonFormat(values) { if (!isObject(values)) { return false; } return Object.keys(values).some((key) => typeof values[key] === 'object'); } } function isObject(value) { return typeof value === 'object' && value !== null; }