@pie-qti/assessment-player 1.0.0-beta.3 → 1.0.0-beta.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.
Files changed (134) hide show
  1. package/README.md +28 -7
  2. package/dist/components/createPlayerConnection.svelte.d.ts +90 -0
  3. package/dist/components/createPlayerConnection.svelte.js +151 -0
  4. package/dist/components/createPlayerConnection.svelte.js.map +1 -0
  5. package/dist/components/displaySettings.svelte.d.ts +23 -0
  6. package/dist/components/displaySettings.svelte.js +40 -0
  7. package/dist/components/displaySettings.svelte.js.map +1 -0
  8. package/dist/components/srOnly.d.ts +29 -0
  9. package/dist/components/srOnly.js +55 -0
  10. package/dist/components/srOnly.js.map +1 -0
  11. package/dist/components/submitDialogAction.d.ts +25 -0
  12. package/dist/components/submitDialogAction.js +89 -0
  13. package/dist/components/submitDialogAction.js.map +1 -0
  14. package/dist/core/AssessmentPlayer.d.ts +1102 -53
  15. package/dist/core/AssessmentPlayer.js +2836 -457
  16. package/dist/core/AssessmentPlayer.js.map +1 -1
  17. package/dist/core/AssessmentSessionCoordinator.d.ts +76 -7
  18. package/dist/core/AssessmentSessionCoordinator.js +185 -10
  19. package/dist/core/AssessmentSessionCoordinator.js.map +1 -1
  20. package/dist/core/AutosaveManager.d.ts +104 -0
  21. package/dist/core/AutosaveManager.js +181 -0
  22. package/dist/core/AutosaveManager.js.map +1 -0
  23. package/dist/core/ItemSessionController.d.ts +17 -26
  24. package/dist/core/ItemSessionController.js +33 -73
  25. package/dist/core/ItemSessionController.js.map +1 -1
  26. package/dist/core/NavigationManager.d.ts +18 -50
  27. package/dist/core/NavigationManager.js +21 -83
  28. package/dist/core/NavigationManager.js.map +1 -1
  29. package/dist/core/TimeManager.d.ts +62 -16
  30. package/dist/core/TimeManager.js +148 -57
  31. package/dist/core/TimeManager.js.map +1 -1
  32. package/dist/core/autosave.d.ts +44 -0
  33. package/dist/core/autosave.js +46 -0
  34. package/dist/core/autosave.js.map +1 -0
  35. package/dist/core/deliveryStructure.d.ts +54 -0
  36. package/dist/core/deliveryStructure.js +72 -0
  37. package/dist/core/deliveryStructure.js.map +1 -0
  38. package/dist/core/errors.d.ts +116 -0
  39. package/dist/core/errors.js +77 -0
  40. package/dist/core/errors.js.map +1 -0
  41. package/dist/core/exitBoundaries.d.ts +64 -0
  42. package/dist/core/exitBoundaries.js +98 -0
  43. package/dist/core/exitBoundaries.js.map +1 -0
  44. package/dist/core/feedback.d.ts +46 -0
  45. package/dist/core/feedback.js +47 -0
  46. package/dist/core/feedback.js.map +1 -0
  47. package/dist/core/formatTime.d.ts +8 -0
  48. package/dist/core/formatTime.js +20 -0
  49. package/dist/core/formatTime.js.map +1 -0
  50. package/dist/core/index.d.ts +7 -4
  51. package/dist/core/index.js +4 -1
  52. package/dist/core/index.js.map +1 -1
  53. package/dist/core/navigationPolicy.d.ts +46 -0
  54. package/dist/core/navigationPolicy.js +66 -0
  55. package/dist/core/navigationPolicy.js.map +1 -0
  56. package/dist/core/pause.d.ts +58 -0
  57. package/dist/core/pause.js +101 -0
  58. package/dist/core/pause.js.map +1 -0
  59. package/dist/core/playerEvents.d.ts +51 -0
  60. package/dist/core/playerEvents.js +66 -0
  61. package/dist/core/playerEvents.js.map +1 -0
  62. package/dist/core/reviewState.d.ts +81 -0
  63. package/dist/core/reviewState.js +113 -0
  64. package/dist/core/reviewState.js.map +1 -0
  65. package/dist/core/reviewViews.d.ts +43 -0
  66. package/dist/core/reviewViews.js +88 -0
  67. package/dist/core/reviewViews.js.map +1 -0
  68. package/dist/core/scopeLocks.d.ts +36 -0
  69. package/dist/core/scopeLocks.js +78 -0
  70. package/dist/core/scopeLocks.js.map +1 -0
  71. package/dist/core/sessionRecords.d.ts +31 -0
  72. package/dist/core/sessionRecords.js +74 -0
  73. package/dist/core/sessionRecords.js.map +1 -0
  74. package/dist/core/submissionPolicy.d.ts +65 -0
  75. package/dist/core/submissionPolicy.js +71 -0
  76. package/dist/core/submissionPolicy.js.map +1 -0
  77. package/dist/core/templateDefaults.d.ts +26 -0
  78. package/dist/core/templateDefaults.js +54 -0
  79. package/dist/core/templateDefaults.js.map +1 -0
  80. package/dist/core/testStructure.d.ts +118 -3
  81. package/dist/core/testStructure.js +255 -6
  82. package/dist/core/testStructure.js.map +1 -1
  83. package/dist/core/timePolicy.d.ts +40 -0
  84. package/dist/core/timePolicy.js +106 -0
  85. package/dist/core/timePolicy.js.map +1 -0
  86. package/dist/index.d.ts +7 -4
  87. package/dist/index.js +5 -1
  88. package/dist/index.js.map +1 -1
  89. package/dist/integration/ReferenceBackendAdapter.d.ts +64 -101
  90. package/dist/integration/ReferenceBackendAdapter.js +214 -1033
  91. package/dist/integration/ReferenceBackendAdapter.js.map +1 -1
  92. package/dist/integration/api-contract.d.ts +175 -10
  93. package/dist/integration/api-contract.js.map +1 -1
  94. package/dist/integration/assessment-item-scorer.d.ts +56 -5
  95. package/dist/integration/assessment-item-scorer.js +116 -13
  96. package/dist/integration/assessment-item-scorer.js.map +1 -1
  97. package/dist/integration/index.d.ts +2 -2
  98. package/dist/integration/index.js +1 -1
  99. package/dist/integration/index.js.map +1 -1
  100. package/dist/integration/qti-test-parser.d.ts +44 -0
  101. package/dist/integration/qti-test-parser.js +558 -0
  102. package/dist/integration/qti-test-parser.js.map +1 -0
  103. package/dist/integration/session-store.d.ts +54 -0
  104. package/dist/integration/session-store.js +75 -0
  105. package/dist/integration/session-store.js.map +1 -0
  106. package/dist/integration/test-navigation.d.ts +23 -0
  107. package/dist/integration/test-navigation.js +32 -0
  108. package/dist/integration/test-navigation.js.map +1 -0
  109. package/dist/integration/toSectionComposition.js +8 -1
  110. package/dist/integration/toSectionComposition.js.map +1 -1
  111. package/dist/reporting/index.d.ts +3 -0
  112. package/dist/reporting/index.js +3 -0
  113. package/dist/reporting/index.js.map +1 -0
  114. package/dist/reporting/inferBaseType.d.ts +13 -0
  115. package/dist/reporting/inferBaseType.js +26 -0
  116. package/dist/reporting/inferBaseType.js.map +1 -0
  117. package/dist/reporting/serializeAssessmentResult.d.ts +27 -0
  118. package/dist/reporting/serializeAssessmentResult.js +377 -0
  119. package/dist/reporting/serializeAssessmentResult.js.map +1 -0
  120. package/dist/reporting/toAssessmentResultXml.d.ts +39 -0
  121. package/dist/reporting/toAssessmentResultXml.js +304 -0
  122. package/dist/reporting/toAssessmentResultXml.js.map +1 -0
  123. package/dist/reporting/types.d.ts +85 -0
  124. package/dist/reporting/types.js +8 -0
  125. package/dist/reporting/types.js.map +1 -0
  126. package/dist/types/index.d.ts +96 -9
  127. package/dist/types/index.js.map +1 -1
  128. package/package.json +18 -14
  129. package/dist/core/StatePersistenceManager.d.ts +0 -125
  130. package/dist/core/StatePersistenceManager.js +0 -268
  131. package/dist/core/StatePersistenceManager.js.map +0 -1
  132. package/dist/utils/PerformanceMonitor.d.ts +0 -114
  133. package/dist/utils/PerformanceMonitor.js +0 -172
  134. package/dist/utils/PerformanceMonitor.js.map +0 -1
@@ -1,6 +1,7 @@
1
1
  /**
2
2
  * QTI test structure shared by backends and the client: the itemSessionControl cascade, the
3
- * session-start draw of selection and ordering, delivery order, and test-scope expressions.
3
+ * session-start draw of selection and ordering, delivery order, the delivery-rules walk
4
+ * (branch rules, preconditions, eligibility), and test-scope expressions.
4
5
  */
5
6
  import { type DeclarationMap, type QtiValue } from '@pie-qti/qti-processing';
6
7
  import type { SecureAssessment, SecureItemRef, SecureItemSessionControl, SecureSection, SecureSectionComponent, SecureTestPart, TestOutcomeValues } from '../integration/api-contract.js';
@@ -9,6 +10,18 @@ export type ResolvedItemSessionControl = Required<SecureItemSessionControl>;
9
10
  export declare const DEFAULT_ITEM_SESSION_CONTROL: Readonly<ResolvedItemSessionControl>;
10
11
  /** True when the item root declares `adaptive="true"`. */
11
12
  export declare function isAdaptiveItemXml(itemXml: string): boolean;
13
+ export interface EndAttemptInteractionInfo {
14
+ /** The response declaration the interaction is bound to. */
15
+ responseIdentifier: string;
16
+ /** QTI `countAttempt` (QTI 3 `count-attempt`); true unless authored as false. */
17
+ countAttempt: boolean;
18
+ }
19
+ /**
20
+ * The item's endAttemptInteraction bindings, read from the item XML. Assessment delivery uses this
21
+ * to recognize an end-attempt response on the session's normal response path: activation counts the
22
+ * attempt unless authored with countAttempt="false" (a hint request).
23
+ */
24
+ export declare function endAttemptInteractionInfo(itemXml: string): EndAttemptInteractionInfo[];
12
25
  /**
13
26
  * Effective itemSessionControl for an item: the test part, each enclosing section from outer to
14
27
  * inner, then the item ref, each set attribute overriding the level above. Adaptive items allow
@@ -25,6 +38,46 @@ export interface DeliveredItem {
25
38
  }
26
39
  /** Items in delivery order. Draws nothing: call it on an assessment the backend has drawn. */
27
40
  export declare function deliveredItems(assessment: SecureAssessment): DeliveredItem[];
41
+ /**
42
+ * Next item after `delivered[index]`. Branch rules come first: the item's, then each enclosing
43
+ * section's it ends (inner to outer), then the test part's when it ends that too. Item and
44
+ * section rules apply in linear navigation only. With no matching rule, navigation falls through
45
+ * to the following item. Preconditions then skip forward from the target. EXIT_TEST means the
46
+ * remaining items are all skipped; undefined means the current item was the last. `onError`
47
+ * receives any condition evaluation failure (see `evaluateTestCondition`).
48
+ */
49
+ export declare function nextItemIdentifier(assessment: SecureAssessment, delivered: DeliveredItem[], index: number, decls: DeclarationMap, rng: () => number, onError?: (expressionXml: string, error: unknown) => void): string | undefined;
50
+ /** The delivered-item shape literal branch-target resolution reads (`DeliveredItem` and `FlatItem` both). */
51
+ export type ScopedDeliveredItem = {
52
+ item: {
53
+ identifier: string;
54
+ };
55
+ /** Enclosing sections, outermost first. */
56
+ sections: readonly {
57
+ identifier: string;
58
+ }[];
59
+ testPart: {
60
+ identifier: string;
61
+ };
62
+ };
63
+ /**
64
+ * The one literal branch-target resolver both live engines share — the reference backend's
65
+ * `resolveBranchTarget` and the client's `exitBoundaries.branchTargetIndex` — so identical
66
+ * branch XML cannot branch differently on the two paths. Forward-only per QTI 2.2 §5.15
67
+ * ("the test jumps forward … the target must refer to an item or section … that has not yet
68
+ * been presented"): the first delivered item strictly after `currentIndex` whose item,
69
+ * enclosing-section, or test-part identifier matches `target`, tried in that order;
70
+ * `undefined` when none does. A target naming an already-presented item therefore resolves
71
+ * to nothing (the rule is skipped, delivery falls through), never backwards.
72
+ */
73
+ export declare function firstForwardBranchTarget(target: string, items: readonly ScopedDeliveredItem[], currentIndex: number): number | undefined;
74
+ /**
75
+ * First item from `start` whose preconditions hold. A test part's are checked on entering it in
76
+ * any navigation mode; a newly entered section's (outermost first) and the item's only in linear
77
+ * navigation. A failing part or section skips everything inside it. `onError` receives any
78
+ * condition evaluation failure (see `evaluateTestCondition`).
79
+ */
80
+ export declare function firstEligibleItem(assessment: SecureAssessment, delivered: DeliveredItem[], start: number, from: DeliveredItem | undefined, decls: DeclarationMap, rng: () => number, onError?: (expressionXml: string, error: unknown) => void): string | undefined;
28
81
  /**
29
82
  * Draws selection and ordering for one session. Required children are always selected; selected
30
83
  * children keep source order before ordering shuffles the non-fixed ones. A child selected more
@@ -55,11 +108,73 @@ export declare function testOutcomeDeclarations(assessment: SecureAssessment, ou
55
108
  * `unprefixed` variables under their own identifiers where the test declares no such outcome.
56
109
  */
57
110
  export declare function addItemVariableDeclarations(decls: DeclarationMap, itemVariables: Record<string, Record<string, QtiValue>>, unprefixed?: Record<string, QtiValue>): DeclarationMap;
111
+ /** Millisecond scope clocks the timing state carries; absent clocks read as 0 seconds. */
112
+ export interface ScopeTiming {
113
+ /** Total assessment elapsed time (ms). */
114
+ totalTime?: number;
115
+ /** Elapsed time per testPart identifier (ms). */
116
+ testPartTimes?: Record<string, number>;
117
+ /** Elapsed time per section identifier (ms). */
118
+ sectionTimes?: Record<string, number>;
119
+ }
120
+ /**
121
+ * Adds the QTI built-in duration variables test-scope expressions read: `duration` for the whole
122
+ * test, `TESTPART_ID.duration` and `SECTION_ID.duration` for each delivered part and section.
123
+ * QTI durations are seconds; the timing state keeps milliseconds, so the values are converted.
124
+ * Authored identifiers win: an existing declaration is never replaced.
125
+ */
126
+ export declare function addScopeDurationDeclarations(decls: DeclarationMap, assessment: SecureAssessment, timing: ScopeTiming | undefined): DeclarationMap;
58
127
  /** Item variables with each variableMapping's source also readable as its target identifier. */
59
128
  export declare function applyVariableMappings(variables: Record<string, QtiValue>, mappings: SecureItemRef['variableMappings']): Record<string, QtiValue>;
60
129
  /** Evaluates a serialized test-scope expression (QTI 2.x or 3) against `decls`. */
61
130
  export declare function evaluateTestExpression(expressionXml: string, decls: DeclarationMap, rng: () => number): QtiValue;
62
- /** True only when the expression evaluates to boolean true; NULL and errors read as false. */
63
- export declare function evaluateTestCondition(expressionXml: string, decls: DeclarationMap, rng: () => number): boolean;
131
+ /**
132
+ * True only when the expression evaluates to boolean true; NULL reads as false (QTI:
133
+ * a NULL condition result is false).
134
+ *
135
+ * An evaluation ERROR also reads as false, but unlike a NULL it is reported: delivery
136
+ * proceeds on the default path (a broken branchRule or preCondition must never abort a
137
+ * candidate's test), yet the failure is never indistinguishable from an authored false.
138
+ * Callers that own an error surface pass `onError` — the AssessmentPlayer reports a
139
+ * coded `testConditionFailed` through `config.onError` — and without one the failure
140
+ * stays a console warning (the reference backend's own evaluation).
141
+ *
142
+ * Documented divergence from the strict spec reading: QTI 2.1/3.0 leave undefined how
143
+ * delivery proceeds when a condition expression cannot be evaluated; reading it as
144
+ * false keeps delivery on the default path and reporting keeps it observable.
145
+ */
146
+ export declare function evaluateTestCondition(expressionXml: string, decls: DeclarationMap, rng: () => number, onError?: (expressionXml: string, error: unknown) => void): boolean;
64
147
  /** Plain value of a QTI value, null for NULL, in the shape item template defaults take. */
65
148
  export declare function plainQtiValue(value: QtiValue): unknown;
149
+ /** A serialized item-session variable, as `SerializedItemSessionState` carries it. */
150
+ interface SerializedVariableShape {
151
+ baseType?: string;
152
+ cardinality: string;
153
+ value: unknown;
154
+ }
155
+ /**
156
+ * The QTI values of a serialized item session's response, outcome and template
157
+ * variables (NULL where unset), keyed by variable identifier — the item's variables a
158
+ * test-scope expression reads as `ITEM.VARIABLE`.
159
+ */
160
+ export declare function itemSessionVariableValues(session: {
161
+ responseVariables?: Record<string, SerializedVariableShape>;
162
+ outcomeVariables?: Record<string, SerializedVariableShape>;
163
+ templateVariables?: Record<string, SerializedVariableShape>;
164
+ }): Record<string, QtiValue>;
165
+ /**
166
+ * An item's variables as test-level branch rules and preconditions read them (`ITEM.VARIABLE`),
167
+ * in the shape the reference backend records after a counted submission (its item test state):
168
+ * the session's context (numAttempts, duration, completionStatus), template, outcome and response
169
+ * variables, with `scoredOutcomes` — the backend's scored outcome values, authoritative where the
170
+ * delivered item carries no response processing — over them, typed by the session's own
171
+ * declarations (a value without one is read as the reference backend reads a bare score: a
172
+ * number as float, anything else as string). Record outcomes keep the session's value.
173
+ */
174
+ export declare function recordedItemVariableValues(session: {
175
+ contextVariables?: Record<string, SerializedVariableShape>;
176
+ responseVariables?: Record<string, SerializedVariableShape>;
177
+ outcomeVariables?: Record<string, SerializedVariableShape>;
178
+ templateVariables?: Record<string, SerializedVariableShape>;
179
+ } | undefined, scoredOutcomes: Record<string, unknown> | undefined): Record<string, QtiValue>;
180
+ export {};
@@ -1,8 +1,9 @@
1
1
  /**
2
2
  * QTI test structure shared by backends and the client: the itemSessionControl cascade, the
3
- * session-start draw of selection and ordering, delivery order, and test-scope expressions.
3
+ * session-start draw of selection and ordering, delivery order, the delivery-rules walk
4
+ * (branch rules, preconditions, eligibility), and test-scope expressions.
4
5
  */
5
- import { buildExpression, DeclarationContext, evalExpr, OperatorRegistry, parseXml, qtiNull, qtiValue, } from '@pie-qti/qti-processing';
6
+ import { buildExpression, DeclarationContext, durationSecondsFromMilliseconds, evalExpr, parseXml, qtiNull, qtiValue, } from '@pie-qti/qti-processing';
6
7
  /** QTI itemSessionControl defaults, applied where no level of the cascade sets an attribute. */
7
8
  export const DEFAULT_ITEM_SESSION_CONTROL = Object.freeze({
8
9
  maxAttempts: 1,
@@ -19,6 +20,42 @@ const ADAPTIVE_ITEM_ROOT = /<(?:[\w-]+:)?(?:qti-assessment-item|assessmentItem)\
19
20
  export function isAdaptiveItemXml(itemXml) {
20
21
  return ADAPTIVE_ITEM_ROOT.test(itemXml);
21
22
  }
23
+ /**
24
+ * The item's endAttemptInteraction bindings, read from the item XML. Assessment delivery uses this
25
+ * to recognize an end-attempt response on the session's normal response path: activation counts the
26
+ * attempt unless authored with countAttempt="false" (a hint request).
27
+ */
28
+ export function endAttemptInteractionInfo(itemXml) {
29
+ const out = [];
30
+ let root = null;
31
+ try {
32
+ root = parseXml(itemXml).documentElement;
33
+ }
34
+ catch {
35
+ return out;
36
+ }
37
+ if (!root)
38
+ return out;
39
+ const visit = (element) => {
40
+ const name = toCanonicalQtiName(element.localName ?? element.nodeName).toLowerCase();
41
+ if (name === 'endattemptinteraction') {
42
+ const responseIdentifier = element.getAttribute('responseIdentifier') ?? element.getAttribute('response-identifier');
43
+ const raw = element.getAttribute('countAttempt') ?? element.getAttribute('count-attempt');
44
+ if (responseIdentifier) {
45
+ out.push({
46
+ responseIdentifier,
47
+ countAttempt: raw ? raw.trim().toLowerCase() !== 'false' : true,
48
+ });
49
+ }
50
+ }
51
+ for (let child = element.firstChild; child; child = child.nextSibling) {
52
+ if (child.nodeType === 1)
53
+ visit(child);
54
+ }
55
+ };
56
+ visit(root);
57
+ return out;
58
+ }
22
59
  /**
23
60
  * Effective itemSessionControl for an item: the test part, each enclosing section from outer to
24
61
  * inner, then the item ref, each set attribute overriding the level above. Adaptive items allow
@@ -68,6 +105,125 @@ export function deliveredItems(assessment) {
68
105
  }
69
106
  return out;
70
107
  }
108
+ /**
109
+ * Next item after `delivered[index]`. Branch rules come first: the item's, then each enclosing
110
+ * section's it ends (inner to outer), then the test part's when it ends that too. Item and
111
+ * section rules apply in linear navigation only. With no matching rule, navigation falls through
112
+ * to the following item. Preconditions then skip forward from the target. EXIT_TEST means the
113
+ * remaining items are all skipped; undefined means the current item was the last. `onError`
114
+ * receives any condition evaluation failure (see `evaluateTestCondition`).
115
+ */
116
+ export function nextItemIdentifier(assessment, delivered, index, decls, rng, onError) {
117
+ const start = branchTarget(assessment, delivered, index, decls, rng, onError) ?? index + 1;
118
+ const next = firstEligibleItem(assessment, delivered, start, delivered[index], decls, rng, onError);
119
+ return next ?? (index + 1 < delivered.length ? 'EXIT_TEST' : undefined);
120
+ }
121
+ function branchTarget(assessment, delivered, index, decls, rng, onError) {
122
+ const current = delivered[index];
123
+ const following = delivered[index + 1];
124
+ const linear = isLinear(assessment, current.testPart);
125
+ const holders = [];
126
+ if (linear) {
127
+ holders.push({ rules: current.item.branchRule, exitSection: current.sections[current.sections.length - 1] });
128
+ for (let level = current.sections.length - 1; level >= 0; level--) {
129
+ const section = current.sections[level];
130
+ if (following?.sections.includes(section))
131
+ break;
132
+ holders.push({ rules: section.branchRule, exitSection: current.sections[level - 1] });
133
+ }
134
+ }
135
+ if (following?.testPart !== current.testPart)
136
+ holders.push({ rules: current.testPart.branchRule });
137
+ for (const { rules, exitSection } of holders) {
138
+ for (const rule of rules ?? []) {
139
+ if (rule.conditionXml && !evaluateTestCondition(rule.conditionXml, decls, rng, onError))
140
+ continue;
141
+ const target = resolveBranchTarget(rule.target, delivered, index, exitSection);
142
+ if (target !== undefined)
143
+ return target;
144
+ }
145
+ }
146
+ return undefined;
147
+ }
148
+ /**
149
+ * The one literal branch-target resolver both live engines share — the reference backend's
150
+ * `resolveBranchTarget` and the client's `exitBoundaries.branchTargetIndex` — so identical
151
+ * branch XML cannot branch differently on the two paths. Forward-only per QTI 2.2 §5.15
152
+ * ("the test jumps forward … the target must refer to an item or section … that has not yet
153
+ * been presented"): the first delivered item strictly after `currentIndex` whose item,
154
+ * enclosing-section, or test-part identifier matches `target`, tried in that order;
155
+ * `undefined` when none does. A target naming an already-presented item therefore resolves
156
+ * to nothing (the rule is skipped, delivery falls through), never backwards.
157
+ */
158
+ export function firstForwardBranchTarget(target, items, currentIndex) {
159
+ return (firstAfter(items, currentIndex, (item) => item.item.identifier === target) ??
160
+ firstAfter(items, currentIndex, (item) => item.sections.some((section) => section.identifier === target)) ??
161
+ firstAfter(items, currentIndex, (item) => item.testPart.identifier === target));
162
+ }
163
+ /** The first element strictly after `from` that satisfies `match`; undefined when none does. */
164
+ function firstAfter(items, from, match) {
165
+ for (let j = from + 1; j < items.length; j++)
166
+ if (match(items[j]))
167
+ return j;
168
+ return undefined;
169
+ }
170
+ /** Index a branch target resolves to, forward of `index`; delivered.length ends the test. */
171
+ function resolveBranchTarget(target, delivered, index, exitSection) {
172
+ const current = delivered[index];
173
+ switch (target) {
174
+ case 'EXIT_TEST':
175
+ return delivered.length;
176
+ case 'EXIT_TESTPART':
177
+ return firstAfter(delivered, index, (d) => d.testPart !== current.testPart) ?? delivered.length;
178
+ case 'EXIT_SECTION':
179
+ if (!exitSection)
180
+ return undefined;
181
+ return firstAfter(delivered, index, (d) => !d.sections.includes(exitSection)) ?? delivered.length;
182
+ default:
183
+ return firstForwardBranchTarget(target, delivered, index);
184
+ }
185
+ }
186
+ /**
187
+ * First item from `start` whose preconditions hold. A test part's are checked on entering it in
188
+ * any navigation mode; a newly entered section's (outermost first) and the item's only in linear
189
+ * navigation. A failing part or section skips everything inside it. `onError` receives any
190
+ * condition evaluation failure (see `evaluateTestCondition`).
191
+ */
192
+ export function firstEligibleItem(assessment, delivered, start, from, decls, rng, onError) {
193
+ const holds = (conditions) => (conditions ?? []).every((condition) => evaluateTestCondition(condition, decls, rng, onError));
194
+ const skipPast = (j, inside) => {
195
+ let next = j + 1;
196
+ while (next < delivered.length && inside(delivered[next]))
197
+ next++;
198
+ return next;
199
+ };
200
+ let j = start;
201
+ candidates: while (j < delivered.length) {
202
+ const candidate = delivered[j];
203
+ const previous = j === start ? from : delivered[j - 1];
204
+ if (candidate.testPart !== previous?.testPart && !holds(candidate.testPart.preConditions)) {
205
+ j = skipPast(j, (d) => d.testPart === candidate.testPart);
206
+ continue;
207
+ }
208
+ if (isLinear(assessment, candidate.testPart)) {
209
+ for (const section of candidate.sections) {
210
+ if (previous?.sections.includes(section) || holds(section.preConditions))
211
+ continue;
212
+ j = skipPast(j, (d) => d.sections.includes(section));
213
+ continue candidates;
214
+ }
215
+ if (!holds(candidate.item.preConditions)) {
216
+ j++;
217
+ continue;
218
+ }
219
+ }
220
+ return candidate.item.identifier;
221
+ }
222
+ return undefined;
223
+ }
224
+ function isLinear(assessment, testPart) {
225
+ return (testPart.navigationMode ?? assessment.navigationMode) === 'linear';
226
+ }
71
227
  /**
72
228
  * Draws selection and ordering for one session. Required children are always selected; selected
73
229
  * children keep source order before ordering shuffles the non-fixed ones. A child selected more
@@ -298,6 +454,31 @@ export function addItemVariableDeclarations(decls, itemVariables, unprefixed = {
298
454
  }
299
455
  return decls;
300
456
  }
457
+ /**
458
+ * Adds the QTI built-in duration variables test-scope expressions read: `duration` for the whole
459
+ * test, `TESTPART_ID.duration` and `SECTION_ID.duration` for each delivered part and section.
460
+ * QTI durations are seconds; the timing state keeps milliseconds, so the values are converted.
461
+ * Authored identifiers win: an existing declaration is never replaced.
462
+ */
463
+ export function addScopeDurationDeclarations(decls, assessment, timing) {
464
+ const durationSeconds = (ms) => durationSecondsFromMilliseconds(Number(ms) || 0);
465
+ const putDuration = (identifier, seconds) => {
466
+ if (!decls[identifier])
467
+ decls[identifier] = declaration(identifier, qtiValue('duration', 'single', seconds));
468
+ };
469
+ putDuration('duration', durationSeconds(timing?.totalTime));
470
+ const visitSections = (sections) => {
471
+ for (const section of sections) {
472
+ putDuration(`${section.identifier}.duration`, durationSeconds(timing?.sectionTimes?.[section.identifier]));
473
+ visitSections(section.sections ?? []);
474
+ }
475
+ };
476
+ for (const testPart of assessment.testParts ?? []) {
477
+ putDuration(`${testPart.identifier}.duration`, durationSeconds(timing?.testPartTimes?.[testPart.identifier]));
478
+ visitSections(testPart.sections ?? []);
479
+ }
480
+ return decls;
481
+ }
301
482
  /** Item variables with each variableMapping's source also readable as its target identifier. */
302
483
  export function applyVariableMappings(variables, mappings) {
303
484
  if (!mappings?.length)
@@ -316,16 +497,33 @@ export function evaluateTestExpression(expressionXml, decls, rng) {
316
497
  if (!root)
317
498
  return qtiNull();
318
499
  const expr = buildExpression(root, { scope: 'test', elementNameMapper: qtiElementNameMapper });
319
- return evalExpr({ ctx: new DeclarationContext(structuredClone(decls)), ops: new OperatorRegistry(), rng }, expr);
500
+ return evalExpr({ ctx: new DeclarationContext(structuredClone(decls)), rng }, expr);
320
501
  }
321
- /** True only when the expression evaluates to boolean true; NULL and errors read as false. */
322
- export function evaluateTestCondition(expressionXml, decls, rng) {
502
+ /**
503
+ * True only when the expression evaluates to boolean true; NULL reads as false (QTI:
504
+ * a NULL condition result is false).
505
+ *
506
+ * An evaluation ERROR also reads as false, but unlike a NULL it is reported: delivery
507
+ * proceeds on the default path (a broken branchRule or preCondition must never abort a
508
+ * candidate's test), yet the failure is never indistinguishable from an authored false.
509
+ * Callers that own an error surface pass `onError` — the AssessmentPlayer reports a
510
+ * coded `testConditionFailed` through `config.onError` — and without one the failure
511
+ * stays a console warning (the reference backend's own evaluation).
512
+ *
513
+ * Documented divergence from the strict spec reading: QTI 2.1/3.0 leave undefined how
514
+ * delivery proceeds when a condition expression cannot be evaluated; reading it as
515
+ * false keeps delivery on the default path and reporting keeps it observable.
516
+ */
517
+ export function evaluateTestCondition(expressionXml, decls, rng, onError) {
323
518
  try {
324
519
  const out = evaluateTestExpression(expressionXml, decls, rng);
325
520
  return out.kind === 'value' && out.value === true;
326
521
  }
327
522
  catch (err) {
328
- console.warn('[assessment-player] test condition failed to evaluate:', err);
523
+ if (onError)
524
+ onError(expressionXml, err);
525
+ else
526
+ console.warn('[assessment-player] test condition failed to evaluate:', err);
329
527
  return false;
330
528
  }
331
529
  }
@@ -333,4 +531,55 @@ export function evaluateTestCondition(expressionXml, decls, rng) {
333
531
  export function plainQtiValue(value) {
334
532
  return value.kind === 'value' ? value.value : null;
335
533
  }
534
+ /**
535
+ * The QTI values of a serialized item session's response, outcome and template
536
+ * variables (NULL where unset), keyed by variable identifier — the item's variables a
537
+ * test-scope expression reads as `ITEM.VARIABLE`.
538
+ */
539
+ export function itemSessionVariableValues(session) {
540
+ const out = {};
541
+ for (const group of [session.responseVariables, session.outcomeVariables, session.templateVariables]) {
542
+ for (const [identifier, variable] of Object.entries(group ?? {})) {
543
+ out[identifier] = toQtiValue(variable.baseType, variable.cardinality, variable.value);
544
+ }
545
+ }
546
+ return out;
547
+ }
548
+ /**
549
+ * An item's variables as test-level branch rules and preconditions read them (`ITEM.VARIABLE`),
550
+ * in the shape the reference backend records after a counted submission (its item test state):
551
+ * the session's context (numAttempts, duration, completionStatus), template, outcome and response
552
+ * variables, with `scoredOutcomes` — the backend's scored outcome values, authoritative where the
553
+ * delivered item carries no response processing — over them, typed by the session's own
554
+ * declarations (a value without one is read as the reference backend reads a bare score: a
555
+ * number as float, anything else as string). Record outcomes keep the session's value.
556
+ */
557
+ export function recordedItemVariableValues(session, scoredOutcomes) {
558
+ const out = {};
559
+ for (const group of [
560
+ session?.contextVariables,
561
+ session?.templateVariables,
562
+ session?.outcomeVariables,
563
+ session?.responseVariables,
564
+ ]) {
565
+ for (const [identifier, variable] of Object.entries(group ?? {})) {
566
+ out[identifier] = toQtiValue(variable.baseType, variable.cardinality, variable.value);
567
+ }
568
+ }
569
+ for (const [identifier, value] of Object.entries(scoredOutcomes ?? {})) {
570
+ const declared = out[identifier];
571
+ if (value === undefined || declared?.cardinality === 'record')
572
+ continue;
573
+ if (declared?.baseType) {
574
+ out[identifier] = toQtiValue(declared.baseType, declared.cardinality ?? 'single', value);
575
+ }
576
+ else if (typeof value === 'number') {
577
+ out[identifier] = qtiValue('float', 'single', value);
578
+ }
579
+ else if (value !== null && typeof value !== 'object') {
580
+ out[identifier] = qtiValue('string', 'single', String(value));
581
+ }
582
+ }
583
+ return out;
584
+ }
336
585
  //# sourceMappingURL=testStructure.js.map