@pie-qti/item-player 1.0.0-beta.4 → 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 (294) 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 -14
  273. package/dist/components/utils/stimulusRender.js.map +0 -1
  274. package/dist/components/utils/stylesheetRender.js.map +0 -1
  275. package/dist/core/constants.d.ts +0 -65
  276. package/dist/core/constants.js +0 -74
  277. package/dist/core/constants.js.map +0 -1
  278. package/dist/element-class-DdpiTalY.js +0 -9226
  279. package/dist/element-class-DdpiTalY.js.map +0 -1
  280. package/dist/extensions/MathLiveEditor.d.ts +0 -31
  281. package/dist/extensions/MathLiveEditor.js +0 -248
  282. package/dist/extensions/MathLiveEditor.js.map +0 -1
  283. package/dist/utils/PerformanceMonitor.d.ts +0 -169
  284. package/dist/utils/PerformanceMonitor.js +0 -243
  285. package/dist/utils/PerformanceMonitor.js.map +0 -1
  286. package/dist/utils/responseUtils.d.ts +0 -15
  287. package/dist/utils/responseUtils.js +0 -46
  288. package/dist/utils/responseUtils.js.map +0 -1
  289. package/dist/web-components/QTIInteractionBase.d.ts +0 -119
  290. package/dist/web-components/QTIInteractionBase.js +0 -244
  291. package/dist/web-components/QTIInteractionBase.js.map +0 -1
  292. /package/dist/{components/utils → presentation}/stimulusRender.d.ts +0 -0
  293. /package/dist/{components/utils → presentation}/stylesheetRender.d.ts +0 -0
  294. /package/dist/{components/utils → presentation}/stylesheetRender.js +0 -0
@@ -0,0 +1,139 @@
1
+ /**
2
+ * Session-state persistence: the serialized snapshot a host stores and restores, the
3
+ * variable application that hydrates a restored session, and the duration clock that
4
+ * feeds the built-in `duration` variable and the host-facing millisecond fields.
5
+ */
6
+ import { durationSecondsFromMilliseconds, qtiValue } from '@pie-qti/qti-processing';
7
+ import { coerceToDeclarationValue } from '../declarations/declarationValues.js';
8
+ import { qtiValueToPci, qtiValueToSerializable } from './valueForms.js';
9
+ /**
10
+ * The QTI ASI built-in variables the session reports as context state — in the serializer's
11
+ * `contextVariables` record and `ItemSessionView.context` — alongside any declared context
12
+ * variables. `duration` moves on every dispatch, `completionStatus` and `numAttempts` at
13
+ * attempt boundaries; the built-ins carry no declaration of their own kind, which is why the
14
+ * set is named here rather than derived.
15
+ */
16
+ export const BUILT_IN_CONTEXT_IDENTIFIERS = new Set([
17
+ 'completionStatus',
18
+ 'numAttempts',
19
+ 'duration',
20
+ ]);
21
+ /**
22
+ * Whether a variable serializes into the session's context record: a built-in context
23
+ * identifier (see {@link BUILT_IN_CONTEXT_IDENTIFIERS}) or a declared context variable.
24
+ * The serializer and the printed-content scan (Player.getContextIdentifiersPrintedInContent)
25
+ * must classify identically — the context record is what the presentation cache compares.
26
+ */
27
+ export function isContextSerialized(variable) {
28
+ if (!variable)
29
+ return false;
30
+ return (BUILT_IN_CONTEXT_IDENTIFIERS.has(variable.identifier) ||
31
+ variable.__kind === 'context');
32
+ }
33
+ export function serializeItemSession(host) {
34
+ const responseVariables = {};
35
+ const outcomeVariables = {};
36
+ const templateVariables = {};
37
+ const contextVariables = {};
38
+ for (const d of Object.values(host.decls)) {
39
+ const variable = serializeVariable(d);
40
+ if (d.isTemplate) {
41
+ templateVariables[d.identifier] = { ...variable, kind: 'template' };
42
+ }
43
+ else if (isContextSerialized(d)) {
44
+ contextVariables[d.identifier] = { ...variable, kind: 'context' };
45
+ }
46
+ else if (d.__kind === 'response') {
47
+ responseVariables[d.identifier] = { ...variable, kind: 'response' };
48
+ }
49
+ else if (d.__kind === 'outcome') {
50
+ outcomeVariables[d.identifier] = { ...variable, kind: 'outcome' };
51
+ }
52
+ }
53
+ const validation = host.validateResponses(host.responseSnapshot());
54
+ return {
55
+ itemIdentifier: host.itemDocument.getAssessmentItemAttribute('identifier') ?? undefined,
56
+ sessionGuid: host.sessionGuid,
57
+ lifecycleStatus: host.lifecycleStatus,
58
+ completionStatus: host.getCompletionStatus(),
59
+ numAttempts: host.getNumAttempts(),
60
+ duration: host.durationMs,
61
+ responseVariables,
62
+ outcomeVariables,
63
+ templateVariables,
64
+ contextVariables,
65
+ validationMessages: validation.issues,
66
+ savedAt: new Date().toISOString(),
67
+ };
68
+ }
69
+ export function applySerializedVariables(host, vars) {
70
+ for (const v of Object.values(vars)) {
71
+ const d = host.decls[v.identifier];
72
+ if (!d)
73
+ continue;
74
+ // Restore the declaration's default value first: template processing is
75
+ // skipped on restore (QTI ASI §10.3 fixes its effects for the session), so
76
+ // a default changed by setDefaultValue — including to NULL — must come from
77
+ // the snapshot. defaultValue is always serialized, so it applies as-is:
78
+ // null restores the NULL default a setDefaultValue rule set, never the
79
+ // default parsed from the item XML. Later resets (attempt starts, outcome
80
+ // resets at response-processing start, templateConstraint restarts) then
81
+ // use the restored default; a new template instance (newTemplate) starts
82
+ // from the declarations instead.
83
+ d.defaultValue = coerceToDeclarationValue({ itemDocument: host.itemDocument }, d.baseType, d.cardinality, v.defaultValue, d.identifier);
84
+ d.value = coerceToDeclarationValue({ itemDocument: host.itemDocument }, d.baseType, d.cardinality, v.value, d.identifier);
85
+ if (d.__kind === 'response') {
86
+ // A correctResponse computed by setCorrectResponse is also a fixed
87
+ // template-rule effect; restoring it keeps a resumed session scoring
88
+ // identically to the session that was saved. The snapshot writes the
89
+ // field whenever the variable has or had a correct response, so it
90
+ // applies as-is: null restores the NULL correct response a
91
+ // setCorrectResponse rule set. When the field is absent the variable
92
+ // has no correct response, and the fresh declaration (parsed from the
93
+ // same item XML) has none either.
94
+ if (v.correctResponse !== undefined) {
95
+ d.correctResponse = coerceToDeclarationValue({ itemDocument: host.itemDocument }, d.baseType, d.cardinality, v.correctResponse, d.identifier);
96
+ }
97
+ host.restorePciResponse(d.identifier, qtiValueToPci(d.value));
98
+ }
99
+ }
100
+ }
101
+ function serializeVariable(d) {
102
+ const variable = {
103
+ identifier: d.identifier,
104
+ kind: (d.__kind ?? (d.isTemplate ? 'template' : 'context')),
105
+ ...(d.baseType ? { baseType: d.baseType } : {}),
106
+ cardinality: d.cardinality,
107
+ value: qtiValueToSerializable(d.value),
108
+ defaultValue: qtiValueToSerializable(d.defaultValue),
109
+ };
110
+ // A correctResponse is part of the session state a template rule
111
+ // (setCorrectResponse, QTI ASI §10.3) can compute, so it must survive a
112
+ // snapshot for the restored session to score identically. Written whenever
113
+ // the variable has or had a correct response — from the XML or from template
114
+ // processing — with null for a NULL correct response, so restore can tell
115
+ // "no correct response" (field absent) from "its correct response is NULL".
116
+ if (d.__kind === 'response' && d.correctResponse !== undefined) {
117
+ variable.correctResponse = qtiValueToSerializable(d.correctResponse);
118
+ }
119
+ return variable;
120
+ }
121
+ export function updateDuration(host) {
122
+ const elapsedMs = Math.max(0, Date.now() - host.sessionStartedAt);
123
+ host.durationMs = Math.max(0, Math.floor(host.accumulatedDurationMs + elapsedMs));
124
+ // QTI 2.2/3.0: the built-in `duration` response variable is a float of seconds, truncated.
125
+ // The host-facing `duration` fields of serialized sessions and action results stay in
126
+ // milliseconds (see getDuration).
127
+ host.ctx.setValue('duration', qtiValue('duration', 'single', durationSecondsFromMilliseconds(host.durationMs)));
128
+ }
129
+ export function freezeDuration(host) {
130
+ updateDuration(host);
131
+ host.accumulatedDurationMs = host.durationMs;
132
+ host.sessionStartedAt = Date.now();
133
+ return host.durationMs;
134
+ }
135
+ /** Time on task in whole milliseconds, as the host-facing session fields report it. */
136
+ export function getDurationMs(host) {
137
+ return host.durationMs;
138
+ }
139
+ //# sourceMappingURL=sessionState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AACH,CAAC;AAED,MAAM,UAAU,cAAc,CAAC,IAAuB;IACrD,cAAc,CAAC,IAAI,CAAC,CAAC;IACrB,IAAI,CAAC,qBAAqB,GAAG,IAAI,CAAC,UAAU,CAAC;IAC7C,IAAI,CAAC,gBAAgB,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;IACnC,OAAO,IAAI,CAAC,UAAU,CAAC;AACxB,CAAC;AAED,uFAAuF;AACvF,MAAM,UAAU,aAAa,CAAC,IAAuB;IACpD,OAAO,IAAI,CAAC,UAAU,CAAC;AACxB,CAAC","sourcesContent":["/**\n * Session-state persistence: the serialized snapshot a host stores and restores, the\n * variable application that hydrates a restored session, and the duration clock that\n * feeds the built-in `duration` variable and the host-facing millisecond fields.\n */\nimport { type DeclarationContext, type DeclarationMap, durationSecondsFromMilliseconds, qtiValue } from '@pie-qti/qti-processing';\nimport type { AssessmentItemDocument } from '../../document/AssessmentItemDocument.js';\nimport type { ItemLifecycleStatus, SerializedItemSessionState, SerializedItemSessionVariable } from '../../types/index.js';\nimport { coerceToDeclarationValue } from '../declarations/declarationValues.js';\nimport { qtiValueToPci, qtiValueToSerializable } from './valueForms.js';\n\n/** What serialization reads from and writes to the session engine. */\nexport interface SerializationHost {\n\treadonly itemDocument: AssessmentItemDocument;\n\treadonly decls: DeclarationMap;\n\treadonly ctx: DeclarationContext;\n\treadonly sessionGuid: string;\n\tlifecycleStatus: ItemLifecycleStatus;\n\tgetCompletionStatus(): SerializedItemSessionState['completionStatus'];\n\tgetNumAttempts(): number;\n\t/**\n\t * The engine's current responses, stable within one response revision (the same record\n\t * the end-attempt gate reads, so their validations memoize together).\n\t */\n\tresponseSnapshot(): Record<string, any>;\n\tvalidateResponses(responses: Record<string, any>): { issues: SerializedItemSessionState['validationMessages'] };\n\trestorePciResponse(responseIdentifier: string, value: unknown): void;\n\t/** Time on task at the last duration update, in milliseconds. */\n\tdurationMs: number;\n\t/** Time on task accumulated before the current clock window, in milliseconds. */\n\taccumulatedDurationMs: number;\n\t/** When the current clock window started (Date.now() base). */\n\tsessionStartedAt: number;\n}\n\n/**\n * The QTI ASI built-in variables the session reports as context state — in the serializer's\n * `contextVariables` record and `ItemSessionView.context` — alongside any declared context\n * variables. `duration` moves on every dispatch, `completionStatus` and `numAttempts` at\n * attempt boundaries; the built-ins carry no declaration of their own kind, which is why the\n * set is named here rather than derived.\n */\nexport const BUILT_IN_CONTEXT_IDENTIFIERS: ReadonlySet<string> = new Set([\n\t'completionStatus',\n\t'numAttempts',\n\t'duration',\n]);\n\n/**\n * Whether a variable serializes into the session's context record: a built-in context\n * identifier (see {@link BUILT_IN_CONTEXT_IDENTIFIERS}) or a declared context variable.\n * The serializer and the printed-content scan (Player.getContextIdentifiersPrintedInContent)\n * must classify identically — the context record is what the presentation cache compares.\n */\nexport function isContextSerialized(variable: { identifier: string } | undefined): boolean {\n\tif (!variable) return false;\n\treturn (\n\t\tBUILT_IN_CONTEXT_IDENTIFIERS.has(variable.identifier) ||\n\t\t(variable as { __kind?: string }).__kind === 'context'\n\t);\n}\n\nexport function serializeItemSession(host: SerializationHost): SerializedItemSessionState {\n\tconst responseVariables: Record<string, SerializedItemSessionVariable> = {};\n\tconst outcomeVariables: Record<string, SerializedItemSessionVariable> = {};\n\tconst templateVariables: Record<string, SerializedItemSessionVariable> = {};\n\tconst contextVariables: Record<string, SerializedItemSessionVariable> = {};\n\n\tfor (const d of Object.values(host.decls)) {\n\t\tconst variable = serializeVariable(d);\n\t\tif (d.isTemplate) {\n\t\t\ttemplateVariables[d.identifier] = { ...variable, kind: 'template' };\n\t\t} else if (isContextSerialized(d)) {\n\t\t\tcontextVariables[d.identifier] = { ...variable, kind: 'context' };\n\t\t} else if ((d as any).__kind === 'response') {\n\t\t\tresponseVariables[d.identifier] = { ...variable, kind: 'response' };\n\t\t} else if ((d as any).__kind === 'outcome') {\n\t\t\toutcomeVariables[d.identifier] = { ...variable, kind: 'outcome' };\n\t\t}\n\t}\n\n\tconst validation = host.validateResponses(host.responseSnapshot());\n\treturn {\n\t\titemIdentifier: host.itemDocument.getAssessmentItemAttribute('identifier') ?? undefined,\n\t\tsessionGuid: host.sessionGuid,\n\t\tlifecycleStatus: host.lifecycleStatus,\n\t\tcompletionStatus: host.getCompletionStatus(),\n\t\tnumAttempts: host.getNumAttempts(),\n\t\tduration: host.durationMs,\n\t\tresponseVariables,\n\t\toutcomeVariables,\n\t\ttemplateVariables,\n\t\tcontextVariables,\n\t\tvalidationMessages: validation.issues,\n\t\tsavedAt: new Date().toISOString(),\n\t};\n}\n\nexport function applySerializedVariables(host: SerializationHost, vars: Record<string, SerializedItemSessionVariable>): void {\n\tfor (const v of Object.values(vars)) {\n\t\tconst d = host.decls[v.identifier];\n\t\tif (!d) continue;\n\t\t// Restore the declaration's default value first: template processing is\n\t\t// skipped on restore (QTI ASI §10.3 fixes its effects for the session), so\n\t\t// a default changed by setDefaultValue — including to NULL — must come from\n\t\t// the snapshot. defaultValue is always serialized, so it applies as-is:\n\t\t// null restores the NULL default a setDefaultValue rule set, never the\n\t\t// default parsed from the item XML. Later resets (attempt starts, outcome\n\t\t// resets at response-processing start, templateConstraint restarts) then\n\t\t// use the restored default; a new template instance (newTemplate) starts\n\t\t// from the declarations instead.\n\t\td.defaultValue = coerceToDeclarationValue({ itemDocument: host.itemDocument }, d.baseType, d.cardinality, v.defaultValue, d.identifier);\n\t\td.value = coerceToDeclarationValue({ itemDocument: host.itemDocument }, d.baseType, d.cardinality, v.value, d.identifier);\n\t\tif ((d as any).__kind === 'response') {\n\t\t\t// A correctResponse computed by setCorrectResponse is also a fixed\n\t\t\t// template-rule effect; restoring it keeps a resumed session scoring\n\t\t\t// identically to the session that was saved. The snapshot writes the\n\t\t\t// field whenever the variable has or had a correct response, so it\n\t\t\t// applies as-is: null restores the NULL correct response a\n\t\t\t// setCorrectResponse rule set. When the field is absent the variable\n\t\t\t// has no correct response, and the fresh declaration (parsed from the\n\t\t\t// same item XML) has none either.\n\t\t\tif (v.correctResponse !== undefined) {\n\t\t\t\td.correctResponse = coerceToDeclarationValue({ itemDocument: host.itemDocument }, d.baseType, d.cardinality, v.correctResponse, d.identifier);\n\t\t\t}\n\t\t\thost.restorePciResponse(d.identifier, qtiValueToPci(d.value));\n\t\t}\n\t}\n}\n\nfunction serializeVariable(d: DeclarationMap[string]): SerializedItemSessionVariable {\n\tconst variable: SerializedItemSessionVariable = {\n\t\tidentifier: d.identifier,\n\t\tkind: ((d as any).__kind ?? (d.isTemplate ? 'template' : 'context')) as SerializedItemSessionVariable['kind'],\n\t\t...(d.baseType ? { baseType: d.baseType } : {}),\n\t\tcardinality: d.cardinality,\n\t\tvalue: qtiValueToSerializable(d.value),\n\t\tdefaultValue: qtiValueToSerializable(d.defaultValue),\n\t};\n\t// A correctResponse is part of the session state a template rule\n\t// (setCorrectResponse, QTI ASI §10.3) can compute, so it must survive a\n\t// snapshot for the restored session to score identically. Written whenever\n\t// the variable has or had a correct response — from the XML or from template\n\t// processing — with null for a NULL correct response, so restore can tell\n\t// \"no correct response\" (field absent) from \"its correct response is NULL\".\n\tif ((d as any).__kind === 'response' && d.correctResponse !== undefined) {\n\t\tvariable.correctResponse = qtiValueToSerializable(d.correctResponse);\n\t}\n\treturn variable;\n}\n\nexport function updateDuration(host: SerializationHost): void {\n\tconst elapsedMs = Math.max(0, Date.now() - host.sessionStartedAt);\n\thost.durationMs = Math.max(0, Math.floor(host.accumulatedDurationMs + elapsedMs));\n\t// QTI 2.2/3.0: the built-in `duration` response variable is a float of seconds, truncated.\n\t// The host-facing `duration` fields of serialized sessions and action results stay in\n\t// milliseconds (see getDuration).\n\thost.ctx.setValue(\n\t\t'duration',\n\t\tqtiValue('duration', 'single', durationSecondsFromMilliseconds(host.durationMs)),\n\t);\n}\n\nexport function freezeDuration(host: SerializationHost): number {\n\tupdateDuration(host);\n\thost.accumulatedDurationMs = host.durationMs;\n\thost.sessionStartedAt = Date.now();\n\treturn host.durationMs;\n}\n\n/** Time on task in whole milliseconds, as the host-facing session fields report it. */\nexport function getDurationMs(host: SerializationHost): number {\n\treturn host.durationMs;\n}\n"]}
@@ -0,0 +1,32 @@
1
+ /**
2
+ * The value forms a session's variables take outside the engine: the serialized snapshot
3
+ * form (records keep each field's base type and cardinality), the public form (records as
4
+ * plain nested values), and the PCI form (the public value, except records, which keep
5
+ * their serialized form so a host can write them into QTI variable JSON).
6
+ */
7
+ import type { QtiValue } from '@pie-qti/qti-processing';
8
+ export declare function qtiValueToSerializable(value: QtiValue | undefined): any;
9
+ /**
10
+ * A value as a PCI host receives it: the public value, except that a record keeps each field's
11
+ * base type and cardinality (its serialized form). A record declaration types none of its
12
+ * fields, so the host could not write them into QTI variable JSON otherwise.
13
+ */
14
+ export declare function qtiValueToPci(value: QtiValue | undefined): unknown;
15
+ export declare function qtiValueToPublic(value: QtiValue | undefined): any;
16
+ /**
17
+ * Structural equality of two variable values, for change detection on reads that may write
18
+ * (a PCI-bound response adopting the mounted module's current response). Primitives compare
19
+ * with Object.is — so File, Blob and Trusted Types payloads compare by identity, which can
20
+ * only over-report a change, never miss one.
21
+ */
22
+ export declare function qtiValueEquals(a: QtiValue | undefined, b: QtiValue | undefined): boolean;
23
+ /**
24
+ * Structural equality of two public variable values (whatever qtiValueToPublic produced:
25
+ * null, primitives, arrays, plain records, and the occasional non-plain leaf such as a File
26
+ * or a drawing's typed arrays). Like payloadEquals for QtiValues, non-plain leaves compare
27
+ * by identity, which can only over-report a change, never miss one. A typed array diffs
28
+ * bytewise only while it is small; a large one (a canvas snapshot) reads as changed, because
29
+ * diffing one per keystroke would cost what the comparison exists to save, and re-rendering
30
+ * is always the safe reading.
31
+ */
32
+ export declare function plainValueEquals(a: unknown, b: unknown): boolean;
@@ -0,0 +1,112 @@
1
+ import { cloneValue } from '../../utils/cloneFreeze.js';
2
+ export function qtiValueToSerializable(value) {
3
+ if (!value || value.kind !== 'value')
4
+ return null;
5
+ if (value.cardinality !== 'record')
6
+ return cloneValue(value.value);
7
+ const serialized = {};
8
+ for (const [fieldIdentifier, fieldValue] of Object.entries(value.value)) {
9
+ serialized[fieldIdentifier] = {
10
+ ...(fieldValue.baseType ? { baseType: fieldValue.baseType } : {}),
11
+ cardinality: fieldValue.cardinality ?? 'single',
12
+ value: qtiValueToSerializable(fieldValue),
13
+ };
14
+ }
15
+ return serialized;
16
+ }
17
+ /**
18
+ * A value as a PCI host receives it: the public value, except that a record keeps each field's
19
+ * base type and cardinality (its serialized form). A record declaration types none of its
20
+ * fields, so the host could not write them into QTI variable JSON otherwise.
21
+ */
22
+ export function qtiValueToPci(value) {
23
+ return value?.kind === 'value' && value.cardinality === 'record'
24
+ ? qtiValueToSerializable(value)
25
+ : qtiValueToPublic(value);
26
+ }
27
+ export function qtiValueToPublic(value) {
28
+ if (!value || value.kind !== 'value')
29
+ return null;
30
+ if (value.cardinality !== 'record')
31
+ return cloneValue(value.value);
32
+ const record = {};
33
+ for (const [fieldIdentifier, fieldValue] of Object.entries(value.value)) {
34
+ record[fieldIdentifier] = qtiValueToPublic(fieldValue);
35
+ }
36
+ return record;
37
+ }
38
+ /**
39
+ * Structural equality of two variable values, for change detection on reads that may write
40
+ * (a PCI-bound response adopting the mounted module's current response). Primitives compare
41
+ * with Object.is — so File, Blob and Trusted Types payloads compare by identity, which can
42
+ * only over-report a change, never miss one.
43
+ */
44
+ export function qtiValueEquals(a, b) {
45
+ if (a === b)
46
+ return true;
47
+ if (!a || !b)
48
+ return false;
49
+ if (a.kind !== b.kind || a.baseType !== b.baseType || a.cardinality !== b.cardinality)
50
+ return false;
51
+ if (a.kind !== 'value' || b.kind !== 'value')
52
+ return true;
53
+ return payloadEquals(a.value, b.value);
54
+ }
55
+ function payloadEquals(a, b) {
56
+ if (a === b)
57
+ return true;
58
+ if (Array.isArray(a) && Array.isArray(b)) {
59
+ return a.length === b.length && a.every((item, index) => payloadEquals(item, b[index]));
60
+ }
61
+ if (a && b && typeof a === 'object' && typeof b === 'object') {
62
+ const ka = Object.keys(a);
63
+ const kb = Object.keys(b);
64
+ if (ka.length !== kb.length)
65
+ return false;
66
+ return ka.every((key) => payloadEquals(a[key], b[key]));
67
+ }
68
+ return false;
69
+ }
70
+ /** Typed arrays up to this many bytes diff bytewise; larger ones read as changed. */
71
+ const TYPED_ARRAY_DIFF_LIMIT = 4096;
72
+ /**
73
+ * Structural equality of two public variable values (whatever qtiValueToPublic produced:
74
+ * null, primitives, arrays, plain records, and the occasional non-plain leaf such as a File
75
+ * or a drawing's typed arrays). Like payloadEquals for QtiValues, non-plain leaves compare
76
+ * by identity, which can only over-report a change, never miss one. A typed array diffs
77
+ * bytewise only while it is small; a large one (a canvas snapshot) reads as changed, because
78
+ * diffing one per keystroke would cost what the comparison exists to save, and re-rendering
79
+ * is always the safe reading.
80
+ */
81
+ export function plainValueEquals(a, b) {
82
+ if (a === b)
83
+ return true;
84
+ if (Array.isArray(a) || Array.isArray(b)) {
85
+ return (Array.isArray(a) &&
86
+ Array.isArray(b) &&
87
+ a.length === b.length &&
88
+ a.every((item, index) => plainValueEquals(item, b[index])));
89
+ }
90
+ if (ArrayBuffer.isView(a) || ArrayBuffer.isView(b)) {
91
+ const viewA = a;
92
+ const viewB = b;
93
+ if (viewA.byteLength !== viewB.byteLength || viewA.byteLength > TYPED_ARRAY_DIFF_LIMIT)
94
+ return false;
95
+ const bytesA = new Uint8Array(viewA.buffer, viewA.byteOffset, viewA.byteLength);
96
+ const bytesB = new Uint8Array(viewB.buffer, viewB.byteOffset, viewB.byteLength);
97
+ for (let index = 0; index < bytesA.length; index++) {
98
+ if (bytesA[index] !== bytesB[index])
99
+ return false;
100
+ }
101
+ return true;
102
+ }
103
+ if (a && b && typeof a === 'object' && typeof b === 'object') {
104
+ const keysA = Object.keys(a);
105
+ const keysB = Object.keys(b);
106
+ if (keysA.length !== keysB.length)
107
+ return false;
108
+ return keysA.every((key) => plainValueEquals(a[key], b[key]));
109
+ }
110
+ return false;
111
+ }
112
+ //# sourceMappingURL=valueForms.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"valueForms.js","sourceR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form (records keep each field's base type and cardinality), the public form (records as\n * plain nested values), and the PCI form (the public value, except records, which keep\n * their serialized form so a host can write them into QTI variable JSON).\n */\nimport type { QtiValue } from '@pie-qti/qti-processing';\nimport { cloneValue } from '../../utils/cloneFreeze.js';\n\nexport function qtiValueToSerializable(value: QtiValue | undefined): any {\n\tif (!value || value.kind !== 'value') return null;\n\tif (value.cardinality !== 'record') return cloneValue(value.value);\n\n\tconst serialized: Record<string, unknown> = {};\n\tfor (const [fieldIdentifier, fieldValue] of Object.entries(value.value as Record<string, QtiValue>)) {\n\t\tserialized[fieldIdentifier] = {\n\t\t\t...(fieldValue.baseType ? { baseType: fieldValue.baseType } : {}),\n\t\t\tcardinality: fieldValue.cardinality ?? 'single',\n\t\t\tvalue: qtiValueToSerializable(fieldValue),\n\t\t};\n\t}\n\treturn serialized;\n}\n\n/**\n * A value as a PCI host receives it: the public value, except that a record keeps each field's\n * base type and cardinality (its serialized form). A record declaration types none of its\n * fields, so the host could not write them into QTI variable JSON otherwise.\n */\nexport function qtiValueToPci(value: QtiValue | undefined): unknown {\n\treturn value?.kind === 'value' && value.cardinality === 'record'\n\t\t? qtiValueToSerializable(value)\n\t\t: qtiValueToPublic(value);\n}\n\nexport function qtiValueToPublic(value: QtiValue | undefined): any {\n\tif (!value || value.kind !== 'value') return null;\n\tif (value.cardinality !== 'record') return cloneValue(value.value);\n\n\tconst record: Record<string, unknown> = {};\n\tfor (const [fieldIdentifier, fieldValue] of Object.entries(value.value as Record<string, QtiValue>)) {\n\t\trecord[fieldIdentifier] = qtiValueToPublic(fieldValue);\n\t}\n\treturn record;\n}\n\n/**\n * Structural equality of two variable values, for change detection on reads that may write\n * (a PCI-bound response adopting the mounted module's current response). Primitives compare\n * with Object.is — so File, Blob and Trusted Types payloads compare by identity, which can\n * only over-report a change, never miss one.\n */\nexport function qtiValueEquals(a: QtiValue | undefined, b: QtiValue | undefined): boolean {\n\tif (a === b) return true;\n\tif (!a || !b) return false;\n\tif (a.kind !== b.kind || a.baseType !== b.baseType || a.cardinality !== b.cardinality) return false;\n\tif (a.kind !== 'value' || b.kind !== 'value') return true;\n\treturn payloadEquals(a.value, b.value);\n}\n\nfunction payloadEquals(a: unknown, b: unknown): boolean {\n\tif (a === b) return true;\n\tif (Array.isArray(a) && Array.isArray(b)) {\n\t\treturn a.length === b.length && a.every((item, index) => payloadEquals(item, b[index]));\n\t}\n\tif (a && b && typeof a === 'object' && typeof b === 'object') {\n\t\tconst ka = Object.keys(a as Record<string, unknown>);\n\t\tconst kb = Object.keys(b as Record<string, unknown>);\n\t\tif (ka.length !== kb.length) return false;\n\t\treturn ka.every((key) =>\n\t\t\tpayloadEquals((a as Record<string, unknown>)[key], (b as Record<string, unknown>)[key]),\n\t\t);\n\t}\n\treturn false;\n}\n\n/** Typed arrays up to this many bytes diff bytewise; larger ones read as changed. */\nconst TYPED_ARRAY_DIFF_LIMIT = 4096;\n\n/**\n * Structural equality of two public variable values (whatever qtiValueToPublic produced:\n * null, primitives, arrays, plain records, and the occasional non-plain leaf such as a File\n * or a drawing's typed arrays). Like payloadEquals for QtiValues, non-plain leaves compare\n * by identity, which can only over-report a change, never miss one. A typed array diffs\n * bytewise only while it is small; a large one (a canvas snapshot) reads as changed, because\n * diffing one per keystroke would cost what the comparison exists to save, and re-rendering\n * is always the safe reading.\n */\nexport function plainValueEquals(a: unknown, b: unknown): boolean {\n\tif (a === b) return true;\n\tif (Array.isArray(a) || Array.isArray(b)) {\n\t\treturn (\n\t\t\tArray.isArray(a) &&\n\t\t\tArray.isArray(b) &&\n\t\t\ta.length === b.length &&\n\t\t\ta.every((item, index) => plainValueEquals(item, b[index]))\n\t\t);\n\t}\n\tif (ArrayBuffer.isView(a) || ArrayBuffer.isView(b)) {\n\t\tconst viewA = a as ArrayBufferView;\n\t\tconst viewB = b as ArrayBufferView;\n\t\tif (viewA.byteLength !== viewB.byteLength || viewA.byteLength > TYPED_ARRAY_DIFF_LIMIT) return false;\n\t\tconst bytesA = new Uint8Array(viewA.buffer, viewA.byteOffset, viewA.byteLength);\n\t\tconst bytesB = new Uint8Array(viewB.buffer, viewB.byteOffset, viewB.byteLength);\n\t\tfor (let index = 0; index < bytesA.length; index++) {\n\t\t\tif (bytesA[index] !== bytesB[index]) return false;\n\t\t}\n\t\treturn true;\n\t}\n\tif (a && b && typeof a === 'object' && typeof b === 'object') {\n\t\tconst keysA = Object.keys(a as Record<string, unknown>);\n\t\tconst keysB = Object.keys(b as Record<string, unknown>);\n\t\tif (keysA.length !== keysB.length) return false;\n\t\treturn keysA.every((key) =>\n\t\t\tplainValueEquals((a as Record<string, unknown>)[key], (b as Record<string, unknown>)[key]),\n\t\t);\n\t}\n\treturn false;\n}\n"]}
@@ -43,8 +43,10 @@ export declare class AssessmentItemDocument {
43
43
  private readonly assessmentItem;
44
44
  /** Immutable serialized source for session-local mutable extraction views. */
45
45
  private readonly extractionSource;
46
+ /** textEntryInteraction number bases by response identifier, read on first use. */
47
+ private textEntryBases?;
48
+ private extendedTextBases?;
46
49
  constructor({ itemXml, elementNameMapper, attributeNameMapper, security, }: AssessmentItemDocumentInput);
47
- detectVersion(): '2.0' | '2.1' | '2.2' | '3.0' | 'unknown';
48
50
  getProcessingElement(kind: ProcessingKind): Element | null;
49
51
  /** The item body's content, resolved by `handlers`. */
50
52
  serializeItemBodyChildren(handlers?: ContentHandlers): string;
@@ -53,11 +55,35 @@ export declare class AssessmentItemDocument {
53
55
  readRubricBlocks(handlers?: ContentHandlers): readonly DocumentRubricBlock[];
54
56
  /** Every modal feedback, with its content resolved by `handlers`. */
55
57
  readModalFeedback(handlers?: ContentHandlers): readonly DocumentModalFeedback[];
58
+ /**
59
+ * The number base the extendedTextInteraction bound to `responseIdentifier` reads typed
60
+ * numeric text in (QTI ASI stringInteraction `base`, default 10), or undefined when no
61
+ * extendedTextInteraction is bound to it. Read once, per interaction identifier, into a
62
+ * map of numbers: the item body source is immutable, and caching the base avoids
63
+ * re-parsing the (mutable) extraction view on every value coercion.
64
+ */
56
65
  getExtendedTextBase(responseIdentifier: string): number | undefined;
66
+ /**
67
+ * The number base the textEntryInteraction bound to `responseIdentifier` reads a numeric
68
+ * response in (QTI ASI stringInteraction `base`, default 10), or undefined when no
69
+ * textEntryInteraction is bound to it. Read once: the item body source is immutable.
70
+ */
71
+ getTextEntryBase(responseIdentifier: string): number | undefined;
57
72
  private findRubricElements;
58
73
  private rubricElementScope;
59
74
  private findModalFeedbackElements;
60
75
  findDeclarationElements(kind: 'response' | 'outcome' | 'template' | 'context'): Element[];
76
+ /**
77
+ * Variable identifiers the content pass substitutes live from the session's variable
78
+ * context while body and rubric content serialize: those named by `printedVariable`
79
+ * (`printedvariable` canonically) inside the item body or a rubric block. Template and
80
+ * processing do not author or remove elements — the compiled document is immutable and
81
+ * handlers resolve clones — so this set is fixed per item and cached.
82
+ */
83
+ printedVariableIdentifiers(): ReadonlySet<string>;
84
+ private printedVariableIds?;
85
+ private collectPrintedVariableIdentifiers;
86
+ private collectPrintedVariableIdentifiersIn;
61
87
  /** The item body's `xml:lang`, else the item's: the language its content is written in. */
62
88
  getContentLanguage(): string | undefined;
63
89
  getAssessmentItemAttribute(name: string): string | null;
@@ -3,6 +3,7 @@ import { parse } from 'node-html-parser';
3
3
  import { dockApipLinks, readApipAccessibility } from '../catalog/apipAccessibility.js';
4
4
  import { enforceItemXmlLimits } from '../core/parsingLimits.js';
5
5
  import { normalizeInteractionTypeFromTagName } from '../interactions/modules.js';
6
+ import { readResponseIdentifier } from '../extraction/responseIdentifier.js';
6
7
  import { resolveContent } from './contentPass.js';
7
8
  const NO_HANDLERS = new Map();
8
9
  export class AssessmentItemDocument {
@@ -18,26 +19,6 @@ export class AssessmentItemDocument {
18
19
  dockApipLinks(this.assessmentItem, readApipAccessibility(this.itemXml));
19
20
  this.extractionSource = this.serializeItemBodyForExtraction();
20
21
  }
21
- detectVersion() {
22
- const namespace = this.assessmentItem.namespaceURI;
23
- if (namespace?.includes('v3p0') || namespace?.includes('imsqtiasi_v3p0'))
24
- return '3.0';
25
- if (namespace?.includes('v2p2') || namespace?.includes('imsqti_v2p2'))
26
- return '2.2';
27
- if (namespace?.includes('v2p1') || namespace?.includes('imsqti_v2p1'))
28
- return '2.1';
29
- if (namespace?.includes('v2p0') || namespace?.includes('imsqti_v2p0'))
30
- return '2.0';
31
- const localName = this.assessmentItem.localName || this.assessmentItem.tagName;
32
- if (localName === 'qti-assessment-item' || localName === 'qti-assessment-test')
33
- return '3.0';
34
- const version = this.assessmentItem.getAttribute('version');
35
- if (version?.startsWith('3.'))
36
- return '3.0';
37
- if (version === '2.2' || version === '2.1' || version === '2.0')
38
- return version;
39
- return 'unknown';
40
- }
41
22
  getProcessingElement(kind) {
42
23
  const tagName = kind === 'template'
43
24
  ? 'templateprocessing'
@@ -93,12 +74,43 @@ export class AssessmentItemDocument {
93
74
  });
94
75
  });
95
76
  }
77
+ /**
78
+ * The number base the extendedTextInteraction bound to `responseIdentifier` reads typed
79
+ * numeric text in (QTI ASI stringInteraction `base`, default 10), or undefined when no
80
+ * extendedTextInteraction is bound to it. Read once, per interaction identifier, into a
81
+ * map of numbers: the item body source is immutable, and caching the base avoids
82
+ * re-parsing the (mutable) extraction view on every value coercion.
83
+ */
96
84
  getExtendedTextBase(responseIdentifier) {
97
- const interaction = this.findExtractionElements(['extendedTextInteraction']).find((candidate) => candidate.responseIdentifier === responseIdentifier);
98
- if (!interaction)
99
- return undefined;
100
- const base = Number(interaction.element.getAttribute?.('base') ?? 10);
101
- return Number.isInteger(base) && base >= 2 && base <= 36 ? base : 10;
85
+ if (!this.extendedTextBases) {
86
+ const bases = new Map();
87
+ for (const { responseIdentifier: id, element } of this.findExtractionElements(['extendedTextInteraction'])) {
88
+ if (bases.has(id))
89
+ continue;
90
+ const base = Number(element.getAttribute?.('base') ?? 10);
91
+ bases.set(id, Number.isInteger(base) && base >= 2 && base <= 36 ? base : 10);
92
+ }
93
+ this.extendedTextBases = bases;
94
+ }
95
+ return this.extendedTextBases.get(responseIdentifier);
96
+ }
97
+ /**
98
+ * The number base the textEntryInteraction bound to `responseIdentifier` reads a numeric
99
+ * response in (QTI ASI stringInteraction `base`, default 10), or undefined when no
100
+ * textEntryInteraction is bound to it. Read once: the item body source is immutable.
101
+ */
102
+ getTextEntryBase(responseIdentifier) {
103
+ if (!this.textEntryBases) {
104
+ const bases = new Map();
105
+ for (const { responseIdentifier: id, element } of this.findExtractionElements(['textEntryInteraction'])) {
106
+ if (bases.has(id))
107
+ continue;
108
+ const base = Number(element.getAttribute?.('base') ?? 10);
109
+ bases.set(id, Number.isInteger(base) && base >= 2 && base <= 36 ? base : 10);
110
+ }
111
+ this.textEntryBases = bases;
112
+ }
113
+ return this.textEntryBases.get(responseIdentifier);
102
114
  }
103
115
  findRubricElements() {
104
116
  return findDescendants(this.assessmentItem, this.elementNameMapper.toNative('rubricblock'));
@@ -122,6 +134,35 @@ export class AssessmentItemDocument {
122
134
  const tagName = `${kind}declaration`;
123
135
  return findDescendants(this.assessmentItem, this.elementNameMapper.toNative(tagName));
124
136
  }
137
+ /**
138
+ * Variable identifiers the content pass substitutes live from the session's variable
139
+ * context while body and rubric content serialize: those named by `printedVariable`
140
+ * (`printedvariable` canonically) inside the item body or a rubric block. Template and
141
+ * processing do not author or remove elements — the compiled document is immutable and
142
+ * handlers resolve clones — so this set is fixed per item and cached.
143
+ */
144
+ printedVariableIdentifiers() {
145
+ this.printedVariableIds ?? (this.printedVariableIds = this.collectPrintedVariableIdentifiers());
146
+ return this.printedVariableIds;
147
+ }
148
+ collectPrintedVariableIdentifiers() {
149
+ const identifiers = new Set();
150
+ const roots = [this.getItemBodyElement(), ...this.findRubricElements()].filter((element) => Boolean(element));
151
+ for (const root of roots)
152
+ this.collectPrintedVariableIdentifiersIn(root, identifiers);
153
+ return identifiers;
154
+ }
155
+ collectPrintedVariableIdentifiersIn(element, identifiers) {
156
+ const tag = element.tagName ?? element.localName ?? '';
157
+ if (this.elementNameMapper.toCanonical(tag) === 'printedvariable') {
158
+ const identifier = this.getMappedAttribute(element, 'identifier')?.trim();
159
+ if (identifier)
160
+ identifiers.add(identifier);
161
+ }
162
+ for (const child of childElements(element)) {
163
+ this.collectPrintedVariableIdentifiersIn(child, identifiers);
164
+ }
165
+ }
125
166
  /** The item body's `xml:lang`, else the item's: the language its content is written in. */
126
167
  getContentLanguage() {
127
168
  const itemBody = this.getItemBodyElement();
@@ -208,12 +249,7 @@ export class AssessmentItemDocument {
208
249
  }
209
250
  }
210
251
  getExtractionResponseIdentifier(element) {
211
- const nativeName = this.attributeNameMapper.toNative('responseIdentifier');
212
- return (element.getAttribute?.('responseIdentifier') ||
213
- element.getAttribute?.(nativeName) ||
214
- element.getAttribute?.('response-identifier') ||
215
- element.getAttribute?.('responseidentifier') ||
216
- '');
252
+ return readResponseIdentifier(element, this.attributeNameMapper) ?? '';
217
253
  }
218
254
  }
219
255
  function isRubricBlockTagName(tagName) {