@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
@@ -3,58 +3,15 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.entity = entity;
4
4
  const schematics_1 = require("@angular-devkit/schematics");
5
5
  const change_1 = require("@schematics/angular/utility/change");
6
- const find_module_1 = require("@schematics/angular/utility/find-module");
7
6
  const parse_name_1 = require("@schematics/angular/utility/parse-name");
8
7
  const workspace_1 = require("@schematics/angular/utility/workspace");
9
8
  const core_1 = require("@angular-devkit/core");
10
9
  const statements_adder_1 = require("../shared/statements-adder");
10
+ const entity_registry_1 = require("../shared/entity-registry");
11
11
  function addInserts(options) {
12
12
  return (host, context) => {
13
13
  const classifiedName = core_1.strings.classify(options.name);
14
14
  const camelizedName = core_1.strings.camelize(options.name);
15
- const dasherizedName = core_1.strings.dasherize(options.name);
16
- const allcapsName = core_1.strings.classify(options.name).toUpperCase();
17
- context.logger.info(`names: ${classifiedName}, ${camelizedName}`);
18
- // app.model.ts changes
19
- const appModelPath = '/src/app/core/store/app.model.ts';
20
- const appModelText = (0, statements_adder_1.getSourceText)(host, appModelPath);
21
- context.logger.info(`appModelPath: ${appModelPath}`);
22
- const entityModelPath = `/${options.path}/` +
23
- dasherizedName + '/' +
24
- dasherizedName + '.model';
25
- context.logger.info(`entityModelPath: ${entityModelPath}`);
26
- const appToEntityModelPath = (0, find_module_1.buildRelativePath)(appModelPath, entityModelPath);
27
- context.logger.info(`appToEntityPath: ${appToEntityModelPath}`);
28
- let insertChangesInAppModel = (0, statements_adder_1.simpleInsert)(appModelText, appModelPath, [
29
- '// Entity Models',
30
- 'export type AnyEntity =',
31
- ], [
32
- `import { ${classifiedName} } from '${appToEntityModelPath}';`,
33
- ` ${classifiedName} |`
34
- ]);
35
- // firebase.mock.service.ts changes
36
- const fbMockPath = '/src/app/core/firebase/firebase.mock.service.ts';
37
- const fbMockText = (0, statements_adder_1.getSourceText)(host, fbMockPath);
38
- const entityMockPath = `/${options.path}/` +
39
- dasherizedName + '/' +
40
- dasherizedName + '.mock';
41
- const fbToEntityMockPath = (0, find_module_1.buildRelativePath)(fbMockPath, entityMockPath);
42
- context.logger.info(`fbMockPath: ${fbMockPath}`);
43
- let insertChangesInFbMock = (0, statements_adder_1.simpleInsert)(fbMockText, fbMockPath, [
44
- '// Entity Model DB Data',
45
- 'readonly DB = {',
46
- '// Init Entity Models',
47
- 'export function provideFirebaseMock({',
48
- '}: {',
49
- 'const service = new FirebaseMockService(injector);',
50
- ], [
51
- `import { ${classifiedName}MockDB, ${allcapsName}_DB } from '${fbToEntityMockPath}';`,
52
- ` '${camelizedName}s': inject(${classifiedName}MockDB),`,
53
- ` this.DB['${camelizedName}s'].init(${allcapsName}_DB);`,
54
- ` ${camelizedName}s,`,
55
- ` ${camelizedName}s?: any[];`,
56
- ` if (${camelizedName}s) service.DB['${camelizedName}s'].init(${camelizedName}s);`
57
- ]);
58
15
  // firestore.rules changes
59
16
  const rulesPath = '/firestore.rules';
60
17
  let rulesInsertChanges = [];
@@ -69,10 +26,7 @@ function addInserts(options) {
69
26
  }
70
27
  context.logger.info(`about to start committing`);
71
28
  // For each of the files and corresponding set of changes, commit to the tree
72
- const fileChanges = [
73
- [appModelPath, insertChangesInAppModel],
74
- [fbMockPath, insertChangesInFbMock],
75
- ];
29
+ const fileChanges = [];
76
30
  if (rulesInsertChanges.length > 0) {
77
31
  fileChanges.push([rulesPath, rulesInsertChanges]);
78
32
  }
@@ -88,6 +42,47 @@ function addInserts(options) {
88
42
  return host;
89
43
  };
90
44
  }
45
+ function addFirestoreIndex(options) {
46
+ return (host, context) => {
47
+ const parsedForeignKeys = options.parsedForeignKeys || [];
48
+ if (parsedForeignKeys.length === 0) {
49
+ return host;
50
+ }
51
+ const indexPath = '/firestore.indexes.json';
52
+ if (!host.exists(indexPath)) {
53
+ context.logger.warn('firestore.indexes.json not found — skipping index generation.');
54
+ return host;
55
+ }
56
+ const camelizedName = core_1.strings.camelize(options.name);
57
+ const collectionGroup = camelizedName + 's';
58
+ // Build the composite index fields: foreign keys + _deleted + _updatedAt + __name__
59
+ const fields = [
60
+ ...parsedForeignKeys.map((fk) => ({
61
+ fieldPath: `__${fk}`,
62
+ order: 'ASCENDING',
63
+ })),
64
+ { fieldPath: '_deleted', order: 'ASCENDING' },
65
+ { fieldPath: '_updatedAt', order: 'ASCENDING' },
66
+ { fieldPath: '__name__', order: 'ASCENDING' },
67
+ ];
68
+ const newIndex = {
69
+ collectionGroup,
70
+ queryScope: 'COLLECTION',
71
+ fields,
72
+ density: 'SPARSE_ALL',
73
+ };
74
+ const indexContent = host.read(indexPath);
75
+ if (!indexContent) {
76
+ context.logger.warn('Could not read firestore.indexes.json — skipping index generation.');
77
+ return host;
78
+ }
79
+ const indexJson = JSON.parse(indexContent.toString());
80
+ indexJson.indexes.push(newIndex);
81
+ host.overwrite(indexPath, JSON.stringify(indexJson, null, 2) + '\n');
82
+ context.logger.info(`Added composite Firestore index for ${collectionGroup} with foreign keys: ${parsedForeignKeys.map(fk => '__' + fk).join(', ')}`);
83
+ return host;
84
+ };
85
+ }
91
86
  function entity(options) {
92
87
  return async (tree, context) => {
93
88
  const workspace = await (0, workspace_1.getWorkspace)(tree);
@@ -123,6 +118,11 @@ function entity(options) {
123
118
  const parsedPath = (0, parse_name_1.parseName)(options.path, options.name);
124
119
  options.name = parsedPath.name;
125
120
  options.path = parsedPath.path;
121
+ // Parse foreign keys from comma-separated string
122
+ const parsedForeignKeys = options.foreignKeys
123
+ ? options.foreignKeys.split(',').map((k) => k.trim()).filter((k) => k.length > 0)
124
+ : [];
125
+ options.parsedForeignKeys = parsedForeignKeys;
126
126
  const templateSource = (0, schematics_1.apply)((0, schematics_1.url)('./files'), [
127
127
  (0, schematics_1.applyTemplates)({
128
128
  ...core_1.strings,
@@ -130,9 +130,21 @@ function entity(options) {
130
130
  }),
131
131
  (0, schematics_1.move)(parsedPath.path),
132
132
  ]);
133
+ // Post-generation reminder about foreign keys and indexes
134
+ if (parsedForeignKeys.length > 0) {
135
+ context.logger.info(`\n📋 REMINDER: Don't forget to deploy the updated Firestore indexes:\n` +
136
+ ` firebase deploy --only firestore:indexes\n`);
137
+ }
138
+ else {
139
+ context.logger.info(`\n📋 REMINDER: If your entity has foreign key fields (e.g., __userId, __collectionId),\n` +
140
+ ` re-generate with --foreign-keys to create the required composite Firestore indexes:\n` +
141
+ ` ng generate @tech4good/angular-schematics:entity ${options.name} --foreign-keys=userId,collectionId\n`);
142
+ }
133
143
  return (0, schematics_1.chain)([
134
144
  addInserts(options),
135
- (0, schematics_1.mergeWith)(templateSource)
145
+ addFirestoreIndex(options),
146
+ (0, schematics_1.mergeWith)(templateSource),
147
+ (0, entity_registry_1.updateEntityRegistry)(),
136
148
  ]);
137
149
  };
138
150
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":";;AA2HA,wBAuDC;AAlLD,2DAIoC;AAEpC,+DAA0E;AAC1E,yEAA4E;AAC5E,uEAAmE;AACnE,qEAAuF;AACvF,+CAA+C;AAE/C,iEAAuF;AAEvF,SAAS,UAAU,CAAC,OAAY;IAC9B,OAAO,CAAC,IAAU,EAAE,OAAyB,EAAE,EAAE;QAE/C,MAAM,cAAc,GAAG,cAAO,CAAC,QAAQ,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QACtD,MAAM,aAAa,GAAG,cAAO,CAAC,QAAQ,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QACrD,MAAM,cAAc,GAAG,cAAO,CAAC,SAAS,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QACvD,MAAM,WAAW,GAAG,cAAO,CAAC,QAAQ,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,WAAW,EAAE,CAAC;QACjE,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,UAAU,cAAc,KAAK,aAAa,EAAE,CAAC,CAAC;QAElE,uBAAuB;QACvB,MAAM,YAAY,GAAG,kCAAkC,CAAC;QACxD,MAAM,YAAY,GAAG,IAAA,gCAAa,EAAC,IAAI,EAA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C,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAS,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,CAAS,EAAE,EAAE,CAAC,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC;YACjG,CAAC,CAAC,EAAE,CAAC;QACP,OAAO,CAAC,iBAAiB,GAAG,iBAAiB,CAAC;QAE9C,MAAM,cAAc,GAAG,IAAA,kBAAK,EAAC,IAAA,gBAAG,EAAC,SAAS,CAAC,EAAE;YAC3C,IAAA,2BAAc,EAAC;gBACb,GAAG,cAAO;gBACV,GAAG,OAAO;aACX,CAAC;YACF,IAAA,iBAAI,EAAC,UAAU,CAAC,IAAI,CAAC;SACtB,CAAC,CAAC;QAEH,0DAA0D;QAC1D,IAAI,iBAAiB,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACjC,OAAO,CAAC,MAAM,CAAC,IAAI,CACjB,wEAAwE;gBACxE,+CAA+C,CAChD,CAAC;QACJ,CAAC;aAAM,CAAC;YACN,OAAO,CAAC,MAAM,CAAC,IAAI,CACjB,0FAA0F;gBAC1F,0FAA0F;gBAC1F,uDAAuD,OAAO,CAAC,IAAI,uCAAuC,CAC3G,CAAC;QACJ,CAAC;QAED,OAAO,IAAA,kBAAK,EAAC;YACX,UAAU,CAAC,OAAO,CAAC;YACnB,iBAAiB,CAAC,OAAO,CAAC;YAC1B,IAAA,sBAAS,EAAC,cAAc,CAAC;YACzB,IAAA,sCAAoB,GAAE;SACvB,CAAC,CAAC;IACL,CAAC,CAAC;AACJ,CAAC"}
@@ -33,6 +33,10 @@
33
33
  "index": 0
34
34
  },
35
35
  "x-prompt": "What name would you like to use for the entity?"
36
+ },
37
+ "foreignKeys": {
38
+ "type": "string",
39
+ "description": "Comma-separated list of foreign key names (without __ prefix). E.g., 'userId,collectionId'. These will be added to the model interface as __fieldName: string fields, and composite Firestore indexes will be generated for efficient querying."
36
40
  }
37
41
  },
38
42
  "required": [
@@ -14,7 +14,6 @@ describe('<%= camelize(name) %> (handleAccess)', () => {
14
14
  name: 'Test User',
15
15
  email: 'test@test.com',
16
16
  isAdmin: false,
17
- isMentor: false,
18
17
  accessState: AccessState.DONE,
19
18
  consented: true,
20
19
  _createdAt: Timestamp.now(),
@@ -62,6 +62,9 @@ jobs:
62
62
  - name: 🛡️ Test Firestore Rules
63
63
  run: npm run test:rules
64
64
 
65
+ - name: 🔍 Check Firestore Indexes
66
+ run: npm run check:indexes
67
+
65
68
  - name: 🏗️ Build Project
66
69
  run: npm run build
67
70
 
@@ -8,6 +8,7 @@
8
8
 
9
9
  # Node
10
10
  /node_modules
11
+ /functions/lib
11
12
  npm-debug.log
12
13
  yarn-error.log
13
14
 
@@ -56,5 +57,9 @@ Thumbs.db
56
57
  # .env
57
58
  .env
58
59
 
60
+ *.log
59
61
  .t4g/
60
62
  .impeccable/
63
+
64
+ # Rebuildable local analytics snapshots and private pseudonymization salt
65
+ /.local/analytics/
@@ -0,0 +1,206 @@
1
+ /**
2
+ * Analytics Dataset Registry
3
+ *
4
+ * Defines the schema and API contract for all local analytics datasets.
5
+ *
6
+ * Privacy Invariants:
7
+ * - Datasets must define a privacy level (`aggregate` vs `deidentified-observation`).
8
+ * - Raw text or non-pseudonymized identifiers must never be exposed to local clients.
9
+ *
10
+ * Admin Traffic Variants:
11
+ * - Datasets with `adminVariants: true` are computed twice during refresh:
12
+ * once with admin traffic included (_includes_admin = 1) and once without
13
+ * (_includes_admin = 0). The Express API filters by the `includeAdmin`
14
+ * query parameter.
15
+ * - Datasets without `adminVariants` (e.g., data-quality, entity tables) are
16
+ * stored once and served regardless of the toggle state.
17
+ */
18
+
19
+ // Helper factory functions to build typed column definition objects
20
+ const integer = (name, options = {}) => ({ name, type: 'INTEGER', ...options });
21
+ const real = (name, options = {}) => ({ name, type: 'REAL', ...options });
22
+ const text = (name, options = {}) => ({ name, type: 'TEXT', ...options });
23
+
24
+ /** Registry of all analytics datasets. */
25
+ export const datasets = [
26
+ {
27
+ id: 'route-visits',
28
+ table: 'fact_route_visit',
29
+ sourceQuery: 'bigquery/queries/dashboard_route_visits.sql',
30
+ grain: 'One finalized deidentified route telemetry segment',
31
+ privacy: 'deidentified-observation',
32
+ requiresIdSalt: true,
33
+ adminVariants: true,
34
+ columns: [
35
+ integer('_includes_admin'),
36
+ text('visit_key', { primaryKey: true }),
37
+ text('journey_key'),
38
+ text('session_key'),
39
+ text('user_key'),
40
+ text('route'),
41
+ integer('started_at_ms'),
42
+ integer('active_ms'),
43
+ integer('rest_ms'),
44
+ ],
45
+ indexes: [['route'], ['started_at_ms'], ['journey_key'], ['_includes_admin']],
46
+ api: {
47
+ filterFields: ['route', 'journey_key', 'session_key'],
48
+ sortFields: ['route', 'started_at_ms', 'active_ms', 'rest_ms'],
49
+ defaultSort: 'started_at_ms',
50
+ defaultDirection: 'desc',
51
+ maxRows: 25000,
52
+ },
53
+ },
54
+ {
55
+ id: 'route-engagement',
56
+ table: 'agg_route_engagement',
57
+ sourceQuery: 'bigquery/queries/active_time_by_route.sql',
58
+ grain: 'One normalized route',
59
+ privacy: 'aggregate',
60
+ requiresIdSalt: true,
61
+ adminVariants: true,
62
+ columns: [
63
+ integer('_includes_admin'),
64
+ text('route', { primaryKey: true }),
65
+ integer('total_visits'),
66
+ real('mean_active_seconds'),
67
+ real('min_active_seconds'),
68
+ real('q1_active_seconds'),
69
+ real('median_active_seconds'),
70
+ real('q3_active_seconds'),
71
+ real('max_active_seconds'),
72
+ ],
73
+ indexes: [['total_visits'], ['_includes_admin']],
74
+ api: {
75
+ filterFields: ['route'],
76
+ sortFields: ['route', 'total_visits', 'mean_active_seconds', 'median_active_seconds'],
77
+ defaultSort: 'total_visits',
78
+ defaultDirection: 'desc',
79
+ maxRows: 1000,
80
+ },
81
+ },
82
+ {
83
+ id: 'onboarding-cohorts',
84
+ table: 'agg_onboarding_cohort',
85
+ sourceQuery: 'bigquery/queries/onboarding_funnel.sql',
86
+ grain: 'One stage in an acquisition or activation cohort',
87
+ privacy: 'aggregate',
88
+ requiresIdSalt: true,
89
+ adminVariants: true,
90
+ columns: [
91
+ integer('_includes_admin'),
92
+ text('cohort_stage_key', { primaryKey: true }),
93
+ text('analysis'),
94
+ text('stage'),
95
+ integer('stage_order'),
96
+ integer('journeys'),
97
+ real('conversion_from_cohort'),
98
+ ],
99
+ indexes: [['analysis', 'stage_order'], ['_includes_admin']],
100
+ api: {
101
+ filterFields: ['analysis', 'stage'],
102
+ sortFields: ['analysis', 'stage_order', 'journeys', 'conversion_from_cohort'],
103
+ defaultSort: 'stage_order',
104
+ defaultDirection: 'asc',
105
+ maxRows: 100,
106
+ },
107
+ },
108
+ {
109
+ id: 'active-user-windows',
110
+ table: 'agg_active_user_window',
111
+ sourceQuery: 'bigquery/queries/active_user_windows.sql',
112
+ grain: 'One calendar day with trailing 1-, 7-, and 30-day active identity windows',
113
+ privacy: 'aggregate',
114
+ requiresIdSalt: true,
115
+ adminVariants: true,
116
+ columns: [
117
+ integer('_includes_admin'),
118
+ text('activity_date', { primaryKey: true }),
119
+ integer('dau'),
120
+ integer('wau'),
121
+ integer('mau'),
122
+ ],
123
+ indexes: [['activity_date'], ['_includes_admin']],
124
+ api: {
125
+ filterFields: [],
126
+ sortFields: ['activity_date', 'dau', 'wau', 'mau'],
127
+ defaultSort: 'activity_date',
128
+ defaultDirection: 'desc',
129
+ maxRows: 5000,
130
+ },
131
+ },
132
+ {
133
+ id: 'weekly-retention-cohorts',
134
+ table: 'agg_weekly_retention_cohort',
135
+ sourceQuery: 'bigquery/queries/weekly_retention_cohorts.sql',
136
+ grain: 'One first-active-week cohort at one elapsed week',
137
+ privacy: 'aggregate',
138
+ requiresIdSalt: true,
139
+ adminVariants: true,
140
+ columns: [
141
+ integer('_includes_admin'),
142
+ text('retention_key', { primaryKey: true }),
143
+ text('cohort_week'),
144
+ integer('weeks_since_first_active'),
145
+ integer('active_users'),
146
+ integer('cohort_size'),
147
+ real('retention_rate'),
148
+ ],
149
+ indexes: [['cohort_week', 'weeks_since_first_active'], ['_includes_admin']],
150
+ api: {
151
+ filterFields: ['cohort_week', 'weeks_since_first_active'],
152
+ sortFields: ['cohort_week', 'weeks_since_first_active', 'active_users', 'cohort_size', 'retention_rate'],
153
+ defaultSort: 'cohort_week',
154
+ defaultDirection: 'desc',
155
+ maxRows: 10000,
156
+ },
157
+ },
158
+ {
159
+ id: 'user-dimensions',
160
+ table: 'dim_user',
161
+ entitySource: 'user-dimensions',
162
+ uploadToBigQuery: true,
163
+ grain: 'One de-identified user entity record',
164
+ privacy: 'deidentified-observation',
165
+ requiresIdSalt: true,
166
+ columns: [
167
+ text('user_key', { primaryKey: true }),
168
+ text('role'),
169
+ text('access_state'),
170
+ integer('source_created_at_ms'),
171
+ integer('source_updated_at_ms'),
172
+ ],
173
+ indexes: [['role'], ['access_state']],
174
+ api: {
175
+ filterFields: ['role', 'access_state'],
176
+ sortFields: ['user_key', 'role', 'access_state', 'source_created_at_ms'],
177
+ defaultSort: 'user_key',
178
+ defaultDirection: 'asc',
179
+ maxRows: 10000,
180
+ },
181
+ },
182
+ {
183
+ id: 'data-quality',
184
+ table: 'agg_data_quality',
185
+ sourceQuery: 'bigquery/queries/data_quality.sql',
186
+ grain: 'One snapshot-level diagnostic',
187
+ privacy: 'aggregate',
188
+ columns: [
189
+ text('metric', { primaryKey: true }),
190
+ integer('value'),
191
+ text('severity'),
192
+ text('detail'),
193
+ ],
194
+ indexes: [['severity']],
195
+ api: {
196
+ filterFields: ['severity'],
197
+ sortFields: ['metric', 'value', 'severity'],
198
+ defaultSort: 'severity',
199
+ defaultDirection: 'asc',
200
+ maxRows: 1000,
201
+ },
202
+ },
203
+ ];
204
+
205
+ /** Lookup map by dataset ID. */
206
+ export const datasetsById = new Map(datasets.map((dataset) => [dataset.id, dataset]));
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Firestore Entity Sources Registry (`entity_sources.js`)
3
+ *
4
+ * Registers Firestore entity mappers to pull incremental updates from the
5
+ * Firestore `users` collection into local SQLite tables.
6
+ *
7
+ * Privacy Invariant:
8
+ * Derived entity mappers MUST strip raw PII (emails, real names) and apply
9
+ * salted HMAC hashing (`pseudonymousEntityKey`) to all user IDs.
10
+ */
11
+
12
+ import { createHash } from 'node:crypto';
13
+
14
+ /** Returns string or empty string if non-string */
15
+ function asString(value) {
16
+ return typeof value === 'string' ? value : '';
17
+ }
18
+
19
+ /** Generates SHA256 pseudonymous key using idSalt */
20
+ export function pseudonymousEntityKey(idSalt, value) {
21
+ if (value === null || value === undefined || value === '') return null;
22
+ return createHash('sha256')
23
+ .update(`${idSalt}:${String(value)}:${idSalt}`)
24
+ .digest('hex');
25
+ }
26
+
27
+ /** Derives non-PII user dimension features from Firestore `users` documents */
28
+ export function deriveUserEntity(data, context) {
29
+ return {
30
+ user_key: pseudonymousEntityKey(context.idSalt, context.documentId),
31
+ role: data.isAdmin === true ? 'admin' : 'user',
32
+ access_state: asString(data.accessState) || null,
33
+ source_created_at_ms: context.sourceCreatedAtMs,
34
+ source_updated_at_ms: context.sourceUpdatedAtMs,
35
+ };
36
+ }
37
+
38
+ function materializeRows(cachedRows) {
39
+ return cachedRows.map((row) => row.derived);
40
+ }
41
+
42
+ /** Entity dataset derivation definitions map */
43
+ export const entityDatasetDefinitions = new Map([
44
+ [
45
+ 'user-dimensions',
46
+ {
47
+ analysisVersion: 4,
48
+ sources: [
49
+ {
50
+ id: 'users',
51
+ collection: 'users',
52
+ derive: deriveUserEntity,
53
+ },
54
+ ],
55
+ materialize: materializeRows,
56
+ },
57
+ ],
58
+ ]);
@@ -0,0 +1,57 @@
1
+ import assert from 'node:assert/strict';
2
+ import { describe, it } from 'node:test';
3
+ import { deriveUserEntity, pseudonymousEntityKey } from './entity_sources.js';
4
+
5
+ describe('entity_sources mapping', () => {
6
+ const context = {
7
+ idSalt: 'test-salt-123',
8
+ documentId: 'user_abc123',
9
+ sourceUpdatedAtMs: 1700000000000,
10
+ sourceCreatedAtMs: 1690000000000,
11
+ };
12
+
13
+ it('correctly maps Firestore user document to a pseudonymous dim_user record', () => {
14
+ const rawDoc = {
15
+ isAdmin: true,
16
+ accessState: 'DONE',
17
+ email: 'secret@example.com', // PII — must not appear in output
18
+ };
19
+
20
+ const derived = deriveUserEntity(rawDoc, context);
21
+
22
+ assert.equal(derived.user_key, pseudonymousEntityKey('test-salt-123', 'user_abc123'));
23
+ assert.match(derived.user_key, /^[0-9a-f]{64}$/);
24
+ assert.equal(derived.role, 'admin');
25
+ assert.equal(derived.access_state, 'DONE');
26
+ assert.equal(derived.source_created_at_ms, 1690000000000);
27
+ assert.equal(derived.source_updated_at_ms, 1700000000000);
28
+ // Verifies PII fields are stripped
29
+ assert.equal(derived.email, undefined);
30
+ });
31
+
32
+ it('passes through sourceCreatedAtMs from context (timestamp conversion is in entity_sync)', () => {
33
+ const derived = deriveUserEntity({}, {
34
+ ...context,
35
+ sourceCreatedAtMs: 1695555000000,
36
+ });
37
+ assert.equal(derived.source_created_at_ms, 1695555000000);
38
+ });
39
+
40
+ it('returns null sourceCreatedAtMs when context has null', () => {
41
+ const derived = deriveUserEntity({}, {
42
+ ...context,
43
+ sourceCreatedAtMs: null,
44
+ });
45
+ assert.equal(derived.source_created_at_ms, null);
46
+ });
47
+
48
+ it('defaults role to "user" when not provided', () => {
49
+ const derived = deriveUserEntity({}, context);
50
+ assert.equal(derived.role, 'user');
51
+ });
52
+
53
+ it('does not treat a legacy role string as an admin flag', () => {
54
+ const derived = deriveUserEntity({ role: 'admin', isAdmin: false }, context);
55
+ assert.equal(derived.role, 'user');
56
+ });
57
+ });
@@ -0,0 +1,87 @@
1
+ /**
2
+ * SQLite API Query Builder
3
+ *
4
+ * Builds parameterized SQL queries for the Express proxy API.
5
+ * Validates client parameters against dataset schema contracts to prevent
6
+ * SQL injection and ensure safe constraints (pagination, allowlists).
7
+ *
8
+ * Admin Traffic Filtering:
9
+ * For datasets with `adminVariants: true`, the builder appends a
10
+ * `_includes_admin = ?` filter based on the `includeAdmin` query parameter.
11
+ */
12
+
13
+ import { quoteIdentifier } from './dataset_schema.js';
14
+
15
+ /**
16
+ * @param {object} dataset
17
+ * @param {URL} url
18
+ * @returns {{ sql: string, params: Array<any>, limit: number, offset: number }}
19
+ */
20
+ export function queryForDataset(dataset, url) {
21
+ const api = dataset.api;
22
+ const where = [];
23
+ const params = [];
24
+
25
+ // Admin traffic variant filtering — only for datasets that have dual variants
26
+ if (dataset.adminVariants) {
27
+ const includeAdmin = url.searchParams.get('includeAdmin') === '1' ? 1 : 0;
28
+ where.push('"_includes_admin" = ?');
29
+ params.push(includeAdmin);
30
+ }
31
+
32
+ for (const [name, value] of url.searchParams.entries()) {
33
+ if (!name.startsWith('filter.')) continue;
34
+ const field = name.slice('filter.'.length);
35
+ if (!api.filterFields.includes(field)) {
36
+ throw new Error(`Filter "${field}" is not allowed for ${dataset.id}.`);
37
+ }
38
+ where.push(`${quoteIdentifier(field)} = ?`);
39
+ params.push(value);
40
+ }
41
+
42
+
43
+ const requestedSort = url.searchParams.get('sort');
44
+ const sort = requestedSort || api.defaultSort;
45
+ if (sort && !api.sortFields.includes(sort)) {
46
+ throw new Error(`Sort "${sort}" is not allowed for ${dataset.id}.`);
47
+ }
48
+
49
+
50
+ const requestedDirection = (
51
+ url.searchParams.get('direction') ||
52
+ api.defaultDirection ||
53
+ 'asc'
54
+ ).toLowerCase();
55
+ if (!['asc', 'desc'].includes(requestedDirection)) {
56
+ throw new Error('Sort direction must be asc or desc.');
57
+ }
58
+
59
+
60
+ const requestedLimit = Number(url.searchParams.get('limit') || api.maxRows);
61
+ const limit = Math.min(
62
+ Number.isInteger(requestedLimit) && requestedLimit > 0 ?
63
+ requestedLimit :
64
+ api.maxRows,
65
+ api.maxRows,
66
+ );
67
+ const requestedOffset = Number(url.searchParams.get('offset') || 0);
68
+ const offset =
69
+ Number.isInteger(requestedOffset) && requestedOffset >= 0 ?
70
+ requestedOffset :
71
+ 0;
72
+
73
+
74
+ const clauses = [
75
+ `SELECT * FROM ${quoteIdentifier(dataset.table)}`,
76
+ where.length ? `WHERE ${where.join(' AND ')}` : '',
77
+ sort ? `ORDER BY ${quoteIdentifier(sort)} ${requestedDirection.toUpperCase()}` : '',
78
+ 'LIMIT ? OFFSET ?',
79
+ ].filter(Boolean);
80
+
81
+ return {
82
+ sql: clauses.join(' '),
83
+ params: [...params, limit, offset],
84
+ limit,
85
+ offset,
86
+ };
87
+ }