@intlayer/cli 8.4.3 → 8.4.5

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 (301) hide show
  1. package/dist/cjs/IntlayerEventListener.cjs +186 -1
  2. package/dist/cjs/IntlayerEventListener.cjs.map +1 -1
  3. package/dist/cjs/_virtual/_rolldown/runtime.cjs +29 -0
  4. package/dist/cjs/_virtual/_utils_asset.cjs +98 -0
  5. package/dist/cjs/auth/login.cjs +90 -2
  6. package/dist/cjs/auth/login.cjs.map +1 -1
  7. package/dist/cjs/build.cjs +30 -1
  8. package/dist/cjs/build.cjs.map +1 -1
  9. package/dist/cjs/ci.cjs +76 -1
  10. package/dist/cjs/ci.cjs.map +1 -1
  11. package/dist/cjs/cli.cjs +485 -1
  12. package/dist/cjs/cli.cjs.map +1 -1
  13. package/dist/cjs/config.cjs +15 -1
  14. package/dist/cjs/config.cjs.map +1 -1
  15. package/dist/cjs/editor.cjs +50 -1
  16. package/dist/cjs/editor.cjs.map +1 -1
  17. package/dist/cjs/extract.cjs +108 -1
  18. package/dist/cjs/extract.cjs.map +1 -1
  19. package/dist/cjs/fill/deepMergeContent.cjs +27 -1
  20. package/dist/cjs/fill/deepMergeContent.cjs.map +1 -1
  21. package/dist/cjs/fill/fill.cjs +84 -1
  22. package/dist/cjs/fill/fill.cjs.map +1 -1
  23. package/dist/cjs/fill/formatAutoFilledFilePath.cjs +32 -1
  24. package/dist/cjs/fill/formatAutoFilledFilePath.cjs.map +1 -1
  25. package/dist/cjs/fill/formatFillData.cjs +87 -1
  26. package/dist/cjs/fill/formatFillData.cjs.map +1 -1
  27. package/dist/cjs/fill/getAvailableLocalesInDictionary.cjs +26 -1
  28. package/dist/cjs/fill/getAvailableLocalesInDictionary.cjs.map +1 -1
  29. package/dist/cjs/fill/getFilterMissingContentPerLocale.cjs +51 -1
  30. package/dist/cjs/fill/getFilterMissingContentPerLocale.cjs.map +1 -1
  31. package/dist/cjs/fill/index.cjs +6 -1
  32. package/dist/cjs/fill/listTranslationsTasks.cjs +72 -1
  33. package/dist/cjs/fill/listTranslationsTasks.cjs.map +1 -1
  34. package/dist/cjs/fill/translateDictionary.cjs +240 -1
  35. package/dist/cjs/fill/translateDictionary.cjs.map +1 -1
  36. package/dist/cjs/fill/writeFill.cjs +55 -1
  37. package/dist/cjs/fill/writeFill.cjs.map +1 -1
  38. package/dist/cjs/getTargetDictionary.cjs +36 -1
  39. package/dist/cjs/getTargetDictionary.cjs.map +1 -1
  40. package/dist/cjs/index.cjs +44 -1
  41. package/dist/cjs/init.cjs +22 -1
  42. package/dist/cjs/init.cjs.map +1 -1
  43. package/dist/cjs/initMCP.cjs +69 -1
  44. package/dist/cjs/initMCP.cjs.map +1 -1
  45. package/dist/cjs/initSkills.cjs +93 -1
  46. package/dist/cjs/initSkills.cjs.map +1 -1
  47. package/dist/cjs/listContentDeclaration.cjs +42 -1
  48. package/dist/cjs/listContentDeclaration.cjs.map +1 -1
  49. package/dist/cjs/listProjects.cjs +28 -1
  50. package/dist/cjs/listProjects.cjs.map +1 -1
  51. package/dist/cjs/liveSync.cjs +153 -8
  52. package/dist/cjs/liveSync.cjs.map +1 -1
  53. package/dist/cjs/pull.cjs +153 -1
  54. package/dist/cjs/pull.cjs.map +1 -1
  55. package/dist/cjs/push/pullLog.cjs +105 -3
  56. package/dist/cjs/push/pullLog.cjs.map +1 -1
  57. package/dist/cjs/push/push.cjs +212 -1
  58. package/dist/cjs/push/push.cjs.map +1 -1
  59. package/dist/cjs/pushConfig.cjs +22 -1
  60. package/dist/cjs/pushConfig.cjs.map +1 -1
  61. package/dist/cjs/pushLog.cjs +86 -3
  62. package/dist/cjs/pushLog.cjs.map +1 -1
  63. package/dist/cjs/reviewDoc/reviewDoc.cjs +73 -1
  64. package/dist/cjs/reviewDoc/reviewDoc.cjs.map +1 -1
  65. package/dist/cjs/reviewDoc/reviewDocBlockAware.cjs +98 -1
  66. package/dist/cjs/reviewDoc/reviewDocBlockAware.cjs.map +1 -1
  67. package/dist/cjs/searchDoc.cjs +41 -1
  68. package/dist/cjs/searchDoc.cjs.map +1 -1
  69. package/dist/cjs/test/index.cjs +7 -1
  70. package/dist/cjs/test/listMissingTranslations.cjs +52 -1
  71. package/dist/cjs/test/listMissingTranslations.cjs.map +1 -1
  72. package/dist/cjs/test/test.cjs +56 -1
  73. package/dist/cjs/test/test.cjs.map +1 -1
  74. package/dist/cjs/translateDoc/index.cjs +9 -1
  75. package/dist/cjs/translateDoc/translateDoc.cjs +79 -1
  76. package/dist/cjs/translateDoc/translateDoc.cjs.map +1 -1
  77. package/dist/cjs/translateDoc/translateFile.cjs +106 -2
  78. package/dist/cjs/translateDoc/translateFile.cjs.map +1 -1
  79. package/dist/cjs/translateDoc/validation.cjs +49 -5
  80. package/dist/cjs/translateDoc/validation.cjs.map +1 -1
  81. package/dist/cjs/translation-alignment/alignBlocks.cjs +67 -1
  82. package/dist/cjs/translation-alignment/alignBlocks.cjs.map +1 -1
  83. package/dist/cjs/translation-alignment/computeSimilarity.cjs +25 -1
  84. package/dist/cjs/translation-alignment/computeSimilarity.cjs.map +1 -1
  85. package/dist/cjs/translation-alignment/fingerprintBlock.cjs +23 -1
  86. package/dist/cjs/translation-alignment/fingerprintBlock.cjs.map +1 -1
  87. package/dist/cjs/translation-alignment/index.cjs +22 -1
  88. package/dist/cjs/translation-alignment/mapChangedLinesToBlocks.cjs +18 -1
  89. package/dist/cjs/translation-alignment/mapChangedLinesToBlocks.cjs.map +1 -1
  90. package/dist/cjs/translation-alignment/normalizeBlock.cjs +22 -1
  91. package/dist/cjs/translation-alignment/normalizeBlock.cjs.map +1 -1
  92. package/dist/cjs/translation-alignment/pipeline.cjs +37 -1
  93. package/dist/cjs/translation-alignment/pipeline.cjs.map +1 -1
  94. package/dist/cjs/translation-alignment/planActions.cjs +46 -1
  95. package/dist/cjs/translation-alignment/planActions.cjs.map +1 -1
  96. package/dist/cjs/translation-alignment/rebuildDocument.cjs +49 -2
  97. package/dist/cjs/translation-alignment/rebuildDocument.cjs.map +1 -1
  98. package/dist/cjs/translation-alignment/segmentDocument.cjs +66 -5
  99. package/dist/cjs/translation-alignment/segmentDocument.cjs.map +1 -1
  100. package/dist/cjs/utils/calculateChunks.cjs +89 -2
  101. package/dist/cjs/utils/calculateChunks.cjs.map +1 -1
  102. package/dist/cjs/utils/checkAccess.cjs +83 -1
  103. package/dist/cjs/utils/checkAccess.cjs.map +1 -1
  104. package/dist/cjs/utils/checkConfigConsistency.cjs +16 -1
  105. package/dist/cjs/utils/checkConfigConsistency.cjs.map +1 -1
  106. package/dist/cjs/utils/checkFileModifiedRange.cjs +81 -1
  107. package/dist/cjs/utils/checkFileModifiedRange.cjs.map +1 -1
  108. package/dist/cjs/utils/checkLastUpdateTime.cjs +19 -1
  109. package/dist/cjs/utils/checkLastUpdateTime.cjs.map +1 -1
  110. package/dist/cjs/utils/chunkInference.cjs +45 -1
  111. package/dist/cjs/utils/chunkInference.cjs.map +1 -1
  112. package/dist/cjs/utils/fixChunkStartEndChars.cjs +27 -3
  113. package/dist/cjs/utils/fixChunkStartEndChars.cjs.map +1 -1
  114. package/dist/cjs/utils/formatTimeDiff.cjs +20 -1
  115. package/dist/cjs/utils/formatTimeDiff.cjs.map +1 -1
  116. package/dist/cjs/utils/getIsFileUpdatedRecently.cjs +16 -1
  117. package/dist/cjs/utils/getIsFileUpdatedRecently.cjs.map +1 -1
  118. package/dist/cjs/utils/getOutputFilePath.cjs +74 -1
  119. package/dist/cjs/utils/getOutputFilePath.cjs.map +1 -1
  120. package/dist/cjs/utils/getParentPackageJSON.cjs +20 -1
  121. package/dist/cjs/utils/getParentPackageJSON.cjs.map +1 -1
  122. package/dist/cjs/utils/listSpecialChars.cjs +54 -2
  123. package/dist/cjs/utils/listSpecialChars.cjs.map +1 -1
  124. package/dist/cjs/utils/mapChunksBetweenFiles.cjs +102 -1
  125. package/dist/cjs/utils/mapChunksBetweenFiles.cjs.map +1 -1
  126. package/dist/cjs/utils/openBrowser.cjs +19 -1
  127. package/dist/cjs/utils/openBrowser.cjs.map +1 -1
  128. package/dist/cjs/utils/reorderParagraphs.cjs +91 -3
  129. package/dist/cjs/utils/reorderParagraphs.cjs.map +1 -1
  130. package/dist/cjs/utils/setupAI.cjs +66 -1
  131. package/dist/cjs/utils/setupAI.cjs.map +1 -1
  132. package/dist/cjs/watch.cjs +47 -1
  133. package/dist/cjs/watch.cjs.map +1 -1
  134. package/dist/esm/IntlayerEventListener.mjs +183 -1
  135. package/dist/esm/IntlayerEventListener.mjs.map +1 -1
  136. package/dist/esm/_virtual/_rolldown/runtime.mjs +8 -0
  137. package/dist/esm/_virtual/_utils_asset.mjs +97 -0
  138. package/dist/esm/auth/login.mjs +86 -2
  139. package/dist/esm/auth/login.mjs.map +1 -1
  140. package/dist/esm/build.mjs +28 -1
  141. package/dist/esm/build.mjs.map +1 -1
  142. package/dist/esm/ci.mjs +74 -1
  143. package/dist/esm/ci.mjs.map +1 -1
  144. package/dist/esm/cli.mjs +482 -1
  145. package/dist/esm/cli.mjs.map +1 -1
  146. package/dist/esm/config.mjs +13 -1
  147. package/dist/esm/config.mjs.map +1 -1
  148. package/dist/esm/editor.mjs +50 -1
  149. package/dist/esm/editor.mjs.map +1 -0
  150. package/dist/esm/extract.mjs +104 -1
  151. package/dist/esm/extract.mjs.map +1 -1
  152. package/dist/esm/fill/deepMergeContent.mjs +25 -1
  153. package/dist/esm/fill/deepMergeContent.mjs.map +1 -1
  154. package/dist/esm/fill/fill.mjs +81 -1
  155. package/dist/esm/fill/fill.mjs.map +1 -1
  156. package/dist/esm/fill/formatAutoFilledFilePath.mjs +30 -1
  157. package/dist/esm/fill/formatAutoFilledFilePath.mjs.map +1 -1
  158. package/dist/esm/fill/formatFillData.mjs +85 -1
  159. package/dist/esm/fill/formatFillData.mjs.map +1 -1
  160. package/dist/esm/fill/getAvailableLocalesInDictionary.mjs +24 -1
  161. package/dist/esm/fill/getAvailableLocalesInDictionary.mjs.map +1 -1
  162. package/dist/esm/fill/getFilterMissingContentPerLocale.mjs +49 -1
  163. package/dist/esm/fill/getFilterMissingContentPerLocale.mjs.map +1 -1
  164. package/dist/esm/fill/index.mjs +4 -1
  165. package/dist/esm/fill/listTranslationsTasks.mjs +69 -1
  166. package/dist/esm/fill/listTranslationsTasks.mjs.map +1 -1
  167. package/dist/esm/fill/translateDictionary.mjs +237 -1
  168. package/dist/esm/fill/translateDictionary.mjs.map +1 -1
  169. package/dist/esm/fill/writeFill.mjs +53 -1
  170. package/dist/esm/fill/writeFill.mjs.map +1 -1
  171. package/dist/esm/getTargetDictionary.mjs +33 -1
  172. package/dist/esm/getTargetDictionary.mjs.map +1 -1
  173. package/dist/esm/index.mjs +20 -1
  174. package/dist/esm/init.mjs +19 -1
  175. package/dist/esm/init.mjs.map +1 -1
  176. package/dist/esm/initMCP.mjs +65 -1
  177. package/dist/esm/initMCP.mjs.map +1 -1
  178. package/dist/esm/initSkills.mjs +87 -1
  179. package/dist/esm/initSkills.mjs.map +1 -1
  180. package/dist/esm/listContentDeclaration.mjs +39 -1
  181. package/dist/esm/listContentDeclaration.mjs.map +1 -1
  182. package/dist/esm/listProjects.mjs +26 -1
  183. package/dist/esm/listProjects.mjs.map +1 -1
  184. package/dist/esm/liveSync.mjs +150 -8
  185. package/dist/esm/liveSync.mjs.map +1 -1
  186. package/dist/esm/pull.mjs +150 -1
  187. package/dist/esm/pull.mjs.map +1 -1
  188. package/dist/esm/push/pullLog.mjs +102 -3
  189. package/dist/esm/push/pullLog.mjs.map +1 -1
  190. package/dist/esm/push/push.mjs +208 -1
  191. package/dist/esm/push/push.mjs.map +1 -1
  192. package/dist/esm/pushConfig.mjs +20 -1
  193. package/dist/esm/pushConfig.mjs.map +1 -1
  194. package/dist/esm/pushLog.mjs +83 -3
  195. package/dist/esm/pushLog.mjs.map +1 -1
  196. package/dist/esm/reviewDoc/reviewDoc.mjs +69 -1
  197. package/dist/esm/reviewDoc/reviewDoc.mjs.map +1 -1
  198. package/dist/esm/reviewDoc/reviewDocBlockAware.mjs +95 -1
  199. package/dist/esm/reviewDoc/reviewDocBlockAware.mjs.map +1 -1
  200. package/dist/esm/searchDoc.mjs +39 -1
  201. package/dist/esm/searchDoc.mjs.map +1 -1
  202. package/dist/esm/test/index.mjs +4 -1
  203. package/dist/esm/test/listMissingTranslations.mjs +49 -1
  204. package/dist/esm/test/listMissingTranslations.mjs.map +1 -1
  205. package/dist/esm/test/test.mjs +53 -1
  206. package/dist/esm/test/test.mjs.map +1 -1
  207. package/dist/esm/translateDoc/index.mjs +5 -1
  208. package/dist/esm/translateDoc/translateDoc.mjs +75 -1
  209. package/dist/esm/translateDoc/translateDoc.mjs.map +1 -1
  210. package/dist/esm/translateDoc/translateFile.mjs +103 -2
  211. package/dist/esm/translateDoc/translateFile.mjs.map +1 -1
  212. package/dist/esm/translateDoc/validation.mjs +46 -5
  213. package/dist/esm/translateDoc/validation.mjs.map +1 -1
  214. package/dist/esm/translation-alignment/alignBlocks.mjs +66 -1
  215. package/dist/esm/translation-alignment/alignBlocks.mjs.map +1 -1
  216. package/dist/esm/translation-alignment/computeSimilarity.mjs +22 -1
  217. package/dist/esm/translation-alignment/computeSimilarity.mjs.map +1 -1
  218. package/dist/esm/translation-alignment/fingerprintBlock.mjs +20 -1
  219. package/dist/esm/translation-alignment/fingerprintBlock.mjs.map +1 -1
  220. package/dist/esm/translation-alignment/index.mjs +11 -1
  221. package/dist/esm/translation-alignment/mapChangedLinesToBlocks.mjs +16 -1
  222. package/dist/esm/translation-alignment/mapChangedLinesToBlocks.mjs.map +1 -1
  223. package/dist/esm/translation-alignment/normalizeBlock.mjs +20 -1
  224. package/dist/esm/translation-alignment/normalizeBlock.mjs.map +1 -1
  225. package/dist/esm/translation-alignment/pipeline.mjs +35 -1
  226. package/dist/esm/translation-alignment/pipeline.mjs.map +1 -1
  227. package/dist/esm/translation-alignment/planActions.mjs +44 -1
  228. package/dist/esm/translation-alignment/planActions.mjs.map +1 -1
  229. package/dist/esm/translation-alignment/rebuildDocument.mjs +46 -2
  230. package/dist/esm/translation-alignment/rebuildDocument.mjs.map +1 -1
  231. package/dist/esm/translation-alignment/segmentDocument.mjs +64 -5
  232. package/dist/esm/translation-alignment/segmentDocument.mjs.map +1 -1
  233. package/dist/esm/utils/calculateChunks.mjs +87 -2
  234. package/dist/esm/utils/calculateChunks.mjs.map +1 -1
  235. package/dist/esm/utils/checkAccess.mjs +79 -1
  236. package/dist/esm/utils/checkAccess.mjs.map +1 -1
  237. package/dist/esm/utils/checkConfigConsistency.mjs +14 -1
  238. package/dist/esm/utils/checkConfigConsistency.mjs.map +1 -1
  239. package/dist/esm/utils/checkFileModifiedRange.mjs +80 -1
  240. package/dist/esm/utils/checkFileModifiedRange.mjs.map +1 -1
  241. package/dist/esm/utils/checkLastUpdateTime.mjs +17 -1
  242. package/dist/esm/utils/checkLastUpdateTime.mjs.map +1 -1
  243. package/dist/esm/utils/chunkInference.mjs +43 -1
  244. package/dist/esm/utils/chunkInference.mjs.map +1 -1
  245. package/dist/esm/utils/fixChunkStartEndChars.mjs +25 -3
  246. package/dist/esm/utils/fixChunkStartEndChars.mjs.map +1 -1
  247. package/dist/esm/utils/formatTimeDiff.mjs +18 -1
  248. package/dist/esm/utils/formatTimeDiff.mjs.map +1 -1
  249. package/dist/esm/utils/getIsFileUpdatedRecently.mjs +14 -1
  250. package/dist/esm/utils/getIsFileUpdatedRecently.mjs.map +1 -1
  251. package/dist/esm/utils/getOutputFilePath.mjs +72 -1
  252. package/dist/esm/utils/getOutputFilePath.mjs.map +1 -1
  253. package/dist/esm/utils/getParentPackageJSON.mjs +18 -1
  254. package/dist/esm/utils/getParentPackageJSON.mjs.map +1 -1
  255. package/dist/esm/utils/listSpecialChars.mjs +52 -2
  256. package/dist/esm/utils/listSpecialChars.mjs.map +1 -1
  257. package/dist/esm/utils/mapChunksBetweenFiles.mjs +100 -1
  258. package/dist/esm/utils/mapChunksBetweenFiles.mjs.map +1 -1
  259. package/dist/esm/utils/openBrowser.mjs +17 -1
  260. package/dist/esm/utils/openBrowser.mjs.map +1 -1
  261. package/dist/esm/utils/reorderParagraphs.mjs +90 -3
  262. package/dist/esm/utils/reorderParagraphs.mjs.map +1 -1
  263. package/dist/esm/utils/setupAI.mjs +63 -1
  264. package/dist/esm/utils/setupAI.mjs.map +1 -1
  265. package/dist/esm/watch.mjs +45 -1
  266. package/dist/esm/watch.mjs.map +1 -1
  267. package/dist/types/fill/fill.d.ts +1 -1
  268. package/dist/types/fill/translateDictionary.d.ts +1 -1
  269. package/dist/types/getTargetDictionary.d.ts +19 -2
  270. package/dist/types/getTargetDictionary.d.ts.map +1 -0
  271. package/dist/types/index.d.ts +2 -2
  272. package/dist/types/reviewDoc/reviewDocBlockAware.d.ts +1 -1
  273. package/dist/types/test/index.d.ts +2 -2
  274. package/dist/types/test/listMissingTranslations.d.ts +28 -2
  275. package/dist/types/test/listMissingTranslations.d.ts.map +1 -0
  276. package/dist/types/test/test.d.ts +11 -2
  277. package/dist/types/test/test.d.ts.map +1 -0
  278. package/dist/types/translateDoc/index.d.ts +1 -1
  279. package/dist/types/translateDoc/translateDoc.d.ts +1 -1
  280. package/dist/types/translateDoc/translateFile.d.ts +1 -1
  281. package/dist/types/translateDoc/types.d.ts +48 -2
  282. package/dist/types/translateDoc/types.d.ts.map +1 -0
  283. package/dist/types/utils/chunkInference.d.ts +1 -1
  284. package/dist/types/utils/setupAI.d.ts +21 -2
  285. package/dist/types/utils/setupAI.d.ts.map +1 -0
  286. package/package.json +12 -12
  287. package/dist/cjs/_utils_asset-ghp_Cjwk.cjs +0 -2
  288. package/dist/cjs/chunk-Bmb41Sf3.cjs +0 -1
  289. package/dist/esm/_utils_asset-B187VPMw.mjs +0 -2
  290. package/dist/esm/editor-D8BGlLzF.mjs +0 -2
  291. package/dist/esm/editor-D8BGlLzF.mjs.map +0 -1
  292. package/dist/types/getTargetDictionary-RBSRtaQj.d.ts +0 -19
  293. package/dist/types/getTargetDictionary-RBSRtaQj.d.ts.map +0 -1
  294. package/dist/types/listMissingTranslations-DxKw7nqI.d.ts +0 -28
  295. package/dist/types/listMissingTranslations-DxKw7nqI.d.ts.map +0 -1
  296. package/dist/types/setupAI-Bosjx7ah.d.ts +0 -21
  297. package/dist/types/setupAI-Bosjx7ah.d.ts.map +0 -1
  298. package/dist/types/test-DUTiJR5_.d.ts +0 -11
  299. package/dist/types/test-DUTiJR5_.d.ts.map +0 -1
  300. package/dist/types/types-BKvc3FmV.d.ts +0 -48
  301. package/dist/types/types-BKvc3FmV.d.ts.map +0 -1
@@ -1,2 +1,50 @@
1
- import{logConfigDetails as e}from"@intlayer/chokidar/cli";import{getConfiguration as t}from"@intlayer/config/node";import{getUnmergedDictionaries as n}from"@intlayer/unmerged-dictionaries-entry";import{getMissingLocalesContentFromDictionary as r}from"@intlayer/core/plugins";import{getDictionaries as i}from"@intlayer/dictionaries-entry";const a=e=>{let t=n(e),a=i(e),o=[],{locales:s,requiredLocales:c}=e.internationalization,l=Object.keys(t);for(let e of l){let n=t[e],i=n.filter(e=>!e.locale);for(let t of i){let n=r(t,s);n.length>0&&o.push({key:e,id:t.id,filePath:t.filePath,locales:n})}if(n.filter(e=>e.locale).length===0)continue;let c=a[e],l=r(c,s);l.length>0&&o.push({key:e,locales:l})}let u=new Set(o.flatMap(e=>e.locales)),d=Array.from(u);return{missingTranslations:o,missingLocales:d,missingRequiredLocales:d.filter(e=>(c??s).includes(e))}},o=n=>{let r=t(n);return e(n),a(r)};export{o as listMissingTranslations,a as listMissingTranslationsWithConfig};
1
+ import { logConfigDetails } from "@intlayer/chokidar/cli";
2
+ import { getConfiguration } from "@intlayer/config/node";
3
+ import { getUnmergedDictionaries } from "@intlayer/unmerged-dictionaries-entry";
4
+ import { getMissingLocalesContentFromDictionary } from "@intlayer/core/plugins";
5
+ import { getDictionaries } from "@intlayer/dictionaries-entry";
6
+
7
+ //#region src/test/listMissingTranslations.ts
8
+ const listMissingTranslationsWithConfig = (configuration) => {
9
+ const unmergedDictionariesRecord = getUnmergedDictionaries(configuration);
10
+ const mergedDictionaries = getDictionaries(configuration);
11
+ const missingTranslations = [];
12
+ const { locales, requiredLocales } = configuration.internationalization;
13
+ const dictionariesKeys = Object.keys(unmergedDictionariesRecord);
14
+ for (const dictionaryKey of dictionariesKeys) {
15
+ const dictionaries = unmergedDictionariesRecord[dictionaryKey];
16
+ const multilingualDictionary = dictionaries.filter((dictionary) => !dictionary.locale);
17
+ for (const dictionary of multilingualDictionary) {
18
+ const missingLocales = getMissingLocalesContentFromDictionary(dictionary, locales);
19
+ if (missingLocales.length > 0) missingTranslations.push({
20
+ key: dictionaryKey,
21
+ id: dictionary.id,
22
+ filePath: dictionary.filePath,
23
+ locales: missingLocales
24
+ });
25
+ }
26
+ if (dictionaries.filter((dictionary) => dictionary.locale).length === 0) continue;
27
+ const mergedDictionary = mergedDictionaries[dictionaryKey];
28
+ const missingLocales = getMissingLocalesContentFromDictionary(mergedDictionary, locales);
29
+ if (missingLocales.length > 0) missingTranslations.push({
30
+ key: dictionaryKey,
31
+ locales: missingLocales
32
+ });
33
+ }
34
+ const missingLocalesSet = new Set(missingTranslations.flatMap((t) => t.locales));
35
+ const missingLocales = Array.from(missingLocalesSet);
36
+ return {
37
+ missingTranslations,
38
+ missingLocales,
39
+ missingRequiredLocales: missingLocales.filter((locale) => (requiredLocales ?? locales).includes(locale))
40
+ };
41
+ };
42
+ const listMissingTranslations = (configurationOptions) => {
43
+ const configuration = getConfiguration(configurationOptions);
44
+ logConfigDetails(configurationOptions);
45
+ return listMissingTranslationsWithConfig(configuration);
46
+ };
47
+
48
+ //#endregion
49
+ export { listMissingTranslations, listMissingTranslationsWithConfig };
2
50
  //# sourceMappingURL=listMissingTranslations.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"listMissingTranslations.mjs","names":[],"sources":["../../../src/test/listMissingTranslations.ts"],"sourcesContent":["import { logConfigDetails } from '@intlayer/chokidar/cli';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport { getMissingLocalesContentFromDictionary } from '@intlayer/core/plugins';\nimport { getDictionaries } from '@intlayer/dictionaries-entry';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport { getUnmergedDictionaries } from '@intlayer/unmerged-dictionaries-entry';\n\nexport const listMissingTranslationsWithConfig = (\n configuration: IntlayerConfig\n) => {\n const unmergedDictionariesRecord = getUnmergedDictionaries(configuration);\n const mergedDictionaries = getDictionaries(configuration);\n\n const missingTranslations: {\n key: string;\n filePath?: string;\n id?: string;\n locales: Locale[];\n }[] = [];\n\n const { locales, requiredLocales } = configuration.internationalization;\n\n const dictionariesKeys = Object.keys(unmergedDictionariesRecord);\n\n for (const dictionaryKey of dictionariesKeys) {\n const dictionaries: Dictionary[] =\n unmergedDictionariesRecord[dictionaryKey];\n\n const multilingualDictionary: Dictionary[] = dictionaries.filter(\n (dictionary) => !dictionary.locale\n );\n\n // Test all by merging all dictionaries to ensure no per-locale dictionary is missing\n for (const dictionary of multilingualDictionary) {\n const missingLocales = getMissingLocalesContentFromDictionary(\n dictionary,\n locales\n );\n\n if (missingLocales.length > 0) {\n missingTranslations.push({\n key: dictionaryKey,\n id: dictionary.id,\n filePath: dictionary.filePath,\n locales: missingLocales,\n });\n }\n }\n\n const perLocaleDictionary: Dictionary[] = dictionaries.filter(\n (dictionary) => dictionary.locale\n );\n\n if (perLocaleDictionary.length === 0) {\n continue;\n }\n\n const mergedDictionary = mergedDictionaries[dictionaryKey];\n\n const missingLocales = getMissingLocalesContentFromDictionary(\n mergedDictionary,\n locales\n );\n\n if (missingLocales.length > 0) {\n missingTranslations.push({\n key: dictionaryKey,\n locales: missingLocales,\n });\n }\n }\n\n const missingLocalesSet = new Set(\n missingTranslations.flatMap((t) => t.locales)\n );\n const missingLocales = Array.from(missingLocalesSet);\n\n const missingRequiredLocales = missingLocales.filter((locale) =>\n (requiredLocales ?? locales).includes(locale)\n );\n\n return { missingTranslations, missingLocales, missingRequiredLocales };\n};\n\nexport const listMissingTranslations = (\n configurationOptions?: GetConfigurationOptions\n) => {\n const configuration = getConfiguration(configurationOptions);\n logConfigDetails(configurationOptions);\n\n return listMissingTranslationsWithConfig(configuration);\n};\n"],"mappings":"kVAYA,MAAa,EACX,GACG,CACH,IAAM,EAA6B,EAAwB,EAAc,CACnE,EAAqB,EAAgB,EAAc,CAEnD,EAKA,EAAE,CAEF,CAAE,UAAS,mBAAoB,EAAc,qBAE7C,EAAmB,OAAO,KAAK,EAA2B,CAEhE,IAAK,IAAM,KAAiB,EAAkB,CAC5C,IAAM,EACJ,EAA2B,GAEvB,EAAuC,EAAa,OACvD,GAAe,CAAC,EAAW,OAC7B,CAGD,IAAK,IAAM,KAAc,EAAwB,CAC/C,IAAM,EAAiB,EACrB,EACA,EACD,CAEG,EAAe,OAAS,GAC1B,EAAoB,KAAK,CACvB,IAAK,EACL,GAAI,EAAW,GACf,SAAU,EAAW,SACrB,QAAS,EACV,CAAC,CAQN,GAJ0C,EAAa,OACpD,GAAe,EAAW,OAC5B,CAEuB,SAAW,EACjC,SAGF,IAAM,EAAmB,EAAmB,GAEtC,EAAiB,EACrB,EACA,EACD,CAEG,EAAe,OAAS,GAC1B,EAAoB,KAAK,CACvB,IAAK,EACL,QAAS,EACV,CAAC,CAIN,IAAM,EAAoB,IAAI,IAC5B,EAAoB,QAAS,GAAM,EAAE,QAAQ,CAC9C,CACK,EAAiB,MAAM,KAAK,EAAkB,CAMpD,MAAO,CAAE,sBAAqB,iBAAgB,uBAJf,EAAe,OAAQ,IACnD,GAAmB,GAAS,SAAS,EAAO,CAC9C,CAEqE,EAG3D,EACX,GACG,CACH,IAAM,EAAgB,EAAiB,EAAqB,CAG5D,OAFA,EAAiB,EAAqB,CAE/B,EAAkC,EAAc"}
1
+ {"version":3,"file":"listMissingTranslations.mjs","names":[],"sources":["../../../src/test/listMissingTranslations.ts"],"sourcesContent":["import { logConfigDetails } from '@intlayer/chokidar/cli';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport { getMissingLocalesContentFromDictionary } from '@intlayer/core/plugins';\nimport { getDictionaries } from '@intlayer/dictionaries-entry';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport { getUnmergedDictionaries } from '@intlayer/unmerged-dictionaries-entry';\n\nexport const listMissingTranslationsWithConfig = (\n configuration: IntlayerConfig\n) => {\n const unmergedDictionariesRecord = getUnmergedDictionaries(configuration);\n const mergedDictionaries = getDictionaries(configuration);\n\n const missingTranslations: {\n key: string;\n filePath?: string;\n id?: string;\n locales: Locale[];\n }[] = [];\n\n const { locales, requiredLocales } = configuration.internationalization;\n\n const dictionariesKeys = Object.keys(unmergedDictionariesRecord);\n\n for (const dictionaryKey of dictionariesKeys) {\n const dictionaries: Dictionary[] =\n unmergedDictionariesRecord[dictionaryKey];\n\n const multilingualDictionary: Dictionary[] = dictionaries.filter(\n (dictionary) => !dictionary.locale\n );\n\n // Test all by merging all dictionaries to ensure no per-locale dictionary is missing\n for (const dictionary of multilingualDictionary) {\n const missingLocales = getMissingLocalesContentFromDictionary(\n dictionary,\n locales\n );\n\n if (missingLocales.length > 0) {\n missingTranslations.push({\n key: dictionaryKey,\n id: dictionary.id,\n filePath: dictionary.filePath,\n locales: missingLocales,\n });\n }\n }\n\n const perLocaleDictionary: Dictionary[] = dictionaries.filter(\n (dictionary) => dictionary.locale\n );\n\n if (perLocaleDictionary.length === 0) {\n continue;\n }\n\n const mergedDictionary = mergedDictionaries[dictionaryKey];\n\n const missingLocales = getMissingLocalesContentFromDictionary(\n mergedDictionary,\n locales\n );\n\n if (missingLocales.length > 0) {\n missingTranslations.push({\n key: dictionaryKey,\n locales: missingLocales,\n });\n }\n }\n\n const missingLocalesSet = new Set(\n missingTranslations.flatMap((t) => t.locales)\n );\n const missingLocales = Array.from(missingLocalesSet);\n\n const missingRequiredLocales = missingLocales.filter((locale) =>\n (requiredLocales ?? locales).includes(locale)\n );\n\n return { missingTranslations, missingLocales, missingRequiredLocales };\n};\n\nexport const listMissingTranslations = (\n configurationOptions?: GetConfigurationOptions\n) => {\n const configuration = getConfiguration(configurationOptions);\n logConfigDetails(configurationOptions);\n\n return listMissingTranslationsWithConfig(configuration);\n};\n"],"mappings":";;;;;;;AAYA,MAAa,qCACX,kBACG;CACH,MAAM,6BAA6B,wBAAwB,cAAc;CACzE,MAAM,qBAAqB,gBAAgB,cAAc;CAEzD,MAAM,sBAKA,EAAE;CAER,MAAM,EAAE,SAAS,oBAAoB,cAAc;CAEnD,MAAM,mBAAmB,OAAO,KAAK,2BAA2B;AAEhE,MAAK,MAAM,iBAAiB,kBAAkB;EAC5C,MAAM,eACJ,2BAA2B;EAE7B,MAAM,yBAAuC,aAAa,QACvD,eAAe,CAAC,WAAW,OAC7B;AAGD,OAAK,MAAM,cAAc,wBAAwB;GAC/C,MAAM,iBAAiB,uCACrB,YACA,QACD;AAED,OAAI,eAAe,SAAS,EAC1B,qBAAoB,KAAK;IACvB,KAAK;IACL,IAAI,WAAW;IACf,UAAU,WAAW;IACrB,SAAS;IACV,CAAC;;AAQN,MAJ0C,aAAa,QACpD,eAAe,WAAW,OAC5B,CAEuB,WAAW,EACjC;EAGF,MAAM,mBAAmB,mBAAmB;EAE5C,MAAM,iBAAiB,uCACrB,kBACA,QACD;AAED,MAAI,eAAe,SAAS,EAC1B,qBAAoB,KAAK;GACvB,KAAK;GACL,SAAS;GACV,CAAC;;CAIN,MAAM,oBAAoB,IAAI,IAC5B,oBAAoB,SAAS,MAAM,EAAE,QAAQ,CAC9C;CACD,MAAM,iBAAiB,MAAM,KAAK,kBAAkB;AAMpD,QAAO;EAAE;EAAqB;EAAgB,wBAJf,eAAe,QAAQ,YACnD,mBAAmB,SAAS,SAAS,OAAO,CAC9C;EAEqE;;AAGxE,MAAa,2BACX,yBACG;CACH,MAAM,gBAAgB,iBAAiB,qBAAqB;AAC5D,kBAAiB,qBAAqB;AAEtC,QAAO,kCAAkC,cAAc"}
@@ -1,2 +1,54 @@
1
- import{listMissingTranslations as e}from"./listMissingTranslations.mjs";import{prepareIntlayer as t}from"@intlayer/chokidar/build";import{formatLocale as n,formatPath as r}from"@intlayer/chokidar/utils";import*as i from"@intlayer/config/colors";import{colon as a,colorize as o,colorizeKey as s,colorizeNumber as c,getAppLogger as l}from"@intlayer/config/logger";import{getConfiguration as u}from"@intlayer/config/node";const d=async d=>{let f=u(d?.configOptions),{locales:p,requiredLocales:m}=f.internationalization,h=l(f);d?.build===!0?await t(f,{forceRun:!0}):d?.build===void 0&&await t(f);let g=e(d?.configOptions),_=g.missingTranslations.map(e=>` - ${e.key}`).reduce((e,t)=>Math.max(e,t.length),0),v=g.missingTranslations.map(e=>n(e.locales,!1)).reduce((e,t)=>Math.max(e,t.length),0),y=g.missingTranslations.map(e=>[a(` - ${s(e.key)}`,{colSize:_,maxSize:40}),` - `,a(n(e.locales,i.RED),{colSize:v,maxSize:40}),e.filePath?` - ${r(e.filePath)}`:``,e.id?` - remote`:``].join(``));h(`Missing translations:`,{level:`info`}),y.forEach(e=>{h(e,{level:`info`})}),h(`Locales: ${n(p)}`),h(`Required locales: ${n(m??p)}`),h(`Missing locales: ${g.missingLocales.length===0?o(`-`,i.GREEN):n(g.missingLocales,i.RED)}`),h(`Missing required locales: ${g.missingRequiredLocales.length===0?o(`-`,i.GREEN):n(g.missingRequiredLocales,i.RED)}`),h(`Total missing locales: ${c(g.missingLocales.length,{one:i.RED,other:i.RED,zero:i.GREEN})}`),h(`Total missing required locales: ${c(g.missingRequiredLocales.length,{one:i.RED,other:i.RED,zero:i.GREEN})}`),g.missingRequiredLocales.length>0&&process.exit(1)};export{d as testMissingTranslations};
1
+ import { listMissingTranslations } from "./listMissingTranslations.mjs";
2
+ import { prepareIntlayer } from "@intlayer/chokidar/build";
3
+ import { formatLocale, formatPath } from "@intlayer/chokidar/utils";
4
+ import * as ANSIColors from "@intlayer/config/colors";
5
+ import { colon, colorize, colorizeKey, colorizeNumber, getAppLogger } from "@intlayer/config/logger";
6
+ import { getConfiguration } from "@intlayer/config/node";
7
+
8
+ //#region src/test/test.ts
9
+ const testMissingTranslations = async (options) => {
10
+ const config = getConfiguration(options?.configOptions);
11
+ const { locales, requiredLocales } = config.internationalization;
12
+ const appLogger = getAppLogger(config);
13
+ if (options?.build === true) await prepareIntlayer(config, { forceRun: true });
14
+ else if (typeof options?.build === "undefined") await prepareIntlayer(config);
15
+ const result = listMissingTranslations(options?.configOptions);
16
+ const maxKeyColSize = result.missingTranslations.map((t) => ` - ${t.key}`).reduce((max, t) => Math.max(max, t.length), 0);
17
+ const maxLocalesColSize = result.missingTranslations.map((t) => formatLocale(t.locales, false)).reduce((max, t) => Math.max(max, t.length), 0);
18
+ const formattedMissingTranslations = result.missingTranslations.map((translation) => [
19
+ colon(` - ${colorizeKey(translation.key)}`, {
20
+ colSize: maxKeyColSize,
21
+ maxSize: 40
22
+ }),
23
+ " - ",
24
+ colon(formatLocale(translation.locales, ANSIColors.RED), {
25
+ colSize: maxLocalesColSize,
26
+ maxSize: 40
27
+ }),
28
+ translation.filePath ? ` - ${formatPath(translation.filePath)}` : "",
29
+ translation.id ? " - remote" : ""
30
+ ].join(""));
31
+ appLogger(`Missing translations:`, { level: "info" });
32
+ formattedMissingTranslations.forEach((t) => {
33
+ appLogger(t, { level: "info" });
34
+ });
35
+ appLogger(`Locales: ${formatLocale(locales)}`);
36
+ appLogger(`Required locales: ${formatLocale(requiredLocales ?? locales)}`);
37
+ appLogger(`Missing locales: ${result.missingLocales.length === 0 ? colorize("-", ANSIColors.GREEN) : formatLocale(result.missingLocales, ANSIColors.RED)}`);
38
+ appLogger(`Missing required locales: ${result.missingRequiredLocales.length === 0 ? colorize("-", ANSIColors.GREEN) : formatLocale(result.missingRequiredLocales, ANSIColors.RED)}`);
39
+ appLogger(`Total missing locales: ${colorizeNumber(result.missingLocales.length, {
40
+ one: ANSIColors.RED,
41
+ other: ANSIColors.RED,
42
+ zero: ANSIColors.GREEN
43
+ })}`);
44
+ appLogger(`Total missing required locales: ${colorizeNumber(result.missingRequiredLocales.length, {
45
+ one: ANSIColors.RED,
46
+ other: ANSIColors.RED,
47
+ zero: ANSIColors.GREEN
48
+ })}`);
49
+ if (result.missingRequiredLocales.length > 0) process.exit(1);
50
+ };
51
+
52
+ //#endregion
53
+ export { testMissingTranslations };
2
54
  //# sourceMappingURL=test.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"test.mjs","names":[],"sources":["../../../src/test/test.ts"],"sourcesContent":["import { prepareIntlayer } from '@intlayer/chokidar/build';\nimport { formatLocale, formatPath } from '@intlayer/chokidar/utils';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport {\n colon,\n colorize,\n colorizeKey,\n colorizeNumber,\n getAppLogger,\n} from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport { listMissingTranslations } from './listMissingTranslations';\n\ntype ListMissingTranslationsOptions = {\n configOptions?: GetConfigurationOptions;\n build?: boolean;\n};\n\nexport const testMissingTranslations = async (\n options?: ListMissingTranslationsOptions\n) => {\n const config = getConfiguration(options?.configOptions);\n const { locales, requiredLocales } = config.internationalization;\n\n const appLogger = getAppLogger(config);\n\n if (options?.build === true) {\n await prepareIntlayer(config, { forceRun: true });\n } else if (typeof options?.build === 'undefined') {\n await prepareIntlayer(config);\n }\n\n const result = listMissingTranslations(options?.configOptions);\n\n const maxKeyColSize = result.missingTranslations\n .map((t) => ` - ${t.key}`)\n .reduce((max, t) => Math.max(max, t.length), 0);\n const maxLocalesColSize = result.missingTranslations\n .map((t) => formatLocale(t.locales, false))\n .reduce((max, t) => Math.max(max, t.length), 0);\n\n const formattedMissingTranslations = result.missingTranslations.map(\n (translation) =>\n [\n colon(` - ${colorizeKey(translation.key)}`, {\n colSize: maxKeyColSize,\n maxSize: 40,\n }),\n ' - ',\n colon(formatLocale(translation.locales, ANSIColors.RED), {\n colSize: maxLocalesColSize,\n maxSize: 40,\n }),\n\n translation.filePath ? ` - ${formatPath(translation.filePath)}` : '',\n translation.id ? ' - remote' : '',\n ].join('')\n );\n\n appLogger(`Missing translations:`, {\n level: 'info',\n });\n\n formattedMissingTranslations.forEach((t) => {\n appLogger(t, {\n level: 'info',\n });\n });\n\n appLogger(`Locales: ${formatLocale(locales)}`);\n appLogger(`Required locales: ${formatLocale(requiredLocales ?? locales)}`);\n appLogger(\n `Missing locales: ${result.missingLocales.length === 0 ? colorize('-', ANSIColors.GREEN) : formatLocale(result.missingLocales, ANSIColors.RED)}`\n );\n\n appLogger(\n `Missing required locales: ${result.missingRequiredLocales.length === 0 ? colorize('-', ANSIColors.GREEN) : formatLocale(result.missingRequiredLocales, ANSIColors.RED)}`\n );\n appLogger(\n `Total missing locales: ${colorizeNumber(result.missingLocales.length, {\n one: ANSIColors.RED,\n other: ANSIColors.RED,\n zero: ANSIColors.GREEN,\n })}`\n );\n appLogger(\n `Total missing required locales: ${colorizeNumber(\n result.missingRequiredLocales.length,\n {\n one: ANSIColors.RED,\n other: ANSIColors.RED,\n zero: ANSIColors.GREEN,\n }\n )}`\n );\n\n if (result.missingRequiredLocales.length > 0) {\n process.exit(1);\n }\n};\n"],"mappings":"maAqBA,MAAa,EAA0B,KACrC,IACG,CACH,IAAM,EAAS,EAAiB,GAAS,cAAc,CACjD,CAAE,UAAS,mBAAoB,EAAO,qBAEtC,EAAY,EAAa,EAAO,CAElC,GAAS,QAAU,GACrB,MAAM,EAAgB,EAAQ,CAAE,SAAU,GAAM,CAAC,CACjC,GAAS,QAAU,QACnC,MAAM,EAAgB,EAAO,CAG/B,IAAM,EAAS,EAAwB,GAAS,cAAc,CAExD,EAAgB,EAAO,oBAC1B,IAAK,GAAM,MAAM,EAAE,MAAM,CACzB,QAAQ,EAAK,IAAM,KAAK,IAAI,EAAK,EAAE,OAAO,CAAE,EAAE,CAC3C,EAAoB,EAAO,oBAC9B,IAAK,GAAM,EAAa,EAAE,QAAS,GAAM,CAAC,CAC1C,QAAQ,EAAK,IAAM,KAAK,IAAI,EAAK,EAAE,OAAO,CAAE,EAAE,CAE3C,EAA+B,EAAO,oBAAoB,IAC7D,GACC,CACE,EAAM,MAAM,EAAY,EAAY,IAAI,GAAI,CAC1C,QAAS,EACT,QAAS,GACV,CAAC,CACF,MACA,EAAM,EAAa,EAAY,QAAS,EAAW,IAAI,CAAE,CACvD,QAAS,EACT,QAAS,GACV,CAAC,CAEF,EAAY,SAAW,MAAM,EAAW,EAAY,SAAS,GAAK,GAClE,EAAY,GAAK,YAAc,GAChC,CAAC,KAAK,GAAG,CACb,CAED,EAAU,wBAAyB,CACjC,MAAO,OACR,CAAC,CAEF,EAA6B,QAAS,GAAM,CAC1C,EAAU,EAAG,CACX,MAAO,OACR,CAAC,EACF,CAEF,EAAU,YAAY,EAAa,EAAQ,GAAG,CAC9C,EAAU,qBAAqB,EAAa,GAAmB,EAAQ,GAAG,CAC1E,EACE,oBAAoB,EAAO,eAAe,SAAW,EAAI,EAAS,IAAK,EAAW,MAAM,CAAG,EAAa,EAAO,eAAgB,EAAW,IAAI,GAC/I,CAED,EACE,6BAA6B,EAAO,uBAAuB,SAAW,EAAI,EAAS,IAAK,EAAW,MAAM,CAAG,EAAa,EAAO,uBAAwB,EAAW,IAAI,GACxK,CACD,EACE,0BAA0B,EAAe,EAAO,eAAe,OAAQ,CACrE,IAAK,EAAW,IAChB,MAAO,EAAW,IAClB,KAAM,EAAW,MAClB,CAAC,GACH,CACD,EACE,mCAAmC,EACjC,EAAO,uBAAuB,OAC9B,CACE,IAAK,EAAW,IAChB,MAAO,EAAW,IAClB,KAAM,EAAW,MAClB,CACF,GACF,CAEG,EAAO,uBAAuB,OAAS,GACzC,QAAQ,KAAK,EAAE"}
1
+ {"version":3,"file":"test.mjs","names":[],"sources":["../../../src/test/test.ts"],"sourcesContent":["import { prepareIntlayer } from '@intlayer/chokidar/build';\nimport { formatLocale, formatPath } from '@intlayer/chokidar/utils';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport {\n colon,\n colorize,\n colorizeKey,\n colorizeNumber,\n getAppLogger,\n} from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport { listMissingTranslations } from './listMissingTranslations';\n\ntype ListMissingTranslationsOptions = {\n configOptions?: GetConfigurationOptions;\n build?: boolean;\n};\n\nexport const testMissingTranslations = async (\n options?: ListMissingTranslationsOptions\n) => {\n const config = getConfiguration(options?.configOptions);\n const { locales, requiredLocales } = config.internationalization;\n\n const appLogger = getAppLogger(config);\n\n if (options?.build === true) {\n await prepareIntlayer(config, { forceRun: true });\n } else if (typeof options?.build === 'undefined') {\n await prepareIntlayer(config);\n }\n\n const result = listMissingTranslations(options?.configOptions);\n\n const maxKeyColSize = result.missingTranslations\n .map((t) => ` - ${t.key}`)\n .reduce((max, t) => Math.max(max, t.length), 0);\n const maxLocalesColSize = result.missingTranslations\n .map((t) => formatLocale(t.locales, false))\n .reduce((max, t) => Math.max(max, t.length), 0);\n\n const formattedMissingTranslations = result.missingTranslations.map(\n (translation) =>\n [\n colon(` - ${colorizeKey(translation.key)}`, {\n colSize: maxKeyColSize,\n maxSize: 40,\n }),\n ' - ',\n colon(formatLocale(translation.locales, ANSIColors.RED), {\n colSize: maxLocalesColSize,\n maxSize: 40,\n }),\n\n translation.filePath ? ` - ${formatPath(translation.filePath)}` : '',\n translation.id ? ' - remote' : '',\n ].join('')\n );\n\n appLogger(`Missing translations:`, {\n level: 'info',\n });\n\n formattedMissingTranslations.forEach((t) => {\n appLogger(t, {\n level: 'info',\n });\n });\n\n appLogger(`Locales: ${formatLocale(locales)}`);\n appLogger(`Required locales: ${formatLocale(requiredLocales ?? locales)}`);\n appLogger(\n `Missing locales: ${result.missingLocales.length === 0 ? colorize('-', ANSIColors.GREEN) : formatLocale(result.missingLocales, ANSIColors.RED)}`\n );\n\n appLogger(\n `Missing required locales: ${result.missingRequiredLocales.length === 0 ? colorize('-', ANSIColors.GREEN) : formatLocale(result.missingRequiredLocales, ANSIColors.RED)}`\n );\n appLogger(\n `Total missing locales: ${colorizeNumber(result.missingLocales.length, {\n one: ANSIColors.RED,\n other: ANSIColors.RED,\n zero: ANSIColors.GREEN,\n })}`\n );\n appLogger(\n `Total missing required locales: ${colorizeNumber(\n result.missingRequiredLocales.length,\n {\n one: ANSIColors.RED,\n other: ANSIColors.RED,\n zero: ANSIColors.GREEN,\n }\n )}`\n );\n\n if (result.missingRequiredLocales.length > 0) {\n process.exit(1);\n }\n};\n"],"mappings":";;;;;;;;AAqBA,MAAa,0BAA0B,OACrC,YACG;CACH,MAAM,SAAS,iBAAiB,SAAS,cAAc;CACvD,MAAM,EAAE,SAAS,oBAAoB,OAAO;CAE5C,MAAM,YAAY,aAAa,OAAO;AAEtC,KAAI,SAAS,UAAU,KACrB,OAAM,gBAAgB,QAAQ,EAAE,UAAU,MAAM,CAAC;UACxC,OAAO,SAAS,UAAU,YACnC,OAAM,gBAAgB,OAAO;CAG/B,MAAM,SAAS,wBAAwB,SAAS,cAAc;CAE9D,MAAM,gBAAgB,OAAO,oBAC1B,KAAK,MAAM,MAAM,EAAE,MAAM,CACzB,QAAQ,KAAK,MAAM,KAAK,IAAI,KAAK,EAAE,OAAO,EAAE,EAAE;CACjD,MAAM,oBAAoB,OAAO,oBAC9B,KAAK,MAAM,aAAa,EAAE,SAAS,MAAM,CAAC,CAC1C,QAAQ,KAAK,MAAM,KAAK,IAAI,KAAK,EAAE,OAAO,EAAE,EAAE;CAEjD,MAAM,+BAA+B,OAAO,oBAAoB,KAC7D,gBACC;EACE,MAAM,MAAM,YAAY,YAAY,IAAI,IAAI;GAC1C,SAAS;GACT,SAAS;GACV,CAAC;EACF;EACA,MAAM,aAAa,YAAY,SAAS,WAAW,IAAI,EAAE;GACvD,SAAS;GACT,SAAS;GACV,CAAC;EAEF,YAAY,WAAW,MAAM,WAAW,YAAY,SAAS,KAAK;EAClE,YAAY,KAAK,cAAc;EAChC,CAAC,KAAK,GAAG,CACb;AAED,WAAU,yBAAyB,EACjC,OAAO,QACR,CAAC;AAEF,8BAA6B,SAAS,MAAM;AAC1C,YAAU,GAAG,EACX,OAAO,QACR,CAAC;GACF;AAEF,WAAU,YAAY,aAAa,QAAQ,GAAG;AAC9C,WAAU,qBAAqB,aAAa,mBAAmB,QAAQ,GAAG;AAC1E,WACE,oBAAoB,OAAO,eAAe,WAAW,IAAI,SAAS,KAAK,WAAW,MAAM,GAAG,aAAa,OAAO,gBAAgB,WAAW,IAAI,GAC/I;AAED,WACE,6BAA6B,OAAO,uBAAuB,WAAW,IAAI,SAAS,KAAK,WAAW,MAAM,GAAG,aAAa,OAAO,wBAAwB,WAAW,IAAI,GACxK;AACD,WACE,0BAA0B,eAAe,OAAO,eAAe,QAAQ;EACrE,KAAK,WAAW;EAChB,OAAO,WAAW;EAClB,MAAM,WAAW;EAClB,CAAC,GACH;AACD,WACE,mCAAmC,eACjC,OAAO,uBAAuB,QAC9B;EACE,KAAK,WAAW;EAChB,OAAO,WAAW;EAClB,MAAM,WAAW;EAClB,CACF,GACF;AAED,KAAI,OAAO,uBAAuB,SAAS,EACzC,SAAQ,KAAK,EAAE"}
@@ -1 +1,5 @@
1
- import"../_utils_asset-B187VPMw.mjs";import{sanitizeChunk as e,validateTranslation as t}from"./validation.mjs";import{translateFile as n}from"./translateFile.mjs";import{translateDoc as r}from"./translateDoc.mjs";import"./types.mjs";export{e as sanitizeChunk,r as translateDoc,n as translateFile,t as validateTranslation};
1
+ import { sanitizeChunk, validateTranslation } from "./validation.mjs";
2
+ import { translateFile } from "./translateFile.mjs";
3
+ import { translateDoc } from "./translateDoc.mjs";
4
+
5
+ export { sanitizeChunk, translateDoc, translateFile, validateTranslation };
@@ -1,2 +1,76 @@
1
- import{setupAI as e}from"../utils/setupAI.mjs";import{checkFileModifiedRange as t}from"../utils/checkFileModifiedRange.mjs";import{getOutputFilePath as n}from"../utils/getOutputFilePath.mjs";import"../_utils_asset-B187VPMw.mjs";import{translateFile as r}from"./translateFile.mjs";import{existsSync as i,mkdirSync as a,writeFileSync as o}from"node:fs";import{dirname as s,join as c}from"node:path";import{listGitFiles as l,logConfigDetails as u}from"@intlayer/chokidar/cli";import{pLimit as d,parallelize as f}from"@intlayer/chokidar/utils";import*as p from"@intlayer/config/colors";import{colorize as m,colorizeNumber as h,getAppLogger as g}from"@intlayer/config/logger";import{getConfiguration as _}from"@intlayer/config/node";import v from"fast-glob";import{performance as y}from"node:perf_hooks";const b=async({docPattern:b,locales:x,excludedGlobPattern:S,baseLocale:C,aiOptions:w,nbSimultaneousFileProcessed:T=20,configOptions:E,customInstructions:D,skipIfModifiedBefore:O,skipIfModifiedAfter:k,skipIfExists:A,gitOptions:j,flushStrategy:M=`incremental`})=>{let N=_(E);u(E);let P=g(N),F=T,I=d(F),L=await v(b,{ignore:S}),R=await e(N,w);if(!R?.hasAIAccess)return;let{aiClient:z,aiConfig:B}=R;if(j){let e=await l(j);e&&(L=L.filter(t=>e.some(e=>c(process.cwd(),t)===e)))}let V=y.now();P(`Translating ${h(L.length)} files to ${h(x.length)} locales. \nGlobal Concurrency: ${h(F)} chunks in parallel.`);let H={count:0,maxErrors:5,shouldStop:!1};await f(L.flatMap(e=>x.map(l=>async()=>{if(H.shouldStop)return;let u=c(N.system.baseDir,e),d=n(u,l,C);if(A&&i(d))return;M===`incremental`&&!i(d)&&(a(s(d),{recursive:!0}),o(d,``));let f=t(d,{skipIfModifiedBefore:O,skipIfModifiedAfter:k});if(f.isSkipped){P(f.message);return}await r({baseFilePath:u,outputFilePath:d,locale:l,baseLocale:C,configuration:N,errorState:H,aiOptions:w,customInstructions:D,aiClient:z,aiConfig:B,flushStrategy:M,limit:I})})),e=>e(),50);let U=((y.now()-V)/1e3).toFixed(2);H.count>0?P(`Finished with ${H.count} errors in ${U}s.`):P(`${m(`✔`,p.GREEN)} Batch completed successfully in ${h(U)}s.`)};export{b as translateDoc};
1
+ import { setupAI } from "../utils/setupAI.mjs";
2
+ import { checkFileModifiedRange } from "../utils/checkFileModifiedRange.mjs";
3
+ import { getOutputFilePath } from "../utils/getOutputFilePath.mjs";
4
+ import { translateFile } from "./translateFile.mjs";
5
+ import { existsSync, mkdirSync, writeFileSync } from "node:fs";
6
+ import { dirname, join } from "node:path";
7
+ import { listGitFiles, logConfigDetails } from "@intlayer/chokidar/cli";
8
+ import { pLimit, parallelize } from "@intlayer/chokidar/utils";
9
+ import * as ANSIColors from "@intlayer/config/colors";
10
+ import { colorize, colorizeNumber, getAppLogger } from "@intlayer/config/logger";
11
+ import { getConfiguration } from "@intlayer/config/node";
12
+ import fg from "fast-glob";
13
+ import { performance } from "node:perf_hooks";
14
+
15
+ //#region src/translateDoc/translateDoc.ts
16
+ const translateDoc = async ({ docPattern, locales, excludedGlobPattern, baseLocale, aiOptions, nbSimultaneousFileProcessed = 20, configOptions, customInstructions, skipIfModifiedBefore, skipIfModifiedAfter, skipIfExists, gitOptions, flushStrategy = "incremental" }) => {
17
+ const configuration = getConfiguration(configOptions);
18
+ logConfigDetails(configOptions);
19
+ const appLogger = getAppLogger(configuration);
20
+ const maxConcurrentChunks = nbSimultaneousFileProcessed;
21
+ const globalChunkLimiter = pLimit(maxConcurrentChunks);
22
+ let docList = await fg(docPattern, { ignore: excludedGlobPattern });
23
+ const aiResult = await setupAI(configuration, aiOptions);
24
+ if (!aiResult?.hasAIAccess) return;
25
+ const { aiClient, aiConfig } = aiResult;
26
+ if (gitOptions) {
27
+ const gitChangedFiles = await listGitFiles(gitOptions);
28
+ if (gitChangedFiles) docList = docList.filter((path) => gitChangedFiles.some((gitFile) => join(process.cwd(), path) === gitFile));
29
+ }
30
+ const batchStartTime = performance.now();
31
+ appLogger(`Translating ${colorizeNumber(docList.length)} files to ${colorizeNumber(locales.length)} locales. \nGlobal Concurrency: ${colorizeNumber(maxConcurrentChunks)} chunks in parallel.`);
32
+ const errorState = {
33
+ count: 0,
34
+ maxErrors: 5,
35
+ shouldStop: false
36
+ };
37
+ await parallelize(docList.flatMap((docPath) => locales.map((locale) => async () => {
38
+ if (errorState.shouldStop) return;
39
+ const absoluteBaseFilePath = join(configuration.system.baseDir, docPath);
40
+ const outputFilePath = getOutputFilePath(absoluteBaseFilePath, locale, baseLocale);
41
+ if (skipIfExists && existsSync(outputFilePath)) return;
42
+ if (flushStrategy === "incremental" && !existsSync(outputFilePath)) {
43
+ mkdirSync(dirname(outputFilePath), { recursive: true });
44
+ writeFileSync(outputFilePath, "");
45
+ }
46
+ const fileModificationData = checkFileModifiedRange(outputFilePath, {
47
+ skipIfModifiedBefore,
48
+ skipIfModifiedAfter
49
+ });
50
+ if (fileModificationData.isSkipped) {
51
+ appLogger(fileModificationData.message);
52
+ return;
53
+ }
54
+ await translateFile({
55
+ baseFilePath: absoluteBaseFilePath,
56
+ outputFilePath,
57
+ locale,
58
+ baseLocale,
59
+ configuration,
60
+ errorState,
61
+ aiOptions,
62
+ customInstructions,
63
+ aiClient,
64
+ aiConfig,
65
+ flushStrategy,
66
+ limit: globalChunkLimiter
67
+ });
68
+ })), (task) => task(), 50);
69
+ const batchDuration = ((performance.now() - batchStartTime) / 1e3).toFixed(2);
70
+ if (errorState.count > 0) appLogger(`Finished with ${errorState.count} errors in ${batchDuration}s.`);
71
+ else appLogger(`${colorize("✔", ANSIColors.GREEN)} Batch completed successfully in ${colorizeNumber(batchDuration)}s.`);
72
+ };
73
+
74
+ //#endregion
75
+ export { translateDoc };
2
76
  //# sourceMappingURL=translateDoc.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"translateDoc.mjs","names":[],"sources":["../../../src/translateDoc/translateDoc.ts"],"sourcesContent":["import { existsSync, mkdirSync, writeFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { performance } from 'node:perf_hooks';\nimport { listGitFiles, logConfigDetails } from '@intlayer/chokidar/cli';\nimport { parallelize, pLimit } from '@intlayer/chokidar/utils';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport {\n colorize,\n colorizeNumber,\n getAppLogger,\n} from '@intlayer/config/logger';\nimport { getConfiguration } from '@intlayer/config/node';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport fg from 'fast-glob';\nimport { checkFileModifiedRange } from '../utils/checkFileModifiedRange';\nimport { getOutputFilePath } from '../utils/getOutputFilePath';\nimport { setupAI } from '../utils/setupAI';\nimport { translateFile } from './translateFile';\nimport type { ErrorState, TranslateDocOptions } from './types';\n\nexport const translateDoc = async ({\n docPattern,\n locales,\n excludedGlobPattern,\n baseLocale,\n aiOptions,\n nbSimultaneousFileProcessed = 20, // Default to a higher concurrency for chunks\n configOptions,\n customInstructions,\n skipIfModifiedBefore,\n skipIfModifiedAfter,\n skipIfExists,\n gitOptions,\n flushStrategy = 'incremental',\n}: TranslateDocOptions) => {\n const configuration = getConfiguration(configOptions);\n logConfigDetails(configOptions);\n\n const appLogger = getAppLogger(configuration);\n\n // 1. GLOBAL QUEUE SETUP\n // We use pLimit to create a single bottleneck for AI requests.\n // This queue is shared across all files and locales.\n const maxConcurrentChunks = nbSimultaneousFileProcessed;\n const globalChunkLimiter = pLimit(maxConcurrentChunks);\n\n let docList: string[] = await fg(docPattern, {\n ignore: excludedGlobPattern,\n });\n\n const aiResult = await setupAI(configuration, aiOptions);\n if (!aiResult?.hasAIAccess) return;\n const { aiClient, aiConfig } = aiResult;\n\n if (gitOptions) {\n const gitChangedFiles = await listGitFiles(gitOptions);\n if (gitChangedFiles) {\n docList = docList.filter((path) =>\n gitChangedFiles.some((gitFile) => join(process.cwd(), path) === gitFile)\n );\n }\n }\n\n const batchStartTime = performance.now();\n\n appLogger(\n `Translating ${colorizeNumber(docList.length)} files to ${colorizeNumber(locales.length)} locales. \\n` +\n `Global Concurrency: ${colorizeNumber(maxConcurrentChunks)} chunks in parallel.`\n );\n\n const errorState: ErrorState = {\n count: 0,\n maxErrors: 5,\n shouldStop: false,\n };\n\n // 2. FLATTENED TASK LIST\n // We create a task for every File x Locale combination.\n const allTasks = docList.flatMap((docPath) =>\n locales.map((locale) => async () => {\n if (errorState.shouldStop) return;\n\n const absoluteBaseFilePath = join(configuration.system.baseDir, docPath);\n const outputFilePath = getOutputFilePath(\n absoluteBaseFilePath,\n locale,\n baseLocale\n );\n\n // Skip logic\n if (skipIfExists && existsSync(outputFilePath)) return;\n\n if (flushStrategy === 'incremental' && !existsSync(outputFilePath)) {\n mkdirSync(dirname(outputFilePath), { recursive: true });\n writeFileSync(outputFilePath, '');\n }\n\n const fileModificationData = checkFileModifiedRange(outputFilePath, {\n skipIfModifiedBefore,\n skipIfModifiedAfter,\n });\n\n if (fileModificationData.isSkipped) {\n appLogger(fileModificationData.message);\n return;\n }\n\n // Execute translation using the SHARED limiter\n await translateFile({\n baseFilePath: absoluteBaseFilePath,\n outputFilePath,\n locale: locale as Locale,\n baseLocale,\n configuration,\n errorState,\n aiOptions,\n customInstructions,\n aiClient,\n aiConfig,\n flushStrategy,\n limit: globalChunkLimiter, // Pass the global queue\n });\n })\n );\n\n // 3. HIGH-THROUGHPUT FILE OPENER\n // We open many files simultaneously (e.g., 50) to ensure the global chunk queue\n // is always saturated with work.\n // If we open too few files, the chunk queue might drain faster than we can read new files.\n const FILE_OPEN_LIMIT = 50;\n\n await parallelize(allTasks, (task) => task(), FILE_OPEN_LIMIT);\n\n const batchEndTime = performance.now();\n const batchDuration = ((batchEndTime - batchStartTime) / 1000).toFixed(2);\n\n if (errorState.count > 0) {\n appLogger(`Finished with ${errorState.count} errors in ${batchDuration}s.`);\n } else {\n appLogger(\n `${colorize('✔', ANSIColors.GREEN)} Batch completed successfully in ${colorizeNumber(batchDuration)}s.`\n );\n }\n};\n"],"mappings":"+xBAoBA,MAAa,EAAe,MAAO,CACjC,aACA,UACA,sBACA,aACA,YACA,8BAA8B,GAC9B,gBACA,qBACA,uBACA,sBACA,eACA,aACA,gBAAgB,iBACS,CACzB,IAAM,EAAgB,EAAiB,EAAc,CACrD,EAAiB,EAAc,CAE/B,IAAM,EAAY,EAAa,EAAc,CAKvC,EAAsB,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iBAAiB,EAAW,MAAM,aAAa,EAAc,IAAI,CAE3E,EACE,GAAG,EAAS,IAAK,EAAW,MAAM,CAAC,mCAAmC,EAAe,EAAc,CAAC,IACrG"}
1
+ {"version":3,"file":"translateDoc.mjs","names":[],"sources":["../../../src/translateDoc/translateDoc.ts"],"sourcesContent":["import { existsSync, mkdirSync, writeFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { performance } from 'node:perf_hooks';\nimport { listGitFiles, logConfigDetails } from '@intlayer/chokidar/cli';\nimport { parallelize, pLimit } from '@intlayer/chokidar/utils';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport {\n colorize,\n colorizeNumber,\n getAppLogger,\n} from '@intlayer/config/logger';\nimport { getConfiguration } from '@intlayer/config/node';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport fg from 'fast-glob';\nimport { checkFileModifiedRange } from '../utils/checkFileModifiedRange';\nimport { getOutputFilePath } from '../utils/getOutputFilePath';\nimport { setupAI } from '../utils/setupAI';\nimport { translateFile } from './translateFile';\nimport type { ErrorState, TranslateDocOptions } from './types';\n\nexport const translateDoc = async ({\n docPattern,\n locales,\n excludedGlobPattern,\n baseLocale,\n aiOptions,\n nbSimultaneousFileProcessed = 20, // Default to a higher concurrency for chunks\n configOptions,\n customInstructions,\n skipIfModifiedBefore,\n skipIfModifiedAfter,\n skipIfExists,\n gitOptions,\n flushStrategy = 'incremental',\n}: TranslateDocOptions) => {\n const configuration = getConfiguration(configOptions);\n logConfigDetails(configOptions);\n\n const appLogger = getAppLogger(configuration);\n\n // 1. GLOBAL QUEUE SETUP\n // We use pLimit to create a single bottleneck for AI requests.\n // This queue is shared across all files and locales.\n const maxConcurrentChunks = nbSimultaneousFileProcessed;\n const globalChunkLimiter = pLimit(maxConcurrentChunks);\n\n let docList: string[] = await fg(docPattern, {\n ignore: excludedGlobPattern,\n });\n\n const aiResult = await setupAI(configuration, aiOptions);\n if (!aiResult?.hasAIAccess) return;\n const { aiClient, aiConfig } = aiResult;\n\n if (gitOptions) {\n const gitChangedFiles = await listGitFiles(gitOptions);\n if (gitChangedFiles) {\n docList = docList.filter((path) =>\n gitChangedFiles.some((gitFile) => join(process.cwd(), path) === gitFile)\n );\n }\n }\n\n const batchStartTime = performance.now();\n\n appLogger(\n `Translating ${colorizeNumber(docList.length)} files to ${colorizeNumber(locales.length)} locales. \\n` +\n `Global Concurrency: ${colorizeNumber(maxConcurrentChunks)} chunks in parallel.`\n );\n\n const errorState: ErrorState = {\n count: 0,\n maxErrors: 5,\n shouldStop: false,\n };\n\n // 2. FLATTENED TASK LIST\n // We create a task for every File x Locale combination.\n const allTasks = docList.flatMap((docPath) =>\n locales.map((locale) => async () => {\n if (errorState.shouldStop) return;\n\n const absoluteBaseFilePath = join(configuration.system.baseDir, docPath);\n const outputFilePath = getOutputFilePath(\n absoluteBaseFilePath,\n locale,\n baseLocale\n );\n\n // Skip logic\n if (skipIfExists && existsSync(outputFilePath)) return;\n\n if (flushStrategy === 'incremental' && !existsSync(outputFilePath)) {\n mkdirSync(dirname(outputFilePath), { recursive: true });\n writeFileSync(outputFilePath, '');\n }\n\n const fileModificationData = checkFileModifiedRange(outputFilePath, {\n skipIfModifiedBefore,\n skipIfModifiedAfter,\n });\n\n if (fileModificationData.isSkipped) {\n appLogger(fileModificationData.message);\n return;\n }\n\n // Execute translation using the SHARED limiter\n await translateFile({\n baseFilePath: absoluteBaseFilePath,\n outputFilePath,\n locale: locale as Locale,\n baseLocale,\n configuration,\n errorState,\n aiOptions,\n customInstructions,\n aiClient,\n aiConfig,\n flushStrategy,\n limit: globalChunkLimiter, // Pass the global queue\n });\n })\n );\n\n // 3. HIGH-THROUGHPUT FILE OPENER\n // We open many files simultaneously (e.g., 50) to ensure the global chunk queue\n // is always saturated with work.\n // If we open too few files, the chunk queue might drain faster than we can read new files.\n const FILE_OPEN_LIMIT = 50;\n\n await parallelize(allTasks, (task) => task(), FILE_OPEN_LIMIT);\n\n const batchEndTime = performance.now();\n const batchDuration = ((batchEndTime - batchStartTime) / 1000).toFixed(2);\n\n if (errorState.count > 0) {\n appLogger(`Finished with ${errorState.count} errors in ${batchDuration}s.`);\n } else {\n appLogger(\n `${colorize('✔', ANSIColors.GREEN)} Batch completed successfully in ${colorizeNumber(batchDuration)}s.`\n );\n }\n};\n"],"mappings":";;;;;;;;;;;;;;;AAoBA,MAAa,eAAe,OAAO,EACjC,YACA,SACA,qBACA,YACA,WACA,8BAA8B,IAC9B,eACA,oBACA,sBACA,qBACA,cACA,YACA,gBAAgB,oBACS;CACzB,MAAM,gBAAgB,iBAAiB,cAAc;AACrD,kBAAiB,cAAc;CAE/B,MAAM,YAAY,aAAa,cAAc;CAK7C,MAAM,sBAAsB;CAC5B,MAAM,qBAAqB,OAAO,oBAAoB;CAEtD,IAAI,UAAoB,MAAM,GAAG,YAAY,EAC3C,QAAQ,qBACT,CAAC;CAEF,MAAM,WAAW,MAAM,QAAQ,eAAe,UAAU;AACxD,KAAI,CAAC,UAAU,YAAa;CAC5B,MAAM,EAAE,UAAU,aAAa;AAE/B,KAAI,YAAY;EACd,MAAM,kBAAkB,MAAM,aAAa,WAAW;AACtD,MAAI,gBACF,WAAU,QAAQ,QAAQ,SACxB,gBAAgB,MAAM,YAAY,KAAK,QAAQ,KAAK,EAAE,KAAK,KAAK,QAAQ,CACzE;;CAIL,MAAM,iBAAiB,YAAY,KAAK;AAExC,WACE,eAAe,eAAe,QAAQ,OAAO,CAAC,YAAY,eAAe,QAAQ,OAAO,CAAC,kCAChE,eAAe,oBAAoB,CAAC,sBAC9D;CAED,MAAM,aAAyB;EAC7B,OAAO;EACP,WAAW;EACX,YAAY;EACb;AAyDD,OAAM,YArDW,QAAQ,SAAS,YAChC,QAAQ,KAAK,WAAW,YAAY;AAClC,MAAI,WAAW,WAAY;EAE3B,MAAM,uBAAuB,KAAK,cAAc,OAAO,SAAS,QAAQ;EACxE,MAAM,iBAAiB,kBACrB,sBACA,QACA,WACD;AAGD,MAAI,gBAAgB,WAAW,eAAe,CAAE;AAEhD,MAAI,kBAAkB,iBAAiB,CAAC,WAAW,eAAe,EAAE;AAClE,aAAU,QAAQ,eAAe,EAAE,EAAE,WAAW,MAAM,CAAC;AACvD,iBAAc,gBAAgB,GAAG;;EAGnC,MAAM,uBAAuB,uBAAuB,gBAAgB;GAClE;GACA;GACD,CAAC;AAEF,MAAI,qBAAqB,WAAW;AAClC,aAAU,qBAAqB,QAAQ;AACvC;;AAIF,QAAM,cAAc;GAClB,cAAc;GACd;GACQ;GACR;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA,OAAO;GACR,CAAC;GACF,CACH,GAQ4B,SAAS,MAAM,EAFpB,GAEsC;CAG9D,MAAM,kBADe,YAAY,KAAK,GACC,kBAAkB,KAAM,QAAQ,EAAE;AAEzE,KAAI,WAAW,QAAQ,EACrB,WAAU,iBAAiB,WAAW,MAAM,aAAa,cAAc,IAAI;KAE3E,WACE,GAAG,SAAS,KAAK,WAAW,MAAM,CAAC,mCAAmC,eAAe,cAAc,CAAC,IACrG"}
@@ -1,3 +1,104 @@
1
- import{t as e}from"../_utils_asset-B187VPMw.mjs";import{sanitizeChunk as t,validateTranslation as n}from"./validation.mjs";import{chunkInference as r}from"../utils/chunkInference.mjs";import{fixChunkStartEndChars as i}from"../utils/fixChunkStartEndChars.mjs";import{chunkText as a}from"../utils/calculateChunks.mjs";import{mkdirSync as o,writeFileSync as s}from"node:fs";import{dirname as c,relative as l}from"node:path";import{formatLocale as u,formatPath as d}from"@intlayer/chokidar/utils";import*as f from"@intlayer/config/colors";import{colon as p,colorize as m,colorizeNumber as h,getAppLogger as g}from"@intlayer/config/logger";import{retryManager as _}from"@intlayer/config/utils";import{readFile as v}from"node:fs/promises";import{performance as y}from"node:perf_hooks";const b=async({baseFilePath:b,outputFilePath:x,locale:S,baseLocale:C,configuration:w,errorState:T,aiOptions:E,customInstructions:D,aiClient:O,aiConfig:k,flushStrategy:A=`incremental`,onChunkReceive:j,limit:M})=>{if(T.shouldStop)return null;let N=g(w,{config:{prefix:``}}),P=y.now();try{let F=a(await v(b,`utf-8`)),I=F.length,L=`${p(`${f.GREY_DARK}[${d(b)}${f.GREY_DARK}] `,{colSize:40})}${f.RESET}`,R=`${p(`${f.GREY_DARK}[${d(b)}${f.GREY_DARK}][${u(S)}${f.GREY_DARK}] `,{colSize:40})}${f.RESET}`;N(`${L}Split into ${h(I)} chunks. Queuing...`);let z=e(`./prompts/TRANSLATE_PROMPT.md`,`utf-8`).replaceAll(`{{localeName}}`,`${u(S,!1)}`).replaceAll(`{{baseLocaleName}}`,`${u(C,!1)}`).replace(`{{applicationContext}}`,E?.applicationContext??`-`).replace(`{{customInstructions}}`,D??`-`),B=Array(I).fill(``),V=M??(e=>e()),H=F.map((e,a)=>V(async()=>{if(T.shouldStop)return null;let l=g(w,{config:{prefix:`${R} ${f.GREY_DARK}[${a+1}/${I}] ${f.RESET}`}}),u=y.now(),d=a===0,p=e.content,m=()=>">>> CONTEXT: PREVIOUS SOURCE CONTENT <<<\n```\n"+(F[a-1]?.content??``)+"\n```\n>>> END PREVIOUS CONTEXT <<<",v=()=>">>> CONTEXT: NEXT CONTENT <<<\n```\n"+(F[a+1]?.content??``)+"\n```\n>>> END NEXT CONTEXT <<<";l(`Process started`);let{content:b,tokens:S}=await _(async()=>{let e=await r([{role:`system`,content:z},...F[a+1]?[{role:`system`,content:v()}]:[],...d?[]:[{role:`system`,content:m()}],{role:`system`,content:[`You are translating TARGET CHUNK (${a+1}/${I}).`,`Translate ONLY the target chunk. Preserve frontmatter/code exactly.`].join(`
2
- `)},{role:`user`,content:`>>> TARGET CHUNK START <<<\n${p}\n>>> TARGET CHUNK END <<<`}],E,w,O,k),o=t(e?.fileContent,p);if(o=i(o,p),!n(p,o,l))throw Error(`Validation failed for chunk ${a+1}/${I}`);return{content:o,tokens:e.tokenUsed}})(),C=(y.now()-u).toFixed(0);if(B[a]=b,j&&j(b,a,I),A===`incremental`&&B.slice(0,a+1).every(e=>e&&e!==``)){let e=0;for(;e<I&&B[e]&&B[e]!==``;)e++;let t=B.slice(0,e).join(``);o(c(x),{recursive:!0}),s(x,t)}l([`${h(S)} tokens used `,`${f.GREY_DARK}in ${h(C)}ms${f.RESET}`].join(``))}));await Promise.all(H);let U=B.join(``);(A===`end`||A===`incremental`)&&(o(c(x),{recursive:!0}),s(x,U));let W=((y.now()-P)/1e3).toFixed(2),G=l(w.system.baseDir,x);return N(`${m(`✔`,f.GREEN)} File ${d(G)} completed in ${h(W)}s.`),U}catch(e){T.count++;let t=e?.message??JSON.stringify(e);return N(`${m(`✖`,f.RED)} Error: ${t}`),T.count>=T.maxErrors&&(T.shouldStop=!0),null}};export{b as translateFile};
1
+ import { readAsset } from "../_virtual/_utils_asset.mjs";
2
+ import { sanitizeChunk, validateTranslation } from "./validation.mjs";
3
+ import { chunkInference } from "../utils/chunkInference.mjs";
4
+ import { fixChunkStartEndChars } from "../utils/fixChunkStartEndChars.mjs";
5
+ import { chunkText } from "../utils/calculateChunks.mjs";
6
+ import { mkdirSync, writeFileSync } from "node:fs";
7
+ import { dirname, relative } from "node:path";
8
+ import { formatLocale, formatPath } from "@intlayer/chokidar/utils";
9
+ import * as ANSIColors from "@intlayer/config/colors";
10
+ import { colon, colorize, colorizeNumber, getAppLogger } from "@intlayer/config/logger";
11
+ import { retryManager } from "@intlayer/config/utils";
12
+ import { readFile } from "node:fs/promises";
13
+ import { performance } from "node:perf_hooks";
14
+
15
+ //#region src/translateDoc/translateFile.ts
16
+ const translateFile = async ({ baseFilePath, outputFilePath, locale, baseLocale, configuration, errorState, aiOptions, customInstructions, aiClient, aiConfig, flushStrategy = "incremental", onChunkReceive, limit }) => {
17
+ if (errorState.shouldStop) return null;
18
+ const appLogger = getAppLogger(configuration, { config: { prefix: "" } });
19
+ const fileStartTime = performance.now();
20
+ try {
21
+ const chunks = chunkText(await readFile(baseFilePath, "utf-8"));
22
+ const totalChunks = chunks.length;
23
+ const filePrefix = `${colon(`${ANSIColors.GREY_DARK}[${formatPath(baseFilePath)}${ANSIColors.GREY_DARK}] `, { colSize: 40 })}${ANSIColors.RESET}`;
24
+ const prefix = `${colon(`${ANSIColors.GREY_DARK}[${formatPath(baseFilePath)}${ANSIColors.GREY_DARK}][${formatLocale(locale)}${ANSIColors.GREY_DARK}] `, { colSize: 40 })}${ANSIColors.RESET}`;
25
+ appLogger(`${filePrefix}Split into ${colorizeNumber(totalChunks)} chunks. Queuing...`);
26
+ const basePrompt = readAsset("./prompts/TRANSLATE_PROMPT.md", "utf-8").replaceAll("{{localeName}}", `${formatLocale(locale, false)}`).replaceAll("{{baseLocaleName}}", `${formatLocale(baseLocale, false)}`).replace("{{applicationContext}}", aiOptions?.applicationContext ?? "-").replace("{{customInstructions}}", customInstructions ?? "-");
27
+ const translatedParts = new Array(totalChunks).fill("");
28
+ const runTask = limit ?? ((fn) => fn());
29
+ const tasks = chunks.map((chunk, i) => runTask(async () => {
30
+ if (errorState.shouldStop) return null;
31
+ const chunkLogger = getAppLogger(configuration, { config: { prefix: `${prefix} ${ANSIColors.GREY_DARK}[${i + 1}/${totalChunks}] ${ANSIColors.RESET}` } });
32
+ const chunkStartTime = performance.now();
33
+ const isFirstChunk = i === 0;
34
+ const fileToTranslateCurrentChunk = chunk.content;
35
+ const getPrevChunkPrompt = () => `>>> CONTEXT: PREVIOUS SOURCE CONTENT <<<\n\`\`\`\n` + (chunks[i - 1]?.content ?? "") + `\n\`\`\`\n>>> END PREVIOUS CONTEXT <<<`;
36
+ const getBaseChunkContextPrompt = () => `>>> CONTEXT: NEXT CONTENT <<<\n\`\`\`\n` + (chunks[i + 1]?.content ?? "") + `\n\`\`\`\n>>> END NEXT CONTEXT <<<`;
37
+ chunkLogger("Process started");
38
+ const { content: translatedChunk, tokens } = await retryManager(async () => {
39
+ const result = await chunkInference([
40
+ {
41
+ role: "system",
42
+ content: basePrompt
43
+ },
44
+ ...chunks[i + 1] ? [{
45
+ role: "system",
46
+ content: getBaseChunkContextPrompt()
47
+ }] : [],
48
+ ...isFirstChunk ? [] : [{
49
+ role: "system",
50
+ content: getPrevChunkPrompt()
51
+ }],
52
+ {
53
+ role: "system",
54
+ content: [`You are translating TARGET CHUNK (${i + 1}/${totalChunks}).`, `Translate ONLY the target chunk. Preserve frontmatter/code exactly.`].join("\n")
55
+ },
56
+ {
57
+ role: "user",
58
+ content: `>>> TARGET CHUNK START <<<\n${fileToTranslateCurrentChunk}\n>>> TARGET CHUNK END <<<`
59
+ }
60
+ ], aiOptions, configuration, aiClient, aiConfig);
61
+ let processedChunk = sanitizeChunk(result?.fileContent, fileToTranslateCurrentChunk);
62
+ processedChunk = fixChunkStartEndChars(processedChunk, fileToTranslateCurrentChunk);
63
+ if (!validateTranslation(fileToTranslateCurrentChunk, processedChunk, chunkLogger)) throw new Error(`Validation failed for chunk ${i + 1}/${totalChunks}`);
64
+ return {
65
+ content: processedChunk,
66
+ tokens: result.tokenUsed
67
+ };
68
+ })();
69
+ const chunkDuration = (performance.now() - chunkStartTime).toFixed(0);
70
+ translatedParts[i] = translatedChunk;
71
+ if (onChunkReceive) onChunkReceive(translatedChunk, i, totalChunks);
72
+ if (flushStrategy === "incremental") {
73
+ if (translatedParts.slice(0, i + 1).every((p) => p && p !== "")) {
74
+ let endIdx = 0;
75
+ while (endIdx < totalChunks && translatedParts[endIdx] && translatedParts[endIdx] !== "") endIdx++;
76
+ const currentContent = translatedParts.slice(0, endIdx).join("");
77
+ mkdirSync(dirname(outputFilePath), { recursive: true });
78
+ writeFileSync(outputFilePath, currentContent);
79
+ }
80
+ }
81
+ chunkLogger([`${colorizeNumber(tokens)} tokens used `, `${ANSIColors.GREY_DARK}in ${colorizeNumber(chunkDuration)}ms${ANSIColors.RESET}`].join(""));
82
+ }));
83
+ await Promise.all(tasks);
84
+ const fullContent = translatedParts.join("");
85
+ if (flushStrategy === "end" || flushStrategy === "incremental") {
86
+ mkdirSync(dirname(outputFilePath), { recursive: true });
87
+ writeFileSync(outputFilePath, fullContent);
88
+ }
89
+ const totalDuration = ((performance.now() - fileStartTime) / 1e3).toFixed(2);
90
+ const relativePath = relative(configuration.system.baseDir, outputFilePath);
91
+ appLogger(`${colorize("✔", ANSIColors.GREEN)} File ${formatPath(relativePath)} completed in ${colorizeNumber(totalDuration)}s.`);
92
+ return fullContent;
93
+ } catch (error) {
94
+ errorState.count++;
95
+ const errorMessage = error?.message ?? JSON.stringify(error);
96
+ appLogger(`${colorize("✖", ANSIColors.RED)} Error: ${errorMessage}`);
97
+ if (errorState.count >= errorState.maxErrors) errorState.shouldStop = true;
98
+ return null;
99
+ }
100
+ };
101
+
102
+ //#endregion
103
+ export { translateFile };
3
104
  //# sourceMappingURL=translateFile.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"translateFile.mjs","names":[],"sources":["../../../src/translateDoc/translateFile.ts"],"sourcesContent":["import { mkdirSync, writeFileSync } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport { dirname, relative } from 'node:path';\nimport { performance } from 'node:perf_hooks';\nimport { readAsset } from 'utils:asset';\nimport { formatLocale, formatPath } from '@intlayer/chokidar/utils';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport {\n colon,\n colorize,\n colorizeNumber,\n getAppLogger,\n} from '@intlayer/config/logger';\nimport { retryManager } from '@intlayer/config/utils';\nimport { chunkText } from '../utils/calculateChunks';\nimport { chunkInference } from '../utils/chunkInference';\nimport { fixChunkStartEndChars } from '../utils/fixChunkStartEndChars';\nimport type { TranslateFileOptions } from './types';\nimport { sanitizeChunk, validateTranslation } from './validation';\n\nexport const translateFile = async ({\n baseFilePath,\n outputFilePath,\n locale,\n baseLocale,\n configuration,\n errorState,\n aiOptions,\n customInstructions,\n aiClient,\n aiConfig,\n flushStrategy = 'incremental',\n onChunkReceive,\n limit, // The Global Limiter\n}: TranslateFileOptions): Promise<string | null> => {\n if (errorState.shouldStop) return null;\n\n const appLogger = getAppLogger(configuration, { config: { prefix: '' } });\n const fileStartTime = performance.now();\n\n try {\n const fileContent = await readFile(baseFilePath, 'utf-8');\n const chunks = chunkText(fileContent);\n const totalChunks = chunks.length;\n\n const filePrefixText = `${ANSIColors.GREY_DARK}[${formatPath(baseFilePath)}${ANSIColors.GREY_DARK}] `;\n const filePrefix = `${colon(filePrefixText, { colSize: 40 })}${ANSIColors.RESET}`;\n const prefixText = `${ANSIColors.GREY_DARK}[${formatPath(baseFilePath)}${ANSIColors.GREY_DARK}][${formatLocale(locale)}${ANSIColors.GREY_DARK}] `;\n const prefix = `${colon(prefixText, { colSize: 40 })}${ANSIColors.RESET}`;\n\n appLogger(\n `${filePrefix}Split into ${colorizeNumber(totalChunks)} chunks. Queuing...`\n );\n\n const basePrompt = readAsset('./prompts/TRANSLATE_PROMPT.md', 'utf-8')\n .replaceAll('{{localeName}}', `${formatLocale(locale, false)}`)\n .replaceAll('{{baseLocaleName}}', `${formatLocale(baseLocale, false)}`)\n .replace('{{applicationContext}}', aiOptions?.applicationContext ?? '-')\n .replace('{{customInstructions}}', customInstructions ?? '-');\n\n const translatedParts: string[] = new Array(totalChunks).fill('');\n\n // Fallback if no limiter is provided (runs immediately)\n const runTask = limit ?? ((fn) => fn());\n\n // MAP CHUNKS TO GLOBAL TASKS\n // This pushes ALL chunks for this file into the Global Queue immediately.\n // They will execute whenever the global concurrency slots open up.\n const tasks = chunks.map((chunk, i) =>\n runTask(async () => {\n if (errorState.shouldStop) return null;\n\n const chunkLogger = getAppLogger(configuration, {\n config: {\n prefix: `${prefix} ${ANSIColors.GREY_DARK}[${i + 1}/${totalChunks}] ${ANSIColors.RESET}`,\n },\n });\n\n const chunkStartTime = performance.now();\n const isFirstChunk = i === 0;\n const fileToTranslateCurrentChunk = chunk.content;\n\n // Context Preparation\n const getPrevChunkPrompt = () =>\n `>>> CONTEXT: PREVIOUS SOURCE CONTENT <<<\\n\\`\\`\\`\\n` +\n (chunks[i - 1]?.content ?? '') +\n `\\n\\`\\`\\`\\n>>> END PREVIOUS CONTEXT <<<`;\n\n const getBaseChunkContextPrompt = () =>\n `>>> CONTEXT: NEXT CONTENT <<<\\n\\`\\`\\`\\n` +\n (chunks[i + 1]?.content ?? '') +\n `\\n\\`\\`\\`\\n>>> END NEXT CONTEXT <<<`;\n\n chunkLogger('Process started');\n\n const chunkTranslation = retryManager(async () => {\n const result = await chunkInference(\n [\n { role: 'system', content: basePrompt },\n ...(chunks[i + 1]\n ? [\n {\n role: 'system',\n content: getBaseChunkContextPrompt(),\n } as const,\n ]\n : []),\n ...(isFirstChunk\n ? []\n : [{ role: 'system', content: getPrevChunkPrompt() } as const]),\n {\n role: 'system',\n content: [\n `You are translating TARGET CHUNK (${i + 1}/${totalChunks}).`,\n `Translate ONLY the target chunk. Preserve frontmatter/code exactly.`,\n ].join('\\n'),\n },\n {\n role: 'user',\n content: `>>> TARGET CHUNK START <<<\\n${fileToTranslateCurrentChunk}\\n>>> TARGET CHUNK END <<<`,\n },\n ],\n aiOptions,\n configuration,\n aiClient,\n aiConfig\n );\n\n let processedChunk = sanitizeChunk(\n result?.fileContent,\n fileToTranslateCurrentChunk\n );\n processedChunk = fixChunkStartEndChars(\n processedChunk,\n fileToTranslateCurrentChunk\n );\n\n const isValid = validateTranslation(\n fileToTranslateCurrentChunk,\n processedChunk,\n chunkLogger\n );\n\n if (!isValid) {\n // Throwing an error here signals retryManager to try again\n throw new Error(\n `Validation failed for chunk ${i + 1}/${totalChunks}`\n );\n }\n\n return { content: processedChunk, tokens: result.tokenUsed };\n });\n\n const { content: translatedChunk, tokens } = await chunkTranslation();\n const chunkEndTime = performance.now();\n const chunkDuration = (chunkEndTime - chunkStartTime).toFixed(0);\n\n // Store Result\n translatedParts[i] = translatedChunk;\n\n if (onChunkReceive) {\n onChunkReceive(translatedChunk, i, totalChunks);\n }\n\n // Incremental Flush Strategy\n if (flushStrategy === 'incremental') {\n const isContiguous = translatedParts\n .slice(0, i + 1)\n .every((p) => p && p !== '');\n\n if (isContiguous) {\n let endIdx = 0;\n while (\n endIdx < totalChunks &&\n translatedParts[endIdx] &&\n translatedParts[endIdx] !== ''\n ) {\n endIdx++;\n }\n const currentContent = translatedParts.slice(0, endIdx).join('');\n // Write asynchronously/sync is fine here as node handles file locks reasonably well for single process\n mkdirSync(dirname(outputFilePath), { recursive: true });\n writeFileSync(outputFilePath, currentContent);\n }\n }\n\n chunkLogger(\n [\n `${colorizeNumber(tokens)} tokens used `,\n `${ANSIColors.GREY_DARK}in ${colorizeNumber(chunkDuration)}ms${ANSIColors.RESET}`,\n ].join('')\n );\n })\n );\n\n // Wait for all chunks for this specific file/locale to finish\n await Promise.all(tasks);\n\n // Final Flush\n const fullContent = translatedParts.join('');\n if (flushStrategy === 'end' || flushStrategy === 'incremental') {\n mkdirSync(dirname(outputFilePath), { recursive: true });\n writeFileSync(outputFilePath, fullContent);\n }\n\n const fileEndTime = performance.now();\n const totalDuration = ((fileEndTime - fileStartTime) / 1000).toFixed(2);\n const relativePath = relative(configuration.system.baseDir, outputFilePath);\n\n appLogger(\n `${colorize('✔', ANSIColors.GREEN)} File ${formatPath(relativePath)} completed in ${colorizeNumber(totalDuration)}s.`\n );\n\n return fullContent;\n } catch (error: any) {\n errorState.count++;\n const errorMessage = error?.message ?? JSON.stringify(error);\n appLogger(`${colorize('✖', ANSIColors.RED)} Error: ${errorMessage}`);\n if (errorState.count >= errorState.maxErrors) errorState.shouldStop = true;\n return null;\n }\n};\n"],"mappings":"2wBAoBA,MAAa,EAAgB,MAAO,CAClC,eACA,iBACA,SACA,aACA,gBACA,aACA,YACA,qBACA,WACA,WACA,gBAAgB,cAChB,iBACA,WACkD,CAClD,GAAI,EAAW,WAAY,OAAO,KAElC,IAAM,EAAY,EAAa,EAAe,CAAE,OAAQ,CAAE,OAAQ,GAAI,CAAE,CAAC,CACnE,EAAgB,EAAY,KAAK,CAEvC,GAAI,CAEF,IAAM,EAAS,EADK,MAAM,EAAS,EAAc,QAAQ,CACpB,CAC/B,EAAc,EAAO,OAGrB,EAAa,GAAG,EADC,GAAG,EAAW,UAAU,GAAG,EAAW,EAAa,GAAG,EAAW,UAAU,IACtD,CAA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,QAAS,EAAe,CAM3E,OAJA,EACE,GAAG,EAAS,IAAK,EAAW,MAAM,CAAC,QAAQ,EAAW,EAAa,CAAC,gBAAgB,EAAe,EAAc,CAAC,IACnH,CAEM,QACA,EAAY,CACnB,EAAW,QACX,IAAM,EAAe,GAAO,SAAW,KAAK,UAAU,EAAM,CAG5D,OAFA,EAAU,GAAG,EAAS,IAAK,EAAW,IAAI,CAAC,UAAU,IAAe,CAChE,EAAW,OAAS,EAAW,YAAW,EAAW,WAAa,IAC/D"}
1
+ {"version":3,"file":"translateFile.mjs","names":[],"sources":["../../../src/translateDoc/translateFile.ts"],"sourcesContent":["import { mkdirSync, writeFileSync } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport { dirname, relative } from 'node:path';\nimport { performance } from 'node:perf_hooks';\nimport { readAsset } from 'utils:asset';\nimport { formatLocale, formatPath } from '@intlayer/chokidar/utils';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport {\n colon,\n colorize,\n colorizeNumber,\n getAppLogger,\n} from '@intlayer/config/logger';\nimport { retryManager } from '@intlayer/config/utils';\nimport { chunkText } from '../utils/calculateChunks';\nimport { chunkInference } from '../utils/chunkInference';\nimport { fixChunkStartEndChars } from '../utils/fixChunkStartEndChars';\nimport type { TranslateFileOptions } from './types';\nimport { sanitizeChunk, validateTranslation } from './validation';\n\nexport const translateFile = async ({\n baseFilePath,\n outputFilePath,\n locale,\n baseLocale,\n configuration,\n errorState,\n aiOptions,\n customInstructions,\n aiClient,\n aiConfig,\n flushStrategy = 'incremental',\n onChunkReceive,\n limit, // The Global Limiter\n}: TranslateFileOptions): Promise<string | null> => {\n if (errorState.shouldStop) return null;\n\n const appLogger = getAppLogger(configuration, { config: { prefix: '' } });\n const fileStartTime = performance.now();\n\n try {\n const fileContent = await readFile(baseFilePath, 'utf-8');\n const chunks = chunkText(fileContent);\n const totalChunks = chunks.length;\n\n const filePrefixText = `${ANSIColors.GREY_DARK}[${formatPath(baseFilePath)}${ANSIColors.GREY_DARK}] `;\n const filePrefix = `${colon(filePrefixText, { colSize: 40 })}${ANSIColors.RESET}`;\n const prefixText = `${ANSIColors.GREY_DARK}[${formatPath(baseFilePath)}${ANSIColors.GREY_DARK}][${formatLocale(locale)}${ANSIColors.GREY_DARK}] `;\n const prefix = `${colon(prefixText, { colSize: 40 })}${ANSIColors.RESET}`;\n\n appLogger(\n `${filePrefix}Split into ${colorizeNumber(totalChunks)} chunks. Queuing...`\n );\n\n const basePrompt = readAsset('./prompts/TRANSLATE_PROMPT.md', 'utf-8')\n .replaceAll('{{localeName}}', `${formatLocale(locale, false)}`)\n .replaceAll('{{baseLocaleName}}', `${formatLocale(baseLocale, false)}`)\n .replace('{{applicationContext}}', aiOptions?.applicationContext ?? '-')\n .replace('{{customInstructions}}', customInstructions ?? '-');\n\n const translatedParts: string[] = new Array(totalChunks).fill('');\n\n // Fallback if no limiter is provided (runs immediately)\n const runTask = limit ?? ((fn) => fn());\n\n // MAP CHUNKS TO GLOBAL TASKS\n // This pushes ALL chunks for this file into the Global Queue immediately.\n // They will execute whenever the global concurrency slots open up.\n const tasks = chunks.map((chunk, i) =>\n runTask(async () => {\n if (errorState.shouldStop) return null;\n\n const chunkLogger = getAppLogger(configuration, {\n config: {\n prefix: `${prefix} ${ANSIColors.GREY_DARK}[${i + 1}/${totalChunks}] ${ANSIColors.RESET}`,\n },\n });\n\n const chunkStartTime = performance.now();\n const isFirstChunk = i === 0;\n const fileToTranslateCurrentChunk = chunk.content;\n\n // Context Preparation\n const getPrevChunkPrompt = () =>\n `>>> CONTEXT: PREVIOUS SOURCE CONTENT <<<\\n\\`\\`\\`\\n` +\n (chunks[i - 1]?.content ?? '') +\n `\\n\\`\\`\\`\\n>>> END PREVIOUS CONTEXT <<<`;\n\n const getBaseChunkContextPrompt = () =>\n `>>> CONTEXT: NEXT CONTENT <<<\\n\\`\\`\\`\\n` +\n (chunks[i + 1]?.content ?? '') +\n `\\n\\`\\`\\`\\n>>> END NEXT CONTEXT <<<`;\n\n chunkLogger('Process started');\n\n const chunkTranslation = retryManager(async () => {\n const result = await chunkInference(\n [\n { role: 'system', content: basePrompt },\n ...(chunks[i + 1]\n ? [\n {\n role: 'system',\n content: getBaseChunkContextPrompt(),\n } as const,\n ]\n : []),\n ...(isFirstChunk\n ? []\n : [{ role: 'system', content: getPrevChunkPrompt() } as const]),\n {\n role: 'system',\n content: [\n `You are translating TARGET CHUNK (${i + 1}/${totalChunks}).`,\n `Translate ONLY the target chunk. Preserve frontmatter/code exactly.`,\n ].join('\\n'),\n },\n {\n role: 'user',\n content: `>>> TARGET CHUNK START <<<\\n${fileToTranslateCurrentChunk}\\n>>> TARGET CHUNK END <<<`,\n },\n ],\n aiOptions,\n configuration,\n aiClient,\n aiConfig\n );\n\n let processedChunk = sanitizeChunk(\n result?.fileContent,\n fileToTranslateCurrentChunk\n );\n processedChunk = fixChunkStartEndChars(\n processedChunk,\n fileToTranslateCurrentChunk\n );\n\n const isValid = validateTranslation(\n fileToTranslateCurrentChunk,\n processedChunk,\n chunkLogger\n );\n\n if (!isValid) {\n // Throwing an error here signals retryManager to try again\n throw new Error(\n `Validation failed for chunk ${i + 1}/${totalChunks}`\n );\n }\n\n return { content: processedChunk, tokens: result.tokenUsed };\n });\n\n const { content: translatedChunk, tokens } = await chunkTranslation();\n const chunkEndTime = performance.now();\n const chunkDuration = (chunkEndTime - chunkStartTime).toFixed(0);\n\n // Store Result\n translatedParts[i] = translatedChunk;\n\n if (onChunkReceive) {\n onChunkReceive(translatedChunk, i, totalChunks);\n }\n\n // Incremental Flush Strategy\n if (flushStrategy === 'incremental') {\n const isContiguous = translatedParts\n .slice(0, i + 1)\n .every((p) => p && p !== '');\n\n if (isContiguous) {\n let endIdx = 0;\n while (\n endIdx < totalChunks &&\n translatedParts[endIdx] &&\n translatedParts[endIdx] !== ''\n ) {\n endIdx++;\n }\n const currentContent = translatedParts.slice(0, endIdx).join('');\n // Write asynchronously/sync is fine here as node handles file locks reasonably well for single process\n mkdirSync(dirname(outputFilePath), { recursive: true });\n writeFileSync(outputFilePath, currentContent);\n }\n }\n\n chunkLogger(\n [\n `${colorizeNumber(tokens)} tokens used `,\n `${ANSIColors.GREY_DARK}in ${colorizeNumber(chunkDuration)}ms${ANSIColors.RESET}`,\n ].join('')\n );\n })\n );\n\n // Wait for all chunks for this specific file/locale to finish\n await Promise.all(tasks);\n\n // Final Flush\n const fullContent = translatedParts.join('');\n if (flushStrategy === 'end' || flushStrategy === 'incremental') {\n mkdirSync(dirname(outputFilePath), { recursive: true });\n writeFileSync(outputFilePath, fullContent);\n }\n\n const fileEndTime = performance.now();\n const totalDuration = ((fileEndTime - fileStartTime) / 1000).toFixed(2);\n const relativePath = relative(configuration.system.baseDir, outputFilePath);\n\n appLogger(\n `${colorize('✔', ANSIColors.GREEN)} File ${formatPath(relativePath)} completed in ${colorizeNumber(totalDuration)}s.`\n );\n\n return fullContent;\n } catch (error: any) {\n errorState.count++;\n const errorMessage = error?.message ?? JSON.stringify(error);\n appLogger(`${colorize('✖', ANSIColors.RED)} Error: ${errorMessage}`);\n if (errorState.count >= errorState.maxErrors) errorState.shouldStop = true;\n return null;\n }\n};\n"],"mappings":";;;;;;;;;;;;;;;AAoBA,MAAa,gBAAgB,OAAO,EAClC,cACA,gBACA,QACA,YACA,eACA,YACA,WACA,oBACA,UACA,UACA,gBAAgB,eAChB,gBACA,YACkD;AAClD,KAAI,WAAW,WAAY,QAAO;CAElC,MAAM,YAAY,aAAa,eAAe,EAAE,QAAQ,EAAE,QAAQ,IAAI,EAAE,CAAC;CACzE,MAAM,gBAAgB,YAAY,KAAK;AAEvC,KAAI;EAEF,MAAM,SAAS,UADK,MAAM,SAAS,cAAc,QAAQ,CACpB;EACrC,MAAM,cAAc,OAAO;EAG3B,MAAM,aAAa,GAAG,MADC,GAAG,WAAW,UAAU,GAAG,WAAW,aAAa,GAAG,WAAW,UAAU,KACtD,EAAE,SAAS,IAAI,CAAC,GAAG,WAAW;EAE1E,MAAM,SAAS,GAAG,MADC,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C,MAAM,kBADc,YAAY,KAAK,GACC,iBAAiB,KAAM,QAAQ,EAAE;EACvE,MAAM,eAAe,SAAS,cAAc,OAAO,SAAS,eAAe;AAE3E,YACE,GAAG,SAAS,KAAK,WAAW,MAAM,CAAC,QAAQ,WAAW,aAAa,CAAC,gBAAgB,eAAe,cAAc,CAAC,IACnH;AAED,SAAO;UACA,OAAY;AACnB,aAAW;EACX,MAAM,eAAe,OAAO,WAAW,KAAK,UAAU,MAAM;AAC5D,YAAU,GAAG,SAAS,KAAK,WAAW,IAAI,CAAC,UAAU,eAAe;AACpE,MAAI,WAAW,SAAS,WAAW,UAAW,YAAW,aAAa;AACtE,SAAO"}
@@ -1,6 +1,47 @@
1
- const e=(e,t,n)=>{let r=[];if(e.trimStart().startsWith(`---`)){t.trimStart().startsWith(`---`)||r.push(`YAML Frontmatter missing: Input starts with "---", output does not.`);let n=(e.match(/^---$/gm)||[]).length,i=(t.match(/^---$/gm)||[]).length;n>=2&&i<2&&r.push(`YAML Frontmatter unclosed: Input has closing "---", output is missing it.`)}let i=/^\s*```/gm,a=(e.match(i)||[]).length,o=(t.match(i)||[]).length;a!==o&&r.push(`Code fence mismatch: Input has ${a}, output has ${o}`);let s=t.length/(e.length||1),c=s>2.5,l=e.length>50;c&&l&&r.push(`Length deviation: Output is ${t.length} chars vs Input ${e.length} (${s.toFixed(1)}x). Likely included context.`);let u=e.split(`
2
- `).length,d=t.split(`
3
- `).length;return u>5&&d<u*.4&&r.push(`Line count deviation: Output has ${d} lines, Input has ${u}. Likely content deletion.`),r.length>0?(n(`Validation Failed: ${r.join(`, `)}`),!1):!0},t=(e,t)=>{let n=e,r=n.match(/^```(?:markdown|md|txt)?\n([\s\S]*?)\n```$/i);return r&&(n=r[1]),!t.startsWith(`
4
- `)&&n.startsWith(`
5
- `)&&(n=n.replace(/^\n+/,``)),!t.startsWith(` `)&&n.startsWith(` `)&&(n=n.trimStart()),n};export{t as sanitizeChunk,e as validateTranslation};
1
+ //#region src/translateDoc/validation.ts
2
+ /**
3
+ * Validates that the translated content matches the structure of the original.
4
+ * Throws an error if a mismatch is found, triggering a retry.
5
+ */
6
+ const validateTranslation = (original, translated, logger) => {
7
+ const errors = [];
8
+ if (original.trimStart().startsWith("---")) {
9
+ if (!translated.trimStart().startsWith("---")) errors.push("YAML Frontmatter missing: Input starts with \"---\", output does not.");
10
+ const originalDashes = (original.match(/^---$/gm) || []).length;
11
+ const translatedDashes = (translated.match(/^---$/gm) || []).length;
12
+ if (originalDashes >= 2 && translatedDashes < 2) errors.push("YAML Frontmatter unclosed: Input has closing \"---\", output is missing it.");
13
+ }
14
+ const fenceRegex = /^\s*```/gm;
15
+ const originalFences = (original.match(fenceRegex) || []).length;
16
+ const translatedFences = (translated.match(fenceRegex) || []).length;
17
+ if (originalFences !== translatedFences) errors.push(`Code fence mismatch: Input has ${originalFences}, output has ${translatedFences}`);
18
+ const ratio = translated.length / (original.length || 1);
19
+ const isTooLong = ratio > 2.5;
20
+ const isSignificantLength = original.length > 50;
21
+ if (isTooLong && isSignificantLength) errors.push(`Length deviation: Output is ${translated.length} chars vs Input ${original.length} (${ratio.toFixed(1)}x). Likely included context.`);
22
+ const originalLines = original.split("\n").length;
23
+ const translatedLines = translated.split("\n").length;
24
+ if (originalLines > 5) {
25
+ if (translatedLines < originalLines * .4) errors.push(`Line count deviation: Output has ${translatedLines} lines, Input has ${originalLines}. Likely content deletion.`);
26
+ }
27
+ if (errors.length > 0) {
28
+ logger(`Validation Failed: ${errors.join(", ")}`);
29
+ return false;
30
+ }
31
+ return true;
32
+ };
33
+ /**
34
+ * Clean common AI artifacts
35
+ */
36
+ const sanitizeChunk = (translated, original) => {
37
+ let cleaned = translated;
38
+ const match = cleaned.match(/^```(?:markdown|md|txt)?\n([\s\S]*?)\n```$/i);
39
+ if (match) cleaned = match[1];
40
+ if (!original.startsWith("\n") && cleaned.startsWith("\n")) cleaned = cleaned.replace(/^\n+/, "");
41
+ if (!original.startsWith(" ") && cleaned.startsWith(" ")) cleaned = cleaned.trimStart();
42
+ return cleaned;
43
+ };
44
+
45
+ //#endregion
46
+ export { sanitizeChunk, validateTranslation };
6
47
  //# sourceMappingURL=validation.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"validation.mjs","names":[],"sources":["../../../src/translateDoc/validation.ts"],"sourcesContent":["import type { Logger } from '@intlayer/config/logger';\n\n/**\n * Validates that the translated content matches the structure of the original.\n * Throws an error if a mismatch is found, triggering a retry.\n */\nexport const validateTranslation = (\n original: string,\n translated: string,\n logger: Logger\n): boolean => {\n const errors: string[] = [];\n\n // YAML Frontmatter Integrity (CRITICAL)\n if (original.trimStart().startsWith('---')) {\n if (!translated.trimStart().startsWith('---')) {\n errors.push(\n 'YAML Frontmatter missing: Input starts with \"---\", output does not.'\n );\n }\n const originalDashes = (original.match(/^---$/gm) || []).length;\n const translatedDashes = (translated.match(/^---$/gm) || []).length;\n if (originalDashes >= 2 && translatedDashes < 2) {\n errors.push(\n 'YAML Frontmatter unclosed: Input has closing \"---\", output is missing it.'\n );\n }\n }\n\n // Code Fence Check\n const fenceRegex = /^\\s*```/gm;\n const originalFences = (original.match(fenceRegex) || []).length;\n const translatedFences = (translated.match(fenceRegex) || []).length;\n\n if (originalFences !== translatedFences) {\n errors.push(\n `Code fence mismatch: Input has ${originalFences}, output has ${translatedFences}`\n );\n }\n\n // Length/Duplication Check\n const ratio = translated.length / (original.length || 1);\n const isTooLong = ratio > 2.5;\n const isSignificantLength = original.length > 50;\n\n if (isTooLong && isSignificantLength) {\n errors.push(\n `Length deviation: Output is ${translated.length} chars vs Input ${original.length} (${ratio.toFixed(1)}x). Likely included context.`\n );\n }\n\n // Line Count Heuristic\n const originalLines = original.split('\\n').length;\n const translatedLines = translated.split('\\n').length;\n\n if (originalLines > 5) {\n if (translatedLines < originalLines * 0.4) {\n errors.push(\n `Line count deviation: Output has ${translatedLines} lines, Input has ${originalLines}. Likely content deletion.`\n );\n }\n }\n\n if (errors.length > 0) {\n logger(`Validation Failed: ${errors.join(', ')}`);\n return false;\n }\n\n return true;\n};\n\n/**\n * Clean common AI artifacts\n */\nexport const sanitizeChunk = (translated: string, original: string): string => {\n let cleaned = translated;\n const wrapRegex = /^```(?:markdown|md|txt)?\\n([\\s\\S]*?)\\n```$/i;\n const match = cleaned.match(wrapRegex);\n if (match) cleaned = match[1];\n\n if (!original.startsWith('\\n') && cleaned.startsWith('\\n')) {\n cleaned = cleaned.replace(/^\\n+/, '');\n }\n if (!original.startsWith(' ') && cleaned.startsWith(' ')) {\n cleaned = cleaned.trimStart();\n }\n return cleaned;\n};\n"],"mappings":"AAMA,MAAa,GACX,EACA,EACA,IACY,CACZ,IAAM,EAAmB,EAAE,CAG3B,GAAI,EAAS,WAAW,CAAC,WAAW,MAAM,CAAE,CACrC,EAAW,WAAW,CAAC,WAAW,MAAM,EAC3C,EAAO,KACL,sEACD,CAEH,IAAM,GAAkB,EAAS,MAAM,UAAU,EAAI,EAAE,EAAE,OACnD,GAAoB,EAAW,MAAM,UAAU,EAAI,EAAE,EAAE,OACzD,GAAkB,GAAK,EAAmB,GAC5C,EAAO,KACL,4EACD,CAKL,IAAM,EAAa,YACb,GAAkB,EAAS,MAAM,EAAW,EAAI,EAAE,EAAE,OACpD,GAAoB,EAAW,MAAM,EAAW,EAAI,EAAE,EAAE,OAE1D,IAAmB,GACrB,EAAO,KACL,kCAAkC,EAAe,eAAe,IACjE,CAIH,IAAM,EAAQ,EAAW,QAAU,EAAS,QAAU,GAChD,EAAY,EAAQ,IACpB,EAAsB,EAAS,OAAS,GAE1C,GAAa,GACf,EAAO,KACL,+BAA+B,EAAW,OAAO,kBAAkB,EAAS,OAAO,IAAI,EAAM,QAAQ,EAAE,CAAC,8BACzG,CAIH,IAAM,EAAgB,EAAS,MAAM;EAAK,CAAC,OACrC,EAAkB,EAAW,MAAM;EAAK,CAAC,OAe/C,OAbI,EAAgB,GACd,EAAkB,EAAgB,IACpC,EAAO,KACL,oCAAoC,EAAgB,oBAAoB,EAAc,4BACvF,CAID,EAAO,OAAS,GAClB,EAAO,sBAAsB,EAAO,KAAK,KAAK,GAAG,CAC1C,IAGF,IAMI,GAAiB,EAAoB,IAA6B,CAC7E,IAAI,EAAU,EAER,EAAQ,EAAQ,MADJ,8CACoB,CAStC,OARI,IAAO,EAAU,EAAM,IAEvB,CAAC,EAAS,WAAW;EAAK,EAAI,EAAQ,WAAW;EAAK,GACxD,EAAU,EAAQ,QAAQ,OAAQ,GAAG,EAEnC,CAAC,EAAS,WAAW,IAAI,EAAI,EAAQ,WAAW,IAAI,GACtD,EAAU,EAAQ,WAAW,EAExB"}
1
+ {"version":3,"file":"validation.mjs","names":[],"sources":["../../../src/translateDoc/validation.ts"],"sourcesContent":["import type { Logger } from '@intlayer/config/logger';\n\n/**\n * Validates that the translated content matches the structure of the original.\n * Throws an error if a mismatch is found, triggering a retry.\n */\nexport const validateTranslation = (\n original: string,\n translated: string,\n logger: Logger\n): boolean => {\n const errors: string[] = [];\n\n // YAML Frontmatter Integrity (CRITICAL)\n if (original.trimStart().startsWith('---')) {\n if (!translated.trimStart().startsWith('---')) {\n errors.push(\n 'YAML Frontmatter missing: Input starts with \"---\", output does not.'\n );\n }\n const originalDashes = (original.match(/^---$/gm) || []).length;\n const translatedDashes = (translated.match(/^---$/gm) || []).length;\n if (originalDashes >= 2 && translatedDashes < 2) {\n errors.push(\n 'YAML Frontmatter unclosed: Input has closing \"---\", output is missing it.'\n );\n }\n }\n\n // Code Fence Check\n const fenceRegex = /^\\s*```/gm;\n const originalFences = (original.match(fenceRegex) || []).length;\n const translatedFences = (translated.match(fenceRegex) || []).length;\n\n if (originalFences !== translatedFences) {\n errors.push(\n `Code fence mismatch: Input has ${originalFences}, output has ${translatedFences}`\n );\n }\n\n // Length/Duplication Check\n const ratio = translated.length / (original.length || 1);\n const isTooLong = ratio > 2.5;\n const isSignificantLength = original.length > 50;\n\n if (isTooLong && isSignificantLength) {\n errors.push(\n `Length deviation: Output is ${translated.length} chars vs Input ${original.length} (${ratio.toFixed(1)}x). Likely included context.`\n );\n }\n\n // Line Count Heuristic\n const originalLines = original.split('\\n').length;\n const translatedLines = translated.split('\\n').length;\n\n if (originalLines > 5) {\n if (translatedLines < originalLines * 0.4) {\n errors.push(\n `Line count deviation: Output has ${translatedLines} lines, Input has ${originalLines}. Likely content deletion.`\n );\n }\n }\n\n if (errors.length > 0) {\n logger(`Validation Failed: ${errors.join(', ')}`);\n return false;\n }\n\n return true;\n};\n\n/**\n * Clean common AI artifacts\n */\nexport const sanitizeChunk = (translated: string, original: string): string => {\n let cleaned = translated;\n const wrapRegex = /^```(?:markdown|md|txt)?\\n([\\s\\S]*?)\\n```$/i;\n const match = cleaned.match(wrapRegex);\n if (match) cleaned = match[1];\n\n if (!original.startsWith('\\n') && cleaned.startsWith('\\n')) {\n cleaned = cleaned.replace(/^\\n+/, '');\n }\n if (!original.startsWith(' ') && cleaned.startsWith(' ')) {\n cleaned = cleaned.trimStart();\n }\n return cleaned;\n};\n"],"mappings":";;;;;AAMA,MAAa,uBACX,UACA,YACA,WACY;CACZ,MAAM,SAAmB,EAAE;AAG3B,KAAI,SAAS,WAAW,CAAC,WAAW,MAAM,EAAE;AAC1C,MAAI,CAAC,WAAW,WAAW,CAAC,WAAW,MAAM,CAC3C,QAAO,KACL,wEACD;EAEH,MAAM,kBAAkB,SAAS,MAAM,UAAU,IAAI,EAAE,EAAE;EACzD,MAAM,oBAAoB,WAAW,MAAM,UAAU,IAAI,EAAE,EAAE;AAC7D,MAAI,kBAAkB,KAAK,mBAAmB,EAC5C,QAAO,KACL,8EACD;;CAKL,MAAM,aAAa;CACnB,MAAM,kBAAkB,SAAS,MAAM,WAAW,IAAI,EAAE,EAAE;CAC1D,MAAM,oBAAoB,WAAW,MAAM,WAAW,IAAI,EAAE,EAAE;AAE9D,KAAI,mBAAmB,iBACrB,QAAO,KACL,kCAAkC,eAAe,eAAe,mBACjE;CAIH,MAAM,QAAQ,WAAW,UAAU,SAAS,UAAU;CACtD,MAAM,YAAY,QAAQ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