@tech4good/angular-schematics 21.5.0 → 21.7.0

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 (273) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/README.md +266 -1
  3. package/package.json +34 -7
  4. package/src/component/files/__name@dasherize__/__name@dasherize__.component.spec.ts.template +4 -5
  5. package/src/component/files/__name@dasherize__/__name@dasherize__.component.ts.template +1 -1
  6. package/src/entity/files/__name@dasherize__/__name@dasherize__.mock.ts.template +16 -7
  7. package/src/entity/files/__name@dasherize__/__name@dasherize__.model.ts.template +13 -6
  8. package/src/entity/files/__name@dasherize__/__name@dasherize__.store.ts.template +18 -10
  9. package/src/entity/index.js +61 -49
  10. package/src/entity/index.js.map +1 -1
  11. package/src/entity/schema.json +4 -0
  12. package/src/guard/files/__name@dasherize__.guard.spec.ts.template +0 -1
  13. package/src/ng-add/files/.github/workflows/angular-github-ci.yml.template +3 -0
  14. package/src/ng-add/files/.gitignore.template +5 -0
  15. package/src/ng-add/files/analytics/datasets.js.template +206 -0
  16. package/src/ng-add/files/analytics/entity_sources.js.template +58 -0
  17. package/src/ng-add/files/analytics/entity_sources.test.js.template +57 -0
  18. package/src/ng-add/files/analytics/lib/api_query.js.template +87 -0
  19. package/src/ng-add/files/analytics/lib/api_query.test.js.template +84 -0
  20. package/src/ng-add/files/analytics/lib/bigquery_query_compatibility.test.js.template +53 -0
  21. package/src/ng-add/files/analytics/lib/dataset_schema.js.template +53 -0
  22. package/src/ng-add/files/analytics/lib/dataset_schema.test.js.template +34 -0
  23. package/src/ng-add/files/analytics/lib/entity_sync.js.template +397 -0
  24. package/src/ng-add/files/analytics/lib/entity_sync.test.js.template +212 -0
  25. package/src/ng-add/files/analytics/lib/identifier_salt.js.template +57 -0
  26. package/src/ng-add/files/analytics/lib/identifier_salt.test.js.template +36 -0
  27. package/src/ng-add/files/analytics/lib/snapshot_files.js.template +46 -0
  28. package/src/ng-add/files/analytics/lib/snapshot_files.test.js.template +67 -0
  29. package/src/ng-add/files/analytics/lib/sqlite.js.template +92 -0
  30. package/src/ng-add/files/analytics/lib/upload_entities.js.template +81 -0
  31. package/src/ng-add/files/analytics/lib/upload_entities.test.js.template +86 -0
  32. package/src/ng-add/files/analytics/proxy.conf.json.template +7 -0
  33. package/src/ng-add/files/analytics/scripts/refresh_snapshot.js.template +518 -0
  34. package/src/ng-add/files/analytics/scripts/start.js.template +88 -0
  35. package/src/ng-add/files/analytics/server/server.js.template +212 -0
  36. package/src/ng-add/files/angular.json.template +80 -1
  37. package/src/ng-add/files/bigquery/queries/active_time_by_route.sql.template +27 -8
  38. package/src/ng-add/files/bigquery/queries/active_user_windows.sql.template +67 -0
  39. package/src/ng-add/files/bigquery/queries/dashboard_route_visits.sql.template +47 -0
  40. package/src/ng-add/files/bigquery/queries/data_quality.sql.template +323 -0
  41. package/src/ng-add/files/bigquery/queries/onboarding_funnel.sql.template +512 -0
  42. package/src/ng-add/files/bigquery/queries/onboarding_stage_observations.sql.template +134 -0
  43. package/src/ng-add/files/bigquery/queries/weekly_retention_cohorts.sql.template +90 -0
  44. package/src/ng-add/files/bigquery/scripts/export_entities.js.template +120 -0
  45. package/src/ng-add/files/bigquery/scripts/init_views.js.template +57 -0
  46. package/src/ng-add/files/bigquery/scripts/run_query.js.template +141 -0
  47. package/src/ng-add/files/bigquery/views/events_flat.sql.template +27 -12
  48. package/src/ng-add/files/bigquery/views/logs_latest.sql.template +16 -3
  49. package/src/ng-add/files/docs-infra/analytics-guide.md.template +270 -25
  50. package/src/ng-add/files/docs-infra/analytics-workbench-guide.md.template +307 -0
  51. package/src/ng-add/files/docs-infra/authentication-architecture.md.template +300 -0
  52. package/src/ng-add/files/docs-infra/email-infrastructure.md.template +43 -0
  53. package/src/ng-add/files/docs-infra/firestore-index-checker.md.template +87 -0
  54. package/src/ng-add/files/docs-infra/infrastructure-guide.md.template +123 -38
  55. package/src/ng-add/files/docs-infra/load-system-architecture.md.template +15 -1
  56. package/src/ng-add/files/docs-infra/querying-strategy.md.template +14 -0
  57. package/src/ng-add/files/docs-infra/stream-system-architecture.md.template +21 -7
  58. package/src/ng-add/files/eslint.config.js.template +22 -3
  59. package/src/ng-add/files/firebase.json.template +6 -0
  60. package/src/ng-add/files/firestore.indexes.json.template +23 -0
  61. package/src/ng-add/files/firestore.rules.spec.ts.template +84 -15
  62. package/src/ng-add/files/firestore.rules.template +29 -17
  63. package/src/ng-add/files/functions/.gitignore.template +3 -0
  64. package/src/ng-add/files/functions/package.json.template +13 -0
  65. package/src/ng-add/files/functions/src/email.ts.template +23 -0
  66. package/src/ng-add/files/functions/src/index.ts.template +44 -0
  67. package/src/ng-add/files/functions/tsconfig.json.template +13 -0
  68. package/src/ng-add/files/jest.config.ts.template +3 -2
  69. package/src/ng-add/files/package.json.template +41 -16
  70. package/src/ng-add/files/projects/analytics/src/app/analytics-api.service.ts.template +130 -0
  71. package/src/ng-add/files/projects/analytics/src/app/app.component.html.template +77 -0
  72. package/src/ng-add/files/projects/analytics/src/app/app.component.scss.template +240 -0
  73. package/src/ng-add/files/projects/analytics/src/app/app.component.ts.template +96 -0
  74. package/src/ng-add/files/projects/analytics/src/app/app.routes.ts.template +11 -0
  75. package/src/ng-add/files/projects/analytics/src/app/dashboard-pages.spec.ts.template +151 -0
  76. package/src/ng-add/files/projects/analytics/src/app/data-quality/data-quality-page/data-quality-page.component.html.template +39 -0
  77. package/src/ng-add/files/projects/analytics/src/app/data-quality/data-quality-page/data-quality-page.component.scss.template +1 -0
  78. package/src/ng-add/files/projects/analytics/src/app/data-quality/data-quality-page/data-quality-page.component.ts.template +95 -0
  79. package/src/ng-add/files/projects/analytics/src/app/engagement/engagement-page/engagement-page.component.html.template +47 -0
  80. package/src/ng-add/files/projects/analytics/src/app/engagement/engagement-page/engagement-page.component.scss.template +1 -0
  81. package/src/ng-add/files/projects/analytics/src/app/engagement/engagement-page/engagement-page.component.ts.template +120 -0
  82. package/src/ng-add/files/projects/analytics/src/app/onboarding/onboarding-page/onboarding-page.component.html.template +40 -0
  83. package/src/ng-add/files/projects/analytics/src/app/onboarding/onboarding-page/onboarding-page.component.scss.template +1 -0
  84. package/src/ng-add/files/projects/analytics/src/app/onboarding/onboarding-page/onboarding-page.component.ts.template +98 -0
  85. package/src/ng-add/files/projects/analytics/src/app/overview/overview-page/overview-page.component.html.template +35 -0
  86. package/src/ng-add/files/projects/analytics/src/app/overview/overview-page/overview-page.component.scss.template +1 -0
  87. package/src/ng-add/files/projects/analytics/src/app/overview/overview-page/overview-page.component.ts.template +84 -0
  88. package/src/ng-add/files/projects/analytics/src/app/routes/routes-page/routes-page.component.html.template +42 -0
  89. package/src/ng-add/files/projects/analytics/src/app/routes/routes-page/routes-page.component.scss.template +1 -0
  90. package/src/ng-add/files/projects/analytics/src/app/routes/routes-page/routes-page.component.ts.template +110 -0
  91. package/src/ng-add/files/projects/analytics/src/app/shared/analytics-utils.ts.template +43 -0
  92. package/src/ng-add/files/projects/analytics/src/app/shared/chart-theme.ts.template +42 -0
  93. package/src/ng-add/files/projects/analytics/src/app/shared/dashboard-layout.scss.template +239 -0
  94. package/src/ng-add/files/projects/analytics/src/app/shared/dashboard-table/dashboard-table.component.html.template +76 -0
  95. package/src/ng-add/files/projects/analytics/src/app/shared/dashboard-table/dashboard-table.component.scss.template +128 -0
  96. package/src/ng-add/files/projects/analytics/src/app/shared/dashboard-table/dashboard-table.component.spec.ts.template +31 -0
  97. package/src/ng-add/files/projects/analytics/src/app/shared/dashboard-table/dashboard-table.component.ts.template +153 -0
  98. package/src/ng-add/files/projects/analytics/src/app/shared/funnel-chart/funnel-chart.component.html.template +16 -0
  99. package/src/ng-add/files/projects/analytics/src/app/shared/funnel-chart/funnel-chart.component.scss.template +63 -0
  100. package/src/ng-add/files/projects/analytics/src/app/shared/funnel-chart/funnel-chart.component.ts.template +52 -0
  101. package/src/ng-add/files/projects/analytics/src/app/shared/metric-card/metric-card.component.html.template +5 -0
  102. package/src/ng-add/files/projects/analytics/src/app/shared/metric-card/metric-card.component.scss.template +56 -0
  103. package/src/ng-add/files/projects/analytics/src/app/shared/metric-card/metric-card.component.spec.ts.template +30 -0
  104. package/src/ng-add/files/projects/analytics/src/app/shared/metric-card/metric-card.component.ts.template +15 -0
  105. package/src/ng-add/files/projects/analytics/src/app/shared/quality-chart/quality-chart.component.html.template +9 -0
  106. package/src/ng-add/files/projects/analytics/src/app/shared/quality-chart/quality-chart.component.scss.template +43 -0
  107. package/src/ng-add/files/projects/analytics/src/app/shared/quality-chart/quality-chart.component.ts.template +62 -0
  108. package/src/ng-add/files/projects/analytics/src/app/shared/route-distribution-chart/route-distribution-chart.component.html.template +9 -0
  109. package/src/ng-add/files/projects/analytics/src/app/shared/route-distribution-chart/route-distribution-chart.component.scss.template +33 -0
  110. package/src/ng-add/files/projects/analytics/src/app/shared/route-distribution-chart/route-distribution-chart.component.ts.template +82 -0
  111. package/src/ng-add/files/projects/analytics/src/app/shared/route-traffic-chart/route-traffic-chart.component.html.template +15 -0
  112. package/src/ng-add/files/projects/analytics/src/app/shared/route-traffic-chart/route-traffic-chart.component.scss.template +45 -0
  113. package/src/ng-add/files/projects/analytics/src/app/shared/route-traffic-chart/route-traffic-chart.component.ts.template +55 -0
  114. package/src/ng-add/files/projects/analytics/src/app/shared/status-message/status-message.component.html.template +18 -0
  115. package/src/ng-add/files/projects/analytics/src/app/shared/status-message/status-message.component.scss.template +45 -0
  116. package/src/ng-add/files/projects/analytics/src/app/shared/status-message/status-message.component.ts.template +15 -0
  117. package/src/ng-add/files/projects/analytics/src/app/vega-chart/vega-chart.component.ts.template +121 -0
  118. package/src/ng-add/files/projects/analytics/src/index.html.template +19 -0
  119. package/src/ng-add/files/projects/analytics/src/main.ts.template +16 -0
  120. package/src/ng-add/files/projects/analytics/src/styles.scss.template +28 -0
  121. package/src/ng-add/files/projects/analytics/tsconfig.app.json.template +13 -0
  122. package/src/ng-add/files/projects/analytics/tsconfig.spec.json.template +15 -0
  123. package/src/ng-add/files/src/app/admin/admin-panel/admin-panel.component.html.template +3 -1
  124. package/src/ng-add/files/src/app/admin/admin-panel/admin-panel.component.spec.ts.template +10 -13
  125. package/src/ng-add/files/src/app/admin/admin-panel/admin-panel.component.ts.template +2 -0
  126. package/src/ng-add/files/src/app/admin/admin-panel/admin-settings/admin-settings.component.spec.ts.template +4 -5
  127. package/src/ng-add/files/src/app/admin/admin-panel/admin-user-list/admin-user-list.component.spec.ts.template +11 -12
  128. package/src/ng-add/files/src/app/admin/admin-panel/admin-user-list/admin-user-list.component.ts.template +7 -7
  129. package/src/ng-add/files/src/app/admin/admin-panel/admin-user-list/admin-user-table/admin-user-table.component.spec.ts.template +8 -10
  130. package/src/ng-add/files/src/app/admin/admin-panel/admin-user-list/admin-user-table/admin-user-table.component.ts.template +3 -2
  131. package/src/ng-add/files/src/app/app.component.html.template +3 -3
  132. package/src/ng-add/files/src/app/app.component.scss.template +1 -1
  133. package/src/ng-add/files/src/app/app.component.spec.ts.template +4 -5
  134. package/src/ng-add/files/src/app/app.component.ts.template +3 -2
  135. package/src/ng-add/files/src/app/app.config.ts.template +21 -15
  136. package/src/ng-add/files/src/app/app.routes.ts.template +6 -0
  137. package/src/ng-add/files/src/app/auth-routing.spec.ts.template +13 -9
  138. package/src/ng-add/files/src/app/core/analytics/time-analytics.service.spec.ts.template +46 -29
  139. package/src/ng-add/files/src/app/core/analytics/time-analytics.service.ts.template +27 -18
  140. package/src/ng-add/files/src/app/core/auth/auth.providers.spec.ts.template +112 -0
  141. package/src/ng-add/files/src/app/core/auth/auth.providers.ts.template +48 -0
  142. package/src/ng-add/files/src/app/core/auth/auth.service.ts.template +14 -23
  143. package/src/ng-add/files/src/app/core/auth/guards/require-admin.guard.spec.ts.template +27 -0
  144. package/src/ng-add/files/src/app/core/auth/guards/require-admin.guard.ts.template +3 -2
  145. package/src/ng-add/files/src/app/core/auth/guards/require-auth-and-consent.guard.ts.template +7 -2
  146. package/src/ng-add/files/src/app/core/firebase/data.providers.prod.ts.template +21 -0
  147. package/src/ng-add/files/src/app/core/firebase/data.providers.ts.template +13 -0
  148. package/src/ng-add/files/src/app/core/local-storage/session.service.spec.ts.template +43 -0
  149. package/src/ng-add/files/src/app/core/local-storage/session.service.ts.template +7 -0
  150. package/src/ng-add/files/src/app/core/store/app-data.spec.ts.template +76 -0
  151. package/src/ng-add/files/src/app/core/store/auth/auth.mock.ts.template +20 -82
  152. package/src/ng-add/files/src/app/core/store/auth/auth.store.spec.ts.template +217 -0
  153. package/src/ng-add/files/src/app/core/store/auth/auth.store.ts.template +36 -172
  154. package/src/ng-add/files/src/app/core/store/user/user.mock.ts.template +18 -15
  155. package/src/ng-add/files/src/app/core/store/user/user.model.ts.template +7 -8
  156. package/src/ng-add/files/src/app/core/store/user/user.store.ts.template +14 -10
  157. package/src/ng-add/files/src/app/core/store/user-context/user-context.mock.ts.template +20 -8
  158. package/src/ng-add/files/src/app/core/store/user-context/user-context.model.ts.template +5 -6
  159. package/src/ng-add/files/src/app/core/store/user-context/user-context.store.ts.template +14 -10
  160. package/src/ng-add/files/src/app/core/store/user-private/user-private.mock.ts.template +20 -7
  161. package/src/ng-add/files/src/app/core/store/user-private/user-private.model.ts.template +6 -6
  162. package/src/ng-add/files/src/app/core/store/user-private/user-private.store.ts.template +14 -10
  163. package/src/ng-add/files/src/app/core/testing/app-mocks.ts.template +42 -0
  164. package/src/ng-add/files/src/app/first-time/auth-action/auth-action.component.html.template +4 -0
  165. package/src/ng-add/files/src/app/first-time/auth-action/auth-action.component.scss.template +1 -0
  166. package/src/ng-add/files/src/app/first-time/auth-action/auth-action.component.ts.template +38 -0
  167. package/src/ng-add/files/src/app/first-time/consent/consent.component.html.template +2 -1
  168. package/src/ng-add/files/src/app/first-time/consent/consent.component.scss.template +7 -3
  169. package/src/ng-add/files/src/app/first-time/consent/consent.component.spec.ts.template +31 -11
  170. package/src/ng-add/files/src/app/first-time/consent/consent.component.ts.template +16 -1
  171. package/src/ng-add/files/src/app/first-time/consent/consent.guard.ts.template +5 -1
  172. package/src/ng-add/files/src/app/first-time/early-access/early-access.component.spec.ts.template +27 -16
  173. package/src/ng-add/files/src/app/first-time/early-access/early-access.component.ts.template +102 -49
  174. package/src/ng-add/files/src/app/first-time/early-access/early-access.guard.ts.template +5 -1
  175. package/src/ng-add/files/src/app/first-time/early-access/survey-form/survey-form.component.html.template +2 -1
  176. package/src/ng-add/files/src/app/first-time/early-access/survey-form/survey-form.component.scss.template +7 -3
  177. package/src/ng-add/files/src/app/first-time/early-access/survey-form/survey-form.component.spec.ts.template +20 -6
  178. package/src/ng-add/files/src/app/first-time/early-access/survey-form/survey-form.component.ts.template +2 -0
  179. package/src/ng-add/files/src/app/first-time/early-access/waitlist-view/waitlist-view.component.spec.ts.template +4 -5
  180. package/src/ng-add/files/src/app/first-time/email-link/email-link.component.html.template +18 -0
  181. package/src/ng-add/files/src/app/first-time/email-link/email-link.component.scss.template +2 -0
  182. package/src/ng-add/files/src/app/first-time/email-link/email-link.component.spec.ts.template +56 -0
  183. package/src/ng-add/files/src/app/first-time/email-link/email-link.component.ts.template +91 -0
  184. package/src/ng-add/files/src/app/first-time/first-time-routing.spec.ts.template +11 -7
  185. package/src/ng-add/files/src/app/first-time/landing/hero/hero.component.html.template +19 -7
  186. package/src/ng-add/files/src/app/first-time/landing/hero/hero.component.scss.template +51 -0
  187. package/src/ng-add/files/src/app/first-time/landing/hero/hero.component.ts.template +44 -5
  188. package/src/ng-add/files/src/app/first-time/landing/landing.component.html.template +2 -1
  189. package/src/ng-add/files/src/app/first-time/landing/landing.component.scss.template +12 -8
  190. package/src/ng-add/files/src/app/first-time/landing/landing.component.spec.ts.template +33 -10
  191. package/src/ng-add/files/src/app/first-time/landing/landing.component.ts.template +6 -19
  192. package/src/ng-add/files/src/app/first-time/login/login.component.html.template +58 -6
  193. package/src/ng-add/files/src/app/first-time/login/login.component.scss.template +151 -22
  194. package/src/ng-add/files/src/app/first-time/login/login.component.spec.ts.template +30 -32
  195. package/src/ng-add/files/src/app/first-time/login/login.component.ts.template +85 -31
  196. package/src/ng-add/files/src/app/first-time/onboarding/onboarding.component.spec.ts.template +4 -2
  197. package/src/ng-add/files/src/app/first-time/onboarding/onboarding.component.ts.template +1 -1
  198. package/src/ng-add/files/src/app/main/account-profile/account-profile.component.html.template +12 -0
  199. package/src/ng-add/files/src/app/main/account-profile/account-profile.component.scss.template +39 -0
  200. package/src/ng-add/files/src/app/main/account-profile/account-profile.component.spec.ts.template +68 -0
  201. package/src/ng-add/files/src/app/main/account-profile/account-profile.component.ts.template +20 -0
  202. package/src/ng-add/files/src/app/main/account-profile/delete-guest-card/delete-guest-card.component.html.template +24 -0
  203. package/src/ng-add/files/src/app/main/account-profile/delete-guest-card/delete-guest-card.component.scss.template +50 -0
  204. package/src/ng-add/files/src/app/main/account-profile/delete-guest-card/delete-guest-card.component.spec.ts.template +65 -0
  205. package/src/ng-add/files/src/app/main/account-profile/delete-guest-card/delete-guest-card.component.ts.template +59 -0
  206. package/src/ng-add/files/src/app/main/account-profile/guest-deletion-dialog.component.ts.template +51 -0
  207. package/src/ng-add/files/src/app/main/account-profile/profile-details-card/profile-details-card.component.html.template +50 -0
  208. package/src/ng-add/files/src/app/main/account-profile/profile-details-card/profile-details-card.component.scss.template +137 -0
  209. package/src/ng-add/files/src/app/main/account-profile/profile-details-card/profile-details-card.component.spec.ts.template +57 -0
  210. package/src/ng-add/files/src/app/main/account-profile/profile-details-card/profile-details-card.component.ts.template +59 -0
  211. package/src/ng-add/files/src/app/main/account-profile/sign-in-methods-card/sign-in-methods-card.component.html.template +133 -0
  212. package/src/ng-add/files/src/app/main/account-profile/sign-in-methods-card/sign-in-methods-card.component.scss.template +207 -0
  213. package/src/ng-add/files/src/app/main/account-profile/sign-in-methods-card/sign-in-methods-card.component.spec.ts.template +74 -0
  214. package/src/ng-add/files/src/app/main/account-profile/sign-in-methods-card/sign-in-methods-card.component.ts.template +130 -0
  215. package/src/ng-add/files/src/app/main/home/home.component.spec.ts.template +4 -5
  216. package/src/ng-add/files/src/app/main/home/home.component.ts.template +1 -6
  217. package/src/ng-add/files/src/app/shared/guest-warning-bar/guest-warning-bar.component.html.template +15 -0
  218. package/src/ng-add/files/src/app/shared/guest-warning-bar/guest-warning-bar.component.scss.template +79 -0
  219. package/src/ng-add/files/src/app/shared/guest-warning-bar/guest-warning-bar.component.spec.ts.template +59 -0
  220. package/src/ng-add/files/src/app/shared/guest-warning-bar/guest-warning-bar.component.ts.template +44 -0
  221. package/src/ng-add/files/src/app/shared/navbar/navbar.component.html.template +45 -15
  222. package/src/ng-add/files/src/app/shared/navbar/navbar.component.scss.template +103 -19
  223. package/src/ng-add/files/src/app/shared/navbar/navbar.component.spec.ts.template +73 -9
  224. package/src/ng-add/files/src/app/shared/navbar/navbar.component.ts.template +46 -18
  225. package/src/ng-add/files/src/environments/environment.prod.ts.template +1 -0
  226. package/src/ng-add/files/src/environments/environment.test.ts.template +1 -0
  227. package/src/ng-add/files/src/environments/environment.ts.template +1 -1
  228. package/src/ng-add/files/tsconfig.spec.json.template +3 -1
  229. package/src/ng-add/index.js +7 -0
  230. package/src/ng-add/index.js.map +1 -1
  231. package/src/shared/entity-registry.d.ts +8 -0
  232. package/src/shared/entity-registry.js +28 -0
  233. package/src/shared/entity-registry.js.map +1 -0
  234. package/tsconfig.json +2 -2
  235. package/.agents/skills/publish-npm/SKILL.md +0 -37
  236. package/.agents/skills/publish-npm/eval.yaml +0 -32
  237. package/.agents/skills/publish-npm/fixtures/package-v21.json.template +0 -8
  238. package/.husky/commit-msg +0 -1
  239. package/.husky/pre-commit +0 -1
  240. package/.t4g/agent-memory.db +0 -0
  241. package/src/component/index_spec.d.ts +0 -1
  242. package/src/component/index_spec.js +0 -68
  243. package/src/component/index_spec.js.map +0 -1
  244. package/src/entity/index_spec.d.ts +0 -1
  245. package/src/entity/index_spec.js +0 -153
  246. package/src/entity/index_spec.js.map +0 -1
  247. package/src/guard/index_spec.d.ts +0 -1
  248. package/src/guard/index_spec.js +0 -64
  249. package/src/guard/index_spec.js.map +0 -1
  250. package/src/ng-add/files/bigquery/scripts/export_entities.py.template +0 -143
  251. package/src/ng-add/files/bigquery/scripts/run_query.py.template +0 -167
  252. package/src/ng-add/files/src/app/core/firebase/cached-listeners.service.ts.template +0 -494
  253. package/src/ng-add/files/src/app/core/firebase/database.service.ts.template +0 -56
  254. package/src/ng-add/files/src/app/core/firebase/firebase.mock.service.ts.template +0 -366
  255. package/src/ng-add/files/src/app/core/firebase/firebase.service.ts.template +0 -342
  256. package/src/ng-add/files/src/app/core/firebase/simulate-load.spec.ts.template +0 -104
  257. package/src/ng-add/files/src/app/core/firebase/simulate-stream.spec.ts.template +0 -127
  258. package/src/ng-add/files/src/app/core/firebase/simulation.mock.ts.template +0 -38
  259. package/src/ng-add/files/src/app/core/firebase/stream-multiplexer.ts.template +0 -445
  260. package/src/ng-add/files/src/app/core/logging/logging.service.spec.ts.template +0 -118
  261. package/src/ng-add/files/src/app/core/logging/logging.service.ts.template +0 -168
  262. package/src/ng-add/files/src/app/core/store/app.model.ts.template +0 -21
  263. package/src/ng-add/files/src/app/core/store/app.store.spec.ts.template +0 -920
  264. package/src/ng-add/files/src/app/core/store/app.store.ts.template +0 -1317
  265. package/src/ng-add/files/src/app/core/store/batch-write.firebase.service.ts.template +0 -58
  266. package/src/ng-add/files/src/app/core/store/batch-write.mock.service.ts.template +0 -105
  267. package/src/ng-add/files/src/app/core/store/batch-write.service.ts.template +0 -126
  268. package/src/ng-add/files/src/app/shared/redeployment-warning/redeployment-warning.component.html.template +0 -9
  269. package/src/ng-add/files/src/app/shared/redeployment-warning/redeployment-warning.component.scss.template +0 -46
  270. package/src/ng-add/files/src/app/shared/redeployment-warning/redeployment-warning.component.spec.ts.template +0 -69
  271. package/src/ng-add/files/src/app/shared/redeployment-warning/redeployment-warning.component.ts.template +0 -39
  272. package/src/ng-add/files/src/app/shared/redeployment-warning/redeployment-warning.service.spec.ts.template +0 -122
  273. package/src/ng-add/files/src/app/shared/redeployment-warning/redeployment-warning.service.ts.template +0 -88
@@ -1,1317 +0,0 @@
1
- import { WritableSignal, inject } from '@angular/core';
2
- import { Timestamp, writeBatch } from '@angular/fire/firestore';
3
- import { patchState, signalStoreFeature, withMethods } from '@ngrx/signals';
4
- import { removeEntities, removeEntity, setEntities, setEntity, updateEntity, withEntities, setAllEntities } from '@ngrx/signals/entities';
5
- import { SelectEntityId } from '@ngrx/signals/entities';
6
- import { CachedListenersService } from '../firebase/cached-listeners.service';
7
- import { DATABASE_SERVICE, DatabaseService } from '../firebase/database.service';
8
- import { AnyEntity, QueryOptions, QueryParams } from './app.model';
9
- import { MatSnackBar, MatSnackBarConfig } from '@angular/material/snack-bar';
10
- import { WriteBatchI } from './batch-write.service';
11
- import { environment } from '../../../environments/environment';
12
- import { LoggingService, getLogger } from '../logging/logging.service';
13
-
14
- const queryLogger = getLogger('query');
15
-
16
- const selectId: SelectEntityId<AnyEntity> = (entity) => entity.__id;
17
-
18
- export function openSnackBarWithUndoOption(
19
- snackBar: MatSnackBar,
20
- snackBarConfig: {
21
- successMessage: string,
22
- failureMessage: string,
23
- undoOnAction?: boolean,
24
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
25
- config?: MatSnackBarConfig<any>,
26
- },
27
- revertFns: Array<() => void>,
28
- dbRevertFns: Array<() => void>,
29
- revertBatch?: WriteBatchI,
30
- ) {
31
- const snackBarRef = snackBar.open(
32
- snackBarConfig.successMessage,
33
- snackBarConfig.undoOnAction ? 'Undo' : '',
34
- snackBarConfig.config,
35
- );
36
- // if there is an undo option for the snackbar, then we should
37
- // revert both local and database changes if the undo was clicked
38
- if (snackBarConfig.undoOnAction) {
39
- snackBarRef.onAction().subscribe(async () => {
40
- try {
41
- // first try to undo changes on the database
42
- // dbRevertFns will directly remove from DB if not in the batch setting.
43
- // if it is a batch setting, it will do revertBatch.set to prepare
44
- // revertBatch for a commit
45
- await Promise.all(dbRevertFns.map((dbRevertFn) => dbRevertFn()));
46
- if (revertBatch) {
47
- await revertBatch.commit();
48
- }
49
- // if successful, then undo changes locally too
50
- revertFns.forEach((revertFn) => revertFn());
51
- } catch (e) {
52
- console.error(e);
53
- snackBar.open('Failed to undo', '', {
54
- duration: 3000,
55
- });
56
- }
57
- });
58
- }
59
- }
60
-
61
- export function withEntitiesAndSelectMethods<S extends AnyEntity>() {
62
- return signalStoreFeature(
63
- withEntities<S>(),
64
- withMethods((store) => {
65
- const queryCache = new Map<string, S[]>();
66
- return {
67
- handleStreamChanges(entitiesToAdd: S[], entitiesToModify: S[], entitiesToRemove: string[]) {
68
- patchState(store, setEntities(entitiesToAdd, { selectId }));
69
- patchState(store, setEntities(entitiesToModify, { selectId }));
70
- patchState(store, removeEntities(entitiesToRemove));
71
- },
72
- selectEntity(id: string): S {
73
- const result = store.entityMap()[id];
74
-
75
- if (result && !result['_deleted']) {
76
- return result;
77
- } else {
78
- return null;
79
- }
80
- },
81
- selectFirst(queryParams: QueryParams, queryOptions: QueryOptions): S {
82
- // Note: selectEntities already filters out _deleted
83
- const entities = selectEntities<S>(store.entityMap(), queryParams, queryOptions);
84
- if (entities && entities.length > 0) {
85
- return entities[0];
86
- } else {
87
- return null;
88
- }
89
- },
90
- selectEntities(queryParams: QueryParams, queryOptions: QueryOptions): S[] {
91
- // Note: The global standalone selectEntities function already filters out entities with _deleted: true
92
- const result = selectEntities<S>(store.entityMap(), queryParams, queryOptions);
93
- const key = JSON.stringify({ queryParams, queryOptions });
94
-
95
- // CRITICAL: Angular's computed() signals rely on strict referential equality (===).
96
- // Because Object.values().filter() creates a brand new array reference every time it is called,
97
- // any computed signal that calls selectEntities() would trigger an update even if the contents
98
- // of the array are identical. This led to infinite loops and massive memory leaks in nested streams.
99
- // By memoizing the array reference here, we ensure that if the query results are strictly identical
100
- // (same length, same entity references in the exact same order), we return the exact same array reference.
101
- const lastResult = queryCache.get(key);
102
- if (lastResult && lastResult.length === result.length && lastResult.every((v, i) => v === result[i])) {
103
- return lastResult;
104
- }
105
-
106
- queryCache.set(key, result);
107
-
108
- // Simple bounded LRU cache (max 50 unique queries per store) to prevent memory ballooning
109
- if (queryCache.size > 50) {
110
- const firstKey = queryCache.keys().next().value;
111
- if (firstKey) queryCache.delete(firstKey);
112
- }
113
- return result;
114
- },
115
- };
116
- }),
117
- );
118
- }
119
-
120
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
121
- function serializeMockDBData(data: any): string {
122
- return JSON.stringify(data, (key, value) => {
123
- if (value && typeof value === 'object' && 'seconds' in value && 'nanoseconds' in value) {
124
- return { __type: 'Timestamp', seconds: value.seconds, nanoseconds: value.nanoseconds };
125
- }
126
- return value;
127
- });
128
- }
129
-
130
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
131
- function deserializeMockDBData(jsonString: string): any {
132
- return JSON.parse(jsonString, (key, value) => {
133
- if (value && typeof value === 'object' && value.__type === 'Timestamp') {
134
- return new Timestamp(value.seconds, value.nanoseconds);
135
- }
136
- return value;
137
- });
138
- }
139
-
140
- export function withEntitiesForMockDB<S extends AnyEntity>(collectionName: string) {
141
- return signalStoreFeature(
142
- withEntitiesAndSelectMethods<S>(),
143
- withMethods((store) => ({
144
- init(entities: S[]) {
145
- const saved = environment.cacheMockData ? localStorage.getItem(`mockDB_${collectionName}`) : null;
146
- if (saved) {
147
- patchState(store, setAllEntities<S>(deserializeMockDBData(saved), { selectId }));
148
- } else {
149
- patchState(store, setAllEntities<S>(entities, { selectId }));
150
- }
151
-
152
- // Listen for changes from other tabs to keep mockDB in sync
153
- window.addEventListener('storage', (event) => {
154
- if (event.key === `mockDB_${collectionName}` && event.newValue) {
155
- patchState(store, setAllEntities<S>(deserializeMockDBData(event.newValue), { selectId }));
156
- }
157
- });
158
- },
159
- add(entity: S) {
160
- patchState(store, setEntity<S>(entity, { selectId }));
161
- if (environment.cacheMockData) {
162
- localStorage.setItem(`mockDB_${collectionName}`, serializeMockDBData(Object.values(store.entityMap())));
163
- }
164
- },
165
- update(id: string, changes: Partial<S>) {
166
- patchState(store, updateEntity({ id, changes }, { selectId }));
167
- if (environment.cacheMockData) {
168
- localStorage.setItem(`mockDB_${collectionName}`, serializeMockDBData(Object.values(store.entityMap())));
169
- }
170
- },
171
- })),
172
- );
173
- }
174
-
175
-
176
- export function withEntitiesAndDBMethods<S extends AnyEntity>(collectionName: string) {
177
- return signalStoreFeature(
178
- withEntitiesAndSelectMethods<S>(),
179
- withMethods((store, cachedLoads = inject(CachedListenersService), db = inject(DATABASE_SERVICE), snackBar = inject(MatSnackBar), logger = inject(LoggingService)) => ({
180
- init(entities: S[]) {
181
- patchState(store, setAllEntities<S>(entities, { selectId }));
182
- },
183
- // streaming tries to reduce redundant loads through the following:
184
- // - caching listeners and reusing them with a 5-second delay after moving to a new container before unsubscribing
185
- // additionally, it has the following constraints:
186
- // - nested loadQueries are only loaded, not streamed, to prevent huge numbers of listeners.
187
- // - nested loadQueries can only be made based on the id of retrieved entities to ensure we only need to replay loads/adds
188
- // - containers pass in an id for loads, then onDestroy, they call cachedListeners.disconnect(id)
189
- async stream(
190
- queryParams: QueryParams,
191
- queryOptions: QueryOptions,
192
- injector,
193
- streamQueries?: (entity: S) => EntityStreamQuery<AnyEntity>[],
194
- options?: {
195
- loading?: WritableSignal<boolean>, // set to true on start, set to false once all are complete
196
- },
197
- ) {
198
- try {
199
- // start loading icon if available
200
- options?.loading?.set(true);
201
-
202
- const isSimpleEqualityQuery = (!queryOptions || Object.keys(queryOptions).length === 0) &&
203
- queryParams.length === 1 &&
204
- (queryParams[0][1] === '==' || queryParams[0][1] === 'in');
205
-
206
- if (isSimpleEqualityQuery) {
207
- const field = queryParams[0][0];
208
- const ids = queryParams[0][1] === 'in' ? queryParams[0][2] : [queryParams[0][2]];
209
- await cachedLoads.processSimpleStreamQuery(collectionName, field, ids, store, injector, streamQueries, options);
210
- } else {
211
- await cachedLoads.processStreamQuery(collectionName, store, queryParams, queryOptions, injector, streamQueries, options);
212
- }
213
- } catch (e) {
214
- console.error(e);
215
-
216
- // stop loading icon. when no error, loading icon is stopped
217
- // upon the initial payload coming through the stream and the
218
- // loadQueries being processed
219
- options?.loading?.set(false);
220
- throw e;
221
- }
222
- },
223
- // loading tries to reduce redundant loads through the following:
224
- // - below only applies when there are no queryOptions
225
- // - only loads (not deleted) entities since the last time this query was made and when there is not already an active stream for that
226
- // - delete entities since the last load where _deleted is true and when there is not already an active stream for that (which would handle deletions too)
227
- // - to calculate loadQueries, use the entities within the store (to get both the deltas and the things already loaded)
228
- async load(
229
- queryParams: QueryParams,
230
- queryOptions: QueryOptions,
231
- loadQueries?: (entity: S) => EntityLoadQuery<AnyEntity>[],
232
- options?: {
233
- loading?: WritableSignal<boolean>,
234
- },
235
- ) {
236
- try {
237
- // start loading icon if available
238
- options?.loading?.set(true);
239
-
240
- const isBatchableEqualityOrIn =
241
- (!queryOptions || Object.keys(queryOptions).length === 0) &&
242
- queryParams.length === 1 &&
243
- (queryParams[0][1] === '==' || queryParams[0][1] === 'in');
244
-
245
- if (!isBatchableEqualityOrIn) {
246
- // ---------------------------------------------------------
247
- // LEGACY PATH: Non-equality queries use full query-string tracking
248
- // ---------------------------------------------------------
249
- // only load if there is not already a listener for the same query
250
- if (!cachedLoads.isStreamForQuery(collectionName, queryParams, queryOptions)) {
251
- // get the last load time and next load time
252
- const lastLoadTime = cachedLoads.getLastLoadTime(collectionName, queryParams, queryOptions);
253
- const newLoadTime = Timestamp.now().toMillis();
254
-
255
- // load entities since last load that are not deleted
256
- // note that we always load all entities if there exist queryOptions since adding
257
- // the _updatedAt filter will change queries with limit
258
- let queryParamsWithTime;
259
- if (lastLoadTime === -1 || (queryOptions && Object.keys(queryOptions).length > 0)) {
260
- queryParamsWithTime = [...queryParams, ['_deleted', '==', false]];
261
- } else {
262
- queryParamsWithTime = [
263
- ...queryParams,
264
- ['_updatedAt', '>', Timestamp.fromMillis(lastLoadTime)],
265
- ['_deleted', '==', false],
266
- ];
267
- }
268
-
269
- // get entities that have been added or updated since last load
270
- const entitiesDelta: S[] = await db.getEntities(
271
- collectionName,
272
- queryParamsWithTime,
273
- queryOptions,
274
- );
275
- patchState(store, setEntities<S>(entitiesDelta, { selectId }));
276
-
277
- // delete any new deleted entities
278
- if (lastLoadTime === -1 || (queryOptions && Object.keys(queryOptions).length > 0)) {
279
- const entitiesDeletedDelta: S[] = await db.getEntities(
280
- collectionName,
281
- [...queryParams, ['_deleted', '==', true]],
282
- queryOptions,
283
- );
284
- patchState(store, removeEntities(
285
- entitiesDeletedDelta.map((e) => e.__id),
286
- ));
287
- } else {
288
- const entitiesDeletedDelta: S[] = await db.getEntities(
289
- collectionName,
290
- [...queryParams,
291
- ['_updatedAt', '>', Timestamp.fromMillis(lastLoadTime)],
292
- ['_deleted', '==', true]],
293
- queryOptions,
294
- );
295
- patchState(store, removeEntities(
296
- entitiesDeletedDelta.map((e) => e.__id),
297
- ));
298
- }
299
-
300
- // save a new lastLoadTime for this query
301
- cachedLoads.setLastLoadTime(collectionName, queryParams, queryOptions, newLoadTime);
302
- }
303
- } else {
304
- // ---------------------------------------------------------
305
- // OPTIMIZED PATH: Per-entity tracking for == and in queries
306
- // ---------------------------------------------------------
307
- const field = queryParams[0][0] as string;
308
- const operator = queryParams[0][1];
309
- const rawValues = operator === '==' ? [queryParams[0][2] as string] : queryParams[0][2] as string[];
310
-
311
- // 1. Remove IDs already covered by active streams
312
- const valuesToLoad = rawValues.filter((v) => {
313
- // Check if it's covered by a multiplexer stream
314
- if (cachedLoads.isIdStreamed(collectionName, field, v)) return false;
315
- return true;
316
- });
317
-
318
- if (valuesToLoad.length > 0) {
319
- const newLoadTime = Timestamp.now().toMillis();
320
-
321
- if (field === '__id' && valuesToLoad.length === 1) {
322
- const idToFetch = valuesToLoad[0];
323
- queryLogger.log(`[Store] Optimized Load Triggered for collection '${collectionName}', fetching single ID using getDoc.`);
324
-
325
- const entity = await db.getEntity<S>(collectionName, idToFetch);
326
-
327
- if (entity) {
328
- if (entity._deleted) {
329
- patchState(store, removeEntities([idToFetch]));
330
- } else {
331
- patchState(store, setEntities<S>([entity], { selectId }));
332
- }
333
- } else {
334
- patchState(store, removeEntities([idToFetch]));
335
- }
336
-
337
- cachedLoads.setEntityLoadTime(collectionName, field, idToFetch, newLoadTime);
338
- } else {
339
- // 2. Group values by their entityLoadTime (Time Bucketing Strategy)
340
- // To prevent the N+1 problem of issuing dozens of queries for items with slightly
341
- // different load times, we group loaded items into 5-minute buckets.
342
- // Unloaded items (-1) are strictly kept in their own bucket to prevent over-fetching.
343
- const BUCKET_MS = 5 * 60 * 1000;
344
-
345
- // Map bucket index to the exact minimum time in that bucket and its values
346
- const groupsByBucket: Map<number, { minTime: number, values: string[] }> = new Map();
347
-
348
- queryLogger.log(`[Store] Optimized Load Triggered for collection '${collectionName}', tracking ${valuesToLoad.length} IDs.`);
349
-
350
- valuesToLoad.forEach((val) => {
351
- const time = cachedLoads.getEntityLoadTime(collectionName, field, val);
352
- const bucketIndex = time === -1 ? -1 : Math.floor(time / BUCKET_MS);
353
-
354
- if (!groupsByBucket.has(bucketIndex)) {
355
- groupsByBucket.set(bucketIndex, { minTime: time, values: [] });
356
- }
357
-
358
- const group = groupsByBucket.get(bucketIndex)!;
359
- // Track the earliest load time in this bucket
360
- if (time !== -1 && time < group.minTime) {
361
- group.minTime = time;
362
- }
363
- group.values.push(val);
364
- });
365
-
366
- // 3. For each group, execute DB fetches
367
- queryLogger.log(`[Store] Grouped ${valuesToLoad.length} IDs into ${groupsByBucket.size} time bucket(s).`);
368
- await Promise.all(Array.from(groupsByBucket.entries()).map(async ([bucketIndex, group]) => {
369
- const lastTime = group.minTime;
370
- const groupValues = group.values;
371
- queryLogger.log(`[Store] Bucket ${bucketIndex === -1 ? '(-1: Never Loaded)' : bucketIndex} (minTime: ${lastTime === -1 ? 'Never' : new Date(lastTime).toISOString()}) fetching ${groupValues.length} IDs.`);
372
- // Chunk into 30s
373
- for (let i = 0; i < groupValues.length; i += 30) {
374
- const chunk = groupValues.slice(i, i + 30);
375
- const batchedParams: QueryParams = [[field, 'in', chunk]];
376
- queryLogger.log(`[Store] -> Fetching chunk of ${chunk.length} IDs...`);
377
-
378
- // Fetch changed entities
379
- let queryParamsWithTime: QueryParams;
380
- if (lastTime === -1) {
381
- queryParamsWithTime = [...batchedParams, ['_deleted', '==', false]];
382
- } else {
383
- queryParamsWithTime = [
384
- ...batchedParams,
385
- ['_updatedAt', '>', Timestamp.fromMillis(lastTime)],
386
- ['_deleted', '==', false],
387
- ];
388
- }
389
- const entitiesDelta: S[] = await db.getEntities(collectionName, queryParamsWithTime, {});
390
- if (entitiesDelta.length > 0) {
391
- queryLogger.log(`[Store] -> Loaded ${entitiesDelta.length} updated/new entities from chunk.`);
392
- }
393
- patchState(store, setEntities<S>(entitiesDelta, { selectId }));
394
-
395
- // Fetch soft-deleted entities
396
- let deletedParamsWithTime: QueryParams;
397
- if (lastTime === -1) {
398
- deletedParamsWithTime = [...batchedParams, ['_deleted', '==', true]];
399
- } else {
400
- deletedParamsWithTime = [
401
- ...batchedParams,
402
- ['_updatedAt', '>', Timestamp.fromMillis(lastTime)],
403
- ['_deleted', '==', true],
404
- ];
405
- }
406
- const entitiesDeletedDelta: S[] = await db.getEntities(collectionName, deletedParamsWithTime, {});
407
- if (entitiesDeletedDelta.length > 0) {
408
- queryLogger.log(`[Store] -> Removed ${entitiesDeletedDelta.length} soft-deleted entities from chunk.`);
409
- }
410
- patchState(store, removeEntities(entitiesDeletedDelta.map(selectId) as string[]));
411
- }
412
- }));
413
-
414
- // 4. Update entityLoadTime for all fetched values to the unified newLoadTime
415
- valuesToLoad.forEach((val) => cachedLoads.setEntityLoadTime(collectionName, field, val, newLoadTime));
416
- }
417
- }
418
- }
419
-
420
- if (loadQueries) {
421
- // retrieve entities from store for loading queries
422
- // note we cannot simply use entities from load since it may not be all entities (only those for which updatedAt > lastLoadTime)
423
- const allQueriedEntities = store.selectEntities(queryParams, queryOptions);
424
- await processLoadQueries<S>(allQueriedEntities, loadQueries);
425
- }
426
- } catch (e) {
427
- console.error(e);
428
- throw e;
429
- } finally {
430
- // stop loading icon
431
- options?.loading?.set(false);
432
- }
433
- },
434
- async count(
435
- queryParams: QueryParams,
436
- queryOptions: QueryOptions,
437
- options?: {
438
- loading?: WritableSignal<boolean>,
439
- },
440
- ): Promise<number> {
441
- try {
442
- // start loading icon if available
443
- options?.loading?.set(true);
444
-
445
- const queryParamsNotDeleted: QueryParams = [...queryParams, ['_deleted', '==', false]];
446
- return await db.count(collectionName, queryParamsNotDeleted, queryOptions);
447
- } catch (e) {
448
- console.error(e);
449
- throw e;
450
- } finally {
451
- // stop loading icon
452
- options?.loading?.set(false);
453
- }
454
- },
455
- async aggregate<T extends { [k: string]: number }>(
456
- queryParams: QueryParams,
457
- queryOptions: QueryOptions,
458
- aggregateParams: { [K in keyof T]: [string] | [string, string] },
459
- options?: {
460
- loading?: WritableSignal<boolean>,
461
- },
462
- ): Promise<{ [K in keyof T]: number }> {
463
- try {
464
- // start loading icon if available
465
- options?.loading?.set(true);
466
-
467
- const queryParamsNotDeleted: QueryParams = [...queryParams, ['_deleted', '==', false]];
468
- return await db.aggregate<T>(
469
- collectionName, queryParamsNotDeleted, queryOptions, aggregateParams,
470
- );
471
- } catch (e) {
472
- console.error(e);
473
- throw e;
474
- } finally {
475
- // stop loading icon
476
- options?.loading?.set(false);
477
- }
478
- },
479
- async increment(id: string, field: string, delta: number, options?: {
480
- loading?: WritableSignal<boolean>,
481
- optimistic?: boolean
482
- }) {
483
- // get current value
484
- const currEntityValue = store.entityMap()[id];
485
- const changes = {};
486
- changes[field] = (currEntityValue[field] || 0) + delta;
487
- changes['_updatedAt'] = Timestamp.now();
488
-
489
- if (options?.optimistic) {
490
- try {
491
- // optimistically set then query backend
492
- patchState(store, updateEntity({
493
- id,
494
- changes: Object.assign({}, changes, {
495
- _updatedAt: Timestamp.now(),
496
- }) as Partial<NoInfer<S>>,
497
- }, { selectId }));
498
- await db.incrementEntityField(collectionName, id, field, delta);
499
- } catch (e) {
500
- // undo ngrx store value
501
- if (currEntityValue) {
502
- patchState(store, setEntity<S>(currEntityValue, { selectId }));
503
- } else {
504
- patchState(store, removeEntity(id));
505
- }
506
- console.error(e);
507
- throw e;
508
- }
509
- } else {
510
- try {
511
- // start loading icon
512
- options?.loading?.set(true);
513
-
514
- // update entity
515
- await db.incrementEntityField(collectionName, id, field, delta);
516
- patchState(store, updateEntity({
517
- id,
518
- changes: Object.assign({}, changes, {
519
- _updatedAt: Timestamp.now(),
520
- }) as Partial<NoInfer<S>>,
521
- }, { selectId }));
522
- } catch (e) {
523
- console.error(e);
524
- throw e;
525
- } finally {
526
- // stop loading icon
527
- options?.loading?.set(false);
528
- }
529
- }
530
- },
531
- async add(
532
- entityOpId: S | Omit<S, '__id'>,
533
- options?: {
534
- optimistic?: boolean,
535
- loading?: WritableSignal<boolean>,
536
- snackBarConfig?: {
537
- successMessage: string,
538
- failureMessage: string,
539
- undoOnAction?: boolean,
540
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
541
- config?: MatSnackBarConfig<any>,
542
- },
543
- batchConfig?: {
544
- batch: WriteBatchI,
545
- revertBatch: WriteBatchI,
546
- patchFns: Array<() => void>,
547
- revertFns: Array<() => void>,
548
- dbRevertFns: Array<() => void>,
549
- optimistic?: boolean,
550
- }
551
- },
552
- ) {
553
- // Create an __id if one was not provided
554
- const entity: S = Object.assign({}, entityOpId, {
555
- __id: entityOpId['__id'] || db.createId(),
556
- }) as S;
557
-
558
- // Function for setting the entity locally
559
- const patchFn = () => {
560
- patchState(store, setEntity<S>(
561
- Object.assign({}, entity, {
562
- _updatedAt: Timestamp.now(),
563
- _createdAt: Timestamp.now(),
564
- _deleted: false,
565
- }),
566
- { selectId },
567
- ));
568
- };
569
-
570
- // Function for reverting changes for optimistic adds
571
- const currEntityValue = store.entityMap()[entity.__id];
572
- const revertFn = () => {
573
- if (currEntityValue) {
574
- patchState(store, setEntity<S>(currEntityValue, { selectId }));
575
- } else {
576
- patchState(store, removeEntity(entity.__id));
577
- }
578
- };
579
-
580
- // Function for reverting changes to the DB when 'Undo' is clicked in the snackbar
581
- const dbRevertFn = async () => {
582
- try {
583
- if (currEntityValue) {
584
- await db.addEntity(collectionName, currEntityValue, options?.batchConfig?.revertBatch);
585
- } else {
586
- await db.removeEntity(collectionName, entity.__id, options?.batchConfig?.revertBatch);
587
- }
588
- } catch (e) {
589
- console.error(e);
590
- throw e;
591
- }
592
- };
593
-
594
- // Add the patchFn, revertFn, dbRevertFn if this is a batch write
595
- options?.batchConfig?.patchFns?.push(patchFn);
596
- options?.batchConfig?.revertFns?.push(revertFn);
597
- options?.batchConfig?.dbRevertFns?.push(dbRevertFn);
598
-
599
-
600
- // optimistically set locally, then in backend and revert if needed
601
- if (options?.optimistic || options?.batchConfig?.optimistic) {
602
- patchFn();
603
- try {
604
- await db.addEntity(collectionName, entity, options?.batchConfig?.batch);
605
- // it will only go into here when not in a batch setting
606
- // since there is no snackBarConfig in the a batch seting
607
- if (options?.snackBarConfig) {
608
- openSnackBarWithUndoOption(snackBar, options.snackBarConfig, [revertFn], [dbRevertFn]);
609
- }
610
- } catch (e) {
611
- // will only get here when it's not a batch
612
- revertFn();
613
- console.error(e);
614
- if (options?.snackBarConfig) {
615
- snackBar.open(
616
- options.snackBarConfig.failureMessage,
617
- '',
618
- options.snackBarConfig.config,
619
- );
620
- }
621
- throw e;
622
- }
623
- // set in backend and then locally if successful
624
- } else {
625
- // start loading icon
626
- options?.loading?.set(true);
627
- try {
628
- await db.addEntity(collectionName, entity, options?.batchConfig?.batch);
629
- // only patch if not using batch writes since if we're using
630
- // batch writes, we should be patching after the batch write
631
- // is successful
632
- if (!options?.batchConfig?.batch) {
633
- patchFn();
634
- if (options?.snackBarConfig) {
635
- openSnackBarWithUndoOption(snackBar, options.snackBarConfig, [revertFn], [dbRevertFn]);
636
- }
637
- }
638
- } catch (e) {
639
- console.error(e);
640
- // will only get here when it's not a batch
641
- if (options?.snackBarConfig) {
642
- snackBar.open(
643
- options.snackBarConfig.failureMessage,
644
- '',
645
- options.snackBarConfig.config,
646
- );
647
- }
648
- throw e;
649
- } finally {
650
- // stop loading icon
651
- options?.loading?.set(false);
652
- }
653
- }
654
- },
655
- async update(
656
- id: string,
657
- changes: Partial<S>,
658
- options?: {
659
- optimistic?: boolean,
660
- loading?: WritableSignal<boolean>,
661
- snackBarConfig?: {
662
- successMessage: string,
663
- failureMessage: string,
664
- undoOnAction?: boolean,
665
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
666
- config?: MatSnackBarConfig<any>,
667
- },
668
- batchConfig?: {
669
- batch: WriteBatchI,
670
- revertBatch: WriteBatchI,
671
- patchFns?: Array<() => void>,
672
- revertFns: Array<() => void>,
673
- dbRevertFns: Array<() => void>,
674
- optimistic?: boolean,
675
- }
676
- },
677
- ) {
678
- // Function for updating the entity locally
679
- const patchFn = () => {
680
- patchState(store, updateEntity({
681
- id,
682
- changes: Object.assign({}, changes, {
683
- _updatedAt: Timestamp.now(),
684
- }) as Partial<NoInfer<S>>,
685
- }, { selectId }));
686
- };
687
-
688
- // Function for reverting changes for optimistic updates
689
- const currEntityValue = store.entityMap()[id];
690
- const revertFn = () => {
691
- if (currEntityValue) {
692
- patchState(store, setEntity<S>(currEntityValue, { selectId }));
693
- } else {
694
- patchState(store, removeEntity(id));
695
- }
696
- };
697
-
698
- // Function for reverting changes to the DB when 'Undo' is clicked in the snackbar
699
- const dbRevertFn = async () => {
700
- try {
701
- if (currEntityValue) {
702
- await db.addEntity(collectionName, currEntityValue, options?.batchConfig?.revertBatch);
703
- } else {
704
- await db.removeEntity(collectionName, id, options?.batchConfig?.revertBatch);
705
- }
706
- } catch (e) {
707
- console.error(e);
708
- throw e;
709
- }
710
- };
711
-
712
- // Add the patchFn, revertFn, dbRevertFn if this is a batch write
713
- options?.batchConfig?.patchFns?.push(patchFn);
714
- options?.batchConfig?.revertFns?.push(revertFn);
715
- options?.batchConfig?.dbRevertFns?.push(dbRevertFn);
716
-
717
- // optimistically update locally, then in backend and revert if needed
718
- if (options?.optimistic || options?.batchConfig?.optimistic) {
719
- patchFn();
720
- try {
721
- await db.updateEntity(collectionName, id, changes, options?.batchConfig?.batch);
722
- // it will only go into here when not in a batch setting
723
- // since there is no snackBarConfig in the a batch seting
724
- if (options?.snackBarConfig) {
725
- openSnackBarWithUndoOption(snackBar, options.snackBarConfig, [revertFn], [dbRevertFn]);
726
- }
727
- } catch (e) {
728
- // will only get here when it's not a batch
729
- revertFn();
730
- console.error(e);
731
- if (options?.snackBarConfig) {
732
- snackBar.open(
733
- options.snackBarConfig.failureMessage,
734
- '',
735
- options.snackBarConfig.config,
736
- );
737
- }
738
- throw e;
739
- }
740
- // update in backend and then locally if successful
741
- } else {
742
- // start loading icon
743
- options?.loading?.set(true);
744
- try {
745
- await db.updateEntity(collectionName, id, changes, options?.batchConfig?.batch);
746
- // only patch if not using batch writes since if we're using
747
- // batch writes, we should be patching after the batch write
748
- // is successful
749
- if (!options?.batchConfig?.batch) {
750
- patchFn();
751
- if (options?.snackBarConfig) {
752
- openSnackBarWithUndoOption(snackBar, options.snackBarConfig, [revertFn], [dbRevertFn]);
753
- }
754
- }
755
- } catch (e) {
756
- console.error(e);
757
- // will only get here when it's not a batch
758
- if (options?.snackBarConfig) {
759
- snackBar.open(
760
- options.snackBarConfig.failureMessage,
761
- '',
762
- options.snackBarConfig.config,
763
- );
764
- }
765
- throw e;
766
- } finally {
767
- // stop loading icon
768
- options?.loading?.set(false);
769
- }
770
- }
771
- },
772
- async remove(
773
- id: string,
774
- options?: {
775
- optimistic?: boolean,
776
- loading?: WritableSignal<boolean>,
777
- snackBarConfig?: {
778
- successMessage: string,
779
- failureMessage: string,
780
- undoOnAction?: boolean,
781
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
782
- config?: MatSnackBarConfig<any>,
783
- },
784
- batchConfig?: {
785
- batch: WriteBatchI,
786
- revertBatch: WriteBatchI,
787
- patchFns?: Array<() => void>,
788
- revertFns: Array<() => void>,
789
- dbRevertFns: Array<() => void>,
790
- optimistic?: boolean,
791
- }
792
- },
793
- ) {
794
- // Function for updating the entity locally
795
- const patchFn = () => {
796
- patchState(store, removeEntity(id));
797
- };
798
-
799
- // Function for reverting changes for optimistic deletes
800
- const currEntityValue = store.entityMap()[id];
801
- const revertFn = () => {
802
- if (currEntityValue) {
803
- patchState(store, setEntity<S>(currEntityValue, { selectId }));
804
- }
805
- };
806
-
807
- // Function for reverting changes to the DB when 'Undo' is clicked in the snackbar
808
- const dbRevertFn = async () => {
809
- try {
810
- if (currEntityValue) {
811
- await db.addEntity(collectionName, currEntityValue, options?.batchConfig?.revertBatch);
812
- }
813
- } catch (e) {
814
- console.error(e);
815
- throw e;
816
- }
817
- };
818
-
819
- // Add the patchFn, revertFn, dbRevertFn if this is a batch write
820
- options?.batchConfig?.patchFns?.push(patchFn);
821
- options?.batchConfig?.revertFns?.push(revertFn);
822
- options?.batchConfig?.dbRevertFns?.push(dbRevertFn);
823
-
824
- // optimistically remove locally, then in backend and revert if needed
825
- if (options?.optimistic || options?.batchConfig?.optimistic) {
826
- patchFn();
827
- try {
828
- await db.removeEntity(collectionName, id, options?.batchConfig?.batch);
829
- // it will only go into here when not in a batch setting
830
- // since there is no snackBarConfig in the a batch seting
831
- if (options?.snackBarConfig) {
832
- openSnackBarWithUndoOption(snackBar, options.snackBarConfig, [revertFn], [dbRevertFn]);
833
- }
834
- } catch (e) {
835
- // will only get here when it's not a batch
836
- revertFn();
837
- console.error(e);
838
- if (options?.snackBarConfig) {
839
- snackBar.open(
840
- options.snackBarConfig.failureMessage,
841
- '',
842
- options.snackBarConfig.config,
843
- );
844
- }
845
- throw e;
846
- }
847
- // update in backend and then locally if successful
848
- } else {
849
- // start loading icon
850
- options?.loading?.set(true);
851
- try {
852
- await db.removeEntity(collectionName, id, options?.batchConfig?.batch);
853
- // only patch if not using batch writes since if we're using
854
- // batch writes, we should be patching after the batch write
855
- // is successful
856
- if (!options?.batchConfig?.batch) {
857
- patchFn();
858
- if (options?.snackBarConfig) {
859
- openSnackBarWithUndoOption(snackBar, options.snackBarConfig, [revertFn], [dbRevertFn]);
860
- }
861
- }
862
- } catch (e) {
863
- console.error(e);
864
- // will only get here when it's not a batch
865
- if (options?.snackBarConfig) {
866
- snackBar.open(
867
- options.snackBarConfig.failureMessage,
868
- '',
869
- options.snackBarConfig.config,
870
- );
871
- }
872
- throw e;
873
- } finally {
874
- // stop loading icon
875
- options?.loading?.set(false);
876
- }
877
- }
878
- },
879
- })),
880
- );
881
- }
882
-
883
- /**
884
- * Select entities from store given the entityMap and queries.
885
- * Filters out any entities that have '_deleted' === true. In general
886
- * this shouldn't matter, but in case someone intentionally sets
887
- * the _deleted parameter, this adds more robustness.
888
- * Note: firestore supports setting and querying for null, but not
889
- * undefined. We filter out cases where the value is undefined
890
- * to protect against cases when people are doing a nested query
891
- * and some entity does not have a particular field, e.g.
892
- * [['__hashtagId', '==', q.__hashtagId]] when __hashtagId is
893
- * an optional parameter
894
- */
895
- export function selectEntities<T>(entityMap: Record<string, T>, queryParams: QueryParams, queryOptions: QueryOptions): T[] {
896
- let filteredEntities = [];
897
-
898
- // APPLY '__id', '=='/in FILTERS
899
- const selectIdEqQueries = queryParams.filter((q) => q[0] === '__id' && q[1] === '==' && q[2] !== undefined);
900
- const uniqSelectEqIds = selectIdEqQueries.map((q) => q[2]).filter((q, i, a) => a.indexOf(q) === i);
901
- const selectIdInQueries = queryParams
902
- .filter((q) => q[0] === '__id' && q[1] === 'in' && q[2] !== undefined)
903
- .map((q) => [q[0], q[1], q[2].filter((v) => v !== undefined)])
904
- .filter((q) => q[2].length > 0);
905
-
906
- if (uniqSelectEqIds.length === 1 && entityMap[uniqSelectEqIds[0]] && !entityMap[uniqSelectEqIds[0]]['_deleted']) {
907
- // If there is exactly one '__id', we can start with that to filter
908
- filteredEntities.push(entityMap[uniqSelectEqIds[0]]);
909
- } else if (uniqSelectEqIds.length > 1) {
910
- // If there are more than one select id ==, then there cannot be any matches
911
- return [];
912
- } else if (selectIdInQueries.length > 0) {
913
- // If there is at least one 'in' query, start with that.
914
- const firstInIds = selectIdInQueries[0][2];
915
- filteredEntities = firstInIds.map((id) => entityMap[id]).filter((e) => e && !e['_deleted']);
916
-
917
- // Then apply remaining 'in' filters. See general filter section
918
- // for comments since this is just copied from that.
919
- if (selectIdInQueries.length > 1) {
920
- filteredEntities = filteredEntities.filter((e) => {
921
- return !selectIdInQueries.slice(1).find((f) => {
922
- const [key, rel, val] = f;
923
- return !(val.includes(e[key]));
924
- });
925
- });
926
- }
927
- } else {
928
- // Otherwise, start with the full list and filter further.
929
- filteredEntities = Object.keys(entityMap)
930
- .map((id) => entityMap[id])
931
- .filter((e) => e && !e['_deleted']);
932
- }
933
-
934
- // APPLY REMAINING FILTERS
935
- if (queryParams) {
936
- filteredEntities = filteredEntities.filter((e) => {
937
- // Looks for the first failed filter. If there exists any,
938
- // return false (filter it out)
939
- const filterValue = !queryParams.find((f) => {
940
- const [key, rel, val] = f;
941
-
942
- // already processed '__id', '=='/'in', so always passes this filter
943
- if (key === '__id' && (rel === '==' || rel === 'in')) {
944
- return false;
945
- }
946
-
947
- // value cannot be undefined. if it is, we ignore this query
948
- // parameter (so it always passes)
949
- if (val === undefined) {
950
- return false;
951
- }
952
-
953
- // we try to handle the same operations as Firestore for consistency
954
- switch (rel) {
955
- case '==':
956
- return !(e[key] === val);
957
-
958
- case '!=':
959
- return !(e[key] !== val);
960
-
961
- case '>=':
962
- return !(e[key] >= val);
963
-
964
- case '<=':
965
- return !(e[key] <= val);
966
-
967
- case '>':
968
- return !(e[key] > val);
969
-
970
- case '<':
971
- return !(e[key] < val);
972
-
973
- case 'array-contains':
974
- // If the parameter in question is optional, it should be filtered out
975
- return e[key] ? !e[key].includes(val) : true;
976
-
977
- case 'array-contains-any':
978
- // If the parameter in question is optional, it should be filtered out
979
- return e[key] ? !val.some((v) => e[key].includes(v)) : true;
980
-
981
- case 'in':
982
- return val.length > 0 && !val.includes(e[key]);
983
-
984
- case 'not-in':
985
- return val.includes(e[key]);
986
-
987
- default:
988
- return false;
989
- }
990
- });
991
- return filterValue;
992
- });
993
- }
994
-
995
- // Sort based on orderBy
996
- if (queryOptions?.orderBy) {
997
- // If orderBy is provided, will only return entities with that property
998
- // just like the Firestore API
999
-
1000
- let orderings: [string, string][] = [];
1001
- if (Array.isArray(queryOptions.orderBy)) {
1002
- if (Array.isArray(queryOptions.orderBy[0])) {
1003
- orderings = queryOptions.orderBy as [string, string][];
1004
- } else {
1005
- orderings = [queryOptions.orderBy as [string, string]];
1006
- }
1007
- } else {
1008
- orderings = [[queryOptions.orderBy as string, 'asc']];
1009
- }
1010
-
1011
- // Filter out entities missing any of the orderBy fields
1012
- for (const [field] of orderings) {
1013
- filteredEntities = filteredEntities.filter((e) => e[field] !== undefined && e[field] !== null);
1014
- }
1015
-
1016
- filteredEntities.sort((a, b) => {
1017
- for (const [field, order] of orderings) {
1018
- if (a[field] < b[field]) return order === 'desc' ? 1 : -1;
1019
- if (a[field] > b[field]) return order === 'desc' ? -1 : 1;
1020
- }
1021
- return 0;
1022
- });
1023
- }
1024
-
1025
- // Filter based on startAt/startAfter/endAt/endAfter
1026
- // Note: Only supports single field orderBy for cursor pagination in local store mock for now
1027
- if (queryOptions?.orderBy && (queryOptions?.startAt !== undefined || queryOptions?.startAfter !== undefined ||
1028
- queryOptions?.endAt !== undefined || queryOptions?.endBefore !== undefined)) {
1029
- let primaryField = '';
1030
- if (Array.isArray(queryOptions.orderBy)) {
1031
- if (Array.isArray(queryOptions.orderBy[0])) {
1032
- primaryField = queryOptions.orderBy[0][0];
1033
- } else {
1034
- primaryField = queryOptions.orderBy[0] as string;
1035
- }
1036
- } else {
1037
- primaryField = queryOptions.orderBy as string;
1038
- }
1039
-
1040
- filteredEntities = filteredEntities.filter((e) => {
1041
- const value = e[primaryField];
1042
- if (queryOptions.startAt !== undefined && value < queryOptions.startAt) {
1043
- return false;
1044
- }
1045
- if (queryOptions.startAfter !== undefined && value <= queryOptions.startAfter) {
1046
- return false;
1047
- }
1048
- if (queryOptions.endAt !== undefined && value > queryOptions.endAt) {
1049
- return false;
1050
- }
1051
- if (queryOptions.endBefore !== undefined && value >= queryOptions.endBefore) {
1052
- return false;
1053
- }
1054
- return true;
1055
- });
1056
- }
1057
-
1058
- // Limit based on limit
1059
- if (queryOptions?.limit !== undefined) {
1060
- filteredEntities = filteredEntities.slice(0, queryOptions.limit);
1061
- }
1062
-
1063
- return filteredEntities;
1064
- }
1065
-
1066
- /**
1067
- * Check whether the entity satisfies the query results.
1068
- * We use this to double-check whether a 'removed' change was truly
1069
- * removed from the backend or whether it just doesn't match
1070
- * the query anymore.
1071
- */
1072
- export function entityInQueryResults<T>(e: T, queryParams: QueryParams, queryOptions: QueryOptions): boolean {
1073
- if (queryParams) {
1074
- // Looks for the first failed filter. If there exists any,
1075
- // return false
1076
- const inQueryParams = !queryParams.find((f) => {
1077
- const [key, rel, val] = f;
1078
-
1079
- // value cannot be undefined. if it is, we ignore this query
1080
- // parameter (so it always passes)
1081
- if (val === undefined) {
1082
- return false;
1083
- }
1084
-
1085
- // we try to handle the same operations as Firestore for consistency
1086
- switch (rel) {
1087
- case '==':
1088
- return !(e[key] === val);
1089
-
1090
- case '!=':
1091
- return !(e[key] !== val);
1092
-
1093
- case '>=':
1094
- return !(e[key] >= val);
1095
-
1096
- case '<=':
1097
- return !(e[key] <= val);
1098
-
1099
- case '>':
1100
- return !(e[key] > val);
1101
-
1102
- case '<':
1103
- return !(e[key] < val);
1104
-
1105
- case 'array-contains':
1106
- // If the parameter in question is optional, it should be filtered out
1107
- return e[key] ? !e[key].includes(val) : true;
1108
-
1109
- case 'array-contains-any':
1110
- // If the parameter in question is optional, it should be filtered out
1111
- return e[key] ? !val.some((v) => e[key].includes(v)) : true;
1112
-
1113
- case 'in':
1114
- return !val.includes(e[key]);
1115
-
1116
- case 'not-in':
1117
- return val.includes(e[key]);
1118
-
1119
- default:
1120
- return false;
1121
- }
1122
- });
1123
-
1124
- if (!inQueryParams) {
1125
- return false;
1126
- }
1127
- }
1128
-
1129
- // Filter based on startAt/startAfter/endAt/endAfter
1130
- if (queryOptions?.orderBy && (queryOptions?.startAt !== undefined || queryOptions?.startAfter !== undefined ||
1131
- queryOptions?.endAt !== undefined || queryOptions?.endBefore !== undefined)) {
1132
- const value = e[queryOptions.orderBy as string];
1133
- if (queryOptions.startAt !== undefined && value < queryOptions.startAt) {
1134
- return false;
1135
- }
1136
- if (queryOptions.startAfter !== undefined && value <= queryOptions.startAfter) {
1137
- return false;
1138
- }
1139
- if (queryOptions.endAt !== undefined && value > queryOptions.endAt) {
1140
- return false;
1141
- }
1142
- if (queryOptions.endBefore !== undefined && value >= queryOptions.endBefore) {
1143
- return false;
1144
- }
1145
- }
1146
-
1147
- return true;
1148
- }
1149
-
1150
- export async function processLoadQueries<T extends { __id: string }>(entities: T[], loadQueries: (entity: T) => EntityLoadQuery<AnyEntity>[]) {
1151
- if (entities.length > 0) {
1152
- // create a matrix of queries, each row corresponding to a given entity
1153
- const queriesByEntity = entities.map((entity) => loadQueries!(entity));
1154
-
1155
- // transpose the matrix so each row corresponds to all queries for the same query type
1156
- const queriesByQueryType = queriesByEntity[0].map((_, colIndex) => queriesByEntity.map((row) => row[colIndex]));
1157
-
1158
- // Process all query types concurrently
1159
- await Promise.all(queriesByQueryType.map(async (queriesForOneType) => {
1160
- // Seeing if we can optimize by collapsing equality queries into 'in' queries
1161
- const optimizedQueries = EntityLoadQuery.optimize(queriesForOneType);
1162
-
1163
- // Process queries concurrently using Promise.all
1164
- await Promise.all(optimizedQueries.filter((q) => !!q).map(async (query) => {
1165
- // Firestore throws an error if an 'in' query is executed with an empty array.
1166
- // Therefore, we skip executing any queries that have an 'in' clause with an empty array.
1167
- // Example: ['__id', 'in', []]
1168
- if (!query.queryParams.some((param) => Array.isArray(param[2]) && param[2].length === 0 && param[1] === 'in')) {
1169
- await query.store.load(query.queryParams, query.queryOptions, query.loadQueries);
1170
- }
1171
- }));
1172
- }));
1173
- }
1174
- }
1175
-
1176
- export class EntityLoadQuery<T> {
1177
- collection: string;
1178
- queryParams: QueryParams;
1179
- queryOptions: QueryOptions;
1180
- loadQueries: (entity: T) => EntityLoadQuery<AnyEntity>[];
1181
- store;
1182
-
1183
- constructor(
1184
- collection: string,
1185
- store,
1186
- queryParams: QueryParams,
1187
- queryOptions: QueryOptions,
1188
- loadQueries?: (entity: T) => EntityLoadQuery<AnyEntity>[],
1189
- ) {
1190
- this.collection = collection;
1191
- this.queryParams = queryParams;
1192
- this.queryOptions = queryOptions;
1193
- this.loadQueries = loadQueries;
1194
- this.store = store;
1195
- }
1196
-
1197
- // Checks if there is a single equality query of the same type
1198
- // that could be transformed into an 'in' query
1199
- static areBatchableEqualityQueries<T>(queries: EntityLoadQuery<T>[]): boolean {
1200
- if (queries.length === 0) return false;
1201
-
1202
- // check if there is only one queryParam for each query and no queryOptions
1203
- const hasSingleQueryParamAndNoOptions = queries.every((q) => {
1204
- return q.queryParams.length === 1 && (!q.queryOptions || Object.keys(q.queryOptions).length === 0);
1205
- });
1206
-
1207
- if (!hasSingleQueryParamAndNoOptions) return false;
1208
-
1209
- // Finally, verify that every query is filtering on the exact same field
1210
- // (e.g., they are all querying '__userId') AND that they are all using the
1211
- // exact equality operator ('=='). This ensures they can be safely collapsed
1212
- // into a single 'in' query (e.g., '__userId in [1, 2, 3]').
1213
- const firstField = queries[0].queryParams[0][0];
1214
- return queries.every((q) => q.queryParams[0][0] === firstField && q.queryParams[0][1] === '==');
1215
- }
1216
-
1217
- // This currently only optimizes for N+1 queries, transforming input queries
1218
- // with a single where equality query (e.g. [['__postId', '==', x]]) and no queryParams.
1219
- // Transform this into 'in' queries, combining up to 30 equality clauses
1220
- // at the same time, https://firebase.google.com/docs/firestore/query-data/queries#in_and_array-contains-any.
1221
- static optimize<T>(queries: EntityLoadQuery<T>[]): EntityLoadQuery<T>[] {
1222
- // Optimization: batch N individual equality queries (e.g. [['__userId', '==', x]])
1223
- // into ceil(N/30) Firestore 'in' queries. This solves the N+1 problem where
1224
- // streaming N parent entities would otherwise create N individual child listeners.
1225
- //
1226
- // Tradeoff: batching changes the query key, which means per-query lastLoadTime
1227
- // tracking cannot efficiently provide incremental (delta-only) loads when the
1228
- // batch composition changes (entity added/removed). However, the reduction from
1229
- // N separate DB reads to 1 batched read far outweighs the cost of occasionally
1230
- // re-fetching already-loaded child documents.
1231
-
1232
- if (this.areBatchableEqualityQueries<T>(queries)) {
1233
- // get the field we are querying against
1234
- const collection: string = queries[0].collection;
1235
- const field: string = queries[0].queryParams[0][0];
1236
- const loadQs: (entity: T) => EntityLoadQuery<AnyEntity>[] = queries[0].loadQueries;
1237
-
1238
- // We no longer chunk into groups of 30 here. Instead, we bundle ALL IDs into a single 'in'
1239
- // query. The `load()` method will intercept this unified query, generate a single `newLoadTime`,
1240
- // and perform the 30-item chunking internally. This guarantees that all entities requested
1241
- // together receive the exact same timestamp.
1242
- const ids = queries.map((q) => q.queryParams[0][2]);
1243
- return [new EntityLoadQuery<T>(collection, queries[0].store, [[field, 'in', ids]], {}, loadQs)];
1244
- } else {
1245
- return queries;
1246
- }
1247
- }
1248
- }
1249
-
1250
- export class EntityStreamQuery<T> {
1251
- collection: string;
1252
- queryParams: QueryParams;
1253
- queryOptions: QueryOptions;
1254
- streamQueries: (entity: T) => EntityStreamQuery<AnyEntity>[];
1255
- store;
1256
-
1257
- constructor(
1258
- collection: string,
1259
- store,
1260
- queryParams: QueryParams,
1261
- queryOptions: QueryOptions,
1262
- streamQueries?: (entity: T) => EntityStreamQuery<AnyEntity>[],
1263
- ) {
1264
- this.collection = collection;
1265
- this.queryParams = queryParams;
1266
- this.queryOptions = queryOptions;
1267
- this.streamQueries = streamQueries;
1268
- this.store = store;
1269
- }
1270
-
1271
- // Checks if there is a single equality query of the same type
1272
- // that could be transformed into an 'in' query
1273
- static areBatchableEqualityQueries<T>(queries: EntityStreamQuery<T>[]): boolean {
1274
- if (queries.length === 0) return false;
1275
-
1276
- // check if there is only one queryParam for each query and no queryOptions
1277
- const hasSingleQueryParamAndNoOptions = queries.every((q) => {
1278
- return q.queryParams.length === 1 && (!q.queryOptions || Object.keys(q.queryOptions).length === 0);
1279
- });
1280
-
1281
- if (!hasSingleQueryParamAndNoOptions) return false;
1282
-
1283
- // Finally, verify that every query is filtering on the exact same field
1284
- // (e.g., they are all querying '__userId') AND that they are all using the
1285
- // exact equality operator ('=='). This ensures they can be safely collapsed
1286
- // into a single 'in' query (e.g., '__userId in [1, 2, 3]').
1287
- const firstField = queries[0].queryParams[0][0];
1288
- return queries.every((q) => q.queryParams[0][0] === firstField && q.queryParams[0][1] === '==');
1289
- }
1290
-
1291
- // This currently only optimizes for N+1 queries, transforming input queries
1292
- // with a single where equality query (e.g. [['__postId', '==', x]]) and no queryParams.
1293
- // Transform this into 'in' queries, combining up to 30 equality clauses
1294
- // at the same time, https://firebase.google.com/docs/firestore/query-data/queries#in_and_array-contains-any.
1295
- static optimize<T>(queries: EntityStreamQuery<T>[]): EntityStreamQuery<T>[] {
1296
- // Optimization: batch N individual equality queries into ceil(N/30) Firestore
1297
- // 'in' queries. For streams, the pairwise() diffing in processStreamQuery()
1298
- // ensures that only changed parent entities trigger nested queries. This means
1299
- // the initial batch of N entities gets optimally collapsed, while subsequent
1300
- // individual changes create small (typically 1-element) listeners.
1301
- //
1302
- // Listener lifecycle: batched 'in' listeners share the parent component's
1303
- // DestroyRef for cleanup, matching the behavior of individual listeners.
1304
-
1305
- if (this.areBatchableEqualityQueries<T>(queries)) {
1306
- // get the field we are querying against
1307
- const collection: string = queries[0].collection;
1308
- const field: string = queries[0].queryParams[0][0];
1309
- const streamQs: (entity: T) => EntityStreamQuery<AnyEntity>[] = queries[0].streamQueries;
1310
-
1311
- const ids = queries.map((q) => q.queryParams[0][2]);
1312
- return [new EntityStreamQuery<T>(collection, queries[0].store, [[field, 'in', ids]], {}, streamQs)];
1313
- } else {
1314
- return queries;
1315
- }
1316
- }
1317
- }