@tech4good/angular-schematics 21.6.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 (229) hide show
  1. package/CHANGELOG.md +28 -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 +14 -6
  7. package/src/entity/files/__name@dasherize__/__name@dasherize__.model.ts.template +12 -6
  8. package/src/entity/files/__name@dasherize__/__name@dasherize__.store.ts.template +18 -10
  9. package/src/entity/index.js +4 -49
  10. package/src/entity/index.js.map +1 -1
  11. package/src/guard/files/__name@dasherize__.guard.spec.ts.template +0 -1
  12. package/src/ng-add/files/.github/workflows/angular-github-ci.yml.template +3 -0
  13. package/src/ng-add/files/.gitignore.template +3 -0
  14. package/src/ng-add/files/analytics/datasets.js.template +206 -0
  15. package/src/ng-add/files/analytics/entity_sources.js.template +58 -0
  16. package/src/ng-add/files/analytics/entity_sources.test.js.template +57 -0
  17. package/src/ng-add/files/analytics/lib/api_query.js.template +87 -0
  18. package/src/ng-add/files/analytics/lib/api_query.test.js.template +84 -0
  19. package/src/ng-add/files/analytics/lib/bigquery_query_compatibility.test.js.template +53 -0
  20. package/src/ng-add/files/analytics/lib/dataset_schema.js.template +53 -0
  21. package/src/ng-add/files/analytics/lib/dataset_schema.test.js.template +34 -0
  22. package/src/ng-add/files/analytics/lib/entity_sync.js.template +397 -0
  23. package/src/ng-add/files/analytics/lib/entity_sync.test.js.template +212 -0
  24. package/src/ng-add/files/analytics/lib/identifier_salt.js.template +57 -0
  25. package/src/ng-add/files/analytics/lib/identifier_salt.test.js.template +36 -0
  26. package/src/ng-add/files/analytics/lib/snapshot_files.js.template +46 -0
  27. package/src/ng-add/files/analytics/lib/snapshot_files.test.js.template +67 -0
  28. package/src/ng-add/files/analytics/lib/sqlite.js.template +92 -0
  29. package/src/ng-add/files/analytics/lib/upload_entities.js.template +81 -0
  30. package/src/ng-add/files/analytics/lib/upload_entities.test.js.template +86 -0
  31. package/src/ng-add/files/analytics/proxy.conf.json.template +7 -0
  32. package/src/ng-add/files/analytics/scripts/refresh_snapshot.js.template +518 -0
  33. package/src/ng-add/files/analytics/scripts/start.js.template +88 -0
  34. package/src/ng-add/files/analytics/server/server.js.template +212 -0
  35. package/src/ng-add/files/angular.json.template +80 -1
  36. package/src/ng-add/files/bigquery/queries/active_time_by_route.sql.template +27 -8
  37. package/src/ng-add/files/bigquery/queries/active_user_windows.sql.template +67 -0
  38. package/src/ng-add/files/bigquery/queries/dashboard_route_visits.sql.template +47 -0
  39. package/src/ng-add/files/bigquery/queries/data_quality.sql.template +323 -0
  40. package/src/ng-add/files/bigquery/queries/onboarding_funnel.sql.template +512 -0
  41. package/src/ng-add/files/bigquery/queries/onboarding_stage_observations.sql.template +134 -0
  42. package/src/ng-add/files/bigquery/queries/weekly_retention_cohorts.sql.template +90 -0
  43. package/src/ng-add/files/bigquery/scripts/export_entities.js.template +120 -0
  44. package/src/ng-add/files/bigquery/scripts/init_views.js.template +57 -0
  45. package/src/ng-add/files/bigquery/scripts/run_query.js.template +141 -0
  46. package/src/ng-add/files/bigquery/views/events_flat.sql.template +27 -12
  47. package/src/ng-add/files/bigquery/views/logs_latest.sql.template +16 -3
  48. package/src/ng-add/files/docs-infra/analytics-guide.md.template +270 -25
  49. package/src/ng-add/files/docs-infra/analytics-workbench-guide.md.template +307 -0
  50. package/src/ng-add/files/docs-infra/authentication-architecture.md.template +54 -24
  51. package/src/ng-add/files/docs-infra/email-infrastructure.md.template +43 -0
  52. package/src/ng-add/files/docs-infra/firestore-index-checker.md.template +87 -0
  53. package/src/ng-add/files/docs-infra/infrastructure-guide.md.template +108 -29
  54. package/src/ng-add/files/docs-infra/load-system-architecture.md.template +15 -1
  55. package/src/ng-add/files/docs-infra/querying-strategy.md.template +14 -0
  56. package/src/ng-add/files/docs-infra/stream-system-architecture.md.template +21 -7
  57. package/src/ng-add/files/eslint.config.js.template +22 -3
  58. package/src/ng-add/files/functions/package.json.template +1 -0
  59. package/src/ng-add/files/functions/src/email.ts.template +23 -0
  60. package/src/ng-add/files/jest.config.ts.template +3 -2
  61. package/src/ng-add/files/package.json.template +39 -16
  62. package/src/ng-add/files/projects/analytics/src/app/analytics-api.service.ts.template +130 -0
  63. package/src/ng-add/files/projects/analytics/src/app/app.component.html.template +77 -0
  64. package/src/ng-add/files/projects/analytics/src/app/app.component.scss.template +240 -0
  65. package/src/ng-add/files/projects/analytics/src/app/app.component.ts.template +96 -0
  66. package/src/ng-add/files/projects/analytics/src/app/app.routes.ts.template +11 -0
  67. package/src/ng-add/files/projects/analytics/src/app/dashboard-pages.spec.ts.template +151 -0
  68. package/src/ng-add/files/projects/analytics/src/app/data-quality/data-quality-page/data-quality-page.component.html.template +39 -0
  69. package/src/ng-add/files/projects/analytics/src/app/data-quality/data-quality-page/data-quality-page.component.scss.template +1 -0
  70. package/src/ng-add/files/projects/analytics/src/app/data-quality/data-quality-page/data-quality-page.component.ts.template +95 -0
  71. package/src/ng-add/files/projects/analytics/src/app/engagement/engagement-page/engagement-page.component.html.template +47 -0
  72. package/src/ng-add/files/projects/analytics/src/app/engagement/engagement-page/engagement-page.component.scss.template +1 -0
  73. package/src/ng-add/files/projects/analytics/src/app/engagement/engagement-page/engagement-page.component.ts.template +120 -0
  74. package/src/ng-add/files/projects/analytics/src/app/onboarding/onboarding-page/onboarding-page.component.html.template +40 -0
  75. package/src/ng-add/files/projects/analytics/src/app/onboarding/onboarding-page/onboarding-page.component.scss.template +1 -0
  76. package/src/ng-add/files/projects/analytics/src/app/onboarding/onboarding-page/onboarding-page.component.ts.template +98 -0
  77. package/src/ng-add/files/projects/analytics/src/app/overview/overview-page/overview-page.component.html.template +35 -0
  78. package/src/ng-add/files/projects/analytics/src/app/overview/overview-page/overview-page.component.scss.template +1 -0
  79. package/src/ng-add/files/projects/analytics/src/app/overview/overview-page/overview-page.component.ts.template +84 -0
  80. package/src/ng-add/files/projects/analytics/src/app/routes/routes-page/routes-page.component.html.template +42 -0
  81. package/src/ng-add/files/projects/analytics/src/app/routes/routes-page/routes-page.component.scss.template +1 -0
  82. package/src/ng-add/files/projects/analytics/src/app/routes/routes-page/routes-page.component.ts.template +110 -0
  83. package/src/ng-add/files/projects/analytics/src/app/shared/analytics-utils.ts.template +43 -0
  84. package/src/ng-add/files/projects/analytics/src/app/shared/chart-theme.ts.template +42 -0
  85. package/src/ng-add/files/projects/analytics/src/app/shared/dashboard-layout.scss.template +239 -0
  86. package/src/ng-add/files/projects/analytics/src/app/shared/dashboard-table/dashboard-table.component.html.template +76 -0
  87. package/src/ng-add/files/projects/analytics/src/app/shared/dashboard-table/dashboard-table.component.scss.template +128 -0
  88. package/src/ng-add/files/projects/analytics/src/app/shared/dashboard-table/dashboard-table.component.spec.ts.template +31 -0
  89. package/src/ng-add/files/projects/analytics/src/app/shared/dashboard-table/dashboard-table.component.ts.template +153 -0
  90. package/src/ng-add/files/projects/analytics/src/app/shared/funnel-chart/funnel-chart.component.html.template +16 -0
  91. package/src/ng-add/files/projects/analytics/src/app/shared/funnel-chart/funnel-chart.component.scss.template +63 -0
  92. package/src/ng-add/files/projects/analytics/src/app/shared/funnel-chart/funnel-chart.component.ts.template +52 -0
  93. package/src/ng-add/files/projects/analytics/src/app/shared/metric-card/metric-card.component.html.template +5 -0
  94. package/src/ng-add/files/projects/analytics/src/app/shared/metric-card/metric-card.component.scss.template +56 -0
  95. package/src/ng-add/files/projects/analytics/src/app/shared/metric-card/metric-card.component.spec.ts.template +30 -0
  96. package/src/ng-add/files/projects/analytics/src/app/shared/metric-card/metric-card.component.ts.template +15 -0
  97. package/src/ng-add/files/projects/analytics/src/app/shared/quality-chart/quality-chart.component.html.template +9 -0
  98. package/src/ng-add/files/projects/analytics/src/app/shared/quality-chart/quality-chart.component.scss.template +43 -0
  99. package/src/ng-add/files/projects/analytics/src/app/shared/quality-chart/quality-chart.component.ts.template +62 -0
  100. package/src/ng-add/files/projects/analytics/src/app/shared/route-distribution-chart/route-distribution-chart.component.html.template +9 -0
  101. package/src/ng-add/files/projects/analytics/src/app/shared/route-distribution-chart/route-distribution-chart.component.scss.template +33 -0
  102. package/src/ng-add/files/projects/analytics/src/app/shared/route-distribution-chart/route-distribution-chart.component.ts.template +82 -0
  103. package/src/ng-add/files/projects/analytics/src/app/shared/route-traffic-chart/route-traffic-chart.component.html.template +15 -0
  104. package/src/ng-add/files/projects/analytics/src/app/shared/route-traffic-chart/route-traffic-chart.component.scss.template +45 -0
  105. package/src/ng-add/files/projects/analytics/src/app/shared/route-traffic-chart/route-traffic-chart.component.ts.template +55 -0
  106. package/src/ng-add/files/projects/analytics/src/app/shared/status-message/status-message.component.html.template +18 -0
  107. package/src/ng-add/files/projects/analytics/src/app/shared/status-message/status-message.component.scss.template +45 -0
  108. package/src/ng-add/files/projects/analytics/src/app/shared/status-message/status-message.component.ts.template +15 -0
  109. package/src/ng-add/files/projects/analytics/src/app/vega-chart/vega-chart.component.ts.template +121 -0
  110. package/src/ng-add/files/projects/analytics/src/index.html.template +19 -0
  111. package/src/ng-add/files/projects/analytics/src/main.ts.template +16 -0
  112. package/src/ng-add/files/projects/analytics/src/styles.scss.template +28 -0
  113. package/src/ng-add/files/projects/analytics/tsconfig.app.json.template +13 -0
  114. package/src/ng-add/files/projects/analytics/tsconfig.spec.json.template +15 -0
  115. package/src/ng-add/files/src/app/admin/admin-panel/admin-panel.component.spec.ts.template +4 -5
  116. package/src/ng-add/files/src/app/admin/admin-panel/admin-settings/admin-settings.component.spec.ts.template +4 -5
  117. package/src/ng-add/files/src/app/admin/admin-panel/admin-user-list/admin-user-list.component.spec.ts.template +11 -12
  118. package/src/ng-add/files/src/app/admin/admin-panel/admin-user-list/admin-user-list.component.ts.template +7 -7
  119. 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
  120. package/src/ng-add/files/src/app/admin/admin-panel/admin-user-list/admin-user-table/admin-user-table.component.ts.template +3 -2
  121. package/src/ng-add/files/src/app/app.component.html.template +1 -1
  122. package/src/ng-add/files/src/app/app.component.scss.template +1 -1
  123. package/src/ng-add/files/src/app/app.component.spec.ts.template +4 -5
  124. package/src/ng-add/files/src/app/app.component.ts.template +1 -2
  125. package/src/ng-add/files/src/app/app.config.ts.template +21 -15
  126. package/src/ng-add/files/src/app/auth-routing.spec.ts.template +4 -5
  127. package/src/ng-add/files/src/app/core/analytics/time-analytics.service.spec.ts.template +46 -29
  128. package/src/ng-add/files/src/app/core/analytics/time-analytics.service.ts.template +27 -18
  129. package/src/ng-add/files/src/app/core/auth/auth.providers.spec.ts.template +112 -0
  130. package/src/ng-add/files/src/app/core/auth/auth.providers.ts.template +48 -0
  131. package/src/ng-add/files/src/app/core/auth/auth.service.ts.template +9 -23
  132. package/src/ng-add/files/src/app/core/auth/guards/require-admin.guard.spec.ts.template +3 -14
  133. package/src/ng-add/files/src/app/core/firebase/data.providers.prod.ts.template +21 -0
  134. package/src/ng-add/files/src/app/core/firebase/data.providers.ts.template +13 -0
  135. package/src/ng-add/files/src/app/core/local-storage/session.service.spec.ts.template +43 -0
  136. package/src/ng-add/files/src/app/core/local-storage/session.service.ts.template +7 -0
  137. package/src/ng-add/files/src/app/core/store/app-data.spec.ts.template +76 -0
  138. package/src/ng-add/files/src/app/core/store/auth/auth.mock.ts.template +19 -67
  139. package/src/ng-add/files/src/app/core/store/auth/auth.store.spec.ts.template +102 -12
  140. package/src/ng-add/files/src/app/core/store/auth/auth.store.ts.template +32 -237
  141. package/src/ng-add/files/src/app/core/store/user/user.mock.ts.template +17 -12
  142. package/src/ng-add/files/src/app/core/store/user/user.model.ts.template +6 -7
  143. package/src/ng-add/files/src/app/core/store/user/user.store.ts.template +14 -10
  144. package/src/ng-add/files/src/app/core/store/user-context/user-context.mock.ts.template +20 -8
  145. package/src/ng-add/files/src/app/core/store/user-context/user-context.model.ts.template +5 -6
  146. package/src/ng-add/files/src/app/core/store/user-context/user-context.store.ts.template +14 -10
  147. package/src/ng-add/files/src/app/core/store/user-private/user-private.mock.ts.template +20 -7
  148. package/src/ng-add/files/src/app/core/store/user-private/user-private.model.ts.template +5 -6
  149. package/src/ng-add/files/src/app/core/store/user-private/user-private.store.ts.template +14 -10
  150. package/src/ng-add/files/src/app/core/testing/app-mocks.ts.template +42 -0
  151. package/src/ng-add/files/src/app/first-time/consent/consent.component.html.template +2 -1
  152. package/src/ng-add/files/src/app/first-time/consent/consent.component.scss.template +7 -3
  153. package/src/ng-add/files/src/app/first-time/consent/consent.component.spec.ts.template +31 -11
  154. package/src/ng-add/files/src/app/first-time/consent/consent.component.ts.template +16 -1
  155. package/src/ng-add/files/src/app/first-time/early-access/early-access.component.spec.ts.template +15 -15
  156. package/src/ng-add/files/src/app/first-time/early-access/early-access.component.ts.template +11 -3
  157. package/src/ng-add/files/src/app/first-time/early-access/survey-form/survey-form.component.html.template +2 -1
  158. package/src/ng-add/files/src/app/first-time/early-access/survey-form/survey-form.component.scss.template +7 -3
  159. package/src/ng-add/files/src/app/first-time/early-access/survey-form/survey-form.component.spec.ts.template +20 -6
  160. package/src/ng-add/files/src/app/first-time/early-access/survey-form/survey-form.component.ts.template +2 -0
  161. package/src/ng-add/files/src/app/first-time/early-access/waitlist-view/waitlist-view.component.spec.ts.template +4 -5
  162. package/src/ng-add/files/src/app/first-time/email-link/email-link.component.spec.ts.template +17 -1
  163. package/src/ng-add/files/src/app/first-time/email-link/email-link.component.ts.template +15 -0
  164. package/src/ng-add/files/src/app/first-time/first-time-routing.spec.ts.template +4 -5
  165. package/src/ng-add/files/src/app/first-time/landing/hero/hero.component.ts.template +15 -0
  166. package/src/ng-add/files/src/app/first-time/landing/landing.component.spec.ts.template +2 -0
  167. package/src/ng-add/files/src/app/first-time/login/login.component.spec.ts.template +21 -3
  168. package/src/ng-add/files/src/app/first-time/login/login.component.ts.template +26 -0
  169. package/src/ng-add/files/src/app/first-time/onboarding/onboarding.component.spec.ts.template +4 -2
  170. package/src/ng-add/files/src/app/first-time/onboarding/onboarding.component.ts.template +1 -1
  171. package/src/ng-add/files/src/app/main/account-profile/account-profile.component.spec.ts.template +2 -2
  172. package/src/ng-add/files/src/app/main/account-profile/delete-guest-card/delete-guest-card.component.spec.ts.template +2 -2
  173. package/src/ng-add/files/src/app/main/account-profile/profile-details-card/profile-details-card.component.spec.ts.template +4 -4
  174. package/src/ng-add/files/src/app/main/account-profile/sign-in-methods-card/sign-in-methods-card.component.spec.ts.template +2 -2
  175. package/src/ng-add/files/src/app/main/home/home.component.spec.ts.template +4 -5
  176. package/src/ng-add/files/src/app/main/home/home.component.ts.template +1 -1
  177. package/src/ng-add/files/src/app/shared/guest-warning-bar/guest-warning-bar.component.spec.ts.template +4 -4
  178. package/src/ng-add/files/src/app/shared/navbar/navbar.component.spec.ts.template +2 -2
  179. package/src/ng-add/files/tsconfig.spec.json.template +3 -1
  180. package/src/ng-add/index.js +7 -0
  181. package/src/ng-add/index.js.map +1 -1
  182. package/src/shared/entity-registry.d.ts +8 -0
  183. package/src/shared/entity-registry.js +28 -0
  184. package/src/shared/entity-registry.js.map +1 -0
  185. package/.agents/skills/publish-npm/SKILL.md +0 -37
  186. package/.agents/skills/publish-npm/eval.yaml +0 -32
  187. package/.agents/skills/publish-npm/fixtures/package-v21.json.template +0 -8
  188. package/.husky/commit-msg +0 -1
  189. package/.husky/pre-commit +0 -1
  190. package/.t4g/agent-memory.db +0 -0
  191. package/src/component/index_spec.d.ts +0 -1
  192. package/src/component/index_spec.js +0 -68
  193. package/src/component/index_spec.js.map +0 -1
  194. package/src/entity/index_spec.d.ts +0 -1
  195. package/src/entity/index_spec.js +0 -153
  196. package/src/entity/index_spec.js.map +0 -1
  197. package/src/guard/index_spec.d.ts +0 -1
  198. package/src/guard/index_spec.js +0 -64
  199. package/src/guard/index_spec.js.map +0 -1
  200. package/src/ng-add/files/bigquery/scripts/export_entities.py.template +0 -143
  201. package/src/ng-add/files/bigquery/scripts/run_query.py.template +0 -167
  202. package/src/ng-add/files/src/app/core/firebase/cached-listeners.service.ts.template +0 -500
  203. package/src/ng-add/files/src/app/core/firebase/database.service.ts.template +0 -73
  204. package/src/ng-add/files/src/app/core/firebase/email-link-context.service.spec.ts.template +0 -59
  205. package/src/ng-add/files/src/app/core/firebase/email-link-context.service.ts.template +0 -147
  206. package/src/ng-add/files/src/app/core/firebase/firebase.mock.service.ts.template +0 -453
  207. package/src/ng-add/files/src/app/core/firebase/firebase.service.spec.ts.template +0 -116
  208. package/src/ng-add/files/src/app/core/firebase/firebase.service.ts.template +0 -639
  209. package/src/ng-add/files/src/app/core/firebase/simulate-load.spec.ts.template +0 -104
  210. package/src/ng-add/files/src/app/core/firebase/simulate-stream.spec.ts.template +0 -127
  211. package/src/ng-add/files/src/app/core/firebase/simulation.mock.ts.template +0 -38
  212. package/src/ng-add/files/src/app/core/firebase/stream-multiplexer.ts.template +0 -445
  213. package/src/ng-add/files/src/app/core/logging/logging.service.spec.ts.template +0 -118
  214. package/src/ng-add/files/src/app/core/logging/logging.service.ts.template +0 -168
  215. package/src/ng-add/files/src/app/core/store/app.model.ts.template +0 -21
  216. package/src/ng-add/files/src/app/core/store/app.store.spec.ts.template +0 -920
  217. package/src/ng-add/files/src/app/core/store/app.store.ts.template +0 -1320
  218. package/src/ng-add/files/src/app/core/store/batch-write.firebase.service.ts.template +0 -58
  219. package/src/ng-add/files/src/app/core/store/batch-write.mock.service.ts.template +0 -105
  220. package/src/ng-add/files/src/app/core/store/batch-write.service.ts.template +0 -126
  221. package/src/ng-add/files/src/app/shared/redeployment-warning/redeployment-warning.component.html.template +0 -9
  222. package/src/ng-add/files/src/app/shared/redeployment-warning/redeployment-warning.component.scss.template +0 -46
  223. package/src/ng-add/files/src/app/shared/redeployment-warning/redeployment-warning.component.spec.ts.template +0 -69
  224. package/src/ng-add/files/src/app/shared/redeployment-warning/redeployment-warning.component.ts.template +0 -39
  225. package/src/ng-add/files/src/app/shared/redeployment-warning/redeployment-warning.service.spec.ts.template +0 -122
  226. package/src/ng-add/files/src/app/shared/redeployment-warning/redeployment-warning.service.ts.template +0 -88
  227. package/src/ng-add/index_spec.d.ts +0 -1
  228. package/src/ng-add/index_spec.js +0 -108
  229. package/src/ng-add/index_spec.js.map +0 -1
@@ -1,147 +0,0 @@
1
- import { DOCUMENT } from '@angular/common';
2
- import { Injectable, inject } from '@angular/core';
3
-
4
- /** Supported email magic link authentication workflows. */
5
- export type EmailLinkFlow = 'sign-in' | 'guest-upgrade' | 'link-email';
6
-
7
- /**
8
- * Encapsulates the same-browser state required to complete an email link authentication request.
9
- */
10
- type EmailLinkContext = {
11
- /** The target email address the magic link was sent to. */
12
- email: string;
13
- /** The intended authentication workflow. */
14
- flow: EmailLinkFlow;
15
- /** The current user's Firebase UID if upgrading a guest or linking email to an existing account. */
16
- uid: string | null;
17
- };
18
-
19
- /**
20
- * Manages same-browser context persistence for passwordless email magic link sign-in flows.
21
- *
22
- * When a user requests a magic link, Firebase Auth redirects them out of the app to their email client.
23
- * Upon clicking the link in the email, the user lands back on the `/auth/action` route.
24
- * To securely process the callback, the application must verify the originating email address,
25
- * flow type, and originating user UID (for account upgrades/linking).
26
- *
27
- * To remain resilient against browser storage restrictions (e.g., Safari ITP, private browsing mode),
28
- * this service uses a dual-layer strategy:
29
- * 1. Primary storage in `localStorage`.
30
- * 2. Fallback in a short-lived (30-minute), `SameSite=Lax` cookie.
31
- */
32
- @Injectable({
33
- providedIn: 'root',
34
- })
35
- export class EmailLinkContextService {
36
- private readonly document = inject(DOCUMENT);
37
- private readonly emailKey = 'app.email-link.email';
38
- private readonly flowKey = 'app.email-link.flow';
39
- private readonly uidKey = 'app.email-link.uid';
40
- private readonly maxAgeSeconds = 30 * 60;
41
-
42
- /**
43
- * Persists email magic link context into localStorage and fallback cookies before sending the email.
44
- *
45
- * @param context The email, flow type, and optional originating UID to store.
46
- */
47
- remember(context: EmailLinkContext): void {
48
- this.set(this.emailKey, context.email);
49
- this.set(this.flowKey, context.flow);
50
- if (context.uid) this.set(this.uidKey, context.uid);
51
- else this.remove(this.uidKey);
52
- }
53
-
54
- /** Retrieves the stored target email address, or `null` if not found or expired. */
55
- getEmail(): string | null {
56
- return this.get(this.emailKey);
57
- }
58
-
59
- /** Retrieves the stored email link flow type (`sign-in`, `guest-upgrade`, or `link-email`). */
60
- getFlow(): EmailLinkFlow | null {
61
- const flow = this.get(this.flowKey);
62
- return flow === 'sign-in' || flow === 'guest-upgrade' || flow === 'link-email' ? flow : null;
63
- }
64
-
65
- /** Retrieves the originating UID for account upgrading/linking flows. */
66
- getUid(): string | null {
67
- return this.get(this.uidKey);
68
- }
69
-
70
- /**
71
- * Clears the persisted context if all fields match the completed context.
72
- */
73
- clearIfMatches(context: EmailLinkContext): void {
74
- if (
75
- this.getEmail() === context.email &&
76
- this.getFlow() === context.flow &&
77
- this.getUid() === context.uid
78
- ) {
79
- this.clear();
80
- }
81
- }
82
-
83
- /** Clears all stored email link context from both localStorage and cookies. */
84
- clear(): void {
85
- this.remove(this.emailKey);
86
- this.remove(this.flowKey);
87
- this.remove(this.uidKey);
88
- }
89
-
90
- /** Safe getter for `localStorage` that handles SSR or restricted window contexts. */
91
- private get storage(): Storage | null {
92
- try {
93
- return this.document.defaultView?.localStorage || null;
94
- } catch {
95
- return null;
96
- }
97
- }
98
-
99
- /** Reads a stored value from localStorage with cookie fallback. */
100
- private get(key: string): string | null {
101
- try {
102
- const storedValue = this.storage?.getItem(key);
103
- if (storedValue) return storedValue;
104
- } catch {
105
- // Fall back to the short-lived cookie below.
106
- }
107
- return this.getCookie(key);
108
- }
109
-
110
- /** Writes a value to both localStorage and a short-lived cookie. */
111
- private set(key: string, value: string): void {
112
- try {
113
- this.storage?.setItem(key, value);
114
- } catch {
115
- // The cookie still preserves the same-browser callback context.
116
- }
117
- this.setCookie(key, value);
118
- }
119
-
120
- /** Removes a key from both localStorage and cookies. */
121
- private remove(key: string): void {
122
- try {
123
- this.storage?.removeItem(key);
124
- } catch {
125
- // The cookie is cleared independently below.
126
- }
127
- this.document.cookie = `${encodeURIComponent(key)}=; Path=/; Max-Age=0; SameSite=Lax`;
128
- }
129
-
130
- /** Reads a cookie by key. */
131
- private getCookie(key: string): string | null {
132
- const encodedKey = `${encodeURIComponent(key)}=`;
133
- const match = this.document.cookie
134
- .split(';')
135
- .map((cookie) => cookie.trim())
136
- .find((cookie) => cookie.startsWith(encodedKey));
137
- return match ? decodeURIComponent(match.slice(encodedKey.length)) : null;
138
- }
139
-
140
- /** Writes a cookie with 30-minute max-age and SameSite=Lax. */
141
- private setCookie(key: string, value: string): void {
142
- const secure = this.document.location?.protocol === 'https:' ? '; Secure' : '';
143
- this.document.cookie =
144
- `${encodeURIComponent(key)}=${encodeURIComponent(value)}; ` +
145
- `Path=/; Max-Age=${this.maxAgeSeconds}; SameSite=Lax${secure}`;
146
- }
147
- }
@@ -1,453 +0,0 @@
1
- import { Injectable, inject, Injector, computed, Provider } from '@angular/core';
2
- import { toObservable } from '@angular/core/rxjs-interop';
3
- import { Observable, combineLatest, merge, of, from, pipe, BehaviorSubject, throwError, NEVER } from 'rxjs';
4
- import { tap, pluck, mergeMap, pairwise, delay, startWith, filter, takeUntil, skip, switchMap, map, take } from 'rxjs/operators';
5
- import { environment } from '../../../environments/environment';
6
- import { DocumentSnapshot, serverTimestamp, Timestamp, getDoc, getDocs, doc, setDoc, updateDoc, deleteDoc, docData, collection, collectionData, collectionChanges, query, where, orderBy, OrderByDirection, limit, startAt, startAfter, endAt, endBefore, DocumentChange, increment, AggregateQuerySnapshot, AggregateField, AggregateSpec, getAggregateFromServer, getCountFromServer } from '@angular/fire/firestore';
7
- import { AnyEntity, QueryParams, QueryOptions } from '../store/app.model';
8
- import { AuthSession, DatabaseService, DATABASE_SERVICE } from './database.service';
9
- import { SelectEntityId } from '@ngrx/signals/entities';
10
- import { AuthMockDB } from '../store/auth/auth.mock';
11
- import { AccessState, User } from '../store/user/user.model';
12
-
13
- // Entity Model DB Data
14
- import { UserMockDB, USER_DB } from '../store/user/user.mock';
15
- import { UserContextMockDB, USERCONTEXT_DB } from '../store/user-context/user-context.mock';
16
- import { UserPrivateMockDB, USERPRIVATE_DB } from '../store/user-private/user-private.mock';
17
-
18
- const selectId: SelectEntityId<AnyEntity> = (entity) => entity.__id;
19
-
20
- @Injectable({
21
- providedIn: 'root',
22
- })
23
- export class FirebaseMockService implements DatabaseService {
24
- readonly authDB = inject(AuthMockDB);
25
- readonly DB = {
26
- 'users': inject(UserMockDB),
27
- 'userContexts': inject(UserContextMockDB),
28
- 'userPrivates': inject(UserPrivateMockDB),
29
- };
30
- private user$ = new BehaviorSubject(this.authDB.afUser());
31
-
32
- // Constant for simulating delay (e.g. to see loading icon in action)
33
- GET_LATENCY_SIMULATION_DELAY = 100;
34
- PUT_LATENCY_SIMULATION_DELAY = 300;
35
-
36
- /**
37
- * Collections that throw/reject on any read operation.
38
- * Set via `provideFirebaseMock({ failCollections: [...] })` or mutate mid-test
39
- * via `db.failCollections = [...]` to simulate error → recovery flows.
40
- */
41
- failCollections: string[] = [];
42
-
43
- /**
44
- * Collections where reads never emit/resolve (simulates perpetual loading).
45
- * Set via `provideFirebaseMock({ stallCollections: [...] })` or mutate mid-test
46
- * via `db.stallCollections = [...]`.
47
- */
48
- stallCollections: string[] = [];
49
-
50
- constructor(
51
- private injector: Injector,
52
- ) {
53
- // Init Entity Models
54
- this.DB['users'].init(USER_DB);
55
- this.DB['userContexts'].init(USERCONTEXT_DB);
56
- this.DB['userPrivates'].init(USERPRIVATE_DB);
57
- }
58
-
59
- /** Creates a unique id */
60
- createId(): string {
61
- // see https://stackoverflow.com/questions/56574593/access-firestore-id-generator-on-the-front-end?noredirect=1&lq=1
62
- // see https://github.com/firebase/firebase-js-sdk/blob/73a586c92afe3f39a844b2be86086fddb6877bb7/packages/firestore/src/util/misc.ts#L36
63
- // Alphanumeric characters
64
- const chars =
65
- 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
66
- let autoId = '';
67
- for (let i = 0; i < 20; i++) {
68
- autoId += chars.charAt(Math.floor(Math.random() * chars.length));
69
- }
70
- return autoId;
71
- }
72
-
73
- afUser(): Observable<AuthSession | null> {
74
- return this.user$;
75
- }
76
-
77
- private setSession(session: AuthSession | null): void {
78
- this.user$.next(session);
79
- }
80
-
81
- async signInWithGoogle(): Promise<AuthSession> {
82
- await this.authDB.signInWithGoogle();
83
- const session = this.authDB.afUser()!;
84
- this.setSession(session);
85
- return session;
86
- }
87
-
88
- async signInAnonymously(): Promise<AuthSession> {
89
- await this.authDB.loginAnonymously();
90
- const session = this.authDB.afUser()!;
91
- this.setSession(session);
92
- return session;
93
- }
94
-
95
- async linkGoogle(): Promise<AuthSession> {
96
- await this.authDB.linkGoogle();
97
- const session = this.authDB.afUser()!;
98
- this.setSession(session);
99
- return session;
100
- }
101
-
102
- async sendEmailSignInLink(): Promise<void> {}
103
-
104
- async sendEmailLinkForCurrentAccount(): Promise<void> {}
105
-
106
- getStoredEmailForEmailLink(): string | null {
107
- return null;
108
- }
109
-
110
- async completeEmailSignInLink(): Promise<AuthSession> {
111
- const session = await this.authDB.completeEmailSignInLink();
112
- this.setSession(session);
113
- return session;
114
- }
115
-
116
- async deleteAnonymousAccount(): Promise<void> {
117
- await this.authDB.deleteAnonymousAccount();
118
- this.setSession(null);
119
- }
120
-
121
- async ensureUserProfile(session: AuthSession): Promise<User> {
122
- const existing = this.DB['users'].selectEntity(session.uid);
123
- const existingPrivate = this.DB['userPrivates'].selectEntity(session.uid);
124
-
125
- let profile = existing;
126
- if (!existing) {
127
- profile = {
128
- __id: session.uid,
129
- name: session.displayName || session.email || (session.isAnonymous ? 'Guest' : 'Learner'),
130
- isAdmin: false,
131
- consented: false,
132
- accessState: AccessState.SUBMIT_INTEREST,
133
- ...(session.photoURL ? { photoURL: session.photoURL } : {}),
134
- _createdAt: Timestamp.now(),
135
- _updatedAt: Timestamp.now(),
136
- _deleted: false,
137
- };
138
- await this.DB['users'].add(profile);
139
- } else {
140
- const generatedName =
141
- !existing.name ||
142
- existing.name === 'Guest' ||
143
- existing.name === 'Learner' ||
144
- existing.name === session.email;
145
- const changes = {
146
- ...(generatedName && session.displayName ? { name: session.displayName } : {}),
147
- ...(session.photoURL && existing.photoURL !== session.photoURL ?
148
- { photoURL: session.photoURL } :
149
- {}),
150
- };
151
- if (Object.keys(changes).length > 0) {
152
- await this.DB['users'].update(session.uid, changes);
153
- profile = { ...existing, ...changes };
154
- }
155
- }
156
-
157
- if (session.email) {
158
- const privateChanges = {
159
- email: session.email,
160
- emailLinkEnabled: session.emailLinkEnabled,
161
- _updatedAt: Timestamp.now(),
162
- _deleted: false,
163
- };
164
- if (existingPrivate) {
165
- await this.DB['userPrivates'].update(session.uid, privateChanges);
166
- } else {
167
- await this.DB['userPrivates'].add({
168
- __id: session.uid,
169
- ...privateChanges,
170
- _createdAt: Timestamp.now(),
171
- });
172
- }
173
- }
174
-
175
- return profile;
176
- }
177
-
178
- async logout(): Promise<void> {
179
- await this.authDB.logout();
180
- this.setSession(null);
181
- }
182
-
183
- streamEntity<T>(collectionName: string, id: string) {
184
- if (this.stallCollections.includes(collectionName)) return NEVER;
185
- if (this.failCollections.includes(collectionName)) {
186
- return throwError(() => new Error(`Simulated read error for collection: ${collectionName}`));
187
- }
188
- const store = this.DB[collectionName];
189
- const entity = computed(() => {
190
- return store.selectEntity(id);
191
- });
192
- return toObservable(entity, { injector: this.injector }).pipe(
193
- delay(this.GET_LATENCY_SIMULATION_DELAY),
194
- );
195
- }
196
-
197
- streamEntities<T>(collectionName, queryParams, queryOptions) {
198
- if (this.stallCollections.includes(collectionName)) return NEVER;
199
- if (this.failCollections.includes(collectionName)) {
200
- return throwError(() => new Error(`Simulated read error for collection: ${collectionName}`));
201
- }
202
- const store = this.DB[collectionName];
203
- const entities = computed(() => {
204
- return store.selectEntities(queryParams, queryOptions);
205
- });
206
-
207
- return toObservable(entities, { injector: this.injector }).pipe(
208
- delay(this.GET_LATENCY_SIMULATION_DELAY),
209
- );
210
- }
211
-
212
- streamEntitiesChanges<T>(collectionName, queryParams, queryOptions) {
213
- if (this.stallCollections.includes(collectionName)) return NEVER;
214
- if (this.failCollections.includes(collectionName)) {
215
- return throwError(() => new Error(`Simulated read error for collection: ${collectionName}`));
216
- }
217
- const store = this.DB[collectionName];
218
- const streamEntities = computed(() => {
219
- return store.selectEntities(queryParams, queryOptions);
220
- });
221
-
222
- return toObservable(streamEntities, { injector: this.injector }).pipe(
223
- // convert to entityMap to more easily compare
224
- map((entities) => {
225
- const entityMap = {};
226
- for (const entity of entities) {
227
- entityMap[entity.__id] = entity;
228
- }
229
- return entityMap;
230
- }),
231
- // compare current with prior including the first
232
- startWith({}),
233
- pairwise(),
234
- // get the changedEntities
235
- map(([prevEntities, currEntities]) => {
236
- const changedEntities = [];
237
- for (const key in currEntities) {
238
- if (!(key in prevEntities)) {
239
- // the entity was added
240
- changedEntities.push({
241
- type: 'added',
242
- docData: currEntities[key],
243
- });
244
- } else if (currEntities[key]['_deleted']) {
245
- // the entity was removed
246
- changedEntities.push({
247
- type: 'removed',
248
- docData: currEntities[key],
249
- });
250
- } else if (currEntities[key]['_updatedAt'] !== prevEntities[key]['_updatedAt']) {
251
- // the entity was modified
252
- changedEntities.push({
253
- type: 'modified',
254
- docData: currEntities[key],
255
- });
256
- }
257
- }
258
-
259
- return changedEntities;
260
- }),
261
- filter((changes: Array<{ type: string, docData: T }>) => changes.length > 0),
262
- delay(this.GET_LATENCY_SIMULATION_DELAY),
263
- );
264
- }
265
-
266
- async getEntity<T>(collectionName: string, id: string) {
267
- if (this.stallCollections.includes(collectionName)) return new Promise(() => {});
268
- if (this.failCollections.includes(collectionName)) {
269
- throw new Error(`Simulated read error for collection: ${collectionName}`);
270
- }
271
- const store = this.DB[collectionName];
272
- await new Promise((resolve) => setTimeout(resolve, this.GET_LATENCY_SIMULATION_DELAY));
273
- return store.selectEntity(id);
274
- }
275
-
276
- async getEntities<S>(
277
- collectionName: string,
278
- queryParams: [string, string, any][],
279
- queryOptions?: { [index: string]: any },
280
- ): Promise<S[]> {
281
- if (this.stallCollections.includes(collectionName)) return new Promise(() => {}) as Promise<S[]>;
282
- if (this.failCollections.includes(collectionName)) {
283
- throw new Error(`Simulated read error for collection: ${collectionName}`);
284
- }
285
- const db = this.DB[collectionName];
286
- await new Promise((resolve) => setTimeout(resolve, this.GET_LATENCY_SIMULATION_DELAY));
287
- return db.selectEntities(queryParams, queryOptions);
288
- }
289
-
290
- async count(
291
- collectionName: string,
292
- queryParams: QueryParams,
293
- queryOptions?: QueryOptions,
294
- ): Promise<number> {
295
- const result = await this.aggregate(collectionName, queryParams, queryOptions, {
296
- count: ['count'],
297
- });
298
- await new Promise((resolve) => setTimeout(resolve, this.GET_LATENCY_SIMULATION_DELAY));
299
- return result['count'];
300
- }
301
-
302
- /*
303
- * Example of aggregateSpec
304
- * {
305
- * countOfDocs: ['count'],
306
- * totalPopulation: ['sum', 'population'],
307
- * averagePopulation: ['average', 'population'],
308
- * }
309
- */
310
- async aggregate<S extends { [k: string]: number }>(
311
- collectionName: string,
312
- queryParams: QueryParams,
313
- queryOptions: QueryOptions,
314
- aggregateSpec: { [K in keyof S]: [string] | [string, string] },
315
- ): Promise<{ [K in keyof S]: number }> {
316
- const store = this.DB[collectionName];
317
- const entities = store.selectEntities(queryParams, queryOptions);
318
- const result: Partial<{ [K in keyof S]: number }> = {};
319
- for (const key in aggregateSpec) {
320
- if (Object.prototype.hasOwnProperty.call(aggregateSpec, key)) {
321
- const value = aggregateSpec[key];
322
-
323
- if (value[0] === 'count') {
324
- result[key] = entities.length;
325
- } else if (value[0] === 'sum') {
326
- result[key] = entities.reduce((s, e) => s + e[value[1]], 0);
327
- } else if (value[0] === 'average') {
328
- result[key] = entities.reduce((s, e) => s + e[value[1]], 0)/entities.length;
329
- }
330
- }
331
- }
332
- await new Promise((resolve) => setTimeout(resolve, this.GET_LATENCY_SIMULATION_DELAY));
333
- return result as { [K in keyof S]: number };
334
- }
335
-
336
- async addEntity(collectionName, entity, batch?) {
337
- const store = this.DB[collectionName];
338
- const entityFinal = Object.assign({}, entity, {
339
- _createdAt: Timestamp.now(),
340
- _updatedAt: Timestamp.now(),
341
- _deleted: false,
342
- });
343
-
344
- if (batch) {
345
- const docRef = {
346
- path: `${collectionName}/${entity.__id}`,
347
- };
348
- return batch.set(docRef, entityFinal);
349
- } else {
350
- await new Promise((resolve) => setTimeout(resolve, this.PUT_LATENCY_SIMULATION_DELAY));
351
- return store.add(entityFinal);
352
- }
353
- }
354
-
355
- async updateEntity(collectionName, id, changes, batch?) {
356
- const store = this.DB[collectionName];
357
- const changesFinal = Object.assign({}, changes, {
358
- _updatedAt: Timestamp.now(),
359
- });
360
-
361
- if (batch) {
362
- const docRef = {
363
- path: `${collectionName}/${id}`,
364
- };
365
- return batch.update(docRef, changesFinal);
366
- } else {
367
- await new Promise((resolve) => setTimeout(resolve, this.PUT_LATENCY_SIMULATION_DELAY));
368
- return store.update(id, changesFinal);
369
- }
370
- }
371
-
372
- async removeEntity(collectionName, id, batch?) {
373
- const store = this.DB[collectionName];
374
- const changes = {
375
- _updatedAt: Timestamp.now(),
376
- _deleted: true,
377
- };
378
-
379
- if (batch) {
380
- const docRef = {
381
- path: `${collectionName}/${id}`,
382
- };
383
- return batch.update(docRef, changes);
384
- } else {
385
- await new Promise((resolve) => setTimeout(resolve, this.PUT_LATENCY_SIMULATION_DELAY));
386
- return store.update(id, changes);
387
- }
388
- }
389
-
390
- async incrementEntityField(collectionName, id, field, delta) {
391
- const store = this.DB[collectionName];
392
- const entity = store.selectEntity(id);
393
- const changes = {
394
- _updatedAt: Timestamp.now(),
395
- };
396
- changes[field] = entity[field] + delta;
397
-
398
- await new Promise((resolve) => setTimeout(resolve, this.PUT_LATENCY_SIMULATION_DELAY));
399
- return await store.update(id, changes);
400
- }
401
- }
402
-
403
- /**
404
- * Creates provider configuration for FirebaseMockService with custom DB collection seeding.
405
- *
406
- * @param options.disableLatency - When true, sets GET and PUT latency simulation delays to 0ms.
407
- * Use this in spec files to avoid the `APP_INITIALIZER` boilerplate for zeroing latency.
408
- * See TEST-AP-005 in testing-guide.md.
409
- * @param options.failCollections - Collections that throw/reject on any read operation.
410
- * The property is mutable mid-test via `db.failCollections = [...]` to simulate
411
- * error → recovery flows (e.g., set failCollections, verify error banner,
412
- * clear failCollections, click Retry, verify recovery).
413
- * @param options.stallCollections - Collections where reads never emit/resolve, simulating
414
- * perpetual loading. Mutable mid-test via `db.stallCollections = [...]`.
415
- */
416
- export function provideFirebaseMock({
417
- users,
418
- userContexts,
419
- userPrivates,
420
- disableLatency,
421
- failCollections,
422
- stallCollections,
423
- }: {
424
- users?: any[];
425
- userContexts?: any[];
426
- userPrivates?: any[];
427
- disableLatency?: boolean;
428
- /** Collections that throw/reject on any read. Mutable mid-test via `db.failCollections`. */
429
- failCollections?: string[];
430
- /** Collections where reads never emit/resolve. Mutable mid-test via `db.stallCollections`. */
431
- stallCollections?: string[];
432
- } = {}): Provider[] {
433
- return [
434
- {
435
- provide: FirebaseMockService,
436
- useFactory: (injector: Injector) => {
437
- const service = new FirebaseMockService(injector);
438
- if (disableLatency) {
439
- service.GET_LATENCY_SIMULATION_DELAY = 0;
440
- service.PUT_LATENCY_SIMULATION_DELAY = 0;
441
- }
442
- if (failCollections) service.failCollections = failCollections;
443
- if (stallCollections) service.stallCollections = stallCollections;
444
- if (users) service.DB['users'].init(users);
445
- if (userContexts) service.DB['userContexts'].init(userContexts);
446
- if (userPrivates) service.DB['userPrivates'].init(userPrivates);
447
- return service;
448
- },
449
- deps: [Injector],
450
- },
451
- { provide: DATABASE_SERVICE, useExisting: FirebaseMockService },
452
- ];
453
- }