@intlayer/cli 6.1.6 → 7.0.0-canary.1

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 (287) hide show
  1. package/dist/cjs/IntlayerEventListener.cjs +187 -239
  2. package/dist/cjs/IntlayerEventListener.cjs.map +1 -1
  3. package/dist/cjs/_virtual/_utils_asset.cjs +104 -0
  4. package/dist/cjs/_virtual/rolldown_runtime.cjs +25 -0
  5. package/dist/cjs/build.cjs +23 -42
  6. package/dist/cjs/build.cjs.map +1 -1
  7. package/dist/cjs/cli.cjs +370 -431
  8. package/dist/cjs/cli.cjs.map +1 -1
  9. package/dist/cjs/config.cjs +10 -35
  10. package/dist/cjs/config.cjs.map +1 -1
  11. package/dist/cjs/editor.cjs +51 -66
  12. package/dist/cjs/editor.cjs.map +1 -1
  13. package/dist/cjs/fill/fill.cjs +73 -301
  14. package/dist/cjs/fill/fill.cjs.map +1 -1
  15. package/dist/cjs/fill/formatAutoFillData.cjs +48 -106
  16. package/dist/cjs/fill/formatAutoFillData.cjs.map +1 -1
  17. package/dist/cjs/fill/formatAutoFilledFilePath.cjs +27 -43
  18. package/dist/cjs/fill/formatAutoFilledFilePath.cjs.map +1 -1
  19. package/dist/cjs/fill/formatFillData.cjs +50 -0
  20. package/dist/cjs/fill/formatFillData.cjs.map +1 -0
  21. package/dist/cjs/fill/groupLimiter.cjs +42 -0
  22. package/dist/cjs/fill/groupLimiter.cjs.map +1 -0
  23. package/dist/cjs/fill/index.cjs +5 -25
  24. package/dist/cjs/fill/listTranslationsTasks.cjs +77 -0
  25. package/dist/cjs/fill/listTranslationsTasks.cjs.map +1 -0
  26. package/dist/cjs/fill/test-original-case.cjs +10 -0
  27. package/dist/cjs/fill/test-original-case.cjs.map +1 -0
  28. package/dist/cjs/fill/translateDictionary.cjs +148 -0
  29. package/dist/cjs/fill/translateDictionary.cjs.map +1 -0
  30. package/dist/cjs/fill/writeAutoFill.cjs +48 -0
  31. package/dist/cjs/fill/writeAutoFill.cjs.map +1 -0
  32. package/dist/cjs/fill/writeFill.cjs +50 -0
  33. package/dist/cjs/fill/writeFill.cjs.map +1 -0
  34. package/dist/cjs/getTargetDictionary.cjs +36 -76
  35. package/dist/cjs/getTargetDictionary.cjs.map +1 -1
  36. package/dist/cjs/index.cjs +31 -45
  37. package/dist/cjs/listContentDeclaration.cjs +36 -64
  38. package/dist/cjs/listContentDeclaration.cjs.map +1 -1
  39. package/dist/cjs/liveSync.cjs +146 -221
  40. package/dist/cjs/liveSync.cjs.map +1 -1
  41. package/dist/cjs/pull.cjs +132 -195
  42. package/dist/cjs/pull.cjs.map +1 -1
  43. package/dist/cjs/push/pullLog.cjs +101 -144
  44. package/dist/cjs/push/pullLog.cjs.map +1 -1
  45. package/dist/cjs/push/push.cjs +159 -249
  46. package/dist/cjs/push/push.cjs.map +1 -1
  47. package/dist/cjs/pushConfig.cjs +18 -45
  48. package/dist/cjs/pushConfig.cjs.map +1 -1
  49. package/dist/cjs/pushLog.cjs +87 -128
  50. package/dist/cjs/pushLog.cjs.map +1 -1
  51. package/dist/cjs/reviewDoc.cjs +183 -291
  52. package/dist/cjs/reviewDoc.cjs.map +1 -1
  53. package/dist/cjs/test/index.cjs +52 -91
  54. package/dist/cjs/test/index.cjs.map +1 -1
  55. package/dist/cjs/test/listMissingTranslations.cjs +35 -62
  56. package/dist/cjs/test/listMissingTranslations.cjs.map +1 -1
  57. package/dist/cjs/translateDoc.cjs +127 -221
  58. package/dist/cjs/translateDoc.cjs.map +1 -1
  59. package/dist/cjs/utils/calculateChunks.cjs +85 -115
  60. package/dist/cjs/utils/calculateChunks.cjs.map +1 -1
  61. package/dist/cjs/utils/checkAccess.cjs +33 -72
  62. package/dist/cjs/utils/checkAccess.cjs.map +1 -1
  63. package/dist/cjs/utils/checkFileModifiedRange.cjs +75 -91
  64. package/dist/cjs/utils/checkFileModifiedRange.cjs.map +1 -1
  65. package/dist/cjs/utils/checkLastUpdateTime.cjs +17 -30
  66. package/dist/cjs/utils/checkLastUpdateTime.cjs.map +1 -1
  67. package/dist/cjs/utils/chunkInference.cjs +28 -47
  68. package/dist/cjs/utils/chunkInference.cjs.map +1 -1
  69. package/dist/cjs/utils/fixChunkStartEndChars.cjs +23 -42
  70. package/dist/cjs/utils/fixChunkStartEndChars.cjs.map +1 -1
  71. package/dist/cjs/utils/formatTimeDiff.cjs +17 -43
  72. package/dist/cjs/utils/formatTimeDiff.cjs.map +1 -1
  73. package/dist/cjs/utils/getIsFileUpdatedRecently.cjs +13 -32
  74. package/dist/cjs/utils/getIsFileUpdatedRecently.cjs.map +1 -1
  75. package/dist/cjs/utils/getOutputFilePath.cjs +71 -86
  76. package/dist/cjs/utils/getOutputFilePath.cjs.map +1 -1
  77. package/dist/cjs/utils/getParentPackageJSON.cjs +19 -44
  78. package/dist/cjs/utils/getParentPackageJSON.cjs.map +1 -1
  79. package/dist/cjs/utils/listSpecialChars.cjs +49 -73
  80. package/dist/cjs/utils/listSpecialChars.cjs.map +1 -1
  81. package/dist/cjs/utils/mapChunksBetweenFiles.cjs +90 -132
  82. package/dist/cjs/utils/mapChunksBetweenFiles.cjs.map +1 -1
  83. package/dist/cjs/utils/reorderParagraphs.cjs +86 -118
  84. package/dist/cjs/utils/reorderParagraphs.cjs.map +1 -1
  85. package/dist/cjs/watch.cjs +21 -39
  86. package/dist/cjs/watch.cjs.map +1 -1
  87. package/dist/esm/IntlayerEventListener.mjs +178 -201
  88. package/dist/esm/IntlayerEventListener.mjs.map +1 -1
  89. package/dist/esm/_virtual/_utils_asset.mjs +100 -0
  90. package/dist/esm/_virtual/rolldown_runtime.mjs +8 -0
  91. package/dist/esm/build.mjs +20 -23
  92. package/dist/esm/build.mjs.map +1 -1
  93. package/dist/esm/cli.mjs +349 -380
  94. package/dist/esm/cli.mjs.map +1 -1
  95. package/dist/esm/config.mjs +8 -14
  96. package/dist/esm/config.mjs.map +1 -1
  97. package/dist/esm/editor.mjs +47 -41
  98. package/dist/esm/editor.mjs.map +1 -1
  99. package/dist/esm/fill/fill.mjs +68 -300
  100. package/dist/esm/fill/fill.mjs.map +1 -1
  101. package/dist/esm/fill/formatAutoFillData.mjs +47 -81
  102. package/dist/esm/fill/formatAutoFillData.mjs.map +1 -1
  103. package/dist/esm/fill/formatAutoFilledFilePath.mjs +25 -19
  104. package/dist/esm/fill/formatAutoFilledFilePath.mjs.map +1 -1
  105. package/dist/esm/fill/formatFillData.mjs +50 -0
  106. package/dist/esm/fill/formatFillData.mjs.map +1 -0
  107. package/dist/esm/fill/groupLimiter.mjs +40 -0
  108. package/dist/esm/fill/groupLimiter.mjs.map +1 -0
  109. package/dist/esm/fill/index.mjs +4 -3
  110. package/dist/esm/fill/listTranslationsTasks.mjs +70 -0
  111. package/dist/esm/fill/listTranslationsTasks.mjs.map +1 -0
  112. package/dist/esm/fill/test-original-case.mjs +10 -0
  113. package/dist/esm/fill/test-original-case.mjs.map +1 -0
  114. package/dist/esm/fill/translateDictionary.mjs +141 -0
  115. package/dist/esm/fill/translateDictionary.mjs.map +1 -0
  116. package/dist/esm/fill/writeAutoFill.mjs +44 -0
  117. package/dist/esm/fill/writeAutoFill.mjs.map +1 -0
  118. package/dist/esm/fill/writeFill.mjs +45 -0
  119. package/dist/esm/fill/writeFill.mjs.map +1 -0
  120. package/dist/esm/getTargetDictionary.mjs +27 -48
  121. package/dist/esm/getTargetDictionary.mjs.map +1 -1
  122. package/dist/esm/index.mjs +15 -13
  123. package/dist/esm/listContentDeclaration.mjs +28 -43
  124. package/dist/esm/listContentDeclaration.mjs.map +1 -1
  125. package/dist/esm/liveSync.mjs +135 -187
  126. package/dist/esm/liveSync.mjs.map +1 -1
  127. package/dist/esm/pull.mjs +125 -178
  128. package/dist/esm/pull.mjs.map +1 -1
  129. package/dist/esm/push/pullLog.mjs +99 -125
  130. package/dist/esm/push/pullLog.mjs.map +1 -1
  131. package/dist/esm/push/push.mjs +149 -221
  132. package/dist/esm/push/push.mjs.map +1 -1
  133. package/dist/esm/pushConfig.mjs +14 -23
  134. package/dist/esm/pushConfig.mjs.map +1 -1
  135. package/dist/esm/pushLog.mjs +85 -109
  136. package/dist/esm/pushLog.mjs.map +1 -1
  137. package/dist/esm/reviewDoc.mjs +167 -264
  138. package/dist/esm/reviewDoc.mjs.map +1 -1
  139. package/dist/esm/test/index.mjs +47 -73
  140. package/dist/esm/test/index.mjs.map +1 -1
  141. package/dist/esm/test/listMissingTranslations.mjs +30 -41
  142. package/dist/esm/test/listMissingTranslations.mjs.map +1 -1
  143. package/dist/esm/translateDoc.mjs +114 -193
  144. package/dist/esm/translateDoc.mjs.map +1 -1
  145. package/dist/esm/utils/calculateChunks.mjs +83 -91
  146. package/dist/esm/utils/calculateChunks.mjs.map +1 -1
  147. package/dist/esm/utils/checkAccess.mjs +28 -46
  148. package/dist/esm/utils/checkAccess.mjs.map +1 -1
  149. package/dist/esm/utils/checkFileModifiedRange.mjs +73 -65
  150. package/dist/esm/utils/checkFileModifiedRange.mjs.map +1 -1
  151. package/dist/esm/utils/checkLastUpdateTime.mjs +15 -6
  152. package/dist/esm/utils/checkLastUpdateTime.mjs.map +1 -1
  153. package/dist/esm/utils/chunkInference.mjs +24 -24
  154. package/dist/esm/utils/chunkInference.mjs.map +1 -1
  155. package/dist/esm/utils/fixChunkStartEndChars.mjs +22 -18
  156. package/dist/esm/utils/fixChunkStartEndChars.mjs.map +1 -1
  157. package/dist/esm/utils/formatTimeDiff.mjs +16 -19
  158. package/dist/esm/utils/formatTimeDiff.mjs.map +1 -1
  159. package/dist/esm/utils/getIsFileUpdatedRecently.mjs +11 -8
  160. package/dist/esm/utils/getIsFileUpdatedRecently.mjs.map +1 -1
  161. package/dist/esm/utils/getOutputFilePath.mjs +70 -62
  162. package/dist/esm/utils/getOutputFilePath.mjs.map +1 -1
  163. package/dist/esm/utils/getParentPackageJSON.mjs +16 -20
  164. package/dist/esm/utils/getParentPackageJSON.mjs.map +1 -1
  165. package/dist/esm/utils/listSpecialChars.mjs +48 -49
  166. package/dist/esm/utils/listSpecialChars.mjs.map +1 -1
  167. package/dist/esm/utils/mapChunksBetweenFiles.mjs +87 -107
  168. package/dist/esm/utils/mapChunksBetweenFiles.mjs.map +1 -1
  169. package/dist/esm/utils/reorderParagraphs.mjs +85 -93
  170. package/dist/esm/utils/reorderParagraphs.mjs.map +1 -1
  171. package/dist/esm/watch.mjs +17 -17
  172. package/dist/esm/watch.mjs.map +1 -1
  173. package/dist/types/IntlayerEventListener.d.ts +63 -59
  174. package/dist/types/IntlayerEventListener.d.ts.map +1 -1
  175. package/dist/types/build.d.ts +10 -7
  176. package/dist/types/build.d.ts.map +1 -1
  177. package/dist/types/cli.d.ts +13 -10
  178. package/dist/types/cli.d.ts.map +1 -1
  179. package/dist/types/config.d.ts +7 -4
  180. package/dist/types/config.d.ts.map +1 -1
  181. package/dist/types/editor.d.ts +6 -4
  182. package/dist/types/editor.d.ts.map +1 -1
  183. package/dist/types/fill/fill.d.ts +20 -14
  184. package/dist/types/fill/fill.d.ts.map +1 -1
  185. package/dist/types/fill/formatAutoFillData.d.ts +10 -7
  186. package/dist/types/fill/formatAutoFillData.d.ts.map +1 -1
  187. package/dist/types/fill/formatAutoFilledFilePath.d.ts +6 -2
  188. package/dist/types/fill/formatAutoFilledFilePath.d.ts.map +1 -1
  189. package/dist/types/fill/formatFillData.d.ts +12 -0
  190. package/dist/types/fill/formatFillData.d.ts.map +1 -0
  191. package/dist/types/fill/groupLimiter.d.ts +15 -0
  192. package/dist/types/fill/groupLimiter.d.ts.map +1 -0
  193. package/dist/types/fill/index.d.ts +3 -3
  194. package/dist/types/fill/listTranslationsTasks.d.ts +15 -0
  195. package/dist/types/fill/listTranslationsTasks.d.ts.map +1 -0
  196. package/dist/types/fill/test-original-case.d.ts +1 -0
  197. package/dist/types/fill/translateDictionary.d.ts +19 -0
  198. package/dist/types/fill/translateDictionary.d.ts.map +1 -0
  199. package/dist/types/fill/writeAutoFill.d.ts +7 -0
  200. package/dist/types/fill/writeAutoFill.d.ts.map +1 -0
  201. package/dist/types/fill/writeFill.d.ts +7 -0
  202. package/dist/types/fill/writeFill.d.ts.map +1 -0
  203. package/dist/types/getTargetDictionary.d.ts +17 -13
  204. package/dist/types/getTargetDictionary.d.ts.map +1 -1
  205. package/dist/types/index.d.ts +15 -14
  206. package/dist/types/listContentDeclaration.d.ts +10 -7
  207. package/dist/types/listContentDeclaration.d.ts.map +1 -1
  208. package/dist/types/liveSync.d.ts +8 -3
  209. package/dist/types/liveSync.d.ts.map +1 -1
  210. package/dist/types/pull.d.ts +9 -6
  211. package/dist/types/pull.d.ts.map +1 -1
  212. package/dist/types/push/pullLog.d.ts +25 -21
  213. package/dist/types/push/pullLog.d.ts.map +1 -1
  214. package/dist/types/push/push.d.ts +13 -9
  215. package/dist/types/push/push.d.ts.map +1 -1
  216. package/dist/types/pushConfig.d.ts +7 -4
  217. package/dist/types/pushConfig.d.ts.map +1 -1
  218. package/dist/types/pushLog.d.ts +23 -20
  219. package/dist/types/pushLog.d.ts.map +1 -1
  220. package/dist/types/reviewDoc.d.ts +34 -17
  221. package/dist/types/reviewDoc.d.ts.map +1 -1
  222. package/dist/types/test/index.d.ts +9 -5
  223. package/dist/types/test/index.d.ts.map +1 -1
  224. package/dist/types/test/listMissingTranslations.d.ts +14 -10
  225. package/dist/types/test/listMissingTranslations.d.ts.map +1 -1
  226. package/dist/types/translateDoc.d.ts +34 -17
  227. package/dist/types/translateDoc.d.ts.map +1 -1
  228. package/dist/types/utils/calculateChunks.d.ts +10 -7
  229. package/dist/types/utils/calculateChunks.d.ts.map +1 -1
  230. package/dist/types/utils/checkAccess.d.ts +8 -4
  231. package/dist/types/utils/checkAccess.d.ts.map +1 -1
  232. package/dist/types/utils/checkFileModifiedRange.d.ts +8 -6
  233. package/dist/types/utils/checkFileModifiedRange.d.ts.map +1 -1
  234. package/dist/types/utils/checkLastUpdateTime.d.ts +4 -1
  235. package/dist/types/utils/checkLastUpdateTime.d.ts.map +1 -1
  236. package/dist/types/utils/chunkInference.d.ts +9 -6
  237. package/dist/types/utils/chunkInference.d.ts.map +1 -1
  238. package/dist/types/utils/fixChunkStartEndChars.d.ts +4 -1
  239. package/dist/types/utils/fixChunkStartEndChars.d.ts.map +1 -1
  240. package/dist/types/utils/formatTimeDiff.d.ts +4 -1
  241. package/dist/types/utils/formatTimeDiff.d.ts.map +1 -1
  242. package/dist/types/utils/getIsFileUpdatedRecently.d.ts +4 -1
  243. package/dist/types/utils/getIsFileUpdatedRecently.d.ts.map +1 -1
  244. package/dist/types/utils/getOutputFilePath.d.ts +7 -2
  245. package/dist/types/utils/getOutputFilePath.d.ts.map +1 -1
  246. package/dist/types/utils/getParentPackageJSON.d.ts +30 -28
  247. package/dist/types/utils/getParentPackageJSON.d.ts.map +1 -1
  248. package/dist/types/utils/listSpecialChars.d.ts +9 -7
  249. package/dist/types/utils/listSpecialChars.d.ts.map +1 -1
  250. package/dist/types/utils/mapChunksBetweenFiles.d.ts +10 -6
  251. package/dist/types/utils/mapChunksBetweenFiles.d.ts.map +1 -1
  252. package/dist/types/utils/reorderParagraphs.d.ts +4 -1
  253. package/dist/types/utils/reorderParagraphs.d.ts.map +1 -1
  254. package/dist/types/watch.d.ts +9 -6
  255. package/dist/types/watch.d.ts.map +1 -1
  256. package/package.json +42 -47
  257. package/LICENSE +0 -202
  258. package/dist/cjs/fill/autoFill.cjs +0 -105
  259. package/dist/cjs/fill/autoFill.cjs.map +0 -1
  260. package/dist/cjs/fill/index.cjs.map +0 -1
  261. package/dist/cjs/index.cjs.map +0 -1
  262. package/dist/cjs/utils/getChunk.cjs +0 -77
  263. package/dist/cjs/utils/getChunk.cjs.map +0 -1
  264. package/dist/cjs/utils/splitTextByLine.cjs +0 -35
  265. package/dist/cjs/utils/splitTextByLine.cjs.map +0 -1
  266. package/dist/esm/fill/autoFill.mjs +0 -92
  267. package/dist/esm/fill/autoFill.mjs.map +0 -1
  268. package/dist/esm/fill/index.mjs.map +0 -1
  269. package/dist/esm/index.mjs.map +0 -1
  270. package/dist/esm/prompts/REVIEW_PROMPT.md +0 -37
  271. package/dist/esm/prompts/TRANSLATE_PROMPT.md +0 -38
  272. package/dist/esm/utils/calculrateChunkTest.md +0 -9
  273. package/dist/esm/utils/getChunk.mjs +0 -53
  274. package/dist/esm/utils/getChunk.mjs.map +0 -1
  275. package/dist/esm/utils/splitTextByLine.mjs +0 -11
  276. package/dist/esm/utils/splitTextByLine.mjs.map +0 -1
  277. package/dist/types/fill/autoFill.d.ts +0 -4
  278. package/dist/types/fill/autoFill.d.ts.map +0 -1
  279. package/dist/types/fill/index.d.ts.map +0 -1
  280. package/dist/types/index.d.ts.map +0 -1
  281. package/dist/types/utils/getChunk.d.ts +0 -9
  282. package/dist/types/utils/getChunk.d.ts.map +0 -1
  283. package/dist/types/utils/splitTextByLine.d.ts +0 -2
  284. package/dist/types/utils/splitTextByLine.d.ts.map +0 -1
  285. /package/dist/{cjs → assets}/prompts/REVIEW_PROMPT.md +0 -0
  286. /package/dist/{cjs → assets}/prompts/TRANSLATE_PROMPT.md +0 -0
  287. /package/dist/{cjs/utils/calculrateChunkTest.md → assets/utils/_calculateChunkTest.md} +0 -0
@@ -1,241 +1,189 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
1
+ const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
2
+ let __intlayer_api = require("@intlayer/api");
3
+ __intlayer_api = require_rolldown_runtime.__toESM(__intlayer_api);
4
+ let __intlayer_config_built = require("@intlayer/config/built");
5
+ __intlayer_config_built = require_rolldown_runtime.__toESM(__intlayer_config_built);
6
+ let __intlayer_config_client = require("@intlayer/config/client");
7
+ __intlayer_config_client = require_rolldown_runtime.__toESM(__intlayer_config_client);
8
+ let eventsource = require("eventsource");
9
+ eventsource = require_rolldown_runtime.__toESM(eventsource);
10
+
11
+ //#region src/IntlayerEventListener.ts
12
+ /**
13
+ * IntlayerEventListener class to listen for dictionary changes via SSE (Server-Sent Events).
14
+ *
15
+ * Usage example:
16
+ *
17
+ * import { buildIntlayerDictionary } from './transpiler/declaration_file_to_dictionary/intlayer_dictionary';
18
+ * import { IntlayerEventListener } from '@intlayer/api';
19
+ *
20
+ * export const checkDictionaryChanges = async () => {
21
+ * // Instantiate the listener
22
+ * const eventListener = new IntlayerEventListener();
23
+ *
24
+ * // Set up your callbacks
25
+ * eventListener.onDictionaryChange = async (dictionary) => {
26
+ * await buildIntlayerDictionary(dictionary);
27
+ * };
28
+ *
29
+ * // Initialize the listener
30
+ * await eventListener.initialize();
31
+ *
32
+ * // Optionally, clean up later when you’re done
33
+ * // eventListener.cleanup();
34
+ * };
35
+ */
36
+ var IntlayerEventListener = class {
37
+ appLogger = (0, __intlayer_config_client.getAppLogger)(__intlayer_config_built.default);
38
+ eventSource = null;
39
+ reconnectAttempts = 0;
40
+ maxReconnectAttempts = 5;
41
+ reconnectDelay = 1e3;
42
+ isManuallyDisconnected = false;
43
+ reconnectTimeout = null;
44
+ /**
45
+ * Callback triggered when a Dictionary is ADDED.
46
+ */
47
+ onDictionaryAdded;
48
+ /**
49
+ * Callback triggered when a Dictionary is UPDATED.
50
+ */
51
+ onDictionaryChange;
52
+ /**
53
+ * Callback triggered when a Dictionary is DELETED.
54
+ */
55
+ onDictionaryDeleted;
56
+ /**
57
+ * Callback triggered when connection is established or re-established.
58
+ */
59
+ onConnectionOpen;
60
+ /**
61
+ * Callback triggered when connection encounters an error.
62
+ */
63
+ onConnectionError;
64
+ constructor(intlayerConfig = __intlayer_config_built.default) {
65
+ this.intlayerConfig = intlayerConfig;
66
+ this.appLogger = (0, __intlayer_config_client.getAppLogger)(this.intlayerConfig);
67
+ }
68
+ /**
69
+ * Initializes the EventSource connection using the given intlayerConfig
70
+ * (or the default config if none was provided).
71
+ */
72
+ async initialize() {
73
+ this.isManuallyDisconnected = false;
74
+ await this.connect();
75
+ }
76
+ /**
77
+ * Establishes the EventSource connection with automatic reconnection support.
78
+ */
79
+ async connect() {
80
+ try {
81
+ const backendURL = this.intlayerConfig.editor.backendURL;
82
+ const accessToken = await (0, __intlayer_api.getIntlayerAPIProxy)(void 0, this.intlayerConfig).oAuth.getOAuth2AccessToken();
83
+ if (!accessToken) throw new Error("Failed to retrieve access token");
84
+ const API_ROUTE = `${backendURL}/api/event-listener`;
85
+ if (this.eventSource) this.eventSource.close();
86
+ this.eventSource = new eventsource.EventSource(API_ROUTE, { fetch: (input, init) => fetch(input, {
87
+ ...init,
88
+ headers: {
89
+ ...init?.headers ?? {},
90
+ Authorization: `Bearer ${accessToken.data?.accessToken}`
91
+ }
92
+ }) });
93
+ this.eventSource.onopen = () => {
94
+ this.reconnectAttempts = 0;
95
+ this.reconnectDelay = 1e3;
96
+ this.onConnectionOpen?.();
97
+ };
98
+ this.eventSource.onmessage = (event) => this.handleMessage(event);
99
+ this.eventSource.onerror = (event) => this.handleError(event);
100
+ } catch (_error) {
101
+ this.appLogger("Failed to establish EventSource connection:", { level: "error" });
102
+ this.scheduleReconnect();
103
+ }
104
+ }
105
+ /**
106
+ * Cleans up (closes) the EventSource connection.
107
+ */
108
+ cleanup() {
109
+ this.isManuallyDisconnected = true;
110
+ if (this.reconnectTimeout) {
111
+ clearTimeout(this.reconnectTimeout);
112
+ this.reconnectTimeout = null;
113
+ }
114
+ if (this.eventSource) {
115
+ this.eventSource.close();
116
+ this.eventSource = null;
117
+ }
118
+ }
119
+ /**
120
+ * Schedules a reconnection attempt with exponential backoff.
121
+ */
122
+ scheduleReconnect() {
123
+ if (this.isManuallyDisconnected || this.reconnectAttempts >= this.maxReconnectAttempts) {
124
+ if (this.reconnectAttempts >= this.maxReconnectAttempts) this.appLogger([`Max reconnection attempts (${this.maxReconnectAttempts}) reached. Giving up.`], { level: "error" });
125
+ return;
126
+ }
127
+ this.reconnectAttempts++;
128
+ const delay = this.reconnectDelay * 2 ** (this.reconnectAttempts - 1);
129
+ this.appLogger(`Scheduling reconnection attempt ${this.reconnectAttempts}/${this.maxReconnectAttempts} in ${delay}ms`);
130
+ this.reconnectTimeout = setTimeout(async () => {
131
+ if (!this.isManuallyDisconnected) await this.connect();
132
+ }, delay);
133
+ }
134
+ /**
135
+ * Handles incoming SSE messages, parses the event data,
136
+ * and invokes the appropriate callback.
137
+ */
138
+ async handleMessage(event) {
139
+ try {
140
+ const { data } = event;
141
+ const dataJSON = JSON.parse(data);
142
+ for (const dataEl of dataJSON) switch (dataEl.object) {
143
+ case "DICTIONARY":
144
+ switch (dataEl.status) {
145
+ case "ADDED":
146
+ await this.onDictionaryAdded?.(dataEl.data);
147
+ break;
148
+ case "UPDATED":
149
+ await this.onDictionaryChange?.(dataEl.data);
150
+ break;
151
+ case "DELETED":
152
+ await this.onDictionaryDeleted?.(dataEl.data);
153
+ break;
154
+ default:
155
+ this.appLogger(["Unhandled dictionary status:", dataEl.status], { level: "error" });
156
+ break;
157
+ }
158
+ break;
159
+ default:
160
+ this.appLogger(["Unknown object type:", dataEl.object], { level: "error" });
161
+ break;
162
+ }
163
+ } catch (error) {
164
+ this.appLogger(["Error processing dictionary update:", error], { level: "error" });
165
+ }
166
+ }
167
+ /**
168
+ * Handles any SSE errors and attempts reconnection if appropriate.
169
+ */
170
+ handleError(event) {
171
+ const errorEvent = event;
172
+ this.appLogger(["EventSource error:", {
173
+ type: errorEvent.type,
174
+ message: errorEvent.message,
175
+ code: errorEvent.code,
176
+ readyState: this.eventSource?.readyState,
177
+ url: this.eventSource?.url
178
+ }], { level: "error" });
179
+ this.onConnectionError?.(event);
180
+ if (errorEvent.type === "error" && (errorEvent.message?.includes("terminated") || errorEvent.message?.includes("closed") || this.eventSource?.readyState === eventsource.EventSource.CLOSED) && !this.isManuallyDisconnected) {
181
+ this.appLogger("Connection was terminated by server, attempting to reconnect...");
182
+ this.scheduleReconnect();
183
+ } else this.cleanup();
184
+ }
11
185
  };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
- var IntlayerEventListener_exports = {};
30
- __export(IntlayerEventListener_exports, {
31
- IntlayerEventListener: () => IntlayerEventListener
32
- });
33
- module.exports = __toCommonJS(IntlayerEventListener_exports);
34
- var import_api = require("@intlayer/api");
35
- var import_built = __toESM(require("@intlayer/config/built"));
36
- var import_client = require("@intlayer/config/client");
37
- var import_eventsource = require("eventsource");
38
- class IntlayerEventListener {
39
- constructor(intlayerConfig = import_built.default) {
40
- this.intlayerConfig = intlayerConfig;
41
- this.appLogger = (0, import_client.getAppLogger)(this.intlayerConfig);
42
- }
43
- appLogger = (0, import_client.getAppLogger)(import_built.default);
44
- eventSource = null;
45
- reconnectAttempts = 0;
46
- maxReconnectAttempts = 5;
47
- reconnectDelay = 1e3;
48
- // Start with 1 second
49
- isManuallyDisconnected = false;
50
- reconnectTimeout = null;
51
- /**
52
- * Callback triggered when a Dictionary is ADDED.
53
- */
54
- onDictionaryAdded;
55
- /**
56
- * Callback triggered when a Dictionary is UPDATED.
57
- */
58
- onDictionaryChange;
59
- /**
60
- * Callback triggered when a Dictionary is DELETED.
61
- */
62
- onDictionaryDeleted;
63
- /**
64
- * Callback triggered when connection is established or re-established.
65
- */
66
- onConnectionOpen;
67
- /**
68
- * Callback triggered when connection encounters an error.
69
- */
70
- onConnectionError;
71
- /**
72
- * Initializes the EventSource connection using the given intlayerConfig
73
- * (or the default config if none was provided).
74
- */
75
- async initialize() {
76
- this.isManuallyDisconnected = false;
77
- await this.connect();
78
- }
79
- /**
80
- * Establishes the EventSource connection with automatic reconnection support.
81
- */
82
- async connect() {
83
- try {
84
- const backendURL = this.intlayerConfig.editor.backendURL;
85
- const accessToken = await (0, import_api.getIntlayerAPIProxy)(
86
- void 0,
87
- this.intlayerConfig
88
- ).oAuth.getOAuth2AccessToken();
89
- if (!accessToken) {
90
- throw new Error("Failed to retrieve access token");
91
- }
92
- const API_ROUTE = `${backendURL}/api/event-listener`;
93
- if (this.eventSource) {
94
- this.eventSource.close();
95
- }
96
- this.eventSource = new import_eventsource.EventSource(API_ROUTE, {
97
- fetch: (input, init) => fetch(input, {
98
- ...init,
99
- headers: {
100
- ...init?.headers ?? {},
101
- Authorization: `Bearer ${accessToken.data?.accessToken}`
102
- }
103
- })
104
- });
105
- this.eventSource.onopen = () => {
106
- this.reconnectAttempts = 0;
107
- this.reconnectDelay = 1e3;
108
- this.onConnectionOpen?.();
109
- };
110
- this.eventSource.onmessage = (event) => this.handleMessage(event);
111
- this.eventSource.onerror = (event) => this.handleError(event);
112
- } catch (error) {
113
- this.appLogger("Failed to establish EventSource connection:", {
114
- level: "error"
115
- });
116
- this.scheduleReconnect();
117
- }
118
- }
119
- /**
120
- * Cleans up (closes) the EventSource connection.
121
- */
122
- cleanup() {
123
- this.isManuallyDisconnected = true;
124
- if (this.reconnectTimeout) {
125
- clearTimeout(this.reconnectTimeout);
126
- this.reconnectTimeout = null;
127
- }
128
- if (this.eventSource) {
129
- this.eventSource.close();
130
- this.eventSource = null;
131
- }
132
- }
133
- /**
134
- * Schedules a reconnection attempt with exponential backoff.
135
- */
136
- scheduleReconnect() {
137
- if (this.isManuallyDisconnected || this.reconnectAttempts >= this.maxReconnectAttempts) {
138
- if (this.reconnectAttempts >= this.maxReconnectAttempts) {
139
- this.appLogger(
140
- [
141
- `Max reconnection attempts (${this.maxReconnectAttempts}) reached. Giving up.`
142
- ],
143
- {
144
- level: "error"
145
- }
146
- );
147
- }
148
- return;
149
- }
150
- this.reconnectAttempts++;
151
- const delay = this.reconnectDelay * Math.pow(2, this.reconnectAttempts - 1);
152
- this.appLogger(
153
- `Scheduling reconnection attempt ${this.reconnectAttempts}/${this.maxReconnectAttempts} in ${delay}ms`
154
- );
155
- this.reconnectTimeout = setTimeout(async () => {
156
- if (!this.isManuallyDisconnected) {
157
- await this.connect();
158
- }
159
- }, delay);
160
- }
161
- /**
162
- * Handles incoming SSE messages, parses the event data,
163
- * and invokes the appropriate callback.
164
- */
165
- async handleMessage(event) {
166
- try {
167
- const { data } = event;
168
- const dataJSON = JSON.parse(data);
169
- for (const dataEl of dataJSON) {
170
- switch (dataEl.object) {
171
- case "DICTIONARY":
172
- switch (dataEl.status) {
173
- case "ADDED":
174
- await this.onDictionaryAdded?.(dataEl.data);
175
- break;
176
- case "UPDATED":
177
- await this.onDictionaryChange?.(dataEl.data);
178
- break;
179
- case "DELETED":
180
- await this.onDictionaryDeleted?.(dataEl.data);
181
- break;
182
- default:
183
- this.appLogger(
184
- ["Unhandled dictionary status:", dataEl.status],
185
- {
186
- level: "error"
187
- }
188
- );
189
- break;
190
- }
191
- break;
192
- default:
193
- this.appLogger(["Unknown object type:", dataEl.object], {
194
- level: "error"
195
- });
196
- break;
197
- }
198
- }
199
- } catch (error) {
200
- this.appLogger(["Error processing dictionary update:", error], {
201
- level: "error"
202
- });
203
- }
204
- }
205
- /**
206
- * Handles any SSE errors and attempts reconnection if appropriate.
207
- */
208
- handleError(event) {
209
- const errorEvent = event;
210
- this.appLogger(
211
- [
212
- "EventSource error:",
213
- {
214
- type: errorEvent.type,
215
- message: errorEvent.message,
216
- code: errorEvent.code,
217
- readyState: this.eventSource?.readyState,
218
- url: this.eventSource?.url
219
- }
220
- ],
221
- {
222
- level: "error"
223
- }
224
- );
225
- this.onConnectionError?.(event);
226
- const isConnectionClosed = errorEvent.type === "error" && (errorEvent.message?.includes("terminated") || errorEvent.message?.includes("closed") || this.eventSource?.readyState === import_eventsource.EventSource.CLOSED);
227
- if (isConnectionClosed && !this.isManuallyDisconnected) {
228
- this.appLogger(
229
- "Connection was terminated by server, attempting to reconnect..."
230
- );
231
- this.scheduleReconnect();
232
- } else {
233
- this.cleanup();
234
- }
235
- }
236
- }
237
- // Annotate the CommonJS export names for ESM import in node:
238
- 0 && (module.exports = {
239
- IntlayerEventListener
240
- });
186
+
187
+ //#endregion
188
+ exports.IntlayerEventListener = IntlayerEventListener;
241
189
  //# sourceMappingURL=IntlayerEventListener.cjs.map
@@ -1 +1 @@
1
- {"version":3,"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 { type IntlayerConfig, getAppLogger } from '@intlayer/config/client';\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 * Math.pow(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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,iBAAoC;AAGpC,mBAA0B;AAC1B,oBAAkD;AAClD,yBAA4B;AA4BrB,MAAM,sBAAsB;AAAA,EAmCjC,YAAoB,iBAAiC,aAAAA,SAAe;AAAhD;AAClB,SAAK,gBAAY,4BAAa,KAAK,cAAc;AAAA,EACnD;AAAA,EApCQ,gBAAY,4BAAa,aAAAA,OAAa;AAAA,EAEtC,cAAkC;AAAA,EAClC,oBAAoB;AAAA,EACpB,uBAAuB;AAAA,EACvB,iBAAiB;AAAA;AAAA,EACjB,yBAAyB;AAAA,EACzB,mBAA0C;AAAA;AAAA;AAAA;AAAA,EAK3C;AAAA;AAAA;AAAA;AAAA,EAKA;AAAA;AAAA;AAAA;AAAA,EAKA;AAAA;AAAA;AAAA;AAAA,EAKA;AAAA;AAAA;AAAA;AAAA,EAKA;AAAA;AAA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G;AAAA,cACtD,OAAO;AAAA,YACT,CAAC;AACD;AAAA,QACJ;AAAA,MACF;AAAA,IACF,SAAS,OAAO;AACd,WAAK,UAAU,CAAC,uCAAuC,KAAK,GAAG;AAAA,QAC7D,OAAO;AAAA,MACT,CAAC;AAAA,IACH;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKQ,YAAY,OAAoB;AACtC,UAAM,aAAa;AAGnB,SAAK;AAAA,MACH;AAAA,QACE;AAAA,QACA;AAAA,UACE,MAAM,WAAW;AAAA,UACjB,SAAS,WAAW;AAAA,UACpB,MAAM,WAAW;AAAA,UACjB,YAAY,KAAK,aAAa;AAAA,UAC9B,KAAK,KAAK,aAAa;AAAA,QACzB;AAAA,MACF;AAAA,MACA;AAAA,QACE,OAAO;AAAA,MACT;AAAA,IACF;AAGA,SAAK,oBAAoB,KAAK;AAG9B,UAAM,qBACJ,WAAW,SAAS,YACnB,WAAW,SAAS,SAAS,YAAY,KACxC,WAAW,SAAS,SAAS,QAAQ,KACrC,KAAK,aAAa,eAAe,+BAAY;AAEjD,QAAI,sBAAsB,CAAC,KAAK,wBAAwB;AACtD,WAAK;AAAA,QACH;AAAA,MACF;AACA,WAAK,kBAAkB;AAAA,IACzB,OAAO;AAEL,WAAK,QAAQ;AAAA,IACf;AAAA,EACF;AACF;","names":["configuration"]}
1
+ {"version":3,"file":"IntlayerEventListener.cjs","names":["configuration","intlayerConfig: IntlayerConfig","EventSource","dataJSON: MessageEventData[]"],"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,uDAAyBA,gCAAc;CAE/C,AAAQ,cAAkC;CAC1C,AAAQ,oBAAoB;CAC5B,AAAQ,uBAAuB;CAC/B,AAAQ,iBAAiB;CACzB,AAAQ,yBAAyB;CACjC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AW,SAAS,SAAS,aAAa,IACzC,WAAW,SAAS,SAAS,SAAS,IACtC,KAAK,aAAa,eAAeD,wBAAY,WAEvB,CAAC,KAAK,wBAAwB;AACtD,QAAK,UACH,kEACD;AACD,QAAK,mBAAmB;QAGxB,MAAK,SAAS"}
@@ -0,0 +1,104 @@
1
+ const require_rolldown_runtime = require('./rolldown_runtime.cjs');
2
+ let node_path = require("node:path");
3
+ node_path = require_rolldown_runtime.__toESM(node_path);
4
+ let node_url = require("node:url");
5
+ node_url = require_rolldown_runtime.__toESM(node_url);
6
+ let node_fs = require("node:fs");
7
+ node_fs = require_rolldown_runtime.__toESM(node_fs);
8
+
9
+ //#region \0utils:asset
10
+ const hereDirname = () => {
11
+ try {
12
+ return (0, node_path.dirname)((0, node_url.fileURLToPath)(require("url").pathToFileURL(__filename).href));
13
+ } catch {
14
+ return typeof __dirname !== "undefined" ? __dirname : process.cwd();
15
+ }
16
+ };
17
+ const findDistRoot = (startDir) => {
18
+ let dir = startDir;
19
+ for (let i = 0; i < 12; i++) {
20
+ if ((dir.split("/").pop() || dir.split("\\\\").pop()) === "dist") return dir;
21
+ const parent = (0, node_path.resolve)(dir, "..");
22
+ if (parent === dir) break;
23
+ dir = parent;
24
+ }
25
+ return null;
26
+ };
27
+ const normalizeFrameFile = (file) => {
28
+ if (!file) return null;
29
+ try {
30
+ if (file.startsWith("file://")) return (0, node_url.fileURLToPath)(file);
31
+ } catch {}
32
+ return file;
33
+ };
34
+ /**
35
+ * Returns the directory of the *caller* module that invoked readAsset.
36
+ * Prefers non-virtual frames; falls back to the first real frame.
37
+ */
38
+ const getCallerDir = () => {
39
+ const prev = Error.prepareStackTrace;
40
+ try {
41
+ Error.prepareStackTrace = (_, structured) => structured;
42
+ const err = /* @__PURE__ */ new Error();
43
+ Error.captureStackTrace(err, getCallerDir);
44
+ /** @type {import('node:vm').CallSite[]} */
45
+ const frames = err.stack || [];
46
+ const isVirtualPath = (p) => p.includes(`${node_path.sep}_virtual${node_path.sep}`) || p.includes("/_virtual/");
47
+ for (const frame of frames) {
48
+ const file = normalizeFrameFile(typeof frame.getFileName === "function" ? frame.getFileName() : null);
49
+ if (!file) continue;
50
+ if (file.includes("node:internal") || file.includes(`${node_path.sep}internal${node_path.sep}modules${node_path.sep}`)) continue;
51
+ if (!isVirtualPath(file)) return (0, node_path.dirname)(file);
52
+ }
53
+ for (const frame of frames) {
54
+ const file = normalizeFrameFile(typeof frame.getFileName === "function" ? frame.getFileName() : null);
55
+ if (file) return (0, node_path.dirname)(file);
56
+ }
57
+ } catch {} finally {
58
+ Error.prepareStackTrace = prev;
59
+ }
60
+ return hereDirname();
61
+ };
62
+ /**
63
+ * Read an asset copied from src/** to dist/assets/**.
64
+ * - './' or '../' is resolved relative to the *caller module's* emitted directory.
65
+ * - otherwise, treat as src-relative.
66
+ *
67
+ * @param {string} relPath - e.g. './PROMPT.md' or 'utils/AI/askDocQuestion/embeddings.json'
68
+ * @param {BufferEncoding} [encoding='utf8']
69
+ */
70
+ const readAsset = (relPath, encoding = "utf8") => {
71
+ const here = hereDirname();
72
+ const distRoot = findDistRoot(here) ?? (0, node_path.resolve)(here, "..", "..", "dist");
73
+ const assetsRoot = (0, node_path.join)(distRoot, "assets");
74
+ const tried = [];
75
+ /**
76
+ * Transform ./dist/esm/my/file.ts to my/file.ts for make resolution easier
77
+ */
78
+ const callerSubpath = (0, node_path.relative)(distRoot, getCallerDir()).split("\\").join("/").replace(/^esm\//, "").replace(/^cjs\//, "").replace(/^_virtual\//, "");
79
+ if (relPath.startsWith("./") || relPath.startsWith("../")) {
80
+ const fromCallerAbs = (0, node_path.resolve)(assetsRoot, callerSubpath, relPath);
81
+ const fromCallerAbsToVirtual = fromCallerAbs.replace(/^dist\/esm\//, "/dist/assets/").replace(/^dist\/cjs\//, "/dist/assets/");
82
+ tried.push(fromCallerAbsToVirtual);
83
+ if ((0, node_fs.existsSync)(fromCallerAbsToVirtual)) return (0, node_fs.readFileSync)(fromCallerAbsToVirtual, encoding);
84
+ tried.push(fromCallerAbs);
85
+ if ((0, node_fs.existsSync)(fromCallerAbs)) return (0, node_fs.readFileSync)(fromCallerAbs, encoding);
86
+ }
87
+ const directPath = (0, node_path.join)(assetsRoot, relPath);
88
+ tried.push(directPath);
89
+ if ((0, node_fs.existsSync)(directPath)) return (0, node_fs.readFileSync)(directPath, encoding);
90
+ if (callerSubpath) {
91
+ const nested = (0, node_path.join)(assetsRoot, callerSubpath, relPath);
92
+ tried.push(nested);
93
+ if ((0, node_fs.existsSync)(nested)) return (0, node_fs.readFileSync)(nested, encoding);
94
+ }
95
+ const msg = [
96
+ "readAsset: file not found.",
97
+ "Searched:",
98
+ ...tried.map((p) => `- ${p}`)
99
+ ].join("\n");
100
+ throw new Error(msg);
101
+ };
102
+
103
+ //#endregion
104
+ exports.readAsset = readAsset;
@@ -0,0 +1,25 @@
1
+ //#region rolldown:runtime
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __copyProps = (to, from, except, desc) => {
9
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
10
+ key = keys[i];
11
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
12
+ get: ((k) => from[k]).bind(null, key),
13
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
14
+ });
15
+ }
16
+ return to;
17
+ };
18
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
19
+ value: mod,
20
+ enumerable: true
21
+ }) : target, mod));
22
+
23
+ //#endregion
24
+
25
+ exports.__toESM = __toESM;