@flowerforce/flowerbase 1.0.1-beta.10

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 (292) hide show
  1. package/CHANGELOG.md +0 -0
  2. package/LICENSE +3 -0
  3. package/README.md +18 -0
  4. package/dist/auth/controller.d.ts +8 -0
  5. package/dist/auth/controller.d.ts.map +1 -0
  6. package/dist/auth/controller.js +76 -0
  7. package/dist/auth/dtos.d.ts +6 -0
  8. package/dist/auth/dtos.d.ts.map +1 -0
  9. package/dist/auth/dtos.js +2 -0
  10. package/dist/auth/plugins/jwt.d.ts +14 -0
  11. package/dist/auth/plugins/jwt.d.ts.map +1 -0
  12. package/dist/auth/plugins/jwt.js +68 -0
  13. package/dist/auth/providers/local-userpass/controller.d.ts +8 -0
  14. package/dist/auth/providers/local-userpass/controller.d.ts.map +1 -0
  15. package/dist/auth/providers/local-userpass/controller.js +184 -0
  16. package/dist/auth/providers/local-userpass/dtos.d.ts +35 -0
  17. package/dist/auth/providers/local-userpass/dtos.d.ts.map +1 -0
  18. package/dist/auth/providers/local-userpass/dtos.js +2 -0
  19. package/dist/auth/utils.d.ts +126 -0
  20. package/dist/auth/utils.d.ts.map +1 -0
  21. package/dist/auth/utils.js +125 -0
  22. package/dist/constants.d.ts +20 -0
  23. package/dist/constants.d.ts.map +1 -0
  24. package/dist/constants.js +36 -0
  25. package/dist/features/endpoints/index.d.ts +10 -0
  26. package/dist/features/endpoints/index.d.ts.map +1 -0
  27. package/dist/features/endpoints/index.js +31 -0
  28. package/dist/features/endpoints/interface.d.ts +27 -0
  29. package/dist/features/endpoints/interface.d.ts.map +1 -0
  30. package/dist/features/endpoints/interface.js +2 -0
  31. package/dist/features/endpoints/utils.d.ts +31 -0
  32. package/dist/features/endpoints/utils.d.ts.map +1 -0
  33. package/dist/features/endpoints/utils.js +88 -0
  34. package/dist/features/functions/controller.d.ts +9 -0
  35. package/dist/features/functions/controller.d.ts.map +1 -0
  36. package/dist/features/functions/controller.js +88 -0
  37. package/dist/features/functions/dtos.d.ts +34 -0
  38. package/dist/features/functions/dtos.d.ts.map +1 -0
  39. package/dist/features/functions/dtos.js +2 -0
  40. package/dist/features/functions/index.d.ts +9 -0
  41. package/dist/features/functions/index.d.ts.map +1 -0
  42. package/dist/features/functions/index.js +28 -0
  43. package/dist/features/functions/interface.d.ts +32 -0
  44. package/dist/features/functions/interface.d.ts.map +1 -0
  45. package/dist/features/functions/interface.js +2 -0
  46. package/dist/features/functions/utils.d.ts +23 -0
  47. package/dist/features/functions/utils.d.ts.map +1 -0
  48. package/dist/features/functions/utils.js +75 -0
  49. package/dist/features/rules/index.d.ts +1 -0
  50. package/dist/features/rules/index.d.ts.map +1 -0
  51. package/dist/features/rules/index.js +1 -0
  52. package/dist/features/rules/interface.d.ts +22 -0
  53. package/dist/features/rules/interface.d.ts.map +1 -0
  54. package/dist/features/rules/interface.js +2 -0
  55. package/dist/features/rules/utils.d.ts +3 -0
  56. package/dist/features/rules/utils.d.ts.map +1 -0
  57. package/dist/features/rules/utils.js +31 -0
  58. package/dist/features/triggers/dtos.d.ts +9 -0
  59. package/dist/features/triggers/dtos.d.ts.map +1 -0
  60. package/dist/features/triggers/dtos.js +2 -0
  61. package/dist/features/triggers/index.d.ts +10 -0
  62. package/dist/features/triggers/index.d.ts.map +1 -0
  63. package/dist/features/triggers/index.js +59 -0
  64. package/dist/features/triggers/interface.d.ts +44 -0
  65. package/dist/features/triggers/interface.d.ts.map +1 -0
  66. package/dist/features/triggers/interface.js +2 -0
  67. package/dist/features/triggers/utils.d.ts +16 -0
  68. package/dist/features/triggers/utils.d.ts.map +1 -0
  69. package/dist/features/triggers/utils.js +153 -0
  70. package/dist/index.d.ts +19 -0
  71. package/dist/index.d.ts.map +1 -0
  72. package/dist/index.js +100 -0
  73. package/dist/model.d.ts +2 -0
  74. package/dist/model.d.ts.map +1 -0
  75. package/dist/model.js +2 -0
  76. package/dist/services/api/index.d.ts +36 -0
  77. package/dist/services/api/index.d.ts.map +1 -0
  78. package/dist/services/api/index.js +36 -0
  79. package/dist/services/api/model.d.ts +33 -0
  80. package/dist/services/api/model.d.ts.map +1 -0
  81. package/dist/services/api/model.js +2 -0
  82. package/dist/services/api/utils.d.ts +16 -0
  83. package/dist/services/api/utils.d.ts.map +1 -0
  84. package/dist/services/api/utils.js +45 -0
  85. package/dist/services/aws/index.d.ts +13 -0
  86. package/dist/services/aws/index.d.ts.map +1 -0
  87. package/dist/services/aws/index.js +50 -0
  88. package/dist/services/index.d.ts +41 -0
  89. package/dist/services/index.d.ts.map +1 -0
  90. package/dist/services/index.js +14 -0
  91. package/dist/services/interface.d.ts +3 -0
  92. package/dist/services/interface.d.ts.map +1 -0
  93. package/dist/services/interface.js +2 -0
  94. package/dist/services/mongodb-atlas/index.d.ts +4 -0
  95. package/dist/services/mongodb-atlas/index.d.ts.map +1 -0
  96. package/dist/services/mongodb-atlas/index.js +483 -0
  97. package/dist/services/mongodb-atlas/model.d.ts +39 -0
  98. package/dist/services/mongodb-atlas/model.d.ts.map +1 -0
  99. package/dist/services/mongodb-atlas/model.js +2 -0
  100. package/dist/services/mongodb-atlas/utils.d.ts +8 -0
  101. package/dist/services/mongodb-atlas/utils.d.ts.map +1 -0
  102. package/dist/services/mongodb-atlas/utils.js +33 -0
  103. package/dist/state.d.ts +6 -0
  104. package/dist/state.d.ts.map +1 -0
  105. package/dist/state.js +18 -0
  106. package/dist/utils/context/helpers.d.ts +74 -0
  107. package/dist/utils/context/helpers.d.ts.map +1 -0
  108. package/dist/utils/context/helpers.js +60 -0
  109. package/dist/utils/context/index.d.ts +14 -0
  110. package/dist/utils/context/index.d.ts.map +1 -0
  111. package/dist/utils/context/index.js +65 -0
  112. package/dist/utils/context/interface.d.ts +18 -0
  113. package/dist/utils/context/interface.d.ts.map +1 -0
  114. package/dist/utils/context/interface.js +2 -0
  115. package/dist/utils/crypto/index.d.ts +19 -0
  116. package/dist/utils/crypto/index.d.ts.map +1 -0
  117. package/dist/utils/crypto/index.js +50 -0
  118. package/dist/utils/helpers/someAsync.d.ts +12 -0
  119. package/dist/utils/helpers/someAsync.d.ts.map +1 -0
  120. package/dist/utils/helpers/someAsync.js +56 -0
  121. package/dist/utils/index.d.ts +3 -0
  122. package/dist/utils/index.d.ts.map +1 -0
  123. package/dist/utils/index.js +11 -0
  124. package/dist/utils/initializer/exposeRoutes.d.ts +8 -0
  125. package/dist/utils/initializer/exposeRoutes.d.ts.map +1 -0
  126. package/dist/utils/initializer/exposeRoutes.js +41 -0
  127. package/dist/utils/initializer/registerPlugins.d.ts +19 -0
  128. package/dist/utils/initializer/registerPlugins.d.ts.map +1 -0
  129. package/dist/utils/initializer/registerPlugins.js +96 -0
  130. package/dist/utils/roles/helpers.d.ts +4 -0
  131. package/dist/utils/roles/helpers.d.ts.map +1 -0
  132. package/dist/utils/roles/helpers.js +47 -0
  133. package/dist/utils/roles/interface.d.ts +33 -0
  134. package/dist/utils/roles/interface.d.ts.map +1 -0
  135. package/dist/utils/roles/interface.js +2 -0
  136. package/dist/utils/roles/machines/commonValidators.d.ts +6 -0
  137. package/dist/utils/roles/machines/commonValidators.d.ts.map +1 -0
  138. package/dist/utils/roles/machines/commonValidators.js +34 -0
  139. package/dist/utils/roles/machines/index.d.ts +14 -0
  140. package/dist/utils/roles/machines/index.d.ts.map +1 -0
  141. package/dist/utils/roles/machines/index.js +27 -0
  142. package/dist/utils/roles/machines/interface.d.ts +46 -0
  143. package/dist/utils/roles/machines/interface.d.ts.map +1 -0
  144. package/dist/utils/roles/machines/interface.js +2 -0
  145. package/dist/utils/roles/machines/machine.d.ts +15 -0
  146. package/dist/utils/roles/machines/machine.d.ts.map +1 -0
  147. package/dist/utils/roles/machines/machine.js +97 -0
  148. package/dist/utils/roles/machines/read/A/index.d.ts +3 -0
  149. package/dist/utils/roles/machines/read/A/index.d.ts.map +1 -0
  150. package/dist/utils/roles/machines/read/A/index.js +27 -0
  151. package/dist/utils/roles/machines/read/B/index.d.ts +3 -0
  152. package/dist/utils/roles/machines/read/B/index.d.ts.map +1 -0
  153. package/dist/utils/roles/machines/read/B/index.js +36 -0
  154. package/dist/utils/roles/machines/read/C/index.d.ts +3 -0
  155. package/dist/utils/roles/machines/read/C/index.d.ts.map +1 -0
  156. package/dist/utils/roles/machines/read/C/index.js +38 -0
  157. package/dist/utils/roles/machines/read/D/index.d.ts +3 -0
  158. package/dist/utils/roles/machines/read/D/index.d.ts.map +1 -0
  159. package/dist/utils/roles/machines/read/D/index.js +26 -0
  160. package/dist/utils/roles/machines/read/D/validators.d.ts +4 -0
  161. package/dist/utils/roles/machines/read/D/validators.d.ts.map +1 -0
  162. package/dist/utils/roles/machines/read/D/validators.js +24 -0
  163. package/dist/utils/roles/machines/read/index.d.ts +2 -0
  164. package/dist/utils/roles/machines/read/index.d.ts.map +1 -0
  165. package/dist/utils/roles/machines/read/index.js +8 -0
  166. package/dist/utils/roles/machines/utils.d.ts +37 -0
  167. package/dist/utils/roles/machines/utils.d.ts.map +1 -0
  168. package/dist/utils/roles/machines/utils.js +54 -0
  169. package/dist/utils/roles/machines/write/A/index.d.ts +3 -0
  170. package/dist/utils/roles/machines/write/A/index.d.ts.map +1 -0
  171. package/dist/utils/roles/machines/write/A/index.js +29 -0
  172. package/dist/utils/roles/machines/write/B/index.d.ts +3 -0
  173. package/dist/utils/roles/machines/write/B/index.d.ts.map +1 -0
  174. package/dist/utils/roles/machines/write/B/index.js +47 -0
  175. package/dist/utils/roles/machines/write/C/index.d.ts +3 -0
  176. package/dist/utils/roles/machines/write/C/index.d.ts.map +1 -0
  177. package/dist/utils/roles/machines/write/C/index.js +26 -0
  178. package/dist/utils/roles/machines/write/C/validators.d.ts +4 -0
  179. package/dist/utils/roles/machines/write/C/validators.d.ts.map +1 -0
  180. package/dist/utils/roles/machines/write/C/validators.js +24 -0
  181. package/dist/utils/roles/machines/write/index.d.ts +2 -0
  182. package/dist/utils/roles/machines/write/index.d.ts.map +1 -0
  183. package/dist/utils/roles/machines/write/index.js +7 -0
  184. package/dist/utils/rules-matcher/interface.d.ts +338 -0
  185. package/dist/utils/rules-matcher/interface.d.ts.map +1 -0
  186. package/dist/utils/rules-matcher/interface.js +26 -0
  187. package/dist/utils/rules-matcher/utils.d.ts +11 -0
  188. package/dist/utils/rules-matcher/utils.d.ts.map +1 -0
  189. package/dist/utils/rules-matcher/utils.js +214 -0
  190. package/dist/utils/rules.d.ts +2 -0
  191. package/dist/utils/rules.d.ts.map +1 -0
  192. package/dist/utils/rules.js +22 -0
  193. package/jest.config.ts +24 -0
  194. package/package.json +62 -0
  195. package/project.json +10 -0
  196. package/rollup.config.js +17 -0
  197. package/src/auth/controller.ts +78 -0
  198. package/src/auth/dtos.ts +6 -0
  199. package/src/auth/plugins/jwt.ts +68 -0
  200. package/src/auth/providers/local-userpass/controller.ts +226 -0
  201. package/src/auth/providers/local-userpass/dtos.ts +40 -0
  202. package/src/auth/utils.ts +168 -0
  203. package/src/babel.config.json +3 -0
  204. package/src/constants.ts +24 -0
  205. package/src/fastify.d.ts +28 -0
  206. package/src/features/endpoints/index.ts +27 -0
  207. package/src/features/endpoints/interface.ts +29 -0
  208. package/src/features/endpoints/utils.ts +74 -0
  209. package/src/features/functions/controller.ts +102 -0
  210. package/src/features/functions/dtos.ts +41 -0
  211. package/src/features/functions/index.ts +21 -0
  212. package/src/features/functions/interface.ts +38 -0
  213. package/src/features/functions/utils.ts +82 -0
  214. package/src/features/rules/index.tsx +0 -0
  215. package/src/features/rules/interface.ts +24 -0
  216. package/src/features/rules/utils.ts +20 -0
  217. package/src/features/triggers/dtos.ts +9 -0
  218. package/src/features/triggers/index.ts +36 -0
  219. package/src/features/triggers/interface.ts +44 -0
  220. package/src/features/triggers/utils.ts +157 -0
  221. package/src/global.d.ts +0 -0
  222. package/src/index.ts +90 -0
  223. package/src/model.ts +1 -0
  224. package/src/services/api/index.ts +50 -0
  225. package/src/services/api/model.ts +38 -0
  226. package/src/services/api/utils.ts +39 -0
  227. package/src/services/aws/index.ts +48 -0
  228. package/src/services/index.ts +9 -0
  229. package/src/services/interface.ts +3 -0
  230. package/src/services/mongodb-atlas/index.ts +569 -0
  231. package/src/services/mongodb-atlas/model.ts +67 -0
  232. package/src/services/mongodb-atlas/utils.ts +44 -0
  233. package/src/state.ts +24 -0
  234. package/src/utils/__tests__/STEP_A_STATES.test.ts +54 -0
  235. package/src/utils/__tests__/STEP_B_STATES.test.ts +113 -0
  236. package/src/utils/__tests__/STEP_C_STATES.test.ts +87 -0
  237. package/src/utils/__tests__/STEP_D_STATES.test.ts +93 -0
  238. package/src/utils/__tests__/checkAdditionalFieldsFn.test.ts +45 -0
  239. package/src/utils/__tests__/checkApplyWhen.test.ts +49 -0
  240. package/src/utils/__tests__/checkFieldsPropertyExists.test.ts +47 -0
  241. package/src/utils/__tests__/checkIsValidFieldNameFn.test.ts +190 -0
  242. package/src/utils/__tests__/comparePassword.test.ts +38 -0
  243. package/src/utils/__tests__/evaluateDocumentsFiltersReadFn.test.ts +57 -0
  244. package/src/utils/__tests__/evaluateDocumentsFiltersWriteFn.test.ts +57 -0
  245. package/src/utils/__tests__/evaluateTopLevelReadFn.test.ts +58 -0
  246. package/src/utils/__tests__/evaluateTopLevelWriteFn.test.ts +66 -0
  247. package/src/utils/__tests__/exposeRoutes.test.ts +65 -0
  248. package/src/utils/__tests__/generateContextData.test.ts +75 -0
  249. package/src/utils/__tests__/getDefaultRule.test.ts +29 -0
  250. package/src/utils/__tests__/getKey.test.ts +12 -0
  251. package/src/utils/__tests__/getKeys.test.ts +11 -0
  252. package/src/utils/__tests__/getWinningRole.test.ts +66 -0
  253. package/src/utils/__tests__/hashPassword.test.ts +28 -0
  254. package/src/utils/__tests__/isEmpty.test.ts +17 -0
  255. package/src/utils/__tests__/logMachineInfo.test.ts +15 -0
  256. package/src/utils/__tests__/operators.test.ts +99 -0
  257. package/src/utils/__tests__/readFileContent.test.ts +35 -0
  258. package/src/utils/__tests__/registerPlugins.test.ts +59 -0
  259. package/src/utils/__tests__/rule.test.ts +51 -0
  260. package/src/utils/__tests__/rulesMatcherInterfaces.test.ts +57 -0
  261. package/src/utils/__tests__/rulesMatcherUtils.test.ts +56 -0
  262. package/src/utils/__tests__/someAsync.test.ts +55 -0
  263. package/src/utils/context/helpers.ts +71 -0
  264. package/src/utils/context/index.ts +74 -0
  265. package/src/utils/context/interface.ts +19 -0
  266. package/src/utils/crypto/index.ts +36 -0
  267. package/src/utils/helpers/someAsync.ts +24 -0
  268. package/src/utils/index.ts +5 -0
  269. package/src/utils/initializer/exposeRoutes.ts +26 -0
  270. package/src/utils/initializer/registerPlugins.ts +111 -0
  271. package/src/utils/roles/helpers.ts +47 -0
  272. package/src/utils/roles/interface.ts +42 -0
  273. package/src/utils/roles/machines/commonValidators.ts +24 -0
  274. package/src/utils/roles/machines/index.ts +20 -0
  275. package/src/utils/roles/machines/interface.ts +46 -0
  276. package/src/utils/roles/machines/machine.ts +85 -0
  277. package/src/utils/roles/machines/read/A/index.ts +19 -0
  278. package/src/utils/roles/machines/read/B/index.ts +31 -0
  279. package/src/utils/roles/machines/read/C/index.ts +30 -0
  280. package/src/utils/roles/machines/read/D/index.ts +20 -0
  281. package/src/utils/roles/machines/read/D/validators.ts +24 -0
  282. package/src/utils/roles/machines/read/index.ts +6 -0
  283. package/src/utils/roles/machines/utils.ts +54 -0
  284. package/src/utils/roles/machines/write/A/index.ts +25 -0
  285. package/src/utils/roles/machines/write/B/index.ts +43 -0
  286. package/src/utils/roles/machines/write/C/index.ts +20 -0
  287. package/src/utils/roles/machines/write/C/validators.ts +24 -0
  288. package/src/utils/roles/machines/write/index.ts +5 -0
  289. package/src/utils/rules-matcher/interface.ts +365 -0
  290. package/src/utils/rules-matcher/utils.ts +281 -0
  291. package/src/utils/rules.ts +19 -0
  292. package/tsconfig.json +28 -0
@@ -0,0 +1,483 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ const isEqual_1 = __importDefault(require("lodash/isEqual"));
16
+ const mongodb_1 = require("mongodb");
17
+ const machines_1 = require("../../utils/roles/machines");
18
+ const utils_1 = require("../../utils/roles/machines/utils");
19
+ const utils_2 = require("./utils");
20
+ //TODO aggiungere no-sql inject security
21
+ const getOperators = (collection, { rules = {}, collName, user, run_as_system }) => ({
22
+ /**
23
+ * Finds a single document in a MongoDB collection with optional role-based filtering and validation.
24
+ *
25
+ * @param {Filter<Document>} query - The MongoDB query used to match the document.
26
+ * @returns {Promise<Document | {} | null>} A promise resolving to the document if found and permitted, an empty object if access is denied, or `null` if not found.
27
+ *
28
+ * @description
29
+ * If `run_as_system` is enabled, the function behaves like a standard `collection.findOne(query)` with no access checks.
30
+ * Otherwise:
31
+ * - Merges the provided query with any access control filters using `getFormattedQuery`.
32
+ * - Attempts to find the document using the formatted query.
33
+ * - Determines the user's role via `getWinningRole`.
34
+ * - Validates the result using `checkValidation` to ensure read permission.
35
+ * - If validation fails, returns an empty object; otherwise returns the validated document.
36
+ */
37
+ findOne: (query) => __awaiter(void 0, void 0, void 0, function* () {
38
+ if (!run_as_system) {
39
+ const { filters, roles } = rules[collName] || {};
40
+ // Apply access control filters to the query
41
+ const formattedQuery = (0, utils_2.getFormattedQuery)(filters, query, user);
42
+ const result = yield collection.findOne({ $and: formattedQuery });
43
+ const winningRole = (0, utils_1.getWinningRole)(result, user, roles);
44
+ const { status, document } = winningRole
45
+ ? yield (0, machines_1.checkValidation)(winningRole, {
46
+ type: "read",
47
+ roles,
48
+ cursor: result,
49
+ expansions: {},
50
+ }, user)
51
+ : { status: true, document: result };
52
+ // Return validated document or empty object if not permitted
53
+ return Promise.resolve(status ? document : {});
54
+ }
55
+ // System mode: no validation applied
56
+ return collection.findOne(query);
57
+ }),
58
+ /**
59
+ * Deletes a single document from a MongoDB collection with optional role-based validation.
60
+ *
61
+ * @param {Filter<Document>} [query={}] - The MongoDB query used to match the document to delete.
62
+ * @returns {Promise<DeleteResult>} A promise resolving to the result of the delete operation.
63
+ *
64
+ * @throws {Error} If the user is not authorized to delete the document.
65
+ *
66
+ * @description
67
+ * If `run_as_system` is enabled, the function deletes the document directly using `collection.deleteOne(query)`.
68
+ * Otherwise:
69
+ * - Applies role-based and custom filters to the query using `getFormattedQuery`.
70
+ * - Retrieves the document using `findOne` to validate user permissions.
71
+ * - Checks if the user has the appropriate role to perform a delete via `checkValidation`.
72
+ * - If validation fails, throws an error.
73
+ * - If validation passes, deletes the document using the filtered query.
74
+ */
75
+ deleteOne: (...args_1) => __awaiter(void 0, [...args_1], void 0, function* (query = {}) {
76
+ if (!run_as_system) {
77
+ const { filters, roles } = rules[collName] || {};
78
+ // Apply access control filters
79
+ const formattedQuery = (0, utils_2.getFormattedQuery)(filters, query, user);
80
+ // Retrieve the document to check permissions before deleting
81
+ const result = yield collection.findOne(formattedQuery);
82
+ const winningRole = (0, utils_1.getWinningRole)(result, user, roles);
83
+ const { status } = winningRole
84
+ ? yield (0, machines_1.checkValidation)(winningRole, {
85
+ type: "delete",
86
+ roles,
87
+ cursor: result,
88
+ expansions: {},
89
+ }, user)
90
+ : { status: true };
91
+ if (!status) {
92
+ throw new Error('Delete not permitted');
93
+ }
94
+ return collection.deleteOne(formattedQuery);
95
+ }
96
+ // System mode: bypass access control
97
+ return collection.deleteOne(query);
98
+ }),
99
+ /**
100
+ * Inserts a single document into a MongoDB collection with optional role-based validation.
101
+ *
102
+ * @param {OptionalId<Document>} data - The document to insert.
103
+ * @param {InsertOneOptions} [options] - Optional settings for the insert operation, such as `writeConcern`.
104
+ * @returns {Promise<InsertOneResult<Document>>} A promise resolving to the result of the insert operation.
105
+ *
106
+ * @throws {Error} If the user is not authorized to insert the document.
107
+ *
108
+ * @description
109
+ * If `run_as_system` is enabled, the document is inserted directly without any validation.
110
+ * Otherwise:
111
+ * - Determines the appropriate user role using `getWinningRole`.
112
+ * - Validates the insert operation using `checkValidation`.
113
+ * - If validation fails, an error is thrown.
114
+ * - If validation passes, the document is inserted.
115
+ *
116
+ * This ensures that only users with the correct permissions can insert data into the collection.
117
+ */
118
+ insertOne: (data, options) => __awaiter(void 0, void 0, void 0, function* () {
119
+ const { roles } = rules[collName] || {};
120
+ if (!run_as_system) {
121
+ const winningRole = (0, utils_1.getWinningRole)(data, user, roles);
122
+ const { status, document } = winningRole
123
+ ? yield (0, machines_1.checkValidation)(winningRole, {
124
+ type: "insert",
125
+ roles,
126
+ cursor: data,
127
+ expansions: {},
128
+ }, user)
129
+ : { status: true, document: data };
130
+ if (!status || !(0, isEqual_1.default)(data, document)) {
131
+ throw new Error('Insert not permitted');
132
+ }
133
+ return collection.insertOne(data, options);
134
+ }
135
+ // System mode: insert without validation
136
+ return collection.insertOne(data, options);
137
+ }),
138
+ /**
139
+ * Updates a single document in a MongoDB collection with optional role-based validation.
140
+ *
141
+ * @param {Filter<Document>} query - The MongoDB query used to match the document to update.
142
+ * @param {UpdateFilter<Document> | Partial<Document>} data - The update operations or replacement document.
143
+ * @param {UpdateOptions} [options] - Optional settings for the update operation.
144
+ * @returns {Promise<UpdateResult>} A promise resolving to the result of the update operation.
145
+ *
146
+ * @throws {Error} If the user is not authorized to update the document.
147
+ *
148
+ * @description
149
+ * If `run_as_system` is enabled, the function directly updates the document using `collection.updateOne(query, data, options)`.
150
+ * Otherwise, it follows these steps:
151
+ * - Applies access control filters to the query using `getFormattedQuery`.
152
+ * - Retrieves the document using `findOne` to check if it exists and whether the user has permission to modify it.
153
+ * - Determines the user's role via `getWinningRole`.
154
+ * - Flattens update operators (`$set`, `$inc`, etc.) if present to extract the final modified fields.
155
+ * - Validates the update data using `checkValidation` to ensure compliance with role-based rules.
156
+ * - Ensures that no unauthorized modifications occur by comparing the validated document with the intended changes.
157
+ * - If validation fails, throws an error; otherwise, updates the document.
158
+ */
159
+ updateOne: (query, data, options) => __awaiter(void 0, void 0, void 0, function* () {
160
+ if (!run_as_system) {
161
+ const { filters, roles } = rules[collName] || {};
162
+ // Apply access control filters
163
+ const formattedQuery = (0, utils_2.getFormattedQuery)(filters, query, user);
164
+ // Retrieve the document to check permissions before updating
165
+ const result = yield collection.findOne({ $and: formattedQuery });
166
+ if (!result) {
167
+ throw new Error('Update not permitted');
168
+ }
169
+ const winningRole = (0, utils_1.getWinningRole)(result, user, roles);
170
+ // Check if the update data contains MongoDB update operators (e.g., $set, $inc)
171
+ const hasOperators = Object.keys(data).some(key => key.startsWith("$"));
172
+ // Flatten the update object to extract the actual fields being modified
173
+ // const docToCheck = hasOperators
174
+ // ? Object.values(data).reduce((acc, operation) => ({ ...acc, ...operation }), {})
175
+ // : data
176
+ const pipeline = [
177
+ {
178
+ $match: formattedQuery,
179
+ },
180
+ {
181
+ $limit: 1
182
+ },
183
+ ...Object.entries(data).map(([key, value]) => ({ [key]: value })),
184
+ ];
185
+ const [docToCheck] = hasOperators ? yield collection.aggregate(pipeline).toArray() : [data];
186
+ // Validate update permissions
187
+ const { status, document } = winningRole
188
+ ? yield (0, machines_1.checkValidation)(winningRole, {
189
+ type: "write",
190
+ roles,
191
+ cursor: docToCheck,
192
+ expansions: {},
193
+ }, user)
194
+ : { status: true, document: docToCheck };
195
+ // Ensure no unauthorized changes are made
196
+ const areDocumentsEqual = (0, isEqual_1.default)(document, docToCheck);
197
+ if (!status || !areDocumentsEqual) {
198
+ throw new Error('Update not permitted');
199
+ }
200
+ return collection.updateOne(formattedQuery, data, options);
201
+ }
202
+ return collection.updateOne(query, data, options);
203
+ }),
204
+ /**
205
+ * Finds documents in a MongoDB collection with optional role-based access control and post-query validation.
206
+ *
207
+ * @param {Filter<Document>} query - The MongoDB query to filter documents.
208
+ * @returns {FindCursor} A customized `FindCursor` that includes additional access control logic in its `toArray()` method.
209
+ *
210
+ * @description
211
+ * If `run_as_system` is enabled, the function simply returns a regular MongoDB cursor (`collection.find(query)`).
212
+ * Otherwise:
213
+ * - Combines the user query with role-based filters via `getFormattedQuery`.
214
+ * - Executes the query using `collection.find` with a `$and` of all filters.
215
+ * - Returns a cloned `FindCursor` where `toArray()`:
216
+ * - Applies additional post-query validation using `checkValidation` for each document.
217
+ * - Filters out documents the current user is not authorized to read.
218
+ *
219
+ * This ensures that both pre-query filtering and post-query validation are applied consistently.
220
+ */
221
+ find: (query) => {
222
+ if (!run_as_system) {
223
+ const { filters, roles } = rules[collName] || {};
224
+ // Pre-query filtering based on access control rules
225
+ const formattedQuery = (0, utils_2.getFormattedQuery)(filters, query, user);
226
+ const originalCursor = collection.find({ $and: formattedQuery });
227
+ // Clone the cursor to override `toArray` with post-query validation
228
+ const client = originalCursor['client'];
229
+ const newCursor = new mongodb_1.FindCursor(client);
230
+ /**
231
+ * Overridden `toArray` method that validates each document for read access.
232
+ *
233
+ * @returns {Promise<Document[]>} An array of documents the user is authorized to read.
234
+ */
235
+ newCursor.toArray = () => __awaiter(void 0, void 0, void 0, function* () {
236
+ const response = yield originalCursor.toArray();
237
+ const filteredResponse = yield Promise.all(response.map((currentDoc) => __awaiter(void 0, void 0, void 0, function* () {
238
+ const winningRole = (0, utils_1.getWinningRole)(currentDoc, user, roles);
239
+ const { status, document } = winningRole
240
+ ? yield (0, machines_1.checkValidation)(winningRole, {
241
+ type: "read",
242
+ roles,
243
+ cursor: currentDoc,
244
+ expansions: {},
245
+ }, user)
246
+ : { status: !roles.length, document: currentDoc };
247
+ return status ? document : undefined;
248
+ })));
249
+ return filteredResponse.filter(Boolean);
250
+ });
251
+ return newCursor;
252
+ }
253
+ // System mode: return original unfiltered cursor
254
+ return collection.find(query);
255
+ },
256
+ /**
257
+ * Watches changes on a MongoDB collection with optional role-based filtering of change events.
258
+ *
259
+ * @param {Document[]} [pipeline=[]] - Optional aggregation pipeline stages to apply to the change stream.
260
+ * @param {ChangeStreamOptions} [options] - Optional settings for the change stream, such as `fullDocument`, `resumeAfter`, etc.
261
+ * @returns {ChangeStream} A MongoDB `ChangeStream` instance, optionally enhanced with access control.
262
+ *
263
+ * @description
264
+ * If `run_as_system` is enabled, this function simply returns `collection.watch(pipeline, options)`.
265
+ * Otherwise:
266
+ * - Applies access control filters via `getFormattedQuery`.
267
+ * - Prepends a `$match` stage to the pipeline to limit watched changes to authorized documents.
268
+ * - Overrides the `.on()` method of the returned `ChangeStream` to:
269
+ * - Validate the `fullDocument` and any `updatedFields` using `checkValidation`.
270
+ * - Filter out change events the user is not authorized to see.
271
+ * - Pass only validated and filtered events to the original listener.
272
+ *
273
+ * This allows fine-grained control over what change events a user can observe, based on roles and filters.
274
+ */
275
+ watch: (pipeline = [], options) => {
276
+ if (!run_as_system) {
277
+ const { filters, roles } = rules[collName] || {};
278
+ // Apply access filters to initial change stream pipeline
279
+ const formattedQuery = (0, utils_2.getFormattedQuery)(filters, {}, user);
280
+ const formattedPipeline = [{
281
+ $match: {
282
+ $and: formattedQuery
283
+ }
284
+ }, ...pipeline];
285
+ const result = collection.watch(formattedPipeline, options);
286
+ const originalOn = result.on.bind(result);
287
+ /**
288
+ * Validates a change event against the user's roles.
289
+ *
290
+ * @param {Document} change - A change event from the ChangeStream.
291
+ * @returns {Promise<{ status: boolean, document: Document, updatedFieldsStatus: boolean, updatedFields: Document }>}
292
+ */
293
+ const isValidChange = (_a) => __awaiter(void 0, [_a], void 0, function* ({ fullDocument, updateDescription }) {
294
+ const winningRole = (0, utils_1.getWinningRole)(fullDocument, user, roles);
295
+ const { status, document } = winningRole
296
+ ? yield (0, machines_1.checkValidation)(winningRole, {
297
+ type: "read",
298
+ roles,
299
+ cursor: fullDocument,
300
+ expansions: {},
301
+ }, user)
302
+ : { status: true, document: fullDocument };
303
+ const { status: updatedFieldsStatus, document: updatedFields } = winningRole
304
+ ? yield (0, machines_1.checkValidation)(winningRole, {
305
+ type: "read",
306
+ roles,
307
+ cursor: updateDescription === null || updateDescription === void 0 ? void 0 : updateDescription.updatedFields,
308
+ expansions: {},
309
+ }, user)
310
+ : { status: true, document: updateDescription === null || updateDescription === void 0 ? void 0 : updateDescription.updatedFields };
311
+ return { status, document, updatedFieldsStatus, updatedFields };
312
+ });
313
+ // Override the .on() method to apply validation before emitting events
314
+ result.on = (eventType, listener) => {
315
+ return originalOn(eventType, (change) => __awaiter(void 0, void 0, void 0, function* () {
316
+ const { status, document, updatedFieldsStatus, updatedFields } = yield isValidChange(change);
317
+ if (!status)
318
+ return;
319
+ const filteredChange = Object.assign(Object.assign({}, change), { fullDocument: document, updateDescription: Object.assign(Object.assign({}, change.updateDescription), { updatedFields: updatedFieldsStatus ? updatedFields : {} }) });
320
+ listener(filteredChange);
321
+ }));
322
+ };
323
+ return result;
324
+ }
325
+ // System mode: no filtering applied
326
+ return collection.watch(pipeline, options);
327
+ },
328
+ //TODO -> add filter & rules in aggregate
329
+ aggregate: (pipeline, options) => collection.aggregate(pipeline, options),
330
+ /**
331
+ * Inserts multiple documents into a MongoDB collection with optional role-based access control and validation.
332
+ *
333
+ * @param {OptionalId<Document>[]} documents - The array of documents to insert.
334
+ * @param {BulkWriteOptions} [options] - Optional settings passed to `insertMany`, such as `ordered`, `writeConcern`, etc.
335
+ * @returns {Promise<InsertManyResult<Document>>} A promise resolving to the result of the insert operation.
336
+ *
337
+ * @throws {Error} If no documents pass validation or user is not permitted to insert.
338
+ *
339
+ * @description
340
+ * If `run_as_system` is enabled, this function directly inserts the documents without validation.
341
+ * Otherwise, for each document:
342
+ * - Finds the user's applicable role using `getWinningRole`.
343
+ * - Validates the insert operation through `checkValidation`.
344
+ * - Filters out any documents the user is not authorized to insert.
345
+ * Only documents passing validation will be inserted.
346
+ */
347
+ insertMany: (documents, options) => __awaiter(void 0, void 0, void 0, function* () {
348
+ if (!run_as_system) {
349
+ const { roles } = rules[collName] || {};
350
+ // Validate each document against user's roles
351
+ const filteredItems = yield Promise.all(documents.map((currentDoc) => __awaiter(void 0, void 0, void 0, function* () {
352
+ const winningRole = (0, utils_1.getWinningRole)(currentDoc, user, roles);
353
+ const { status, document } = winningRole
354
+ ? yield (0, machines_1.checkValidation)(winningRole, {
355
+ type: "insert",
356
+ roles,
357
+ cursor: currentDoc,
358
+ expansions: {},
359
+ }, user)
360
+ : { status: !roles.length, document: currentDoc };
361
+ return status ? document : undefined;
362
+ })));
363
+ const canInsert = (0, isEqual_1.default)(filteredItems, documents);
364
+ if (!canInsert) {
365
+ throw new Error('Insert not permitted');
366
+ }
367
+ return collection.insertMany(documents, options);
368
+ }
369
+ // If system mode is active, insert all documents without validation
370
+ return collection.insertMany(documents, options);
371
+ }),
372
+ updateMany: (query, data, options) => __awaiter(void 0, void 0, void 0, function* () {
373
+ if (!run_as_system) {
374
+ const { filters, roles } = rules[collName] || {};
375
+ // Apply access control filters
376
+ const formattedQuery = (0, utils_2.getFormattedQuery)(filters, query, user);
377
+ // Retrieve the document to check permissions before updating
378
+ const result = yield collection.find({ $and: formattedQuery }).toArray();
379
+ if (!result) {
380
+ throw new Error('Update not permitted');
381
+ }
382
+ // Check if the update data contains MongoDB update operators (e.g., $set, $inc)
383
+ const hasOperators = Object.keys(data).some(key => key.startsWith("$"));
384
+ // Flatten the update object to extract the actual fields being modified
385
+ // const docToCheck = hasOperators
386
+ // ? Object.values(data).reduce((acc, operation) => ({ ...acc, ...operation }), {})
387
+ // : data
388
+ const pipeline = [
389
+ {
390
+ $match: formattedQuery,
391
+ },
392
+ ...Object.entries(data).map(([key, value]) => ({ [key]: value })),
393
+ ];
394
+ const docsToCheck = hasOperators ? yield collection.aggregate(pipeline).toArray() : result;
395
+ const filteredItems = yield Promise.all(docsToCheck.map((currentDoc) => __awaiter(void 0, void 0, void 0, function* () {
396
+ const winningRole = (0, utils_1.getWinningRole)(currentDoc, user, roles);
397
+ const { status, document } = winningRole
398
+ ? yield (0, machines_1.checkValidation)(winningRole, {
399
+ type: "write",
400
+ roles,
401
+ cursor: currentDoc,
402
+ expansions: {},
403
+ }, user)
404
+ : { status: !roles.length, document: currentDoc };
405
+ return status ? document : undefined;
406
+ })));
407
+ // Ensure no unauthorized changes are made
408
+ const areDocumentsEqual = (0, isEqual_1.default)(docsToCheck, filteredItems);
409
+ if (!areDocumentsEqual) {
410
+ throw new Error('Update not permitted');
411
+ }
412
+ return collection.updateMany(formattedQuery, data, options);
413
+ }
414
+ return collection.updateMany(query, data, options);
415
+ }),
416
+ /**
417
+ * Deletes multiple documents from a MongoDB collection with role-based access control and validation.
418
+ *
419
+ * @param query - The initial MongoDB query to filter documents to be deleted.
420
+ * @returns {Promise<{ acknowledged: boolean, deletedCount: number }>} A promise resolving to the deletion result.
421
+ *
422
+ * @description
423
+ * If `run_as_system` is enabled, this function directly deletes documents matching the given query.
424
+ * Otherwise, it:
425
+ * - Applies additional filters from access control rules.
426
+ * - Fetches matching documents.
427
+ * - Validates each document against user roles.
428
+ * - Deletes only the documents that the current user has permission to delete.
429
+ */
430
+ deleteMany: (...args_1) => __awaiter(void 0, [...args_1], void 0, function* (query = {}) {
431
+ if (!run_as_system) {
432
+ const { filters, roles } = rules[collName] || {};
433
+ // Apply access control filters
434
+ const formattedQuery = (0, utils_2.getFormattedQuery)(filters, query, user);
435
+ // Fetch documents matching the combined filters
436
+ const data = yield collection.find({ $and: formattedQuery }).toArray();
437
+ // Filter and validate each document based on user's roles
438
+ const filteredItems = yield Promise.all(data.map((currentDoc) => __awaiter(void 0, void 0, void 0, function* () {
439
+ const winningRole = (0, utils_1.getWinningRole)(currentDoc, user, roles);
440
+ const { status, document } = winningRole
441
+ ? yield (0, machines_1.checkValidation)(winningRole, {
442
+ type: "delete",
443
+ roles,
444
+ cursor: currentDoc,
445
+ expansions: {},
446
+ }, user)
447
+ : { status: !roles.length, document: currentDoc };
448
+ return status ? document : undefined;
449
+ })));
450
+ // Extract IDs of documents that passed validation
451
+ const elementsToDelete = filteredItems.filter(Boolean).map(({ _id }) => _id);
452
+ if (!elementsToDelete.length) {
453
+ return Promise.resolve({
454
+ acknowledged: true,
455
+ deletedCount: 0
456
+ });
457
+ }
458
+ // Build final delete query with access control and ID filter
459
+ const deleteQuery = {
460
+ $and: [
461
+ ...formattedQuery,
462
+ { _id: { $in: elementsToDelete } }
463
+ ]
464
+ };
465
+ return collection.deleteMany(deleteQuery);
466
+ }
467
+ // If running as system, bypass access control and delete directly
468
+ return collection.deleteMany(query);
469
+ })
470
+ });
471
+ const MongodbAtlas = (app, { rules, user, run_as_system } = {}) => ({
472
+ db: (dbName) => {
473
+ return {
474
+ collection: (collName) => {
475
+ const collection = app.mongo.client
476
+ .db(dbName)
477
+ .collection(collName);
478
+ return getOperators(collection, { rules, collName, user, run_as_system });
479
+ }
480
+ };
481
+ }
482
+ });
483
+ exports.default = MongodbAtlas;
@@ -0,0 +1,39 @@
1
+ import { FastifyInstance } from 'fastify';
2
+ import { Collection, Document, FindCursor, WithId } from 'mongodb';
3
+ import { User } from '../../auth/dtos';
4
+ import { Filter, Rules } from '../../features/rules/interface';
5
+ import { Role } from '../../utils/roles/interface';
6
+ export type MongodbAtlasFunction = (app: FastifyInstance, { rules, user, run_as_system }: {
7
+ user?: User;
8
+ rules?: Rules;
9
+ run_as_system?: boolean;
10
+ }) => {
11
+ db: (dbName: string) => {
12
+ collection: (collName: string) => ReturnType<GetOperatorsFunction>;
13
+ };
14
+ };
15
+ export type GetValidRuleParams<T extends Role | Filter> = {
16
+ filters: T[];
17
+ user: User;
18
+ record?: WithId<Document> | Document | null;
19
+ };
20
+ type Method<T extends keyof Collection<Document>> = Collection<Document>[T];
21
+ export type GetOperatorsFunction = (collection: Collection<Document>, { rules, collName, user, run_as_system, }: {
22
+ user?: User;
23
+ rules?: Rules;
24
+ run_as_system?: boolean;
25
+ collName: string;
26
+ }) => {
27
+ findOne: (...params: Parameters<Method<"findOne">>) => ReturnType<Method<"findOne">>;
28
+ deleteOne: (...params: Parameters<Method<"findOne">>) => ReturnType<Method<"findOne">>;
29
+ insertOne: (...params: Parameters<Method<'insertOne'>>) => ReturnType<Method<'insertOne'>>;
30
+ updateOne: (...params: Parameters<Method<'updateOne'>>) => ReturnType<Method<'updateOne'>>;
31
+ find: (...params: Parameters<Method<'find'>>) => FindCursor;
32
+ watch: (...params: Parameters<Method<'watch'>>) => ReturnType<Method<'watch'>>;
33
+ aggregate: (...params: Parameters<Method<'aggregate'>>) => ReturnType<Method<'aggregate'>>;
34
+ insertMany: (...params: Parameters<Method<'insertMany'>>) => ReturnType<Method<'insertMany'>>;
35
+ updateMany: (...params: Parameters<Method<'updateMany'>>) => ReturnType<Method<'updateMany'>>;
36
+ deleteMany: (...params: Parameters<Method<'deleteMany'>>) => ReturnType<Method<'deleteMany'>>;
37
+ };
38
+ export {};
39
+ //# sourceMappingURL=model.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"model.d.ts","sourceRoot":"","sources":["../../../src/services/mongodb-atlas/model.ts"],"names":[],"mappings":"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"}
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,8 @@
1
+ import { Collection, Document } from 'mongodb';
2
+ import { User } from '../../auth/dtos';
3
+ import { Filter } from '../../features/rules/interface';
4
+ import { Role } from '../../utils/roles/interface';
5
+ import { GetValidRuleParams } from './model';
6
+ export declare const getValidRule: <T extends Role | Filter>({ filters, user, record }: GetValidRuleParams<T>) => T[];
7
+ export declare const getFormattedQuery: (filters: Filter[] | undefined, query: Parameters<Collection<Document>["findOne"]>[0], user?: User) => any[];
8
+ //# sourceMappingURL=utils.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../../src/services/mongodb-atlas/utils.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAA;AAC9C,OAAO,EAAE,IAAI,EAAE,MAAM,iBAAiB,CAAA;AACtC,OAAO,EAAE,MAAM,EAAE,MAAM,gCAAgC,CAAA;AACvD,OAAO,EAAE,IAAI,EAAE,MAAM,6BAA6B,CAAA;AAGlD,OAAO,EAAE,kBAAkB,EAAE,MAAM,SAAS,CAAA;AAE5C,eAAO,MAAM,YAAY,GAAI,CAAC,SAAS,IAAI,GAAG,MAAM,EAAE,2BAInD,kBAAkB,CAAC,CAAC,CAAC,QAoBvB,CAAA;AAGD,eAAO,MAAM,iBAAiB,GAAI,SAAS,MAAM,EAAE,YAAK,EAAE,OAAO,UAAU,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,OAAO,IAAI,UAO3H,CAAA"}
@@ -0,0 +1,33 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.getFormattedQuery = exports.getValidRule = void 0;
7
+ const rules_1 = require("../../utils/rules");
8
+ const utils_1 = __importDefault(require("../../utils/rules-matcher/utils"));
9
+ const getValidRule = ({ filters = [], user, record = null }) => {
10
+ if (!filters.length)
11
+ return [];
12
+ return filters.filter((f) => {
13
+ if (Object.keys(f.apply_when).length === 0)
14
+ return true;
15
+ const conditions = (0, rules_1.expandQuery)(f.apply_when, {
16
+ '%%user': user,
17
+ '%%true': true
18
+ /** values */
19
+ });
20
+ const valid = utils_1.default.checkRule(conditions, Object.assign(Object.assign({}, (record !== null && record !== void 0 ? record : {})), { '%%user': user }), {});
21
+ return valid;
22
+ });
23
+ };
24
+ exports.getValidRule = getValidRule;
25
+ const getFormattedQuery = (filters = [], query, user) => {
26
+ const preFilter = (0, exports.getValidRule)({ filters, user });
27
+ const isValidPreFilter = !!(preFilter === null || preFilter === void 0 ? void 0 : preFilter.length);
28
+ return [
29
+ isValidPreFilter && (0, rules_1.expandQuery)(preFilter[0].query, { '%%user': user }),
30
+ query
31
+ ].filter(Boolean);
32
+ };
33
+ exports.getFormattedQuery = getFormattedQuery;
@@ -0,0 +1,6 @@
1
+ export declare class StateManager {
2
+ private static _state;
3
+ static select<K extends keyof typeof this._state>(key: K): NonNullable<typeof this._state[K]>;
4
+ static setData<K extends keyof typeof this._state>(key: K, value: typeof this._state[K]): void;
5
+ }
6
+ //# sourceMappingURL=state.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"state.d.ts","sourceRoot":"","sources":["../src/state.ts"],"names":[],"mappings":"AASA,qBAAa,YAAY;IACrB,OAAO,CAAC,MAAM,CAAC,MAAM,CAKnB;IACF,MAAM,CAAC,MAAM,CAAC,CAAC,SAAS,MAAM,OAAO,IAAI,CAAC,MAAM,EAAE,GAAG,EAAE,CAAC,GAAG,WAAW,CAAC,OAAO,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;IAI7F,MAAM,CAAC,OAAO,CAAC,CAAC,SAAS,MAAM,OAAO,IAAI,CAAC,MAAM,EAAE,GAAG,EAAE,CAAC,EAAE,KAAK,EAAE,OAAO,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC;CAG1F"}
package/dist/state.js ADDED
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.StateManager = void 0;
4
+ class StateManager {
5
+ static select(key) {
6
+ return this._state[key];
7
+ }
8
+ static setData(key, value) {
9
+ this._state[key] = value;
10
+ }
11
+ }
12
+ exports.StateManager = StateManager;
13
+ StateManager._state = {
14
+ functions: {},
15
+ triggers: [],
16
+ endpoints: [],
17
+ rules: {}
18
+ };