@pie-qti/item-player 0.1.1 → 0.1.4

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