@pie-qti/assessment-player 0.1.10 → 0.1.11

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 (86) hide show
  1. package/README.md +22 -82
  2. package/dist/core/AssessmentPlayer.d.ts +0 -1
  3. package/dist/core/AssessmentPlayer.js +1 -0
  4. package/dist/core/AssessmentPlayer.js.map +1 -0
  5. package/dist/core/AssessmentSessionCoordinator.d.ts +0 -1
  6. package/dist/core/AssessmentSessionCoordinator.js +1 -0
  7. package/dist/core/AssessmentSessionCoordinator.js.map +1 -0
  8. package/dist/core/ItemSessionController.d.ts +0 -1
  9. package/dist/core/ItemSessionController.js +1 -0
  10. package/dist/core/ItemSessionController.js.map +1 -0
  11. package/dist/core/NavigationManager.d.ts +0 -1
  12. package/dist/core/NavigationManager.js +1 -0
  13. package/dist/core/NavigationManager.js.map +1 -0
  14. package/dist/core/StatePersistenceManager.d.ts +0 -1
  15. package/dist/core/StatePersistenceManager.js +1 -0
  16. package/dist/core/StatePersistenceManager.js.map +1 -0
  17. package/dist/core/TimeManager.d.ts +0 -1
  18. package/dist/core/TimeManager.js +1 -0
  19. package/dist/core/TimeManager.js.map +1 -0
  20. package/dist/core/index.d.ts +0 -1
  21. package/dist/core/index.js +1 -0
  22. package/dist/core/index.js.map +1 -0
  23. package/dist/index.d.ts +0 -1
  24. package/dist/index.js +1 -3
  25. package/dist/index.js.map +1 -0
  26. package/dist/integration/ReferenceBackendAdapter.d.ts +0 -1
  27. package/dist/integration/ReferenceBackendAdapter.js +1 -0
  28. package/dist/integration/ReferenceBackendAdapter.js.map +1 -0
  29. package/dist/integration/api-contract.d.ts +0 -1
  30. package/dist/integration/api-contract.js +1 -0
  31. package/dist/integration/api-contract.js.map +1 -0
  32. package/dist/integration/assessment-item-scorer.d.ts +0 -1
  33. package/dist/integration/assessment-item-scorer.js +1 -0
  34. package/dist/integration/assessment-item-scorer.js.map +1 -0
  35. package/dist/integration/index.d.ts +0 -1
  36. package/dist/integration/index.js +1 -0
  37. package/dist/integration/index.js.map +1 -0
  38. package/dist/types/index.d.ts +0 -1
  39. package/dist/types/index.js +1 -0
  40. package/dist/types/index.js.map +1 -0
  41. package/dist/utils/PerformanceMonitor.d.ts +0 -1
  42. package/dist/utils/PerformanceMonitor.js +1 -0
  43. package/dist/utils/PerformanceMonitor.js.map +1 -0
  44. package/package.json +8 -37
  45. package/dist/core/AssessmentPlayer.d.ts.map +0 -1
  46. package/dist/core/AssessmentSessionCoordinator.d.ts.map +0 -1
  47. package/dist/core/ItemSessionController.d.ts.map +0 -1
  48. package/dist/core/NavigationManager.d.ts.map +0 -1
  49. package/dist/core/StatePersistenceManager.d.ts.map +0 -1
  50. package/dist/core/TimeManager.d.ts.map +0 -1
  51. package/dist/core/index.d.ts.map +0 -1
  52. package/dist/index.d.ts.map +0 -1
  53. package/dist/integration/ReferenceBackendAdapter.d.ts.map +0 -1
  54. package/dist/integration/api-contract.d.ts.map +0 -1
  55. package/dist/integration/assessment-item-scorer.d.ts.map +0 -1
  56. package/dist/integration/index.d.ts.map +0 -1
  57. package/dist/types/index.d.ts.map +0 -1
  58. package/dist/utils/PerformanceMonitor.d.ts.map +0 -1
  59. package/src/ambient.d.ts +0 -55
  60. package/src/components/AccessibilityAnnouncer.svelte +0 -113
  61. package/src/components/AssessmentHeader.svelte +0 -76
  62. package/src/components/AssessmentShell.svelte +0 -468
  63. package/src/components/AssessmentTimer.svelte +0 -251
  64. package/src/components/ItemRenderer.svelte +0 -156
  65. package/src/components/ItemSessionInfo.svelte +0 -241
  66. package/src/components/NavigationBar.svelte +0 -146
  67. package/src/components/RubricDisplay.svelte +0 -185
  68. package/src/components/SectionMenu.svelte +0 -273
  69. package/src/components/SplitPaneResizer.svelte +0 -288
  70. package/src/components/TestFeedback.svelte +0 -147
  71. package/src/components/index.ts +0 -19
  72. package/src/core/AssessmentPlayer.ts +0 -952
  73. package/src/core/AssessmentSessionCoordinator.ts +0 -274
  74. package/src/core/ItemSessionController.ts +0 -287
  75. package/src/core/NavigationManager.ts +0 -126
  76. package/src/core/StatePersistenceManager.ts +0 -344
  77. package/src/core/TimeManager.ts +0 -306
  78. package/src/core/index.ts +0 -15
  79. package/src/index.ts +0 -13
  80. package/src/integration/ReferenceBackendAdapter.ts +0 -1382
  81. package/src/integration/api-contract.ts +0 -480
  82. package/src/integration/assessment-item-scorer.ts +0 -58
  83. package/src/integration/index.ts +0 -77
  84. package/src/svelte-shims.d.ts +0 -7
  85. package/src/types/index.ts +0 -59
  86. package/src/utils/PerformanceMonitor.ts +0 -222
@@ -1,1382 +0,0 @@
1
- /**
2
- * Reference Backend Adapter - localStorage Implementation
3
- *
4
- * This is a REFERENCE IMPLEMENTATION demonstrating the BackendAdapter contract.
5
- * It uses localStorage for persistence and performs scoring CLIENT-SIDE.
6
- *
7
- * ## Security Warning
8
- *
9
- * This implementation is INSECURE for production use because:
10
- * - Scoring is done client-side (can be manipulated)
11
- * - QTI XML with correct answers is stored in client
12
- * - No authentication or authorization checks
13
- *
14
- * ## Purpose
15
- *
16
- * This adapter serves as:
17
- * 1. Reference implementation showing the API contract
18
- * 2. Development/demo tool for offline testing
19
- * 3. Template for building secure backend adapters
20
- *
21
- * ## Production Use
22
- *
23
- * Replace this with a real backend adapter that:
24
- * - Stores QTI XML server-side
25
- * - Performs scoring server-side
26
- * - Validates all requests with authentication
27
- * - Filters sensitive data based on role
28
- */
29
-
30
- import {
31
- buildExpression,
32
- buildOutcomeProcessingAst,
33
- DeclarationContext,
34
- type DeclarationMap,
35
- evalExpr,
36
- execProgram,
37
- OperatorRegistry,
38
- parseXml,
39
- serializeXml,
40
- type QtiValue,
41
- qtiNull,
42
- qtiValue,
43
- } from '@pie-qti/qti-processing';
44
- import {
45
- createResolvedItemDeliveryContext,
46
- extractAssessmentStimulusRefs,
47
- resolveRelativePath as resolveQtiRelativePath,
48
- } from '@pie-qti/ims-cp-core';
49
- import { parse } from 'node-html-parser';
50
- import type {
51
- AssessmentSessionState,
52
- AssessmentScoringResult,
53
- BackendAdapter,
54
- FinalizeAssessmentRequest,
55
- FinalizeAssessmentResponse,
56
- InitSessionRequest,
57
- InitSessionResponse,
58
- QueryItemBankRequest,
59
- QueryItemBankResponse,
60
- SaveAssessmentStateRequest,
61
- SaveAssessmentStateResponse,
62
- SecureAssessment,
63
- SecureItemRef,
64
- SecureSection,
65
- SecureTestPart,
66
- SessionId,
67
- SubmitResponsesRequest,
68
- SubmitResponsesResponse,
69
- } from './api-contract.js';
70
- import { scoreAssessmentItem } from './assessment-item-scorer.js';
71
-
72
- /**
73
- * Storage key prefix for localStorage
74
- */
75
- const STORAGE_PREFIX = 'qti_session_';
76
-
77
- /**
78
- * Cache key for item bank queries
79
- */
80
- const BANK_CACHE_PREFIX = 'qti_bank_cache_';
81
-
82
- function toCanonicalQtiName(name: string | null | undefined): string {
83
- const withoutPrefix = (name ?? '').replace(/^qti-/, '');
84
- return withoutPrefix.replace(/-([a-z])/g, (_, char: string) => char.toUpperCase());
85
- }
86
-
87
- const qtiElementNameMapper = {
88
- version: 'qti2x-or-qti3',
89
- toCanonical: (elementName: string) => toCanonicalQtiName(elementName).toLowerCase(),
90
- toNative: (canonicalName: string) => canonicalName,
91
- isValidElementName: () => true,
92
- };
93
-
94
- /**
95
- * Cache entry for item bank queries
96
- */
97
- interface BankCacheEntry {
98
- items: SecureItemRef[];
99
- timestamp: number;
100
- ttl: number; // milliseconds
101
- }
102
-
103
- /**
104
- * Stored session data (includes full QTI XML - INSECURE)
105
- */
106
- interface StoredSession {
107
- sessionId: SessionId;
108
- assessmentId: string;
109
- candidateId: string;
110
- /** Full assessment structure with QTI XML */
111
- assessment: SecureAssessment;
112
- /** Current state */
113
- state: AssessmentSessionState;
114
- /** Created timestamp */
115
- createdAt: number;
116
- /** Finalized flag */
117
- finalized: boolean;
118
- }
119
-
120
- /**
121
- * Reference Backend Adapter using localStorage
122
- *
123
- * @example
124
- * ```typescript
125
- * const adapter = new ReferenceBackendAdapter();
126
- * const response = await adapter.initSession({
127
- * assessmentId: 'test-001',
128
- * candidateId: 'student-123'
129
- * });
130
- * ```
131
- */
132
- export class ReferenceBackendAdapter implements BackendAdapter {
133
- private registeredAssessments: Map<string, SecureAssessment> = new Map();
134
-
135
- /**
136
- * Register/override a client-provided assessment structure for a given assessmentId.
137
- *
138
- * This is useful for demos or web-components that supply assessment XML directly.
139
- * Security: this remains a reference/demo adapter; production backends should not
140
- * accept client-authored assessments.
141
- */
142
- public registerAssessment(assessmentId: string, assessment: SecureAssessment) {
143
- this.registeredAssessments.set(assessmentId, assessment);
144
- }
145
-
146
- private getAssessment(assessmentId: string): SecureAssessment {
147
- return this.registeredAssessments.get(assessmentId) ?? this.createDemoAssessment(assessmentId);
148
- }
149
-
150
- private hasAnyResponse(responses: Record<string, unknown>): boolean {
151
- for (const value of Object.values(responses)) {
152
- if (value == null) continue;
153
- if (Array.isArray(value)) {
154
- if (value.length > 0) return true;
155
- continue;
156
- }
157
- if (typeof value === 'string') {
158
- if (value.trim().length > 0) return true;
159
- continue;
160
- }
161
- return true;
162
- }
163
- return false;
164
- }
165
-
166
- /**
167
- * Initialize a new assessment session
168
- */
169
- async initSession(request: InitSessionRequest): Promise<InitSessionResponse> {
170
- // Check if resuming existing session
171
- if (request.resumeSessionId) {
172
- const stored = this.loadSession(request.resumeSessionId);
173
- if (stored) {
174
- return {
175
- sessionId: stored.sessionId,
176
- assessment: stored.assessment,
177
- restoredState: stored.state,
178
- };
179
- }
180
- }
181
-
182
- // Create new session
183
- const sessionId = this.generateSessionId(request.assessmentId, request.candidateId);
184
-
185
- // In a real backend, you would:
186
- // 1. Fetch assessment from database
187
- // 2. Filter QTI XML based on role
188
- // 3. Remove responseProcessing for candidates
189
- //
190
- // For reference implementation, we'll use demo data
191
- const assessment = this.getAssessment(request.assessmentId);
192
-
193
- const state: AssessmentSessionState = {
194
- currentItemIdentifier: assessment.testParts[0].sections[0].assessmentItemRefs[0].identifier,
195
- visitedItems: [],
196
- itemResponses: {},
197
- itemScores: {},
198
- itemSessions: {},
199
- timing: {
200
- startedAt: Date.now(),
201
- itemTimes: {},
202
- totalTime: 0,
203
- },
204
- };
205
-
206
- const session: StoredSession = {
207
- sessionId,
208
- assessmentId: request.assessmentId,
209
- candidateId: request.candidateId,
210
- assessment,
211
- state,
212
- createdAt: Date.now(),
213
- finalized: false,
214
- };
215
-
216
- this.saveSession(session);
217
-
218
- return {
219
- sessionId,
220
- assessment,
221
- };
222
- }
223
-
224
- /**
225
- * Submit responses and get scoring result
226
- */
227
- async submitResponses(request: SubmitResponsesRequest): Promise<SubmitResponsesResponse> {
228
- const session = this.loadSession(request.sessionId);
229
- if (!session) {
230
- return {
231
- success: false,
232
- error: 'Session not found',
233
- };
234
- }
235
-
236
- if (session.finalized) {
237
- return {
238
- success: false,
239
- error: 'Session already finalized',
240
- };
241
- }
242
-
243
- const receivedAt = Date.now();
244
- const assessmentLimit = session.assessment.timeLimits;
245
- const effectiveAssessmentLimitSeconds =
246
- request.timing?.scope === 'assessment' && request.timing.limitSeconds !== undefined
247
- ? request.timing.limitSeconds
248
- : assessmentLimit?.maxTime;
249
- const assessmentAllowsLate = assessmentLimit?.allowLateSubmission ?? request.timing?.allowLateSubmission;
250
- if (
251
- effectiveAssessmentLimitSeconds !== undefined &&
252
- assessmentAllowsLate !== true &&
253
- receivedAt - session.createdAt > effectiveAssessmentLimitSeconds * 1000
254
- ) {
255
- return {
256
- success: false,
257
- error: 'Assessment time limit expired',
258
- };
259
- }
260
-
261
- const evidenceExpired =
262
- request.timing?.limitSeconds !== undefined &&
263
- request.timing.elapsedMs >= request.timing.limitSeconds * 1000;
264
- if (evidenceExpired && request.timing?.allowLateSubmission !== true) {
265
- return {
266
- success: false,
267
- error: 'Time limit expired',
268
- };
269
- }
270
-
271
- // Find the item XML
272
- const itemXml = this.findItemXml(session.assessment, request.itemIdentifier);
273
- if (!itemXml) {
274
- return {
275
- success: false,
276
- error: 'Item not found',
277
- };
278
- }
279
-
280
- // **SECURITY WARNING**: Client-side scoring is INSECURE
281
- // In production, this MUST be done server-side
282
- const result = scoreAssessmentItem({ itemXml, responses: request.responses, itemSession: request.itemSession });
283
-
284
- // Store responses and result
285
- session.state.itemResponses[request.itemIdentifier] = request.responses;
286
- if (!session.state.itemScores) {
287
- session.state.itemScores = {};
288
- }
289
- session.state.itemScores[request.itemIdentifier] = result;
290
- if (request.itemSession) {
291
- session.state.itemSessions = {
292
- ...(session.state.itemSessions ?? {}),
293
- [request.itemIdentifier]: request.itemSession,
294
- };
295
- }
296
- const previousItemSession = session.state.itemSessionStates?.[request.itemIdentifier];
297
- session.state.itemSessionStates = {
298
- ...(session.state.itemSessionStates ?? {}),
299
- [request.itemIdentifier]: {
300
- itemIdentifier: request.itemIdentifier,
301
- attemptCount: (previousItemSession?.attemptCount ?? 0) + 1,
302
- isAnswered: this.hasAnyResponse(request.responses),
303
- isSubmitted: true,
304
- lastSubmissionTime: request.submittedAt,
305
- },
306
- };
307
-
308
- // Update timing
309
- if (request.timeSpent) {
310
- session.state.timing.itemTimes[request.itemIdentifier] = request.timeSpent;
311
- }
312
-
313
- // Add to visited items if not already there
314
- if (!session.state.visitedItems.includes(request.itemIdentifier)) {
315
- session.state.visitedItems.push(request.itemIdentifier);
316
- }
317
-
318
- this.saveSession(session);
319
-
320
- const order = this.getItemOrder(session.assessment);
321
- const idx = order.indexOf(request.itemIdentifier);
322
- let nextItemIdentifier: string | undefined = idx >= 0 ? order[idx + 1] : undefined;
323
-
324
- // QTI branchRule evaluation (backend-authoritative).
325
- // Evaluate each rule in order; the first matching rule determines the next item.
326
- // Special targets EXIT_TEST / EXIT_TESTPART / EXIT_SECTION are returned as-is for
327
- // the client to interpret.
328
- const itemRef = this.findItemRef(session.assessment, request.itemIdentifier);
329
- if (itemRef?.branchRule && itemRef.branchRule.length > 0) {
330
- const outcomeVars: Record<string, unknown> = {
331
- ...result.outcomeValues,
332
- SCORE: result.score,
333
- };
334
- nextItemIdentifier = undefined; // reset — branch rules take full control
335
- for (const rule of itemRef.branchRule) {
336
- const matches = rule.conditionXml
337
- ? this.evaluateConditionXml(rule.conditionXml, outcomeVars)
338
- : true; // unconditional branch
339
- if (matches) {
340
- nextItemIdentifier = rule.target;
341
- break;
342
- }
343
- }
344
- }
345
-
346
- return {
347
- success: true,
348
- result,
349
- nextItemIdentifier,
350
- updatedState: session.state,
351
- };
352
- }
353
-
354
- /**
355
- * Save session state (for auto-save)
356
- */
357
- async saveState(request: SaveAssessmentStateRequest): Promise<SaveAssessmentStateResponse> {
358
- const session = this.loadSession(request.sessionId);
359
- if (!session) {
360
- return {
361
- success: false,
362
- savedAt: Date.now(),
363
- };
364
- }
365
-
366
- // Update state
367
- session.state = request.state;
368
- this.saveSession(session);
369
-
370
- return {
371
- success: true,
372
- savedAt: Date.now(),
373
- };
374
- }
375
-
376
- /**
377
- * Finalize assessment and compute final scores
378
- */
379
- async finalizeAssessment(
380
- request: FinalizeAssessmentRequest
381
- ): Promise<FinalizeAssessmentResponse> {
382
- const session = this.loadSession(request.sessionId);
383
- if (!session) {
384
- return {
385
- success: false,
386
- totalScore: 0,
387
- maxScore: 0,
388
- itemScores: {},
389
- finalizedAt: Date.now(),
390
- };
391
- }
392
-
393
- // Mark as finalized
394
- session.finalized = true;
395
- this.saveSession(session);
396
-
397
- // Compute total score
398
- const itemScores = session.state.itemScores || {};
399
- const fallbackTotal = Object.values(itemScores).reduce((sum, result) => sum + result.score, 0);
400
- const maxScore = Object.values(itemScores).reduce((sum, result) => sum + result.maxScore, 0);
401
-
402
- // Execute test-level outcome processing if available
403
- const outcomes = this.runOutcomeProcessing(session.assessment, itemScores);
404
- const totalScore = outcomes !== null ? (outcomes['SCORE_TOTAL'] ?? outcomes['SCORE'] ?? fallbackTotal) as number : fallbackTotal;
405
-
406
- return {
407
- success: true,
408
- totalScore,
409
- maxScore,
410
- itemScores,
411
- finalizedAt: Date.now(),
412
- };
413
- }
414
-
415
- /**
416
- * Execute test-level outcome processing (T9/T1).
417
- * Returns a map of outcome variable values, or null if no outcomeProcessing is defined.
418
- */
419
- private runOutcomeProcessing(
420
- assessment: SecureAssessment,
421
- itemScores: Record<string, AssessmentScoringResult>
422
- ): Record<string, unknown> | null {
423
- if (!assessment.outcomeProcessingXml) {
424
- return null;
425
- }
426
-
427
- try {
428
- // Build declaration map from outcomeDeclarations
429
- const decls: DeclarationMap = {};
430
- for (const d of assessment.outcomeDeclarations || []) {
431
- const baseType = d.baseType as any;
432
- const cardinality = d.cardinality as any;
433
- let defaultQtiValue: QtiValue;
434
- if (d.defaultValue !== undefined) {
435
- defaultQtiValue = qtiValue(baseType, cardinality, d.defaultValue);
436
- } else if (baseType === 'float' || baseType === 'integer') {
437
- defaultQtiValue = qtiValue(baseType, 'single', 0);
438
- } else {
439
- defaultQtiValue = qtiNull();
440
- }
441
- decls[d.identifier] = {
442
- identifier: d.identifier,
443
- baseType,
444
- cardinality,
445
- defaultValue: defaultQtiValue,
446
- value: { ...defaultQtiValue },
447
- };
448
- }
449
-
450
- const ctx = new DeclarationContext(decls);
451
- const ops = new OperatorRegistry();
452
-
453
- // Build test items array for testVariables expression
454
- const testItems = Object.entries(itemScores).map(([id, scoring]) => ({
455
- identifier: id,
456
- variables: {
457
- SCORE: qtiValue('float', 'single', scoring.score),
458
- // Add any other outcome values from the scoring result
459
- ...Object.fromEntries(
460
- Object.entries(scoring.outcomeValues || {}).map(([k, v]) => [
461
- k,
462
- typeof v === 'number'
463
- ? qtiValue('float', 'single', v)
464
- : qtiValue('string', 'single', String(v)),
465
- ])
466
- ),
467
- },
468
- }));
469
-
470
- // Parse and execute outcome processing
471
- const opEl = parseXml(assessment.outcomeProcessingXml).documentElement;
472
- if (!opEl) return null;
473
-
474
- const program = buildOutcomeProcessingAst(opEl, {
475
- scope: 'test',
476
- elementNameMapper: qtiElementNameMapper,
477
- });
478
- execProgram(
479
- {
480
- ctx,
481
- ops,
482
- rng: Math.random,
483
- test: { items: testItems },
484
- },
485
- program
486
- );
487
-
488
- // Extract outcome values
489
- const result: Record<string, unknown> = {};
490
- for (const d of assessment.outcomeDeclarations || []) {
491
- const v = ctx.getValue(d.identifier);
492
- if (v.kind === 'value') {
493
- result[d.identifier] = v.value;
494
- }
495
- }
496
- return result;
497
- } catch (err) {
498
- console.warn('[ReferenceBackendAdapter] outcomeProcessing failed:', err);
499
- return null;
500
- }
501
- }
502
-
503
- /**
504
- * Resume existing session (alias for initSession with resumeSessionId)
505
- */
506
- async resumeSession(sessionId: SessionId): Promise<InitSessionResponse> {
507
- return this.initSession({
508
- assessmentId: '',
509
- candidateId: '',
510
- resumeSessionId: sessionId,
511
- });
512
- }
513
-
514
- /**
515
- * Query item bank for random item selection
516
- *
517
- * This reference implementation:
518
- * - Caches bank queries to avoid repeated calls
519
- * - Implements retry logic with exponential backoff
520
- * - Returns demo items (in production, fetch from real item bank)
521
- *
522
- * @param request - Item bank query request
523
- * @returns Selected items from bank
524
- */
525
- async queryItemBank(request: QueryItemBankRequest): Promise<QueryItemBankResponse> {
526
- const { sessionId, bankId, count, withReplacement, filters } = request;
527
-
528
- // Validate session exists
529
- const session = this.loadSession(sessionId);
530
- if (!session) {
531
- throw new Error(`Session not found: ${sessionId}`);
532
- }
533
-
534
- // Check cache first
535
- const cacheKey = this.getBankCacheKey(sessionId, bankId, count, withReplacement, filters);
536
- const cached = this.loadBankCache(cacheKey);
537
- if (cached) {
538
- return {
539
- items: cached.items,
540
- selectedAt: cached.timestamp,
541
- };
542
- }
543
-
544
- // Simulate network call with retry logic
545
- const items = await this.fetchItemsFromBank(bankId, count, withReplacement, filters);
546
-
547
- // Cache the result (5 minute TTL)
548
- this.saveBankCache(cacheKey, {
549
- items,
550
- timestamp: Date.now(),
551
- ttl: 5 * 60 * 1000, // 5 minutes
552
- });
553
-
554
- return {
555
- items,
556
- selectedAt: Date.now(),
557
- };
558
- }
559
-
560
- // =========================================================================
561
- // PRIVATE HELPERS
562
- // =========================================================================
563
-
564
- private generateSessionId(assessmentId: string, candidateId: string): SessionId {
565
- return `${assessmentId}:${candidateId}:${Date.now()}`;
566
- }
567
-
568
- private loadSession(sessionId: SessionId): StoredSession | null {
569
- try {
570
- const key = STORAGE_PREFIX + sessionId;
571
- const data = localStorage.getItem(key);
572
- if (!data) return null;
573
- return JSON.parse(data) as StoredSession;
574
- } catch {
575
- return null;
576
- }
577
- }
578
-
579
- private saveSession(session: StoredSession): void {
580
- try {
581
- const key = STORAGE_PREFIX + session.sessionId;
582
- localStorage.setItem(key, JSON.stringify(session));
583
- } catch (error) {
584
- console.error('Failed to save session to localStorage:', error);
585
- }
586
- }
587
-
588
- private findItemXml(assessment: SecureAssessment, itemIdentifier: string): string | null {
589
- for (const part of assessment.testParts) {
590
- for (const section of part.sections) {
591
- for (const item of section.assessmentItemRefs) {
592
- if (item.identifier === itemIdentifier) {
593
- return item.itemXml;
594
- }
595
- }
596
- }
597
- }
598
- return null;
599
- }
600
-
601
- private findItemRef(assessment: SecureAssessment, itemIdentifier: string): SecureItemRef | null {
602
- for (const part of assessment.testParts) {
603
- for (const section of part.sections) {
604
- for (const item of section.assessmentItemRefs) {
605
- if (item.identifier === itemIdentifier) {
606
- return item;
607
- }
608
- }
609
- }
610
- }
611
- return null;
612
- }
613
-
614
- /**
615
- * Create demo assessment for testing
616
- *
617
- * In production, this would fetch from database
618
- */
619
- private createDemoAssessment(assessmentId: string): SecureAssessment {
620
- // This is a minimal demo assessment
621
- // In production, load from database and filter based on role
622
- return {
623
- identifier: assessmentId,
624
- title: 'Demo Assessment',
625
- navigationMode: 'nonlinear',
626
- submissionMode: 'simultaneous',
627
- testParts: [
628
- {
629
- identifier: 'part1',
630
- rubricBlocks: [],
631
- itemSessionControl: {
632
- maxAttempts: 1,
633
- showFeedback: true,
634
- allowReview: true,
635
- showSolution: false,
636
- allowComment: false,
637
- allowSkipping: true,
638
- validateResponses: true,
639
- },
640
- sections: [
641
- {
642
- identifier: 'section1',
643
- title: 'Section 1',
644
- visible: true,
645
- assessmentItemRefs: [
646
- {
647
- identifier: 'item1',
648
- role: 'candidate',
649
- // In production, load from database
650
- // For candidates, responseProcessing should be removed server-side
651
- itemXml: `<assessmentItem identifier="item1" title="Sample Item" adaptive="false" timeDependent="false">
652
- <responseDeclaration identifier="RESPONSE" cardinality="single" baseType="identifier">
653
- <correctResponse>
654
- <value>A</value>
655
- </correctResponse>
656
- </responseDeclaration>
657
- <outcomeDeclaration identifier="SCORE" cardinality="single" baseType="float">
658
- <defaultValue>
659
- <value>0</value>
660
- </defaultValue>
661
- </outcomeDeclaration>
662
- <itemBody>
663
- <p>What is 2 + 2?</p>
664
- <choiceInteraction responseIdentifier="RESPONSE" shuffle="false" maxChoices="1">
665
- <simpleChoice identifier="A">4</simpleChoice>
666
- <simpleChoice identifier="B">3</simpleChoice>
667
- <simpleChoice identifier="C">5</simpleChoice>
668
- </choiceInteraction>
669
- </itemBody>
670
- <responseProcessing>
671
- <responseCondition>
672
- <responseIf>
673
- <match>
674
- <variable identifier="RESPONSE" />
675
- <correct identifier="RESPONSE" />
676
- </match>
677
- <setOutcomeValue identifier="SCORE">
678
- <baseValue baseType="float">1</baseValue>
679
- </setOutcomeValue>
680
- </responseIf>
681
- <responseElse>
682
- <setOutcomeValue identifier="SCORE">
683
- <baseValue baseType="float">0</baseValue>
684
- </setOutcomeValue>
685
- </responseElse>
686
- </responseCondition>
687
- </responseProcessing>
688
- </assessmentItem>`,
689
- },
690
- {
691
- identifier: 'item2',
692
- role: 'candidate',
693
- itemXml: `<assessmentItem identifier="item2" title="Follow-up Item" adaptive="false" timeDependent="false">
694
- <responseDeclaration identifier="RESPONSE" cardinality="single" baseType="identifier">
695
- <correctResponse>
696
- <value>A</value>
697
- </correctResponse>
698
- </responseDeclaration>
699
- <outcomeDeclaration identifier="SCORE" cardinality="single" baseType="float">
700
- <defaultValue>
701
- <value>0</value>
702
- </defaultValue>
703
- </outcomeDeclaration>
704
- <itemBody>
705
- <p>Demo follow-up item</p>
706
- <choiceInteraction responseIdentifier="RESPONSE" shuffle="false" maxChoices="1">
707
- <simpleChoice identifier="A">ok</simpleChoice>
708
- <simpleChoice identifier="B">no</simpleChoice>
709
- </choiceInteraction>
710
- </itemBody>
711
- <responseProcessing>
712
- <responseCondition>
713
- <responseIf>
714
- <match>
715
- <variable identifier="RESPONSE" />
716
- <correct identifier="RESPONSE" />
717
- </match>
718
- <setOutcomeValue identifier="SCORE">
719
- <baseValue baseType="float">1</baseValue>
720
- </setOutcomeValue>
721
- </responseIf>
722
- </responseCondition>
723
- </responseProcessing>
724
- </assessmentItem>`,
725
- },
726
- ],
727
- },
728
- ],
729
- },
730
- ],
731
- };
732
- }
733
-
734
- // =========================================================================
735
- // STATIC: QTI TEST XML PARSER
736
- // =========================================================================
737
-
738
- /**
739
- * Parse a QTI assessmentTest XML string into a SecureAssessment structure.
740
- *
741
- * Handles:
742
- * - S1: section-level itemSessionControl
743
- * - S9: assessmentSectionRef href resolution (requires fileResolver)
744
- * - T9/T1: outcomeDeclarations + outcomeProcessing extraction
745
- *
746
- * @param testXml - Raw QTI assessmentTest XML string
747
- * @param options.role - Role to assign to items (default: 'candidate')
748
- * @param options.itemXmlMap - Map of item identifier -> itemXml for pre-loaded items
749
- * @param options.fileResolver - Async function to load external files by relative href
750
- * @param options.baseUrl - Base URL for resolving relative hrefs
751
- */
752
- static async parseAssessmentTestXml(
753
- testXml: string,
754
- options: {
755
- role?: SecureItemRef['role'];
756
- itemXmlMap?: Record<string, string>;
757
- fileResolver?: (href: string) => Promise<string>;
758
- baseUrl?: string;
759
- } = {}
760
- ): Promise<SecureAssessment> {
761
- const { role = 'candidate', itemXmlMap = {}, fileResolver, baseUrl } = options;
762
- const doc = parseXml(testXml);
763
- const root = doc.documentElement;
764
- if (!root) throw new Error('Empty assessmentTest XML');
765
-
766
- const getAttr = (el: Element, name: string): string | undefined => {
767
- const direct = el.getAttribute(name);
768
- if (direct !== null && direct !== '') return direct;
769
- const mapped = el.getAttribute(name.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`));
770
- return mapped === null || mapped === '' ? undefined : mapped;
771
- };
772
-
773
- const childElements = (el: Element): Element[] =>
774
- Array.from(el.childNodes).filter((n): n is Element => n.nodeType === 1);
775
-
776
- const childrenByTag = (el: Element, tag: string): Element[] =>
777
- childElements(el).filter((c) => toCanonicalQtiName(c.localName) === tag);
778
-
779
- // Parse itemSessionControl element
780
- const parseItemSessionControl = (
781
- el: Element
782
- ): SecureSection['itemSessionControl'] | undefined => {
783
- const isc = childrenByTag(el, 'itemSessionControl')[0];
784
- if (!isc) return undefined;
785
- const boolAttr = (name: string): boolean | undefined => {
786
- const v = getAttr(isc, name);
787
- return v === undefined ? undefined : v !== 'false';
788
- };
789
- const intAttr = (name: string): number | undefined => {
790
- const v = getAttr(isc, name);
791
- return v === undefined ? undefined : parseInt(v, 10);
792
- };
793
- return {
794
- maxAttempts: intAttr('maxAttempts'),
795
- showFeedback: boolAttr('showFeedback') ?? boolAttr('show-feedback'),
796
- allowReview: boolAttr('allowReview') ?? boolAttr('allow-review'),
797
- showSolution: boolAttr('showSolution') ?? boolAttr('show-solution'),
798
- allowComment: boolAttr('allowComment') ?? boolAttr('allow-comment'),
799
- allowSkipping: boolAttr('allowSkipping') ?? boolAttr('allow-skipping'),
800
- validateResponses: boolAttr('validateResponses') ?? boolAttr('validate-responses'),
801
- };
802
- };
803
-
804
- const parseTimeLimits = (el: Element): SecureAssessment['timeLimits'] | undefined => {
805
- const limitsEl = childrenByTag(el, 'timeLimit')[0] ?? childrenByTag(el, 'timeLimits')[0];
806
- if (!limitsEl) return undefined;
807
- const numberAttr = (name: string): number | undefined => {
808
- const value = getAttr(limitsEl, name);
809
- if (value === undefined) return undefined;
810
- const parsed = Number(value);
811
- return Number.isFinite(parsed) ? parsed : undefined;
812
- };
813
- const boolAttr = (name: string): boolean | undefined => {
814
- const value = getAttr(limitsEl, name);
815
- return value === undefined ? undefined : value === 'true';
816
- };
817
- return {
818
- minTime: numberAttr('minTime'),
819
- maxTime: numberAttr('maxTime'),
820
- allowLateSubmission: boolAttr('allowLateSubmission'),
821
- };
822
- };
823
-
824
- const resolveAgainstBase = (href: string | undefined): string | undefined => {
825
- if (!href) return undefined;
826
- return baseUrl ? resolveQtiRelativePath(baseUrl, href) : href;
827
- };
828
-
829
- const loadText = async (href: string | undefined): Promise<string | undefined> => {
830
- if (!href) return undefined;
831
- const candidates = [href, resolveAgainstBase(href)].filter((value, index, all): value is string =>
832
- Boolean(value) && all.indexOf(value) === index
833
- );
834
- for (const candidate of candidates) {
835
- if (itemXmlMap[candidate] !== undefined) {
836
- return itemXmlMap[candidate];
837
- }
838
- }
839
- if (!fileResolver) return undefined;
840
- for (const candidate of candidates) {
841
- try {
842
- return await fileResolver(candidate);
843
- } catch {
844
- // Try the next candidate before giving up.
845
- }
846
- }
847
- return undefined;
848
- };
849
-
850
- const buildDeliveryContext = async (
851
- itemXml: string,
852
- itemHref: string | undefined
853
- ): Promise<SecureItemRef['deliveryContext'] | undefined> => {
854
- if (!itemHref || extractAssessmentStimulusRefs(itemXml).length === 0) {
855
- return undefined;
856
- }
857
- const stimulusXmlByPath: Record<string, string> = {};
858
- for (const ref of extractAssessmentStimulusRefs(itemXml)) {
859
- const stimulusPath = resolveQtiRelativePath(itemHref, ref.href);
860
- const stimulusXml = await loadText(stimulusPath);
861
- if (stimulusXml) {
862
- stimulusXmlByPath[stimulusPath] = stimulusXml;
863
- }
864
- }
865
- return createResolvedItemDeliveryContext({
866
- itemXml,
867
- itemHref,
868
- readText: (path) => stimulusXmlByPath[path] ?? itemXmlMap[path],
869
- });
870
- };
871
-
872
- // Parse a single assessmentSection element
873
- const parseSection = async (sectionEl: Element): Promise<SecureSection> => {
874
- const identifier = getAttr(sectionEl, 'identifier') ?? 'section';
875
- const title = getAttr(sectionEl, 'title');
876
- const visibleRaw = getAttr(sectionEl, 'visible');
877
- const visible = visibleRaw === undefined ? true : visibleRaw !== 'false';
878
-
879
- const itemSessionControl = parseItemSessionControl(sectionEl);
880
- const timeLimits = parseTimeLimits(sectionEl);
881
-
882
- // rubricBlocks
883
- const rubricBlockEls = childrenByTag(sectionEl, 'rubricBlock');
884
- const rubricBlocks = rubricBlockEls.length > 0
885
- ? rubricBlockEls.map((b, idx) => ({
886
- identifier: getAttr(b, 'identifier') ?? `${identifier}-rubric-${idx + 1}`,
887
- view: (getAttr(b, 'view') ?? 'candidate').split(/\s+/).filter(Boolean) as any[],
888
- use: getAttr(b, 'use'),
889
- content: serializeXml(b),
890
- }))
891
- : undefined;
892
-
893
- // assessmentItemRefs
894
- const itemRefEls = childrenByTag(sectionEl, 'assessmentItemRef');
895
- const assessmentItemRefs: SecureItemRef[] = [];
896
- for (const ref of itemRefEls) {
897
- const itemId = getAttr(ref, 'identifier') ?? 'item';
898
- const href = getAttr(ref, 'href');
899
- const itemHref = resolveAgainstBase(href) ?? href;
900
- // Look up pre-loaded XML by identifier or href
901
- const resolvedXml = itemXmlMap[itemId] ?? (href ? itemXmlMap[href] : undefined) ?? (itemHref ? itemXmlMap[itemHref] : undefined) ?? (await loadText(href)) ?? '';
902
- const requiredRaw = getAttr(ref, 'required');
903
- const required = requiredRaw === undefined ? undefined : requiredRaw !== 'false';
904
- assessmentItemRefs.push({
905
- identifier: itemId,
906
- itemXml: resolvedXml,
907
- role,
908
- required,
909
- timeLimits: parseTimeLimits(ref),
910
- deliveryContext: await buildDeliveryContext(resolvedXml, itemHref),
911
- });
912
- }
913
-
914
- return {
915
- identifier,
916
- title,
917
- visible,
918
- assessmentItemRefs,
919
- rubricBlocks,
920
- itemSessionControl,
921
- timeLimits,
922
- };
923
- };
924
-
925
- // Resolve assessmentSectionRef: load and parse referenced section file
926
- const resolveSectionRef = async (sectionRefEl: Element): Promise<SecureSection | null> => {
927
- const href = getAttr(sectionRefEl, 'href');
928
- if (!href) {
929
- console.warn('[ReferenceBackendAdapter] assessmentSectionRef missing href, skipping');
930
- return null;
931
- }
932
-
933
- if (!fileResolver) {
934
- console.warn(
935
- `[ReferenceBackendAdapter] assessmentSectionRef href="${href}" found but no fileResolver provided, skipping`
936
- );
937
- return null;
938
- }
939
-
940
- try {
941
- const sectionXml = await fileResolver(href);
942
- const secDoc = parseXml(sectionXml);
943
- const secRoot = secDoc.documentElement;
944
- if (!secRoot || toCanonicalQtiName(secRoot.localName) !== 'assessmentSection') {
945
- console.warn(
946
- `[ReferenceBackendAdapter] assessmentSectionRef href="${href}": root element is not <assessmentSection>, skipping`
947
- );
948
- return null;
949
- }
950
- return parseSection(secRoot);
951
- } catch (err) {
952
- console.warn(
953
- `[ReferenceBackendAdapter] Failed to load assessmentSectionRef href="${href}":`,
954
- err
955
- );
956
- return null;
957
- }
958
- };
959
-
960
- // Parse testPart children (sections + sectionRefs)
961
- const parseSectionsForTestPart = async (testPartEl: Element): Promise<SecureSection[]> => {
962
- const sections: SecureSection[] = [];
963
- for (const child of childElements(testPartEl)) {
964
- if (toCanonicalQtiName(child.localName) === 'assessmentSection') {
965
- sections.push(await parseSection(child));
966
- } else if (toCanonicalQtiName(child.localName) === 'assessmentSectionRef') {
967
- const resolved = await resolveSectionRef(child);
968
- if (resolved) sections.push(resolved);
969
- }
970
- }
971
- return sections;
972
- };
973
-
974
- // Parse testPart-level itemSessionControl
975
- const parseTestPartItemSessionControl = (
976
- testPartEl: Element
977
- ): SecureTestPart['itemSessionControl'] | undefined => {
978
- const isc = childrenByTag(testPartEl, 'itemSessionControl')[0];
979
- if (!isc) return undefined;
980
- const boolAttr = (name: string): boolean | undefined => {
981
- const v = getAttr(isc, name);
982
- return v === undefined ? undefined : v !== 'false';
983
- };
984
- const intAttr = (name: string): number | undefined => {
985
- const v = getAttr(isc, name);
986
- return v === undefined ? undefined : parseInt(v, 10);
987
- };
988
- return {
989
- maxAttempts: intAttr('maxAttempts'),
990
- showFeedback: boolAttr('showFeedback') ?? boolAttr('show-feedback'),
991
- allowReview: boolAttr('allowReview') ?? boolAttr('allow-review'),
992
- showSolution: boolAttr('showSolution') ?? boolAttr('show-solution'),
993
- allowComment: boolAttr('allowComment') ?? boolAttr('allow-comment'),
994
- allowSkipping: boolAttr('allowSkipping') ?? boolAttr('allow-skipping'),
995
- validateResponses: boolAttr('validateResponses') ?? boolAttr('validate-responses'),
996
- };
997
- };
998
-
999
- // Extract outcomeDeclarations
1000
- const outcomeDeclarations = childrenByTag(root, 'outcomeDeclaration').map((d) => {
1001
- const identifier = getAttr(d, 'identifier') ?? 'OUTCOME';
1002
- const baseType = getAttr(d, 'baseType') ?? 'float';
1003
- const cardinality = getAttr(d, 'cardinality') ?? 'single';
1004
- // Parse defaultValue if present
1005
- const defaultValueEl = childrenByTag(d, 'defaultValue')[0];
1006
- let defaultValue: unknown = undefined;
1007
- if (defaultValueEl) {
1008
- const valueEl = childrenByTag(defaultValueEl, 'value')[0];
1009
- if (valueEl) {
1010
- const text = valueEl.textContent?.trim() ?? '0';
1011
- if (baseType === 'float' || baseType === 'integer') {
1012
- defaultValue = Number(text);
1013
- } else {
1014
- defaultValue = text;
1015
- }
1016
- }
1017
- }
1018
- return { identifier, baseType, cardinality, defaultValue };
1019
- });
1020
-
1021
- // Extract outcomeProcessing XML
1022
- const outcomeProcessingEl = childrenByTag(root, 'outcomeProcessing')[0];
1023
- const outcomeProcessingXml = outcomeProcessingEl
1024
- ? serializeXml(outcomeProcessingEl)
1025
- : undefined;
1026
-
1027
- // Extract assessment-level timeLimits.
1028
- const timeLimits = parseTimeLimits(root);
1029
-
1030
- // Parse testParts
1031
- const testPartEls = childrenByTag(root, 'testPart');
1032
- const firstTestPart = testPartEls[0];
1033
-
1034
- // Navigation/submission mode from first testPart (QTI 2.2 spec)
1035
- const navigationMode = (getAttr(firstTestPart ?? root, 'navigationMode') ?? 'nonlinear') as
1036
- | 'linear'
1037
- | 'nonlinear';
1038
- const submissionMode = (getAttr(firstTestPart ?? root, 'submissionMode') ?? 'simultaneous') as
1039
- | 'individual'
1040
- | 'simultaneous';
1041
-
1042
- const testParts: SecureTestPart[] = [];
1043
- for (const tp of testPartEls) {
1044
- const tpIdentifier = getAttr(tp, 'identifier') ?? 'part-1';
1045
- const tpItemSessionControl = parseTestPartItemSessionControl(tp);
1046
- const tpTimeLimits = parseTimeLimits(tp);
1047
- const tpRubricBlockEls = childrenByTag(tp, 'rubricBlock');
1048
- const tpRubricBlocks = tpRubricBlockEls.length > 0
1049
- ? tpRubricBlockEls.map((b, idx) => ({
1050
- identifier: getAttr(b, 'identifier') ?? `${tpIdentifier}-rubric-${idx + 1}`,
1051
- view: (getAttr(b, 'view') ?? 'candidate').split(/\s+/).filter(Boolean) as any[],
1052
- use: getAttr(b, 'use'),
1053
- content: serializeXml(b),
1054
- }))
1055
- : undefined;
1056
-
1057
- const sections = await parseSectionsForTestPart(tp);
1058
- testParts.push({
1059
- identifier: tpIdentifier,
1060
- sections,
1061
- rubricBlocks: tpRubricBlocks,
1062
- itemSessionControl: tpItemSessionControl,
1063
- timeLimits: tpTimeLimits,
1064
- });
1065
- }
1066
-
1067
- // If no testParts, try top-level sections
1068
- if (testParts.length === 0) {
1069
- const topSections: SecureSection[] = [];
1070
- for (const child of childElements(root)) {
1071
- if (toCanonicalQtiName(child.localName) === 'assessmentSection') {
1072
- topSections.push(await parseSection(child));
1073
- } else if (toCanonicalQtiName(child.localName) === 'assessmentSectionRef') {
1074
- const resolved = await resolveSectionRef(child);
1075
- if (resolved) topSections.push(resolved);
1076
- }
1077
- }
1078
- if (topSections.length > 0) {
1079
- testParts.push({
1080
- identifier: 'part-1',
1081
- sections: topSections,
1082
- });
1083
- }
1084
- }
1085
-
1086
- return {
1087
- identifier: getAttr(root, 'identifier') ?? 'assessment',
1088
- title: getAttr(root, 'title') ?? 'Assessment',
1089
- navigationMode,
1090
- submissionMode,
1091
- testParts,
1092
- timeLimits,
1093
- outcomeDeclarations: outcomeDeclarations.length > 0 ? outcomeDeclarations : undefined,
1094
- outcomeProcessingXml,
1095
- baseUrl,
1096
- };
1097
- }
1098
-
1099
- private evaluateConditionXml(conditionXml: string, vars: Record<string, unknown>): boolean {
1100
- // conditionXml is an operator element like <gt>...</gt> (not wrapped in <expression>).
1101
- const doc = parseXml(conditionXml);
1102
- const root = doc.documentElement;
1103
- if (!root) return false;
1104
-
1105
- const decls: DeclarationMap = {};
1106
- for (const [k, raw] of Object.entries(vars)) {
1107
- let v: QtiValue = qtiNull();
1108
- if (typeof raw === 'number') v = qtiValue('float', 'single', raw);
1109
- else if (typeof raw === 'boolean') v = qtiValue('boolean', 'single', raw);
1110
- else if (typeof raw === 'string') v = qtiValue('string', 'single', raw);
1111
- decls[k] = {
1112
- identifier: k,
1113
- baseType: v.kind === 'value' ? v.baseType : 'string',
1114
- cardinality: 'single',
1115
- defaultValue: qtiNull(),
1116
- value: v,
1117
- };
1118
- }
1119
-
1120
- const ctx = new DeclarationContext(decls);
1121
- const ops = new OperatorRegistry();
1122
- const expr = buildExpression(root, { scope: 'test' });
1123
- const out = evalExpr({ ctx, ops, rng: Math.random }, expr);
1124
- return out.kind === 'value' && out.baseType === 'boolean' ? Boolean(out.value) : false;
1125
- }
1126
-
1127
- private getItemOrder(assessment: SecureAssessment): string[] {
1128
- const out: string[] = [];
1129
- for (const part of assessment.testParts || []) {
1130
- for (const section of part.sections || []) {
1131
- for (const item of section.assessmentItemRefs || []) {
1132
- out.push(item.identifier);
1133
- }
1134
- }
1135
- }
1136
- return out;
1137
- }
1138
-
1139
- // =========================================================================
1140
- // ITEM BANK HELPERS
1141
- // =========================================================================
1142
-
1143
- /**
1144
- * Generate cache key for item bank query
1145
- */
1146
- private getBankCacheKey(
1147
- sessionId: SessionId,
1148
- bankId: string,
1149
- count: number,
1150
- withReplacement?: boolean,
1151
- filters?: Record<string, unknown>
1152
- ): string {
1153
- const filterKey = filters ? JSON.stringify(filters) : '';
1154
- return `${BANK_CACHE_PREFIX}${sessionId}:${bankId}:${count}:${withReplacement}:${filterKey}`;
1155
- }
1156
-
1157
- /**
1158
- * Load item bank cache from localStorage
1159
- */
1160
- private loadBankCache(cacheKey: string): BankCacheEntry | null {
1161
- try {
1162
- const data = localStorage.getItem(cacheKey);
1163
- if (!data) return null;
1164
-
1165
- const entry = JSON.parse(data) as BankCacheEntry;
1166
-
1167
- // Check if cache is expired
1168
- const now = Date.now();
1169
- if (now - entry.timestamp > entry.ttl) {
1170
- // Clean up expired cache
1171
- localStorage.removeItem(cacheKey);
1172
- return null;
1173
- }
1174
-
1175
- return entry;
1176
- } catch {
1177
- return null;
1178
- }
1179
- }
1180
-
1181
- /**
1182
- * Save item bank cache to localStorage
1183
- */
1184
- private saveBankCache(cacheKey: string, entry: BankCacheEntry): void {
1185
- try {
1186
- localStorage.setItem(cacheKey, JSON.stringify(entry));
1187
- } catch (error) {
1188
- console.error('Failed to save bank cache to localStorage:', error);
1189
- }
1190
- }
1191
-
1192
- /**
1193
- * Fetch items from item bank with retry logic
1194
- *
1195
- * **DEMO IMPLEMENTATION**: Returns hardcoded items
1196
- * In production, this would make HTTP request to item bank service
1197
- */
1198
- private async fetchItemsFromBank(
1199
- bankId: string,
1200
- count: number,
1201
- withReplacement?: boolean,
1202
- filters?: Record<string, unknown>,
1203
- retryCount = 0
1204
- ): Promise<SecureItemRef[]> {
1205
- const maxRetries = 3;
1206
- const baseDelay = 1000; // 1 second
1207
-
1208
- try {
1209
- // Simulate network call delay
1210
- await this.delay(100);
1211
-
1212
- // **DEMO**: Return hardcoded items
1213
- // In production, replace with:
1214
- // const response = await fetch(`/api/item-banks/${bankId}`, {
1215
- // method: 'POST',
1216
- // headers: { 'Content-Type': 'application/json' },
1217
- // body: JSON.stringify({ count, withReplacement, filters })
1218
- // });
1219
- // return response.json();
1220
-
1221
- const demoItems: SecureItemRef[] = [
1222
- {
1223
- identifier: `bank-${bankId}-item1`,
1224
- role: 'candidate',
1225
- itemXml: `<assessmentItem identifier="bank-${bankId}-item1" title="Bank Item 1" adaptive="false" timeDependent="false">
1226
- <responseDeclaration identifier="RESPONSE" cardinality="single" baseType="identifier">
1227
- <correctResponse><value>A</value></correctResponse>
1228
- </responseDeclaration>
1229
- <outcomeDeclaration identifier="SCORE" cardinality="single" baseType="float">
1230
- <defaultValue><value>0</value></defaultValue>
1231
- </outcomeDeclaration>
1232
- <itemBody>
1233
- <p>Sample question from bank ${bankId}</p>
1234
- <choiceInteraction responseIdentifier="RESPONSE" shuffle="false" maxChoices="1">
1235
- <simpleChoice identifier="A">Option A</simpleChoice>
1236
- <simpleChoice identifier="B">Option B</simpleChoice>
1237
- </choiceInteraction>
1238
- </itemBody>
1239
- <responseProcessing>
1240
- <responseCondition>
1241
- <responseIf>
1242
- <match>
1243
- <variable identifier="RESPONSE" />
1244
- <correct identifier="RESPONSE" />
1245
- </match>
1246
- <setOutcomeValue identifier="SCORE">
1247
- <baseValue baseType="float">1</baseValue>
1248
- </setOutcomeValue>
1249
- </responseIf>
1250
- <responseElse>
1251
- <setOutcomeValue identifier="SCORE">
1252
- <baseValue baseType="float">0</baseValue>
1253
- </setOutcomeValue>
1254
- </responseElse>
1255
- </responseCondition>
1256
- </responseProcessing>
1257
- </assessmentItem>`,
1258
- },
1259
- {
1260
- identifier: `bank-${bankId}-item2`,
1261
- role: 'candidate',
1262
- itemXml: `<assessmentItem identifier="bank-${bankId}-item2" title="Bank Item 2" adaptive="false" timeDependent="false">
1263
- <responseDeclaration identifier="RESPONSE" cardinality="single" baseType="identifier">
1264
- <correctResponse><value>B</value></correctResponse>
1265
- </responseDeclaration>
1266
- <outcomeDeclaration identifier="SCORE" cardinality="single" baseType="float">
1267
- <defaultValue><value>0</value></defaultValue>
1268
- </outcomeDeclaration>
1269
- <itemBody>
1270
- <p>Another question from bank ${bankId}</p>
1271
- <choiceInteraction responseIdentifier="RESPONSE" shuffle="false" maxChoices="1">
1272
- <simpleChoice identifier="A">Option A</simpleChoice>
1273
- <simpleChoice identifier="B">Option B</simpleChoice>
1274
- </choiceInteraction>
1275
- </itemBody>
1276
- <responseProcessing>
1277
- <responseCondition>
1278
- <responseIf>
1279
- <match>
1280
- <variable identifier="RESPONSE" />
1281
- <correct identifier="RESPONSE" />
1282
- </match>
1283
- <setOutcomeValue identifier="SCORE">
1284
- <baseValue baseType="float">1</baseValue>
1285
- </setOutcomeValue>
1286
- </responseIf>
1287
- <responseElse>
1288
- <setOutcomeValue identifier="SCORE">
1289
- <baseValue baseType="float">0</baseValue>
1290
- </setOutcomeValue>
1291
- </responseElse>
1292
- </responseCondition>
1293
- </responseProcessing>
1294
- </assessmentItem>`,
1295
- },
1296
- {
1297
- identifier: `bank-${bankId}-item3`,
1298
- role: 'candidate',
1299
- itemXml: `<assessmentItem identifier="bank-${bankId}-item3" title="Bank Item 3" adaptive="false" timeDependent="false">
1300
- <responseDeclaration identifier="RESPONSE" cardinality="single" baseType="identifier">
1301
- <correctResponse><value>A</value></correctResponse>
1302
- </responseDeclaration>
1303
- <outcomeDeclaration identifier="SCORE" cardinality="single" baseType="float">
1304
- <defaultValue><value>0</value></defaultValue>
1305
- </outcomeDeclaration>
1306
- <itemBody>
1307
- <p>Third question from bank ${bankId}</p>
1308
- <choiceInteraction responseIdentifier="RESPONSE" shuffle="false" maxChoices="1">
1309
- <simpleChoice identifier="A">Option A</simpleChoice>
1310
- <simpleChoice identifier="B">Option B</simpleChoice>
1311
- </choiceInteraction>
1312
- </itemBody>
1313
- <responseProcessing>
1314
- <responseCondition>
1315
- <responseIf>
1316
- <match>
1317
- <variable identifier="RESPONSE" />
1318
- <correct identifier="RESPONSE" />
1319
- </match>
1320
- <setOutcomeValue identifier="SCORE">
1321
- <baseValue baseType="float">1</baseValue>
1322
- </setOutcomeValue>
1323
- </responseIf>
1324
- <responseElse>
1325
- <setOutcomeValue identifier="SCORE">
1326
- <baseValue baseType="float">0</baseValue>
1327
- </setOutcomeValue>
1328
- </responseElse>
1329
- </responseCondition>
1330
- </responseProcessing>
1331
- </assessmentItem>`,
1332
- },
1333
- ];
1334
-
1335
- // Apply filtering if specified (demo implementation)
1336
- let filteredItems = [...demoItems];
1337
- if (filters?.difficulty) {
1338
- // In production, server would filter by metadata
1339
- console.log(`Filtering by difficulty: ${filters.difficulty}`);
1340
- }
1341
-
1342
- // Select requested number of items
1343
- if (withReplacement) {
1344
- // Allow duplicates
1345
- const selected: SecureItemRef[] = [];
1346
- for (let i = 0; i < count; i++) {
1347
- const randomIndex = Math.floor(Math.random() * filteredItems.length);
1348
- selected.push(filteredItems[randomIndex]);
1349
- }
1350
- return selected;
1351
- } else {
1352
- // No duplicates - shuffle and take first N
1353
- const shuffled = [...filteredItems].sort(() => Math.random() - 0.5);
1354
- return shuffled.slice(0, Math.min(count, shuffled.length));
1355
- }
1356
- } catch (error) {
1357
- // Implement exponential backoff retry
1358
- if (retryCount < maxRetries) {
1359
- const delay = baseDelay * Math.pow(2, retryCount);
1360
- console.warn(
1361
- `Item bank query failed (attempt ${retryCount + 1}/${maxRetries + 1}). ` +
1362
- `Retrying in ${delay}ms...`,
1363
- error
1364
- );
1365
- await this.delay(delay);
1366
- return this.fetchItemsFromBank(bankId, count, withReplacement, filters, retryCount + 1);
1367
- }
1368
-
1369
- // All retries exhausted
1370
- throw new Error(
1371
- `Failed to load items from bank "${bankId}" after ${maxRetries + 1} attempts: ${error}`
1372
- );
1373
- }
1374
- }
1375
-
1376
- /**
1377
- * Delay helper for async operations
1378
- */
1379
- private delay(ms: number): Promise<void> {
1380
- return new Promise((resolve) => setTimeout(resolve, ms));
1381
- }
1382
- }