@pie-qti/item-player 1.0.0-beta.3 → 1.0.0-beta.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (300) hide show
  1. package/README.md +33 -5
  2. package/dist/catalog/applyGlossaryTriggers.js +14 -2
  3. package/dist/catalog/applyGlossaryTriggers.js.map +1 -1
  4. package/dist/catalog/catalogExtractor.js +2 -4
  5. package/dist/catalog/catalogExtractor.js.map +1 -1
  6. package/dist/catalog/sessionCatalog.d.ts +46 -0
  7. package/dist/catalog/sessionCatalog.js +87 -0
  8. package/dist/catalog/sessionCatalog.js.map +1 -0
  9. package/dist/components/utils/endAttempt.d.ts +16 -0
  10. package/dist/components/utils/endAttempt.js +28 -0
  11. package/dist/components/utils/endAttempt.js.map +1 -0
  12. package/dist/components/utils/focus.d.ts +19 -0
  13. package/dist/components/utils/focus.js +67 -0
  14. package/dist/components/utils/focus.js.map +1 -0
  15. package/dist/components/utils/itemBodyRenderer.d.ts +44 -0
  16. package/dist/components/utils/itemBodyRenderer.js +177 -0
  17. package/dist/components/utils/itemBodyRenderer.js.map +1 -0
  18. package/dist/components/utils/sentenceContext.d.ts +6 -0
  19. package/dist/components/utils/sentenceContext.js +16 -0
  20. package/dist/components/utils/sentenceContext.js.map +1 -0
  21. package/dist/core/AssessmentItemDefinition.d.ts +20 -1
  22. package/dist/core/AssessmentItemDefinition.js +12 -31
  23. package/dist/core/AssessmentItemDefinition.js.map +1 -1
  24. package/dist/core/ComponentRegistry.d.ts +92 -0
  25. package/dist/core/ComponentRegistry.js +7 -1
  26. package/dist/core/ComponentRegistry.js.map +1 -1
  27. package/dist/core/ItemSession.d.ts +18 -1
  28. package/dist/core/ItemSession.js +79 -41
  29. package/dist/core/ItemSession.js.map +1 -1
  30. package/dist/core/Player.d.ts +118 -141
  31. package/dist/core/Player.js +387 -1233
  32. package/dist/core/Player.js.map +1 -1
  33. package/dist/core/compliance.d.ts +72 -0
  34. package/dist/core/compliance.js +147 -0
  35. package/dist/core/compliance.js.map +1 -0
  36. package/dist/core/declarations/declarationBuilder.d.ts +29 -0
  37. package/dist/core/declarations/declarationBuilder.js +284 -0
  38. package/dist/core/declarations/declarationBuilder.js.map +1 -0
  39. package/dist/core/declarations/declarationValues.d.ts +11 -0
  40. package/dist/core/declarations/declarationValues.js +168 -0
  41. package/dist/core/declarations/declarationValues.js.map +1 -0
  42. package/dist/core/matchGroups.d.ts +36 -0
  43. package/dist/core/matchGroups.js +100 -0
  44. package/dist/core/matchGroups.js.map +1 -0
  45. package/dist/core/nameMappers.d.ts +35 -0
  46. package/dist/core/nameMappers.js +47 -0
  47. package/dist/core/nameMappers.js.map +1 -0
  48. package/dist/core/parsingLimits.d.ts +4 -0
  49. package/dist/core/parsingLimits.js +5 -2
  50. package/dist/core/parsingLimits.js.map +1 -1
  51. package/dist/core/processing/responseProcessing.d.ts +88 -0
  52. package/dist/core/processing/responseProcessing.js +317 -0
  53. package/dist/core/processing/responseProcessing.js.map +1 -0
  54. package/dist/core/processing/responseValidation.d.ts +55 -0
  55. package/dist/core/processing/responseValidation.js +335 -0
  56. package/dist/core/processing/responseValidation.js.map +1 -0
  57. package/dist/core/rendering/contentPass.d.ts +31 -0
  58. package/dist/core/rendering/contentPass.js +152 -0
  59. package/dist/core/rendering/contentPass.js.map +1 -0
  60. package/dist/core/rendering/htmlRender.d.ts +21 -0
  61. package/dist/core/rendering/htmlRender.js +56 -0
  62. package/dist/core/rendering/htmlRender.js.map +1 -0
  63. package/dist/core/responseProcessingTemplates.d.ts +23 -0
  64. package/dist/core/responseProcessingTemplates.js +45 -0
  65. package/dist/core/responseProcessingTemplates.js.map +1 -0
  66. package/dist/core/rolePolicy.d.ts +5 -0
  67. package/dist/core/rolePolicy.js +21 -0
  68. package/dist/core/rolePolicy.js.map +1 -1
  69. package/dist/core/sanitizer.js +8 -14
  70. package/dist/core/sanitizer.js.map +1 -1
  71. package/dist/core/serialization/sessionState.d.ts +56 -0
  72. package/dist/core/serialization/sessionState.js +139 -0
  73. package/dist/core/serialization/sessionState.js.map +1 -0
  74. package/dist/core/serialization/valueForms.d.ts +32 -0
  75. package/dist/core/serialization/valueForms.js +112 -0
  76. package/dist/core/serialization/valueForms.js.map +1 -0
  77. package/dist/document/AssessmentItemDocument.d.ts +27 -1
  78. package/dist/document/AssessmentItemDocument.js +67 -31
  79. package/dist/document/AssessmentItemDocument.js.map +1 -1
  80. package/dist/element-class-BbF4Dj7F.js +3773 -0
  81. package/dist/element-class-BbF4Dj7F.js.map +1 -0
  82. package/dist/element-class.d.ts +34 -1
  83. package/dist/element-class.js +1 -1
  84. package/dist/element.js +1 -1
  85. package/dist/extraction/ExtractionRegistry.js +6 -12
  86. package/dist/extraction/ExtractionRegistry.js.map +1 -1
  87. package/dist/extraction/createContext.d.ts +2 -2
  88. package/dist/extraction/createContext.js.map +1 -1
  89. package/dist/extraction/index.d.ts +2 -2
  90. package/dist/extraction/index.js +1 -1
  91. package/dist/extraction/index.js.map +1 -1
  92. package/dist/extraction/interactionCoverage.d.ts +31 -0
  93. package/dist/extraction/interactionCoverage.js +40 -0
  94. package/dist/extraction/interactionCoverage.js.map +1 -0
  95. package/dist/extraction/interactionExtractionPipeline.js +5 -10
  96. package/dist/extraction/interactionExtractionPipeline.js.map +1 -1
  97. package/dist/extraction/interactionSecurity.js +1 -28
  98. package/dist/extraction/interactionSecurity.js.map +1 -1
  99. package/dist/extraction/mergeDeliveryFields.d.ts +13 -0
  100. package/dist/extraction/mergeDeliveryFields.js +17 -0
  101. package/dist/extraction/mergeDeliveryFields.js.map +1 -0
  102. package/dist/extraction/responseIdentifier.d.ts +19 -0
  103. package/dist/extraction/responseIdentifier.js +29 -0
  104. package/dist/extraction/responseIdentifier.js.map +1 -0
  105. package/dist/extraction/types.d.ts +11 -18
  106. package/dist/extraction/types.js +0 -12
  107. package/dist/extraction/types.js.map +1 -1
  108. package/dist/extraction/utils.d.ts +14 -0
  109. package/dist/extraction/utils.js +35 -5
  110. package/dist/extraction/utils.js.map +1 -1
  111. package/dist/index.d.ts +16 -10
  112. package/dist/index.js +19 -8
  113. package/dist/index.js.map +1 -1
  114. package/dist/interactions/associate/extractor.d.ts +1 -0
  115. package/dist/interactions/associate/extractor.js +10 -12
  116. package/dist/interactions/associate/extractor.js.map +1 -1
  117. package/dist/interactions/choice/extractor.js +6 -13
  118. package/dist/interactions/choice/extractor.js.map +1 -1
  119. package/dist/interactions/drawing/extractor.d.ts +6 -0
  120. package/dist/interactions/drawing/extractor.js +30 -9
  121. package/dist/interactions/drawing/extractor.js.map +1 -1
  122. package/dist/interactions/end-attempt/extractor.js +2 -1
  123. package/dist/interactions/end-attempt/extractor.js.map +1 -1
  124. package/dist/interactions/extended-text/extractor.d.ts +6 -1
  125. package/dist/interactions/extended-text/extractor.js +10 -5
  126. package/dist/interactions/extended-text/extractor.js.map +1 -1
  127. package/dist/interactions/extended-text/response.js +18 -18
  128. package/dist/interactions/extended-text/response.js.map +1 -1
  129. package/dist/interactions/gap-match/extractor.d.ts +40 -2
  130. package/dist/interactions/gap-match/extractor.js +197 -39
  131. package/dist/interactions/gap-match/extractor.js.map +1 -1
  132. package/dist/interactions/graphic-associate/extractor.d.ts +11 -0
  133. package/dist/interactions/graphic-associate/extractor.js +35 -24
  134. package/dist/interactions/graphic-associate/extractor.js.map +1 -1
  135. package/dist/interactions/graphic-gap-match/extractor.d.ts +21 -0
  136. package/dist/interactions/graphic-gap-match/extractor.js +79 -43
  137. package/dist/interactions/graphic-gap-match/extractor.js.map +1 -1
  138. package/dist/interactions/graphic-order/extractor.d.ts +15 -0
  139. package/dist/interactions/graphic-order/extractor.js +39 -24
  140. package/dist/interactions/graphic-order/extractor.js.map +1 -1
  141. package/dist/interactions/hotspot/extractor.d.ts +6 -0
  142. package/dist/interactions/hotspot/extractor.js +31 -16
  143. package/dist/interactions/hotspot/extractor.js.map +1 -1
  144. package/dist/interactions/hottext/extractor.js +2 -12
  145. package/dist/interactions/hottext/extractor.js.map +1 -1
  146. package/dist/interactions/inline/accessibleName.d.ts +29 -0
  147. package/dist/interactions/inline/accessibleName.js +35 -0
  148. package/dist/interactions/inline/accessibleName.js.map +1 -0
  149. package/dist/interactions/inline/render-plan.d.ts +5 -14
  150. package/dist/interactions/inline/render-plan.js +5 -56
  151. package/dist/interactions/inline/render-plan.js.map +1 -1
  152. package/dist/interactions/inline-choice/extractor.d.ts +4 -0
  153. package/dist/interactions/inline-choice/extractor.js +13 -12
  154. package/dist/interactions/inline-choice/extractor.js.map +1 -1
  155. package/dist/interactions/match/extractor.d.ts +2 -0
  156. package/dist/interactions/match/extractor.js +14 -28
  157. package/dist/interactions/match/extractor.js.map +1 -1
  158. package/dist/interactions/media/extractor.d.ts +5 -11
  159. package/dist/interactions/media/extractor.js +100 -36
  160. package/dist/interactions/media/extractor.js.map +1 -1
  161. package/dist/interactions/modules.js +8 -2
  162. package/dist/interactions/modules.js.map +1 -1
  163. package/dist/interactions/order/extractor.d.ts +2 -0
  164. package/dist/interactions/order/extractor.js +8 -12
  165. package/dist/interactions/order/extractor.js.map +1 -1
  166. package/dist/interactions/order/limits.d.ts +29 -0
  167. package/dist/interactions/order/limits.js +28 -0
  168. package/dist/interactions/order/limits.js.map +1 -0
  169. package/dist/interactions/portable-custom/extractor.js +4 -2
  170. package/dist/interactions/portable-custom/extractor.js.map +1 -1
  171. package/dist/interactions/position-object/extractor.d.ts +18 -1
  172. package/dist/interactions/position-object/extractor.js +81 -22
  173. package/dist/interactions/position-object/extractor.js.map +1 -1
  174. package/dist/interactions/select-point/extractor.d.ts +6 -0
  175. package/dist/interactions/select-point/extractor.js +31 -19
  176. package/dist/interactions/select-point/extractor.js.map +1 -1
  177. package/dist/interactions/shared/imageAlt.d.ts +54 -0
  178. package/dist/interactions/shared/imageAlt.js +84 -0
  179. package/dist/interactions/shared/imageAlt.js.map +1 -0
  180. package/dist/interactions/shared/interactionImage.d.ts +32 -0
  181. package/dist/interactions/shared/interactionImage.js +39 -0
  182. package/dist/interactions/shared/interactionImage.js.map +1 -0
  183. package/dist/interactions/shared/specDefaults.d.ts +20 -0
  184. package/dist/interactions/shared/specDefaults.js +25 -0
  185. package/dist/interactions/shared/specDefaults.js.map +1 -0
  186. package/dist/interactions/shared/types.d.ts +212 -40
  187. package/dist/interactions/shared/types.js.map +1 -1
  188. package/dist/interactions/text-entry/extractor.d.ts +9 -0
  189. package/dist/interactions/text-entry/extractor.js +9 -0
  190. package/dist/interactions/text-entry/extractor.js.map +1 -1
  191. package/dist/interactions/text-entry/inlineInputStyle.d.ts +10 -0
  192. package/dist/interactions/text-entry/inlineInputStyle.js +12 -0
  193. package/dist/interactions/text-entry/inlineInputStyle.js.map +1 -0
  194. package/dist/interactions/text-entry/inputMode.d.ts +35 -0
  195. package/dist/interactions/text-entry/inputMode.js +134 -0
  196. package/dist/interactions/text-entry/inputMode.js.map +1 -0
  197. package/dist/interactions/text-entry/response.d.ts +15 -0
  198. package/dist/interactions/text-entry/response.js +25 -0
  199. package/dist/interactions/text-entry/response.js.map +1 -0
  200. package/dist/interactions/upload/extractor.js +2 -2
  201. package/dist/interactions/upload/extractor.js.map +1 -1
  202. package/dist/pci/PciHost.d.ts +1 -1
  203. package/dist/pci/PciHost.js +11 -11
  204. package/dist/pci/PciHost.js.map +1 -1
  205. package/dist/pci/index.d.ts +1 -0
  206. package/dist/pci/index.js.map +1 -1
  207. package/dist/pci/modulePaths.d.ts +16 -0
  208. package/dist/pci/modulePaths.js +33 -0
  209. package/dist/pci/modulePaths.js.map +1 -0
  210. package/dist/pci/pageRealmSession.js +3 -15
  211. package/dist/pci/pageRealmSession.js.map +1 -1
  212. package/dist/pci/qtiVariableJson.d.ts +46 -3
  213. package/dist/pci/qtiVariableJson.js +247 -53
  214. package/dist/pci/qtiVariableJson.js.map +1 -1
  215. package/dist/pci/sandbox/SandboxedPciSession.d.ts +3 -0
  216. package/dist/pci/sandbox/SandboxedPciSession.js +15 -14
  217. package/dist/pci/sandbox/SandboxedPciSession.js.map +1 -1
  218. package/dist/pci/sandbox/iframeConnector.d.ts +18 -4
  219. package/dist/pci/sandbox/iframeConnector.js +35 -6
  220. package/dist/pci/sandbox/iframeConnector.js.map +1 -1
  221. package/dist/pci/sandbox/protocol.d.ts +14 -0
  222. package/dist/pci/sandbox/protocol.js.map +1 -1
  223. package/dist/pci/sessionHosts.d.ts +47 -0
  224. package/dist/pci/sessionHosts.js +66 -0
  225. package/dist/pci/sessionHosts.js.map +1 -0
  226. package/dist/pci/types.d.ts +7 -1
  227. package/dist/pci/types.js.map +1 -1
  228. package/dist/pnp/applyPnp.d.ts +20 -3
  229. package/dist/pnp/applyPnp.js +84 -9
  230. package/dist/pnp/applyPnp.js.map +1 -1
  231. package/dist/pnp/parsePnpXml.js +2 -0
  232. package/dist/pnp/parsePnpXml.js.map +1 -1
  233. package/dist/pnp/types.d.ts +16 -8
  234. package/dist/pnp/types.js.map +1 -1
  235. package/dist/presentation/feedbackAnnouncement.d.ts +56 -0
  236. package/dist/presentation/feedbackAnnouncement.js +150 -0
  237. package/dist/presentation/feedbackAnnouncement.js.map +1 -0
  238. package/dist/presentation/interactionSlots.d.ts +31 -0
  239. package/dist/presentation/interactionSlots.js +101 -0
  240. package/dist/presentation/interactionSlots.js.map +1 -0
  241. package/dist/presentation/itemPresentationPlan.d.ts +69 -6
  242. package/dist/presentation/itemPresentationPlan.js +93 -81
  243. package/dist/presentation/itemPresentationPlan.js.map +1 -1
  244. package/dist/{components/utils → presentation}/stimulusRender.js +3 -12
  245. package/dist/presentation/stimulusRender.js.map +1 -0
  246. package/dist/presentation/stylesheetRender.js.map +1 -0
  247. package/dist/security/escapeHtml.d.ts +15 -0
  248. package/dist/security/escapeHtml.js +22 -0
  249. package/dist/security/escapeHtml.js.map +1 -0
  250. package/dist/security/index.d.ts +1 -0
  251. package/dist/security/index.js +1 -0
  252. package/dist/security/index.js.map +1 -1
  253. package/dist/server.d.ts +8 -1
  254. package/dist/server.js.map +1 -1
  255. package/dist/session-inputs.d.ts +108 -0
  256. package/dist/session-inputs.js +130 -0
  257. package/dist/session-inputs.js.map +1 -0
  258. package/dist/types/index.d.ts +67 -35
  259. package/dist/types/index.js.map +1 -1
  260. package/dist/utils/cloneFreeze.d.ts +52 -0
  261. package/dist/utils/cloneFreeze.js +113 -0
  262. package/dist/utils/cloneFreeze.js.map +1 -0
  263. package/dist/utils/htmlAttributes.d.ts +13 -0
  264. package/dist/utils/htmlAttributes.js +22 -0
  265. package/dist/utils/htmlAttributes.js.map +1 -0
  266. package/dist/web-components/QTIInteractionElement.d.ts +0 -29
  267. package/dist/web-components/QTIInteractionElement.js +0 -32
  268. package/dist/web-components/QTIInteractionElement.js.map +1 -1
  269. package/dist/web-components/index.d.ts +1 -2
  270. package/dist/web-components/index.js +2 -3
  271. package/dist/web-components/index.js.map +1 -1
  272. package/package.json +15 -18
  273. package/dist/components/utils/feedbackUtils.d.ts +0 -77
  274. package/dist/components/utils/feedbackUtils.js +0 -138
  275. package/dist/components/utils/feedbackUtils.js.map +0 -1
  276. package/dist/components/utils/index.d.ts +0 -4
  277. package/dist/components/utils/index.js +0 -5
  278. package/dist/components/utils/index.js.map +0 -1
  279. package/dist/components/utils/stimulusRender.js.map +0 -1
  280. package/dist/components/utils/stylesheetRender.js.map +0 -1
  281. package/dist/core/constants.d.ts +0 -65
  282. package/dist/core/constants.js +0 -74
  283. package/dist/core/constants.js.map +0 -1
  284. package/dist/element-class-X2XXDa29.js +0 -9299
  285. package/dist/element-class-X2XXDa29.js.map +0 -1
  286. package/dist/extensions/MathLiveEditor.d.ts +0 -31
  287. package/dist/extensions/MathLiveEditor.js +0 -248
  288. package/dist/extensions/MathLiveEditor.js.map +0 -1
  289. package/dist/utils/PerformanceMonitor.d.ts +0 -169
  290. package/dist/utils/PerformanceMonitor.js +0 -243
  291. package/dist/utils/PerformanceMonitor.js.map +0 -1
  292. package/dist/utils/responseUtils.d.ts +0 -15
  293. package/dist/utils/responseUtils.js +0 -46
  294. package/dist/utils/responseUtils.js.map +0 -1
  295. package/dist/web-components/QTIInteractionBase.d.ts +0 -119
  296. package/dist/web-components/QTIInteractionBase.js +0 -244
  297. package/dist/web-components/QTIInteractionBase.js.map +0 -1
  298. /package/dist/{components/utils → presentation}/stimulusRender.d.ts +0 -0
  299. /package/dist/{components/utils → presentation}/stylesheetRender.d.ts +0 -0
  300. /package/dist/{components/utils → presentation}/stylesheetRender.js +0 -0
@@ -0,0 +1,168 @@
1
+ /**
2
+ * Runtime value coercion: raw host/component/serialized values read as a declaration's
3
+ * QTI base type and cardinality.
4
+ */
5
+ import { coerceBaseValue, qtiNull, qtiValue, } from '@pie-qti/qti-processing';
6
+ import { createExtendedTextNumericRecord, EXTENDED_TEXT_RECORD_FIELD_TYPES, } from '../../interactions/extended-text/response.js';
7
+ import { cloneValue } from '../../utils/cloneFreeze.js';
8
+ export function coerceToDeclarationValue(input, baseType, cardinality, raw, identifier) {
9
+ if (raw === null || raw === undefined)
10
+ return qtiNull(baseType, cardinality);
11
+ // Allow callers to pass fully-formed QtiValue (e.g. session restore).
12
+ if (typeof raw === 'object' && raw && 'kind' in raw) {
13
+ return cloneValue(raw);
14
+ }
15
+ const inputBase = identifier ? getNumericInputBase(input, identifier) : undefined;
16
+ if (cardinality === 'record') {
17
+ return coerceRecordValue(input, raw, inputBase ?? 10);
18
+ }
19
+ if (!baseType)
20
+ return qtiNull(undefined, cardinality);
21
+ // For file types, preserve QTIFileResponse objects directly
22
+ if (baseType === 'file') {
23
+ if (cardinality === 'multiple' || cardinality === 'ordered') {
24
+ const arr = Array.isArray(raw) ? raw : [raw];
25
+ return qtiValue(baseType, cardinality, cloneValue(arr.filter((v) => v !== null && v !== undefined)));
26
+ }
27
+ return qtiValue(baseType, cardinality, cloneValue(raw));
28
+ }
29
+ if (cardinality === 'multiple' || cardinality === 'ordered') {
30
+ const arr = Array.isArray(raw) ? raw : [raw];
31
+ const coerced = arr
32
+ .map((entry) => coerceSingleValue(input, baseType, entry, inputBase))
33
+ .filter((v) => v.kind === 'value')
34
+ .map((v) => v.value);
35
+ // Multiple/ordered can legitimately be an empty container (distinct from null).
36
+ return qtiValue(baseType, cardinality, coerced);
37
+ }
38
+ return coerceSingleValue(input, baseType, raw, inputBase);
39
+ }
40
+ /**
41
+ * One value of a response, read as its base type. Typed numeric text reads in the number base
42
+ * of the string interaction bound to the response (QTI ASI stringInteraction `base`). The base
43
+ * applies to typed text only: a finite number already is the variable's value — a restored
44
+ * session, a correct response or default, a value read back from the session — and reading
45
+ * its decimal digits in the base again would change it on every round trip.
46
+ */
47
+ function coerceSingleValue(input, baseType, raw, inputBase) {
48
+ const text = String(raw ?? '');
49
+ const t = text.trim();
50
+ if (t.length === 0)
51
+ return qtiNull(baseType, 'single');
52
+ const typed = !(typeof raw === 'number' && Number.isFinite(raw));
53
+ if (inputBase !== undefined && typed && (baseType === 'integer' || baseType === 'float')) {
54
+ const numeric = createExtendedTextNumericRecord(t, inputBase, contentLanguage(input));
55
+ const value = baseType === 'integer' ? numeric.integerValue : numeric.floatValue;
56
+ return value === null ? qtiNull(baseType, 'single') : qtiValue(baseType, 'single', value);
57
+ }
58
+ // A string response is the candidate's text, spaces included: the text fields are controlled
59
+ // by the stored response — the extended text rebuilds its fields from what the session holds
60
+ // after every keystroke — so a value trimmed here echoes back into the field and deletes the
61
+ // space the candidate just typed, corrupting every multi-word typed answer. Comparisons that
62
+ // need the trimmed form trim at the point of comparison instead.
63
+ if (baseType === 'string')
64
+ return qtiValue('string', 'single', text);
65
+ return coerceBaseValue(baseType, t, contentLanguage(input));
66
+ }
67
+ /**
68
+ * The number base typed numeric text for `responseIdentifier` reads in (QTI ASI
69
+ * stringInteraction `base`): the bound extendedTextInteraction's, decimal included (its
70
+ * lexical reading also fills the numeric record fields), or the bound textEntryInteraction's
71
+ * when it is not decimal. Undefined otherwise: decimal text entry keeps the content-language
72
+ * number reading.
73
+ */
74
+ function getNumericInputBase(input, responseIdentifier) {
75
+ const extendedTextBase = input.itemDocument.getExtendedTextBase(responseIdentifier);
76
+ if (extendedTextBase !== undefined)
77
+ return extendedTextBase;
78
+ const textEntryBase = input.itemDocument.getTextEntryBase(responseIdentifier);
79
+ return textEntryBase !== undefined && textEntryBase !== 10 ? textEntryBase : undefined;
80
+ }
81
+ function coerceRecordValue(input, raw, base) {
82
+ let source = raw;
83
+ if (typeof source === 'string') {
84
+ const stringSource = source;
85
+ if (stringSource.trim().length === 0)
86
+ return qtiNull(undefined, 'record');
87
+ if (stringSource.trimStart().startsWith('{')) {
88
+ try {
89
+ source = JSON.parse(stringSource);
90
+ }
91
+ catch {
92
+ return qtiNull(undefined, 'record');
93
+ }
94
+ }
95
+ else {
96
+ source = createExtendedTextNumericRecord(stringSource, base, contentLanguage(input));
97
+ }
98
+ }
99
+ if (!source || typeof source !== 'object' || Array.isArray(source)) {
100
+ return qtiNull(undefined, 'record');
101
+ }
102
+ const fields = {};
103
+ for (const [fieldIdentifier, rawField] of Object.entries(source)) {
104
+ if (rawField && typeof rawField === 'object' && 'kind' in rawField) {
105
+ fields[fieldIdentifier] = rawField;
106
+ continue;
107
+ }
108
+ let fieldBaseType = EXTENDED_TEXT_RECORD_FIELD_TYPES[fieldIdentifier];
109
+ let fieldValue = rawField;
110
+ let fieldCardinality = Array.isArray(rawField) ? 'multiple' : 'single';
111
+ if (rawField && typeof rawField === 'object' && !Array.isArray(rawField) && 'value' in rawField) {
112
+ const serializedField = rawField;
113
+ fieldBaseType = serializedField.baseType ?? fieldBaseType;
114
+ fieldValue = serializedField.value;
115
+ fieldCardinality =
116
+ serializedField.cardinality === 'multiple' || serializedField.cardinality === 'ordered'
117
+ ? serializedField.cardinality
118
+ : Array.isArray(fieldValue) ? 'multiple' : 'single';
119
+ }
120
+ if (!fieldBaseType) {
121
+ const sample = Array.isArray(fieldValue)
122
+ ? fieldValue.find((item) => item !== null && item !== undefined)
123
+ : fieldValue;
124
+ fieldBaseType = typeof sample === 'boolean'
125
+ ? 'boolean'
126
+ : typeof sample === 'number'
127
+ ? (Number.isInteger(sample) ? 'integer' : 'float')
128
+ : 'string';
129
+ }
130
+ if (fieldValue === null || fieldValue === undefined) {
131
+ fields[fieldIdentifier] = qtiNull(fieldBaseType, fieldCardinality);
132
+ }
133
+ else if (fieldCardinality !== 'single') {
134
+ // A container field, such as a PCI record member written as `list`: each value
135
+ // is coerced, rather than the whole array as one string.
136
+ const containerBaseType = fieldBaseType;
137
+ const items = (Array.isArray(fieldValue) ? fieldValue : [fieldValue])
138
+ .filter((item) => item !== null && item !== undefined)
139
+ .map((item) => {
140
+ if (containerBaseType === 'file' && typeof item === 'object')
141
+ return item;
142
+ const coerced = coerceBaseValue(containerBaseType, String(item), contentLanguage(input));
143
+ return coerced.kind === 'value' ? coerced.value : null;
144
+ })
145
+ .filter((item) => item !== null);
146
+ fields[fieldIdentifier] = qtiValue(containerBaseType, fieldCardinality, items);
147
+ }
148
+ else if (fieldBaseType === 'file' && typeof fieldValue === 'object') {
149
+ fields[fieldIdentifier] = qtiValue('file', 'single', fieldValue);
150
+ }
151
+ else if (fieldBaseType === 'string') {
152
+ // A string field is text as typed, spaces included (a numeric record's `stringValue`
153
+ // keeps the input as typed): the same at-rest rule as the single-value coercion.
154
+ const fieldText = String(fieldValue);
155
+ fields[fieldIdentifier] = qtiValue('string', 'single', fieldText.trim() ? fieldText : '');
156
+ }
157
+ else {
158
+ fields[fieldIdentifier] = coerceBaseValue(fieldBaseType, String(fieldValue), contentLanguage(input));
159
+ }
160
+ }
161
+ return Object.keys(fields).length > 0
162
+ ? qtiValue(undefined, 'record', fields)
163
+ : qtiNull(undefined, 'record');
164
+ }
165
+ function contentLanguage(input) {
166
+ return input.itemDocument.getContentLanguage();
167
+ }
168
+ //# sourceMappingURL=declarationValues.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"declarationValues.js","sourceRoot":"","sources":["../../../src/core/declarations/declarationValues.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAGN,eAAe,EAEf,OAAO,EACP,QAAQ,GACR,MAAM,yBAAyB,CAAC;AAEj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ACvC,qFAAqF;YACrF,iFAAiF;YACjF,MAAM,SAAS,GAAG,MAAM,CAAC,UAAU,CAAC,CAAC;YACrC,MAAM,CAAC,eAAe,CAAC,GAAG,QAAQ,CAAC,QAAQ,EAAE,QAAQ,EAAE,SAAS,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;QAC3F,CAAC;aAAM,CAAC;YACP,MAAM,CAAC,eAAe,CAAC,GAAG,eAAe,CAAC,aAAa,EAAE,MAAM,CAAC,UAAU,CAAC,EAAE,eAAe,CAAC,KAAK,CAAC,CAAC,CAAC;QACtG,CAAC;IACF,CAAC;IAED,OAAO,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,MAAM,GAAG,CAAC;QACpC,CAAC,CAAC,QAAQ,CAAC,SAAS,EAAE,QAAQ,EAAE,MAAM,CAAC;QACvC,CAAC,CAAC,OAAO,CAAC,SAAS,EAAE,QAAQ,CAAC,CAAC;AACjC,CAAC;AAED,SAAS,eAAe,CAAC,KAA4B;IACpD,OAAO,KAAK,CAAC,YAAY,CAAC,kBAAkB,EAAE,CAAC;AAChD,CAAC","sourcesContent":["/**\n * Runtime value coercion: raw host/component/serialized values read as a declaration's\n * QTI base type and cardinality.\n */\nimport {\n\ttype BaseType,\n\ttype Cardinality,\n\tcoerceBaseValue,\n\ttype QtiValue,\n\tqtiNull,\n\tqtiValue,\n} from '@pie-qti/qti-processing';\nimport type { AssessmentItemDocument } from '../../document/AssessmentItemDocument.js';\nimport {\n\tcreateExtendedTextNumericRecord,\n\tEXTENDED_TEXT_RECORD_FIELD_TYPES,\n} from '../../interactions/extended-text/response.js';\nimport { cloneValue } from '../../utils/cloneFreeze.js';\n\n/** The parsed item document numeric input bases and the content language are read from. */\nexport interface DeclarationValueInput {\n\treadonly itemDocument: AssessmentItemDocument;\n}\n\nexport function coerceToDeclarationValue(\n\tinput: DeclarationValueInput,\n\tbaseType: BaseType | undefined,\n\tcardinality: Cardinality,\n\traw: unknown,\n\tidentifier?: string,\n): QtiValue {\n\tif (raw === null || raw === undefined) return qtiNull(baseType, cardinality);\n\n\t// Allow callers to pass fully-formed QtiValue (e.g. session restore).\n\tif (typeof raw === 'object' && raw && 'kind' in raw) {\n\t\treturn cloneValue(raw as QtiValue);\n\t}\n\n\tconst inputBase = identifier ? getNumericInputBase(input, identifier) : undefined;\n\tif (cardinality === 'record') {\n\t\treturn coerceRecordValue(input, raw, inputBase ?? 10);\n\t}\n\n\tif (!baseType) return qtiNull(undefined, cardinality);\n\n\t// For file types, preserve QTIFileResponse objects directly\n\tif (baseType === 'file') {\n\t\tif (cardinality === 'multiple' || cardinality === 'ordered') {\n\t\t\tconst arr = Array.isArray(raw) ? raw : [raw];\n\t\t\treturn qtiValue(\n\t\t\t\tbaseType,\n\t\t\t\tcardinality,\n\t\t\t\tcloneValue(arr.filter((v) => v !== null && v !== undefined)),\n\t\t\t);\n\t\t}\n\t\treturn qtiValue(baseType, cardinality, cloneValue(raw));\n\t}\n\n\tif (cardinality === 'multiple' || cardinality === 'ordered') {\n\t\tconst arr = Array.isArray(raw) ? raw : [raw];\n\t\tconst coerced = arr\n\t\t\t.map((entry) => coerceSingleValue(input, baseType, entry, inputBase))\n\t\t\t.filter((v): v is Extract<QtiValue, { kind: 'value' }> => v.kind === 'value')\n\t\t\t.map((v) => v.value);\n\t\t// Multiple/ordered can legitimately be an empty container (distinct from null).\n\t\treturn qtiValue(baseType, cardinality, coerced);\n\t}\n\n\treturn coerceSingleValue(input, baseType, raw, inputBase);\n}\n\n/**\n * One value of a response, read as its base type. Typed numeric text reads in the number base\n * of the string interaction bound to the response (QTI ASI stringInteraction `base`). The base\n * applies to typed text only: a finite number already is the variable's value — a restored\n * session, a correct response or default, a value read back from the session — and reading\n * its decimal digits in the base again would change it on every round trip.\n */\nfunction coerceSingleValue(\n\tinput: DeclarationValueInput,\n\tbaseType: BaseType,\n\traw: unknown,\n\tinputBase: number | undefined,\n): QtiValue {\n\tconst text = String(raw ?? '');\n\tconst t = text.trim();\n\tif (t.length === 0) return qtiNull(baseType, 'single');\n\tconst typed = !(typeof raw === 'number' && Number.isFinite(raw));\n\tif (inputBase !== undefined && typed && (baseType === 'integer' || baseType === 'float')) {\n\t\tconst numeric = createExtendedTextNumericRecord(t, inputBase, contentLanguage(input));\n\t\tconst value = baseType === 'integer' ? numeric.integerValue : numeric.floatValue;\n\t\treturn value === null ? qtiNull(baseType, 'single') : qtiValue(baseType, 'single', value);\n\t}\n\t// A string response is the candidate's text, spaces included: the text fields are controlled\n\t// by the stored response — the extended text rebuilds its fields from what the session holds\n\t// after every keystroke — so a value trimmed here echoes back into the field and deletes the\n\t// space the candidate just typed, corrupting every multi-word typed answer. Comparisons that\n\t// need the trimmed form trim at the point of comparison instead.\n\tif (baseType === 'string') return qtiValue('string', 'single', text);\n\treturn coerceBaseValue(baseType, t, contentLanguage(input));\n}\n\n/**\n * The number base typed numeric text for `responseIdentifier` reads in (QTI ASI\n * stringInteraction `base`): the bound extendedTextInteraction's, decimal included (its\n * lexical reading also fills the numeric record fields), or the bound textEntryInteraction's\n * when it is not decimal. Undefined otherwise: decimal text entry keeps the content-language\n * number reading.\n */\nfunction getNumericInputBase(input: DeclarationValueInput, responseIdentifier: string): number | undefined {\n\tconst extendedTextBase = input.itemDocument.getExtendedTextBase(responseIdentifier);\n\tif (extendedTextBase !== undefined) return extendedTextBase;\n\tconst textEntryBase = input.itemDocument.getTextEntryBase(responseIdentifier);\n\treturn textEntryBase !== undefined && textEntryBase !== 10 ? textEntryBase : undefined;\n}\n\nfunction coerceRecordValue(input: DeclarationValueInput, raw: unknown, base: number): QtiValue {\n\tlet source = raw;\n\tif (typeof source === 'string') {\n\t\tconst stringSource = source;\n\t\tif (stringSource.trim().length === 0) return qtiNull(undefined, 'record');\n\t\tif (stringSource.trimStart().startsWith('{')) {\n\t\t\ttry {\n\t\t\t\tsource = JSON.parse(stringSource);\n\t\t\t} catch {\n\t\t\t\treturn qtiNull(undefined, 'record');\n\t\t\t}\n\t\t} else {\n\t\t\tsource = createExtendedTextNumericRecord(stringSource, base, contentLanguage(input));\n\t\t}\n\t}\n\tif (!source || typeof source !== 'object' || Array.isArray(source)) {\n\t\treturn qtiNull(undefined, 'record');\n\t}\n\n\tconst fields: Record<string, QtiValue> = {};\n\tfor (const [fieldIdentifier, rawField] of Object.entries(source)) {\n\t\tif (rawField && typeof rawField === 'object' && 'kind' in rawField) {\n\t\t\tfields[fieldIdentifier] = rawField as QtiValue;\n\t\t\tcontinue;\n\t\t}\n\n\t\tlet fieldBaseType = EXTENDED_TEXT_RECORD_FIELD_TYPES[\n\t\t\tfieldIdentifier as keyof typeof EXTENDED_TEXT_RECORD_FIELD_TYPES\n\t\t] as BaseType | undefined;\n\t\tlet fieldValue = rawField;\n\t\tlet fieldCardinality: Cardinality = Array.isArray(rawField) ? 'multiple' : 'single';\n\t\tif (rawField && typeof rawField === 'object' && !Array.isArray(rawField) && 'value' in rawField) {\n\t\t\tconst serializedField = rawField as {\n\t\t\t\tbaseType?: BaseType;\n\t\t\t\tcardinality?: Cardinality;\n\t\t\t\tvalue: unknown;\n\t\t\t};\n\t\t\tfieldBaseType = serializedField.baseType ?? fieldBaseType;\n\t\t\tfieldValue = serializedField.value;\n\t\t\tfieldCardinality =\n\t\t\t\tserializedField.cardinality === 'multiple' || serializedField.cardinality === 'ordered'\n\t\t\t\t\t? serializedField.cardinality\n\t\t\t\t\t: Array.isArray(fieldValue) ? 'multiple' : 'single';\n\t\t}\n\n\t\tif (!fieldBaseType) {\n\t\t\tconst sample = Array.isArray(fieldValue)\n\t\t\t\t? fieldValue.find((item) => item !== null && item !== undefined)\n\t\t\t\t: fieldValue;\n\t\t\tfieldBaseType = typeof sample === 'boolean'\n\t\t\t\t? 'boolean'\n\t\t\t\t: typeof sample === 'number'\n\t\t\t\t\t? (Number.isInteger(sample) ? 'integer' : 'float')\n\t\t\t\t\t: 'string';\n\t\t}\n\t\tif (fieldValue === null || fieldValue === undefined) {\n\t\t\tfields[fieldIdentifier] = qtiNull(fieldBaseType, fieldCardinality);\n\t\t} else if (fieldCardinality !== 'single') {\n\t\t\t// A container field, such as a PCI record member written as `list`: each value\n\t\t\t// is coerced, rather than the whole array as one string.\n\t\t\tconst containerBaseType = fieldBaseType;\n\t\t\tconst items = (Array.isArray(fieldValue) ? fieldValue : [fieldValue])\n\t\t\t\t.filter((item) => item !== null && item !== undefined)\n\t\t\t\t.map((item) => {\n\t\t\t\t\tif (containerBaseType === 'file' && typeof item === 'object') return item;\n\t\t\t\t\tconst coerced = coerceBaseValue(containerBaseType, String(item), contentLanguage(input));\n\t\t\t\t\treturn coerced.kind === 'value' ? coerced.value : null;\n\t\t\t\t})\n\t\t\t\t.filter((item) => item !== null);\n\t\t\tfields[fieldIdentifier] = qtiValue(containerBaseType, fieldCardinality, items);\n\t\t} else if (fieldBaseType === 'file' && typeof fieldValue === 'object') {\n\t\t\tfields[fieldIdentifier] = qtiValue('file', 'single', fieldValue);\n\t\t} else if (fieldBaseType === 'string') {\n\t\t\t// A string field is text as typed, spaces included (a numeric record's `stringValue`\n\t\t\t// keeps the input as typed): the same at-rest rule as the single-value coercion.\n\t\t\tconst fieldText = String(fieldValue);\n\t\t\tfields[fieldIdentifier] = qtiValue('string', 'single', fieldText.trim() ? fieldText : '');\n\t\t} else {\n\t\t\tfields[fieldIdentifier] = coerceBaseValue(fieldBaseType, String(fieldValue), contentLanguage(input));\n\t\t}\n\t}\n\n\treturn Object.keys(fields).length > 0\n\t\t? qtiValue(undefined, 'record', fields)\n\t\t: qtiNull(undefined, 'record');\n}\n\nfunction contentLanguage(input: DeclarationValueInput): string | undefined {\n\treturn input.itemDocument.getContentLanguage();\n}\n"]}
@@ -0,0 +1,36 @@
1
+ import type { ElementNameMapper } from '@pie-qti/qti-common';
2
+ /** A choice, gap or hotspot that takes part in pairings, with its authored `matchGroup`. */
3
+ export interface MatchGroupChoice {
4
+ readonly identifier: string;
5
+ /** The `matchGroup` tokens; empty when the attribute is absent. */
6
+ readonly matchGroup: readonly string[];
7
+ }
8
+ /** The pairing constraints of one associate, match, gap match or graphic interaction. */
9
+ export interface MatchGroupConstraints {
10
+ /** True for `directedPair` responses (source, then target); false for `pair` responses. */
11
+ readonly directed: boolean;
12
+ readonly sources: ReadonlyMap<string, MatchGroupChoice>;
13
+ /** The same map as `sources` for undirected interactions. */
14
+ readonly targets: ReadonlyMap<string, MatchGroupChoice>;
15
+ }
16
+ /**
17
+ * Whether `matchGroup` lets two choices be paired.
18
+ *
19
+ * QTI 2.2 and 3.0 define `matchGroup` as "a list of the identifiers for the objects that can be
20
+ * matched with this" choice, gap or hotspot, empty meaning unrestricted, each side subject to its
21
+ * own constraint. Content (and the `@pie-qti/default-components` renderers) also use the tokens
22
+ * as shared group labels. A pairing is refused only when neither reading allows it, so a response
23
+ * a candidate could build in the delivered UI, or that the specification allows, always passes.
24
+ */
25
+ export declare function isMatchGroupCompatible(a: MatchGroupChoice, b: MatchGroupChoice): boolean;
26
+ /**
27
+ * The pairs of a `pair` / `directedPair` response (single or container) that `matchGroup` does not
28
+ * allow, as `"source target"`. Pairs naming identifiers the interaction does not have are left to
29
+ * other validation.
30
+ */
31
+ export declare function findMatchGroupViolations(response: unknown, constraints: MatchGroupConstraints): string[];
32
+ /**
33
+ * The `matchGroup` constraints of every pairing interaction in `item` that authors a `matchGroup`
34
+ * anywhere, by response identifier. `item` is the parsed source item.
35
+ */
36
+ export declare function readMatchGroupConstraints(item: Element, elementNameMapper: ElementNameMapper): Map<string, MatchGroupConstraints>;
@@ -0,0 +1,100 @@
1
+ import { childElements, getAttr } from '@pie-qti/qti-processing';
2
+ /**
3
+ * Whether `matchGroup` lets two choices be paired.
4
+ *
5
+ * QTI 2.2 and 3.0 define `matchGroup` as "a list of the identifiers for the objects that can be
6
+ * matched with this" choice, gap or hotspot, empty meaning unrestricted, each side subject to its
7
+ * own constraint. Content (and the `@pie-qti/default-components` renderers) also use the tokens
8
+ * as shared group labels. A pairing is refused only when neither reading allows it, so a response
9
+ * a candidate could build in the delivered UI, or that the specification allows, always passes.
10
+ */
11
+ export function isMatchGroupCompatible(a, b) {
12
+ if (a.matchGroup.length === 0 || b.matchGroup.length === 0)
13
+ return true;
14
+ if (a.matchGroup.includes(b.identifier) && b.matchGroup.includes(a.identifier))
15
+ return true;
16
+ return a.matchGroup.some((group) => b.matchGroup.includes(group));
17
+ }
18
+ /**
19
+ * The pairs of a `pair` / `directedPair` response (single or container) that `matchGroup` does not
20
+ * allow, as `"source target"`. Pairs naming identifiers the interaction does not have are left to
21
+ * other validation.
22
+ */
23
+ export function findMatchGroupViolations(response, constraints) {
24
+ const entries = Array.isArray(response) ? response : response === null || response === undefined ? [] : [response];
25
+ const violations = [];
26
+ for (const entry of entries) {
27
+ if (typeof entry !== 'string')
28
+ continue;
29
+ const [first, second] = entry.trim().split(/\s+/);
30
+ if (!first || !second)
31
+ continue;
32
+ const source = constraints.sources.get(first);
33
+ const target = constraints.targets.get(second);
34
+ if (!source || !target)
35
+ continue;
36
+ if (!isMatchGroupCompatible(source, target))
37
+ violations.push(`${first} ${second}`);
38
+ }
39
+ return violations;
40
+ }
41
+ /** Which elements an interaction pairs: canonical source names, then canonical target names. */
42
+ const PAIRING_INTERACTIONS = {
43
+ associateinteraction: { directed: false, sources: ['simpleassociablechoice'] },
44
+ graphicassociateinteraction: { directed: false, sources: ['associablehotspot'] },
45
+ matchinteraction: { directed: true, sources: ['simpleassociablechoice'] },
46
+ gapmatchinteraction: { directed: true, sources: ['gaptext', 'gapimg'], targets: ['gap'] },
47
+ graphicgapmatchinteraction: { directed: true, sources: ['gaptext', 'gapimg'], targets: ['associablehotspot'] },
48
+ };
49
+ /**
50
+ * The `matchGroup` constraints of every pairing interaction in `item` that authors a `matchGroup`
51
+ * anywhere, by response identifier. `item` is the parsed source item.
52
+ */
53
+ export function readMatchGroupConstraints(item, elementNameMapper) {
54
+ const canonical = (element) => elementNameMapper.toCanonical(element.localName);
55
+ const constraints = new Map();
56
+ const visit = (element) => {
57
+ const pairing = PAIRING_INTERACTIONS[canonical(element)];
58
+ const responseIdentifier = pairing ? getAttr(element, 'responseIdentifier')?.trim() : undefined;
59
+ if (pairing && responseIdentifier) {
60
+ let sources;
61
+ let targets;
62
+ if (canonical(element) === 'matchinteraction') {
63
+ // The first simpleMatchSet holds the sources, the second the targets.
64
+ const [sourceSet, targetSet] = childElements(element).filter((child) => canonical(child) === 'simplematchset');
65
+ sources = choicesIn(sourceSet, pairing.sources, canonical);
66
+ targets = choicesIn(targetSet, pairing.sources, canonical);
67
+ }
68
+ else {
69
+ sources = choicesIn(element, pairing.sources, canonical);
70
+ targets = pairing.targets ? choicesIn(element, pairing.targets, canonical) : sources;
71
+ }
72
+ const authored = [...sources.values(), ...targets.values()].some((choice) => choice.matchGroup.length > 0);
73
+ if (authored)
74
+ constraints.set(responseIdentifier, { directed: pairing.directed, sources, targets });
75
+ }
76
+ for (const child of childElements(element))
77
+ visit(child);
78
+ };
79
+ visit(item);
80
+ return constraints;
81
+ }
82
+ function choicesIn(root, names, canonical) {
83
+ const choices = new Map();
84
+ const visit = (element) => {
85
+ if (names.includes(canonical(element))) {
86
+ const identifier = getAttr(element, 'identifier')?.trim();
87
+ if (identifier) {
88
+ const matchGroup = (getAttr(element, 'matchGroup') ?? '').split(/\s+/).filter(Boolean);
89
+ choices.set(identifier, Object.freeze({ identifier, matchGroup: Object.freeze(matchGroup) }));
90
+ }
91
+ }
92
+ for (const child of childElements(element))
93
+ visit(child);
94
+ };
95
+ if (root)
96
+ for (const child of childElements(root))
97
+ visit(child);
98
+ return choices;
99
+ }
100
+ //# sourceMappingURL=matchGroups.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"matchGroups.js","sourceRoot":"","sources":["../../src/core/matchGroups.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,aAAa,EAAE,OAAO,EAAE,MAAM,yBAAyB,CAAC;AAkBjE;;;;;;;;GAQG;AACH,MAAM,UAAU,sBAAsB,CAAC,CAAmB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K,IAAI,aAAa,CAAC,OAAO,CAAC;YAAE,KAAK,CAAC,KAAK,CAAC,CAAC;IAC1D,CAAC,CAAC;IACF,KAAK,CAAC,IAAI,CAAC,CAAC;IACZ,OAAO,WAAW,CAAC;AACpB,CAAC;AAED,SAAS,SAAS,CACjB,IAAyB,EACzB,KAAwB,EACxB,SAAuC;IAEvC,MAAM,OAAO,GAAG,IAAI,GAAG,EAA4B,CAAC;IACpD,MAAM,KAAK,GAAG,CAAC,OAAgB,EAAQ,EAAE;QACxC,IAAI,KAAK,CAAC,QAAQ,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC,EAAE,CAAC;YACxC,MAAM,UAAU,GAAG,OAAO,CAAC,OAAO,EAAE,YAAY,CAAC,EAAE,IAAI,EAAE,CAAC;YAC1D,IAAI,UAAU,EAAE,CAAC;gBAChB,MAAM,UAAU,GAAG,CAAC,OAAO,CAAC,OAAO,EAAE,YAAY,CAAC,IAAI,EAAE,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;gBACvF,OAAO,CAAC,GAAG,CAAC,UAAU,EAAE,MAAM,CAAC,MAAM,CAAC,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,CAAC,MAAM,CAAC,UAAU,CAAC,EAAE,CAAC,CAAC,CAAC;YAC/F,CAAC;QACF,CAAC;QACD,KAAK,MAAM,KAAK,IAAI,aAAa,CAAC,OAAO,CAAC;YAAE,KAAK,CAAC,KAAK,CAAC,CAAC;IAC1D,CAAC,CAAC;IACF,IAAI,IAAI;QAAE,KAAK,MAAM,KAAK,IAAI,aAAa,CAAC,IAAI,CAAC;YAAE,KAAK,CAAC,KAAK,CAAC,CAAC;IAChE,OAAO,OAAO,CAAC;AAChB,CAAC","sourcesContent":["import type { ElementNameMapper } from '@pie-qti/qti-common';\nimport { childElements, getAttr } from '@pie-qti/qti-processing';\n\n/** A choice, gap or hotspot that takes part in pairings, with its authored `matchGroup`. */\nexport interface MatchGroupChoice {\n\treadonly identifier: string;\n\t/** The `matchGroup` tokens; empty when the attribute is absent. */\n\treadonly matchGroup: readonly string[];\n}\n\n/** The pairing constraints of one associate, match, gap match or graphic interaction. */\nexport interface MatchGroupConstraints {\n\t/** True for `directedPair` responses (source, then target); false for `pair` responses. */\n\treadonly directed: boolean;\n\treadonly sources: ReadonlyMap<string, MatchGroupChoice>;\n\t/** The same map as `sources` for undirected interactions. */\n\treadonly targets: ReadonlyMap<string, MatchGroupChoice>;\n}\n\n/**\n * Whether `matchGroup` lets two choices be paired.\n *\n * QTI 2.2 and 3.0 define `matchGroup` as \"a list of the identifiers for the objects that can be\n * matched with this\" choice, gap or hotspot, empty meaning unrestricted, each side subject to its\n * own constraint. Content (and the `@pie-qti/default-components` renderers) also use the tokens\n * as shared group labels. A pairing is refused only when neither reading allows it, so a response\n * a candidate could build in the delivered UI, or that the specification allows, always passes.\n */\nexport function isMatchGroupCompatible(a: MatchGroupChoice, b: MatchGroupChoice): boolean {\n\tif (a.matchGroup.length === 0 || b.matchGroup.length === 0) return true;\n\tif (a.matchGroup.includes(b.identifier) && b.matchGroup.includes(a.identifier)) return true;\n\treturn a.matchGroup.some((group) => b.matchGroup.includes(group));\n}\n\n/**\n * The pairs of a `pair` / `directedPair` response (single or container) that `matchGroup` does not\n * allow, as `\"source target\"`. Pairs naming identifiers the interaction does not have are left to\n * other validation.\n */\nexport function findMatchGroupViolations(response: unknown, constraints: MatchGroupConstraints): string[] {\n\tconst entries = Array.isArray(response) ? response : response === null || response === undefined ? [] : [response];\n\tconst violations: string[] = [];\n\tfor (const entry of entries) {\n\t\tif (typeof entry !== 'string') continue;\n\t\tconst [first, second] = entry.trim().split(/\\s+/);\n\t\tif (!first || !second) continue;\n\t\tconst source = constraints.sources.get(first);\n\t\tconst target = constraints.targets.get(second);\n\t\tif (!source || !target) continue;\n\t\tif (!isMatchGroupCompatible(source, target)) violations.push(`${first} ${second}`);\n\t}\n\treturn violations;\n}\n\n/** Which elements an interaction pairs: canonical source names, then canonical target names. */\nconst PAIRING_INTERACTIONS: Readonly<\n\tRecord<string, { directed: boolean; sources: readonly string[]; targets?: readonly string[] }>\n> = {\n\tassociateinteraction: { directed: false, sources: ['simpleassociablechoice'] },\n\tgraphicassociateinteraction: { directed: false, sources: ['associablehotspot'] },\n\tmatchinteraction: { directed: true, sources: ['simpleassociablechoice'] },\n\tgapmatchinteraction: { directed: true, sources: ['gaptext', 'gapimg'], targets: ['gap'] },\n\tgraphicgapmatchinteraction: { directed: true, sources: ['gaptext', 'gapimg'], targets: ['associablehotspot'] },\n};\n\n/**\n * The `matchGroup` constraints of every pairing interaction in `item` that authors a `matchGroup`\n * anywhere, by response identifier. `item` is the parsed source item.\n */\nexport function readMatchGroupConstraints(\n\titem: Element,\n\telementNameMapper: ElementNameMapper,\n): Map<string, MatchGroupConstraints> {\n\tconst canonical = (element: Element): string => elementNameMapper.toCanonical(element.localName);\n\tconst constraints = new Map<string, MatchGroupConstraints>();\n\n\tconst visit = (element: Element): void => {\n\t\tconst pairing = PAIRING_INTERACTIONS[canonical(element)];\n\t\tconst responseIdentifier = pairing ? getAttr(element, 'responseIdentifier')?.trim() : undefined;\n\t\tif (pairing && responseIdentifier) {\n\t\t\tlet sources: Map<string, MatchGroupChoice>;\n\t\t\tlet targets: Map<string, MatchGroupChoice>;\n\t\t\tif (canonical(element) === 'matchinteraction') {\n\t\t\t\t// The first simpleMatchSet holds the sources, the second the targets.\n\t\t\t\tconst [sourceSet, targetSet] = childElements(element).filter((child) => canonical(child) === 'simplematchset');\n\t\t\t\tsources = choicesIn(sourceSet, pairing.sources, canonical);\n\t\t\t\ttargets = choicesIn(targetSet, pairing.sources, canonical);\n\t\t\t} else {\n\t\t\t\tsources = choicesIn(element, pairing.sources, canonical);\n\t\t\t\ttargets = pairing.targets ? choicesIn(element, pairing.targets, canonical) : sources;\n\t\t\t}\n\t\t\tconst authored = [...sources.values(), ...targets.values()].some((choice) => choice.matchGroup.length > 0);\n\t\t\tif (authored) constraints.set(responseIdentifier, { directed: pairing.directed, sources, targets });\n\t\t}\n\t\tfor (const child of childElements(element)) visit(child);\n\t};\n\tvisit(item);\n\treturn constraints;\n}\n\nfunction choicesIn(\n\troot: Element | undefined,\n\tnames: readonly string[],\n\tcanonical: (element: Element) => string,\n): Map<string, MatchGroupChoice> {\n\tconst choices = new Map<string, MatchGroupChoice>();\n\tconst visit = (element: Element): void => {\n\t\tif (names.includes(canonical(element))) {\n\t\t\tconst identifier = getAttr(element, 'identifier')?.trim();\n\t\t\tif (identifier) {\n\t\t\t\tconst matchGroup = (getAttr(element, 'matchGroup') ?? '').split(/\\s+/).filter(Boolean);\n\t\t\t\tchoices.set(identifier, Object.freeze({ identifier, matchGroup: Object.freeze(matchGroup) }));\n\t\t\t}\n\t\t}\n\t\tfor (const child of childElements(element)) visit(child);\n\t};\n\tif (root) for (const child of childElements(root)) visit(child);\n\treturn choices;\n}\n"]}
@@ -0,0 +1,35 @@
1
+ import { type AttributeNameMapper, type ElementNameMapper, type QtiVersion } from '@pie-qti/qti-common';
2
+ /**
3
+ * The player's one name-mapper resolution.
4
+ *
5
+ * An unknown (or any non-3.0) version maps to QTI 2.x, the primary supported
6
+ * format. Explicitly passed mappers always win over version-derived ones; the
7
+ * `createExtractionUtils()` default stays QTI 2.x regardless of the item's
8
+ * version (extractors ask for their own mapper explicitly when they need one).
9
+ */
10
+ /** The element name mapper for a QTI version: `'3.0'` maps QTI 3.0 names, anything else to QTI 2.x. */
11
+ export declare function elementNameMapperForVersion(version: QtiVersion | string): ElementNameMapper;
12
+ /** The attribute name mapper for a QTI version, with the same version rule. */
13
+ export declare function attributeNameMapperForVersion(version: QtiVersion | string): AttributeNameMapper;
14
+ /**
15
+ * The mapper pair for a compiled item definition: explicitly passed mappers
16
+ * win; each missing one comes from the version detected from the item XML (an
17
+ * unknown version maps to QTI 2.x). The definition's attribute mapper follows
18
+ * the detected version, not the element mapper's.
19
+ */
20
+ export declare function resolveNameMappers(config: {
21
+ itemXml?: string;
22
+ elementNameMapper?: ElementNameMapper;
23
+ attributeNameMapper?: AttributeNameMapper;
24
+ }): {
25
+ elementNameMapper: ElementNameMapper;
26
+ attributeNameMapper: AttributeNameMapper;
27
+ };
28
+ /**
29
+ * The mappers extraction helpers resolve names with when the caller passes
30
+ * none: QTI 2.x, whatever version the extracted markup is.
31
+ */
32
+ export declare function defaultExtractionMappers(mapper?: ElementNameMapper, attributeMapper?: AttributeNameMapper): {
33
+ elementMapper: ElementNameMapper;
34
+ attrMapper: AttributeNameMapper;
35
+ };
@@ -0,0 +1,47 @@
1
+ import { detectQtiVersion, Qti2xAttributeNameMapper, Qti2xElementNameMapper, Qti3AttributeNameMapper, Qti3ElementNameMapper, } from '@pie-qti/qti-common';
2
+ /**
3
+ * The player's one name-mapper resolution.
4
+ *
5
+ * An unknown (or any non-3.0) version maps to QTI 2.x, the primary supported
6
+ * format. Explicitly passed mappers always win over version-derived ones; the
7
+ * `createExtractionUtils()` default stays QTI 2.x regardless of the item's
8
+ * version (extractors ask for their own mapper explicitly when they need one).
9
+ */
10
+ /** The element name mapper for a QTI version: `'3.0'` maps QTI 3.0 names, anything else to QTI 2.x. */
11
+ export function elementNameMapperForVersion(version) {
12
+ return version === '3.0' ? new Qti3ElementNameMapper() : new Qti2xElementNameMapper();
13
+ }
14
+ /** The attribute name mapper for a QTI version, with the same version rule. */
15
+ export function attributeNameMapperForVersion(version) {
16
+ return version === '3.0' ? new Qti3AttributeNameMapper() : new Qti2xAttributeNameMapper();
17
+ }
18
+ /**
19
+ * The mapper pair for a compiled item definition: explicitly passed mappers
20
+ * win; each missing one comes from the version detected from the item XML (an
21
+ * unknown version maps to QTI 2.x). The definition's attribute mapper follows
22
+ * the detected version, not the element mapper's.
23
+ */
24
+ export function resolveNameMappers(config) {
25
+ if (config.elementNameMapper && config.attributeNameMapper) {
26
+ return {
27
+ elementNameMapper: config.elementNameMapper,
28
+ attributeNameMapper: config.attributeNameMapper,
29
+ };
30
+ }
31
+ const version = detectQtiVersion(config.itemXml ?? '');
32
+ return {
33
+ elementNameMapper: config.elementNameMapper ?? elementNameMapperForVersion(version),
34
+ attributeNameMapper: config.attributeNameMapper ?? attributeNameMapperForVersion(version),
35
+ };
36
+ }
37
+ /**
38
+ * The mappers extraction helpers resolve names with when the caller passes
39
+ * none: QTI 2.x, whatever version the extracted markup is.
40
+ */
41
+ export function defaultExtractionMappers(mapper, attributeMapper) {
42
+ return {
43
+ elementMapper: mapper ?? new Qti2xElementNameMapper(),
44
+ attrMapper: attributeMapper ?? new Qti2xAttributeNameMapper(),
45
+ };
46
+ }
47
+ //# sourceMappingURL=nameMappers.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"nameMappers.js","sourceRoot":"","sources":["../../src/core/nameMappers.ts"],"names":[],"mappings":"AAAA,OAAO,EAEN,gBAAgB,EAEhB,wBAAwB,EACxB,sBAAsB,EACtB,uBAAuB,EACvB,qBAAqB,GAErB,MAAM,qBAAqB,CAAC;AAE7B;;;;;;;GAOG;AAEH,uGAAuG;AACvG,MAAM,UAAU,2BAA2B,CAAC,OAA4B;IACvE,OAAO,OAAO,KAAK,KAAK,CAAC,CAAC,CAAC,IAAI,qBAAqB,EAAE,CAAC,CAAC,CAAC,IAAI,sBAAsB,EAAE,CAAC;AACvF,CAAC;AAED,+EAA+E;AAC/E,MAAM,UAAU,6BAA6B,CAAC,OAA4B;IACzE,OAAO,OAAO,KAAK,KAAK,CAAC,CAAC,CAAC,IAAI,uBAAuB,EAAE,CAAC,CAAC,CAAC,IAAI,wBAAwB,EAAE,CAAC;AAC3F,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,kBAAkB,CAAC,MAIlC;IACA,IAAI,MAAM,CAAC,iBAAiB,IAAI,MAAM,CAAC,mBAAmB,EAAE,CAAC;QAC5D,OAAO;YACN,iBAAiB,EAAE,MAAM,CAAC,iBAAiB;YAC3C,mBAAmB,EAAE,MAAM,CAAC,mBAAmB;SAC/C,CAAC;IACH,CAAC;IAED,MAAM,OAAO,GAAG,gBAAgB,CAAC,MAAM,CAAC,OAAO,IAAI,EAAE,CAAC,CAAC;IACvD,OAAO;QACN,iBAAiB,EAAE,MAAM,CAAC,iBAAiB,IAAI,2BAA2B,CAAC,OAAO,CAAC;QACnF,mBAAmB,EAAE,MAAM,CAAC,mBAAmB,IAAI,6BAA6B,CAAC,OAAO,CAAC;KACzF,CAAC;AACH,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,wBAAwB,CACvC,MAA0B,EAC1B,eAAqC;IAErC,OAAO;QACN,aAAa,EAAE,MAAM,IAAI,IAAI,sBAAsB,EAAE;QACrD,UAAU,EAAE,eAAe,IAAI,IAAI,wBAAwB,EAAE;KAC7D,CAAC;AACH,CAAC","sourcesContent":["import {\n\ttype AttributeNameMapper,\n\tdetectQtiVersion,\n\ttype ElementNameMapper,\n\tQti2xAttributeNameMapper,\n\tQti2xElementNameMapper,\n\tQti3AttributeNameMapper,\n\tQti3ElementNameMapper,\n\ttype QtiVersion,\n} from '@pie-qti/qti-common';\n\n/**\n * The player's one name-mapper resolution.\n *\n * An unknown (or any non-3.0) version maps to QTI 2.x, the primary supported\n * format. Explicitly passed mappers always win over version-derived ones; the\n * `createExtractionUtils()` default stays QTI 2.x regardless of the item's\n * version (extractors ask for their own mapper explicitly when they need one).\n */\n\n/** The element name mapper for a QTI version: `'3.0'` maps QTI 3.0 names, anything else to QTI 2.x. */\nexport function elementNameMapperForVersion(version: QtiVersion | string): ElementNameMapper {\n\treturn version === '3.0' ? new Qti3ElementNameMapper() : new Qti2xElementNameMapper();\n}\n\n/** The attribute name mapper for a QTI version, with the same version rule. */\nexport function attributeNameMapperForVersion(version: QtiVersion | string): AttributeNameMapper {\n\treturn version === '3.0' ? new Qti3AttributeNameMapper() : new Qti2xAttributeNameMapper();\n}\n\n/**\n * The mapper pair for a compiled item definition: explicitly passed mappers\n * win; each missing one comes from the version detected from the item XML (an\n * unknown version maps to QTI 2.x). The definition's attribute mapper follows\n * the detected version, not the element mapper's.\n */\nexport function resolveNameMappers(config: {\n\titemXml?: string;\n\telementNameMapper?: ElementNameMapper;\n\tattributeNameMapper?: AttributeNameMapper;\n}): { elementNameMapper: ElementNameMapper; attributeNameMapper: AttributeNameMapper } {\n\tif (config.elementNameMapper && config.attributeNameMapper) {\n\t\treturn {\n\t\t\telementNameMapper: config.elementNameMapper,\n\t\t\tattributeNameMapper: config.attributeNameMapper,\n\t\t};\n\t}\n\n\tconst version = detectQtiVersion(config.itemXml ?? '');\n\treturn {\n\t\telementNameMapper: config.elementNameMapper ?? elementNameMapperForVersion(version),\n\t\tattributeNameMapper: config.attributeNameMapper ?? attributeNameMapperForVersion(version),\n\t};\n}\n\n/**\n * The mappers extraction helpers resolve names with when the caller passes\n * none: QTI 2.x, whatever version the extracted markup is.\n */\nexport function defaultExtractionMappers(\n\tmapper?: ElementNameMapper,\n\tattributeMapper?: AttributeNameMapper,\n): { elementMapper: ElementNameMapper; attrMapper: AttributeNameMapper } {\n\treturn {\n\t\telementMapper: mapper ?? new Qti2xElementNameMapper(),\n\t\tattrMapper: attributeMapper ?? new Qti2xAttributeNameMapper(),\n\t};\n}\n"]}
@@ -7,5 +7,9 @@ export type NormalizedParsingLimits = {
7
7
  maxHtmlNodes: number;
8
8
  maxHtmlDepth: number;
9
9
  };
10
+ /**
11
+ * The parsing limits in force: on unless the host opts out with `parsingLimits.enabled: false`,
12
+ * each limit taken from the config or its default.
13
+ */
10
14
  export declare function normalizeParsingLimits(security?: PlayerSecurityConfig): NormalizedParsingLimits;
11
15
  export declare function enforceItemXmlLimits(itemXml: string, security?: PlayerSecurityConfig): void;
@@ -13,10 +13,13 @@ function getByteLengthUtf8(s) {
13
13
  return s.length * 2;
14
14
  return new TE().encode(s).byteLength;
15
15
  }
16
+ /**
17
+ * The parsing limits in force: on unless the host opts out with `parsingLimits.enabled: false`,
18
+ * each limit taken from the config or its default.
19
+ */
16
20
  export function normalizeParsingLimits(security) {
17
21
  const cfg = security?.parsingLimits;
18
- const enabled = cfg?.enabled === true;
19
- if (!enabled) {
22
+ if (cfg?.enabled === false) {
20
23
  return { enabled: false, ...DEFAULTS };
21
24
  }
22
25
  return {
@@ -1 +1 @@
1
- {"version":3,"file":"parsingLimits.js","sourceRoot":"","sources":["../../src/core/parsingLimits.ts"],"names":[],"mappings":"AAWA,MAAM,QAAQ,GAA6C;IAC1D,aAAa,EAAE,IAAI;IACnB,eAAe,EAAE,QAAU;IAC3B,YAAY,EAAE,OAAS;IACvB,YAAY,EAAE,MAAO;IACrB,YAAY,EAAE,GAAG;CACjB,CAAC;AAEF,SAAS,iBAAiB,CAAC,CAAS;IACnC,wEAAwE;IACxE,4DAA4D;IAC5D,MAAM,EAAE,GAAoC,UAAkB,CAAC,WAAW,CAAC;IAC3E,IAAI,CAAC,EAAE;QAAE,OAAO,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC;IAC7B,OAAO,IAAI,EAAE,EAAE,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC;AACtC,CAAC;AAED,MAAM,UAAU,sBAAsB,CAAC,QAA+B;IACrE,MAAM,GAAG,GAAG,QAAQ,EAAE,aAAa,CAAC;IACpC,MAAM,OAAO,GAAG,GAAG,EAAE,OAAO,KAAK,IAAI,CAAC;IACtC,IAAI,CAAC,OAAO,EAAE,CAAC;QACd,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,GAAG,QAAQ,EAAE,CAAC;IACxC,CAAC;IAED,OAAO;QACN,OAAO,EAAE,IAAI;QACb,aAAa,EAAE,GAAG,EAAE,aAAa,IAAI,QAAQ,CAAC,aAAa;QAC3D,eAAe,EAAE,GAAG,EAAE,eAAe,IAAI,QAAQ,CAAC,eAAe;QACjE,YAAY,EAAE,GAAG,EAAE,YAAY,IAAI,QAAQ,CAAC,YAAY;QACxD,YAAY,EAAE,GAAG,EAAE,YAAY,IAAI,QAAQ,CAAC,YAAY;QACxD,YAAY,EAAE,GAAG,EAAE,YAAY,IAAI,QAAQ,CAAC,YAAY;KACxD,CAAC;AACH,CAAC;AAED,MAAM,UAAU,oBAAoB,CAAC,OAAe,EAAE,QAA+B;IACpF,MAAM,MAAM,GAAG,sBAAsB,CAAC,QAAQ,CAAC,CAAC;IAChD,IAAI,CAAC,MAAM,CAAC,OAAO;QAAE,OAAO;IAE5B,MAAM,KAAK,GAAG,iBAAiB,CAAC,MAAM,CAAC,OAAO,IAAI,EAAE,CAAC,CAAC,CAAC;IACvD,IAAI,KAAK,GAAG,MAAM,CAAC,eAAe,EAAE,CAAC;QACpC,MAAM,IAAI,KAAK,CAAC,oCAAoC,KAAK,MAAM,MAAM,CAAC,eAAe,GAAG,CAAC,CAAC;IAC3F,CAAC;IAED,IAAI,MAAM,CAAC,aAAa,EAAE,CAAC;QAC1B,2DAA2D;QAC3D,IAAI,eAAe,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC;YACnC,MAAM,IAAI,KAAK,CAAC,iEAAiE,CAAC,CAAC;QACpF,CAAC;IACF,CAAC;AACF,CAAC","sourcesContent":["import type { PlayerSecurityConfig } from '../types/index.js';\n\nexport type NormalizedParsingLimits = {\n\tenabled: boolean;\n\trejectDoctype: boolean;\n\tmaxItemXmlBytes: number;\n\tmaxHtmlBytes: number;\n\tmaxHtmlNodes: number;\n\tmaxHtmlDepth: number;\n};\n\nconst DEFAULTS: Omit<NormalizedParsingLimits, 'enabled'> = {\n\trejectDoctype: true,\n\tmaxItemXmlBytes: 10_000_000,\n\tmaxHtmlBytes: 5_000_000,\n\tmaxHtmlNodes: 200_000,\n\tmaxHtmlDepth: 200,\n};\n\nfunction getByteLengthUtf8(s: string): number {\n\t// TextEncoder is available in modern runtimes (browser + Bun/node 20+).\n\t// Fall back to a conservative approximation if unavailable.\n\tconst TE: typeof TextEncoder | undefined = (globalThis as any).TextEncoder;\n\tif (!TE) return s.length * 2;\n\treturn new TE().encode(s).byteLength;\n}\n\nexport function normalizeParsingLimits(security?: PlayerSecurityConfig): NormalizedParsingLimits {\n\tconst cfg = security?.parsingLimits;\n\tconst enabled = cfg?.enabled === true;\n\tif (!enabled) {\n\t\treturn { enabled: false, ...DEFAULTS };\n\t}\n\n\treturn {\n\t\tenabled: true,\n\t\trejectDoctype: cfg?.rejectDoctype ?? DEFAULTS.rejectDoctype,\n\t\tmaxItemXmlBytes: cfg?.maxItemXmlBytes ?? DEFAULTS.maxItemXmlBytes,\n\t\tmaxHtmlBytes: cfg?.maxHtmlBytes ?? DEFAULTS.maxHtmlBytes,\n\t\tmaxHtmlNodes: cfg?.maxHtmlNodes ?? DEFAULTS.maxHtmlNodes,\n\t\tmaxHtmlDepth: cfg?.maxHtmlDepth ?? DEFAULTS.maxHtmlDepth,\n\t};\n}\n\nexport function enforceItemXmlLimits(itemXml: string, security?: PlayerSecurityConfig): void {\n\tconst limits = normalizeParsingLimits(security);\n\tif (!limits.enabled) return;\n\n\tconst bytes = getByteLengthUtf8(String(itemXml ?? ''));\n\tif (bytes > limits.maxItemXmlBytes) {\n\t\tthrow new Error(`itemXml exceeds maxItemXmlBytes (${bytes} > ${limits.maxItemXmlBytes})`);\n\t}\n\n\tif (limits.rejectDoctype) {\n\t\t// Case-insensitive and tolerant of whitespace: \"<!DOCTYPE\"\n\t\tif (/<!\\s*doctype/i.test(itemXml)) {\n\t\t\tthrow new Error('itemXml contains <!DOCTYPE>, which is rejected by parsingLimits');\n\t\t}\n\t}\n}\n\n\n"]}
1
+ {"version":3,"file":"parsingLimits.js","sourceRoot":"","sources":["../../src/core/parsingLimits.ts"],"names":[],"mappings":"AAWA,MAAM,QAAQ,GAA6C;IAC1D,aAAa,EAAE,IAAI;IACnB,eAAe,EAAE,QAAU;IAC3B,YAAY,EAAE,OAAS;IACvB,YAAY,EAAE,MAAO;IACrB,YAAY,EAAE,GAAG;CACjB,CAAC;AAEF,SAAS,iBAAiB,CAAC,CAAS;IACnC,wEAAwE;IACxE,4DAA4D;IAC5D,MAAM,EAAE,GAAoC,UAAkB,CAAC,WAAW,CAAC;IAC3E,IAAI,CAAC,EAAE;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AAO,CAAC,EAAE,CAAC;YACnC,MAAM,IAAI,KAAK,CAAC,iEAAiE,CAAC,CAAC;QACpF,CAAC;IACF,CAAC;AACF,CAAC","sourcesContent":["import type { PlayerSecurityConfig } from '../types/index.js';\n\nexport type NormalizedParsingLimits = {\n\tenabled: boolean;\n\trejectDoctype: boolean;\n\tmaxItemXmlBytes: number;\n\tmaxHtmlBytes: number;\n\tmaxHtmlNodes: number;\n\tmaxHtmlDepth: number;\n};\n\nconst DEFAULTS: Omit<NormalizedParsingLimits, 'enabled'> = {\n\trejectDoctype: true,\n\tmaxItemXmlBytes: 10_000_000,\n\tmaxHtmlBytes: 5_000_000,\n\tmaxHtmlNodes: 200_000,\n\tmaxHtmlDepth: 200,\n};\n\nfunction getByteLengthUtf8(s: string): number {\n\t// TextEncoder is available in modern runtimes (browser + Bun/node 20+).\n\t// Fall back to a conservative approximation if unavailable.\n\tconst TE: typeof TextEncoder | undefined = (globalThis as any).TextEncoder;\n\tif (!TE) return s.length * 2;\n\treturn new TE().encode(s).byteLength;\n}\n\n/**\n * The parsing limits in force: on unless the host opts out with `parsingLimits.enabled: false`,\n * each limit taken from the config or its default.\n */\nexport function normalizeParsingLimits(security?: PlayerSecurityConfig): NormalizedParsingLimits {\n\tconst cfg = security?.parsingLimits;\n\tif (cfg?.enabled === false) {\n\t\treturn { enabled: false, ...DEFAULTS };\n\t}\n\n\treturn {\n\t\tenabled: true,\n\t\trejectDoctype: cfg?.rejectDoctype ?? DEFAULTS.rejectDoctype,\n\t\tmaxItemXmlBytes: cfg?.maxItemXmlBytes ?? DEFAULTS.maxItemXmlBytes,\n\t\tmaxHtmlBytes: cfg?.maxHtmlBytes ?? DEFAULTS.maxHtmlBytes,\n\t\tmaxHtmlNodes: cfg?.maxHtmlNodes ?? DEFAULTS.maxHtmlNodes,\n\t\tmaxHtmlDepth: cfg?.maxHtmlDepth ?? DEFAULTS.maxHtmlDepth,\n\t};\n}\n\nexport function enforceItemXmlLimits(itemXml: string, security?: PlayerSecurityConfig): void {\n\tconst limits = normalizeParsingLimits(security);\n\tif (!limits.enabled) return;\n\n\tconst bytes = getByteLengthUtf8(String(itemXml ?? ''));\n\tif (bytes > limits.maxItemXmlBytes) {\n\t\tthrow new Error(`itemXml exceeds maxItemXmlBytes (${bytes} > ${limits.maxItemXmlBytes})`);\n\t}\n\n\tif (limits.rejectDoctype) {\n\t\t// Case-insensitive and tolerant of whitespace: \"<!DOCTYPE\"\n\t\tif (/<!\\s*doctype/i.test(itemXml)) {\n\t\t\tthrow new Error('itemXml contains <!DOCTYPE>, which is rejected by parsingLimits');\n\t\t}\n\t}\n}\n\n\n"]}
@@ -0,0 +1,88 @@
1
+ /**
2
+ * Response, template and outcome processing execution: the evaluator environment,
3
+ * the compiled program runs, the standard response-processing templates, the variable
4
+ * resets a new template instance starts from, and the scoring result assembly.
5
+ */
6
+ import { type DeclarationMap, DeclarationContext, type ProcessingProgram, type QtiValue } from '@pie-qti/qti-processing';
7
+ import type { AssessmentItemDocument, ResponseProcessingDescriptor } from '../../document/AssessmentItemDocument.js';
8
+ import { UnsupportedResponseProcessingTemplateError } from '../responseProcessingTemplates.js';
9
+ import type { ItemSessionEngineConfig, ModalFeedback, ScoringResult } from '../../types/index.js';
10
+ /** What response processing execution reads from the session engine. */
11
+ export interface ResponseProcessingHost {
12
+ readonly itemDocument: AssessmentItemDocument;
13
+ readonly config: ItemSessionEngineConfig;
14
+ readonly decls: DeclarationMap;
15
+ /** The declarations as compiled from the item source, before any template rule changed them. */
16
+ readonly sourceDeclarations: DeclarationMap;
17
+ readonly ctx: DeclarationContext;
18
+ readonly rng: () => number;
19
+ readonly responseProcessing: ResponseProcessingDescriptor;
20
+ readonly responseProcessingProgram: ProcessingProgram | null;
21
+ readonly templateProcessingProgram: ProcessingProgram | null;
22
+ readonly outcomeProcessingProgram: ProcessingProgram | null;
23
+ /**
24
+ * End-attempt responses the candidate turned true since the attempt last ended; a response
25
+ * reset to its default also deactivates (see resetResponsesToDefault).
26
+ */
27
+ readonly endAttemptActivations: Set<string>;
28
+ /** Set once the implied-zero MAXSCORE warning has fired. */
29
+ warnedImpliedZeroMaxScore: boolean;
30
+ isAdaptive(): boolean;
31
+ getNumAttempts(): number;
32
+ getContentLanguage(): string | undefined;
33
+ updateDuration(): void;
34
+ restorePciResponse(responseIdentifier: string, value: unknown): void;
35
+ qtiValueToPci(value: QtiValue | undefined): unknown;
36
+ qtiValueToPublic(value: QtiValue | undefined): any;
37
+ getModalFeedback(outcomes: Record<string, any>): ModalFeedback[];
38
+ }
39
+ /**
40
+ * The evaluator's environment, which reads responses in the item's content language and
41
+ * compares strings with the host's string comparison folds.
42
+ */
43
+ export declare function processingEnv(host: ResponseProcessingHost): {
44
+ ctx: DeclarationContext;
45
+ rng: () => number;
46
+ language: string | undefined;
47
+ stringComparison: import("@pie-qti/qti-processing").StringComparisonOptions | undefined;
48
+ customOperators: Record<string, (args: QtiValue[], meta: {
49
+ class?: string;
50
+ definition?: string;
51
+ }) => QtiValue> | undefined;
52
+ };
53
+ export declare function execTemplateProcessingProgram(host: ResponseProcessingHost): void;
54
+ export declare function execResponseProcessingProgram(host: ResponseProcessingHost): void;
55
+ export declare function execOutcomeProcessingProgram(host: ResponseProcessingHost): void;
56
+ export declare function execResponseProcessingTemplate(host: ResponseProcessingHost, templateUrl: string): void;
57
+ /**
58
+ * A template reference is the item's only scoring rule when responseProcessing has no rules of
59
+ * its own. Without a built-in program for that template the item would score its defaults
60
+ * silently, so compilation fails instead (docs/SPEC-GAPS-PLAN.md G-19).
61
+ */
62
+ export declare function assertSupportedResponseProcessing(host: ResponseProcessingHost): void;
63
+ export declare function unsupportedTemplateError(host: ResponseProcessingHost, templateUri: string): UnsupportedResponseProcessingTemplateError;
64
+ export declare function resetOutcomesToDefault(host: ResponseProcessingHost): void;
65
+ export declare function resetResponsesToDefault(host: ResponseProcessingHost): void;
66
+ export declare function resetTemplatesToDefault(host: ResponseProcessingHost): void;
67
+ /**
68
+ * QTI ASI §10.3 with §5.1: template processing runs on a fresh instance of the item, so a new
69
+ * template instance starts from the declarations, not from the instance before it. The
70
+ * template rules setDefaultValue and setCorrectResponse change response and outcome
71
+ * declarations for one instance; their declared defaults and correct responses come back
72
+ * here, before the variables reset and template processing runs again. Template variables
73
+ * keep their defaults: template rules do not change them, and they hold the
74
+ * assessmentItemRef's templateDefault values (applied at session start, carried by a
75
+ * snapshot), which apply to every instance.
76
+ */
77
+ export declare function restoreDeclaredTemplateRuleTargets(host: ResponseProcessingHost): void;
78
+ export declare function runResponseProcessing(host: ResponseProcessingHost, options: {
79
+ finalizeNonAdaptiveAttempt: boolean;
80
+ countAttempt?: boolean;
81
+ }): ScoringResult;
82
+ /**
83
+ * QTI item correctness, as test-level `numberCorrect` reads it: every declared response matches
84
+ * its correct response. Undefined when the item has no response or one declares no correct
85
+ * response.
86
+ */
87
+ export declare function responsesMatchCorrect(host: ResponseProcessingHost): boolean | undefined;
88
+ export declare function collectOutcomes(host: ResponseProcessingHost): Record<string, unknown>;