next-intl
Version:
Internationalization (i18n) for Next.js
41 lines (38 loc) • 1.09 kB
JavaScript
import { getSortedMessages, setNestedProperty } from '../../utils.js';
import { defineCodec } from '../ExtractorCodec.js';
var JSONCodec = defineCodec(() => ({
decode(source) {
const json = JSON.parse(source);
const messages = [];
traverseMessages(json, (message, id) => {
messages.push({
id,
message
});
});
return messages;
},
encode(messages) {
const root = {};
for (const message of getSortedMessages(messages)) {
setNestedProperty(root, message.id, message.message);
}
return JSON.stringify(root, null, 2) + '\n';
},
toJSONString(source) {
return source;
}
}));
function traverseMessages(obj, callback, path = '') {
const NAMESPACE_SEPARATOR = '.';
for (const key of Object.keys(obj)) {
const newPath = path ? path + NAMESPACE_SEPARATOR + key : key;
const value = obj[key];
if (typeof value === 'string') {
callback(value, newPath);
} else if (typeof value === 'object') {
traverseMessages(value, callback, newPath);
}
}
}
export { JSONCodec as default };