@pie-qti/assessment-player 0.1.4 → 0.1.5

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.
@@ -29,11 +29,14 @@
29
29
 
30
30
  import {
31
31
  buildExpression,
32
+ buildOutcomeProcessingAst,
32
33
  DeclarationContext,
33
34
  type DeclarationMap,
34
35
  evalExpr,
36
+ execProgram,
35
37
  OperatorRegistry,
36
38
  parseXml,
39
+ serializeXml,
37
40
  type QtiValue,
38
41
  qtiNull,
39
42
  qtiValue,
@@ -54,6 +57,8 @@ import type {
54
57
  SaveAssessmentStateResponse,
55
58
  SecureAssessment,
56
59
  SecureItemRef,
60
+ SecureSection,
61
+ SecureTestPart,
57
62
  SessionId,
58
63
  SubmitResponsesRequest,
59
64
  SubmitResponsesResponse,
@@ -69,6 +74,18 @@ const STORAGE_PREFIX = 'qti_session_';
69
74
  */
70
75
  const BANK_CACHE_PREFIX = 'qti_bank_cache_';
71
76
 
77
+ function toCanonicalQtiName(name: string | null | undefined): string {
78
+ const withoutPrefix = (name ?? '').replace(/^qti-/, '');
79
+ return withoutPrefix.replace(/-([a-z])/g, (_, char: string) => char.toUpperCase());
80
+ }
81
+
82
+ const qtiElementNameMapper = {
83
+ version: 'qti2x-or-qti3',
84
+ toCanonical: (elementName: string) => toCanonicalQtiName(elementName).toLowerCase(),
85
+ toNative: (canonicalName: string) => canonicalName,
86
+ isValidElementName: () => true,
87
+ };
88
+
72
89
  /**
73
90
  * Cache entry for item bank queries
74
91
  */
@@ -235,15 +252,27 @@ export class ReferenceBackendAdapter implements BackendAdapter {
235
252
 
236
253
  const order = this.getItemOrder(session.assessment);
237
254
  const idx = order.indexOf(request.itemIdentifier);
238
- let nextItemIdentifier = idx >= 0 ? order[idx + 1] : undefined;
239
-
240
- // Demo branching using qti-processing (backend-authoritative). If SCORE > 0, go to item2.
241
- if (request.itemIdentifier === 'item1') {
242
- const condXml = `<gt><variable identifier="SCORE" /><baseValue baseType="float">0</baseValue></gt>`;
243
- if (this.evaluateConditionXml(condXml, { SCORE: result.score })) {
244
- nextItemIdentifier = 'item2';
245
- } else {
246
- nextItemIdentifier = undefined;
255
+ let nextItemIdentifier: string | undefined = idx >= 0 ? order[idx + 1] : undefined;
256
+
257
+ // QTI branchRule evaluation (backend-authoritative).
258
+ // Evaluate each rule in order; the first matching rule determines the next item.
259
+ // Special targets EXIT_TEST / EXIT_TESTPART / EXIT_SECTION are returned as-is for
260
+ // the client to interpret.
261
+ const itemRef = this.findItemRef(session.assessment, request.itemIdentifier);
262
+ if (itemRef?.branchRule && itemRef.branchRule.length > 0) {
263
+ const outcomeVars: Record<string, unknown> = {
264
+ ...result.outcomeValues,
265
+ SCORE: result.score,
266
+ };
267
+ nextItemIdentifier = undefined; // reset — branch rules take full control
268
+ for (const rule of itemRef.branchRule) {
269
+ const matches = rule.conditionXml
270
+ ? this.evaluateConditionXml(rule.conditionXml, outcomeVars)
271
+ : true; // unconditional branch
272
+ if (matches) {
273
+ nextItemIdentifier = rule.target;
274
+ break;
275
+ }
247
276
  }
248
277
  }
249
278
 
@@ -300,9 +329,13 @@ export class ReferenceBackendAdapter implements BackendAdapter {
300
329
 
301
330
  // Compute total score
302
331
  const itemScores = session.state.itemScores || {};
303
- const totalScore = Object.values(itemScores).reduce((sum, result) => sum + result.score, 0);
332
+ const fallbackTotal = Object.values(itemScores).reduce((sum, result) => sum + result.score, 0);
304
333
  const maxScore = Object.values(itemScores).reduce((sum, result) => sum + result.maxScore, 0);
305
334
 
335
+ // Execute test-level outcome processing if available
336
+ const outcomes = this.runOutcomeProcessing(session.assessment, itemScores);
337
+ const totalScore = outcomes !== null ? (outcomes['SCORE_TOTAL'] ?? outcomes['SCORE'] ?? fallbackTotal) as number : fallbackTotal;
338
+
306
339
  return {
307
340
  success: true,
308
341
  totalScore,
@@ -312,6 +345,94 @@ export class ReferenceBackendAdapter implements BackendAdapter {
312
345
  };
313
346
  }
314
347
 
348
+ /**
349
+ * Execute test-level outcome processing (T9/T1).
350
+ * Returns a map of outcome variable values, or null if no outcomeProcessing is defined.
351
+ */
352
+ private runOutcomeProcessing(
353
+ assessment: SecureAssessment,
354
+ itemScores: Record<string, AssessmentScoringResult>
355
+ ): Record<string, unknown> | null {
356
+ if (!assessment.outcomeProcessingXml) {
357
+ return null;
358
+ }
359
+
360
+ try {
361
+ // Build declaration map from outcomeDeclarations
362
+ const decls: DeclarationMap = {};
363
+ for (const d of assessment.outcomeDeclarations || []) {
364
+ const baseType = d.baseType as any;
365
+ const cardinality = d.cardinality as any;
366
+ let defaultQtiValue: QtiValue;
367
+ if (d.defaultValue !== undefined) {
368
+ defaultQtiValue = qtiValue(baseType, cardinality, d.defaultValue);
369
+ } else if (baseType === 'float' || baseType === 'integer') {
370
+ defaultQtiValue = qtiValue(baseType, 'single', 0);
371
+ } else {
372
+ defaultQtiValue = qtiNull();
373
+ }
374
+ decls[d.identifier] = {
375
+ identifier: d.identifier,
376
+ baseType,
377
+ cardinality,
378
+ defaultValue: defaultQtiValue,
379
+ value: { ...defaultQtiValue },
380
+ };
381
+ }
382
+
383
+ const ctx = new DeclarationContext(decls);
384
+ const ops = new OperatorRegistry();
385
+
386
+ // Build test items array for testVariables expression
387
+ const testItems = Object.entries(itemScores).map(([id, scoring]) => ({
388
+ identifier: id,
389
+ variables: {
390
+ SCORE: qtiValue('float', 'single', scoring.score),
391
+ // Add any other outcome values from the scoring result
392
+ ...Object.fromEntries(
393
+ Object.entries(scoring.outcomeValues || {}).map(([k, v]) => [
394
+ k,
395
+ typeof v === 'number'
396
+ ? qtiValue('float', 'single', v)
397
+ : qtiValue('string', 'single', String(v)),
398
+ ])
399
+ ),
400
+ },
401
+ }));
402
+
403
+ // Parse and execute outcome processing
404
+ const opEl = parseXml(assessment.outcomeProcessingXml).documentElement;
405
+ if (!opEl) return null;
406
+
407
+ const program = buildOutcomeProcessingAst(opEl, {
408
+ scope: 'test',
409
+ elementNameMapper: qtiElementNameMapper,
410
+ });
411
+ execProgram(
412
+ {
413
+ ctx,
414
+ ops,
415
+ rng: Math.random,
416
+ test: { items: testItems },
417
+ },
418
+ program
419
+ );
420
+
421
+ // Extract outcome values
422
+ const result: Record<string, unknown> = {};
423
+ for (const d of assessment.outcomeDeclarations || []) {
424
+ const v = ctx.getValue(d.identifier);
425
+ if (v.kind === 'value') {
426
+ result[d.identifier] = v.value;
427
+ }
428
+ }
429
+ return result;
430
+ } catch (err) {
431
+ console.warn('[ReferenceBackendAdapter] outcomeProcessing failed:', err);
432
+ return null;
433
+ }
434
+ }
435
+
315
436
  /**
316
437
  * Resume existing session (alias for initSession with resumeSessionId)
317
438
  */
@@ -410,6 +531,19 @@ export class ReferenceBackendAdapter implements BackendAdapter {
410
531
  return null;
411
532
  }
412
533
 
534
+ private findItemRef(assessment: SecureAssessment, itemIdentifier: string): SecureItemRef | null {
535
+ for (const part of assessment.testParts) {
536
+ for (const section of part.sections) {
537
+ for (const item of section.assessmentItemRefs) {
538
+ if (item.identifier === itemIdentifier) {
539
+ return item;
540
+ }
541
+ }
542
+ }
543
+ }
544
+ return null;
545
+ }
546
+
413
547
  /**
414
548
  * Score an item using the Player
415
549
  *
@@ -575,6 +709,303 @@ export class ReferenceBackendAdapter implements BackendAdapter {
575
709
  };
576
710
  }
577
711
 
712
+ // =========================================================================
713
+ // STATIC: QTI TEST XML PARSER
714
+ // =========================================================================
715
+
716
+ /**
717
+ * Parse a QTI assessmentTest XML string into a SecureAssessment structure.
718
+ *
719
+ * Handles:
720
+ * - S1: section-level itemSessionControl
721
+ * - S9: assessmentSectionRef href resolution (requires fileResolver)
722
+ * - T9/T1: outcomeDeclarations + outcomeProcessing extraction
723
+ *
724
+ * @param testXml - Raw QTI assessmentTest XML string
725
+ * @param options.role - Role to assign to items (default: 'candidate')
726
+ * @param options.itemXmlMap - Map of item identifier -> itemXml for pre-loaded items
727
+ * @param options.fileResolver - Async function to load external files by relative href
728
+ * @param options.baseUrl - Base URL for resolving relative hrefs
729
+ */
730
+ static async parseAssessmentTestXml(
731
+ testXml: string,
732
+ options: {
733
+ role?: SecureItemRef['role'];
734
+ itemXmlMap?: Record<string, string>;
735
+ fileResolver?: (href: string) => Promise<string>;
736
+ baseUrl?: string;
737
+ } = {}
738
+ ): Promise<SecureAssessment> {
739
+ const { role = 'candidate', itemXmlMap = {}, fileResolver, baseUrl } = options;
740
+ const doc = parseXml(testXml);
741
+ const root = doc.documentElement;
742
+ if (!root) throw new Error('Empty assessmentTest XML');
743
+
744
+ const getAttr = (el: Element, name: string): string | undefined => {
745
+ const direct = el.getAttribute(name);
746
+ if (direct !== null && direct !== '') return direct;
747
+ const mapped = el.getAttribute(name.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`));
748
+ return mapped === null || mapped === '' ? undefined : mapped;
749
+ };
750
+
751
+ const childElements = (el: Element): Element[] =>
752
+ Array.from(el.childNodes).filter((n): n is Element => n.nodeType === 1);
753
+
754
+ const childrenByTag = (el: Element, tag: string): Element[] =>
755
+ childElements(el).filter((c) => toCanonicalQtiName(c.localName) === tag);
756
+
757
+ // Parse itemSessionControl element
758
+ const parseItemSessionControl = (
759
+ el: Element
760
+ ): SecureSection['itemSessionControl'] | undefined => {
761
+ const isc = childrenByTag(el, 'itemSessionControl')[0];
762
+ if (!isc) return undefined;
763
+ const boolAttr = (name: string): boolean | undefined => {
764
+ const v = getAttr(isc, name);
765
+ return v === undefined ? undefined : v !== 'false';
766
+ };
767
+ const intAttr = (name: string): number | undefined => {
768
+ const v = getAttr(isc, name);
769
+ return v === undefined ? undefined : parseInt(v, 10);
770
+ };
771
+ return {
772
+ maxAttempts: intAttr('maxAttempts'),
773
+ showFeedback: boolAttr('showFeedback') ?? boolAttr('show-feedback'),
774
+ allowReview: boolAttr('allowReview') ?? boolAttr('allow-review'),
775
+ showSolution: boolAttr('showSolution') ?? boolAttr('show-solution'),
776
+ allowComment: boolAttr('allowComment') ?? boolAttr('allow-comment'),
777
+ allowSkipping: boolAttr('allowSkipping') ?? boolAttr('allow-skipping'),
778
+ validateResponses: boolAttr('validateResponses') ?? boolAttr('validate-responses'),
779
+ };
780
+ };
781
+
782
+ // Parse a single assessmentSection element
783
+ const parseSection = (sectionEl: Element): SecureSection => {
784
+ const identifier = getAttr(sectionEl, 'identifier') ?? 'section';
785
+ const title = getAttr(sectionEl, 'title');
786
+ const visibleRaw = getAttr(sectionEl, 'visible');
787
+ const visible = visibleRaw === undefined ? true : visibleRaw !== 'false';
788
+
789
+ const itemSessionControl = parseItemSessionControl(sectionEl);
790
+
791
+ // rubricBlocks
792
+ const rubricBlockEls = childrenByTag(sectionEl, 'rubricBlock');
793
+ const rubricBlocks = rubricBlockEls.length > 0
794
+ ? rubricBlockEls.map((b, idx) => ({
795
+ identifier: getAttr(b, 'identifier') ?? `${identifier}-rubric-${idx + 1}`,
796
+ view: (getAttr(b, 'view') ?? 'candidate').split(/\s+/).filter(Boolean) as any[],
797
+ use: getAttr(b, 'use'),
798
+ content: serializeXml(b),
799
+ }))
800
+ : undefined;
801
+
802
+ // assessmentItemRefs
803
+ const itemRefEls = childrenByTag(sectionEl, 'assessmentItemRef');
804
+ const assessmentItemRefs: SecureItemRef[] = itemRefEls.map((ref) => {
805
+ const itemId = getAttr(ref, 'identifier') ?? 'item';
806
+ const href = getAttr(ref, 'href');
807
+ // Look up pre-loaded XML by identifier or href
808
+ const resolvedXml = itemXmlMap[itemId] ?? (href ? itemXmlMap[href] : undefined) ?? '';
809
+ const requiredRaw = getAttr(ref, 'required');
810
+ const required = requiredRaw === undefined ? undefined : requiredRaw !== 'false';
811
+ return {
812
+ identifier: itemId,
813
+ itemXml: resolvedXml,
814
+ role,
815
+ required,
816
+ };
817
+ });
818
+
819
+ return {
820
+ identifier,
821
+ title,
822
+ visible,
823
+ assessmentItemRefs,
824
+ rubricBlocks,
825
+ itemSessionControl,
826
+ };
827
+ };
828
+
829
+ // Resolve assessmentSectionRef: load and parse referenced section file
830
+ const resolveSectionRef = async (sectionRefEl: Element): Promise<SecureSection | null> => {
831
+ const href = getAttr(sectionRefEl, 'href');
832
+ if (!href) {
833
+ console.warn('[ReferenceBackendAdapter] assessmentSectionRef missing href, skipping');
834
+ return null;
835
+ }
836
+
837
+ if (!fileResolver) {
838
+ console.warn(
839
+ `[ReferenceBackendAdapter] assessmentSectionRef href="${href}" found but no fileResolver provided, skipping`
840
+ );
841
+ return null;
842
+ }
843
+
844
+ try {
845
+ const sectionXml = await fileResolver(href);
846
+ const secDoc = parseXml(sectionXml);
847
+ const secRoot = secDoc.documentElement;
848
+ if (!secRoot || toCanonicalQtiName(secRoot.localName) !== 'assessmentSection') {
849
+ console.warn(
850
+ `[ReferenceBackendAdapter] assessmentSectionRef href="${href}": root element is not <assessmentSection>, skipping`
851
+ );
852
+ return null;
853
+ }
854
+ return parseSection(secRoot);
855
+ } catch (err) {
856
+ console.warn(
857
+ `[ReferenceBackendAdapter] Failed to load assessmentSectionRef href="${href}":`,
858
+ err
859
+ );
860
+ return null;
861
+ }
862
+ };
863
+
864
+ // Parse testPart children (sections + sectionRefs)
865
+ const parseSectionsForTestPart = async (testPartEl: Element): Promise<SecureSection[]> => {
866
+ const sections: SecureSection[] = [];
867
+ for (const child of childElements(testPartEl)) {
868
+ if (toCanonicalQtiName(child.localName) === 'assessmentSection') {
869
+ sections.push(parseSection(child));
870
+ } else if (toCanonicalQtiName(child.localName) === 'assessmentSectionRef') {
871
+ const resolved = await resolveSectionRef(child);
872
+ if (resolved) sections.push(resolved);
873
+ }
874
+ }
875
+ return sections;
876
+ };
877
+
878
+ // Parse testPart-level itemSessionControl
879
+ const parseTestPartItemSessionControl = (
880
+ testPartEl: Element
881
+ ): SecureTestPart['itemSessionControl'] | undefined => {
882
+ const isc = childrenByTag(testPartEl, 'itemSessionControl')[0];
883
+ if (!isc) return undefined;
884
+ const boolAttr = (name: string): boolean | undefined => {
885
+ const v = getAttr(isc, name);
886
+ return v === undefined ? undefined : v !== 'false';
887
+ };
888
+ const intAttr = (name: string): number | undefined => {
889
+ const v = getAttr(isc, name);
890
+ return v === undefined ? undefined : parseInt(v, 10);
891
+ };
892
+ return {
893
+ maxAttempts: intAttr('maxAttempts'),
894
+ showFeedback: boolAttr('showFeedback') ?? boolAttr('show-feedback'),
895
+ allowReview: boolAttr('allowReview') ?? boolAttr('allow-review'),
896
+ showSolution: boolAttr('showSolution') ?? boolAttr('show-solution'),
897
+ allowComment: boolAttr('allowComment') ?? boolAttr('allow-comment'),
898
+ allowSkipping: boolAttr('allowSkipping') ?? boolAttr('allow-skipping'),
899
+ validateResponses: boolAttr('validateResponses') ?? boolAttr('validate-responses'),
900
+ };
901
+ };
902
+
903
+ // Extract outcomeDeclarations
904
+ const outcomeDeclarations = childrenByTag(root, 'outcomeDeclaration').map((d) => {
905
+ const identifier = getAttr(d, 'identifier') ?? 'OUTCOME';
906
+ const baseType = getAttr(d, 'baseType') ?? 'float';
907
+ const cardinality = getAttr(d, 'cardinality') ?? 'single';
908
+ // Parse defaultValue if present
909
+ const defaultValueEl = childrenByTag(d, 'defaultValue')[0];
910
+ let defaultValue: unknown = undefined;
911
+ if (defaultValueEl) {
912
+ const valueEl = childrenByTag(defaultValueEl, 'value')[0];
913
+ if (valueEl) {
914
+ const text = valueEl.textContent?.trim() ?? '0';
915
+ if (baseType === 'float' || baseType === 'integer') {
916
+ defaultValue = Number(text);
917
+ } else {
918
+ defaultValue = text;
919
+ }
920
+ }
921
+ }
922
+ return { identifier, baseType, cardinality, defaultValue };
923
+ });
924
+
925
+ // Extract outcomeProcessing XML
926
+ const outcomeProcessingEl = childrenByTag(root, 'outcomeProcessing')[0];
927
+ const outcomeProcessingXml = outcomeProcessingEl
928
+ ? serializeXml(outcomeProcessingEl)
929
+ : undefined;
930
+
931
+ // Extract timeLimits
932
+ const timeLimitsEl = childrenByTag(root, 'timeLimit')[0] ?? childrenByTag(root, 'timeLimits')[0];
933
+ const timeLimits = timeLimitsEl
934
+ ? {
935
+ maxTime: getAttr(timeLimitsEl, 'maxTime')
936
+ ? Number(getAttr(timeLimitsEl, 'maxTime'))
937
+ : undefined,
938
+ allowLateSubmission: getAttr(timeLimitsEl, 'allowLateSubmission') === 'true',
939
+ }
940
+ : undefined;
941
+
942
+ // Parse testParts
943
+ const testPartEls = childrenByTag(root, 'testPart');
944
+ const firstTestPart = testPartEls[0];
945
+
946
+ // Navigation/submission mode from first testPart (QTI 2.2 spec)
947
+ const navigationMode = (getAttr(firstTestPart ?? root, 'navigationMode') ?? 'nonlinear') as
948
+ | 'linear'
949
+ | 'nonlinear';
950
+ const submissionMode = (getAttr(firstTestPart ?? root, 'submissionMode') ?? 'simultaneous') as
951
+ | 'individual'
952
+ | 'simultaneous';
953
+
954
+ const testParts: SecureTestPart[] = [];
955
+ for (const tp of testPartEls) {
956
+ const tpIdentifier = getAttr(tp, 'identifier') ?? 'part-1';
957
+ const tpItemSessionControl = parseTestPartItemSessionControl(tp);
958
+ const tpRubricBlockEls = childrenByTag(tp, 'rubricBlock');
959
+ const tpRubricBlocks = tpRubricBlockEls.length > 0
960
+ ? tpRubricBlockEls.map((b, idx) => ({
961
+ identifier: getAttr(b, 'identifier') ?? `${tpIdentifier}-rubric-${idx + 1}`,
962
+ view: (getAttr(b, 'view') ?? 'candidate').split(/\s+/).filter(Boolean) as any[],
963
+ use: getAttr(b, 'use'),
964
+ content: serializeXml(b),
965
+ }))
966
+ : undefined;
967
+
968
+ const sections = await parseSectionsForTestPart(tp);
969
+ testParts.push({
970
+ identifier: tpIdentifier,
971
+ sections,
972
+ rubricBlocks: tpRubricBlocks,
973
+ itemSessionControl: tpItemSessionControl,
974
+ });
975
+ }
976
+
977
+ // If no testParts, try top-level sections
978
+ if (testParts.length === 0) {
979
+ const topSections: SecureSection[] = [];
980
+ for (const child of childElements(root)) {
981
+ if (toCanonicalQtiName(child.localName) === 'assessmentSection') {
982
+ topSections.push(parseSection(child));
983
+ } else if (toCanonicalQtiName(child.localName) === 'assessmentSectionRef') {
984
+ const resolved = await resolveSectionRef(child);
985
+ if (resolved) topSections.push(resolved);
986
+ }
987
+ }
988
+ if (topSections.length > 0) {
989
+ testParts.push({
990
+ identifier: 'part-1',
991
+ sections: topSections,
992
+ });
993
+ }
994
+ }
995
+
996
+ return {
997
+ identifier: getAttr(root, 'identifier') ?? 'assessment',
998
+ title: getAttr(root, 'title') ?? 'Assessment',
999
+ navigationMode,
1000
+ submissionMode,
1001
+ testParts,
1002
+ timeLimits,
1003
+ outcomeDeclarations: outcomeDeclarations.length > 0 ? outcomeDeclarations : undefined,
1004
+ outcomeProcessingXml,
1005
+ baseUrl,
1006
+ };
1007
+ }
1008
+
578
1009
  private evaluateConditionXml(conditionXml: string, vars: Record<string, unknown>): boolean {
579
1010
  // conditionXml is an operator element like <gt>...</gt> (not wrapped in <expression>).
580
1011
  const doc = parseXml(conditionXml);
@@ -61,6 +61,18 @@ export interface InitSessionResponse {
61
61
  *
62
62
  * Security: NO correct answers, NO scoring rules, NO sensitive rubrics
63
63
  */
64
+ export interface TestFeedbackItem {
65
+ identifier: string;
66
+ /** Outcome variable name to evaluate (e.g. "PASS", "GRADE") */
67
+ outcomeIdentifier: string;
68
+ /** 'show' = show when outcome equals identifier; 'hide' = show when it does not */
69
+ showHide: 'show' | 'hide';
70
+ /** 'atEnd' = only after submission; 'during' = also during attempt */
71
+ access: 'atEnd' | 'during';
72
+ /** HTML content to display */
73
+ content: string;
74
+ }
75
+
64
76
  export interface SecureAssessment {
65
77
  identifier: string;
66
78
  title: string;
@@ -75,6 +87,19 @@ export interface SecureAssessment {
75
87
  maxTime?: number; // seconds
76
88
  allowLateSubmission?: boolean;
77
89
  };
90
+ /** QTI outcomeDeclarations for test-level variables */
91
+ outcomeDeclarations?: Array<{
92
+ identifier: string;
93
+ baseType: string;
94
+ cardinality: string;
95
+ defaultValue?: unknown;
96
+ }>;
97
+ /** Raw <outcomeProcessing> XML string, if present */
98
+ outcomeProcessingXml?: string;
99
+ /** Base URL/path for resolving relative hrefs (e.g. assessmentSectionRef) */
100
+ baseUrl?: string;
101
+ /** QTI testFeedback blocks for post-submission display */
102
+ testFeedback?: TestFeedbackItem[];
78
103
  }
79
104
 
80
105
  export interface SecureTestPart {
@@ -103,7 +128,7 @@ export interface SecureSection {
103
128
  title?: string;
104
129
  /** Visible determines if section appears in navigation */
105
130
  visible: boolean;
106
- /** Assessment item references */
131
+ /** Assessment item references (order reflects selection/ordering already applied server-side) */
107
132
  assessmentItemRefs: SecureItemRef[];
108
133
  /** Section-level time limit */
109
134
  timeLimits?: {
@@ -111,6 +136,35 @@ export interface SecureSection {
111
136
  };
112
137
  /** Candidate instructions (safe for display) */
113
138
  rubricBlocks?: AssessmentRubricBlock[];
139
+ /**
140
+ * QTI selection: how many items to present from this section.
141
+ * When present the server has already applied selection; client uses this for progress display.
142
+ */
143
+ selection?: {
144
+ /** Number of items selected for this session */
145
+ select: number;
146
+ withReplacement?: boolean;
147
+ };
148
+ /**
149
+ * QTI ordering: whether items were shuffled.
150
+ * When true the server has already shuffled assessmentItemRefs.
151
+ */
152
+ ordering?: {
153
+ shuffle: boolean;
154
+ };
155
+ /**
156
+ * Item session control (QTI assessmentSection/itemSessionControl).
157
+ * Section-level values take precedence over testPart-level when present.
158
+ */
159
+ itemSessionControl?: {
160
+ maxAttempts?: number;
161
+ showFeedback?: boolean;
162
+ allowReview?: boolean;
163
+ showSolution?: boolean;
164
+ allowComment?: boolean;
165
+ allowSkipping?: boolean;
166
+ validateResponses?: boolean;
167
+ };
114
168
  }
115
169
 
116
170
  export interface SecureItemRef {
@@ -122,6 +176,18 @@ export interface SecureItemRef {
122
176
  role: QTIRole;
123
177
  /** Required=true means item must be attempted */
124
178
  required?: boolean;
179
+ /**
180
+ * QTI branchRule: ordered list of branch rules on this item.
181
+ * The backend evaluates these after scoring and returns nextItemIdentifier in SubmitResponsesResponse.
182
+ * Carried here so reference/demo adapters can evaluate them client-side.
183
+ */
184
+ branchRule?: Array<{
185
+ /** Identifier of the target item, section, testPart, or one of the special values:
186
+ * EXIT_TEST | EXIT_TESTPART | EXIT_SECTION */
187
+ target: string;
188
+ /** Serialised QTI expression XML (the child of <branchRule>). Absent means unconditional. */
189
+ conditionXml?: string;
190
+ }>;
125
191
  }
126
192
 
127
193
  export interface AssessmentRubricBlock {
@@ -277,8 +343,14 @@ export interface FinalizeAssessmentResponse {
277
343
  maxScore: number;
278
344
  /** Per-item results */
279
345
  itemScores: Record<string, AssessmentScoringResult>;
280
- /** Assessment-level feedback */
346
+ /** Assessment-level feedback (legacy: single string; prefer outcomes + assessment.testFeedback) */
281
347
  feedback?: string;
348
+ /**
349
+ * Test-level outcome variable values after outcomeProcessing.
350
+ * Used to evaluate testFeedback visibility via string equality.
351
+ * Keys are outcome identifiers (e.g. "PASS", "GRADE"); values are their string representations.
352
+ */
353
+ outcomes?: Record<string, string>;
282
354
  /** Server timestamp */
283
355
  finalizedAt: number;
284
356
  }