@pie-qti/assessment-player 0.1.6 → 0.1.8

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.
@@ -8,7 +8,7 @@
8
8
  * - Apply backend navigation decisions + session state
9
9
  */
10
10
 
11
- import type { QTIRole, PnpProfile } from '@pie-qti/item-player';
11
+ import type { QTIRole, PnpProfile, SerializedItemSessionState } from '@pie-qti/item-player';
12
12
  import { Player } from '@pie-qti/item-player';
13
13
  import type {
14
14
  AssessmentRubricBlock,
@@ -28,6 +28,7 @@ import type {
28
28
  AssessmentResults,
29
29
  ItemResult,
30
30
  NavigationState,
31
+ TimeLimits,
31
32
  } from '../types/index.js';
32
33
  import { ItemSessionController, type ItemSessionState } from './ItemSessionController.js';
33
34
  import { NavigationManager } from './NavigationManager.js';
@@ -54,6 +55,12 @@ export interface BackendAssessmentPlayerConfig {
54
55
  * If provided, this will be passed to all item players in the assessment.
55
56
  */
56
57
  security?: any; // Will be PlayerSecurityConfig from @pie-qti/item-player
58
+ /**
59
+ * Demo/reference-only escape hatch. When false (default), rich item-session
60
+ * variables stay client-local and are not submitted because template variables
61
+ * can contain answer keys. Production backends should own this state server-side.
62
+ */
63
+ sendItemSessionToBackend?: boolean;
57
64
  // UI options
58
65
  showSections?: boolean;
59
66
  allowSectionNavigation?: boolean;
@@ -88,6 +95,22 @@ type CurrentItemView = {
88
95
  title?: string;
89
96
  required?: boolean;
90
97
  itemXml: string;
98
+ deliveryContext?: SecureItemRef['deliveryContext'];
99
+ };
100
+
101
+ export interface EffectiveItemTimeLimits {
102
+ timeLimits?: TimeLimits;
103
+ source?: 'item' | 'section' | 'testPart' | 'assessment';
104
+ }
105
+
106
+ type ItemSessionCapablePlayer = Player & {
107
+ suspendAttempt(): { sessionState: SerializedItemSessionState; duration: number };
108
+ endAttempt(options?: { countAttempt?: boolean; validateResponses?: boolean }): {
109
+ sessionState: SerializedItemSessionState;
110
+ duration: number;
111
+ validation?: { valid: boolean; issues: Array<{ message: string }> };
112
+ };
113
+ restoreItemSession(state: SerializedItemSessionState): void;
91
114
  };
92
115
 
93
116
  export class AssessmentPlayer {
@@ -134,6 +157,7 @@ export class AssessmentPlayer {
134
157
  visitedItems: [],
135
158
  itemResponses: {},
136
159
  itemScores: {},
160
+ itemSessions: {},
137
161
  timing: { startedAt: Date.now(), itemTimes: {}, totalTime: 0 },
138
162
  } as AssessmentSessionState);
139
163
 
@@ -153,23 +177,22 @@ export class AssessmentPlayer {
153
177
  }
154
178
  this.restoreItemSessionsFromState(this.state);
155
179
 
156
- // Initialize time manager if time limits exist
157
- if (this.assessment.timeLimits?.maxTime) {
158
- this.timeManager = new TimeManager({
159
- assessmentTimeLimits: this.assessment.timeLimits,
160
- warningThreshold: config.timeWarningThreshold || 60,
161
- extendedTime: config.pnp?.content?.extendedTime,
162
- onWarning: (remainingSeconds) => this.notifyTimeWarning(remainingSeconds),
163
- onExpired: () => this.notifyTimeExpired(),
164
- onTick: (remainingSeconds, elapsedSeconds) => this.notifyTimeTick(remainingSeconds, elapsedSeconds),
165
- });
166
- }
180
+ this.timeManager = new TimeManager({
181
+ assessmentTimeLimits: this.assessment.timeLimits,
182
+ warningThreshold: config.timeWarningThreshold || 60,
183
+ extendedTime: config.pnp?.content?.extendedTime,
184
+ onWarning: (remainingSeconds) => this.notifyTimeWarning(remainingSeconds),
185
+ onExpired: () => this.notifyTimeExpired(),
186
+ onTick: (remainingSeconds, elapsedSeconds) => this.notifyTimeTick(remainingSeconds, elapsedSeconds),
187
+ });
167
188
 
168
189
  // Restore to backend-provided current item if present
169
190
  const startId = this.state.currentItemIdentifier;
170
191
  const idx = startId ? this.items.findIndex((q) => q.identifier === startId) : -1;
171
192
  if (idx >= 0) {
172
193
  this.navigateTo(idx, { restoring: true }).catch(() => {});
194
+ } else if (this.items.length > 0) {
195
+ this.navigateTo(0, { restoring: true }).catch(() => {});
173
196
  }
174
197
  }
175
198
 
@@ -196,6 +219,70 @@ export class AssessmentPlayer {
196
219
  };
197
220
  }
198
221
 
222
+ private getEffectiveItemTimeLimits(flat: FlatItem): EffectiveItemTimeLimits {
223
+ const scopes: Array<{ source: EffectiveItemTimeLimits['source']; limits?: TimeLimits }> = [
224
+ { source: 'assessment', limits: this.assessment.timeLimits },
225
+ { source: 'testPart', limits: flat.testPart.timeLimits },
226
+ { source: 'section', limits: flat.section.timeLimits },
227
+ { source: 'item', limits: flat.item.timeLimits },
228
+ ];
229
+ let source: EffectiveItemTimeLimits['source'];
230
+ let minTime: number | undefined;
231
+ let maxTime: number | undefined;
232
+ let allowLateSubmission: boolean | undefined;
233
+ for (const scope of scopes) {
234
+ if (!scope.limits) continue;
235
+ if (scope.limits.minTime !== undefined) {
236
+ minTime = minTime === undefined ? scope.limits.minTime : Math.max(minTime, scope.limits.minTime);
237
+ }
238
+ if (scope.limits.maxTime !== undefined) {
239
+ const extended = this.config.pnp?.content?.extendedTime;
240
+ const scopedMaxTime = extended?.active
241
+ ? extended.multiplier === Infinity
242
+ ? undefined
243
+ : scope.limits.maxTime * extended.multiplier
244
+ : scope.limits.maxTime;
245
+ if (scopedMaxTime !== undefined && (maxTime === undefined || scopedMaxTime < maxTime)) {
246
+ maxTime = scopedMaxTime;
247
+ source = scope.source;
248
+ allowLateSubmission = scope.limits.allowLateSubmission;
249
+ }
250
+ } else if (scope.limits.allowLateSubmission !== undefined && maxTime === undefined) {
251
+ allowLateSubmission = scope.limits.allowLateSubmission;
252
+ source = scope.source;
253
+ }
254
+ }
255
+
256
+ if (maxTime === undefined && minTime === undefined && allowLateSubmission === undefined) {
257
+ return {};
258
+ }
259
+ return { source, timeLimits: { minTime, maxTime, allowLateSubmission } };
260
+ }
261
+
262
+ public getCurrentEffectiveTimeLimits(): EffectiveItemTimeLimits {
263
+ const q = this.items[this.currentItemIndex];
264
+ return q ? this.getEffectiveItemTimeLimits(q) : {};
265
+ }
266
+
267
+ private getSubmitTimingEvidence(q: FlatItem, elapsedMs: number): import('../integration/api-contract.js').SubmitTimingEvidence | undefined {
268
+ const effective = this.getEffectiveItemTimeLimits(q);
269
+ const limitSeconds = effective.timeLimits?.maxTime;
270
+ if (!effective.source || limitSeconds === undefined) return undefined;
271
+ if (effective.source !== 'item' && effective.source !== 'assessment') {
272
+ return undefined;
273
+ }
274
+ const scopedElapsedMs = effective.source === 'assessment'
275
+ ? (this.timeManager?.getElapsedSeconds() ?? 0) * 1000
276
+ : elapsedMs;
277
+ return {
278
+ scope: effective.source,
279
+ elapsedMs: scopedElapsedMs,
280
+ limitSeconds,
281
+ expired: scopedElapsedMs >= limitSeconds * 1000,
282
+ allowLateSubmission: effective.timeLimits?.allowLateSubmission,
283
+ };
284
+ }
285
+
199
286
  private hasAnyResponse(responses: Record<string, unknown>): boolean {
200
287
  for (const v of Object.values(responses)) {
201
288
  if (v == null) continue;
@@ -329,6 +416,7 @@ export class AssessmentPlayer {
329
416
  title: q.section.title,
330
417
  required: q.item.required,
331
418
  itemXml: q.item.itemXml,
419
+ deliveryContext: q.item.deliveryContext,
332
420
  };
333
421
  }
334
422
 
@@ -381,17 +469,53 @@ export class AssessmentPlayer {
381
469
  return { ...this.responses };
382
470
  }
383
471
 
472
+ public saveCurrentItemSession(): SerializedItemSessionState | null {
473
+ const q = this.items[this.currentItemIndex];
474
+ if (!q || !this.currentItemPlayer) return null;
475
+ this.currentItemPlayer.setResponses(this.responses as any);
476
+ const result = (this.currentItemPlayer as ItemSessionCapablePlayer).suspendAttempt();
477
+ this.state.itemSessions = {
478
+ ...(this.state.itemSessions ?? {}),
479
+ [q.identifier]: result.sessionState,
480
+ };
481
+ this.state.itemResponses[q.identifier] = this.responses as any;
482
+ this.state.timing.itemTimes[q.identifier] = result.duration;
483
+ this.sessionController.markAnswered(q.identifier, this.hasAnyResponse(this.responses));
484
+ return result.sessionState;
485
+ }
486
+
487
+ private endItemSessionForSubmit(
488
+ q: FlatItem,
489
+ responses: Record<string, unknown>,
490
+ itemSession?: SerializedItemSessionState
491
+ ): SerializedItemSessionState {
492
+ const player = new Player({
493
+ itemXml: q.item.itemXml,
494
+ role: q.item.role,
495
+ i18nProvider: this.i18nProvider,
496
+ pnp: this.config.pnp,
497
+ security: this.config.security,
498
+ deliveryContext: q.item.deliveryContext,
499
+ }) as ItemSessionCapablePlayer;
500
+ if (itemSession) {
501
+ player.restoreItemSession(itemSession);
502
+ }
503
+ player.setResponses(responses as any);
504
+ return player.endAttempt().sessionState;
505
+ }
506
+
384
507
  /**
385
508
  * Get the current session state snapshot (client-side view).
386
509
  * Note: backend remains authoritative; this is intended for simple save/resume.
387
510
  */
388
- public getState(): AssessmentSessionState {
511
+ public getState(options: { includeItemSessions?: boolean } = {}): AssessmentSessionState {
389
512
  // Shallow clone to avoid accidental external mutation.
390
513
  return {
391
514
  ...this.state,
392
515
  visitedItems: [...this.state.visitedItems],
393
516
  itemResponses: { ...this.state.itemResponses },
394
517
  itemScores: this.state.itemScores ? { ...this.state.itemScores } : undefined,
518
+ itemSessions: options.includeItemSessions && this.state.itemSessions ? { ...this.state.itemSessions } : undefined,
395
519
  itemSessionStates: this.getItemSessionStateSnapshot(),
396
520
  timing: {
397
521
  ...this.state.timing,
@@ -450,9 +574,25 @@ export class AssessmentPlayer {
450
574
  throw new Error('You cannot go back to previous questions in this assessment.');
451
575
  }
452
576
 
577
+ const currentItem = this.items[this.currentItemIndex];
578
+ const currentSessionStatus = currentItem ? this.state.itemSessions?.[currentItem.identifier]?.lifecycleStatus : undefined;
579
+ if (
580
+ !options.restoring &&
581
+ this.currentItemIndex >= 0 &&
582
+ this.currentItemIndex !== index &&
583
+ currentSessionStatus !== 'closed'
584
+ ) {
585
+ this.saveCurrentItemSession();
586
+ }
587
+ if (currentItem && this.currentItemIndex !== index) {
588
+ this.timeManager?.endItem(currentItem.identifier);
589
+ }
590
+
453
591
  this.currentItemIndex = index;
454
592
  const q = this.items[index]!;
455
593
  this.state.currentItemIdentifier = q.identifier;
594
+ this.timeManager?.startSection(q.section.identifier);
595
+ this.timeManager?.startItem(q.identifier);
456
596
 
457
597
  // Apply three-level itemSessionControl fallback for this item's section (S1).
458
598
  const effectiveControl = this.getEffectiveItemSessionControl(q);
@@ -464,12 +604,21 @@ export class AssessmentPlayer {
464
604
  this.responses = { ...(this.state.itemResponses[q.identifier] || {}) };
465
605
 
466
606
  // Create item player
607
+ this.currentItemPlayer?.destroy();
467
608
  this.currentItemPlayer = new Player({
468
609
  itemXml: q.item.itemXml,
469
610
  role: q.item.role,
470
611
  i18nProvider: this.i18nProvider,
612
+ pnp: this.config.pnp,
613
+ security: this.config.security,
614
+ deliveryContext: q.item.deliveryContext,
471
615
  });
472
- this.currentItemPlayer.setResponses(this.responses as any);
616
+ const restoredItemSession = this.state.itemSessions?.[q.identifier];
617
+ if (restoredItemSession) {
618
+ (this.currentItemPlayer as ItemSessionCapablePlayer).restoreItemSession(restoredItemSession);
619
+ } else {
620
+ this.currentItemPlayer.setResponses(this.responses as any);
621
+ }
473
622
 
474
623
  this.notifyItemChange();
475
624
  this.notifySectionChange();
@@ -518,11 +667,29 @@ export class AssessmentPlayer {
518
667
  if (!q) throw new Error('No current item');
519
668
 
520
669
  const submittedAt = Date.now();
670
+ let itemSession: SerializedItemSessionState | undefined;
671
+ if (this.currentItemPlayer) {
672
+ this.currentItemPlayer.setResponses(this.responses as any);
673
+ const attempt = (this.currentItemPlayer as ItemSessionCapablePlayer).endAttempt({
674
+ validateResponses: this.sessionController.mustValidateResponses(),
675
+ });
676
+ if (attempt.validation && !attempt.validation.valid) {
677
+ throw new Error(attempt.validation.issues[0]?.message || 'Submit failed: invalid response');
678
+ }
679
+ itemSession = attempt.sessionState;
680
+ this.state.itemSessions = {
681
+ ...(this.state.itemSessions ?? {}),
682
+ [q.identifier]: itemSession,
683
+ };
684
+ }
521
685
  const res = await this.backend.submitResponses({
522
686
  sessionId: this.sessionId,
523
687
  itemIdentifier: q.identifier,
524
688
  responses: this.responses as any,
525
689
  submittedAt,
690
+ timeSpent: itemSession?.duration,
691
+ timing: this.getSubmitTimingEvidence(q, itemSession?.duration ?? 0),
692
+ itemSession: this.config.sendItemSessionToBackend ? itemSession : undefined,
526
693
  });
527
694
 
528
695
  if (!res.success || !res.result) {
@@ -530,13 +697,20 @@ export class AssessmentPlayer {
530
697
  }
531
698
 
532
699
  if (res.updatedState) {
700
+ const localItemSessions = this.state.itemSessions;
533
701
  this.state = res.updatedState;
702
+ if (localItemSessions) {
703
+ this.state.itemSessions = { ...(this.state.itemSessions ?? {}), ...localItemSessions };
704
+ }
534
705
  } else {
535
706
  // Minimal state update when backend doesn't return full state.
536
707
  this.state.itemScores = this.state.itemScores || {};
537
708
  this.state.itemScores[q.identifier] = res.result;
538
709
  if (!this.state.visitedItems.includes(q.identifier)) this.state.visitedItems.push(q.identifier);
539
710
  this.state.itemResponses[q.identifier] = this.responses as any;
711
+ if (itemSession) {
712
+ this.state.itemSessions = { ...(this.state.itemSessions ?? {}), [q.identifier]: itemSession };
713
+ }
540
714
  }
541
715
 
542
716
  const itemResult: ItemResult = {
@@ -614,21 +788,28 @@ export class AssessmentPlayer {
614
788
  // For simultaneous submission, ensure all items are submitted before finalize so
615
789
  // the backend can compute a complete test score.
616
790
  if (this.assessment.submissionMode === 'simultaneous') {
791
+ this.saveCurrentItemSession();
617
792
  // Preserve client-collected responses across backend state updates.
618
793
  // Some backend adapters return an updatedState snapshot that may only include
619
794
  // responses for items that have been submitted so far, which would otherwise
620
795
  // wipe out responses for later items during this loop.
621
796
  const allItemResponses = { ...(this.state.itemResponses || {}) } as any;
797
+ const allItemSessions = { ...(this.state.itemSessions || {}) };
622
798
 
623
799
  for (const q of this.items) {
624
800
  if (this.itemResults.has(q.identifier)) continue;
625
801
  const submittedAt = Date.now();
626
802
  const responsesForItem = (allItemResponses?.[q.identifier] || {}) as any;
803
+ const itemSession = this.endItemSessionForSubmit(q, responsesForItem, allItemSessions[q.identifier]);
804
+ allItemSessions[q.identifier] = itemSession;
627
805
  const res = await this.backend.submitResponses({
628
806
  sessionId: this.sessionId,
629
807
  itemIdentifier: q.identifier,
630
808
  responses: responsesForItem,
631
809
  submittedAt,
810
+ timeSpent: itemSession?.duration,
811
+ timing: this.getSubmitTimingEvidence(q, itemSession?.duration ?? 0),
812
+ itemSession: this.config.sendItemSessionToBackend ? itemSession : undefined,
632
813
  });
633
814
  if (!res.success || !res.result) {
634
815
  throw new Error(res.error || `Submit failed for item ${q.identifier}`);
@@ -637,11 +818,15 @@ export class AssessmentPlayer {
637
818
  this.state = res.updatedState;
638
819
  // Restore full response map captured on the client.
639
820
  this.state.itemResponses = allItemResponses;
821
+ this.state.itemSessions = allItemSessions;
640
822
  } else {
641
823
  this.state.itemScores = this.state.itemScores || {};
642
824
  this.state.itemScores[q.identifier] = res.result;
643
825
  if (!this.state.visitedItems.includes(q.identifier)) this.state.visitedItems.push(q.identifier);
644
826
  this.state.itemResponses[q.identifier] = responsesForItem;
827
+ if (itemSession) {
828
+ this.state.itemSessions = { ...(this.state.itemSessions ?? {}), [q.identifier]: itemSession };
829
+ }
645
830
  }
646
831
  this.itemResults.set(q.identifier, {
647
832
  itemIdentifier: q.identifier,
@@ -790,6 +975,8 @@ export class AssessmentPlayer {
790
975
  }
791
976
 
792
977
  public destroy(): void {
978
+ this.timeManager?.destroy();
979
+ this.currentItemPlayer?.destroy();
793
980
  this.itemChangeListeners.clear();
794
981
  this.sectionChangeListeners.clear();
795
982
  this.responseChangeListeners.clear();
@@ -41,6 +41,11 @@ import {
41
41
  qtiNull,
42
42
  qtiValue,
43
43
  } from '@pie-qti/qti-processing';
44
+ import {
45
+ createResolvedItemDeliveryContext,
46
+ extractAssessmentStimulusRefs,
47
+ resolveRelativePath as resolveQtiRelativePath,
48
+ } from '@pie-qti/ims-cp-core';
44
49
  import { parse } from 'node-html-parser';
45
50
  import type {
46
51
  AssessmentSessionState,
@@ -190,6 +195,7 @@ export class ReferenceBackendAdapter implements BackendAdapter {
190
195
  visitedItems: [],
191
196
  itemResponses: {},
192
197
  itemScores: {},
198
+ itemSessions: {},
193
199
  timing: {
194
200
  startedAt: Date.now(),
195
201
  itemTimes: {},
@@ -234,6 +240,34 @@ export class ReferenceBackendAdapter implements BackendAdapter {
234
240
  };
235
241
  }
236
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
+
237
271
  // Find the item XML
238
272
  const itemXml = this.findItemXml(session.assessment, request.itemIdentifier);
239
273
  if (!itemXml) {
@@ -245,7 +279,7 @@ export class ReferenceBackendAdapter implements BackendAdapter {
245
279
 
246
280
  // **SECURITY WARNING**: Client-side scoring is INSECURE
247
281
  // In production, this MUST be done server-side
248
- const result = scoreAssessmentItem({ itemXml, responses: request.responses });
282
+ const result = scoreAssessmentItem({ itemXml, responses: request.responses, itemSession: request.itemSession });
249
283
 
250
284
  // Store responses and result
251
285
  session.state.itemResponses[request.itemIdentifier] = request.responses;
@@ -253,6 +287,12 @@ export class ReferenceBackendAdapter implements BackendAdapter {
253
287
  session.state.itemScores = {};
254
288
  }
255
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
+ }
256
296
  const previousItemSession = session.state.itemSessionStates?.[request.itemIdentifier];
257
297
  session.state.itemSessionStates = {
258
298
  ...(session.state.itemSessionStates ?? {}),
@@ -761,14 +801,83 @@ export class ReferenceBackendAdapter implements BackendAdapter {
761
801
  };
762
802
  };
763
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
+
764
872
  // Parse a single assessmentSection element
765
- const parseSection = (sectionEl: Element): SecureSection => {
873
+ const parseSection = async (sectionEl: Element): Promise<SecureSection> => {
766
874
  const identifier = getAttr(sectionEl, 'identifier') ?? 'section';
767
875
  const title = getAttr(sectionEl, 'title');
768
876
  const visibleRaw = getAttr(sectionEl, 'visible');
769
877
  const visible = visibleRaw === undefined ? true : visibleRaw !== 'false';
770
878
 
771
879
  const itemSessionControl = parseItemSessionControl(sectionEl);
880
+ const timeLimits = parseTimeLimits(sectionEl);
772
881
 
773
882
  // rubricBlocks
774
883
  const rubricBlockEls = childrenByTag(sectionEl, 'rubricBlock');
@@ -783,20 +892,24 @@ export class ReferenceBackendAdapter implements BackendAdapter {
783
892
 
784
893
  // assessmentItemRefs
785
894
  const itemRefEls = childrenByTag(sectionEl, 'assessmentItemRef');
786
- const assessmentItemRefs: SecureItemRef[] = itemRefEls.map((ref) => {
895
+ const assessmentItemRefs: SecureItemRef[] = [];
896
+ for (const ref of itemRefEls) {
787
897
  const itemId = getAttr(ref, 'identifier') ?? 'item';
788
898
  const href = getAttr(ref, 'href');
899
+ const itemHref = resolveAgainstBase(href) ?? href;
789
900
  // Look up pre-loaded XML by identifier or href
790
- const resolvedXml = itemXmlMap[itemId] ?? (href ? itemXmlMap[href] : undefined) ?? '';
901
+ const resolvedXml = itemXmlMap[itemId] ?? (href ? itemXmlMap[href] : undefined) ?? (itemHref ? itemXmlMap[itemHref] : undefined) ?? (await loadText(href)) ?? '';
791
902
  const requiredRaw = getAttr(ref, 'required');
792
903
  const required = requiredRaw === undefined ? undefined : requiredRaw !== 'false';
793
- return {
904
+ assessmentItemRefs.push({
794
905
  identifier: itemId,
795
906
  itemXml: resolvedXml,
796
907
  role,
797
908
  required,
798
- };
799
- });
909
+ timeLimits: parseTimeLimits(ref),
910
+ deliveryContext: await buildDeliveryContext(resolvedXml, itemHref),
911
+ });
912
+ }
800
913
 
801
914
  return {
802
915
  identifier,
@@ -805,6 +918,7 @@ export class ReferenceBackendAdapter implements BackendAdapter {
805
918
  assessmentItemRefs,
806
919
  rubricBlocks,
807
920
  itemSessionControl,
921
+ timeLimits,
808
922
  };
809
923
  };
810
924
 
@@ -848,7 +962,7 @@ export class ReferenceBackendAdapter implements BackendAdapter {
848
962
  const sections: SecureSection[] = [];
849
963
  for (const child of childElements(testPartEl)) {
850
964
  if (toCanonicalQtiName(child.localName) === 'assessmentSection') {
851
- sections.push(parseSection(child));
965
+ sections.push(await parseSection(child));
852
966
  } else if (toCanonicalQtiName(child.localName) === 'assessmentSectionRef') {
853
967
  const resolved = await resolveSectionRef(child);
854
968
  if (resolved) sections.push(resolved);
@@ -910,16 +1024,8 @@ export class ReferenceBackendAdapter implements BackendAdapter {
910
1024
  ? serializeXml(outcomeProcessingEl)
911
1025
  : undefined;
912
1026
 
913
- // Extract timeLimits
914
- const timeLimitsEl = childrenByTag(root, 'timeLimit')[0] ?? childrenByTag(root, 'timeLimits')[0];
915
- const timeLimits = timeLimitsEl
916
- ? {
917
- maxTime: getAttr(timeLimitsEl, 'maxTime')
918
- ? Number(getAttr(timeLimitsEl, 'maxTime'))
919
- : undefined,
920
- allowLateSubmission: getAttr(timeLimitsEl, 'allowLateSubmission') === 'true',
921
- }
922
- : undefined;
1027
+ // Extract assessment-level timeLimits.
1028
+ const timeLimits = parseTimeLimits(root);
923
1029
 
924
1030
  // Parse testParts
925
1031
  const testPartEls = childrenByTag(root, 'testPart');
@@ -937,6 +1043,7 @@ export class ReferenceBackendAdapter implements BackendAdapter {
937
1043
  for (const tp of testPartEls) {
938
1044
  const tpIdentifier = getAttr(tp, 'identifier') ?? 'part-1';
939
1045
  const tpItemSessionControl = parseTestPartItemSessionControl(tp);
1046
+ const tpTimeLimits = parseTimeLimits(tp);
940
1047
  const tpRubricBlockEls = childrenByTag(tp, 'rubricBlock');
941
1048
  const tpRubricBlocks = tpRubricBlockEls.length > 0
942
1049
  ? tpRubricBlockEls.map((b, idx) => ({
@@ -953,6 +1060,7 @@ export class ReferenceBackendAdapter implements BackendAdapter {
953
1060
  sections,
954
1061
  rubricBlocks: tpRubricBlocks,
955
1062
  itemSessionControl: tpItemSessionControl,
1063
+ timeLimits: tpTimeLimits,
956
1064
  });
957
1065
  }
958
1066
 
@@ -961,7 +1069,7 @@ export class ReferenceBackendAdapter implements BackendAdapter {
961
1069
  const topSections: SecureSection[] = [];
962
1070
  for (const child of childElements(root)) {
963
1071
  if (toCanonicalQtiName(child.localName) === 'assessmentSection') {
964
- topSections.push(parseSection(child));
1072
+ topSections.push(await parseSection(child));
965
1073
  } else if (toCanonicalQtiName(child.localName) === 'assessmentSectionRef') {
966
1074
  const resolved = await resolveSectionRef(child);
967
1075
  if (resolved) topSections.push(resolved);