@tech4good/angular-schematics 20.3.1 → 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 (144) 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/.t4g/agent-memory.db +0 -0
  5. package/CHANGELOG.md +62 -0
  6. package/contributing-docs/commit-message.md +3 -6
  7. package/package.json +5 -5
  8. package/src/collection.json +8 -0
  9. package/src/component/files/__name@dasherize__/__name@dasherize__.component.ts.template +1 -3
  10. package/src/component/index_spec.js +57 -4
  11. package/src/component/index_spec.js.map +1 -1
  12. package/src/entity/index.js +7 -1
  13. package/src/entity/index.js.map +1 -1
  14. package/src/entity/index_spec.js +108 -4
  15. package/src/entity/index_spec.js.map +1 -1
  16. package/src/guard/files/__name@dasherize__.guard.spec.ts.template +45 -0
  17. package/src/guard/files/__name@dasherize__.guard.ts.template +32 -0
  18. package/src/guard/index.d.ts +2 -0
  19. package/src/guard/index.js +38 -0
  20. package/src/guard/index.js.map +1 -0
  21. package/src/guard/index_spec.d.ts +1 -0
  22. package/src/guard/index_spec.js +64 -0
  23. package/src/guard/index_spec.js.map +1 -0
  24. package/src/guard/schema.json +46 -0
  25. package/src/ng-add/files/.firebaserc.template +3 -2
  26. package/src/ng-add/files/.github/workflows/angular-github-ci.yml.template +105 -39
  27. package/src/ng-add/files/.gitignore.template +1 -2
  28. package/src/ng-add/files/angular.json.template +1 -5
  29. package/src/ng-add/files/docs-infra/infrastructure-guide.md.template +390 -0
  30. package/src/ng-add/files/docs-infra/load-system-architecture.md.template +166 -0
  31. package/src/ng-add/files/docs-infra/querying-strategy.md.template +157 -0
  32. package/src/ng-add/files/docs-infra/stream-system-architecture.md.template +283 -0
  33. package/src/ng-add/files/eslint.config.js.template +4 -1
  34. package/src/ng-add/files/firebase.json.template +37 -0
  35. package/src/ng-add/files/firestore.rules.spec.ts.template +221 -0
  36. package/src/ng-add/files/firestore.rules.template +67 -0
  37. package/src/ng-add/files/jest.config.ts.template +6 -1
  38. package/src/ng-add/files/package.json.template +41 -31
  39. package/src/ng-add/files/setup-jest.ts.template +13 -5
  40. package/src/ng-add/files/src/app/admin/admin-panel/admin-panel.component.spec.ts.template +76 -12
  41. package/src/ng-add/files/src/app/admin/admin-panel/admin-panel.component.ts.template +1 -3
  42. package/src/ng-add/files/src/app/admin/admin-panel/admin-settings/admin-settings.component.spec.ts.template +90 -0
  43. package/src/ng-add/files/src/app/admin/admin-panel/admin-settings/admin-settings.component.ts.template +1 -1
  44. 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
  45. 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
  46. 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
  47. package/src/ng-add/files/src/app/admin/admin-panel/admin-user-list/admin-user-counts/admin-user-counts.component.ts.template +3 -5
  48. package/src/ng-add/files/src/app/admin/admin-panel/admin-user-list/admin-user-list.component.html.template +2 -2
  49. package/src/ng-add/files/src/app/admin/admin-panel/admin-user-list/admin-user-list.component.spec.ts.template +108 -0
  50. package/src/ng-add/files/src/app/admin/admin-panel/admin-user-list/admin-user-list.component.ts.template +11 -11
  51. package/src/ng-add/files/src/app/admin/admin-panel/admin-user-list/admin-user-table/admin-user-table.component.html.template +6 -2
  52. 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
  53. package/src/ng-add/files/src/app/admin/admin-panel/admin-user-list/admin-user-table/admin-user-table.component.ts.template +8 -5
  54. package/src/ng-add/files/src/app/app.component.html.template +1 -1
  55. package/src/ng-add/files/src/app/app.component.scss.template +10 -0
  56. package/src/ng-add/files/src/app/app.component.ts.template +1 -1
  57. package/src/ng-add/files/src/app/app.config.ts.template +11 -11
  58. package/src/ng-add/files/src/app/auth-routing.spec.ts.template +101 -0
  59. package/src/ng-add/files/src/app/core/analytics/log.service.ts.template +5 -8
  60. package/src/ng-add/files/src/app/core/analytics/time-analytics.service.spec.ts.template +140 -0
  61. package/src/ng-add/files/src/app/core/analytics/time-analytics.service.ts.template +25 -7
  62. package/src/ng-add/files/src/app/core/auth/guards/redirect-if-authenticated.guard.ts.template +1 -1
  63. package/src/ng-add/files/src/app/core/auth/guards/require-admin.guard.ts.template +1 -1
  64. package/src/ng-add/files/src/app/core/auth/guards/require-auth-and-consent.guard.ts.template +1 -1
  65. package/src/ng-add/files/src/app/core/auth/guards/require-auth.guard.ts.template +1 -1
  66. package/src/ng-add/files/src/app/core/firebase/cached-listeners.service.ts.template +229 -14
  67. package/src/ng-add/files/src/app/core/firebase/database.service.ts.template +1 -1
  68. package/src/ng-add/files/src/app/core/firebase/firebase.mock.service.ts.template +34 -9
  69. package/src/ng-add/files/src/app/core/firebase/firebase.service.ts.template +4 -4
  70. package/src/ng-add/files/src/app/core/firebase/query-logger.ts.template +11 -0
  71. package/src/ng-add/files/src/app/core/firebase/simulate-load.spec.ts.template +104 -0
  72. package/src/ng-add/files/src/app/core/firebase/simulate-stream.spec.ts.template +127 -0
  73. package/src/ng-add/files/src/app/core/firebase/simulation.mock.ts.template +38 -0
  74. package/src/ng-add/files/src/app/core/firebase/stream-multiplexer.ts.template +443 -0
  75. package/src/ng-add/files/src/app/core/store/app.store.spec.ts.template +920 -0
  76. package/src/ng-add/files/src/app/core/store/app.store.ts.template +303 -137
  77. package/src/ng-add/files/src/app/core/store/auth/auth.mock.ts.template +65 -23
  78. package/src/ng-add/files/src/app/core/store/auth/auth.store.ts.template +68 -67
  79. package/src/ng-add/files/src/app/core/store/user/user.mock.ts.template +46 -0
  80. package/src/ng-add/files/src/app/core/store/user-context/user-context.mock.ts.template +17 -0
  81. package/src/ng-add/files/src/app/core/testing/test-utils.ts.template +26 -0
  82. package/src/ng-add/files/src/app/first-time/consent/consent.component.html.template +3 -3
  83. package/src/ng-add/files/src/app/first-time/consent/consent.component.spec.ts.template +89 -13
  84. package/src/ng-add/files/src/app/first-time/consent/consent.component.ts.template +46 -17
  85. package/src/ng-add/files/src/app/first-time/consent/consent.guard.ts.template +1 -1
  86. package/src/ng-add/files/src/app/first-time/early-access/early-access.component.html.template +5 -63
  87. package/src/ng-add/files/src/app/first-time/early-access/early-access.component.scss.template +1 -94
  88. package/src/ng-add/files/src/app/first-time/early-access/early-access.component.spec.ts.template +150 -14
  89. package/src/ng-add/files/src/app/first-time/early-access/early-access.component.ts.template +15 -42
  90. package/src/ng-add/files/src/app/first-time/early-access/early-access.guard.ts.template +2 -2
  91. package/src/ng-add/files/src/app/first-time/early-access/early-access.model.ts.template +5 -0
  92. package/src/ng-add/files/src/app/first-time/early-access/survey-form/survey-form.component.html.template +42 -0
  93. package/src/ng-add/files/src/app/first-time/early-access/survey-form/survey-form.component.scss.template +96 -0
  94. package/src/ng-add/files/src/app/first-time/early-access/survey-form/survey-form.component.spec.ts.template +37 -0
  95. package/src/ng-add/files/src/app/first-time/early-access/survey-form/survey-form.component.ts.template +63 -0
  96. package/src/ng-add/files/src/app/first-time/early-access/waitlist-view/waitlist-view.component.html.template +16 -0
  97. package/src/ng-add/files/src/app/first-time/early-access/waitlist-view/waitlist-view.component.scss.template +7 -0
  98. package/src/ng-add/files/src/app/first-time/early-access/waitlist-view/waitlist-view.component.spec.ts.template +41 -0
  99. package/src/ng-add/files/src/app/first-time/early-access/waitlist-view/waitlist-view.component.ts.template +26 -0
  100. package/src/ng-add/files/src/app/first-time/first-time-routing.spec.ts.template +123 -0
  101. package/src/ng-add/files/src/app/first-time/landing/hero/hero.component.html.template +11 -4
  102. package/src/ng-add/files/src/app/first-time/landing/hero/hero.component.scss.template +17 -4
  103. package/src/ng-add/files/src/app/first-time/landing/hero/hero.component.ts.template +5 -5
  104. package/src/ng-add/files/src/app/first-time/landing/landing.component.html.template +1 -1
  105. package/src/ng-add/files/src/app/first-time/landing/landing.component.scss.template +0 -1
  106. package/src/ng-add/files/src/app/first-time/landing/landing.component.spec.ts.template +25 -17
  107. package/src/ng-add/files/src/app/first-time/landing/landing.component.ts.template +4 -12
  108. package/src/ng-add/files/src/app/first-time/landing/rotating-quotes/rotating-quotes.component.ts.template +1 -1
  109. package/src/ng-add/files/src/app/first-time/login/login.component.spec.ts.template +36 -16
  110. package/src/ng-add/files/src/app/first-time/login/login.component.ts.template +1 -1
  111. package/src/ng-add/files/src/app/first-time/onboarding/onboarding.component.spec.ts.template +11 -15
  112. package/src/ng-add/files/src/app/first-time/onboarding/onboarding.component.ts.template +1 -3
  113. package/src/ng-add/files/src/app/main/home/home.component.ts.template +1 -3
  114. package/src/ng-add/files/src/app/shared/dev-status-bar/dev-status-bar.component.spec.ts.template +98 -0
  115. package/src/ng-add/files/src/app/shared/dev-status-bar/dev-status-bar.component.ts.template +9 -3
  116. package/src/ng-add/files/src/app/shared/hint-visibility/hint-visibility.directive.spec.ts.template +164 -0
  117. package/src/ng-add/files/src/app/shared/hint-visibility/hint-visibility.directive.ts.template +20 -18
  118. package/src/ng-add/files/src/app/shared/navbar/navbar.component.spec.ts.template +38 -17
  119. package/src/ng-add/files/src/app/shared/navbar/navbar.component.ts.template +1 -1
  120. package/src/ng-add/files/src/app/shared/redeployment-warning/redeployment-warning.component.html.template +1 -1
  121. package/src/ng-add/files/src/app/shared/redeployment-warning/redeployment-warning.component.spec.ts.template +49 -10
  122. package/src/ng-add/files/src/app/shared/redeployment-warning/redeployment-warning.component.ts.template +5 -5
  123. package/src/ng-add/files/src/app/shared/redeployment-warning/redeployment-warning.service.spec.ts.template +86 -0
  124. package/src/ng-add/files/src/app/shared/redeployment-warning/redeployment-warning.service.ts.template +11 -9
  125. package/src/ng-add/files/src/environments/environment.prod.ts.template +1 -0
  126. package/src/ng-add/files/src/environments/environment.test.ts.template +1 -0
  127. package/src/ng-add/files/src/environments/environment.ts.template +2 -8
  128. package/src/ng-add/files/src/styles.scss.template +29 -1
  129. package/src/ng-add/files/tsconfig.app.json.template +6 -6
  130. package/src/ng-add/files/tsconfig.json.template +13 -8
  131. package/src/ng-add/files/tsconfig.spec.json.template +6 -5
  132. package/src/ng-add/index.js +19 -1
  133. package/src/ng-add/index.js.map +1 -1
  134. package/src/component/files/__name@dasherize__/__name@dasherize__.animations.ts.template +0 -4
  135. package/src/ng-add/files/src/app/admin/admin-panel/admin-panel.animations.ts.template +0 -4
  136. 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
  137. package/src/ng-add/files/src/app/admin/admin-panel/admin-user-list/admin-user-counts/admin-user-counts.animations.ts.template +0 -4
  138. package/src/ng-add/files/src/app/admin/admin-panel/admin-user-list/admin-user-table/admin-user-table.animations.ts.template +0 -4
  139. package/src/ng-add/files/src/app/first-time/consent/consent.animations.ts.template +0 -4
  140. package/src/ng-add/files/src/app/first-time/early-access/early-access.animations.ts.template +0 -10
  141. package/src/ng-add/files/src/app/first-time/landing/hero/hero.animations.ts.template +0 -15
  142. package/src/ng-add/files/src/app/first-time/landing/landing.animations.ts.template +0 -4
  143. package/src/ng-add/files/src/app/first-time/onboarding/onboarding.animations.ts.template +0 -4
  144. package/src/ng-add/files/src/app/main/home/home.animations.ts.template +0 -4
@@ -0,0 +1,920 @@
1
+ /**
2
+ * Test suite for the core query system in app.store.ts.
3
+ *
4
+ * Tests are organized into three groups:
5
+ * 1. Pure function tests: selectEntities(), entityInQueryResults()
6
+ * 2. Query class tests: EntityLoadQuery.areBatchableEqualityQueries(), EntityLoadQuery.optimize(),
7
+ * EntityStreamQuery.areBatchableEqualityQueries(), EntityStreamQuery.optimize()
8
+ * 3. Integration tests: processLoadQueries() end-to-end with mock stores
9
+ *
10
+ * Tests marked with [OPTIMIZATION] are expected to fail until the optimize()
11
+ * methods are re-enabled (Phase 3). They document the intended batching behavior.
12
+ */
13
+ import {
14
+ selectEntities,
15
+ entityInQueryResults,
16
+ EntityLoadQuery,
17
+ EntityStreamQuery,
18
+ processLoadQueries,
19
+ } from './app.store';
20
+ import { Timestamp } from '@angular/fire/firestore';
21
+
22
+ // ---------------------------------------------------------------------------
23
+ // Helpers: create minimal mock entities with required metadata fields
24
+ // ---------------------------------------------------------------------------
25
+
26
+ /**
27
+ * Creates a minimal entity with the required __id, _deleted, and _updatedAt fields.
28
+ * Additional fields can be passed as overrides.
29
+ */
30
+ function createEntity(
31
+ id: string,
32
+ overrides: Record<string, any> = {},
33
+ ): { __id: string } & Record<string, any> {
34
+ return {
35
+ __id: id,
36
+ _deleted: false,
37
+ _createdAt: Timestamp.now(),
38
+ _updatedAt: Timestamp.now(),
39
+ ...overrides,
40
+ };
41
+ }
42
+
43
+ // ---------------------------------------------------------------------------
44
+ // 1. selectEntities() — local store filtering
45
+ // ---------------------------------------------------------------------------
46
+ describe('selectEntities', () => {
47
+ // Build a reusable entityMap for these tests
48
+ const entityMap: Record<string, any> = {
49
+ u1: createEntity('u1', { name: 'Alice', age: 30, tags: ['admin', 'editor'] }),
50
+ u2: createEntity('u2', { name: 'Bob', age: 25, tags: ['viewer'] }),
51
+ u3: createEntity('u3', { name: 'Charlie', age: 35, tags: ['admin'] }),
52
+ u4: createEntity('u4', { name: 'Deleted', age: 40, _deleted: true }),
53
+ u5: createEntity('u5', { name: 'Eve', age: 28, tags: ['editor', 'viewer'] }),
54
+ };
55
+
56
+ it('should return all non-deleted entities when no filters are provided', () => {
57
+ const result = selectEntities(entityMap, [], {});
58
+ expect(result).toHaveLength(4);
59
+ expect(result.map((e) => e.__id).sort()).toEqual(['u1', 'u2', 'u3', 'u5']);
60
+ });
61
+
62
+ it('should filter out deleted entities', () => {
63
+ const result = selectEntities(entityMap, [], {});
64
+ expect(result.find((e) => e.__id === 'u4')).toBeUndefined();
65
+ });
66
+
67
+ // --- Equality filters ---
68
+
69
+ it('should filter by equality (==) on a field', () => {
70
+ const result = selectEntities(entityMap, [['name', '==', 'Alice']], {});
71
+ expect(result).toHaveLength(1);
72
+ expect(result[0].__id).toBe('u1');
73
+ });
74
+
75
+ it('should filter by inequality (!=) on a field', () => {
76
+ const result = selectEntities(entityMap, [['name', '!=', 'Alice']], {});
77
+ expect(result).toHaveLength(3);
78
+ expect(result.find((e) => e.name === 'Alice')).toBeUndefined();
79
+ });
80
+
81
+ // --- Comparison filters ---
82
+
83
+ it('should filter by greater-than (>) comparison', () => {
84
+ const result = selectEntities(entityMap, [['age', '>', 28]], {});
85
+ expect(result).toHaveLength(2);
86
+ expect(result.map((e) => e.__id).sort()).toEqual(['u1', 'u3']);
87
+ });
88
+
89
+ it('should filter by greater-than-or-equal (>=) comparison', () => {
90
+ const result = selectEntities(entityMap, [['age', '>=', 28]], {});
91
+ expect(result).toHaveLength(3);
92
+ expect(result.map((e) => e.__id).sort()).toEqual(['u1', 'u3', 'u5']);
93
+ });
94
+
95
+ it('should filter by less-than (<) comparison', () => {
96
+ const result = selectEntities(entityMap, [['age', '<', 28]], {});
97
+ expect(result).toHaveLength(1);
98
+ expect(result[0].__id).toBe('u2');
99
+ });
100
+
101
+ it('should filter by less-than-or-equal (<=) comparison', () => {
102
+ const result = selectEntities(entityMap, [['age', '<=', 28]], {});
103
+ expect(result).toHaveLength(2);
104
+ expect(result.map((e) => e.__id).sort()).toEqual(['u2', 'u5']);
105
+ });
106
+
107
+ // --- Array filters ---
108
+
109
+ it('should filter by array-contains', () => {
110
+ const result = selectEntities(entityMap, [['tags', 'array-contains', 'admin']], {});
111
+ expect(result).toHaveLength(2);
112
+ expect(result.map((e) => e.__id).sort()).toEqual(['u1', 'u3']);
113
+ });
114
+
115
+ it('should filter by array-contains-any', () => {
116
+ const result = selectEntities(
117
+ entityMap,
118
+ [['tags', 'array-contains-any', ['admin', 'viewer']]],
119
+ {},
120
+ );
121
+ expect(result).toHaveLength(4);
122
+ });
123
+
124
+ // --- 'in' and 'not-in' filters ---
125
+
126
+ it('should filter by in operator', () => {
127
+ const result = selectEntities(entityMap, [['name', 'in', ['Alice', 'Bob']]], {});
128
+ expect(result).toHaveLength(2);
129
+ expect(result.map((e) => e.__id).sort()).toEqual(['u1', 'u2']);
130
+ });
131
+
132
+ it('should filter by not-in operator', () => {
133
+ const result = selectEntities(entityMap, [['name', 'not-in', ['Alice', 'Bob']]], {});
134
+ expect(result).toHaveLength(2);
135
+ expect(result.map((e) => e.__id).sort()).toEqual(['u3', 'u5']);
136
+ });
137
+
138
+ it('should pass all entities through for non-__id in query with empty values', () => {
139
+ // When 'in' is used on a non-__id field with an empty array, Firestore
140
+ // semantically returns nothing, but selectEntities treats empty 'in' arrays
141
+ // as a vacuously true filter (no values to exclude). The empty-in guard is
142
+ // handled at the processLoadQueries level, not in selectEntities.
143
+ const result = selectEntities(entityMap, [['name', 'in', []]], {});
144
+ expect(result).toHaveLength(4);
145
+ });
146
+
147
+ // --- __id-specific optimized path ---
148
+
149
+ it('should use optimized path for single __id == query', () => {
150
+ const result = selectEntities(entityMap, [['__id', '==', 'u1']], {});
151
+ expect(result).toHaveLength(1);
152
+ expect(result[0].name).toBe('Alice');
153
+ });
154
+
155
+ it('should fall through to full scan for __id == with non-existent id', () => {
156
+ // When __id == 'nonexistent' doesn't find a match in the entityMap,
157
+ // the optimized path condition fails (entity is undefined) and it falls
158
+ // through to the general filter. The general filter then returns all
159
+ // non-deleted entities because the __id == filter is skipped in the
160
+ // general processing section (it was already handled by the optimized path).
161
+ const result = selectEntities(entityMap, [['__id', '==', 'nonexistent']], {});
162
+ expect(result).toHaveLength(4);
163
+ });
164
+
165
+ it('should return empty for two contradictory __id == queries', () => {
166
+ const result = selectEntities(
167
+ entityMap,
168
+ [
169
+ ['__id', '==', 'u1'],
170
+ ['__id', '==', 'u2'],
171
+ ],
172
+ {},
173
+ );
174
+ expect(result).toHaveLength(0);
175
+ });
176
+
177
+ it('should use optimized path for __id in query', () => {
178
+ const result = selectEntities(entityMap, [['__id', 'in', ['u1', 'u3']]], {});
179
+ expect(result).toHaveLength(2);
180
+ expect(result.map((e) => e.__id).sort()).toEqual(['u1', 'u3']);
181
+ });
182
+
183
+ it('should filter out deleted entities in __id in query', () => {
184
+ const result = selectEntities(entityMap, [['__id', 'in', ['u1', 'u4']]], {});
185
+ // u4 is deleted, so only u1 should be returned
186
+ expect(result).toHaveLength(1);
187
+ expect(result[0].__id).toBe('u1');
188
+ });
189
+
190
+ // --- Multiple combined filters ---
191
+
192
+ it('should apply multiple filters conjunctively (AND)', () => {
193
+ const result = selectEntities(
194
+ entityMap,
195
+ [
196
+ ['age', '>=', 25],
197
+ ['tags', 'array-contains', 'admin'],
198
+ ],
199
+ {},
200
+ );
201
+ expect(result).toHaveLength(2);
202
+ expect(result.map((e) => e.__id).sort()).toEqual(['u1', 'u3']);
203
+ });
204
+
205
+ // --- Undefined value handling ---
206
+
207
+ it('should ignore query params with undefined values', () => {
208
+ const result = selectEntities(entityMap, [['name', '==', undefined]], {});
209
+ // Should return all non-deleted since undefined params are ignored
210
+ expect(result).toHaveLength(4);
211
+ });
212
+
213
+ // --- QueryOptions: orderBy ---
214
+
215
+ it('should sort results by orderBy ascending', () => {
216
+ const result = selectEntities(entityMap, [], { orderBy: [['age', 'asc']] });
217
+ expect(result.map((e) => e.__id)).toEqual(['u2', 'u5', 'u1', 'u3']);
218
+ });
219
+
220
+ it('should sort results by orderBy descending', () => {
221
+ const result = selectEntities(entityMap, [], { orderBy: [['age', 'desc']] });
222
+ expect(result.map((e) => e.__id)).toEqual(['u3', 'u1', 'u5', 'u2']);
223
+ });
224
+
225
+ it('should filter out entities missing the orderBy field', () => {
226
+ // Create an entityMap where one entity is missing the 'age' field
227
+ const mapWithMissing = {
228
+ ...entityMap,
229
+ u6: createEntity('u6', { name: 'NoAge' }), // no 'age' field
230
+ };
231
+ const result = selectEntities(mapWithMissing, [], { orderBy: [['age', 'asc']] });
232
+ // u6 should be excluded because it lacks the 'age' field
233
+ expect(result.find((e) => e['__id'] === 'u6')).toBeUndefined();
234
+ });
235
+
236
+ // --- QueryOptions: limit ---
237
+
238
+ it('should respect the limit option', () => {
239
+ const result = selectEntities(entityMap, [], {
240
+ orderBy: [['age', 'asc']],
241
+ limit: 2,
242
+ });
243
+ expect(result).toHaveLength(2);
244
+ expect(result[0].__id).toBe('u2'); // youngest
245
+ expect(result[1].__id).toBe('u5');
246
+ });
247
+
248
+ // --- QueryOptions: pagination cursors ---
249
+
250
+ it('should apply startAt cursor', () => {
251
+ const result = selectEntities(entityMap, [], {
252
+ orderBy: [['age', 'asc']],
253
+ startAt: '30',
254
+ });
255
+ expect(result.map((e) => e.__id)).toEqual(['u1', 'u3']);
256
+ });
257
+
258
+ it('should apply startAfter cursor', () => {
259
+ const result = selectEntities(entityMap, [], {
260
+ orderBy: [['age', 'asc']],
261
+ startAfter: '28',
262
+ });
263
+ // Should exclude age 28 (u5), include 30 (u1) and 35 (u3)
264
+ expect(result.map((e) => e.__id)).toEqual(['u1', 'u3']);
265
+ });
266
+ });
267
+
268
+ // ---------------------------------------------------------------------------
269
+ // 2. entityInQueryResults() — single entity filter check
270
+ // ---------------------------------------------------------------------------
271
+ describe('entityInQueryResults', () => {
272
+ const entity = createEntity('e1', {
273
+ name: 'TestUser',
274
+ status: 'active',
275
+ score: 85,
276
+ tags: ['a', 'b'],
277
+ });
278
+
279
+ it('should return true when entity satisfies all equality query params', () => {
280
+ expect(
281
+ entityInQueryResults(entity, [['name', '==', 'TestUser']], {}),
282
+ ).toBe(true);
283
+ });
284
+
285
+ it('should return false when entity fails an equality check', () => {
286
+ expect(
287
+ entityInQueryResults(entity, [['name', '==', 'OtherUser']], {}),
288
+ ).toBe(false);
289
+ });
290
+
291
+ it('should handle in queries correctly', () => {
292
+ expect(
293
+ entityInQueryResults(entity, [['status', 'in', ['active', 'paused']]], {}),
294
+ ).toBe(true);
295
+ expect(
296
+ entityInQueryResults(entity, [['status', 'in', ['paused', 'archived']]], {}),
297
+ ).toBe(false);
298
+ });
299
+
300
+ it('should handle not-in queries correctly', () => {
301
+ expect(
302
+ entityInQueryResults(entity, [['status', 'not-in', ['paused', 'archived']]], {}),
303
+ ).toBe(true);
304
+ expect(
305
+ entityInQueryResults(entity, [['status', 'not-in', ['active', 'archived']]], {}),
306
+ ).toBe(false);
307
+ });
308
+
309
+ it('should handle array-contains correctly', () => {
310
+ expect(
311
+ entityInQueryResults(entity, [['tags', 'array-contains', 'a']], {}),
312
+ ).toBe(true);
313
+ expect(
314
+ entityInQueryResults(entity, [['tags', 'array-contains', 'z']], {}),
315
+ ).toBe(false);
316
+ });
317
+
318
+ it('should handle comparison operators', () => {
319
+ expect(entityInQueryResults(entity, [['score', '>', 80]], {})).toBe(true);
320
+ expect(entityInQueryResults(entity, [['score', '>', 90]], {})).toBe(false);
321
+ expect(entityInQueryResults(entity, [['score', '>=', 85]], {})).toBe(true);
322
+ expect(entityInQueryResults(entity, [['score', '<', 90]], {})).toBe(true);
323
+ expect(entityInQueryResults(entity, [['score', '<=', 85]], {})).toBe(true);
324
+ });
325
+
326
+ it('should ignore undefined query param values', () => {
327
+ expect(
328
+ entityInQueryResults(entity, [['name', '==', undefined]], {}),
329
+ ).toBe(true);
330
+ });
331
+
332
+ it('should handle queryOptions cursor checks', () => {
333
+ expect(
334
+ entityInQueryResults(entity, [], { orderBy: 'score', startAt: '80' }),
335
+ ).toBe(true);
336
+ expect(
337
+ entityInQueryResults(entity, [], { orderBy: 'score', startAt: '90' }),
338
+ ).toBe(false);
339
+ });
340
+ });
341
+
342
+ // ---------------------------------------------------------------------------
343
+ // 3. EntityLoadQuery — static methods
344
+ // ---------------------------------------------------------------------------
345
+ describe('EntityLoadQuery', () => {
346
+ /**
347
+ * Helper to create a minimal EntityLoadQuery with the required fields.
348
+ * The `store` parameter is a mock that won't actually be called by static methods.
349
+ */
350
+ function createLoadQuery(
351
+ field: string,
352
+ operator: string,
353
+ value: any,
354
+ collection = 'users',
355
+ ): EntityLoadQuery<any> {
356
+ return new EntityLoadQuery(
357
+ collection,
358
+ {} as any, // mock store — static methods don't use it
359
+ [[field, operator, value]],
360
+ {},
361
+ );
362
+ }
363
+
364
+ describe('areBatchableEqualityQueries', () => {
365
+ it('should return true for a set of single-param equality queries on the same field', () => {
366
+ const queries = [
367
+ createLoadQuery('__userId', '==', 'a'),
368
+ createLoadQuery('__userId', '==', 'b'),
369
+ createLoadQuery('__userId', '==', 'c'),
370
+ ];
371
+ expect(EntityLoadQuery.areBatchableEqualityQueries(queries)).toBe(true);
372
+ });
373
+
374
+ it('should return false for empty queries', () => {
375
+ expect(EntityLoadQuery.areBatchableEqualityQueries([])).toBe(false);
376
+ });
377
+
378
+ it('should return false if queries use different operators', () => {
379
+ const queries = [
380
+ createLoadQuery('__userId', '==', 'a'),
381
+ createLoadQuery('__userId', '>', 'b'),
382
+ ];
383
+ expect(EntityLoadQuery.areBatchableEqualityQueries(queries)).toBe(false);
384
+ });
385
+
386
+ it('should return false if queries target different fields', () => {
387
+ const queries = [
388
+ createLoadQuery('__userId', '==', 'a'),
389
+ createLoadQuery('__communityId', '==', 'b'),
390
+ ];
391
+ expect(EntityLoadQuery.areBatchableEqualityQueries(queries)).toBe(false);
392
+ });
393
+
394
+ it('should return false if any query has multiple queryParams', () => {
395
+ const multiParamQuery = new EntityLoadQuery(
396
+ 'users',
397
+ {} as any,
398
+ [
399
+ ['__userId', '==', 'a'],
400
+ ['status', '==', 'active'],
401
+ ],
402
+ {},
403
+ );
404
+ const queries = [createLoadQuery('__userId', '==', 'b'), multiParamQuery];
405
+ expect(EntityLoadQuery.areBatchableEqualityQueries(queries)).toBe(false);
406
+ });
407
+ });
408
+
409
+ describe('optimize', () => {
410
+ it('should return non-equality queries unchanged', () => {
411
+ const queries = [
412
+ createLoadQuery('age', '>', 25),
413
+ createLoadQuery('age', '>', 30),
414
+ ];
415
+ const result = EntityLoadQuery.optimize(queries);
416
+ expect(result).toHaveLength(2);
417
+ });
418
+
419
+ /**
420
+ * [OPTIMIZATION] This test verifies the core batching behavior.
421
+ * It is expected to fail while optimize() is disabled (returns queries early).
422
+ * Once the early `return queries;` is removed, this should pass.
423
+ */
424
+ it('[OPTIMIZATION] should batch equality queries into a single in query', () => {
425
+ const queries = [
426
+ createLoadQuery('__userId', '==', 'a'),
427
+ createLoadQuery('__userId', '==', 'b'),
428
+ createLoadQuery('__userId', '==', 'c'),
429
+ ];
430
+ const result = EntityLoadQuery.optimize(queries);
431
+
432
+ // When optimization is enabled:
433
+ // 3 equality queries -> 1 'in' query with values ['a', 'b', 'c']
434
+ expect(result).toHaveLength(1);
435
+ expect(result[0].queryParams[0][0]).toBe('__userId');
436
+ expect(result[0].queryParams[0][1]).toBe('in');
437
+ expect(result[0].queryParams[0][2]).toEqual(['a', 'b', 'c']);
438
+ });
439
+
440
+ it('should not batch equality queries if they contain queryOptions', () => {
441
+ const queries = [
442
+ new EntityLoadQuery('users', {} as any, [['__userId', '==', 'a']], { limit: 1 }),
443
+ new EntityLoadQuery('users', {} as any, [['__userId', '==', 'b']], { limit: 1 }),
444
+ ];
445
+ const result = EntityLoadQuery.optimize(queries);
446
+
447
+ // Should return the original queries untouched because queryOptions are present
448
+ expect(result).toHaveLength(2);
449
+ expect(result[0].queryOptions).toEqual({ limit: 1 });
450
+ expect(result[1].queryOptions).toEqual({ limit: 1 });
451
+ });
452
+
453
+ /**
454
+ * [OPTIMIZATION] Verifies that EntityLoadQuery.optimize bundles ALL IDs into a single query.
455
+ * The actual 30-item chunking for Firestore limits is now handled internally by `load()`.
456
+ */
457
+ it('[OPTIMIZATION] should bundle equality queries into a single in query without chunking', () => {
458
+ // Create 65 equality queries
459
+ const queries = Array.from({ length: 65 }, (_, i) =>
460
+ createLoadQuery('__userId', '==', `user_${i}`),
461
+ );
462
+ const result = EntityLoadQuery.optimize(queries);
463
+
464
+ // Should return exactly 1 query containing all 65 IDs
465
+ expect(result).toHaveLength(1);
466
+ expect(result[0].queryParams[0][2]).toHaveLength(65);
467
+ });
468
+
469
+ /**
470
+ * [OPTIMIZATION] A single equality query should still be batched into
471
+ * an 'in' query with a single value (for consistency).
472
+ */
473
+ it('[OPTIMIZATION] should batch a single equality query into an in query', () => {
474
+ const queries = [createLoadQuery('__userId', '==', 'only_one')];
475
+ const result = EntityLoadQuery.optimize(queries);
476
+
477
+ expect(result).toHaveLength(1);
478
+ expect(result[0].queryParams[0][1]).toBe('in');
479
+ expect(result[0].queryParams[0][2]).toEqual(['only_one']);
480
+ });
481
+
482
+ /**
483
+ * [OPTIMIZATION] Verify that the optimized query preserves the collection
484
+ * name and store reference from the original queries.
485
+ */
486
+ it('[OPTIMIZATION] should preserve collection and store from original queries', () => {
487
+ const mockStore = { id: 'mock-user-store' };
488
+ const query = new EntityLoadQuery(
489
+ 'userContexts',
490
+ mockStore as any,
491
+ [['__userId', '==', 'a']],
492
+ {},
493
+ );
494
+ const result = EntityLoadQuery.optimize([query]);
495
+
496
+ expect(result[0].collection).toBe('userContexts');
497
+ expect(result[0].store).toBe(mockStore);
498
+ });
499
+ });
500
+ });
501
+
502
+ // ---------------------------------------------------------------------------
503
+ // 4. EntityStreamQuery — static methods (mirrors EntityLoadQuery)
504
+ // ---------------------------------------------------------------------------
505
+ describe('EntityStreamQuery', () => {
506
+ function createStreamQuery(
507
+ field: string,
508
+ operator: string,
509
+ value: any,
510
+ collection = 'users',
511
+ ): EntityStreamQuery<any> {
512
+ return new EntityStreamQuery(
513
+ collection,
514
+ {} as any,
515
+ [[field, operator, value]],
516
+ {},
517
+ );
518
+ }
519
+
520
+ describe('areBatchableEqualityQueries', () => {
521
+ it('should return true for equality queries on the same field', () => {
522
+ const queries = [
523
+ createStreamQuery('__userId', '==', 'x'),
524
+ createStreamQuery('__userId', '==', 'y'),
525
+ ];
526
+ expect(EntityStreamQuery.areBatchableEqualityQueries(queries)).toBe(true);
527
+ });
528
+
529
+ it('should return false for empty queries', () => {
530
+ expect(EntityStreamQuery.areBatchableEqualityQueries([])).toBe(false);
531
+ });
532
+
533
+ it('should return false for mixed operators', () => {
534
+ const queries = [
535
+ createStreamQuery('__userId', '==', 'x'),
536
+ createStreamQuery('__userId', '!=', 'y'),
537
+ ];
538
+ expect(EntityStreamQuery.areBatchableEqualityQueries(queries)).toBe(false);
539
+ });
540
+
541
+ it('should return false for different fields', () => {
542
+ const queries = [
543
+ createStreamQuery('__userId', '==', 'x'),
544
+ createStreamQuery('__communityId', '==', 'y'),
545
+ ];
546
+ expect(EntityStreamQuery.areBatchableEqualityQueries(queries)).toBe(false);
547
+ });
548
+ });
549
+
550
+ describe('optimize', () => {
551
+ it('should return non-equality queries unchanged', () => {
552
+ const queries = [
553
+ createStreamQuery('score', '>=', 50),
554
+ createStreamQuery('score', '>=', 75),
555
+ ];
556
+ const result = EntityStreamQuery.optimize(queries);
557
+ expect(result).toHaveLength(2);
558
+ });
559
+
560
+ /**
561
+ * [OPTIMIZATION] Core stream batching test.
562
+ * Mirrors the EntityLoadQuery test — expected to fail while disabled.
563
+ */
564
+ it('[OPTIMIZATION] should batch equality queries into a single in query', () => {
565
+ const queries = [
566
+ createStreamQuery('__userId', '==', 'a'),
567
+ createStreamQuery('__userId', '==', 'b'),
568
+ createStreamQuery('__userId', '==', 'c'),
569
+ ];
570
+ const result = EntityStreamQuery.optimize(queries);
571
+
572
+ expect(result).toHaveLength(1);
573
+ expect(result[0].queryParams[0][0]).toBe('__userId');
574
+ expect(result[0].queryParams[0][1]).toBe('in');
575
+ expect(result[0].queryParams[0][2]).toEqual(['a', 'b', 'c']);
576
+ });
577
+
578
+ it('should not batch stream equality queries if they contain queryOptions', () => {
579
+ const queries = [
580
+ new EntityStreamQuery('users', {} as any, [['__userId', '==', 'a']], { limit: 5 }),
581
+ new EntityStreamQuery('users', {} as any, [['__userId', '==', 'b']], { limit: 5 }),
582
+ ];
583
+ const result = EntityStreamQuery.optimize(queries);
584
+
585
+ expect(result).toHaveLength(2);
586
+ expect(result[0].queryOptions).toEqual({ limit: 5 });
587
+ expect(result[1].queryOptions).toEqual({ limit: 5 });
588
+ });
589
+
590
+ /**
591
+ * [OPTIMIZATION] Stream equality queries should collapse completely to allow multiplexer chunking.
592
+ */
593
+ it('[OPTIMIZATION] should collapse all stream equality queries into a single in query', () => {
594
+ const queries = Array.from({ length: 45 }, (_, i) =>
595
+ createStreamQuery('__communityId', '==', `comm_${i}`),
596
+ );
597
+ const result = EntityStreamQuery.optimize(queries);
598
+
599
+ expect(result).toHaveLength(1);
600
+ expect(result[0].queryParams[0][2]).toHaveLength(45);
601
+ });
602
+
603
+ /**
604
+ * [OPTIMIZATION] Verify that the optimized stream query preserves metadata.
605
+ */
606
+ it('[OPTIMIZATION] should preserve collection and store from original stream queries', () => {
607
+ const mockStore = { id: 'mock-context-store' };
608
+ const query = new EntityStreamQuery(
609
+ 'userContexts',
610
+ mockStore as any,
611
+ [['__userId', '==', 'a']],
612
+ {},
613
+ );
614
+ const result = EntityStreamQuery.optimize([query]);
615
+
616
+ expect(result[0].collection).toBe('userContexts');
617
+ expect(result[0].store).toBe(mockStore);
618
+ });
619
+ });
620
+ });
621
+
622
+ // ---------------------------------------------------------------------------
623
+ // 5. processLoadQueries() — integration with mock stores
624
+ // ---------------------------------------------------------------------------
625
+ describe('processLoadQueries', () => {
626
+ it('should do nothing when entities array is empty', async () => {
627
+ const loadQueriesFn = jest.fn();
628
+ await processLoadQueries([], loadQueriesFn);
629
+ // loadQueries function should never be called for an empty entity list
630
+ expect(loadQueriesFn).not.toHaveBeenCalled();
631
+ });
632
+
633
+ it('should batch equality queries and invoke store.load once per batch', async () => {
634
+ // Track how many times load() is called on the mock store
635
+ const loadSpy = jest.fn().mockResolvedValue(undefined);
636
+ const mockStore = { load: loadSpy };
637
+
638
+ // Create parent entities that will generate nested load queries
639
+ const parentEntities = [
640
+ createEntity('p1'),
641
+ createEntity('p2'),
642
+ ];
643
+
644
+ // Each parent entity generates one nested load query targeting the child collection
645
+ const loadQueriesFn = (entity: any) => [
646
+ new EntityLoadQuery(
647
+ 'userContexts',
648
+ mockStore as any,
649
+ [['__userId', '==', entity.__id]],
650
+ {},
651
+ ),
652
+ ];
653
+
654
+ await processLoadQueries(parentEntities, loadQueriesFn);
655
+
656
+ // Because optimize() batches the two equality queries into one 'in' query,
657
+ // load should be called once with a batched query.
658
+ expect(loadSpy).toHaveBeenCalledTimes(1);
659
+
660
+ // Verify the batched query params
661
+ expect(loadSpy).toHaveBeenCalledWith(
662
+ [['__userId', 'in', ['p1', 'p2']]],
663
+ {},
664
+ undefined,
665
+ );
666
+ });
667
+
668
+ it('should skip queries with empty in arrays (safety check)', async () => {
669
+ const loadSpy = jest.fn().mockResolvedValue(undefined);
670
+ const mockStore = { load: loadSpy };
671
+
672
+ const parentEntities = [createEntity('p1')];
673
+
674
+ // Simulate an optimized query that ended up with an empty 'in' array
675
+ // (edge case that processLoadQueries explicitly guards against)
676
+ const loadQueriesFn = () => [
677
+ new EntityLoadQuery(
678
+ 'userContexts',
679
+ mockStore as any,
680
+ [['__userId', 'in', []]],
681
+ {},
682
+ ),
683
+ ];
684
+
685
+ await processLoadQueries(parentEntities, loadQueriesFn);
686
+
687
+ // The empty 'in' query should be skipped entirely
688
+ expect(loadSpy).not.toHaveBeenCalled();
689
+ });
690
+
691
+ it('should transpose and batch queries by query type across multiple stores', async () => {
692
+ const contextLoadSpy = jest.fn().mockResolvedValue(undefined);
693
+ const sessionLoadSpy = jest.fn().mockResolvedValue(undefined);
694
+
695
+ const contextStore = { load: contextLoadSpy };
696
+ const sessionStore = { load: sessionLoadSpy };
697
+
698
+ const parentEntities = [
699
+ createEntity('p1'),
700
+ createEntity('p2'),
701
+ ];
702
+
703
+ // Each parent generates TWO nested query types (contexts + sessions)
704
+ const loadQueriesFn = (entity: any) => [
705
+ new EntityLoadQuery(
706
+ 'userContexts',
707
+ contextStore as any,
708
+ [['__userId', '==', entity.__id]],
709
+ {},
710
+ ),
711
+ new EntityLoadQuery(
712
+ 'sessions',
713
+ sessionStore as any,
714
+ [['__ownerId', '==', entity.__id]],
715
+ {},
716
+ ),
717
+ ];
718
+
719
+ await processLoadQueries(parentEntities, loadQueriesFn);
720
+
721
+ // With optimization enabled: 2 parents × 2 query types = 2 batched loads
722
+ // (1 batched context load + 1 batched session load)
723
+ expect(contextLoadSpy).toHaveBeenCalledTimes(1);
724
+ expect(sessionLoadSpy).toHaveBeenCalledTimes(1);
725
+
726
+ // Verify the batched query params for each type
727
+ expect(contextLoadSpy).toHaveBeenCalledWith(
728
+ [['__userId', 'in', ['p1', 'p2']]],
729
+ {},
730
+ undefined,
731
+ );
732
+ expect(sessionLoadSpy).toHaveBeenCalledWith(
733
+ [['__ownerId', 'in', ['p1', 'p2']]],
734
+ {},
735
+ undefined,
736
+ );
737
+ });
738
+
739
+ /**
740
+ * [OPTIMIZATION] When optimize() is re-enabled, N equality queries of
741
+ * the same type should be batched into ceil(N/30) 'in' queries.
742
+ * With 2 parents, we should get 1 batched 'in' query per type, not 2 individual ones.
743
+ */
744
+ it('[OPTIMIZATION] should batch nested equality queries when optimize is enabled', async () => {
745
+ const loadSpy = jest.fn().mockResolvedValue(undefined);
746
+ const mockStore = { load: loadSpy };
747
+
748
+ // Create 5 parent entities to generate 5 nested equality queries
749
+ const parentEntities = Array.from({ length: 5 }, (_, i) =>
750
+ createEntity(`p${i}`),
751
+ );
752
+
753
+ const loadQueriesFn = (entity: any) => [
754
+ new EntityLoadQuery(
755
+ 'userContexts',
756
+ mockStore as any,
757
+ [['__userId', '==', entity.__id]],
758
+ {},
759
+ ),
760
+ ];
761
+
762
+ await processLoadQueries(parentEntities, loadQueriesFn);
763
+
764
+ // When optimization is enabled: 5 equality queries -> 1 batched 'in' query
765
+ // When optimization is disabled: 5 individual queries -> 5 load() calls
766
+ // This test documents the expected optimized behavior.
767
+ expect(loadSpy).toHaveBeenCalledTimes(1);
768
+ expect(loadSpy).toHaveBeenCalledWith(
769
+ [['__userId', 'in', ['p0', 'p1', 'p2', 'p3', 'p4']]],
770
+ {},
771
+ undefined,
772
+ );
773
+ });
774
+
775
+ it('should not batch queries if they contain queryOptions (like limits), preserving the options', async () => {
776
+ const loadSpy = jest.fn().mockResolvedValue(undefined);
777
+ const mockStore = { load: loadSpy };
778
+
779
+ // Create 2 parent entities
780
+ const parentEntities = [
781
+ createEntity('p1'),
782
+ createEntity('p2'),
783
+ ];
784
+
785
+ // Each parent generates a nested equality query, but WITH a queryOption (limit: 5)
786
+ const loadQueriesFn = (entity: any) => [
787
+ new EntityLoadQuery(
788
+ 'userContexts',
789
+ mockStore as any,
790
+ [['__userId', '==', entity.__id]],
791
+ { limit: 5 },
792
+ ),
793
+ ];
794
+
795
+ await processLoadQueries(parentEntities, loadQueriesFn);
796
+
797
+ // If queryOptions are preserved correctly, these queries cannot be batched
798
+ // because a batched 'in' query with a limit would apply the limit to the ENTIRE batch,
799
+ // not per-parent. So it should fall back to individual queries, preserving the limit.
800
+ expect(loadSpy).toHaveBeenCalledTimes(2);
801
+
802
+ // Verify each call preserved the limit
803
+ expect(loadSpy).toHaveBeenCalledWith(
804
+ [['__userId', '==', 'p1']],
805
+ { limit: 5 },
806
+ undefined,
807
+ );
808
+ expect(loadSpy).toHaveBeenCalledWith(
809
+ [['__userId', '==', 'p2']],
810
+ { limit: 5 },
811
+ undefined,
812
+ );
813
+ });
814
+ });
815
+
816
+ // ---------------------------------------------------------------------------
817
+ // 6. load() batching integration tests (Scenarios A, B, C)
818
+ // ---------------------------------------------------------------------------
819
+ import { TestBed } from '@angular/core/testing';
820
+ import { signalStore } from '@ngrx/signals';
821
+ import { withEntitiesAndDBMethods } from './app.store';
822
+ import { CachedListenersService } from '../firebase/cached-listeners.service';
823
+ import { DATABASE_SERVICE } from '../firebase/database.service';
824
+
825
+ describe('load() batching integration tests (Scenarios A, B, C)', () => {
826
+ let store: any;
827
+ let mockDb: any;
828
+ let cachedListeners: CachedListenersService;
829
+
830
+ beforeEach(() => {
831
+ mockDb = {
832
+ getEntities: jest.fn().mockResolvedValue([]),
833
+ getEntity: jest.fn().mockResolvedValue(null),
834
+ };
835
+
836
+ TestBed.configureTestingModule({
837
+ providers: [
838
+ CachedListenersService,
839
+ { provide: DATABASE_SERVICE, useValue: mockDb },
840
+ ],
841
+ });
842
+
843
+ cachedListeners = TestBed.inject(CachedListenersService);
844
+
845
+ const UserStore = signalStore(
846
+ withEntitiesAndDBMethods('users'),
847
+ );
848
+ store = TestBed.runInInjectionContext(() => new UserStore());
849
+ });
850
+
851
+ afterEach(() => {
852
+ cachedListeners.clearCache();
853
+ jest.clearAllMocks();
854
+ });
855
+
856
+ it('Scenario A: Normal load should query DB and set unified timestamp', async () => {
857
+ const ids = ['u1', 'u2'];
858
+ mockDb.getEntities.mockResolvedValue([createEntity('u1'), createEntity('u2')]);
859
+
860
+ await store.load([['__id', 'in', ids]], {});
861
+
862
+ expect(mockDb.getEntities).toHaveBeenCalledTimes(2); // 1 for active, 1 for deleted
863
+ expect(mockDb.getEntities).toHaveBeenNthCalledWith(1, 'users', [['__id', 'in', ids], ['_deleted', '==', false]], {});
864
+ expect(mockDb.getEntities).toHaveBeenNthCalledWith(2, 'users', [['__id', 'in', ids], ['_deleted', '==', true]], {});
865
+
866
+ const t1 = cachedListeners.getEntityLoadTime('users', '__id', 'u1');
867
+ const t2 = cachedListeners.getEntityLoadTime('users', '__id', 'u2');
868
+ expect(t1).toBeGreaterThan(0);
869
+ expect(t1).toEqual(t2); // Unified timestamp
870
+ });
871
+
872
+ it('Scenario B: Overlapping batches should split fetch but unify timestamp', async () => {
873
+ // 1. Initial load of u1..u5
874
+ const initialIds = ['u1', 'u2', 'u3', 'u4', 'u5'];
875
+ await store.load([['__id', 'in', initialIds]], {});
876
+ mockDb.getEntities.mockClear();
877
+
878
+ const initialTime = cachedListeners.getEntityLoadTime('users', '__id', 'u1');
879
+
880
+ // 2. Wait a bit to ensure timestamp differs
881
+ await new Promise((resolve) => setTimeout(resolve, 10));
882
+
883
+ // 3. Subsequent load of u1..u6
884
+ const overlappingIds = ['u1', 'u2', 'u3', 'u4', 'u5', 'u6'];
885
+ await store.load([['__id', 'in', overlappingIds]], {});
886
+
887
+ // It should group u1..u5 (having initialTime) and u6 (having -1)
888
+ // For u1..u5, we expect a fetch with _updatedAt > initialTime
889
+ // For u6, we expect a fetch with no _updatedAt filter
890
+ expect(mockDb.getEntities).toHaveBeenCalledTimes(4); // 2 active fetches, 2 deleted fetches
891
+
892
+ const u6Time = cachedListeners.getEntityLoadTime('users', '__id', 'u6');
893
+ const u1Time = cachedListeners.getEntityLoadTime('users', '__id', 'u1');
894
+
895
+ // Unified timestamp applied to ALL elements
896
+ expect(u1Time).toBeGreaterThan(initialTime);
897
+ expect(u1Time).toEqual(u6Time);
898
+ });
899
+
900
+ it('Scenario C: Active stream deduplication should filter out streamed IDs', async () => {
901
+ // Simulate an active stream for 'u1'
902
+ jest.spyOn(cachedListeners, 'isIdStreamed').mockImplementation((col, field, id) => {
903
+ if (field === '__id' && id === 'u1') return true;
904
+ return false;
905
+ });
906
+
907
+ const ids = ['u1', 'u2'];
908
+ mockDb.getEntity.mockResolvedValue(createEntity('u2'));
909
+ await store.load([['__id', 'in', ids]], {});
910
+
911
+ // Only 'u2' should be fetched, using the optimized getEntity path since there's only 1 ID left
912
+ expect(mockDb.getEntities).not.toHaveBeenCalled();
913
+ expect(mockDb.getEntity).toHaveBeenCalledTimes(1);
914
+ expect(mockDb.getEntity).toHaveBeenCalledWith('users', 'u2');
915
+
916
+ // u1 should NOT have a load time since it was skipped
917
+ expect(cachedListeners.getEntityLoadTime('users', '__id', 'u1')).toBe(-1);
918
+ expect(cachedListeners.getEntityLoadTime('users', '__id', 'u2')).toBeGreaterThan(0);
919
+ });
920
+ });