@lyxa.ai/core 1.3.75 → 1.3.79

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 (51) hide show
  1. package/dist/index.js +2 -2
  2. package/dist/index.js.map +1 -1
  3. package/dist/libraries/socket/PushNotificationEvent.d.ts +1 -1
  4. package/dist/libraries/socket/PushNotificationEvent.js.map +1 -1
  5. package/dist/libraries/socket/adapters/socket-subscription.js +3 -2
  6. package/dist/libraries/socket/adapters/socket-subscription.js.map +1 -1
  7. package/dist/libraries/socket/connections/batch.d.ts +12 -0
  8. package/dist/libraries/socket/connections/batch.js +58 -0
  9. package/dist/libraries/socket/connections/batch.js.map +1 -0
  10. package/dist/libraries/socket/connections/cache.d.ts +9 -0
  11. package/dist/libraries/socket/connections/cache.js +36 -0
  12. package/dist/libraries/socket/connections/cache.js.map +1 -0
  13. package/dist/libraries/socket/connections/constants.d.ts +2 -0
  14. package/dist/libraries/socket/connections/constants.js +6 -0
  15. package/dist/libraries/socket/connections/constants.js.map +1 -0
  16. package/dist/libraries/socket/connections/event-subscribers.d.ts +5 -0
  17. package/dist/libraries/socket/connections/event-subscribers.js +60 -0
  18. package/dist/libraries/socket/connections/event-subscribers.js.map +1 -0
  19. package/dist/libraries/socket/connections/index.d.ts +7 -0
  20. package/dist/libraries/socket/connections/index.js +24 -0
  21. package/dist/libraries/socket/connections/index.js.map +1 -0
  22. package/dist/libraries/socket/connections/instance-disconnect.d.ts +2 -0
  23. package/dist/libraries/socket/connections/instance-disconnect.js +43 -0
  24. package/dist/libraries/socket/connections/instance-disconnect.js.map +1 -0
  25. package/dist/libraries/socket/connections/keys.d.ts +10 -0
  26. package/dist/libraries/socket/connections/keys.js +23 -0
  27. package/dist/libraries/socket/connections/keys.js.map +1 -0
  28. package/dist/libraries/socket/connections/presence.d.ts +4 -0
  29. package/dist/libraries/socket/connections/presence.js +23 -0
  30. package/dist/libraries/socket/connections/presence.js.map +1 -0
  31. package/dist/libraries/socket/connections/redis-helpers.d.ts +2 -0
  32. package/dist/libraries/socket/connections/redis-helpers.js +14 -0
  33. package/dist/libraries/socket/connections/redis-helpers.js.map +1 -0
  34. package/dist/libraries/socket/connections/subscription.d.ts +13 -0
  35. package/dist/libraries/socket/connections/subscription.js +73 -0
  36. package/dist/libraries/socket/connections/subscription.js.map +1 -0
  37. package/dist/libraries/socket/core/index.d.ts +0 -1
  38. package/dist/libraries/socket/core/index.js +0 -1
  39. package/dist/libraries/socket/core/index.js.map +1 -1
  40. package/dist/libraries/socket/core/local-subscription-registry.d.ts +1 -1
  41. package/dist/libraries/socket/core/local-subscription-registry.js.map +1 -1
  42. package/dist/libraries/socket/core/socket-event-publisher.d.ts +1 -1
  43. package/dist/libraries/socket/core/socket-event-publisher.js +9 -15
  44. package/dist/libraries/socket/core/socket-event-publisher.js.map +1 -1
  45. package/dist/types/README.md +1 -1
  46. package/dist/types/package.json +1 -1
  47. package/dist/types/utilities/validation/common-validation.d.ts +12 -12
  48. package/package.json +1 -1
  49. package/dist/libraries/socket/core/socket-redis-connections.d.ts +0 -36
  50. package/dist/libraries/socket/core/socket-redis-connections.js +0 -412
  51. package/dist/libraries/socket/core/socket-redis-connections.js.map +0 -1
package/dist/index.js CHANGED
@@ -56,10 +56,10 @@ const settings_1 = require("./libraries/cache/settings");
56
56
  const fcmService_1 = require("./libraries/firebase/fcmService");
57
57
  const bull_mq_service_1 = require("./libraries/bullmq/bull-mq-service");
58
58
  const cash_settlement_1 = require("./libraries/cash-settlement");
59
- const socket_1 = require("./libraries/socket");
60
59
  const EnvironmentConfigurationType_1 = require("./libraries/configuration/types/EnvironmentConfigurationType");
61
60
  const osrm_1 = require("./libraries/map/providers/osrm");
62
61
  const rabbitmq_environments_1 = require("./utilities/environment/rabbitmq-environments");
62
+ const instance_disconnect_1 = require("./libraries/socket/connections/instance-disconnect");
63
63
  var EnvironmentConfigurationType_2 = require("./libraries/configuration/types/EnvironmentConfigurationType");
64
64
  Object.defineProperty(exports, "EnvironmentConfigurationType", { enumerable: true, get: function () { return EnvironmentConfigurationType_2.EnvironmentConfigurationType; } });
65
65
  var mongo_2 = require("./libraries/mongo");
@@ -71,7 +71,7 @@ async function bootstrapCore(options) {
71
71
  const gracefulShutdown = async () => {
72
72
  getLibraries().getLogger().logger.info('Received shutdown signal, shutting down gracefully...');
73
73
  if (options?.instanceType == 'socket')
74
- await (0, socket_1.disconnectAllEntitiesFromInstance)();
74
+ await (0, instance_disconnect_1.disconnectAllEntitiesFromInstance)();
75
75
  process.exit();
76
76
  };
77
77
  process.on('SIGTERM', gracefulShutdown);
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"/","sources":["index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BA,sCA0BC;AAED,8CAuGC;AAED,oCAEC;AApKD,qFAAqF;AACrF,IAAA,0CAAqB,GAAE,CAAC;AAExB,2CAA6C;AAC7C,mCAAmC;AACnC,6DAAuF;AACvF,+CAAgD;AAChD,6CAAiD;AACjD,6CAAoF;AACpF,iDAA2D;AAC3D,uDAAgE;AAChE,+CAAmD;AACnD,mDAAuD;AACvD,6CAAmE;AACnE,0FAAuF;AACvF,yCAAgE;AAChE,yDAAmE;AACnE,gEAAuH;AACvH,wEAAmE;AACnE,iEAA4F;AAC5F,+CAAuE;AACvE,+GAA4G;AAC5G,yDAAgE;AAChE,yFAA+E;AAG/E,6GAA4G;AAAnG,4IAAA,4BAA4B,OAAA;AACrC,2CAAyD;AAAhD,6GAAA,oBAAoB,OAAA;AAEtB,KAAK,UAAU,aAAa,CAAC,OAA8B;IACjE,IAAI,CAAC;QACJ,MAAM,iBAAiB,CAAC,OAAO,CAAC,CAAC;QAEjC,YAAY,EAAE,CAAC,SAAS,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,sCAAsC,CAAC,CAAC;QAE/E,MAAM,gBAAgB,GAAG,KAAK,IAAI,EAAE;YACnC,YAA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,CAAC,iBAAiB,CAAC,CAAC;QAC3D,IAAI,CAAC,QAAQ,EAAE,CAAC;YACf,QAAQ,GAAG,kBAAS,CAAC,GAAG,CAAC,iBAAwB,CAAC,CAAC;YACnD,oBAAoB,CAAC,GAAG,CAAC,iBAAiB,EAAE,QAAQ,CAAC,CAAC;QACvD,CAAC;QAED,MAAM,IAAA,wBAAgB,EAAC,OAAO,EAAE,KAAK,EAAC,OAAO,EAAC,EAAE;YAC/C,OAAO,QAAQ,CAAC,UAAU,CAAC,CAAC,OAAO,CAAC,CAAC;QACtC,CAAC,CAAC,CAAC;IACJ,CAAC;AACF,CAAC;AAED,SAAgB,YAAY;IAC3B,OAAO,kBAAS,CAAC,GAAG,CAAC,0BAAc,CAAC,CAAC;AACtC,CAAC","sourcesContent":["// Apply the soft delete plugin globally before any connections or models\nimport { applySoftDeletePlugin } from './libraries/mongo/plugins/soft-delete-plugin';\napplySoftDeletePlugin();\n\nimport { LibraryManager } from './libraries';\nimport { Container } from 'typedi';\nimport { ConfigurationOptions, ConfigurationService } from './libraries/configuration';\nimport { LyxaLogger } from './libraries/logger';\nimport { RedisService } from './libraries/redis';\nimport { initGlobalConnection, initLyxaMongoDbConnection } from './libraries/mongo';\nimport { SecretManagerService } from './libraries/secrets';\nimport { MicroServiceDispatcher } from './libraries/dispatcher';\nimport { TwilioService } from './libraries/twilio';\nimport { FirebaseService } from './libraries/firebase';\nimport { initEventBus, subscribeToEvent } from './libraries/event';\nimport { SubscriptionRegistry } from './libraries/event/registry/SubscriptionRegistry';\nimport { GoogleMapsService, MapService } from './libraries/map';\nimport { CachedSettingsService } from './libraries/cache/settings';\nimport { FCMService, FCMServiceForRider, FCMServiceForShop, FCMServiceForUser } from './libraries/firebase/fcmService';\nimport { BullMQService } from './libraries/bullmq/bull-mq-service';\nimport { BOBSecrets, BOBService, CashSettlementService } from './libraries/cash-settlement';\nimport { disconnectAllEntitiesFromInstance } from './libraries/socket';\nimport { EnvironmentConfigurationType } from './libraries/configuration/types/EnvironmentConfigurationType';\nimport { OsrmMapService } from './libraries/map/providers/osrm';\nimport { RabbitMQUrlMap } from './utilities/environment/rabbitmq-environments';\n\nexport { ConfigurationOptions } from './libraries/configuration';\nexport { EnvironmentConfigurationType } from './libraries/configuration/types/EnvironmentConfigurationType';\nexport { initGlobalConnection } from './libraries/mongo';\n\nexport async function bootstrapCore(options?: ConfigurationOptions) {\n\ttry {\n\t\tawait registerLibraries(options);\n\n\t\tgetLibraries().getLogger().logger.info('Successfully bootstrapped lyxa-core.');\n\n\t\tconst gracefulShutdown = async () => {\n\t\t\tgetLibraries().getLogger().logger.info('Received shutdown signal, shutting down gracefully...');\n\t\t\tif (options?.instanceType == 'socket') await disconnectAllEntitiesFromInstance();\n\t\t\tprocess.exit();\n\t\t};\n\n\t\tprocess.on('SIGTERM', gracefulShutdown);\n\t\tprocess.on('SIGINT', gracefulShutdown);\n\t\tprocess.on('uncaughtException', err => {\n\t\t\tgetLibraries().getLogger().logger.error('Uncaught exception, shutting down...', err);\n\t\t\tgracefulShutdown();\n\t\t});\n\t\tprocess.on('exit', code => {\n\t\t\tgetLibraries().getLogger().logger.info(`Exiting with code: ${code}`);\n\t\t});\n\n\t\tconsole.log('Created hooks.');\n\t} catch (e) {\n\t\tconsole.error(e);\n\t}\n}\n\nexport async function registerLibraries(options?: ConfigurationOptions) {\n\t// Setup configuration.\n\tconst configurationInstance = new ConfigurationService(options);\n\tContainer.set(ConfigurationService, configurationInstance);\n\n\t// Setup redis.\n\tconst redisInstance = new RedisService(configurationInstance.redisURL);\n\tContainer.set(RedisService, redisInstance);\n\n\t// Setup secret\n\tconst secretInstance = new SecretManagerService(configurationInstance, redisInstance);\n\tContainer.set(SecretManagerService, secretInstance);\n\n\t// Setup BullMQ\n\tconst bullMQInstance = new BullMQService(redisInstance);\n\tContainer.set(BullMQService, bullMQInstance);\n\n\tconst mongoUrl = options?.mongoDbUrl\n\t\t? options.mongoDbUrl\n\t\t: await getLibraries().getSecretsService().getKey('MONGO_URL');\n\n\tawait initLyxaMongoDbConnection(mongoUrl!, options);\n\tawait initGlobalConnection(mongoUrl!, options!.environment);\n\n\t// Setup logger\n\tconst loggerInstance = new LyxaLogger(options!.instanceType!, mongoUrl!);\n\tContainer.set(LyxaLogger, loggerInstance);\n\n\t// Setup firebase\n\tconst firebaseInstance = new FirebaseService(configurationInstance!);\n\tContainer.set(FirebaseService, firebaseInstance);\n\n\t// Setup microservice dispatcher\n\tconst microserviceDispatcherInstance = new MicroServiceDispatcher(secretInstance);\n\tContainer.set(MicroServiceDispatcher, microserviceDispatcherInstance);\n\n\t// Setup twilio\n\tconst twilioServiceInstance = new TwilioService();\n\tContainer.set(TwilioService, twilioServiceInstance);\n\n\t// Setup map service\n\tconst googleMapsKey = await getLibraries().getSecretsService().getKey('GOOGLE_MAPS_API_KEY');\n\tconst googleMapService = new GoogleMapsService(redisInstance, googleMapsKey as string);\n\tconst osrmMapService = new OsrmMapService();\n\tconst mapServiceInstance = new MapService(googleMapService, osrmMapService);\n\tContainer.set(MapService, mapServiceInstance);\n\n\t// Setup cash settlement service\n\tconst bobUsername = await getLibraries().getSecretsService().getKey('BOB_USER_NAME');\n\tconst bobPassword = await getLibraries().getSecretsService().getKey('BOB_PASSWORD');\n\tconst bobURL = await getLibraries().getSecretsService().getKey('BOB_URL');\n\n\tconst bobService = new BOBService({\n\t\tBOB_USER_NAME: bobUsername,\n\t\tBOB_PASSWORD: bobPassword,\n\t\tBOB_URL: bobURL,\n\t} as BOBSecrets);\n\tconst cashSettlementServiceInstance = new CashSettlementService(bobService);\n\tContainer.set(CashSettlementService, cashSettlementServiceInstance);\n\tContainer.set(BOBService, bobService);\n\n\tconst settingsServiceInstance = new CachedSettingsService(redisInstance);\n\tContainer.set(CachedSettingsService, settingsServiceInstance);\n\n\ttry {\n\t\tconst settings = await settingsServiceInstance.getSettings();\n\t\tconst { _setTimezone } = await import('./utilities/dayjs/dayjs');\n\t\t_setTimezone(settings?.timezone || 'Asia/Beirut');\n\t\tconsole.log('Timezone initialized:', settings?.timezone || 'Asia/Beirut');\n\t} catch (error) {\n\t\tconsole.error('Failed to initialize timezone:', error);\n\t}\n\n\t// Setup fcm service\n\tconst firebaseService = getLibraries().getFirebaseService();\n\tconst fcmServiceInstance = new FCMService(firebaseService.superApp);\n\tconst fcmServiceInstanceForUser = new FCMService(firebaseService.userApp);\n\tconst fcmServiceInstanceForRider = new FCMService(firebaseService.riderApp);\n\tconst fcmServiceInstanceForShop = new FCMService(firebaseService.shopApp);\n\tContainer.set(FCMService, fcmServiceInstance);\n\tContainer.set(FCMServiceForUser, fcmServiceInstanceForUser);\n\tContainer.set(FCMServiceForRider, fcmServiceInstanceForRider);\n\tContainer.set(FCMServiceForShop, fcmServiceInstanceForShop);\n\n\tconsole.log('Initialized everything');\n\n\tawait initEventBus(RabbitMQUrlMap[options?.environment ?? EnvironmentConfigurationType.DEV]);\n\n\tconst allSubscriptions = SubscriptionRegistry.getAllSubscriptions();\n\n\tconst instantiatedServices = new Map<Function, any>();\n\n\tfor (const { eventId, targetConstructor, methodName } of allSubscriptions) {\n\t\tlet instance = instantiatedServices.get(targetConstructor);\n\t\tif (!instance) {\n\t\t\tinstance = Container.get(targetConstructor as any);\n\t\t\tinstantiatedServices.set(targetConstructor, instance);\n\t\t}\n\n\t\tawait subscribeToEvent(eventId, async payload => {\n\t\t\treturn instance[methodName](payload);\n\t\t});\n\t}\n}\n\nexport function getLibraries(): LibraryManager {\n\treturn Container.get(LibraryManager);\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"/","sources":["index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BA,sCA0BC;AAED,8CAuGC;AAED,oCAEC;AApKD,qFAAqF;AACrF,IAAA,0CAAqB,GAAE,CAAC;AAExB,2CAA6C;AAC7C,mCAAmC;AACnC,6DAAuF;AACvF,+CAAgD;AAChD,6CAAiD;AACjD,6CAAoF;AACpF,iDAA2D;AAC3D,uDAAgE;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AG,CAAC,+BAAkB,EAAE,0BAA0B,CAAC,CAAC;IAC9D,kBAAS,CAAC,GAAG,CAAC,8BAAiB,EAAE,yBAAyB,CAAC,CAAC;IAE5D,OAAO,CAAC,GAAG,CAAC,wBAAwB,CAAC,CAAC;IAEtC,MAAM,IAAA,oBAAY,EAAC,sCAAc,CAAC,OAAO,EAAE,WAAW,IAAI,2DAA4B,CAAC,GAAG,CAAC,CAAC,CAAC;IAE7F,MAAM,gBAAgB,GAAG,2CAAoB,CAAC,mBAAmB,EAAE,CAAC;IAEpE,MAAM,oBAAoB,GAAG,IAAI,GAAG,EAAiB,CAAC;IAEtD,KAAK,MAAM,EAAE,OAAO,EAAE,iBAAiB,EAAE,UAAU,EAAE,IAAI,gBAAgB,EAAE,CAAC;QAC3E,IAAI,QAAQ,GAAG,oBAAoB,CAAC,GAAG,CAAC,iBAAiB,CAAC,CAAC;QAC3D,IAAI,CAAC,QAAQ,EAAE,CAAC;YACf,QAAQ,GAAG,kBAAS,CAAC,GAAG,CAAC,iBAAwB,CAAC,CAAC;YACnD,oBAAoB,CAAC,GAAG,CAAC,iBAAiB,EAAE,QAAQ,CAAC,CAAC;QACvD,CAAC;QAED,MAAM,IAAA,wBAAgB,EAAC,OAAO,EAAE,KAAK,EAAC,OAAO,EAAC,EAAE;YAC/C,OAAO,QAAQ,CAAC,UAAU,CAAC,CAAC,OAAO,CAAC,CAAC;QACtC,CAAC,CAAC,CAAC;IACJ,CAAC;AACF,CAAC;AAED,SAAgB,YAAY;IAC3B,OAAO,kBAAS,CAAC,GAAG,CAAC,0BAAc,CAAC,CAAC;AACtC,CAAC","sourcesContent":["// Apply the soft delete plugin globally before any connections or models\nimport { applySoftDeletePlugin } from './libraries/mongo/plugins/soft-delete-plugin';\napplySoftDeletePlugin();\n\nimport { LibraryManager } from './libraries';\nimport { Container } from 'typedi';\nimport { ConfigurationOptions, ConfigurationService } from './libraries/configuration';\nimport { LyxaLogger } from './libraries/logger';\nimport { RedisService } from './libraries/redis';\nimport { initGlobalConnection, initLyxaMongoDbConnection } from './libraries/mongo';\nimport { SecretManagerService } from './libraries/secrets';\nimport { MicroServiceDispatcher } from './libraries/dispatcher';\nimport { TwilioService } from './libraries/twilio';\nimport { FirebaseService } from './libraries/firebase';\nimport { initEventBus, subscribeToEvent } from './libraries/event';\nimport { SubscriptionRegistry } from './libraries/event/registry/SubscriptionRegistry';\nimport { GoogleMapsService, MapService } from './libraries/map';\nimport { CachedSettingsService } from './libraries/cache/settings';\nimport { FCMService, FCMServiceForRider, FCMServiceForShop, FCMServiceForUser } from './libraries/firebase/fcmService';\nimport { BullMQService } from './libraries/bullmq/bull-mq-service';\nimport { BOBSecrets, BOBService, CashSettlementService } from './libraries/cash-settlement';\n import { EnvironmentConfigurationType } from './libraries/configuration/types/EnvironmentConfigurationType';\nimport { OsrmMapService } from './libraries/map/providers/osrm';\nimport { RabbitMQUrlMap } from './utilities/environment/rabbitmq-environments';\nimport { disconnectAllEntitiesFromInstance } from './libraries/socket/connections/instance-disconnect';\n\nexport { ConfigurationOptions } from './libraries/configuration';\nexport { EnvironmentConfigurationType } from './libraries/configuration/types/EnvironmentConfigurationType';\nexport { initGlobalConnection } from './libraries/mongo';\n\nexport async function bootstrapCore(options?: ConfigurationOptions) {\n\ttry {\n\t\tawait registerLibraries(options);\n\n\t\tgetLibraries().getLogger().logger.info('Successfully bootstrapped lyxa-core.');\n\n\t\tconst gracefulShutdown = async () => {\n\t\t\tgetLibraries().getLogger().logger.info('Received shutdown signal, shutting down gracefully...');\n\t\t\tif (options?.instanceType == 'socket') await disconnectAllEntitiesFromInstance();\n\t\t\tprocess.exit();\n\t\t};\n\n\t\tprocess.on('SIGTERM', gracefulShutdown);\n\t\tprocess.on('SIGINT', gracefulShutdown);\n\t\tprocess.on('uncaughtException', err => {\n\t\t\tgetLibraries().getLogger().logger.error('Uncaught exception, shutting down...', err);\n\t\t\tgracefulShutdown();\n\t\t});\n\t\tprocess.on('exit', code => {\n\t\t\tgetLibraries().getLogger().logger.info(`Exiting with code: ${code}`);\n\t\t});\n\n\t\tconsole.log('Created hooks.');\n\t} catch (e) {\n\t\tconsole.error(e);\n\t}\n}\n\nexport async function registerLibraries(options?: ConfigurationOptions) {\n\t// Setup configuration.\n\tconst configurationInstance = new ConfigurationService(options);\n\tContainer.set(ConfigurationService, configurationInstance);\n\n\t// Setup redis.\n\tconst redisInstance = new RedisService(configurationInstance.redisURL);\n\tContainer.set(RedisService, redisInstance);\n\n\t// Setup secret\n\tconst secretInstance = new SecretManagerService(configurationInstance, redisInstance);\n\tContainer.set(SecretManagerService, secretInstance);\n\n\t// Setup BullMQ\n\tconst bullMQInstance = new BullMQService(redisInstance);\n\tContainer.set(BullMQService, bullMQInstance);\n\n\tconst mongoUrl = options?.mongoDbUrl\n\t\t? options.mongoDbUrl\n\t\t: await getLibraries().getSecretsService().getKey('MONGO_URL');\n\n\tawait initLyxaMongoDbConnection(mongoUrl!, options);\n\tawait initGlobalConnection(mongoUrl!, options!.environment);\n\n\t// Setup logger\n\tconst loggerInstance = new LyxaLogger(options!.instanceType!, mongoUrl!);\n\tContainer.set(LyxaLogger, loggerInstance);\n\n\t// Setup firebase\n\tconst firebaseInstance = new FirebaseService(configurationInstance!);\n\tContainer.set(FirebaseService, firebaseInstance);\n\n\t// Setup microservice dispatcher\n\tconst microserviceDispatcherInstance = new MicroServiceDispatcher(secretInstance);\n\tContainer.set(MicroServiceDispatcher, microserviceDispatcherInstance);\n\n\t// Setup twilio\n\tconst twilioServiceInstance = new TwilioService();\n\tContainer.set(TwilioService, twilioServiceInstance);\n\n\t// Setup map service\n\tconst googleMapsKey = await getLibraries().getSecretsService().getKey('GOOGLE_MAPS_API_KEY');\n\tconst googleMapService = new GoogleMapsService(redisInstance, googleMapsKey as string);\n\tconst osrmMapService = new OsrmMapService();\n\tconst mapServiceInstance = new MapService(googleMapService, osrmMapService);\n\tContainer.set(MapService, mapServiceInstance);\n\n\t// Setup cash settlement service\n\tconst bobUsername = await getLibraries().getSecretsService().getKey('BOB_USER_NAME');\n\tconst bobPassword = await getLibraries().getSecretsService().getKey('BOB_PASSWORD');\n\tconst bobURL = await getLibraries().getSecretsService().getKey('BOB_URL');\n\n\tconst bobService = new BOBService({\n\t\tBOB_USER_NAME: bobUsername,\n\t\tBOB_PASSWORD: bobPassword,\n\t\tBOB_URL: bobURL,\n\t} as BOBSecrets);\n\tconst cashSettlementServiceInstance = new CashSettlementService(bobService);\n\tContainer.set(CashSettlementService, cashSettlementServiceInstance);\n\tContainer.set(BOBService, bobService);\n\n\tconst settingsServiceInstance = new CachedSettingsService(redisInstance);\n\tContainer.set(CachedSettingsService, settingsServiceInstance);\n\n\ttry {\n\t\tconst settings = await settingsServiceInstance.getSettings();\n\t\tconst { _setTimezone } = await import('./utilities/dayjs/dayjs');\n\t\t_setTimezone(settings?.timezone || 'Asia/Beirut');\n\t\tconsole.log('Timezone initialized:', settings?.timezone || 'Asia/Beirut');\n\t} catch (error) {\n\t\tconsole.error('Failed to initialize timezone:', error);\n\t}\n\n\t// Setup fcm service\n\tconst firebaseService = getLibraries().getFirebaseService();\n\tconst fcmServiceInstance = new FCMService(firebaseService.superApp);\n\tconst fcmServiceInstanceForUser = new FCMService(firebaseService.userApp);\n\tconst fcmServiceInstanceForRider = new FCMService(firebaseService.riderApp);\n\tconst fcmServiceInstanceForShop = new FCMService(firebaseService.shopApp);\n\tContainer.set(FCMService, fcmServiceInstance);\n\tContainer.set(FCMServiceForUser, fcmServiceInstanceForUser);\n\tContainer.set(FCMServiceForRider, fcmServiceInstanceForRider);\n\tContainer.set(FCMServiceForShop, fcmServiceInstanceForShop);\n\n\tconsole.log('Initialized everything');\n\n\tawait initEventBus(RabbitMQUrlMap[options?.environment ?? EnvironmentConfigurationType.DEV]);\n\n\tconst allSubscriptions = SubscriptionRegistry.getAllSubscriptions();\n\n\tconst instantiatedServices = new Map<Function, any>();\n\n\tfor (const { eventId, targetConstructor, methodName } of allSubscriptions) {\n\t\tlet instance = instantiatedServices.get(targetConstructor);\n\t\tif (!instance) {\n\t\t\tinstance = Container.get(targetConstructor as any);\n\t\t\tinstantiatedServices.set(targetConstructor, instance);\n\t\t}\n\n\t\tawait subscribeToEvent(eventId, async payload => {\n\t\t\treturn instance[methodName](payload);\n\t\t});\n\t}\n}\n\nexport function getLibraries(): LibraryManager {\n\treturn Container.get(LibraryManager);\n}\n"]}
@@ -1,7 +1,7 @@
1
1
  import { BaseEvent } from '../event/BaseEvent';
2
2
  import { ClickType, SocketEventType } from '../../utilities/enum';
3
- import { EntitySubscription } from './core/socket-redis-connections';
4
3
  import { REGISTRY } from './core/socket-event-registry.map';
4
+ import { EntitySubscription } from './connections';
5
5
  type SocketEventPayloads = {
6
6
  [K in SocketEventType]: (typeof REGISTRY)[K] extends {
7
7
  schemas: {
@@ -1 +1 @@
1
- {"version":3,"file":"PushNotificationEvent.js","sourceRoot":"/","sources":["libraries/socket/PushNotificationEvent.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,kDAA+C;AAG/C,2DAA6D;AAC7D,oDAAwD;AAgCjD,IAAM,qBAAqB,GAA3B,MAAM,qBAAmE,SAAQ,qBAEvF;IACA,YACC,SAAY,EACZ,IAA4B,EAC5B,UAAgC,EAChC,QAA8B;QAE9B,MAAM,OAAO,GAAG,IAAI,CAAC;QACrB,KAAK,CAAC,8BAAiB,CAAC,8BAA8B,EAAE;YACvD,SAAS;YACT,UAAU;YACV,OAAO;YACP,oBAAoB,EAAE,QAAQ;SACE,CAAC,CAAC;IACpC,CAAC;IAED,IAAI,IAAI;QACP,OAAO,IAAI,CAAC,OAAO,CAAC,SAAS,CAAC;IAC/B,CAAC;IAED,IAAI,UAAU;QACb,OAAO,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC;IAChC,CAAC;IAED,UAAU;QACT,OAAO,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC;IAC7B,CAAC;CACD,CAAA;AA7BY,sDAAqB;gCAArB,qBAAqB;IALjC,IAAA,wBAAa,EAAC,mBAAmB,EAAE;QACnC,EAAE,IAAI,EAAE,WAAW,EAAE,IAAI,EAAE,iBAAiB,EAAE;QAC9C,EAAE,IAAI,EAAE,YAAY,EAAE,IAAI,EAAE,sBAAsB,EAAE;QACpD,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE,KAAK,EAAE;KAChC,CAAC;;GACW,qBAAqB,CA6BjC","sourcesContent":["import { BaseEvent } from '../event/BaseEvent';\nimport { ClickType, SocketEventType } from '../../utilities/enum';\nimport { EntitySubscription } from './core/socket-redis-connections';\nimport { EventMetadata } from '../event/decorators/metadata';\nimport { PublishEventEnums } from '../event/EventEnums';\nimport { REGISTRY } from './core/socket-event-registry.map';\n\n// Extract payload types from the registry - use pushNotificationOutput when available, otherwise output\ntype SocketEventPayloads = {\n\t[K in SocketEventType]: (typeof REGISTRY)[K] extends { schemas: { pushNotificationOutput: any } }\n\t\t? import('zod').infer<(typeof REGISTRY)[K]['schemas']['pushNotificationOutput']>\n\t\t: (typeof REGISTRY)[K] extends { schemas: { output: any } }\n\t\t\t? import('zod').infer<(typeof REGISTRY)[K]['schemas']['output']>\n\t\t\t: any;\n};\n\nexport type NotificationSettings =\n\t| { isPushNotification: false }\n\t| {\n\t\t\tisPushNotification: true;\n\t\t\tisClickable: boolean;\n\t\t\tclickType: ClickType;\n\t };\n\nexport type PushNotificationEventData<T extends SocketEventType = SocketEventType> = {\n\teventName: T;\n\trecipients: EntitySubscription[];\n\tpayload: SocketEventPayloads[T];\n\tnotificationSettings: NotificationSettings;\n};\n\n@EventMetadata('notification.push', [\n\t{ name: 'eventName', type: 'SocketEventType' },\n\t{ name: 'recipients', type: 'EntitySubscription[]' },\n\t{ name: 'payload', type: 'any' },\n])\nexport class PushNotificationEvent<T extends SocketEventType = SocketEventType> extends BaseEvent<\n\tPushNotificationEventData<T>\n> {\n\tconstructor(\n\t\teventName: T,\n\t\tdata: SocketEventPayloads[T],\n\t\trecipients: EntitySubscription[],\n\t\tsettings: NotificationSettings\n\t) {\n\t\tconst payload = data;\n\t\tsuper(PublishEventEnums.SOCKET_PUSH_NOTIFICATION_EVENT, {\n\t\t\teventName,\n\t\t\trecipients,\n\t\t\tpayload,\n\t\t\tnotificationSettings: settings,\n\t\t} as PushNotificationEventData<T>);\n\t}\n\n\tget type(): T {\n\t\treturn this.payload.eventName;\n\t}\n\n\tget recipients(): EntitySubscription[] {\n\t\treturn this.payload.recipients;\n\t}\n\n\tgetPayload(): SocketEventPayloads[T] {\n\t\treturn this.payload.payload;\n\t}\n}\n"]}
1
+ {"version":3,"file":"PushNotificationEvent.js","sourceRoot":"/","sources":["libraries/socket/PushNotificationEvent.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,kDAA+C;AAE/C,2DAA6D;AAC7D,oDAAwD;AAiCjD,IAAM,qBAAqB,GAA3B,MAAM,qBAAmE,SAAQ,qBAEvF;IACA,YACC,SAAY,EACZ,IAA4B,EAC5B,UAAgC,EAChC,QAA8B;QAE9B,MAAM,OAAO,GAAG,IAAI,CAAC;QACrB,KAAK,CAAC,8BAAiB,CAAC,8BAA8B,EAAE;YACvD,SAAS;YACT,UAAU;YACV,OAAO;YACP,oBAAoB,EAAE,QAAQ;SACE,CAAC,CAAC;IACpC,CAAC;IAED,IAAI,IAAI;QACP,OAAO,IAAI,CAAC,OAAO,CAAC,SAAS,CAAC;IAC/B,CAAC;IAED,IAAI,UAAU;QACb,OAAO,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC;IAChC,CAAC;IAED,UAAU;QACT,OAAO,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC;IAC7B,CAAC;CACD,CAAA;AA7BY,sDAAqB;gCAArB,qBAAqB;IALjC,IAAA,wBAAa,EAAC,mBAAmB,EAAE;QACnC,EAAE,IAAI,EAAE,WAAW,EAAE,IAAI,EAAE,iBAAiB,EAAE;QAC9C,EAAE,IAAI,EAAE,YAAY,EAAE,IAAI,EAAE,sBAAsB,EAAE;QACpD,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE,KAAK,EAAE;KAChC,CAAC;;GACW,qBAAqB,CA6BjC","sourcesContent":["import { BaseEvent } from '../event/BaseEvent';\nimport { ClickType, SocketEventType } from '../../utilities/enum';\nimport { EventMetadata } from '../event/decorators/metadata';\nimport { PublishEventEnums } from '../event/EventEnums';\nimport { REGISTRY } from './core/socket-event-registry.map';\nimport { EntitySubscription } from './connections';\n\n// Extract payload types from the registry - use pushNotificationOutput when available, otherwise output\ntype SocketEventPayloads = {\n\t[K in SocketEventType]: (typeof REGISTRY)[K] extends { schemas: { pushNotificationOutput: any } }\n\t\t? import('zod').infer<(typeof REGISTRY)[K]['schemas']['pushNotificationOutput']>\n\t\t: (typeof REGISTRY)[K] extends { schemas: { output: any } }\n\t\t\t? import('zod').infer<(typeof REGISTRY)[K]['schemas']['output']>\n\t\t\t: any;\n};\n\nexport type NotificationSettings =\n\t| { isPushNotification: false }\n\t| {\n\t\t\tisPushNotification: true;\n\t\t\tisClickable: boolean;\n\t\t\tclickType: ClickType;\n\t };\n\nexport type PushNotificationEventData<T extends SocketEventType = SocketEventType> = {\n\teventName: T;\n\trecipients: EntitySubscription[];\n\tpayload: SocketEventPayloads[T];\n\tnotificationSettings: NotificationSettings;\n};\n\n@EventMetadata('notification.push', [\n\t{ name: 'eventName', type: 'SocketEventType' },\n\t{ name: 'recipients', type: 'EntitySubscription[]' },\n\t{ name: 'payload', type: 'any' },\n])\nexport class PushNotificationEvent<T extends SocketEventType = SocketEventType> extends BaseEvent<\n\tPushNotificationEventData<T>\n> {\n\tconstructor(\n\t\teventName: T,\n\t\tdata: SocketEventPayloads[T],\n\t\trecipients: EntitySubscription[],\n\t\tsettings: NotificationSettings\n\t) {\n\t\tconst payload = data;\n\t\tsuper(PublishEventEnums.SOCKET_PUSH_NOTIFICATION_EVENT, {\n\t\t\teventName,\n\t\t\trecipients,\n\t\t\tpayload,\n\t\t\tnotificationSettings: settings,\n\t\t} as PushNotificationEventData<T>);\n\t}\n\n\tget type(): T {\n\t\treturn this.payload.eventName;\n\t}\n\n\tget recipients(): EntitySubscription[] {\n\t\treturn this.payload.recipients;\n\t}\n\n\tgetPayload(): SocketEventPayloads[T] {\n\t\treturn this.payload.payload;\n\t}\n}\n"]}
@@ -7,6 +7,7 @@ const instance_utils_1 = require("../../../utilities/instance.utils");
7
7
  const auth_1 = require("../../auth");
8
8
  const events_1 = require("events");
9
9
  const index_1 = require("../../../index");
10
+ const connections_1 = require("../connections");
10
11
  function getEntityId(entity) {
11
12
  switch (entity.type) {
12
13
  case auth_1.AuthEntityType.SELLER:
@@ -29,12 +30,12 @@ async function* _createSocketSubscription(eventType, opts) {
29
30
  const socketId = (0, crypto_1.randomUUID)();
30
31
  const socketInfo = { socketId, eventKey, instanceId: (0, instance_utils_1.getInstanceId)() };
31
32
  const localEE = new core_1.LocalEventEmitter(socketId);
32
- await (0, core_1.connectEntityToSocketEvent)(entity, socketInfo);
33
+ await (0, connections_1.connectEntityToSocketEvent)(entity, socketInfo);
33
34
  core_1.LocalSubs.bind(entity, eventKey, localEE);
34
35
  logger.debug({ entity, socketId, eventKey }, 'Socket subscription connected');
35
36
  opts.signal?.addEventListener('abort', () => {
36
37
  core_1.LocalSubs.unbind(entity, eventKey, localEE);
37
- (0, core_1.disconnectEntityFromSocketEvent)(entity, socketInfo);
38
+ (0, connections_1.disconnectEntityFromSocketEvent)(entity, socketInfo);
38
39
  logger.debug({ entity, socketId, eventKey }, 'Socket subscription disconnected');
39
40
  });
40
41
  for await (const [data] of (0, events_1.on)(localEE.ee, eventKey, { signal: opts.signal })) {
@@ -1 +1 @@
1
- {"version":3,"file":"socket-subscription.js","sourceRoot":"/","sources":["libraries/socket/adapters/socket-subscription.ts"],"names":[],"mappings":";;AAmGA,0EAKC;AAvGD,kCASiB;AACjB,mCAAoC;AACpC,sEAAkE;AAClE,qCAAuD;AAGvD,mCAA4B;AAC5B,0CAA8C;AA+B9C,SAAS,WAAW,CAAC,MAAqB;IACzC,QAAQ,MAAM,CAAC,IAAI,EAAE,C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,EAAE,OAAO,CAAC,CAAC;IAC1C,MAAM,CAAC,KAAK,CAAC,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,EAAE,EAAE,+BAA+B,CAAC,CAAC;IAG9E,IAAI,CAAC,MAAM,EAAE,gBAAgB,CAAC,OAAO,EAAE,GAAG,EAAE;QAC3C,gBAAS,CAAC,MAAM,CAAC,MAAM,EAAE,QAAQ,EAAE,OAAO,CAAC,CAAC;QAC5C,IAAA,sCAA+B,EAAC,MAAM,EAAE,UAAU,CAAC,CAAC;QACpD,MAAM,CAAC,KAAK,CAAC,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,EAAE,EAAE,kCAAkC,CAAC,CAAC;IAClF,CAAC,CAAC,CAAC;IAIH,IAAI,KAAK,EAAE,MAAM,CAAC,IAAI,CAAC,IAAI,IAAA,WAAE,EAAC,OAAO,CAAC,EAAE,EAAE,QAAQ,EAAE,EAAE,MAAM,EAAE,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,CAAC;QAC9E,MAAM,CAAC,KAAK,CAAC,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,EAAE,kCAAkC,CAAC,CAAC;QACvF,MAAM,IAAW,CAAC;IACnB,CAAC;AACF,CAAC;AAED,SAAgB,+BAA+B,CAG7C,SAAqB;IACtB,OAAO,CAAC,IAAkC,EAAE,EAAE,CAAC,yBAAyB,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;AAC3F,CAAC","sourcesContent":["import { SocketEventType } from '../../../utilities/enum';\nimport {\n\tconnectEntityToSocketEvent,\n\tdisconnectEntityFromSocketEvent,\n\tEntitySubscription,\n\tEventFactory,\n\tInputFor,\n\tLocalEventEmitter,\n\tLocalSubs,\n\tOutputFor,\n} from '../core';\nimport { randomUUID } from 'crypto';\nimport { getInstanceId } from '../../../utilities/instance.utils';\nimport { AuthEntityType, TokenType } from '../../auth';\nimport { ProcedureResolverOptions } from '@trpc/server/unstable-core-do-not-import';\nimport { EntityContext, LyxaHTTPContext } from '../../trpc/context';\nimport { on } from 'events';\nimport { getLibraries } from '../../../index';\nimport mongoose from 'mongoose';\n\ntype optsType<\n\tTEventType extends SocketEventType,\n\tTInput extends InputFor<TEventType>,\n> = ProcedureResolverOptions<\n\tobject,\n\tLyxaHTTPContext,\n\t{\n\t\tres: import('http').ServerResponse<import('http').IncomingMessage>;\n\t\ttokenType: TokenType | undefined;\n\t\tentity: EntityContext | undefined;\n\t\treq: import('http').IncomingMessage;\n\t\trequestId: string | undefined;\n\t\tusedRefreshToken: boolean | undefined;\n\t\ttokenRenewed: boolean | undefined;\n\t},\n\tTInput\n>;\n\ninterface _SubscriptionContext {\n\tentity?: { id: string; type: AuthEntityType };\n\tsignal?: AbortSignal;\n}\n\ninterface _SubscriptionOpts<TEventType extends SocketEventType, TInput extends InputFor<TEventType>> {\n\tctx: _SubscriptionContext;\n\tinput: TInput;\n}\n\nfunction getEntityId(entity: EntityContext) {\n\tswitch (entity.type) {\n\t\tcase AuthEntityType.SELLER:\n\t\t\tconst shops = entity.parameters.shops as mongoose.Types.ObjectId[];\n\t\t\treturn shops[0];\n\t\tdefault:\n\t\t\treturn entity.id;\n\t}\n}\n\nasync function* _createSocketSubscription<\n\tTEventType extends SocketEventType,\n\tTInput extends InputFor<TEventType>,\n>(eventType: TEventType, opts: optsType<TEventType, TInput>) {\n\tconst { ctx } = opts;\n\tconst logger = getLibraries().getLogger().logger;\n\n\t// --- USE getEntityId ---\n\tif (!ctx.entity) throw new Error('Entity is required for socket subscription');\n\tconst entityId = getEntityId(ctx.entity);\n\n\tlogger.debug(`Entity ID: ${entityId}`);\n\tconst entity: EntitySubscription = { id: entityId.toString(), type: ctx.entity.type };\n\n\tconst eventKey = EventFactory.getSubscriptionKey(eventType, opts.input);\n\tconsole.log('Event Key:', eventKey);\n\tconst socketId = randomUUID();\n\tconst socketInfo = { socketId, eventKey, instanceId: getInstanceId() };\n\n\tconst localEE = new LocalEventEmitter(socketId);\n\n\t// --- CONNECT ---\n\tawait connectEntityToSocketEvent(entity, socketInfo);\n\tLocalSubs.bind(entity, eventKey, localEE);\n\tlogger.debug({ entity, socketId, eventKey }, 'Socket subscription connected');\n\n\t// --- DISCONNECT ---\n\topts.signal?.addEventListener('abort', () => {\n\t\tLocalSubs.unbind(entity, eventKey, localEE);\n\t\tdisconnectEntityFromSocketEvent(entity, socketInfo);\n\t\tlogger.debug({ entity, socketId, eventKey }, 'Socket subscription disconnected');\n\t});\n\n\t// --- STREAM EVENTS ---\n\ttype Out = OutputFor<TEventType>;\n\tfor await (const [data] of on(localEE.ee, eventKey, { signal: opts.signal })) {\n\t\tlogger.debug({ entity, socketId, eventKey, data }, 'Socket subscription sending data');\n\t\tyield data as Out;\n\t}\n}\n\nexport function createSocketSubscriptionAdapter<\n\tTEventType extends SocketEventType,\n\tTInput extends InputFor<TEventType>,\n>(eventType: TEventType) {\n\treturn (opts: optsType<TEventType, TInput>) => _createSocketSubscription(eventType, opts);\n}\n\n/**\n * @Example\n * const socketRouterTwo = createTRPCRouter({\n * \tonMessage: createAuthenticatedProcedure({ entityTypes: [AuthEntityType.CRM] })\n * \t\t.input(ChatroomMessageSendSocketInputSchema)\n * \t\t.output(zAsyncIterable({ yield: ChatroomMessageSendOutputSchema }))\n * \t\t.subscription(createSocketSubscriptionAdapter(SocketEventType.CHATROOM_MESSAGE_SEND)),\n * });\n */\n"]}
1
+ {"version":3,"file":"socket-subscription.js","sourceRoot":"/","sources":["libraries/socket/adapters/socket-subscription.ts"],"names":[],"mappings":";;AA+FA,0EAKC;AAnGD,kCAA0F;AAC1F,mCAAoC;AACpC,sEAAkE;AAClE,qCAAuD;AAGvD,mCAA4B;AAC5B,0CAA8C;AAE9C,gDAIwB;AA8BxB,SAAS,WAAW,CAAC,MAAqB;IACzC,QAAQ,MAAM,CAAC,IAAI,EAAE,CAAC;QACrB,KAAK,qBAAc,CAAC,MAAM;YACzB,MAAM,KAAK,GAAG,MAAM,CAAC,UAAU,CAAC,KA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E,QAAQ,EAAE,EAAE,+BAA+B,CAAC,CAAC;IAG9E,IAAI,CAAC,MAAM,EAAE,gBAAgB,CAAC,OAAO,EAAE,GAAG,EAAE;QAC3C,gBAAS,CAAC,MAAM,CAAC,MAAM,EAAE,QAAQ,EAAE,OAAO,CAAC,CAAC;QAC5C,IAAA,6CAA+B,EAAC,MAAM,EAAE,UAAU,CAAC,CAAC;QACpD,MAAM,CAAC,KAAK,CAAC,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,EAAE,EAAE,kCAAkC,CAAC,CAAC;IAClF,CAAC,CAAC,CAAC;IAIH,IAAI,KAAK,EAAE,MAAM,CAAC,IAAI,CAAC,IAAI,IAAA,WAAE,EAAC,OAAO,CAAC,EAAE,EAAE,QAAQ,EAAE,EAAE,MAAM,EAAE,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,CAAC;QAC9E,MAAM,CAAC,KAAK,CAAC,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,EAAE,kCAAkC,CAAC,CAAC;QACvF,MAAM,IAAW,CAAC;IACnB,CAAC;AACF,CAAC;AAED,SAAgB,+BAA+B,CAG7C,SAAqB;IACtB,OAAO,CAAC,IAAkC,EAAE,EAAE,CAAC,yBAAyB,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;AAC3F,CAAC","sourcesContent":["import { SocketEventType } from '../../../utilities/enum';\nimport { EventFactory, InputFor, LocalEventEmitter, LocalSubs, OutputFor } from '../core';\nimport { randomUUID } from 'crypto';\nimport { getInstanceId } from '../../../utilities/instance.utils';\nimport { AuthEntityType, TokenType } from '../../auth';\nimport { ProcedureResolverOptions } from '@trpc/server/unstable-core-do-not-import';\nimport { EntityContext, LyxaHTTPContext } from '../../trpc/context';\nimport { on } from 'events';\nimport { getLibraries } from '../../../index';\nimport mongoose from 'mongoose';\nimport {\n\tconnectEntityToSocketEvent,\n\tdisconnectEntityFromSocketEvent,\n\tEntitySubscription,\n} from '../connections';\n\ntype optsType<\n\tTEventType extends SocketEventType,\n\tTInput extends InputFor<TEventType>,\n> = ProcedureResolverOptions<\n\tobject,\n\tLyxaHTTPContext,\n\t{\n\t\tres: import('http').ServerResponse<import('http').IncomingMessage>;\n\t\ttokenType: TokenType | undefined;\n\t\tentity: EntityContext | undefined;\n\t\treq: import('http').IncomingMessage;\n\t\trequestId: string | undefined;\n\t\tusedRefreshToken: boolean | undefined;\n\t\ttokenRenewed: boolean | undefined;\n\t},\n\tTInput\n>;\n\ninterface _SubscriptionContext {\n\tentity?: { id: string; type: AuthEntityType };\n\tsignal?: AbortSignal;\n}\n\ninterface _SubscriptionOpts<TEventType extends SocketEventType, TInput extends InputFor<TEventType>> {\n\tctx: _SubscriptionContext;\n\tinput: TInput;\n}\n\nfunction getEntityId(entity: EntityContext) {\n\tswitch (entity.type) {\n\t\tcase AuthEntityType.SELLER:\n\t\t\tconst shops = entity.parameters.shops as mongoose.Types.ObjectId[];\n\t\t\treturn shops[0];\n\t\tdefault:\n\t\t\treturn entity.id;\n\t}\n}\n\nasync function* _createSocketSubscription<\n\tTEventType extends SocketEventType,\n\tTInput extends InputFor<TEventType>,\n>(eventType: TEventType, opts: optsType<TEventType, TInput>) {\n\tconst { ctx } = opts;\n\tconst logger = getLibraries().getLogger().logger;\n\n\t// --- USE getEntityId ---\n\tif (!ctx.entity) throw new Error('Entity is required for socket subscription');\n\tconst entityId = getEntityId(ctx.entity);\n\n\tlogger.debug(`Entity ID: ${entityId}`);\n\tconst entity: EntitySubscription = { id: entityId.toString(), type: ctx.entity.type };\n\n\tconst eventKey = EventFactory.getSubscriptionKey(eventType, opts.input);\n\tconsole.log('Event Key:', eventKey);\n\tconst socketId = randomUUID();\n\tconst socketInfo = { socketId, eventKey, instanceId: getInstanceId() };\n\n\tconst localEE = new LocalEventEmitter(socketId);\n\n\t// --- CONNECT ---\n\tawait connectEntityToSocketEvent(entity, socketInfo);\n\tLocalSubs.bind(entity, eventKey, localEE);\n\tlogger.debug({ entity, socketId, eventKey }, 'Socket subscription connected');\n\n\t// --- DISCONNECT ---\n\topts.signal?.addEventListener('abort', () => {\n\t\tLocalSubs.unbind(entity, eventKey, localEE);\n\t\tdisconnectEntityFromSocketEvent(entity, socketInfo);\n\t\tlogger.debug({ entity, socketId, eventKey }, 'Socket subscription disconnected');\n\t});\n\n\t// --- STREAM EVENTS ---\n\ttype Out = OutputFor<TEventType>;\n\tfor await (const [data] of on(localEE.ee, eventKey, { signal: opts.signal })) {\n\t\tlogger.debug({ entity, socketId, eventKey, data }, 'Socket subscription sending data');\n\t\tyield data as Out;\n\t}\n}\n\nexport function createSocketSubscriptionAdapter<\n\tTEventType extends SocketEventType,\n\tTInput extends InputFor<TEventType>,\n>(eventType: TEventType) {\n\treturn (opts: optsType<TEventType, TInput>) => _createSocketSubscription(eventType, opts);\n}\n\n/**\n * @Example\n * const socketRouterTwo = createTRPCRouter({\n * \tonMessage: createAuthenticatedProcedure({ entityTypes: [AuthEntityType.CRM] })\n * \t\t.input(ChatroomMessageSendSocketInputSchema)\n * \t\t.output(zAsyncIterable({ yield: ChatroomMessageSendOutputSchema }))\n * \t\t.subscription(createSocketSubscriptionAdapter(SocketEventType.CHATROOM_MESSAGE_SEND)),\n * });\n */\n"]}
@@ -0,0 +1,12 @@
1
+ import { EntitySubscription } from './keys';
2
+ export declare function getEntitySubscriptionInfo(entity: EntitySubscription, eventKey: string): Promise<{
3
+ isSubscribed: boolean;
4
+ instances: string[];
5
+ }>;
6
+ export declare function getEntitySubscriptionInfoBatch(entities: Array<{
7
+ entity: EntitySubscription;
8
+ eventKey: string;
9
+ }>): Promise<Map<string, {
10
+ isSubscribed: boolean;
11
+ instances: string[];
12
+ }>>;
@@ -0,0 +1,58 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getEntitySubscriptionInfo = getEntitySubscriptionInfo;
4
+ exports.getEntitySubscriptionInfoBatch = getEntitySubscriptionInfoBatch;
5
+ const __1 = require("../../..");
6
+ const keys_1 = require("./keys");
7
+ const cache_1 = require("./cache");
8
+ const constants_1 = require("./constants");
9
+ const subscriptionCache = new cache_1.LRUCache(10000);
10
+ async function getEntitySubscriptionInfo(entity, eventKey) {
11
+ const cacheKey = `${(0, keys_1.entityKey)(entity)}:${eventKey}`;
12
+ const cached = subscriptionCache.get(cacheKey);
13
+ if (cached && Date.now() - cached.timestamp < constants_1.CACHE_TTL) {
14
+ return { isSubscribed: cached.isSubscribed, instances: cached.instances };
15
+ }
16
+ const redis = (0, __1.getLibraries)().getRedisService();
17
+ const sockets = await redis.getSetMembers((0, keys_1.kEntityEventSockets)(entity, eventKey));
18
+ const instanceSet = new Set();
19
+ for (const s of sockets) {
20
+ const [instanceId] = s.split('|');
21
+ if (instanceId)
22
+ instanceSet.add(instanceId);
23
+ }
24
+ const result = {
25
+ isSubscribed: sockets.length > 0,
26
+ instances: Array.from(instanceSet),
27
+ };
28
+ subscriptionCache.set(cacheKey, { ...result, timestamp: Date.now() });
29
+ return result;
30
+ }
31
+ async function getEntitySubscriptionInfoBatch(entities) {
32
+ const redis = (0, __1.getLibraries)().getRedisService();
33
+ const results = new Map();
34
+ const now = Date.now();
35
+ await Promise.all(entities.map(async ({ entity, eventKey }) => {
36
+ const cacheKey = `${(0, keys_1.entityKey)(entity)}:${eventKey}`;
37
+ const cached = subscriptionCache.get(cacheKey);
38
+ if (cached && now - cached.timestamp < constants_1.CACHE_TTL) {
39
+ results.set(cacheKey, cached);
40
+ return;
41
+ }
42
+ const sockets = await redis.getSetMembers((0, keys_1.kEntityEventSockets)(entity, eventKey));
43
+ const instanceSet = new Set();
44
+ for (const s of sockets) {
45
+ const [instanceId] = s.split('|');
46
+ if (instanceId)
47
+ instanceSet.add(instanceId);
48
+ }
49
+ const result = {
50
+ isSubscribed: sockets.length > 0,
51
+ instances: Array.from(instanceSet),
52
+ };
53
+ subscriptionCache.set(cacheKey, { ...result, timestamp: now });
54
+ results.set(cacheKey, result);
55
+ }));
56
+ return results;
57
+ }
58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ACd,YAAY,EAAE,OAAO,CAAC,MAAM,GAAG,CAAC;YAChC,SAAS,EAAE,KAAK,CAAC,IAAI,CAAC,WAAW,CAAC;SAClC,CAAC;QACF,iBAAiB,CAAC,GAAG,CAAC,QAAQ,EAAE,EAAE,GAAG,MAAM,EAAE,SAAS,EAAE,GAAG,EAAE,CAAC,CAAC;QAC/D,OAAO,CAAC,GAAG,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;IAC/B,CAAC,CAAC,CACF,CAAC;IACF,OAAO,OAAO,CAAC;AAChB,CAAC","sourcesContent":["// Batch and query helpers for socket Redis logic\nimport { getLibraries } from '../../..';\nimport { kEntityEventSockets, entityKey, EntitySubscription } from './keys';\nimport { LRUCache } from './cache';\nimport { CACHE_TTL } from './constants';\n\nconst subscriptionCache = new LRUCache<\n\tstring,\n\t{ isSubscribed: boolean; instances: string[]; timestamp: number }\n>(10000);\n\nexport async function getEntitySubscriptionInfo(\n\tentity: EntitySubscription,\n\teventKey: string\n): Promise<{ isSubscribed: boolean; instances: string[] }> {\n\tconst cacheKey = `${entityKey(entity)}:${eventKey}`;\n\tconst cached = subscriptionCache.get(cacheKey);\n\tif (cached && Date.now() - cached.timestamp < CACHE_TTL) {\n\t\treturn { isSubscribed: cached.isSubscribed, instances: cached.instances };\n\t}\n\tconst redis = getLibraries().getRedisService();\n\tconst sockets = await redis.getSetMembers(kEntityEventSockets(entity, eventKey));\n\tconst instanceSet = new Set<string>();\n\tfor (const s of sockets) {\n\t\tconst [instanceId] = s.split('|');\n\t\tif (instanceId) instanceSet.add(instanceId);\n\t}\n\tconst result = {\n\t\tisSubscribed: sockets.length > 0,\n\t\tinstances: Array.from(instanceSet),\n\t};\n\tsubscriptionCache.set(cacheKey, { ...result, timestamp: Date.now() });\n\treturn result;\n}\n\nexport async function getEntitySubscriptionInfoBatch(\n\tentities: Array<{ entity: EntitySubscription; eventKey: string }>\n): Promise<Map<string, { isSubscribed: boolean; instances: string[] }>> {\n\tconst redis = getLibraries().getRedisService();\n\tconst results = new Map<string, { isSubscribed: boolean; instances: string[] }>();\n\tconst now = Date.now();\n\tawait Promise.all(\n\t\tentities.map(async ({ entity, eventKey }) => {\n\t\t\tconst cacheKey = `${entityKey(entity)}:${eventKey}`;\n\t\t\tconst cached = subscriptionCache.get(cacheKey);\n\t\t\tif (cached && now - cached.timestamp < CACHE_TTL) {\n\t\t\t\tresults.set(cacheKey, cached);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst sockets = await redis.getSetMembers(kEntityEventSockets(entity, eventKey));\n\t\t\tconst instanceSet = new Set<string>();\n\t\t\tfor (const s of sockets) {\n\t\t\t\tconst [instanceId] = s.split('|');\n\t\t\t\tif (instanceId) instanceSet.add(instanceId);\n\t\t\t}\n\t\t\tconst result = {\n\t\t\t\tisSubscribed: sockets.length > 0,\n\t\t\t\tinstances: Array.from(instanceSet),\n\t\t\t};\n\t\t\tsubscriptionCache.set(cacheKey, { ...result, timestamp: now });\n\t\t\tresults.set(cacheKey, result);\n\t\t})\n\t);\n\treturn results;\n}\n"]}
@@ -0,0 +1,9 @@
1
+ export declare class LRUCache<K, V> {
2
+ private cache;
3
+ private maxSize;
4
+ constructor(maxSize?: number);
5
+ get(key: K): V | undefined;
6
+ set(key: K, value: V): void;
7
+ delete(key: K): void;
8
+ clear(): void;
9
+ }
@@ -0,0 +1,36 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.LRUCache = void 0;
4
+ class LRUCache {
5
+ cache = new Map();
6
+ maxSize;
7
+ constructor(maxSize = 10000) {
8
+ this.maxSize = maxSize;
9
+ }
10
+ get(key) {
11
+ const value = this.cache.get(key);
12
+ if (value !== undefined) {
13
+ this.cache.delete(key);
14
+ this.cache.set(key, value);
15
+ }
16
+ return value;
17
+ }
18
+ set(key, value) {
19
+ this.cache.delete(key);
20
+ if (this.cache.size >= this.maxSize) {
21
+ const firstKey = this.cache.keys().next().value;
22
+ if (firstKey !== undefined) {
23
+ this.cache.delete(firstKey);
24
+ }
25
+ }
26
+ this.cache.set(key, value);
27
+ }
28
+ delete(key) {
29
+ this.cache.delete(key);
30
+ }
31
+ clear() {
32
+ this.cache.clear();
33
+ }
34
+ }
35
+ exports.LRUCache = LRUCache;
36
+ //# sourceMappingURL=cache.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cache.js","sourceRoot":"/","sources":["libraries/socket/connections/cache.ts"],"names":[],"mappings":";;;AACA,MAAa,QAAQ;IACZ,KAAK,GAAG,IAAI,GAAG,EAAQ,CAAC;IACxB,OAAO,CAAS;IAExB,YAAY,OAAO,GAAG,KAAK;QAC1B,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACxB,CAAC;IAED,GAAG,CAAC,GAAM;QACT,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QAClC,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;YACzB,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;YACvB,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;QAC5B,CAAC;QACD,OAAO,KAAK,CAAC;IACd,CAAC;IAED,GAAG,CAAC,GAAM,EAAE,KAAQ;QACnB,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;QACvB,IAAI,IAAI,CAAC,KAAK,CAAC,IAAI,IAAI,IAAI,CAAC,OAAO,EAAE,CAAC;YACrC,MAAM,QAAQ,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC;YAChD,IAAI,QAAQ,KAAK,SAAS,EAAE,CAAC;gBAC5B,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;YAC7B,CAAC;QACF,CAAC;QACD,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;IAC5B,CAAC;IAED,MAAM,CAAC,GAAM;QACZ,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;IACxB,CAAC;IAED,KAAK;QACJ,IAAI,CAAC,KAAK,CAAC,KAAK,EAAE,CAAC;IACpB,CAAC;CACD;AAnCD,4BAmCC","sourcesContent":["// LRUCache and cache instances for socket Redis logic\nexport class LRUCache<K, V> {\n\tprivate cache = new Map<K, V>();\n\tprivate maxSize: number;\n\n\tconstructor(maxSize = 10000) {\n\t\tthis.maxSize = maxSize;\n\t}\n\n\tget(key: K): V | undefined {\n\t\tconst value = this.cache.get(key);\n\t\tif (value !== undefined) {\n\t\t\tthis.cache.delete(key);\n\t\t\tthis.cache.set(key, value);\n\t\t}\n\t\treturn value;\n\t}\n\n\tset(key: K, value: V): void {\n\t\tthis.cache.delete(key);\n\t\tif (this.cache.size >= this.maxSize) {\n\t\t\tconst firstKey = this.cache.keys().next().value;\n\t\t\tif (firstKey !== undefined) {\n\t\t\t\tthis.cache.delete(firstKey);\n\t\t\t}\n\t\t}\n\t\tthis.cache.set(key, value);\n\t}\n\n\tdelete(key: K): void {\n\t\tthis.cache.delete(key);\n\t}\n\n\tclear(): void {\n\t\tthis.cache.clear();\n\t}\n}\n"]}
@@ -0,0 +1,2 @@
1
+ export declare const CACHE_TTL = 5000;
2
+ export declare const REDIS_KEY_TTL_SECONDS = 120;
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.REDIS_KEY_TTL_SECONDS = exports.CACHE_TTL = void 0;
4
+ exports.CACHE_TTL = 5000;
5
+ exports.REDIS_KEY_TTL_SECONDS = 120;
6
+ //# sourceMappingURL=constants.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"constants.js","sourceRoot":"/","sources":["libraries/socket/connections/constants.ts"],"names":[],"mappings":";;;AACa,QAAA,SAAS,GAAG,IAAI,CAAC;AACjB,QAAA,qBAAqB,GAAG,GAAG,CAAC","sourcesContent":["// Constants for socket Redis logic\nexport const CACHE_TTL = 5000;\nexport const REDIS_KEY_TTL_SECONDS = 120;\n"]}
@@ -0,0 +1,5 @@
1
+ import { EntitySubscription } from './keys';
2
+ import { AuthEntityType } from '../../auth';
3
+ export declare function getEventSubscribers(eventKey: string): Promise<EntitySubscription[]>;
4
+ export declare function getEventSubscribersByType(eventKey: string, entityType: AuthEntityType): Promise<EntitySubscription[]>;
5
+ export declare function getEventSubscriberCount(eventKey: string): Promise<number>;
@@ -0,0 +1,60 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getEventSubscribers = getEventSubscribers;
4
+ exports.getEventSubscribersByType = getEventSubscribersByType;
5
+ exports.getEventSubscriberCount = getEventSubscriberCount;
6
+ const __1 = require("../../..");
7
+ const keys_1 = require("./keys");
8
+ const cache_1 = require("./cache");
9
+ const constants_1 = require("./constants");
10
+ const eventSubscribersCache = new cache_1.LRUCache(5000);
11
+ async function getEventSubscribers(eventKey) {
12
+ const cached = eventSubscribersCache.get(eventKey);
13
+ if (cached && Date.now() - cached.timestamp < constants_1.CACHE_TTL) {
14
+ return cached.subscribers;
15
+ }
16
+ const redis = (0, __1.getLibraries)().getRedisService();
17
+ const data = await redis.getSetMembers((0, keys_1.kEventEntity)(eventKey));
18
+ const map = new Map();
19
+ for (const s of data) {
20
+ const [entityKeyStr] = s.split('|');
21
+ if (!map.has(entityKeyStr)) {
22
+ const [type, id] = entityKeyStr.split(':');
23
+ map.set(entityKeyStr, { id, type: type === 'default' ? undefined : type });
24
+ }
25
+ }
26
+ const subscribers = Array.from(map.values());
27
+ eventSubscribersCache.set(eventKey, { subscribers, timestamp: Date.now() });
28
+ return subscribers;
29
+ }
30
+ async function getEventSubscribersByType(eventKey, entityType) {
31
+ const cached = eventSubscribersCache.get(eventKey);
32
+ if (cached && Date.now() - cached.timestamp < constants_1.CACHE_TTL) {
33
+ return cached.subscribers.filter(s => s.type === entityType);
34
+ }
35
+ const redis = (0, __1.getLibraries)().getRedisService();
36
+ const data = await redis.getSetMembers((0, keys_1.kEventEntity)(eventKey));
37
+ const filtered = [];
38
+ const map = new Map();
39
+ for (const s of data) {
40
+ const [entityKeyStr] = s.split('|');
41
+ if (!map.has(entityKeyStr)) {
42
+ const [type, id] = entityKeyStr.split(':');
43
+ const entity = { id, type: type === 'default' ? undefined : type };
44
+ map.set(entityKeyStr, entity);
45
+ if (entity.type === entityType)
46
+ filtered.push(entity);
47
+ }
48
+ }
49
+ eventSubscribersCache.set(eventKey, { subscribers: Array.from(map.values()), timestamp: Date.now() });
50
+ return filtered;
51
+ }
52
+ async function getEventSubscriberCount(eventKey) {
53
+ const cached = eventSubscribersCache.get(eventKey);
54
+ if (cached && Date.now() - cached.timestamp < constants_1.CACHE_TTL) {
55
+ return cached.subscribers.length;
56
+ }
57
+ const redis = (0, __1.getLibraries)().getRedisService();
58
+ return (await redis.getSetMembers((0, keys_1.kEventEntity)(eventKey))).length;
59
+ }
60
+ //# sourceMappingURL=event-subscribers.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"event-subscribers.js","sourceRoot":"/","sources":["libraries/socket/connections/event-subscribers.ts"],"names":[],"mappings":";;AAWA,kDAmBC;AAED,8DAuBC;AAED,0DAOC;AA/DD,gCAAwC;AACxC,iCAAqE;AACrE,mCAAmC;AACnC,2CAAwC;AAGxC,MAAM,qBAAqB,GAAG,IAAI,gBAAQ,CACzC,IAAI,CACJ,CAAC;AAEK,KAAK,UAAU,mBAAmB,CAAC,QAAgB;IACzD,MAAM,MAAM,GAAG,qBAAqB,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;IACnD,IAAI,MAAM,IAAI,IAAI,CAAC,GAAG,EAAE,GAAG,MAAM,CAAC,SAAS,GAAG,qBAAS,EAAE,CAAC;QACzD,OAAO,MAAM,CAAC,WAAW,CAAC;IAC3B,CAAC;IACD,MAAM,KAAK,GAAG,IAAA,gBAAY,GAAE,CAAC,eAAe,EAAE,CAAC;I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AS,EAAE,CAAC;QACzD,OAAO,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC;IAClC,CAAC;IACD,MAAM,KAAK,GAAG,IAAA,gBAAY,GAAE,CAAC,eAAe,EAAE,CAAC;IAC/C,OAAO,CAAC,MAAM,KAAK,CAAC,aAAa,CAAC,IAAA,mBAAY,EAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC;AACnE,CAAC","sourcesContent":["// Event subscriber helpers for socket Redis logic\nimport { getLibraries } from '../../..';\nimport { kEventEntity, entityKey, EntitySubscription } from './keys';\nimport { LRUCache } from './cache';\nimport { CACHE_TTL } from './constants';\nimport { AuthEntityType } from '../../auth';\n\nconst eventSubscribersCache = new LRUCache<string, { subscribers: EntitySubscription[]; timestamp: number }>(\n\t5000\n);\n\nexport async function getEventSubscribers(eventKey: string): Promise<EntitySubscription[]> {\n\tconst cached = eventSubscribersCache.get(eventKey);\n\tif (cached && Date.now() - cached.timestamp < CACHE_TTL) {\n\t\treturn cached.subscribers;\n\t}\n\tconst redis = getLibraries().getRedisService();\n\tconst data = await redis.getSetMembers(kEventEntity(eventKey));\n\tconst map = new Map<string, EntitySubscription>();\n\tfor (const s of data) {\n\t\t// s = \"entityKey|instanceId|socketId\"\n\t\tconst [entityKeyStr] = s.split('|');\n\t\tif (!map.has(entityKeyStr)) {\n\t\t\tconst [type, id] = entityKeyStr.split(':');\n\t\t\tmap.set(entityKeyStr, { id, type: type === 'default' ? undefined : (type as AuthEntityType) });\n\t\t}\n\t}\n\tconst subscribers = Array.from(map.values());\n\teventSubscribersCache.set(eventKey, { subscribers, timestamp: Date.now() });\n\treturn subscribers;\n}\n\nexport async function getEventSubscribersByType(\n\teventKey: string,\n\tentityType: AuthEntityType\n): Promise<EntitySubscription[]> {\n\tconst cached = eventSubscribersCache.get(eventKey);\n\tif (cached && Date.now() - cached.timestamp < CACHE_TTL) {\n\t\treturn cached.subscribers.filter(s => s.type === entityType);\n\t}\n\tconst redis = getLibraries().getRedisService();\n\tconst data = await redis.getSetMembers(kEventEntity(eventKey));\n\tconst filtered: EntitySubscription[] = [];\n\tconst map = new Map<string, EntitySubscription>();\n\tfor (const s of data) {\n\t\tconst [entityKeyStr] = s.split('|');\n\t\tif (!map.has(entityKeyStr)) {\n\t\t\tconst [type, id] = entityKeyStr.split(':');\n\t\t\tconst entity = { id, type: type === 'default' ? undefined : (type as AuthEntityType) };\n\t\t\tmap.set(entityKeyStr, entity);\n\t\t\tif (entity.type === entityType) filtered.push(entity);\n\t\t}\n\t}\n\teventSubscribersCache.set(eventKey, { subscribers: Array.from(map.values()), timestamp: Date.now() });\n\treturn filtered;\n}\n\nexport async function getEventSubscriberCount(eventKey: string): Promise<number> {\n\tconst cached = eventSubscribersCache.get(eventKey);\n\tif (cached && Date.now() - cached.timestamp < CACHE_TTL) {\n\t\treturn cached.subscribers.length;\n\t}\n\tconst redis = getLibraries().getRedisService();\n\treturn (await redis.getSetMembers(kEventEntity(eventKey))).length;\n}\n"]}
@@ -0,0 +1,7 @@
1
+ export * from './presence';
2
+ export * from './keys';
3
+ export * from './cache';
4
+ export * from './constants';
5
+ export * from './redis-helpers';
6
+ export * from './subscription';
7
+ export * from './batch';
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./presence"), exports);
18
+ __exportStar(require("./keys"), exports);
19
+ __exportStar(require("./cache"), exports);
20
+ __exportStar(require("./constants"), exports);
21
+ __exportStar(require("./redis-helpers"), exports);
22
+ __exportStar(require("./subscription"), exports);
23
+ __exportStar(require("./batch"), exports);
24
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"/","sources":["libraries/socket/connections/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,6CAA2B;AAC3B,yCAAuB;AACvB,0CAAwB;AACxB,8CAA4B;AAC5B,kDAAgC;AAChC,iDAA+B;AAC/B,0CAAwB","sourcesContent":["export * from './presence';\nexport * from './keys';\nexport * from './cache';\nexport * from './constants';\nexport * from './redis-helpers';\nexport * from './subscription';\nexport * from './batch';\n"]}
@@ -0,0 +1,2 @@
1
+ import { AuthEntityType } from '../../auth';
2
+ export declare function disconnectAllEntitiesFromInstance(entityType?: AuthEntityType): Promise<void>;
@@ -0,0 +1,43 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.disconnectAllEntitiesFromInstance = disconnectAllEntitiesFromInstance;
4
+ const instance_utils_1 = require("../../../utilities/instance.utils");
5
+ const __1 = require("../../..");
6
+ const keys_1 = require("./keys");
7
+ const redis_helpers_1 = require("./redis-helpers");
8
+ async function disconnectAllEntitiesFromInstance(entityType) {
9
+ const instanceId = (0, instance_utils_1.getInstanceId)();
10
+ const redis = (0, __1.getLibraries)().getRedisService();
11
+ const pattern = entityType
12
+ ? `socket:active_subscriptions:${entityType}:*`
13
+ : 'socket:active_subscriptions:*';
14
+ const ledgerKeys = await (0, redis_helpers_1.scanKeys)(redis.redisClient, pattern);
15
+ const affectedEvents = new Set();
16
+ await Promise.all(ledgerKeys.map(async (ledgerKey) => {
17
+ const [, , type, id] = ledgerKey.split(':');
18
+ const entity = {
19
+ id,
20
+ type: type === 'default' ? undefined : type,
21
+ };
22
+ const eventKeys = await redis.getSetMembers(ledgerKey);
23
+ const pipeline = redis.redisClient.pipeline();
24
+ for (const eventKey of eventKeys) {
25
+ const entityEventKey = (0, keys_1.kEntityEventSockets)(entity, eventKey);
26
+ const sockets = await redis.getSetMembers(entityEventKey);
27
+ const toRemove = sockets.filter(s => {
28
+ const [sInstanceId] = s.split('|');
29
+ return sInstanceId === instanceId;
30
+ });
31
+ for (const s of toRemove) {
32
+ pipeline.srem(entityEventKey, s);
33
+ }
34
+ if (sockets.length - toRemove.length === 0) {
35
+ pipeline.del(entityEventKey);
36
+ pipeline.srem(ledgerKey, eventKey);
37
+ }
38
+ affectedEvents.add(eventKey);
39
+ }
40
+ await pipeline.exec();
41
+ }));
42
+ }
43
+ //# sourceMappingURL=instance-disconnect.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"instance-disconnect.js","sourceRoot":"/","sources":["libraries/socket/connections/instance-disconnect.ts"],"names":[],"mappings":";;AAgBA,8EAqCC;AApDD,sEAAkE;AAClE,gCAAwC;AACxC,iCAA0F;AAC1F,mDAA2C;AAYpC,KAAK,UAAU,iCAAiC,CAAC,UAA2B;IAClF,MAAM,UAAU,GAAG,IAAA,8BAAa,GAAE,CAAC;IACnC,MAAM,KAAK,GAAG,IAAA,gBAAY,GAAE,CAAC,eAAe,EAAE,CAAC;IAC/C,MAAM,OAAO,GAAG,UAAU;QACzB,CAAC,CAAC,+BAA+B,UAAU,IAAI;QAC/C,CAAC,CAAC,+BAA+B,CAAC;IACnC,MAAM,UAAU,GAAG,MAAM,IAAA,wBAAQ,EAAC,KAAK,CAAC,WAAW,EAAE,OAAO,CAAC,CAAC;IAC9D,MAAM,cAAc,GAAG,IAAI,GAAG,EAAU,CAAC;IACzC,MAAM,OAAO,CAAC,GAAG,CAChB,UAAU,CAAC,GAAG,CAAC,KAAK,EAAC,SAAS,EAAC,EAAE;QAChC,MAAM,CAAC,EAAE,AAAD,EAAG,IAAI,EAAE,EAAE,CAAC,GAAG,SAAS,CAAC,KAA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../../utilities/instance.utils';\nimport { getLibraries } from '../../..';\nimport { kEntityEvent, kEntityEventSockets, entityKey, EntitySubscription } from './keys';\nimport { scanKeys } from './redis-helpers';\nimport { AuthEntityType } from '../../auth';\nimport { LRUCache } from './cache';\n\n/**\n * Removes all sockets belonging to the current instance.\n * Used on shutdown or crash recovery.\n * Cleans entity-event keys, event subscribers, and ledgers in bulk.\n *\n * NOTE: This currently scans all ledgers (SCAN), which is acceptable for small/medium scale and infrequent use.\n * For very large scale or frequent shutdowns, consider maintaining a reverse index (instance → ledgers) to avoid SCAN entirely.\n */\nexport async function disconnectAllEntitiesFromInstance(entityType?: AuthEntityType) {\n\tconst instanceId = getInstanceId();\n\tconst redis = getLibraries().getRedisService();\n\tconst pattern = entityType\n\t\t? `socket:active_subscriptions:${entityType}:*`\n\t\t: 'socket:active_subscriptions:*';\n\tconst ledgerKeys = await scanKeys(redis.redisClient, pattern);\n\tconst affectedEvents = new Set<string>();\n\tawait Promise.all(\n\t\tledgerKeys.map(async ledgerKey => {\n\t\t\tconst [, , type, id] = ledgerKey.split(':');\n\t\t\tconst entity: EntitySubscription = {\n\t\t\t\tid,\n\t\t\t\ttype: type === 'default' ? undefined : (type as AuthEntityType),\n\t\t\t};\n\t\t\tconst eventKeys = await redis.getSetMembers(ledgerKey);\n\t\t\tconst pipeline = redis.redisClient.pipeline();\n\t\t\tfor (const eventKey of eventKeys) {\n\t\t\t\tconst entityEventKey = kEntityEventSockets(entity, eventKey);\n\t\t\t\tconst sockets = await redis.getSetMembers(entityEventKey);\n\t\t\t\t// Remove all sockets for this instance\n\t\t\t\tconst toRemove = sockets.filter(s => {\n\t\t\t\t\tconst [sInstanceId] = s.split('|');\n\t\t\t\t\treturn sInstanceId === instanceId;\n\t\t\t\t});\n\t\t\t\tfor (const s of toRemove) {\n\t\t\t\t\tpipeline.srem(entityEventKey, s);\n\t\t\t\t}\n\t\t\t\tif (sockets.length - toRemove.length === 0) {\n\t\t\t\t\tpipeline.del(entityEventKey);\n\t\t\t\t\tpipeline.srem(ledgerKey, eventKey);\n\t\t\t\t}\n\t\t\t\taffectedEvents.add(eventKey);\n\t\t\t}\n\t\t\tawait pipeline.exec();\n\t\t})\n\t);\n}\n"]}
@@ -0,0 +1,10 @@
1
+ import { AuthEntityType } from '../../auth';
2
+ export type EntitySubscription = {
3
+ id: string;
4
+ type?: AuthEntityType;
5
+ };
6
+ export declare const entityKey: (entity: EntitySubscription) => string;
7
+ export declare const kEventEntity: (eventKey: string) => string;
8
+ export declare const kEntityEvent: (entity: EntitySubscription) => string;
9
+ export declare const kOnlineEntities: (type: AuthEntityType) => string;
10
+ export declare const kEntityEventSockets: (entity: EntitySubscription, eventKey: string) => string;
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.kEntityEventSockets = exports.kOnlineEntities = exports.kEntityEvent = exports.kEventEntity = exports.entityKey = void 0;
4
+ const keyCache = new Map();
5
+ const entityKey = (entity) => {
6
+ const cacheKey = `${entity.type}:${entity.id}`;
7
+ let key = keyCache.get(cacheKey);
8
+ if (!key) {
9
+ key = `${entity.type ?? 'default'}:${entity.id}`;
10
+ keyCache.set(cacheKey, key);
11
+ }
12
+ return key;
13
+ };
14
+ exports.entityKey = entityKey;
15
+ const kEventEntity = (eventKey) => `socket:event:${eventKey}`;
16
+ exports.kEventEntity = kEventEntity;
17
+ const kEntityEvent = (entity) => `socket:subscriptions:${(0, exports.entityKey)(entity)}`;
18
+ exports.kEntityEvent = kEntityEvent;
19
+ const kOnlineEntities = (type) => `socket:online:${type}`;
20
+ exports.kOnlineEntities = kOnlineEntities;
21
+ const kEntityEventSockets = (entity, eventKey) => `socket:entity:${(0, exports.entityKey)(entity)}:${eventKey}`;
22
+ exports.kEntityEventSockets = kEntityEventSockets;
23
+ //# sourceMappingURL=keys.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"keys.js","sourceRoot":"/","sources":["libraries/socket/connections/keys.ts"],"names":[],"mappings":";;;AAOA,MAAM,QAAQ,GAAG,IAAI,GAAG,EAAkB,CAAC;AAEpC,MAAM,SAAS,GAAG,CAAC,MAA0B,EAAU,EAAE;IAC/D,MAAM,QAAQ,GAAG,GAAG,MAAM,CAAC,IAAI,IAAI,MAAM,CAAC,EAAE,EAAE,CAAC;IAC/C,IAAI,GAAG,GAAG,QAAQ,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;IACjC,IAAI,CAAC,GAAG,EAAE,CAAC;QACV,GAAG,GAAG,GAAG,MAAM,CAAC,IAAI,IAAI,SAAS,IAAI,MAAM,CAAC,EAAE,EAAE,CAAC;QACjD,QAAQ,CAAC,GAAG,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAC;IAC7B,CAAC;IACD,OAAO,GAAG,CAAC;AACZ,CAAC,CAAC;AARW,QAAA,SAAS,aAQpB;AAEK,MAAM,YAAY,GAAG,CAAC,QAAgB,EAAE,EAAE,CAAC,gBAAgB,QAAQ,EAAE,CAAC;AAAhE,QAAA,YAAY,gBAAoD;AAEtE,MAAM,YAAY,GAAG,CAAC,MAA0B,EAAE,EAAE,CAAC,wBAAwB,IAAA,iBAAS,EAAC,MAAM,CAAC,EAAE,CAAC;AAA3F,QAAA,YAAY,gBAA+E;AAEjG,MAAM,eAAe,GAAG,CAAC,IAAoB,EAAE,EAAE,CAAC,iBAAiB,IAAI,EAAE,CAAC;AAApE,QAAA,eAAe,mBAAqD;AAE1E,MAAM,mBAAmB,GAAG,CAAC,MAA0B,EAAE,QAAgB,EAAE,EAAE,CACnF,iBAAiB,IAAA,iBAAS,EAAC,MAAM,CAAC,IAAI,QAAQ,EAAE,CAAC;AADrC,QAAA,mBAAmB,uBACkB","sourcesContent":["import { AuthEntityType } from '../../auth';\n\nexport type EntitySubscription = {\n\tid: string;\n\ttype?: AuthEntityType;\n};\n\nconst keyCache = new Map<string, string>();\n\nexport const entityKey = (entity: EntitySubscription): string => {\n\tconst cacheKey = `${entity.type}:${entity.id}`;\n\tlet key = keyCache.get(cacheKey);\n\tif (!key) {\n\t\tkey = `${entity.type ?? 'default'}:${entity.id}`;\n\t\tkeyCache.set(cacheKey, key);\n\t}\n\treturn key;\n};\n\nexport const kEventEntity = (eventKey: string) => `socket:event:${eventKey}`;\n\nexport const kEntityEvent = (entity: EntitySubscription) => `socket:subscriptions:${entityKey(entity)}`;\n\nexport const kOnlineEntities = (type: AuthEntityType) => `socket:online:${type}`;\n\nexport const kEntityEventSockets = (entity: EntitySubscription, eventKey: string) =>\n\t`socket:entity:${entityKey(entity)}:${eventKey}`;\n"]}
@@ -0,0 +1,4 @@
1
+ import { AuthEntityType } from '../../auth';
2
+ export declare function setUserOnline(userId: string, type: AuthEntityType, timestamp?: number): Promise<void>;
3
+ export declare function setUserOffline(userId: string, type: AuthEntityType): Promise<void>;
4
+ export declare function getOnlineUsers(type: AuthEntityType, page?: number, pageSize?: number): Promise<string[]>;
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.setUserOnline = setUserOnline;
4
+ exports.setUserOffline = setUserOffline;
5
+ exports.getOnlineUsers = getOnlineUsers;
6
+ const __1 = require("../../..");
7
+ const keys_1 = require("./keys");
8
+ async function setUserOnline(userId, type, timestamp = Date.now()) {
9
+ const redis = (0, __1.getLibraries)().getRedisService().redisClient;
10
+ await redis.zadd((0, keys_1.kOnlineEntities)(type), timestamp, userId);
11
+ }
12
+ async function setUserOffline(userId, type) {
13
+ const redis = (0, __1.getLibraries)().getRedisService().redisClient;
14
+ await redis.zrem((0, keys_1.kOnlineEntities)(type), userId);
15
+ }
16
+ async function getOnlineUsers(type, page = 1, pageSize = 100) {
17
+ const redis = (0, __1.getLibraries)().getRedisService().redisClient;
18
+ const zsetKey = (0, keys_1.kOnlineEntities)(type);
19
+ const start = (page - 1) * pageSize;
20
+ const end = start + pageSize - 1;
21
+ return await redis.zrange(zsetKey, start, end);
22
+ }
23
+ //# sourceMappingURL=presence.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"presence.js","sourceRoot":"/","sources":["libraries/socket/connections/presence.ts"],"names":[],"mappings":";;AAQA,sCAGC;AAKD,wCAGC;AAKD,wCAUC;AAlCD,gCAAwC;AAExC,iCAAyC;AAMlC,KAAK,UAAU,aAAa,CAAC,MAAc,EAAE,IAAoB,EAAE,YAAoB,IAAI,CAAC,GAAG,EAAE;IACvG,MAAM,KAAK,GAAG,IAAA,gBAAY,GAAE,CAAC,eAAe,EAAE,CAAC,WAAoB,CAAC;IACpE,MAAM,KAAK,CAAC,IAAI,CAAC,IAAA,sBAAe,EAAC,IAAI,CAAC,EAAE,SAAS,EAAE,MAAM,CAAC,CAAC;AAC5D,CAAC;AAKM,KAAK,UAAU,cAAc,CAAC,MAAc,EAAE,IAAoB;IACxE,MAAM,KAAK,GAAG,IAAA,gBAAY,GAAE,CAAC,eAAe,EAAE,CAAC,WAAoB,CAAC;IACpE,MAAM,KAAK,CAAC,IAAI,CAAC,IAAA,sBAAe,EAAC,IAAI,CAAC,EAAE,MAAM,CAAC,CAAC;AACjD,CAAC;AAKM,KAAK,UAAU,cAAc,CACnC,IAAoB,EACpB,OAAe,CAAC,EAChB,WAAmB,GAAG;IAEtB,MAAM,KAAK,GAAG,IAAA,gBAAY,GAAE,CAAC,eAAe,EAAE,CAAC,WAAoB,CAAC;IACpE,MAAM,OAAO,GAAG,IAAA,sBAAe,EAAC,IAAI,CAAC,CAAC;IACtC,MAAM,KAAK,GAAG,CAAC,IAAI,GAAG,CAAC,CAAC,GAAG,QAAQ,CAAC;IACpC,MAAM,GAAG,GAAG,KAAK,GAAG,QAAQ,GAAG,CAAC,CAAC;IACjC,OAAO,MAAM,KAAK,CAAC,MAAM,CAAC,OAAO,EAAE,KAAK,EAAE,GAAG,CAAC,CAAC;AAChD,CAAC","sourcesContent":["import { getLibraries } from '../../..';\nimport { AuthEntityType } from '../../auth';\nimport { kOnlineEntities } from './keys';\nimport type { Redis } from 'ioredis';\n\n/**\n * Add or update a user as online in the type-based ZSET.\n */\nexport async function setUserOnline(userId: string, type: AuthEntityType, timestamp: number = Date.now()) {\n\tconst redis = getLibraries().getRedisService().redisClient as Redis;\n\tawait redis.zadd(kOnlineEntities(type), timestamp, userId);\n}\n\n/**\n * Remove a user from the type-based online ZSET (on disconnect).\n */\nexport async function setUserOffline(userId: string, type: AuthEntityType) {\n\tconst redis = getLibraries().getRedisService().redisClient as Redis;\n\tawait redis.zrem(kOnlineEntities(type), userId);\n}\n\n/**\n * Paginate online users for a given entity type (deep pagination, scalable).\n */\nexport async function getOnlineUsers(\n\ttype: AuthEntityType,\n\tpage: number = 1,\n\tpageSize: number = 100\n): Promise<string[]> {\n\tconst redis = getLibraries().getRedisService().redisClient as Redis;\n\tconst zsetKey = kOnlineEntities(type);\n\tconst start = (page - 1) * pageSize;\n\tconst end = start + pageSize - 1;\n\treturn await redis.zrange(zsetKey, start, end);\n}\n/**\n * Example usage:\n *\n * import { getConnectedEntityByType } from './type-queries';\n *\n * // For entity type 'user', get page 2, 100 per page:\n * const users = await getConnectedEntityByType('user', 2, 100);\n */\n"]}
@@ -0,0 +1,2 @@
1
+ import type { Redis } from 'ioredis';
2
+ export declare function scanKeys(redis: Redis, pattern: string): Promise<string[]>;
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.scanKeys = scanKeys;
4
+ async function scanKeys(redis, pattern) {
5
+ const keys = [];
6
+ let cursor = '0';
7
+ do {
8
+ const [newCursor, foundKeys] = await redis.scan(cursor, 'MATCH', pattern, 'COUNT', 100);
9
+ cursor = newCursor;
10
+ keys.push(...foundKeys);
11
+ } while (cursor !== '0');
12
+ return keys;
13
+ }
14
+ //# sourceMappingURL=redis-helpers.js.map