@memberjunction/actions-bizapps-lms 5.22.0 → 5.24.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 (60) hide show
  1. package/.env.integration.example +4 -0
  2. package/.turbo/turbo-build.log +1 -1
  3. package/CHANGELOG.md +27 -0
  4. package/dist/base/base-lms.action.d.ts +5 -0
  5. package/dist/base/base-lms.action.d.ts.map +1 -1
  6. package/dist/base/base-lms.action.js +11 -4
  7. package/dist/base/base-lms.action.js.map +1 -1
  8. package/dist/providers/learnworlds/actions/create-user.action.d.ts.map +1 -1
  9. package/dist/providers/learnworlds/actions/create-user.action.js +3 -0
  10. package/dist/providers/learnworlds/actions/create-user.action.js.map +1 -1
  11. package/dist/providers/learnworlds/actions/get-course-details.action.js +6 -6
  12. package/dist/providers/learnworlds/actions/get-course-details.action.js.map +1 -1
  13. package/dist/providers/learnworlds/actions/get-courses.action.d.ts +5 -0
  14. package/dist/providers/learnworlds/actions/get-courses.action.d.ts.map +1 -1
  15. package/dist/providers/learnworlds/actions/get-courses.action.js +73 -48
  16. package/dist/providers/learnworlds/actions/get-courses.action.js.map +1 -1
  17. package/dist/providers/learnworlds/actions/get-user-details.action.d.ts +3 -3
  18. package/dist/providers/learnworlds/actions/get-user-details.action.d.ts.map +1 -1
  19. package/dist/providers/learnworlds/actions/get-user-details.action.js +23 -23
  20. package/dist/providers/learnworlds/actions/get-user-details.action.js.map +1 -1
  21. package/dist/providers/learnworlds/actions/get-user-progress.action.d.ts +4 -1
  22. package/dist/providers/learnworlds/actions/get-user-progress.action.d.ts.map +1 -1
  23. package/dist/providers/learnworlds/actions/get-user-progress.action.js +48 -37
  24. package/dist/providers/learnworlds/actions/get-user-progress.action.js.map +1 -1
  25. package/dist/providers/learnworlds/actions/get-users.action.d.ts +3 -0
  26. package/dist/providers/learnworlds/actions/get-users.action.d.ts.map +1 -1
  27. package/dist/providers/learnworlds/actions/get-users.action.js +21 -15
  28. package/dist/providers/learnworlds/actions/get-users.action.js.map +1 -1
  29. package/dist/providers/learnworlds/actions/onboard-learner.action.js +4 -4
  30. package/dist/providers/learnworlds/actions/onboard-learner.action.js.map +1 -1
  31. package/dist/providers/learnworlds/actions/update-user-progress.action.js +2 -2
  32. package/dist/providers/learnworlds/actions/update-user-progress.action.js.map +1 -1
  33. package/dist/providers/learnworlds/learnworlds-base.action.d.ts +44 -0
  34. package/dist/providers/learnworlds/learnworlds-base.action.d.ts.map +1 -1
  35. package/dist/providers/learnworlds/learnworlds-base.action.js +107 -2
  36. package/dist/providers/learnworlds/learnworlds-base.action.js.map +1 -1
  37. package/package.json +6 -6
  38. package/src/__tests__/get-certificates.action.test.ts +467 -0
  39. package/src/__tests__/get-course-analytics.action.test.ts +340 -0
  40. package/src/__tests__/get-course-details.action.test.ts +510 -0
  41. package/src/__tests__/get-courses.action.test.ts +1191 -0
  42. package/src/__tests__/get-quiz-results.action.test.ts +575 -0
  43. package/src/__tests__/get-user-details.action.test.ts +533 -0
  44. package/src/__tests__/get-user-enrollments.action.test.ts +387 -0
  45. package/src/__tests__/get-user-progress.action.test.ts +588 -0
  46. package/src/__tests__/get-users.action.test.ts +464 -0
  47. package/src/__tests__/integration.test.ts +252 -3
  48. package/src/__tests__/rate-limit-retry.test.ts +296 -0
  49. package/src/__tests__/update-user-progress.action.test.ts +312 -0
  50. package/src/base/base-lms.action.ts +12 -4
  51. package/src/providers/learnworlds/actions/create-user.action.ts +4 -0
  52. package/src/providers/learnworlds/actions/get-course-details.action.ts +6 -6
  53. package/src/providers/learnworlds/actions/get-courses.action.ts +78 -58
  54. package/src/providers/learnworlds/actions/get-user-details.action.ts +32 -25
  55. package/src/providers/learnworlds/actions/get-user-progress.action.ts +54 -41
  56. package/src/providers/learnworlds/actions/get-users.action.ts +24 -16
  57. package/src/providers/learnworlds/actions/onboard-learner.action.ts +4 -4
  58. package/src/providers/learnworlds/actions/update-user-progress.action.ts +2 -2
  59. package/src/providers/learnworlds/learnworlds-base.action.ts +128 -2
  60. package/tsconfig.json +2 -1
@@ -1,10 +1,11 @@
1
1
  /**
2
2
  * LearnWorlds Integration Tests — hits the REAL LearnWorlds API.
3
3
  *
4
- * Covers ALL 17 LearnWorlds actions chained together:
5
- * Read-only (no setup needed): GetCourses, GetCourseDetails, GetBundles, GetUsers
4
+ * Covers ALL 19 LearnWorlds actions chained together:
5
+ * Read-only (no setup needed): GetCourses, GetCourseDetails, GetCourseAnalytics, GetBundles, GetUsers
6
6
  * Create/mutate: CreateUser, UpdateUser, AttachTags, DetachTags
7
- * Enrollment: EnrollUser, GetUserEnrollments, GetUserProgress
7
+ * Enrollment: EnrollUser, GetUserEnrollments, GetUserProgress, UpdateUserProgress
8
+ * Assessment & Achievement: GetCertificates, GetQuizResults
8
9
  * Auth: SSOLogin
9
10
  * Details: GetUserDetails
10
11
  * Orchestration: OnboardLearner
@@ -83,6 +84,11 @@ import { UpdateUserAction } from '../providers/learnworlds/actions/update-user.a
83
84
  import { AttachTagsAction } from '../providers/learnworlds/actions/attach-tags.action';
84
85
  import { DetachTagsAction } from '../providers/learnworlds/actions/detach-tags.action';
85
86
  import { OnboardLearnerAction } from '../providers/learnworlds/actions/onboard-learner.action';
87
+ import { GetLearnWorldsBulkDataAction } from '../providers/learnworlds/actions/get-bulk-data.action';
88
+ import { GetCourseAnalyticsAction } from '../providers/learnworlds/actions/get-course-analytics.action';
89
+ import { GetCertificatesAction } from '../providers/learnworlds/actions/get-certificates.action';
90
+ import { GetQuizResultsAction } from '../providers/learnworlds/actions/get-quiz-results.action';
91
+ import { UpdateUserProgressAction } from '../providers/learnworlds/actions/update-user-progress.action';
86
92
  import { LearnWorldsBaseAction } from '../providers/learnworlds/learnworlds-base.action';
87
93
  import { UserInfo } from '@memberjunction/core';
88
94
 
@@ -92,6 +98,7 @@ const API_KEY = process.env.LW_API_KEY || '';
92
98
  const CLIENT_ID = process.env.LW_CLIENT_ID || '';
93
99
  const COMPANY_ID = process.env.LW_COMPANY_ID || '00000000-0000-0000-0000-000000000001';
94
100
  const TEST_COURSE_ID = process.env.LW_TEST_COURSE_ID || '';
101
+ const TEST_LESSON_ID = process.env.LW_TEST_LESSON_ID || '';
95
102
  const TEST_EMAIL = process.env.LW_TEST_EMAIL || `mj-test-${Date.now()}@example.com`;
96
103
  const ONBOARD_EMAIL = `mj-onboard-${Date.now()}@example.com`;
97
104
 
@@ -168,6 +175,30 @@ describe.skipIf(!RUN_INTEGRATION)('LearnWorlds Integration Tests', () => {
168
175
  console.log(` GetCourseDetails: OK (title: "${result.CourseDetails.title}")`);
169
176
  });
170
177
 
178
+ // ─── GetCourseAnalytics ────────────────────────────────────────────
179
+ it('GetCourseAnalytics — should get course analytics', async () => {
180
+ if (!TEST_COURSE_ID) {
181
+ console.warn(' Skipping GetCourseAnalytics — LW_TEST_COURSE_ID not set');
182
+ return;
183
+ }
184
+
185
+ const action = patchCredentials(new GetCourseAnalyticsAction());
186
+ const result = await action.GetCourseAnalytics(
187
+ {
188
+ CompanyID: COMPANY_ID,
189
+ CourseID: TEST_COURSE_ID,
190
+ IncludeUserBreakdown: false,
191
+ IncludeModuleStats: false,
192
+ IncludeRevenue: false,
193
+ },
194
+ contextUser,
195
+ );
196
+
197
+ expect(result.CourseAnalytics).toBeDefined();
198
+ expect(result.Summary).toBeDefined();
199
+ console.log(` GetCourseAnalytics: OK (enrollments=${result.CourseAnalytics.totalEnrollments}, completionRate=${result.CourseAnalytics.completionRate}%)`);
200
+ });
201
+
171
202
  // ─── GetBundles ──────────────────────────────────────────────────
172
203
  it('GetBundles — should list bundles', async () => {
173
204
  const action = patchCredentials(new GetBundlesAction());
@@ -394,6 +425,114 @@ describe.skipIf(!RUN_INTEGRATION)('LearnWorlds Integration Tests', () => {
394
425
  console.log(` GetUserProgress: OK (courses=${result.UserProgress.totalCourses}, overall=${result.UserProgress.overallProgressPercentage}%)`);
395
426
  });
396
427
 
428
+ // ─── UpdateUserProgress ────────────────────────────────────────────
429
+ it('UpdateUserProgress — should update course progress', async () => {
430
+ if (!createdUserId || !TEST_COURSE_ID) {
431
+ console.warn(' Skipping UpdateUserProgress — no userId or no TEST_COURSE_ID');
432
+ return;
433
+ }
434
+
435
+ const action = patchCredentials(new UpdateUserProgressAction());
436
+
437
+ try {
438
+ const result = await action.UpdateProgress(
439
+ {
440
+ CompanyID: COMPANY_ID,
441
+ UserID: createdUserId,
442
+ CourseID: TEST_COURSE_ID,
443
+ ...(TEST_LESSON_ID ? { LessonID: TEST_LESSON_ID, Completed: true } : { ProgressPercentage: 10 }),
444
+ },
445
+ contextUser,
446
+ );
447
+
448
+ expect(result.ProgressDetails).toBeDefined();
449
+ expect(result.Summary).toBeDefined();
450
+ const updateType = result.ProgressDetails.updateType;
451
+ const newPct = result.Summary.newPercentage;
452
+ console.log(` UpdateUserProgress: OK (type=${updateType}, newProgress=${newPct}%, completed=${result.Summary.isCompleted})`);
453
+ } catch (error) {
454
+ // LearnWorlds enrollment/progress endpoints may not be available for all course types
455
+ // or may take time to register a new enrollment. Log and pass if it's a 404.
456
+ const msg = error instanceof Error ? error.message : String(error);
457
+ if (msg.includes('not enrolled') || msg.includes('does not exist') || msg.includes('404')) {
458
+ console.warn(` UpdateUserProgress: SKIPPED (enrollment not ready or endpoint unavailable: ${msg})`);
459
+ } else {
460
+ throw error;
461
+ }
462
+ }
463
+ });
464
+
465
+ // ─── GetCertificates ────────────────────────────────────────────
466
+ it('GetCertificates — should list certificates for the user', async () => {
467
+ if (!createdUserId) {
468
+ console.warn(' Skipping GetCertificates — no userId');
469
+ return;
470
+ }
471
+
472
+ const action = patchCredentials(new GetCertificatesAction());
473
+
474
+ try {
475
+ const result = await action.GetCertificates(
476
+ {
477
+ CompanyID: COMPANY_ID,
478
+ UserID: createdUserId,
479
+ IncludeDownloadLinks: true,
480
+ MaxResults: 10,
481
+ },
482
+ contextUser,
483
+ );
484
+
485
+ expect(result.Certificates).toBeDefined();
486
+ expect(Array.isArray(result.Certificates)).toBe(true);
487
+ console.log(` GetCertificates: OK (${result.TotalCount} certificate(s) found)`);
488
+ } catch (error) {
489
+ // A newly created test user typically has no certificates.
490
+ // The certificates endpoint may return 404 if no certificates exist.
491
+ const msg = error instanceof Error ? error.message : String(error);
492
+ if (msg.includes('does not exist') || msg.includes('404')) {
493
+ console.warn(` GetCertificates: SKIPPED (no certificates for test user — endpoint returned 404)`);
494
+ } else {
495
+ throw error;
496
+ }
497
+ }
498
+ });
499
+
500
+ // ─── GetQuizResults ─────────────────────────────────────────────
501
+ it('GetQuizResults — should list quiz results for the user', async () => {
502
+ if (!createdUserId) {
503
+ console.warn(' Skipping GetQuizResults — no userId');
504
+ return;
505
+ }
506
+
507
+ const action = patchCredentials(new GetQuizResultsAction());
508
+
509
+ try {
510
+ const result = await action.GetQuizResults(
511
+ {
512
+ CompanyID: COMPANY_ID,
513
+ UserID: createdUserId,
514
+ IncludeQuestions: false,
515
+ IncludeAnswers: false,
516
+ MaxResults: 10,
517
+ },
518
+ contextUser,
519
+ );
520
+
521
+ expect(result.QuizResults).toBeDefined();
522
+ expect(Array.isArray(result.QuizResults)).toBe(true);
523
+ console.log(` GetQuizResults: OK (${result.TotalCount} quiz result(s) found)`);
524
+ } catch (error) {
525
+ // A newly created test user has no quiz attempts.
526
+ // The quiz-results endpoint may return 404.
527
+ const msg = error instanceof Error ? error.message : String(error);
528
+ if (msg.includes('does not exist') || msg.includes('404')) {
529
+ console.warn(` GetQuizResults: SKIPPED (no quiz results for test user — endpoint returned 404)`);
530
+ } else {
531
+ throw error;
532
+ }
533
+ }
534
+ });
535
+
397
536
  // ─── FindUserByEmail (verify) ────────────────────────────────────
398
537
  it('FindUserByEmail (verify) — should find the user we created', async () => {
399
538
  if (!createdUserId) {
@@ -507,4 +646,114 @@ describe.skipIf(!RUN_INTEGRATION)('LearnWorlds Integration Tests', () => {
507
646
  console.log(` OnboardLearner (re-run): OK (isNewUser=false, same userId=${result.LearnWorldsUserId})`);
508
647
  });
509
648
  });
649
+
650
+ // ═══════════════════════════════════════════════════════════════════
651
+ // PHASE 6: Bulk data retrieval — rate limit stress test
652
+ //
653
+ // This is the test that reproduces GitHub issue #2312.
654
+ // It fetches ALL users then hits the enrollment endpoint for each one,
655
+ // which is the exact pattern that triggers 429 rate limiting.
656
+ // ═══════════════════════════════════════════════════════════════════
657
+
658
+ describe('Phase 6: GetBulkData rate limit stress test', () => {
659
+ it('GetBulkData — should fetch all users + enrollments without 429 failures', async () => {
660
+ // Reset global rate limiter to ensure a clean sliding window
661
+ LearnWorldsBaseAction.ResetRateLimiter();
662
+
663
+ // Seed the CLIENT_ID env var so buildRequestConfig resolves it
664
+ // (normally seeded by patchCredentials() in earlier phases)
665
+ const provider = 'LEARNWORLDS';
666
+ process.env[`BIZAPPS_${provider}_${COMPANY_ID}_CLIENT_ID`] = CLIENT_ID || SCHOOL_DOMAIN;
667
+
668
+ // Patch credentials at the prototype level so all inner action instances
669
+ // (GetUsersAction, GetUserEnrollmentsAction, etc.) also get them
670
+ const credentialMock = async () => ({
671
+ CompanyID: COMPANY_ID,
672
+ APIKey: API_KEY,
673
+ ExternalSystemID: SCHOOL_DOMAIN,
674
+ AccessToken: null,
675
+ CustomAttribute1: null,
676
+ });
677
+ const apiCredMock = async () => ({
678
+ apiKey: API_KEY,
679
+ apiSecret: undefined,
680
+ accessToken: undefined,
681
+ });
682
+ vi.spyOn(LearnWorldsBaseAction.prototype as Record<string, unknown>, 'getCompanyIntegration' as never).mockImplementation(credentialMock as never);
683
+ vi.spyOn(LearnWorldsBaseAction.prototype as Record<string, unknown>, 'getAPICredentials' as never).mockImplementation(apiCredMock as never);
684
+
685
+ // Track 429 retries via console.warn spy
686
+ const retryWarnings: string[] = [];
687
+ const originalWarn = console.warn;
688
+ console.warn = (...args: unknown[]) => {
689
+ const msg = String(args[0]);
690
+ if (msg.includes('429 rate limited')) {
691
+ retryWarnings.push(msg);
692
+ }
693
+ originalWarn.apply(console, args);
694
+ };
695
+
696
+ const action = new GetLearnWorldsBulkDataAction();
697
+ const startTime = Date.now();
698
+
699
+ try {
700
+ const result = await action.GetBulkData(
701
+ {
702
+ CompanyID: COMPANY_ID,
703
+ IncludeUsers: true,
704
+ IncludeCourses: true,
705
+ IncludeBundles: true,
706
+ IncludeEnrollments: true,
707
+ IncludeProgress: true,
708
+ IncludeCertificates: false,
709
+ IncludeQuizResults: false,
710
+ MaxResultsPerEntity: 20,
711
+ },
712
+ contextUser,
713
+ );
714
+
715
+ const elapsed = ((Date.now() - startTime) / 1000).toFixed(1);
716
+
717
+ // Log comprehensive results
718
+ console.log(`\n ══════════════════════════════════════════════════`);
719
+ console.log(` GetBulkData Rate Limit Stress Test Results`);
720
+ console.log(` ──────────────────────────────────────────────────`);
721
+ console.log(` Duration: ${elapsed}s`);
722
+ console.log(` Total API calls: ${result.totalApiCalls}`);
723
+ console.log(` Users: ${result.users?.length ?? 0}`);
724
+ console.log(` Courses: ${result.courses?.length ?? 0}`);
725
+ console.log(` Bundles: ${result.bundles?.length ?? 0}`);
726
+ console.log(` Enrollments: ${result.enrollments?.length ?? 0}`);
727
+ console.log(` Progress: ${result.progress?.length ?? 0}`);
728
+ console.log(` 429 retries: ${retryWarnings.length}`);
729
+ console.log(` Errors: ${result.errors.length}`);
730
+
731
+ if (retryWarnings.length > 0) {
732
+ console.log(` ── Retry details ──`);
733
+ for (const warning of retryWarnings) {
734
+ console.log(` ${warning}`);
735
+ }
736
+ }
737
+
738
+ if (result.errors.length > 0) {
739
+ console.log(` ── Errors ──`);
740
+ for (const err of result.errors) {
741
+ console.log(` [${err.entity}] ${err.entityId || '(no id)'}: ${err.message}`);
742
+ }
743
+ }
744
+ console.log(` ══════════════════════════════════════════════════\n`);
745
+
746
+ // The key assertion: zero errors means all enrollment/progress fetches succeeded.
747
+ // Before the fix, ~35 out of 100+ users would fail with 429 errors.
748
+ expect(result.errors).toEqual([]);
749
+ expect(result.users).toBeDefined();
750
+ expect(result.users!.length).toBeGreaterThan(0);
751
+ expect(result.enrollments).toBeDefined();
752
+ expect(result.progress).toBeDefined();
753
+
754
+ } finally {
755
+ console.warn = originalWarn;
756
+ }
757
+ }, 300_000); // 5-minute timeout — rate limiting (25 req/10s + inter-batch delays) makes bulk runs slower
758
+ });
510
759
  });
@@ -0,0 +1,296 @@
1
+ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
2
+
3
+ // Mock dependencies
4
+ vi.mock('@memberjunction/actions', () => ({
5
+ BaseAction: class BaseAction {
6
+ protected async InternalRunAction(): Promise<unknown> {
7
+ return {};
8
+ }
9
+ },
10
+ }));
11
+
12
+ vi.mock('@memberjunction/global', () => ({
13
+ RegisterClass: () => (target: unknown) => target,
14
+ }));
15
+
16
+ vi.mock('@memberjunction/core', () => ({
17
+ UserInfo: class UserInfo {},
18
+ Metadata: vi.fn(),
19
+ RunView: vi.fn().mockImplementation(() => ({
20
+ RunView: vi.fn().mockResolvedValue({ Success: true, Results: [] }),
21
+ })),
22
+ }));
23
+
24
+ vi.mock('@memberjunction/core-entities', () => ({
25
+ MJCompanyIntegrationEntity: class MJCompanyIntegrationEntity {
26
+ CompanyID: string = '';
27
+ APIKey: string | null = null;
28
+ AccessToken: string | null = null;
29
+ ExternalSystemID: string | null = null;
30
+ CustomAttribute1: string | null = null;
31
+ },
32
+ }));
33
+
34
+ vi.mock('@memberjunction/actions-base', () => ({
35
+ ActionParam: class ActionParam {
36
+ Name: string = '';
37
+ Value: unknown = null;
38
+ Type: string = 'Input';
39
+ },
40
+ }));
41
+
42
+ import { LearnWorldsBaseAction } from '../providers/learnworlds/learnworlds-base.action';
43
+
44
+ /**
45
+ * Concrete subclass to expose protected/private methods for testing.
46
+ */
47
+ class TestableLearnWorldsAction extends LearnWorldsBaseAction {
48
+ protected async InternalRunAction(): Promise<{ Success: boolean; Message: string; ResultCode: string }> {
49
+ return { Success: true, Message: '', ResultCode: 'SUCCESS' };
50
+ }
51
+
52
+ // Expose rate limiter reset for testing
53
+ public static resetRateLimiter(): void {
54
+ LearnWorldsBaseAction.ResetRateLimiter();
55
+ }
56
+
57
+ // Expose protected methods for testing
58
+ public testCalculateRetryDelay(attempt: number, retryAfterHeader: string | null): number {
59
+ return this['calculateRetryDelay'](attempt, retryAfterHeader);
60
+ }
61
+
62
+ public async testProcessInBatches<TItem, TResult>(
63
+ items: TItem[],
64
+ processFn: (item: TItem) => Promise<TResult>,
65
+ batchSize?: number,
66
+ ): Promise<TResult[]> {
67
+ return this.processInBatches(items, processFn, batchSize);
68
+ }
69
+
70
+ public async testSendRequestWithRetry(url: string, init: RequestInit): Promise<Response> {
71
+ return this['sendRequestWithRetry'](url, init);
72
+ }
73
+
74
+ public testWaitForRetryDelay(ms: number): Promise<void> {
75
+ return this['waitForRetryDelay'](ms);
76
+ }
77
+ }
78
+
79
+ function createMockResponse(status: number, body: object, headers?: Record<string, string>): Response {
80
+ const headerMap = new Headers(headers);
81
+ return {
82
+ ok: status >= 200 && status < 300,
83
+ status,
84
+ statusText: status === 429 ? 'Too Many Requests' : 'OK',
85
+ headers: headerMap,
86
+ json: () => Promise.resolve(body),
87
+ text: () => Promise.resolve(JSON.stringify(body)),
88
+ } as unknown as Response;
89
+ }
90
+
91
+ describe('Rate Limit Retry Logic', () => {
92
+ let action: TestableLearnWorldsAction;
93
+ let originalFetch: typeof globalThis.fetch;
94
+
95
+ beforeEach(() => {
96
+ action = new TestableLearnWorldsAction();
97
+ originalFetch = globalThis.fetch;
98
+ vi.useFakeTimers({ shouldAdvanceTime: true });
99
+ });
100
+
101
+ afterEach(() => {
102
+ globalThis.fetch = originalFetch;
103
+ vi.useRealTimers();
104
+ vi.restoreAllMocks();
105
+ TestableLearnWorldsAction.resetRateLimiter();
106
+ });
107
+
108
+ describe('sendRequestWithRetry', () => {
109
+ it('should return response on first success without retrying', async () => {
110
+ const mockResponse = createMockResponse(200, { data: 'ok' });
111
+ globalThis.fetch = vi.fn().mockResolvedValue(mockResponse);
112
+
113
+ const result = await action.testSendRequestWithRetry('https://api.test.com/v2/users', { method: 'GET' });
114
+
115
+ expect(result.status).toBe(200);
116
+ expect(globalThis.fetch).toHaveBeenCalledTimes(1);
117
+ });
118
+
119
+ it('should retry on 429 and succeed on subsequent attempt', async () => {
120
+ const rateLimitResponse = createMockResponse(429, { error: 'rate limited' });
121
+ const successResponse = createMockResponse(200, { data: 'ok' });
122
+ globalThis.fetch = vi.fn()
123
+ .mockResolvedValueOnce(rateLimitResponse)
124
+ .mockResolvedValueOnce(successResponse);
125
+
126
+ // Mock waitForRetryDelay to not actually wait
127
+ vi.spyOn(action as unknown as { waitForRetryDelay: (ms: number) => Promise<void> }, 'waitForRetryDelay' as never)
128
+ .mockResolvedValue(undefined as never);
129
+
130
+ const result = await action.testSendRequestWithRetry('https://api.test.com/v2/users', { method: 'GET' });
131
+
132
+ expect(result.status).toBe(200);
133
+ expect(globalThis.fetch).toHaveBeenCalledTimes(2);
134
+ });
135
+
136
+ it('should return 429 response after exhausting MAX_RETRIES', async () => {
137
+ const rateLimitResponse = createMockResponse(429, { error: 'rate limited' });
138
+ globalThis.fetch = vi.fn().mockResolvedValue(rateLimitResponse);
139
+
140
+ vi.spyOn(action as unknown as { waitForRetryDelay: (ms: number) => Promise<void> }, 'waitForRetryDelay' as never)
141
+ .mockResolvedValue(undefined as never);
142
+
143
+ const result = await action.testSendRequestWithRetry('https://api.test.com/v2/users', { method: 'GET' });
144
+
145
+ expect(result.status).toBe(429);
146
+ // MAX_RETRIES = 5, so: 1 initial + 5 retries = 6 total fetch calls
147
+ expect(globalThis.fetch).toHaveBeenCalledTimes(6);
148
+ });
149
+
150
+ it('should pass through non-429 error responses without retrying', async () => {
151
+ const errorResponse = createMockResponse(500, { error: 'server error' });
152
+ globalThis.fetch = vi.fn().mockResolvedValue(errorResponse);
153
+
154
+ const result = await action.testSendRequestWithRetry('https://api.test.com/v2/users', { method: 'GET' });
155
+
156
+ expect(result.status).toBe(500);
157
+ expect(globalThis.fetch).toHaveBeenCalledTimes(1);
158
+ });
159
+
160
+ it('should respect Retry-After header on 429 responses', async () => {
161
+ const rateLimitResponse = createMockResponse(429, { error: 'rate limited' }, { 'Retry-After': '3' });
162
+ const successResponse = createMockResponse(200, { data: 'ok' });
163
+ globalThis.fetch = vi.fn()
164
+ .mockResolvedValueOnce(rateLimitResponse)
165
+ .mockResolvedValueOnce(successResponse);
166
+
167
+ const waitSpy = vi.spyOn(action as unknown as { waitForRetryDelay: (ms: number) => Promise<void> }, 'waitForRetryDelay' as never)
168
+ .mockResolvedValue(undefined as never);
169
+
170
+ await action.testSendRequestWithRetry('https://api.test.com/v2/users', { method: 'GET' });
171
+
172
+ // Retry-After: 3 => 3000ms delay
173
+ expect(waitSpy).toHaveBeenCalledWith(3000);
174
+ });
175
+ });
176
+
177
+ describe('calculateRetryDelay', () => {
178
+ it('should use Retry-After header value when present', () => {
179
+ const delay = action.testCalculateRetryDelay(0, '5');
180
+
181
+ expect(delay).toBe(5000);
182
+ });
183
+
184
+ it('should cap Retry-After at MAX_DELAY_MS', () => {
185
+ const delay = action.testCalculateRetryDelay(0, '60');
186
+
187
+ expect(delay).toBe(30_000);
188
+ });
189
+
190
+ it('should ignore invalid Retry-After values and use exponential backoff', () => {
191
+ const delay = action.testCalculateRetryDelay(0, 'invalid');
192
+
193
+ // Attempt 0: BASE_DELAY_MS * 2^0 + jitter = 1000 + [0..1000)
194
+ expect(delay).toBeGreaterThanOrEqual(1000);
195
+ expect(delay).toBeLessThan(2000);
196
+ });
197
+
198
+ it('should use exponential backoff when no Retry-After header', () => {
199
+ const delay0 = action.testCalculateRetryDelay(0, null);
200
+ const delay2 = action.testCalculateRetryDelay(2, null);
201
+
202
+ // Attempt 0: 1000 * 2^0 + jitter => [1000, 2000)
203
+ expect(delay0).toBeGreaterThanOrEqual(1000);
204
+ expect(delay0).toBeLessThan(2000);
205
+
206
+ // Attempt 2: 1000 * 2^2 + jitter => [4000, 5000)
207
+ expect(delay2).toBeGreaterThanOrEqual(4000);
208
+ expect(delay2).toBeLessThan(5000);
209
+ });
210
+
211
+ it('should cap exponential backoff at MAX_DELAY_MS', () => {
212
+ const delay = action.testCalculateRetryDelay(10, null);
213
+
214
+ expect(delay).toBe(30_000);
215
+ });
216
+
217
+ it('should ignore zero or negative Retry-After values', () => {
218
+ const delayZero = action.testCalculateRetryDelay(0, '0');
219
+ const delayNeg = action.testCalculateRetryDelay(0, '-5');
220
+
221
+ // Both should fall back to exponential backoff
222
+ expect(delayZero).toBeGreaterThanOrEqual(1000);
223
+ expect(delayNeg).toBeGreaterThanOrEqual(1000);
224
+ });
225
+ });
226
+
227
+ describe('processInBatches with inter-batch delay', () => {
228
+ it('should add delay between batches but not before the first', async () => {
229
+ const waitSpy = vi.spyOn(action as unknown as { waitForRetryDelay: (ms: number) => Promise<void> }, 'waitForRetryDelay' as never)
230
+ .mockResolvedValue(undefined as never);
231
+
232
+ const items = [1, 2, 3, 4, 5, 6];
233
+ const processFn = vi.fn().mockImplementation((n: number) => Promise.resolve(n * 2));
234
+
235
+ const results = await action.testProcessInBatches(items, processFn, 2);
236
+
237
+ expect(results).toEqual([2, 4, 6, 8, 10, 12]);
238
+ // 3 batches of 2: delay before batch 2 and batch 3 (not before batch 1)
239
+ expect(waitSpy).toHaveBeenCalledTimes(2);
240
+ });
241
+
242
+ it('should not add delay when there is only one batch', async () => {
243
+ const waitSpy = vi.spyOn(action as unknown as { waitForRetryDelay: (ms: number) => Promise<void> }, 'waitForRetryDelay' as never)
244
+ .mockResolvedValue(undefined as never);
245
+
246
+ const items = [1, 2];
247
+ const processFn = vi.fn().mockImplementation((n: number) => Promise.resolve(n * 2));
248
+
249
+ const results = await action.testProcessInBatches(items, processFn, 5);
250
+
251
+ expect(results).toEqual([2, 4]);
252
+ expect(waitSpy).not.toHaveBeenCalled();
253
+ });
254
+ });
255
+
256
+ describe('proactive rate limiter', () => {
257
+ it('should allow requests when under capacity', async () => {
258
+ const mockResponse = createMockResponse(200, { data: 'ok' });
259
+ globalThis.fetch = vi.fn().mockResolvedValue(mockResponse);
260
+
261
+ // Make a few requests — well under the 25/10s limit
262
+ for (let i = 0; i < 3; i++) {
263
+ await action.testSendRequestWithRetry('https://api.test.com/v2/users', { method: 'GET' });
264
+ }
265
+
266
+ // All should have gone through without delays
267
+ expect(globalThis.fetch).toHaveBeenCalledTimes(3);
268
+ });
269
+
270
+ it('should share rate limiter state across instances', async () => {
271
+ const mockResponse = createMockResponse(200, { data: 'ok' });
272
+ globalThis.fetch = vi.fn().mockResolvedValue(mockResponse);
273
+
274
+ const action1 = new TestableLearnWorldsAction();
275
+ const action2 = new TestableLearnWorldsAction();
276
+
277
+ // Both instances share the same static rate limiter
278
+ await action1.testSendRequestWithRetry('https://api.test.com/v2/users', { method: 'GET' });
279
+ await action2.testSendRequestWithRetry('https://api.test.com/v2/courses', { method: 'GET' });
280
+
281
+ // Both should succeed (2 requests, well under limit)
282
+ expect(globalThis.fetch).toHaveBeenCalledTimes(2);
283
+ });
284
+
285
+ it('should reset cleanly between tests', async () => {
286
+ const mockResponse = createMockResponse(200, { data: 'ok' });
287
+ globalThis.fetch = vi.fn().mockResolvedValue(mockResponse);
288
+
289
+ // After resetRateLimiter() in afterEach, the window should be empty
290
+ TestableLearnWorldsAction.resetRateLimiter();
291
+
292
+ await action.testSendRequestWithRetry('https://api.test.com/v2/users', { method: 'GET' });
293
+ expect(globalThis.fetch).toHaveBeenCalledTimes(1);
294
+ });
295
+ });
296
+ });