@pie-qti/item-player 0.1.12 → 0.1.14

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.
@@ -3,6 +3,29 @@
3
3
  *
4
4
  * Extracts data from gapMatchInteraction elements (drag words into gaps)
5
5
  */
6
+ const GAP_ELEMENT_PATTERN = /<(?:qti-gap|gap)(?=[\s/>])([^>]*)\/?>/gi;
7
+ const GAP_CLOSE_PATTERN = /<\/(?:qti-gap|gap)>/gi;
8
+ const GAP_TEXT_PATTERN = /<(?:qti-gap-text|gapText)\b[\s\S]*?<\/(?:qti-gap-text|gapText)>/gi;
9
+ const GAP_MATCH_OPEN_PATTERN = /<(?:qti-gap-match-interaction|gapMatchInteraction)\b[^>]*>/i;
10
+ const GAP_MATCH_CLOSE_PATTERN = /<\/(?:qti-gap-match-interaction|gapMatchInteraction)>/i;
11
+ const PROMPT_PATTERN = /<(?:qti-prompt|prompt)\b[\s\S]*?<\/(?:qti-prompt|prompt)>/gi;
12
+ function extractAttribute(attrs, name) {
13
+ const match = new RegExp(`\\b${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)')`, 'i').exec(attrs);
14
+ return (match?.[1] ?? match?.[2] ?? '').trim();
15
+ }
16
+ function promptTextFromInteractionBody(interactionHtml) {
17
+ return interactionHtml
18
+ .replace(GAP_MATCH_OPEN_PATTERN, '')
19
+ .replace(GAP_MATCH_CLOSE_PATTERN, '')
20
+ .replace(PROMPT_PATTERN, '')
21
+ .replace(GAP_TEXT_PATTERN, '')
22
+ .replace(GAP_ELEMENT_PATTERN, (_match, attrs) => {
23
+ const id = extractAttribute(attrs, 'identifier');
24
+ return id ? `[GAP:${id}]` : '';
25
+ })
26
+ .replace(GAP_CLOSE_PATTERN, '')
27
+ .trim();
28
+ }
6
29
  /**
7
30
  * Standard QTI gap match interaction extractor
8
31
  * Handles gapMatchInteraction elements (drag words into gaps in text)
@@ -57,32 +80,26 @@ export const standardGapMatchExtractor = {
57
80
  promptText = promptHtml
58
81
  .replace(/<qti-prompt[^>]*>|<prompt[^>]*>/, '')
59
82
  .replace(/<\/qti-prompt>|<\/prompt>/, '')
60
- .replace(/<(?:qti-)?gap\s+identifier="([^"]+)"[^>]*>/g, '[GAP:$1]')
61
- .replace(/<(?:qti-)?gap\s+identifier='([^']+)'[^>]*>/g, '[GAP:$1]')
62
- .replace(/<\/(?:qti-)?gap>/g, '')
83
+ .replace(GAP_ELEMENT_PATTERN, (_match, attrs) => {
84
+ const id = extractAttribute(attrs, 'identifier');
85
+ return id ? `[GAP:${id}]` : '';
86
+ })
87
+ .replace(GAP_CLOSE_PATTERN, '')
63
88
  .trim();
64
89
  }
65
90
  // If gaps were not found inside a <prompt>, search the full interaction body.
66
91
  // This handles items where <gap> elements appear in <p>/<blockquote> siblings of <prompt>.
67
92
  if (gaps.length === 0) {
68
93
  const interactionHtml = element.outerHTML || element.toString();
69
- const gapIdMatches = Array.from(interactionHtml.matchAll(/<(?:qti-)?gap\s+identifier=(?:"([^"]+)"|'([^']+)')[^>]*\/?>/gi));
94
+ const gapIdMatches = Array.from(interactionHtml.matchAll(GAP_ELEMENT_PATTERN));
70
95
  for (const m of gapIdMatches) {
71
- const id = (m[1] || m[2] || '').trim();
96
+ const id = extractAttribute(m[1] ?? '', 'identifier');
72
97
  if (id)
73
98
  gaps.push(id);
74
99
  }
75
- if (!promptText) {
76
- // No prompt element either: build promptText from full interaction content.
77
- const interactionHtml2 = element.outerHTML || element.toString();
78
- promptText = interactionHtml2
79
- .replace(/<(?:qti-)?gap-match-interaction[^>]*>|<gapMatchInteraction[^>]*>/, '')
80
- .replace(/<\/(?:qti-)?gap-match-interaction>|<\/gapMatchInteraction>/, '')
81
- .replace(/<(?:qti-)?gap-text[\s\S]*?<\/(?:qti-)?gap-text>|<gapText[\s\S]*?<\/gapText>/g, '')
82
- .replace(/<(?:qti-)?gap\s+identifier="([^"]+)"[^>]*\/?>/g, '[GAP:$1]')
83
- .replace(/<(?:qti-)?gap\s+identifier='([^']+)'[^>]*\/?>/g, '[GAP:$1]')
84
- .replace(/<\/(?:qti-)?gap>/g, '')
85
- .trim();
100
+ if (gaps.length > 0 && (!promptText || !promptText.includes('[GAP:'))) {
101
+ // Build promptText from the interaction body when gaps are authored outside the prompt.
102
+ promptText = promptTextFromInteractionBody(interactionHtml);
86
103
  }
87
104
  }
88
105
  // Extract attributes
@@ -1 +1 @@
1
- {"version":3,"file":"extractor.js","sourceRoot":"","sources":["../../../src/interactions/gap-match/extractor.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAsBH;;;GAGG;AACH,MAAM,CAAC,MAAM,yBAAyB,GAAmC;IACxE,EAAE,EAAE,2BAA2B;IAC/B,IAAI,EAAE,oCAAoC;IAC1C,QAAQ,EAAE,EAAE;IACZ,YAAY,EAAE,CAAC,qBAAqB,CAAC;IACrC,WAAW,EAAE,kEAAkE;IAE/E,SAAS,CAAC,OAAO,EAAE,QAAQ;QAC1B,gDAAgD;QAChD,OAAO,OAAO,CAAC,UAAU,KAAK,qBAAqB,CAAC;IACrD,CAAC;IAED,OAAO,CAAC,OAAO,EAAE,OAAO;QACvB,MAAM,EAAE,KAAK,EAAE,GAAG,OAAO,CAAC;QAE1B,6CAA6C;QAC7C,MAAM,eAAe,GAAG,KAAK,CAAC,gBAAgB,CAAC,OAAO,EAAE,SAAS,CAAC,CAAC;QACnE,MAAM,QAAQ,GAAG,eAAe,CAAC,GAAG,CAAC,CAAC,OAAO,EAAE,EAAE;YAChD,MAAM,OAAO,GAAG,KAAK,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;YAC1C,MAAM,QAAQ,GAAG,KAAK,CAAC,kBAAkB,CAAC,OAAO,EAAE,UAAU,EAAE,CAAC,CAAC,CAAC;YAClE,MAAM,QAAQ,GAAG,KAAK,CAAC,kBAAkB,CAAC,OAAO,EAAE,UAAU,EAAE,CAAC,CAAC,CAAC;YAClE,MAAM,aAAa,GAAG,KAAK,CAAC,YAAY,CAAC,OAAO,EAAE,YAAY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G,EAAU,CAAC;YACtC,KAAK,MAAM,GAAG,IAAI,IAAI,CAAC,IAAI,EAAE,CAAC;gBAC7B,IAAI,CAAC,GAAG,EAAE,CAAC;oBACV,MAAM,CAAC,IAAI,CAAC,kCAAkC,CAAC,CAAC;gBACjD,CAAC;qBAAM,IAAI,WAAW,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC;oBACjC,MAAM,CAAC,IAAI,CAAC,6BAA6B,GAAG,EAAE,CAAC,CAAC;gBACjD,CAAC;qBAAM,CAAC;oBACP,WAAW,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;gBACtB,CAAC;YACF,CAAC;QACF,CAAC;QAED,OAAO;YACN,KAAK,EAAE,MAAM,CAAC,MAAM,KAAK,CAAC;YAC1B,MAAM,EAAE,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS;SAC9C,CAAC;IACH,CAAC;CACD,CAAC","sourcesContent":["/**\n * Standard QTI gapMatchInteraction extractor\n *\n * Extracts data from gapMatchInteraction elements (drag words into gaps)\n */\n\nimport type { ElementExtractor } from '../../extraction/types.js';\n\n/**\n * Gap match data extracted from gapMatchInteraction elements\n */\nexport interface GapMatchData {\n\tgapTexts: Array<{\n\t\tidentifier: string;\n\t\ttext: string;\n\t\tmatchMax: number;\n\t\tmatchMin?: number;\n\t\tmatchGroup?: string[];\n\t\tclasses?: string[];\n\t}>;\n\tgaps: string[];\n\tshuffle: boolean;\n\tprompt: string | null;\n\tpromptText: string;\n}\n\n/**\n * Standard QTI gap match interaction extractor\n * Handles gapMatchInteraction elements (drag words into gaps in text)\n */\nexport const standardGapMatchExtractor: ElementExtractor<GapMatchData> = {\n\tid: 'qti:gap-match-interaction',\n\tname: 'QTI Standard Gap Match Interaction',\n\tpriority: 10,\n\telementTypes: ['gapMatchInteraction'],\n\tdescription: 'Extracts standard QTI gapMatchInteraction (drag words into gaps)',\n\n\tcanHandle(element, _context) {\n\t\t// All gapMatchInteraction elements are standard\n\t\treturn element.rawTagName === 'gapMatchInteraction';\n\t},\n\n\textract(element, context) {\n\t\tconst { utils } = context;\n\n\t\t// Extract gapText children (draggable items)\n\t\tconst gapTextElements = utils.getChildrenByTag(element, 'gapText');\n\t\tconst gapTexts = gapTextElements.map((gapText) => {\n\t\t\tconst classes = utils.getClasses(gapText);\n\t\t\tconst matchMax = utils.getNumberAttribute(gapText, 'matchMax', 1);\n\t\t\tconst matchMin = utils.getNumberAttribute(gapText, 'matchMin', 0);\n\t\t\tconst matchGroupRaw = utils.getAttribute(gapText, 'matchGroup', '');\n\t\t\tconst matchGroup = matchGroupRaw.split(/\\s+/).filter(Boolean);\n\n\t\t\treturn {\n\t\t\t\tidentifier: utils.getAttribute(gapText, 'identifier', ''),\n\t\t\t\ttext: utils.getTextContent(gapText),\n\t\t\t\tmatchMax,\n\t\t\t\t...(matchMin > 0 ? { matchMin } : {}),\n\t\t\t\t...(matchGroup.length > 0 ? { matchGroup } : {}),\n\t\t\t\t...(classes.length > 0 ? { classes } : {}),\n\t\t\t};\n\t\t});\n\n\t\t// Extract prompt (optional) and process gap placeholders.\n\t\t// NOTE: Many QTI items place `<gap>` elements in the interaction content (e.g. a `<p>`/`<blockquote>`)\n\t\t// rather than inside a `<prompt>` element. Support both patterns.\n\t\tconst promptElements = utils.getChildrenByTag(element, 'prompt');\n\t\tlet prompt: string | null = null;\n\t\tlet promptText = '';\n\t\tconst gaps: string[] = [];\n\n\t\tif (promptElements.length > 0) {\n\t\t\tconst promptElement = promptElements[0];\n\t\t\tprompt = utils.getHtmlContent(promptElement);\n\n\t\t\t// Get the raw HTML content and extract gaps\n\t\t\tconst promptHtml = promptElement.outerHTML || promptElement.toString();\n\n\t\t\t// Extract gap elements from prompt children\n\t\t\tconst gapElements = utils.getChildrenByTag(promptElement, 'gap');\n\t\t\tfor (const gap of gapElements) {\n\t\t\t\tgaps.push(utils.getAttribute(gap, 'identifier', ''));\n\t\t\t}\n\n\t\t\t// Replace gap elements with placeholders in the text\n\t\t\tpromptText = promptHtml\n\t\t\t\t.replace(/<qti-prompt[^>]*>|<prompt[^>]*>/, '')\n\t\t\t\t.replace(/<\\/qti-prompt>|<\\/prompt>/, '')\n\t\t\t\t.replace(/<(?:qti-)?gap\\s+identifier=\"([^\"]+)\"[^>]*>/g, '[GAP:$1]')\n\t\t\t\t.replace(/<(?:qti-)?gap\\s+identifier='([^']+)'[^>]*>/g, '[GAP:$1]')\n\t\t\t\t.replace(/<\\/(?:qti-)?gap>/g, '')\n\t\t\t\t.trim();\n\t\t}\n\n\t\t// If gaps were not found inside a <prompt>, search the full interaction body.\n\t\t// This handles items where <gap> elements appear in <p>/<blockquote> siblings of <prompt>.\n\t\tif (gaps.length === 0) {\n\t\t\tconst interactionHtml = element.outerHTML || element.toString();\n\t\t\tconst gapIdMatches = Array.from(\n\t\t\t\tinteractionHtml.matchAll(/<(?:qti-)?gap\\s+identifier=(?:\"([^\"]+)\"|'([^']+)')[^>]*\\/?>/gi)\n\t\t\t);\n\t\t\tfor (const m of gapIdMatches) {\n\t\t\t\tconst id = (m[1] || m[2] || '').trim();\n\t\t\t\tif (id) gaps.push(id);\n\t\t\t}\n\n\t\t\tif (!promptText) {\n\t\t\t\t// No prompt element either: build promptText from full interaction content.\n\t\t\t\tconst interactionHtml2 = element.outerHTML || element.toString();\n\t\t\t\tpromptText = interactionHtml2\n\t\t\t\t\t.replace(/<(?:qti-)?gap-match-interaction[^>]*>|<gapMatchInteraction[^>]*>/, '')\n\t\t\t\t\t.replace(/<\\/(?:qti-)?gap-match-interaction>|<\\/gapMatchInteraction>/, '')\n\t\t\t\t\t.replace(/<(?:qti-)?gap-text[\\s\\S]*?<\\/(?:qti-)?gap-text>|<gapText[\\s\\S]*?<\\/gapText>/g, '')\n\t\t\t\t\t.replace(/<(?:qti-)?gap\\s+identifier=\"([^\"]+)\"[^>]*\\/?>/g, '[GAP:$1]')\n\t\t\t\t\t.replace(/<(?:qti-)?gap\\s+identifier='([^']+)'[^>]*\\/?>/g, '[GAP:$1]')\n\t\t\t\t\t.replace(/<\\/(?:qti-)?gap>/g, '')\n\t\t\t\t\t.trim();\n\t\t\t}\n\t\t}\n\n\t\t// Extract attributes\n\t\tconst shuffle = utils.getBooleanAttribute(element, 'shuffle');\n\t\tconst interactionClasses = utils.getClasses(element);\n\t\tconst choicesContainerWidth = utils.getAttribute(element, 'data-choices-container-width', '') || null;\n\t\tconst maxSelectionsMessage = utils.getAttribute(element, 'data-max-selections-message', '') || null;\n\t\tconst minSelectionsMessage = utils.getAttribute(element, 'data-min-selections-message', '') || null;\n\n\t\treturn {\n\t\t\tgapTexts,\n\t\t\tgaps,\n\t\t\tshuffle,\n\t\t\tprompt,\n\t\t\tpromptText,\n\t\t\t...(interactionClasses.length > 0 ? { interactionClasses } : {}),\n\t\t\t...(choicesContainerWidth ? { choicesContainerWidth } : {}),\n\t\t\t...(maxSelectionsMessage ? { maxSelectionsMessage } : {}),\n\t\t\t...(minSelectionsMessage ? { minSelectionsMessage } : {}),\n\t\t};\n\t},\n\n\tvalidate(data) {\n\t\tconst errors: string[] = [];\n\n\t\t// Validate gapTexts exist\n\t\tif (!data.gapTexts || data.gapTexts.length === 0) {\n\t\t\terrors.push('gapMatchInteraction must have at least one gapText');\n\t\t}\n\n\t\t// Validate gaps exist\n\t\tif (!data.gaps || data.gaps.length === 0) {\n\t\t\terrors.push('gapMatchInteraction must have at least one gap in the prompt');\n\t\t}\n\n\t\t// Validate gapText identifiers\n\t\tif (data.gapTexts) {\n\t\t\tconst identifiers = new Set<string>();\n\t\t\tfor (const gapText of data.gapTexts) {\n\t\t\t\tif (!gapText.identifier) {\n\t\t\t\t\terrors.push('All gapTexts must have an identifier');\n\t\t\t\t} else if (identifiers.has(gapText.identifier)) {\n\t\t\t\t\terrors.push(`Duplicate gapText identifier: ${gapText.identifier}`);\n\t\t\t\t} else {\n\t\t\t\t\tidentifiers.add(gapText.identifier);\n\t\t\t\t}\n\n\t\t\t\t// Validate matchMax\n\t\t\t\tif (gapText.matchMax < 0) {\n\t\t\t\t\terrors.push(`matchMax must be non-negative for gapText ${gapText.identifier}`);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Validate gap identifiers\n\t\tif (data.gaps) {\n\t\t\tconst identifiers = new Set<string>();\n\t\t\tfor (const gap of data.gaps) {\n\t\t\t\tif (!gap) {\n\t\t\t\t\terrors.push('All gaps must have an identifier');\n\t\t\t\t} else if (identifiers.has(gap)) {\n\t\t\t\t\terrors.push(`Duplicate gap identifier: ${gap}`);\n\t\t\t\t} else {\n\t\t\t\t\tidentifiers.add(gap);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn {\n\t\t\tvalid: errors.length === 0,\n\t\t\terrors: errors.length > 0 ? errors : undefined,\n\t\t};\n\t},\n};\n"]}
1
+ {"version":3,"file":"extractor.js","sourceRoot":"","sources":["../../../src/interactions/gap-match/extractor.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAIH,MAAM,mBAAmB,GAAG,yCAAyC,CAAC;AACtE,MAAM,iBAAiB,GAAG,uBAAuB,CAAC;AAClD,MAAM,gBAAgB,GAAG,mEAAmE,CAAC;AAC7F,MAAM,sBAAsB,GAAG,6DAA6D,CAAC;AAC7F,MAAM,uBAAuB,GAAG,wDAAwD,CAAC;AACzF,MAAM,cAAc,GAAG,6DAA6D,CAAC;AAErF,SAAS,gBAAgB,CAAC,KAAa,EAAE,IAAY;IACpD,MAAM,KAAK,GAAG,IAAI,MAAM,CAAC,MAAM,IAAI,kCAAkC,EAAE,GAAG,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IACxF,OAAO,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,EAAE,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC;AAChD,CAAC;AAED,SAAS,6BAA6B,CAAC,eAAuB;IAC7D,OAAO,eAAe;SACpB,OAAO,CAAC,sBAAsB,EAAE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C;YACtC,KAAK,MAAM,GAAG,IAAI,IAAI,CAAC,IAAI,EAAE,CAAC;gBAC7B,IAAI,CAAC,GAAG,EAAE,CAAC;oBACV,MAAM,CAAC,IAAI,CAAC,kCAAkC,CAAC,CAAC;gBACjD,CAAC;qBAAM,IAAI,WAAW,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC;oBACjC,MAAM,CAAC,IAAI,CAAC,6BAA6B,GAAG,EAAE,CAAC,CAAC;gBACjD,CAAC;qBAAM,CAAC;oBACP,WAAW,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;gBACtB,CAAC;YACF,CAAC;QACF,CAAC;QAED,OAAO;YACN,KAAK,EAAE,MAAM,CAAC,MAAM,KAAK,CAAC;YAC1B,MAAM,EAAE,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS;SAC9C,CAAC;IACH,CAAC;CACD,CAAC","sourcesContent":["/**\n * Standard QTI gapMatchInteraction extractor\n *\n * Extracts data from gapMatchInteraction elements (drag words into gaps)\n */\n\nimport type { ElementExtractor } from '../../extraction/types.js';\n\nconst GAP_ELEMENT_PATTERN = /<(?:qti-gap|gap)(?=[\\s/>])([^>]*)\\/?>/gi;\nconst GAP_CLOSE_PATTERN = /<\\/(?:qti-gap|gap)>/gi;\nconst GAP_TEXT_PATTERN = /<(?:qti-gap-text|gapText)\\b[\\s\\S]*?<\\/(?:qti-gap-text|gapText)>/gi;\nconst GAP_MATCH_OPEN_PATTERN = /<(?:qti-gap-match-interaction|gapMatchInteraction)\\b[^>]*>/i;\nconst GAP_MATCH_CLOSE_PATTERN = /<\\/(?:qti-gap-match-interaction|gapMatchInteraction)>/i;\nconst PROMPT_PATTERN = /<(?:qti-prompt|prompt)\\b[\\s\\S]*?<\\/(?:qti-prompt|prompt)>/gi;\n\nfunction extractAttribute(attrs: string, name: string): string {\n\tconst match = new RegExp(`\\\\b${name}\\\\s*=\\\\s*(?:\"([^\"]*)\"|'([^']*)')`, 'i').exec(attrs);\n\treturn (match?.[1] ?? match?.[2] ?? '').trim();\n}\n\nfunction promptTextFromInteractionBody(interactionHtml: string): string {\n\treturn interactionHtml\n\t\t.replace(GAP_MATCH_OPEN_PATTERN, '')\n\t\t.replace(GAP_MATCH_CLOSE_PATTERN, '')\n\t\t.replace(PROMPT_PATTERN, '')\n\t\t.replace(GAP_TEXT_PATTERN, '')\n\t\t.replace(GAP_ELEMENT_PATTERN, (_match, attrs: string) => {\n\t\t\tconst id = extractAttribute(attrs, 'identifier');\n\t\t\treturn id ? `[GAP:${id}]` : '';\n\t\t})\n\t\t.replace(GAP_CLOSE_PATTERN, '')\n\t\t.trim();\n}\n\n/**\n * Gap match data extracted from gapMatchInteraction elements\n */\nexport interface GapMatchData {\n\tgapTexts: Array<{\n\t\tidentifier: string;\n\t\ttext: string;\n\t\tmatchMax: number;\n\t\tmatchMin?: number;\n\t\tmatchGroup?: string[];\n\t\tclasses?: string[];\n\t}>;\n\tgaps: string[];\n\tshuffle: boolean;\n\tprompt: string | null;\n\tpromptText: string;\n}\n\n/**\n * Standard QTI gap match interaction extractor\n * Handles gapMatchInteraction elements (drag words into gaps in text)\n */\nexport const standardGapMatchExtractor: ElementExtractor<GapMatchData> = {\n\tid: 'qti:gap-match-interaction',\n\tname: 'QTI Standard Gap Match Interaction',\n\tpriority: 10,\n\telementTypes: ['gapMatchInteraction'],\n\tdescription: 'Extracts standard QTI gapMatchInteraction (drag words into gaps)',\n\n\tcanHandle(element, _context) {\n\t\t// All gapMatchInteraction elements are standard\n\t\treturn element.rawTagName === 'gapMatchInteraction';\n\t},\n\n\textract(element, context) {\n\t\tconst { utils } = context;\n\n\t\t// Extract gapText children (draggable items)\n\t\tconst gapTextElements = utils.getChildrenByTag(element, 'gapText');\n\t\tconst gapTexts = gapTextElements.map((gapText) => {\n\t\t\tconst classes = utils.getClasses(gapText);\n\t\t\tconst matchMax = utils.getNumberAttribute(gapText, 'matchMax', 1);\n\t\t\tconst matchMin = utils.getNumberAttribute(gapText, 'matchMin', 0);\n\t\t\tconst matchGroupRaw = utils.getAttribute(gapText, 'matchGroup', '');\n\t\t\tconst matchGroup = matchGroupRaw.split(/\\s+/).filter(Boolean);\n\n\t\t\treturn {\n\t\t\t\tidentifier: utils.getAttribute(gapText, 'identifier', ''),\n\t\t\t\ttext: utils.getTextContent(gapText),\n\t\t\t\tmatchMax,\n\t\t\t\t...(matchMin > 0 ? { matchMin } : {}),\n\t\t\t\t...(matchGroup.length > 0 ? { matchGroup } : {}),\n\t\t\t\t...(classes.length > 0 ? { classes } : {}),\n\t\t\t};\n\t\t});\n\n\t\t// Extract prompt (optional) and process gap placeholders.\n\t\t// NOTE: Many QTI items place `<gap>` elements in the interaction content (e.g. a `<p>`/`<blockquote>`)\n\t\t// rather than inside a `<prompt>` element. Support both patterns.\n\t\tconst promptElements = utils.getChildrenByTag(element, 'prompt');\n\t\tlet prompt: string | null = null;\n\t\tlet promptText = '';\n\t\tconst gaps: string[] = [];\n\n\t\tif (promptElements.length > 0) {\n\t\t\tconst promptElement = promptElements[0];\n\t\t\tprompt = utils.getHtmlContent(promptElement);\n\n\t\t\t// Get the raw HTML content and extract gaps\n\t\t\tconst promptHtml = promptElement.outerHTML || promptElement.toString();\n\n\t\t\t// Extract gap elements from prompt children\n\t\t\tconst gapElements = utils.getChildrenByTag(promptElement, 'gap');\n\t\t\tfor (const gap of gapElements) {\n\t\t\t\tgaps.push(utils.getAttribute(gap, 'identifier', ''));\n\t\t\t}\n\n\t\t\t// Replace gap elements with placeholders in the text\n\t\t\tpromptText = promptHtml\n\t\t\t\t.replace(/<qti-prompt[^>]*>|<prompt[^>]*>/, '')\n\t\t\t\t.replace(/<\\/qti-prompt>|<\\/prompt>/, '')\n\t\t\t\t.replace(GAP_ELEMENT_PATTERN, (_match, attrs: string) => {\n\t\t\t\t\tconst id = extractAttribute(attrs, 'identifier');\n\t\t\t\t\treturn id ? `[GAP:${id}]` : '';\n\t\t\t\t})\n\t\t\t\t.replace(GAP_CLOSE_PATTERN, '')\n\t\t\t\t.trim();\n\t\t}\n\n\t\t// If gaps were not found inside a <prompt>, search the full interaction body.\n\t\t// This handles items where <gap> elements appear in <p>/<blockquote> siblings of <prompt>.\n\t\tif (gaps.length === 0) {\n\t\t\tconst interactionHtml = element.outerHTML || element.toString();\n\t\t\tconst gapIdMatches = Array.from(interactionHtml.matchAll(GAP_ELEMENT_PATTERN));\n\t\t\tfor (const m of gapIdMatches) {\n\t\t\t\tconst id = extractAttribute(m[1] ?? '', 'identifier');\n\t\t\t\tif (id) gaps.push(id);\n\t\t\t}\n\n\t\t\tif (gaps.length > 0 && (!promptText || !promptText.includes('[GAP:'))) {\n\t\t\t\t// Build promptText from the interaction body when gaps are authored outside the prompt.\n\t\t\t\tpromptText = promptTextFromInteractionBody(interactionHtml);\n\t\t\t}\n\t\t}\n\n\t\t// Extract attributes\n\t\tconst shuffle = utils.getBooleanAttribute(element, 'shuffle');\n\t\tconst interactionClasses = utils.getClasses(element);\n\t\tconst choicesContainerWidth = utils.getAttribute(element, 'data-choices-container-width', '') || null;\n\t\tconst maxSelectionsMessage = utils.getAttribute(element, 'data-max-selections-message', '') || null;\n\t\tconst minSelectionsMessage = utils.getAttribute(element, 'data-min-selections-message', '') || null;\n\n\t\treturn {\n\t\t\tgapTexts,\n\t\t\tgaps,\n\t\t\tshuffle,\n\t\t\tprompt,\n\t\t\tpromptText,\n\t\t\t...(interactionClasses.length > 0 ? { interactionClasses } : {}),\n\t\t\t...(choicesContainerWidth ? { choicesContainerWidth } : {}),\n\t\t\t...(maxSelectionsMessage ? { maxSelectionsMessage } : {}),\n\t\t\t...(minSelectionsMessage ? { minSelectionsMessage } : {}),\n\t\t};\n\t},\n\n\tvalidate(data) {\n\t\tconst errors: string[] = [];\n\n\t\t// Validate gapTexts exist\n\t\tif (!data.gapTexts || data.gapTexts.length === 0) {\n\t\t\terrors.push('gapMatchInteraction must have at least one gapText');\n\t\t}\n\n\t\t// Validate gaps exist\n\t\tif (!data.gaps || data.gaps.length === 0) {\n\t\t\terrors.push('gapMatchInteraction must have at least one gap in the prompt');\n\t\t}\n\n\t\t// Validate gapText identifiers\n\t\tif (data.gapTexts) {\n\t\t\tconst identifiers = new Set<string>();\n\t\t\tfor (const gapText of data.gapTexts) {\n\t\t\t\tif (!gapText.identifier) {\n\t\t\t\t\terrors.push('All gapTexts must have an identifier');\n\t\t\t\t} else if (identifiers.has(gapText.identifier)) {\n\t\t\t\t\terrors.push(`Duplicate gapText identifier: ${gapText.identifier}`);\n\t\t\t\t} else {\n\t\t\t\t\tidentifiers.add(gapText.identifier);\n\t\t\t\t}\n\n\t\t\t\t// Validate matchMax\n\t\t\t\tif (gapText.matchMax < 0) {\n\t\t\t\t\terrors.push(`matchMax must be non-negative for gapText ${gapText.identifier}`);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Validate gap identifiers\n\t\tif (data.gaps) {\n\t\t\tconst identifiers = new Set<string>();\n\t\t\tfor (const gap of data.gaps) {\n\t\t\t\tif (!gap) {\n\t\t\t\t\terrors.push('All gaps must have an identifier');\n\t\t\t\t} else if (identifiers.has(gap)) {\n\t\t\t\t\terrors.push(`Duplicate gap identifier: ${gap}`);\n\t\t\t\t} else {\n\t\t\t\t\tidentifiers.add(gap);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn {\n\t\t\tvalid: errors.length === 0,\n\t\t\terrors: errors.length > 0 ? errors : undefined,\n\t\t};\n\t},\n};\n"]}
@@ -117,7 +117,7 @@ export const standardHottextExtractor = {
117
117
  if (data.minChoices !== undefined &&
118
118
  data.maxChoices > 0 &&
119
119
  data.minChoices > data.maxChoices) {
120
- errors.push('minChoices cannot exceed maxChoices');
120
+ warnings.push(`minChoices (${data.minChoices}) exceeds maxChoices (${data.maxChoices}); rendering interaction with authoring constraint warning`);
121
121
  }
122
122
  return {
123
123
  valid: errors.length === 0,
@@ -1 +1 @@
1
- {"version":3,"file":"extractor.js","sourceRoot":"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AM,KAAK,CAAC;YAC1B,MAAM,EAAE,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS;YAC9C,QAAQ,EAAE,QAAQ,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,SAAS;SACpD,CAAC;IACH,CAAC;CACD,CAAC","sourcesContent":["/**\n * Standard QTI hottextInteraction extractor\n *\n * Extracts data from hottextInteraction elements (select text spans)\n */\n\nimport { sanitizeHtml } from '../../core/sanitizer.js';\nimport type { QTIElement } from '../shared/types.js';\nimport type { ElementExtractor } from '../../extraction/types.js';\n\n/**\n * Hottext data extracted from hottextInteraction elements\n */\nexport interface HottextData {\n\thottextChoices: Array<{ identifier: string; text: string; classes?: string[] }>;\n\tcontentHtml: string;\n\tmaxChoices: number;\n\tminChoices: number;\n\tprompt: string | null;\n}\n\n/**\n * Standard QTI hottext interaction extractor\n * Handles hottextInteraction elements (selectable text spans)\n */\nexport const standardHottextExtractor: ElementExtractor<HottextData> = {\n\tid: 'qti:hottext-interaction',\n\tname: 'QTI Standard Hottext Interaction',\n\tpriority: 10,\n\telementTypes: ['hottextInteraction'],\n\tdescription: 'Extracts standard QTI hottextInteraction (select text spans)',\n\n\tcanHandle(element, _context) {\n\t\t// All hottextInteraction elements are standard\n\t\treturn element.rawTagName === 'hottextInteraction' || element.rawTagName === 'qti-hottext-interaction';\n\t},\n\n\textract(element, context) {\n\t\tconst { utils } = context;\n\n\t\t// Extract hottext children (selectable text spans) - recursively search entire tree\n\t\tconst findHottextElements = (el: any): any[] => {\n\t\t\tconst results: any[] = [];\n\t\t\tif (el.rawTagName === 'hottext' || el.rawTagName === 'qti-hottext') {\n\t\t\t\tresults.push(el);\n\t\t\t}\n\t\t\tif (el.childNodes) {\n\t\t\t\tfor (const child of el.childNodes) {\n\t\t\t\t\tif (typeof child !== 'string') {\n\t\t\t\t\t\tresults.push(...findHottextElements(child));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn results;\n\t\t};\n\n\t\tconst hottextElements = findHottextElements(element);\n\t\tconst hottextChoices = hottextElements.map((hottext) => {\n\t\t\tconst classes = utils.getClasses(hottext);\n\t\t\treturn {\n\t\t\t\tidentifier: utils.getAttribute(hottext, 'identifier', ''),\n\t\t\t\ttext: utils.getTextContent(hottext),\n\t\t\t\t...(classes.length > 0 ? { classes } : {}),\n\t\t\t};\n\t\t});\n\n\t\t// Extract attributes\n\t\tconst maxChoices = utils.getNumberAttribute(element, 'maxChoices', 1);\n\t\tconst minChoices = utils.getNumberAttribute(element, 'minChoices', 0);\n\t\tconst interactionClasses = utils.getClasses(element);\n\t\tconst maxSelectionsMessage = utils.getAttribute(element, 'data-max-selections-message', '') || null;\n\t\tconst minSelectionsMessage = utils.getAttribute(element, 'data-min-selections-message', '') || null;\n\n\t\t// Extract prompt (optional)\n\t\tconst promptElements = utils.getChildrenByTag(element, 'prompt');\n\t\tconst prompt = promptElements.length > 0 ? utils.getHtmlContent(promptElements[0]) : null;\n\n\t\t// Extract content HTML (all content except prompt)\n\t\tlet contentHtml = '';\n\t\tfor (const child of element.childNodes) {\n\t\t\t// Skip prompt elements\n\t\t\tif (\n\t\t\t\ttypeof child !== 'string' &&\n\t\t\t\t(child as QTIElement).rawTagName !== 'prompt' &&\n\t\t\t\t(child as QTIElement).rawTagName !== 'qti-prompt'\n\t\t\t) {\n\t\t\t\tcontentHtml += (child as QTIElement).outerHTML || child.toString();\n\t\t\t} else if (typeof child === 'string') {\n\t\t\t\tcontentHtml += child;\n\t\t\t}\n\t\t}\n\n\t\t// Sanitize extracted HTML before rendering via {@html} in the component.\n\t\tcontentHtml = sanitizeHtml(contentHtml, { security: context.config.security });\n\n\t\treturn {\n\t\t\thottextChoices,\n\t\t\tcontentHtml,\n\t\t\tmaxChoices,\n\t\t\tminChoices,\n\t\t\tprompt,\n\t\t\t...(interactionClasses.length > 0 ? { interactionClasses } : {}),\n\t\t\t...(maxSelectionsMessage ? { maxSelectionsMessage } : {}),\n\t\t\t...(minSelectionsMessage ? { minSelectionsMessage } : {}),\n\t\t};\n\t},\n\n\tvalidate(data) {\n\t\tconst errors: string[] = [];\n\t\tconst warnings: string[] = [];\n\n\t\t// Validate hottextChoices exist\n\t\tif (!data.hottextChoices || data.hottextChoices.length === 0) {\n\t\t\terrors.push('hottextInteraction must have at least one hottext');\n\t\t}\n\n\t\t// Validate hottext identifiers\n\t\tif (data.hottextChoices) {\n\t\t\tconst identifiers = new Set<string>();\n\t\t\tfor (const hottext of data.hottextChoices) {\n\t\t\t\tif (!hottext.identifier) {\n\t\t\t\t\terrors.push('All hottext elements must have an identifier');\n\t\t\t\t} else if (identifiers.has(hottext.identifier)) {\n\t\t\t\t\terrors.push(`Duplicate hottext identifier: ${hottext.identifier}`);\n\t\t\t\t} else {\n\t\t\t\t\tidentifiers.add(hottext.identifier);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Validate maxChoices\n\t\tif (data.maxChoices < 0) {\n\t\t\terrors.push('maxChoices must be non-negative');\n\t\t}\n\n\t\t// Warn if maxChoices exceeds hottext count\n\t\tif (data.hottextChoices && data.maxChoices > data.hottextChoices.length) {\n\t\t\twarnings.push(\n\t\t\t\t`maxChoices (${data.maxChoices}) exceeds the number of hottext choices (${data.hottextChoices.length})`\n\t\t\t);\n\t\t}\n\n\t\t// Validate minChoices\n\t\tif (data.minChoices !== undefined && data.minChoices < 0) {\n\t\t\terrors.push('minChoices must be non-negative');\n\t\t}\n\n\t\t// Validate minChoices <= maxChoices\n\t\tif (\n\t\t\tdata.minChoices !== undefined &&\n\t\t\tdata.maxChoices > 0 &&\n\t\t\tdata.minChoices > data.maxChoices\n\t\t) {\n\t\t\terrors.push('minChoices cannot exceed maxChoices');\n\t\t}\n\n\t\treturn {\n\t\t\tvalid: errors.length === 0,\n\t\t\terrors: errors.length > 0 ? errors : undefined,\n\t\t\twarnings: warnings.length > 0 ? warnings : undefined,\n\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UAAU,yBAAyB,IAAI,CAAC,UAAU,4DAA4D,CAClI,CAAC;QACH,CAAC;QAED,OAAO;YACN,KAAK,EAAE,MAAM,CAAC,MAAM,KAAK,CAAC;YAC1B,MAAM,EAAE,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS;YAC9C,QAAQ,EAAE,QAAQ,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,SAAS;SACpD,CAAC;IACH,CAAC;CACD,CAAC","sourcesContent":["/**\n * Standard QTI hottextInteraction extractor\n *\n * Extracts data from hottextInteraction elements (select text spans)\n */\n\nimport { sanitizeHtml } from '../../core/sanitizer.js';\nimport type { QTIElement } from '../shared/types.js';\nimport type { ElementExtractor } from '../../extraction/types.js';\n\n/**\n * Hottext data extracted from hottextInteraction elements\n */\nexport interface HottextData {\n\thottextChoices: Array<{ identifier: string; text: string; classes?: string[] }>;\n\tcontentHtml: string;\n\tmaxChoices: number;\n\tminChoices: number;\n\tprompt: string | null;\n}\n\n/**\n * Standard QTI hottext interaction extractor\n * Handles hottextInteraction elements (selectable text spans)\n */\nexport const standardHottextExtractor: ElementExtractor<HottextData> = {\n\tid: 'qti:hottext-interaction',\n\tname: 'QTI Standard Hottext Interaction',\n\tpriority: 10,\n\telementTypes: ['hottextInteraction'],\n\tdescription: 'Extracts standard QTI hottextInteraction (select text spans)',\n\n\tcanHandle(element, _context) {\n\t\t// All hottextInteraction elements are standard\n\t\treturn element.rawTagName === 'hottextInteraction' || element.rawTagName === 'qti-hottext-interaction';\n\t},\n\n\textract(element, context) {\n\t\tconst { utils } = context;\n\n\t\t// Extract hottext children (selectable text spans) - recursively search entire tree\n\t\tconst findHottextElements = (el: any): any[] => {\n\t\t\tconst results: any[] = [];\n\t\t\tif (el.rawTagName === 'hottext' || el.rawTagName === 'qti-hottext') {\n\t\t\t\tresults.push(el);\n\t\t\t}\n\t\t\tif (el.childNodes) {\n\t\t\t\tfor (const child of el.childNodes) {\n\t\t\t\t\tif (typeof child !== 'string') {\n\t\t\t\t\t\tresults.push(...findHottextElements(child));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn results;\n\t\t};\n\n\t\tconst hottextElements = findHottextElements(element);\n\t\tconst hottextChoices = hottextElements.map((hottext) => {\n\t\t\tconst classes = utils.getClasses(hottext);\n\t\t\treturn {\n\t\t\t\tidentifier: utils.getAttribute(hottext, 'identifier', ''),\n\t\t\t\ttext: utils.getTextContent(hottext),\n\t\t\t\t...(classes.length > 0 ? { classes } : {}),\n\t\t\t};\n\t\t});\n\n\t\t// Extract attributes\n\t\tconst maxChoices = utils.getNumberAttribute(element, 'maxChoices', 1);\n\t\tconst minChoices = utils.getNumberAttribute(element, 'minChoices', 0);\n\t\tconst interactionClasses = utils.getClasses(element);\n\t\tconst maxSelectionsMessage = utils.getAttribute(element, 'data-max-selections-message', '') || null;\n\t\tconst minSelectionsMessage = utils.getAttribute(element, 'data-min-selections-message', '') || null;\n\n\t\t// Extract prompt (optional)\n\t\tconst promptElements = utils.getChildrenByTag(element, 'prompt');\n\t\tconst prompt = promptElements.length > 0 ? utils.getHtmlContent(promptElements[0]) : null;\n\n\t\t// Extract content HTML (all content except prompt)\n\t\tlet contentHtml = '';\n\t\tfor (const child of element.childNodes) {\n\t\t\t// Skip prompt elements\n\t\t\tif (\n\t\t\t\ttypeof child !== 'string' &&\n\t\t\t\t(child as QTIElement).rawTagName !== 'prompt' &&\n\t\t\t\t(child as QTIElement).rawTagName !== 'qti-prompt'\n\t\t\t) {\n\t\t\t\tcontentHtml += (child as QTIElement).outerHTML || child.toString();\n\t\t\t} else if (typeof child === 'string') {\n\t\t\t\tcontentHtml += child;\n\t\t\t}\n\t\t}\n\n\t\t// Sanitize extracted HTML before rendering via {@html} in the component.\n\t\tcontentHtml = sanitizeHtml(contentHtml, { security: context.config.security });\n\n\t\treturn {\n\t\t\thottextChoices,\n\t\t\tcontentHtml,\n\t\t\tmaxChoices,\n\t\t\tminChoices,\n\t\t\tprompt,\n\t\t\t...(interactionClasses.length > 0 ? { interactionClasses } : {}),\n\t\t\t...(maxSelectionsMessage ? { maxSelectionsMessage } : {}),\n\t\t\t...(minSelectionsMessage ? { minSelectionsMessage } : {}),\n\t\t};\n\t},\n\n\tvalidate(data) {\n\t\tconst errors: string[] = [];\n\t\tconst warnings: string[] = [];\n\n\t\t// Validate hottextChoices exist\n\t\tif (!data.hottextChoices || data.hottextChoices.length === 0) {\n\t\t\terrors.push('hottextInteraction must have at least one hottext');\n\t\t}\n\n\t\t// Validate hottext identifiers\n\t\tif (data.hottextChoices) {\n\t\t\tconst identifiers = new Set<string>();\n\t\t\tfor (const hottext of data.hottextChoices) {\n\t\t\t\tif (!hottext.identifier) {\n\t\t\t\t\terrors.push('All hottext elements must have an identifier');\n\t\t\t\t} else if (identifiers.has(hottext.identifier)) {\n\t\t\t\t\terrors.push(`Duplicate hottext identifier: ${hottext.identifier}`);\n\t\t\t\t} else {\n\t\t\t\t\tidentifiers.add(hottext.identifier);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Validate maxChoices\n\t\tif (data.maxChoices < 0) {\n\t\t\terrors.push('maxChoices must be non-negative');\n\t\t}\n\n\t\t// Warn if maxChoices exceeds hottext count\n\t\tif (data.hottextChoices && data.maxChoices > data.hottextChoices.length) {\n\t\t\twarnings.push(\n\t\t\t\t`maxChoices (${data.maxChoices}) exceeds the number of hottext choices (${data.hottextChoices.length})`\n\t\t\t);\n\t\t}\n\n\t\t// Validate minChoices\n\t\tif (data.minChoices !== undefined && data.minChoices < 0) {\n\t\t\terrors.push('minChoices must be non-negative');\n\t\t}\n\n\t\t// Validate minChoices <= maxChoices\n\t\tif (\n\t\t\tdata.minChoices !== undefined &&\n\t\t\tdata.maxChoices > 0 &&\n\t\t\tdata.minChoices > data.maxChoices\n\t\t) {\n\t\t\twarnings.push(\n\t\t\t\t`minChoices (${data.minChoices}) exceeds maxChoices (${data.maxChoices}); rendering interaction with authoring constraint warning`\n\t\t\t);\n\t\t}\n\n\t\treturn {\n\t\t\tvalid: errors.length === 0,\n\t\t\terrors: errors.length > 0 ? errors : undefined,\n\t\t\twarnings: warnings.length > 0 ? warnings : undefined,\n\t\t};\n\t},\n};\n"]}
@@ -28,6 +28,7 @@ export interface CreateItemPresentationPlanOptions {
28
28
  stimulusContent?: Record<string, string>;
29
29
  deliveryContext?: ResolvedItemDeliveryContext;
30
30
  itemBodyScopeSelector?: string;
31
+ renderItemBodyRubrics?: boolean;
31
32
  onComponentError?: (interaction: InteractionData, error: unknown) => void;
32
33
  }
33
34
  export interface BlockInteractionPresentation {
@@ -49,5 +50,5 @@ export interface ItemPresentationPlan {
49
50
  inlineSegments: InlineRenderSegment[];
50
51
  blockInteractions: BlockInteractionPresentation[];
51
52
  }
52
- export declare function createItemPresentationPlan({ player, responses, disabled, role, outcomeValues, heuristicsConfig, stimulusContent, deliveryContext, itemBodyScopeSelector, onComponentError, }: CreateItemPresentationPlanOptions): ItemPresentationPlan;
53
+ export declare function createItemPresentationPlan({ player, responses, disabled, role, outcomeValues, heuristicsConfig, stimulusContent, deliveryContext, itemBodyScopeSelector, renderItemBodyRubrics, onComponentError, }: CreateItemPresentationPlanOptions): ItemPresentationPlan;
53
54
  export declare function interactionKey(interaction: InteractionData): string;
@@ -1,21 +1,24 @@
1
1
  import { normalizeHeuristicsConfig, } from '@pie-qti/ims-cp-core';
2
+ import { parse } from 'node-html-parser';
2
3
  import { getRoleCapabilities } from '../core/rolePolicy.js';
3
4
  import { processFeedbackInline } from '../components/utils/feedbackUtils.js';
4
5
  import { buildScopedStylesheetCss } from '../components/utils/stylesheetRender.js';
5
6
  import { buildEffectiveStimulusContent, injectStimulusContent } from '../components/utils/stimulusRender.js';
6
7
  import { createInlineRenderPlan, isInlineInteractionTagName, isInlineInteractionType, } from '../interactions/inline/render-plan.js';
7
- export function createItemPresentationPlan({ player, responses = {}, disabled = false, role = 'candidate', outcomeValues = {}, heuristicsConfig, stimulusContent = {}, deliveryContext, itemBodyScopeSelector = '[data-qti-item-body-scope]', onComponentError, }) {
8
+ export function createItemPresentationPlan({ player, responses = {}, disabled = false, role = 'candidate', outcomeValues = {}, heuristicsConfig, stimulusContent = {}, deliveryContext, itemBodyScopeSelector = '[data-qti-item-body-scope]', renderItemBodyRubrics = true, onComponentError, }) {
8
9
  const interactions = player.getInteractionData();
9
10
  const roleCapabilities = getRoleCapabilities(role);
10
11
  const effectiveDisabled = disabled || roleCapabilities.isReadOnly;
11
12
  const correctResponses = roleCapabilities.canViewCorrectResponses ? player.getCorrectResponses() : {};
12
13
  const itemBodyHtml = buildItemBodyPresentationHtml({
13
14
  player,
15
+ role,
14
16
  outcomeValues,
15
17
  heuristicsConfig,
16
18
  stimulusContent,
17
19
  deliveryContext,
18
20
  itemBodyScopeSelector,
21
+ renderItemBodyRubrics,
19
22
  });
20
23
  return {
21
24
  roleCapabilities,
@@ -34,7 +37,7 @@ export function createItemPresentationPlan({ player, responses = {}, disabled =
34
37
  }),
35
38
  };
36
39
  }
37
- function buildItemBodyPresentationHtml({ player, outcomeValues, heuristicsConfig, stimulusContent, deliveryContext, itemBodyScopeSelector, }) {
40
+ function buildItemBodyPresentationHtml({ player, role, outcomeValues, heuristicsConfig, stimulusContent, deliveryContext, itemBodyScopeSelector, renderItemBodyRubrics, }) {
38
41
  let html = String(player.getItemBodyHtml());
39
42
  const resolvedDeliveryContext = deliveryContext ?? player.getDeliveryContext();
40
43
  const stylesheetCss = buildScopedStylesheetCss(resolvedDeliveryContext, itemBodyScopeSelector);
@@ -43,6 +46,7 @@ function buildItemBodyPresentationHtml({ player, outcomeValues, heuristicsConfig
43
46
  if (stylesheetCss) {
44
47
  html = `<style data-qti-stylesheets="resolved">${stylesheetCss}</style>${html}`;
45
48
  }
49
+ html = renderRubricBlocksForRole(html, role, { renderRubrics: renderItemBodyRubrics });
46
50
  const heuristics = normalizeHeuristicsConfig(heuristicsConfig);
47
51
  html = processFeedbackInline(html, {
48
52
  outcomeValues,
@@ -51,6 +55,74 @@ function buildItemBodyPresentationHtml({ player, outcomeValues, heuristicsConfig
51
55
  });
52
56
  return hideBlockInteractionMarkup(html);
53
57
  }
58
+ function renderRubricBlocksForRole(html, role, { renderRubrics }) {
59
+ if (!html || !/rubric-?block/i.test(html)) {
60
+ return html;
61
+ }
62
+ try {
63
+ const root = parse(html, { lowerCaseTagName: false, comment: false });
64
+ renderRubricBlockChildren(root, role, { renderRubrics });
65
+ return root.toString();
66
+ }
67
+ catch {
68
+ return html;
69
+ }
70
+ }
71
+ function renderRubricBlockChildren(element, role, { renderRubrics }) {
72
+ const children = [...element.childNodes];
73
+ for (const child of children) {
74
+ const tagName = child.rawTagName?.toLowerCase();
75
+ if (tagName &&
76
+ isRubricBlockTag(tagName) &&
77
+ (!renderRubrics || !rubricBlockVisibleToRole(child, role))) {
78
+ child.remove();
79
+ continue;
80
+ }
81
+ if (child.childNodes?.length) {
82
+ renderRubricBlockChildren(child, role, { renderRubrics });
83
+ }
84
+ if (tagName && isRubricBlockTag(tagName)) {
85
+ child.replaceWith(renderRubricBlockWrapper(child));
86
+ }
87
+ }
88
+ }
89
+ function isRubricBlockTag(tagName) {
90
+ return tagName === 'rubricblock' || tagName === 'qti-rubric-block';
91
+ }
92
+ function rubricBlockVisibleToRole(element, role) {
93
+ const view = element.getAttribute('view')?.trim();
94
+ if (!view) {
95
+ return true;
96
+ }
97
+ return splitRubricView(view).includes(role);
98
+ }
99
+ function renderRubricBlockWrapper(element) {
100
+ const view = element.getAttribute('view')?.trim();
101
+ const use = element.getAttribute('use')?.trim();
102
+ const attrs = [
103
+ 'class="qti-rubric-block"',
104
+ view ? `data-qti-rubric-view="${escapeHtmlAttribute(view)}"` : '',
105
+ use ? `data-qti-rubric-use="${escapeHtmlAttribute(use)}"` : '',
106
+ ]
107
+ .filter(Boolean)
108
+ .join(' ');
109
+ return `<div ${attrs}>${serializeHtmlChildren(element)}</div>`;
110
+ }
111
+ function splitRubricView(view) {
112
+ return view.split(/[\s,]+/).filter(Boolean);
113
+ }
114
+ function serializeHtmlChildren(element) {
115
+ return [...element.childNodes]
116
+ .map((child) => child.toString())
117
+ .join('');
118
+ }
119
+ function escapeHtmlAttribute(value) {
120
+ return value
121
+ .replace(/&/g, '&amp;')
122
+ .replace(/"/g, '&quot;')
123
+ .replace(/</g, '&lt;')
124
+ .replace(/>/g, '&gt;');
125
+ }
54
126
  function hideBlockInteractionMarkup(html) {
55
127
  return html.replace(/<(\w+Interaction|qti-[\w-]+-interaction)(\s[^>]*)?>[\s\S]*?<\/\1>/gi, (match, tagName) => {
56
128
  const lower = tagName.toLowerCase();
@@ -1 +1 @@
1
- {"version":3,"file":"itemPresentationPlan.js","sourceRoot":"","sources":["../../src/presentation/itemPresentationPlan.ts"],"names":[],"mappings":"AACA,OAAO,EACN,yBAAyB,GAEzB,MAAM,sBAAsB,CAAC;AAE9B,OAAO,EAAE,mBAAmB,EAAyB,MAAM,uBAAuB,CAAC;AAEnF,OAAO,EAAE,qBAAqB,EAAE,MAAM,sCAAsC,CAAC;AAC7E,OAAO,EAAE,wBAAwB,EAAE,MAAM,yCAAyC,CAAC;AACnF,OAAO,EAAE,6BAA6B,EAAE,qBAAqB,EAAE,MAAM,uCAAuC,CAAC;AAC7G,OAAO,EACN,sBAAsB,EACtB,0BAA0B,EAC1B,uBAAuB,GAEvB,MAAM,uCAAuC,CAAC;AAqD/C,MAAM,UAAU,0BAA0B,CAAC,EAC1C,MAAM,EACN,SAAS,GAAG,EAAE,EACd,QAAQ,GAAG,KAAK,EAChB,IAAI,GAAG,WAAW,EAClB,aAAa,GAAG,EAAE,EAClB,gBAAgB,EAChB,eAAe,GAAG,EAAE,EACpB,eAAe,EACf,qBAAqB,GAAG,4BAA4B,EACpD,gBAAgB,GACmB;IACnC,MAAM,YAAY,GAAG,MAAM,CAAC,kBAAkB,EAAE,CAAC;IACjD,MAAM,gBAAgB,GAAG,mBAAmB,CAAC,IAAI,C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DeliveryContext } from '@pie-qti/ims-cp-core';\nimport {\n\tnormalizeHeuristicsConfig,\n\ttype QtiHeuristicsConfig,\n} from '@pie-qti/ims-cp-core';\nimport type { PnpProfile } from '../pnp/types.js';\nimport { getRoleCapabilities, type RoleCapabilities } from '../core/rolePolicy.js';\nimport type { InteractionData, HtmlContent, QTIRole } from '../types/index.js';\nimport { processFeedbackInline } from '../components/utils/feedbackUtils.js';\nimport { buildScopedStylesheetCss } from '../components/utils/stylesheetRender.js';\nimport { buildEffectiveStimulusContent, injectStimulusContent } from '../components/utils/stimulusRender.js';\nimport {\n\tcreateInlineRenderPlan,\n\tisInlineInteractionTagName,\n\tisInlineInteractionType,\n\ttype InlineRenderSegment,\n} from '../interactions/inline/render-plan.js';\n\nexport type ItemPresentationResponseValue = unknown;\nexport type ItemPresentationResponseMap = Record<string, ItemPresentationResponseValue>;\n\nexport interface ItemPresentationComponentRegistry {\n\tgetTagName(interaction: InteractionData): string;\n}\n\nexport interface ItemPresentationPlayer {\n\tgetComponentRegistry(): ItemPresentationComponentRegistry;\n\tgetInteractionData(): InteractionData[];\n\tgetCorrectResponses(): Record<string, unknown>;\n\tgetItemBodyHtml(): HtmlContent;\n\tgetDeliveryContext(): ResolvedItemDeliveryContext | undefined;\n\tsanitizeHtmlContent(html: string): string;\n\tgetPnp(): PnpProfile | undefined;\n}\n\nexport interface CreateItemPresentationPlanOptions {\n\tplayer: ItemPresentationPlayer;\n\tresponses?: ItemPresentationResponseMap;\n\tdisabled?: boolean;\n\trole?: QTIRole;\n\toutcomeValues?: Record<string, unknown>;\n\theuristicsConfig?: QtiHeuristicsConfig;\n\tstimulusContent?: Record<string, string>;\n\tdeliveryContext?: ResolvedItemDeliveryContext;\n\titemBodyScopeSelector?: string;\n\tonComponentError?: (interaction: InteractionData, error: unknown) => void;\n}\n\nexport interface BlockInteractionPresentation {\n\tinteraction: InteractionData;\n\ttagName: string;\n\tkey: string;\n\tresponse: ItemPresentationResponseValue | null;\n\tcorrectResponse: unknown;\n\tpnp: PnpProfile | undefined;\n\teliminationTool: boolean;\n\tdisabled: boolean;\n\tcomponentRole: 'scorer' | undefined;\n}\n\nexport interface ItemPresentationPlan {\n\troleCapabilities: RoleCapabilities;\n\teffectiveDisabled: boolean;\n\tcorrectResponses: Record<string, unknown>;\n\titemBodyHtml: string;\n\tinlineSegments: InlineRenderSegment[];\n\tblockInteractions: BlockInteractionPresentation[];\n}\n\nexport function createItemPresentationPlan({\n\tplayer,\n\tresponses = {},\n\tdisabled = false,\n\trole = 'candidate',\n\toutcomeValues = {},\n\theuristicsConfig,\n\tstimulusContent = {},\n\tdeliveryContext,\n\titemBodyScopeSelector = '[data-qti-item-body-scope]',\n\tonComponentError,\n}: CreateItemPresentationPlanOptions): ItemPresentationPlan {\n\tconst interactions = player.getInteractionData();\n\tconst roleCapabilities = getRoleCapabilities(role);\n\tconst effectiveDisabled = disabled || roleCapabilities.isReadOnly;\n\tconst correctResponses = roleCapabilities.canViewCorrectResponses ? player.getCorrectResponses() : {};\n\tconst itemBodyHtml = buildItemBodyPresentationHtml({\n\t\tplayer,\n\t\toutcomeValues,\n\t\theuristicsConfig,\n\t\tstimulusContent,\n\t\tdeliveryContext,\n\t\titemBodyScopeSelector,\n\t});\n\n\treturn {\n\t\troleCapabilities,\n\t\teffectiveDisabled,\n\t\tcorrectResponses,\n\t\titemBodyHtml,\n\t\tinlineSegments: createInlineRenderPlan(itemBodyHtml, interactions),\n\t\tblockInteractions: createBlockInteractionPresentations({\n\t\t\tinteractions,\n\t\t\tplayer,\n\t\t\tresponses,\n\t\t\tcorrectResponses,\n\t\t\troleCapabilities,\n\t\t\teffectiveDisabled,\n\t\t\tonComponentError,\n\t\t}),\n\t};\n}\n\nfunction buildItemBodyPresentationHtml({\n\tplayer,\n\toutcomeValues,\n\theuristicsConfig,\n\tstimulusContent,\n\tdeliveryContext,\n\titemBodyScopeSelector,\n}: {\n\tplayer: ItemPresentationPlayer;\n\toutcomeValues: Record<string, unknown>;\n\theuristicsConfig: QtiHeuristicsConfig | undefined;\n\tstimulusContent: Record<string, string>;\n\tdeliveryContext: ResolvedItemDeliveryContext | undefined;\n\titemBodyScopeSelector: string;\n}): string {\n\tlet html = String(player.getItemBodyHtml());\n\tconst resolvedDeliveryContext = deliveryContext ?? player.getDeliveryContext();\n\tconst stylesheetCss = buildScopedStylesheetCss(resolvedDeliveryContext, itemBodyScopeSelector);\n\tconst effectiveStimulusContent = buildEffectiveStimulusContent(\n\t\tresolvedDeliveryContext,\n\t\tstimulusContent,\n\t\t(content) => player.sanitizeHtmlContent(content)\n\t);\n\n\thtml = injectStimulusContent(html, effectiveStimulusContent);\n\tif (stylesheetCss) {\n\t\thtml = `<style data-qti-stylesheets=\"resolved\">${stylesheetCss}</style>${html}`;\n\t}\n\n\tconst heuristics = normalizeHeuristicsConfig(heuristicsConfig);\n\thtml = processFeedbackInline(html, {\n\t\toutcomeValues,\n\t\tapplyHeuristics: heuristics.feedbackTextFormatting,\n\t\twrapWithSpan: false,\n\t});\n\n\treturn hideBlockInteractionMarkup(html);\n}\n\nfunction hideBlockInteractionMarkup(html: string): string {\n\treturn html.replace(\n\t\t/<(\\w+Interaction|qti-[\\w-]+-interaction)(\\s[^>]*)?>[\\s\\S]*?<\\/\\1>/gi,\n\t\t(match, tagName) => {\n\t\t\tconst lower = tagName.toLowerCase();\n\t\t\tif (isInlineInteractionTagName(lower)) return match;\n\t\t\treturn `<span class=\"qti-hidden-interaction\">${match}</span>`;\n\t\t}\n\t);\n}\n\nfunction createBlockInteractionPresentations({\n\tinteractions,\n\tplayer,\n\tresponses,\n\tcorrectResponses,\n\troleCapabilities,\n\teffectiveDisabled,\n\tonComponentError,\n}: {\n\tinteractions: InteractionData[];\n\tplayer: ItemPresentationPlayer;\n\tresponses: ItemPresentationResponseMap;\n\tcorrectResponses: Record<string, unknown>;\n\troleCapabilities: RoleCapabilities;\n\teffectiveDisabled: boolean;\n\tonComponentError?: (interaction: InteractionData, error: unknown) => void;\n}): BlockInteractionPresentation[] {\n\tconst componentRegistry = player.getComponentRegistry();\n\treturn interactions\n\t\t.filter((interaction) => !isInlineInteractionType(interaction.type))\n\t\t.map((interaction) => {\n\t\t\ttry {\n\t\t\t\tconst block: BlockInteractionPresentation = {\n\t\t\t\t\tinteraction,\n\t\t\t\t\ttagName: componentRegistry.getTagName(interaction),\n\t\t\t\t\tkey: interactionKey(interaction),\n\t\t\t\t\tresponse: responses[interaction.responseId] ?? null,\n\t\t\t\t\tcorrectResponse: roleCapabilities.canViewCorrectResponses\n\t\t\t\t\t\t? (correctResponses[interaction.responseId] ?? null)\n\t\t\t\t\t\t: null,\n\t\t\t\t\tpnp: player.getPnp(),\n\t\t\t\t\teliminationTool: player.getPnp()?.cognitive?.eliminationTool === true,\n\t\t\t\t\tdisabled: effectiveDisabled,\n\t\t\t\t\tcomponentRole: roleCapabilities.canViewCorrectResponses ? 'scorer' : undefined,\n\t\t\t\t};\n\t\t\t\treturn block;\n\t\t\t} catch (error) {\n\t\t\t\tonComponentError?.(interaction, error);\n\t\t\t\treturn null;\n\t\t\t}\n\t\t})\n\t\t.filter((item): item is BlockInteractionPresentation => item !== null);\n}\n\nexport function interactionKey(interaction: InteractionData): string {\n\tconst anyInteraction = interaction as any;\n\tconst ids =\n\t\tArray.isArray(anyInteraction?.choices) && anyInteraction.choices.length > 0\n\t\t\t? anyInteraction.choices.map((choice: any) => choice?.identifier).filter(Boolean).join(',')\n\t\t\t: '';\n\tconst prompt = typeof anyInteraction?.prompt === 'string' ? anyInteraction.prompt : '';\n\treturn `${interaction.type}|${interaction.responseId}|${ids}|${prompt}`;\n}\n"]}
1
+ {"version":3,"file":"itemPresentationPlan.js","sourceRoot":"","sources":["../../src/presentation/itemPresentationPlan.ts"],"names":[],"mappings":"AACA,OAAO,EACN,yBAAyB,GAEzB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,KAAK,EAAE,MAAM,kBAAkB,CAAC;AAGzC,OAAO,EAAE,mBAAmB,EAAyB,MAAM,uB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ype QtiHeuristicsConfig,\n} from '@pie-qti/ims-cp-core';\nimport { parse } from 'node-html-parser';\nimport type { HTMLElement as ParsedHtmlElement } from 'node-html-parser';\nimport type { PnpProfile } from '../pnp/types.js';\nimport { getRoleCapabilities, type RoleCapabilities } from '../core/rolePolicy.js';\nimport type { InteractionData, HtmlContent, QTIRole } from '../types/index.js';\nimport { processFeedbackInline } from '../components/utils/feedbackUtils.js';\nimport { buildScopedStylesheetCss } from '../components/utils/stylesheetRender.js';\nimport { buildEffectiveStimulusContent, injectStimulusContent } from '../components/utils/stimulusRender.js';\nimport {\n\tcreateInlineRenderPlan,\n\tisInlineInteractionTagName,\n\tisInlineInteractionType,\n\ttype InlineRenderSegment,\n} from '../interactions/inline/render-plan.js';\n\nexport type ItemPresentationResponseValue = unknown;\nexport type ItemPresentationResponseMap = Record<string, ItemPresentationResponseValue>;\n\nexport interface ItemPresentationComponentRegistry {\n\tgetTagName(interaction: InteractionData): string;\n}\n\nexport interface ItemPresentationPlayer {\n\tgetComponentRegistry(): ItemPresentationComponentRegistry;\n\tgetInteractionData(): InteractionData[];\n\tgetCorrectResponses(): Record<string, unknown>;\n\tgetItemBodyHtml(): HtmlContent;\n\tgetDeliveryContext(): ResolvedItemDeliveryContext | undefined;\n\tsanitizeHtmlContent(html: string): string;\n\tgetPnp(): PnpProfile | undefined;\n}\n\nexport interface CreateItemPresentationPlanOptions {\n\tplayer: ItemPresentationPlayer;\n\tresponses?: ItemPresentationResponseMap;\n\tdisabled?: boolean;\n\trole?: QTIRole;\n\toutcomeValues?: Record<string, unknown>;\n\theuristicsConfig?: QtiHeuristicsConfig;\n\tstimulusContent?: Record<string, string>;\n\tdeliveryContext?: ResolvedItemDeliveryContext;\n\titemBodyScopeSelector?: string;\n\trenderItemBodyRubrics?: boolean;\n\tonComponentError?: (interaction: InteractionData, error: unknown) => void;\n}\n\nexport interface BlockInteractionPresentation {\n\tinteraction: InteractionData;\n\ttagName: string;\n\tkey: string;\n\tresponse: ItemPresentationResponseValue | null;\n\tcorrectResponse: unknown;\n\tpnp: PnpProfile | undefined;\n\teliminationTool: boolean;\n\tdisabled: boolean;\n\tcomponentRole: 'scorer' | undefined;\n}\n\nexport interface ItemPresentationPlan {\n\troleCapabilities: RoleCapabilities;\n\teffectiveDisabled: boolean;\n\tcorrectResponses: Record<string, unknown>;\n\titemBodyHtml: string;\n\tinlineSegments: InlineRenderSegment[];\n\tblockInteractions: BlockInteractionPresentation[];\n}\n\nexport function createItemPresentationPlan({\n\tplayer,\n\tresponses = {},\n\tdisabled = false,\n\trole = 'candidate',\n\toutcomeValues = {},\n\theuristicsConfig,\n\tstimulusContent = {},\n\tdeliveryContext,\n\titemBodyScopeSelector = '[data-qti-item-body-scope]',\n\trenderItemBodyRubrics = true,\n\tonComponentError,\n}: CreateItemPresentationPlanOptions): ItemPresentationPlan {\n\tconst interactions = player.getInteractionData();\n\tconst roleCapabilities = getRoleCapabilities(role);\n\tconst effectiveDisabled = disabled || roleCapabilities.isReadOnly;\n\tconst correctResponses = roleCapabilities.canViewCorrectResponses ? player.getCorrectResponses() : {};\n\tconst itemBodyHtml = buildItemBodyPresentationHtml({\n\t\tplayer,\n\t\trole,\n\t\toutcomeValues,\n\t\theuristicsConfig,\n\t\tstimulusContent,\n\t\tdeliveryContext,\n\t\titemBodyScopeSelector,\n\t\trenderItemBodyRubrics,\n\t});\n\n\treturn {\n\t\troleCapabilities,\n\t\teffectiveDisabled,\n\t\tcorrectResponses,\n\t\titemBodyHtml,\n\t\tinlineSegments: createInlineRenderPlan(itemBodyHtml, interactions),\n\t\tblockInteractions: createBlockInteractionPresentations({\n\t\t\tinteractions,\n\t\t\tplayer,\n\t\t\tresponses,\n\t\t\tcorrectResponses,\n\t\t\troleCapabilities,\n\t\t\teffectiveDisabled,\n\t\t\tonComponentError,\n\t\t}),\n\t};\n}\n\nfunction buildItemBodyPresentationHtml({\n\tplayer,\n\trole,\n\toutcomeValues,\n\theuristicsConfig,\n\tstimulusContent,\n\tdeliveryContext,\n\titemBodyScopeSelector,\n\trenderItemBodyRubrics,\n}: {\n\tplayer: ItemPresentationPlayer;\n\trole: QTIRole;\n\toutcomeValues: Record<string, unknown>;\n\theuristicsConfig: QtiHeuristicsConfig | undefined;\n\tstimulusContent: Record<string, string>;\n\tdeliveryContext: ResolvedItemDeliveryContext | undefined;\n\titemBodyScopeSelector: string;\n\trenderItemBodyRubrics: boolean;\n}): string {\n\tlet html = String(player.getItemBodyHtml());\n\tconst resolvedDeliveryContext = deliveryContext ?? player.getDeliveryContext();\n\tconst stylesheetCss = buildScopedStylesheetCss(resolvedDeliveryContext, itemBodyScopeSelector);\n\tconst effectiveStimulusContent = buildEffectiveStimulusContent(\n\t\tresolvedDeliveryContext,\n\t\tstimulusContent,\n\t\t(content) => player.sanitizeHtmlContent(content)\n\t);\n\n\thtml = injectStimulusContent(html, effectiveStimulusContent);\n\tif (stylesheetCss) {\n\t\thtml = `<style data-qti-stylesheets=\"resolved\">${stylesheetCss}</style>${html}`;\n\t}\n\thtml = renderRubricBlocksForRole(html, role, { renderRubrics: renderItemBodyRubrics });\n\n\tconst heuristics = normalizeHeuristicsConfig(heuristicsConfig);\n\thtml = processFeedbackInline(html, {\n\t\toutcomeValues,\n\t\tapplyHeuristics: heuristics.feedbackTextFormatting,\n\t\twrapWithSpan: false,\n\t});\n\n\treturn hideBlockInteractionMarkup(html);\n}\n\nfunction renderRubricBlocksForRole(\n\thtml: string,\n\trole: QTIRole,\n\t{ renderRubrics }: { renderRubrics: boolean }\n): string {\n\tif (!html || !/rubric-?block/i.test(html)) {\n\t\treturn html;\n\t}\n\n\ttry {\n\t\tconst root = parse(html, { lowerCaseTagName: false, comment: false });\n\t\trenderRubricBlockChildren(root as unknown as ParsedHtmlElement, role, { renderRubrics });\n\t\treturn root.toString();\n\t} catch {\n\t\treturn html;\n\t}\n}\n\nfunction renderRubricBlockChildren(\n\telement: ParsedHtmlElement,\n\trole: QTIRole,\n\t{ renderRubrics }: { renderRubrics: boolean }\n): void {\n\tconst children = [...element.childNodes] as unknown as ParsedHtmlElement[];\n\tfor (const child of children) {\n\t\tconst tagName = child.rawTagName?.toLowerCase();\n\t\tif (\n\t\t\ttagName &&\n\t\t\tisRubricBlockTag(tagName) &&\n\t\t\t(!renderRubrics || !rubricBlockVisibleToRole(child, role))\n\t\t) {\n\t\t\tchild.remove();\n\t\t\tcontinue;\n\t\t}\n\t\tif (child.childNodes?.length) {\n\t\t\trenderRubricBlockChildren(child, role, { renderRubrics });\n\t\t}\n\t\tif (tagName && isRubricBlockTag(tagName)) {\n\t\t\tchild.replaceWith(renderRubricBlockWrapper(child));\n\t\t}\n\t}\n}\n\nfunction isRubricBlockTag(tagName: string): boolean {\n\treturn tagName === 'rubricblock' || tagName === 'qti-rubric-block';\n}\n\nfunction rubricBlockVisibleToRole(element: ParsedHtmlElement, role: QTIRole): boolean {\n\tconst view = element.getAttribute('view')?.trim();\n\tif (!view) {\n\t\treturn true;\n\t}\n\treturn splitRubricView(view).includes(role);\n}\n\nfunction renderRubricBlockWrapper(element: ParsedHtmlElement): string {\n\tconst view = element.getAttribute('view')?.trim();\n\tconst use = element.getAttribute('use')?.trim();\n\tconst attrs = [\n\t\t'class=\"qti-rubric-block\"',\n\t\tview ? `data-qti-rubric-view=\"${escapeHtmlAttribute(view)}\"` : '',\n\t\tuse ? `data-qti-rubric-use=\"${escapeHtmlAttribute(use)}\"` : '',\n\t]\n\t\t.filter(Boolean)\n\t\t.join(' ');\n\treturn `<div ${attrs}>${serializeHtmlChildren(element)}</div>`;\n}\n\nfunction splitRubricView(view: string): string[] {\n\treturn view.split(/[\\s,]+/).filter(Boolean);\n}\n\nfunction serializeHtmlChildren(element: ParsedHtmlElement): string {\n\treturn ([...element.childNodes] as unknown as ParsedHtmlElement[])\n\t\t.map((child) => child.toString())\n\t\t.join('');\n}\n\nfunction escapeHtmlAttribute(value: string): string {\n\treturn value\n\t\t.replace(/&/g, '&amp;')\n\t\t.replace(/\"/g, '&quot;')\n\t\t.replace(/</g, '&lt;')\n\t\t.replace(/>/g, '&gt;');\n}\n\nfunction hideBlockInteractionMarkup(html: string): string {\n\treturn html.replace(\n\t\t/<(\\w+Interaction|qti-[\\w-]+-interaction)(\\s[^>]*)?>[\\s\\S]*?<\\/\\1>/gi,\n\t\t(match, tagName) => {\n\t\t\tconst lower = tagName.toLowerCase();\n\t\t\tif (isInlineInteractionTagName(lower)) return match;\n\t\t\treturn `<span class=\"qti-hidden-interaction\">${match}</span>`;\n\t\t}\n\t);\n}\n\nfunction createBlockInteractionPresentations({\n\tinteractions,\n\tplayer,\n\tresponses,\n\tcorrectResponses,\n\troleCapabilities,\n\teffectiveDisabled,\n\tonComponentError,\n}: {\n\tinteractions: InteractionData[];\n\tplayer: ItemPresentationPlayer;\n\tresponses: ItemPresentationResponseMap;\n\tcorrectResponses: Record<string, unknown>;\n\troleCapabilities: RoleCapabilities;\n\teffectiveDisabled: boolean;\n\tonComponentError?: (interaction: InteractionData, error: unknown) => void;\n}): BlockInteractionPresentation[] {\n\tconst componentRegistry = player.getComponentRegistry();\n\treturn interactions\n\t\t.filter((interaction) => !isInlineInteractionType(interaction.type))\n\t\t.map((interaction) => {\n\t\t\ttry {\n\t\t\t\tconst block: BlockInteractionPresentation = {\n\t\t\t\t\tinteraction,\n\t\t\t\t\ttagName: componentRegistry.getTagName(interaction),\n\t\t\t\t\tkey: interactionKey(interaction),\n\t\t\t\t\tresponse: responses[interaction.responseId] ?? null,\n\t\t\t\t\tcorrectResponse: roleCapabilities.canViewCorrectResponses\n\t\t\t\t\t\t? (correctResponses[interaction.responseId] ?? null)\n\t\t\t\t\t\t: null,\n\t\t\t\t\tpnp: player.getPnp(),\n\t\t\t\t\teliminationTool: player.getPnp()?.cognitive?.eliminationTool === true,\n\t\t\t\t\tdisabled: effectiveDisabled,\n\t\t\t\t\tcomponentRole: roleCapabilities.canViewCorrectResponses ? 'scorer' : undefined,\n\t\t\t\t};\n\t\t\t\treturn block;\n\t\t\t} catch (error) {\n\t\t\t\tonComponentError?.(interaction, error);\n\t\t\t\treturn null;\n\t\t\t}\n\t\t})\n\t\t.filter((item): item is BlockInteractionPresentation => item !== null);\n}\n\nexport function interactionKey(interaction: InteractionData): string {\n\tconst anyInteraction = interaction as any;\n\tconst ids =\n\t\tArray.isArray(anyInteraction?.choices) && anyInteraction.choices.length > 0\n\t\t\t? anyInteraction.choices.map((choice: any) => choice?.identifier).filter(Boolean).join(',')\n\t\t\t: '';\n\tconst prompt = typeof anyInteraction?.prompt === 'string' ? anyInteraction.prompt : '';\n\treturn `${interaction.type}|${interaction.responseId}|${ids}|${prompt}`;\n}\n"]}
@@ -0,0 +1,14 @@
1
+ import { sanitizeHtml, sanitizeTextContent, type SanitizeHtmlOptions } from '../core/sanitizer.js';
2
+ import { sanitizeResourceUrl, type UrlKind } from '../core/urlPolicy.js';
3
+ import { toTrustedHtml, htmlToString } from '../core/trustedTypes.js';
4
+ import type { HtmlContent, PlayerSecurityConfig } from '../types/index.js';
5
+ export { sanitizeHtml, sanitizeTextContent, type SanitizeHtmlOptions };
6
+ export { sanitizeResourceUrl, type UrlKind };
7
+ export { enforceItemXmlLimits, normalizeParsingLimits, type NormalizedParsingLimits, } from '../core/parsingLimits.js';
8
+ export { toTrustedHtml, htmlToString };
9
+ export { applyInteractionSecurity } from '../extraction/interactionSecurity.js';
10
+ export type { HtmlContent, ParsingLimitsConfig, PlayerSecurityConfig, TrustedTypesHtml, UrlPolicyConfig, } from '../types/index.js';
11
+ export interface SanitizeSharedHtmlOptions {
12
+ sanitizeUrl?: SanitizeHtmlOptions['sanitizeUrl'];
13
+ }
14
+ export declare function sanitizeSharedHtml(html: string, security?: PlayerSecurityConfig, options?: SanitizeSharedHtmlOptions): HtmlContent;
@@ -0,0 +1,13 @@
1
+ import { sanitizeHtml, sanitizeTextContent } from '../core/sanitizer.js';
2
+ import { sanitizeResourceUrl } from '../core/urlPolicy.js';
3
+ import { toTrustedHtml, htmlToString } from '../core/trustedTypes.js';
4
+ export { sanitizeHtml, sanitizeTextContent };
5
+ export { sanitizeResourceUrl };
6
+ export { enforceItemXmlLimits, normalizeParsingLimits, } from '../core/parsingLimits.js';
7
+ export { toTrustedHtml, htmlToString };
8
+ export { applyInteractionSecurity } from '../extraction/interactionSecurity.js';
9
+ export function sanitizeSharedHtml(html, security, options) {
10
+ const sanitized = sanitizeHtml(html, { security, sanitizeUrl: options?.sanitizeUrl });
11
+ return toTrustedHtml(sanitized, security?.trustedTypesPolicyName);
12
+ }
13
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/security/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,mBAAmB,EAA4B,MAAM,sBAAsB,CAAC;AACnG,OAAO,EAAE,mBAAmB,EAAgB,MAAM,sBAAsB,CAAC;AACzE,OAAO,EAAE,aAAa,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAC;AAGtE,OAAO,EAAE,YAAY,EAAE,mBAAmB,EAA4B,CAAC;AACvE,OAAO,EAAE,mBAAmB,EAAgB,CAAC;AAC7C,OAAO,EACN,oBAAoB,EACpB,sBAAsB,GAEtB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,aAAa,EAAE,YAAY,EAAE,CAAC;AACvC,OAAO,EAAE,wBAAwB,EAAE,MAAM,sCAAsC,CAAC;AAahF,MAAM,UAAU,kBAAkB,CACjC,IAAY,EACZ,QAA+B,EAC/B,OAAmC;IAEnC,MAAM,SAAS,GAAG,YAAY,CAAC,IAAI,EAAE,EAAE,QAAQ,EAAE,WAAW,EAAE,OAAO,EAAE,WAAW,EAAE,CAAC,CAAC;IACtF,OAAO,aAAa,CAAC,SAAS,EAAE,QAAQ,EAAE,sBAAsB,CAAC,CAAC;AACnE,CAAC","sourcesContent":["import { sanitizeHtml, sanitizeTextContent, type SanitizeHtmlOptions } from '../core/sanitizer.js';\nimport { sanitizeResourceUrl, type UrlKind } from '../core/urlPolicy.js';\nimport { toTrustedHtml, htmlToString } from '../core/trustedTypes.js';\nimport type { HtmlContent, PlayerSecurityConfig } from '../types/index.js';\n\nexport { sanitizeHtml, sanitizeTextContent, type SanitizeHtmlOptions };\nexport { sanitizeResourceUrl, type UrlKind };\nexport {\n\tenforceItemXmlLimits,\n\tnormalizeParsingLimits,\n\ttype NormalizedParsingLimits,\n} from '../core/parsingLimits.js';\nexport { toTrustedHtml, htmlToString };\nexport { applyInteractionSecurity } from '../extraction/interactionSecurity.js';\nexport type {\n\tHtmlContent,\n\tParsingLimitsConfig,\n\tPlayerSecurityConfig,\n\tTrustedTypesHtml,\n\tUrlPolicyConfig,\n} from '../types/index.js';\n\nexport interface SanitizeSharedHtmlOptions {\n\tsanitizeUrl?: SanitizeHtmlOptions['sanitizeUrl'];\n}\n\nexport function sanitizeSharedHtml(\n\thtml: string,\n\tsecurity?: PlayerSecurityConfig,\n\toptions?: SanitizeSharedHtmlOptions\n): HtmlContent {\n\tconst sanitized = sanitizeHtml(html, { security, sanitizeUrl: options?.sanitizeUrl });\n\treturn toTrustedHtml(sanitized, security?.trustedTypesPolicyName);\n}\n"]}
@@ -188,9 +188,19 @@ export interface AdaptiveAttemptResult extends ScoringResult {
188
188
  * policy layered on top of these roles.
189
189
  */
190
190
  export type QTIRole = 'candidate' | 'scorer' | 'proctor' | 'testConstructor' | 'tutor' | 'author';
191
+ export type RubricBlockScope = 'direct' | 'itemBody';
192
+ export interface RubricBlockOptions {
193
+ /**
194
+ * `direct` rubrics are assessment-item children and are intended for host placement.
195
+ * `itemBody` rubrics are authored in the visible item body flow.
196
+ */
197
+ scope?: RubricBlockScope | 'all';
198
+ }
191
199
  export interface RubricBlock {
192
200
  view: string[];
193
201
  html: HtmlContent;
202
+ scope: RubricBlockScope;
203
+ use?: string;
194
204
  }
195
205
  /**
196
206
  * QTI specification compliance configuration.
@@ -295,6 +305,10 @@ export interface UrlPolicyConfig {
295
305
  allowDataImages?: boolean;
296
306
  /** Allow data:image/svg+xml (default false) */
297
307
  allowSvgDataImages?: boolean;
308
+ /** Allow blob: URLs for package-resolved images (default false). */
309
+ allowBlobImages?: boolean;
310
+ /** Allow blob: URLs for package-resolved audio/video media (default false). */
311
+ allowBlobMedia?: boolean;
298
312
  /** Optional allowlist of hostnames for absolute URLs (exact match). */
299
313
  allowedHosts?: string[];
300
314
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/types/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AA6YH,cAAc,yBAAyB,CAAC","sourcesContent":["/**\n * Core QTI types for the player\n */\n\nimport type {\n\tBaseType as ProcessingBaseType,\n\tCardinality as ProcessingCardinality,\n\tQtiValue,\n} from '@pie-qti/qti-processing';\nimport type { ResolvedItemDeliveryContext } from '@pie-qti/ims-cp-core';\nimport type { ResponseValidationResult } from './responseValidation.js';\n\n/**\n * QTI base type identifier\n * Extensible string type allows custom base types\n */\nexport type VariableBaseType = ProcessingBaseType;\n\n/**\n * QTI cardinality identifier\n * Extensible string type allows custom cardinality values\n */\nexport type VariableCardinality = ProcessingCardinality;\n\nexport interface VariableDeclaration {\n\tidentifier: string;\n\tbaseType: VariableBaseType;\n\tcardinality: VariableCardinality;\n\tvalue: any;\n\tdefaultValue?: any;\n\tmapping?: Mapping;\n\tareaMapping?: AreaMapping;\n}\n\nexport interface Mapping {\n\tdefaultValue?: number;\n\tlowerBound?: number;\n\tupperBound?: number;\n\t/**\n\t * QTI attribute on <mapping>. When \"false\", string mappings are case-insensitive by default.\n\t * Stored as raw string to match XML attribute values (\"true\"/\"false\").\n\t */\n\tcaseSensitive?: string;\n\tentries: Record<string, MapEntry>;\n}\n\nexport interface MapEntry {\n\tmapKey: string;\n\tmappedValue: number;\n\tcaseSensitive?: string;\n}\n\nexport interface AreaMapping {\n\tdefaultValue?: number;\n\tlowerBound?: number;\n\tupperBound?: number;\n\tentries: AreaMapEntry[];\n}\n\nexport interface AreaMapEntry {\n\tshape: 'circle' | 'rect' | 'poly' | 'ellipse' | 'default';\n\tcoords: string;\n\tmappedValue: number;\n}\n\nexport interface ResponseDeclaration extends VariableDeclaration {\n\tcorrectResponse?: any;\n}\n\nexport interface OutcomeDeclaration extends VariableDeclaration {\n\tinterpretation?: string;\n\tlongInterpretation?: string;\n\tnormalMaximum?: number;\n\tnormalMinimum?: number;\n\tmasteryValue?: number;\n\tviews?: string[];\n}\n\nexport interface ItemSessionState {\n\t[variableId: string]: any;\n}\n\nexport type ItemLifecycleStatus = 'initial' | 'interacting' | 'suspended' | 'closed' | 'review' | 'solution' | 'answer';\n\nexport type SerializedVariableKind = 'response' | 'outcome' | 'template' | 'context';\n\nexport interface SerializedItemSessionVariable {\n\tidentifier: string;\n\tkind: SerializedVariableKind;\n\tbaseType: VariableBaseType;\n\tcardinality: VariableCardinality;\n\tvalue: any;\n\tdefaultValue?: any;\n}\n\nexport interface SerializedItemSessionState {\n\titemIdentifier?: string;\n\tsessionGuid: string;\n\tlifecycleStatus: ItemLifecycleStatus;\n\tcompletionStatus: CompletionStatus;\n\tnumAttempts: number;\n\t/**\n\t * Time-on-task in milliseconds, stored as the QTI built-in duration variable value.\n\t */\n\tduration: number;\n\tresponseVariables: Record<string, SerializedItemSessionVariable>;\n\toutcomeVariables: Record<string, SerializedItemSessionVariable>;\n\ttemplateVariables: Record<string, SerializedItemSessionVariable>;\n\tcontextVariables: Record<string, SerializedItemSessionVariable>;\n\tvalidationMessages: ResponseValidationResult['issues'];\n\tsavedAt: string;\n}\n\nexport type ItemSessionAction =\n\t| 'suspendAttempt'\n\t| 'endAttempt'\n\t| 'scoreAttempt'\n\t| 'newTemplate'\n\t| 'submitAttempt';\n\nexport type ItemSessionActionCommand =\n\t| { action: 'suspendAttempt' }\n\t| { action: 'endAttempt'; countAttempt?: boolean; validateResponses?: boolean }\n\t| { action: 'scoreAttempt' }\n\t| { action: 'newTemplate'; resetResponses?: boolean }\n\t| { action: 'submitAttempt'; countAttempt?: boolean };\n\nexport interface ItemSessionActionResult {\n\taction: ItemSessionAction;\n\tlifecycleStatus: ItemLifecycleStatus;\n\tcompletionStatus: CompletionStatus;\n\tnumAttempts: number;\n\tduration: number;\n\tcompleted: boolean;\n\tsessionState: SerializedItemSessionState;\n\tvalidation?: ResponseValidationResult;\n\tscoring?: ScoringResult;\n}\n\nexport interface InteractionResponse {\n\t[responseId: string]: any;\n}\n\n/**\n * Serializable representation of a QTI baseType=\"file\" response.\n * (We cannot store a browser File object in session state / JSON exports.)\n */\nexport interface QTIFileResponse {\n\tname: string;\n\ttype: string;\n\tsize: number;\n\tlastModified: number;\n\t/** Base64 data URL, e.g. data:application/pdf;base64,... */\n\tdataUrl: string;\n\t/**\n\t * Optional ImageData extracted from canvas (for drawing interactions).\n\t * This allows custom operators to analyze drawing content synchronously\n\t * without needing to decode the dataUrl asynchronously.\n\t */\n\timageData?: {\n\t\tdata: Uint8ClampedArray;\n\t\twidth: number;\n\t\theight: number;\n\t};\n}\n\nexport interface ModalFeedback {\n\t/** Unique identifier for this feedback block */\n\tidentifier: string;\n\t/** Outcome variable identifier this feedback is tied to */\n\toutcomeIdentifier: string;\n\t/** When to show: 'show' means display when outcome matches identifier */\n\tshowHide: 'show' | 'hide';\n\t/** HTML content to display */\n\tcontent: HtmlContent;\n\t/** Optional title for the feedback */\n\ttitle?: string;\n}\n\nexport interface ScoringResult {\n\tscore: number;\n\tmaxScore: number;\n\tcompleted: boolean;\n\toutcomeValues: Record<string, any>;\n\t/** Modal feedback elements that should be displayed based on outcome values */\n\tmodalFeedback?: ModalFeedback[];\n}\n\n/**\n * QTI 2.2 completionStatus values for adaptive items\n * - not_attempted: No interaction has occurred yet\n * - unknown: Response exists but hasn't been scored/evaluated\n * - incomplete: Item has been scored but is still active (can submit again)\n * - completed: Item is finished (final state)\n */\nexport type CompletionStatus = 'not_attempted' | 'unknown' | 'incomplete' | 'completed';\n\n/**\n * Extended scoring result for adaptive items with multi-attempt support\n */\nexport interface AdaptiveAttemptResult extends ScoringResult {\n\t/** Number of attempts made so far */\n\tnumAttempts: number;\n\t/** Current completion status of the item */\n\tcompletionStatus: CompletionStatus;\n\t/** Whether the item can accept more submissions */\n\tcanContinue: boolean;\n}\n\n/**\n * QTI role/view actors used for audience filtering (for example rubric/outcome visibility).\n * Runtime interaction behavior (readonly vs editable, correct-answer visibility) is a player\n * policy layered on top of these roles.\n */\nexport type QTIRole = 'candidate' | 'scorer' | 'proctor' | 'testConstructor' | 'tutor' | 'author';\n\nexport interface RubricBlock {\n\tview: string[]; // Array of role strings that can see this rubric\n\thtml: HtmlContent; // HTML content of the rubric\n}\n\n/**\n * QTI specification compliance configuration.\n * Controls whether the player enforces strict QTI 2.2 spec or allows vendor extensions.\n */\nexport interface QTIComplianceConfig {\n\t/** Enable strict QTI 2.2 compliance mode. Default: false (lenient) */\n\tenabled?: boolean;\n\n\t/** Reject items with unknown or non-standard elements. Default: false */\n\trejectUnknownExtensions?: boolean;\n\n\t/** Log warnings for spec deviations and vendor extensions. Default: true */\n\tlogDeviations?: boolean;\n}\n\nexport interface PlayerConfig {\n\titemXml?: string;\n\t/**\n\t * QTI 3.0 §6.2 Personal Needs and Preferences profile.\n\t * Color scheme is applied immediately as data-qti-colorscheme on the player root.\n\t * Use player.updatePnp() to change mid-session without re-parsing the item.\n\t */\n\tpnp?: import('../pnp/types.js').PnpProfile;\n\t/**\n\t * Optional shared catalog XML string (QTI 3.0 §6.3).\n\t * Parsed and merged with any catalog embedded in the item XML.\n\t * Item-level catalog entries take precedence over shared entries with the same identifier.\n\t * Deferred: external catalog files from IMS manifest (G-15) are not yet supported.\n\t */\n\tcatalogXml?: string;\n\t/**\n\t * Optional resolved delivery context produced by IMS package/assessment layers.\n\t * This is additive to catalogXml: shared catalog sources are merged first, then\n\t * catalogXml, then item-embedded catalog entries so item-local entries win.\n\t */\n\tdeliveryContext?: ResolvedItemDeliveryContext;\n\tsessionState?: ItemSessionState;\n\tresponses?: InteractionResponse;\n\trole?: QTIRole;\n\t/** Optional seed for deterministic random operations (e.g. templateProcessing randomInteger) */\n\tseed?: number;\n\t/** Optional RNG override (takes precedence over seed if provided) */\n\trng?: () => number;\n\t/**\n\t * Optional element name mapper for handling different QTI versions.\n\t * Defaults to Qti2xElementNameMapper (primary supported QTI format).\n\t * @since 0.2.0\n\t */\n\telementNameMapper?: any; // Will be ElementNameMapper from @pie-qti/qti-common\n\t/**\n\t * Optional attribute name mapper for handling different QTI versions.\n\t * Defaults to Qti2xAttributeNameMapper (primary supported QTI format).\n\t * @since 0.3.0\n\t */\n\tattributeNameMapper?: any; // Will be AttributeNameMapper from @pie-qti/qti-common\n\t/** Optional web component registry for custom interaction components */\n\tcomponentRegistry?: any; // Will be ComponentRegistry, but avoiding circular dependency\n\t/** Optional extraction registry for custom element extractors */\n\textractionRegistry?: any; // Will be ExtractionRegistry, but avoiding circular dependency\n\t/** Optional plugins to extend player functionality */\n\tplugins?: any[]; // Will be QTIPlugin[], but avoiding circular dependency\n\t/**\n\t * Optional i18n provider for internationalization.\n\t * If not provided, defaults to DefaultI18nProvider with English messages.\n\t */\n\ti18nProvider?: any; // Will be I18nProvider from @pie-qti/i18n\n\t/**\n\t * Optional registry for executing QTI <customOperator> expressions.\n\t * Keyed by operator `class` (preferred) or `definition` URI.\n\t */\n\tcustomOperators?: Record<string, (args: QtiValue[], meta: { class?: string; definition?: string }) => QtiValue>;\n\t/**\n\t * Optional base URL for resolving relative PCI module paths.\n\t * Defaults to document.baseURI when running in a browser.\n\t */\n\tpciBaseUrl?: string;\n\n\t/**\n\t * Security-related controls for untrusted QTI rendered into the host DOM.\n\t * Defaults are conservative for same-DOM embedding.\n\t */\n\tsecurity?: PlayerSecurityConfig;\n\n\t/**\n\t * QTI specification compliance settings.\n\t * Set strictQtiCompliance.enabled = true for strict QTI 2.2 validation.\n\t */\n\tstrictQtiCompliance?: QTIComplianceConfig;\n}\n\nexport interface UrlPolicyConfig {\n\t/**\n\t * Optional base URL used to resolve relative asset URLs (e.g. images/media).\n\t * If omitted, relative URLs are preserved as-is.\n\t */\n\tassetBaseUrl?: string;\n\t/** Allow https: URLs */\n\tallowHttps?: boolean;\n\t/** Allow http: URLs (default false; prefer https) */\n\tallowHttp?: boolean;\n\t/** Allow protocol-relative URLs (e.g. //cdn.example/asset). Default false. */\n\tallowProtocolRelative?: boolean;\n\t/** Allow data:image/* for <img src>. */\n\tallowDataImages?: boolean;\n\t/** Allow data:image/svg+xml (default false) */\n\tallowSvgDataImages?: boolean;\n\t/** Optional allowlist of hostnames for absolute URLs (exact match). */\n\tallowedHosts?: string[];\n}\n\n/**\n * Trusted Types support:\n * - When enabled and supported by the host browser + CSP, HTML-returning APIs may return TrustedHTML instead of string.\n * - When not enabled (default), APIs return plain strings as before.\n */\nexport type TrustedTypesHtml = typeof globalThis extends { TrustedHTML: infer T } ? T : never;\nexport type HtmlContent = string | TrustedTypesHtml;\n\nexport interface PlayerSecurityConfig {\n\t/** URL policy applied to extracted URL fields and HTML attribute URLs */\n\turlPolicy?: UrlPolicyConfig;\n\t/** Allow <object>/<embed> usage (default false) */\n\tallowObjectEmbeds?: boolean;\n\t/** Allow <iframe> usage (default false) */\n\tallowIframes?: boolean;\n\t/**\n\t * Optional parsing/processing guardrails to reduce DoS risk from untrusted QTI.\n\t * Disabled by default for compatibility.\n\t */\n\tparsingLimits?: ParsingLimitsConfig;\n\t/**\n\t * Optional Trusted Types policy name (host-controlled).\n\t * When set, and Trusted Types is available, the player will produce TrustedHTML for HTML injection sinks.\n\t *\n\t * Note: this is only effective when the host enables Trusted Types via CSP.\n\t */\n\ttrustedTypesPolicyName?: string;\n}\n\nexport interface ParsingLimitsConfig {\n\t/**\n\t * Enables parsing limits. When false/undefined, the player behaves exactly as before (compat default).\n\t */\n\tenabled?: boolean;\n\t/**\n\t * Reject any XML containing <!DOCTYPE ...> (case-insensitive) when enabled.\n\t * Helps reduce entity-expansion and other parser edge-case risks.\n\t */\n\trejectDoctype?: boolean;\n\t/**\n\t * Maximum bytes for `itemXml` input (UTF-8). Enforced when enabled.\n\t */\n\tmaxItemXmlBytes?: number;\n\t/**\n\t * Maximum bytes for HTML strings passed to sanitizer (UTF-8). Enforced when enabled.\n\t */\n\tmaxHtmlBytes?: number;\n\t/**\n\t * Maximum number of element nodes sanitized per HTML input. Enforced when enabled.\n\t */\n\tmaxHtmlNodes?: number;\n\t/**\n\t * Maximum element depth sanitized per HTML input. Enforced when enabled.\n\t */\n\tmaxHtmlDepth?: number;\n}\n\nexport interface InteractionContext {\n\tresponseIdentifier: string;\n\tmaxChoices?: number;\n\tminChoices?: number;\n\tshuffle?: boolean;\n\torientation?: 'horizontal' | 'vertical';\n}\n\n// Interaction data shapes for the component/plugin system.\n// Exported here so consumers can import them from `@pie-qti/item-player`.\nexport type * from '../interactions/index.js';\nexport * from './responseValidation.js';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/types/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AA6ZH,cAAc,yBAAyB,CAAC","sourcesContent":["/**\n * Core QTI types for the player\n */\n\nimport type {\n\tBaseType as ProcessingBaseType,\n\tCardinality as ProcessingCardinality,\n\tQtiValue,\n} from '@pie-qti/qti-processing';\nimport type { ResolvedItemDeliveryContext } from '@pie-qti/ims-cp-core';\nimport type { ResponseValidationResult } from './responseValidation.js';\n\n/**\n * QTI base type identifier\n * Extensible string type allows custom base types\n */\nexport type VariableBaseType = ProcessingBaseType;\n\n/**\n * QTI cardinality identifier\n * Extensible string type allows custom cardinality values\n */\nexport type VariableCardinality = ProcessingCardinality;\n\nexport interface VariableDeclaration {\n\tidentifier: string;\n\tbaseType: VariableBaseType;\n\tcardinality: VariableCardinality;\n\tvalue: any;\n\tdefaultValue?: any;\n\tmapping?: Mapping;\n\tareaMapping?: AreaMapping;\n}\n\nexport interface Mapping {\n\tdefaultValue?: number;\n\tlowerBound?: number;\n\tupperBound?: number;\n\t/**\n\t * QTI attribute on <mapping>. When \"false\", string mappings are case-insensitive by default.\n\t * Stored as raw string to match XML attribute values (\"true\"/\"false\").\n\t */\n\tcaseSensitive?: string;\n\tentries: Record<string, MapEntry>;\n}\n\nexport interface MapEntry {\n\tmapKey: string;\n\tmappedValue: number;\n\tcaseSensitive?: string;\n}\n\nexport interface AreaMapping {\n\tdefaultValue?: number;\n\tlowerBound?: number;\n\tupperBound?: number;\n\tentries: AreaMapEntry[];\n}\n\nexport interface AreaMapEntry {\n\tshape: 'circle' | 'rect' | 'poly' | 'ellipse' | 'default';\n\tcoords: string;\n\tmappedValue: number;\n}\n\nexport interface ResponseDeclaration extends VariableDeclaration {\n\tcorrectResponse?: any;\n}\n\nexport interface OutcomeDeclaration extends VariableDeclaration {\n\tinterpretation?: string;\n\tlongInterpretation?: string;\n\tnormalMaximum?: number;\n\tnormalMinimum?: number;\n\tmasteryValue?: number;\n\tviews?: string[];\n}\n\nexport interface ItemSessionState {\n\t[variableId: string]: any;\n}\n\nexport type ItemLifecycleStatus = 'initial' | 'interacting' | 'suspended' | 'closed' | 'review' | 'solution' | 'answer';\n\nexport type SerializedVariableKind = 'response' | 'outcome' | 'template' | 'context';\n\nexport interface SerializedItemSessionVariable {\n\tidentifier: string;\n\tkind: SerializedVariableKind;\n\tbaseType: VariableBaseType;\n\tcardinality: VariableCardinality;\n\tvalue: any;\n\tdefaultValue?: any;\n}\n\nexport interface SerializedItemSessionState {\n\titemIdentifier?: string;\n\tsessionGuid: string;\n\tlifecycleStatus: ItemLifecycleStatus;\n\tcompletionStatus: CompletionStatus;\n\tnumAttempts: number;\n\t/**\n\t * Time-on-task in milliseconds, stored as the QTI built-in duration variable value.\n\t */\n\tduration: number;\n\tresponseVariables: Record<string, SerializedItemSessionVariable>;\n\toutcomeVariables: Record<string, SerializedItemSessionVariable>;\n\ttemplateVariables: Record<string, SerializedItemSessionVariable>;\n\tcontextVariables: Record<string, SerializedItemSessionVariable>;\n\tvalidationMessages: ResponseValidationResult['issues'];\n\tsavedAt: string;\n}\n\nexport type ItemSessionAction =\n\t| 'suspendAttempt'\n\t| 'endAttempt'\n\t| 'scoreAttempt'\n\t| 'newTemplate'\n\t| 'submitAttempt';\n\nexport type ItemSessionActionCommand =\n\t| { action: 'suspendAttempt' }\n\t| { action: 'endAttempt'; countAttempt?: boolean; validateResponses?: boolean }\n\t| { action: 'scoreAttempt' }\n\t| { action: 'newTemplate'; resetResponses?: boolean }\n\t| { action: 'submitAttempt'; countAttempt?: boolean };\n\nexport interface ItemSessionActionResult {\n\taction: ItemSessionAction;\n\tlifecycleStatus: ItemLifecycleStatus;\n\tcompletionStatus: CompletionStatus;\n\tnumAttempts: number;\n\tduration: number;\n\tcompleted: boolean;\n\tsessionState: SerializedItemSessionState;\n\tvalidation?: ResponseValidationResult;\n\tscoring?: ScoringResult;\n}\n\nexport interface InteractionResponse {\n\t[responseId: string]: any;\n}\n\n/**\n * Serializable representation of a QTI baseType=\"file\" response.\n * (We cannot store a browser File object in session state / JSON exports.)\n */\nexport interface QTIFileResponse {\n\tname: string;\n\ttype: string;\n\tsize: number;\n\tlastModified: number;\n\t/** Base64 data URL, e.g. data:application/pdf;base64,... */\n\tdataUrl: string;\n\t/**\n\t * Optional ImageData extracted from canvas (for drawing interactions).\n\t * This allows custom operators to analyze drawing content synchronously\n\t * without needing to decode the dataUrl asynchronously.\n\t */\n\timageData?: {\n\t\tdata: Uint8ClampedArray;\n\t\twidth: number;\n\t\theight: number;\n\t};\n}\n\nexport interface ModalFeedback {\n\t/** Unique identifier for this feedback block */\n\tidentifier: string;\n\t/** Outcome variable identifier this feedback is tied to */\n\toutcomeIdentifier: string;\n\t/** When to show: 'show' means display when outcome matches identifier */\n\tshowHide: 'show' | 'hide';\n\t/** HTML content to display */\n\tcontent: HtmlContent;\n\t/** Optional title for the feedback */\n\ttitle?: string;\n}\n\nexport interface ScoringResult {\n\tscore: number;\n\tmaxScore: number;\n\tcompleted: boolean;\n\toutcomeValues: Record<string, any>;\n\t/** Modal feedback elements that should be displayed based on outcome values */\n\tmodalFeedback?: ModalFeedback[];\n}\n\n/**\n * QTI 2.2 completionStatus values for adaptive items\n * - not_attempted: No interaction has occurred yet\n * - unknown: Response exists but hasn't been scored/evaluated\n * - incomplete: Item has been scored but is still active (can submit again)\n * - completed: Item is finished (final state)\n */\nexport type CompletionStatus = 'not_attempted' | 'unknown' | 'incomplete' | 'completed';\n\n/**\n * Extended scoring result for adaptive items with multi-attempt support\n */\nexport interface AdaptiveAttemptResult extends ScoringResult {\n\t/** Number of attempts made so far */\n\tnumAttempts: number;\n\t/** Current completion status of the item */\n\tcompletionStatus: CompletionStatus;\n\t/** Whether the item can accept more submissions */\n\tcanContinue: boolean;\n}\n\n/**\n * QTI role/view actors used for audience filtering (for example rubric/outcome visibility).\n * Runtime interaction behavior (readonly vs editable, correct-answer visibility) is a player\n * policy layered on top of these roles.\n */\nexport type QTIRole = 'candidate' | 'scorer' | 'proctor' | 'testConstructor' | 'tutor' | 'author';\n\nexport type RubricBlockScope = 'direct' | 'itemBody';\n\nexport interface RubricBlockOptions {\n\t/**\n\t * `direct` rubrics are assessment-item children and are intended for host placement.\n\t * `itemBody` rubrics are authored in the visible item body flow.\n\t */\n\tscope?: RubricBlockScope | 'all';\n}\n\nexport interface RubricBlock {\n\tview: string[]; // Array of role strings that can see this rubric\n\thtml: HtmlContent; // HTML content of the rubric\n\tscope: RubricBlockScope;\n\tuse?: string;\n}\n\n/**\n * QTI specification compliance configuration.\n * Controls whether the player enforces strict QTI 2.2 spec or allows vendor extensions.\n */\nexport interface QTIComplianceConfig {\n\t/** Enable strict QTI 2.2 compliance mode. Default: false (lenient) */\n\tenabled?: boolean;\n\n\t/** Reject items with unknown or non-standard elements. Default: false */\n\trejectUnknownExtensions?: boolean;\n\n\t/** Log warnings for spec deviations and vendor extensions. Default: true */\n\tlogDeviations?: boolean;\n}\n\nexport interface PlayerConfig {\n\titemXml?: string;\n\t/**\n\t * QTI 3.0 §6.2 Personal Needs and Preferences profile.\n\t * Color scheme is applied immediately as data-qti-colorscheme on the player root.\n\t * Use player.updatePnp() to change mid-session without re-parsing the item.\n\t */\n\tpnp?: import('../pnp/types.js').PnpProfile;\n\t/**\n\t * Optional shared catalog XML string (QTI 3.0 §6.3).\n\t * Parsed and merged with any catalog embedded in the item XML.\n\t * Item-level catalog entries take precedence over shared entries with the same identifier.\n\t * Deferred: external catalog files from IMS manifest (G-15) are not yet supported.\n\t */\n\tcatalogXml?: string;\n\t/**\n\t * Optional resolved delivery context produced by IMS package/assessment layers.\n\t * This is additive to catalogXml: shared catalog sources are merged first, then\n\t * catalogXml, then item-embedded catalog entries so item-local entries win.\n\t */\n\tdeliveryContext?: ResolvedItemDeliveryContext;\n\tsessionState?: ItemSessionState;\n\tresponses?: InteractionResponse;\n\trole?: QTIRole;\n\t/** Optional seed for deterministic random operations (e.g. templateProcessing randomInteger) */\n\tseed?: number;\n\t/** Optional RNG override (takes precedence over seed if provided) */\n\trng?: () => number;\n\t/**\n\t * Optional element name mapper for handling different QTI versions.\n\t * Defaults to Qti2xElementNameMapper (primary supported QTI format).\n\t * @since 0.2.0\n\t */\n\telementNameMapper?: any; // Will be ElementNameMapper from @pie-qti/qti-common\n\t/**\n\t * Optional attribute name mapper for handling different QTI versions.\n\t * Defaults to Qti2xAttributeNameMapper (primary supported QTI format).\n\t * @since 0.3.0\n\t */\n\tattributeNameMapper?: any; // Will be AttributeNameMapper from @pie-qti/qti-common\n\t/** Optional web component registry for custom interaction components */\n\tcomponentRegistry?: any; // Will be ComponentRegistry, but avoiding circular dependency\n\t/** Optional extraction registry for custom element extractors */\n\textractionRegistry?: any; // Will be ExtractionRegistry, but avoiding circular dependency\n\t/** Optional plugins to extend player functionality */\n\tplugins?: any[]; // Will be QTIPlugin[], but avoiding circular dependency\n\t/**\n\t * Optional i18n provider for internationalization.\n\t * If not provided, defaults to DefaultI18nProvider with English messages.\n\t */\n\ti18nProvider?: any; // Will be I18nProvider from @pie-qti/i18n\n\t/**\n\t * Optional registry for executing QTI <customOperator> expressions.\n\t * Keyed by operator `class` (preferred) or `definition` URI.\n\t */\n\tcustomOperators?: Record<string, (args: QtiValue[], meta: { class?: string; definition?: string }) => QtiValue>;\n\t/**\n\t * Optional base URL for resolving relative PCI module paths.\n\t * Defaults to document.baseURI when running in a browser.\n\t */\n\tpciBaseUrl?: string;\n\n\t/**\n\t * Security-related controls for untrusted QTI rendered into the host DOM.\n\t * Defaults are conservative for same-DOM embedding.\n\t */\n\tsecurity?: PlayerSecurityConfig;\n\n\t/**\n\t * QTI specification compliance settings.\n\t * Set strictQtiCompliance.enabled = true for strict QTI 2.2 validation.\n\t */\n\tstrictQtiCompliance?: QTIComplianceConfig;\n}\n\nexport interface UrlPolicyConfig {\n\t/**\n\t * Optional base URL used to resolve relative asset URLs (e.g. images/media).\n\t * If omitted, relative URLs are preserved as-is.\n\t */\n\tassetBaseUrl?: string;\n\t/** Allow https: URLs */\n\tallowHttps?: boolean;\n\t/** Allow http: URLs (default false; prefer https) */\n\tallowHttp?: boolean;\n\t/** Allow protocol-relative URLs (e.g. //cdn.example/asset). Default false. */\n\tallowProtocolRelative?: boolean;\n\t/** Allow data:image/* for <img src>. */\n\tallowDataImages?: boolean;\n\t/** Allow data:image/svg+xml (default false) */\n\tallowSvgDataImages?: boolean;\n\t/** Allow blob: URLs for package-resolved images (default false). */\n\tallowBlobImages?: boolean;\n\t/** Allow blob: URLs for package-resolved audio/video media (default false). */\n\tallowBlobMedia?: boolean;\n\t/** Optional allowlist of hostnames for absolute URLs (exact match). */\n\tallowedHosts?: string[];\n}\n\n/**\n * Trusted Types support:\n * - When enabled and supported by the host browser + CSP, HTML-returning APIs may return TrustedHTML instead of string.\n * - When not enabled (default), APIs return plain strings as before.\n */\nexport type TrustedTypesHtml = typeof globalThis extends { TrustedHTML: infer T } ? T : never;\nexport type HtmlContent = string | TrustedTypesHtml;\n\nexport interface PlayerSecurityConfig {\n\t/** URL policy applied to extracted URL fields and HTML attribute URLs */\n\turlPolicy?: UrlPolicyConfig;\n\t/** Allow <object>/<embed> usage (default false) */\n\tallowObjectEmbeds?: boolean;\n\t/** Allow <iframe> usage (default false) */\n\tallowIframes?: boolean;\n\t/**\n\t * Optional parsing/processing guardrails to reduce DoS risk from untrusted QTI.\n\t * Disabled by default for compatibility.\n\t */\n\tparsingLimits?: ParsingLimitsConfig;\n\t/**\n\t * Optional Trusted Types policy name (host-controlled).\n\t * When set, and Trusted Types is available, the player will produce TrustedHTML for HTML injection sinks.\n\t *\n\t * Note: this is only effective when the host enables Trusted Types via CSP.\n\t */\n\ttrustedTypesPolicyName?: string;\n}\n\nexport interface ParsingLimitsConfig {\n\t/**\n\t * Enables parsing limits. When false/undefined, the player behaves exactly as before (compat default).\n\t */\n\tenabled?: boolean;\n\t/**\n\t * Reject any XML containing <!DOCTYPE ...> (case-insensitive) when enabled.\n\t * Helps reduce entity-expansion and other parser edge-case risks.\n\t */\n\trejectDoctype?: boolean;\n\t/**\n\t * Maximum bytes for `itemXml` input (UTF-8). Enforced when enabled.\n\t */\n\tmaxItemXmlBytes?: number;\n\t/**\n\t * Maximum bytes for HTML strings passed to sanitizer (UTF-8). Enforced when enabled.\n\t */\n\tmaxHtmlBytes?: number;\n\t/**\n\t * Maximum number of element nodes sanitized per HTML input. Enforced when enabled.\n\t */\n\tmaxHtmlNodes?: number;\n\t/**\n\t * Maximum element depth sanitized per HTML input. Enforced when enabled.\n\t */\n\tmaxHtmlDepth?: number;\n}\n\nexport interface InteractionContext {\n\tresponseIdentifier: string;\n\tmaxChoices?: number;\n\tminChoices?: number;\n\tshuffle?: boolean;\n\torientation?: 'horizontal' | 'vertical';\n}\n\n// Interaction data shapes for the component/plugin system.\n// Exported here so consumers can import them from `@pie-qti/item-player`.\nexport type * from '../interactions/index.js';\nexport * from './responseValidation.js';\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pie-qti/item-player",
3
- "version": "0.1.12",
3
+ "version": "0.1.14",
4
4
  "description": "Modern QTI player supporting QTI 2.2 and 3.0 - Client-side with optional backend hooks",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -27,18 +27,10 @@
27
27
  ],
28
28
  "license": "MIT",
29
29
  "dependencies": {
30
- "@pie-qti/i18n": "0.1.12",
31
- "@pie-qti/ims-cp-core": "0.1.12",
32
- "@pie-qti/qti-common": "0.1.12",
33
- "@pie-qti/qti-processing": "0.1.12",
34
- "@pie-qti/typeset-katex": "0.1.12",
35
- "@tiptap/core": "^3.15.3",
36
- "@tiptap/extension-mathematics": "^3.15.3",
37
- "@tiptap/extension-placeholder": "^3.15.3",
38
- "@tiptap/starter-kit": "^3.15.3",
39
- "@xmldom/xmldom": "^0.8.11",
40
- "decimal.js": "^10.6.0",
41
- "katex": "^0.16.27",
30
+ "@pie-qti/i18n": "0.1.14",
31
+ "@pie-qti/ims-cp-core": "0.1.14",
32
+ "@pie-qti/qti-common": "0.1.14",
33
+ "@pie-qti/qti-processing": "0.1.14",
42
34
  "mathlive": "^0.108.2",
43
35
  "node-html-parser": "^7.0.2"
44
36
  },
@@ -69,6 +61,10 @@
69
61
  "types": "./dist/iframe/index.d.ts",
70
62
  "import": "./dist/iframe/index.js"
71
63
  },
64
+ "./security": {
65
+ "types": "./dist/security/index.d.ts",
66
+ "import": "./dist/security/index.js"
67
+ },
72
68
  "./components/utils": {
73
69
  "types": "./dist/components/utils/index.d.ts",
74
70
  "import": "./dist/components/utils/index.js"