@pie-qti/item-player 0.1.1

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 (335) hide show
  1. package/.turbo/turbo-build.log +1 -0
  2. package/CHANGELOG.md +9 -0
  3. package/README.md +466 -0
  4. package/docs/QTI-COMPLIANCE.md +197 -0
  5. package/docs/WCAG-2.2-COMPLIANCE.md +466 -0
  6. package/docs/custom-extractors.md +679 -0
  7. package/docs/iframe-mode.md +78 -0
  8. package/docs/security-audit.md +236 -0
  9. package/docs/server-api.md +691 -0
  10. package/package.json +78 -0
  11. package/src/components/ItemBody.svelte +382 -0
  12. package/src/components/ItemPlayer.svelte +155 -0
  13. package/src/components/ModalFeedbackDisplay.svelte +87 -0
  14. package/src/components/actions/typesetAction.ts +74 -0
  15. package/src/components/index.ts +19 -0
  16. package/src/components/utils/assignProps.ts +24 -0
  17. package/src/components/utils/feedbackUtils.ts +140 -0
  18. package/src/components/utils/index.ts +13 -0
  19. package/src/core/ComponentRegistry.ts +219 -0
  20. package/src/core/ItemRenderer.ts +367 -0
  21. package/src/core/Player.ts +1152 -0
  22. package/src/core/Plugin.ts +123 -0
  23. package/src/core/PluginManager.ts +182 -0
  24. package/src/core/constants.ts +117 -0
  25. package/src/core/declarations.ts +171 -0
  26. package/src/core/parsingLimits.ts +62 -0
  27. package/src/core/random.ts +24 -0
  28. package/src/core/sanitizer.ts +235 -0
  29. package/src/core/trustedTypes.ts +63 -0
  30. package/src/core/urlPolicy.ts +95 -0
  31. package/src/extensions/MathLiveEditor.ts +310 -0
  32. package/src/extraction/ExtractionRegistry.ts +295 -0
  33. package/src/extraction/createContext.ts +47 -0
  34. package/src/extraction/extractors/associateExtractor.ts +129 -0
  35. package/src/extraction/extractors/choiceExtractor.ts +110 -0
  36. package/src/extraction/extractors/customExtractor.ts +72 -0
  37. package/src/extraction/extractors/drawingExtractor.ts +113 -0
  38. package/src/extraction/extractors/endAttemptExtractor.ts +74 -0
  39. package/src/extraction/extractors/extendedTextExtractor.ts +80 -0
  40. package/src/extraction/extractors/gapMatchExtractor.ts +178 -0
  41. package/src/extraction/extractors/graphicAssociateExtractor.ts +188 -0
  42. package/src/extraction/extractors/graphicGapMatchExtractor.ts +185 -0
  43. package/src/extraction/extractors/graphicOrderExtractor.ts +162 -0
  44. package/src/extraction/extractors/hotspotExtractor.ts +190 -0
  45. package/src/extraction/extractors/hottextExtractor.ts +153 -0
  46. package/src/extraction/extractors/index.ts +111 -0
  47. package/src/extraction/extractors/inlineChoiceExtractor.ts +88 -0
  48. package/src/extraction/extractors/matchExtractor.ts +160 -0
  49. package/src/extraction/extractors/mediaExtractor.ts +168 -0
  50. package/src/extraction/extractors/orderExtractor.ts +114 -0
  51. package/src/extraction/extractors/positionObjectExtractor.ts +243 -0
  52. package/src/extraction/extractors/selectPointExtractor.ts +143 -0
  53. package/src/extraction/extractors/sliderExtractor.ts +102 -0
  54. package/src/extraction/extractors/textEntryExtractor.ts +70 -0
  55. package/src/extraction/extractors/uploadExtractor.ts +73 -0
  56. package/src/extraction/index.ts +109 -0
  57. package/src/extraction/types.ts +246 -0
  58. package/src/extraction/utils.ts +160 -0
  59. package/src/iframe/IFramePlayerHost.ts +265 -0
  60. package/src/iframe/index.ts +11 -0
  61. package/src/iframe/protocol.ts +137 -0
  62. package/src/index.ts +87 -0
  63. package/src/server.ts +14 -0
  64. package/src/types/index.ts +301 -0
  65. package/src/types/interactions.ts +354 -0
  66. package/src/types/responseValidation.ts +29 -0
  67. package/src/utils/PerformanceMonitor.ts +335 -0
  68. package/src/utils/responseUtils.ts +51 -0
  69. package/src/utils/touchDragHelper.ts +211 -0
  70. package/src/web-components/QTIInteractionBase.ts +302 -0
  71. package/src/web-components/QTIInteractionElement.ts +118 -0
  72. package/src/web-components/index.ts +21 -0
  73. package/tests/conformance/FIXTURE_POLICY.md +29 -0
  74. package/tests/conformance/README.md +70 -0
  75. package/tests/conformance/fixtures/baseTypes_all/cases.json +61 -0
  76. package/tests/conformance/fixtures/baseTypes_all/item.xml +131 -0
  77. package/tests/conformance/fixtures/baseTypes_all/manifest.json +7 -0
  78. package/tests/conformance/fixtures/choice_match_correct/cases.json +17 -0
  79. package/tests/conformance/fixtures/choice_match_correct/item.xml +55 -0
  80. package/tests/conformance/fixtures/choice_match_correct/manifest.json +14 -0
  81. package/tests/conformance/fixtures/contains_multiple/cases.json +12 -0
  82. package/tests/conformance/fixtures/contains_multiple/item.xml +37 -0
  83. package/tests/conformance/fixtures/contains_multiple/manifest.json +13 -0
  84. package/tests/conformance/fixtures/isNull_isNotNull/cases.json +9 -0
  85. package/tests/conformance/fixtures/isNull_isNotNull/item.xml +41 -0
  86. package/tests/conformance/fixtures/isNull_isNotNull/manifest.json +23 -0
  87. package/tests/conformance/fixtures/mapResponse_bounds_default_duplicates/cases.json +27 -0
  88. package/tests/conformance/fixtures/mapResponse_bounds_default_duplicates/item.xml +30 -0
  89. package/tests/conformance/fixtures/mapResponse_bounds_default_duplicates/manifest.json +15 -0
  90. package/tests/conformance/fixtures/mapResponse_integer_mapKey/cases.json +11 -0
  91. package/tests/conformance/fixtures/mapResponse_integer_mapKey/item.xml +26 -0
  92. package/tests/conformance/fixtures/mapResponse_integer_mapKey/manifest.json +13 -0
  93. package/tests/conformance/fixtures/mapResponse_mapEntry_caseSensitive_override/cases.json +27 -0
  94. package/tests/conformance/fixtures/mapResponse_mapEntry_caseSensitive_override/item.xml +32 -0
  95. package/tests/conformance/fixtures/mapResponse_mapEntry_caseSensitive_override/manifest.json +7 -0
  96. package/tests/conformance/fixtures/mapResponse_mapping_caseSensitive_defaultValue/cases.json +9 -0
  97. package/tests/conformance/fixtures/mapResponse_mapping_caseSensitive_defaultValue/item.xml +25 -0
  98. package/tests/conformance/fixtures/mapResponse_mapping_caseSensitive_defaultValue/manifest.json +12 -0
  99. package/tests/conformance/fixtures/mapResponse_multiple_cardinality/cases.json +12 -0
  100. package/tests/conformance/fixtures/mapResponse_multiple_cardinality/item.xml +35 -0
  101. package/tests/conformance/fixtures/mapResponse_multiple_cardinality/manifest.json +11 -0
  102. package/tests/conformance/fixtures/mapping_bounds_upperLower/cases.json +12 -0
  103. package/tests/conformance/fixtures/mapping_bounds_upperLower/item.xml +37 -0
  104. package/tests/conformance/fixtures/mapping_bounds_upperLower/manifest.json +11 -0
  105. package/tests/conformance/fixtures/mapping_mapResponse/cases.json +22 -0
  106. package/tests/conformance/fixtures/mapping_mapResponse/item.xml +53 -0
  107. package/tests/conformance/fixtures/mapping_mapResponse/manifest.json +16 -0
  108. package/tests/conformance/fixtures/member_multiple/cases.json +12 -0
  109. package/tests/conformance/fixtures/member_multiple/item.xml +37 -0
  110. package/tests/conformance/fixtures/member_multiple/manifest.json +13 -0
  111. package/tests/conformance/fixtures/modalFeedback_basic/cases.json +17 -0
  112. package/tests/conformance/fixtures/modalFeedback_basic/item.xml +52 -0
  113. package/tests/conformance/fixtures/modalFeedback_basic/manifest.json +13 -0
  114. package/tests/conformance/fixtures/multiple_unordered_match/cases.json +17 -0
  115. package/tests/conformance/fixtures/multiple_unordered_match/item.xml +44 -0
  116. package/tests/conformance/fixtures/multiple_unordered_match/manifest.json +11 -0
  117. package/tests/conformance/fixtures/ordered_match/cases.json +17 -0
  118. package/tests/conformance/fixtures/ordered_match/item.xml +48 -0
  119. package/tests/conformance/fixtures/ordered_match/manifest.json +13 -0
  120. package/tests/conformance/fixtures/outcomeProcessing_derive_percent_passfail/cases.json +27 -0
  121. package/tests/conformance/fixtures/outcomeProcessing_derive_percent_passfail/item.xml +103 -0
  122. package/tests/conformance/fixtures/outcomeProcessing_derive_percent_passfail/manifest.json +7 -0
  123. package/tests/conformance/fixtures/outcomeProcessing_exitTest/cases.json +15 -0
  124. package/tests/conformance/fixtures/outcomeProcessing_exitTest/item.xml +33 -0
  125. package/tests/conformance/fixtures/outcomeProcessing_exitTest/manifest.json +10 -0
  126. package/tests/conformance/fixtures/outcomeProcessing_numberExpressions/cases.json +14 -0
  127. package/tests/conformance/fixtures/outcomeProcessing_numberExpressions/item.xml +26 -0
  128. package/tests/conformance/fixtures/outcomeProcessing_numberExpressions/manifest.json +8 -0
  129. package/tests/conformance/fixtures/outcomeProcessing_outcomeCondition_equal/cases.json +17 -0
  130. package/tests/conformance/fixtures/outcomeProcessing_outcomeCondition_equal/item.xml +43 -0
  131. package/tests/conformance/fixtures/outcomeProcessing_outcomeCondition_equal/manifest.json +16 -0
  132. package/tests/conformance/fixtures/outcomeProcessing_outcomeCondition_toBoolean/cases.json +27 -0
  133. package/tests/conformance/fixtures/outcomeProcessing_outcomeCondition_toBoolean/item.xml +37 -0
  134. package/tests/conformance/fixtures/outcomeProcessing_outcomeCondition_toBoolean/manifest.json +16 -0
  135. package/tests/conformance/fixtures/outcomeProcessing_outcomeMaximum/cases.json +14 -0
  136. package/tests/conformance/fixtures/outcomeProcessing_outcomeMaximum/item.xml +35 -0
  137. package/tests/conformance/fixtures/outcomeProcessing_outcomeMaximum/manifest.json +8 -0
  138. package/tests/conformance/fixtures/outcomeProcessing_outcomeMinimum/cases.json +14 -0
  139. package/tests/conformance/fixtures/outcomeProcessing_outcomeMinimum/item.xml +35 -0
  140. package/tests/conformance/fixtures/outcomeProcessing_outcomeMinimum/manifest.json +8 -0
  141. package/tests/conformance/fixtures/outcomeProcessing_outcomeProcessingFragment/cases.json +15 -0
  142. package/tests/conformance/fixtures/outcomeProcessing_outcomeProcessingFragment/item.xml +39 -0
  143. package/tests/conformance/fixtures/outcomeProcessing_outcomeProcessingFragment/manifest.json +11 -0
  144. package/tests/conformance/fixtures/outcomeProcessing_testVariables/cases.json +14 -0
  145. package/tests/conformance/fixtures/outcomeProcessing_testVariables/item.xml +35 -0
  146. package/tests/conformance/fixtures/outcomeProcessing_testVariables/manifest.json +8 -0
  147. package/tests/conformance/fixtures/pair_unordered_match/cases.json +22 -0
  148. package/tests/conformance/fixtures/pair_unordered_match/item.xml +44 -0
  149. package/tests/conformance/fixtures/pair_unordered_match/manifest.json +13 -0
  150. package/tests/conformance/fixtures/positionObject_coordinateSystem_aspectRatio/cases.json +95 -0
  151. package/tests/conformance/fixtures/positionObject_coordinateSystem_aspectRatio/item.xml +53 -0
  152. package/tests/conformance/fixtures/positionObject_mapResponsePoint_scoring/cases.json +115 -0
  153. package/tests/conformance/fixtures/positionObject_mapResponsePoint_scoring/item.xml +45 -0
  154. package/tests/conformance/fixtures/positionObject_mapResponse_wrong/cases.json +29 -0
  155. package/tests/conformance/fixtures/positionObject_mapResponse_wrong/item.xml +40 -0
  156. package/tests/conformance/fixtures/responseCondition_elseIf_chain/cases.json +10 -0
  157. package/tests/conformance/fixtures/responseCondition_elseIf_chain/item.xml +49 -0
  158. package/tests/conformance/fixtures/responseCondition_elseIf_chain/manifest.json +15 -0
  159. package/tests/conformance/fixtures/responseProcessing_anyN/cases.json +27 -0
  160. package/tests/conformance/fixtures/responseProcessing_anyN/item.xml +47 -0
  161. package/tests/conformance/fixtures/responseProcessing_anyN/manifest.json +16 -0
  162. package/tests/conformance/fixtures/responseProcessing_anyN_allN/cases.json +27 -0
  163. package/tests/conformance/fixtures/responseProcessing_anyN_allN/item.xml +69 -0
  164. package/tests/conformance/fixtures/responseProcessing_anyN_allN/manifest.json +23 -0
  165. package/tests/conformance/fixtures/responseProcessing_arithmetic_nulls/cases.json +15 -0
  166. package/tests/conformance/fixtures/responseProcessing_arithmetic_nulls/item.xml +58 -0
  167. package/tests/conformance/fixtures/responseProcessing_arithmetic_nulls/manifest.json +15 -0
  168. package/tests/conformance/fixtures/responseProcessing_boolean_compare_ops/cases.json +37 -0
  169. package/tests/conformance/fixtures/responseProcessing_boolean_compare_ops/item.xml +94 -0
  170. package/tests/conformance/fixtures/responseProcessing_boolean_compare_ops/manifest.json +27 -0
  171. package/tests/conformance/fixtures/responseProcessing_containerSize_index/cases.json +33 -0
  172. package/tests/conformance/fixtures/responseProcessing_containerSize_index/item.xml +79 -0
  173. package/tests/conformance/fixtures/responseProcessing_containerSize_index/manifest.json +16 -0
  174. package/tests/conformance/fixtures/responseProcessing_customOperator/cases.json +15 -0
  175. package/tests/conformance/fixtures/responseProcessing_customOperator/item.xml +30 -0
  176. package/tests/conformance/fixtures/responseProcessing_customOperator/manifest.json +12 -0
  177. package/tests/conformance/fixtures/responseProcessing_default_expression/cases.json +12 -0
  178. package/tests/conformance/fixtures/responseProcessing_default_expression/item.xml +48 -0
  179. package/tests/conformance/fixtures/responseProcessing_default_expression/manifest.json +13 -0
  180. package/tests/conformance/fixtures/responseProcessing_deleteValue_repeat/cases.json +29 -0
  181. package/tests/conformance/fixtures/responseProcessing_deleteValue_repeat/item.xml +68 -0
  182. package/tests/conformance/fixtures/responseProcessing_deleteValue_repeat/manifest.json +17 -0
  183. package/tests/conformance/fixtures/responseProcessing_equalRounded_tolerance/cases.json +39 -0
  184. package/tests/conformance/fixtures/responseProcessing_equalRounded_tolerance/item.xml +39 -0
  185. package/tests/conformance/fixtures/responseProcessing_equalRounded_tolerance/manifest.json +17 -0
  186. package/tests/conformance/fixtures/responseProcessing_exitResponse/cases.json +12 -0
  187. package/tests/conformance/fixtures/responseProcessing_exitResponse/item.xml +25 -0
  188. package/tests/conformance/fixtures/responseProcessing_exitResponse/manifest.json +12 -0
  189. package/tests/conformance/fixtures/responseProcessing_inside_duration_statsOperator/cases.json +26 -0
  190. package/tests/conformance/fixtures/responseProcessing_inside_duration_statsOperator/item.xml +134 -0
  191. package/tests/conformance/fixtures/responseProcessing_inside_duration_statsOperator/manifest.json +16 -0
  192. package/tests/conformance/fixtures/responseProcessing_lookupTable_interpolationTable/cases.json +27 -0
  193. package/tests/conformance/fixtures/responseProcessing_lookupTable_interpolationTable/item.xml +33 -0
  194. package/tests/conformance/fixtures/responseProcessing_lookupTable_interpolationTable/manifest.json +13 -0
  195. package/tests/conformance/fixtures/responseProcessing_lookupTable_matchTable/cases.json +22 -0
  196. package/tests/conformance/fixtures/responseProcessing_lookupTable_matchTable/item.xml +33 -0
  197. package/tests/conformance/fixtures/responseProcessing_lookupTable_matchTable/manifest.json +13 -0
  198. package/tests/conformance/fixtures/responseProcessing_mapOutcome_basic/cases.json +27 -0
  199. package/tests/conformance/fixtures/responseProcessing_mapOutcome_basic/item.xml +40 -0
  200. package/tests/conformance/fixtures/responseProcessing_mapOutcome_basic/manifest.json +18 -0
  201. package/tests/conformance/fixtures/responseProcessing_mapResponsePoint_basic/cases.json +22 -0
  202. package/tests/conformance/fixtures/responseProcessing_mapResponsePoint_basic/item.xml +33 -0
  203. package/tests/conformance/fixtures/responseProcessing_mapResponsePoint_basic/manifest.json +12 -0
  204. package/tests/conformance/fixtures/responseProcessing_mapResponse_directedPair_ordered/cases.json +29 -0
  205. package/tests/conformance/fixtures/responseProcessing_mapResponse_directedPair_ordered/item.xml +26 -0
  206. package/tests/conformance/fixtures/responseProcessing_mapResponse_directedPair_ordered/manifest.json +7 -0
  207. package/tests/conformance/fixtures/responseProcessing_mapResponse_directedPair_whitespace/cases.json +23 -0
  208. package/tests/conformance/fixtures/responseProcessing_mapResponse_directedPair_whitespace/item.xml +28 -0
  209. package/tests/conformance/fixtures/responseProcessing_mapResponse_directedPair_whitespace/manifest.json +11 -0
  210. package/tests/conformance/fixtures/responseProcessing_mapResponse_pair_unordered/cases.json +29 -0
  211. package/tests/conformance/fixtures/responseProcessing_mapResponse_pair_unordered/item.xml +26 -0
  212. package/tests/conformance/fixtures/responseProcessing_mapResponse_pair_unordered/manifest.json +7 -0
  213. package/tests/conformance/fixtures/responseProcessing_mathOperator_integerUtils/cases.json +31 -0
  214. package/tests/conformance/fixtures/responseProcessing_mathOperator_integerUtils/item.xml +102 -0
  215. package/tests/conformance/fixtures/responseProcessing_mathOperator_integerUtils/manifest.json +18 -0
  216. package/tests/conformance/fixtures/responseProcessing_math_max_min_round_truncate/cases.json +22 -0
  217. package/tests/conformance/fixtures/responseProcessing_math_max_min_round_truncate/item.xml +45 -0
  218. package/tests/conformance/fixtures/responseProcessing_math_max_min_round_truncate/manifest.json +21 -0
  219. package/tests/conformance/fixtures/responseProcessing_misc_math_string_stats/cases.json +26 -0
  220. package/tests/conformance/fixtures/responseProcessing_misc_math_string_stats/item.xml +157 -0
  221. package/tests/conformance/fixtures/responseProcessing_misc_math_string_stats/manifest.json +22 -0
  222. package/tests/conformance/fixtures/responseProcessing_notEqual_basic/cases.json +22 -0
  223. package/tests/conformance/fixtures/responseProcessing_notEqual_basic/item.xml +39 -0
  224. package/tests/conformance/fixtures/responseProcessing_notEqual_basic/manifest.json +18 -0
  225. package/tests/conformance/fixtures/responseProcessing_patternMatch_caseSensitive/cases.json +22 -0
  226. package/tests/conformance/fixtures/responseProcessing_patternMatch_caseSensitive/item.xml +51 -0
  227. package/tests/conformance/fixtures/responseProcessing_patternMatch_caseSensitive/manifest.json +19 -0
  228. package/tests/conformance/fixtures/responseProcessing_preCondition/cases.json +31 -0
  229. package/tests/conformance/fixtures/responseProcessing_preCondition/item.xml +44 -0
  230. package/tests/conformance/fixtures/responseProcessing_preCondition/manifest.json +12 -0
  231. package/tests/conformance/fixtures/responseProcessing_random_lookupOutcomeValue/cases.json +27 -0
  232. package/tests/conformance/fixtures/responseProcessing_random_lookupOutcomeValue/item.xml +42 -0
  233. package/tests/conformance/fixtures/responseProcessing_random_lookupOutcomeValue/manifest.json +14 -0
  234. package/tests/conformance/fixtures/responseProcessing_record_fieldValue/cases.json +12 -0
  235. package/tests/conformance/fixtures/responseProcessing_record_fieldValue/item.xml +40 -0
  236. package/tests/conformance/fixtures/responseProcessing_record_fieldValue/manifest.json +17 -0
  237. package/tests/conformance/fixtures/responseProcessing_responseCondition_toBoolean/cases.json +17 -0
  238. package/tests/conformance/fixtures/responseProcessing_responseCondition_toBoolean/item.xml +63 -0
  239. package/tests/conformance/fixtures/responseProcessing_responseCondition_toBoolean/manifest.json +9 -0
  240. package/tests/conformance/fixtures/responseProcessing_responseProcessingFragment/cases.json +12 -0
  241. package/tests/conformance/fixtures/responseProcessing_responseProcessingFragment/item.xml +40 -0
  242. package/tests/conformance/fixtures/responseProcessing_responseProcessingFragment/manifest.json +13 -0
  243. package/tests/conformance/fixtures/responseProcessing_setDefaultValue/cases.json +15 -0
  244. package/tests/conformance/fixtures/responseProcessing_setDefaultValue/item.xml +67 -0
  245. package/tests/conformance/fixtures/responseProcessing_setDefaultValue/manifest.json +9 -0
  246. package/tests/conformance/fixtures/responseProcessing_setResponseValue_setDefaultValue/cases.json +27 -0
  247. package/tests/conformance/fixtures/responseProcessing_setResponseValue_setDefaultValue/item.xml +69 -0
  248. package/tests/conformance/fixtures/responseProcessing_setResponseValue_setDefaultValue/manifest.json +10 -0
  249. package/tests/conformance/fixtures/responseProcessing_subtract_divide/cases.json +15 -0
  250. package/tests/conformance/fixtures/responseProcessing_subtract_divide/item.xml +35 -0
  251. package/tests/conformance/fixtures/responseProcessing_subtract_divide/manifest.json +11 -0
  252. package/tests/conformance/fixtures/responseProcessing_template_map_response/cases.json +17 -0
  253. package/tests/conformance/fixtures/responseProcessing_template_map_response/item.xml +31 -0
  254. package/tests/conformance/fixtures/responseProcessing_template_map_response/manifest.json +8 -0
  255. package/tests/conformance/fixtures/responseProcessing_template_map_response_point/cases.json +22 -0
  256. package/tests/conformance/fixtures/responseProcessing_template_map_response_point/item.xml +27 -0
  257. package/tests/conformance/fixtures/responseProcessing_template_map_response_point/manifest.json +8 -0
  258. package/tests/conformance/fixtures/responseProcessing_template_match_correct/cases.json +17 -0
  259. package/tests/conformance/fixtures/responseProcessing_template_match_correct/item.xml +34 -0
  260. package/tests/conformance/fixtures/responseProcessing_template_match_correct/manifest.json +8 -0
  261. package/tests/conformance/fixtures/responseProcessing_template_match_correct_directedPair/cases.json +22 -0
  262. package/tests/conformance/fixtures/responseProcessing_template_match_correct_directedPair/item.xml +30 -0
  263. package/tests/conformance/fixtures/responseProcessing_template_match_correct_directedPair/manifest.json +7 -0
  264. package/tests/conformance/fixtures/responseProcessing_template_match_correct_two_responses/cases.json +17 -0
  265. package/tests/conformance/fixtures/responseProcessing_template_match_correct_two_responses/item.xml +30 -0
  266. package/tests/conformance/fixtures/responseProcessing_template_match_correct_two_responses/manifest.json +9 -0
  267. package/tests/conformance/fixtures/responseProcessing_template_match_nothing/cases.json +17 -0
  268. package/tests/conformance/fixtures/responseProcessing_template_match_nothing/item.xml +30 -0
  269. package/tests/conformance/fixtures/responseProcessing_template_match_nothing/manifest.json +8 -0
  270. package/tests/conformance/fixtures/responseProcessing_xiInclude/cases.json +14 -0
  271. package/tests/conformance/fixtures/responseProcessing_xiInclude/item.xml +25 -0
  272. package/tests/conformance/fixtures/responseProcessing_xiInclude/manifest.json +9 -0
  273. package/tests/conformance/fixtures/stringMatch_caseSensitive_substring/cases.json +12 -0
  274. package/tests/conformance/fixtures/stringMatch_caseSensitive_substring/item.xml +52 -0
  275. package/tests/conformance/fixtures/stringMatch_caseSensitive_substring/manifest.json +14 -0
  276. package/tests/conformance/fixtures/templateProcessing_exitTemplate/cases.json +12 -0
  277. package/tests/conformance/fixtures/templateProcessing_exitTemplate/item.xml +48 -0
  278. package/tests/conformance/fixtures/templateProcessing_exitTemplate/manifest.json +13 -0
  279. package/tests/conformance/fixtures/templateProcessing_setCorrectResponse/cases.json +27 -0
  280. package/tests/conformance/fixtures/templateProcessing_setCorrectResponse/item.xml +74 -0
  281. package/tests/conformance/fixtures/templateProcessing_setCorrectResponse/manifest.json +22 -0
  282. package/tests/conformance/fixtures/templateProcessing_templateCondition_branching/cases.json +17 -0
  283. package/tests/conformance/fixtures/templateProcessing_templateCondition_branching/item.xml +133 -0
  284. package/tests/conformance/fixtures/templateProcessing_templateCondition_branching/manifest.json +22 -0
  285. package/tests/conformance/fixtures/templateProcessing_templateCondition_toBoolean/cases.json +12 -0
  286. package/tests/conformance/fixtures/templateProcessing_templateCondition_toBoolean/item.xml +107 -0
  287. package/tests/conformance/fixtures/templateProcessing_templateCondition_toBoolean/manifest.json +16 -0
  288. package/tests/conformance/fixtures/templateProcessing_templateConstraint/cases.json +15 -0
  289. package/tests/conformance/fixtures/templateProcessing_templateConstraint/item.xml +52 -0
  290. package/tests/conformance/fixtures/templateProcessing_templateConstraint/manifest.json +14 -0
  291. package/tests/conformance/fixtures/template_randomFloat_roundTo_mathConstant/cases.json +16 -0
  292. package/tests/conformance/fixtures/template_randomFloat_roundTo_mathConstant/item.xml +49 -0
  293. package/tests/conformance/fixtures/template_randomFloat_roundTo_mathConstant/manifest.json +15 -0
  294. package/tests/conformance/fixtures/template_randomInteger_printedVariable/cases.json +16 -0
  295. package/tests/conformance/fixtures/template_randomInteger_printedVariable/item.xml +38 -0
  296. package/tests/conformance/fixtures/template_randomInteger_printedVariable/manifest.json +13 -0
  297. package/tests/conformance/harness.ts +84 -0
  298. package/tests/conformance/run-fixtures.test.ts +127 -0
  299. package/tests/conformance/scripts/normalize-covers.ts +152 -0
  300. package/tests/conformance/types.ts +53 -0
  301. package/tests/core/Player.test.ts +563 -0
  302. package/tests/core/adaptiveItems.test.ts +442 -0
  303. package/tests/core/correctResponse.test.ts +280 -0
  304. package/tests/core/interaction-plumbing.test.ts +141 -0
  305. package/tests/core/modalFeedback.test.ts +308 -0
  306. package/tests/core/outcome-reset.test.ts +43 -0
  307. package/tests/extraction/extractors/associateExtractor.test.ts +182 -0
  308. package/tests/extraction/extractors/choiceExtractor.test.ts +239 -0
  309. package/tests/extraction/extractors/customExtractor.test.ts +83 -0
  310. package/tests/extraction/extractors/drawingExtractor.test.ts +94 -0
  311. package/tests/extraction/extractors/endAttemptExtractor.test.ts +188 -0
  312. package/tests/extraction/extractors/extendedTextExtractor.test.ts +178 -0
  313. package/tests/extraction/extractors/gapMatchExtractor.test.ts +318 -0
  314. package/tests/extraction/extractors/graphicAssociateExtractor.test.ts +260 -0
  315. package/tests/extraction/extractors/graphicGapMatchExtractor.test.ts +320 -0
  316. package/tests/extraction/extractors/graphicOrderExtractor.test.ts +223 -0
  317. package/tests/extraction/extractors/hotspotExtractor.test.ts +298 -0
  318. package/tests/extraction/extractors/hottextExtractor.test.ts +240 -0
  319. package/tests/extraction/extractors/inlineChoiceExtractor.test.ts +292 -0
  320. package/tests/extraction/extractors/matchExtractor.test.ts +241 -0
  321. package/tests/extraction/extractors/mediaExtractor.test.ts +295 -0
  322. package/tests/extraction/extractors/orderExtractor.test.ts +212 -0
  323. package/tests/extraction/extractors/positionObjectExtractor.test.ts +363 -0
  324. package/tests/extraction/extractors/selectPointExtractor.test.ts +214 -0
  325. package/tests/extraction/extractors/sliderExtractor.test.ts +293 -0
  326. package/tests/extraction/extractors/textEntryExtractor.test.ts +133 -0
  327. package/tests/extraction/extractors/uploadExtractor.test.ts +119 -0
  328. package/tests/extraction/test-utils.ts +57 -0
  329. package/tests/iframe/host.test.ts +145 -0
  330. package/tests/iframe/protocol.test.ts +42 -0
  331. package/tests/performance/player-benchmarks.bench.ts +191 -0
  332. package/tests/security/dos-limits.test.ts +56 -0
  333. package/tests/security/xss-prevention.test.ts +522 -0
  334. package/tsconfig.json +20 -0
  335. package/tsconfig.svelte.json +14 -0
@@ -0,0 +1,1152 @@
1
+ import {
2
+ type AreaMapEntry,
3
+ type AreaMapping,
4
+ type BaseType,
5
+ buildOutcomeProcessingAst,
6
+ buildResponseProcessingAst,
7
+ buildTemplateProcessingAst,
8
+ type Cardinality,
9
+ childElements,
10
+ coerceBaseValue,
11
+ DeclarationContext,
12
+ type DeclarationMap,
13
+ evalExpr,
14
+ execProgram,
15
+ findAssessmentItem,
16
+ findDescendants,
17
+ findFirstDescendant,
18
+ getAttr,
19
+ OperatorRegistry,
20
+ type ProcessingProgram,
21
+ parseXml,
22
+ type QtiValue,
23
+ qtiNull,
24
+ qtiValue,
25
+ serializeXml,
26
+ toBoolean,
27
+ toNumber,
28
+ toStringValue,
29
+ } from '@pie-qti/qti-processing';
30
+ import type { ElementNameMapper } from '@pie-qti/qti-common';
31
+ import { Qti2xElementNameMapper } from '@pie-qti/qti-common';
32
+ import { parse } from 'node-html-parser';
33
+ import type { ExtractionRegistry } from '../extraction/ExtractionRegistry.js';
34
+ import { createExtractionRegistry } from '../extraction/ExtractionRegistry.js';
35
+ import { ALL_STANDARD_EXTRACTORS, createExtractionContext } from '../extraction/index.js';
36
+ import type { VariableDeclaration as ExtractionVariableDeclaration } from '../extraction/types.js';
37
+ import type {
38
+ AdaptiveAttemptResult,
39
+ CompletionStatus,
40
+ HtmlContent,
41
+ ModalFeedback,
42
+ PlayerConfig,
43
+ PlayerSecurityConfig,
44
+ QTIRole,
45
+ RubricBlock,
46
+ ScoringResult,
47
+ SessionState,
48
+ } from '../types/index.js';
49
+ import type { InteractionData, QTIElement } from '../types/interactions.js';
50
+ import type { ResponseValidationResult } from '../types/responseValidation.js';
51
+ import type { ComponentRegistry } from './ComponentRegistry.js';
52
+ import { createComponentRegistry } from './ComponentRegistry.js';
53
+ import { enforceItemXmlLimits } from './parsingLimits.js';
54
+ import { createSeededRng } from './random.js';
55
+ import { sanitizeHtml } from './sanitizer.js';
56
+ import { toTrustedHtml } from './trustedTypes.js';
57
+ import { sanitizeResourceUrl } from './urlPolicy.js';
58
+
59
+ type DeclKind = 'response' | 'outcome' | 'template';
60
+
61
+ export class Player {
62
+ private role: QTIRole;
63
+ private config: PlayerConfig;
64
+ private itemXml: string;
65
+ private doc: Document;
66
+ private assessmentItem: Element;
67
+ private decls: DeclarationMap;
68
+ private ctx: DeclarationContext;
69
+ private rng: () => number;
70
+ private ops: OperatorRegistry;
71
+ private extractionRegistry: ExtractionRegistry;
72
+ private componentRegistry: ComponentRegistry;
73
+ private i18nProvider: any; // I18nProvider from @pie-qti/i18n
74
+ private mapper: ElementNameMapper;
75
+
76
+ private responseProcessingProgram: ProcessingProgram | null = null;
77
+ private templateProcessingProgram: ProcessingProgram | null = null;
78
+ private outcomeProcessingProgram: ProcessingProgram | null = null;
79
+
80
+ constructor(config: PlayerConfig) {
81
+ this.config = config;
82
+ this.itemXml = config.itemXml ?? '';
83
+ this.role = config.role ?? 'candidate';
84
+ this.rng = config.rng ?? (typeof config.seed === 'number' ? createSeededRng(config.seed) : Math.random);
85
+ this.mapper = (config.elementNameMapper as ElementNameMapper | undefined) ?? new Qti2xElementNameMapper();
86
+
87
+ // Optional DoS guardrails for untrusted content (compat-by-default; disabled unless enabled).
88
+ enforceItemXmlLimits(this.itemXml, this.config.security);
89
+
90
+ this.doc = parseXml(this.itemXml);
91
+ this.assessmentItem = findAssessmentItem(this.doc);
92
+
93
+ this.decls = this.buildDeclarations(this.assessmentItem);
94
+ this.ensureBuiltinDeclarations(this.decls);
95
+ this.ctx = new DeclarationContext(this.decls);
96
+ this.ops = new OperatorRegistry();
97
+
98
+ // Restore session state (outcomes + responses) before running templateProcessing.
99
+ if (config.sessionState) {
100
+ this.applySessionState(config.sessionState);
101
+ }
102
+
103
+ // Extraction + rendering registries (for interaction rendering)
104
+ this.extractionRegistry = (config.extractionRegistry as ExtractionRegistry | undefined) ?? createExtractionRegistry();
105
+ this.componentRegistry = (config.componentRegistry as ComponentRegistry | undefined) ?? createComponentRegistry();
106
+
107
+ // I18n provider (defaults to a simple fallback if not provided)
108
+ this.i18nProvider = config.i18nProvider ?? this.createDefaultI18nProvider();
109
+
110
+ // Register standard extractors (idempotent per-registry instance)
111
+ for (const ex of ALL_STANDARD_EXTRACTORS) {
112
+ try {
113
+ this.extractionRegistry.register(ex as any);
114
+ } catch {
115
+ // ignore duplicates if a caller pre-registered
116
+ }
117
+ }
118
+
119
+ // Plugins can further extend registries
120
+ for (const p of (config.plugins ?? []) as any[]) {
121
+ try {
122
+ p?.registerExtractors?.(this.extractionRegistry);
123
+ p?.registerComponents?.(this.componentRegistry);
124
+ } catch {
125
+ // plugin errors shouldn't prevent core parsing
126
+ }
127
+ }
128
+
129
+ // Build ASTs once.
130
+ const templateProcessing = findFirstDescendant(this.assessmentItem, this.mapper.toNative('templateprocessing'));
131
+ if (templateProcessing) {
132
+ this.templateProcessingProgram = buildTemplateProcessingAst(templateProcessing, {
133
+ elementNameMapper: this.mapper,
134
+ });
135
+ this.execTemplateProcessing();
136
+ }
137
+
138
+ const responseProcessing = findFirstDescendant(this.assessmentItem, this.mapper.toNative('responseprocessing'));
139
+ if (responseProcessing) {
140
+ this.responseProcessingProgram = buildResponseProcessingAst(responseProcessing, {
141
+ elementNameMapper: this.mapper,
142
+ });
143
+ }
144
+
145
+ const outcomeProcessing = findFirstDescendant(this.assessmentItem, this.mapper.toNative('outcomeprocessing'));
146
+ if (outcomeProcessing) {
147
+ this.outcomeProcessingProgram = buildOutcomeProcessingAst(outcomeProcessing, {
148
+ elementNameMapper: this.mapper,
149
+ });
150
+ }
151
+
152
+ // Apply initial responses after templateProcessing (so template vars are ready).
153
+ if (config.responses) {
154
+ this.setResponses(config.responses as Record<string, unknown>);
155
+ }
156
+
157
+ // Detect and log QTI version for compatibility awareness
158
+ const detectedVersion = this.detectQTIVersion();
159
+ if (detectedVersion === 'unknown') {
160
+ console.warn('[QTI Player] Could not detect QTI version. Assuming QTI 2.2 compatibility.');
161
+ } else if (detectedVersion === '2.0') {
162
+ console.warn(
163
+ '[QTI Player] QTI 2.0 detected. Some features may not be fully supported. QTI 2.2 is recommended.'
164
+ );
165
+ } else if (detectedVersion === '2.1') {
166
+ console.info(
167
+ '[QTI Player] QTI 2.1 detected. Using QTI 2.2 compatibility mode with CC2 template support.'
168
+ );
169
+ }
170
+
171
+ // Check strict compliance if enabled
172
+ if (this.config.strictQtiCompliance?.enabled) {
173
+ this.validateStrictCompliance();
174
+ }
175
+ }
176
+
177
+ /** Breaking-change API: returns the typed declaration map */
178
+ public getDeclarations(): DeclarationMap {
179
+ return this.decls;
180
+ }
181
+
182
+ public setResponses(responses: Record<string, unknown>): void {
183
+ for (const [id, raw] of Object.entries(responses)) {
184
+ const d = this.decls[id];
185
+ if (!d) continue;
186
+ d.value = this.coerceToDeclarationValue(d.baseType, d.cardinality, raw);
187
+ }
188
+ }
189
+
190
+ public processResponses(): ScoringResult {
191
+ // Spec-aligned behavior: each processing run starts from outcome defaults.
192
+ // This prevents stale outcomes when response/outcome processing doesn't set every variable.
193
+ this.resetOutcomesToDefault();
194
+
195
+ // Execute response processing if present
196
+ const rpEl = findFirstDescendant(this.assessmentItem, this.mapper.toNative('responseprocessing'));
197
+ if (rpEl) {
198
+ // If responseProcessing has explicit statements, run the compiled program.
199
+ // Otherwise, fall back to template-based processing (responseProcessing@template).
200
+ const hasStatements = childElements(rpEl).length > 0;
201
+ if (hasStatements) {
202
+ this.execResponseProcessingProgram();
203
+ } else {
204
+ const templateUrl = getAttr(rpEl, 'template');
205
+ if (templateUrl) this.execResponseProcessingTemplate(templateUrl);
206
+ }
207
+ }
208
+
209
+ // Execute outcome processing if present (runs after responseProcessing)
210
+ this.execOutcomeProcessingProgram();
211
+
212
+ const outcomes = this.collectOutcomes();
213
+ const score = Number(outcomes.SCORE ?? 0);
214
+ const maxScore = Number(outcomes.MAXSCORE ?? 1);
215
+ const completionStatus = (outcomes.completionStatus as CompletionStatus | undefined) ?? 'not_attempted';
216
+ const completed = completionStatus === 'completed' || !this.isAdaptive();
217
+
218
+ return {
219
+ score,
220
+ maxScore,
221
+ completed,
222
+ outcomeValues: outcomes,
223
+ modalFeedback: this.getModalFeedback(outcomes),
224
+ };
225
+ }
226
+
227
+ public getSecurityConfig(): PlayerSecurityConfig | undefined {
228
+ return this.config.security;
229
+ }
230
+
231
+ public getTrustedTypesPolicyName(): string | undefined {
232
+ return this.config.security?.trustedTypesPolicyName;
233
+ }
234
+
235
+ /**
236
+ * Get the i18n provider instance
237
+ * @returns I18nProvider instance
238
+ */
239
+ public getI18nProvider(): any {
240
+ return this.i18nProvider;
241
+ }
242
+
243
+ /**
244
+ * Create a simple fallback i18n provider when none is provided
245
+ * This avoids a hard dependency on @pie-qti/i18n
246
+ */
247
+ private createDefaultI18nProvider(): any {
248
+ return {
249
+ getLocale: () => 'en-US',
250
+ setLocale: () => {},
251
+ t: (key: string) => key, // Fallback to key
252
+ plural: (key: string) => key,
253
+ formatNumber: (value: number) => value.toString(),
254
+ formatDate: (date: Date) => date.toISOString(),
255
+ };
256
+ }
257
+
258
+ /**
259
+ * Detects the QTI version from the assessmentItem element.
260
+ * Checks both namespace URI and version attribute.
261
+ *
262
+ * @returns QTI version string ('2.0', '2.1', '2.2') or 'unknown'
263
+ */
264
+ private detectQTIVersion(): string {
265
+ const ns = (this.assessmentItem as any).namespaceURI;
266
+ if (ns?.includes('v2p2') || ns?.includes('imsqti_v2p2')) return '2.2';
267
+ if (ns?.includes('v2p1') || ns?.includes('imsqti_v2p1')) return '2.1';
268
+ if (ns?.includes('v2p0') || ns?.includes('imsqti_v2p0')) return '2.0';
269
+
270
+ const versionAttr = getAttr(this.assessmentItem, 'version');
271
+ if (versionAttr === '2.0') return '2.0';
272
+ if (versionAttr === '2.1') return '2.1';
273
+ if (versionAttr === '2.2') return '2.2';
274
+
275
+ return 'unknown';
276
+ }
277
+
278
+ /**
279
+ * Validates strict QTI 2.2 compliance if enabled in configuration.
280
+ * Logs warnings or throws errors based on config settings.
281
+ */
282
+ private validateStrictCompliance(): void {
283
+ const config = this.config.strictQtiCompliance;
284
+ if (!config?.enabled) return;
285
+
286
+ const version = this.detectQTIVersion();
287
+ if (version !== '2.2') {
288
+ const message = `[QTI Player] Strict compliance enabled but item version is ${version}, not 2.2`;
289
+ if (config.rejectUnknownExtensions) {
290
+ throw new Error(message);
291
+ } else if (config.logDeviations !== false) {
292
+ console.warn(message);
293
+ }
294
+ }
295
+
296
+ // Future: Add validation for non-standard elements/attributes
297
+ }
298
+
299
+ private resetOutcomesToDefault(): void {
300
+ for (const d of Object.values(this.decls)) {
301
+ if ((d as any).__kind !== 'outcome') continue;
302
+ // Built-in stateful variables must survive across processing runs.
303
+ // They are updated by the runtime (adaptive attempt tracking), not by outcome defaults.
304
+ if (d.identifier === 'numAttempts' || d.identifier === 'completionStatus') continue;
305
+ this.ctx.resetToDefault(d.identifier);
306
+ }
307
+ }
308
+
309
+ public getItemBodyHtml(): HtmlContent {
310
+ const itemBody = findFirstDescendant(this.assessmentItem, this.mapper.toNative('itembody'));
311
+ if (!itemBody) return '';
312
+
313
+ // Serialize children rather than the container tag itself.
314
+ const inner = childElements(itemBody).map((c) => serializeXml(c)).join('');
315
+ const printed = this.renderPrintedVariables(inner);
316
+ const sanitized = sanitizeHtml(printed, { security: this.config.security });
317
+ return toTrustedHtml(sanitized, this.config.security?.trustedTypesPolicyName);
318
+ }
319
+
320
+ /**
321
+ * Extract rubric blocks for the current role.
322
+ *
323
+ * QTI uses `<rubricBlock view="...">` to provide role-specific guidance.
324
+ * We return sanitized HTML for direct rendering.
325
+ */
326
+ public getRubrics(): RubricBlock[] {
327
+ const role = this.role;
328
+ const rubricEls = findDescendants(this.assessmentItem, this.mapper.toNative('rubricblock'));
329
+ if (rubricEls.length === 0) return [];
330
+
331
+ const blocks: RubricBlock[] = [];
332
+ for (const el of rubricEls) {
333
+ const viewRaw = (getAttr(el, 'view') || '').trim();
334
+ const view = viewRaw ? viewRaw.split(/\s+/).filter(Boolean) : [];
335
+
336
+ // If view is specified, show only when it includes the current role.
337
+ if (view.length > 0 && role && !view.includes(role)) continue;
338
+
339
+ // Serialize children rather than the container tag itself.
340
+ const contentRaw = childElements(el).map((c) => serializeXml(c)).join('') || (el.textContent || '');
341
+ const printed = this.renderPrintedVariables(contentRaw);
342
+ const sanitized = sanitizeHtml(printed, { security: this.config.security });
343
+ const html = toTrustedHtml(sanitized, this.config.security?.trustedTypesPolicyName);
344
+
345
+ blocks.push({ view, html });
346
+ }
347
+
348
+ return blocks;
349
+ }
350
+
351
+ public getComponentRegistry(): ComponentRegistry {
352
+ return this.componentRegistry;
353
+ }
354
+
355
+ public getExtractionRegistry(): ExtractionRegistry {
356
+ return this.extractionRegistry;
357
+ }
358
+
359
+ /**
360
+ * Canonical interaction API (new): extracted, typed interaction data.
361
+ */
362
+ public getInteractionData(): InteractionData[] {
363
+ const itemBody = findFirstDescendant(this.assessmentItem, this.mapper.toNative('itembody'));
364
+ if (!itemBody) return [];
365
+
366
+ // Parse the original item XML with node-html-parser (extractors depend on its HTMLElement API).
367
+ // Important: using the original XML avoids namespace/serialization artifacts from XMLSerializer.
368
+ enforceItemXmlLimits(this.itemXml, this.config.security);
369
+ const docRoot = parse(this.itemXml, { lowerCaseTagName: false, comment: false }) as any as QTIElement;
370
+ // node-html-parser's CSS selectors match lowercase tag names.
371
+ const parsedItemBody = (docRoot.querySelector?.('itembody') as any as QTIElement | null) ?? null;
372
+ const root = parsedItemBody ?? docRoot;
373
+
374
+ const declMap = new Map<string, ExtractionVariableDeclaration>();
375
+ for (const d of Object.values(this.decls)) {
376
+ declMap.set(d.identifier, {
377
+ identifier: d.identifier,
378
+ cardinality: d.cardinality as any,
379
+ baseType: d.baseType,
380
+ });
381
+ }
382
+
383
+ // Discover all elements that match any standard extractor elementType
384
+ const tagSet = new Set<string>();
385
+ for (const ex of ALL_STANDARD_EXTRACTORS) {
386
+ for (const t of ex.elementTypes ?? []) tagSet.add(t.toLowerCase());
387
+ }
388
+
389
+ const elements: QTIElement[] = [];
390
+ for (const tag of tagSet) {
391
+ try {
392
+ elements.push(...(root.querySelectorAll(tag) as any));
393
+ } catch {
394
+ // ignore selector errors
395
+ }
396
+ }
397
+
398
+ const interactions: InteractionData[] = [];
399
+ for (const el of elements) {
400
+ const responseId = el.getAttribute?.('responseIdentifier') || el.getAttribute?.('responseidentifier') || '';
401
+ if (!responseId) continue;
402
+
403
+ const ctx = createExtractionContext(el, responseId, root, declMap, this.config);
404
+ const res = this.extractionRegistry.extract<any>(el, ctx);
405
+ if (!res.success) continue;
406
+
407
+ interactions.push({
408
+ type: el.rawTagName as any,
409
+ responseId,
410
+ ...res.data,
411
+ });
412
+ }
413
+
414
+ // Apply URL policy + embed allowances to standard extracted URL fields.
415
+ const policy = this.config.security?.urlPolicy;
416
+ const allowObjectEmbeds = this.config.security?.allowObjectEmbeds === true;
417
+ const ttPolicyName = this.config.security?.trustedTypesPolicyName;
418
+
419
+ for (const i of interactions as any[]) {
420
+ // Wrap known HTML injection fields in TrustedHTML (when enabled).
421
+ // Important: do NOT wrap fields that are rendered as plain text in our Svelte components
422
+ // (e.g. prompt) to avoid "[object Object]" rendering.
423
+ if (i.type === 'choiceInteraction' && Array.isArray(i.choices)) {
424
+ for (const c of i.choices) {
425
+ if (typeof c?.text === 'string') c.text = toTrustedHtml(c.text, ttPolicyName);
426
+ }
427
+ }
428
+
429
+ // Shared ImageData shape
430
+ if (i.imageData?.src) {
431
+ i.imageData.src = sanitizeResourceUrl(i.imageData.src, policy, 'img') ?? '';
432
+ }
433
+ if (i.imageData?.content && typeof i.imageData.content === 'string') {
434
+ i.imageData.content = toTrustedHtml(i.imageData.content, ttPolicyName);
435
+ }
436
+
437
+ // positionObject stages
438
+ if (Array.isArray(i.positionObjectStages)) {
439
+ for (const st of i.positionObjectStages) {
440
+ if (st?.objectData?.src) {
441
+ st.objectData.src = sanitizeResourceUrl(st.objectData.src, policy, 'img') ?? '';
442
+ }
443
+ if (st?.objectData?.content && typeof st.objectData.content === 'string') {
444
+ st.objectData.content = toTrustedHtml(st.objectData.content, ttPolicyName);
445
+ }
446
+ }
447
+ }
448
+
449
+ // mediaInteraction
450
+ if (i.type === 'mediaInteraction' && i.mediaElement?.src) {
451
+ const kind = i.mediaElement.type === 'object' ? 'object' : 'media';
452
+ i.mediaElement.src = sanitizeResourceUrl(i.mediaElement.src, policy, kind) ?? '';
453
+ i.allowObjectEmbeds = allowObjectEmbeds;
454
+ }
455
+
456
+ // hottextInteraction content is injected via {@html}
457
+ if (i.type === 'hottextInteraction' && typeof i.contentHtml === 'string') {
458
+ i.contentHtml = toTrustedHtml(i.contentHtml, ttPolicyName);
459
+ }
460
+ }
461
+
462
+ return interactions;
463
+ }
464
+
465
+ /**
466
+ * Convenience API (used by tests/bench): returns a minimal interaction list with QTI-ish field names.
467
+ */
468
+ public getInteractions(): Array<{ type: string; responseIdentifier: string } & Record<string, any>> {
469
+ return this.getInteractionData().map((i: any) => ({
470
+ ...i,
471
+ responseIdentifier: i.responseId,
472
+ }));
473
+ }
474
+
475
+ public getResponseInteractions(): Array<{ type: string; responseIdentifier: string } & Record<string, any>> {
476
+ return this.getInteractions().filter((i) => i.type !== 'endAttemptInteraction');
477
+ }
478
+
479
+ public getResponseIdentifiers(): string[] {
480
+ return this.getResponseInteractions().map((i) => i.responseIdentifier);
481
+ }
482
+
483
+ public isAdaptive(): boolean {
484
+ return (getAttr(this.assessmentItem, 'adaptive') || '').toLowerCase() === 'true';
485
+ }
486
+
487
+ public getNumAttempts(): number {
488
+ return Math.max(0, Math.floor(toNumber(this.ctx.getValue('numAttempts')) || 0));
489
+ }
490
+
491
+ public getCompletionStatus(): CompletionStatus {
492
+ const s = (toStringValue(this.ctx.getValue('completionStatus')) || '').trim() as CompletionStatus;
493
+ return (s || 'not_attempted') as CompletionStatus;
494
+ }
495
+
496
+ public isCompleted(): boolean {
497
+ return this.getCompletionStatus() === 'completed';
498
+ }
499
+
500
+ public submitAttempt(countAttempt: boolean = true): AdaptiveAttemptResult {
501
+ if (this.isCompleted()) {
502
+ throw new Error('Cannot submit: item is already completed');
503
+ }
504
+
505
+ // QTI adaptive semantics: numAttempts should reflect the attempt being processed.
506
+ if (this.isAdaptive() && countAttempt) {
507
+ const next = this.getNumAttempts() + 1;
508
+ this.ctx.setValue('numAttempts', qtiValue('integer', 'single', next));
509
+ // Promote completionStatus from not_attempted -> unknown on first submission unless RP sets it.
510
+ if (this.getCompletionStatus() === 'not_attempted') {
511
+ this.ctx.setValue('completionStatus', qtiValue('identifier', 'single', 'unknown'));
512
+ }
513
+ }
514
+
515
+ const base = this.processResponses();
516
+ const completionStatus = this.getCompletionStatus();
517
+ const completed = completionStatus === 'completed';
518
+ const canContinue = this.isAdaptive() ? !completed : false;
519
+
520
+ return {
521
+ ...base,
522
+ completed,
523
+ numAttempts: this.getNumAttempts(),
524
+ completionStatus,
525
+ canContinue,
526
+ };
527
+ }
528
+
529
+ public getResponses(): Record<string, any> {
530
+ const out: Record<string, any> = {};
531
+ for (const d of Object.values(this.decls)) {
532
+ if ((d as any).__kind !== 'response') continue;
533
+ out[d.identifier] = d.value.kind === 'value' ? d.value.value : null;
534
+ }
535
+ return out;
536
+ }
537
+
538
+ /**
539
+ * Get correct response for a specific response identifier
540
+ * @param responseId - The response identifier
541
+ * @returns The correct response value, or undefined if not available
542
+ */
543
+ public getCorrectResponse(responseId: string): any | undefined {
544
+ const decl = this.decls[responseId];
545
+ if (!decl || (decl as any).__kind !== 'response') return undefined;
546
+ const respDecl = decl as any; // ResponseDeclaration from qti-processing
547
+ if (!respDecl.correctResponse) return undefined;
548
+ if (respDecl.correctResponse.kind !== 'value') return undefined;
549
+ return respDecl.correctResponse.value;
550
+ }
551
+
552
+ /**
553
+ * Get all correct responses as a map
554
+ * @returns Map of responseId to correct response value
555
+ */
556
+ public getCorrectResponses(): Record<string, any> {
557
+ const out: Record<string, any> = {};
558
+ for (const d of Object.values(this.decls)) {
559
+ if ((d as any).__kind !== 'response') continue;
560
+ const respDecl = d as any;
561
+ if (!respDecl.correctResponse || respDecl.correctResponse.kind !== 'value') continue;
562
+ out[d.identifier] = respDecl.correctResponse.value;
563
+ }
564
+ return out;
565
+ }
566
+
567
+ public getTemplateVariables(): Record<string, any> {
568
+ const out: Record<string, any> = {};
569
+ for (const d of Object.values(this.decls)) {
570
+ if (!d.isTemplate) continue;
571
+ out[d.identifier] = d.value.kind === 'value' ? d.value.value : null;
572
+ }
573
+ return out;
574
+ }
575
+
576
+ public setTemplateVariables(vars: Record<string, any>): void {
577
+ for (const [id, raw] of Object.entries(vars)) {
578
+ const d = this.decls[id];
579
+ if (!d?.isTemplate) continue;
580
+ d.value = this.coerceToDeclarationValue(d.baseType, d.cardinality, raw);
581
+ }
582
+ }
583
+
584
+ public getSessionState(): SessionState {
585
+ const out: SessionState = {};
586
+ for (const d of Object.values(this.decls)) {
587
+ out[d.identifier] = d.value.kind === 'value' ? d.value.value : null;
588
+ }
589
+ return out;
590
+ }
591
+
592
+ public validateResponses(responses: Record<string, any>): ResponseValidationResult {
593
+ const interactions = this.getInteractions();
594
+ const entries: ResponseValidationResult['entries'] = {};
595
+ const issues: ResponseValidationResult['issues'] = [];
596
+
597
+ for (const i of interactions) {
598
+ const responseId = i.responseIdentifier;
599
+ const decl = this.decls[responseId];
600
+ const value = responses[responseId];
601
+
602
+ const required =
603
+ i.type !== 'endAttemptInteraction' &&
604
+ (i.type !== 'mediaInteraction' || (typeof i.minPlays === 'number' && i.minPlays > 0));
605
+
606
+ let complete = !required;
607
+ if (i.type === 'mediaInteraction' && required) {
608
+ const minPlays = Number(i.minPlays || 0);
609
+ complete = Number(value || 0) >= minPlays;
610
+ } else if (required) {
611
+ if (Array.isArray(value)) complete = value.length > 0;
612
+ else complete = value !== null && value !== undefined && value !== '';
613
+ }
614
+
615
+ const errors: string[] = [];
616
+ const warnings: string[] = [];
617
+
618
+ if (decl) {
619
+ if (decl.cardinality === 'multiple' || decl.cardinality === 'ordered') {
620
+ if (!(value === null || value === undefined || Array.isArray(value))) {
621
+ errors.push(`Expected an array for ${decl.cardinality} response '${responseId}'`);
622
+ }
623
+ } else {
624
+ if (Array.isArray(value)) {
625
+ errors.push(`Expected a single value for response '${responseId}'`);
626
+ }
627
+ }
628
+ }
629
+
630
+ const valid = errors.length === 0;
631
+ entries[responseId] = {
632
+ responseId,
633
+ interactionType: i.type,
634
+ required,
635
+ complete,
636
+ valid,
637
+ errors,
638
+ warnings,
639
+ };
640
+
641
+ for (const e of errors) {
642
+ issues.push({
643
+ responseId,
644
+ code: 'invalid_shape',
645
+ message: e,
646
+ severity: 'error',
647
+ });
648
+ }
649
+ }
650
+
651
+ const allValid = Object.values(entries).every((e) => e.valid);
652
+ return { valid: allValid, entries, issues };
653
+ }
654
+
655
+ public getProgress(responses: Record<string, any>): { total: number; answered: number; unanswered: number } {
656
+ const v = this.validateResponses(responses);
657
+ const required = Object.values(v.entries).filter((e) => e.required);
658
+ const answered = required.filter((e) => e.complete).length;
659
+ const total = required.length;
660
+ return { total, answered, unanswered: Math.max(0, total - answered) };
661
+ }
662
+
663
+ public canSubmitResponses(responses: Record<string, any>): boolean {
664
+ const v = this.validateResponses(responses);
665
+ const required = Object.values(v.entries).filter((e) => e.required);
666
+ return v.valid && required.every((e) => e.complete);
667
+ }
668
+
669
+ /**
670
+ * True if the learner has made any meaningful interaction, even if submission is not yet allowed.
671
+ * Used by assessment/session controllers to track "answered" state.
672
+ */
673
+ public isAttempted(responses: Record<string, any>): boolean {
674
+ for (const i of this.getResponseInteractions()) {
675
+ const id = i.responseIdentifier;
676
+ const v = responses[id];
677
+ if (i.type === 'mediaInteraction') {
678
+ if (Number(v || 0) > 0) return true;
679
+ continue;
680
+ }
681
+ if (Array.isArray(v)) {
682
+ if (v.length > 0) return true;
683
+ continue;
684
+ }
685
+ if (v !== null && v !== undefined && v !== '') return true;
686
+ }
687
+ return false;
688
+ }
689
+
690
+ // ----------------------------------------------------------------------------
691
+ // Execution
692
+ // ----------------------------------------------------------------------------
693
+
694
+ private execTemplateProcessing(): void {
695
+ if (!this.templateProcessingProgram) return;
696
+ execProgram(
697
+ {
698
+ ctx: this.ctx,
699
+ ops: this.ops,
700
+ rng: this.rng,
701
+ customOperators: this.config.customOperators,
702
+ },
703
+ this.templateProcessingProgram
704
+ );
705
+ }
706
+
707
+ private execResponseProcessingProgram(): void {
708
+ if (!this.responseProcessingProgram) return;
709
+ execProgram(
710
+ {
711
+ ctx: this.ctx,
712
+ ops: this.ops,
713
+ rng: this.rng,
714
+ customOperators: this.config.customOperators,
715
+ },
716
+ this.responseProcessingProgram
717
+ );
718
+ }
719
+
720
+ private execOutcomeProcessingProgram(): void {
721
+ if (!this.outcomeProcessingProgram) return;
722
+ execProgram(
723
+ {
724
+ ctx: this.ctx,
725
+ ops: this.ops,
726
+ rng: this.rng,
727
+ customOperators: this.config.customOperators,
728
+ },
729
+ this.outcomeProcessingProgram
730
+ );
731
+ }
732
+
733
+ private execResponseProcessingTemplate(templateUrl: string): void {
734
+ const name = templateUrl.split('/').pop()?.toLowerCase();
735
+ if (!name) {
736
+ console.warn(`[QTI Player] Could not extract template name from URL: ${templateUrl}`);
737
+ return;
738
+ }
739
+
740
+ const responseDeclIds = Object.values(this.decls)
741
+ .filter((d) => (d as any).__kind === 'response')
742
+ .map((d) => d.identifier);
743
+
744
+ switch (name) {
745
+ case 'match_correct':
746
+ case 'cc2_match': { // CC2_match is an alias for match_correct (QTI 2.1 compatibility)
747
+ const allCorrect = responseDeclIds.every((id) => {
748
+ const expr = { kind: 'expr.match', id: 'tmp', a: { kind: 'expr.variable', id: 'tmp', identifier: id }, b: { kind: 'expr.correct', id: 'tmp', identifier: id } } as any;
749
+ // Use evaluator match semantics by evaluating a constructed MatchExpr
750
+ return toBoolean(
751
+ evalExpr(
752
+ { ctx: this.ctx, ops: this.ops, rng: this.rng, customOperators: this.config.customOperators },
753
+ expr
754
+ )
755
+ );
756
+ });
757
+
758
+ const max = toNumber(this.ctx.getValue('MAXSCORE'));
759
+ this.ctx.setValue('SCORE', qtiValue('float', 'single', allCorrect ? (Number.isFinite(max) ? max : 1) : 0));
760
+ return;
761
+ }
762
+ case 'match_nothing':
763
+ case 'cc2_match_nothing': { // QTI 2.1 compatibility
764
+ const isEmptyResponse = (v: QtiValue | undefined): boolean => {
765
+ if (!v) return true;
766
+ if (v.kind === 'null') return true;
767
+ if (v.kind === 'invalid') return false;
768
+ if (v.value === null || v.value === undefined) return true;
769
+ if (Array.isArray(v.value)) return v.value.length === 0;
770
+ if (typeof v.value === 'string') return v.value.trim().length === 0;
771
+ return false;
772
+ };
773
+
774
+ const allEmpty = responseDeclIds.every((id) => isEmptyResponse(this.ctx.getValue(id)));
775
+ const max = toNumber(this.ctx.getValue('MAXSCORE'));
776
+ this.ctx.setValue('SCORE', qtiValue('float', 'single', allEmpty ? (Number.isFinite(max) ? max : 1) : 0));
777
+ return;
778
+ }
779
+ case 'map_response':
780
+ case 'cc2_map_response': { // QTI 2.1 compatibility
781
+ let total = 0;
782
+ for (const id of responseDeclIds) {
783
+ const d = this.decls[id];
784
+ if (!d.mapping) continue;
785
+ const v = evalExpr(
786
+ { ctx: this.ctx, ops: this.ops, rng: this.rng },
787
+ { kind: 'expr.mapResponse', id: 'tmp', identifier: id } as any
788
+ );
789
+ total += toNumber(v) || 0;
790
+ }
791
+ this.ctx.setValue('SCORE', qtiValue('float', 'single', total));
792
+ return;
793
+ }
794
+ case 'map_response_point':
795
+ case 'cc2_map_response_point': { // QTI 2.1 compatibility
796
+ let total = 0;
797
+ for (const id of responseDeclIds) {
798
+ const d = this.decls[id];
799
+ if (!d.areaMapping) continue;
800
+ const v = evalExpr(
801
+ { ctx: this.ctx, ops: this.ops, rng: this.rng },
802
+ { kind: 'expr.mapResponsePoint', id: 'tmp', identifier: id } as any
803
+ );
804
+ total += toNumber(v) || 0;
805
+ }
806
+ this.ctx.setValue('SCORE', qtiValue('float', 'single', total));
807
+ return;
808
+ }
809
+ default:
810
+ console.warn(`[QTI Player] Unsupported response processing template: ${name}`);
811
+ return;
812
+ }
813
+ }
814
+
815
+ // ----------------------------------------------------------------------------
816
+ // Declarations
817
+ // ----------------------------------------------------------------------------
818
+
819
+ private buildDeclarations(root: Element): DeclarationMap {
820
+ const decls: DeclarationMap = {};
821
+
822
+ const addDecl = (kind: DeclKind, el: Element) => {
823
+ const identifier = getAttr(el, 'identifier');
824
+ const cardinality = (getAttr(el, 'cardinality') || 'single') as Cardinality;
825
+ const baseType = (getAttr(el, 'baseType') || 'string') as BaseType;
826
+ if (!identifier) return;
827
+
828
+ const defaultValue = this.parseDefaultValue(el, baseType, cardinality);
829
+ decls[identifier] = {
830
+ identifier,
831
+ baseType,
832
+ cardinality,
833
+ defaultValue,
834
+ value: defaultValue,
835
+ isTemplate: kind === 'template',
836
+ // @ts-expect-error internal marker for templates
837
+ __kind: kind,
838
+ };
839
+
840
+ // Response + outcome declarations may define mappings used by mapResponse/mapOutcome.
841
+ // (Templates do not participate in mapping.)
842
+ if (kind === 'response' || kind === 'outcome') {
843
+ const mappingEl = findFirstDescendant(el, 'mapping');
844
+ if (mappingEl) {
845
+ decls[identifier].mapping = this.parseMapping(mappingEl, baseType);
846
+ }
847
+ }
848
+
849
+ // Outcome declarations may define a lookup table (matchTable or interpolationTable)
850
+ // used by the lookupOutcomeValue rule.
851
+ if (kind === 'outcome') {
852
+ const matchTableEl = findFirstDescendant(el, 'matchTable');
853
+ const interpolationTableEl = findFirstDescendant(el, 'interpolationTable');
854
+ if (matchTableEl) {
855
+ decls[identifier].lookupTable = this.parseMatchTable(matchTableEl);
856
+ } else if (interpolationTableEl) {
857
+ decls[identifier].lookupTable = this.parseInterpolationTable(interpolationTableEl);
858
+ }
859
+ }
860
+
861
+ if (kind === 'response') {
862
+ const correctEl = findFirstDescendant(el, 'correctResponse');
863
+ if (correctEl) {
864
+ decls[identifier].correctResponse = this.parseCorrectResponse(correctEl, baseType, cardinality);
865
+ }
866
+ const areaMappingEl = findFirstDescendant(el, 'areaMapping');
867
+ if (areaMappingEl) {
868
+ decls[identifier].areaMapping = this.parseAreaMapping(areaMappingEl);
869
+ }
870
+ }
871
+ };
872
+
873
+ for (const el of findDescendants(root, this.mapper.toNative('responsedeclaration'))) addDecl('response', el);
874
+ for (const el of findDescendants(root, this.mapper.toNative('outcomedeclaration'))) addDecl('outcome', el);
875
+ for (const el of findDescendants(root, this.mapper.toNative('templatedeclaration'))) addDecl('template', el);
876
+
877
+ return decls;
878
+ }
879
+
880
+ private parseMatchTable(el: Element) {
881
+ const defaultValueRaw = (getAttr(el, 'defaultValue') || '').trim();
882
+ const defaultValue = defaultValueRaw ? Number(defaultValueRaw) : undefined;
883
+ return {
884
+ kind: 'table.matchTable' as const,
885
+ defaultValue: Number.isFinite(defaultValue as any) ? defaultValue : undefined,
886
+ entries: findDescendants(el, 'matchTableEntry').map((e) => ({
887
+ sourceValue: (getAttr(e, 'sourceValue') || '').trim(),
888
+ targetValue: (getAttr(e, 'targetValue') || '').trim(),
889
+ })),
890
+ };
891
+ }
892
+
893
+ private parseInterpolationTable(el: Element) {
894
+ const defaultValueRaw = (getAttr(el, 'defaultValue') || '').trim();
895
+ const defaultValue = defaultValueRaw ? Number(defaultValueRaw) : undefined;
896
+ const interpolationMethod = (getAttr(el, 'interpolationMethod') || 'linear').trim();
897
+ return {
898
+ kind: 'table.interpolationTable' as const,
899
+ defaultValue: Number.isFinite(defaultValue as any) ? defaultValue : undefined,
900
+ interpolationMethod,
901
+ entries: findDescendants(el, 'interpolationTableEntry')
902
+ .map((e) => ({
903
+ sourceValue: Number((getAttr(e, 'sourceValue') || '').trim()),
904
+ targetValue: Number((getAttr(e, 'targetValue') || '').trim()),
905
+ }))
906
+ .filter((e) => Number.isFinite(e.sourceValue) && Number.isFinite(e.targetValue)),
907
+ };
908
+ }
909
+
910
+ private ensureBuiltinDeclarations(decls: DeclarationMap): void {
911
+ // completionStatus + numAttempts are defined in QTI (esp. adaptive items) and commonly used
912
+ // without explicit outcomeDeclaration in authoring content.
913
+ if (!decls.completionStatus) {
914
+ decls.completionStatus = {
915
+ identifier: 'completionStatus',
916
+ baseType: 'identifier',
917
+ cardinality: 'single',
918
+ value: qtiValue('identifier', 'single', 'not_attempted'),
919
+ isTemplate: false,
920
+ // @ts-expect-error internal marker
921
+ __kind: 'outcome',
922
+ };
923
+ }
924
+
925
+ if (!decls.numAttempts) {
926
+ decls.numAttempts = {
927
+ identifier: 'numAttempts',
928
+ baseType: 'integer',
929
+ cardinality: 'single',
930
+ value: qtiValue('integer', 'single', 0),
931
+ isTemplate: false,
932
+ // @ts-expect-error internal marker
933
+ __kind: 'outcome',
934
+ };
935
+ }
936
+
937
+ // Common scoring defaults
938
+ if (!decls.SCORE) {
939
+ decls.SCORE = {
940
+ identifier: 'SCORE',
941
+ baseType: 'float',
942
+ cardinality: 'single',
943
+ value: qtiValue('float', 'single', 0),
944
+ isTemplate: false,
945
+ // @ts-expect-error internal marker
946
+ __kind: 'outcome',
947
+ };
948
+ }
949
+ if (!decls.MAXSCORE) {
950
+ decls.MAXSCORE = {
951
+ identifier: 'MAXSCORE',
952
+ baseType: 'float',
953
+ cardinality: 'single',
954
+ value: qtiValue('float', 'single', 1),
955
+ isTemplate: false,
956
+ // @ts-expect-error internal marker
957
+ __kind: 'outcome',
958
+ };
959
+ }
960
+ }
961
+
962
+ private applySessionState(state: SessionState): void {
963
+ for (const [id, raw] of Object.entries(state)) {
964
+ const d = this.decls[id];
965
+ if (!d) continue;
966
+ d.value = this.coerceToDeclarationValue(d.baseType, d.cardinality, raw);
967
+ }
968
+ }
969
+
970
+ private parseDefaultValue(declEl: Element, baseType: BaseType, cardinality: Cardinality): QtiValue {
971
+ const defaultEl = findFirstDescendant(declEl, 'defaultValue');
972
+ if (!defaultEl) return qtiNull(baseType, cardinality);
973
+ const values = findDescendants(defaultEl, 'value').map((v) => (v.textContent || '').trim());
974
+ if (cardinality === 'multiple' || cardinality === 'ordered') {
975
+ return qtiValue(
976
+ baseType,
977
+ cardinality,
978
+ values.map((t) => {
979
+ const v = coerceBaseValue(baseType, t);
980
+ return v.kind === 'value' ? v.value : null;
981
+ })
982
+ );
983
+ }
984
+ return coerceBaseValue(baseType, values[0] ?? '');
985
+ }
986
+
987
+ private parseCorrectResponse(correctEl: Element, baseType: BaseType, cardinality: Cardinality): QtiValue {
988
+ const values = findDescendants(correctEl, 'value').map((v) => (v.textContent || '').trim());
989
+ if (cardinality === 'multiple' || cardinality === 'ordered') {
990
+ return qtiValue(
991
+ baseType,
992
+ cardinality,
993
+ values.map((t) => {
994
+ const v = coerceBaseValue(baseType, t);
995
+ return v.kind === 'value' ? v.value : null;
996
+ })
997
+ );
998
+ }
999
+ return coerceBaseValue(baseType, values[0] ?? '');
1000
+ }
1001
+
1002
+ private parseMapping(mappingEl: Element, baseType: BaseType) {
1003
+ const defaultValue = Number(getAttr(mappingEl, 'defaultValue') || 0);
1004
+ const lowerBound = getAttr(mappingEl, 'lowerBound') ? Number(getAttr(mappingEl, 'lowerBound')) : undefined;
1005
+ const upperBound = getAttr(mappingEl, 'upperBound') ? Number(getAttr(mappingEl, 'upperBound')) : undefined;
1006
+ const mappingCaseSensitive = getAttr(mappingEl, 'caseSensitive') || 'true';
1007
+ const entries: Record<string, any> = {};
1008
+
1009
+ const normalizePairKey = (k: string): string => {
1010
+ const parts = k.trim().split(/\s+/).filter(Boolean);
1011
+ if (parts.length === 2) return [...parts].sort().join(' ');
1012
+ return k.trim();
1013
+ };
1014
+
1015
+ const normalizeDirectedPairKey = (k: string): string => {
1016
+ const parts = k.trim().split(/\s+/).filter(Boolean);
1017
+ if (parts.length >= 2) return `${parts[0]} ${parts[1]}`;
1018
+ return k.trim();
1019
+ };
1020
+
1021
+ for (const e of findDescendants(mappingEl, 'mapEntry')) {
1022
+ const mapKey = getAttr(e, 'mapKey');
1023
+ const mappedValue = getAttr(e, 'mappedValue');
1024
+ if (!mapKey || mappedValue === null) continue;
1025
+ const effectiveCaseSensitive = getAttr(e, 'caseSensitive') || mappingCaseSensitive || 'true';
1026
+ const storedKey =
1027
+ baseType === 'pair'
1028
+ ? normalizePairKey(mapKey)
1029
+ : baseType === 'directedPair'
1030
+ ? normalizeDirectedPairKey(mapKey)
1031
+ : mapKey;
1032
+ entries[storedKey] = { mapKey: storedKey, mappedValue: Number(mappedValue), caseSensitive: effectiveCaseSensitive };
1033
+ if (effectiveCaseSensitive !== 'true') {
1034
+ const lowerKey = storedKey.toLowerCase();
1035
+ entries[lowerKey] = {
1036
+ mapKey: lowerKey,
1037
+ mappedValue: Number(mappedValue),
1038
+ caseSensitive: effectiveCaseSensitive,
1039
+ };
1040
+ }
1041
+ }
1042
+
1043
+ return { defaultValue, lowerBound, upperBound, caseSensitive: mappingCaseSensitive, entries };
1044
+ }
1045
+
1046
+ private parseAreaMapping(areaMappingEl: Element): AreaMapping {
1047
+ const defaultValue = Number(getAttr(areaMappingEl, 'defaultValue') || 0);
1048
+ const lowerBound = getAttr(areaMappingEl, 'lowerBound')
1049
+ ? Number(getAttr(areaMappingEl, 'lowerBound'))
1050
+ : undefined;
1051
+ const upperBound = getAttr(areaMappingEl, 'upperBound')
1052
+ ? Number(getAttr(areaMappingEl, 'upperBound'))
1053
+ : undefined;
1054
+
1055
+ const entries: AreaMapEntry[] = [];
1056
+ for (const e of findDescendants(areaMappingEl, 'areaMapEntry')) {
1057
+ const shape = (getAttr(e, 'shape') || 'default') as AreaMapEntry['shape'];
1058
+ const coords = String(getAttr(e, 'coords') || '');
1059
+ const mappedValue = Number(getAttr(e, 'mappedValue') || 0);
1060
+ entries.push({ shape, coords, mappedValue });
1061
+ }
1062
+
1063
+ return { defaultValue, lowerBound, upperBound, entries };
1064
+ }
1065
+
1066
+ private coerceToDeclarationValue(baseType: BaseType, cardinality: Cardinality, raw: unknown): QtiValue {
1067
+ if (raw === null || raw === undefined) return qtiNull(baseType, cardinality);
1068
+
1069
+ // Allow callers to pass fully-formed QtiValue (e.g. session restore).
1070
+ if (typeof raw === 'object' && raw && 'kind' in raw) {
1071
+ return raw as QtiValue;
1072
+ }
1073
+
1074
+ if (cardinality === 'multiple' || cardinality === 'ordered') {
1075
+ const arr = Array.isArray(raw) ? raw : [raw];
1076
+ const coerced = arr
1077
+ .map((v) => String(v ?? '').trim())
1078
+ .filter((s) => s.length > 0)
1079
+ .map((t) => {
1080
+ const v = coerceBaseValue(baseType, t);
1081
+ return v.kind === 'value' ? v.value : null;
1082
+ })
1083
+ .filter((v) => v !== null);
1084
+ // Multiple/ordered can legitimately be an empty container (distinct from null).
1085
+ return qtiValue(baseType, cardinality, coerced);
1086
+ }
1087
+
1088
+ const t = String(raw ?? '').trim();
1089
+ if (t.length === 0) return qtiNull(baseType, cardinality);
1090
+ return coerceBaseValue(baseType, t);
1091
+ }
1092
+
1093
+ private collectOutcomes(): Record<string, unknown> {
1094
+ const out: Record<string, unknown> = {};
1095
+ for (const d of Object.values(this.decls)) {
1096
+ if ((d as any).__kind !== 'outcome') continue;
1097
+ if (d.value.kind === 'value') out[d.identifier] = d.value.value;
1098
+ else if (d.value.kind === 'null') out[d.identifier] = null;
1099
+ }
1100
+ return out;
1101
+ }
1102
+
1103
+ // ----------------------------------------------------------------------------
1104
+ // printedVariable + feedback
1105
+ // ----------------------------------------------------------------------------
1106
+
1107
+ private renderPrintedVariables(html: string): string {
1108
+ const readIdentifier = (attrs: string): string | null => {
1109
+ const m = attrs.match(/identifier\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s>]+))/i);
1110
+ return (m?.[1] || m?.[2] || m?.[3] || '').trim() || null;
1111
+ };
1112
+
1113
+ const renderId = (id: string | null): string => {
1114
+ if (!id) return '';
1115
+ const v = this.ctx.getValue(id);
1116
+ if (v.kind !== 'value') return '';
1117
+ if (Array.isArray(v.value)) return v.value.map(String).join(', ');
1118
+ return String(v.value);
1119
+ };
1120
+
1121
+ let out = html.replace(/<printedVariable\b([^>]*)>([\s\S]*?)<\/printedVariable>/gi, (_m, attrs) =>
1122
+ renderId(readIdentifier(String(attrs)))
1123
+ );
1124
+ out = out.replace(/<printedVariable\b([^>]*)\/>/gi, (_m, attrs) => renderId(readIdentifier(String(attrs))));
1125
+ return out;
1126
+ }
1127
+
1128
+ private getModalFeedback(outcomes: Record<string, any>): ModalFeedback[] {
1129
+ const feedbackEls = findDescendants(this.assessmentItem, this.mapper.toNative('modalfeedback'));
1130
+ const active: ModalFeedback[] = [];
1131
+
1132
+ for (const el of feedbackEls) {
1133
+ const identifier = getAttr(el, 'identifier') || '';
1134
+ const outcomeIdentifier = getAttr(el, 'outcomeIdentifier') || '';
1135
+ const showHide = (getAttr(el, 'showHide') || 'show') as 'show' | 'hide';
1136
+ const title = getAttr(el, 'title') || undefined;
1137
+
1138
+ const contentRaw = childElements(el).map((c) => serializeXml(c)).join('') || (el.textContent || '');
1139
+ const sanitized = sanitizeHtml(contentRaw, { security: this.config.security });
1140
+ const content = toTrustedHtml(sanitized, this.config.security?.trustedTypesPolicyName);
1141
+
1142
+ const outcomeValue = outcomes[outcomeIdentifier];
1143
+ const shouldShow = showHide === 'show' ? outcomeValue === identifier : outcomeValue !== identifier;
1144
+ if (shouldShow && content) {
1145
+ active.push({ identifier, outcomeIdentifier, showHide, content, title });
1146
+ }
1147
+ }
1148
+ return active;
1149
+ }
1150
+ }
1151
+
1152
+