@intlayer/cli 8.1.2 → 8.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (310) hide show
  1. package/dist/cjs/IntlayerEventListener.cjs +1 -186
  2. package/dist/cjs/IntlayerEventListener.cjs.map +1 -1
  3. package/dist/cjs/_virtual/_rolldown/runtime.cjs +1 -29
  4. package/dist/cjs/_virtual/_utils_asset.cjs +2 -98
  5. package/dist/cjs/auth/login.cjs +2 -85
  6. package/dist/cjs/auth/login.cjs.map +1 -1
  7. package/dist/cjs/build.cjs +1 -27
  8. package/dist/cjs/build.cjs.map +1 -1
  9. package/dist/cjs/ci.cjs +1 -73
  10. package/dist/cjs/ci.cjs.map +1 -1
  11. package/dist/cjs/cli.cjs +1 -476
  12. package/dist/cjs/cli.cjs.map +1 -1
  13. package/dist/cjs/config.cjs +1 -12
  14. package/dist/cjs/config.cjs.map +1 -1
  15. package/dist/cjs/editor.cjs +1 -50
  16. package/dist/cjs/editor.cjs.map +1 -1
  17. package/dist/cjs/extract.cjs +1 -96
  18. package/dist/cjs/extract.cjs.map +1 -1
  19. package/dist/cjs/fill/deepMergeContent.cjs +1 -27
  20. package/dist/cjs/fill/deepMergeContent.cjs.map +1 -1
  21. package/dist/cjs/fill/fill.cjs +1 -78
  22. package/dist/cjs/fill/fill.cjs.map +1 -1
  23. package/dist/cjs/fill/formatAutoFilledFilePath.cjs +1 -29
  24. package/dist/cjs/fill/formatAutoFilledFilePath.cjs.map +1 -1
  25. package/dist/cjs/fill/formatFillData.cjs +1 -50
  26. package/dist/cjs/fill/formatFillData.cjs.map +1 -1
  27. package/dist/cjs/fill/getAvailableLocalesInDictionary.cjs +1 -26
  28. package/dist/cjs/fill/getAvailableLocalesInDictionary.cjs.map +1 -1
  29. package/dist/cjs/fill/getFilterMissingContentPerLocale.cjs +1 -50
  30. package/dist/cjs/fill/getFilterMissingContentPerLocale.cjs.map +1 -1
  31. package/dist/cjs/fill/index.cjs +1 -6
  32. package/dist/cjs/fill/listTranslationsTasks.cjs +1 -70
  33. package/dist/cjs/fill/listTranslationsTasks.cjs.map +1 -1
  34. package/dist/cjs/fill/mergeChunks.cjs +1 -28
  35. package/dist/cjs/fill/mergeChunks.cjs.map +1 -1
  36. package/dist/cjs/fill/translateDictionary.cjs +1 -205
  37. package/dist/cjs/fill/translateDictionary.cjs.map +1 -1
  38. package/dist/cjs/fill/writeFill.cjs +1 -54
  39. package/dist/cjs/fill/writeFill.cjs.map +1 -1
  40. package/dist/cjs/getTargetDictionary.cjs +1 -36
  41. package/dist/cjs/getTargetDictionary.cjs.map +1 -1
  42. package/dist/cjs/index.cjs +1 -39
  43. package/dist/cjs/init.cjs +1 -322
  44. package/dist/cjs/init.cjs.map +1 -1
  45. package/dist/cjs/initSkills.cjs +2 -0
  46. package/dist/cjs/initSkills.cjs.map +1 -0
  47. package/dist/cjs/listContentDeclaration.cjs +1 -41
  48. package/dist/cjs/listContentDeclaration.cjs.map +1 -1
  49. package/dist/cjs/listProjects.cjs +1 -28
  50. package/dist/cjs/listProjects.cjs.map +1 -1
  51. package/dist/cjs/liveSync.cjs +8 -151
  52. package/dist/cjs/liveSync.cjs.map +1 -1
  53. package/dist/cjs/pull.cjs +1 -146
  54. package/dist/cjs/pull.cjs.map +1 -1
  55. package/dist/cjs/push/pullLog.cjs +3 -102
  56. package/dist/cjs/push/pullLog.cjs.map +1 -1
  57. package/dist/cjs/push/push.cjs +1 -206
  58. package/dist/cjs/push/push.cjs.map +1 -1
  59. package/dist/cjs/pushConfig.cjs +1 -19
  60. package/dist/cjs/pushConfig.cjs.map +1 -1
  61. package/dist/cjs/pushLog.cjs +3 -84
  62. package/dist/cjs/pushLog.cjs.map +1 -1
  63. package/dist/cjs/reviewDoc/reviewDoc.cjs +1 -68
  64. package/dist/cjs/reviewDoc/reviewDoc.cjs.map +1 -1
  65. package/dist/cjs/reviewDoc/reviewDocBlockAware.cjs +1 -94
  66. package/dist/cjs/reviewDoc/reviewDocBlockAware.cjs.map +1 -1
  67. package/dist/cjs/searchDoc.cjs +1 -38
  68. package/dist/cjs/searchDoc.cjs.map +1 -1
  69. package/dist/cjs/test/index.cjs +1 -7
  70. package/dist/cjs/test/listMissingTranslations.cjs +1 -49
  71. package/dist/cjs/test/listMissingTranslations.cjs.map +1 -1
  72. package/dist/cjs/test/test.cjs +1 -53
  73. package/dist/cjs/test/test.cjs.map +1 -1
  74. package/dist/cjs/translateDoc/index.cjs +1 -9
  75. package/dist/cjs/translateDoc/translateDoc.cjs +1 -74
  76. package/dist/cjs/translateDoc/translateDoc.cjs.map +1 -1
  77. package/dist/cjs/translateDoc/translateFile.cjs +2 -103
  78. package/dist/cjs/translateDoc/translateFile.cjs.map +1 -1
  79. package/dist/cjs/translateDoc/validation.cjs +5 -49
  80. package/dist/cjs/translateDoc/validation.cjs.map +1 -1
  81. package/dist/cjs/translation-alignment/alignBlocks.cjs +1 -67
  82. package/dist/cjs/translation-alignment/alignBlocks.cjs.map +1 -1
  83. package/dist/cjs/translation-alignment/computeSimilarity.cjs +1 -25
  84. package/dist/cjs/translation-alignment/computeSimilarity.cjs.map +1 -1
  85. package/dist/cjs/translation-alignment/fingerprintBlock.cjs +1 -23
  86. package/dist/cjs/translation-alignment/fingerprintBlock.cjs.map +1 -1
  87. package/dist/cjs/translation-alignment/index.cjs +1 -22
  88. package/dist/cjs/translation-alignment/mapChangedLinesToBlocks.cjs +1 -18
  89. package/dist/cjs/translation-alignment/mapChangedLinesToBlocks.cjs.map +1 -1
  90. package/dist/cjs/translation-alignment/normalizeBlock.cjs +1 -22
  91. package/dist/cjs/translation-alignment/normalizeBlock.cjs.map +1 -1
  92. package/dist/cjs/translation-alignment/pipeline.cjs +1 -37
  93. package/dist/cjs/translation-alignment/pipeline.cjs.map +1 -1
  94. package/dist/cjs/translation-alignment/planActions.cjs +1 -46
  95. package/dist/cjs/translation-alignment/planActions.cjs.map +1 -1
  96. package/dist/cjs/translation-alignment/rebuildDocument.cjs +2 -49
  97. package/dist/cjs/translation-alignment/rebuildDocument.cjs.map +1 -1
  98. package/dist/cjs/translation-alignment/segmentDocument.cjs +5 -66
  99. package/dist/cjs/translation-alignment/segmentDocument.cjs.map +1 -1
  100. package/dist/cjs/utils/calculateChunks.cjs +2 -89
  101. package/dist/cjs/utils/calculateChunks.cjs.map +1 -1
  102. package/dist/cjs/utils/checkAccess.cjs +1 -81
  103. package/dist/cjs/utils/checkAccess.cjs.map +1 -1
  104. package/dist/cjs/utils/checkConfigConsistency.cjs +1 -16
  105. package/dist/cjs/utils/checkConfigConsistency.cjs.map +1 -1
  106. package/dist/cjs/utils/checkFileModifiedRange.cjs +1 -81
  107. package/dist/cjs/utils/checkFileModifiedRange.cjs.map +1 -1
  108. package/dist/cjs/utils/checkLastUpdateTime.cjs +1 -19
  109. package/dist/cjs/utils/checkLastUpdateTime.cjs.map +1 -1
  110. package/dist/cjs/utils/chunkInference.cjs +1 -45
  111. package/dist/cjs/utils/chunkInference.cjs.map +1 -1
  112. package/dist/cjs/utils/fixChunkStartEndChars.cjs +3 -27
  113. package/dist/cjs/utils/fixChunkStartEndChars.cjs.map +1 -1
  114. package/dist/cjs/utils/formatTimeDiff.cjs +1 -20
  115. package/dist/cjs/utils/formatTimeDiff.cjs.map +1 -1
  116. package/dist/cjs/utils/getIsFileUpdatedRecently.cjs +1 -16
  117. package/dist/cjs/utils/getIsFileUpdatedRecently.cjs.map +1 -1
  118. package/dist/cjs/utils/getOutputFilePath.cjs +1 -74
  119. package/dist/cjs/utils/getOutputFilePath.cjs.map +1 -1
  120. package/dist/cjs/utils/getParentPackageJSON.cjs +1 -20
  121. package/dist/cjs/utils/getParentPackageJSON.cjs.map +1 -1
  122. package/dist/cjs/utils/listSpecialChars.cjs +2 -54
  123. package/dist/cjs/utils/listSpecialChars.cjs.map +1 -1
  124. package/dist/cjs/utils/mapChunksBetweenFiles.cjs +1 -102
  125. package/dist/cjs/utils/mapChunksBetweenFiles.cjs.map +1 -1
  126. package/dist/cjs/utils/openBrowser.cjs +1 -19
  127. package/dist/cjs/utils/openBrowser.cjs.map +1 -1
  128. package/dist/cjs/utils/reorderParagraphs.cjs +3 -91
  129. package/dist/cjs/utils/reorderParagraphs.cjs.map +1 -1
  130. package/dist/cjs/utils/setupAI.cjs +1 -64
  131. package/dist/cjs/utils/setupAI.cjs.map +1 -1
  132. package/dist/cjs/watch.cjs +1 -43
  133. package/dist/cjs/watch.cjs.map +1 -1
  134. package/dist/esm/IntlayerEventListener.mjs +1 -183
  135. package/dist/esm/IntlayerEventListener.mjs.map +1 -1
  136. package/dist/esm/_virtual/_rolldown/runtime.mjs +1 -8
  137. package/dist/esm/_virtual/_utils_asset.mjs +2 -97
  138. package/dist/esm/auth/login.mjs +2 -82
  139. package/dist/esm/auth/login.mjs.map +1 -1
  140. package/dist/esm/build.mjs +1 -25
  141. package/dist/esm/build.mjs.map +1 -1
  142. package/dist/esm/ci.mjs +1 -71
  143. package/dist/esm/ci.mjs.map +1 -1
  144. package/dist/esm/cli.mjs +1 -473
  145. package/dist/esm/cli.mjs.map +1 -1
  146. package/dist/esm/config.mjs +1 -10
  147. package/dist/esm/config.mjs.map +1 -1
  148. package/dist/esm/editor.mjs +1 -49
  149. package/dist/esm/editor.mjs.map +1 -1
  150. package/dist/esm/extract.mjs +1 -93
  151. package/dist/esm/extract.mjs.map +1 -1
  152. package/dist/esm/fill/deepMergeContent.mjs +1 -25
  153. package/dist/esm/fill/deepMergeContent.mjs.map +1 -1
  154. package/dist/esm/fill/fill.mjs +1 -76
  155. package/dist/esm/fill/fill.mjs.map +1 -1
  156. package/dist/esm/fill/formatAutoFilledFilePath.mjs +1 -27
  157. package/dist/esm/fill/formatAutoFilledFilePath.mjs.map +1 -1
  158. package/dist/esm/fill/formatFillData.mjs +1 -49
  159. package/dist/esm/fill/formatFillData.mjs.map +1 -1
  160. package/dist/esm/fill/getAvailableLocalesInDictionary.mjs +1 -24
  161. package/dist/esm/fill/getAvailableLocalesInDictionary.mjs.map +1 -1
  162. package/dist/esm/fill/getFilterMissingContentPerLocale.mjs +1 -48
  163. package/dist/esm/fill/getFilterMissingContentPerLocale.mjs.map +1 -1
  164. package/dist/esm/fill/index.mjs +1 -4
  165. package/dist/esm/fill/listTranslationsTasks.mjs +1 -68
  166. package/dist/esm/fill/listTranslationsTasks.mjs.map +1 -1
  167. package/dist/esm/fill/mergeChunks.mjs +1 -26
  168. package/dist/esm/fill/mergeChunks.mjs.map +1 -1
  169. package/dist/esm/fill/translateDictionary.mjs +1 -203
  170. package/dist/esm/fill/translateDictionary.mjs.map +1 -1
  171. package/dist/esm/fill/writeFill.mjs +1 -52
  172. package/dist/esm/fill/writeFill.mjs.map +1 -1
  173. package/dist/esm/getTargetDictionary.mjs +1 -33
  174. package/dist/esm/getTargetDictionary.mjs.map +1 -1
  175. package/dist/esm/index.mjs +1 -18
  176. package/dist/esm/init.mjs +1 -317
  177. package/dist/esm/init.mjs.map +1 -1
  178. package/dist/esm/initSkills.mjs +2 -0
  179. package/dist/esm/initSkills.mjs.map +1 -0
  180. package/dist/esm/listContentDeclaration.mjs +1 -38
  181. package/dist/esm/listContentDeclaration.mjs.map +1 -1
  182. package/dist/esm/listProjects.mjs +1 -26
  183. package/dist/esm/listProjects.mjs.map +1 -1
  184. package/dist/esm/liveSync.mjs +8 -148
  185. package/dist/esm/liveSync.mjs.map +1 -1
  186. package/dist/esm/pull.mjs +1 -144
  187. package/dist/esm/pull.mjs.map +1 -1
  188. package/dist/esm/push/pullLog.mjs +3 -100
  189. package/dist/esm/push/pullLog.mjs.map +1 -1
  190. package/dist/esm/push/push.mjs +1 -203
  191. package/dist/esm/push/push.mjs.map +1 -1
  192. package/dist/esm/pushConfig.mjs +1 -17
  193. package/dist/esm/pushConfig.mjs.map +1 -1
  194. package/dist/esm/pushLog.mjs +3 -82
  195. package/dist/esm/pushLog.mjs.map +1 -1
  196. package/dist/esm/reviewDoc/reviewDoc.mjs +1 -65
  197. package/dist/esm/reviewDoc/reviewDoc.mjs.map +1 -1
  198. package/dist/esm/reviewDoc/reviewDocBlockAware.mjs +1 -92
  199. package/dist/esm/reviewDoc/reviewDocBlockAware.mjs.map +1 -1
  200. package/dist/esm/searchDoc.mjs +1 -36
  201. package/dist/esm/searchDoc.mjs.map +1 -1
  202. package/dist/esm/test/index.mjs +1 -4
  203. package/dist/esm/test/listMissingTranslations.mjs +1 -46
  204. package/dist/esm/test/listMissingTranslations.mjs.map +1 -1
  205. package/dist/esm/test/test.mjs +1 -51
  206. package/dist/esm/test/test.mjs.map +1 -1
  207. package/dist/esm/translateDoc/index.mjs +1 -5
  208. package/dist/esm/translateDoc/translateDoc.mjs +1 -71
  209. package/dist/esm/translateDoc/translateDoc.mjs.map +1 -1
  210. package/dist/esm/translateDoc/translateFile.mjs +2 -101
  211. package/dist/esm/translateDoc/translateFile.mjs.map +1 -1
  212. package/dist/esm/translateDoc/validation.mjs +5 -46
  213. package/dist/esm/translateDoc/validation.mjs.map +1 -1
  214. package/dist/esm/translation-alignment/alignBlocks.mjs +1 -66
  215. package/dist/esm/translation-alignment/alignBlocks.mjs.map +1 -1
  216. package/dist/esm/translation-alignment/computeSimilarity.mjs +1 -22
  217. package/dist/esm/translation-alignment/computeSimilarity.mjs.map +1 -1
  218. package/dist/esm/translation-alignment/fingerprintBlock.mjs +1 -20
  219. package/dist/esm/translation-alignment/fingerprintBlock.mjs.map +1 -1
  220. package/dist/esm/translation-alignment/index.mjs +1 -11
  221. package/dist/esm/translation-alignment/mapChangedLinesToBlocks.mjs +1 -16
  222. package/dist/esm/translation-alignment/mapChangedLinesToBlocks.mjs.map +1 -1
  223. package/dist/esm/translation-alignment/normalizeBlock.mjs +1 -20
  224. package/dist/esm/translation-alignment/normalizeBlock.mjs.map +1 -1
  225. package/dist/esm/translation-alignment/pipeline.mjs +1 -35
  226. package/dist/esm/translation-alignment/pipeline.mjs.map +1 -1
  227. package/dist/esm/translation-alignment/planActions.mjs +1 -44
  228. package/dist/esm/translation-alignment/planActions.mjs.map +1 -1
  229. package/dist/esm/translation-alignment/rebuildDocument.mjs +2 -46
  230. package/dist/esm/translation-alignment/rebuildDocument.mjs.map +1 -1
  231. package/dist/esm/translation-alignment/segmentDocument.mjs +5 -64
  232. package/dist/esm/translation-alignment/segmentDocument.mjs.map +1 -1
  233. package/dist/esm/utils/calculateChunks.mjs +2 -87
  234. package/dist/esm/utils/calculateChunks.mjs.map +1 -1
  235. package/dist/esm/utils/checkAccess.mjs +1 -78
  236. package/dist/esm/utils/checkAccess.mjs.map +1 -1
  237. package/dist/esm/utils/checkConfigConsistency.mjs +1 -14
  238. package/dist/esm/utils/checkConfigConsistency.mjs.map +1 -1
  239. package/dist/esm/utils/checkFileModifiedRange.mjs +1 -80
  240. package/dist/esm/utils/checkFileModifiedRange.mjs.map +1 -1
  241. package/dist/esm/utils/checkLastUpdateTime.mjs +1 -17
  242. package/dist/esm/utils/checkLastUpdateTime.mjs.map +1 -1
  243. package/dist/esm/utils/chunkInference.mjs +1 -43
  244. package/dist/esm/utils/chunkInference.mjs.map +1 -1
  245. package/dist/esm/utils/fixChunkStartEndChars.mjs +3 -25
  246. package/dist/esm/utils/fixChunkStartEndChars.mjs.map +1 -1
  247. package/dist/esm/utils/formatTimeDiff.mjs +1 -18
  248. package/dist/esm/utils/formatTimeDiff.mjs.map +1 -1
  249. package/dist/esm/utils/getIsFileUpdatedRecently.mjs +1 -14
  250. package/dist/esm/utils/getIsFileUpdatedRecently.mjs.map +1 -1
  251. package/dist/esm/utils/getOutputFilePath.mjs +1 -72
  252. package/dist/esm/utils/getOutputFilePath.mjs.map +1 -1
  253. package/dist/esm/utils/getParentPackageJSON.mjs +1 -18
  254. package/dist/esm/utils/getParentPackageJSON.mjs.map +1 -1
  255. package/dist/esm/utils/listSpecialChars.mjs +2 -52
  256. package/dist/esm/utils/listSpecialChars.mjs.map +1 -1
  257. package/dist/esm/utils/mapChunksBetweenFiles.mjs +1 -100
  258. package/dist/esm/utils/mapChunksBetweenFiles.mjs.map +1 -1
  259. package/dist/esm/utils/openBrowser.mjs +1 -17
  260. package/dist/esm/utils/openBrowser.mjs.map +1 -1
  261. package/dist/esm/utils/reorderParagraphs.mjs +3 -90
  262. package/dist/esm/utils/reorderParagraphs.mjs.map +1 -1
  263. package/dist/esm/utils/setupAI.mjs +1 -62
  264. package/dist/esm/utils/setupAI.mjs.map +1 -1
  265. package/dist/esm/watch.mjs +1 -41
  266. package/dist/esm/watch.mjs.map +1 -1
  267. package/dist/types/auth/login.d.ts +1 -1
  268. package/dist/types/auth/login.d.ts.map +1 -1
  269. package/dist/types/build.d.ts +1 -1
  270. package/dist/types/build.d.ts.map +1 -1
  271. package/dist/types/cli.d.ts.map +1 -1
  272. package/dist/types/config.d.ts +1 -1
  273. package/dist/types/extract.d.ts +1 -1
  274. package/dist/types/extract.d.ts.map +1 -1
  275. package/dist/types/fill/fill.d.ts +1 -1
  276. package/dist/types/fill/fill.d.ts.map +1 -1
  277. package/dist/types/fill/translateDictionary.d.ts +2 -2
  278. package/dist/types/fill/translateDictionary.d.ts.map +1 -1
  279. package/dist/types/fill/writeFill.d.ts.map +1 -1
  280. package/dist/types/getTargetDictionary.d.ts +2 -2
  281. package/dist/types/index.d.ts +7 -3
  282. package/dist/types/init.d.ts +2 -5
  283. package/dist/types/init.d.ts.map +1 -1
  284. package/dist/types/initSkills.d.ts +8 -0
  285. package/dist/types/initSkills.d.ts.map +1 -0
  286. package/dist/types/listContentDeclaration.d.ts +1 -1
  287. package/dist/types/listContentDeclaration.d.ts.map +1 -1
  288. package/dist/types/liveSync.d.ts +1 -1
  289. package/dist/types/pull.d.ts +1 -1
  290. package/dist/types/pull.d.ts.map +1 -1
  291. package/dist/types/push/pullLog.d.ts +1 -1
  292. package/dist/types/push/pullLog.d.ts.map +1 -1
  293. package/dist/types/push/push.d.ts +2 -2
  294. package/dist/types/pushConfig.d.ts +1 -1
  295. package/dist/types/reviewDoc/reviewDoc.d.ts +2 -2
  296. package/dist/types/reviewDoc/reviewDoc.d.ts.map +1 -1
  297. package/dist/types/reviewDoc/reviewDocBlockAware.d.ts +1 -1
  298. package/dist/types/reviewDoc/reviewDocBlockAware.d.ts.map +1 -1
  299. package/dist/types/searchDoc.d.ts +1 -1
  300. package/dist/types/searchDoc.d.ts.map +1 -1
  301. package/dist/types/test/listMissingTranslations.d.ts +1 -1
  302. package/dist/types/test/test.d.ts +1 -1
  303. package/dist/types/test/test.d.ts.map +1 -1
  304. package/dist/types/translateDoc/translateDoc.d.ts.map +1 -1
  305. package/dist/types/translateDoc/types.d.ts +2 -2
  306. package/dist/types/translateDoc/validation.d.ts +1 -1
  307. package/dist/types/utils/checkAccess.d.ts.map +1 -1
  308. package/dist/types/watch.d.ts +1 -1
  309. package/dist/types/watch.d.ts.map +1 -1
  310. package/package.json +11 -11
@@ -1,184 +1,2 @@
1
- import { getIntlayerAPIProxy } from "@intlayer/api";
2
- import configuration from "@intlayer/config/built";
3
- import { getAppLogger } from "@intlayer/config/client";
4
- import { EventSource } from "eventsource";
5
-
6
- //#region src/IntlayerEventListener.ts
7
- /**
8
- * IntlayerEventListener class to listen for dictionary changes via SSE (Server-Sent Events).
9
- *
10
- * Usage example:
11
- *
12
- * import { buildIntlayerDictionary } from './transpiler/declaration_file_to_dictionary/intlayer_dictionary';
13
- * import { IntlayerEventListener } from '@intlayer/api';
14
- *
15
- * export const checkDictionaryChanges = async () => {
16
- * // Instantiate the listener
17
- * const eventListener = new IntlayerEventListener();
18
- *
19
- * // Set up your callbacks
20
- * eventListener.onDictionaryChange = async (dictionary) => {
21
- * await buildIntlayerDictionary(dictionary);
22
- * };
23
- *
24
- * // Initialize the listener
25
- * await eventListener.initialize();
26
- *
27
- * // Optionally, clean up later when you’re done
28
- * // eventListener.cleanup();
29
- * };
30
- */
31
- var IntlayerEventListener = class {
32
- appLogger = getAppLogger(configuration);
33
- eventSource = null;
34
- reconnectAttempts = 0;
35
- maxReconnectAttempts = 5;
36
- reconnectDelay = 1e3;
37
- isManuallyDisconnected = false;
38
- reconnectTimeout = null;
39
- /**
40
- * Callback triggered when a Dictionary is ADDED.
41
- */
42
- onDictionaryAdded;
43
- /**
44
- * Callback triggered when a Dictionary is UPDATED.
45
- */
46
- onDictionaryChange;
47
- /**
48
- * Callback triggered when a Dictionary is DELETED.
49
- */
50
- onDictionaryDeleted;
51
- /**
52
- * Callback triggered when connection is established or re-established.
53
- */
54
- onConnectionOpen;
55
- /**
56
- * Callback triggered when connection encounters an error.
57
- */
58
- onConnectionError;
59
- constructor(intlayerConfig = configuration) {
60
- this.intlayerConfig = intlayerConfig;
61
- this.appLogger = getAppLogger(this.intlayerConfig);
62
- }
63
- /**
64
- * Initializes the EventSource connection using the given intlayerConfig
65
- * (or the default config if none was provided).
66
- */
67
- async initialize() {
68
- this.isManuallyDisconnected = false;
69
- await this.connect();
70
- }
71
- /**
72
- * Establishes the EventSource connection with automatic reconnection support.
73
- */
74
- async connect() {
75
- try {
76
- const backendURL = this.intlayerConfig.editor.backendURL;
77
- const accessToken = await getIntlayerAPIProxy(void 0, this.intlayerConfig).oAuth.getOAuth2AccessToken();
78
- if (!accessToken) throw new Error("Failed to retrieve access token");
79
- const API_ROUTE = `${backendURL}/api/event-listener`;
80
- if (this.eventSource) this.eventSource.close();
81
- this.eventSource = new EventSource(API_ROUTE, { fetch: (input, init) => fetch(input, {
82
- ...init,
83
- headers: {
84
- ...init?.headers ?? {},
85
- Authorization: `Bearer ${accessToken.data?.accessToken}`
86
- }
87
- }) });
88
- this.eventSource.onopen = () => {
89
- this.reconnectAttempts = 0;
90
- this.reconnectDelay = 1e3;
91
- this.onConnectionOpen?.();
92
- };
93
- this.eventSource.onmessage = (event) => this.handleMessage(event);
94
- this.eventSource.onerror = (event) => this.handleError(event);
95
- } catch (_error) {
96
- this.appLogger("Failed to establish EventSource connection:", { level: "error" });
97
- this.scheduleReconnect();
98
- }
99
- }
100
- /**
101
- * Cleans up (closes) the EventSource connection.
102
- */
103
- cleanup() {
104
- this.isManuallyDisconnected = true;
105
- if (this.reconnectTimeout) {
106
- clearTimeout(this.reconnectTimeout);
107
- this.reconnectTimeout = null;
108
- }
109
- if (this.eventSource) {
110
- this.eventSource.close();
111
- this.eventSource = null;
112
- }
113
- }
114
- /**
115
- * Schedules a reconnection attempt with exponential backoff.
116
- */
117
- scheduleReconnect() {
118
- if (this.isManuallyDisconnected || this.reconnectAttempts >= this.maxReconnectAttempts) {
119
- if (this.reconnectAttempts >= this.maxReconnectAttempts) this.appLogger([`Max reconnection attempts (${this.maxReconnectAttempts}) reached. Giving up.`], { level: "error" });
120
- return;
121
- }
122
- this.reconnectAttempts++;
123
- const delay = this.reconnectDelay * 2 ** (this.reconnectAttempts - 1);
124
- this.appLogger(`Scheduling reconnection attempt ${this.reconnectAttempts}/${this.maxReconnectAttempts} in ${delay}ms`);
125
- this.reconnectTimeout = setTimeout(async () => {
126
- if (!this.isManuallyDisconnected) await this.connect();
127
- }, delay);
128
- }
129
- /**
130
- * Handles incoming SSE messages, parses the event data,
131
- * and invokes the appropriate callback.
132
- */
133
- async handleMessage(event) {
134
- try {
135
- const { data } = event;
136
- const dataJSON = JSON.parse(data);
137
- for (const dataEl of dataJSON) switch (dataEl.object) {
138
- case "DICTIONARY":
139
- switch (dataEl.status) {
140
- case "ADDED":
141
- await this.onDictionaryAdded?.(dataEl.data);
142
- break;
143
- case "UPDATED":
144
- await this.onDictionaryChange?.(dataEl.data);
145
- break;
146
- case "DELETED":
147
- await this.onDictionaryDeleted?.(dataEl.data);
148
- break;
149
- default:
150
- this.appLogger(["Unhandled dictionary status:", dataEl.status], { level: "error" });
151
- break;
152
- }
153
- break;
154
- default:
155
- this.appLogger(["Unknown object type:", dataEl.object], { level: "error" });
156
- break;
157
- }
158
- } catch (error) {
159
- this.appLogger(["Error processing dictionary update:", error], { level: "error" });
160
- }
161
- }
162
- /**
163
- * Handles any SSE errors and attempts reconnection if appropriate.
164
- */
165
- handleError(event) {
166
- const errorEvent = event;
167
- this.appLogger(["EventSource error:", {
168
- type: errorEvent.type,
169
- message: errorEvent.message,
170
- code: errorEvent.code,
171
- readyState: this.eventSource?.readyState,
172
- url: this.eventSource?.url
173
- }], { level: "error" });
174
- this.onConnectionError?.(event);
175
- if (errorEvent.type === "error" && (errorEvent.message?.includes("terminated") || errorEvent.message?.includes("closed") || this.eventSource?.readyState === EventSource.CLOSED) && !this.isManuallyDisconnected) {
176
- this.appLogger("Connection was terminated by server, attempting to reconnect...");
177
- this.scheduleReconnect();
178
- } else this.cleanup();
179
- }
180
- };
181
-
182
- //#endregion
183
- export { IntlayerEventListener };
1
+ import{getIntlayerAPIProxy as e}from"@intlayer/api";import t from"@intlayer/config/built";import{getAppLogger as n}from"@intlayer/config/client";import{EventSource as r}from"eventsource";var i=class{appLogger=n(t);eventSource=null;reconnectAttempts=0;maxReconnectAttempts=5;reconnectDelay=1e3;isManuallyDisconnected=!1;reconnectTimeout=null;onDictionaryAdded;onDictionaryChange;onDictionaryDeleted;onConnectionOpen;onConnectionError;constructor(e=t){this.intlayerConfig=e,this.appLogger=n(this.intlayerConfig)}async initialize(){this.isManuallyDisconnected=!1,await this.connect()}async connect(){try{let t=this.intlayerConfig.editor.backendURL,n=await e(void 0,this.intlayerConfig).oAuth.getOAuth2AccessToken();if(!n)throw Error(`Failed to retrieve access token`);let i=`${t}/api/event-listener`;this.eventSource&&this.eventSource.close(),this.eventSource=new r(i,{fetch:(e,t)=>fetch(e,{...t,headers:{...t?.headers??{},Authorization:`Bearer ${n.data?.accessToken}`}})}),this.eventSource.onopen=()=>{this.reconnectAttempts=0,this.reconnectDelay=1e3,this.onConnectionOpen?.()},this.eventSource.onmessage=e=>this.handleMessage(e),this.eventSource.onerror=e=>this.handleError(e)}catch{this.appLogger(`Failed to establish EventSource connection:`,{level:`error`}),this.scheduleReconnect()}}cleanup(){this.isManuallyDisconnected=!0,this.reconnectTimeout&&=(clearTimeout(this.reconnectTimeout),null),this.eventSource&&=(this.eventSource.close(),null)}scheduleReconnect(){if(this.isManuallyDisconnected||this.reconnectAttempts>=this.maxReconnectAttempts){this.reconnectAttempts>=this.maxReconnectAttempts&&this.appLogger([`Max reconnection attempts (${this.maxReconnectAttempts}) reached. Giving up.`],{level:`error`});return}this.reconnectAttempts++;let e=this.reconnectDelay*2**(this.reconnectAttempts-1);this.appLogger(`Scheduling reconnection attempt ${this.reconnectAttempts}/${this.maxReconnectAttempts} in ${e}ms`),this.reconnectTimeout=setTimeout(async()=>{this.isManuallyDisconnected||await this.connect()},e)}async handleMessage(e){try{let{data:t}=e,n=JSON.parse(t);for(let e of n)switch(e.object){case`DICTIONARY`:switch(e.status){case`ADDED`:await this.onDictionaryAdded?.(e.data);break;case`UPDATED`:await this.onDictionaryChange?.(e.data);break;case`DELETED`:await this.onDictionaryDeleted?.(e.data);break;default:this.appLogger([`Unhandled dictionary status:`,e.status],{level:`error`});break}break;default:this.appLogger([`Unknown object type:`,e.object],{level:`error`});break}}catch(e){this.appLogger([`Error processing dictionary update:`,e],{level:`error`})}}handleError(e){let t=e;this.appLogger([`EventSource error:`,{type:t.type,message:t.message,code:t.code,readyState:this.eventSource?.readyState,url:this.eventSource?.url}],{level:`error`}),this.onConnectionError?.(e),t.type===`error`&&(t.message?.includes(`terminated`)||t.message?.includes(`closed`)||this.eventSource?.readyState===r.CLOSED)&&!this.isManuallyDisconnected?(this.appLogger(`Connection was terminated by server, attempting to reconnect...`),this.scheduleReconnect()):this.cleanup()}};export{i as IntlayerEventListener};
184
2
  //# sourceMappingURL=IntlayerEventListener.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"IntlayerEventListener.mjs","names":[],"sources":["../../src/IntlayerEventListener.ts"],"sourcesContent":["import { getIntlayerAPIProxy } from '@intlayer/api';\n// @ts-ignore: @intlayer/backend is not built yet\nimport type { DictionaryAPI, MessageEventData } from '@intlayer/backend';\nimport configuration from '@intlayer/config/built';\nimport { getAppLogger } from '@intlayer/config/client';\nimport type { IntlayerConfig } from '@intlayer/types';\nimport { EventSource } from 'eventsource';\n\nexport type IntlayerMessageEvent = MessageEvent;\n\n/**\n * IntlayerEventListener class to listen for dictionary changes via SSE (Server-Sent Events).\n *\n * Usage example:\n *\n * import { buildIntlayerDictionary } from './transpiler/declaration_file_to_dictionary/intlayer_dictionary';\n * import { IntlayerEventListener } from '@intlayer/api';\n *\n * export const checkDictionaryChanges = async () => {\n * // Instantiate the listener\n * const eventListener = new IntlayerEventListener();\n *\n * // Set up your callbacks\n * eventListener.onDictionaryChange = async (dictionary) => {\n * await buildIntlayerDictionary(dictionary);\n * };\n *\n * // Initialize the listener\n * await eventListener.initialize();\n *\n * // Optionally, clean up later when you’re done\n * // eventListener.cleanup();\n * };\n */\nexport class IntlayerEventListener {\n private appLogger = getAppLogger(configuration);\n\n private eventSource: EventSource | null = null;\n private reconnectAttempts = 0;\n private maxReconnectAttempts = 5;\n private reconnectDelay = 1000; // Start with 1 second\n private isManuallyDisconnected = false;\n private reconnectTimeout: NodeJS.Timeout | null = null;\n\n /**\n * Callback triggered when a Dictionary is ADDED.\n */\n public onDictionaryAdded?: (dictionary: DictionaryAPI) => any;\n\n /**\n * Callback triggered when a Dictionary is UPDATED.\n */\n public onDictionaryChange?: (dictionary: DictionaryAPI) => any;\n\n /**\n * Callback triggered when a Dictionary is DELETED.\n */\n public onDictionaryDeleted?: (dictionary: DictionaryAPI) => any;\n\n /**\n * Callback triggered when connection is established or re-established.\n */\n public onConnectionOpen?: () => any;\n\n /**\n * Callback triggered when connection encounters an error.\n */\n public onConnectionError?: (error: Event) => any;\n\n constructor(private intlayerConfig: IntlayerConfig = configuration) {\n this.appLogger = getAppLogger(this.intlayerConfig);\n }\n\n /**\n * Initializes the EventSource connection using the given intlayerConfig\n * (or the default config if none was provided).\n */\n public async initialize(): Promise<void> {\n this.isManuallyDisconnected = false;\n await this.connect();\n }\n\n /**\n * Establishes the EventSource connection with automatic reconnection support.\n */\n private async connect(): Promise<void> {\n try {\n const backendURL = this.intlayerConfig.editor.backendURL;\n\n // Retrieve the access token via proxy\n const accessToken = await getIntlayerAPIProxy(\n undefined,\n this.intlayerConfig\n ).oAuth.getOAuth2AccessToken();\n\n if (!accessToken) {\n throw new Error('Failed to retrieve access token');\n }\n\n const API_ROUTE = `${backendURL}/api/event-listener`;\n\n // Close existing connection if any\n if (this.eventSource) {\n this.eventSource.close();\n }\n\n this.eventSource = new EventSource(API_ROUTE, {\n fetch: (input, init) =>\n fetch(input, {\n ...init,\n headers: {\n ...(init?.headers ?? {}),\n Authorization: `Bearer ${accessToken.data?.accessToken}`,\n },\n }),\n });\n\n this.eventSource.onopen = () => {\n this.reconnectAttempts = 0;\n this.reconnectDelay = 1000; // Reset delay\n this.onConnectionOpen?.();\n };\n\n this.eventSource.onmessage = (event) => this.handleMessage(event);\n this.eventSource.onerror = (event) => this.handleError(event);\n } catch (_error) {\n this.appLogger('Failed to establish EventSource connection:', {\n level: 'error',\n });\n this.scheduleReconnect();\n }\n }\n\n /**\n * Cleans up (closes) the EventSource connection.\n */\n public cleanup(): void {\n this.isManuallyDisconnected = true;\n\n if (this.reconnectTimeout) {\n clearTimeout(this.reconnectTimeout);\n this.reconnectTimeout = null;\n }\n\n if (this.eventSource) {\n this.eventSource.close();\n this.eventSource = null;\n }\n }\n\n /**\n * Schedules a reconnection attempt with exponential backoff.\n */\n private scheduleReconnect(): void {\n if (\n this.isManuallyDisconnected ||\n this.reconnectAttempts >= this.maxReconnectAttempts\n ) {\n if (this.reconnectAttempts >= this.maxReconnectAttempts) {\n this.appLogger(\n [\n `Max reconnection attempts (${this.maxReconnectAttempts}) reached. Giving up.`,\n ],\n {\n level: 'error',\n }\n );\n }\n return;\n }\n\n this.reconnectAttempts++;\n const delay = this.reconnectDelay * 2 ** (this.reconnectAttempts - 1); // Exponential backoff\n\n this.appLogger(\n `Scheduling reconnection attempt ${this.reconnectAttempts}/${this.maxReconnectAttempts} in ${delay}ms`\n );\n\n this.reconnectTimeout = setTimeout(async () => {\n if (!this.isManuallyDisconnected) {\n await this.connect();\n }\n }, delay);\n }\n\n /**\n * Handles incoming SSE messages, parses the event data,\n * and invokes the appropriate callback.\n */\n private async handleMessage(event: IntlayerMessageEvent): Promise<void> {\n try {\n const { data } = event;\n\n const dataJSON: MessageEventData[] = JSON.parse(data);\n\n for (const dataEl of dataJSON) {\n switch (dataEl.object) {\n case 'DICTIONARY':\n switch (dataEl.status) {\n case 'ADDED':\n await this.onDictionaryAdded?.(dataEl.data);\n break;\n case 'UPDATED':\n await this.onDictionaryChange?.(dataEl.data);\n break;\n case 'DELETED':\n await this.onDictionaryDeleted?.(dataEl.data);\n break;\n default:\n this.appLogger(\n ['Unhandled dictionary status:', dataEl.status],\n {\n level: 'error',\n }\n );\n break;\n }\n break;\n default:\n this.appLogger(['Unknown object type:', dataEl.object], {\n level: 'error',\n });\n break;\n }\n }\n } catch (error) {\n this.appLogger(['Error processing dictionary update:', error], {\n level: 'error',\n });\n }\n }\n\n /**\n * Handles any SSE errors and attempts reconnection if appropriate.\n */\n private handleError(event: Event): void {\n const errorEvent = event as any;\n\n // Log detailed error information\n this.appLogger(\n [\n 'EventSource error:',\n {\n type: errorEvent.type,\n message: errorEvent.message,\n code: errorEvent.code,\n readyState: this.eventSource?.readyState,\n url: this.eventSource?.url,\n },\n ],\n {\n level: 'error',\n }\n );\n\n // Notify error callback\n this.onConnectionError?.(event);\n\n // Check if this is a connection close error\n const isConnectionClosed =\n errorEvent.type === 'error' &&\n (errorEvent.message?.includes('terminated') ||\n errorEvent.message?.includes('closed') ||\n this.eventSource?.readyState === EventSource.CLOSED);\n\n if (isConnectionClosed && !this.isManuallyDisconnected) {\n this.appLogger(\n 'Connection was terminated by server, attempting to reconnect...'\n );\n this.scheduleReconnect();\n } else {\n // For other types of errors, close the connection\n this.cleanup();\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCA,IAAa,wBAAb,MAAmC;CACjC,AAAQ,YAAY,aAAa,cAAc;CAE/C,AAAQ,cAAkC;CAC1C,AAAQ,oBAAoB;CAC5B,AAAQ,uBAAuB;CAC/B,AAA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oB,MAAM;AAS/B,MALE,WAAW,SAAS,YACnB,WAAW,SAAS,SAAS,aAAa,IACzC,WAAW,SAAS,SAAS,SAAS,IACtC,KAAK,aAAa,eAAe,YAAY,WAEvB,CAAC,KAAK,wBAAwB;AACtD,QAAK,UACH,kEACD;AACD,QAAK,mBAAmB;QAGxB,MAAK,SAAS"}
1
+ {"version":3,"file":"IntlayerEventListener.mjs","names":[],"sources":["../../src/IntlayerEventListener.ts"],"sourcesContent":["import { getIntlayerAPIProxy } from '@intlayer/api';\n// @ts-ignore: @intlayer/backend is not built yet\nimport type { DictionaryAPI, MessageEventData } from '@intlayer/backend';\nimport configuration from '@intlayer/config/built';\nimport { getAppLogger } from '@intlayer/config/client';\nimport type { IntlayerConfig } from '@intlayer/types';\nimport { EventSource } from 'eventsource';\n\nexport type IntlayerMessageEvent = MessageEvent;\n\n/**\n * IntlayerEventListener class to listen for dictionary changes via SSE (Server-Sent Events).\n *\n * Usage example:\n *\n * import { buildIntlayerDictionary } from './transpiler/declaration_file_to_dictionary/intlayer_dictionary';\n * import { IntlayerEventListener } from '@intlayer/api';\n *\n * export const checkDictionaryChanges = async () => {\n * // Instantiate the listener\n * const eventListener = new IntlayerEventListener();\n *\n * // Set up your callbacks\n * eventListener.onDictionaryChange = async (dictionary) => {\n * await buildIntlayerDictionary(dictionary);\n * };\n *\n * // Initialize the listener\n * await eventListener.initialize();\n *\n * // Optionally, clean up later when you’re done\n * // eventListener.cleanup();\n * };\n */\nexport class IntlayerEventListener {\n private appLogger = getAppLogger(configuration);\n\n private eventSource: EventSource | null = null;\n private reconnectAttempts = 0;\n private maxReconnectAttempts = 5;\n private reconnectDelay = 1000; // Start with 1 second\n private isManuallyDisconnected = false;\n private reconnectTimeout: NodeJS.Timeout | null = null;\n\n /**\n * Callback triggered when a Dictionary is ADDED.\n */\n public onDictionaryAdded?: (dictionary: DictionaryAPI) => any;\n\n /**\n * Callback triggered when a Dictionary is UPDATED.\n */\n public onDictionaryChange?: (dictionary: DictionaryAPI) => any;\n\n /**\n * Callback triggered when a Dictionary is DELETED.\n */\n public onDictionaryDeleted?: (dictionary: DictionaryAPI) => any;\n\n /**\n * Callback triggered when connection is established or re-established.\n */\n public onConnectionOpen?: () => any;\n\n /**\n * Callback triggered when connection encounters an error.\n */\n public onConnectionError?: (error: Event) => any;\n\n constructor(private intlayerConfig: IntlayerConfig = configuration) {\n this.appLogger = getAppLogger(this.intlayerConfig);\n }\n\n /**\n * Initializes the EventSource connection using the given intlayerConfig\n * (or the default config if none was provided).\n */\n public async initialize(): Promise<void> {\n this.isManuallyDisconnected = false;\n await this.connect();\n }\n\n /**\n * Establishes the EventSource connection with automatic reconnection support.\n */\n private async connect(): Promise<void> {\n try {\n const backendURL = this.intlayerConfig.editor.backendURL;\n\n // Retrieve the access token via proxy\n const accessToken = await getIntlayerAPIProxy(\n undefined,\n this.intlayerConfig\n ).oAuth.getOAuth2AccessToken();\n\n if (!accessToken) {\n throw new Error('Failed to retrieve access token');\n }\n\n const API_ROUTE = `${backendURL}/api/event-listener`;\n\n // Close existing connection if any\n if (this.eventSource) {\n this.eventSource.close();\n }\n\n this.eventSource = new EventSource(API_ROUTE, {\n fetch: (input, init) =>\n fetch(input, {\n ...init,\n headers: {\n ...(init?.headers ?? {}),\n Authorization: `Bearer ${accessToken.data?.accessToken}`,\n },\n }),\n });\n\n this.eventSource.onopen = () => {\n this.reconnectAttempts = 0;\n this.reconnectDelay = 1000; // Reset delay\n this.onConnectionOpen?.();\n };\n\n this.eventSource.onmessage = (event) => this.handleMessage(event);\n this.eventSource.onerror = (event) => this.handleError(event);\n } catch (_error) {\n this.appLogger('Failed to establish EventSource connection:', {\n level: 'error',\n });\n this.scheduleReconnect();\n }\n }\n\n /**\n * Cleans up (closes) the EventSource connection.\n */\n public cleanup(): void {\n this.isManuallyDisconnected = true;\n\n if (this.reconnectTimeout) {\n clearTimeout(this.reconnectTimeout);\n this.reconnectTimeout = null;\n }\n\n if (this.eventSource) {\n this.eventSource.close();\n this.eventSource = null;\n }\n }\n\n /**\n * Schedules a reconnection attempt with exponential backoff.\n */\n private scheduleReconnect(): void {\n if (\n this.isManuallyDisconnected ||\n this.reconnectAttempts >= this.maxReconnectAttempts\n ) {\n if (this.reconnectAttempts >= this.maxReconnectAttempts) {\n this.appLogger(\n [\n `Max reconnection attempts (${this.maxReconnectAttempts}) reached. Giving up.`,\n ],\n {\n level: 'error',\n }\n );\n }\n return;\n }\n\n this.reconnectAttempts++;\n const delay = this.reconnectDelay * 2 ** (this.reconnectAttempts - 1); // Exponential backoff\n\n this.appLogger(\n `Scheduling reconnection attempt ${this.reconnectAttempts}/${this.maxReconnectAttempts} in ${delay}ms`\n );\n\n this.reconnectTimeout = setTimeout(async () => {\n if (!this.isManuallyDisconnected) {\n await this.connect();\n }\n }, delay);\n }\n\n /**\n * Handles incoming SSE messages, parses the event data,\n * and invokes the appropriate callback.\n */\n private async handleMessage(event: IntlayerMessageEvent): Promise<void> {\n try {\n const { data } = event;\n\n const dataJSON: MessageEventData[] = JSON.parse(data);\n\n for (const dataEl of dataJSON) {\n switch (dataEl.object) {\n case 'DICTIONARY':\n switch (dataEl.status) {\n case 'ADDED':\n await this.onDictionaryAdded?.(dataEl.data);\n break;\n case 'UPDATED':\n await this.onDictionaryChange?.(dataEl.data);\n break;\n case 'DELETED':\n await this.onDictionaryDeleted?.(dataEl.data);\n break;\n default:\n this.appLogger(\n ['Unhandled dictionary status:', dataEl.status],\n {\n level: 'error',\n }\n );\n break;\n }\n break;\n default:\n this.appLogger(['Unknown object type:', dataEl.object], {\n level: 'error',\n });\n break;\n }\n }\n } catch (error) {\n this.appLogger(['Error processing dictionary update:', error], {\n level: 'error',\n });\n }\n }\n\n /**\n * Handles any SSE errors and attempts reconnection if appropriate.\n */\n private handleError(event: Event): void {\n const errorEvent = event as any;\n\n // Log detailed error information\n this.appLogger(\n [\n 'EventSource error:',\n {\n type: errorEvent.type,\n message: errorEvent.message,\n code: errorEvent.code,\n readyState: this.eventSource?.readyState,\n url: this.eventSource?.url,\n },\n ],\n {\n level: 'error',\n }\n );\n\n // Notify error callback\n this.onConnectionError?.(event);\n\n // Check if this is a connection close error\n const isConnectionClosed =\n errorEvent.type === 'error' &&\n (errorEvent.message?.includes('terminated') ||\n errorEvent.message?.includes('closed') ||\n this.eventSource?.readyState === EventSource.CLOSED);\n\n if (isConnectionClosed && !this.isManuallyDisconnected) {\n this.appLogger(\n 'Connection was terminated by server, attempting to reconnect...'\n );\n this.scheduleReconnect();\n } else {\n // For other types of errors, close the connection\n this.cleanup();\n }\n }\n}\n"],"mappings":"2LAkCA,IAAa,EAAb,KAAmC,CACjC,UAAoB,EAAa,EAAc,CAE/C,YAA0C,KAC1C,kBAA4B,EAC5B,qBAA+B,EAC/B,eAAyB,IACzB,uBAAiC,GACjC,iBAAkD,KAKlD,kBAKA,mBAKA,oBAKA,iBAKA,kBAEA,YAAY,EAAyC,EAAe,CAAhD,KAAA,eAAA,EAClB,KAAK,UAAY,EAAa,KAAK,eAAe,CAOpD,MAAa,YAA4B,CACvC,KAAK,uBAAyB,GAC9B,MAAM,KAAK,SAAS,CAMtB,MAAc,SAAyB,CACrC,GAAI,CACF,IAAM,EAAa,KAAK,eAAe,OAAO,WAGxC,EAAc,MAAM,EACxB,IAAA,GACA,KAAK,eACN,CAAC,MAAM,sBAAsB,CAE9B,GAAI,CAAC,EACH,MAAU,MAAM,kCAAkC,CAGpD,IAAM,EAAY,GAAG,EAAW,qBAG5B,KAAK,aACP,KAAK,YAAY,OAAO,CAG1B,KAAK,YAAc,IAAI,EAAY,EAAW,CAC5C,OAAQ,EAAO,IACb,MAAM,EAAO,CACX,GAAG,EACH,QAAS,CACP,GAAI,GAAM,SAAW,EAAE,CACvB,cAAe,UAAU,EAAY,MAAM,cAC5C,CACF,CAAC,CACL,CAAC,CAEF,KAAK,YAAY,WAAe,CAC9B,KAAK,kBAAoB,EACzB,KAAK,eAAiB,IACtB,KAAK,oBAAoB,EAG3B,KAAK,YAAY,UAAa,GAAU,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M,CAAE,CAC7D,MAAO,QACR,CAAC,EAON,YAAoB,EAAoB,CACtC,IAAM,EAAa,EAGnB,KAAK,UACH,CACE,qBACA,CACE,KAAM,EAAW,KACjB,QAAS,EAAW,QACpB,KAAM,EAAW,KACjB,WAAY,KAAK,aAAa,WAC9B,IAAK,KAAK,aAAa,IACxB,CACF,CACD,CACE,MAAO,QACR,CACF,CAGD,KAAK,oBAAoB,EAAM,CAI7B,EAAW,OAAS,UACnB,EAAW,SAAS,SAAS,aAAa,EACzC,EAAW,SAAS,SAAS,SAAS,EACtC,KAAK,aAAa,aAAe,EAAY,SAEvB,CAAC,KAAK,wBAC9B,KAAK,UACH,kEACD,CACD,KAAK,mBAAmB,EAGxB,KAAK,SAAS"}
@@ -1,8 +1 @@
1
- //#region \0rolldown/runtime.js
2
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, { get: (a, b) => (typeof require !== "undefined" ? require : a)[b] }) : x)(function(x) {
3
- if (typeof require !== "undefined") return require.apply(this, arguments);
4
- throw Error("Calling `require` for \"" + x + "\" in an environment that doesn't expose the `require` function. See https://rolldown.rs/in-depth/bundling-cjs#require-external-modules for more details.");
5
- });
6
-
7
- //#endregion
8
- export { __require };
1
+ var e=(e=>typeof require<`u`?require:typeof Proxy<`u`?new Proxy(e,{get:(e,t)=>(typeof require<`u`?require:e)[t]}):e)(function(e){if(typeof require<`u`)return require.apply(this,arguments);throw Error('Calling `require` for "'+e+"\" in an environment that doesn't expose the `require` function. See https://rolldown.rs/in-depth/bundling-cjs#require-external-modules for more details.")});export{e as __require};
@@ -1,97 +1,2 @@
1
- import { basename, dirname, join, relative, resolve, sep } from "node:path";
2
- import { fileURLToPath } from "node:url";
3
- import { existsSync, readFileSync } from "node:fs";
4
-
5
- //#region \0utils:asset
6
- const hereDirname = () => {
7
- try {
8
- return dirname(fileURLToPath(import.meta.url));
9
- } catch {
10
- return typeof __dirname !== "undefined" ? __dirname : process.cwd();
11
- }
12
- };
13
- const findDistRoot = (startDir) => {
14
- let dir = startDir;
15
- for (let i = 0; i < 12; i++) {
16
- if (basename(dir) === "dist") return dir;
17
- const parent = resolve(dir, "..");
18
- if (parent === dir) break;
19
- dir = parent;
20
- }
21
- return null;
22
- };
23
- const normalizeFrameFile = (file) => {
24
- if (!file) return null;
25
- try {
26
- if (file.startsWith("file://")) return fileURLToPath(file);
27
- } catch {}
28
- return file;
29
- };
30
- /**
31
- * Returns the directory of the *caller* module that invoked readAsset.
32
- * Prefers non-virtual frames; falls back to the first real frame.
33
- */
34
- const getCallerDir = () => {
35
- const prev = Error.prepareStackTrace;
36
- try {
37
- Error.prepareStackTrace = (_, structured) => structured;
38
- const err = /* @__PURE__ */ new Error();
39
- Error.captureStackTrace(err, getCallerDir);
40
- /** @type {import('node:vm').CallSite[]} */
41
- const frames = err.stack || [];
42
- const isVirtualPath = (p) => p.includes(`${sep}_virtual${sep}`) || p.includes("/_virtual/");
43
- for (const frame of frames) {
44
- const file = normalizeFrameFile(typeof frame.getFileName === "function" ? frame.getFileName() : null);
45
- if (!file) continue;
46
- if (file.includes("node:internal") || file.includes(`${sep}internal${sep}modules${sep}`)) continue;
47
- if (!isVirtualPath(file)) return dirname(file);
48
- }
49
- for (const frame of frames) {
50
- const file = normalizeFrameFile(typeof frame.getFileName === "function" ? frame.getFileName() : null);
51
- if (file) return dirname(file);
52
- }
53
- } catch {} finally {
54
- Error.prepareStackTrace = prev;
55
- }
56
- return hereDirname();
57
- };
58
- /**
59
- * Read an asset copied from src/** to dist/assets/**.
60
- * - './' or '../' is resolved relative to the *caller module's* emitted directory.
61
- * - otherwise, treat as src-relative.
62
- *
63
- * @param {string} relPath - e.g. './PROMPT.md' or 'utils/AI/askDocQuestion/embeddings/<fileKey>.json'
64
- * @param {BufferEncoding} [encoding='utf8']
65
- */
66
- const readAsset = (relPath, encoding = "utf8") => {
67
- const here = hereDirname();
68
- const distRoot = findDistRoot(here) ?? resolve(here, "..", "..", "dist");
69
- const assetsRoot = join(distRoot, "assets");
70
- const tried = [];
71
- /**
72
- * Transform dist/(esm|cjs)/... and _virtual/ prefix to clean subpath (Windows-safe)
73
- */
74
- const callerSubpath = relative(distRoot, getCallerDir()).split("\\").join("/").replace(/^(?:dist\/)?(?:esm|cjs)\//, "").replace(/^_virtual\//, "");
75
- if (relPath.startsWith("./") || relPath.startsWith("../")) {
76
- const fromCallerAbs = resolve(assetsRoot, callerSubpath, relPath);
77
- tried.push(fromCallerAbs);
78
- if (existsSync(fromCallerAbs)) return readFileSync(fromCallerAbs, encoding);
79
- }
80
- const directPath = join(assetsRoot, relPath);
81
- tried.push(directPath);
82
- if (existsSync(directPath)) return readFileSync(directPath, encoding);
83
- if (callerSubpath) {
84
- const nested = join(assetsRoot, callerSubpath, relPath);
85
- tried.push(nested);
86
- if (existsSync(nested)) return readFileSync(nested, encoding);
87
- }
88
- const msg = [
89
- "readAsset: file not found.",
90
- "Searched:",
91
- ...tried.map((p) => `- ${p}`)
92
- ].join("\n");
93
- throw new Error(msg);
94
- };
95
-
96
- //#endregion
97
- export { readAsset };
1
+ import{basename as e,dirname as t,join as n,relative as r,resolve as i,sep as a}from"node:path";import{fileURLToPath as o}from"node:url";import{existsSync as s,readFileSync as c}from"node:fs";const l=()=>{try{return t(o(import.meta.url))}catch{return typeof __dirname<`u`?__dirname:process.cwd()}},u=t=>{let n=t;for(let t=0;t<12;t++){if(e(n)===`dist`)return n;let t=i(n,`..`);if(t===n)break;n=t}return null},d=e=>{if(!e)return null;try{if(e.startsWith(`file://`))return o(e)}catch{}return e},f=()=>{let e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;let e=Error();Error.captureStackTrace(e,f);let n=e.stack||[],r=e=>e.includes(`${a}_virtual${a}`)||e.includes(`/_virtual/`);for(let e of n){let n=d(typeof e.getFileName==`function`?e.getFileName():null);if(n&&!(n.includes(`node:internal`)||n.includes(`${a}internal${a}modules${a}`))&&!r(n))return t(n)}for(let e of n){let n=d(typeof e.getFileName==`function`?e.getFileName():null);if(n)return t(n)}}catch{}finally{Error.prepareStackTrace=e}return l()},p=(e,t=`utf8`)=>{let a=l(),o=u(a)??i(a,`..`,`..`,`dist`),d=n(o,`assets`),p=[],m=r(o,f()).split(`\\`).join(`/`).replace(/^(?:dist\/)?(?:esm|cjs)\//,``).replace(/^_virtual\//,``);if(e.startsWith(`./`)||e.startsWith(`../`)){let n=i(d,m,e);if(p.push(n),s(n))return c(n,t)}let h=n(d,e);if(p.push(h),s(h))return c(h,t);if(m){let r=n(d,m,e);if(p.push(r),s(r))return c(r,t)}let g=[`readAsset: file not found.`,`Searched:`,...p.map(e=>`- ${e}`)].join(`
2
+ `);throw Error(g)};export{p as readAsset};
@@ -1,57 +1,4 @@
1
- import { openBrowser } from "../utils/openBrowser.mjs";
2
- import { ANSIColors, colorize, colorizePath, getAppLogger, getConfiguration } from "@intlayer/config";
3
- import { URL } from "node:url";
4
- import http from "node:http";
5
-
6
- //#region src/auth/login.ts
7
- const login = async (options) => {
8
- const configuration = getConfiguration(options.configOptions);
9
- const logger = getAppLogger(configuration);
10
- const cmsUrl = options.cmsUrl ?? configuration.editor.cmsURL;
11
- return new Promise((resolve) => {
12
- const server = http.createServer((req, res) => {
13
- const url = new URL(req.url ?? "", `http://${req.headers.host}`);
14
- res.setHeader("Access-Control-Allow-Origin", "*");
15
- res.setHeader("Access-Control-Allow-Methods", "GET, OPTIONS");
16
- res.setHeader("Access-Control-Allow-Headers", "Content-Type");
17
- if (req.method === "OPTIONS") {
18
- res.writeHead(204);
19
- res.end();
20
- return;
21
- }
22
- if (url.pathname === "/callback") {
23
- const clientId = url.searchParams.get("clientId");
24
- const clientSecret = url.searchParams.get("clientSecret");
25
- if (clientId && clientSecret) {
26
- logger("");
27
- logger("Log in successful. Client ID and Client Secret received.");
28
- logger("");
29
- logger([
30
- "1. Insert the Client ID and Client Secret in your",
31
- colorizePath(".env"),
32
- "file:"
33
- ]);
34
- logger(colorize("--------------------------------", ANSIColors.GREY_DARK));
35
- logger([colorize("INTLAYER_CLIENT_ID=", ANSIColors.GREY_LIGHT), colorize(clientId, ANSIColors.BLUE)].join(""));
36
- logger([colorize("INTLAYER_CLIENT_SECRET=", ANSIColors.GREY_LIGHT), colorize(clientSecret, ANSIColors.BLUE)].join(""));
37
- logger(colorize("--------------------------------", ANSIColors.GREY_DARK));
38
- logger("");
39
- logger("2. Insert in your Intlayer configuration file:");
40
- logger(colorize("--------------------------------", ANSIColors.GREY_DARK));
41
- [
42
- `${ANSIColors.GREY_LIGHT}{`,
43
- ` editor: {`,
44
- ` cmsURL: '${colorizePath(cmsUrl, void 0, ANSIColors.GREY_LIGHT)}',`,
45
- ` clientId: '${colorize("process.env.INTLAYER_CLIENT_ID", ANSIColors.BLUE, ANSIColors.GREY_LIGHT)}',`,
46
- ` clientSecret: '${colorize("process.env.INTLAYER_CLIENT_SECRET", ANSIColors.BLUE, ANSIColors.GREY_LIGHT)}',`,
47
- ` },`,
48
- `}`
49
- ].forEach((line) => {
50
- logger(line);
51
- });
52
- logger(colorize("--------------------------------", ANSIColors.GREY_DARK));
53
- res.writeHead(200, { "Content-Type": "text/html" });
54
- res.end(`
1
+ import{openBrowser as e}from"../utils/openBrowser.mjs";import{getConfiguration as t}from"@intlayer/config/node";import{ANSIColors as n,colorize as r,colorizePath as i,getAppLogger as a}from"@intlayer/config/logger";import{URL as o}from"node:url";import s from"node:http";const c=async c=>{let l=t(c.configOptions),u=a(l),d=c.cmsUrl??l.editor.cmsURL;return new Promise(t=>{let a=s.createServer((e,s)=>{let c=new o(e.url??``,`http://${e.headers.host}`);if(s.setHeader(`Access-Control-Allow-Origin`,`*`),s.setHeader(`Access-Control-Allow-Methods`,`GET, OPTIONS`),s.setHeader(`Access-Control-Allow-Headers`,`Content-Type`),e.method===`OPTIONS`){s.writeHead(204),s.end();return}if(c.pathname===`/callback`){let e=c.searchParams.get(`clientId`),o=c.searchParams.get(`clientSecret`);e&&o?(u(``),u(`Log in successful. Client ID and Client Secret received.`),u(``),u([`1. Insert the Client ID and Client Secret in your`,i(`.env`),`file:`]),u(r(`--------------------------------`,n.GREY_DARK)),u([r(`INTLAYER_CLIENT_ID=`,n.GREY_LIGHT),r(e,n.BLUE)].join(``)),u([r(`INTLAYER_CLIENT_SECRET=`,n.GREY_LIGHT),r(o,n.BLUE)].join(``)),u(r(`--------------------------------`,n.GREY_DARK)),u(``),u(`2. Insert in your Intlayer configuration file:`),u(r(`--------------------------------`,n.GREY_DARK)),[`${n.GREY_LIGHT}{`,` editor: {`,` cmsURL: '${i(d,void 0,n.GREY_LIGHT)}',`,` clientId: '${r(`process.env.INTLAYER_CLIENT_ID`,n.BLUE,n.GREY_LIGHT)}',`,` clientSecret: '${r(`process.env.INTLAYER_CLIENT_SECRET`,n.BLUE,n.GREY_LIGHT)}',`,` },`,`}`].forEach(e=>{u(e)}),u(r(`--------------------------------`,n.GREY_DARK)),s.writeHead(200,{"Content-Type":`text/html`}),s.end(`
55
2
  <!DOCTYPE html>
56
3
  <html lang="en" data-theme="dark">
57
4
  <head>
@@ -123,32 +70,5 @@ const login = async (options) => {
123
70
  <\/script>
124
71
  </body>
125
72
  </html>
126
- `);
127
- server.close(() => {
128
- resolve();
129
- process.exit(0);
130
- });
131
- } else {
132
- res.writeHead(400, { "Content-Type": "text/plain" });
133
- res.end("Missing parameters");
134
- }
135
- } else {
136
- res.writeHead(404, { "Content-Type": "text/plain" });
137
- res.end("Not found");
138
- }
139
- });
140
- server.listen(0, () => {
141
- const address = server.address();
142
- const port = typeof address === "object" && address ? address.port : 0;
143
- const state = Math.random().toString(36).substring(7);
144
- const loginUrl = `${cmsUrl ?? process.env.INTLAYER_SITE_URL ?? "http://localhost:3000"}/en/auth/cli-login?port=${port}&state=${state}`;
145
- logger("Opening browser for login...");
146
- logger(`If browser does not open, visit: ${colorizePath(loginUrl)}`);
147
- openBrowser(loginUrl);
148
- });
149
- });
150
- };
151
-
152
- //#endregion
153
- export { login };
73
+ `),a.close(()=>{t(),process.exit(0)})):(s.writeHead(400,{"Content-Type":`text/plain`}),s.end(`Missing parameters`))}else s.writeHead(404,{"Content-Type":`text/plain`}),s.end(`Not found`)});a.listen(0,()=>{let t=a.address(),n=typeof t==`object`&&t?t.port:0,r=Math.random().toString(36).substring(7),o=`${d??process.env.INTLAYER_SITE_URL??`http://localhost:3000`}/en/auth/cli-login?port=${n}&state=${r}`;u(`Opening browser for login...`),u(`If browser does not open, visit: ${i(o)}`),e(o)})})};export{c as login};
154
74
  //# sourceMappingURL=login.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"login.mjs","names":[],"sources":["../../../src/auth/login.ts"],"sourcesContent":["import http from 'node:http';\nimport { URL } from 'node:url';\nimport type { GetConfigurationOptions } from '@intlayer/config';\nimport {\n ANSIColors,\n colorize,\n colorizePath,\n getAppLogger,\n getConfiguration,\n} from '@intlayer/config';\nimport { openBrowser } from '../utils/openBrowser';\n\ntype LoginOptions = {\n cmsUrl?: string;\n configOptions?: GetConfigurationOptions;\n};\n\nexport const login = async (options: LoginOptions) => {\n const configuration = getConfiguration(options.configOptions);\n const logger = getAppLogger(configuration);\n\n const cmsUrl = options.cmsUrl ?? configuration.editor.cmsURL;\n\n return new Promise<void>((resolve) => {\n const server = http.createServer((req, res) => {\n const url = new URL(req.url ?? '', `http://${req.headers.host}`);\n\n // Set CORS headers\n res.setHeader('Access-Control-Allow-Origin', '*');\n res.setHeader('Access-Control-Allow-Methods', 'GET, OPTIONS');\n res.setHeader('Access-Control-Allow-Headers', 'Content-Type');\n\n if (req.method === 'OPTIONS') {\n res.writeHead(204);\n res.end();\n return;\n }\n\n if (url.pathname === '/callback') {\n const clientId = url.searchParams.get('clientId');\n const clientSecret = url.searchParams.get('clientSecret');\n\n if (clientId && clientSecret) {\n logger('');\n logger('Log in successful. Client ID and Client Secret received.');\n\n logger('');\n logger([\n '1. Insert the Client ID and Client Secret in your',\n colorizePath('.env'),\n 'file:',\n ]);\n logger(\n colorize('--------------------------------', ANSIColors.GREY_DARK)\n );\n logger(\n [\n colorize('INTLAYER_CLIENT_ID=', ANSIColors.GREY_LIGHT),\n colorize(clientId, ANSIColors.BLUE),\n ].join('')\n );\n logger(\n [\n colorize('INTLAYER_CLIENT_SECRET=', ANSIColors.GREY_LIGHT),\n colorize(clientSecret, ANSIColors.BLUE),\n ].join('')\n );\n logger(\n colorize('--------------------------------', ANSIColors.GREY_DARK)\n );\n logger('');\n logger('2. Insert in your Intlayer configuration file:');\n logger(\n colorize('--------------------------------', ANSIColors.GREY_DARK)\n );\n [\n `${ANSIColors.GREY_LIGHT}{`,\n ` editor: {`,\n ` cmsURL: '${colorizePath(cmsUrl, undefined, ANSIColors.GREY_LIGHT)}',`,\n ` clientId: '${colorize('process.env.INTLAYER_CLIENT_ID', ANSIColors.BLUE, ANSIColors.GREY_LIGHT)}',`,\n ` clientSecret: '${colorize('process.env.INTLAYER_CLIENT_SECRET', ANSIColors.BLUE, ANSIColors.GREY_LIGHT)}',`,\n ` },`,\n `}`,\n ].forEach((line) => {\n logger(line);\n });\n logger(\n colorize('--------------------------------', ANSIColors.GREY_DARK)\n );\n\n res.writeHead(200, { 'Content-Type': 'text/html' });\n res.end(`\n <!DOCTYPE html>\n <html lang=\"en\" data-theme=\"dark\">\n <head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Intlayer CLI Login</title>\n <style>\n :root {\n --color-background: rgba(23, 23, 23);\n --color-card: rgba(39, 39, 39);\n --color-text: rgba(255, 245, 237);\n --color-neutral: rgba(93, 93, 93);\n --font-sans: \"Inter\", -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;\n }\n \n * {\n box-sizing: border-box;\n }\n \n body {\n font-family: var(--font-sans);\n display: flex;\n align-items: center;\n justify-content: center;\n min-height: 100vh;\n margin: 0;\n padding: 1rem;\n background-color: var(--color-background);\n color: var(--color-text);\n }\n \n .container {\n text-align: center;\n padding: 2rem;\n border-radius: 1rem;\n background-color: var(--color-card);\n box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);\n max-width: 400px;\n width: 100%;\n }\n \n h1 {\n margin: 0 0 1rem 0;\n font-size: 1.5rem;\n font-weight: 700;\n color: var(--color-text);\n }\n \n p {\n color: var(--color-neutral);\n margin: 0 0 1.5rem 0;\n line-height: 1.5;\n }\n </style>\n </head>\n <body>\n <div class=\"container\">\n <h1>Login Successful</h1>\n <p>You have successfully logged in to Intlayer CLI. You can now close this tab and return to your terminal.</p>\n </div>\n <script>\n // Attempt to close the window\n window.close();\n \n // Fallback: if window.close() doesn't work, show a message\n setTimeout(() => {\n window.close();\n }, 1000);\n </script>\n </body>\n </html>\n `);\n\n server.close(() => {\n resolve();\n process.exit(0);\n });\n } else {\n res.writeHead(400, { 'Content-Type': 'text/plain' });\n res.end('Missing parameters');\n }\n } else {\n res.writeHead(404, { 'Content-Type': 'text/plain' });\n res.end('Not found');\n }\n });\n\n server.listen(0, () => {\n const address = server.address();\n const port = typeof address === 'object' && address ? address.port : 0;\n const state = Math.random().toString(36).substring(7);\n\n const websiteUrl =\n cmsUrl ?? process.env.INTLAYER_SITE_URL ?? 'http://localhost:3000';\n const loginUrl = `${websiteUrl}/en/auth/cli-login?port=${port}&state=${state}`;\n\n logger('Opening browser for login...');\n logger(`If browser does not open, visit: ${colorizePath(loginUrl)}`);\n\n openBrowser(loginUrl);\n });\n });\n};\n"],"mappings":";;;;;;AAiBA,MAAa,QAAQ,OAAO,YAA0B;CACpD,MAAM,gBAAgB,iBAAiB,QAAQ,cAAc;CAC7D,MAAM,SAAS,aAAa,cAAc;CAE1C,MAAM,SAAS,QAAQ,UAAU,cAAc,OAAO;AAEtD,QAAO,IAAI,SAAe,YAAY;EACpC,MAAM,SAAS,KAAK,cAAc,KAAK,QAAQ;GAC7C,MAAM,MAAM,IAAI,IAAI,IAAI,OAAO,IAAI,UAAU,IAAI,QAAQ,OAAO;AAGhE,OAAI,UAAU,+BAA+B,IAAI;AACjD,OAAI,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eAAS;AACT,cAAQ,KAAK,EAAE;OACf;WACG;AACL,SAAI,UAAU,KAAK,EAAE,gBAAgB,cAAc,CAAC;AACpD,SAAI,IAAI,qBAAqB;;UAE1B;AACL,QAAI,UAAU,KAAK,EAAE,gBAAgB,cAAc,CAAC;AACpD,QAAI,IAAI,YAAY;;IAEtB;AAEF,SAAO,OAAO,SAAS;GACrB,MAAM,UAAU,OAAO,SAAS;GAChC,MAAM,OAAO,OAAO,YAAY,YAAY,UAAU,QAAQ,OAAO;GACrE,MAAM,QAAQ,KAAK,QAAQ,CAAC,SAAS,GAAG,CAAC,UAAU,EAAE;GAIrD,MAAM,WAAW,GADf,UAAU,QAAQ,IAAI,qBAAqB,wBACd,0BAA0B,KAAK,SAAS;AAEvE,UAAO,+BAA+B;AACtC,UAAO,oCAAoC,aAAa,SAAS,GAAG;AAEpE,eAAY,SAAS;IACrB;GACF"}
1
+ {"version":3,"file":"login.mjs","names":[],"sources":["../../../src/auth/login.ts"],"sourcesContent":["import http from 'node:http';\nimport { URL } from 'node:url';\nimport {\n ANSIColors,\n colorize,\n colorizePath,\n getAppLogger,\n} from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport { openBrowser } from '../utils/openBrowser';\n\ntype LoginOptions = {\n cmsUrl?: string;\n configOptions?: GetConfigurationOptions;\n};\n\nexport const login = async (options: LoginOptions) => {\n const configuration = getConfiguration(options.configOptions);\n const logger = getAppLogger(configuration);\n\n const cmsUrl = options.cmsUrl ?? configuration.editor.cmsURL;\n\n return new Promise<void>((resolve) => {\n const server = http.createServer((req, res) => {\n const url = new URL(req.url ?? '', `http://${req.headers.host}`);\n\n // Set CORS headers\n res.setHeader('Access-Control-Allow-Origin', '*');\n res.setHeader('Access-Control-Allow-Methods', 'GET, OPTIONS');\n res.setHeader('Access-Control-Allow-Headers', 'Content-Type');\n\n if (req.method === 'OPTIONS') {\n res.writeHead(204);\n res.end();\n return;\n }\n\n if (url.pathname === '/callback') {\n const clientId = url.searchParams.get('clientId');\n const clientSecret = url.searchParams.get('clientSecret');\n\n if (clientId && clientSecret) {\n logger('');\n logger('Log in successful. Client ID and Client Secret received.');\n\n logger('');\n logger([\n '1. Insert the Client ID and Client Secret in your',\n colorizePath('.env'),\n 'file:',\n ]);\n logger(\n colorize('--------------------------------', ANSIColors.GREY_DARK)\n );\n logger(\n [\n colorize('INTLAYER_CLIENT_ID=', ANSIColors.GREY_LIGHT),\n colorize(clientId, ANSIColors.BLUE),\n ].join('')\n );\n logger(\n [\n colorize('INTLAYER_CLIENT_SECRET=', ANSIColors.GREY_LIGHT),\n colorize(clientSecret, ANSIColors.BLUE),\n ].join('')\n );\n logger(\n colorize('--------------------------------', ANSIColors.GREY_DARK)\n );\n logger('');\n logger('2. Insert in your Intlayer configuration file:');\n logger(\n colorize('--------------------------------', ANSIColors.GREY_DARK)\n );\n [\n `${ANSIColors.GREY_LIGHT}{`,\n ` editor: {`,\n ` cmsURL: '${colorizePath(cmsUrl, undefined, ANSIColors.GREY_LIGHT)}',`,\n ` clientId: '${colorize('process.env.INTLAYER_CLIENT_ID', ANSIColors.BLUE, ANSIColors.GREY_LIGHT)}',`,\n ` clientSecret: '${colorize('process.env.INTLAYER_CLIENT_SECRET', ANSIColors.BLUE, ANSIColors.GREY_LIGHT)}',`,\n ` },`,\n `}`,\n ].forEach((line) => {\n logger(line);\n });\n logger(\n colorize('--------------------------------', ANSIColors.GREY_DARK)\n );\n\n res.writeHead(200, { 'Content-Type': 'text/html' });\n res.end(`\n <!DOCTYPE html>\n <html lang=\"en\" data-theme=\"dark\">\n <head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Intlayer CLI Login</title>\n <style>\n :root {\n --color-background: rgba(23, 23, 23);\n --color-card: rgba(39, 39, 39);\n --color-text: rgba(255, 245, 237);\n --color-neutral: rgba(93, 93, 93);\n --font-sans: \"Inter\", -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;\n }\n \n * {\n box-sizing: border-box;\n }\n \n body {\n font-family: var(--font-sans);\n display: flex;\n align-items: center;\n justify-content: center;\n min-height: 100vh;\n margin: 0;\n padding: 1rem;\n background-color: var(--color-background);\n color: var(--color-text);\n }\n \n .container {\n text-align: center;\n padding: 2rem;\n border-radius: 1rem;\n background-color: var(--color-card);\n box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);\n max-width: 400px;\n width: 100%;\n }\n \n h1 {\n margin: 0 0 1rem 0;\n font-size: 1.5rem;\n font-weight: 700;\n color: var(--color-text);\n }\n \n p {\n color: var(--color-neutral);\n margin: 0 0 1.5rem 0;\n line-height: 1.5;\n }\n </style>\n </head>\n <body>\n <div class=\"container\">\n <h1>Login Successful</h1>\n <p>You have successfully logged in to Intlayer CLI. You can now close this tab and return to your terminal.</p>\n </div>\n <script>\n // Attempt to close the window\n window.close();\n \n // Fallback: if window.close() doesn't work, show a message\n setTimeout(() => {\n window.close();\n }, 1000);\n </script>\n </body>\n </html>\n `);\n\n server.close(() => {\n resolve();\n process.exit(0);\n });\n } else {\n res.writeHead(400, { 'Content-Type': 'text/plain' });\n res.end('Missing parameters');\n }\n } else {\n res.writeHead(404, { 'Content-Type': 'text/plain' });\n res.end('Not found');\n }\n });\n\n server.listen(0, () => {\n const address = server.address();\n const port = typeof address === 'object' && address ? address.port : 0;\n const state = Math.random().toString(36).substring(7);\n\n const websiteUrl =\n cmsUrl ?? process.env.INTLAYER_SITE_URL ?? 'http://localhost:3000';\n const loginUrl = `${websiteUrl}/en/auth/cli-login?port=${port}&state=${state}`;\n\n logger('Opening browser for login...');\n logger(`If browser does not open, visit: ${colorizePath(loginUrl)}`);\n\n openBrowser(loginUrl);\n });\n });\n};\n"],"mappings":"+QAmBA,MAAa,EAAQ,KAAO,IAA0B,CACpD,IAAM,EAAgB,EAAiB,EAAQ,cAAc,CACvD,EAAS,EAAa,EAAc,CAEpC,EAAS,EAAQ,QAAU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AU,CACnE,CAED,EAAI,UAAU,IAAK,CAAE,eAAgB,YAAa,CAAC,CACnD,EAAI,IAAI;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;YAwEN,CAEF,EAAO,UAAY,CACjB,GAAS,CACT,QAAQ,KAAK,EAAE,EACf,GAEF,EAAI,UAAU,IAAK,CAAE,eAAgB,aAAc,CAAC,CACpD,EAAI,IAAI,qBAAqB,OAG/B,EAAI,UAAU,IAAK,CAAE,eAAgB,aAAc,CAAC,CACpD,EAAI,IAAI,YAAY,EAEtB,CAEF,EAAO,OAAO,MAAS,CACrB,IAAM,EAAU,EAAO,SAAS,CAC1B,EAAO,OAAO,GAAY,UAAY,EAAU,EAAQ,KAAO,EAC/D,EAAQ,KAAK,QAAQ,CAAC,SAAS,GAAG,CAAC,UAAU,EAAE,CAI/C,EAAW,GADf,GAAU,QAAQ,IAAI,mBAAqB,wBACd,0BAA0B,EAAK,SAAS,IAEvE,EAAO,+BAA+B,CACtC,EAAO,oCAAoC,EAAa,EAAS,GAAG,CAEpE,EAAY,EAAS,EACrB,EACF"}
@@ -1,26 +1,2 @@
1
- import { buildAndWatchIntlayer, runParallel } from "@intlayer/chokidar";
2
- import { getConfiguration } from "@intlayer/config";
3
-
4
- //#region src/build.ts
5
- /**
6
- * Get locales dictionaries .content.{json|ts|tsx|js|jsx|mjs|cjs} and build the JSON dictionaries in the .intlayer directory.
7
- * Watch mode available to get the change in the .content.{json|ts|tsx|js|jsx|mjs|cjs}
8
- */
9
- const build = async (options) => {
10
- const config = getConfiguration(options?.configOptions);
11
- let parallelProcess = null;
12
- if (options?.with) {
13
- parallelProcess = runParallel(options.with);
14
- parallelProcess.result.catch(() => {});
15
- }
16
- await buildAndWatchIntlayer({
17
- persistent: options?.watch ?? false,
18
- skipPrepare: options?.skipPrepare ?? false,
19
- configuration: config
20
- });
21
- if (!options?.watch && parallelProcess) parallelProcess.kill();
22
- };
23
-
24
- //#endregion
25
- export { build };
1
+ import{runParallel as e}from"@intlayer/chokidar/utils";import{buildAndWatchIntlayer as t}from"@intlayer/chokidar/watcher";import{getConfiguration as n}from"@intlayer/config/node";const r=async r=>{let i=n(r?.configOptions),a=null;r?.with&&(a=e(r.with),a.result.catch(()=>{})),await t({persistent:r?.watch??!1,skipPrepare:r?.skipPrepare??!1,configuration:i}),!r?.watch&&a&&a.kill()};export{r as build};
26
2
  //# sourceMappingURL=build.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"build.mjs","names":[],"sources":["../../src/build.ts"],"sourcesContent":["import {\n buildAndWatchIntlayer,\n type ParallelHandle,\n runParallel,\n} from '@intlayer/chokidar';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config';\n\ntype BuildOptions = {\n watch?: boolean;\n skipPrepare?: boolean;\n with?: string | string[];\n configOptions?: GetConfigurationOptions;\n};\n\n/**\n * Get locales dictionaries .content.{json|ts|tsx|js|jsx|mjs|cjs} and build the JSON dictionaries in the .intlayer directory.\n * Watch mode available to get the change in the .content.{json|ts|tsx|js|jsx|mjs|cjs}\n */\nexport const build = async (options?: BuildOptions) => {\n const config = getConfiguration(options?.configOptions);\n let parallelProcess: ParallelHandle | null = null;\n\n if (options?.with) {\n parallelProcess = runParallel(options.with);\n // Handle the promise to avoid unhandled rejection\n parallelProcess.result.catch(() => {\n // Parallel process failed or was terminated\n });\n }\n\n await buildAndWatchIntlayer({\n persistent: options?.watch ?? false,\n skipPrepare: options?.skipPrepare ?? false,\n configuration: config,\n });\n\n if (!options?.watch && parallelProcess) {\n parallelProcess.kill();\n }\n};\n"],"mappings":";;;;;;;;AAqBA,MAAa,QAAQ,OAAO,YAA2B;CACrD,MAAM,SAAS,iBAAiB,SAAS,cAAc;CACvD,IAAI,kBAAyC;AAE7C,KAAI,SAAS,MAAM;AACjB,oBAAkB,YAAY,QAAQ,KAAK;AAE3C,kBAAgB,OAAO,YAAY,GAEjC;;AAGJ,OAAM,sBAAsB;EAC1B,YAAY,SAAS,SAAS;EAC9B,aAAa,SAAS,eAAe;EACrC,eAAe;EAChB,CAAC;AAEF,KAAI,CAAC,SAAS,SAAS,gBACrB,iBAAgB,MAAM"}
1
+ {"version":3,"file":"build.mjs","names":[],"sources":["../../src/build.ts"],"sourcesContent":["import { type ParallelHandle, runParallel } from '@intlayer/chokidar/utils';\nimport { buildAndWatchIntlayer } from '@intlayer/chokidar/watcher';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\n\ntype BuildOptions = {\n watch?: boolean;\n skipPrepare?: boolean;\n with?: string | string[];\n configOptions?: GetConfigurationOptions;\n};\n\n/**\n * Get locales dictionaries .content.{json|ts|tsx|js|jsx|mjs|cjs} and build the JSON dictionaries in the .intlayer directory.\n * Watch mode available to get the change in the .content.{json|ts|tsx|js|jsx|mjs|cjs}\n */\nexport const build = async (options?: BuildOptions) => {\n const config = getConfiguration(options?.configOptions);\n let parallelProcess: ParallelHandle | null = null;\n\n if (options?.with) {\n parallelProcess = runParallel(options.with);\n // Handle the promise to avoid unhandled rejection\n parallelProcess.result.catch(() => {\n // Parallel process failed or was terminated\n });\n }\n\n await buildAndWatchIntlayer({\n persistent: options?.watch ?? false,\n skipPrepare: options?.skipPrepare ?? false,\n configuration: config,\n });\n\n if (!options?.watch && parallelProcess) {\n parallelProcess.kill();\n }\n};\n"],"mappings":"mLAkBA,MAAa,EAAQ,KAAO,IAA2B,CACrD,IAAM,EAAS,EAAiB,GAAS,cAAc,CACnD,EAAyC,KAEzC,GAAS,OACX,EAAkB,EAAY,EAAQ,KAAK,CAE3C,EAAgB,OAAO,UAAY,GAEjC,EAGJ,MAAM,EAAsB,CAC1B,WAAY,GAAS,OAAS,GAC9B,YAAa,GAAS,aAAe,GACrC,cAAe,EAChB,CAAC,CAEE,CAAC,GAAS,OAAS,GACrB,EAAgB,MAAM"}
package/dist/esm/ci.mjs CHANGED
@@ -1,72 +1,2 @@
1
- import { listProjects } from "@intlayer/chokidar";
2
- import { logger } from "@intlayer/config";
3
- import { spawnSync } from "node:child_process";
4
- import { normalize, resolve } from "node:path";
5
-
6
- //#region src/ci.ts
7
- const getPackageManagerCommand = () => {
8
- const userAgent = process.env.npm_config_user_agent;
9
- if (userAgent?.startsWith("bun")) return {
10
- command: "bun",
11
- args: ["intlayer"]
12
- };
13
- if (userAgent?.startsWith("pnpm")) return {
14
- command: "pnpm",
15
- args: ["exec", "intlayer"]
16
- };
17
- if (userAgent?.startsWith("yarn")) return {
18
- command: "yarn",
19
- args: ["run", "intlayer"]
20
- };
21
- return {
22
- command: "npx",
23
- args: ["intlayer"]
24
- };
25
- };
26
- const runCI = async (commands) => {
27
- const credentialsEnv = process.env.INTLAYER_PROJECT_CREDENTIALS;
28
- let credentials = {};
29
- if (credentialsEnv) try {
30
- credentials = JSON.parse(credentialsEnv);
31
- } catch {
32
- logger("INTLAYER_PROJECT_CREDENTIALS is not valid JSON. Proceeding without credentials.", { level: "warn" });
33
- }
34
- const cwd = process.cwd();
35
- const { projectsPath } = await listProjects();
36
- if (projectsPath.length === 0) {
37
- logger("No Intlayer projects found.", { level: "warn" });
38
- return;
39
- }
40
- const currentProject = projectsPath.find((p) => cwd === p);
41
- const projectsToRun = currentProject ? [currentProject] : projectsPath;
42
- const { command, args: pmArgs } = getPackageManagerCommand();
43
- const finalArgs = [...pmArgs, ...commands];
44
- logger(`CI: Using package manager: ${command}`, { level: "verbose" });
45
- if (currentProject) logger(`CI: Detected project context: ${currentProject}`, { level: "info" });
46
- else logger(`CI: No specific project context detected. Iterating over ${projectsToRun.length} discovered projects...`, { level: "info" });
47
- let hasError = false;
48
- for (const projectPath of projectsToRun) {
49
- const creds = Object.entries(credentials).find(([key]) => {
50
- return resolve(key) === projectPath || projectPath.endsWith(normalize(key));
51
- })?.[1];
52
- logger(`\nCI: Executing for ${projectPath}...`, { level: "info" });
53
- const envVars = { ...process.env };
54
- if (creds) {
55
- envVars.INTLAYER_CLIENT_ID = creds.clientId;
56
- envVars.INTLAYER_CLIENT_SECRET = creds.clientSecret;
57
- } else if (credentialsEnv) logger(`CI: No matching credentials found for ${projectPath} in INTLAYER_PROJECT_CREDENTIALS.`, { level: "verbose" });
58
- if (spawnSync(command, finalArgs, {
59
- cwd: projectPath,
60
- stdio: "inherit",
61
- env: envVars
62
- }).status !== 0) {
63
- logger(`CI: Failed for ${projectPath}`, { level: "error" });
64
- hasError = true;
65
- }
66
- }
67
- if (hasError) process.exit(1);
68
- };
69
-
70
- //#endregion
71
- export { runCI };
1
+ import{spawnSync as e}from"node:child_process";import{normalize as t,resolve as n}from"node:path";import{listProjects as r}from"@intlayer/chokidar/cli";import{logger as i}from"@intlayer/config/logger";const a=()=>{let e=process.env.npm_config_user_agent;return e?.startsWith(`bun`)?{command:`bun`,args:[`intlayer`]}:e?.startsWith(`pnpm`)?{command:`pnpm`,args:[`exec`,`intlayer`]}:e?.startsWith(`yarn`)?{command:`yarn`,args:[`run`,`intlayer`]}:{command:`npx`,args:[`intlayer`]}},o=async o=>{let s=process.env.INTLAYER_PROJECT_CREDENTIALS,c={};if(s)try{c=JSON.parse(s)}catch{i(`INTLAYER_PROJECT_CREDENTIALS is not valid JSON. Proceeding without credentials.`,{level:`warn`})}let l=process.cwd(),{projectsPath:u}=await r();if(u.length===0){i(`No Intlayer projects found.`,{level:`warn`});return}let d=u.find(e=>l===e),f=d?[d]:u,{command:p,args:m}=a(),h=[...m,...o];i(`CI: Using package manager: ${p}`,{level:`verbose`}),i(d?`CI: Detected project context: ${d}`:`CI: No specific project context detected. Iterating over ${f.length} discovered projects...`,{level:`info`});let g=!1;for(let r of f){let a=Object.entries(c).find(([e])=>n(e)===r||r.endsWith(t(e)))?.[1];i(`\nCI: Executing for ${r}...`,{level:`info`});let o={...process.env};a?(o.INTLAYER_CLIENT_ID=a.clientId,o.INTLAYER_CLIENT_SECRET=a.clientSecret):s&&i(`CI: No matching credentials found for ${r} in INTLAYER_PROJECT_CREDENTIALS.`,{level:`verbose`}),e(p,h,{cwd:r,stdio:`inherit`,env:o}).status!==0&&(i(`CI: Failed for ${r}`,{level:`error`}),g=!0)}g&&process.exit(1)};export{o as runCI};
72
2
  //# sourceMappingURL=ci.mjs.map