@pie-qti/assessment-player 0.1.4 → 0.1.6

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 (32) hide show
  1. package/README.md +19 -16
  2. package/dist/core/AssessmentPlayer.d.ts +21 -2
  3. package/dist/core/AssessmentPlayer.d.ts.map +1 -1
  4. package/dist/core/AssessmentPlayer.js +144 -15
  5. package/dist/core/TimeManager.d.ts +9 -0
  6. package/dist/core/TimeManager.d.ts.map +1 -1
  7. package/dist/core/TimeManager.js +16 -3
  8. package/dist/integration/ReferenceBackendAdapter.d.ts +28 -8
  9. package/dist/integration/ReferenceBackendAdapter.d.ts.map +1 -1
  10. package/dist/integration/ReferenceBackendAdapter.js +409 -51
  11. package/dist/integration/api-contract.d.ts +82 -2
  12. package/dist/integration/api-contract.d.ts.map +1 -1
  13. package/dist/integration/assessment-item-scorer.d.ts +12 -0
  14. package/dist/integration/assessment-item-scorer.d.ts.map +1 -0
  15. package/dist/integration/assessment-item-scorer.js +40 -0
  16. package/dist/integration/index.d.ts +1 -0
  17. package/dist/integration/index.d.ts.map +1 -1
  18. package/dist/integration/index.js +1 -0
  19. package/package.json +6 -6
  20. package/src/components/AccessibilityAnnouncer.svelte +13 -2
  21. package/src/components/AssessmentShell.svelte +13 -8
  22. package/src/components/AssessmentTimer.svelte +23 -0
  23. package/src/components/ItemRenderer.svelte +7 -3
  24. package/src/components/NavigationBar.svelte +2 -0
  25. package/src/components/SectionMenu.svelte +72 -5
  26. package/src/components/index.ts +1 -1
  27. package/src/core/AssessmentPlayer.ts +162 -17
  28. package/src/core/TimeManager.ts +20 -3
  29. package/src/integration/ReferenceBackendAdapter.ts +467 -54
  30. package/src/integration/api-contract.ts +84 -2
  31. package/src/integration/assessment-item-scorer.ts +53 -0
  32. package/src/integration/index.ts +5 -0
@@ -26,8 +26,8 @@
26
26
  * - Validates all requests with authentication
27
27
  * - Filters sensitive data based on role
28
28
  */
29
- import { buildExpression, DeclarationContext, evalExpr, OperatorRegistry, parseXml, qtiNull, qtiValue, } from '@pie-qti/qti-processing';
30
- import { Player } from '@pie-qti/item-player';
29
+ import { buildExpression, buildOutcomeProcessingAst, DeclarationContext, evalExpr, execProgram, OperatorRegistry, parseXml, serializeXml, qtiNull, qtiValue, } from '@pie-qti/qti-processing';
30
+ import { scoreAssessmentItem } from './assessment-item-scorer.js';
31
31
  /**
32
32
  * Storage key prefix for localStorage
33
33
  */
@@ -36,6 +36,16 @@ const STORAGE_PREFIX = 'qti_session_';
36
36
  * Cache key for item bank queries
37
37
  */
38
38
  const BANK_CACHE_PREFIX = 'qti_bank_cache_';
39
+ function toCanonicalQtiName(name) {
40
+ const withoutPrefix = (name ?? '').replace(/^qti-/, '');
41
+ return withoutPrefix.replace(/-([a-z])/g, (_, char) => char.toUpperCase());
42
+ }
43
+ const qtiElementNameMapper = {
44
+ version: 'qti2x-or-qti3',
45
+ toCanonical: (elementName) => toCanonicalQtiName(elementName).toLowerCase(),
46
+ toNative: (canonicalName) => canonicalName,
47
+ isValidElementName: () => true,
48
+ };
39
49
  /**
40
50
  * Reference Backend Adapter using localStorage
41
51
  *
@@ -65,6 +75,24 @@ export class ReferenceBackendAdapter {
65
75
  getAssessment(assessmentId) {
66
76
  return this.registeredAssessments.get(assessmentId) ?? this.createDemoAssessment(assessmentId);
67
77
  }
78
+ hasAnyResponse(responses) {
79
+ for (const value of Object.values(responses)) {
80
+ if (value == null)
81
+ continue;
82
+ if (Array.isArray(value)) {
83
+ if (value.length > 0)
84
+ return true;
85
+ continue;
86
+ }
87
+ if (typeof value === 'string') {
88
+ if (value.trim().length > 0)
89
+ return true;
90
+ continue;
91
+ }
92
+ return true;
93
+ }
94
+ return false;
95
+ }
68
96
  /**
69
97
  * Initialize a new assessment session
70
98
  */
@@ -142,13 +170,24 @@ export class ReferenceBackendAdapter {
142
170
  }
143
171
  // **SECURITY WARNING**: Client-side scoring is INSECURE
144
172
  // In production, this MUST be done server-side
145
- const result = this.scoreItem(itemXml, request.responses);
173
+ const result = scoreAssessmentItem({ itemXml, responses: request.responses });
146
174
  // Store responses and result
147
175
  session.state.itemResponses[request.itemIdentifier] = request.responses;
148
176
  if (!session.state.itemScores) {
149
177
  session.state.itemScores = {};
150
178
  }
151
179
  session.state.itemScores[request.itemIdentifier] = result;
180
+ const previousItemSession = session.state.itemSessionStates?.[request.itemIdentifier];
181
+ session.state.itemSessionStates = {
182
+ ...(session.state.itemSessionStates ?? {}),
183
+ [request.itemIdentifier]: {
184
+ itemIdentifier: request.itemIdentifier,
185
+ attemptCount: (previousItemSession?.attemptCount ?? 0) + 1,
186
+ isAnswered: this.hasAnyResponse(request.responses),
187
+ isSubmitted: true,
188
+ lastSubmissionTime: request.submittedAt,
189
+ },
190
+ };
152
191
  // Update timing
153
192
  if (request.timeSpent) {
154
193
  session.state.timing.itemTimes[request.itemIdentifier] = request.timeSpent;
@@ -161,14 +200,25 @@ export class ReferenceBackendAdapter {
161
200
  const order = this.getItemOrder(session.assessment);
162
201
  const idx = order.indexOf(request.itemIdentifier);
163
202
  let nextItemIdentifier = idx >= 0 ? order[idx + 1] : undefined;
164
- // Demo branching using qti-processing (backend-authoritative). If SCORE > 0, go to item2.
165
- if (request.itemIdentifier === 'item1') {
166
- const condXml = `<gt><variable identifier="SCORE" /><baseValue baseType="float">0</baseValue></gt>`;
167
- if (this.evaluateConditionXml(condXml, { SCORE: result.score })) {
168
- nextItemIdentifier = 'item2';
169
- }
170
- else {
171
- nextItemIdentifier = undefined;
203
+ // QTI branchRule evaluation (backend-authoritative).
204
+ // Evaluate each rule in order; the first matching rule determines the next item.
205
+ // Special targets EXIT_TEST / EXIT_TESTPART / EXIT_SECTION are returned as-is for
206
+ // the client to interpret.
207
+ const itemRef = this.findItemRef(session.assessment, request.itemIdentifier);
208
+ if (itemRef?.branchRule && itemRef.branchRule.length > 0) {
209
+ const outcomeVars = {
210
+ ...result.outcomeValues,
211
+ SCORE: result.score,
212
+ };
213
+ nextItemIdentifier = undefined; // reset — branch rules take full control
214
+ for (const rule of itemRef.branchRule) {
215
+ const matches = rule.conditionXml
216
+ ? this.evaluateConditionXml(rule.conditionXml, outcomeVars)
217
+ : true; // unconditional branch
218
+ if (matches) {
219
+ nextItemIdentifier = rule.target;
220
+ break;
221
+ }
172
222
  }
173
223
  }
174
224
  return {
@@ -216,8 +266,11 @@ export class ReferenceBackendAdapter {
216
266
  this.saveSession(session);
217
267
  // Compute total score
218
268
  const itemScores = session.state.itemScores || {};
219
- const totalScore = Object.values(itemScores).reduce((sum, result) => sum + result.score, 0);
269
+ const fallbackTotal = Object.values(itemScores).reduce((sum, result) => sum + result.score, 0);
220
270
  const maxScore = Object.values(itemScores).reduce((sum, result) => sum + result.maxScore, 0);
271
+ // Execute test-level outcome processing if available
272
+ const outcomes = this.runOutcomeProcessing(session.assessment, itemScores);
273
+ const totalScore = outcomes !== null ? (outcomes['SCORE_TOTAL'] ?? outcomes['SCORE'] ?? fallbackTotal) : fallbackTotal;
221
274
  return {
222
275
  success: true,
223
276
  totalScore,
@@ -226,6 +279,83 @@ export class ReferenceBackendAdapter {
226
279
  finalizedAt: Date.now(),
227
280
  };
228
281
  }
282
+ /**
283
+ * Execute test-level outcome processing (T9/T1).
284
+ * Returns a map of outcome variable values, or null if no outcomeProcessing is defined.
285
+ */
286
+ runOutcomeProcessing(assessment, itemScores) {
287
+ if (!assessment.outcomeProcessingXml) {
288
+ return null;
289
+ }
290
+ try {
291
+ // Build declaration map from outcomeDeclarations
292
+ const decls = {};
293
+ for (const d of assessment.outcomeDeclarations || []) {
294
+ const baseType = d.baseType;
295
+ const cardinality = d.cardinality;
296
+ let defaultQtiValue;
297
+ if (d.defaultValue !== undefined) {
298
+ defaultQtiValue = qtiValue(baseType, cardinality, d.defaultValue);
299
+ }
300
+ else if (baseType === 'float' || baseType === 'integer') {
301
+ defaultQtiValue = qtiValue(baseType, 'single', 0);
302
+ }
303
+ else {
304
+ defaultQtiValue = qtiNull();
305
+ }
306
+ decls[d.identifier] = {
307
+ identifier: d.identifier,
308
+ baseType,
309
+ cardinality,
310
+ defaultValue: defaultQtiValue,
311
+ value: { ...defaultQtiValue },
312
+ };
313
+ }
314
+ const ctx = new DeclarationContext(decls);
315
+ const ops = new OperatorRegistry();
316
+ // Build test items array for testVariables expression
317
+ const testItems = Object.entries(itemScores).map(([id, scoring]) => ({
318
+ identifier: id,
319
+ variables: {
320
+ SCORE: qtiValue('float', 'single', scoring.score),
321
+ // Add any other outcome values from the scoring result
322
+ ...Object.fromEntries(Object.entries(scoring.outcomeValues || {}).map(([k, v]) => [
323
+ k,
324
+ typeof v === 'number'
325
+ ? qtiValue('float', 'single', v)
326
+ : qtiValue('string', 'single', String(v)),
327
+ ])),
328
+ },
329
+ }));
330
+ // Parse and execute outcome processing
331
+ const opEl = parseXml(assessment.outcomeProcessingXml).documentElement;
332
+ if (!opEl)
333
+ return null;
334
+ const program = buildOutcomeProcessingAst(opEl, {
335
+ scope: 'test',
336
+ elementNameMapper: qtiElementNameMapper,
337
+ });
338
+ execProgram({
339
+ ctx,
340
+ ops,
341
+ rng: Math.random,
342
+ test: { items: testItems },
343
+ }, program);
344
+ // Extract outcome values
345
+ const result = {};
346
+ for (const d of assessment.outcomeDeclarations || []) {
347
+ const v = ctx.getValue(d.identifier);
348
+ if (v.kind === 'value') {
349
+ result[d.identifier] = v.value;
350
+ }
351
+ }
352
+ return result;
353
+ }
354
+ catch (err) {
355
+ console.warn('[ReferenceBackendAdapter] outcomeProcessing failed:', err);
356
+ return null;
357
+ }
358
+ }
229
359
  /**
230
360
  * Resume existing session (alias for initSession with resumeSessionId)
231
361
  */
@@ -315,46 +445,17 @@ export class ReferenceBackendAdapter {
315
445
  }
316
446
  return null;
317
447
  }
318
- /**
319
- * Score an item using the Player
320
- *
321
- * **SECURITY WARNING**: This is done CLIENT-SIDE for demo purposes only.
322
- * Production implementations MUST perform scoring SERVER-SIDE.
323
- */
324
- scoreItem(itemXml, responses) {
325
- try {
326
- // Extract identifier from XML using regex (more reliable than DOM parsing)
327
- const identifierMatch = itemXml.match(/assessmentItem[^>]+identifier=["']([^"']+)["']/);
328
- const itemIdentifier = identifierMatch?.[1] || 'unknown';
329
- // Use a scorer-grade view of the item for accurate scoring.
330
- // NOTE: This reference adapter is intentionally insecure and runs client-side.
331
- // In production, scoring must happen server-side with secured item content.
332
- const player = new Player({
333
- itemXml,
334
- role: 'scorer',
335
- });
336
- // Set responses using setResponses (plural)
337
- player.setResponses(responses);
338
- // Process and score
339
- const result = player.processResponses();
340
- return {
341
- itemIdentifier,
342
- score: result.score,
343
- maxScore: result.maxScore,
344
- completed: result.completed,
345
- outcomeValues: result.outcomeValues,
346
- };
347
- }
348
- catch (error) {
349
- console.error('Scoring error:', error);
350
- return {
351
- itemIdentifier: 'unknown',
352
- score: 0,
353
- maxScore: 1,
354
- completed: false,
355
- outcomeValues: {},
356
- };
448
+ findItemRef(assessment, itemIdentifier) {
449
+ for (const part of assessment.testParts) {
450
+ for (const section of part.sections) {
451
+ for (const item of section.assessmentItemRefs) {
452
+ if (item.identifier === itemIdentifier) {
453
+ return item;
454
+ }
455
+ }
456
+ }
357
457
  }
458
+ return null;
358
459
  }
359
460
  /**
360
461
  * Create demo assessment for testing
@@ -475,6 +576,263 @@ export class ReferenceBackendAdapter {
475
576
  ],
476
577
  };
477
578
  }
579
+ // =========================================================================
580
+ // STATIC: QTI TEST XML PARSER
581
+ // =========================================================================
582
+ /**
583
+ * Parse a QTI assessmentTest XML string into a SecureAssessment structure.
584
+ *
585
+ * Handles:
586
+ * - S1: section-level itemSessionControl
587
+ * - S9: assessmentSectionRef href resolution (requires fileResolver)
588
+ * - T9/T1: outcomeDeclarations + outcomeProcessing extraction
589
+ *
590
+ * @param testXml - Raw QTI assessmentTest XML string
591
+ * @param options.role - Role to assign to items (default: 'candidate')
592
+ * @param options.itemXmlMap - Map of item identifier -> itemXml for pre-loaded items
593
+ * @param options.fileResolver - Async function to load external files by relative href
594
+ * @param options.baseUrl - Base URL for resolving relative hrefs
595
+ */
596
+ static async parseAssessmentTestXml(testXml, options = {}) {
597
+ const { role = 'candidate', itemXmlMap = {}, fileResolver, baseUrl } = options;
598
+ const doc = parseXml(testXml);
599
+ const root = doc.documentElement;
600
+ if (!root)
601
+ throw new Error('Empty assessmentTest XML');
602
+ const getAttr = (el, name) => {
603
+ const direct = el.getAttribute(name);
604
+ if (direct !== null && direct !== '')
605
+ return direct;
606
+ const mapped = el.getAttribute(name.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`));
607
+ return mapped === null || mapped === '' ? undefined : mapped;
608
+ };
609
+ const childElements = (el) => Array.from(el.childNodes).filter((n) => n.nodeType === 1);
610
+ const childrenByTag = (el, tag) => childElements(el).filter((c) => toCanonicalQtiName(c.localName) === tag);
611
+ // Parse itemSessionControl element
612
+ const parseItemSessionControl = (el) => {
613
+ const isc = childrenByTag(el, 'itemSessionControl')[0];
614
+ if (!isc)
615
+ return undefined;
616
+ const boolAttr = (name) => {
617
+ const v = getAttr(isc, name);
618
+ return v === undefined ? undefined : v !== 'false';
619
+ };
620
+ const intAttr = (name) => {
621
+ const v = getAttr(isc, name);
622
+ return v === undefined ? undefined : parseInt(v, 10);
623
+ };
624
+ return {
625
+ maxAttempts: intAttr('maxAttempts'),
626
+ showFeedback: boolAttr('showFeedback') ?? boolAttr('show-feedback'),
627
+ allowReview: boolAttr('allowReview') ?? boolAttr('allow-review'),
628
+ showSolution: boolAttr('showSolution') ?? boolAttr('show-solution'),
629
+ allowComment: boolAttr('allowComment') ?? boolAttr('allow-comment'),
630
+ allowSkipping: boolAttr('allowSkipping') ?? boolAttr('allow-skipping'),
631
+ validateResponses: boolAttr('validateResponses') ?? boolAttr('validate-responses'),
632
+ };
633
+ };
634
+ // Parse a single assessmentSection element
635
+ const parseSection = (sectionEl) => {
636
+ const identifier = getAttr(sectionEl, 'identifier') ?? 'section';
637
+ const title = getAttr(sectionEl, 'title');
638
+ const visibleRaw = getAttr(sectionEl, 'visible');
639
+ const visible = visibleRaw === undefined ? true : visibleRaw !== 'false';
640
+ const itemSessionControl = parseItemSessionControl(sectionEl);
641
+ // rubricBlocks
642
+ const rubricBlockEls = childrenByTag(sectionEl, 'rubricBlock');
643
+ const rubricBlocks = rubricBlockEls.length > 0
644
+ ? rubricBlockEls.map((b, idx) => ({
645
+ identifier: getAttr(b, 'identifier') ?? `${identifier}-rubric-${idx + 1}`,
646
+ view: (getAttr(b, 'view') ?? 'candidate').split(/\s+/).filter(Boolean),
647
+ use: getAttr(b, 'use'),
648
+ content: serializeXml(b),
649
+ }))
650
+ : undefined;
651
+ // assessmentItemRefs
652
+ const itemRefEls = childrenByTag(sectionEl, 'assessmentItemRef');
653
+ const assessmentItemRefs = itemRefEls.map((ref) => {
654
+ const itemId = getAttr(ref, 'identifier') ?? 'item';
655
+ const href = getAttr(ref, 'href');
656
+ // Look up pre-loaded XML by identifier or href
657
+ const resolvedXml = itemXmlMap[itemId] ?? (href ? itemXmlMap[href] : undefined) ?? '';
658
+ const requiredRaw = getAttr(ref, 'required');
659
+ const required = requiredRaw === undefined ? undefined : requiredRaw !== 'false';
660
+ return {
661
+ identifier: itemId,
662
+ itemXml: resolvedXml,
663
+ role,
664
+ required,
665
+ };
666
+ });
667
+ return {
668
+ identifier,
669
+ title,
670
+ visible,
671
+ assessmentItemRefs,
672
+ rubricBlocks,
673
+ itemSessionControl,
674
+ };
675
+ };
676
+ // Resolve assessmentSectionRef: load and parse referenced section file
677
+ const resolveSectionRef = async (sectionRefEl) => {
678
+ const href = getAttr(sectionRefEl, 'href');
679
+ if (!href) {
680
+ console.warn('[ReferenceBackendAdapter] assessmentSectionRef missing href, skipping');
681
+ return null;
682
+ }
683
+ if (!fileResolver) {
684
+ console.warn(`[ReferenceBackendAdapter] assessmentSectionRef href="${href}" found but no fileResolver provided, skipping`);
685
+ return null;
686
+ }
687
+ try {
688
+ const sectionXml = await fileResolver(href);
689
+ const secDoc = parseXml(sectionXml);
690
+ const secRoot = secDoc.documentElement;
691
+ if (!secRoot || toCanonicalQtiName(secRoot.localName) !== 'assessmentSection') {
692
+ console.warn(`[ReferenceBackendAdapter] assessmentSectionRef href="${href}": root element is not <assessmentSection>, skipping`);
693
+ return null;
694
+ }
695
+ return parseSection(secRoot);
696
+ }
697
+ catch (err) {
698
+ console.warn(`[ReferenceBackendAdapter] Failed to load assessmentSectionRef href="${href}":`, err);
699
+ return null;
700
+ }
701
+ };
702
+ // Parse testPart children (sections + sectionRefs)
703
+ const parseSectionsForTestPart = async (testPartEl) => {
704
+ const sections = [];
705
+ for (const child of childElements(testPartEl)) {
706
+ if (toCanonicalQtiName(child.localName) === 'assessmentSection') {
707
+ sections.push(parseSection(child));
708
+ }
709
+ else if (toCanonicalQtiName(child.localName) === 'assessmentSectionRef') {
710
+ const resolved = await resolveSectionRef(child);
711
+ if (resolved)
712
+ sections.push(resolved);
713
+ }
714
+ }
715
+ return sections;
716
+ };
717
+ // Parse testPart-level itemSessionControl
718
+ const parseTestPartItemSessionControl = (testPartEl) => {
719
+ const isc = childrenByTag(testPartEl, 'itemSessionControl')[0];
720
+ if (!isc)
721
+ return undefined;
722
+ const boolAttr = (name) => {
723
+ const v = getAttr(isc, name);
724
+ return v === undefined ? undefined : v !== 'false';
725
+ };
726
+ const intAttr = (name) => {
727
+ const v = getAttr(isc, name);
728
+ return v === undefined ? undefined : parseInt(v, 10);
729
+ };
730
+ return {
731
+ maxAttempts: intAttr('maxAttempts'),
732
+ showFeedback: boolAttr('showFeedback') ?? boolAttr('show-feedback'),
733
+ allowReview: boolAttr('allowReview') ?? boolAttr('allow-review'),
734
+ showSolution: boolAttr('showSolution') ?? boolAttr('show-solution'),
735
+ allowComment: boolAttr('allowComment') ?? boolAttr('allow-comment'),
736
+ allowSkipping: boolAttr('allowSkipping') ?? boolAttr('allow-skipping'),
737
+ validateResponses: boolAttr('validateResponses') ?? boolAttr('validate-responses'),
738
+ };
739
+ };
740
+ // Extract outcomeDeclarations
741
+ const outcomeDeclarations = childrenByTag(root, 'outcomeDeclaration').map((d) => {
742
+ const identifier = getAttr(d, 'identifier') ?? 'OUTCOME';
743
+ const baseType = getAttr(d, 'baseType') ?? 'float';
744
+ const cardinality = getAttr(d, 'cardinality') ?? 'single';
745
+ // Parse defaultValue if present
746
+ const defaultValueEl = childrenByTag(d, 'defaultValue')[0];
747
+ let defaultValue = undefined;
748
+ if (defaultValueEl) {
749
+ const valueEl = childrenByTag(defaultValueEl, 'value')[0];
750
+ if (valueEl) {
751
+ const text = valueEl.textContent?.trim() ?? '0';
752
+ if (baseType === 'float' || baseType === 'integer') {
753
+ defaultValue = Number(text);
754
+ }
755
+ else {
756
+ defaultValue = text;
757
+ }
758
+ }
759
+ }
760
+ return { identifier, baseType, cardinality, defaultValue };
761
+ });
762
+ // Extract outcomeProcessing XML
763
+ const outcomeProcessingEl = childrenByTag(root, 'outcomeProcessing')[0];
764
+ const outcomeProcessingXml = outcomeProcessingEl
765
+ ? serializeXml(outcomeProcessingEl)
766
+ : undefined;
767
+ // Extract timeLimits
768
+ const timeLimitsEl = childrenByTag(root, 'timeLimit')[0] ?? childrenByTag(root, 'timeLimits')[0];
769
+ const timeLimits = timeLimitsEl
770
+ ? {
771
+ maxTime: getAttr(timeLimitsEl, 'maxTime')
772
+ ? Number(getAttr(timeLimitsEl, 'maxTime'))
773
+ : undefined,
774
+ allowLateSubmission: getAttr(timeLimitsEl, 'allowLateSubmission') === 'true',
775
+ }
776
+ : undefined;
777
+ // Parse testParts
778
+ const testPartEls = childrenByTag(root, 'testPart');
779
+ const firstTestPart = testPartEls[0];
780
+ // Navigation/submission mode from first testPart (QTI 2.2 spec)
781
+ const navigationMode = (getAttr(firstTestPart ?? root, 'navigationMode') ?? 'nonlinear');
782
+ const submissionMode = (getAttr(firstTestPart ?? root, 'submissionMode') ?? 'simultaneous');
783
+ const testParts = [];
784
+ for (const tp of testPartEls) {
785
+ const tpIdentifier = getAttr(tp, 'identifier') ?? 'part-1';
786
+ const tpItemSessionControl = parseTestPartItemSessionControl(tp);
787
+ const tpRubricBlockEls = childrenByTag(tp, 'rubricBlock');
788
+ const tpRubricBlocks = tpRubricBlockEls.length > 0
789
+ ? tpRubricBlockEls.map((b, idx) => ({
790
+ identifier: getAttr(b, 'identifier') ?? `${tpIdentifier}-rubric-${idx + 1}`,
791
+ view: (getAttr(b, 'view') ?? 'candidate').split(/\s+/).filter(Boolean),
792
+ use: getAttr(b, 'use'),
793
+ content: serializeXml(b),
794
+ }))
795
+ : undefined;
796
+ const sections = await parseSectionsForTestPart(tp);
797
+ testParts.push({
798
+ identifier: tpIdentifier,
799
+ sections,
800
+ rubricBlocks: tpRubricBlocks,
801
+ itemSessionControl: tpItemSessionControl,
802
+ });
803
+ }
804
+ // If no testParts, try top-level sections
805
+ if (testParts.length === 0) {
806
+ const topSections = [];
807
+ for (const child of childElements(root)) {
808
+ if (toCanonicalQtiName(child.localName) === 'assessmentSection') {
809
+ topSections.push(parseSection(child));
810
+ }
811
+ else if (toCanonicalQtiName(child.localName) === 'assessmentSectionRef') {
812
+ const resolved = await resolveSectionRef(child);
813
+ if (resolved)
814
+ topSections.push(resolved);
815
+ }
816
+ }
817
+ if (topSections.length > 0) {
818
+ testParts.push({
819
+ identifier: 'part-1',
820
+ sections: topSections,
821
+ });
822
+ }
823
+ }
824
+ return {
825
+ identifier: getAttr(root, 'identifier') ?? 'assessment',
826
+ title: getAttr(root, 'title') ?? 'Assessment',
827
+ navigationMode,
828
+ submissionMode,
829
+ testParts,
830
+ timeLimits,
831
+ outcomeDeclarations: outcomeDeclarations.length > 0 ? outcomeDeclarations : undefined,
832
+ outcomeProcessingXml,
833
+ baseUrl,
834
+ };
835
+ }
478
836
  evaluateConditionXml(conditionXml, vars) {
479
837
  // conditionXml is an operator element like <gt>...</gt> (not wrapped in <expression>).
480
838
  const doc = parseXml(conditionXml);
@@ -48,6 +48,17 @@ export interface InitSessionResponse {
48
48
  *
49
49
  * Security: NO correct answers, NO scoring rules, NO sensitive rubrics
50
50
  */
51
+ export interface TestFeedbackItem {
52
+ identifier: string;
53
+ /** Outcome variable name to evaluate (e.g. "PASS", "GRADE") */
54
+ outcomeIdentifier: string;
55
+ /** 'show' = show when outcome equals identifier; 'hide' = show when it does not */
56
+ showHide: 'show' | 'hide';
57
+ /** 'atEnd' = only after submission; 'during' = also during attempt */
58
+ access: 'atEnd' | 'during';
59
+ /** HTML content to display */
60
+ content: string;
61
+ }
51
62
  export interface SecureAssessment {
52
63
  identifier: string;
53
64
  title: string;
@@ -62,6 +73,19 @@ export interface SecureAssessment {
62
73
  maxTime?: number;
63
74
  allowLateSubmission?: boolean;
64
75
  };
76
+ /** QTI outcomeDeclarations for test-level variables */
77
+ outcomeDeclarations?: Array<{
78
+ identifier: string;
79
+ baseType: string;
80
+ cardinality: string;
81
+ defaultValue?: unknown;
82
+ }>;
83
+ /** Raw <outcomeProcessing> XML string, if present */
84
+ outcomeProcessingXml?: string;
85
+ /** Base URL/path for resolving relative hrefs (e.g. assessmentSectionRef) */
86
+ baseUrl?: string;
87
+ /** QTI testFeedback blocks for post-submission display */
88
+ testFeedback?: TestFeedbackItem[];
65
89
  }
66
90
  export interface SecureTestPart {
67
91
  identifier: string;
@@ -88,7 +112,7 @@ export interface SecureSection {
88
112
  title?: string;
89
113
  /** Visible determines if section appears in navigation */
90
114
  visible: boolean;
91
- /** Assessment item references */
115
+ /** Assessment item references (order reflects selection/ordering already applied server-side) */
92
116
  assessmentItemRefs: SecureItemRef[];
93
117
  /** Section-level time limit */
94
118
  timeLimits?: {
@@ -96,6 +120,35 @@ export interface SecureSection {
96
120
  };
97
121
  /** Candidate instructions (safe for display) */
98
122
  rubricBlocks?: AssessmentRubricBlock[];
123
+ /**
124
+ * QTI selection: how many items to present from this section.
125
+ * When present the server has already applied selection; client uses this for progress display.
126
+ */
127
+ selection?: {
128
+ /** Number of items selected for this session */
129
+ select: number;
130
+ withReplacement?: boolean;
131
+ };
132
+ /**
133
+ * QTI ordering: whether items were shuffled.
134
+ * When true the server has already shuffled assessmentItemRefs.
135
+ */
136
+ ordering?: {
137
+ shuffle: boolean;
138
+ };
139
+ /**
140
+ * Item session control (QTI assessmentSection/itemSessionControl).
141
+ * Section-level values take precedence over testPart-level when present.
142
+ */
143
+ itemSessionControl?: {
144
+ maxAttempts?: number;
145
+ showFeedback?: boolean;
146
+ allowReview?: boolean;
147
+ showSolution?: boolean;
148
+ allowComment?: boolean;
149
+ allowSkipping?: boolean;
150
+ validateResponses?: boolean;
151
+ };
99
152
  }
100
153
  export interface SecureItemRef {
101
154
  /** Unique item identifier */
@@ -106,6 +159,18 @@ export interface SecureItemRef {
106
159
  role: QTIRole;
107
160
  /** Required=true means item must be attempted */
108
161
  required?: boolean;
162
+ /**
163
+ * QTI branchRule: ordered list of branch rules on this item.
164
+ * The backend evaluates these after scoring and returns nextItemIdentifier in SubmitResponsesResponse.
165
+ * Carried here so reference/demo adapters can evaluate them client-side.
166
+ */
167
+ branchRule?: Array<{
168
+ /** Identifier of the target item, section, testPart, or one of the special values:
169
+ * EXIT_TEST | EXIT_TESTPART | EXIT_SECTION */
170
+ target: string;
171
+ /** Serialised QTI expression XML (the child of <branchRule>). Absent means unconditional. */
172
+ conditionXml?: string;
173
+ }>;
109
174
  }
110
175
  export interface AssessmentRubricBlock {
111
176
  /** Optional rubric identifier (QTI rubricBlock@identifier) */
@@ -208,6 +273,8 @@ export interface AssessmentSessionState {
208
273
  itemResponses: Record<string, Record<string, ResponseValue>>;
209
274
  /** Scoring results per item (populated after submission) */
210
275
  itemScores?: Record<string, AssessmentScoringResult>;
276
+ /** ItemSession lifecycle hints per item, used to restore attempt/review UI state */
277
+ itemSessionStates?: Record<string, AssessmentItemSessionState>;
211
278
  /** Time tracking */
212
279
  timing: {
213
280
  /** Session start time */
@@ -218,6 +285,13 @@ export interface AssessmentSessionState {
218
285
  totalTime: number;
219
286
  };
220
287
  }
288
+ export interface AssessmentItemSessionState {
289
+ itemIdentifier: string;
290
+ attemptCount: number;
291
+ isAnswered: boolean;
292
+ isSubmitted: boolean;
293
+ lastSubmissionTime?: number;
294
+ }
221
295
  /**
222
296
  * Finalize assessment and get full results
223
297
  *
@@ -234,8 +308,14 @@ export interface FinalizeAssessmentResponse {
234
308
  maxScore: number;
235
309
  /** Per-item results */
236
310
  itemScores: Record<string, AssessmentScoringResult>;
237
- /** Assessment-level feedback */
311
+ /** Assessment-level feedback (legacy: single string; prefer outcomes + assessment.testFeedback) */
238
312
  feedback?: string;
313
+ /**
314
+ * Test-level outcome variable values after outcomeProcessing.
315
+ * Used to evaluate testFeedback visibility via string equality.
316
+ * Keys are outcome identifiers (e.g. "PASS", "GRADE"); values are their string representations.
317
+ */
318
+ outcomes?: Record<string, string>;
239
319
  /** Server timestamp */
240
320
  finalizedAt: number;
241
321
  }