@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
@@ -0,0 +1,558 @@
1
+ /**
2
+ * QTI assessmentTest XML parser for the reference backend.
3
+ *
4
+ * Extracted verbatim from ReferenceBackendAdapter; the adapter's static
5
+ * `parseAssessmentTestXml` delegates here. Its output feeds both the adapter's
6
+ * session model and (via player-elements' discovery parser) element-side
7
+ * prefetch; keep identifier/href extraction in lockstep with
8
+ * packages/player-elements/src/qti/parseAssessmentTest.ts.
9
+ */
10
+ import { parseXml, serializeXml } from '@pie-qti/qti-processing';
11
+ import { createResolvedItemDeliveryContext, extractAssessmentStimulusRefs, extractProcessingIncludeRefs, extractQtiStylesheets, parseAssessmentStimulusXml, resolveCheckedPackagePath, resolveCheckedPackagePathFromFile, } from '@pie-qti/ims-cp-core';
12
+ import { toCanonicalQtiName } from '../core/testStructure.js';
13
+ /** Maximum assessmentSection nesting before parsing gives up (QTI 3.0 §2.2). */
14
+ class AssessmentSectionReferenceLimitError extends Error {
15
+ }
16
+ /**
17
+ * Parse a QTI assessmentTest XML string into a SecureAssessment structure.
18
+ *
19
+ * Handles:
20
+ * - S1: section-level itemSessionControl
21
+ * - S9: assessmentSectionRef href resolution (requires fileResolver)
22
+ * - T9/T1: outcomeDeclarations + outcomeProcessing extraction
23
+ *
24
+ * @param testXml - Raw QTI assessmentTest XML string
25
+ * @param options.role - Role to assign to items (default: 'candidate')
26
+ * @param options.itemXmlMap - Map of item identifier -> itemXml for pre-loaded items
27
+ * @param options.fileResolver - Async function to load external files by relative href
28
+ * @param options.baseUrl - Base URL for resolving relative hrefs
29
+ */
30
+ export async function parseAssessmentTestXml(testXml, options = {}) {
31
+ const { role = 'candidate', itemXmlMap = {}, fileResolver, baseUrl, sharedCatalogs } = options;
32
+ const maxSectionDepth = options.sectionReferenceLimits?.maxDepth ?? 32;
33
+ if (!Number.isInteger(maxSectionDepth) || maxSectionDepth < 1) {
34
+ throw new Error('sectionReferenceLimits.maxDepth must be a positive integer');
35
+ }
36
+ const doc = parseXml(testXml);
37
+ const root = doc.documentElement;
38
+ if (!root)
39
+ throw new Error('Empty assessmentTest XML');
40
+ // Reads camelCase and QTI 3 kebab-case attribute spellings alike. Empty values
41
+ // are treated as missing here; the player-elements discovery parser keeps '' —
42
+ // the two are intentionally not shared so each call site keeps its semantics.
43
+ const getAttr = (el, name) => {
44
+ const direct = el.getAttribute(name);
45
+ if (direct !== null && direct !== '')
46
+ return direct;
47
+ const mapped = el.getAttribute(name.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`));
48
+ return mapped === null || mapped === '' ? undefined : mapped;
49
+ };
50
+ const childElements = (el) => Array.from(el.childNodes).filter((n) => n.nodeType === 1);
51
+ const childrenByTag = (el, tag) => childElements(el).filter((c) => toCanonicalQtiName(c.localName) === tag);
52
+ /**
53
+ * The language `el`'s content is written in, by XML language inheritance (XML 1.0 §2.12):
54
+ * its own `xml:lang` (QTI 3 content may also say `lang`), else its nearest ancestor's.
55
+ * `xml:lang=""` declares no language and stops the inheritance. The root of an external
56
+ * section inherits `inherited`, the language in force at its assessmentSectionRef.
57
+ */
58
+ const contentLanguageOf = (el, inherited) => {
59
+ for (let node = el; node && node.nodeType === 1; node = node.parentNode) {
60
+ const element = node;
61
+ const name = element.hasAttribute('xml:lang') ? 'xml:lang' : element.hasAttribute('lang') ? 'lang' : null;
62
+ if (name)
63
+ return element.getAttribute(name)?.trim() || undefined;
64
+ }
65
+ return inherited;
66
+ };
67
+ /** A rubric block's content language: its content body's (QTI 3), else the block's. */
68
+ const rubricLanguageOf = (block, inherited) => contentLanguageOf(childrenByTag(block, 'contentBody')[0] ?? block, inherited);
69
+ // Parse itemSessionControl element
70
+ const parseItemSessionControl = (el) => {
71
+ const isc = childrenByTag(el, 'itemSessionControl')[0];
72
+ if (!isc)
73
+ return undefined;
74
+ const boolAttr = (name) => {
75
+ const v = getAttr(isc, name);
76
+ return v === undefined ? undefined : v !== 'false';
77
+ };
78
+ const intAttr = (name) => {
79
+ const v = getAttr(isc, name);
80
+ return v === undefined ? undefined : parseInt(v, 10);
81
+ };
82
+ return {
83
+ maxAttempts: intAttr('maxAttempts'),
84
+ showFeedback: boolAttr('showFeedback') ?? boolAttr('show-feedback'),
85
+ allowReview: boolAttr('allowReview') ?? boolAttr('allow-review'),
86
+ showSolution: boolAttr('showSolution') ?? boolAttr('show-solution'),
87
+ allowComment: boolAttr('allowComment') ?? boolAttr('allow-comment'),
88
+ allowSkipping: boolAttr('allowSkipping') ?? boolAttr('allow-skipping'),
89
+ validateResponses: boolAttr('validateResponses') ?? boolAttr('validate-responses'),
90
+ };
91
+ };
92
+ const parseTimeLimits = (el) => {
93
+ const limitsEl = childrenByTag(el, 'timeLimit')[0] ?? childrenByTag(el, 'timeLimits')[0];
94
+ if (!limitsEl)
95
+ return undefined;
96
+ const numberAttr = (name) => {
97
+ const value = getAttr(limitsEl, name);
98
+ if (value === undefined)
99
+ return undefined;
100
+ const parsed = Number(value);
101
+ return Number.isFinite(parsed) ? parsed : undefined;
102
+ };
103
+ const boolAttr = (name) => {
104
+ const value = getAttr(limitsEl, name);
105
+ return value === undefined ? undefined : value === 'true';
106
+ };
107
+ return {
108
+ minTime: numberAttr('minTime'),
109
+ maxTime: numberAttr('maxTime'),
110
+ allowLateSubmission: boolAttr('allowLateSubmission'),
111
+ };
112
+ };
113
+ const parseConditionExpressions = (el, tag) => {
114
+ const expressions = childrenByTag(el, tag)
115
+ .map((condition) => childElements(condition)[0])
116
+ .filter((expression) => Boolean(expression))
117
+ .map((expression) => serializeXml(expression));
118
+ return expressions.length > 0 ? expressions : undefined;
119
+ };
120
+ const parseBranchRules = (el) => {
121
+ const rules = childrenByTag(el, 'branchRule').flatMap((rule) => {
122
+ const target = getAttr(rule, 'target');
123
+ if (!target)
124
+ return [];
125
+ const expression = childElements(rule)[0];
126
+ return [{ target, conditionXml: expression ? serializeXml(expression) : undefined }];
127
+ });
128
+ return rules.length > 0 ? rules : undefined;
129
+ };
130
+ const parseSelection = (el) => {
131
+ const selection = childrenByTag(el, 'selection')[0];
132
+ if (!selection)
133
+ return undefined;
134
+ const select = Number.parseInt(getAttr(selection, 'select') ?? '', 10);
135
+ if (!Number.isInteger(select) || select < 0)
136
+ return undefined;
137
+ const withReplacementRaw = getAttr(selection, 'withReplacement');
138
+ return {
139
+ select,
140
+ withReplacement: withReplacementRaw === undefined ? undefined : withReplacementRaw === 'true',
141
+ };
142
+ };
143
+ const parseOrdering = (el) => {
144
+ const ordering = childrenByTag(el, 'ordering')[0];
145
+ if (!ordering)
146
+ return undefined;
147
+ return { shuffle: getAttr(ordering, 'shuffle') === 'true' };
148
+ };
149
+ const resolveCheckedHref = (href, sourceHref) => {
150
+ if (!href)
151
+ return undefined;
152
+ if (sourceHref) {
153
+ return resolveCheckedPackagePathFromFile(sourceHref, href) ?? undefined;
154
+ }
155
+ return baseUrl
156
+ ? resolveCheckedPackagePathFromFile(baseUrl, href) ?? undefined
157
+ : resolveCheckedPackagePath(undefined, href) ?? undefined;
158
+ };
159
+ const loadText = async (href, sourceHref) => {
160
+ if (!href)
161
+ return undefined;
162
+ const candidates = [href, resolveCheckedHref(href, sourceHref)].filter((value, index, all) => Boolean(value) && all.indexOf(value) === index);
163
+ for (const candidate of candidates) {
164
+ if (itemXmlMap[candidate] !== undefined) {
165
+ return itemXmlMap[candidate];
166
+ }
167
+ }
168
+ if (!fileResolver)
169
+ return undefined;
170
+ for (const candidate of candidates) {
171
+ try {
172
+ return await fileResolver(candidate);
173
+ }
174
+ catch {
175
+ // Try the next candidate before giving up.
176
+ }
177
+ }
178
+ return undefined;
179
+ };
180
+ const buildDeliveryContext = async (itemXml, itemHref) => {
181
+ if (!itemHref) {
182
+ return undefined;
183
+ }
184
+ const stimulusXmlByPath = {};
185
+ const packageTextByPath = {};
186
+ const preloadText = async (baseHref, href) => {
187
+ const resolvedPath = resolveCheckedPackagePathFromFile(baseHref, href);
188
+ if (!resolvedPath)
189
+ return;
190
+ const text = await loadText(resolvedPath);
191
+ if (text !== undefined) {
192
+ packageTextByPath[resolvedPath] = text;
193
+ }
194
+ };
195
+ for (const stylesheet of extractQtiStylesheets(itemXml)) {
196
+ await preloadText(itemHref, stylesheet.href);
197
+ }
198
+ for (const ref of extractAssessmentStimulusRefs(itemXml)) {
199
+ const stimulusPath = resolveCheckedPackagePathFromFile(itemHref, ref.href);
200
+ if (!stimulusPath)
201
+ continue;
202
+ const stimulusXml = await loadText(stimulusPath);
203
+ if (stimulusXml) {
204
+ stimulusXmlByPath[stimulusPath] = stimulusXml;
205
+ for (const stylesheet of parseAssessmentStimulusXml(stimulusXml).stylesheets) {
206
+ await preloadText(stimulusPath, stylesheet.href);
207
+ }
208
+ }
209
+ }
210
+ // Preload external processing fragments so the item session's synchronous
211
+ // resolver stays package-contained. Nested includes resolve relative to the
212
+ // fragment that references them; the processing engine still validates
213
+ // namespace, mode, depth, and cycles at build time.
214
+ const processingFragments = {};
215
+ const collectProcessingFragments = async (sourceXml, sourceHref, seen) => {
216
+ for (const includeHref of extractProcessingIncludeRefs(sourceXml)) {
217
+ const fragmentPath = resolveCheckedPackagePathFromFile(sourceHref, includeHref);
218
+ if (!fragmentPath || seen.has(fragmentPath))
219
+ continue;
220
+ seen.add(fragmentPath);
221
+ const fragmentXml = await loadText(fragmentPath);
222
+ if (fragmentXml === undefined)
223
+ continue;
224
+ processingFragments[fragmentPath] = fragmentXml;
225
+ await collectProcessingFragments(fragmentXml, fragmentPath, seen);
226
+ }
227
+ };
228
+ const fragmentSeen = new Set();
229
+ await collectProcessingFragments(itemXml, itemHref, fragmentSeen);
230
+ // Shared catalog files resolve against the package root, not the item.
231
+ const packageCatalogSources = [];
232
+ for (const shared of sharedCatalogs ?? []) {
233
+ if (shared.xml) {
234
+ packageCatalogSources.push({ href: shared.href, xml: shared.xml });
235
+ continue;
236
+ }
237
+ if (!shared.href)
238
+ continue;
239
+ const href = resolveCheckedHref(shared.href);
240
+ if (!href)
241
+ continue;
242
+ const xml = await loadText(href);
243
+ if (xml !== undefined)
244
+ packageCatalogSources.push({ href, xml });
245
+ }
246
+ return createResolvedItemDeliveryContext({
247
+ itemXml,
248
+ itemHref,
249
+ readText: (path) => packageTextByPath[path] ?? stimulusXmlByPath[path] ?? itemXmlMap[path],
250
+ ...(Object.keys(processingFragments).length > 0 ? { processingFragments } : {}),
251
+ ...(packageCatalogSources.length > 0 ? { packageCatalogSources } : {}),
252
+ });
253
+ };
254
+ let resolveSectionRef;
255
+ const parseItemRef = async (ref, sourceHref) => {
256
+ const itemId = getAttr(ref, 'identifier') ?? 'item';
257
+ const href = getAttr(ref, 'href');
258
+ const itemHref = resolveCheckedHref(href, sourceHref);
259
+ const resolvedXml = href && !itemHref
260
+ ? ''
261
+ : itemXmlMap[itemId] ??
262
+ (href ? itemXmlMap[href] : undefined) ??
263
+ (itemHref ? itemXmlMap[itemHref] : undefined) ??
264
+ (await loadText(itemHref)) ??
265
+ '';
266
+ const requiredRaw = getAttr(ref, 'required');
267
+ const fixedRaw = getAttr(ref, 'fixed');
268
+ const categories = (getAttr(ref, 'category') ?? '').split(/\s+/).filter(Boolean);
269
+ const weights = childrenByTag(ref, 'weight').flatMap((weight) => {
270
+ const identifier = getAttr(weight, 'identifier');
271
+ const value = Number(getAttr(weight, 'value'));
272
+ return identifier && Number.isFinite(value) ? [{ identifier, value }] : [];
273
+ });
274
+ const variableMappings = childrenByTag(ref, 'variableMapping').flatMap((mapping) => {
275
+ const sourceIdentifier = getAttr(mapping, 'sourceIdentifier');
276
+ const targetIdentifier = getAttr(mapping, 'targetIdentifier');
277
+ return sourceIdentifier && targetIdentifier ? [{ sourceIdentifier, targetIdentifier }] : [];
278
+ });
279
+ const templateDefaults = childrenByTag(ref, 'templateDefault').flatMap((templateDefault) => {
280
+ const templateIdentifier = getAttr(templateDefault, 'templateIdentifier');
281
+ const expression = childElements(templateDefault)[0];
282
+ return templateIdentifier && expression
283
+ ? [{ templateIdentifier, expressionXml: serializeXml(expression) }]
284
+ : [];
285
+ });
286
+ return {
287
+ identifier: itemId,
288
+ itemXml: resolvedXml,
289
+ role,
290
+ required: requiredRaw === undefined ? undefined : requiredRaw !== 'false',
291
+ fixed: fixedRaw === undefined ? undefined : fixedRaw !== 'false',
292
+ timeLimits: parseTimeLimits(ref),
293
+ deliveryContext: await buildDeliveryContext(resolvedXml, itemHref),
294
+ branchRule: parseBranchRules(ref),
295
+ preConditions: parseConditionExpressions(ref, 'preCondition'),
296
+ weights: weights.length > 0 ? weights : undefined,
297
+ categories: categories.length > 0 ? categories : undefined,
298
+ itemSessionControl: parseItemSessionControl(ref),
299
+ variableMappings: variableMappings.length > 0 ? variableMappings : undefined,
300
+ templateDefaults: templateDefaults.length > 0 ? templateDefaults : undefined,
301
+ };
302
+ };
303
+ // Parse a single assessmentSection element without flattening nested sections.
304
+ // `inheritedLanguage` is the content language at the assessmentSectionRef of an
305
+ // external section file, whose own root has no ancestors to inherit it from.
306
+ const parseSection = async (sectionEl, sourceHref, ancestorHrefs = [], depth = 1, inheritedLanguage) => {
307
+ const identifier = getAttr(sectionEl, 'identifier') ?? 'section';
308
+ if (depth > maxSectionDepth) {
309
+ throw new AssessmentSectionReferenceLimitError(`assessmentSection nesting exceeds maxDepth (${maxSectionDepth}) at "${identifier}"`);
310
+ }
311
+ const title = getAttr(sectionEl, 'title');
312
+ const visibleRaw = getAttr(sectionEl, 'visible');
313
+ const visible = visibleRaw === undefined ? true : visibleRaw !== 'false';
314
+ const requiredRaw = getAttr(sectionEl, 'required');
315
+ const fixedRaw = getAttr(sectionEl, 'fixed');
316
+ const keepTogetherRaw = getAttr(sectionEl, 'keepTogether');
317
+ const itemSessionControl = parseItemSessionControl(sectionEl);
318
+ const timeLimits = parseTimeLimits(sectionEl);
319
+ // rubricBlocks
320
+ const rubricBlockEls = childrenByTag(sectionEl, 'rubricBlock');
321
+ const rubricBlocks = rubricBlockEls.length > 0
322
+ ? rubricBlockEls.map((b, idx) => {
323
+ const language = rubricLanguageOf(b, inheritedLanguage);
324
+ return {
325
+ identifier: getAttr(b, 'identifier') ?? `${identifier}-rubric-${idx + 1}`,
326
+ view: (getAttr(b, 'view') ?? 'candidate').split(/\s+/).filter(Boolean),
327
+ use: getAttr(b, 'use'),
328
+ content: serializeXml(b),
329
+ ...(language ? { language } : {}),
330
+ };
331
+ })
332
+ : undefined;
333
+ const assessmentItemRefs = [];
334
+ const sections = [];
335
+ const children = [];
336
+ for (const child of childElements(sectionEl)) {
337
+ const name = toCanonicalQtiName(child.localName);
338
+ if (name === 'assessmentItemRef') {
339
+ const item = await parseItemRef(child, sourceHref);
340
+ assessmentItemRefs.push(item);
341
+ children.push({ type: 'item', item });
342
+ }
343
+ else if (name === 'assessmentSection') {
344
+ const section = await parseSection(child, sourceHref, ancestorHrefs, depth + 1, inheritedLanguage);
345
+ sections.push(section);
346
+ children.push({ type: 'section', section });
347
+ }
348
+ else if (name === 'assessmentSectionRef') {
349
+ const section = await resolveSectionRef(child, sourceHref, ancestorHrefs, depth + 1, inheritedLanguage);
350
+ if (section) {
351
+ sections.push(section);
352
+ children.push({ type: 'section', section });
353
+ }
354
+ }
355
+ }
356
+ return {
357
+ identifier,
358
+ title,
359
+ visible,
360
+ required: requiredRaw === undefined ? undefined : requiredRaw !== 'false',
361
+ fixed: fixedRaw === undefined ? undefined : fixedRaw !== 'false',
362
+ assessmentItemRefs,
363
+ sections: sections.length > 0 ? sections : undefined,
364
+ children: children.length > 0 ? children : undefined,
365
+ rubricBlocks,
366
+ itemSessionControl,
367
+ timeLimits,
368
+ selection: parseSelection(sectionEl),
369
+ ordering: parseOrdering(sectionEl),
370
+ preConditions: parseConditionExpressions(sectionEl, 'preCondition'),
371
+ branchRule: parseBranchRules(sectionEl),
372
+ keepTogether: keepTogetherRaw === undefined ? undefined : keepTogetherRaw !== 'false',
373
+ };
374
+ };
375
+ // Resolve assessmentSectionRef: load and parse referenced section file
376
+ resolveSectionRef = async (sectionRefEl, sourceHref, ancestorHrefs = [], depth = 1, inheritedLanguage) => {
377
+ const href = getAttr(sectionRefEl, 'href');
378
+ if (!href) {
379
+ console.warn('[ReferenceBackendAdapter] assessmentSectionRef missing href, skipping');
380
+ return null;
381
+ }
382
+ if (!fileResolver) {
383
+ console.warn(`[ReferenceBackendAdapter] assessmentSectionRef href="${href}" found but no fileResolver provided, skipping`);
384
+ return null;
385
+ }
386
+ try {
387
+ const resolvedHref = resolveCheckedHref(href, sourceHref);
388
+ if (!resolvedHref) {
389
+ console.warn(`[ReferenceBackendAdapter] assessmentSectionRef href="${href}" is unsafe, skipping`);
390
+ return null;
391
+ }
392
+ if (ancestorHrefs.includes(resolvedHref)) {
393
+ throw new AssessmentSectionReferenceLimitError(`Cyclic assessmentSectionRef detected: ${[...ancestorHrefs, resolvedHref].join(' -> ')}`);
394
+ }
395
+ if (depth > maxSectionDepth) {
396
+ throw new AssessmentSectionReferenceLimitError(`assessmentSectionRef nesting exceeds maxDepth (${maxSectionDepth}) at "${resolvedHref}"`);
397
+ }
398
+ const sectionXml = await fileResolver(resolvedHref);
399
+ const secDoc = parseXml(sectionXml);
400
+ const secRoot = secDoc.documentElement;
401
+ if (!secRoot || toCanonicalQtiName(secRoot.localName) !== 'assessmentSection') {
402
+ console.warn(`[ReferenceBackendAdapter] assessmentSectionRef href="${href}": root element is not <assessmentSection>, skipping`);
403
+ return null;
404
+ }
405
+ // The referenced section stands in for the ref: it inherits the ref's language.
406
+ return parseSection(secRoot, resolvedHref, [...ancestorHrefs, resolvedHref], depth, contentLanguageOf(sectionRefEl, inheritedLanguage));
407
+ }
408
+ catch (err) {
409
+ if (err instanceof AssessmentSectionReferenceLimitError)
410
+ throw err;
411
+ console.warn(`[ReferenceBackendAdapter] Failed to load assessmentSectionRef href="${href}":`, err);
412
+ return null;
413
+ }
414
+ };
415
+ // Parse testPart children (sections + sectionRefs)
416
+ const parseSectionsForTestPart = async (testPartEl) => {
417
+ const sections = [];
418
+ for (const child of childElements(testPartEl)) {
419
+ if (toCanonicalQtiName(child.localName) === 'assessmentSection') {
420
+ sections.push(await parseSection(child));
421
+ }
422
+ else if (toCanonicalQtiName(child.localName) === 'assessmentSectionRef') {
423
+ const resolved = await resolveSectionRef(child);
424
+ if (resolved)
425
+ sections.push(resolved);
426
+ }
427
+ }
428
+ return sections;
429
+ };
430
+ // Extract outcomeDeclarations
431
+ const outcomeDeclarations = childrenByTag(root, 'outcomeDeclaration').map((d) => {
432
+ const identifier = getAttr(d, 'identifier') ?? 'OUTCOME';
433
+ const baseType = getAttr(d, 'baseType') ?? 'float';
434
+ const cardinality = getAttr(d, 'cardinality') ?? 'single';
435
+ // Parse defaultValue if present
436
+ const defaultValueEl = childrenByTag(d, 'defaultValue')[0];
437
+ let defaultValue = undefined;
438
+ if (defaultValueEl) {
439
+ const valueEl = childrenByTag(defaultValueEl, 'value')[0];
440
+ if (valueEl) {
441
+ const text = valueEl.textContent?.trim() ?? '0';
442
+ if (baseType === 'float' || baseType === 'integer') {
443
+ defaultValue = Number(text);
444
+ }
445
+ else {
446
+ defaultValue = text;
447
+ }
448
+ }
449
+ }
450
+ return { identifier, baseType, cardinality, defaultValue };
451
+ });
452
+ // Extract outcomeProcessing XML
453
+ const outcomeProcessingEl = childrenByTag(root, 'outcomeProcessing')[0];
454
+ const outcomeProcessingXml = outcomeProcessingEl
455
+ ? serializeXml(outcomeProcessingEl)
456
+ : undefined;
457
+ // QTI 3 wraps testFeedback content in qti-content-body. Only the body's children are
458
+ // kept as content, so the language it is written in travels as `language`.
459
+ const parseTestFeedback = (parent) => {
460
+ const items = childrenByTag(parent, 'testFeedback').flatMap((feedback, index) => {
461
+ const outcomeIdentifier = getAttr(feedback, 'outcomeIdentifier');
462
+ if (!outcomeIdentifier)
463
+ return [];
464
+ const body = childrenByTag(feedback, 'contentBody')[0] ?? feedback;
465
+ const content = Array.from(body.childNodes).map((node) => serializeXml(node)).join('');
466
+ const language = contentLanguageOf(body);
467
+ return [{
468
+ identifier: getAttr(feedback, 'identifier') ?? `test-feedback-${index + 1}`,
469
+ outcomeIdentifier,
470
+ showHide: (getAttr(feedback, 'showHide') ?? 'show'),
471
+ access: (getAttr(feedback, 'access') ?? 'atEnd'),
472
+ content,
473
+ ...(language ? { language } : {}),
474
+ }];
475
+ });
476
+ return items.length > 0 ? items : undefined;
477
+ };
478
+ const testFeedback = parseTestFeedback(root);
479
+ // Extract assessment-level timeLimits.
480
+ const timeLimits = parseTimeLimits(root);
481
+ // Parse testParts
482
+ const testPartEls = childrenByTag(root, 'testPart');
483
+ const firstTestPart = testPartEls[0];
484
+ // Retain top-level compatibility fields while preserving the authoritative
485
+ // mode on every testPart below.
486
+ const navigationMode = (getAttr(firstTestPart ?? root, 'navigationMode') ?? 'nonlinear');
487
+ const submissionMode = (getAttr(firstTestPart ?? root, 'submissionMode') ?? 'simultaneous');
488
+ const testParts = [];
489
+ for (const tp of testPartEls) {
490
+ const tpIdentifier = getAttr(tp, 'identifier') ?? 'part-1';
491
+ const tpNavigationMode = (getAttr(tp, 'navigationMode') ?? 'nonlinear');
492
+ const tpSubmissionMode = (getAttr(tp, 'submissionMode') ?? 'simultaneous');
493
+ const tpItemSessionControl = parseItemSessionControl(tp);
494
+ const tpTimeLimits = parseTimeLimits(tp);
495
+ const tpRubricBlockEls = childrenByTag(tp, 'rubricBlock');
496
+ const tpRubricBlocks = tpRubricBlockEls.length > 0
497
+ ? tpRubricBlockEls.map((b, idx) => {
498
+ const language = rubricLanguageOf(b);
499
+ return {
500
+ identifier: getAttr(b, 'identifier') ?? `${tpIdentifier}-rubric-${idx + 1}`,
501
+ view: (getAttr(b, 'view') ?? 'candidate').split(/\s+/).filter(Boolean),
502
+ use: getAttr(b, 'use'),
503
+ content: serializeXml(b),
504
+ ...(language ? { language } : {}),
505
+ };
506
+ })
507
+ : undefined;
508
+ const sections = await parseSectionsForTestPart(tp);
509
+ testParts.push({
510
+ identifier: tpIdentifier,
511
+ navigationMode: tpNavigationMode,
512
+ submissionMode: tpSubmissionMode,
513
+ sections,
514
+ rubricBlocks: tpRubricBlocks,
515
+ testFeedback: parseTestFeedback(tp),
516
+ itemSessionControl: tpItemSessionControl,
517
+ timeLimits: tpTimeLimits,
518
+ preConditions: parseConditionExpressions(tp, 'preCondition'),
519
+ branchRule: parseBranchRules(tp),
520
+ });
521
+ }
522
+ // If no testParts, try top-level sections
523
+ if (testParts.length === 0) {
524
+ const topSections = [];
525
+ for (const child of childElements(root)) {
526
+ if (toCanonicalQtiName(child.localName) === 'assessmentSection') {
527
+ topSections.push(await parseSection(child));
528
+ }
529
+ else if (toCanonicalQtiName(child.localName) === 'assessmentSectionRef') {
530
+ const resolved = await resolveSectionRef(child);
531
+ if (resolved)
532
+ topSections.push(resolved);
533
+ }
534
+ }
535
+ if (topSections.length > 0) {
536
+ testParts.push({
537
+ identifier: 'part-1',
538
+ navigationMode,
539
+ submissionMode,
540
+ sections: topSections,
541
+ });
542
+ }
543
+ }
544
+ return {
545
+ identifier: getAttr(root, 'identifier') ?? 'assessment',
546
+ // Left empty when absent: shells show a localized generic title, not English text.
547
+ title: getAttr(root, 'title') ?? '',
548
+ navigationMode,
549
+ submissionMode,
550
+ testParts,
551
+ timeLimits,
552
+ outcomeDeclarations: outcomeDeclarations.length > 0 ? outcomeDeclarations : undefined,
553
+ outcomeProcessingXml,
554
+ testFeedback,
555
+ baseUrl,
556
+ };
557
+ }
558
+ //# sourceMappingURL=qti-test-parser.js.map