@open-core/framework 1.0.1-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (275) hide show
  1. package/LICENSE +373 -0
  2. package/README.md +350 -0
  3. package/dist/client/client-bootstrap.d.ts +1 -0
  4. package/dist/client/client-bootstrap.js +53 -0
  5. package/dist/client/client-container.d.ts +2 -0
  6. package/dist/client/client-container.js +6 -0
  7. package/dist/client/client-core.d.ts +18 -0
  8. package/dist/client/client-core.js +52 -0
  9. package/dist/client/decorators/controller.d.ts +3 -0
  10. package/dist/client/decorators/controller.js +14 -0
  11. package/dist/client/decorators/export.d.ts +7 -0
  12. package/dist/client/decorators/export.js +15 -0
  13. package/dist/client/decorators/gameEvent.d.ts +47 -0
  14. package/dist/client/decorators/gameEvent.js +54 -0
  15. package/dist/client/decorators/index.d.ts +10 -0
  16. package/dist/client/decorators/index.js +26 -0
  17. package/dist/client/decorators/interval.d.ts +7 -0
  18. package/dist/client/decorators/interval.js +15 -0
  19. package/dist/client/decorators/key.d.ts +2 -0
  20. package/dist/client/decorators/key.js +10 -0
  21. package/dist/client/decorators/localEvent.d.ts +7 -0
  22. package/dist/client/decorators/localEvent.js +15 -0
  23. package/dist/client/decorators/nui.d.ts +1 -0
  24. package/dist/client/decorators/nui.js +9 -0
  25. package/dist/client/decorators/onNet.d.ts +1 -0
  26. package/dist/client/decorators/onNet.js +9 -0
  27. package/dist/client/decorators/resourceLifecycle.d.ts +11 -0
  28. package/dist/client/decorators/resourceLifecycle.js +24 -0
  29. package/dist/client/decorators/tick.d.ts +1 -0
  30. package/dist/client/decorators/tick.js +9 -0
  31. package/dist/client/index.d.ts +6 -0
  32. package/dist/client/index.js +22 -0
  33. package/dist/client/loaders/exports.loader.d.ts +1 -0
  34. package/dist/client/loaders/exports.loader.js +13 -0
  35. package/dist/client/player/player.d.ts +262 -0
  36. package/dist/client/player/player.js +480 -0
  37. package/dist/client/player/player.loader.d.ts +1 -0
  38. package/dist/client/player/player.loader.js +22 -0
  39. package/dist/client/services/core/index.d.ts +1 -0
  40. package/dist/client/services/core/index.js +17 -0
  41. package/dist/client/services/core/spawn.service.d.ts +20 -0
  42. package/dist/client/services/core/spawn.service.js +143 -0
  43. package/dist/client/services/index.d.ts +4 -0
  44. package/dist/client/services/index.js +24 -0
  45. package/dist/client/services/streaming/index.d.ts +1 -0
  46. package/dist/client/services/streaming/index.js +17 -0
  47. package/dist/client/services/streaming/streaming.service.d.ts +165 -0
  48. package/dist/client/services/streaming/streaming.service.js +341 -0
  49. package/dist/client/services/ui/index.d.ts +3 -0
  50. package/dist/client/services/ui/index.js +19 -0
  51. package/dist/client/services/ui/notification.service.d.ts +76 -0
  52. package/dist/client/services/ui/notification.service.js +111 -0
  53. package/dist/client/services/ui/progress.service.d.ts +82 -0
  54. package/dist/client/services/ui/progress.service.js +210 -0
  55. package/dist/client/services/ui/textui.service.d.ts +82 -0
  56. package/dist/client/services/ui/textui.service.js +156 -0
  57. package/dist/client/services/world/blip.service.d.ts +112 -0
  58. package/dist/client/services/world/blip.service.js +215 -0
  59. package/dist/client/services/world/index.d.ts +4 -0
  60. package/dist/client/services/world/index.js +20 -0
  61. package/dist/client/services/world/marker.service.d.ts +94 -0
  62. package/dist/client/services/world/marker.service.js +153 -0
  63. package/dist/client/services/world/ped.service.d.ts +182 -0
  64. package/dist/client/services/world/ped.service.js +302 -0
  65. package/dist/client/services/world/vehicle.service.d.ts +168 -0
  66. package/dist/client/services/world/vehicle.service.js +296 -0
  67. package/dist/client/system/metadata-client.keys.d.ts +13 -0
  68. package/dist/client/system/metadata-client.keys.js +16 -0
  69. package/dist/client/system/processors/export.processor.d.ts +7 -0
  70. package/dist/client/system/processors/export.processor.js +39 -0
  71. package/dist/client/system/processors/gameEvent.processor.d.ts +10 -0
  72. package/dist/client/system/processors/gameEvent.processor.js +58 -0
  73. package/dist/client/system/processors/interval.processor.d.ts +7 -0
  74. package/dist/client/system/processors/interval.processor.js +43 -0
  75. package/dist/client/system/processors/key.processor.d.ts +8 -0
  76. package/dist/client/system/processors/key.processor.js +27 -0
  77. package/dist/client/system/processors/localEvent.processor.d.ts +7 -0
  78. package/dist/client/system/processors/localEvent.processor.js +38 -0
  79. package/dist/client/system/processors/netEvent.processor.d.ts +7 -0
  80. package/dist/client/system/processors/netEvent.processor.js +38 -0
  81. package/dist/client/system/processors/nui.processor.d.ts +7 -0
  82. package/dist/client/system/processors/nui.processor.js +40 -0
  83. package/dist/client/system/processors/resourceLifecycle.processor.d.ts +9 -0
  84. package/dist/client/system/processors/resourceLifecycle.processor.js +69 -0
  85. package/dist/client/system/processors/tick.processor.d.ts +5 -0
  86. package/dist/client/system/processors/tick.processor.js +37 -0
  87. package/dist/client/system/processors.register.d.ts +1 -0
  88. package/dist/client/system/processors.register.js +27 -0
  89. package/dist/client/types/game-events.d.ts +126 -0
  90. package/dist/client/types/game-events.js +83 -0
  91. package/dist/client/types/index.d.ts +1 -0
  92. package/dist/client/types/index.js +17 -0
  93. package/dist/client/ui-bridge.d.ts +116 -0
  94. package/dist/client/ui-bridge.js +201 -0
  95. package/dist/index.d.ts +7 -0
  96. package/dist/index.js +46 -0
  97. package/dist/server/bootstrap.d.ts +16 -0
  98. package/dist/server/bootstrap.js +57 -0
  99. package/dist/server/bus/core-event-bus.d.ts +6 -0
  100. package/dist/server/bus/core-event-bus.js +31 -0
  101. package/dist/server/configs/api.config.d.ts +71 -0
  102. package/dist/server/configs/api.config.js +81 -0
  103. package/dist/server/configs/config.base.d.ts +63 -0
  104. package/dist/server/configs/config.base.js +64 -0
  105. package/dist/server/configs/index.d.ts +2 -0
  106. package/dist/server/configs/index.js +18 -0
  107. package/dist/server/container.d.ts +2 -0
  108. package/dist/server/container.js +6 -0
  109. package/dist/server/controllers/chat.controller.d.ts +10 -0
  110. package/dist/server/controllers/chat.controller.js +50 -0
  111. package/dist/server/controllers/command.controller.d.ts +7 -0
  112. package/dist/server/controllers/command.controller.js +47 -0
  113. package/dist/server/core.d.ts +1 -0
  114. package/dist/server/core.js +7 -0
  115. package/dist/server/database/adapters/oxmysql.adapter.d.ts +89 -0
  116. package/dist/server/database/adapters/oxmysql.adapter.js +149 -0
  117. package/dist/server/database/database.contract.d.ts +128 -0
  118. package/dist/server/database/database.contract.js +29 -0
  119. package/dist/server/database/database.service.d.ts +216 -0
  120. package/dist/server/database/database.service.js +301 -0
  121. package/dist/server/database/index.d.ts +53 -0
  122. package/dist/server/database/index.js +70 -0
  123. package/dist/server/database/types.d.ts +67 -0
  124. package/dist/server/database/types.js +7 -0
  125. package/dist/server/database.d.ts +7 -0
  126. package/dist/server/database.js +23 -0
  127. package/dist/server/decorators/bind.d.ts +2 -0
  128. package/dist/server/decorators/bind.js +15 -0
  129. package/dist/server/decorators/command.d.ts +19 -0
  130. package/dist/server/decorators/command.js +18 -0
  131. package/dist/server/decorators/controller.d.ts +3 -0
  132. package/dist/server/decorators/controller.js +14 -0
  133. package/dist/server/decorators/coreEvent.d.ts +2 -0
  134. package/dist/server/decorators/coreEvent.js +9 -0
  135. package/dist/server/decorators/export.d.ts +1 -0
  136. package/dist/server/decorators/export.js +9 -0
  137. package/dist/server/decorators/guard.d.ts +5 -0
  138. package/dist/server/decorators/guard.js +39 -0
  139. package/dist/server/decorators/index.d.ts +10 -0
  140. package/dist/server/decorators/index.js +26 -0
  141. package/dist/server/decorators/netEvent.d.ts +36 -0
  142. package/dist/server/decorators/netEvent.js +40 -0
  143. package/dist/server/decorators/onTick.d.ts +1 -0
  144. package/dist/server/decorators/onTick.js +9 -0
  145. package/dist/server/decorators/public.d.ts +16 -0
  146. package/dist/server/decorators/public.js +25 -0
  147. package/dist/server/decorators/requiresState.d.ts +55 -0
  148. package/dist/server/decorators/requiresState.js +62 -0
  149. package/dist/server/decorators/throttle.d.ts +9 -0
  150. package/dist/server/decorators/throttle.js +36 -0
  151. package/dist/server/decorators/utils.d.ts +7 -0
  152. package/dist/server/decorators/utils.js +13 -0
  153. package/dist/server/entities/index.d.ts +1 -0
  154. package/dist/server/entities/index.js +17 -0
  155. package/dist/server/entities/player.d.ts +157 -0
  156. package/dist/server/entities/player.js +217 -0
  157. package/dist/server/error-handler.d.ts +2 -0
  158. package/dist/server/error-handler.js +43 -0
  159. package/dist/server/index.d.ts +10 -0
  160. package/dist/server/index.js +29 -0
  161. package/dist/server/loaders/exports.loader.d.ts +0 -0
  162. package/dist/server/loaders/exports.loader.js +23 -0
  163. package/dist/server/loaders/playerSession.loader.d.ts +1 -0
  164. package/dist/server/loaders/playerSession.loader.js +42 -0
  165. package/dist/server/services/access-control.service.d.ts +56 -0
  166. package/dist/server/services/access-control.service.js +99 -0
  167. package/dist/server/services/chat.service.d.ts +7 -0
  168. package/dist/server/services/chat.service.js +31 -0
  169. package/dist/server/services/command.service.d.ts +15 -0
  170. package/dist/server/services/command.service.js +74 -0
  171. package/dist/server/services/config.service.d.ts +75 -0
  172. package/dist/server/services/config.service.js +116 -0
  173. package/dist/server/services/default/default-security.handler.d.ts +6 -0
  174. package/dist/server/services/default/default-security.handler.js +26 -0
  175. package/dist/server/services/http/http.service.d.ts +50 -0
  176. package/dist/server/services/http/http.service.js +126 -0
  177. package/dist/server/services/index.d.ts +10 -0
  178. package/dist/server/services/index.js +26 -0
  179. package/dist/server/services/parallel/index.d.ts +49 -0
  180. package/dist/server/services/parallel/index.js +67 -0
  181. package/dist/server/services/parallel/parallel-compute.service.d.ts +132 -0
  182. package/dist/server/services/parallel/parallel-compute.service.js +449 -0
  183. package/dist/server/services/parallel/types.d.ts +188 -0
  184. package/dist/server/services/parallel/types.js +7 -0
  185. package/dist/server/services/parallel/worker-pool.d.ts +83 -0
  186. package/dist/server/services/parallel/worker-pool.js +350 -0
  187. package/dist/server/services/parallel/worker.d.ts +19 -0
  188. package/dist/server/services/parallel/worker.js +49 -0
  189. package/dist/server/services/persistence.service.d.ts +59 -0
  190. package/dist/server/services/persistence.service.js +166 -0
  191. package/dist/server/services/player.service.d.ts +96 -0
  192. package/dist/server/services/player.service.js +132 -0
  193. package/dist/server/services/rate-limiter.service.d.ts +5 -0
  194. package/dist/server/services/rate-limiter.service.js +39 -0
  195. package/dist/server/services/registers.d.ts +1 -0
  196. package/dist/server/services/registers.js +18 -0
  197. package/dist/server/setup.d.ts +9 -0
  198. package/dist/server/setup.js +28 -0
  199. package/dist/server/system/metadata-server.keys.d.ts +9 -0
  200. package/dist/server/system/metadata-server.keys.js +12 -0
  201. package/dist/server/system/processors/command.processor.d.ts +9 -0
  202. package/dist/server/system/processors/command.processor.js +31 -0
  203. package/dist/server/system/processors/coreEvent.processor.d.ts +7 -0
  204. package/dist/server/system/processors/coreEvent.processor.js +38 -0
  205. package/dist/server/system/processors/export.processor.d.ts +7 -0
  206. package/dist/server/system/processors/export.processor.js +26 -0
  207. package/dist/server/system/processors/netEvent.processor.d.ts +11 -0
  208. package/dist/server/system/processors/netEvent.processor.js +100 -0
  209. package/dist/server/system/processors/tick.processor.d.ts +5 -0
  210. package/dist/server/system/processors/tick.processor.js +36 -0
  211. package/dist/server/system/processors.register.d.ts +1 -0
  212. package/dist/server/system/processors.register.js +21 -0
  213. package/dist/server/templates/admin/admin.controller-template.d.ts +10 -0
  214. package/dist/server/templates/admin/admin.controller-template.js +2 -0
  215. package/dist/server/templates/auth/auth-provider.contract.d.ts +58 -0
  216. package/dist/server/templates/auth/auth-provider.contract.js +23 -0
  217. package/dist/server/templates/index.d.ts +8 -0
  218. package/dist/server/templates/index.js +21 -0
  219. package/dist/server/templates/persistence/index.d.ts +30 -0
  220. package/dist/server/templates/persistence/index.js +34 -0
  221. package/dist/server/templates/persistence/player-persistence.contract.d.ts +86 -0
  222. package/dist/server/templates/persistence/player-persistence.contract.js +52 -0
  223. package/dist/server/templates/repository/index.d.ts +57 -0
  224. package/dist/server/templates/repository/index.js +61 -0
  225. package/dist/server/templates/repository/repository.contract.d.ts +224 -0
  226. package/dist/server/templates/repository/repository.contract.js +342 -0
  227. package/dist/server/templates/repository/repository.types.d.ts +51 -0
  228. package/dist/server/templates/repository/repository.types.js +7 -0
  229. package/dist/server/templates/security/permission.types.d.ts +32 -0
  230. package/dist/server/templates/security/permission.types.js +2 -0
  231. package/dist/server/templates/security/principal-provider.contract.d.ts +43 -0
  232. package/dist/server/templates/security/principal-provider.contract.js +19 -0
  233. package/dist/server/templates/security/security-handler.contract.d.ts +5 -0
  234. package/dist/server/templates/security/security-handler.contract.js +6 -0
  235. package/dist/server/types/core-events.d.ts +17 -0
  236. package/dist/server/types/core-events.js +2 -0
  237. package/dist/server/types/security.types.d.ts +7 -0
  238. package/dist/server/types/security.types.js +2 -0
  239. package/dist/shared/index.d.ts +1 -0
  240. package/dist/shared/index.js +17 -0
  241. package/dist/shared/logger/core-logger.d.ts +35 -0
  242. package/dist/shared/logger/core-logger.js +52 -0
  243. package/dist/shared/logger/index.d.ts +11 -0
  244. package/dist/shared/logger/index.js +26 -0
  245. package/dist/shared/logger/logger.config.d.ts +47 -0
  246. package/dist/shared/logger/logger.config.js +33 -0
  247. package/dist/shared/logger/logger.service.d.ts +161 -0
  248. package/dist/shared/logger/logger.service.js +279 -0
  249. package/dist/shared/logger/logger.types.d.ts +85 -0
  250. package/dist/shared/logger/logger.types.js +74 -0
  251. package/dist/shared/logger/transports/buffered.transport.d.ts +88 -0
  252. package/dist/shared/logger/transports/buffered.transport.js +174 -0
  253. package/dist/shared/logger/transports/console.transport.d.ts +37 -0
  254. package/dist/shared/logger/transports/console.transport.js +134 -0
  255. package/dist/shared/logger/transports/index.d.ts +3 -0
  256. package/dist/shared/logger/transports/index.js +19 -0
  257. package/dist/shared/logger/transports/transport.interface.d.ts +40 -0
  258. package/dist/shared/logger/transports/transport.interface.js +2 -0
  259. package/dist/system/class-constructor.d.ts +1 -0
  260. package/dist/system/class-constructor.js +2 -0
  261. package/dist/system/decorator-processor.d.ts +4 -0
  262. package/dist/system/decorator-processor.js +2 -0
  263. package/dist/system/metadata.scanner.d.ts +7 -0
  264. package/dist/system/metadata.scanner.js +45 -0
  265. package/dist/utils/errors.d.ts +14 -0
  266. package/dist/utils/errors.js +25 -0
  267. package/dist/utils/index.d.ts +4 -0
  268. package/dist/utils/index.js +20 -0
  269. package/dist/utils/result.d.ts +12 -0
  270. package/dist/utils/result.js +10 -0
  271. package/dist/utils/rgb.d.ts +5 -0
  272. package/dist/utils/rgb.js +2 -0
  273. package/dist/utils/vector3.d.ts +13 -0
  274. package/dist/utils/vector3.js +27 -0
  275. package/package.json +70 -0
@@ -0,0 +1,49 @@
1
+ /**
2
+ * ParallelCompute Module
3
+ *
4
+ * Provides parallel computation capabilities using worker threads.
5
+ *
6
+ * @example
7
+ * ```typescript
8
+ * import {
9
+ * initParallelCompute,
10
+ * defineTask,
11
+ * filterByDistance,
12
+ * } from '@open-core/framework/server'
13
+ *
14
+ * // Initialize the worker pool (call once at startup)
15
+ * initParallelCompute({ maxWorkers: 4 })
16
+ *
17
+ * // Use built-in tasks
18
+ * const nearby = await filterByDistance.run({
19
+ * entities: allEntities,
20
+ * position: player.coords,
21
+ * radius: 100,
22
+ * })
23
+ *
24
+ * // Define custom tasks
25
+ * const processPlayers = defineTask({
26
+ * name: 'processPlayers',
27
+ * estimateCost: (input) => input.length * 10,
28
+ * workerThreshold: 500,
29
+ * compute: (players) => players.map(p => ({
30
+ * ...p,
31
+ * processed: true,
32
+ * })),
33
+ * })
34
+ *
35
+ * // Run with automatic mode selection
36
+ * const result = await processPlayers.run(players)
37
+ *
38
+ * // Force sync execution
39
+ * const resultSync = processPlayers.sync(players)
40
+ *
41
+ * // Force parallel execution
42
+ * const resultParallel = await processPlayers.parallel(players)
43
+ * ```
44
+ */
45
+ export type { ExecutionMode, WorkerPoolConfig, ParallelTaskOptions, ParallelTask, ParallelComputeMetrics, TaskResult, WorkerInfo, WorkerStatus, } from './types';
46
+ export { ParallelComputeService } from './parallel-compute.service';
47
+ export { getParallelComputeService, initParallelCompute, shutdownParallelCompute, defineTask, } from './parallel-compute.service';
48
+ export { filterByDistance, sortByDistance, findClosest, defineBatchTransform, defineBatchFilter, defineBatchReduce, type Vector3Like, } from './parallel-compute.service';
49
+ export { WorkerPool } from './worker-pool';
@@ -0,0 +1,67 @@
1
+ "use strict";
2
+ /**
3
+ * ParallelCompute Module
4
+ *
5
+ * Provides parallel computation capabilities using worker threads.
6
+ *
7
+ * @example
8
+ * ```typescript
9
+ * import {
10
+ * initParallelCompute,
11
+ * defineTask,
12
+ * filterByDistance,
13
+ * } from '@open-core/framework/server'
14
+ *
15
+ * // Initialize the worker pool (call once at startup)
16
+ * initParallelCompute({ maxWorkers: 4 })
17
+ *
18
+ * // Use built-in tasks
19
+ * const nearby = await filterByDistance.run({
20
+ * entities: allEntities,
21
+ * position: player.coords,
22
+ * radius: 100,
23
+ * })
24
+ *
25
+ * // Define custom tasks
26
+ * const processPlayers = defineTask({
27
+ * name: 'processPlayers',
28
+ * estimateCost: (input) => input.length * 10,
29
+ * workerThreshold: 500,
30
+ * compute: (players) => players.map(p => ({
31
+ * ...p,
32
+ * processed: true,
33
+ * })),
34
+ * })
35
+ *
36
+ * // Run with automatic mode selection
37
+ * const result = await processPlayers.run(players)
38
+ *
39
+ * // Force sync execution
40
+ * const resultSync = processPlayers.sync(players)
41
+ *
42
+ * // Force parallel execution
43
+ * const resultParallel = await processPlayers.parallel(players)
44
+ * ```
45
+ */
46
+ Object.defineProperty(exports, "__esModule", { value: true });
47
+ exports.WorkerPool = exports.defineBatchReduce = exports.defineBatchFilter = exports.defineBatchTransform = exports.findClosest = exports.sortByDistance = exports.filterByDistance = exports.defineTask = exports.shutdownParallelCompute = exports.initParallelCompute = exports.getParallelComputeService = exports.ParallelComputeService = void 0;
48
+ // Service
49
+ var parallel_compute_service_1 = require("./parallel-compute.service");
50
+ Object.defineProperty(exports, "ParallelComputeService", { enumerable: true, get: function () { return parallel_compute_service_1.ParallelComputeService; } });
51
+ // Standalone functions
52
+ var parallel_compute_service_2 = require("./parallel-compute.service");
53
+ Object.defineProperty(exports, "getParallelComputeService", { enumerable: true, get: function () { return parallel_compute_service_2.getParallelComputeService; } });
54
+ Object.defineProperty(exports, "initParallelCompute", { enumerable: true, get: function () { return parallel_compute_service_2.initParallelCompute; } });
55
+ Object.defineProperty(exports, "shutdownParallelCompute", { enumerable: true, get: function () { return parallel_compute_service_2.shutdownParallelCompute; } });
56
+ Object.defineProperty(exports, "defineTask", { enumerable: true, get: function () { return parallel_compute_service_2.defineTask; } });
57
+ // Built-in tasks
58
+ var parallel_compute_service_3 = require("./parallel-compute.service");
59
+ Object.defineProperty(exports, "filterByDistance", { enumerable: true, get: function () { return parallel_compute_service_3.filterByDistance; } });
60
+ Object.defineProperty(exports, "sortByDistance", { enumerable: true, get: function () { return parallel_compute_service_3.sortByDistance; } });
61
+ Object.defineProperty(exports, "findClosest", { enumerable: true, get: function () { return parallel_compute_service_3.findClosest; } });
62
+ Object.defineProperty(exports, "defineBatchTransform", { enumerable: true, get: function () { return parallel_compute_service_3.defineBatchTransform; } });
63
+ Object.defineProperty(exports, "defineBatchFilter", { enumerable: true, get: function () { return parallel_compute_service_3.defineBatchFilter; } });
64
+ Object.defineProperty(exports, "defineBatchReduce", { enumerable: true, get: function () { return parallel_compute_service_3.defineBatchReduce; } });
65
+ // Worker pool (for advanced usage)
66
+ var worker_pool_1 = require("./worker-pool");
67
+ Object.defineProperty(exports, "WorkerPool", { enumerable: true, get: function () { return worker_pool_1.WorkerPool; } });
@@ -0,0 +1,132 @@
1
+ /**
2
+ * ParallelCompute Service
3
+ *
4
+ * Provides an ergonomic API for parallel computation.
5
+ * Uses virtual workers in FiveM environment, with async execution
6
+ * that yields to the event loop for better performance.
7
+ *
8
+ * Automatically decides whether to run synchronously or asynchronously
9
+ * based on estimated computational cost.
10
+ */
11
+ import type { ParallelTaskOptions, ParallelTask, WorkerPoolConfig, ParallelComputeMetrics, TaskResult } from './types';
12
+ /**
13
+ * Service for managing parallel computation
14
+ */
15
+ export declare class ParallelComputeService {
16
+ private pool;
17
+ private metrics;
18
+ private totalExecutionTime;
19
+ private isInitialized;
20
+ private poolConfig;
21
+ /**
22
+ * Initialize the worker pool
23
+ * Must be called before using parallel execution
24
+ */
25
+ initialize(config?: Partial<WorkerPoolConfig>): void;
26
+ /**
27
+ * Check if initialized
28
+ */
29
+ get initialized(): boolean;
30
+ /**
31
+ * Check if using native workers
32
+ */
33
+ get isNative(): boolean;
34
+ /**
35
+ * Shutdown the service and worker pool
36
+ */
37
+ shutdown(): Promise<void>;
38
+ /**
39
+ * Get current metrics
40
+ */
41
+ getMetrics(): ParallelComputeMetrics;
42
+ /**
43
+ * Get worker pool statistics
44
+ */
45
+ getPoolStats(): {
46
+ totalWorkers: number;
47
+ idleWorkers: number;
48
+ busyWorkers: number;
49
+ queuedTasks: number;
50
+ isNative: boolean;
51
+ } | null;
52
+ /**
53
+ * Reset metrics
54
+ */
55
+ resetMetrics(): void;
56
+ /**
57
+ * Execute a compute function with automatic mode selection
58
+ */
59
+ run<TInput, TOutput>(options: ParallelTaskOptions<TInput, TOutput>, input: TInput): Promise<TaskResult<TOutput>>;
60
+ /**
61
+ * Execute synchronously on main thread
62
+ */
63
+ sync<TInput, TOutput>(options: ParallelTaskOptions<TInput, TOutput>, input: TInput): TaskResult<TOutput>;
64
+ /**
65
+ * Execute on worker (async with yielding in FiveM)
66
+ */
67
+ parallel<TInput, TOutput>(options: ParallelTaskOptions<TInput, TOutput>, input: TInput): Promise<TaskResult<TOutput>>;
68
+ /**
69
+ * Execute distributed across multiple workers
70
+ */
71
+ distributed<TInput, TOutput>(options: ParallelTaskOptions<TInput, TOutput>, input: TInput, workerCount?: number): Promise<TaskResult<TOutput>>;
72
+ /**
73
+ * Update internal metrics
74
+ */
75
+ private updateMetrics;
76
+ }
77
+ /**
78
+ * Get or create the global ParallelCompute service instance
79
+ */
80
+ export declare function getParallelComputeService(): ParallelComputeService;
81
+ /**
82
+ * Initialize the global ParallelCompute service
83
+ */
84
+ export declare function initParallelCompute(config?: Partial<WorkerPoolConfig>): void;
85
+ /**
86
+ * Shutdown the global ParallelCompute service
87
+ */
88
+ export declare function shutdownParallelCompute(): Promise<void>;
89
+ /**
90
+ * Define a parallel task with the given options
91
+ * Returns a task object with run, sync, parallel, and distributed methods
92
+ */
93
+ export declare function defineTask<TInput, TOutput>(options: ParallelTaskOptions<TInput, TOutput>): ParallelTask<TInput, TOutput>;
94
+ export interface Vector3Like {
95
+ x: number;
96
+ y: number;
97
+ z: number;
98
+ }
99
+ /**
100
+ * Built-in task: Filter entities by distance from a position
101
+ */
102
+ export declare const filterByDistance: ParallelTask<{
103
+ entities: Vector3Like[];
104
+ position: Vector3Like;
105
+ radius: number;
106
+ }, Vector3Like[]>;
107
+ /**
108
+ * Built-in task: Sort entities by distance from a position
109
+ */
110
+ export declare const sortByDistance: ParallelTask<{
111
+ entities: Vector3Like[];
112
+ position: Vector3Like;
113
+ }, Vector3Like[]>;
114
+ /**
115
+ * Built-in task: Find closest entity to a position
116
+ */
117
+ export declare const findClosest: ParallelTask<{
118
+ entities: Vector3Like[];
119
+ position: Vector3Like;
120
+ }, Vector3Like | null>;
121
+ /**
122
+ * Built-in task: Batch transform items
123
+ */
124
+ export declare function defineBatchTransform<T, R>(name: string, transform: (item: T) => R, threshold?: number): ParallelTask<T[], R[]>;
125
+ /**
126
+ * Built-in task: Batch filter items
127
+ */
128
+ export declare function defineBatchFilter<T>(name: string, predicate: (item: T) => boolean, threshold?: number): ParallelTask<T[], T[]>;
129
+ /**
130
+ * Built-in task: Batch reduce items
131
+ */
132
+ export declare function defineBatchReduce<T, R>(name: string, reducer: (acc: R, item: T) => R, initial: R, merger: (results: R[]) => R, threshold?: number): ParallelTask<T[], R>;
@@ -0,0 +1,449 @@
1
+ "use strict";
2
+ /**
3
+ * ParallelCompute Service
4
+ *
5
+ * Provides an ergonomic API for parallel computation.
6
+ * Uses virtual workers in FiveM environment, with async execution
7
+ * that yields to the event loop for better performance.
8
+ *
9
+ * Automatically decides whether to run synchronously or asynchronously
10
+ * based on estimated computational cost.
11
+ */
12
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
13
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
14
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
15
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
16
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
17
+ };
18
+ Object.defineProperty(exports, "__esModule", { value: true });
19
+ exports.findClosest = exports.sortByDistance = exports.filterByDistance = exports.ParallelComputeService = void 0;
20
+ exports.getParallelComputeService = getParallelComputeService;
21
+ exports.initParallelCompute = initParallelCompute;
22
+ exports.shutdownParallelCompute = shutdownParallelCompute;
23
+ exports.defineTask = defineTask;
24
+ exports.defineBatchTransform = defineBatchTransform;
25
+ exports.defineBatchFilter = defineBatchFilter;
26
+ exports.defineBatchReduce = defineBatchReduce;
27
+ const tsyringe_1 = require("tsyringe");
28
+ const uuid_1 = require("uuid");
29
+ const worker_pool_1 = require("./worker-pool");
30
+ const DEFAULT_WORKER_THRESHOLD = 10000;
31
+ /**
32
+ * Service for managing parallel computation
33
+ */
34
+ let ParallelComputeService = class ParallelComputeService {
35
+ constructor() {
36
+ this.pool = null;
37
+ this.metrics = {
38
+ totalTasks: 0,
39
+ syncTasks: 0,
40
+ parallelTasks: 0,
41
+ failedTasks: 0,
42
+ avgExecutionTime: 0,
43
+ estimatedTimeSaved: 0,
44
+ activeWorkers: 0,
45
+ peakWorkers: 0,
46
+ };
47
+ this.totalExecutionTime = 0;
48
+ this.isInitialized = false;
49
+ this.poolConfig = {};
50
+ }
51
+ /**
52
+ * Initialize the worker pool
53
+ * Must be called before using parallel execution
54
+ */
55
+ initialize(config = {}) {
56
+ if (this.isInitialized)
57
+ return;
58
+ this.poolConfig = config;
59
+ this.pool = new worker_pool_1.WorkerPool(config);
60
+ this.pool.on('taskCompleted', (data) => {
61
+ const { executionTime } = data;
62
+ this.updateMetrics(executionTime, 'parallel');
63
+ });
64
+ this.pool.on('workerSpawned', () => {
65
+ var _a;
66
+ const stats = (_a = this.pool) === null || _a === void 0 ? void 0 : _a.getStats();
67
+ if (stats) {
68
+ this.metrics.activeWorkers = stats.totalWorkers;
69
+ this.metrics.peakWorkers = Math.max(this.metrics.peakWorkers, stats.totalWorkers);
70
+ }
71
+ });
72
+ this.pool.on('workerExit', () => {
73
+ var _a;
74
+ const stats = (_a = this.pool) === null || _a === void 0 ? void 0 : _a.getStats();
75
+ if (stats) {
76
+ this.metrics.activeWorkers = stats.totalWorkers;
77
+ }
78
+ });
79
+ this.isInitialized = true;
80
+ }
81
+ /**
82
+ * Check if initialized
83
+ */
84
+ get initialized() {
85
+ return this.isInitialized;
86
+ }
87
+ /**
88
+ * Check if using native workers
89
+ */
90
+ get isNative() {
91
+ var _a, _b;
92
+ return (_b = (_a = this.pool) === null || _a === void 0 ? void 0 : _a.isNative) !== null && _b !== void 0 ? _b : false;
93
+ }
94
+ /**
95
+ * Shutdown the service and worker pool
96
+ */
97
+ async shutdown() {
98
+ if (this.pool) {
99
+ await this.pool.shutdown();
100
+ this.pool = null;
101
+ }
102
+ this.isInitialized = false;
103
+ }
104
+ /**
105
+ * Get current metrics
106
+ */
107
+ getMetrics() {
108
+ return Object.assign({}, this.metrics);
109
+ }
110
+ /**
111
+ * Get worker pool statistics
112
+ */
113
+ getPoolStats() {
114
+ var _a, _b;
115
+ return (_b = (_a = this.pool) === null || _a === void 0 ? void 0 : _a.getStats()) !== null && _b !== void 0 ? _b : null;
116
+ }
117
+ /**
118
+ * Reset metrics
119
+ */
120
+ resetMetrics() {
121
+ var _a, _b;
122
+ this.metrics = {
123
+ totalTasks: 0,
124
+ syncTasks: 0,
125
+ parallelTasks: 0,
126
+ failedTasks: 0,
127
+ avgExecutionTime: 0,
128
+ estimatedTimeSaved: 0,
129
+ activeWorkers: (_b = (_a = this.pool) === null || _a === void 0 ? void 0 : _a.getStats().totalWorkers) !== null && _b !== void 0 ? _b : 0,
130
+ peakWorkers: 0,
131
+ };
132
+ this.totalExecutionTime = 0;
133
+ }
134
+ /**
135
+ * Execute a compute function with automatic mode selection
136
+ */
137
+ async run(options, input) {
138
+ var _a, _b, _c;
139
+ const cost = (_b = (_a = options.estimateCost) === null || _a === void 0 ? void 0 : _a.call(options, input)) !== null && _b !== void 0 ? _b : 0;
140
+ const threshold = (_c = options.workerThreshold) !== null && _c !== void 0 ? _c : DEFAULT_WORKER_THRESHOLD;
141
+ if (cost > threshold && this.pool) {
142
+ return this.parallel(options, input);
143
+ }
144
+ return this.sync(options, input);
145
+ }
146
+ /**
147
+ * Execute synchronously on main thread
148
+ */
149
+ sync(options, input) {
150
+ const startTime = performance.now();
151
+ try {
152
+ const result = options.compute(input);
153
+ const executionTime = performance.now() - startTime;
154
+ this.updateMetrics(executionTime, 'sync');
155
+ return {
156
+ result,
157
+ executionTime,
158
+ mode: 'sync',
159
+ };
160
+ }
161
+ catch (error) {
162
+ this.metrics.failedTasks++;
163
+ throw error;
164
+ }
165
+ }
166
+ /**
167
+ * Execute on worker (async with yielding in FiveM)
168
+ */
169
+ async parallel(options, input) {
170
+ if (!this.pool) {
171
+ // Fallback to sync if pool not initialized
172
+ return this.sync(options, input);
173
+ }
174
+ const startTime = performance.now();
175
+ try {
176
+ const message = {
177
+ id: (0, uuid_1.v4)(),
178
+ taskName: options.name,
179
+ functionBody: options.compute.toString(),
180
+ input,
181
+ };
182
+ const result = (await this.pool.execute(message));
183
+ const executionTime = performance.now() - startTime;
184
+ return {
185
+ result,
186
+ executionTime,
187
+ mode: 'parallel',
188
+ };
189
+ }
190
+ catch (error) {
191
+ this.metrics.failedTasks++;
192
+ throw error;
193
+ }
194
+ }
195
+ /**
196
+ * Execute distributed across multiple workers
197
+ */
198
+ async distributed(options, input, workerCount) {
199
+ var _a;
200
+ if (!options.chunker || !options.merger) {
201
+ throw new Error('Distributed execution requires chunker and merger functions');
202
+ }
203
+ if (!this.pool) {
204
+ // Fallback to sync if pool not initialized
205
+ return this.sync(options, input);
206
+ }
207
+ const startTime = performance.now();
208
+ const actualWorkerCount = (_a = workerCount !== null && workerCount !== void 0 ? workerCount : this.poolConfig.maxWorkers) !== null && _a !== void 0 ? _a : 4;
209
+ try {
210
+ const chunks = options.chunker(input, actualWorkerCount);
211
+ const results = await Promise.all(chunks.map(async (chunk) => {
212
+ const message = {
213
+ id: (0, uuid_1.v4)(),
214
+ taskName: options.name,
215
+ functionBody: options.compute.toString(),
216
+ input: chunk,
217
+ };
218
+ return this.pool.execute(message);
219
+ }));
220
+ const mergedResult = options.merger(results);
221
+ const executionTime = performance.now() - startTime;
222
+ this.updateMetrics(executionTime, 'distributed');
223
+ return {
224
+ result: mergedResult,
225
+ executionTime,
226
+ mode: 'distributed',
227
+ workerCount: chunks.length,
228
+ };
229
+ }
230
+ catch (error) {
231
+ this.metrics.failedTasks++;
232
+ throw error;
233
+ }
234
+ }
235
+ /**
236
+ * Update internal metrics
237
+ */
238
+ updateMetrics(executionTime, mode) {
239
+ this.metrics.totalTasks++;
240
+ this.totalExecutionTime += executionTime;
241
+ this.metrics.avgExecutionTime = this.totalExecutionTime / this.metrics.totalTasks;
242
+ if (mode === 'sync') {
243
+ this.metrics.syncTasks++;
244
+ }
245
+ else {
246
+ this.metrics.parallelTasks++;
247
+ }
248
+ }
249
+ };
250
+ exports.ParallelComputeService = ParallelComputeService;
251
+ exports.ParallelComputeService = ParallelComputeService = __decorate([
252
+ (0, tsyringe_1.injectable)()
253
+ ], ParallelComputeService);
254
+ // ─────────────────────────────────────────────────────────────────────────────
255
+ // Standalone Functions (no DI required)
256
+ // ─────────────────────────────────────────────────────────────────────────────
257
+ let globalService = null;
258
+ /**
259
+ * Get or create the global ParallelCompute service instance
260
+ */
261
+ function getParallelComputeService() {
262
+ if (!globalService) {
263
+ globalService = new ParallelComputeService();
264
+ }
265
+ return globalService;
266
+ }
267
+ /**
268
+ * Initialize the global ParallelCompute service
269
+ */
270
+ function initParallelCompute(config = {}) {
271
+ const service = getParallelComputeService();
272
+ service.initialize(config);
273
+ }
274
+ /**
275
+ * Shutdown the global ParallelCompute service
276
+ */
277
+ async function shutdownParallelCompute() {
278
+ if (globalService) {
279
+ await globalService.shutdown();
280
+ globalService = null;
281
+ }
282
+ }
283
+ /**
284
+ * Define a parallel task with the given options
285
+ * Returns a task object with run, sync, parallel, and distributed methods
286
+ */
287
+ function defineTask(options) {
288
+ const service = getParallelComputeService();
289
+ return {
290
+ name: options.name,
291
+ options,
292
+ async run(input) {
293
+ const result = await service.run(options, input);
294
+ return result.result;
295
+ },
296
+ sync(input) {
297
+ const result = service.sync(options, input);
298
+ return result.result;
299
+ },
300
+ async parallel(input) {
301
+ const result = await service.parallel(options, input);
302
+ return result.result;
303
+ },
304
+ async distributed(input, workerCount) {
305
+ const result = await service.distributed(options, input, workerCount);
306
+ return result.result;
307
+ },
308
+ };
309
+ }
310
+ /**
311
+ * Built-in task: Filter entities by distance from a position
312
+ */
313
+ exports.filterByDistance = defineTask({
314
+ name: 'filterByDistance',
315
+ estimateCost: (input) => input.entities.length,
316
+ workerThreshold: 1000,
317
+ compute: (input) => {
318
+ const { entities, position, radius } = input;
319
+ const radiusSquared = radius * radius;
320
+ return entities.filter((entity) => {
321
+ const dx = entity.x - position.x;
322
+ const dy = entity.y - position.y;
323
+ const dz = entity.z - position.z;
324
+ return dx * dx + dy * dy + dz * dz <= radiusSquared;
325
+ });
326
+ },
327
+ chunker: (input, workerCount) => {
328
+ const { entities, position, radius } = input;
329
+ const chunkSize = Math.ceil(entities.length / workerCount);
330
+ const chunks = [];
331
+ for (let i = 0; i < entities.length; i += chunkSize) {
332
+ chunks.push({
333
+ entities: entities.slice(i, i + chunkSize),
334
+ position,
335
+ radius,
336
+ });
337
+ }
338
+ return chunks;
339
+ },
340
+ merger: (results) => [].concat(...results),
341
+ });
342
+ /**
343
+ * Built-in task: Sort entities by distance from a position
344
+ */
345
+ exports.sortByDistance = defineTask({
346
+ name: 'sortByDistance',
347
+ estimateCost: (input) => input.entities.length * Math.log(input.entities.length),
348
+ workerThreshold: 500,
349
+ compute: (input) => {
350
+ const { entities, position } = input;
351
+ return [...entities].sort((a, b) => {
352
+ const dxA = a.x - position.x;
353
+ const dyA = a.y - position.y;
354
+ const dzA = a.z - position.z;
355
+ const distA = dxA * dxA + dyA * dyA + dzA * dzA;
356
+ const dxB = b.x - position.x;
357
+ const dyB = b.y - position.y;
358
+ const dzB = b.z - position.z;
359
+ const distB = dxB * dxB + dyB * dyB + dzB * dzB;
360
+ return distA - distB;
361
+ });
362
+ },
363
+ });
364
+ /**
365
+ * Built-in task: Find closest entity to a position
366
+ */
367
+ exports.findClosest = defineTask({
368
+ name: 'findClosest',
369
+ estimateCost: (input) => input.entities.length,
370
+ workerThreshold: 5000,
371
+ compute: (input) => {
372
+ const { entities, position } = input;
373
+ if (entities.length === 0)
374
+ return null;
375
+ let closest = entities[0];
376
+ let minDistSquared = Infinity;
377
+ for (const entity of entities) {
378
+ const dx = entity.x - position.x;
379
+ const dy = entity.y - position.y;
380
+ const dz = entity.z - position.z;
381
+ const distSquared = dx * dx + dy * dy + dz * dz;
382
+ if (distSquared < minDistSquared) {
383
+ minDistSquared = distSquared;
384
+ closest = entity;
385
+ }
386
+ }
387
+ return closest;
388
+ },
389
+ });
390
+ /**
391
+ * Built-in task: Batch transform items
392
+ */
393
+ function defineBatchTransform(name, transform, threshold = 1000) {
394
+ return defineTask({
395
+ name,
396
+ estimateCost: (input) => input.length,
397
+ workerThreshold: threshold,
398
+ compute: (input) => input.map(transform),
399
+ chunker: (input, workerCount) => {
400
+ const chunkSize = Math.ceil(input.length / workerCount);
401
+ const chunks = [];
402
+ for (let i = 0; i < input.length; i += chunkSize) {
403
+ chunks.push(input.slice(i, i + chunkSize));
404
+ }
405
+ return chunks;
406
+ },
407
+ merger: (results) => [].concat(...results),
408
+ });
409
+ }
410
+ /**
411
+ * Built-in task: Batch filter items
412
+ */
413
+ function defineBatchFilter(name, predicate, threshold = 1000) {
414
+ return defineTask({
415
+ name,
416
+ estimateCost: (input) => input.length,
417
+ workerThreshold: threshold,
418
+ compute: (input) => input.filter(predicate),
419
+ chunker: (input, workerCount) => {
420
+ const chunkSize = Math.ceil(input.length / workerCount);
421
+ const chunks = [];
422
+ for (let i = 0; i < input.length; i += chunkSize) {
423
+ chunks.push(input.slice(i, i + chunkSize));
424
+ }
425
+ return chunks;
426
+ },
427
+ merger: (results) => [].concat(...results),
428
+ });
429
+ }
430
+ /**
431
+ * Built-in task: Batch reduce items
432
+ */
433
+ function defineBatchReduce(name, reducer, initial, merger, threshold = 1000) {
434
+ return defineTask({
435
+ name,
436
+ estimateCost: (input) => input.length,
437
+ workerThreshold: threshold,
438
+ compute: (input) => input.reduce(reducer, initial),
439
+ chunker: (input, workerCount) => {
440
+ const chunkSize = Math.ceil(input.length / workerCount);
441
+ const chunks = [];
442
+ for (let i = 0; i < input.length; i += chunkSize) {
443
+ chunks.push(input.slice(i, i + chunkSize));
444
+ }
445
+ return chunks;
446
+ },
447
+ merger,
448
+ });
449
+ }