gtx-cli 2.3.6-alpha.2 → 2.3.6-alpha.3

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.
Files changed (191) hide show
  1. package/dist/api/checkFileTranslations.d.ts +23 -0
  2. package/dist/api/checkFileTranslations.js +236 -0
  3. package/dist/api/downloadFileBatch.d.ts +20 -0
  4. package/dist/api/downloadFileBatch.js +113 -0
  5. package/dist/api/sendFiles.d.ts +17 -0
  6. package/dist/api/sendFiles.js +115 -0
  7. package/dist/api/uploadFiles.d.ts +27 -0
  8. package/dist/api/uploadFiles.js +40 -0
  9. package/dist/cli/base.d.ts +32 -0
  10. package/dist/cli/base.js +335 -0
  11. package/dist/cli/commands/stage.d.ts +5 -0
  12. package/dist/cli/commands/stage.js +100 -0
  13. package/dist/cli/commands/translate.d.ts +6 -0
  14. package/dist/cli/commands/translate.js +63 -0
  15. package/dist/cli/flags.d.ts +3 -0
  16. package/dist/cli/flags.js +38 -0
  17. package/dist/cli/next.d.ts +11 -0
  18. package/dist/cli/next.js +20 -0
  19. package/dist/cli/react.d.ts +18 -0
  20. package/dist/cli/react.js +175 -0
  21. package/dist/config/generateSettings.d.ts +9 -0
  22. package/dist/config/generateSettings.js +176 -0
  23. package/dist/config/optionPresets.d.ts +2 -0
  24. package/dist/config/optionPresets.js +56 -0
  25. package/dist/config/resolveConfig.d.ts +4 -0
  26. package/dist/config/resolveConfig.js +19 -0
  27. package/dist/config/utils.d.ts +2 -0
  28. package/dist/config/utils.js +4 -0
  29. package/dist/config/validateSettings.d.ts +3 -0
  30. package/dist/config/validateSettings.js +32 -0
  31. package/dist/console/colors.d.ts +5 -0
  32. package/dist/console/colors.js +16 -0
  33. package/dist/console/index.d.ts +21 -0
  34. package/dist/console/index.js +24 -0
  35. package/dist/console/logging.d.ts +53 -0
  36. package/dist/console/logging.js +185 -0
  37. package/dist/formats/files/fileMapping.d.ts +11 -0
  38. package/dist/formats/files/fileMapping.js +82 -0
  39. package/dist/formats/files/save.d.ts +5 -0
  40. package/dist/formats/files/save.js +17 -0
  41. package/dist/formats/files/supportedFiles.d.ts +10 -0
  42. package/dist/formats/files/supportedFiles.js +18 -0
  43. package/dist/formats/files/translate.d.ts +4 -0
  44. package/dist/formats/files/translate.js +119 -0
  45. package/dist/formats/files/upload.d.ts +13 -0
  46. package/dist/formats/files/upload.js +136 -0
  47. package/dist/formats/gt/save.d.ts +9 -0
  48. package/dist/formats/gt/save.js +26 -0
  49. package/dist/formats/json/flattenJson.d.ts +14 -0
  50. package/dist/formats/json/flattenJson.js +64 -0
  51. package/dist/formats/json/mergeJson.d.ts +13 -0
  52. package/dist/formats/json/mergeJson.js +257 -0
  53. package/dist/formats/json/parseJson.d.ts +2 -0
  54. package/dist/formats/json/parseJson.js +108 -0
  55. package/dist/formats/json/utils.d.ts +47 -0
  56. package/dist/formats/json/utils.js +149 -0
  57. package/dist/formats/utils.d.ts +2 -0
  58. package/dist/formats/utils.js +24 -0
  59. package/dist/formats/yaml/mergeYaml.d.ts +5 -0
  60. package/dist/formats/yaml/mergeYaml.js +55 -0
  61. package/dist/formats/yaml/parseYaml.d.ts +5 -0
  62. package/dist/formats/yaml/parseYaml.js +23 -0
  63. package/dist/formats/yaml/utils.d.ts +2 -0
  64. package/dist/formats/yaml/utils.js +22 -0
  65. package/dist/fs/config/loadConfig.d.ts +1 -0
  66. package/dist/fs/config/loadConfig.js +9 -0
  67. package/dist/fs/config/parseFilesConfig.d.ts +27 -0
  68. package/dist/fs/config/parseFilesConfig.js +129 -0
  69. package/dist/fs/config/setupConfig.d.ts +17 -0
  70. package/dist/fs/config/setupConfig.js +50 -0
  71. package/dist/fs/config/updateConfig.d.ts +10 -0
  72. package/dist/fs/config/updateConfig.js +36 -0
  73. package/dist/fs/config/updateVersions.d.ts +10 -0
  74. package/dist/fs/config/updateVersions.js +30 -0
  75. package/dist/fs/copyFile.d.ts +7 -0
  76. package/dist/fs/copyFile.js +39 -0
  77. package/dist/fs/createLoadTranslationsFile.d.ts +1 -0
  78. package/dist/fs/createLoadTranslationsFile.js +36 -0
  79. package/dist/fs/determineFramework.d.ts +5 -0
  80. package/dist/fs/determineFramework.js +46 -0
  81. package/dist/fs/findFilepath.d.ts +36 -0
  82. package/dist/fs/findFilepath.js +89 -0
  83. package/dist/fs/getPackageResource.d.ts +1 -0
  84. package/dist/fs/getPackageResource.js +6 -0
  85. package/dist/fs/index.d.ts +1 -0
  86. package/dist/fs/index.js +1 -0
  87. package/dist/fs/loadJSON.d.ts +6 -0
  88. package/dist/fs/loadJSON.js +17 -0
  89. package/dist/fs/matchFiles.d.ts +1 -0
  90. package/dist/fs/matchFiles.js +8 -0
  91. package/dist/fs/saveJSON.d.ts +1 -0
  92. package/dist/fs/saveJSON.js +7 -0
  93. package/dist/fs/utils.d.ts +1 -0
  94. package/dist/fs/utils.js +16 -0
  95. package/dist/hooks/postProcess.d.ts +4 -0
  96. package/dist/hooks/postProcess.js +110 -0
  97. package/dist/index.d.ts +4 -0
  98. package/dist/index.js +20 -0
  99. package/dist/main.d.ts +2 -0
  100. package/dist/main.js +9 -0
  101. package/dist/next/config/parseNextConfig.d.ts +10 -0
  102. package/dist/next/config/parseNextConfig.js +53 -0
  103. package/dist/next/jsx/utils.d.ts +7 -0
  104. package/dist/next/jsx/utils.js +42 -0
  105. package/dist/next/parse/handleInitGT.d.ts +7 -0
  106. package/dist/next/parse/handleInitGT.js +208 -0
  107. package/dist/next/parse/wrapContent.d.ts +11 -0
  108. package/dist/next/parse/wrapContent.js +163 -0
  109. package/dist/react/config/createESBuildConfig.d.ts +2 -0
  110. package/dist/react/config/createESBuildConfig.js +119 -0
  111. package/dist/react/data-_gt/addGTIdentifierToSyntaxTree.d.ts +8 -0
  112. package/dist/react/data-_gt/addGTIdentifierToSyntaxTree.js +111 -0
  113. package/dist/react/jsx/evaluateJsx.d.ts +17 -0
  114. package/dist/react/jsx/evaluateJsx.js +85 -0
  115. package/dist/react/jsx/trimJsxStringChildren.d.ts +7 -0
  116. package/dist/react/jsx/trimJsxStringChildren.js +95 -0
  117. package/dist/react/jsx/utils/constants.d.ts +10 -0
  118. package/dist/react/jsx/utils/constants.js +31 -0
  119. package/dist/react/jsx/utils/parseAst.d.ts +30 -0
  120. package/dist/react/jsx/utils/parseAst.js +277 -0
  121. package/dist/react/jsx/utils/parseJsx.d.ts +21 -0
  122. package/dist/react/jsx/utils/parseJsx.js +244 -0
  123. package/dist/react/jsx/utils/parseStringFunction.d.ts +16 -0
  124. package/dist/react/jsx/utils/parseStringFunction.js +411 -0
  125. package/dist/react/jsx/utils/validateStringFunction.d.ts +7 -0
  126. package/dist/react/jsx/utils/validateStringFunction.js +31 -0
  127. package/dist/react/jsx/wrapJsx.d.ts +51 -0
  128. package/dist/react/jsx/wrapJsx.js +387 -0
  129. package/dist/react/parse/createDictionaryUpdates.d.ts +3 -0
  130. package/dist/react/parse/createDictionaryUpdates.js +169 -0
  131. package/dist/react/parse/createInlineUpdates.d.ts +6 -0
  132. package/dist/react/parse/createInlineUpdates.js +122 -0
  133. package/dist/react/parse/wrapContent.d.ts +11 -0
  134. package/dist/react/parse/wrapContent.js +162 -0
  135. package/dist/react/utils/flattenDictionary.d.ts +20 -0
  136. package/dist/react/utils/flattenDictionary.js +75 -0
  137. package/dist/react/utils/getEntryAndMetadata.d.ts +5 -0
  138. package/dist/react/utils/getEntryAndMetadata.js +11 -0
  139. package/dist/react/utils/getVariableName.d.ts +25 -0
  140. package/dist/react/utils/getVariableName.js +37 -0
  141. package/dist/setup/userInput.d.ts +4 -0
  142. package/dist/setup/userInput.js +29 -0
  143. package/dist/setup/wizard.d.ts +2 -0
  144. package/dist/setup/wizard.js +127 -0
  145. package/dist/translation/parse.d.ts +15 -0
  146. package/dist/translation/parse.js +76 -0
  147. package/dist/translation/stage.d.ts +2 -0
  148. package/dist/translation/stage.js +44 -0
  149. package/dist/translation/validate.d.ts +2 -0
  150. package/dist/translation/validate.js +50 -0
  151. package/dist/types/data/json.d.ts +6 -0
  152. package/dist/types/data/json.js +1 -0
  153. package/dist/types/data.d.ts +30 -0
  154. package/dist/types/data.js +1 -0
  155. package/dist/types/files.d.ts +1 -0
  156. package/dist/types/files.js +1 -0
  157. package/dist/types/index.d.ts +173 -0
  158. package/dist/types/index.js +1 -0
  159. package/dist/utils/addExplicitAnchorIds.d.ts +24 -0
  160. package/dist/utils/addExplicitAnchorIds.js +260 -0
  161. package/dist/utils/constants.d.ts +2 -0
  162. package/dist/utils/constants.js +2 -0
  163. package/dist/utils/credentials.d.ts +12 -0
  164. package/dist/utils/credentials.js +119 -0
  165. package/dist/utils/flattenJsonFiles.d.ts +2 -0
  166. package/dist/utils/flattenJsonFiles.js +36 -0
  167. package/dist/utils/gt.d.ts +2 -0
  168. package/dist/utils/gt.js +2 -0
  169. package/dist/utils/hash.d.ts +6 -0
  170. package/dist/utils/hash.js +11 -0
  171. package/dist/utils/headers.d.ts +1 -0
  172. package/dist/utils/headers.js +14 -0
  173. package/dist/utils/installPackage.d.ts +3 -0
  174. package/dist/utils/installPackage.js +77 -0
  175. package/dist/utils/localizeStaticImports.d.ts +15 -0
  176. package/dist/utils/localizeStaticImports.js +341 -0
  177. package/dist/utils/localizeStaticUrls.d.ts +19 -0
  178. package/dist/utils/localizeStaticUrls.js +432 -0
  179. package/dist/utils/packageInfo.d.ts +3 -0
  180. package/dist/utils/packageInfo.js +17 -0
  181. package/dist/utils/packageJson.d.ts +6 -0
  182. package/dist/utils/packageJson.js +76 -0
  183. package/dist/utils/packageManager.d.ts +28 -0
  184. package/dist/utils/packageManager.js +269 -0
  185. package/dist/utils/processAnchorIds.d.ts +6 -0
  186. package/dist/utils/processAnchorIds.js +47 -0
  187. package/dist/utils/sanitizeFileContent.d.ts +6 -0
  188. package/dist/utils/sanitizeFileContent.js +29 -0
  189. package/dist/utils/validateMdx.d.ts +10 -0
  190. package/dist/utils/validateMdx.js +25 -0
  191. package/package.json +3 -3
@@ -0,0 +1,64 @@
1
+ import { JSONPath } from 'jsonpath-plus';
2
+ import { logError } from '../../console/logging.js';
3
+ /**
4
+ * Flattens a JSON object according to a list of JSON paths.
5
+ * @param json - The JSON object to flatten
6
+ * @param jsonPaths - The list of JSON paths to flatten
7
+ * @returns A mapping of json pointers to their values
8
+ */
9
+ export function flattenJson(json, jsonPaths) {
10
+ const extractedJson = {};
11
+ for (const jsonPath of jsonPaths) {
12
+ try {
13
+ const results = JSONPath({
14
+ json,
15
+ path: jsonPath,
16
+ resultType: 'all',
17
+ flatten: true,
18
+ wrap: true,
19
+ });
20
+ if (!results || results.length === 0) {
21
+ continue;
22
+ }
23
+ results.forEach((result) => {
24
+ extractedJson[result.pointer] = result.value;
25
+ });
26
+ }
27
+ catch (error) {
28
+ logError(`Error with JSONPath pattern: ${jsonPath}`);
29
+ }
30
+ }
31
+ return extractedJson;
32
+ }
33
+ /**
34
+ * Flattens a JSON object according to a list of JSON paths, only including strings
35
+ * @param json - The JSON object to flatten
36
+ * @param jsonPaths - The list of JSON paths to flatten
37
+ * @returns A mapping of json pointers to their values
38
+ */
39
+ export function flattenJsonWithStringFilter(json, jsonPaths) {
40
+ const extractedJson = {};
41
+ for (const jsonPath of jsonPaths) {
42
+ try {
43
+ const results = JSONPath({
44
+ json,
45
+ path: jsonPath,
46
+ resultType: 'all',
47
+ flatten: true,
48
+ wrap: true,
49
+ });
50
+ if (!results || results.length === 0) {
51
+ continue;
52
+ }
53
+ results.forEach((result) => {
54
+ if (typeof result.value === 'string') {
55
+ extractedJson[result.pointer] = result.value;
56
+ }
57
+ });
58
+ }
59
+ catch {
60
+ logError(`Error with JSONPath pattern: ${jsonPath}`);
61
+ }
62
+ }
63
+ return extractedJson;
64
+ }
@@ -0,0 +1,13 @@
1
+ import { AdditionalOptions, SourceObjectOptions } from '../../types/index.js';
2
+ export declare function mergeJson(originalContent: string, inputPath: string, options: AdditionalOptions, targets: {
3
+ translatedContent: string;
4
+ targetLocale: string;
5
+ }[], defaultLocale: string): string[];
6
+ /**
7
+ * Apply transformations to the sourceItem in-place
8
+ * @param sourceItem - The source item to apply transformations to
9
+ * @param transform - The transformations to apply
10
+ * @param targetLocale - The target locale
11
+ * @param defaultLocale - The default locale
12
+ */
13
+ export declare function applyTransformations(sourceItem: any, transform: SourceObjectOptions['transform'], targetLocale: string, defaultLocale: string): void;
@@ -0,0 +1,257 @@
1
+ import JSONPointer from 'jsonpointer';
2
+ import { exit, logError, logWarning } from '../../console/logging.js';
3
+ import { findMatchingItemArray, findMatchingItemObject, generateSourceObjectPointers, getSourceObjectOptionsArray, validateJsonSchema, } from './utils.js';
4
+ import { JSONPath } from 'jsonpath-plus';
5
+ import { getLocaleProperties } from 'generaltranslation';
6
+ import { replaceLocalePlaceholders } from '../utils.js';
7
+ export function mergeJson(originalContent, inputPath, options, targets, defaultLocale) {
8
+ const jsonSchema = validateJsonSchema(options, inputPath);
9
+ if (!jsonSchema) {
10
+ return targets.map((target) => target.translatedContent);
11
+ }
12
+ let originalJson;
13
+ try {
14
+ originalJson = JSON.parse(originalContent);
15
+ }
16
+ catch {
17
+ logError(`Invalid JSON file: ${inputPath}`);
18
+ exit(1);
19
+ }
20
+ // Handle include
21
+ if (jsonSchema.include) {
22
+ const output = [];
23
+ for (const target of targets) {
24
+ // Must clone the original JSON to avoid mutations
25
+ const mergedJson = structuredClone(originalJson);
26
+ const translatedJson = JSON.parse(target.translatedContent);
27
+ for (const [jsonPointer, translatedValue] of Object.entries(translatedJson)) {
28
+ try {
29
+ const value = JSONPointer.get(mergedJson, jsonPointer);
30
+ if (!value)
31
+ continue;
32
+ JSONPointer.set(mergedJson, jsonPointer, translatedValue);
33
+ }
34
+ catch {
35
+ /* empty */
36
+ }
37
+ }
38
+ output.push(JSON.stringify(mergedJson, null, 2));
39
+ }
40
+ return output;
41
+ }
42
+ if (!jsonSchema.composite) {
43
+ logError('No composite property found in JSON schema');
44
+ exit(1);
45
+ }
46
+ // Handle composite
47
+ // Create a deep copy of the original JSON to avoid mutations
48
+ const mergedJson = structuredClone(originalJson);
49
+ // Create mapping of sourceObjectPointer to SourceObjectOptions
50
+ const sourceObjectPointers = generateSourceObjectPointers(jsonSchema.composite, originalJson);
51
+ // Find the source object
52
+ for (const [sourceObjectPointer, { sourceObjectValue, sourceObjectOptions },] of Object.entries(sourceObjectPointers)) {
53
+ // Find the source item
54
+ if (sourceObjectOptions.type === 'array') {
55
+ // Validate type
56
+ if (!Array.isArray(sourceObjectValue)) {
57
+ logError(`Source object value is not an array at path: ${sourceObjectPointer}`);
58
+ exit(1);
59
+ }
60
+ // Get source item for default locale
61
+ const matchingDefaultLocaleItems = findMatchingItemArray(defaultLocale, sourceObjectOptions, sourceObjectPointer, sourceObjectValue);
62
+ if (!Object.keys(matchingDefaultLocaleItems).length) {
63
+ logWarning(`Matching sourceItems not found at path: ${sourceObjectPointer}. Please check your JSON file includes the key field. Skipping this target`);
64
+ continue;
65
+ }
66
+ const matchingDefaultLocaleItemKeys = new Set(Object.keys(matchingDefaultLocaleItems));
67
+ // For each target:
68
+ // 1. Get the target items
69
+ // 2. Track all array indecies to remove (will be overwritten)
70
+ // 3. Merge matchingDefaultLocaleItems and targetItems
71
+ // 4. Validate that the mergedItems is not empty
72
+ // For each target item:
73
+ // 5. Validate that all the array indecies are still present in the source json
74
+ // 6. Override the source item with the translated values
75
+ // 7. Apply additional mutations to the sourceItem
76
+ // 8. Track all items to add
77
+ // 9. Check that items to add is >= items to remove
78
+ // 10. Remove all items for the target locale (they can be identified by the key)
79
+ const indiciesToRemove = new Set();
80
+ const itemsToAdd = [];
81
+ for (const target of targets) {
82
+ const targetJson = JSON.parse(target.translatedContent);
83
+ let targetItems = targetJson[sourceObjectPointer];
84
+ // 1. Get the target items
85
+ if (!targetItems) {
86
+ // If no translation can be found, a transformation may need to happen still
87
+ targetItems = {};
88
+ }
89
+ // 2. Track all array indecies to remove (will be overwritten)
90
+ const targetItemsToRemove = findMatchingItemArray(target.targetLocale, sourceObjectOptions, sourceObjectPointer, sourceObjectValue);
91
+ Object.values(targetItemsToRemove).forEach(({ index }) => indiciesToRemove.add(index));
92
+ // 3. Merge matchingDefaultLocaleItems and targetItems
93
+ const mergedItems = {
94
+ ...(sourceObjectOptions.transform ? matchingDefaultLocaleItems : {}),
95
+ ...targetItems,
96
+ };
97
+ // 4. Validate that the mergedItems is not empty
98
+ if (Object.keys(mergedItems).length === 0) {
99
+ logWarning(`Translated JSON for locale: ${target.targetLocale} does not have a valid sourceObjectPointer: ${sourceObjectPointer}. Skipping this target`);
100
+ continue;
101
+ }
102
+ for (const [sourceItemPointer, targetItem] of Object.entries(mergedItems)) {
103
+ // 5. Validate that all the array indecies are still present in the source json
104
+ if (!matchingDefaultLocaleItemKeys.has(sourceItemPointer)) {
105
+ logError(`Array index ${sourceItemPointer} is not present in the source json. It is possible that the source json has been modified since the translation was generated.`);
106
+ exit(1);
107
+ }
108
+ // 6. Override the source item with the translated values
109
+ const defaultLocaleSourceItem = matchingDefaultLocaleItems[sourceItemPointer].sourceItem;
110
+ const defaultLocaleKeyPointer = matchingDefaultLocaleItems[sourceItemPointer].keyPointer;
111
+ const mutatedSourceItem = structuredClone(defaultLocaleSourceItem);
112
+ const { identifyingLocaleProperty: targetLocaleKeyProperty } = getSourceObjectOptionsArray(target.targetLocale, sourceObjectPointer, sourceObjectOptions);
113
+ JSONPointer.set(mutatedSourceItem, defaultLocaleKeyPointer, targetLocaleKeyProperty);
114
+ for (const [translatedKeyJsonPointer, translatedValue,] of Object.entries(targetItem || {})) {
115
+ try {
116
+ const value = JSONPointer.get(mutatedSourceItem, translatedKeyJsonPointer);
117
+ if (!value)
118
+ continue;
119
+ JSONPointer.set(mutatedSourceItem, translatedKeyJsonPointer, translatedValue);
120
+ }
121
+ catch {
122
+ /* empty */
123
+ }
124
+ }
125
+ // 7. Apply additional mutations to the sourceItem
126
+ applyTransformations(mutatedSourceItem, sourceObjectOptions.transform, target.targetLocale, defaultLocale);
127
+ itemsToAdd.push(mutatedSourceItem);
128
+ }
129
+ }
130
+ // 8. Check that items to add is >= items to remove (if this happens, something is very wrong)
131
+ if (itemsToAdd.length < indiciesToRemove.size) {
132
+ logError(`Items to add is less than items to remove at path: ${sourceObjectPointer}. Please check your JSON schema key field.`);
133
+ exit(1);
134
+ }
135
+ // 9. Remove all items for the target locale (they can be identified by the key)
136
+ const filteredSourceObjectValue = sourceObjectValue.filter((_, index) => !indiciesToRemove.has(index));
137
+ // 10. Add all items to the original JSON
138
+ filteredSourceObjectValue.push(...itemsToAdd);
139
+ JSONPointer.set(mergedJson, sourceObjectPointer, filteredSourceObjectValue);
140
+ }
141
+ else {
142
+ // Validate type
143
+ if (typeof sourceObjectValue !== 'object' || sourceObjectValue === null) {
144
+ logError(`Source object value is not an object at path: ${sourceObjectPointer}`);
145
+ exit(1);
146
+ }
147
+ // Validate localeProperty
148
+ const matchingDefaultLocaleItem = findMatchingItemObject(defaultLocale, sourceObjectPointer, sourceObjectOptions, sourceObjectValue);
149
+ // Validate source item exists
150
+ if (!matchingDefaultLocaleItem.sourceItem) {
151
+ logError(`Source item not found at path: ${sourceObjectPointer}. You must specify a source item where its key matches the default locale`);
152
+ exit(1);
153
+ }
154
+ const { sourceItem: defaultLocaleSourceItem } = matchingDefaultLocaleItem;
155
+ // For each target:
156
+ // 1. Get the target items
157
+ // 2. Find the source item for the target locale
158
+ // 3. Merge the target items with the source item
159
+ // 4. Validate that the mergedItems is not empty
160
+ // 5. Override the source item with the translated values
161
+ // 6. Apply additional mutations to the sourceItem
162
+ // 7. Merge the source item with the original JSON (if the source item is not a new item)
163
+ for (const target of targets) {
164
+ const targetJson = JSON.parse(target.translatedContent);
165
+ // 1. Get the target items
166
+ let targetItems = targetJson[sourceObjectPointer];
167
+ if (!targetItems) {
168
+ targetItems = {};
169
+ }
170
+ // 2. Find the source item for the target locale
171
+ const matchingTargetItem = findMatchingItemObject(target.targetLocale, sourceObjectPointer, sourceObjectOptions, sourceObjectValue);
172
+ // If the target locale has a matching source item, use it to mutate the source item
173
+ // Otherwise, fallback to the default locale source item
174
+ const mutateSourceItem = structuredClone(defaultLocaleSourceItem);
175
+ const mutateSourceItemKey = matchingTargetItem.keyParentProperty;
176
+ // 3. Merge the target items with the source item (if there are transformations to perform)
177
+ const mergedItems = {
178
+ ...(sourceObjectOptions.transform ? defaultLocaleSourceItem : {}),
179
+ ...targetItems,
180
+ };
181
+ // 4. Validate that the mergedItems is not empty
182
+ if (Object.keys(mergedItems).length === 0) {
183
+ logWarning(`Translated JSON for locale: ${target.targetLocale} does not have a valid sourceObjectPointer: ${sourceObjectPointer}. Skipping this target`);
184
+ continue;
185
+ }
186
+ // 5. Override the source item with the translated values
187
+ for (const [translatedKeyJsonPointer, translatedValue,] of Object.entries(mergedItems || {})) {
188
+ try {
189
+ const value = JSONPointer.get(mutateSourceItem, translatedKeyJsonPointer);
190
+ if (!value)
191
+ continue;
192
+ JSONPointer.set(mutateSourceItem, translatedKeyJsonPointer, translatedValue);
193
+ }
194
+ catch {
195
+ /* empty */
196
+ }
197
+ }
198
+ // 6. Apply additional mutations to the sourceItem
199
+ applyTransformations(mutateSourceItem, sourceObjectOptions.transform, target.targetLocale, defaultLocale);
200
+ // 7. Merge the source item with the original JSON
201
+ sourceObjectValue[mutateSourceItemKey] = mutateSourceItem;
202
+ }
203
+ JSONPointer.set(mergedJson, sourceObjectPointer, sourceObjectValue);
204
+ }
205
+ }
206
+ return [JSON.stringify(mergedJson, null, 2)];
207
+ }
208
+ /**
209
+ * Apply transformations to the sourceItem in-place
210
+ * @param sourceItem - The source item to apply transformations to
211
+ * @param transform - The transformations to apply
212
+ * @param targetLocale - The target locale
213
+ * @param defaultLocale - The default locale
214
+ */
215
+ export function applyTransformations(sourceItem, transform, targetLocale, defaultLocale) {
216
+ if (!transform)
217
+ return;
218
+ const targetLocaleProperties = getLocaleProperties(targetLocale);
219
+ const defaultLocaleProperties = getLocaleProperties(defaultLocale);
220
+ for (const [transformPath, transformOptions] of Object.entries(transform)) {
221
+ if (!transformOptions.replace ||
222
+ typeof transformOptions.replace !== 'string') {
223
+ continue;
224
+ }
225
+ const results = JSONPath({
226
+ json: sourceItem,
227
+ path: transformPath,
228
+ resultType: 'all',
229
+ flatten: true,
230
+ wrap: true,
231
+ });
232
+ if (!results || results.length === 0) {
233
+ continue;
234
+ }
235
+ results.forEach((result) => {
236
+ if (typeof result.value !== 'string') {
237
+ return;
238
+ }
239
+ // Replace locale placeholders in the replace string
240
+ let replaceString = transformOptions.replace;
241
+ // Replace all locale property placeholders
242
+ replaceString = replaceLocalePlaceholders(replaceString, targetLocaleProperties);
243
+ if (transformOptions.match &&
244
+ typeof transformOptions.match === 'string') {
245
+ // Replace locale placeholders in the match string using defaultLocale properties
246
+ let matchString = transformOptions.match;
247
+ matchString = replaceLocalePlaceholders(matchString, defaultLocaleProperties);
248
+ result.value = result.value.replace(new RegExp(matchString, 'g'), replaceString);
249
+ }
250
+ else {
251
+ result.value = replaceString;
252
+ }
253
+ // Update the actual sourceItem using JSONPointer
254
+ JSONPointer.set(sourceItem, result.pointer, result.value);
255
+ });
256
+ }
257
+ }
@@ -0,0 +1,2 @@
1
+ import { AdditionalOptions } from '../../types/index.js';
2
+ export declare function parseJson(content: string, filePath: string, options: AdditionalOptions, defaultLocale: string): string;
@@ -0,0 +1,108 @@
1
+ import { flattenJsonWithStringFilter } from './flattenJson.js';
2
+ import { JSONPath } from 'jsonpath-plus';
3
+ import { exit, logError } from '../../console/logging.js';
4
+ import { findMatchingItemArray, findMatchingItemObject, generateSourceObjectPointers, validateJsonSchema, } from './utils.js';
5
+ // Parse a JSON file according to a JSON schema
6
+ export function parseJson(content, filePath, options, defaultLocale) {
7
+ const jsonSchema = validateJsonSchema(options, filePath);
8
+ if (!jsonSchema) {
9
+ return content;
10
+ }
11
+ let json;
12
+ try {
13
+ json = JSON.parse(content);
14
+ }
15
+ catch {
16
+ logError(`Invalid JSON file: ${filePath}`);
17
+ exit(1);
18
+ }
19
+ // Handle include
20
+ if (jsonSchema.include) {
21
+ const flattenedJson = flattenJsonWithStringFilter(json, jsonSchema.include);
22
+ return JSON.stringify(flattenedJson);
23
+ }
24
+ if (!jsonSchema.composite) {
25
+ logError('No composite property found in JSON schema');
26
+ exit(1);
27
+ }
28
+ // Construct lvl 1
29
+ // Create mapping of sourceObjectPointer to SourceObjectOptions
30
+ const sourceObjectPointers = generateSourceObjectPointers(jsonSchema.composite, json);
31
+ // Construct lvl 2
32
+ const sourceObjectsToTranslate = {};
33
+ for (const [sourceObjectPointer, { sourceObjectValue, sourceObjectOptions },] of Object.entries(sourceObjectPointers)) {
34
+ // Skip if no includes
35
+ if (!sourceObjectOptions.include.length) {
36
+ continue;
37
+ }
38
+ // Find the default locale in each source item in each sourceObjectValue
39
+ // Array: use key field
40
+ if (sourceObjectOptions.type === 'array') {
41
+ // Validate type
42
+ if (!Array.isArray(sourceObjectValue)) {
43
+ logError(`Source object value is not an array at path: ${sourceObjectPointer}`);
44
+ exit(1);
45
+ }
46
+ // Find matching source items
47
+ const matchingItems = findMatchingItemArray(defaultLocale, sourceObjectOptions, sourceObjectPointer, sourceObjectValue);
48
+ if (!Object.keys(matchingItems).length) {
49
+ logError(`Matching sourceItem not found at path: ${sourceObjectPointer} for locale: ${defaultLocale}. Please check your JSON schema`);
50
+ exit(1);
51
+ }
52
+ // Construct lvl 3
53
+ const sourceItemsToTranslate = {};
54
+ for (const [arrayPointer, matchingItem] of Object.entries(matchingItems)) {
55
+ const { sourceItem, keyPointer } = matchingItem;
56
+ // Get the fields to translate from the includes
57
+ const matchingItemsToTranslate = [];
58
+ for (const include of sourceObjectOptions.include) {
59
+ try {
60
+ const matchingItems = JSONPath({
61
+ json: sourceItem,
62
+ path: include,
63
+ resultType: 'all',
64
+ flatten: true,
65
+ wrap: true,
66
+ });
67
+ if (matchingItems) {
68
+ matchingItemsToTranslate.push(...matchingItems);
69
+ }
70
+ }
71
+ catch {
72
+ /* empty */
73
+ }
74
+ }
75
+ // Filter out the key pointer
76
+ sourceItemsToTranslate[arrayPointer] = Object.fromEntries(matchingItemsToTranslate
77
+ .filter((item) => item.pointer !== keyPointer)
78
+ .map((item) => [
79
+ item.pointer,
80
+ item.value,
81
+ ]));
82
+ }
83
+ // Add the items to translate to the result
84
+ sourceObjectsToTranslate[sourceObjectPointer] = sourceItemsToTranslate;
85
+ }
86
+ else {
87
+ // Object: use the key in this object with the matching locale property
88
+ // Validate type
89
+ if (typeof sourceObjectValue !== 'object' || sourceObjectValue === null) {
90
+ logError(`Source object value is not an object at path: ${sourceObjectPointer}`);
91
+ exit(1);
92
+ }
93
+ // Validate localeProperty
94
+ const matchingItem = findMatchingItemObject(defaultLocale, sourceObjectPointer, sourceObjectOptions, sourceObjectValue);
95
+ // Validate source item exists
96
+ if (!matchingItem.sourceItem) {
97
+ logError(`Source item not found at path: ${sourceObjectPointer}. You must specify a source item where its key matches the default locale`);
98
+ exit(1);
99
+ }
100
+ const { sourceItem } = matchingItem;
101
+ // Get the fields to translate from the includes
102
+ const itemsToTranslate = flattenJsonWithStringFilter(sourceItem, sourceObjectOptions.include);
103
+ // Add the items to translate to the result
104
+ sourceObjectsToTranslate[sourceObjectPointer] = itemsToTranslate;
105
+ }
106
+ }
107
+ return JSON.stringify(sourceObjectsToTranslate);
108
+ }
@@ -0,0 +1,47 @@
1
+ import { AdditionalOptions, JsonSchema, SourceObjectOptions } from '../../types/index.js';
2
+ export declare function findMatchingItemArray(locale: string, sourceObjectOptions: SourceObjectOptions, sourceObjectPointer: string, sourceObjectValue: any): Record<string, {
3
+ sourceItem: any;
4
+ keyParentProperty: string;
5
+ keyPointer: string;
6
+ index: number;
7
+ }>;
8
+ export declare function findMatchingItemObject(locale: string, sourceObjectPointer: string, sourceObjectOptions: SourceObjectOptions, sourceObjectValue: any): {
9
+ sourceItem: any | undefined;
10
+ keyParentProperty: string;
11
+ };
12
+ /**
13
+ * Get the identifying locale property for an object
14
+ * @param locale - The locale to get the identifying locale property for
15
+ * @param sourceObjectPointer - The path to the source object
16
+ * @param sourceObjectOptions - The source object options
17
+ * @returns The identifying locale property
18
+ */
19
+ export declare function getIdentifyingLocaleProperty(locale: string, sourceObjectPointer: string, sourceObjectOptions: SourceObjectOptions): string;
20
+ /**
21
+ * Get the identifying locale property and the json path to the key for an array
22
+ * @param locale - The locale to get the identifying locale property for
23
+ * @param sourceObjectPointer - The path to the source object
24
+ * @param sourceObjectOptions - The source object options
25
+ * @returns The identifying locale property and the json path to the key
26
+ */
27
+ export declare function getSourceObjectOptionsArray(locale: string, sourceObjectPointer: string, sourceObjectOptions: SourceObjectOptions): {
28
+ identifyingLocaleProperty: string;
29
+ localeKeyJsonPath: string;
30
+ };
31
+ export declare function getSourceObjectOptionsObject(defaultLocale: string, sourceObjectPointer: string, sourceObjectOptions: SourceObjectOptions): {
32
+ identifyingLocaleProperty: string;
33
+ };
34
+ /**
35
+ * Generate a mapping of sourceObjectPointer to SourceObjectOptions
36
+ * where the sourceObjectPointer is a jsonpointer to the array or object containing
37
+ * @param jsonSchema - The json schema to generate the mapping from
38
+ * @param originalJson - The original json to generate the mapping from
39
+ * @returns A mapping of sourceObjectPointer to SourceObjectOptions
40
+ */
41
+ export declare function generateSourceObjectPointers(jsonSchema: {
42
+ [sourceObjectPath: string]: SourceObjectOptions;
43
+ }, originalJson: any): Record<string, {
44
+ sourceObjectValue: any;
45
+ sourceObjectOptions: SourceObjectOptions;
46
+ }>;
47
+ export declare function validateJsonSchema(options: AdditionalOptions, filePath: string): JsonSchema | null;
@@ -0,0 +1,149 @@
1
+ import { getLocaleProperties } from 'generaltranslation';
2
+ import { exit, logError } from '../../console/logging.js';
3
+ import { JSONPath } from 'jsonpath-plus';
4
+ import { flattenJson } from './flattenJson.js';
5
+ import path from 'node:path';
6
+ import micromatch from 'micromatch';
7
+ const { isMatch } = micromatch;
8
+ // Find the matching source item in an array
9
+ // where the key matches the identifying locale property
10
+ // If no matching item is found, exit with an error
11
+ export function findMatchingItemArray(locale, sourceObjectOptions, sourceObjectPointer, sourceObjectValue) {
12
+ const { identifyingLocaleProperty, localeKeyJsonPath } = getSourceObjectOptionsArray(locale, sourceObjectPointer, sourceObjectOptions);
13
+ // Use the json pointer key to locate the source item
14
+ const matchingItems = {};
15
+ for (const [index, item] of sourceObjectValue.entries()) {
16
+ // Get the key candidates
17
+ const keyCandidates = JSONPath({
18
+ json: item,
19
+ path: localeKeyJsonPath,
20
+ resultType: 'all',
21
+ flatten: true,
22
+ wrap: true,
23
+ });
24
+ if (!keyCandidates) {
25
+ logError(`Source item at path: ${sourceObjectPointer} does not have a key value at path: ${localeKeyJsonPath}`);
26
+ exit(1);
27
+ }
28
+ else if (keyCandidates.length === 0) {
29
+ // If no key candidates, skip the item
30
+ continue;
31
+ }
32
+ else if (keyCandidates.length > 1) {
33
+ // If multiple key candidates, exit with an error
34
+ logError(`Source item at path: ${sourceObjectPointer} has multiple matching keys with path: ${localeKeyJsonPath}`);
35
+ exit(1);
36
+ }
37
+ else if (identifyingLocaleProperty !== keyCandidates[0].value) {
38
+ // Validate the key is the identifying locale property
39
+ continue;
40
+ }
41
+ // Map the index to the source item
42
+ matchingItems[`/${index}`] = {
43
+ sourceItem: item,
44
+ keyParentProperty: keyCandidates[0].parentProperty,
45
+ keyPointer: keyCandidates[0].pointer,
46
+ index,
47
+ };
48
+ }
49
+ return matchingItems;
50
+ }
51
+ export function findMatchingItemObject(locale, sourceObjectPointer, sourceObjectOptions, sourceObjectValue) {
52
+ const { identifyingLocaleProperty } = getSourceObjectOptionsObject(locale, sourceObjectPointer, sourceObjectOptions);
53
+ // Locate the source item
54
+ if (sourceObjectValue[identifyingLocaleProperty]) {
55
+ return {
56
+ sourceItem: sourceObjectValue[identifyingLocaleProperty],
57
+ keyParentProperty: identifyingLocaleProperty,
58
+ };
59
+ }
60
+ return {
61
+ sourceItem: undefined,
62
+ keyParentProperty: identifyingLocaleProperty,
63
+ };
64
+ }
65
+ /**
66
+ * Get the identifying locale property for an object
67
+ * @param locale - The locale to get the identifying locale property for
68
+ * @param sourceObjectPointer - The path to the source object
69
+ * @param sourceObjectOptions - The source object options
70
+ * @returns The identifying locale property
71
+ */
72
+ export function getIdentifyingLocaleProperty(locale, sourceObjectPointer, sourceObjectOptions) {
73
+ // Validate localeProperty
74
+ const localeProperty = sourceObjectOptions.localeProperty || 'code';
75
+ const identifyingLocaleProperty = getLocaleProperties(locale)[localeProperty];
76
+ if (!identifyingLocaleProperty) {
77
+ logError(`Source object options localeProperty is not a valid locale property at path: ${sourceObjectPointer}`);
78
+ exit(1);
79
+ }
80
+ return identifyingLocaleProperty;
81
+ }
82
+ /**
83
+ * Get the identifying locale property and the json path to the key for an array
84
+ * @param locale - The locale to get the identifying locale property for
85
+ * @param sourceObjectPointer - The path to the source object
86
+ * @param sourceObjectOptions - The source object options
87
+ * @returns The identifying locale property and the json path to the key
88
+ */
89
+ export function getSourceObjectOptionsArray(locale, sourceObjectPointer, sourceObjectOptions) {
90
+ const identifyingLocaleProperty = getIdentifyingLocaleProperty(locale, sourceObjectPointer, sourceObjectOptions);
91
+ const localeKeyJsonPath = sourceObjectOptions.key;
92
+ if (!localeKeyJsonPath) {
93
+ logError(`Source object options key is required for array at path: ${sourceObjectPointer}`);
94
+ exit(1);
95
+ }
96
+ return { identifyingLocaleProperty, localeKeyJsonPath };
97
+ }
98
+ export function getSourceObjectOptionsObject(defaultLocale, sourceObjectPointer, sourceObjectOptions) {
99
+ const identifyingLocaleProperty = getIdentifyingLocaleProperty(defaultLocale, sourceObjectPointer, sourceObjectOptions);
100
+ const jsonPathKey = sourceObjectOptions.key;
101
+ if (jsonPathKey) {
102
+ logError(`Source object options key is not allowed for object at path: ${sourceObjectPointer}`);
103
+ exit(1);
104
+ }
105
+ return { identifyingLocaleProperty };
106
+ }
107
+ /**
108
+ * Generate a mapping of sourceObjectPointer to SourceObjectOptions
109
+ * where the sourceObjectPointer is a jsonpointer to the array or object containing
110
+ * @param jsonSchema - The json schema to generate the mapping from
111
+ * @param originalJson - The original json to generate the mapping from
112
+ * @returns A mapping of sourceObjectPointer to SourceObjectOptions
113
+ */
114
+ export function generateSourceObjectPointers(jsonSchema, originalJson) {
115
+ const sourceObjectPointers = Object.entries(jsonSchema).reduce((acc, [sourceObjectPath, sourceObjectOptions]) => {
116
+ const sourceObjects = flattenJson(originalJson, [sourceObjectPath]);
117
+ Object.entries(sourceObjects).forEach(([pointer, value]) => {
118
+ acc[pointer] = {
119
+ sourceObjectValue: value,
120
+ sourceObjectOptions,
121
+ };
122
+ });
123
+ return acc;
124
+ }, {});
125
+ return sourceObjectPointers;
126
+ }
127
+ export function validateJsonSchema(options, filePath) {
128
+ if (!options.jsonSchema) {
129
+ return null;
130
+ }
131
+ const fileGlobs = Object.keys(options.jsonSchema);
132
+ const matchingGlob = fileGlobs.find((fileGlob) => isMatch(path.relative(process.cwd(), filePath), fileGlob));
133
+ if (!matchingGlob || !options.jsonSchema[matchingGlob]) {
134
+ return null;
135
+ }
136
+ // Validate includes or composite
137
+ const jsonSchema = options.jsonSchema[matchingGlob];
138
+ if (jsonSchema.include && jsonSchema.composite) {
139
+ logError('include and composite cannot be used together in the same JSON schema');
140
+ exit(1);
141
+ return null;
142
+ }
143
+ if (!jsonSchema.include && !jsonSchema.composite) {
144
+ logError('No include or composite property found in JSON schema');
145
+ exit(1);
146
+ return null;
147
+ }
148
+ return jsonSchema;
149
+ }
@@ -0,0 +1,2 @@
1
+ import { LocaleProperties } from 'generaltranslation/types';
2
+ export declare function replaceLocalePlaceholders(string: string, localeProperties: LocaleProperties): string;
@@ -0,0 +1,24 @@
1
+ // helper function to replace locale placeholders in a string
2
+ // with the corresponding locale properties
3
+ // ex: {locale} -> will be replaced with the locale code
4
+ // ex: {localeName} -> will be replaced with the locale name
5
+ export function replaceLocalePlaceholders(string, localeProperties) {
6
+ return string.replace(/\{(\w+)\}/g, (match, property) => {
7
+ // Handle common aliases
8
+ if (property === 'locale' || property === 'localeCode') {
9
+ return localeProperties.code;
10
+ }
11
+ if (property === 'localeName') {
12
+ return localeProperties.name;
13
+ }
14
+ if (property === 'localeNativeName') {
15
+ return localeProperties.nativeName;
16
+ }
17
+ // Check if the property exists in localeProperties
18
+ if (property in localeProperties) {
19
+ return localeProperties[property];
20
+ }
21
+ // Return the original placeholder if property not found
22
+ return match;
23
+ });
24
+ }