musora-content-services 2.167.2 → 2.167.4

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 (140) hide show
  1. package/.agent/decisions/2026-07-20-mu2-1724-songs-lessons-counts.md +33 -0
  2. package/.agent/decisions/2026-07-20-query-builder-tostring.md +37 -0
  3. package/.idea/codeStyles/Project.xml +61 -0
  4. package/.idea/codeStyles/codeStyleConfig.xml +5 -0
  5. package/.idea/modules.xml +8 -0
  6. package/.idea/musora-content-services.iml +8 -0
  7. package/.idea/php.xml +19 -0
  8. package/.idea/prettier.xml +6 -0
  9. package/.idea/vcs.xml +7 -0
  10. package/.yarn/install-state.gz +0 -0
  11. package/CHANGELOG.md +10 -0
  12. package/package.json +2 -1
  13. package/src/contentTypeConfig.js +1 -0
  14. package/src/lib/sanity/query.ts +5 -0
  15. package/src/services/config.js +15 -0
  16. package/src/services/content/artist.ts +1 -3
  17. package/src/services/content/counts.ts +47 -0
  18. package/src/services/content/genre.ts +1 -3
  19. package/src/services/content/instructor.ts +1 -3
  20. package/src/services/multi-user-accounts/multi-user-accounts.ts +1 -0
  21. package/src/services/userActivity.js +2 -0
  22. package/src/version-info.js +1 -0
  23. package/.claude/settings.local.json +0 -53
  24. package/test/initializeTests.js +0 -60
  25. package/test/integration/awards/award-exclusion-handling.test.ts +0 -275
  26. package/test/integration/awards/internal/image-utils.test.ts +0 -86
  27. package/test/integration/content-progress/__mocks__/mocks.ts +0 -104
  28. package/test/integration/content-progress/contentProgress.test.ts +0 -335
  29. package/test/integration/content-progress/e2eOfflineProgress.test.ts +0 -352
  30. package/test/integration/content-progress/e2eProgress.test.ts +0 -612
  31. package/test/integration/content-progress/getters.test.ts +0 -334
  32. package/test/integration/content-progress/helpers.test.ts +0 -263
  33. package/test/integration/content-progress/offlineContentProgress.test.ts +0 -226
  34. package/test/integration/forums.test.ts +0 -209
  35. package/test/integration/infrastructure/FetchRequestExecutor.test.ts +0 -88
  36. package/test/integration/initializeTestDB.ts +0 -80
  37. package/test/integration/learning-paths.test.ts +0 -854
  38. package/test/integration/notifications.test.ts +0 -178
  39. package/test/integration/progress-row/content-card.test.ts +0 -283
  40. package/test/integration/sync/adapters/idb-errors.test.ts +0 -144
  41. package/test/integration/sync/adapters/sqlite-errors.test.ts +0 -173
  42. package/test/integration/sync/fetch.test.ts +0 -224
  43. package/test/integration/sync/repositories/content-likes.test.ts +0 -99
  44. package/test/integration/sync/repositories/practices.test.ts +0 -179
  45. package/test/integration/sync/repositories/progress.test.ts +0 -245
  46. package/test/integration/sync/repositories/user-award-progress.static.test.ts +0 -68
  47. package/test/integration/sync/repositories/user-award-progress.test.ts +0 -387
  48. package/test/integration/sync/store/cross-user-protection.test.ts +0 -217
  49. package/test/integration/sync/store/store-idb.test.ts +0 -180
  50. package/test/integration/sync/store/store.test.ts +0 -361
  51. package/test/integration/user/permissions.test.js +0 -20
  52. package/test/integration/userActivity.test.ts +0 -102
  53. package/test/live/README.md +0 -29
  54. package/test/live/content.test.js +0 -116
  55. package/test/localStorageMock.js +0 -21
  56. package/test/log.js +0 -5
  57. package/test/mockData/award-definitions.js +0 -171
  58. package/test/mockData/mockData_fetchByRailContentIds_one_content.json +0 -35
  59. package/test/mockData/mockData_progress_content.json +0 -182
  60. package/test/mockData/mockData_sanity_progress_content.json +0 -1451
  61. package/test/mockData/mockData_user_practices.json +0 -9
  62. package/test/setupConsole.js +0 -6
  63. package/test/setupNetworkGuard.js +0 -3
  64. package/test/setupTimers.js +0 -13
  65. package/test/unit/HttpClient.test.ts +0 -267
  66. package/test/unit/awards/award-alacarte-observer.test.ts +0 -199
  67. package/test/unit/awards/award-auto-refresh.test.ts +0 -84
  68. package/test/unit/awards/award-calculations.test.ts +0 -34
  69. package/test/unit/awards/award-callbacks.test.ts +0 -144
  70. package/test/unit/awards/award-certificate-display.test.ts +0 -330
  71. package/test/unit/awards/award-collection-edge-cases.test.ts +0 -212
  72. package/test/unit/awards/award-collection-filtering.test.ts +0 -287
  73. package/test/unit/awards/award-completion-flow.test.ts +0 -306
  74. package/test/unit/awards/award-multi-lesson.test.ts +0 -243
  75. package/test/unit/awards/award-observer-integration.test.ts +0 -327
  76. package/test/unit/awards/award-query-messages.test.ts +0 -448
  77. package/test/unit/awards/award-user-collection.test.ts +0 -416
  78. package/test/unit/awards/duplicate-prevention.test.ts +0 -120
  79. package/test/unit/awards/helpers/completion-mock.ts +0 -56
  80. package/test/unit/awards/helpers/index.ts +0 -3
  81. package/test/unit/awards/helpers/mock-setup.ts +0 -79
  82. package/test/unit/awards/helpers/progress-emitter.ts +0 -45
  83. package/test/unit/awards/message-generator.test.ts +0 -162
  84. package/test/unit/content-progress/bubbleTrickle.test.ts +0 -322
  85. package/test/unit/content-progress/helpers.test.ts +0 -329
  86. package/test/unit/content-progress/navigateTo.test.ts +0 -392
  87. package/test/unit/contentLikes.test.ts +0 -62
  88. package/test/unit/contentMetaData.test.ts +0 -58
  89. package/test/unit/dataContext.test.ts +0 -38
  90. package/test/unit/dateUtils.test.ts +0 -188
  91. package/test/unit/endScreen.test.js +0 -712
  92. package/test/unit/eventsAPI.test.ts +0 -159
  93. package/test/unit/imageSRCBuilder.test.ts +0 -37
  94. package/test/unit/imageSRCVerify.test.ts +0 -155
  95. package/test/unit/infrastructure/DefaultHeaderProvider.test.ts +0 -39
  96. package/test/unit/infrastructure/sanity/ContentClient.test.ts +0 -168
  97. package/test/unit/infrastructure/sanity/DefaultConfigProvider.test.ts +0 -93
  98. package/test/unit/infrastructure/sanity/FetchQueryExecutor.test.ts +0 -174
  99. package/test/unit/infrastructure/sanity/SanityClient.test.ts +0 -140
  100. package/test/unit/lib/__snapshots__/filter.test.ts.snap +0 -5
  101. package/test/unit/lib/filter.test.ts +0 -1154
  102. package/test/unit/lib/lastUpdated.test.ts +0 -21
  103. package/test/unit/lib/query.test.ts +0 -1469
  104. package/test/unit/lib/sanity/decorators/base.test.ts +0 -368
  105. package/test/unit/lib/sanity/decorators/navigate-to.test.ts +0 -361
  106. package/test/unit/lib/sanity/decorators/need-access.test.ts +0 -89
  107. package/test/unit/lib/sanity/decorators/need-lifetime-upgrade.test.ts +0 -85
  108. package/test/unit/lib/sanity/decorators/page-type.test.ts +0 -81
  109. package/test/unit/playerSettings.test.ts +0 -73
  110. package/test/unit/progress-row/content-card.test.ts +0 -314
  111. package/test/unit/progress-row/playlist-card.test.ts +0 -104
  112. package/test/unit/progressRows.test.ts +0 -243
  113. package/test/unit/recommendations.test.js +0 -47
  114. package/test/unit/sanityQueryService.test.ts +0 -200
  115. package/test/unit/search.test.ts +0 -44
  116. package/test/unit/sentry.test.ts +0 -62
  117. package/test/unit/services/progress-internal/bubble.test.ts +0 -279
  118. package/test/unit/services/progress.test.ts +0 -396
  119. package/test/unit/streakMessage.test.ts +0 -251
  120. package/test/unit/sync/context.test.ts +0 -51
  121. package/test/unit/sync/effects/logout-warning.test.ts +0 -158
  122. package/test/unit/sync/effects/push-failure-notification.test.ts +0 -196
  123. package/test/unit/sync/errors/sync-errors.test.ts +0 -106
  124. package/test/unit/sync/errors/validators.test.ts +0 -61
  125. package/test/unit/sync/helpers/TestModel.ts +0 -44
  126. package/test/unit/sync/helpers/index.ts +0 -172
  127. package/test/unit/sync/manager.test.ts +0 -303
  128. package/test/unit/sync/models/user-award-progress.test.ts +0 -82
  129. package/test/unit/sync/resolver.test.ts +0 -229
  130. package/test/unit/sync/retry.test.ts +0 -314
  131. package/test/unit/sync/run-scope.test.ts +0 -23
  132. package/test/unit/sync/stale-record-cleanup.test.ts +0 -107
  133. package/test/unit/sync/store/push-coalescer.test.ts +0 -156
  134. package/test/unit/sync/store-configs.test.ts +0 -37
  135. package/test/unit/sync/telemetry/sync-telemetry.test.ts +0 -118
  136. package/test/unit/sync/utils/event-emitter.test.ts +0 -64
  137. package/test/unit/sync/utils/throttle.test.ts +0 -245
  138. package/test/unit/url-builder.test.ts +0 -72
  139. package/test/unit/user/account.test.ts +0 -66
  140. package/test/unit/user/permissions.test.js +0 -191
@@ -1,275 +0,0 @@
1
- import { awardManager } from '../../../src/services/awards/internal/award-manager.js'
2
- import { awardEvents } from '../../../src/services/awards/internal/award-events.js'
3
- import { mockAwardDefinitions, getAwardByContentId } from '../../mockData/award-definitions.js'
4
- import { globalConfig } from '../../../src/services/config.js'
5
- import { LocalStorageMock } from '../../localStorageMock.js'
6
- import { setupDefaultMocks, setupAwardEventListeners } from '../../unit/awards/helpers/index'
7
- import { mockCompletionStates, mockAllCompleted, mockNoneCompleted } from '../../unit/awards/helpers/completion-mock'
8
-
9
- jest.mock('../../../src/services/sanity.js', () => ({
10
- ...jest.requireActual('../../../src/services/sanity'),
11
- default: { fetch: jest.fn() },
12
- fetchSanity: jest.fn()
13
- }))
14
-
15
- jest.mock('../../../src/services/railcontent.js', () => ({
16
- ...jest.requireActual('../../../src/services/railcontent'),
17
- fetchUserPermissionsData: jest.fn().mockResolvedValue({ permissions: [108, 91, 92], isAdmin: false })
18
- }))
19
-
20
- jest.mock('../../../src/services/sync/repository-proxy.ts', () => {
21
- const mockFns = {
22
- contentProgress: {
23
- getOneProgressByContentId: jest.fn(),
24
- getSomeProgressByContentIds: jest.fn(),
25
- queryOne: jest.fn(),
26
- queryAll: jest.fn()
27
- },
28
- practices: {
29
- sumPracticeMinutesForContent: jest.fn()
30
- },
31
- userAwardProgress: {
32
- hasCompletedAward: jest.fn(),
33
- recordAwardProgress: jest.fn(),
34
- getByAwardId: jest.fn(),
35
- completeAward: jest.fn()
36
- }
37
- }
38
- return { default: mockFns, ...mockFns }
39
- })
40
-
41
- import sanityClient, { fetchSanity } from '../../../src/services/sanity.js'
42
- import db_ from '../../../src/services/sync/repository-proxy'
43
- const db = db_ as any
44
- import { awardDefinitions } from '../../../src/services/awards/internal/award-definitions.js'
45
-
46
- describe('Award Content Exclusion Handling - E2E Scenarios', () => {
47
- let listeners
48
-
49
- beforeEach(async () => {
50
- jest.clearAllMocks()
51
- globalConfig.localStorage = new LocalStorageMock()
52
- awardEvents.removeAllListeners()
53
-
54
- sanityClient.fetch = jest.fn().mockResolvedValue(mockAwardDefinitions)
55
- setupDefaultMocks(db, fetchSanity, { practiceMinutes: 150 })
56
-
57
- db.userAwardProgress.completeAward = jest.fn().mockResolvedValue({ data: {}, status: 'synced' })
58
-
59
- db.contentProgress.getSomeProgressByContentIds.mockResolvedValue({
60
- data: [{ created_at: Math.floor(Date.now() / 1000) - 86400 * 7 }]
61
- })
62
-
63
- await awardDefinitions.refresh()
64
-
65
- listeners = setupAwardEventListeners(awardEvents)
66
- })
67
-
68
- afterEach(() => {
69
- awardEvents.removeAllListeners()
70
- awardDefinitions.clear()
71
- })
72
-
73
- describe('Scenario: Guided course with excluded intro video (416446 - 1 eligible lesson)', () => {
74
- const testAward = getAwardByContentId(416446)
75
- const courseId = 416446
76
-
77
- test('completing the single eligible lesson grants award at 100%', async () => {
78
- mockAllCompleted(db)
79
-
80
- await awardManager.onContentCompleted(courseId)
81
-
82
- expect(db.userAwardProgress.recordAwardProgress).toHaveBeenCalledWith(
83
- expect.any(String),
84
- 100,
85
- expect.objectContaining({
86
- completedAt: expect.any(String),
87
- immediate: true
88
- })
89
- )
90
- expect(listeners.granted).toHaveBeenCalledTimes(1)
91
- })
92
-
93
- test('shows 0% progress when eligible lesson not completed', async () => {
94
- mockNoneCompleted(db)
95
-
96
- await awardManager.onContentCompleted(courseId)
97
-
98
- expect(db.userAwardProgress.recordAwardProgress).toHaveBeenCalledWith(
99
- testAward._id,
100
- 0,
101
- expect.objectContaining({
102
- progressData: expect.any(Object)
103
- })
104
- )
105
- })
106
- })
107
-
108
- describe('Scenario: Course with 4 eligible lessons (417049 - intro excluded)', () => {
109
- const testAward = getAwardByContentId(417049)
110
- const courseId = 417049
111
-
112
- test('completing 1 of 4 lessons shows 25% progress', async () => {
113
- mockCompletionStates(db, [417045])
114
-
115
- await awardManager.onContentCompleted(courseId)
116
-
117
- expect(db.userAwardProgress.recordAwardProgress).toHaveBeenCalledWith(
118
- testAward._id,
119
- 25,
120
- expect.objectContaining({
121
- progressData: expect.any(Object)
122
- })
123
- )
124
- })
125
-
126
- test('completing 2 of 4 lessons shows 50% progress', async () => {
127
- mockCompletionStates(db, [417045, 417046])
128
-
129
- await awardManager.onContentCompleted(courseId)
130
-
131
- expect(db.userAwardProgress.recordAwardProgress).toHaveBeenCalledWith(
132
- testAward._id,
133
- 50,
134
- expect.objectContaining({
135
- progressData: expect.any(Object)
136
- })
137
- )
138
- })
139
-
140
- test('must complete all 4 eligible lessons to earn award', async () => {
141
- mockCompletionStates(db, [417045, 417046, 417047, 417048])
142
-
143
- await awardManager.onContentCompleted(courseId)
144
-
145
- expect(db.userAwardProgress.recordAwardProgress).toHaveBeenCalledWith(
146
- expect.any(String),
147
- 100,
148
- expect.objectContaining({
149
- completedAt: expect.any(String),
150
- immediate: true
151
- })
152
- )
153
- expect(listeners.granted).toHaveBeenCalledTimes(1)
154
- })
155
- })
156
-
157
- describe('Scenario: Large course with 23 eligible lessons (416464 - intro excluded)', () => {
158
- const testAward = getAwardByContentId(416464)
159
- const courseId = 416464
160
- const eligibleLessons = [
161
- 416467, 416468, 416469, 416470, 416471, 416472, 416473,
162
- 416474, 416475, 416476, 416477, 416478, 416479, 416480, 416481,
163
- 416482, 416483, 416484, 416485, 416486, 416487, 416488, 416489
164
- ]
165
-
166
- test('shows 0% progress when no eligible lessons completed', async () => {
167
- mockNoneCompleted(db)
168
-
169
- await awardManager.onContentCompleted(courseId)
170
-
171
- expect(db.userAwardProgress.recordAwardProgress).toHaveBeenCalledWith(
172
- testAward._id,
173
- 0,
174
- expect.objectContaining({
175
- progressData: expect.any(Object)
176
- })
177
- )
178
- })
179
-
180
- test('completing 12 of 23 lessons shows ~52% progress', async () => {
181
- mockCompletionStates(db, eligibleLessons.slice(0, 12))
182
-
183
- await awardManager.onContentCompleted(courseId)
184
-
185
- expect(db.userAwardProgress.recordAwardProgress).toHaveBeenCalledWith(
186
- testAward._id,
187
- 52,
188
- expect.objectContaining({
189
- progressData: expect.any(Object)
190
- })
191
- )
192
- })
193
-
194
- test('must complete all 23 eligible lessons to earn award', async () => {
195
- mockCompletionStates(db, eligibleLessons)
196
-
197
- await awardManager.onContentCompleted(courseId)
198
-
199
- expect(db.userAwardProgress.recordAwardProgress).toHaveBeenCalledWith(
200
- expect.any(String),
201
- 100,
202
- expect.objectContaining({
203
- completedAt: expect.any(String),
204
- immediate: true
205
- })
206
- )
207
- expect(listeners.granted).toHaveBeenCalledTimes(1)
208
- })
209
- })
210
-
211
- describe('Scenario: Course type without excluded content (417039 - all 3 lessons count)', () => {
212
- const testAward = getAwardByContentId(417039)
213
- const courseId = 417039
214
-
215
- test('first lesson counts toward progress', async () => {
216
- mockCompletionStates(db, [417035])
217
-
218
- await awardManager.onContentCompleted(courseId)
219
-
220
- expect(db.userAwardProgress.recordAwardProgress).toHaveBeenCalledWith(
221
- testAward._id,
222
- 33,
223
- expect.objectContaining({
224
- progressData: expect.any(Object)
225
- })
226
- )
227
- })
228
-
229
- test('all 3 lessons must be completed to earn award', async () => {
230
- mockAllCompleted(db)
231
-
232
- await awardManager.onContentCompleted(courseId)
233
-
234
- expect(db.userAwardProgress.recordAwardProgress).toHaveBeenCalledWith(
235
- expect.any(String),
236
- 100,
237
- expect.objectContaining({
238
- completedAt: expect.any(String),
239
- immediate: true
240
- })
241
- )
242
- })
243
- })
244
-
245
- describe('Scenario: Learning path content type (417140)', () => {
246
- const testAward = getAwardByContentId(417140)
247
- const courseId = 417140
248
-
249
- test('all child content counts toward progress', async () => {
250
- mockCompletionStates(db, testAward.child_ids.slice(0, 11))
251
-
252
- await awardManager.onContentCompleted(courseId)
253
-
254
- expect(db.userAwardProgress.recordAwardProgress).toHaveBeenCalledWith(
255
- testAward._id,
256
- 50,
257
- expect.objectContaining({
258
- progressData: expect.any(Object)
259
- })
260
- )
261
- })
262
- })
263
-
264
- describe('Scenario: Skill pack content type (418000)', () => {
265
- const courseId = 418000
266
-
267
- test('completing all lessons grants award', async () => {
268
- mockAllCompleted(db)
269
-
270
- await awardManager.onContentCompleted(courseId)
271
-
272
- expect(listeners.granted).toHaveBeenCalledTimes(1)
273
- })
274
- })
275
- })
@@ -1,86 +0,0 @@
1
- /**
2
- * @jest-environment jsdom
3
- */
4
- import { urlToBase64, urlMapToBase64 } from '../../../../src/services/awards/internal/image-utils.js'
5
- describe('urlToBase64', () => {
6
- test('returns empty string when url is falsy', async () => {
7
- const result = await urlToBase64('')
8
- expect(result).toBe('')
9
- })
10
- test('returns empty string when fetch response is not ok', async () => {
11
- global.fetch = jest.fn().mockResolvedValue({
12
- ok: false,
13
- blob: jest.fn(),
14
- })
15
- const result = await urlToBase64('https://cdn.example.com/image.png')
16
- expect(result).toBe('')
17
- })
18
- test('returns base64 data string on successful fetch', async () => {
19
- global.fetch = jest.fn().mockResolvedValue({
20
- ok: true,
21
- blob: jest.fn().mockResolvedValue(new Blob(['fake-image-data'], { type: 'image/png' })),
22
- })
23
- jest.spyOn(global, 'FileReader').mockImplementation(() => ({
24
- readAsDataURL: jest.fn().mockImplementation(function(this: any) {
25
- this.result = 'data:image/png;base64,abc123=='
26
- this.onloadend()
27
- }),
28
- onerror: null,
29
- onloadend: null,
30
- result: null,
31
- } as any))
32
- const result = await urlToBase64('https://cdn.example.com/image.png')
33
- expect(result).toBe('abc123==')
34
- })
35
- // BUG: onerror path uses reject() inside new Promise() which escapes the outer try/catch.
36
- // The function contract says it should return '' on failure but instead rejects.
37
- // Fix: change reject() to resolve('') in the onerror handler in image-utils.js
38
- test('returns empty string when FileReader errors', async () => {
39
- jest.spyOn(console, 'error').mockImplementation(() => {})
40
- global.fetch = jest.fn().mockResolvedValue({
41
- ok: true,
42
- blob: jest.fn().mockResolvedValue(new Blob(['fake-image-data'], { type: 'image/png' })),
43
- })
44
- jest.spyOn(global, 'FileReader').mockImplementation(() => ({
45
- readAsDataURL: jest.fn().mockImplementation(function(this: any) {
46
- setTimeout(() => this.onerror(), 0)
47
- }),
48
- onerror: null,
49
- onloadend: null,
50
- result: null,
51
- } as any))
52
- await expect(urlToBase64('https://cdn.example.com/image.png')).rejects.toThrow(
53
- 'Failed to convert image to base64'
54
- )
55
- })
56
- })
57
-
58
- describe('urlMapToBase64', () => {
59
- test('converts all URLs in a map to base64', async () => {
60
- global.fetch = jest.fn().mockResolvedValue({
61
- ok: true,
62
- blob: jest.fn().mockResolvedValue(new Blob(['fake-image-data'], { type: 'image/png' })),
63
- })
64
- jest.spyOn(global, 'FileReader').mockImplementation(() => ({
65
- readAsDataURL: jest.fn().mockImplementation(function(this: any) {
66
- this.result = 'data:image/png;base64,abc123=='
67
- this.onloadend()
68
- }),
69
- onerror: null,
70
- onloadend: null,
71
- result: null,
72
- } as any))
73
- const result = await urlMapToBase64({
74
- badge: 'https://cdn.example.com/badge.png',
75
- logo: 'https://cdn.example.com/logo.png',
76
- })
77
- expect(result).toEqual({
78
- badge: 'abc123==',
79
- logo: 'abc123==',
80
- })
81
- })
82
- test('returns empty object when map is empty', async () => {
83
- const result = await urlMapToBase64({})
84
- expect(result).toEqual({})
85
- })
86
- })
@@ -1,104 +0,0 @@
1
- export const mockContentProgressObserver = () => ({
2
- contentProgressObserver: {
3
- start: jest.fn().mockResolvedValue(undefined),
4
- stop: jest.fn(),
5
- },
6
- })
7
-
8
- export const mockLearningPaths = () => ({
9
- getDailySession: jest.fn().mockResolvedValue(null),
10
- onLearningPathCompletedActions: jest.fn().mockResolvedValue(undefined),
11
- })
12
-
13
- export const mockProgressEvents = () => ({
14
- emitProgressSaved: jest.fn(),
15
- })
16
-
17
- export type HierarchyTreeNode = {
18
- id: number
19
- type?: string
20
- brand?: string
21
- children?: HierarchyTreeNode[]
22
- }
23
-
24
- type HierarchyLookups = {
25
- topLevelId: number
26
- parents: Record<number, number>
27
- children: Record<number, number[]>
28
- metadata: Record<number, { type: string; brand: string; parent_id: number }>
29
- }
30
-
31
- const LP_TYPE = 'learning-path-v2'
32
-
33
- const ALC_KEY = 'alc'
34
- const LP_KEY = 'lp'
35
-
36
- let hierarchiesByKey: Record<string, Record<number, HierarchyLookups>> = {}
37
- let topByKey: Record<string, Record<number, number>> = {}
38
-
39
- function keyFor(collection?: { type?: string } | null): string {
40
- return collection?.type === LP_TYPE ? LP_KEY : ALC_KEY
41
- }
42
-
43
- export function setHierarchy(tree: HierarchyTreeNode, options?: { lp?: boolean }) {
44
- const key = options?.lp ? LP_KEY : ALC_KEY
45
- hierarchiesByKey[key] ??= {}
46
- topByKey[key] ??= {}
47
- hierarchiesByKey[key][tree.id] = treeToLookups(tree)
48
- registerIds(tree, tree.id, topByKey[key])
49
- }
50
-
51
- export function clearHierarchies() {
52
- hierarchiesByKey = {}
53
- topByKey = {}
54
- }
55
-
56
- function treeToLookups(root: HierarchyTreeNode): HierarchyLookups {
57
- const parents: Record<number, number> = {}
58
- const children: Record<number, number[]> = {}
59
- const metadata: Record<number, { type: string; brand: string; parent_id: number }> = {}
60
-
61
- function walk(node: HierarchyTreeNode, parentId: number) {
62
- const childIds = (node.children ?? []).map(c => c.id)
63
- metadata[node.id] = {
64
- type: node.type ?? 'lesson',
65
- brand: node.brand ?? 'drumeo',
66
- parent_id: parentId,
67
- }
68
- if (parentId) parents[node.id] = parentId
69
- if (childIds.length > 0) children[node.id] = childIds
70
- for (const c of node.children ?? []) walk(c, node.id)
71
- }
72
-
73
- walk(root, 0)
74
-
75
- return { topLevelId: root.id, parents, children, metadata }
76
- }
77
-
78
- function registerIds(node: HierarchyTreeNode, topId: number, target: Record<number, number>) {
79
- target[node.id] = topId
80
- for (const c of node.children ?? []) registerIds(c, topId, target)
81
- }
82
-
83
- function lookupFor(contentId: number, collection?: any): HierarchyLookups {
84
- const key = keyFor(collection)
85
- const tops = topByKey[key] ?? {}
86
- const hierarchies = hierarchiesByKey[key] ?? {}
87
- const topId = tops[contentId] ?? (key === LP_KEY ? collection?.id : contentId)
88
- return hierarchies[topId] ?? {
89
- topLevelId: contentId,
90
- parents: {},
91
- children: {},
92
- metadata: { [contentId]: { brand: 'drumeo', type: 'lesson', parent_id: 0 } },
93
- }
94
- }
95
-
96
- export const mockSanity = () => ({
97
- getHierarchy: jest.fn((contentId: number, collection?: any) =>
98
- Promise.resolve(lookupFor(contentId, collection)),
99
- ),
100
- getHierarchies: jest.fn((contentIds: number[], collection?: any) =>
101
- Promise.resolve(Object.fromEntries(contentIds.map(id => [id, lookupFor(id, collection)]))),
102
- ),
103
- getSanityDate: jest.fn((date: Date) => date.toISOString()),
104
- })