@l10nmonster/helpers-json 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,13 @@
1
+ # L10n Monster JSON Helpers
2
+
3
+ ### JSON Filter
4
+
5
+ A filter for JSON files. It supports annotations as defined by the [ARB spec](https://github.com/google/app-resource-bundle/wiki/ApplicationResourceBundleSpecification). In addition it supports nested keys and plurals as defined by the [i18next JSON v4](https://www.i18next.com/misc/json-format) format.
6
+
7
+ ```js
8
+ this.resourceFilter = new filters.JsonFilter({
9
+ enableArbAnnotations: true,
10
+ enablePluralSuffixes: true,
11
+ emitArbAnnotations: true
12
+ });
13
+ ```
package/i18next.js ADDED
@@ -0,0 +1,85 @@
1
+ // i18next v4 json format defined at https://www.i18next.com/misc/json-format
2
+ const flat = require('flat');
3
+ const { regex } = require('@l10nmonster/helpers');
4
+
5
+ const isArbAnnotations = e => e[0].split('.').slice(-2)[0].startsWith('@');
6
+ const validArbAnnotations = new Set(['description', 'type', 'context', 'placeholders', 'screenshot', 'video', 'source_text']);
7
+ const validPluralSuffixes = new Set(['one', 'other', 'zero', 'two', 'few', 'many']);
8
+ const extractArbGroupsRegex = /(?<prefix>.+?\.)?@(?<key>\S+)\.(?<attribute>\S+)/;
9
+
10
+ function parseResourceAnnotations(resource, enableArbAnnotations) {
11
+ let parsedResource = Object.entries(flat.flatten(resource));
12
+ const notes = {};
13
+ if (enableArbAnnotations) {
14
+ for (const [key, value] of parsedResource.filter(isArbAnnotations)) {
15
+ const arbGroups = extractArbGroupsRegex.exec(key).groups;
16
+ const sid = `${arbGroups.prefix ?? ''}${arbGroups.key}`;
17
+ if (validArbAnnotations.has(arbGroups.attribute)) {
18
+ notes[sid] = `${notes[sid] ? `${notes[sid]}\n` : ''}${arbGroups.attribute === 'description' ? '' : `${arbGroups.attribute}: `}${arbGroups.attribute === 'placeholders' ? JSON.stringify(value) : value}`;
19
+ } else {
20
+ l10nmonster.logger.verbose(`Unexpected ${arbGroups.attribute} annotation for SID ${sid}`);
21
+ }
22
+ }
23
+ }
24
+ enableArbAnnotations && (parsedResource = parsedResource.filter(e => !isArbAnnotations(e)));
25
+ return [ parsedResource, notes ];
26
+ }
27
+
28
+ exports.Filter = class I18nextFilter {
29
+ constructor(params) {
30
+ this.enableArbAnnotations = params?.enableArbAnnotations || false;
31
+ this.enablePluralSuffixes = params?.enablePluralSuffixes || false;
32
+ this.emitArbAnnotations = params?.emitArbAnnotations || false;
33
+ }
34
+
35
+ async parseResource({ resource }) {
36
+ const segments = [];
37
+ const [ parsedResource, notes ] = parseResourceAnnotations(JSON.parse(resource), this.enableArbAnnotations);
38
+ for (const [key, value] of parsedResource) {
39
+ let seg = { sid: key, str: value };
40
+ notes[key] && (seg.notes = notes[key]);
41
+ if (this.enablePluralSuffixes && key.indexOf('_') !== -1 && validPluralSuffixes.has(key.split('_').slice(-1)[0])) {
42
+ seg.isSuffixPluralized = true;
43
+ }
44
+ segments.push(seg);
45
+ }
46
+ return {
47
+ segments,
48
+ };
49
+ }
50
+
51
+ async translateResource({ resource, translator }) {
52
+ let flatResource = flat.flatten(JSON.parse(resource));
53
+ for (const entry of Object.entries(flatResource)) {
54
+ if (!this.enableArbAnnotations || !isArbAnnotations(entry)) {
55
+ const translation = await translator(...entry);
56
+ if (translation === undefined) {
57
+ delete flatResource[entry[0]];
58
+ } else {
59
+ flatResource[entry[0]] = translation;
60
+ // TODO: deal with pluralized forms as well
61
+ }
62
+ }
63
+ }
64
+ if (this.enableArbAnnotations) {
65
+ for (const entry of Object.entries(flatResource).filter(entry => isArbAnnotations(entry))) {
66
+ const arbGroups = extractArbGroupsRegex.exec(entry[0]).groups;
67
+ const sid = `${arbGroups.prefix ?? ''}${arbGroups.key}`;
68
+ if (!this.emitArbAnnotations || !flatResource[sid]) {
69
+ delete flatResource[entry[0]];
70
+ }
71
+ }
72
+ }
73
+ return JSON.stringify(flat.unflatten(flatResource), null, 2);
74
+ }
75
+ }
76
+
77
+ // i18next v4 placeholder formats
78
+ // - "keyNesting": "reuse $t(keyDeep.inner)", or
79
+ // - "keyInterpolate": "replace this {{value}}"
80
+ // See: https://www.i18next.com/misc/json-format#i18next-json-v4
81
+ exports.phDecoder = regex.decoderMaker(
82
+ 'i18nextKey',
83
+ /(?<nestingPh>\$t\([\w:.]+\))|(?<doubleBracePh>{{[^}]+}})/g,
84
+ (groups) => ({ t: 'x', v: groups.nestingPh ?? groups.doubleBracePh })
85
+ );
package/index.js ADDED
@@ -0,0 +1 @@
1
+ exports.i18next = { ...require('./i18next') };
package/package.json ADDED
@@ -0,0 +1,17 @@
1
+ {
2
+ "name": "@l10nmonster/helpers-json",
3
+ "version": "1.0.0",
4
+ "description": "Helpers to deal with JSON file formats",
5
+ "main": "index.js",
6
+ "scripts": {
7
+ "test": "echo \"Error: no test specified\" && exit 1"
8
+ },
9
+ "author": "Diego Lagunas",
10
+ "license": "MIT",
11
+ "dependencies": {
12
+ "flat": "^5.0.2"
13
+ },
14
+ "peerDependencies": {
15
+ "@l10nmonster/helpers": "^1"
16
+ }
17
+ }