node-server-engine 1.1.4 → 1.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (468) hide show
  1. package/.env.example +193 -193
  2. package/.mocharc.js +13 -13
  3. package/.nycrc +18 -18
  4. package/.prettierrc +7 -7
  5. package/Dockerfile +30 -30
  6. package/README.md +991 -991
  7. package/babel.config.json +34 -35
  8. package/dist/const/DebeziumEvent.js.map +1 -1
  9. package/dist/const/LogSeverity.js.map +1 -1
  10. package/dist/const/index.js.map +1 -1
  11. package/dist/const/metrics.js.map +1 -1
  12. package/dist/const/mime.js.map +1 -1
  13. package/dist/const/tokenIssuer.js.map +1 -1
  14. package/dist/db/migrations/20241030121500-create-sequelize-meta-table.js.map +1 -1
  15. package/dist/db/models/SequelizeMeta.js +1 -0
  16. package/dist/db/models/SequelizeMeta.js.map +1 -1
  17. package/dist/db/models/index.js.map +1 -1
  18. package/dist/entities/ElasticSearch/ElasticSearch.js +7 -7
  19. package/dist/entities/ElasticSearch/ElasticSearch.js.map +1 -1
  20. package/dist/entities/ElasticSearch/ElasticSearch.types.js.map +1 -1
  21. package/dist/entities/ElasticSearch/index.js.map +1 -1
  22. package/dist/entities/Endpoint/Endpoint.js +18 -17
  23. package/dist/entities/Endpoint/Endpoint.js.map +1 -1
  24. package/dist/entities/Endpoint/Endpoint.types.js.map +1 -1
  25. package/dist/entities/Endpoint/index.js.map +1 -1
  26. package/dist/entities/EngineError/EngineError.js +7 -6
  27. package/dist/entities/EngineError/EngineError.js.map +1 -1
  28. package/dist/entities/EngineError/EngineError.types.js.map +1 -1
  29. package/dist/entities/EngineError/index.js.map +1 -1
  30. package/dist/entities/KeySet/KeySet.js +10 -9
  31. package/dist/entities/KeySet/KeySet.js.map +1 -1
  32. package/dist/entities/KeySet/KeySet.types.js.map +1 -1
  33. package/dist/entities/KeySet/index.js.map +1 -1
  34. package/dist/entities/LifecycleController/LifecycleController.js.map +1 -1
  35. package/dist/entities/LifecycleController/LifecycleController.types.js.map +1 -1
  36. package/dist/entities/LifecycleController/index.js.map +1 -1
  37. package/dist/entities/Localizator/Localizator.js +7 -7
  38. package/dist/entities/Localizator/Localizator.js.map +1 -1
  39. package/dist/entities/Localizator/Localizator.types.js.map +1 -1
  40. package/dist/entities/Localizator/guessNamingConvention/guessNamingConvention.js.map +1 -1
  41. package/dist/entities/Localizator/guessNamingConvention/index.js.map +1 -1
  42. package/dist/entities/Localizator/index.js.map +1 -1
  43. package/dist/entities/MessageHandler/MessageHandler.js +7 -6
  44. package/dist/entities/MessageHandler/MessageHandler.js.map +1 -1
  45. package/dist/entities/MessageHandler/MessageHandler.types.js.map +1 -1
  46. package/dist/entities/MessageHandler/index.js.map +1 -1
  47. package/dist/entities/PubSub/PubSub.js +25 -25
  48. package/dist/entities/PubSub/PubSub.js.map +1 -1
  49. package/dist/entities/PubSub/PubSub.types.js.map +1 -1
  50. package/dist/entities/PubSub/handleMessage/handleMessage.js +6 -6
  51. package/dist/entities/PubSub/handleMessage/handleMessage.js.map +1 -1
  52. package/dist/entities/PubSub/handleMessage/index.js.map +1 -1
  53. package/dist/entities/PubSub/index.js.map +1 -1
  54. package/dist/entities/PushNotification/PushNotification.js +4 -4
  55. package/dist/entities/PushNotification/PushNotification.js.map +1 -1
  56. package/dist/entities/PushNotification/PushNotification.types.js.map +1 -1
  57. package/dist/entities/PushNotification/index.js.map +1 -1
  58. package/dist/entities/Redis/Redis.js +8 -8
  59. package/dist/entities/Redis/Redis.js.map +1 -1
  60. package/dist/entities/Redis/Redis.types.js.map +1 -1
  61. package/dist/entities/Redis/Redis.validate.js +2 -2
  62. package/dist/entities/Redis/Redis.validate.js.map +1 -1
  63. package/dist/entities/Redis/index.js.map +1 -1
  64. package/dist/entities/Sequelize/Sequelize.config.js.map +1 -1
  65. package/dist/entities/Sequelize/Sequelize.js +2 -2
  66. package/dist/entities/Sequelize/Sequelize.js.map +1 -1
  67. package/dist/entities/Sequelize/Sequelize.types.js.map +1 -1
  68. package/dist/entities/Sequelize/Sequelize.validate.js +2 -2
  69. package/dist/entities/Sequelize/Sequelize.validate.js.map +1 -1
  70. package/dist/entities/Sequelize/index.js.map +1 -1
  71. package/dist/entities/Server/Server.const.js.map +1 -1
  72. package/dist/entities/Server/Server.js +18 -17
  73. package/dist/entities/Server/Server.js.map +1 -1
  74. package/dist/entities/Server/Server.types.js.map +1 -1
  75. package/dist/entities/Server/index.js.map +1 -1
  76. package/dist/entities/SocketClient/SocketClient.js +33 -32
  77. package/dist/entities/SocketClient/SocketClient.js.map +1 -1
  78. package/dist/entities/SocketClient/SocketClient.types.js.map +1 -1
  79. package/dist/entities/SocketClient/index.js.map +1 -1
  80. package/dist/entities/SocketClient/parseMessage/index.js.map +1 -1
  81. package/dist/entities/SocketClient/parseMessage/parseMessage.js +2 -2
  82. package/dist/entities/SocketClient/parseMessage/parseMessage.js.map +1 -1
  83. package/dist/entities/Storage/Storage.js +20 -20
  84. package/dist/entities/Storage/Storage.js.map +1 -1
  85. package/dist/entities/Storage/Storage.types.js.map +1 -1
  86. package/dist/entities/Storage/index.js.map +1 -1
  87. package/dist/entities/ValidationError/ValidationError.js.map +1 -1
  88. package/dist/entities/ValidationError/index.js.map +1 -1
  89. package/dist/entities/WebError/WebError.js +7 -6
  90. package/dist/entities/WebError/WebError.js.map +1 -1
  91. package/dist/entities/WebError/WebError.types.js.map +1 -1
  92. package/dist/entities/WebError/index.js.map +1 -1
  93. package/dist/entities/index.js.map +1 -1
  94. package/dist/index.js.map +1 -1
  95. package/dist/metrics/debug.js.map +1 -1
  96. package/dist/metrics/index.js.map +1 -1
  97. package/dist/metrics/request.js.map +1 -1
  98. package/dist/middleware/authAdmin/authAdmin.js.map +1 -1
  99. package/dist/middleware/authAdmin/authAdmin.types.js.map +1 -1
  100. package/dist/middleware/authAdmin/index.js.map +1 -1
  101. package/dist/middleware/authHmac/authHmac.js.map +1 -1
  102. package/dist/middleware/authHmac/authHmac.types.js.map +1 -1
  103. package/dist/middleware/authHmac/index.js.map +1 -1
  104. package/dist/middleware/authJwt/authJwt.js.map +1 -1
  105. package/dist/middleware/authJwt/authJwt.types.js.map +1 -1
  106. package/dist/middleware/authJwt/index.js.map +1 -1
  107. package/dist/middleware/authStatic/authStatic.js +3 -3
  108. package/dist/middleware/authStatic/authStatic.js.map +1 -1
  109. package/dist/middleware/authStatic/index.js.map +1 -1
  110. package/dist/middleware/authTls/authTls.js +8 -8
  111. package/dist/middleware/authTls/authTls.js.map +1 -1
  112. package/dist/middleware/authTls/authTls.types.js.map +1 -1
  113. package/dist/middleware/authTls/index.js.map +1 -1
  114. package/dist/middleware/checkPermission/checkPermission.js.map +1 -1
  115. package/dist/middleware/error/error.js.map +1 -1
  116. package/dist/middleware/error/index.js.map +1 -1
  117. package/dist/middleware/fileUploader/compressAvatar/compressAvatar.js +2 -2
  118. package/dist/middleware/fileUploader/compressAvatar/compressAvatar.js.map +1 -1
  119. package/dist/middleware/fileUploader/compressAvatar/compressAvatar.types.js.map +1 -1
  120. package/dist/middleware/fileUploader/compressAvatar/index.js.map +1 -1
  121. package/dist/middleware/fileUploader/fileUploader.js +12 -12
  122. package/dist/middleware/fileUploader/fileUploader.js.map +1 -1
  123. package/dist/middleware/fileUploader/fileUploader.types.js.map +1 -1
  124. package/dist/middleware/fileUploader/index.js.map +1 -1
  125. package/dist/middleware/fileUploader/isMultiPart/index.js.map +1 -1
  126. package/dist/middleware/fileUploader/isMultiPart/isMultipart.js.map +1 -1
  127. package/dist/middleware/fileUploader/validate/index.js.map +1 -1
  128. package/dist/middleware/fileUploader/validate/validate.js.map +1 -1
  129. package/dist/middleware/fourOhFour/fourOhFour.js.map +1 -1
  130. package/dist/middleware/fourOhFour/index.js.map +1 -1
  131. package/dist/middleware/geminiFileUploader/geminiFileUploader.js.map +1 -1
  132. package/dist/middleware/geminiFileUploader/index.js.map +1 -1
  133. package/dist/middleware/healthCheck/healthCheck.js +2 -2
  134. package/dist/middleware/healthCheck/healthCheck.js.map +1 -1
  135. package/dist/middleware/healthCheck/index.js.map +1 -1
  136. package/dist/middleware/index.js.map +1 -1
  137. package/dist/middleware/metrics/index.js.map +1 -1
  138. package/dist/middleware/metrics/metrics.js.map +1 -1
  139. package/dist/middleware/requestMetrics/index.js.map +1 -1
  140. package/dist/middleware/requestMetrics/requestMetrics.js.map +1 -1
  141. package/dist/middleware/swaggerDocs/index.js.map +1 -1
  142. package/dist/middleware/swaggerDocs/swaggerDocs.js +7 -7
  143. package/dist/middleware/swaggerDocs/swaggerDocs.js.map +1 -1
  144. package/dist/middleware/swaggerDocs/swaggerDocs.types.js.map +1 -1
  145. package/dist/middleware/userResolver/index.js.map +1 -1
  146. package/dist/middleware/userResolver/userResolver.js.map +1 -1
  147. package/dist/middleware/validate/index.js.map +1 -1
  148. package/dist/middleware/validate/validate.js.map +1 -1
  149. package/dist/middleware/version/index.js.map +1 -1
  150. package/dist/middleware/version/version.js +3 -3
  151. package/dist/middleware/version/version.js.map +1 -1
  152. package/dist/utils/checkEnvironment/index.js +13 -13
  153. package/dist/utils/checkEnvironment/index.js.map +1 -1
  154. package/dist/utils/createHttpServer/createHttpServer.js.map +1 -1
  155. package/dist/utils/createHttpServer/createHttpServer.validate.js +2 -2
  156. package/dist/utils/createHttpServer/createHttpServer.validate.js.map +1 -1
  157. package/dist/utils/createHttpServer/index.js.map +1 -1
  158. package/dist/utils/createSortedObject/createSortedObject.js.map +1 -1
  159. package/dist/utils/createSortedObject/index.js.map +1 -1
  160. package/dist/utils/dbMigration/dbMigration.js +8 -8
  161. package/dist/utils/dbMigration/dbMigration.js.map +1 -1
  162. package/dist/utils/dbMigration/dbMigration.types.js.map +1 -1
  163. package/dist/utils/dbMigration/index.js.map +1 -1
  164. package/dist/utils/dbMigration/migrateMetadataTable/index.js.map +1 -1
  165. package/dist/utils/dbMigration/migrateMetadataTable/migrateMetadataTable.js +4 -4
  166. package/dist/utils/dbMigration/migrateMetadataTable/migrateMetadataTable.js.map +1 -1
  167. package/dist/utils/envAssert/envAssert.js +6 -6
  168. package/dist/utils/envAssert/envAssert.js.map +1 -1
  169. package/dist/utils/envAssert/index.js.map +1 -1
  170. package/dist/utils/envAssert/validators/hostList.js +2 -2
  171. package/dist/utils/envAssert/validators/hostList.js.map +1 -1
  172. package/dist/utils/envAssert/validators/index.js.map +1 -1
  173. package/dist/utils/envAssert/validators/ipList.js +2 -2
  174. package/dist/utils/envAssert/validators/ipList.js.map +1 -1
  175. package/dist/utils/envAssert/validators/path.js +2 -2
  176. package/dist/utils/envAssert/validators/path.js.map +1 -1
  177. package/dist/utils/envAssert/validators/string.js +2 -2
  178. package/dist/utils/envAssert/validators/string.js.map +1 -1
  179. package/dist/utils/envAssert/validators/stringList.js +3 -3
  180. package/dist/utils/envAssert/validators/stringList.js.map +1 -1
  181. package/dist/utils/filter/filter.js +4 -4
  182. package/dist/utils/filter/filter.js.map +1 -1
  183. package/dist/utils/filter/index.js.map +1 -1
  184. package/dist/utils/getDynamicLink/getDynamicLink.js.map +1 -1
  185. package/dist/utils/getDynamicLink/getDynamicLink.types.js.map +1 -1
  186. package/dist/utils/getDynamicLink/getDynamicLink.validate.js.map +1 -1
  187. package/dist/utils/getDynamicLink/index.js.map +1 -1
  188. package/dist/utils/hmac/checkEnv/checkEnv.js +2 -2
  189. package/dist/utils/hmac/checkEnv/checkEnv.js.map +1 -1
  190. package/dist/utils/hmac/checkEnv/index.js.map +1 -1
  191. package/dist/utils/hmac/createHmac/createHmac.js.map +1 -1
  192. package/dist/utils/hmac/createHmac/index.js.map +1 -1
  193. package/dist/utils/hmac/index.js.map +1 -1
  194. package/dist/utils/hmac/index.types.js.map +1 -1
  195. package/dist/utils/hmac/signPayload/index.js.map +1 -1
  196. package/dist/utils/hmac/signPayload/signPayload.js.map +1 -1
  197. package/dist/utils/hmac/verifySignature/index.js.map +1 -1
  198. package/dist/utils/hmac/verifySignature/verifySignature.js.map +1 -1
  199. package/dist/utils/index.js.map +1 -1
  200. package/dist/utils/jwt/index.js.map +1 -1
  201. package/dist/utils/jwt/jwt.js.map +1 -1
  202. package/dist/utils/jwt/jwt.types.js.map +1 -1
  203. package/dist/utils/report/index.js.map +1 -1
  204. package/dist/utils/report/output.js.map +1 -1
  205. package/dist/utils/report/output.types.js.map +1 -1
  206. package/dist/utils/report/report.js.map +1 -1
  207. package/dist/utils/report/report.types.js.map +1 -1
  208. package/dist/utils/request/index.js.map +1 -1
  209. package/dist/utils/request/request.js.map +1 -1
  210. package/dist/utils/semverCompare/index.js.map +1 -1
  211. package/dist/utils/semverCompare/semverCompare.js +5 -5
  212. package/dist/utils/semverCompare/semverCompare.js.map +1 -1
  213. package/dist/utils/sendEmail/index.js.map +1 -1
  214. package/dist/utils/sendEmail/sendEmail.js +8 -8
  215. package/dist/utils/sendEmail/sendEmail.js.map +1 -1
  216. package/dist/utils/sendEmail/sendEmail.types.js.map +1 -1
  217. package/dist/utils/sendPush/index.js.map +1 -1
  218. package/dist/utils/sendPush/sendPush.js +5 -5
  219. package/dist/utils/sendPush/sendPush.js.map +1 -1
  220. package/dist/utils/sendPush/sendPush.types.js.map +1 -1
  221. package/dist/utils/tlsConfig/index.js.map +1 -1
  222. package/dist/utils/tlsConfig/tlsConfig.js +2 -2
  223. package/dist/utils/tlsConfig/tlsConfig.js.map +1 -1
  224. package/dist/utils/tlsConfig/tlsConfig.types.js.map +1 -1
  225. package/dist/utils/tlsConfig/tlsConfig.validate.js +2 -2
  226. package/dist/utils/tlsConfig/tlsConfig.validate.js.map +1 -1
  227. package/dist/utils/tlsRequest/index.js.map +1 -1
  228. package/dist/utils/tlsRequest/tlsRequest.js.map +1 -1
  229. package/dist/utils/trimPathSlash/index.js.map +1 -1
  230. package/dist/utils/trimPathSlash/trimPathSlash.js +4 -4
  231. package/dist/utils/trimPathSlash/trimPathSlash.js.map +1 -1
  232. package/eslint.config.mjs +11 -11
  233. package/package.json +159 -164
  234. package/src/const/DebeziumEvent.ts +6 -6
  235. package/src/const/LogSeverity.ts +7 -7
  236. package/src/const/index.ts +5 -5
  237. package/src/const/metrics.ts +6 -6
  238. package/src/const/mime.ts +37 -37
  239. package/src/const/tokenIssuer.ts +9 -9
  240. package/src/db/migrations/20241030121500-create-sequelize-meta-table.ts +29 -29
  241. package/src/db/models/SequelizeMeta.ts +16 -16
  242. package/src/db/models/index.ts +2 -2
  243. package/src/entities/ElasticSearch/ElasticSearch.ts +103 -103
  244. package/src/entities/ElasticSearch/ElasticSearch.types.ts +7 -7
  245. package/src/entities/ElasticSearch/index.ts +2 -2
  246. package/src/entities/Endpoint/Endpoint.test.ts +337 -337
  247. package/src/entities/Endpoint/Endpoint.ts +202 -202
  248. package/src/entities/Endpoint/Endpoint.types.ts +205 -205
  249. package/src/entities/Endpoint/index.ts +2 -2
  250. package/src/entities/EngineError/EngineError.ts +28 -28
  251. package/src/entities/EngineError/EngineError.types.ts +15 -15
  252. package/src/entities/EngineError/index.ts +2 -2
  253. package/src/entities/KeySet/KeySet.test.ts +126 -126
  254. package/src/entities/KeySet/KeySet.ts +172 -172
  255. package/src/entities/KeySet/KeySet.types.ts +28 -28
  256. package/src/entities/KeySet/index.ts +2 -2
  257. package/src/entities/LifecycleController/LifecycleController.test.ts +48 -48
  258. package/src/entities/LifecycleController/LifecycleController.ts +24 -24
  259. package/src/entities/LifecycleController/LifecycleController.types.ts +5 -5
  260. package/src/entities/LifecycleController/index.ts +2 -2
  261. package/src/entities/Localizator/Localizator.ts +139 -139
  262. package/src/entities/Localizator/Localizator.types.ts +52 -52
  263. package/src/entities/Localizator/guessNamingConvention/guessNamingConvention.test.ts +165 -165
  264. package/src/entities/Localizator/guessNamingConvention/guessNamingConvention.ts +58 -58
  265. package/src/entities/Localizator/guessNamingConvention/index.ts +1 -1
  266. package/src/entities/Localizator/index.ts +2 -2
  267. package/src/entities/MessageHandler/MessageHandler.test.ts +130 -130
  268. package/src/entities/MessageHandler/MessageHandler.ts +72 -72
  269. package/src/entities/MessageHandler/MessageHandler.types.ts +15 -15
  270. package/src/entities/MessageHandler/index.ts +2 -2
  271. package/src/entities/PubSub/PubSub.test.ts +297 -297
  272. package/src/entities/PubSub/PubSub.ts +202 -202
  273. package/src/entities/PubSub/PubSub.types.ts +76 -76
  274. package/src/entities/PubSub/handleMessage/handleMessage.test.ts +102 -102
  275. package/src/entities/PubSub/handleMessage/handleMessage.ts +65 -65
  276. package/src/entities/PubSub/handleMessage/index.ts +1 -1
  277. package/src/entities/PubSub/index.ts +2 -2
  278. package/src/entities/PushNotification/PushNotification.test.ts +35 -35
  279. package/src/entities/PushNotification/PushNotification.ts +44 -44
  280. package/src/entities/PushNotification/PushNotification.types.ts +25 -25
  281. package/src/entities/PushNotification/index.ts +2 -2
  282. package/src/entities/Redis/Redis.ts +71 -71
  283. package/src/entities/Redis/Redis.types.ts +19 -19
  284. package/src/entities/Redis/Redis.validate.ts +17 -17
  285. package/src/entities/Redis/index.ts +2 -2
  286. package/src/entities/Sequelize/Sequelize.config.ts +59 -59
  287. package/src/entities/Sequelize/Sequelize.test.ts +21 -21
  288. package/src/entities/Sequelize/Sequelize.ts +75 -75
  289. package/src/entities/Sequelize/Sequelize.types.ts +10 -10
  290. package/src/entities/Sequelize/Sequelize.validate.ts +15 -15
  291. package/src/entities/Sequelize/index.ts +2 -2
  292. package/src/entities/Server/Server.const.ts +56 -56
  293. package/src/entities/Server/Server.test.ts +272 -272
  294. package/src/entities/Server/Server.ts +445 -445
  295. package/src/entities/Server/Server.types.ts +88 -88
  296. package/src/entities/Server/index.ts +2 -2
  297. package/src/entities/SocketClient/SocketClient.test.ts +392 -392
  298. package/src/entities/SocketClient/SocketClient.ts +401 -401
  299. package/src/entities/SocketClient/SocketClient.types.ts +62 -62
  300. package/src/entities/SocketClient/index.ts +2 -2
  301. package/src/entities/SocketClient/parseMessage/index.ts +1 -1
  302. package/src/entities/SocketClient/parseMessage/parseMessage.test.ts +20 -20
  303. package/src/entities/SocketClient/parseMessage/parseMessage.ts +26 -26
  304. package/src/entities/Storage/Storage.test.ts +58 -58
  305. package/src/entities/Storage/Storage.ts +219 -219
  306. package/src/entities/Storage/Storage.types.ts +57 -57
  307. package/src/entities/Storage/index.ts +2 -2
  308. package/src/entities/ValidationError/ValidationError.ts +34 -34
  309. package/src/entities/ValidationError/index.ts +1 -1
  310. package/src/entities/WebError/WebError.test.ts +18 -18
  311. package/src/entities/WebError/WebError.ts +23 -23
  312. package/src/entities/WebError/WebError.types.ts +9 -9
  313. package/src/entities/WebError/index.ts +2 -2
  314. package/src/entities/index.ts +16 -16
  315. package/src/index.ts +4 -4
  316. package/src/metrics/debug.ts +10 -10
  317. package/src/metrics/index.ts +2 -2
  318. package/src/metrics/request.ts +17 -17
  319. package/src/middleware/authAdmin/authAdmin.test.ts +199 -199
  320. package/src/middleware/authAdmin/authAdmin.ts +114 -114
  321. package/src/middleware/authAdmin/authAdmin.types.ts +19 -19
  322. package/src/middleware/authAdmin/index.ts +2 -2
  323. package/src/middleware/authHmac/authHmac.test.ts +86 -86
  324. package/src/middleware/authHmac/authHmac.ts +56 -56
  325. package/src/middleware/authHmac/authHmac.types.ts +7 -7
  326. package/src/middleware/authHmac/index.ts +2 -2
  327. package/src/middleware/authJwt/authJwt.test.ts +54 -54
  328. package/src/middleware/authJwt/authJwt.ts +55 -55
  329. package/src/middleware/authJwt/authJwt.types.ts +14 -14
  330. package/src/middleware/authJwt/index.ts +2 -2
  331. package/src/middleware/authStatic/authStatic.test.ts +36 -36
  332. package/src/middleware/authStatic/authStatic.ts +45 -45
  333. package/src/middleware/authStatic/index.ts +1 -1
  334. package/src/middleware/authTls/authTls.test.ts +138 -138
  335. package/src/middleware/authTls/authTls.ts +106 -106
  336. package/src/middleware/authTls/authTls.types.ts +13 -13
  337. package/src/middleware/authTls/index.ts +2 -2
  338. package/src/middleware/checkPermission/checkPermission.ts +32 -32
  339. package/src/middleware/error/error.test.ts +60 -60
  340. package/src/middleware/error/error.ts +25 -25
  341. package/src/middleware/error/index.ts +1 -1
  342. package/src/middleware/fileUploader/compressAvatar/compressAvatar.ts +25 -25
  343. package/src/middleware/fileUploader/compressAvatar/compressAvatar.types.ts +12 -12
  344. package/src/middleware/fileUploader/compressAvatar/index.ts +2 -2
  345. package/src/middleware/fileUploader/fileUploader.test.ts +310 -310
  346. package/src/middleware/fileUploader/fileUploader.ts +303 -303
  347. package/src/middleware/fileUploader/fileUploader.types.ts +52 -52
  348. package/src/middleware/fileUploader/index.ts +2 -2
  349. package/src/middleware/fileUploader/isMultiPart/index.ts +1 -1
  350. package/src/middleware/fileUploader/isMultiPart/isMultipart.ts +9 -9
  351. package/src/middleware/fileUploader/validate/index.ts +1 -1
  352. package/src/middleware/fileUploader/validate/validate.ts +27 -27
  353. package/src/middleware/fourOhFour/fourOhFour.test.ts +14 -14
  354. package/src/middleware/fourOhFour/fourOhFour.ts +13 -13
  355. package/src/middleware/fourOhFour/index.ts +1 -1
  356. package/src/middleware/geminiFileUploader/geminiFileUploader.ts +117 -117
  357. package/src/middleware/geminiFileUploader/index.ts +1 -1
  358. package/src/middleware/healthCheck/healthCheck.test.ts +12 -12
  359. package/src/middleware/healthCheck/healthCheck.ts +14 -14
  360. package/src/middleware/healthCheck/index.ts +1 -1
  361. package/src/middleware/index.ts +17 -17
  362. package/src/middleware/metrics/index.ts +1 -1
  363. package/src/middleware/metrics/metrics.test.ts +46 -46
  364. package/src/middleware/metrics/metrics.ts +24 -24
  365. package/src/middleware/requestMetrics/index.ts +1 -1
  366. package/src/middleware/requestMetrics/requestMetrics.test.ts +77 -77
  367. package/src/middleware/requestMetrics/requestMetrics.ts +20 -20
  368. package/src/middleware/swaggerDocs/index.ts +2 -2
  369. package/src/middleware/swaggerDocs/swaggerDocs.ts +114 -114
  370. package/src/middleware/swaggerDocs/swaggerDocs.types.ts +41 -41
  371. package/src/middleware/userResolver/index.ts +1 -1
  372. package/src/middleware/userResolver/userResolver.test.ts +35 -35
  373. package/src/middleware/userResolver/userResolver.ts +35 -35
  374. package/src/middleware/validate/index.ts +1 -1
  375. package/src/middleware/validate/validate.test.ts +43 -43
  376. package/src/middleware/validate/validate.ts +25 -25
  377. package/src/middleware/version/index.ts +1 -1
  378. package/src/middleware/version/version.test.ts +23 -23
  379. package/src/middleware/version/version.ts +12 -12
  380. package/src/utils/checkEnvironment/index.ts +49 -49
  381. package/src/utils/createHttpServer/createHttpServer.test.ts +24 -24
  382. package/src/utils/createHttpServer/createHttpServer.ts +34 -34
  383. package/src/utils/createHttpServer/createHttpServer.validate.ts +17 -17
  384. package/src/utils/createHttpServer/index.ts +1 -1
  385. package/src/utils/createSortedObject/createSortedObject.ts +20 -20
  386. package/src/utils/createSortedObject/createSortedObjet.test.ts +47 -47
  387. package/src/utils/createSortedObject/index.ts +1 -1
  388. package/src/utils/dbMigration/dbMigration.test.ts +209 -209
  389. package/src/utils/dbMigration/dbMigration.ts +199 -199
  390. package/src/utils/dbMigration/dbMigration.types.ts +11 -11
  391. package/src/utils/dbMigration/index.ts +2 -2
  392. package/src/utils/dbMigration/migrateMetadataTable/index.ts +1 -1
  393. package/src/utils/dbMigration/migrateMetadataTable/migrateMetadataTable.test.ts +59 -59
  394. package/src/utils/dbMigration/migrateMetadataTable/migrateMetadataTable.ts +102 -102
  395. package/src/utils/envAssert/envAssert.ts +31 -31
  396. package/src/utils/envAssert/index.ts +1 -1
  397. package/src/utils/envAssert/validators/hostList.ts +17 -17
  398. package/src/utils/envAssert/validators/index.ts +5 -5
  399. package/src/utils/envAssert/validators/ipList.ts +13 -13
  400. package/src/utils/envAssert/validators/path.ts +13 -13
  401. package/src/utils/envAssert/validators/string.ts +9 -9
  402. package/src/utils/envAssert/validators/stringList.ts +13 -13
  403. package/src/utils/filter/filter.ts +17 -17
  404. package/src/utils/filter/index.ts +1 -1
  405. package/src/utils/getDynamicLink/getDynamicLink.test.ts +51 -51
  406. package/src/utils/getDynamicLink/getDynamicLink.ts +28 -28
  407. package/src/utils/getDynamicLink/getDynamicLink.types.ts +11 -11
  408. package/src/utils/getDynamicLink/getDynamicLink.validate.ts +6 -6
  409. package/src/utils/getDynamicLink/index.ts +2 -2
  410. package/src/utils/hmac/checkEnv/checkEnv.test.ts +18 -18
  411. package/src/utils/hmac/checkEnv/checkEnv.ts +9 -9
  412. package/src/utils/hmac/checkEnv/index.ts +1 -1
  413. package/src/utils/hmac/createHmac/createHmac.ts +33 -33
  414. package/src/utils/hmac/createHmac/index.ts +1 -1
  415. package/src/utils/hmac/index.ts +4 -4
  416. package/src/utils/hmac/index.types.ts +13 -13
  417. package/src/utils/hmac/signPayload/index.ts +1 -1
  418. package/src/utils/hmac/signPayload/signPayload.ts +16 -16
  419. package/src/utils/hmac/verifySignature/index.ts +1 -1
  420. package/src/utils/hmac/verifySignature/verifySignature.ts +24 -24
  421. package/src/utils/index.ts +26 -26
  422. package/src/utils/jwt/index.ts +2 -2
  423. package/src/utils/jwt/jwt.test.ts +41 -41
  424. package/src/utils/jwt/jwt.ts +204 -204
  425. package/src/utils/jwt/jwt.types.ts +21 -21
  426. package/src/utils/report/index.ts +3 -3
  427. package/src/utils/report/output.ts +45 -45
  428. package/src/utils/report/output.types.ts +70 -70
  429. package/src/utils/report/report.test.ts +133 -133
  430. package/src/utils/report/report.ts +134 -134
  431. package/src/utils/report/report.types.ts +13 -13
  432. package/src/utils/request/index.ts +1 -1
  433. package/src/utils/request/request.test.ts +26 -26
  434. package/src/utils/request/request.ts +48 -48
  435. package/src/utils/semverCompare/index.ts +1 -1
  436. package/src/utils/semverCompare/semverCompare.test.ts +49 -49
  437. package/src/utils/semverCompare/semverCompare.ts +60 -60
  438. package/src/utils/sendEmail/index.ts +1 -1
  439. package/src/utils/sendEmail/sendEmail.ts +27 -27
  440. package/src/utils/sendEmail/sendEmail.types.ts +7 -7
  441. package/src/utils/sendPush/index.ts +2 -2
  442. package/src/utils/sendPush/sendPush.ts +20 -20
  443. package/src/utils/sendPush/sendPush.types.ts +25 -25
  444. package/src/utils/tlsConfig/index.ts +2 -2
  445. package/src/utils/tlsConfig/tlsConfig.test.ts +32 -32
  446. package/src/utils/tlsConfig/tlsConfig.ts +47 -47
  447. package/src/utils/tlsConfig/tlsConfig.types.ts +11 -11
  448. package/src/utils/tlsConfig/tlsConfig.validate.ts +25 -25
  449. package/src/utils/tlsRequest/index.ts +1 -1
  450. package/src/utils/tlsRequest/tlsRequest.test.ts +63 -63
  451. package/src/utils/tlsRequest/tlsRequest.ts +12 -12
  452. package/src/utils/trimPathSlash/index.ts +1 -1
  453. package/src/utils/trimPathSlash/trimPathSlash.test.ts +26 -26
  454. package/src/utils/trimPathSlash/trimPathSlash.ts +8 -8
  455. package/test/env.ts +56 -56
  456. package/test/factory/index.ts +8 -8
  457. package/test/factory/sequelizeMeta.ts +12 -12
  458. package/test/hooks.ts +37 -37
  459. package/test/index.ts +3 -3
  460. package/test/stub/index.ts +3 -3
  461. package/test/stub/stubLocales.ts +68 -68
  462. package/test/stub/stubPubSub.ts +7 -7
  463. package/test/stub/stubStorage.ts +77 -77
  464. package/test/stub/stubStorage.types.ts +11 -11
  465. package/test/utils/app.ts +31 -31
  466. package/test/utils/index.ts +1 -1
  467. package/tsconfig.build.json +5 -5
  468. package/tsconfig.json +32 -32
@@ -7,6 +7,7 @@ Object.defineProperty(exports, "__esModule", {
7
7
  exports.KeySet = void 0;
8
8
  var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
9
9
  var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
10
+ var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
10
11
  var _crypto = require("crypto");
11
12
  var _fs = require("fs");
12
13
  var _const = require("../../const");
@@ -19,26 +20,26 @@ const namespace = 'engine:keySet';
19
20
  // Number of seconds between each key refresh
20
21
  const KEY_REFRESH_INTERVAL = 300;
21
22
 
22
- /**
23
- * Fetch Json Web Key Sets and cache them
24
- * Keys can then be used for Json Web Token authentication
23
+ /**
24
+ * Fetch Json Web Key Sets and cache them
25
+ * Keys can then be used for Json Web Token authentication
25
26
  */
26
27
  let KeySet = exports.KeySet = /*#__PURE__*/function () {
27
28
  /** Create a new Key Set */
28
29
  function KeySet(url, options = {}) {
29
30
  (0, _classCallCheck2.default)(this, KeySet);
30
31
  /** Latest known value for the keys in the set, indexed by the key id */
31
- this.keySet = {};
32
+ (0, _defineProperty2.default)(this, "keySet", {});
32
33
  /** URL at which the key set can be fetched */
33
- this.url = void 0;
34
+ (0, _defineProperty2.default)(this, "url", void 0);
34
35
  /** This resource is located on a service inside of our private cluster */
35
- this.internal = void 0;
36
+ (0, _defineProperty2.default)(this, "internal", void 0);
36
37
  /** This URL is actually a path to a local key file encoded in PEM */
37
- this.file = void 0;
38
+ (0, _defineProperty2.default)(this, "file", void 0);
38
39
  /** This input is actually a full PEM string representation of a key */
39
- this.pem = void 0;
40
+ (0, _defineProperty2.default)(this, "pem", void 0);
40
41
  /** Timer for the key fetching interval */
41
- this.interval = void 0;
42
+ (0, _defineProperty2.default)(this, "interval", void 0);
42
43
  this.url = url;
43
44
  this.internal = options.internal ?? false;
44
45
  this.file = options.file ?? false;
@@ -1 +1 @@
1
- {"version":3,"file":"KeySet.js","names":["_crypto","require","_fs","_const","_EngineError","_report","_request","_tlsRequest","namespace","KEY_REFRESH_INTERVAL","KeySet","exports","url","options","_classCallCheck2","default","keySet","internal","file","pem","interval","_createClass2","key","value","init","fetch","setInterval","error","reportError","catch","shutdown","clearInterval","getKey","keyId","getKeys","reportDebug","message","data","kid","calculateKeyId","set","JSON","parse","readFileSync","keys","Array","EngineError","severity","LogSeverity","ERROR","reduce","createPublicKey","format","export","type","requestOptions","method","tlsRequest","request","Object","length","keyIds","hash","createHash","update","trim","digest"],"sources":["../../../src/entities/KeySet/KeySet.ts"],"sourcesContent":["import { createPublicKey, createHash } from 'crypto';\r\nimport { readFileSync } from 'fs';\r\nimport { Method } from 'axios';\r\nimport { KeySetOptions, KeySetValues, JWKS } from './KeySet.types';\r\nimport { LogSeverity } from 'const';\r\nimport { EngineError } from 'entities/EngineError';\r\nimport { reportDebug, reportError } from 'utils/report';\r\nimport { request } from 'utils/request';\r\nimport { tlsRequest } from 'utils/tlsRequest';\r\n\r\nconst namespace = 'engine:keySet';\r\n\r\n// Number of seconds between each key refresh\r\nconst KEY_REFRESH_INTERVAL = 300;\r\n\r\n/**\r\n * Fetch Json Web Key Sets and cache them\r\n * Keys can then be used for Json Web Token authentication\r\n */\r\nexport class KeySet {\r\n /** Latest known value for the keys in the set, indexed by the key id */\r\n private keySet: KeySetValues = {};\r\n /** URL at which the key set can be fetched */\r\n private url: string;\r\n /** This resource is located on a service inside of our private cluster */\r\n private internal: boolean;\r\n /** This URL is actually a path to a local key file encoded in PEM */\r\n private file: boolean;\r\n /** This input is actually a full PEM string representation of a key */\r\n private pem: boolean;\r\n /** Timer for the key fetching interval */\r\n private interval?: NodeJS.Timeout | string | number | undefined;\r\n\r\n /** Create a new Key Set */\r\n public constructor(url: string, options: KeySetOptions = {}) {\r\n this.url = url;\r\n this.internal = options.internal ?? false;\r\n this.file = options.file ?? false;\r\n this.pem = options.pem ?? false;\r\n }\r\n\r\n /** Calculate key ID from PEM string */\r\n private static calculateKeyId(pem: string): string {\r\n // We use the md5 hash of the PEM file to defined the key ID\r\n const hash = createHash('md5');\r\n hash.update(pem.trim());\r\n const kid = hash.digest('base64url');\r\n reportDebug({\r\n namespace,\r\n message: `Calculated Key ID: \"${kid}\"`,\r\n data: { key: pem }\r\n });\r\n return kid;\r\n }\r\n\r\n /** Initialize a KeySet, should be run on server startup to avoid any misconfiguration */\r\n public async init(): Promise<void> {\r\n await this.fetch();\r\n this.interval = setInterval(() => {\r\n (async (): Promise<void> => {\r\n try {\r\n await this.fetch();\r\n } catch (error) {\r\n reportError(error);\r\n }\r\n })().catch((error) => {\r\n reportError(error);\r\n });\r\n }, KEY_REFRESH_INTERVAL * 1000);\r\n }\r\n\r\n /** Clear any pending timers to avoid pending process */\r\n public shutdown(): void {\r\n if (this.interval) clearInterval(this.interval);\r\n }\r\n\r\n /** Get the PEM encoded version of a key by its id */\r\n public getKey(keyId: string): string | undefined {\r\n return this.keySet[keyId];\r\n }\r\n\r\n /** Get all the keys in the set mapped by their ID */\r\n public getKeys(): KeySetValues {\r\n return this.keySet;\r\n }\r\n\r\n /** Fetch the latest version of the key set */\r\n private async fetch(): Promise<void> {\r\n reportDebug({\r\n namespace,\r\n message: `Fetching JWKS`,\r\n data: { url: this.url }\r\n });\r\n\r\n if (this.pem) {\r\n // Read the key from the parameter directly\r\n reportDebug({\r\n namespace,\r\n message: 'Processing key from given PEM string'\r\n });\r\n\r\n const kid = KeySet.calculateKeyId(this.url);\r\n\r\n this.keySet = { [kid]: this.url };\r\n } else if (this.file) {\r\n // Read the key from a file\r\n reportDebug({\r\n namespace,\r\n message: `Reading key on disk at path \"${this.url}\"`\r\n });\r\n const set = JSON.parse(readFileSync(this.url, 'utf-8'));\r\n\r\n // Check that the returned data has the shape of a JWKS\r\n if (!(set.keys && set.keys instanceof Array))\r\n throw new EngineError({\r\n severity: LogSeverity.ERROR,\r\n message: 'Fetched key set is not in an appropriate format',\r\n data: { url: this.url, set }\r\n });\r\n\r\n // Create a node.crypto public key object for each key in the set\r\n this.keySet = set.keys.reduce(\r\n (set: { [x: string]: string; }, key: { kid: string | number; }) => {\r\n set[key.kid] = createPublicKey({ key, format: 'jwk' }).export({\r\n format: 'pem',\r\n type: 'spki'\r\n }) as string;\r\n return set;\r\n },\r\n {} as Record<string, string>\r\n );\r\n } else {\r\n // Fetch key by making a network request\r\n reportDebug({\r\n namespace,\r\n message: `Making network request to \"${this.url}\"`\r\n });\r\n\r\n const requestOptions = { url: this.url, method: 'get' as Method };\r\n // For services inside of our cluster we use the TLS authenticated request method\r\n const { data: set } = await (this.internal\r\n ? tlsRequest<JWKS>(requestOptions)\r\n : request<JWKS>(requestOptions));\r\n\r\n // Check that the returned data has the shape of a JWKS\r\n if (!(set.keys && set.keys instanceof Array))\r\n throw new EngineError({\r\n severity: LogSeverity.ERROR,\r\n message: 'Fetched key set is not in an appropriate format',\r\n data: { url: this.url, set }\r\n });\r\n\r\n // Create a node.crypto public key object for each key in the set\r\n this.keySet = set.keys.reduce(\r\n (set, key) => {\r\n set[key.kid] = createPublicKey({ key, format: 'jwk' }).export({\r\n format: 'pem',\r\n type: 'spki'\r\n }) as string;\r\n return set;\r\n },\r\n {} as Record<string, string>\r\n );\r\n }\r\n\r\n reportDebug({\r\n namespace,\r\n message: `Stored ${Object.keys(this.keySet).length} keys`,\r\n data: { keyIds: Object.keys(this.keySet) }\r\n });\r\n }\r\n}\r\n"],"mappings":";;;;;;;;;AAAA,IAAAA,OAAA,GAAAC,OAAA;AACA,IAAAC,GAAA,GAAAD,OAAA;AAGA,IAAAE,MAAA,GAAAF,OAAA;AACA,IAAAG,YAAA,GAAAH,OAAA;AACA,IAAAI,OAAA,GAAAJ,OAAA;AACA,IAAAK,QAAA,GAAAL,OAAA;AACA,IAAAM,WAAA,GAAAN,OAAA;AAEA,MAAMO,SAAS,GAAG,eAAe;;AAEjC;AACA,MAAMC,oBAAoB,GAAG,GAAG;;AAEhC;AACA;AACA;AACA;AAHA,IAIaC,MAAM,GAAAC,OAAA,CAAAD,MAAA;EAcjB;EACA,SAAAA,OAAmBE,GAAW,EAAEC,OAAsB,GAAG,CAAC,CAAC,EAAE;IAAA,IAAAC,gBAAA,CAAAC,OAAA,QAAAL,MAAA;IAd7D;IAAA,KACQM,MAAM,GAAiB,CAAC,CAAC;IACjC;IAAA,KACQJ,GAAG;IACX;IAAA,KACQK,QAAQ;IAChB;IAAA,KACQC,IAAI;IACZ;IAAA,KACQC,GAAG;IACX;IAAA,KACQC,QAAQ;IAId,IAAI,CAACR,GAAG,GAAGA,GAAG;IACd,IAAI,CAACK,QAAQ,GAAGJ,OAAO,CAACI,QAAQ,IAAI,KAAK;IACzC,IAAI,CAACC,IAAI,GAAGL,OAAO,CAACK,IAAI,IAAI,KAAK;IACjC,IAAI,CAACC,GAAG,GAAGN,OAAO,CAACM,GAAG,IAAI,KAAK;EACjC;;EAEA;EAAA,WAAAE,aAAA,CAAAN,OAAA,EA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D;MACA,MAAM2C,IAAI,GAAG,IAAAC,kBAAU,EAAC,KAAK,CAAC;MAC9BD,IAAI,CAACE,MAAM,CAAC7C,GAAG,CAAC8C,IAAI,CAAC,CAAC,CAAC;MACvB,MAAM3B,GAAG,GAAGwB,IAAI,CAACI,MAAM,CAAC,WAAW,CAAC;MACpC,IAAA/B,mBAAW,EAAC;QACV3B,SAAS;QACT4B,OAAO,EAAE,uBAAuBE,GAAG,GAAG;QACtCD,IAAI,EAAE;UAAEf,GAAG,EAAEH;QAAI;MACnB,CAAC,CAAC;MACF,OAAOmB,GAAG;IACZ;EAAC;AAAA","ignoreList":[]}
1
+ {"version":3,"file":"KeySet.js","names":["_crypto","require","_fs","_const","_EngineError","_report","_request","_tlsRequest","namespace","KEY_REFRESH_INTERVAL","KeySet","exports","url","options","_classCallCheck2","default","_defineProperty2","internal","file","pem","_createClass2","key","value","init","fetch","interval","setInterval","error","reportError","catch","shutdown","clearInterval","getKey","keyId","keySet","getKeys","reportDebug","message","data","kid","calculateKeyId","set","JSON","parse","readFileSync","keys","Array","EngineError","severity","LogSeverity","ERROR","reduce","createPublicKey","format","export","type","requestOptions","method","tlsRequest","request","Object","length","keyIds","hash","createHash","update","trim","digest"],"sources":["../../../src/entities/KeySet/KeySet.ts"],"sourcesContent":["import { createPublicKey, createHash } from 'crypto';\nimport { readFileSync } from 'fs';\nimport { Method } from 'axios';\nimport { KeySetOptions, KeySetValues, JWKS } from './KeySet.types';\nimport { LogSeverity } from 'const';\nimport { EngineError } from 'entities/EngineError';\nimport { reportDebug, reportError } from 'utils/report';\nimport { request } from 'utils/request';\nimport { tlsRequest } from 'utils/tlsRequest';\n\nconst namespace = 'engine:keySet';\n\n// Number of seconds between each key refresh\nconst KEY_REFRESH_INTERVAL = 300;\n\n/**\n * Fetch Json Web Key Sets and cache them\n * Keys can then be used for Json Web Token authentication\n */\nexport class KeySet {\n /** Latest known value for the keys in the set, indexed by the key id */\n private keySet: KeySetValues = {};\n /** URL at which the key set can be fetched */\n private url: string;\n /** This resource is located on a service inside of our private cluster */\n private internal: boolean;\n /** This URL is actually a path to a local key file encoded in PEM */\n private file: boolean;\n /** This input is actually a full PEM string representation of a key */\n private pem: boolean;\n /** Timer for the key fetching interval */\n private interval?: NodeJS.Timeout | string | number | undefined;\n\n /** Create a new Key Set */\n public constructor(url: string, options: KeySetOptions = {}) {\n this.url = url;\n this.internal = options.internal ?? false;\n this.file = options.file ?? false;\n this.pem = options.pem ?? false;\n }\n\n /** Calculate key ID from PEM string */\n private static calculateKeyId(pem: string): string {\n // We use the md5 hash of the PEM file to defined the key ID\n const hash = createHash('md5');\n hash.update(pem.trim());\n const kid = hash.digest('base64url');\n reportDebug({\n namespace,\n message: `Calculated Key ID: \"${kid}\"`,\n data: { key: pem }\n });\n return kid;\n }\n\n /** Initialize a KeySet, should be run on server startup to avoid any misconfiguration */\n public async init(): Promise<void> {\n await this.fetch();\n this.interval = setInterval(() => {\n (async (): Promise<void> => {\n try {\n await this.fetch();\n } catch (error) {\n reportError(error);\n }\n })().catch((error) => {\n reportError(error);\n });\n }, KEY_REFRESH_INTERVAL * 1000);\n }\n\n /** Clear any pending timers to avoid pending process */\n public shutdown(): void {\n if (this.interval) clearInterval(this.interval);\n }\n\n /** Get the PEM encoded version of a key by its id */\n public getKey(keyId: string): string | undefined {\n return this.keySet[keyId];\n }\n\n /** Get all the keys in the set mapped by their ID */\n public getKeys(): KeySetValues {\n return this.keySet;\n }\n\n /** Fetch the latest version of the key set */\n private async fetch(): Promise<void> {\n reportDebug({\n namespace,\n message: `Fetching JWKS`,\n data: { url: this.url }\n });\n\n if (this.pem) {\n // Read the key from the parameter directly\n reportDebug({\n namespace,\n message: 'Processing key from given PEM string'\n });\n\n const kid = KeySet.calculateKeyId(this.url);\n\n this.keySet = { [kid]: this.url };\n } else if (this.file) {\n // Read the key from a file\n reportDebug({\n namespace,\n message: `Reading key on disk at path \"${this.url}\"`\n });\n const set = JSON.parse(readFileSync(this.url, 'utf-8'));\n\n // Check that the returned data has the shape of a JWKS\n if (!(set.keys && set.keys instanceof Array))\n throw new EngineError({\n severity: LogSeverity.ERROR,\n message: 'Fetched key set is not in an appropriate format',\n data: { url: this.url, set }\n });\n\n // Create a node.crypto public key object for each key in the set\n this.keySet = set.keys.reduce(\n (set: { [x: string]: string; }, key: { kid: string | number; }) => {\n set[key.kid] = createPublicKey({ key, format: 'jwk' }).export({\n format: 'pem',\n type: 'spki'\n }) as string;\n return set;\n },\n {} as Record<string, string>\n );\n } else {\n // Fetch key by making a network request\n reportDebug({\n namespace,\n message: `Making network request to \"${this.url}\"`\n });\n\n const requestOptions = { url: this.url, method: 'get' as Method };\n // For services inside of our cluster we use the TLS authenticated request method\n const { data: set } = await (this.internal\n ? tlsRequest<JWKS>(requestOptions)\n : request<JWKS>(requestOptions));\n\n // Check that the returned data has the shape of a JWKS\n if (!(set.keys && set.keys instanceof Array))\n throw new EngineError({\n severity: LogSeverity.ERROR,\n message: 'Fetched key set is not in an appropriate format',\n data: { url: this.url, set }\n });\n\n // Create a node.crypto public key object for each key in the set\n this.keySet = set.keys.reduce(\n (set, key) => {\n set[key.kid] = createPublicKey({ key, format: 'jwk' }).export({\n format: 'pem',\n type: 'spki'\n }) as string;\n return set;\n },\n {} as Record<string, string>\n );\n }\n\n reportDebug({\n namespace,\n message: `Stored ${Object.keys(this.keySet).length} keys`,\n data: { keyIds: Object.keys(this.keySet) }\n });\n }\n}\n"],"mappings":";;;;;;;;;;AAAA,IAAAA,OAAA,GAAAC,OAAA;AACA,IAAAC,GAAA,GAAAD,OAAA;AAGA,IAAAE,MAAA,GAAAF,OAAA;AACA,IAAAG,YAAA,GAAAH,OAAA;AACA,IAAAI,OAAA,GAAAJ,OAAA;AACA,IAAAK,QAAA,GAAAL,OAAA;AACA,IAAAM,WAAA,GAAAN,OAAA;AAEA,MAAMO,SAAS,GAAG,eAAe;;AAEjC;AACA,MAAMC,oBAAoB,GAAG,GAAG;;AAEhC;AACA;AACA;AACA;AAHA,IAIaC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ACP,MAAM,GAAGO,GAAG,CAACI,IAAI,CAACM,MAAM,CAC3B,CAACV,GAAG,EAAEpB,GAAG,KAAK;UACZoB,GAAG,CAACpB,GAAG,CAACkB,GAAG,CAAC,GAAG,IAAAa,uBAAe,EAAC;YAAE/B,GAAG;YAAEgC,MAAM,EAAE;UAAM,CAAC,CAAC,CAACC,MAAM,CAAC;YAC5DD,MAAM,EAAE,KAAK;YACbE,IAAI,EAAE;UACR,CAAC,CAAW;UACZ,OAAOd,GAAG;QACZ,CAAC,EACD,CAAC,CACH,CAAC;MACH;MAEA,IAAAL,mBAAW,EAAC;QACV5B,SAAS;QACT6B,OAAO,EAAE,UAAUuB,MAAM,CAACf,IAAI,CAAC,IAAI,CAACX,MAAM,CAAC,CAAC2B,MAAM,OAAO;QACzDvB,IAAI,EAAE;UAAEwB,MAAM,EAAEF,MAAM,CAACf,IAAI,CAAC,IAAI,CAACX,MAAM;QAAE;MAC3C,CAAC,CAAC;IACJ;EAAC;IAAAb,GAAA;IAAAC,KAAA,EAhID,SAAekB,cAAcA,CAACrB,GAAW,EAAU;MACjD;MACA,MAAM4C,IAAI,GAAG,IAAAC,kBAAU,EAAC,KAAK,CAAC;MAC9BD,IAAI,CAACE,MAAM,CAAC9C,GAAG,CAAC+C,IAAI,CAAC,CAAC,CAAC;MACvB,MAAM3B,GAAG,GAAGwB,IAAI,CAACI,MAAM,CAAC,WAAW,CAAC;MACpC,IAAA/B,mBAAW,EAAC;QACV5B,SAAS;QACT6B,OAAO,EAAE,uBAAuBE,GAAG,GAAG;QACtCD,IAAI,EAAE;UAAEjB,GAAG,EAAEF;QAAI;MACnB,CAAC,CAAC;MACF,OAAOoB,GAAG;IACZ;EAAC;AAAA","ignoreList":[]}
@@ -1 +1 @@
1
- {"version":3,"file":"KeySet.types.js","names":[],"sources":["../../../src/entities/KeySet/KeySet.types.ts"],"sourcesContent":["import { JsonWebKey } from 'crypto';\r\n\r\n/** KeySet initialization options */\r\nexport interface KeySetOptions {\r\n /** This resource is located on a service inside of our private cluster */\r\n internal?: boolean;\r\n /** This URL is actually a path to a local key file encoded in PEM */\r\n file?: boolean;\r\n /** This input is actually a full PEM string representation of a key */\r\n pem?: boolean;\r\n}\r\n\r\n/** Keep a mapping ok keyId => PEM */\r\nexport interface KeySetValues {\r\n [id: string]: string;\r\n}\r\n\r\n/** Object holding JWK keys */\r\nexport interface JWKS {\r\n /** Key set is JWKS format */\r\n keys: Array<JWK>;\r\n}\r\n\r\n/** JWK key with custom claims */\r\ninterface JWK extends JsonWebKey {\r\n /** ID of the key */\r\n kid: string;\r\n}\r\n"],"mappings":"","ignoreList":[]}
1
+ {"version":3,"file":"KeySet.types.js","names":[],"sources":["../../../src/entities/KeySet/KeySet.types.ts"],"sourcesContent":["import { JsonWebKey } from 'crypto';\n\n/** KeySet initialization options */\nexport interface KeySetOptions {\n /** This resource is located on a service inside of our private cluster */\n internal?: boolean;\n /** This URL is actually a path to a local key file encoded in PEM */\n file?: boolean;\n /** This input is actually a full PEM string representation of a key */\n pem?: boolean;\n}\n\n/** Keep a mapping ok keyId => PEM */\nexport interface KeySetValues {\n [id: string]: string;\n}\n\n/** Object holding JWK keys */\nexport interface JWKS {\n /** Key set is JWKS format */\n keys: Array<JWK>;\n}\n\n/** JWK key with custom claims */\ninterface JWK extends JsonWebKey {\n /** ID of the key */\n kid: string;\n}\n"],"mappings":"","ignoreList":[]}
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["_KeySet","require","Object","keys","forEach","key","exports","defineProperty","enumerable","get","_KeySet2"],"sources":["../../../src/entities/KeySet/index.ts"],"sourcesContent":["export * from './KeySet';\r\nexport * from './KeySet.types';\r\n"],"mappings":";;;;;AAAA,IAAAA,OAAA,GAAAC,OAAA;AAAAC,MAAA,CAAAC,IAAA,CAAAH,OAAA,EAAAI,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAA,GAAA,IAAAC,OAAA,IAAAA,OAAA,CAAAD,GAAA,MAAAL,OAAA,CAAAK,GAAA;EAAAH,MAAA,CAAAK,cAAA,CAAAD,OAAA,EAAAD,GAAA;IAAAG,UAAA;IAAAC,GAAA,WAAAA,CAAA;MAAA,OAAAT,OAAA,CAAAK,GAAA;IAAA;EAAA;AAAA;AACA,IAAAK,QAAA,GAAAT,OAAA;AAAAC,MAAA,CAAAC,IAAA,CAAAO,QAAA,EAAAN,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAA,GAAA,IAAAC,OAAA,IAAAA,OAAA,CAAAD,GAAA,MAAAK,QAAA,CAAAL,GAAA;EAAAH,MAAA,CAAAK,cAAA,CAAAD,OAAA,EAAAD,GAAA;IAAAG,UAAA;IAAAC,GAAA,WAAAA,CAAA;MAAA,OAAAC,QAAA,CAAAL,GAAA;IAAA;EAAA;AAAA","ignoreList":[]}
1
+ {"version":3,"file":"index.js","names":["_KeySet","require","Object","keys","forEach","key","exports","defineProperty","enumerable","get","_KeySet2"],"sources":["../../../src/entities/KeySet/index.ts"],"sourcesContent":["export * from './KeySet';\nexport * from './KeySet.types';\n"],"mappings":";;;;;AAAA,IAAAA,OAAA,GAAAC,OAAA;AAAAC,MAAA,CAAAC,IAAA,CAAAH,OAAA,EAAAI,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAA,GAAA,IAAAC,OAAA,IAAAA,OAAA,CAAAD,GAAA,MAAAL,OAAA,CAAAK,GAAA;EAAAH,MAAA,CAAAK,cAAA,CAAAD,OAAA,EAAAD,GAAA;IAAAG,UAAA;IAAAC,GAAA,WAAAA,CAAA;MAAA,OAAAT,OAAA,CAAAK,GAAA;IAAA;EAAA;AAAA;AACA,IAAAK,QAAA,GAAAT,OAAA;AAAAC,MAAA,CAAAC,IAAA,CAAAO,QAAA,EAAAN,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAA,GAAA,IAAAC,OAAA,IAAAA,OAAA,CAAAD,GAAA,MAAAK,QAAA,CAAAL,GAAA;EAAAH,MAAA,CAAAK,cAAA,CAAAD,OAAA,EAAAD,GAAA;IAAAG,UAAA;IAAAC,GAAA,WAAAA,CAAA;MAAA,OAAAC,QAAA,CAAAL,GAAA;IAAA;EAAA;AAAA","ignoreList":[]}
@@ -1 +1 @@
1
- {"version":3,"file":"LifecycleController.js","names":["runningInstances","exports","Set","LifecycleController","register","instance","add","shutdownRunningInstances","promises","push","shutdown","bind","Promise","all","clear"],"sources":["../../../src/entities/LifecycleController/LifecycleController.ts"],"sourcesContent":["import { LifecycleControlledInstance } from './LifecycleController.types';\r\n\r\n/** List of initialized entities */\r\nexport const runningInstances: Set<LifecycleControlledInstance> = new Set();\r\n\r\n/** LifecycleController is used to shutdown all the entities on server shutdown */\r\nexport const LifecycleController = {\r\n /** Add the initialized instances into the runningInstance property */\r\n register(instance: LifecycleControlledInstance): void {\r\n runningInstances.add(instance);\r\n },\r\n\r\n /** Shutdown all the running instances */\r\n async shutdownRunningInstances(): Promise<void> {\r\n const promises = [];\r\n for (const instance of runningInstances) {\r\n if (instance) {\r\n promises.push(instance.shutdown.bind(instance)());\r\n }\r\n }\r\n await Promise.all(promises);\r\n runningInstances.clear();\r\n }\r\n};\r\n"],"mappings":";;;;;;AAEA;AACO,MAAMA,gBAAkD,GAAAC,OAAA,CAAAD,gBAAA,GAAG,IAAIE,GAAG,CAAC,CAAC;;AAE3E;AACO,MAAMC,mBAAmB,GAAAF,OAAA,CAAAE,mBAAA,GAAG;EACjC;EACAC,QAAQA,CAACC,QAAqC,EAAQ;IACpDL,gBAAgB,CAACM,GAAG,CAACD,QAAQ,CAAC;EAChC,CAAC;EAED;EACA,MAAME,wBAAwBA,CAAA,EAAkB;IAC9C,MAAMC,QAAQ,GAAG,EAAE;IACnB,KAAK,MAAMH,QAAQ,IAAIL,gBAAgB,EAAE;MACvC,IAAIK,QAAQ,EAAE;QACZG,QAAQ,CAACC,IAAI,CAACJ,QAAQ,CAACK,QAAQ,CAACC,IAAI,CAACN,QAAQ,CAAC,CAAC,CAAC,CAAC;MACnD;IACF;IACA,MAAMO,OAAO,CAACC,GAAG,CAACL,QAAQ,CAAC;IAC3BR,gBAAgB,CAACc,KAAK,CAAC,CAAC;EAC1B;AACF,CAAC","ignoreList":[]}
1
+ {"version":3,"file":"LifecycleController.js","names":["runningInstances","exports","Set","LifecycleController","register","instance","add","shutdownRunningInstances","promises","push","shutdown","bind","Promise","all","clear"],"sources":["../../../src/entities/LifecycleController/LifecycleController.ts"],"sourcesContent":["import { LifecycleControlledInstance } from './LifecycleController.types';\n\n/** List of initialized entities */\nexport const runningInstances: Set<LifecycleControlledInstance> = new Set();\n\n/** LifecycleController is used to shutdown all the entities on server shutdown */\nexport const LifecycleController = {\n /** Add the initialized instances into the runningInstance property */\n register(instance: LifecycleControlledInstance): void {\n runningInstances.add(instance);\n },\n\n /** Shutdown all the running instances */\n async shutdownRunningInstances(): Promise<void> {\n const promises = [];\n for (const instance of runningInstances) {\n if (instance) {\n promises.push(instance.shutdown.bind(instance)());\n }\n }\n await Promise.all(promises);\n runningInstances.clear();\n }\n};\n"],"mappings":";;;;;;AAEA;AACO,MAAMA,gBAAkD,GAAAC,OAAA,CAAAD,gBAAA,GAAG,IAAIE,GAAG,CAAC,CAAC;;AAE3E;AACO,MAAMC,mBAAmB,GAAAF,OAAA,CAAAE,mBAAA,GAAG;EACjC;EACAC,QAAQA,CAACC,QAAqC,EAAQ;IACpDL,gBAAgB,CAACM,GAAG,CAACD,QAAQ,CAAC;EAChC,CAAC;EAED;EACA,MAAME,wBAAwBA,CAAA,EAAkB;IAC9C,MAAMC,QAAQ,GAAG,EAAE;IACnB,KAAK,MAAMH,QAAQ,IAAIL,gBAAgB,EAAE;MACvC,IAAIK,QAAQ,EAAE;QACZG,QAAQ,CAACC,IAAI,CAACJ,QAAQ,CAACK,QAAQ,CAACC,IAAI,CAACN,QAAQ,CAAC,CAAC,CAAC,CAAC;MACnD;IACF;IACA,MAAMO,OAAO,CAACC,GAAG,CAACL,QAAQ,CAAC;IAC3BR,gBAAgB,CAACc,KAAK,CAAC,CAAC;EAC1B;AACF,CAAC","ignoreList":[]}
@@ -1 +1 @@
1
- {"version":3,"file":"LifecycleController.types.js","names":[],"sources":["../../../src/entities/LifecycleController/LifecycleController.types.ts"],"sourcesContent":["/** Service instance that can be auto-shutdown by the Lifecycle Controller */\r\nexport interface LifecycleControlledInstance {\r\n /** Function that will be called on server shutdown, should trigger the instance cleanup */\r\n shutdown: () => void | Promise<void>;\r\n}\r\n"],"mappings":"","ignoreList":[]}
1
+ {"version":3,"file":"LifecycleController.types.js","names":[],"sources":["../../../src/entities/LifecycleController/LifecycleController.types.ts"],"sourcesContent":["/** Service instance that can be auto-shutdown by the Lifecycle Controller */\nexport interface LifecycleControlledInstance {\n /** Function that will be called on server shutdown, should trigger the instance cleanup */\n shutdown: () => void | Promise<void>;\n}\n"],"mappings":"","ignoreList":[]}
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["_LifecycleController","require","_LifecycleController2","Object","keys","forEach","key","prototype","hasOwnProperty","call","_exportNames","exports","defineProperty","enumerable","get"],"sources":["../../../src/entities/LifecycleController/index.ts"],"sourcesContent":["export { LifecycleController } from './LifecycleController';\r\nexport * from './LifecycleController.types';\r\n"],"mappings":";;;;;;;;;;;;;;AAAA,IAAAA,oBAAA,GAAAC,OAAA;AACA,IAAAC,qBAAA,GAAAD,OAAA;AAAAE,MAAA,CAAAC,IAAA,CAAAF,qBAAA,EAAAG,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAH,MAAA,CAAAI,SAAA,CAAAC,cAAA,CAAAC,IAAA,CAAAC,YAAA,EAAAJ,GAAA;EAAA,IAAAA,GAAA,IAAAK,OAAA,IAAAA,OAAA,CAAAL,GAAA,MAAAJ,qBAAA,CAAAI,GAAA;EAAAH,MAAA,CAAAS,cAAA,CAAAD,OAAA,EAAAL,GAAA;IAAAO,UAAA;IAAAC,GAAA,WAAAA,CAAA;MAAA,OAAAZ,qBAAA,CAAAI,GAAA;IAAA;EAAA;AAAA","ignoreList":[]}
1
+ {"version":3,"file":"index.js","names":["_LifecycleController","require","_LifecycleController2","Object","keys","forEach","key","prototype","hasOwnProperty","call","_exportNames","exports","defineProperty","enumerable","get"],"sources":["../../../src/entities/LifecycleController/index.ts"],"sourcesContent":["export { LifecycleController } from './LifecycleController';\nexport * from './LifecycleController.types';\n"],"mappings":";;;;;;;;;;;;;;AAAA,IAAAA,oBAAA,GAAAC,OAAA;AACA,IAAAC,qBAAA,GAAAD,OAAA;AAAAE,MAAA,CAAAC,IAAA,CAAAF,qBAAA,EAAAG,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAH,MAAA,CAAAI,SAAA,CAAAC,cAAA,CAAAC,IAAA,CAAAC,YAAA,EAAAJ,GAAA;EAAA,IAAAA,GAAA,IAAAK,OAAA,IAAAA,OAAA,CAAAL,GAAA,MAAAJ,qBAAA,CAAAI,GAAA;EAAAH,MAAA,CAAAS,cAAA,CAAAD,OAAA,EAAAL,GAAA;IAAAO,UAAA;IAAAC,GAAA,WAAAA,CAAA;MAAA,OAAAZ,qBAAA,CAAAI,GAAA;IAAA;EAAA;AAAA","ignoreList":[]}
@@ -32,8 +32,8 @@ const Localizator = exports.Localizator = {
32
32
  }, REFRESH_FREQUENCY);
33
33
  _LifecycleController.LifecycleController.register(Localizator);
34
34
  },
35
- /**
36
- * Fetch a JSON file from the locales bucket
35
+ /**
36
+ * Fetch a JSON file from the locales bucket
37
37
  */
38
38
  async getLocaleFile(file) {
39
39
  (0, _report.reportDebug)({
@@ -60,9 +60,9 @@ const Localizator = exports.Localizator = {
60
60
  });
61
61
  return result;
62
62
  },
63
- /**
64
- * Synchronizes the localeData and scripts files
65
- * Should be called only once on startup
63
+ /**
64
+ * Synchronizes the localeData and scripts files
65
+ * Should be called only once on startup
66
66
  */
67
67
  async synchronize() {
68
68
  (0, _report.reportDebug)({
@@ -95,8 +95,8 @@ const Localizator = exports.Localizator = {
95
95
  const name = firstName + lastName; // merge two names if possible
96
96
  return (0, _guessNamingConvention.guessNamingConvention)(scripts, localeData, name, locale);
97
97
  },
98
- /**
99
- * Calculate the different display names for a user
98
+ /**
99
+ * Calculate the different display names for a user
100
100
  */
101
101
  getDisplayNames(firstName, lastName, locale) {
102
102
  const convention = Localizator.guessNamingConvention(firstName, lastName, locale);
@@ -1 +1 @@
1
- {"version":3,"file":"Localizator.js","names":["_guessNamingConvention","require","_EngineError","_LifecycleController","_Storage","_checkEnvironment","_envAssert","_report","namespace","REFRESH_FREQUENCY","localeData","scripts","interval","Localizator","exports","init","checkEnvironment","LOCALES_BUCKET","envAssert","isString","synchronize","setInterval","catch","error","reportError","LifecycleController","register","getLocaleFile","file","reportDebug","message","data","bucket","process","env","Storage","get","stringified","toString","result","JSON","parse","fetchedLocaleData","fetchedScripts","Promise","all","buildRangeRegex","script","i","Object","keys","ranges","rangeRegex","RegExp","join","guessNamingConvention","firstName","lastName","locale","EngineError","name","getDisplayNames","convention","reduce","type","safeType","replace","trim","getLocaleData","isValidLocale","undefined","shutdown","clearTimeout"],"sources":["../../../src/entities/Localizator/Localizator.ts"],"sourcesContent":["import { guessNamingConvention } from './guessNamingConvention';\r\nimport {\r\n LocalizatorLocalizationData,\r\n LocalizatorLocalizationDataElement,\r\n LocalizatorScripts,\r\n LocalizatorNamingConventions\r\n} from './Localizator.types';\r\nimport { EngineError } from 'entities/EngineError';\r\nimport { LifecycleController } from 'entities/LifecycleController';\r\nimport { Storage } from 'entities/Storage';\r\nimport { checkEnvironment } from 'utils/checkEnvironment';\r\nimport { envAssert } from 'utils/envAssert';\r\nimport { reportError, reportDebug } from 'utils/report';\r\n\r\nconst namespace = 'engine:localizator';\r\n\r\nconst REFRESH_FREQUENCY = 10 * 60 * 1000;\r\n\r\nlet localeData: undefined | LocalizatorLocalizationData;\r\nlet scripts: undefined | LocalizatorScripts;\r\nlet interval: NodeJS.Timeout | string | number | undefined;\r\n\r\n/** Service handling contextual localization */\r\nexport const Localizator = {\r\n async init(): Promise<void> {\r\n checkEnvironment({ LOCALES_BUCKET: envAssert.isString() });\r\n await Localizator.synchronize();\r\n // Keep synchronizing\r\n interval = setInterval(() => {\r\n Localizator.synchronize().catch((error) => {\r\n reportError(error);\r\n });\r\n }, REFRESH_FREQUENCY);\r\n LifecycleController.register(Localizator);\r\n },\r\n\r\n /**\r\n * Fetch a JSON file from the locales bucket\r\n */\r\n async getLocaleFile<T>(file: string): Promise<T> {\r\n reportDebug({\r\n namespace,\r\n message: `Starting download of localization file [${file}]`,\r\n data: { bucket: process.env.LOCALES_BUCKET, file }\r\n });\r\n const { data } = await Storage.get(\r\n process.env.LOCALES_BUCKET as string,\r\n file\r\n );\r\n const stringified = data.toString('utf-8');\r\n const result = JSON.parse(stringified) as T;\r\n reportDebug({\r\n namespace,\r\n message: `Fetched localization file [${file}]`,\r\n data: { bucket: process.env.LOCALES_BUCKET, file, result }\r\n });\r\n return result;\r\n },\r\n\r\n /**\r\n * Synchronizes the localeData and scripts files\r\n * Should be called only once on startup\r\n */\r\n async synchronize(): Promise<void> {\r\n reportDebug({ namespace, message: `Starting synchronizing` });\r\n const [fetchedLocaleData, fetchedScripts] = await Promise.all([\r\n Localizator.getLocaleFile<LocalizatorLocalizationData>('localeData.json'),\r\n Localizator.getLocaleFile<LocalizatorScripts>('scripts.json')\r\n ]);\r\n localeData = fetchedLocaleData;\r\n scripts = Localizator.buildRangeRegex(fetchedScripts);\r\n reportDebug({ namespace, message: `Finished synchronizing` });\r\n },\r\n\r\n /** Transform unicode ranges in scripts data to regex */\r\n buildRangeRegex(script: LocalizatorScripts): LocalizatorScripts {\r\n for (const i of Object.keys(script)) {\r\n const ranges = script[i].ranges;\r\n if (ranges) {\r\n script[i].rangeRegex = new RegExp(`[${ranges.join('')}]`, 'u');\r\n }\r\n }\r\n return script;\r\n },\r\n\r\n /** Guess the naming convention to use for a given name and locale */\r\n guessNamingConvention(\r\n firstName: string,\r\n lastName: string,\r\n locale: string\r\n ): LocalizatorNamingConventions {\r\n if (!scripts || !localeData)\r\n throw new EngineError({ message: 'Localizator is not initialized' });\r\n const name = firstName + lastName; // merge two names if possible\r\n return guessNamingConvention(scripts, localeData, name, locale);\r\n },\r\n\r\n /**\r\n * Calculate the different display names for a user\r\n */\r\n getDisplayNames(\r\n firstName: string,\r\n lastName: string,\r\n locale: string\r\n ): LocalizatorNamingConventions {\r\n const convention = Localizator.guessNamingConvention(\r\n firstName,\r\n lastName,\r\n locale\r\n );\r\n return Object.keys(convention).reduce((convention, type) => {\r\n const safeType = type as keyof LocalizatorNamingConventions;\r\n convention[safeType] = convention[safeType]\r\n .replace('{firstName}', firstName)\r\n .replace('{lastName}', lastName ?? '')\r\n .trim();\r\n return convention;\r\n }, convention);\r\n },\r\n\r\n /** Get the localization data for a locale */\r\n getLocaleData(locale: string): LocalizatorLocalizationDataElement {\r\n if (!localeData)\r\n throw new EngineError({ message: 'Localizator is not initialized' });\r\n return localeData[locale];\r\n },\r\n\r\n /** Check if a locale exists */\r\n isValidLocale(locale: string): boolean {\r\n if (!localeData)\r\n throw new EngineError({ message: 'Localizator is not initialized' });\r\n return localeData[locale] !== undefined;\r\n },\r\n\r\n /** Cleanup the instance */\r\n shutdown(): void {\r\n if (interval) clearTimeout(interval);\r\n }\r\n};\r\n"],"mappings":";;;;;;AAAA,IAAAA,sBAAA,GAAAC,OAAA;AAOA,IAAAC,YAAA,GAAAD,OAAA;AACA,IAAAE,oBAAA,GAAAF,OAAA;AACA,IAAAG,QAAA,GAAAH,OAAA;AACA,IAAAI,iBAAA,GAAAJ,OAAA;AACA,IAAAK,UAAA,GAAAL,OAAA;AACA,IAAAM,OAAA,GAAAN,OAAA;AAEA,MAAMO,SAAS,GAAG,oBAAoB;AAEtC,MAAMC,iBAAiB,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI;AAExC,IAAIC,UAAmD;AACvD,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AM,CAAC;EACjE,CAAC;EAED;AACF;AACA;EACEG,eAAeA,CACbL,SAAiB,EACjBC,QAAgB,EAChBC,MAAc,EACgB;IAC9B,MAAMI,UAAU,GAAGjD,WAAW,CAAC0C,qBAAqB,CAClDC,SAAS,EACTC,QAAQ,EACRC,MACF,CAAC;IACD,OAAOT,MAAM,CAACC,IAAI,CAACY,UAAU,CAAC,CAACC,MAAM,CAAC,CAACD,UAAU,EAAEE,IAAI,KAAK;MAC1D,MAAMC,QAAQ,GAAGD,IAA0C;MAC3DF,UAAU,CAACG,QAAQ,CAAC,GAAGH,UAAU,CAACG,QAAQ,CAAC,CACxCC,OAAO,CAAC,aAAa,EAAEV,SAAS,CAAC,CACjCU,OAAO,CAAC,YAAY,EAAET,QAAQ,IAAI,EAAE,CAAC,CACrCU,IAAI,CAAC,CAAC;MACT,OAAOL,UAAU;IACnB,CAAC,EAAEA,UAAU,CAAC;EAChB,CAAC;EAED;EACAM,aAAaA,CAACV,MAAc,EAAsC;IAChE,IAAI,CAAChD,UAAU,EACb,MAAM,IAAIiD,wBAAW,CAAC;MAAE7B,OAAO,EAAE;IAAiC,CAAC,CAAC;IACtE,OAAOpB,UAAU,CAACgD,MAAM,CAAC;EAC3B,CAAC;EAED;EACAW,aAAaA,CAACX,MAAc,EAAW;IACrC,IAAI,CAAChD,UAAU,EACb,MAAM,IAAIiD,wBAAW,CAAC;MAAE7B,OAAO,EAAE;IAAiC,CAAC,CAAC;IACtE,OAAOpB,UAAU,CAACgD,MAAM,CAAC,KAAKY,SAAS;EACzC,CAAC;EAED;EACAC,QAAQA,CAAA,EAAS;IACf,IAAI3D,QAAQ,EAAE4D,YAAY,CAAC5D,QAAQ,CAAC;EACtC;AACF,CAAC","ignoreList":[]}
1
+ {"version":3,"file":"Localizator.js","names":["_guessNamingConvention","require","_EngineError","_LifecycleController","_Storage","_checkEnvironment","_envAssert","_report","namespace","REFRESH_FREQUENCY","localeData","scripts","interval","Localizator","exports","init","checkEnvironment","LOCALES_BUCKET","envAssert","isString","synchronize","setInterval","catch","error","reportError","LifecycleController","register","getLocaleFile","file","reportDebug","message","data","bucket","process","env","Storage","get","stringified","toString","result","JSON","parse","fetchedLocaleData","fetchedScripts","Promise","all","buildRangeRegex","script","i","Object","keys","ranges","rangeRegex","RegExp","join","guessNamingConvention","firstName","lastName","locale","EngineError","name","getDisplayNames","convention","reduce","type","safeType","replace","trim","getLocaleData","isValidLocale","undefined","shutdown","clearTimeout"],"sources":["../../../src/entities/Localizator/Localizator.ts"],"sourcesContent":["import { guessNamingConvention } from './guessNamingConvention';\nimport {\n LocalizatorLocalizationData,\n LocalizatorLocalizationDataElement,\n LocalizatorScripts,\n LocalizatorNamingConventions\n} from './Localizator.types';\nimport { EngineError } from 'entities/EngineError';\nimport { LifecycleController } from 'entities/LifecycleController';\nimport { Storage } from 'entities/Storage';\nimport { checkEnvironment } from 'utils/checkEnvironment';\nimport { envAssert } from 'utils/envAssert';\nimport { reportError, reportDebug } from 'utils/report';\n\nconst namespace = 'engine:localizator';\n\nconst REFRESH_FREQUENCY = 10 * 60 * 1000;\n\nlet localeData: undefined | LocalizatorLocalizationData;\nlet scripts: undefined | LocalizatorScripts;\nlet interval: NodeJS.Timeout | string | number | undefined;\n\n/** Service handling contextual localization */\nexport const Localizator = {\n async init(): Promise<void> {\n checkEnvironment({ LOCALES_BUCKET: envAssert.isString() });\n await Localizator.synchronize();\n // Keep synchronizing\n interval = setInterval(() => {\n Localizator.synchronize().catch((error) => {\n reportError(error);\n });\n }, REFRESH_FREQUENCY);\n LifecycleController.register(Localizator);\n },\n\n /**\n * Fetch a JSON file from the locales bucket\n */\n async getLocaleFile<T>(file: string): Promise<T> {\n reportDebug({\n namespace,\n message: `Starting download of localization file [${file}]`,\n data: { bucket: process.env.LOCALES_BUCKET, file }\n });\n const { data } = await Storage.get(\n process.env.LOCALES_BUCKET as string,\n file\n );\n const stringified = data.toString('utf-8');\n const result = JSON.parse(stringified) as T;\n reportDebug({\n namespace,\n message: `Fetched localization file [${file}]`,\n data: { bucket: process.env.LOCALES_BUCKET, file, result }\n });\n return result;\n },\n\n /**\n * Synchronizes the localeData and scripts files\n * Should be called only once on startup\n */\n async synchronize(): Promise<void> {\n reportDebug({ namespace, message: `Starting synchronizing` });\n const [fetchedLocaleData, fetchedScripts] = await Promise.all([\n Localizator.getLocaleFile<LocalizatorLocalizationData>('localeData.json'),\n Localizator.getLocaleFile<LocalizatorScripts>('scripts.json')\n ]);\n localeData = fetchedLocaleData;\n scripts = Localizator.buildRangeRegex(fetchedScripts);\n reportDebug({ namespace, message: `Finished synchronizing` });\n },\n\n /** Transform unicode ranges in scripts data to regex */\n buildRangeRegex(script: LocalizatorScripts): LocalizatorScripts {\n for (const i of Object.keys(script)) {\n const ranges = script[i].ranges;\n if (ranges) {\n script[i].rangeRegex = new RegExp(`[${ranges.join('')}]`, 'u');\n }\n }\n return script;\n },\n\n /** Guess the naming convention to use for a given name and locale */\n guessNamingConvention(\n firstName: string,\n lastName: string,\n locale: string\n ): LocalizatorNamingConventions {\n if (!scripts || !localeData)\n throw new EngineError({ message: 'Localizator is not initialized' });\n const name = firstName + lastName; // merge two names if possible\n return guessNamingConvention(scripts, localeData, name, locale);\n },\n\n /**\n * Calculate the different display names for a user\n */\n getDisplayNames(\n firstName: string,\n lastName: string,\n locale: string\n ): LocalizatorNamingConventions {\n const convention = Localizator.guessNamingConvention(\n firstName,\n lastName,\n locale\n );\n return Object.keys(convention).reduce((convention, type) => {\n const safeType = type as keyof LocalizatorNamingConventions;\n convention[safeType] = convention[safeType]\n .replace('{firstName}', firstName)\n .replace('{lastName}', lastName ?? '')\n .trim();\n return convention;\n }, convention);\n },\n\n /** Get the localization data for a locale */\n getLocaleData(locale: string): LocalizatorLocalizationDataElement {\n if (!localeData)\n throw new EngineError({ message: 'Localizator is not initialized' });\n return localeData[locale];\n },\n\n /** Check if a locale exists */\n isValidLocale(locale: string): boolean {\n if (!localeData)\n throw new EngineError({ message: 'Localizator is not initialized' });\n return localeData[locale] !== undefined;\n },\n\n /** Cleanup the instance */\n shutdown(): void {\n if (interval) clearTimeout(interval);\n }\n};\n"],"mappings":";;;;;;AAAA,IAAAA,sBAAA,GAAAC,OAAA;AAOA,IAAAC,YAAA,GAAAD,OAAA;AACA,IAAAE,oBAAA,GAAAF,OAAA;AACA,IAAAG,QAAA,GAAAH,OAAA;AACA,IAAAI,iBAAA,GAAAJ,OAAA;AACA,IAAAK,UAAA,GAAAL,OAAA;AACA,IAAAM,OAAA,GAAAN,OAAA;AAEA,MAAMO,SAAS,GAAG,oBAAoB;AAEtC,MAAMC,iBAAiB,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI;AAExC,IAAIC,UAAmD;AACvD,IAAIC,OAAuC;AAC3C,IAAIC,QAAsD;;AAE1D;AACO,MAAMC,WAAW,GAAAC,OAAA,CAAAD,WAAA,GAAG;EACzB,MAAME,IAAIA,CAAA,EAAkB;IAC1B,IAAAC,kCAAgB,EAAC;MAAEC,cAAc,EAAEC,oBAAS,CAACC,QAAQ,CAAC;IAAE,CAAC,CAAC;IAC1D,MAAMN,WAAW,CAACO,WAAW,CAAC,CAAC;IAC/B;IACAR,QAAQ,GAAGS,WAAW,CAAC,MAAM;MAC3BR,WAAW,CAACO,WAAW,CAAC,CAAC,CAACE,KAAK,CAAEC,KAAK,IAAK;QACzC,IAAAC,mBAAW,EAACD,KAAK,CAAC;MACpB,CAAC,CAAC;IACJ,CAAC,EAAEd,iBAAiB,CAAC;IACrBgB,wCAAmB,CAACC,QAAQ,CAACb,WAAW,CAAC;EAC3C,CAAC;EAED;AACF;AACA;EACE,MAAMc,aAAaA,CAAIC,IAAY,EAAc;IAC/C,IAAAC,mBAAW,EAAC;MACVrB,SAAS;MACTsB,OAAO,EAAE,2CAA2CF,IAAI,GAAG;MAC3DG,IAAI,EAAE;QAAEC,MAAM,EAAEC,OAAO,CAACC,GAAG,CAACjB,cAAc;QAAEW;MAAK;IACnD,CAAC,CAAC;IACF,MAAM;MAAEG;IAAK,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,EAAW;IACrC,IAAI,CAAChD,UAAU,EACb,MAAM,IAAIiD,wBAAW,CAAC;MAAE7B,OAAO,EAAE;IAAiC,CAAC,CAAC;IACtE,OAAOpB,UAAU,CAACgD,MAAM,CAAC,KAAKY,SAAS;EACzC,CAAC;EAED;EACAC,QAAQA,CAAA,EAAS;IACf,IAAI3D,QAAQ,EAAE4D,YAAY,CAAC5D,QAAQ,CAAC;EACtC;AACF,CAAC","ignoreList":[]}
@@ -1 +1 @@
1
- {"version":3,"file":"Localizator.types.js","names":[],"sources":["../../../src/entities/Localizator/Localizator.types.ts"],"sourcesContent":["/** Defines how a name should be displayed for a locale in diferent context */\r\nexport interface LocalizatorNamingConventions {\r\n /** How the name is displayed in a common way */\r\n regular: string;\r\n /** How the name is displayed in a formal way */\r\n formal: string;\r\n /** How the name is displayed in a casual way */\r\n casual: string;\r\n}\r\n\r\n/** Localization data for each of the locales */\r\nexport interface LocalizatorLocalizationData {\r\n [locale: string]: LocalizatorLocalizationDataElement;\r\n}\r\n\r\n/** Describes localization settings for a locale */\r\nexport interface LocalizatorLocalizationDataElement {\r\n /** Is this locale available to the public */\r\n enabled: boolean;\r\n /** How this locale is displayed to the user */\r\n display: string;\r\n /** Configuration on how to display names in that locale */\r\n names: {\r\n /** Should the first name or the last name be displayed first */\r\n firstNameFirst: boolean;\r\n /** Is there a space between the two parts of the name */\r\n spacing: boolean;\r\n /** In case the user's name is not displayed in this language's script, how should it be displayed */\r\n fallback?: LocalizatorNamingConventions;\r\n };\r\n /** Script used to identify text written in that language */\r\n script?: string;\r\n /** Key in google translation to identify that language */\r\n cloudTranslationKey: string;\r\n /** Unicode CLDR key to identify that language if it is different from the locale */\r\n unicode?: string;\r\n}\r\n\r\n/** Script config data indexed by the script id */\r\nexport interface LocalizatorScripts {\r\n [script: string]: LocalizatorScript;\r\n}\r\n\r\n/** Localization config for a script */\r\nexport interface LocalizatorScript {\r\n /** Unicode range used to detect the script */\r\n ranges: Array<string>;\r\n /** How names are displayed when written in the script */\r\n names: LocalizatorNamingConventions;\r\n /** Regex added by the Localizator, used to match with the script unicode ranges */\r\n rangeRegex?: RegExp;\r\n}\r\n"],"mappings":"","ignoreList":[]}
1
+ {"version":3,"file":"Localizator.types.js","names":[],"sources":["../../../src/entities/Localizator/Localizator.types.ts"],"sourcesContent":["/** Defines how a name should be displayed for a locale in diferent context */\nexport interface LocalizatorNamingConventions {\n /** How the name is displayed in a common way */\n regular: string;\n /** How the name is displayed in a formal way */\n formal: string;\n /** How the name is displayed in a casual way */\n casual: string;\n}\n\n/** Localization data for each of the locales */\nexport interface LocalizatorLocalizationData {\n [locale: string]: LocalizatorLocalizationDataElement;\n}\n\n/** Describes localization settings for a locale */\nexport interface LocalizatorLocalizationDataElement {\n /** Is this locale available to the public */\n enabled: boolean;\n /** How this locale is displayed to the user */\n display: string;\n /** Configuration on how to display names in that locale */\n names: {\n /** Should the first name or the last name be displayed first */\n firstNameFirst: boolean;\n /** Is there a space between the two parts of the name */\n spacing: boolean;\n /** In case the user's name is not displayed in this language's script, how should it be displayed */\n fallback?: LocalizatorNamingConventions;\n };\n /** Script used to identify text written in that language */\n script?: string;\n /** Key in google translation to identify that language */\n cloudTranslationKey: string;\n /** Unicode CLDR key to identify that language if it is different from the locale */\n unicode?: string;\n}\n\n/** Script config data indexed by the script id */\nexport interface LocalizatorScripts {\n [script: string]: LocalizatorScript;\n}\n\n/** Localization config for a script */\nexport interface LocalizatorScript {\n /** Unicode range used to detect the script */\n ranges: Array<string>;\n /** How names are displayed when written in the script */\n names: LocalizatorNamingConventions;\n /** Regex added by the Localizator, used to match with the script unicode ranges */\n rangeRegex?: RegExp;\n}\n"],"mappings":"","ignoreList":[]}
@@ -1 +1 @@
1
- {"version":3,"file":"guessNamingConvention.js","names":["DEFAULT_NAMING_CONVENTION","exports","regular","formal","casual","guessNamingConvention","scripts","localeData","name","locale","script","defaultScript","testScriptMatch","names","Object","keys","fallback","string","rangeRegex","test"],"sources":["../../../../src/entities/Localizator/guessNamingConvention/guessNamingConvention.ts"],"sourcesContent":["import {\r\n LocalizatorLocalizationData,\r\n LocalizatorScripts,\r\n LocalizatorNamingConventions\r\n} from '../Localizator.types';\r\n\r\nexport const DEFAULT_NAMING_CONVENTION = {\r\n regular: '{firstName} {lastName}',\r\n formal: '{firstName}',\r\n casual: '{firstName}'\r\n};\r\n\r\n/** Guess the naming convention to use for a given name and locale */\r\nexport function guessNamingConvention(\r\n scripts: LocalizatorScripts,\r\n localeData: LocalizatorLocalizationData,\r\n name: string,\r\n locale: string\r\n): LocalizatorNamingConventions {\r\n // When the locale has a specific script\r\n // Check if the name matches that script, and use its naming convention\r\n if (localeData[locale]?.script) {\r\n const defaultScript = localeData[locale].script as string;\r\n if (\r\n testScriptMatch(scripts, defaultScript, name) &&\r\n scripts[defaultScript].names\r\n ) {\r\n return scripts[defaultScript].names;\r\n }\r\n }\r\n\r\n // Check if there is a match with any given script and use its naming convention\r\n for (const script of Object.keys(scripts)) {\r\n if (testScriptMatch(scripts, script, name) && scripts[script].names) {\r\n return scripts[script].names;\r\n }\r\n }\r\n\r\n // Use the current locale's fallback convention\r\n if (localeData[locale]?.names?.fallback) {\r\n return localeData[locale].names.fallback as LocalizatorNamingConventions;\r\n }\r\n\r\n // If everything fails, use the default convention\r\n return DEFAULT_NAMING_CONVENTION;\r\n}\r\n\r\n/** Test if a given string is in a given script */\r\nfunction testScriptMatch(\r\n scripts: LocalizatorScripts,\r\n script: string,\r\n string: string\r\n): boolean {\r\n if (scripts[script]?.rangeRegex) {\r\n return (scripts[script].rangeRegex as RegExp).test(string);\r\n }\r\n return false;\r\n}\r\n"],"mappings":";;;;;;;AAMO,MAAMA,yBAAyB,GAAAC,OAAA,CAAAD,yBAAA,GAAG;EACvCE,OAAO,EAAE,wBAAwB;EACjCC,MAAM,EAAE,aAAa;EACrBC,MAAM,EAAE;AACV,CAAC;;AAED;AACO,SAASC,qBAAqBA,CACnCC,OAA2B,EAC3BC,UAAuC,EACvCC,IAAY,EACZC,MAAc,EACgB;EAC9B;EACA;EACA,IAAIF,UAAU,CAACE,MAAM,CAAC,EAAEC,MAAM,EAAE;IAC9B,MAAMC,aAAa,GAAGJ,UAAU,CAACE,MAAM,CAAC,CAACC,MAAgB;IACzD,IACEE,eAAe,CAACN,OAAO,EAAEK,aAAa,EAAEH,IAAI,CAAC,IAC7CF,OAAO,CAACK,aAAa,CAAC,CAACE,KAAK,EAC5B;MACA,OAAOP,OAAO,CAACK,aAAa,CAAC,CAACE,KAAK;IACrC;EACF;;EAEA;EACA,KAAK,MAAMH,MAAM,IAAII,MAAM,CAACC,IAAI,CAACT,OAAO,CAAC,EAAE;IACzC,IAAIM,eAAe,CAACN,OAAO,EAAEI,MAAM,EAAEF,IAAI,CAAC,IAAIF,OAAO,CAACI,MAAM,CAAC,CAACG,KAAK,EAAE;MACnE,OAAOP,OAAO,CAACI,MAAM,CAAC,CAACG,KAAK;IAC9B;EACF;;EAEA;EACA,IAAIN,UAAU,CAACE,MAAM,CAAC,EAAEI,KAAK,EAAEG,QAAQ,EAAE;IACvC,OAAOT,UAAU,CAACE,MAAM,CAAC,CAACI,KAAK,CAACG,QAAQ;EAC1C;;EAEA;EACA,OAAOhB,yBAAyB;AAClC;;AAEA;AACA,SAASY,eAAeA,CACtBN,OAA2B,EAC3BI,MAAc,EACdO,MAAc,EACL;EACT,IAAIX,OAAO,CAACI,MAAM,CAAC,EAAEQ,UAAU,EAAE;IAC/B,OAAQZ,OAAO,CAACI,MAAM,CAAC,CAACQ,UAAU,CAAYC,IAAI,CAACF,MAAM,CAAC;EAC5D;EACA,OAAO,KAAK;AACd","ignoreList":[]}
1
+ {"version":3,"file":"guessNamingConvention.js","names":["DEFAULT_NAMING_CONVENTION","exports","regular","formal","casual","guessNamingConvention","scripts","localeData","name","locale","script","defaultScript","testScriptMatch","names","Object","keys","fallback","string","rangeRegex","test"],"sources":["../../../../src/entities/Localizator/guessNamingConvention/guessNamingConvention.ts"],"sourcesContent":["import {\n LocalizatorLocalizationData,\n LocalizatorScripts,\n LocalizatorNamingConventions\n} from '../Localizator.types';\n\nexport const DEFAULT_NAMING_CONVENTION = {\n regular: '{firstName} {lastName}',\n formal: '{firstName}',\n casual: '{firstName}'\n};\n\n/** Guess the naming convention to use for a given name and locale */\nexport function guessNamingConvention(\n scripts: LocalizatorScripts,\n localeData: LocalizatorLocalizationData,\n name: string,\n locale: string\n): LocalizatorNamingConventions {\n // When the locale has a specific script\n // Check if the name matches that script, and use its naming convention\n if (localeData[locale]?.script) {\n const defaultScript = localeData[locale].script as string;\n if (\n testScriptMatch(scripts, defaultScript, name) &&\n scripts[defaultScript].names\n ) {\n return scripts[defaultScript].names;\n }\n }\n\n // Check if there is a match with any given script and use its naming convention\n for (const script of Object.keys(scripts)) {\n if (testScriptMatch(scripts, script, name) && scripts[script].names) {\n return scripts[script].names;\n }\n }\n\n // Use the current locale's fallback convention\n if (localeData[locale]?.names?.fallback) {\n return localeData[locale].names.fallback as LocalizatorNamingConventions;\n }\n\n // If everything fails, use the default convention\n return DEFAULT_NAMING_CONVENTION;\n}\n\n/** Test if a given string is in a given script */\nfunction testScriptMatch(\n scripts: LocalizatorScripts,\n script: string,\n string: string\n): boolean {\n if (scripts[script]?.rangeRegex) {\n return (scripts[script].rangeRegex as RegExp).test(string);\n }\n return false;\n}\n"],"mappings":";;;;;;;AAMO,MAAMA,yBAAyB,GAAAC,OAAA,CAAAD,yBAAA,GAAG;EACvCE,OAAO,EAAE,wBAAwB;EACjCC,MAAM,EAAE,aAAa;EACrBC,MAAM,EAAE;AACV,CAAC;;AAED;AACO,SAASC,qBAAqBA,CACnCC,OAA2B,EAC3BC,UAAuC,EACvCC,IAAY,EACZC,MAAc,EACgB;EAC9B;EACA;EACA,IAAIF,UAAU,CAACE,MAAM,CAAC,EAAEC,MAAM,EAAE;IAC9B,MAAMC,aAAa,GAAGJ,UAAU,CAACE,MAAM,CAAC,CAACC,MAAgB;IACzD,IACEE,eAAe,CAACN,OAAO,EAAEK,aAAa,EAAEH,IAAI,CAAC,IAC7CF,OAAO,CAACK,aAAa,CAAC,CAACE,KAAK,EAC5B;MACA,OAAOP,OAAO,CAACK,aAAa,CAAC,CAACE,KAAK;IACrC;EACF;;EAEA;EACA,KAAK,MAAMH,MAAM,IAAII,MAAM,CAACC,IAAI,CAACT,OAAO,CAAC,EAAE;IACzC,IAAIM,eAAe,CAACN,OAAO,EAAEI,MAAM,EAAEF,IAAI,CAAC,IAAIF,OAAO,CAACI,MAAM,CAAC,CAACG,KAAK,EAAE;MACnE,OAAOP,OAAO,CAACI,MAAM,CAAC,CAACG,KAAK;IAC9B;EACF;;EAEA;EACA,IAAIN,UAAU,CAACE,MAAM,CAAC,EAAEI,KAAK,EAAEG,QAAQ,EAAE;IACvC,OAAOT,UAAU,CAACE,MAAM,CAAC,CAACI,KAAK,CAACG,QAAQ;EAC1C;;EAEA;EACA,OAAOhB,yBAAyB;AAClC;;AAEA;AACA,SAASY,eAAeA,CACtBN,OAA2B,EAC3BI,MAAc,EACdO,MAAc,EACL;EACT,IAAIX,OAAO,CAACI,MAAM,CAAC,EAAEQ,UAAU,EAAE;IAC/B,OAAQZ,OAAO,CAACI,MAAM,CAAC,CAACQ,UAAU,CAAYC,IAAI,CAACF,MAAM,CAAC;EAC5D;EACA,OAAO,KAAK;AACd","ignoreList":[]}
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["_guessNamingConvention","require","Object","keys","forEach","key","exports","defineProperty","enumerable","get"],"sources":["../../../../src/entities/Localizator/guessNamingConvention/index.ts"],"sourcesContent":["export * from './guessNamingConvention';\r\n"],"mappings":";;;;;AAAA,IAAAA,sBAAA,GAAAC,OAAA;AAAAC,MAAA,CAAAC,IAAA,CAAAH,sBAAA,EAAAI,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAA,GAAA,IAAAC,OAAA,IAAAA,OAAA,CAAAD,GAAA,MAAAL,sBAAA,CAAAK,GAAA;EAAAH,MAAA,CAAAK,cAAA,CAAAD,OAAA,EAAAD,GAAA;IAAAG,UAAA;IAAAC,GAAA,WAAAA,CAAA;MAAA,OAAAT,sBAAA,CAAAK,GAAA;IAAA;EAAA;AAAA","ignoreList":[]}
1
+ {"version":3,"file":"index.js","names":["_guessNamingConvention","require","Object","keys","forEach","key","exports","defineProperty","enumerable","get"],"sources":["../../../../src/entities/Localizator/guessNamingConvention/index.ts"],"sourcesContent":["export * from './guessNamingConvention';\n"],"mappings":";;;;;AAAA,IAAAA,sBAAA,GAAAC,OAAA;AAAAC,MAAA,CAAAC,IAAA,CAAAH,sBAAA,EAAAI,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAA,GAAA,IAAAC,OAAA,IAAAA,OAAA,CAAAD,GAAA,MAAAL,sBAAA,CAAAK,GAAA;EAAAH,MAAA,CAAAK,cAAA,CAAAD,OAAA,EAAAD,GAAA;IAAAG,UAAA;IAAAC,GAAA,WAAAA,CAAA;MAAA,OAAAT,sBAAA,CAAAK,GAAA;IAAA;EAAA;AAAA","ignoreList":[]}
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["_Localizator","require","Object","keys","forEach","key","exports","defineProperty","enumerable","get","_Localizator2"],"sources":["../../../src/entities/Localizator/index.ts"],"sourcesContent":["export * from './Localizator';\r\nexport * from './Localizator.types';\r\n"],"mappings":";;;;;AAAA,IAAAA,YAAA,GAAAC,OAAA;AAAAC,MAAA,CAAAC,IAAA,CAAAH,YAAA,EAAAI,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAA,GAAA,IAAAC,OAAA,IAAAA,OAAA,CAAAD,GAAA,MAAAL,YAAA,CAAAK,GAAA;EAAAH,MAAA,CAAAK,cAAA,CAAAD,OAAA,EAAAD,GAAA;IAAAG,UAAA;IAAAC,GAAA,WAAAA,CAAA;MAAA,OAAAT,YAAA,CAAAK,GAAA;IAAA;EAAA;AAAA;AACA,IAAAK,aAAA,GAAAT,OAAA;AAAAC,MAAA,CAAAC,IAAA,CAAAO,aAAA,EAAAN,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAA,GAAA,IAAAC,OAAA,IAAAA,OAAA,CAAAD,GAAA,MAAAK,aAAA,CAAAL,GAAA;EAAAH,MAAA,CAAAK,cAAA,CAAAD,OAAA,EAAAD,GAAA;IAAAG,UAAA;IAAAC,GAAA,WAAAA,CAAA;MAAA,OAAAC,aAAA,CAAAL,GAAA;IAAA;EAAA;AAAA","ignoreList":[]}
1
+ {"version":3,"file":"index.js","names":["_Localizator","require","Object","keys","forEach","key","exports","defineProperty","enumerable","get","_Localizator2"],"sources":["../../../src/entities/Localizator/index.ts"],"sourcesContent":["export * from './Localizator';\nexport * from './Localizator.types';\n"],"mappings":";;;;;AAAA,IAAAA,YAAA,GAAAC,OAAA;AAAAC,MAAA,CAAAC,IAAA,CAAAH,YAAA,EAAAI,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAA,GAAA,IAAAC,OAAA,IAAAA,OAAA,CAAAD,GAAA,MAAAL,YAAA,CAAAK,GAAA;EAAAH,MAAA,CAAAK,cAAA,CAAAD,OAAA,EAAAD,GAAA;IAAAG,UAAA;IAAAC,GAAA,WAAAA,CAAA;MAAA,OAAAT,YAAA,CAAAK,GAAA;IAAA;EAAA;AAAA;AACA,IAAAK,aAAA,GAAAT,OAAA;AAAAC,MAAA,CAAAC,IAAA,CAAAO,aAAA,EAAAN,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAA,GAAA,IAAAC,OAAA,IAAAA,OAAA,CAAAD,GAAA,MAAAK,aAAA,CAAAL,GAAA;EAAAH,MAAA,CAAAK,cAAA,CAAAD,OAAA,EAAAD,GAAA;IAAAG,UAAA;IAAAC,GAAA,WAAAA,CAAA;MAAA,OAAAC,aAAA,CAAAL,GAAA;IAAA;EAAA;AAAA","ignoreList":[]}
@@ -7,23 +7,24 @@ Object.defineProperty(exports, "__esModule", {
7
7
  exports.MessageHandler = void 0;
8
8
  var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
9
9
  var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
10
+ var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
10
11
  var _EngineError = require("../EngineError");
11
12
  var _WebError = require("../WebError");
12
- /**
13
- * Message handlers should be used to define how messages should be handled in web socket servers
13
+ /**
14
+ * Message handlers should be used to define how messages should be handled in web socket servers
14
15
  */
15
16
  let MessageHandler = exports.MessageHandler = /*#__PURE__*/function () {
16
17
  /** Create a new websocket message handler */
17
18
  function MessageHandler(type, handler, validator, options = {}) {
18
19
  (0, _classCallCheck2.default)(this, MessageHandler);
19
20
  /** The type of messages that are handled by the instance */
20
- this.type = void 0;
21
+ (0, _defineProperty2.default)(this, "type", void 0);
21
22
  /** Function that should handle the message */
22
- this.handler = void 0;
23
+ (0, _defineProperty2.default)(this, "handler", void 0);
23
24
  /** Schema against which incoming messages should be validated */
24
- this.validator = void 0;
25
+ (0, _defineProperty2.default)(this, "validator", void 0);
25
26
  /** Indicates that this handler should only run when the client is authenticated */
26
- this.authenticated = void 0;
27
+ (0, _defineProperty2.default)(this, "authenticated", void 0);
27
28
  if (!type) throw new _EngineError.EngineError({
28
29
  message: 'MessageHandler has no type defined'
29
30
  });
@@ -1 +1 @@
1
- {"version":3,"file":"MessageHandler.js","names":["_EngineError","require","_WebError","MessageHandler","exports","type","handler","validator","options","_classCallCheck2","default","authenticated","EngineError","message","_createClass2","key","value","handle","client","valid","payload","hint","errors","reduce","error","instancePath","keyword","WebError","statusCode","errorCode","data","isAuthenticated"],"sources":["../../../src/entities/MessageHandler/MessageHandler.ts"],"sourcesContent":["import { ValidateFunction } from 'ajv';\r\nimport { EngineError } from '../EngineError';\r\nimport {\r\n MessageHandlerOptions,\r\n MessageHandlerHandler\r\n} from './MessageHandler.types';\r\nimport { SocketMessage, SocketClient } from 'entities/SocketClient';\r\nimport { WebError } from 'entities/WebError';\r\n\r\n/**\r\n * Message handlers should be used to define how messages should be handled in web socket servers\r\n */\r\nexport class MessageHandler {\r\n /** The type of messages that are handled by the instance */\r\n public readonly type: string;\r\n /** Function that should handle the message */\r\n private handler: MessageHandlerHandler;\r\n /** Schema against which incoming messages should be validated */\r\n private validator: ValidateFunction;\r\n /** Indicates that this handler should only run when the client is authenticated */\r\n private authenticated: boolean;\r\n\r\n /** Create a new websocket message handler */\r\n public constructor(\r\n type: string,\r\n handler: MessageHandlerHandler,\r\n validator: ValidateFunction,\r\n options: MessageHandlerOptions = {}\r\n ) {\r\n if (!type)\r\n throw new EngineError({ message: 'MessageHandler has no type defined' });\r\n this.type = type;\r\n if (!handler)\r\n throw new EngineError({\r\n message: 'MessageHandler should have a handler function'\r\n });\r\n this.handler = handler;\r\n this.validator = validator;\r\n this.authenticated = options.authenticated ?? true;\r\n }\r\n\r\n /** Handle received messages, and propagate them to the handler if needed */\r\n public async handle(\r\n message: SocketMessage,\r\n client: SocketClient\r\n ): Promise<void> {\r\n const valid = this.validator(message.payload);\r\n if (!valid) {\r\n const hint = this.validator.errors?.reduce(\r\n (hint, error) => ({\r\n ...hint,\r\n [error.instancePath]: error.message\r\n ? `${error.keyword}: ${error.message}`\r\n : error.keyword\r\n }),\r\n {}\r\n );\r\n throw new WebError({\r\n statusCode: 400,\r\n errorCode: 'invalid-message',\r\n message: 'Message validation failed',\r\n data: hint,\r\n hint\r\n });\r\n }\r\n // Do not handle if it not for this type of handler\r\n if (this.type !== message.type) return;\r\n // When handler requires authentication but that client is not authenticated, do not handle the message.\r\n if (this.authenticated && !client.isAuthenticated()) return;\r\n await this.handler(message.payload ?? {}, client);\r\n }\r\n}\r\n"],"mappings":";;;;;;;;;AACA,IAAAA,YAAA,GAAAC,OAAA;AAMA,IAAAC,SAAA,GAAAD,OAAA;AAEA;AACA;AACA;AAFA,IAGa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AE,GAAG;UACfC,SAAS,EAAE,iBAAiB;UAC5BhB,OAAO,EAAE,2BAA2B;UACpCiB,IAAI,EAAET,IAAI;UACVA;QACF,CAAC,CAAC;MACJ;MACA;MACA,IAAI,IAAI,CAAChB,IAAI,KAAKQ,OAAO,CAACR,IAAI,EAAE;MAChC;MACA,IAAI,IAAI,CAACM,aAAa,IAAI,CAACO,MAAM,CAACa,eAAe,CAAC,CAAC,EAAE;MACrD,MAAM,IAAI,CAACzB,OAAO,CAACO,OAAO,CAACO,OAAO,IAAI,CAAC,CAAC,EAAEF,MAAM,CAAC;IACnD;EAAC;AAAA","ignoreList":[]}
1
+ {"version":3,"file":"MessageHandler.js","names":["_EngineError","require","_WebError","MessageHandler","exports","type","handler","validator","options","_classCallCheck2","default","_defineProperty2","EngineError","message","authenticated","_createClass2","key","value","handle","client","valid","payload","hint","errors","reduce","error","instancePath","keyword","WebError","statusCode","errorCode","data","isAuthenticated"],"sources":["../../../src/entities/MessageHandler/MessageHandler.ts"],"sourcesContent":["import { ValidateFunction } from 'ajv';\nimport { EngineError } from '../EngineError';\nimport {\n MessageHandlerOptions,\n MessageHandlerHandler\n} from './MessageHandler.types';\nimport { SocketMessage, SocketClient } from 'entities/SocketClient';\nimport { WebError } from 'entities/WebError';\n\n/**\n * Message handlers should be used to define how messages should be handled in web socket servers\n */\nexport class MessageHandler {\n /** The type of messages that are handled by the instance */\n public readonly type: string;\n /** Function that should handle the message */\n private handler: MessageHandlerHandler;\n /** Schema against which incoming messages should be validated */\n private validator: ValidateFunction;\n /** Indicates that this handler should only run when the client is authenticated */\n private authenticated: boolean;\n\n /** Create a new websocket message handler */\n public constructor(\n type: string,\n handler: MessageHandlerHandler,\n validator: ValidateFunction,\n options: MessageHandlerOptions = {}\n ) {\n if (!type)\n throw new EngineError({ message: 'MessageHandler has no type defined' });\n this.type = type;\n if (!handler)\n throw new EngineError({\n message: 'MessageHandler should have a handler function'\n });\n this.handler = handler;\n this.validator = validator;\n this.authenticated = options.authenticated ?? true;\n }\n\n /** Handle received messages, and propagate them to the handler if needed */\n public async handle(\n message: SocketMessage,\n client: SocketClient\n ): Promise<void> {\n const valid = this.validator(message.payload);\n if (!valid) {\n const hint = this.validator.errors?.reduce(\n (hint, error) => ({\n ...hint,\n [error.instancePath]: error.message\n ? `${error.keyword}: ${error.message}`\n : error.keyword\n }),\n {}\n );\n throw new WebError({\n statusCode: 400,\n errorCode: 'invalid-message',\n message: 'Message validation failed',\n data: hint,\n hint\n });\n }\n // Do not handle if it not for this type of handler\n if (this.type !== message.type) return;\n // When handler requires authentication but that client is not authenticated, do not handle the message.\n if (this.authenticated && !client.isAuthenticated()) return;\n await this.handler(message.payload ?? {}, client);\n }\n}\n"],"mappings":";;;;;;;;;;AACA,IAAAA,YAAA,GAAAC,OAAA;AAMA,IAAAC,SAAA,GAAAD,OAAA;AAEA;AACA;AACA;AAFA,IAGaE,cAAc,GAAAC,OAAA,CAAAD,cAAA;EAUzB;EACA,SAAAA,eACEE,IAAY,EACZC,OAA8B,EAC9BC,SAA2B,EAC3BC,OAA8B,GAAG,CAAC,CAAC,EACnC;IAAA,IAAAC,gBAAA,CAAAC,OAAA,QAAAP,cAAA;IAfF;IAAA,IAAAQ,gBAAA,CAAAD,OAAA;IAEA;IAAA,IAAAC,gBAAA,CAAAD,OAAA;IAEA;IAAA,IAAAC,gBAAA,CAAAD,OAAA;IAEA;IAAA,IAAAC,gBAAA,CAAAD,OAAA;IAUE,IAAI,CAACL,IAAI,EACP,MAAM,IAAIO,wBAAW,CAAC;MAAEC,OAAO,EAAE;IAAqC,CAAC,CAAC;IAC1E,IAAI,CAACR,IAAI,GAAGA,IAAI;IAChB,IAAI,CAACC,OAAO,EACV,MAAM,IAAIM,wBAAW,CAAC;MACpBC,OAAO,EAAE;IACX,CAAC,CAAC;IACJ,IAAI,CAACP,OAAO,GAAGA,OAAO;IACtB,IAAI,CAACC,SAAS,GAAGA,SAAS;IAC1B,IAAI,CAACO,aAAa,GAAGN,OAAO,CAACM,aAAa,IAAI,IAAI;EACpD;;EAEA;EAAA,WAAAC,aAAA,CAAAL,OAAA,EAAAP,cAAA;IAAAa,GAAA;IAAAC,KAAA,EACA,eAAaC,MAAMA,CACjBL,OAAsB,EACtBM,MAAoB,EACL;MACf,MAAMC,KAAK,GAAG,IAAI,CAACb,SAAS,CAACM,OAAO,CAACQ,OAAO,CAAC;MAC7C,IAAI,CAACD,KAAK,EAAE;QACV,MAAME,IAAI,GAAG,IAAI,CAACf,SAAS,CAACgB,MAAM,EAAEC,MAAM,CACxC,CAACF,IAAI,EAAEG,KAAK,MAAM;UAChB,GAAGH,IAAI;UACP,CAACG,KAAK,CAACC,YAAY,GAAGD,KAAK,CAACZ,OAAO,GAC/B,GAAGY,KAAK,CAACE,OAAO,KAAKF,KAAK,CAACZ,OAAO,EAAE,GACpCY,KAAK,CAACE;QACZ,CAAC,CAAC,EACF,CAAC,CACH,CAAC;QACD,MAAM,IAAIC,kBAAQ,CAAC;UACjBC,UAAU,EAAE,GAAG;UACfC,SAAS,EAAE,iBAAiB;UAC5BjB,OAAO,EAAE,2BAA2B;UACpCkB,IAAI,EAAET,IAAI;UACVA;QACF,CAAC,CAAC;MACJ;MACA;MACA,IAAI,IAAI,CAACjB,IAAI,KAAKQ,OAAO,CAACR,IAAI,EAAE;MAChC;MACA,IAAI,IAAI,CAACS,aAAa,IAAI,CAACK,MAAM,CAACa,eAAe,CAAC,CAAC,EAAE;MACrD,MAAM,IAAI,CAAC1B,OAAO,CAACO,OAAO,CAACQ,OAAO,IAAI,CAAC,CAAC,EAAEF,MAAM,CAAC;IACnD;EAAC;AAAA","ignoreList":[]}
@@ -1 +1 @@
1
- {"version":3,"file":"MessageHandler.types.js","names":[],"sources":["../../../src/entities/MessageHandler/MessageHandler.types.ts"],"sourcesContent":["import { ValidateFunction } from 'ajv';\r\nimport { SocketClient } from 'entities/SocketClient';\r\n\r\n/** Initialization options for the message handler */\r\nexport interface MessageHandlerOptions {\r\n /** The handler will only be called for authenticated clients (default: true) */\r\n authenticated?: boolean;\r\n /** Schema to validate the message before passing it to the handler */\r\n validator?: ValidateFunction;\r\n}\r\n\r\nexport type MessageHandlerHandler = (\r\n payload: unknown,\r\n client: SocketClient\r\n) => unknown | Promise<unknown>;\r\n"],"mappings":"","ignoreList":[]}
1
+ {"version":3,"file":"MessageHandler.types.js","names":[],"sources":["../../../src/entities/MessageHandler/MessageHandler.types.ts"],"sourcesContent":["import { ValidateFunction } from 'ajv';\nimport { SocketClient } from 'entities/SocketClient';\n\n/** Initialization options for the message handler */\nexport interface MessageHandlerOptions {\n /** The handler will only be called for authenticated clients (default: true) */\n authenticated?: boolean;\n /** Schema to validate the message before passing it to the handler */\n validator?: ValidateFunction;\n}\n\nexport type MessageHandlerHandler = (\n payload: unknown,\n client: SocketClient\n) => unknown | Promise<unknown>;\n"],"mappings":"","ignoreList":[]}
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["_MessageHandler","require","Object","keys","forEach","key","exports","defineProperty","enumerable","get","_MessageHandler2"],"sources":["../../../src/entities/MessageHandler/index.ts"],"sourcesContent":["export * from './MessageHandler';\r\nexport * from './MessageHandler.types';\r\n"],"mappings":";;;;;AAAA,IAAAA,eAAA,GAAAC,OAAA;AAAAC,MAAA,CAAAC,IAAA,CAAAH,eAAA,EAAAI,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAA,GAAA,IAAAC,OAAA,IAAAA,OAAA,CAAAD,GAAA,MAAAL,eAAA,CAAAK,GAAA;EAAAH,MAAA,CAAAK,cAAA,CAAAD,OAAA,EAAAD,GAAA;IAAAG,UAAA;IAAAC,GAAA,WAAAA,CAAA;MAAA,OAAAT,eAAA,CAAAK,GAAA;IAAA;EAAA;AAAA;AACA,IAAAK,gBAAA,GAAAT,OAAA;AAAAC,MAAA,CAAAC,IAAA,CAAAO,gBAAA,EAAAN,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAA,GAAA,IAAAC,OAAA,IAAAA,OAAA,CAAAD,GAAA,MAAAK,gBAAA,CAAAL,GAAA;EAAAH,MAAA,CAAAK,cAAA,CAAAD,OAAA,EAAAD,GAAA;IAAAG,UAAA;IAAAC,GAAA,WAAAA,CAAA;MAAA,OAAAC,gBAAA,CAAAL,GAAA;IAAA;EAAA;AAAA","ignoreList":[]}
1
+ {"version":3,"file":"index.js","names":["_MessageHandler","require","Object","keys","forEach","key","exports","defineProperty","enumerable","get","_MessageHandler2"],"sources":["../../../src/entities/MessageHandler/index.ts"],"sourcesContent":["export * from './MessageHandler';\nexport * from './MessageHandler.types';\n"],"mappings":";;;;;AAAA,IAAAA,eAAA,GAAAC,OAAA;AAAAC,MAAA,CAAAC,IAAA,CAAAH,eAAA,EAAAI,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAA,GAAA,IAAAC,OAAA,IAAAA,OAAA,CAAAD,GAAA,MAAAL,eAAA,CAAAK,GAAA;EAAAH,MAAA,CAAAK,cAAA,CAAAD,OAAA,EAAAD,GAAA;IAAAG,UAAA;IAAAC,GAAA,WAAAA,CAAA;MAAA,OAAAT,eAAA,CAAAK,GAAA;IAAA;EAAA;AAAA;AACA,IAAAK,gBAAA,GAAAT,OAAA;AAAAC,MAAA,CAAAC,IAAA,CAAAO,gBAAA,EAAAN,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAA,GAAA,IAAAC,OAAA,IAAAA,OAAA,CAAAD,GAAA,MAAAK,gBAAA,CAAAL,GAAA;EAAAH,MAAA,CAAAK,cAAA,CAAAD,OAAA,EAAAD,GAAA;IAAAG,UAAA;IAAAC,GAAA,WAAAA,CAAA;MAAA,OAAAC,gBAAA,CAAAL,GAAA;IAAA;EAAA;AAAA","ignoreList":[]}
@@ -11,25 +11,25 @@ var _LifecycleController = require("../LifecycleController");
11
11
  var _utils = require("../../utils");
12
12
  const namespace = 'engine:PubSub';
13
13
 
14
- /**
15
- * Associative containing all the subscriptions sorted by topic registered for publishing
14
+ /**
15
+ * Associative containing all the subscriptions sorted by topic registered for publishing
16
16
  */
17
17
  const subscriptions = {};
18
18
 
19
- /**
20
- * Associative containing all the topics registered for publishing
19
+ /**
20
+ * Associative containing all the topics registered for publishing
21
21
  */
22
22
  const topics = {};
23
23
  const pubSubClient = new _pubsub.PubSub();
24
24
 
25
- /**
26
- * This is a singleton service who's role is to manage pub/sub connections
27
- * It is the preferred way to interact with Pub/Sub as it manages the underlying subscription and handler objects
28
- * It avoids potential subscription splitting on an instance
25
+ /**
26
+ * This is a singleton service who's role is to manage pub/sub connections
27
+ * It is the preferred way to interact with Pub/Sub as it manages the underlying subscription and handler objects
28
+ * It avoids potential subscription splitting on an instance
29
29
  */
30
30
  const PubSub = exports.PubSub = {
31
- /**
32
- * Initialize the registered publishers and subscribers
31
+ /**
32
+ * Initialize the registered publishers and subscribers
33
33
  */
34
34
  async init() {
35
35
  (0, _utils.reportDebug)({
@@ -73,8 +73,8 @@ const PubSub = exports.PubSub = {
73
73
  }
74
74
  _LifecycleController.LifecycleController.register(PubSub);
75
75
  },
76
- /**
77
- * Shutdown the registered publishers and subscribers
76
+ /**
77
+ * Shutdown the registered publishers and subscribers
78
78
  */
79
79
  async shutdown() {
80
80
  (0, _utils.reportDebug)({
@@ -91,8 +91,8 @@ const PubSub = exports.PubSub = {
91
91
  // Close the client
92
92
  await pubSubClient.close();
93
93
  },
94
- /**
95
- * Creates a publisher if it does not exist yet
94
+ /**
95
+ * Creates a publisher if it does not exist yet
96
96
  */
97
97
  addPublisher(topic) {
98
98
  const topicArray = topic instanceof Array ? topic : [topic];
@@ -109,11 +109,11 @@ const PubSub = exports.PubSub = {
109
109
  }
110
110
  }
111
111
  },
112
- /**
113
- * Add message handlers to a subscription
114
- * @param subscription - Name of the Pub/Sub subscription
115
- * @param handler - Function or list of functions to set as message handlers
116
- * @param options - Indicates that the additional options need to handle on Subscriber
112
+ /**
113
+ * Add message handlers to a subscription
114
+ * @param subscription - Name of the Pub/Sub subscription
115
+ * @param handler - Function or list of functions to set as message handlers
116
+ * @param options - Indicates that the additional options need to handle on Subscriber
117
117
  */
118
118
  addSubscriber(subscription, handler, options = {}) {
119
119
  const handlers = handler instanceof Array ? handler : [handler];
@@ -139,12 +139,12 @@ const PubSub = exports.PubSub = {
139
139
  if (isDebezium) subscriptions[subscription].isDebezium = true;
140
140
  if (first) subscriptions[subscription].handlers.push(...handlers);else subscriptions[subscription].handlers.unshift(...handlers);
141
141
  },
142
- /**
143
- * Send a message to a Pub/Sub topic
144
- * @param topic - Name of the topic
145
- * @param message - Content of the message, must be an object that can be JSON stringified
146
- * @param attributes - Attributes for this message, can be used to filter messages on the subscription
147
- * @param orderingKey - Enforce order guarantee of messages sent with the same key
142
+ /**
143
+ * Send a message to a Pub/Sub topic
144
+ * @param topic - Name of the topic
145
+ * @param message - Content of the message, must be an object that can be JSON stringified
146
+ * @param attributes - Attributes for this message, can be used to filter messages on the subscription
147
+ * @param orderingKey - Enforce order guarantee of messages sent with the same key
148
148
  */
149
149
  async publish(topic, message, attributes, orderingKey) {
150
150
  if (!topics[topic]) throw new _EngineError.EngineError(`No publisher was registered for topic '${topic}'`);
@@ -1 +1 @@
1
- {"version":3,"file":"PubSub.js","names":["_pubsub","require","_handleMessage","_EngineError","_LifecycleController","_utils","namespace","subscriptions","topics","pubSubClient","PubsubClient","PubSub","exports","init","reportDebug","message","Promise","all","Object","values","map","topic","exists","EngineError","name","permissions","iam","testPermissions","hasPermissions","every","success","subscription","handlers","isDebezium","on","handleMessage","catch","error","reportError","LifecycleController","register","shutdown","flush","close","keys","forEach","addPublisher","topicArray","Array","join","includes","enableOpenTelemetryTracing","addSubscriber","handler","options","first","data","handlersCount","length","push","unshift","publish","attributes","orderingKey","publishMessage","json"],"sources":["../../../src/entities/PubSub/PubSub.ts"],"sourcesContent":["import {\r\n Attributes,\r\n PubSub as PubsubClient,\r\n Message\r\n} from '@google-cloud/pubsub';\r\nimport { handleMessage } from './handleMessage';\r\nimport {\r\n PubSubTopicsMap,\r\n PubSubSubscriptionsMap,\r\n PubSubAddSubscriberOptions,\r\n PubSubMessageHandler\r\n} from './PubSub.types';\r\nimport { EngineError } from 'entities/EngineError';\r\nimport { LifecycleController } from 'entities/LifecycleController';\r\nimport { reportDebug, reportError } from 'utils';\r\n\r\nconst namespace = 'engine:PubSub';\r\n\r\n/**\r\n * Associative containing all the subscriptions sorted by topic registered for publishing\r\n */\r\nconst subscriptions: PubSubSubscriptionsMap = {};\r\n\r\n/**\r\n * Associative containing all the topics registered for publishing\r\n */\r\nconst topics: PubSubTopicsMap = {};\r\n\r\nconst pubSubClient = new PubsubClient();\r\n\r\n/**\r\n * This is a singleton service who's role is to manage pub/sub connections\r\n * It is the preferred way to interact with Pub/Sub as it manages the underlying subscription and handler objects\r\n * It avoids potential subscription splitting on an instance\r\n */\r\nexport const PubSub = {\r\n /**\r\n * Initialize the registered publishers and subscribers\r\n */\r\n async init(): Promise<void> {\r\n reportDebug({ namespace, message: `Initializing Pub/Sub` });\r\n // Check that all topics/permissions exist, and that we have permission on them\r\n await Promise.all([\r\n // Test that all topics actually exist and that we have permissions\r\n ...Object.values(topics).map(async (topic) => {\r\n const [exists] = await topic.exists();\r\n if (!exists)\r\n throw new EngineError(`Topic ${topic.name} does not exist`);\r\n // Test permission ton publish to topic\r\n const [permissions] = await topic.iam.testPermissions([\r\n 'pubsub.topics.publish'\r\n ]);\r\n const hasPermissions = Object.values(permissions).every(\r\n (success) => success\r\n );\r\n if (!hasPermissions)\r\n throw new EngineError(\r\n `Instance does not have appropriate permissions to publish to topic ${topic.name}`\r\n );\r\n }),\r\n // Test that all subscriptions actually exist and that we have permissions\r\n ...Object.values(subscriptions).map(async ({ subscription }) => {\r\n const [exists] = await subscription.exists();\r\n if (!exists)\r\n throw new EngineError(\r\n `Subscription ${subscription.name} does not exist`\r\n );\r\n // Test permission ton consume subscription\r\n const [permissions] = await subscription.iam.testPermissions([\r\n 'pubsub.subscriptions.consume'\r\n ]);\r\n const hasPermissions = Object.values(permissions).every(\r\n (success) => success\r\n );\r\n if (!hasPermissions)\r\n throw new EngineError(\r\n `Instance does not have appropriate permissions to subscribe to subscription ${subscription.name}`\r\n );\r\n })\r\n ]);\r\n\r\n // Register handlers on the subscriptions to activate them\r\n for (const { subscription, handlers, isDebezium } of Object.values(\r\n subscriptions\r\n )) {\r\n subscription.on('message', (message) => {\r\n handleMessage(\r\n message as Message,\r\n subscription,\r\n handlers,\r\n isDebezium\r\n ).catch((error) => {\r\n reportError(error);\r\n });\r\n });\r\n }\r\n\r\n LifecycleController.register(PubSub);\r\n },\r\n\r\n /**\r\n * Shutdown the registered publishers and subscribers\r\n */\r\n async shutdown(): Promise<void> {\r\n reportDebug({ namespace, message: `Shutting down Pub/Sub` });\r\n // Flush all pending messages and shut down connections\r\n await Promise.all([\r\n ...Object.values(topics).map(async (topic) => topic.flush()),\r\n ...Object.values(subscriptions).map(async ({ subscription }) =>\r\n subscription.close()\r\n )\r\n ]);\r\n // Delete the stored topics/subscriptions\r\n Object.keys(topics).forEach((topic) => delete topics[topic]);\r\n Object.keys(subscriptions).forEach(\r\n (subscription) => delete subscriptions[subscription]\r\n );\r\n // Close the client\r\n await pubSubClient.close();\r\n },\r\n\r\n /**\r\n * Creates a publisher if it does not exist yet\r\n */\r\n addPublisher(topic: string | Array<string>): void {\r\n const topicArray = topic instanceof Array ? topic : [topic];\r\n reportDebug({\r\n namespace,\r\n message: `Registering publisher for topics '${topicArray.join(\"', '\")}'`\r\n });\r\n // Register a new topic if it does not exist yet\r\n for (const topic of topicArray) {\r\n if (!Object.keys(topics).includes(topic)) {\r\n topics[topic] = pubSubClient.topic(topic, {\r\n enableOpenTelemetryTracing: true\r\n });\r\n }\r\n }\r\n },\r\n\r\n /**\r\n * Add message handlers to a subscription\r\n * @param subscription - Name of the Pub/Sub subscription\r\n * @param handler - Function or list of functions to set as message handlers\r\n * @param options - Indicates that the additional options need to handle on Subscriber\r\n */\r\n addSubscriber<T>(\r\n subscription: string,\r\n handler: PubSubMessageHandler<T> | Array<PubSubMessageHandler<T>>,\r\n options: PubSubAddSubscriberOptions = {}\r\n ): void {\r\n const handlers = handler instanceof Array ? handler : [handler];\r\n const isDebezium = options?.isDebezium ?? false;\r\n const first = options?.first ?? false;\r\n\r\n reportDebug({\r\n namespace,\r\n message: `Registering subscriber for subscription '${subscription}'`,\r\n data: { first, handlersCount: handlers.length, isDebezium }\r\n });\r\n if (!Object.keys(subscriptions).includes(subscription)) {\r\n subscriptions[subscription] = {\r\n subscription: pubSubClient.subscription(subscription, {\r\n enableOpenTelemetryTracing: true\r\n }),\r\n handlers: []\r\n };\r\n }\r\n\r\n if (isDebezium) subscriptions[subscription].isDebezium = true;\r\n\r\n if (first) subscriptions[subscription].handlers.push(...handlers);\r\n else subscriptions[subscription].handlers.unshift(...handlers);\r\n },\r\n\r\n /**\r\n * Send a message to a Pub/Sub topic\r\n * @param topic - Name of the topic\r\n * @param message - Content of the message, must be an object that can be JSON stringified\r\n * @param attributes - Attributes for this message, can be used to filter messages on the subscription\r\n * @param orderingKey - Enforce order guarantee of messages sent with the same key\r\n */\r\n async publish(\r\n topic: string,\r\n message: unknown,\r\n attributes?: Attributes,\r\n orderingKey?: string\r\n ): Promise<void> {\r\n if (!topics[topic])\r\n throw new EngineError(`No publisher was registered for topic '${topic}'`);\r\n reportDebug({\r\n namespace,\r\n message: `Sending message to topic '${topic}'`,\r\n data: { message, attributes, orderingKey }\r\n });\r\n await topics[topic].publishMessage({\r\n json: message,\r\n attributes,\r\n orderingKey\r\n });\r\n }\r\n};\r\n"],"mappings":";;;;;;AAAA,IAAAA,OAAA,GAAAC,OAAA;AAKA,IAAAC,cAAA,GAAAD,OAAA;AAOA,IAAAE,YAAA,GAAAF,OAAA;AACA,IAAAG,oBAAA,GAAAH,OAAA;AACA,IAAAI,MAAA,GAAAJ,OAAA;AAEA,MAAMK,SAAS,GAAG,eAAe;;AAEjC;A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ACF,CAAC","ignoreList":[]}
1
+ {"version":3,"file":"PubSub.js","names":["_pubsub","require","_handleMessage","_EngineError","_LifecycleController","_utils","namespace","subscriptions","topics","pubSubClient","PubsubClient","PubSub","exports","init","reportDebug","message","Promise","all","Object","values","map","topic","exists","EngineError","name","permissions","iam","testPermissions","hasPermissions","every","success","subscription","handlers","isDebezium","on","handleMessage","catch","error","reportError","LifecycleController","register","shutdown","flush","close","keys","forEach","addPublisher","topicArray","Array","join","includes","enableOpenTelemetryTracing","addSubscriber","handler","options","first","data","handlersCount","length","push","unshift","publish","attributes","orderingKey","publishMessage","json"],"sources":["../../../src/entities/PubSub/PubSub.ts"],"sourcesContent":["import {\n Attributes,\n PubSub as PubsubClient,\n Message\n} from '@google-cloud/pubsub';\nimport { handleMessage } from './handleMessage';\nimport {\n PubSubTopicsMap,\n PubSubSubscriptionsMap,\n PubSubAddSubscriberOptions,\n PubSubMessageHandler\n} from './PubSub.types';\nimport { EngineError } from 'entities/EngineError';\nimport { LifecycleController } from 'entities/LifecycleController';\nimport { reportDebug, reportError } from 'utils';\n\nconst namespace = 'engine:PubSub';\n\n/**\n * Associative containing all the subscriptions sorted by topic registered for publishing\n */\nconst subscriptions: PubSubSubscriptionsMap = {};\n\n/**\n * Associative containing all the topics registered for publishing\n */\nconst topics: PubSubTopicsMap = {};\n\nconst pubSubClient = new PubsubClient();\n\n/**\n * This is a singleton service who's role is to manage pub/sub connections\n * It is the preferred way to interact with Pub/Sub as it manages the underlying subscription and handler objects\n * It avoids potential subscription splitting on an instance\n */\nexport const PubSub = {\n /**\n * Initialize the registered publishers and subscribers\n */\n async init(): Promise<void> {\n reportDebug({ namespace, message: `Initializing Pub/Sub` });\n // Check that all topics/permissions exist, and that we have permission on them\n await Promise.all([\n // Test that all topics actually exist and that we have permissions\n ...Object.values(topics).map(async (topic) => {\n const [exists] = await topic.exists();\n if (!exists)\n throw new EngineError(`Topic ${topic.name} does not exist`);\n // Test permission ton publish to topic\n const [permissions] = await topic.iam.testPermissions([\n 'pubsub.topics.publish'\n ]);\n const hasPermissions = Object.values(permissions).every(\n (success) => success\n );\n if (!hasPermissions)\n throw new EngineError(\n `Instance does not have appropriate permissions to publish to topic ${topic.name}`\n );\n }),\n // Test that all subscriptions actually exist and that we have permissions\n ...Object.values(subscriptions).map(async ({ subscription }) => {\n const [exists] = await subscription.exists();\n if (!exists)\n throw new EngineError(\n `Subscription ${subscription.name} does not exist`\n );\n // Test permission ton consume subscription\n const [permissions] = await subscription.iam.testPermissions([\n 'pubsub.subscriptions.consume'\n ]);\n const hasPermissions = Object.values(permissions).every(\n (success) => success\n );\n if (!hasPermissions)\n throw new EngineError(\n `Instance does not have appropriate permissions to subscribe to subscription ${subscription.name}`\n );\n })\n ]);\n\n // Register handlers on the subscriptions to activate them\n for (const { subscription, handlers, isDebezium } of Object.values(\n subscriptions\n )) {\n subscription.on('message', (message) => {\n handleMessage(\n message as Message,\n subscription,\n handlers,\n isDebezium\n ).catch((error) => {\n reportError(error);\n });\n });\n }\n\n LifecycleController.register(PubSub);\n },\n\n /**\n * Shutdown the registered publishers and subscribers\n */\n async shutdown(): Promise<void> {\n reportDebug({ namespace, message: `Shutting down Pub/Sub` });\n // Flush all pending messages and shut down connections\n await Promise.all([\n ...Object.values(topics).map(async (topic) => topic.flush()),\n ...Object.values(subscriptions).map(async ({ subscription }) =>\n subscription.close()\n )\n ]);\n // Delete the stored topics/subscriptions\n Object.keys(topics).forEach((topic) => delete topics[topic]);\n Object.keys(subscriptions).forEach(\n (subscription) => delete subscriptions[subscription]\n );\n // Close the client\n await pubSubClient.close();\n },\n\n /**\n * Creates a publisher if it does not exist yet\n */\n addPublisher(topic: string | Array<string>): void {\n const topicArray = topic instanceof Array ? topic : [topic];\n reportDebug({\n namespace,\n message: `Registering publisher for topics '${topicArray.join(\"', '\")}'`\n });\n // Register a new topic if it does not exist yet\n for (const topic of topicArray) {\n if (!Object.keys(topics).includes(topic)) {\n topics[topic] = pubSubClient.topic(topic, {\n enableOpenTelemetryTracing: true\n });\n }\n }\n },\n\n /**\n * Add message handlers to a subscription\n * @param subscription - Name of the Pub/Sub subscription\n * @param handler - Function or list of functions to set as message handlers\n * @param options - Indicates that the additional options need to handle on Subscriber\n */\n addSubscriber<T>(\n subscription: string,\n handler: PubSubMessageHandler<T> | Array<PubSubMessageHandler<T>>,\n options: PubSubAddSubscriberOptions = {}\n ): void {\n const handlers = handler instanceof Array ? handler : [handler];\n const isDebezium = options?.isDebezium ?? false;\n const first = options?.first ?? false;\n\n reportDebug({\n namespace,\n message: `Registering subscriber for subscription '${subscription}'`,\n data: { first, handlersCount: handlers.length, isDebezium }\n });\n if (!Object.keys(subscriptions).includes(subscription)) {\n subscriptions[subscription] = {\n subscription: pubSubClient.subscription(subscription, {\n enableOpenTelemetryTracing: true\n }),\n handlers: []\n };\n }\n\n if (isDebezium) subscriptions[subscription].isDebezium = true;\n\n if (first) subscriptions[subscription].handlers.push(...handlers);\n else subscriptions[subscription].handlers.unshift(...handlers);\n },\n\n /**\n * Send a message to a Pub/Sub topic\n * @param topic - Name of the topic\n * @param message - Content of the message, must be an object that can be JSON stringified\n * @param attributes - Attributes for this message, can be used to filter messages on the subscription\n * @param orderingKey - Enforce order guarantee of messages sent with the same key\n */\n async publish(\n topic: string,\n message: unknown,\n attributes?: Attributes,\n orderingKey?: string\n ): Promise<void> {\n if (!topics[topic])\n throw new EngineError(`No publisher was registered for topic '${topic}'`);\n reportDebug({\n namespace,\n message: `Sending message to topic '${topic}'`,\n data: { message, attributes, orderingKey }\n });\n await topics[topic].publishMessage({\n json: message,\n attributes,\n orderingKey\n });\n }\n};\n"],"mappings":";;;;;;AAAA,IAAAA,OAAA,GAAAC,OAAA;AAKA,IAAAC,cAAA,GAAAD,OAAA;AAOA,IAAAE,YAAA,GAAAF,OAAA;AACA,IAAAG,oBAAA,GAAAH,OAAA;AACA,IAAAI,MAAA,GAAAJ,OAAA;AAEA,MAAMK,SAAS,GAAG,eAAe;;AAEjC;AACA;AACA;AACA,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reList":[]}
@@ -1 +1 @@
1
- {"version":3,"file":"PubSub.types.js","names":[],"sources":["../../../src/entities/PubSub/PubSub.types.ts"],"sourcesContent":["import { Topic, Subscription, Attributes } from '@google-cloud/pubsub';\r\nimport { DebeziumEvent } from 'const/DebeziumEvent';\r\n\r\n/** List of all active topics */\r\nexport interface PubSubTopicsMap {\r\n [topic: string]: Topic;\r\n}\r\n\r\n/** List of subscriptions handled for each topic */\r\nexport interface PubSubSubscriptionsMap {\r\n [topic: string]: {\r\n /** The Pub/Sub subscription object */\r\n subscription: Subscription;\r\n /** The message handling functions */\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n handlers: Array<PubSubMessageHandler<any>>;\r\n /** Indicates that the subscription from Debezium events */\r\n isDebezium?: boolean;\r\n };\r\n}\r\n\r\n/** Options to setup a subscription */\r\nexport interface PubSubAddSubscriberOptions {\r\n /** Should the handlers declared here be added to the top of the queue, and called first when an new message arrives */\r\n first?: boolean;\r\n /** Indicates that the topic is a Debezium CDC topic, additional processing is done on the message */\r\n isDebezium?: boolean;\r\n}\r\n\r\nexport type PubSubMessageHandler<T> = (\r\n message: T,\r\n attributes: Attributes,\r\n publishedAt: Date\r\n) => void | Promise<void>;\r\n\r\n/** Debezium create event payload */\r\ninterface PubSubDebeziumCreatePayload<T> {\r\n /** The instance properties before the operation */\r\n before: null;\r\n /** The instance properties after the operation */\r\n after: T;\r\n /** The operation that was executed */\r\n op: DebeziumEvent.Create;\r\n /** List of fields that have changed */\r\n diff: Array<string>;\r\n}\r\n\r\n/** Debezium update event payload */\r\ninterface PubSubDebeziumUpdatePayload<T> {\r\n /** The instance properties before the operation */\r\n before: T;\r\n /** The instance properties after the operation */\r\n after: T;\r\n /** The operation that was executed */\r\n op: DebeziumEvent.Update;\r\n /** List of fields that have changed */\r\n diff: Array<string>;\r\n}\r\n\r\n/** Debezium delete event payload */\r\ninterface PubSubDebeziumDeletePayload<T> {\r\n /** The instance properties before the operation */\r\n before: T;\r\n /** The instance properties after the operation */\r\n after: null;\r\n /** The operation that was executed */\r\n op: DebeziumEvent.Delete;\r\n /** List of fields that have changed */\r\n diff: Array<string>;\r\n}\r\n\r\n/** Payload of Debezium messages */\r\nexport type PubSubDebeziumPayload<T> =\r\n | PubSubDebeziumCreatePayload<T>\r\n | PubSubDebeziumUpdatePayload<T>\r\n | PubSubDebeziumDeletePayload<T>;\r\n"],"mappings":"","ignoreList":[]}
1
+ {"version":3,"file":"PubSub.types.js","names":[],"sources":["../../../src/entities/PubSub/PubSub.types.ts"],"sourcesContent":["import { Topic, Subscription, Attributes } from '@google-cloud/pubsub';\nimport { DebeziumEvent } from 'const/DebeziumEvent';\n\n/** List of all active topics */\nexport interface PubSubTopicsMap {\n [topic: string]: Topic;\n}\n\n/** List of subscriptions handled for each topic */\nexport interface PubSubSubscriptionsMap {\n [topic: string]: {\n /** The Pub/Sub subscription object */\n subscription: Subscription;\n /** The message handling functions */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n handlers: Array<PubSubMessageHandler<any>>;\n /** Indicates that the subscription from Debezium events */\n isDebezium?: boolean;\n };\n}\n\n/** Options to setup a subscription */\nexport interface PubSubAddSubscriberOptions {\n /** Should the handlers declared here be added to the top of the queue, and called first when an new message arrives */\n first?: boolean;\n /** Indicates that the topic is a Debezium CDC topic, additional processing is done on the message */\n isDebezium?: boolean;\n}\n\nexport type PubSubMessageHandler<T> = (\n message: T,\n attributes: Attributes,\n publishedAt: Date\n) => void | Promise<void>;\n\n/** Debezium create event payload */\ninterface PubSubDebeziumCreatePayload<T> {\n /** The instance properties before the operation */\n before: null;\n /** The instance properties after the operation */\n after: T;\n /** The operation that was executed */\n op: DebeziumEvent.Create;\n /** List of fields that have changed */\n diff: Array<string>;\n}\n\n/** Debezium update event payload */\ninterface PubSubDebeziumUpdatePayload<T> {\n /** The instance properties before the operation */\n before: T;\n /** The instance properties after the operation */\n after: T;\n /** The operation that was executed */\n op: DebeziumEvent.Update;\n /** List of fields that have changed */\n diff: Array<string>;\n}\n\n/** Debezium delete event payload */\ninterface PubSubDebeziumDeletePayload<T> {\n /** The instance properties before the operation */\n before: T;\n /** The instance properties after the operation */\n after: null;\n /** The operation that was executed */\n op: DebeziumEvent.Delete;\n /** List of fields that have changed */\n diff: Array<string>;\n}\n\n/** Payload of Debezium messages */\nexport type PubSubDebeziumPayload<T> =\n | PubSubDebeziumCreatePayload<T>\n | PubSubDebeziumUpdatePayload<T>\n | PubSubDebeziumDeletePayload<T>;\n"],"mappings":"","ignoreList":[]}
@@ -9,12 +9,12 @@ var _EngineError = require("../../EngineError");
9
9
  var _utils = require("../../../utils");
10
10
  const namespace = 'engine:PubSub:handleMessage';
11
11
 
12
- /**
13
- * handle the pubSubClients on message event
14
- * @param message - Message to parse and handle
15
- * @param subscription - The related Pub/Sub subscription object
16
- * @param handlers - Message handlers
17
- * @param isDebezium - Indicates that the subscription from Debezium events
12
+ /**
13
+ * handle the pubSubClients on message event
14
+ * @param message - Message to parse and handle
15
+ * @param subscription - The related Pub/Sub subscription object
16
+ * @param handlers - Message handlers
17
+ * @param isDebezium - Indicates that the subscription from Debezium events
18
18
  */
19
19
  async function handleMessage(message, subscription, handlers, isDebezium = false) {
20
20
  (0, _utils.reportDebug)({