@tech4good/angular-schematics 20.3.0 → 21.0.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 (147) hide show
  1. package/.agents/skills/publish-npm/SKILL.md +1 -1
  2. package/.agents/skills/publish-npm/eval.yaml +15 -0
  3. package/.agents/skills/publish-npm/fixtures/package-v21.json.template +8 -0
  4. package/.husky/commit-msg +1 -0
  5. package/.husky/pre-commit +1 -0
  6. package/.t4g/agent-memory.db +0 -0
  7. package/CHANGELOG.md +100 -26
  8. package/commitlint.config.js +15 -0
  9. package/contributing-docs/commit-message.md +3 -6
  10. package/package.json +10 -6
  11. package/src/collection.json +8 -0
  12. package/src/component/files/__name@dasherize__/__name@dasherize__.component.ts.template +1 -3
  13. package/src/component/index_spec.js +57 -4
  14. package/src/component/index_spec.js.map +1 -1
  15. package/src/entity/index.js +7 -1
  16. package/src/entity/index.js.map +1 -1
  17. package/src/entity/index_spec.js +108 -4
  18. package/src/entity/index_spec.js.map +1 -1
  19. package/src/guard/files/__name@dasherize__.guard.spec.ts.template +45 -0
  20. package/src/guard/files/__name@dasherize__.guard.ts.template +32 -0
  21. package/src/guard/index.d.ts +2 -0
  22. package/src/guard/index.js +38 -0
  23. package/src/guard/index.js.map +1 -0
  24. package/src/guard/index_spec.d.ts +1 -0
  25. package/src/guard/index_spec.js +64 -0
  26. package/src/guard/index_spec.js.map +1 -0
  27. package/src/guard/schema.json +46 -0
  28. package/src/ng-add/files/.firebaserc.template +3 -2
  29. package/src/ng-add/files/.github/workflows/angular-github-ci.yml.template +105 -39
  30. package/src/ng-add/files/.gitignore.template +1 -2
  31. package/src/ng-add/files/angular.json.template +1 -5
  32. package/src/ng-add/files/docs-infra/infrastructure-guide.md.template +390 -0
  33. package/src/ng-add/files/docs-infra/load-system-architecture.md.template +166 -0
  34. package/src/ng-add/files/docs-infra/querying-strategy.md.template +157 -0
  35. package/src/ng-add/files/docs-infra/stream-system-architecture.md.template +283 -0
  36. package/src/ng-add/files/eslint.config.js.template +4 -1
  37. package/src/ng-add/files/firebase.json.template +37 -0
  38. package/src/ng-add/files/firestore.rules.spec.ts.template +221 -0
  39. package/src/ng-add/files/firestore.rules.template +67 -0
  40. package/src/ng-add/files/jest.config.ts.template +6 -1
  41. package/src/ng-add/files/package.json.template +41 -31
  42. package/src/ng-add/files/setup-jest.ts.template +13 -5
  43. package/src/ng-add/files/src/app/admin/admin-panel/admin-panel.component.spec.ts.template +76 -12
  44. package/src/ng-add/files/src/app/admin/admin-panel/admin-panel.component.ts.template +1 -3
  45. package/src/ng-add/files/src/app/admin/admin-panel/admin-settings/admin-settings.component.spec.ts.template +90 -0
  46. package/src/ng-add/files/src/app/admin/admin-panel/admin-settings/admin-settings.component.ts.template +1 -1
  47. package/src/ng-add/files/src/app/admin/admin-panel/admin-user-list/admin-user-counts/admin-count-pill/admin-count-pill.component.spec.ts.template +12 -17
  48. package/src/ng-add/files/src/app/admin/admin-panel/admin-user-list/admin-user-counts/admin-count-pill/admin-count-pill.component.ts.template +2 -4
  49. package/src/ng-add/files/src/app/admin/admin-panel/admin-user-list/admin-user-counts/admin-user-counts.component.spec.ts.template +40 -19
  50. package/src/ng-add/files/src/app/admin/admin-panel/admin-user-list/admin-user-counts/admin-user-counts.component.ts.template +3 -5
  51. package/src/ng-add/files/src/app/admin/admin-panel/admin-user-list/admin-user-list.component.html.template +2 -2
  52. package/src/ng-add/files/src/app/admin/admin-panel/admin-user-list/admin-user-list.component.spec.ts.template +108 -0
  53. package/src/ng-add/files/src/app/admin/admin-panel/admin-user-list/admin-user-list.component.ts.template +11 -11
  54. package/src/ng-add/files/src/app/admin/admin-panel/admin-user-list/admin-user-table/admin-user-table.component.html.template +6 -2
  55. package/src/ng-add/files/src/app/admin/admin-panel/admin-user-list/admin-user-table/admin-user-table.component.spec.ts.template +136 -19
  56. package/src/ng-add/files/src/app/admin/admin-panel/admin-user-list/admin-user-table/admin-user-table.component.ts.template +8 -5
  57. package/src/ng-add/files/src/app/app.component.html.template +1 -1
  58. package/src/ng-add/files/src/app/app.component.scss.template +10 -0
  59. package/src/ng-add/files/src/app/app.component.ts.template +1 -1
  60. package/src/ng-add/files/src/app/app.config.ts.template +11 -11
  61. package/src/ng-add/files/src/app/auth-routing.spec.ts.template +101 -0
  62. package/src/ng-add/files/src/app/core/analytics/log.service.ts.template +5 -8
  63. package/src/ng-add/files/src/app/core/analytics/time-analytics.service.spec.ts.template +140 -0
  64. package/src/ng-add/files/src/app/core/analytics/time-analytics.service.ts.template +25 -7
  65. package/src/ng-add/files/src/app/core/auth/guards/redirect-if-authenticated.guard.ts.template +1 -1
  66. package/src/ng-add/files/src/app/core/auth/guards/require-admin.guard.ts.template +1 -1
  67. package/src/ng-add/files/src/app/core/auth/guards/require-auth-and-consent.guard.ts.template +1 -1
  68. package/src/ng-add/files/src/app/core/auth/guards/require-auth.guard.ts.template +1 -1
  69. package/src/ng-add/files/src/app/core/firebase/cached-listeners.service.ts.template +229 -14
  70. package/src/ng-add/files/src/app/core/firebase/database.service.ts.template +1 -1
  71. package/src/ng-add/files/src/app/core/firebase/firebase.mock.service.ts.template +34 -9
  72. package/src/ng-add/files/src/app/core/firebase/firebase.service.ts.template +4 -4
  73. package/src/ng-add/files/src/app/core/firebase/query-logger.ts.template +11 -0
  74. package/src/ng-add/files/src/app/core/firebase/simulate-load.spec.ts.template +104 -0
  75. package/src/ng-add/files/src/app/core/firebase/simulate-stream.spec.ts.template +127 -0
  76. package/src/ng-add/files/src/app/core/firebase/simulation.mock.ts.template +38 -0
  77. package/src/ng-add/files/src/app/core/firebase/stream-multiplexer.ts.template +443 -0
  78. package/src/ng-add/files/src/app/core/store/app.store.spec.ts.template +920 -0
  79. package/src/ng-add/files/src/app/core/store/app.store.ts.template +303 -137
  80. package/src/ng-add/files/src/app/core/store/auth/auth.mock.ts.template +65 -23
  81. package/src/ng-add/files/src/app/core/store/auth/auth.store.ts.template +68 -67
  82. package/src/ng-add/files/src/app/core/store/user/user.mock.ts.template +46 -0
  83. package/src/ng-add/files/src/app/core/store/user-context/user-context.mock.ts.template +17 -0
  84. package/src/ng-add/files/src/app/core/testing/test-utils.ts.template +26 -0
  85. package/src/ng-add/files/src/app/first-time/consent/consent.component.html.template +3 -3
  86. package/src/ng-add/files/src/app/first-time/consent/consent.component.spec.ts.template +89 -13
  87. package/src/ng-add/files/src/app/first-time/consent/consent.component.ts.template +46 -17
  88. package/src/ng-add/files/src/app/first-time/consent/consent.guard.ts.template +1 -1
  89. package/src/ng-add/files/src/app/first-time/early-access/early-access.component.html.template +5 -63
  90. package/src/ng-add/files/src/app/first-time/early-access/early-access.component.scss.template +1 -94
  91. package/src/ng-add/files/src/app/first-time/early-access/early-access.component.spec.ts.template +150 -14
  92. package/src/ng-add/files/src/app/first-time/early-access/early-access.component.ts.template +15 -42
  93. package/src/ng-add/files/src/app/first-time/early-access/early-access.guard.ts.template +2 -2
  94. package/src/ng-add/files/src/app/first-time/early-access/early-access.model.ts.template +5 -0
  95. package/src/ng-add/files/src/app/first-time/early-access/survey-form/survey-form.component.html.template +42 -0
  96. package/src/ng-add/files/src/app/first-time/early-access/survey-form/survey-form.component.scss.template +96 -0
  97. package/src/ng-add/files/src/app/first-time/early-access/survey-form/survey-form.component.spec.ts.template +37 -0
  98. package/src/ng-add/files/src/app/first-time/early-access/survey-form/survey-form.component.ts.template +63 -0
  99. package/src/ng-add/files/src/app/first-time/early-access/waitlist-view/waitlist-view.component.html.template +16 -0
  100. package/src/ng-add/files/src/app/first-time/early-access/waitlist-view/waitlist-view.component.scss.template +7 -0
  101. package/src/ng-add/files/src/app/first-time/early-access/waitlist-view/waitlist-view.component.spec.ts.template +41 -0
  102. package/src/ng-add/files/src/app/first-time/early-access/waitlist-view/waitlist-view.component.ts.template +26 -0
  103. package/src/ng-add/files/src/app/first-time/first-time-routing.spec.ts.template +123 -0
  104. package/src/ng-add/files/src/app/first-time/landing/hero/hero.component.html.template +11 -4
  105. package/src/ng-add/files/src/app/first-time/landing/hero/hero.component.scss.template +17 -4
  106. package/src/ng-add/files/src/app/first-time/landing/hero/hero.component.ts.template +5 -5
  107. package/src/ng-add/files/src/app/first-time/landing/landing.component.html.template +1 -1
  108. package/src/ng-add/files/src/app/first-time/landing/landing.component.scss.template +0 -1
  109. package/src/ng-add/files/src/app/first-time/landing/landing.component.spec.ts.template +25 -17
  110. package/src/ng-add/files/src/app/first-time/landing/landing.component.ts.template +4 -12
  111. package/src/ng-add/files/src/app/first-time/landing/rotating-quotes/rotating-quotes.component.ts.template +1 -1
  112. package/src/ng-add/files/src/app/first-time/login/login.component.spec.ts.template +36 -16
  113. package/src/ng-add/files/src/app/first-time/login/login.component.ts.template +1 -1
  114. package/src/ng-add/files/src/app/first-time/onboarding/onboarding.component.spec.ts.template +11 -15
  115. package/src/ng-add/files/src/app/first-time/onboarding/onboarding.component.ts.template +1 -3
  116. package/src/ng-add/files/src/app/main/home/home.component.ts.template +1 -3
  117. package/src/ng-add/files/src/app/shared/dev-status-bar/dev-status-bar.component.spec.ts.template +98 -0
  118. package/src/ng-add/files/src/app/shared/dev-status-bar/dev-status-bar.component.ts.template +9 -3
  119. package/src/ng-add/files/src/app/shared/hint-visibility/hint-visibility.directive.spec.ts.template +164 -0
  120. package/src/ng-add/files/src/app/shared/hint-visibility/hint-visibility.directive.ts.template +20 -18
  121. package/src/ng-add/files/src/app/shared/navbar/navbar.component.spec.ts.template +38 -17
  122. package/src/ng-add/files/src/app/shared/navbar/navbar.component.ts.template +1 -1
  123. package/src/ng-add/files/src/app/shared/redeployment-warning/redeployment-warning.component.html.template +1 -1
  124. package/src/ng-add/files/src/app/shared/redeployment-warning/redeployment-warning.component.spec.ts.template +49 -10
  125. package/src/ng-add/files/src/app/shared/redeployment-warning/redeployment-warning.component.ts.template +5 -5
  126. package/src/ng-add/files/src/app/shared/redeployment-warning/redeployment-warning.service.spec.ts.template +86 -0
  127. package/src/ng-add/files/src/app/shared/redeployment-warning/redeployment-warning.service.ts.template +11 -9
  128. package/src/ng-add/files/src/environments/environment.prod.ts.template +1 -0
  129. package/src/ng-add/files/src/environments/environment.test.ts.template +1 -0
  130. package/src/ng-add/files/src/environments/environment.ts.template +2 -8
  131. package/src/ng-add/files/src/styles.scss.template +29 -1
  132. package/src/ng-add/files/tsconfig.app.json.template +6 -6
  133. package/src/ng-add/files/tsconfig.json.template +13 -8
  134. package/src/ng-add/files/tsconfig.spec.json.template +6 -5
  135. package/src/ng-add/index.js +19 -1
  136. package/src/ng-add/index.js.map +1 -1
  137. package/src/component/files/__name@dasherize__/__name@dasherize__.animations.ts.template +0 -4
  138. package/src/ng-add/files/src/app/admin/admin-panel/admin-panel.animations.ts.template +0 -4
  139. package/src/ng-add/files/src/app/admin/admin-panel/admin-user-list/admin-user-counts/admin-count-pill/admin-count-pill.animations.ts.template +0 -4
  140. package/src/ng-add/files/src/app/admin/admin-panel/admin-user-list/admin-user-counts/admin-user-counts.animations.ts.template +0 -4
  141. package/src/ng-add/files/src/app/admin/admin-panel/admin-user-list/admin-user-table/admin-user-table.animations.ts.template +0 -4
  142. package/src/ng-add/files/src/app/first-time/consent/consent.animations.ts.template +0 -4
  143. package/src/ng-add/files/src/app/first-time/early-access/early-access.animations.ts.template +0 -10
  144. package/src/ng-add/files/src/app/first-time/landing/hero/hero.animations.ts.template +0 -15
  145. package/src/ng-add/files/src/app/first-time/landing/landing.animations.ts.template +0 -4
  146. package/src/ng-add/files/src/app/first-time/onboarding/onboarding.animations.ts.template +0 -4
  147. package/src/ng-add/files/src/app/main/home/home.animations.ts.template +0 -4
@@ -2,12 +2,14 @@ import { WritableSignal, inject } from '@angular/core';
2
2
  import { Timestamp, writeBatch } from '@angular/fire/firestore';
3
3
  import { patchState, signalStoreFeature, withMethods } from '@ngrx/signals';
4
4
  import { removeEntities, removeEntity, setEntities, setEntity, updateEntity, withEntities, setAllEntities } from '@ngrx/signals/entities';
5
- import { EntityChanges, EntityId, SelectEntityId } from '@ngrx/signals/entities/src/models';
5
+ import { SelectEntityId } from '@ngrx/signals/entities';
6
6
  import { CachedListenersService } from '../firebase/cached-listeners.service';
7
+ import { queryLog } from '../firebase/query-logger';
7
8
  import { DATABASE_SERVICE, DatabaseService } from '../firebase/database.service';
8
9
  import { AnyEntity, QueryOptions, QueryParams } from './app.model';
9
10
  import { MatSnackBar, MatSnackBarConfig } from '@angular/material/snack-bar';
10
11
  import { WriteBatchI } from './batch-write.service';
12
+ import { environment } from '../../../environments/environment';
11
13
 
12
14
  const selectId: SelectEntityId<AnyEntity> = (entity) => entity.__id;
13
15
 
@@ -57,38 +59,59 @@ export function openSnackBarWithUndoOption(
57
59
  export function withEntitiesAndSelectMethods<S extends AnyEntity>() {
58
60
  return signalStoreFeature(
59
61
  withEntities<S>(),
60
- withMethods((store) => ({
61
- init(entities: S[]) {
62
- patchState(store, setAllEntities<S>(entities, { selectId }));
63
- },
64
- handleStreamChanges(entitiesToAdd: S[], entitiesToModify: S[], entitiesToRemove: string[]) {
65
- patchState(store, setEntities(entitiesToAdd, { selectId }));
66
- patchState(store, setEntities(entitiesToModify, { selectId }));
67
- patchState(store, removeEntities(entitiesToRemove));
68
- },
69
- selectEntity(id: string): S {
70
- const result = store.entityMap()[id];
62
+ withMethods((store) => {
63
+ const queryCache = new Map<string, S[]>();
64
+ return {
65
+ handleStreamChanges(entitiesToAdd: S[], entitiesToModify: S[], entitiesToRemove: string[]) {
66
+ patchState(store, setEntities(entitiesToAdd, { selectId }));
67
+ patchState(store, setEntities(entitiesToModify, { selectId }));
68
+ patchState(store, removeEntities(entitiesToRemove));
69
+ },
70
+ selectEntity(id: string): S {
71
+ const result = store.entityMap()[id];
72
+
73
+ if (result && !result['_deleted']) {
74
+ return result;
75
+ } else {
76
+ return null;
77
+ }
78
+ },
79
+ selectFirst(queryParams: QueryParams, queryOptions: QueryOptions): S {
80
+ // Note: selectEntities already filters out _deleted
81
+ const entities = selectEntities<S>(store.entityMap(), queryParams, queryOptions);
82
+ if (entities && entities.length > 0) {
83
+ return entities[0];
84
+ } else {
85
+ return null;
86
+ }
87
+ },
88
+ selectEntities(queryParams: QueryParams, queryOptions: QueryOptions): S[] {
89
+ // Note: The global standalone selectEntities function already filters out entities with _deleted: true
90
+ const result = selectEntities<S>(store.entityMap(), queryParams, queryOptions);
91
+ const key = JSON.stringify({ queryParams, queryOptions });
92
+
93
+ // CRITICAL: Angular's computed() signals rely on strict referential equality (===).
94
+ // Because Object.values().filter() creates a brand new array reference every time it is called,
95
+ // any computed signal that calls selectEntities() would trigger an update even if the contents
96
+ // of the array are identical. This led to infinite loops and massive memory leaks in nested streams.
97
+ // By memoizing the array reference here, we ensure that if the query results are strictly identical
98
+ // (same length, same entity references in the exact same order), we return the exact same array reference.
99
+ const lastResult = queryCache.get(key);
100
+ if (lastResult && lastResult.length === result.length && lastResult.every((v, i) => v === result[i])) {
101
+ return lastResult;
102
+ }
71
103
 
72
- if (result && !result['_deleted']) {
104
+ queryCache.set(key, result);
105
+
106
+ // Simple bounded LRU cache (max 50 unique queries per store) to prevent memory ballooning
107
+ if (queryCache.size > 50) {
108
+ const firstKey = queryCache.keys().next().value;
109
+ if (firstKey) queryCache.delete(firstKey);
110
+ }
73
111
  return result;
74
- } else {
75
- return null;
76
- }
77
- },
78
- selectFirst(queryParams: QueryParams, queryOptions: QueryOptions): S {
79
- // Note: selectEntities already filters out _deleted
80
- const entities = selectEntities<S>(store.entityMap(), queryParams, queryOptions);
81
- if (entities && entities.length > 0) {
82
- return entities[0];
83
- } else {
84
- return null;
85
- }
86
- },
87
- selectEntities(queryParams: QueryParams, queryOptions: QueryOptions): S[] {
88
- // Note: selectEntities already filters out _deleted
89
- return selectEntities<S>(store.entityMap(), queryParams, queryOptions);
90
- },
91
- })),
112
+ },
113
+ };
114
+ }),
92
115
  );
93
116
  }
94
117
 
@@ -117,7 +140,7 @@ export function withEntitiesForMockDB<S extends AnyEntity>(collectionName: strin
117
140
  withEntitiesAndSelectMethods<S>(),
118
141
  withMethods((store) => ({
119
142
  init(entities: S[]) {
120
- const saved = localStorage.getItem(`mockDB_${collectionName}`);
143
+ const saved = environment.cacheMockData ? localStorage.getItem(`mockDB_${collectionName}`) : null;
121
144
  if (saved) {
122
145
  patchState(store, setAllEntities<S>(deserializeMockDBData(saved), { selectId }));
123
146
  } else {
@@ -133,11 +156,15 @@ export function withEntitiesForMockDB<S extends AnyEntity>(collectionName: strin
133
156
  },
134
157
  add(entity: S) {
135
158
  patchState(store, setEntity<S>(entity, { selectId }));
136
- localStorage.setItem(`mockDB_${collectionName}`, serializeMockDBData(Object.values(store.entityMap())));
159
+ if (environment.cacheMockData) {
160
+ localStorage.setItem(`mockDB_${collectionName}`, serializeMockDBData(Object.values(store.entityMap())));
161
+ }
137
162
  },
138
163
  update(id: string, changes: Partial<S>) {
139
164
  patchState(store, updateEntity({ id, changes }, { selectId }));
140
- localStorage.setItem(`mockDB_${collectionName}`, serializeMockDBData(Object.values(store.entityMap())));
165
+ if (environment.cacheMockData) {
166
+ localStorage.setItem(`mockDB_${collectionName}`, serializeMockDBData(Object.values(store.entityMap())));
167
+ }
141
168
  },
142
169
  })),
143
170
  );
@@ -148,6 +175,9 @@ export function withEntitiesAndDBMethods<S extends AnyEntity>(collectionName: st
148
175
  return signalStoreFeature(
149
176
  withEntitiesAndSelectMethods<S>(),
150
177
  withMethods((store, cachedLoads = inject(CachedListenersService), db = inject(DATABASE_SERVICE), snackBar = inject(MatSnackBar)) => ({
178
+ init(entities: S[]) {
179
+ patchState(store, setAllEntities<S>(entities, { selectId }));
180
+ },
151
181
  // streaming tries to reduce redundant loads through the following:
152
182
  // - caching listeners and reusing them with a 5-second delay after moving to a new container before unsubscribing
153
183
  // additionally, it has the following constraints:
@@ -167,7 +197,17 @@ export function withEntitiesAndDBMethods<S extends AnyEntity>(collectionName: st
167
197
  // start loading icon if available
168
198
  options?.loading?.set(true);
169
199
 
170
- await cachedLoads.processStreamQuery(collectionName, store, queryParams, queryOptions, injector, streamQueries, options);
200
+ const isSimpleEqualityQuery = (!queryOptions || Object.keys(queryOptions).length === 0) &&
201
+ queryParams.length === 1 &&
202
+ (queryParams[0][1] === '==' || queryParams[0][1] === 'in');
203
+
204
+ if (isSimpleEqualityQuery) {
205
+ const field = queryParams[0][0];
206
+ const ids = queryParams[0][1] === 'in' ? queryParams[0][2] : [queryParams[0][2]];
207
+ await cachedLoads.processSimpleStreamQuery(collectionName, field, ids, store, injector, streamQueries, options);
208
+ } else {
209
+ await cachedLoads.processStreamQuery(collectionName, store, queryParams, queryOptions, injector, streamQueries, options);
210
+ }
171
211
  } catch (e) {
172
212
  console.error(e);
173
213
 
@@ -195,59 +235,184 @@ export function withEntitiesAndDBMethods<S extends AnyEntity>(collectionName: st
195
235
  // start loading icon if available
196
236
  options?.loading?.set(true);
197
237
 
198
- // only load if there is not already a listener for the same query
199
- if (!cachedLoads.isStreamForQuery(collectionName, queryParams, queryOptions)) {
200
- // get the last load time and next load time
201
- const lastLoadTime = cachedLoads.getLastLoadTime(collectionName, queryParams, queryOptions);
202
- const newLoadTime = Timestamp.now().toMillis();
203
-
204
- // load entities since last load that are not deleted
205
- // note that we always load all entities if there exist queryOptions since adding
206
- // the _updatedAt filter will change queries with limit
207
- let queryParamsWithTime;
208
- if (lastLoadTime === -1 || (queryOptions && Object.keys(queryOptions).length > 0)) {
209
- queryParamsWithTime = [...queryParams, ['_deleted', '==', false]];
210
- } else {
211
- queryParamsWithTime = [
212
- ...queryParams,
213
- ['_updatedAt', '>', Timestamp.fromMillis(lastLoadTime)],
214
- ['_deleted', '==', false],
215
- ];
216
- }
238
+ const isBatchableEqualityOrIn =
239
+ (!queryOptions || Object.keys(queryOptions).length === 0) &&
240
+ queryParams.length === 1 &&
241
+ (queryParams[0][1] === '==' || queryParams[0][1] === 'in');
242
+
243
+ if (!isBatchableEqualityOrIn) {
244
+ // ---------------------------------------------------------
245
+ // LEGACY PATH: Non-equality queries use full query-string tracking
246
+ // ---------------------------------------------------------
247
+ // only load if there is not already a listener for the same query
248
+ if (!cachedLoads.isStreamForQuery(collectionName, queryParams, queryOptions)) {
249
+ // get the last load time and next load time
250
+ const lastLoadTime = cachedLoads.getLastLoadTime(collectionName, queryParams, queryOptions);
251
+ const newLoadTime = Timestamp.now().toMillis();
252
+
253
+ // load entities since last load that are not deleted
254
+ // note that we always load all entities if there exist queryOptions since adding
255
+ // the _updatedAt filter will change queries with limit
256
+ let queryParamsWithTime;
257
+ if (lastLoadTime === -1 || (queryOptions && Object.keys(queryOptions).length > 0)) {
258
+ queryParamsWithTime = [...queryParams, ['_deleted', '==', false]];
259
+ } else {
260
+ queryParamsWithTime = [
261
+ ...queryParams,
262
+ ['_updatedAt', '>', Timestamp.fromMillis(lastLoadTime)],
263
+ ['_deleted', '==', false],
264
+ ];
265
+ }
217
266
 
218
- // get entities that have been added or updated since last load
219
- const entitiesDelta: S[] = await db.getEntities(
220
- collectionName,
221
- queryParamsWithTime,
222
- queryOptions,
223
- );
224
- patchState(store, setEntities<S>(entitiesDelta, { selectId }));
225
-
226
- // delete any new deleted entities
227
- if (lastLoadTime === -1 || (queryOptions && Object.keys(queryOptions).length > 0)) {
228
- const entitiesDeletedDelta: S[] = await db.getEntities(
267
+ // get entities that have been added or updated since last load
268
+ const entitiesDelta: S[] = await db.getEntities(
229
269
  collectionName,
230
- [...queryParams, ['_deleted', '==', true]],
231
- queryOptions,
232
- );
233
- patchState(store, removeEntities(
234
- entitiesDeletedDelta.map((e) => e.__id),
235
- ));
236
- } else {
237
- const entitiesDeletedDelta: S[] = await db.getEntities(
238
- collectionName,
239
- [...queryParams,
240
- ['_updatedAt', '>', Timestamp.fromMillis(lastLoadTime)],
241
- ['_deleted', '==', true]],
270
+ queryParamsWithTime,
242
271
  queryOptions,
243
272
  );
244
- patchState(store, removeEntities(
245
- entitiesDeletedDelta.map((e) => e.__id),
246
- ));
247
- }
273
+ patchState(store, setEntities<S>(entitiesDelta, { selectId }));
274
+
275
+ // delete any new deleted entities
276
+ if (lastLoadTime === -1 || (queryOptions && Object.keys(queryOptions).length > 0)) {
277
+ const entitiesDeletedDelta: S[] = await db.getEntities(
278
+ collectionName,
279
+ [...queryParams, ['_deleted', '==', true]],
280
+ queryOptions,
281
+ );
282
+ patchState(store, removeEntities(
283
+ entitiesDeletedDelta.map((e) => e.__id),
284
+ ));
285
+ } else {
286
+ const entitiesDeletedDelta: S[] = await db.getEntities(
287
+ collectionName,
288
+ [...queryParams,
289
+ ['_updatedAt', '>', Timestamp.fromMillis(lastLoadTime)],
290
+ ['_deleted', '==', true]],
291
+ queryOptions,
292
+ );
293
+ patchState(store, removeEntities(
294
+ entitiesDeletedDelta.map((e) => e.__id),
295
+ ));
296
+ }
248
297
 
249
- // save a new lastLoadTime for this query
250
- cachedLoads.setLastLoadTime(collectionName, queryParams, queryOptions, newLoadTime);
298
+ // save a new lastLoadTime for this query
299
+ cachedLoads.setLastLoadTime(collectionName, queryParams, queryOptions, newLoadTime);
300
+ }
301
+ } else {
302
+ // ---------------------------------------------------------
303
+ // OPTIMIZED PATH: Per-entity tracking for == and in queries
304
+ // ---------------------------------------------------------
305
+ const field = queryParams[0][0] as string;
306
+ const operator = queryParams[0][1];
307
+ const rawValues = operator === '==' ? [queryParams[0][2] as string] : queryParams[0][2] as string[];
308
+
309
+ // 1. Remove IDs already covered by active streams
310
+ const valuesToLoad = rawValues.filter((v) => {
311
+ // Check if it's covered by a multiplexer stream
312
+ if (cachedLoads.isIdStreamed(collectionName, field, v)) return false;
313
+ return true;
314
+ });
315
+
316
+ if (valuesToLoad.length > 0) {
317
+ const newLoadTime = Timestamp.now().toMillis();
318
+
319
+ if (field === '__id' && valuesToLoad.length === 1) {
320
+ const idToFetch = valuesToLoad[0];
321
+ queryLog(`[Store] Optimized Load Triggered for collection '${collectionName}', fetching single ID using getDoc.`);
322
+
323
+ const entity = await db.getEntity<S>(collectionName, idToFetch);
324
+
325
+ if (entity) {
326
+ if (entity._deleted) {
327
+ patchState(store, removeEntities([idToFetch]));
328
+ } else {
329
+ patchState(store, setEntities<S>([entity], { selectId }));
330
+ }
331
+ } else {
332
+ patchState(store, removeEntities([idToFetch]));
333
+ }
334
+
335
+ cachedLoads.setEntityLoadTime(collectionName, field, idToFetch, newLoadTime);
336
+ } else {
337
+ // 2. Group values by their entityLoadTime (Time Bucketing Strategy)
338
+ // To prevent the N+1 problem of issuing dozens of queries for items with slightly
339
+ // different load times, we group loaded items into 5-minute buckets.
340
+ // Unloaded items (-1) are strictly kept in their own bucket to prevent over-fetching.
341
+ const BUCKET_MS = 5 * 60 * 1000;
342
+
343
+ // Map bucket index to the exact minimum time in that bucket and its values
344
+ const groupsByBucket: Map<number, { minTime: number, values: string[] }> = new Map();
345
+
346
+ queryLog(`[Store] Optimized Load Triggered for collection '${collectionName}', tracking ${valuesToLoad.length} IDs.`);
347
+
348
+ valuesToLoad.forEach((val) => {
349
+ const time = cachedLoads.getEntityLoadTime(collectionName, field, val);
350
+ const bucketIndex = time === -1 ? -1 : Math.floor(time / BUCKET_MS);
351
+
352
+ if (!groupsByBucket.has(bucketIndex)) {
353
+ groupsByBucket.set(bucketIndex, { minTime: time, values: [] });
354
+ }
355
+
356
+ const group = groupsByBucket.get(bucketIndex)!;
357
+ // Track the earliest load time in this bucket
358
+ if (time !== -1 && time < group.minTime) {
359
+ group.minTime = time;
360
+ }
361
+ group.values.push(val);
362
+ });
363
+
364
+ // 3. For each group, execute DB fetches
365
+ queryLog(`[Store] Grouped ${valuesToLoad.length} IDs into ${groupsByBucket.size} time bucket(s).`);
366
+ await Promise.all(Array.from(groupsByBucket.entries()).map(async ([bucketIndex, group]) => {
367
+ const lastTime = group.minTime;
368
+ const groupValues = group.values;
369
+ queryLog(`[Store] Bucket ${bucketIndex === -1 ? '(-1: Never Loaded)' : bucketIndex} (minTime: ${lastTime === -1 ? 'Never' : new Date(lastTime).toISOString()}) fetching ${groupValues.length} IDs.`);
370
+ // Chunk into 30s
371
+ for (let i = 0; i < groupValues.length; i += 30) {
372
+ const chunk = groupValues.slice(i, i + 30);
373
+ const batchedParams: QueryParams = [[field, 'in', chunk]];
374
+ queryLog(`[Store] -> Fetching chunk of ${chunk.length} IDs...`);
375
+
376
+ // Fetch changed entities
377
+ let queryParamsWithTime: QueryParams;
378
+ if (lastTime === -1) {
379
+ queryParamsWithTime = [...batchedParams, ['_deleted', '==', false]];
380
+ } else {
381
+ queryParamsWithTime = [
382
+ ...batchedParams,
383
+ ['_updatedAt', '>', Timestamp.fromMillis(lastTime)],
384
+ ['_deleted', '==', false],
385
+ ];
386
+ }
387
+ const entitiesDelta: S[] = await db.getEntities(collectionName, queryParamsWithTime, {});
388
+ if (entitiesDelta.length > 0) {
389
+ queryLog(`[Store] -> Loaded ${entitiesDelta.length} updated/new entities from chunk.`);
390
+ }
391
+ patchState(store, setEntities<S>(entitiesDelta, { selectId }));
392
+
393
+ // Fetch soft-deleted entities
394
+ let deletedParamsWithTime: QueryParams;
395
+ if (lastTime === -1) {
396
+ deletedParamsWithTime = [...batchedParams, ['_deleted', '==', true]];
397
+ } else {
398
+ deletedParamsWithTime = [
399
+ ...batchedParams,
400
+ ['_updatedAt', '>', Timestamp.fromMillis(lastTime)],
401
+ ['_deleted', '==', true],
402
+ ];
403
+ }
404
+ const entitiesDeletedDelta: S[] = await db.getEntities(collectionName, deletedParamsWithTime, {});
405
+ if (entitiesDeletedDelta.length > 0) {
406
+ queryLog(`[Store] -> Removed ${entitiesDeletedDelta.length} soft-deleted entities from chunk.`);
407
+ }
408
+ patchState(store, removeEntities(entitiesDeletedDelta.map(selectId) as string[]));
409
+ }
410
+ }));
411
+
412
+ // 4. Update entityLoadTime for all fetched values to the unified newLoadTime
413
+ valuesToLoad.forEach((val) => cachedLoads.setEntityLoadTime(collectionName, field, val, newLoadTime));
414
+ }
415
+ }
251
416
  }
252
417
 
253
418
  if (loadQueries) {
@@ -326,7 +491,7 @@ export function withEntitiesAndDBMethods<S extends AnyEntity>(collectionName: st
326
491
  id,
327
492
  changes: Object.assign({}, changes, {
328
493
  _updatedAt: Timestamp.now(),
329
- }) as EntityChanges<NoInfer<S>>,
494
+ }) as Partial<NoInfer<S>>,
330
495
  }, { selectId }));
331
496
  await db.incrementEntityField(collectionName, id, field, delta);
332
497
  } catch (e) {
@@ -350,7 +515,7 @@ export function withEntitiesAndDBMethods<S extends AnyEntity>(collectionName: st
350
515
  id,
351
516
  changes: Object.assign({}, changes, {
352
517
  _updatedAt: Timestamp.now(),
353
- }) as EntityChanges<NoInfer<S>>,
518
+ }) as Partial<NoInfer<S>>,
354
519
  }, { selectId }));
355
520
  } catch (e) {
356
521
  console.error(e);
@@ -514,7 +679,7 @@ export function withEntitiesAndDBMethods<S extends AnyEntity>(collectionName: st
514
679
  id,
515
680
  changes: Object.assign({}, changes, {
516
681
  _updatedAt: Timestamp.now(),
517
- }) as EntityChanges<NoInfer<S>>,
682
+ }) as Partial<NoInfer<S>>,
518
683
  }, { selectId }));
519
684
  };
520
685
 
@@ -859,7 +1024,6 @@ export function selectEntities<T>(entityMap: Record<string, T>, queryParams: Que
859
1024
  // Note: Only supports single field orderBy for cursor pagination in local store mock for now
860
1025
  if (queryOptions?.orderBy && (queryOptions?.startAt !== undefined || queryOptions?.startAfter !== undefined ||
861
1026
  queryOptions?.endAt !== undefined || queryOptions?.endBefore !== undefined)) {
862
-
863
1027
  let primaryField = '';
864
1028
  if (Array.isArray(queryOptions.orderBy)) {
865
1029
  if (Array.isArray(queryOptions.orderBy[0])) {
@@ -996,6 +1160,9 @@ export async function processLoadQueries<T extends { __id: string }>(entities: T
996
1160
 
997
1161
  // Process queries concurrently using Promise.all
998
1162
  await Promise.all(optimizedQueries.filter((q) => !!q).map(async (query) => {
1163
+ // Firestore throws an error if an 'in' query is executed with an empty array.
1164
+ // Therefore, we skip executing any queries that have an 'in' clause with an empty array.
1165
+ // Example: ['__id', 'in', []]
999
1166
  if (!query.queryParams.some((param) => Array.isArray(param[2]) && param[2].length === 0 && param[1] === 'in')) {
1000
1167
  await query.store.load(query.queryParams, query.queryOptions, query.loadQueries);
1001
1168
  }
@@ -1027,15 +1194,20 @@ export class EntityLoadQuery<T> {
1027
1194
 
1028
1195
  // Checks if there is a single equality query of the same type
1029
1196
  // that could be transformed into an 'in' query
1030
- static isEqualityQuery<T>(queries: EntityLoadQuery<T>[]): boolean {
1197
+ static areBatchableEqualityQueries<T>(queries: EntityLoadQuery<T>[]): boolean {
1031
1198
  if (queries.length === 0) return false;
1032
1199
 
1033
- // check if there is only one queryParam for each query
1034
- const hasSingleQueryParam = queries.every((q) => q.queryParams.length === 1);
1200
+ // check if there is only one queryParam for each query and no queryOptions
1201
+ const hasSingleQueryParamAndNoOptions = queries.every((q) => {
1202
+ return q.queryParams.length === 1 && (!q.queryOptions || Object.keys(q.queryOptions).length === 0);
1203
+ });
1035
1204
 
1036
- if (!hasSingleQueryParam) return false;
1205
+ if (!hasSingleQueryParamAndNoOptions) return false;
1037
1206
 
1038
- // check if the field is the same and it is an equality query
1207
+ // Finally, verify that every query is filtering on the exact same field
1208
+ // (e.g., they are all querying '__userId') AND that they are all using the
1209
+ // exact equality operator ('=='). This ensures they can be safely collapsed
1210
+ // into a single 'in' query (e.g., '__userId in [1, 2, 3]').
1039
1211
  const firstField = queries[0].queryParams[0][0];
1040
1212
  return queries.every((q) => q.queryParams[0][0] === firstField && q.queryParams[0][1] === '==');
1041
1213
  }
@@ -1045,31 +1217,28 @@ export class EntityLoadQuery<T> {
1045
1217
  // Transform this into 'in' queries, combining up to 30 equality clauses
1046
1218
  // at the same time, https://firebase.google.com/docs/firestore/query-data/queries#in_and_array-contains-any.
1047
1219
  static optimize<T>(queries: EntityLoadQuery<T>[]): EntityLoadQuery<T>[] {
1048
- // TODO: we are temporarily not doing any of these optimizations until we can
1049
- // figure out a better way to prevent reloading of duplicate queries. Right
1050
- // now we remember the load time of particular queries which allows us to
1051
- // only query for documents past a given time. However, by grouping them
1052
- // together into 'in' queries, we won't be able to take advantage of that since
1053
- // the grouping could be different as entities are added/deleted
1054
- return queries;
1055
-
1056
- if (this.isEqualityQuery<T>(queries)) {
1220
+ // Optimization: batch N individual equality queries (e.g. [['__userId', '==', x]])
1221
+ // into ceil(N/30) Firestore 'in' queries. This solves the N+1 problem where
1222
+ // streaming N parent entities would otherwise create N individual child listeners.
1223
+ //
1224
+ // Tradeoff: batching changes the query key, which means per-query lastLoadTime
1225
+ // tracking cannot efficiently provide incremental (delta-only) loads when the
1226
+ // batch composition changes (entity added/removed). However, the reduction from
1227
+ // N separate DB reads to 1 batched read far outweighs the cost of occasionally
1228
+ // re-fetching already-loaded child documents.
1229
+
1230
+ if (this.areBatchableEqualityQueries<T>(queries)) {
1057
1231
  // get the field we are querying against
1058
1232
  const collection: string = queries[0].collection;
1059
1233
  const field: string = queries[0].queryParams[0][0];
1060
1234
  const loadQs: (entity: T) => EntityLoadQuery<AnyEntity>[] = queries[0].loadQueries;
1061
1235
 
1062
- // chunk queries into chunks of 30
1063
- const chunkedQueries: EntityLoadQuery<T>[][] = [];
1064
- for (let i = 0; i < queries.length; i += 30) {
1065
- chunkedQueries.push(queries.slice(i, i + 30));
1066
- }
1067
-
1068
- // transform every 30 into an 'in' query
1069
- return chunkedQueries.map((queryChunk) => {
1070
- const ids = queryChunk.map((q) => q.queryParams[0][2]);
1071
- return new EntityLoadQuery<T>(collection, queries[0].store, [[field, 'in', ids]], {}, loadQs);
1072
- });
1236
+ // We no longer chunk into groups of 30 here. Instead, we bundle ALL IDs into a single 'in'
1237
+ // query. The `load()` method will intercept this unified query, generate a single `newLoadTime`,
1238
+ // and perform the 30-item chunking internally. This guarantees that all entities requested
1239
+ // together receive the exact same timestamp.
1240
+ const ids = queries.map((q) => q.queryParams[0][2]);
1241
+ return [new EntityLoadQuery<T>(collection, queries[0].store, [[field, 'in', ids]], {}, loadQs)];
1073
1242
  } else {
1074
1243
  return queries;
1075
1244
  }
@@ -1099,15 +1268,20 @@ export class EntityStreamQuery<T> {
1099
1268
 
1100
1269
  // Checks if there is a single equality query of the same type
1101
1270
  // that could be transformed into an 'in' query
1102
- static isEqualityQuery<T>(queries: EntityStreamQuery<T>[]): boolean {
1271
+ static areBatchableEqualityQueries<T>(queries: EntityStreamQuery<T>[]): boolean {
1103
1272
  if (queries.length === 0) return false;
1104
1273
 
1105
- // check if there is only one queryParam for each query
1106
- const hasSingleQueryParam = queries.every((q) => q.queryParams.length === 1);
1274
+ // check if there is only one queryParam for each query and no queryOptions
1275
+ const hasSingleQueryParamAndNoOptions = queries.every((q) => {
1276
+ return q.queryParams.length === 1 && (!q.queryOptions || Object.keys(q.queryOptions).length === 0);
1277
+ });
1107
1278
 
1108
- if (!hasSingleQueryParam) return false;
1279
+ if (!hasSingleQueryParamAndNoOptions) return false;
1109
1280
 
1110
- // check if the field is the same and it is an equality query
1281
+ // Finally, verify that every query is filtering on the exact same field
1282
+ // (e.g., they are all querying '__userId') AND that they are all using the
1283
+ // exact equality operator ('=='). This ensures they can be safely collapsed
1284
+ // into a single 'in' query (e.g., '__userId in [1, 2, 3]').
1111
1285
  const firstField = queries[0].queryParams[0][0];
1112
1286
  return queries.every((q) => q.queryParams[0][0] === firstField && q.queryParams[0][1] === '==');
1113
1287
  }
@@ -1117,31 +1291,23 @@ export class EntityStreamQuery<T> {
1117
1291
  // Transform this into 'in' queries, combining up to 30 equality clauses
1118
1292
  // at the same time, https://firebase.google.com/docs/firestore/query-data/queries#in_and_array-contains-any.
1119
1293
  static optimize<T>(queries: EntityStreamQuery<T>[]): EntityStreamQuery<T>[] {
1120
- // TODO: we are temporarily not doing any of these optimizations until we can
1121
- // figure out a better way to prevent reloading of duplicate queries. Right
1122
- // now we remember the load time of particular queries which allows us to
1123
- // only query for documents past a given time. However, by grouping them
1124
- // together into 'in' queries, we won't be able to take advantage of that since
1125
- // the grouping could be different as entities are added/deleted
1126
- return queries;
1127
-
1128
- if (this.isEqualityQuery<T>(queries)) {
1294
+ // Optimization: batch N individual equality queries into ceil(N/30) Firestore
1295
+ // 'in' queries. For streams, the pairwise() diffing in processStreamQuery()
1296
+ // ensures that only changed parent entities trigger nested queries. This means
1297
+ // the initial batch of N entities gets optimally collapsed, while subsequent
1298
+ // individual changes create small (typically 1-element) listeners.
1299
+ //
1300
+ // Listener lifecycle: batched 'in' listeners share the parent component's
1301
+ // DestroyRef for cleanup, matching the behavior of individual listeners.
1302
+
1303
+ if (this.areBatchableEqualityQueries<T>(queries)) {
1129
1304
  // get the field we are querying against
1130
1305
  const collection: string = queries[0].collection;
1131
1306
  const field: string = queries[0].queryParams[0][0];
1132
1307
  const streamQs: (entity: T) => EntityStreamQuery<AnyEntity>[] = queries[0].streamQueries;
1133
1308
 
1134
- // chunk queries into chunks of 30
1135
- const chunkedQueries: EntityStreamQuery<T>[][] = [];
1136
- for (let i = 0; i < queries.length; i += 30) {
1137
- chunkedQueries.push(queries.slice(i, i + 30));
1138
- }
1139
-
1140
- // transform every 30 into an 'in' query
1141
- return chunkedQueries.map((queryChunk) => {
1142
- const ids = queryChunk.map((q) => q.queryParams[0][2]);
1143
- return new EntityStreamQuery<T>(collection, queries[0].store, [[field, 'in', ids]], {}, streamQs);
1144
- });
1309
+ const ids = queries.map((q) => q.queryParams[0][2]);
1310
+ return [new EntityStreamQuery<T>(collection, queries[0].store, [[field, 'in', ids]], {}, streamQs)];
1145
1311
  } else {
1146
1312
  return queries;
1147
1313
  }