acomm-core-lib 2.6.8 → 2.6.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 (239) hide show
  1. package/dist/package.json +3 -1
  2. package/dist/src/core/activity_log/activity_log.layout.d.ts +1 -1
  3. package/dist/src/core/activity_log/activity_log.schema.d.ts +4 -3
  4. package/dist/src/core/activity_log/activity_log.schema.js +4 -0
  5. package/dist/src/core/activity_log/activity_log.schema.js.map +1 -1
  6. package/dist/src/core/activity_log/activity_log.service.d.ts +1 -1
  7. package/dist/src/core/activity_log/activity_log.service.js +5 -0
  8. package/dist/src/core/activity_log/activity_log.service.js.map +1 -1
  9. package/dist/src/core/address/address.layout.d.ts +1 -1
  10. package/dist/src/core/address/address.schema.d.ts +1 -1
  11. package/dist/src/core/address/address.service.d.ts +2 -2
  12. package/dist/src/core/api_key/api_key.layout.d.ts +1 -1
  13. package/dist/src/core/api_key/api_key.layout.js +22 -0
  14. package/dist/src/core/api_key/api_key.layout.js.map +1 -1
  15. package/dist/src/core/api_key/api_key.schema.d.ts +5 -1
  16. package/dist/src/core/api_key/api_key.schema.js +21 -0
  17. package/dist/src/core/api_key/api_key.schema.js.map +1 -1
  18. package/dist/src/core/api_key/api_key.service.d.ts +2 -2
  19. package/dist/src/core/api_key/api_key.service.js.map +1 -1
  20. package/dist/src/core/attachment/attachment.service.d.ts +1 -1
  21. package/dist/src/core/attachment/attachment.service.js +31 -2
  22. package/dist/src/core/attachment/attachment.service.js.map +1 -1
  23. package/dist/src/core/audit_log/audit_log.enum.d.ts +2 -0
  24. package/dist/src/core/audit_log/audit_log.enum.js +2 -0
  25. package/dist/src/core/audit_log/audit_log.enum.js.map +1 -1
  26. package/dist/src/core/audit_log/audit_log.layout.d.ts +1 -1
  27. package/dist/src/core/audit_log/audit_log.schema.d.ts +2 -2
  28. package/dist/src/core/audit_log/audit_log.service.d.ts +1 -1
  29. package/dist/src/core/audit_log/audit_log.service.js +6 -4
  30. package/dist/src/core/audit_log/audit_log.service.js.map +1 -1
  31. package/dist/src/core/auth/auth.controller.d.ts +2 -0
  32. package/dist/src/core/auth/auth.controller.js +22 -1
  33. package/dist/src/core/auth/auth.controller.js.map +1 -1
  34. package/dist/src/core/auth/auth.service.d.ts +2 -0
  35. package/dist/src/core/auth/auth.service.js +199 -4
  36. package/dist/src/core/auth/auth.service.js.map +1 -1
  37. package/dist/src/core/auth/constants.d.ts +2 -0
  38. package/dist/src/core/auth/constants.js +3 -1
  39. package/dist/src/core/auth/constants.js.map +1 -1
  40. package/dist/src/core/auth/guards/jwt_auth.guard.js +9 -1
  41. package/dist/src/core/auth/guards/jwt_auth.guard.js.map +1 -1
  42. package/dist/src/core/auth/providers/auth_exchange.provider.d.ts +12 -0
  43. package/dist/src/core/auth/providers/auth_exchange.provider.js +46 -0
  44. package/dist/src/core/auth/providers/auth_exchange.provider.js.map +1 -0
  45. package/dist/src/core/auth/providers/auth_local.provider.d.ts +1 -1
  46. package/dist/src/core/auth/providers/auth_otp.provider.d.ts +1 -1
  47. package/dist/src/core/auth/providers/auth_otp.provider.js +3 -0
  48. package/dist/src/core/auth/providers/auth_otp.provider.js.map +1 -1
  49. package/dist/src/core/auth/providers/base_auth.provider.d.ts +2 -2
  50. package/dist/src/core/comment_data/comment_data.layout.d.ts +1 -1
  51. package/dist/src/core/comment_data/comment_data.schema.d.ts +2 -2
  52. package/dist/src/core/comment_data/comment_data.service.d.ts +1 -1
  53. package/dist/src/core/common/base/base.service.js +24 -9
  54. package/dist/src/core/common/base/base.service.js.map +1 -1
  55. package/dist/src/core/common/base/base_module.service.d.ts +1 -1
  56. package/dist/src/core/common/constants.d.ts +1 -0
  57. package/dist/src/core/common/constants.js +1 -0
  58. package/dist/src/core/common/constants.js.map +1 -1
  59. package/dist/src/core/common/interceptors/filter.interceptor.js +5 -4
  60. package/dist/src/core/common/interceptors/filter.interceptor.js.map +1 -1
  61. package/dist/src/core/common/utils/build_search.d.ts +2 -1
  62. package/dist/src/core/common/utils/build_search.js +132 -50
  63. package/dist/src/core/common/utils/build_search.js.map +1 -1
  64. package/dist/src/core/common/utils/entity.d.ts +1 -1
  65. package/dist/src/core/common/utils/exchange.d.ts +1 -0
  66. package/dist/src/core/common/utils/exchange.js +21 -0
  67. package/dist/src/core/common/utils/exchange.js.map +1 -0
  68. package/dist/src/core/common/utils/executions.d.ts +1 -1
  69. package/dist/src/core/common/utils/executions.js +2 -0
  70. package/dist/src/core/common/utils/executions.js.map +1 -1
  71. package/dist/src/core/common/utils/func.d.ts +1 -1
  72. package/dist/src/core/common/utils/global.d.ts +2 -1
  73. package/dist/src/core/common/utils/global.js +12 -1
  74. package/dist/src/core/common/utils/global.js.map +1 -1
  75. package/dist/src/core/common/utils/hook.d.ts +2 -2
  76. package/dist/src/core/common/utils/hook.js +9 -3
  77. package/dist/src/core/common/utils/hook.js.map +1 -1
  78. package/dist/src/core/common/utils/mongo.js +14 -7
  79. package/dist/src/core/common/utils/mongo.js.map +1 -1
  80. package/dist/src/core/common/utils/sanitize.d.ts +4 -0
  81. package/dist/src/core/common/utils/sanitize.js +45 -0
  82. package/dist/src/core/common/utils/sanitize.js.map +1 -0
  83. package/dist/src/core/common/utils/schema.d.ts +1 -1
  84. package/dist/src/core/common/utils/schema.js +482 -87
  85. package/dist/src/core/common/utils/schema.js.map +1 -1
  86. package/dist/src/core/common/utils/template.d.ts +1 -1
  87. package/dist/src/core/common/utils/template.js +10 -2
  88. package/dist/src/core/common/utils/template.js.map +1 -1
  89. package/dist/src/core/common/utils/text_search.d.ts +1 -1
  90. package/dist/src/core/common/utils/text_search.js +23 -2
  91. package/dist/src/core/common/utils/text_search.js.map +1 -1
  92. package/dist/src/core/company/company.layout.d.ts +1 -1
  93. package/dist/src/core/company/company.schema.d.ts +3 -3
  94. package/dist/src/core/company/company.service.d.ts +2 -2
  95. package/dist/src/core/currency/currency.layout.d.ts +1 -1
  96. package/dist/src/core/currency/currency.schema.d.ts +1 -1
  97. package/dist/src/core/currency/currency.service.d.ts +2 -2
  98. package/dist/src/core/custom_function/custom_function.schema.d.ts +1 -1
  99. package/dist/src/core/deploy/deploy.layout.d.ts +1 -1
  100. package/dist/src/core/deploy/deploy.schema.d.ts +1 -1
  101. package/dist/src/core/deploy/deploy.service.d.ts +1 -1
  102. package/dist/src/core/deploy/log/deploy_log.schema.d.ts +1 -1
  103. package/dist/src/core/deploy/log/deploy_log.service.d.ts +1 -1
  104. package/dist/src/core/entities/entities.service.d.ts +1 -1
  105. package/dist/src/core/entities/entities.service.js +49 -9
  106. package/dist/src/core/entities/entities.service.js.map +1 -1
  107. package/dist/src/core/entities/entity.schema.d.ts +2 -1
  108. package/dist/src/core/entities/entity.schema.js +4 -0
  109. package/dist/src/core/entities/entity.schema.js.map +1 -1
  110. package/dist/src/core/execution_log/execution_log.layout.d.ts +1 -1
  111. package/dist/src/core/import_export/import_export.layout.d.ts +1 -1
  112. package/dist/src/core/import_export/import_export.schema.d.ts +1 -1
  113. package/dist/src/core/import_export/import_export.service.d.ts +1 -1
  114. package/dist/src/core/import_export/import_export.service.js +1 -1
  115. package/dist/src/core/import_export/import_export.service.js.map +1 -1
  116. package/dist/src/core/import_export/log/import_export_log.layout.d.ts +1 -1
  117. package/dist/src/core/import_export/log/import_export_log.schema.d.ts +2 -2
  118. package/dist/src/core/import_export/log/import_export_log.service.d.ts +2 -2
  119. package/dist/src/core/import_export/provider/export.provider.d.ts +2 -2
  120. package/dist/src/core/import_export/provider/import.provider.d.ts +2 -2
  121. package/dist/src/core/index.d.ts +1 -0
  122. package/dist/src/core/index.js +4 -1
  123. package/dist/src/core/index.js.map +1 -1
  124. package/dist/src/core/language/language.layout.d.ts +1 -1
  125. package/dist/src/core/language/language.schema.d.ts +1 -1
  126. package/dist/src/core/language/language.service.d.ts +1 -1
  127. package/dist/src/core/layout/share_widget/share_widget.layout.d.ts +1 -1
  128. package/dist/src/core/layout/share_widget/share_widget.schema.d.ts +1 -1
  129. package/dist/src/core/layout/share_widget/share_widget.service.d.ts +3 -3
  130. package/dist/src/core/mail/log/mail_log.layout.d.ts +1 -1
  131. package/dist/src/core/mail/log/mail_log.schema.d.ts +1 -1
  132. package/dist/src/core/mail/log/mail_log.service.d.ts +2 -2
  133. package/dist/src/core/mail/mail.enum.d.ts +2 -1
  134. package/dist/src/core/mail/mail.enum.js +1 -0
  135. package/dist/src/core/mail/mail.enum.js.map +1 -1
  136. package/dist/src/core/mail/mail.layout.d.ts +1 -1
  137. package/dist/src/core/mail/mail.schema.d.ts +1 -1
  138. package/dist/src/core/mail/mail.service.d.ts +1 -1
  139. package/dist/src/core/map_location/map_location.layout.d.ts +1 -1
  140. package/dist/src/core/map_location/map_location.schema.d.ts +1 -1
  141. package/dist/src/core/map_location/map_location.service.d.ts +2 -2
  142. package/dist/src/core/notification/log/log.layout.d.ts +1 -1
  143. package/dist/src/core/notification/log/log.schema.d.ts +1 -1
  144. package/dist/src/core/notification/log/log.service.d.ts +2 -2
  145. package/dist/src/core/notification/message/message.layout.d.ts +1 -1
  146. package/dist/src/core/notification/message/message.schema.d.ts +1 -1
  147. package/dist/src/core/notification/message/message.service.d.ts +8 -2
  148. package/dist/src/core/notification/message/message.service.js +23 -0
  149. package/dist/src/core/notification/message/message.service.js.map +1 -1
  150. package/dist/src/core/notification/message/message.workflow.d.ts +1 -1
  151. package/dist/src/core/notification/message_queue/message_queue.layout.d.ts +1 -1
  152. package/dist/src/core/notification/message_queue/message_queue.schema.d.ts +1 -1
  153. package/dist/src/core/notification/message_queue/message_queue.service.d.ts +2 -2
  154. package/dist/src/core/notification/subscription /subscription.layout.d.ts +1 -1
  155. package/dist/src/core/notification/subscription /subscription.schema.d.ts +1 -1
  156. package/dist/src/core/notification/subscription /subscription.service.d.ts +8 -2
  157. package/dist/src/core/notification/subscription /subscription.service.js +23 -0
  158. package/dist/src/core/notification/subscription /subscription.service.js.map +1 -1
  159. package/dist/src/core/pipeline/job/job.layout.d.ts +1 -1
  160. package/dist/src/core/pipeline/job/job.schema.d.ts +1 -1
  161. package/dist/src/core/pipeline/job/job.service.d.ts +1 -1
  162. package/dist/src/core/pipeline/log/log.layout.d.ts +1 -1
  163. package/dist/src/core/pipeline/log/log.schema.d.ts +1 -1
  164. package/dist/src/core/pipeline/log/log.service.d.ts +2 -2
  165. package/dist/src/core/pipeline/pipeline.layout.d.ts +1 -1
  166. package/dist/src/core/pipeline/pipeline.schema.d.ts +1 -1
  167. package/dist/src/core/pipeline/pipeline.service.d.ts +1 -1
  168. package/dist/src/core/reason/reason.layout.d.ts +1 -1
  169. package/dist/src/core/reason/reason.schema.d.ts +2 -2
  170. package/dist/src/core/reason/reason.service.d.ts +1 -1
  171. package/dist/src/core/schedule_action/log/schedule_log.layout.d.ts +1 -1
  172. package/dist/src/core/schedule_action/log/schedule_log.schema.d.ts +1 -1
  173. package/dist/src/core/schedule_action/log/schedule_log.service.d.ts +2 -2
  174. package/dist/src/core/schedule_action/schedule_action.layout.d.ts +1 -1
  175. package/dist/src/core/schedule_action/schedule_action.schema.d.ts +2 -2
  176. package/dist/src/core/schedule_action/schedule_action.service.d.ts +2 -2
  177. package/dist/src/core/search_text/search_text.service.js +40 -12
  178. package/dist/src/core/search_text/search_text.service.js.map +1 -1
  179. package/dist/src/core/setting/dto/menu_setting.dto.d.ts +1 -1
  180. package/dist/src/core/setting/setting.controller.d.ts +1 -1
  181. package/dist/src/core/setting/setting.schema.d.ts +1 -1
  182. package/dist/src/core/setting/setting.service.js +13 -3
  183. package/dist/src/core/setting/setting.service.js.map +1 -1
  184. package/dist/src/core/shortly/url/url.layout.d.ts +1 -1
  185. package/dist/src/core/shortly/url/url.schema.d.ts +1 -1
  186. package/dist/src/core/shortly/url/url.service.d.ts +2 -2
  187. package/dist/src/core/sms/log/sms_log.layout.d.ts +1 -1
  188. package/dist/src/core/sms/log/sms_log.service.d.ts +1 -1
  189. package/dist/src/core/sms/sms.layout.d.ts +1 -1
  190. package/dist/src/core/template/log/print_log.layout.d.ts +1 -1
  191. package/dist/src/core/template/log/print_log.schema.d.ts +2 -2
  192. package/dist/src/core/template/log/print_log.service.d.ts +2 -2
  193. package/dist/src/core/template/provider/base_template.provider.d.ts +1 -1
  194. package/dist/src/core/template/provider/base_template.provider.js +1 -1
  195. package/dist/src/core/template/provider/base_template.provider.js.map +1 -1
  196. package/dist/src/core/template/provider/email.provider.d.ts +2 -2
  197. package/dist/src/core/template/provider/sms.provider.d.ts +2 -2
  198. package/dist/src/core/template/provider/template.interface.d.ts +1 -1
  199. package/dist/src/core/template/provider/template_print.provider.d.ts +1 -1
  200. package/dist/src/core/template/provider/template_print.provider.js +6 -3
  201. package/dist/src/core/template/provider/template_print.provider.js.map +1 -1
  202. package/dist/src/core/template/template.controller.d.ts +1 -0
  203. package/dist/src/core/template/template.controller.js +12 -0
  204. package/dist/src/core/template/template.controller.js.map +1 -1
  205. package/dist/src/core/template/template.layout.d.ts +1 -1
  206. package/dist/src/core/template/template.schema.d.ts +2 -2
  207. package/dist/src/core/template/template.service.d.ts +3 -2
  208. package/dist/src/core/template/template.service.js +28 -6
  209. package/dist/src/core/template/template.service.js.map +1 -1
  210. package/dist/src/core/translate/translate.json +5 -1
  211. package/dist/src/core/translate/translate.layout.d.ts +1 -1
  212. package/dist/src/core/translate/translate.schema.d.ts +3 -3
  213. package/dist/src/core/translate/translate.service.d.ts +1 -1
  214. package/dist/src/core/users/user.constant.d.ts +1 -1
  215. package/dist/src/core/users/user.constant.js +1 -1
  216. package/dist/src/core/users/user.constant.js.map +1 -1
  217. package/dist/src/core/users/user.controller.d.ts +1 -0
  218. package/dist/src/core/users/user.controller.js +10 -0
  219. package/dist/src/core/users/user.controller.js.map +1 -1
  220. package/dist/src/core/users/user.enum.d.ts +2 -1
  221. package/dist/src/core/users/user.enum.js +1 -0
  222. package/dist/src/core/users/user.enum.js.map +1 -1
  223. package/dist/src/core/users/user.hook.d.ts +2 -0
  224. package/dist/src/core/users/user.hook.js +2 -1
  225. package/dist/src/core/users/user.hook.js.map +1 -1
  226. package/dist/src/core/users/user.layout.d.ts +1 -1
  227. package/dist/src/core/users/user.permission.d.ts +1 -1
  228. package/dist/src/core/users/user.schema.d.ts +4 -4
  229. package/dist/src/core/users/user.service.d.ts +5 -2
  230. package/dist/src/core/users/user.service.js +15 -0
  231. package/dist/src/core/users/user.service.js.map +1 -1
  232. package/dist/src/core/version_data/version_data.schema.d.ts +2 -2
  233. package/dist/src/core/version_data/version_data.service.d.ts +1 -1
  234. package/dist/src/core/widget/widget.schema.d.ts +2 -2
  235. package/dist/src/core/widget/widget.service.d.ts +1 -1
  236. package/dist/src/main.js +16 -0
  237. package/dist/src/main.js.map +1 -1
  238. package/dist/tsconfig.build.tsbuildinfo +1 -1
  239. package/package.json +4 -2
@@ -799,6 +799,7 @@ const saveRelatedFields = async (entity, reqHeaders, newData, oldData) => {
799
799
  };
800
800
  exports.saveRelatedFields = saveRelatedFields;
801
801
  const saveRelatedFieldsV2 = async (entity, reqHeaders, newData, oldData) => {
802
+ var _a;
802
803
  const relatedFields = listFieldByType(newData, entity, "related");
803
804
  for (const field of relatedFields) {
804
805
  const ignoreSaveRelated = _.get(reqHeaders, "ignore_save_related");
@@ -828,8 +829,19 @@ const saveRelatedFieldsV2 = async (entity, reqHeaders, newData, oldData) => {
828
829
  for (const data of field.data || []) {
829
830
  const isExists = (_.get(oldData, field.name) || [])
830
831
  .filter(j => j)
831
- .find(j => `${j._id || j.id}` === `${data._id || data.id}`);
832
- let id = data._id || data.id;
832
+ .find(j => {
833
+ var _a, _b;
834
+ let jId = j;
835
+ if (_.isPlainObject(j)) {
836
+ jId = j.id || ((_a = j._id) === null || _a === void 0 ? void 0 : _a.toString());
837
+ }
838
+ let dataId = data;
839
+ if (_.isPlainObject(data)) {
840
+ dataId = data.id || ((_b = data._id) === null || _b === void 0 ? void 0 : _b.toString());
841
+ }
842
+ return `${jId}` === `${dataId}`;
843
+ });
844
+ let id = data.id || ((_a = data._id) === null || _a === void 0 ? void 0 : _a.toString());
833
845
  if (id && !isExists) {
834
846
  ids.push(id);
835
847
  continue;
@@ -1579,7 +1591,7 @@ const hashEncryptFields = (entity, newData) => {
1579
1591
  };
1580
1592
  exports.hashEncryptFields = hashEncryptFields;
1581
1593
  const addActivityLog = async (entity, request, data, type, action, status, start_process_time, end_process_time, message, description, newData, oldData) => {
1582
- var _a;
1594
+ var _a, _b;
1583
1595
  if ((entity.name === "activity_log" ||
1584
1596
  _.get(request, "headers.ignore_activity_log") === "true") &&
1585
1597
  type !== activity_log_enum_1.ActivityLogType.workflow) {
@@ -1615,7 +1627,12 @@ const addActivityLog = async (entity, request, data, type, action, status, start
1615
1627
  log["diff"] = diff;
1616
1628
  }
1617
1629
  }
1618
- await callCreateInternalService("activity_log", log, _.get(request, "headers"));
1630
+ if (action === activity_log_enum_1.ActivityLogAction.deleted) {
1631
+ const uniqueFields = (_b = entity === null || entity === void 0 ? void 0 : entity.fields) === null || _b === void 0 ? void 0 : _b.filter(field => field.unique).map(field => field.name);
1632
+ const uniqueData = _.pick(data, uniqueFields);
1633
+ log['raw_data'] = JSON.stringify(uniqueData);
1634
+ }
1635
+ await callCreateInternalService("activity_log", log);
1619
1636
  return true;
1620
1637
  };
1621
1638
  exports.addActivityLog = addActivityLog;
@@ -1804,6 +1821,35 @@ const getCollectionName = (entity) => {
1804
1821
  return entity;
1805
1822
  }
1806
1823
  };
1824
+ const _getObjectIdCastingExpression = (field) => {
1825
+ return {
1826
+ $cond: [
1827
+ { $isArray: field },
1828
+ {
1829
+ $map: {
1830
+ input: field,
1831
+ as: "it",
1832
+ in: {
1833
+ $convert: {
1834
+ input: "$$it",
1835
+ to: "objectId",
1836
+ onError: "$$it",
1837
+ onNull: "$$it",
1838
+ },
1839
+ },
1840
+ },
1841
+ },
1842
+ {
1843
+ $convert: {
1844
+ input: field,
1845
+ to: "objectId",
1846
+ onError: field,
1847
+ onNull: field,
1848
+ },
1849
+ },
1850
+ ],
1851
+ };
1852
+ };
1807
1853
  const transformMediaPipeline = (fieldPath) => {
1808
1854
  const apiDomain = _.get(constants_1.CONST.MEDIA_SETTING, "api_domain");
1809
1855
  const provideCode = _.get(constants_1.CONST.MEDIA_SETTING, "provider");
@@ -2023,8 +2069,231 @@ const _normalizeField = (fields, currentPath = "", ignorePaths = []) => {
2023
2069
  }
2024
2070
  return normalizedFields;
2025
2071
  };
2026
- const buildNestedLookups = async (pipeline, relateFieldNames, entityName, requestedFieldNames = [], currentPath = "", level = 0, visitedEntities = new Set(), customPopulate = false, originalRequestedFieldNames = [], maxLevel = 1) => {
2072
+ const _buildOne2ManySubPipeline = async (entityName, requestedFieldNames, originalRequestedFieldNames, currentPath, level, visitedEntities, customPopulate, maxLevel) => {
2027
2073
  if (level > maxLevel)
2074
+ return [];
2075
+ const entity = await _loadEntity(entityName);
2076
+ if (!entity || !entity.fields)
2077
+ return [];
2078
+ const relatedFields = ["related", "image", "map", "file"];
2079
+ const needMapEntities = ["image", "map", "file"];
2080
+ const subPipeline = [];
2081
+ subPipeline.push({ $addFields: { id: { $toString: "$_id" } } });
2082
+ subPipeline.push({ $unset: ["_search_text"] });
2083
+ const availableFieldNames = entity.fields
2084
+ .filter(f => relatedFields.includes(f.type))
2085
+ .map(f => f.name);
2086
+ const fieldsToPopulate = customPopulate && requestedFieldNames.length > 0
2087
+ ? getFieldsToPopulate(availableFieldNames, requestedFieldNames)
2088
+ : availableFieldNames;
2089
+ const relateFields = entity.fields.filter(f => relatedFields.includes(f.type) &&
2090
+ (requestedFieldNames.length === 0 || fieldsToPopulate.includes(f.name)));
2091
+ for (const field of relateFields) {
2092
+ const fieldName = field.name;
2093
+ const targetEntityPath = `${currentPath}.${fieldName}.${field.related_ref}`;
2094
+ if (!needMapEntities.includes(field.type) &&
2095
+ visitedEntities.has(targetEntityPath)) {
2096
+ continue;
2097
+ }
2098
+ try {
2099
+ const collectionName = needMapEntities.includes(field.type)
2100
+ ? getCollectionName(mapEntity(field.type))
2101
+ : getCollectionName(field.related_ref);
2102
+ const relatedType = field.related_type || _.get(field, "options.related_type");
2103
+ const isRequestedSpecifically = !customPopulate ||
2104
+ requestedFieldNames.some(f => f === fieldName || f === `${fieldName}.*` || f.startsWith(`${fieldName}.`));
2105
+ if (!isRequestedSpecifically) {
2106
+ continue;
2107
+ }
2108
+ const hasMoreNestedRelationships = originalRequestedFieldNames.some(f => {
2109
+ const prefix = `${currentPath}.${fieldName}`;
2110
+ if (!f.startsWith(prefix + "."))
2111
+ return false;
2112
+ if (f === `${prefix}.*`)
2113
+ return false;
2114
+ const remaining = f.substring(prefix.length + 1);
2115
+ return remaining.includes(".");
2116
+ });
2117
+ if (relatedType === "one2many" && hasMoreNestedRelationships) {
2118
+ const newVisitedEntities = new Set(visitedEntities);
2119
+ newVisitedEntities.add(targetEntityPath);
2120
+ const subFieldNames = originalRequestedFieldNames
2121
+ .filter(f => f.startsWith(`${currentPath}.${fieldName}.`))
2122
+ .map(f => f.substring(`${currentPath}.${fieldName}.`.length));
2123
+ const nestedSubPipeline = await _buildOne2ManySubPipeline(field.related_ref, subFieldNames, originalRequestedFieldNames, `${currentPath}.${fieldName}`, level + 1, newVisitedEntities, customPopulate, maxLevel);
2124
+ subPipeline.push({
2125
+ $lookup: {
2126
+ from: collectionName,
2127
+ let: { local_ids: _getObjectIdCastingExpression(`$${fieldName}`) },
2128
+ pipeline: [
2129
+ {
2130
+ $match: {
2131
+ $expr: {
2132
+ $in: [
2133
+ "$_id",
2134
+ {
2135
+ $cond: [
2136
+ { $isArray: "$$local_ids" },
2137
+ "$$local_ids",
2138
+ { $cond: [{ $ne: ["$$local_ids", null] }, ["$$local_ids"], []] },
2139
+ ],
2140
+ },
2141
+ ],
2142
+ },
2143
+ },
2144
+ },
2145
+ ...nestedSubPipeline,
2146
+ ],
2147
+ as: fieldName,
2148
+ },
2149
+ });
2150
+ }
2151
+ else if (relatedType === "one2one") {
2152
+ subPipeline.push({
2153
+ $addFields: {
2154
+ [fieldName]: _getObjectIdCastingExpression(`$${fieldName}`),
2155
+ },
2156
+ });
2157
+ subPipeline.push({
2158
+ $lookup: {
2159
+ from: collectionName,
2160
+ localField: fieldName,
2161
+ foreignField: "_id",
2162
+ as: fieldName
2163
+ }
2164
+ });
2165
+ subPipeline.push({
2166
+ $addFields: { [fieldName]: { $arrayElemAt: [`$${fieldName}`, 0] } }
2167
+ });
2168
+ subPipeline.push({
2169
+ $addFields: {
2170
+ [fieldName]: {
2171
+ $cond: [
2172
+ { $ne: [{ $ifNull: [`$${fieldName}._id`, null] }, null] },
2173
+ { $mergeObjects: [`$${fieldName}`, { id: { $toString: `$${fieldName}._id` } }] },
2174
+ null
2175
+ ]
2176
+ }
2177
+ }
2178
+ });
2179
+ subPipeline.push({
2180
+ $addFields: {
2181
+ [fieldName]: {
2182
+ $cond: [
2183
+ { $ne: [`$${fieldName}`, null] },
2184
+ { $unsetField: { field: "_search_text", input: `$${fieldName}` } },
2185
+ null
2186
+ ]
2187
+ }
2188
+ }
2189
+ });
2190
+ }
2191
+ else {
2192
+ const fieldSubRequests = requestedFieldNames
2193
+ .filter(f => f.startsWith(`${fieldName}.`) && !f.endsWith(".*"))
2194
+ .map(f => f.substring(`${fieldName}.`.length));
2195
+ const hasEntityWildcard = requestedFieldNames.some(f => f === `${fieldName}.*`);
2196
+ const hasSpecificSubFields = fieldSubRequests.length > 0 && !hasEntityWildcard;
2197
+ if (hasSpecificSubFields) {
2198
+ const projectFields = { _id: 1 };
2199
+ for (const f of fieldSubRequests) {
2200
+ projectFields[f] = 1;
2201
+ }
2202
+ subPipeline.push({
2203
+ $lookup: {
2204
+ from: collectionName,
2205
+ let: { local_ids: _getObjectIdCastingExpression(`$${fieldName}`) },
2206
+ pipeline: [
2207
+ {
2208
+ $match: {
2209
+ $expr: {
2210
+ $in: [
2211
+ "$_id",
2212
+ {
2213
+ $cond: [
2214
+ { $isArray: "$$local_ids" },
2215
+ "$$local_ids",
2216
+ { $cond: [{ $ne: ["$$local_ids", null] }, ["$$local_ids"], []] },
2217
+ ],
2218
+ },
2219
+ ],
2220
+ },
2221
+ },
2222
+ },
2223
+ { $addFields: { id: { $toString: "$_id" } } },
2224
+ { $unset: ["_search_text"] },
2225
+ { $project: Object.assign(Object.assign({}, projectFields), { id: 1 }) },
2226
+ ],
2227
+ as: fieldName,
2228
+ },
2229
+ });
2230
+ }
2231
+ else {
2232
+ subPipeline.push({
2233
+ $addFields: {
2234
+ [fieldName]: _getObjectIdCastingExpression(`$${fieldName}`),
2235
+ },
2236
+ });
2237
+ subPipeline.push({
2238
+ $lookup: {
2239
+ from: collectionName,
2240
+ localField: fieldName,
2241
+ foreignField: "_id",
2242
+ as: fieldName
2243
+ }
2244
+ });
2245
+ subPipeline.push({
2246
+ $addFields: {
2247
+ [fieldName]: {
2248
+ $map: {
2249
+ input: `$${fieldName}`,
2250
+ as: "item",
2251
+ in: { $mergeObjects: ["$$item", { id: { $toString: "$$item._id" } }] }
2252
+ }
2253
+ }
2254
+ }
2255
+ });
2256
+ subPipeline.push({
2257
+ $addFields: {
2258
+ [fieldName]: {
2259
+ $map: {
2260
+ input: `$${fieldName}`,
2261
+ as: "item",
2262
+ in: { $unsetField: { field: "_search_text", input: "$$item" } }
2263
+ }
2264
+ }
2265
+ }
2266
+ });
2267
+ }
2268
+ }
2269
+ }
2270
+ catch (error) {
2271
+ console.error(`Could not load related entity (sub-pipeline): ${field.related_ref} at level ${level}`);
2272
+ }
2273
+ }
2274
+ const hasWildcardAtThisLevel = requestedFieldNames.includes("*") ||
2275
+ requestedFieldNames.some(f => f === "*" || f.startsWith("*."));
2276
+ if (!hasWildcardAtThisLevel && requestedFieldNames.length > 0) {
2277
+ const topLevelFields = [
2278
+ ...new Set(requestedFieldNames
2279
+ .map(f => f.split(".")[0])
2280
+ .filter(f => f && f !== "*"))
2281
+ ];
2282
+ if (topLevelFields.length > 0) {
2283
+ const projectStage = {
2284
+ $project: { _id: 1, id: 1 }
2285
+ };
2286
+ for (const f of topLevelFields) {
2287
+ projectStage.$project[f] = 1;
2288
+ }
2289
+ subPipeline.push(projectStage);
2290
+ }
2291
+ }
2292
+ return subPipeline;
2293
+ };
2294
+ const buildNestedLookups = async (pipeline, relateFieldNames, entityName, requestedFieldNames = [], currentPath = "", level = 0, visitedEntities = new Set(), customPopulate = false, originalRequestedFieldNames = [], maxLevel = 1) => {
2295
+ const finalizedMaxLevel = (requestedFieldNames.length > 0 || !customPopulate) ? maxLevel : 1;
2296
+ if (level >= finalizedMaxLevel)
2028
2297
  return;
2029
2298
  const entity = await _loadEntity(entityName);
2030
2299
  if (!entity || !entity.fields)
@@ -2053,15 +2322,78 @@ const buildNestedLookups = async (pipeline, relateFieldNames, entityName, reques
2053
2322
  const collectionName = needMapEntities.includes(field.type)
2054
2323
  ? getCollectionName(mapEntity(field.type))
2055
2324
  : getCollectionName(field.related_ref);
2325
+ const relatedType = field.related_type || _.get(field, "options.related_type");
2326
+ const currentFieldPrefix = currentPath
2327
+ ? `${currentPath}.${field.name}`
2328
+ : field.name;
2329
+ const hasMoreNestedRelationships = originalRequestedFieldNames.some(f => {
2330
+ if (!f.startsWith(currentFieldPrefix + "."))
2331
+ return false;
2332
+ if (f === `${currentFieldPrefix}.*`)
2333
+ return false;
2334
+ const remaining = f.substring(currentFieldPrefix.length + 1);
2335
+ return remaining.includes(".");
2336
+ });
2337
+ if (relatedType === "one2many" && hasMoreNestedRelationships) {
2338
+ const newVisitedEntities = new Set(visitedEntities);
2339
+ newVisitedEntities.add(targetEntityPath);
2340
+ const subFieldNames = originalRequestedFieldNames
2341
+ .filter(f => f.startsWith(currentFieldPrefix + "."))
2342
+ .map(f => f.substring(currentFieldPrefix.length + 1));
2343
+ const clonedOriginalRequestedFieldNames = _.cloneDeep(originalRequestedFieldNames);
2344
+ const subPipeline = await _buildOne2ManySubPipeline(field.related_ref, subFieldNames, clonedOriginalRequestedFieldNames, currentFieldPrefix, level + 1, newVisitedEntities, customPopulate, maxLevel);
2345
+ pipeline.push({
2346
+ $lookup: {
2347
+ from: collectionName,
2348
+ let: { local_ids: _getObjectIdCastingExpression(`$${fieldPath}`) },
2349
+ pipeline: [
2350
+ {
2351
+ $match: {
2352
+ $expr: {
2353
+ $in: [
2354
+ "$_id",
2355
+ {
2356
+ $cond: [
2357
+ { $isArray: "$$local_ids" },
2358
+ "$$local_ids",
2359
+ { $cond: [{ $ne: ["$$local_ids", null] }, ["$$local_ids"], []] },
2360
+ ],
2361
+ },
2362
+ ],
2363
+ },
2364
+ },
2365
+ },
2366
+ ...subPipeline,
2367
+ ],
2368
+ as: fieldPath,
2369
+ },
2370
+ });
2371
+ continue;
2372
+ }
2373
+ const lookupAlias = fieldPath.includes(".")
2374
+ ? `__tmp_${fieldPath.replace(/\./g, "__")}`
2375
+ : fieldPath;
2376
+ pipeline.push({
2377
+ $addFields: {
2378
+ [fieldPath]: _getObjectIdCastingExpression(`$${fieldPath}`),
2379
+ },
2380
+ });
2056
2381
  pipeline.push({
2057
2382
  $lookup: {
2058
2383
  from: collectionName,
2059
2384
  localField: fieldPath,
2060
2385
  foreignField: "_id",
2061
- as: fieldPath
2386
+ as: lookupAlias
2062
2387
  }
2063
2388
  });
2064
- const relatedType = field.related_type || _.get(field, "options.related_type");
2389
+ if (lookupAlias !== fieldPath) {
2390
+ pipeline.push({
2391
+ $addFields: { [fieldPath]: `$${lookupAlias}` }
2392
+ });
2393
+ pipeline.push({
2394
+ $unset: lookupAlias
2395
+ });
2396
+ }
2065
2397
  if (relatedType === "one2one") {
2066
2398
  pipeline.push({
2067
2399
  $addFields: { [fieldPath]: { $arrayElemAt: [`$${fieldPath}`, 0] } }
@@ -2072,58 +2404,43 @@ const buildNestedLookups = async (pipeline, relateFieldNames, entityName, reques
2072
2404
  pipeline.push(...transformStage);
2073
2405
  continue;
2074
2406
  }
2075
- const nestedFieldsForThisField = requestedFieldNames.filter(f => f.startsWith(`${fieldPath}.`) && f !== `${fieldPath}.*`);
2076
- const hasNestedProjection = nestedFieldsForThisField.length > 0;
2077
- const nextLevelFields = hasNestedProjection
2078
- ? nestedFieldsForThisField
2079
- .map(f => f.substring(fieldPath.length + 1))
2080
- .map(f => f.split(".")[0])
2081
- .filter((f, i, arr) => arr.indexOf(f) === i)
2082
- : [];
2083
- const directFields = requestedFieldNames
2084
- .filter(f => !f.includes(".") || f.split(".").length === 1)
2085
- .filter(f => f !== "*");
2086
- const nestedFields = [];
2087
- for (const field of requestedFieldNames) {
2088
- if (field.includes(".") && !field.endsWith(".*")) {
2089
- const parts = field.split(".");
2090
- if (hasNestedProjection) {
2091
- for (const part of parts) {
2092
- if (part !== "*") {
2093
- nestedFields.push(part);
2094
- }
2095
- }
2096
- }
2097
- else {
2098
- const lastPart = parts[parts.length - 1];
2099
- if (lastPart !== "*") {
2100
- nestedFields.push(lastPart);
2101
- }
2102
- }
2103
- }
2407
+ const isWildcardActive = requestedFieldNames.includes("*") || (fieldPath && requestedFieldNames.includes(`${fieldPath}.*`));
2408
+ const subRequestedFields = requestedFieldNames
2409
+ .filter(f => f === field.name || f.startsWith(`${field.name}.`))
2410
+ .map(f => f === field.name ? "*" : f.substring(field.name.length + 1));
2411
+ if (isWildcardActive && !subRequestedFields.includes("*")) {
2412
+ subRequestedFields.push("*");
2104
2413
  }
2105
- const levelSpecificFields = [...directFields, ...nestedFields].filter((f, i, arr) => arr.indexOf(f) === i);
2106
- const hasWildcard = requestedFieldNames.includes("*") ||
2107
- requestedFieldNames.some(f => f.endsWith(".*"));
2414
+ const nestedAbsolute = requestedFieldNames.filter(f => f.startsWith(`${fieldPath}.`) && f !== `${fieldPath}.*`);
2415
+ const hasWildcard = subRequestedFields.includes("*") || isWildcardActive;
2108
2416
  let allowedFields = null;
2109
2417
  if (hasWildcard) {
2110
2418
  allowedFields = null;
2111
2419
  }
2112
- else if (hasNestedProjection || levelSpecificFields.length > 0) {
2113
- if (hasNestedProjection) {
2114
- allowedFields = [...nextLevelFields, ...levelSpecificFields];
2115
- }
2116
- else {
2117
- allowedFields = [...levelSpecificFields];
2420
+ else {
2421
+ const nextLevelFromRelative = subRequestedFields
2422
+ .filter(f => f.includes("."))
2423
+ .map(f => f.split(".")[0]);
2424
+ const nextLevelFromAbsolute = nestedAbsolute
2425
+ .map(f => f.substring(fieldPath.length + 1).split(".")[0]);
2426
+ const directFromRelative = subRequestedFields.filter(f => !f.includes(".") && f !== "*");
2427
+ const combinedFields = [...nextLevelFromRelative, ...nextLevelFromAbsolute, ...directFromRelative];
2428
+ const uniqueFields = combinedFields.filter((f, i, arr) => f && arr.indexOf(f) === i).sort();
2429
+ if (uniqueFields.length > 0) {
2430
+ allowedFields = ["_id", ...uniqueFields];
2118
2431
  }
2119
- allowedFields = ["_id", ...allowedFields];
2120
2432
  }
2121
2433
  if (relatedType === "one2one") {
2122
2434
  pipeline.push({
2123
2435
  $addFields: {
2124
2436
  [fieldPath]: {
2125
2437
  $cond: [
2126
- { $ne: [{ $ifNull: [`$${fieldPath}._id`, null] }, null] },
2438
+ {
2439
+ $and: [
2440
+ { $ne: [{ $type: `$${fieldPath}` }, "missing"] },
2441
+ { $ne: [`$${fieldPath}`, null] }
2442
+ ]
2443
+ },
2127
2444
  allowedFields !== null
2128
2445
  ? {
2129
2446
  $mergeObjects: [
@@ -2198,19 +2515,7 @@ const buildNestedLookups = async (pipeline, relateFieldNames, entityName, reques
2198
2515
  }
2199
2516
  });
2200
2517
  }
2201
- const currentFieldPrefix = currentPath
2202
- ? `${currentPath}.${field.name}`
2203
- : field.name;
2204
- const hasMoreNestedRelationships = originalRequestedFieldNames.some(f => {
2205
- if (!f.startsWith(currentFieldPrefix + "."))
2206
- return false;
2207
- if (f === `${currentFieldPrefix}.*`)
2208
- return false;
2209
- const remaining = f.substring(currentFieldPrefix.length + 1);
2210
- const result = remaining.includes(".");
2211
- return result;
2212
- });
2213
- if (hasMoreNestedRelationships) {
2518
+ if (relatedType === "one2one" && hasMoreNestedRelationships) {
2214
2519
  const newVisitedEntities = new Set(visitedEntities);
2215
2520
  newVisitedEntities.add(targetEntityPath);
2216
2521
  const subFieldNames = originalRequestedFieldNames
@@ -2313,50 +2618,101 @@ const buildPopulate = async (doc, entityName, fields) => {
2313
2618
  }
2314
2619
  };
2315
2620
  exports.buildPopulate = buildPopulate;
2621
+ const _splitFilter = (query) => {
2622
+ const local = {};
2623
+ const nested = {};
2624
+ if (!_.isObject(query) || _.isArray(query))
2625
+ return { local: query, nested: {} };
2626
+ for (const key of Object.keys(query)) {
2627
+ if (key.startsWith("$") && ["$and", "$or", "$nor"].includes(key) && Array.isArray(query[key])) {
2628
+ const localParts = [], nestedParts = [];
2629
+ for (const part of query[key]) {
2630
+ const { local: lp, nested: np } = _splitFilter(part);
2631
+ if (!_.isEmpty(lp))
2632
+ localParts.push(lp);
2633
+ if (!_.isEmpty(np))
2634
+ nestedParts.push(np);
2635
+ }
2636
+ if (localParts.length > 0)
2637
+ local[key] = localParts;
2638
+ if (nestedParts.length > 0)
2639
+ nested[key] = nestedParts;
2640
+ }
2641
+ else if (key.includes(".")) {
2642
+ nested[key] = query[key];
2643
+ }
2644
+ else {
2645
+ local[key] = query[key];
2646
+ }
2647
+ }
2648
+ return { local, nested };
2649
+ };
2316
2650
  const buildAggregate = async (aggregate, entityName, fields, page = 1, pageSize = 10000, sort = "") => {
2317
2651
  let cloneAggregate = _.cloneDeep(aggregate);
2318
2652
  const customPopulate = _.isArray(fields) && fields.length > 0 && _.isString(fields[0]);
2319
2653
  if (_.isPlainObject(cloneAggregate)) {
2320
2654
  cloneAggregate = [cloneAggregate];
2321
2655
  }
2656
+ const entity = await _loadEntity(entityName);
2657
+ const nestedStages = [];
2658
+ const nestedFilterFields = new Set();
2659
+ if (Array.isArray(cloneAggregate)) {
2660
+ for (let i = 0; i < cloneAggregate.length; i++) {
2661
+ const stage = cloneAggregate[i];
2662
+ if (stage === null || stage === void 0 ? void 0 : stage.$match) {
2663
+ if (entity && entity.fields) {
2664
+ stage.$match = (0, build_search_1.convertQueryValues)(stage.$match, entity.fields);
2665
+ }
2666
+ const { local, nested } = _splitFilter(stage.$match);
2667
+ if (!_.isEmpty(nested)) {
2668
+ nestedStages.push({ $match: nested });
2669
+ Object.keys(nested).forEach(k => {
2670
+ const root = k.split('.')[0];
2671
+ nestedFilterFields.add(root);
2672
+ });
2673
+ if (_.isEmpty(local)) {
2674
+ cloneAggregate.splice(i, 1);
2675
+ i--;
2676
+ }
2677
+ else {
2678
+ cloneAggregate[i] = { $match: local };
2679
+ }
2680
+ }
2681
+ }
2682
+ }
2683
+ }
2322
2684
  let normalizedFields = [];
2323
2685
  let includedFields = [];
2324
2686
  let excludedFields = [];
2687
+ let maxLevel = 1;
2325
2688
  if (typeof fields === "string") {
2326
- const fieldList = fields.split(",").map(name => name.trim());
2689
+ const fieldList = (fields || "").split(",").map(name => name.trim()).filter(f => !_.isEmpty(f));
2327
2690
  normalizedFields = fieldList.map(name => ({ name }));
2328
2691
  includedFields = fieldList.filter(f => !f.startsWith("-"));
2329
- excludedFields = fieldList
2330
- .filter(f => f.startsWith("-"))
2331
- .map(f => f.substring(1));
2692
+ excludedFields = fieldList.filter(f => f.startsWith("-")).map(f => f.substring(1));
2332
2693
  }
2333
2694
  else if (Array.isArray(fields)) {
2334
2695
  if (fields.length > 0 && typeof fields[0] === "string") {
2335
- const trimmedFields = fields.map(name => name.trim());
2336
- normalizedFields = trimmedFields.map(name => ({ name }));
2337
- includedFields = trimmedFields.filter(f => !f.startsWith("-"));
2338
- excludedFields = trimmedFields
2339
- .filter(f => f.startsWith("-"))
2340
- .map(f => f.substring(1));
2696
+ const fieldList = fields.map(name => name.trim()).filter(f => !_.isEmpty(f));
2697
+ normalizedFields = fieldList.map(name => ({ name }));
2698
+ includedFields = fieldList.filter(f => !f.startsWith("-"));
2699
+ excludedFields = fieldList.filter(f => f.startsWith("-")).map(f => f.substring(1));
2341
2700
  }
2342
2701
  else {
2343
2702
  normalizedFields = fields;
2703
+ includedFields = fields.map(f => f.name).filter(f => !f.startsWith("-"));
2704
+ excludedFields = fields.map(f => f.name).filter(f => f.startsWith("-")).map(f => f.substring(1));
2344
2705
  }
2345
2706
  }
2346
- if (sort) {
2347
- cloneAggregate.push({
2348
- $sort: (0, build_search_1.buildSort)(sort)
2349
- });
2350
- }
2351
- if (page > 0) {
2352
- cloneAggregate.push({
2353
- $skip: page
2354
- });
2355
- }
2356
- if (pageSize > 0) {
2357
- cloneAggregate.push({
2358
- $limit: pageSize
2707
+ if (includedFields.length > 0) {
2708
+ let dynamicMaxLevel = 1;
2709
+ includedFields.forEach(f => {
2710
+ const depth = (f.match(/\./g) || []).length + 1;
2711
+ if (depth > dynamicMaxLevel) {
2712
+ dynamicMaxLevel = depth;
2713
+ }
2359
2714
  });
2715
+ maxLevel = dynamicMaxLevel;
2360
2716
  }
2361
2717
  let project = {};
2362
2718
  if (!_.isEmpty(normalizedFields)) {
@@ -2374,7 +2730,7 @@ const buildAggregate = async (aggregate, entityName, fields, page = 1, pageSize
2374
2730
  else if (includedFields.length > 0) {
2375
2731
  fieldsToProject = allAvailableFields.filter(field => includedFields.some(pattern => pattern === field ||
2376
2732
  (pattern.endsWith(".*") && field === pattern.slice(0, -2)) ||
2377
- field.startsWith(pattern.replace(".*", "."))));
2733
+ pattern.startsWith(field + ".")));
2378
2734
  }
2379
2735
  else {
2380
2736
  fieldsToProject = allAvailableFields;
@@ -2408,10 +2764,7 @@ const buildAggregate = async (aggregate, entityName, fields, page = 1, pageSize
2408
2764
  project = projectSelected;
2409
2765
  }
2410
2766
  }
2411
- const entity = await _loadEntity(entityName);
2412
2767
  if (entity && entity.fields) {
2413
- const entityNormalizedFields = _normalizeField(entity.fields, "");
2414
- cloneAggregate.push(...entityNormalizedFields);
2415
2768
  const initialVisitedEntities = new Set();
2416
2769
  initialVisitedEntities.add(entityName);
2417
2770
  const relateFieldNames = [];
@@ -2429,9 +2782,38 @@ const buildAggregate = async (aggregate, entityName, fields, page = 1, pageSize
2429
2782
  else {
2430
2783
  requestedFieldNames = [];
2431
2784
  }
2785
+ nestedFilterFields.forEach(root => {
2786
+ const rootExists = requestedFieldNames.some(f => {
2787
+ const fRoot = f.split('.')[0].replace(/^_keepPopulate\((.*)\)$/, '$1');
2788
+ return fRoot === root;
2789
+ });
2790
+ if (!rootExists) {
2791
+ requestedFieldNames.push(root);
2792
+ }
2793
+ });
2432
2794
  const maxLevel = _.max(requestedFieldNames.map(f => f.split(".").length - 1)) || 1;
2433
2795
  const originalRequestedFieldNames = _.cloneDeep(requestedFieldNames);
2796
+ const canDoEarlyPagination = _.isEmpty(nestedStages);
2797
+ if (canDoEarlyPagination) {
2798
+ if (sort)
2799
+ cloneAggregate.push({ $sort: (0, build_search_1.buildSort)(sort) });
2800
+ if (page > 0)
2801
+ cloneAggregate.push({ $skip: page });
2802
+ if (pageSize > 0)
2803
+ cloneAggregate.push({ $limit: pageSize });
2804
+ }
2434
2805
  await buildNestedLookups(cloneAggregate, relateFieldNames, entityName, requestedFieldNames, "", 0, initialVisitedEntities, customPopulate, originalRequestedFieldNames, maxLevel);
2806
+ if (!_.isEmpty(nestedStages)) {
2807
+ cloneAggregate.push(...nestedStages);
2808
+ }
2809
+ if (!canDoEarlyPagination) {
2810
+ if (sort)
2811
+ cloneAggregate.push({ $sort: (0, build_search_1.buildSort)(sort) });
2812
+ if (page > 0)
2813
+ cloneAggregate.push({ $skip: page });
2814
+ if (pageSize > 0)
2815
+ cloneAggregate.push({ $limit: pageSize });
2816
+ }
2435
2817
  if (project && typeof project === "object" && "$project" in project) {
2436
2818
  const projectStage = project;
2437
2819
  const filteredRelateFieldNames = relateFieldNames.filter(fieldPath => {
@@ -2450,6 +2832,19 @@ const buildAggregate = async (aggregate, entityName, fields, page = 1, pageSize
2450
2832
  projectStage.$project[fieldPath] = 1;
2451
2833
  }
2452
2834
  });
2835
+ includedFields.forEach(f => {
2836
+ if (f.includes(".") && !f.endsWith(".*")) {
2837
+ const rootField = f.split(".")[0];
2838
+ const hasParentProjected = Object.keys(projectStage.$project).some(existingPath => {
2839
+ return f.startsWith(existingPath + ".");
2840
+ });
2841
+ if (!hasParentProjected && projectStage.$project[rootField] === undefined) {
2842
+ projectStage.$project[f] = 1;
2843
+ projectStage.$project[`${rootField}._id`] = 1;
2844
+ projectStage.$project[`${rootField}.id`] = 1;
2845
+ }
2846
+ }
2847
+ });
2453
2848
  }
2454
2849
  }
2455
2850
  if (entityName === "attachment") {