@pie-qti/player-elements 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/.turbo/turbo-build.log +14 -0
  2. package/CHANGELOG.md +10 -0
  3. package/README.md +111 -0
  4. package/bunfig.toml +2 -0
  5. package/dist/constants.d.ts +3 -0
  6. package/dist/constants.d.ts.map +1 -0
  7. package/dist/define.d.ts +2 -0
  8. package/dist/define.d.ts.map +1 -0
  9. package/dist/elements/BaseSvelteMountElement.d.ts +12 -0
  10. package/dist/elements/BaseSvelteMountElement.d.ts.map +1 -0
  11. package/dist/elements/QtiAssessmentPlayerElement.d.ts +54 -0
  12. package/dist/elements/QtiAssessmentPlayerElement.d.ts.map +1 -0
  13. package/dist/elements/QtiItemPlayerElement.d.ts +49 -0
  14. package/dist/elements/QtiItemPlayerElement.d.ts.map +1 -0
  15. package/dist/index-B1sHDWWn.js +30415 -0
  16. package/dist/index-B1sHDWWn.js.map +1 -0
  17. package/dist/index-C_WHHKJ8.js +34157 -0
  18. package/dist/index-C_WHHKJ8.js.map +1 -0
  19. package/dist/index.d.ts +9 -0
  20. package/dist/index.d.ts.map +1 -0
  21. package/dist/index.js +13 -0
  22. package/dist/index.js.map +1 -0
  23. package/dist/mathlive.min-B8mv5Blc.js +15374 -0
  24. package/dist/mathlive.min-B8mv5Blc.js.map +1 -0
  25. package/dist/player-elements.css +1 -0
  26. package/dist/qti/parseAssessmentTest.d.ts +3 -0
  27. package/dist/qti/parseAssessmentTest.d.ts.map +1 -0
  28. package/dist/qti/resolveItems.d.ts +8 -0
  29. package/dist/qti/resolveItems.d.ts.map +1 -0
  30. package/dist/qti/types.d.ts +28 -0
  31. package/dist/qti/types.d.ts.map +1 -0
  32. package/dist/register.d.ts +2 -0
  33. package/dist/register.d.ts.map +1 -0
  34. package/dist/register.js +6 -0
  35. package/dist/register.js.map +1 -0
  36. package/dist/utils/json.d.ts +2 -0
  37. package/dist/utils/json.d.ts.map +1 -0
  38. package/package.json +39 -0
  39. package/src/constants.ts +4 -0
  40. package/src/define.ts +9 -0
  41. package/src/elements/BaseSvelteMountElement.ts +63 -0
  42. package/src/elements/QtiAssessmentPlayerElement.ts +384 -0
  43. package/src/elements/QtiItemPlayerElement.ts +197 -0
  44. package/src/index.ts +26 -0
  45. package/src/qti/parseAssessmentTest.ts +174 -0
  46. package/src/qti/resolveItems.ts +94 -0
  47. package/src/qti/types.ts +33 -0
  48. package/src/register.ts +7 -0
  49. package/src/utils/json.ts +10 -0
  50. package/svelte.config.js +14 -0
  51. package/tests/qti-assessment-test-parsing.test.ts +125 -0
  52. package/tests/setup.ts +29 -0
  53. package/tsconfig.build.json +15 -0
  54. package/tsconfig.json +18 -0
  55. package/vite.config.ts +25 -0
@@ -0,0 +1,197 @@
1
+ import ItemRenderer from '@pie-qti/assessment-player/components/ItemRenderer.svelte';
2
+ import type { PlayerSecurityConfig, QTIRole } from '@pie-qti/item-player';
3
+ import { QTI_ITEM_PLAYER_TAG } from '../constants.js';
4
+ import { safeJsonParse } from '../utils/json.js';
5
+ import { BaseSvelteMountElement } from './BaseSvelteMountElement.js';
6
+
7
+ export type QtiItemPlayerResponseChangeDetail = {
8
+ responseId: string;
9
+ value: unknown;
10
+ responses: Record<string, unknown>;
11
+ };
12
+
13
+ export class QtiItemPlayerElement extends BaseSvelteMountElement<Record<string, unknown>> {
14
+ static get observedAttributes() {
15
+ return [
16
+ 'item-xml',
17
+ 'identifier',
18
+ 'title',
19
+ 'role',
20
+ 'extended-text-editor',
21
+ 'responses-json',
22
+ 'security-json',
23
+ ];
24
+ }
25
+
26
+ protected Component = ItemRenderer;
27
+
28
+ #itemXml: string | null = null;
29
+ #identifier = 'item-1';
30
+ #title: string | undefined;
31
+ #role: QTIRole = 'candidate';
32
+ #extendedTextEditor: 'tiptap' | 'textarea' = 'tiptap';
33
+ #responses: Record<string, unknown> = {};
34
+ #security: PlayerSecurityConfig | undefined;
35
+
36
+ #updateSeq = 0;
37
+
38
+ connectedCallback() {
39
+ super.connectedCallback();
40
+ queueMicrotask(() => {
41
+ this.dispatchEvent(new CustomEvent('ready', { bubbles: true, composed: true }));
42
+ });
43
+ }
44
+
45
+ attributeChangedCallback(name: string, _oldValue: string | null, newValue: string | null) {
46
+ switch (name) {
47
+ case 'item-xml':
48
+ this.#itemXml = newValue;
49
+ break;
50
+ case 'identifier':
51
+ if (newValue) this.#identifier = newValue;
52
+ break;
53
+ case 'title':
54
+ this.#title = newValue ?? undefined;
55
+ break;
56
+ case 'role':
57
+ if (newValue) this.#role = newValue as QTIRole;
58
+ break;
59
+ case 'extended-text-editor':
60
+ if (newValue === 'tiptap' || newValue === 'textarea') {
61
+ this.#extendedTextEditor = newValue;
62
+ }
63
+ break;
64
+ case 'responses-json': {
65
+ const parsed = safeJsonParse<Record<string, unknown>>(newValue);
66
+ if (parsed) this.#responses = parsed;
67
+ break;
68
+ }
69
+ case 'security-json': {
70
+ const parsed = safeJsonParse<PlayerSecurityConfig>(newValue);
71
+ if (parsed) this.#security = parsed;
72
+ break;
73
+ }
74
+ }
75
+
76
+ void this.#syncState();
77
+ }
78
+
79
+ /**
80
+ * Preferred API: set QTI via JS property (attributes are awkward for large XML).
81
+ */
82
+ get itemXml() {
83
+ return this.#itemXml;
84
+ }
85
+ set itemXml(value: string | null) {
86
+ this.#itemXml = value;
87
+ void this.#syncState();
88
+ }
89
+
90
+ get identifier() {
91
+ return this.#identifier;
92
+ }
93
+ set identifier(value: string) {
94
+ this.#identifier = value;
95
+ void this.#syncState();
96
+ }
97
+
98
+ get title() {
99
+ return this.#title ?? '';
100
+ }
101
+ set title(value: string) {
102
+ this.#title = value || undefined;
103
+ void this.#syncState();
104
+ }
105
+
106
+ get role() {
107
+ return this.#role;
108
+ }
109
+ set role(value: QTIRole) {
110
+ this.#role = value;
111
+ void this.#syncState();
112
+ }
113
+
114
+ get extendedTextEditor() {
115
+ return this.#extendedTextEditor;
116
+ }
117
+ set extendedTextEditor(value: 'tiptap' | 'textarea') {
118
+ this.#extendedTextEditor = value;
119
+ void this.#syncState();
120
+ }
121
+
122
+ get responses() {
123
+ return { ...this.#responses };
124
+ }
125
+ set responses(value: Record<string, unknown>) {
126
+ this.#responses = value ?? {};
127
+ void this.#syncState();
128
+ }
129
+
130
+ get security() {
131
+ return this.#security;
132
+ }
133
+ set security(value: PlayerSecurityConfig | undefined) {
134
+ this.#security = value;
135
+ void this.#syncState();
136
+ }
137
+
138
+ /**
139
+ * Convenience: programmatically set a response.
140
+ */
141
+ setResponse(responseId: string, value: unknown) {
142
+ this.#responses = { ...this.#responses, [responseId]: value };
143
+ void this.#syncState();
144
+ }
145
+
146
+ /**
147
+ * Async state synchronization method for consistency with assessment player architecture.
148
+ * Currently synchronous since item player doesn't require async operations,
149
+ * but using async pattern allows future enhancements (validation, preprocessing, etc.)
150
+ */
151
+ async #syncState() {
152
+ const seq = ++this.#updateSeq;
153
+
154
+ // Future: could add validation, preprocessing, etc. here
155
+ // For now, just proceed to mount/update
156
+
157
+ if (seq !== this.#updateSeq) return; // superseded by newer update
158
+ this._mountOrUpdate();
159
+ }
160
+
161
+ getProps() {
162
+ return {
163
+ questionRef: {
164
+ identifier: this.#identifier,
165
+ title: this.#title,
166
+ itemXml: this.#itemXml ?? '',
167
+ },
168
+ role: this.#role,
169
+ extendedTextEditor: this.#extendedTextEditor,
170
+ responses: this.#responses,
171
+ security: this.#security,
172
+ onResponseChange: (responseId: string, value: unknown) => {
173
+ this.#responses = { ...this.#responses, [responseId]: value };
174
+ const detail: QtiItemPlayerResponseChangeDetail = {
175
+ responseId,
176
+ value,
177
+ responses: { ...this.#responses },
178
+ };
179
+ this.dispatchEvent(
180
+ new CustomEvent<QtiItemPlayerResponseChangeDetail>('response-change', {
181
+ detail,
182
+ bubbles: true,
183
+ composed: true,
184
+ }),
185
+ );
186
+ },
187
+ };
188
+ }
189
+ }
190
+
191
+ export function defineQtiItemPlayerElement() {
192
+ if (!customElements.get(QTI_ITEM_PLAYER_TAG)) {
193
+ customElements.define(QTI_ITEM_PLAYER_TAG, QtiItemPlayerElement);
194
+ }
195
+ }
196
+
197
+
package/src/index.ts ADDED
@@ -0,0 +1,26 @@
1
+ export { QTI_ASSESSMENT_PLAYER_TAG, QTI_ITEM_PLAYER_TAG } from './constants.js';
2
+ export { defineQtiPlayerElements } from './define.js';
3
+ export {
4
+ defineQtiAssessmentPlayerElement,
5
+ type QtiAssessmentItemChangeDetail,
6
+ QtiAssessmentPlayerElement,
7
+ type QtiAssessmentResponseChangeDetail,
8
+ type QtiAssessmentSectionChangeDetail,
9
+ type QtiAssessmentSubmitDetail,
10
+ } from './elements/QtiAssessmentPlayerElement.js';
11
+ export {
12
+ defineQtiItemPlayerElement,
13
+ QtiItemPlayerElement,
14
+ type QtiItemPlayerResponseChangeDetail,
15
+ } from './elements/QtiItemPlayerElement.js';
16
+ export type { QtiItemMap } from './qti/resolveItems.js';
17
+ export { parseAssessmentTestXml } from './qti/parseAssessmentTest.js';
18
+ export { resolveItemsForAssessment } from './qti/resolveItems.js';
19
+ export type {
20
+ ParsedAssessmentTest,
21
+ ParsedTestPart,
22
+ ParsedAssessmentSection,
23
+ ParsedQuestionRef,
24
+ } from './qti/types.js';
25
+
26
+
@@ -0,0 +1,174 @@
1
+ import type { QTIRole, RubricBlock } from '@pie-qti/assessment-player';
2
+ import { DOMParser as LinkedomDOMParser } from 'linkedom';
3
+ import type { ParsedAssessmentSection, ParsedAssessmentTest, ParsedQuestionRef, ParsedTestPart } from './types.js';
4
+
5
+ // Use native DOMParser in browser, linkedom in Node/Bun
6
+ const DOMParserImpl = typeof DOMParser !== 'undefined' ? DOMParser : LinkedomDOMParser;
7
+
8
+ function firstByLocalName(parent: ParentNode, localName: string): Element | null {
9
+ const all = (parent as any).getElementsByTagNameNS
10
+ ? (parent as any).getElementsByTagNameNS('*', localName)
11
+ : (parent as any).getElementsByTagName?.(localName);
12
+ return all?.[0] ?? null;
13
+ }
14
+
15
+ function childrenByLocalName(parent: ParentNode, localName: string): Element[] {
16
+ const all = (parent as any).getElementsByTagNameNS
17
+ ? (parent as any).getElementsByTagNameNS('*', localName)
18
+ : (parent as any).getElementsByTagName?.(localName);
19
+ return all ? Array.from(all) : [];
20
+ }
21
+
22
+ function serializeInnerXml(el: Element): string {
23
+ // In linkedom, use innerHTML; in browser, use XMLSerializer
24
+ if (typeof XMLSerializer !== 'undefined') {
25
+ const s = new XMLSerializer();
26
+ let out = '';
27
+ for (const node of Array.from(el.childNodes)) {
28
+ out += s.serializeToString(node);
29
+ }
30
+ return out.trim();
31
+ } else {
32
+ // linkedom: use innerHTML which works for both HTML and XML
33
+ return el.innerHTML.trim();
34
+ }
35
+ }
36
+
37
+ function getAttr(el: Element, name: string): string | undefined {
38
+ const v = el.getAttribute(name);
39
+ return v === null ? undefined : v;
40
+ }
41
+
42
+ function parseQtiRoleList(viewAttr: string | undefined): QTIRole[] {
43
+ if (!viewAttr) return ['candidate'];
44
+ const roles = viewAttr
45
+ .split(/\s+/g)
46
+ .map((r) => r.trim())
47
+ .filter(Boolean) as QTIRole[];
48
+ return roles.length ? roles : ['candidate'];
49
+ }
50
+
51
+ function parseRubricBlocks(sectionEl: Element): RubricBlock[] | undefined {
52
+ const blocks = childrenByLocalName(sectionEl, 'rubricBlock');
53
+ if (blocks.length === 0) return undefined;
54
+
55
+ return blocks.map((b, idx) => ({
56
+ identifier: getAttr(b, 'identifier') ?? `${getAttr(sectionEl, 'identifier') ?? 'section'}-rubric-${idx + 1}`,
57
+ view: parseQtiRoleList(getAttr(b, 'view')),
58
+ use: getAttr(b, 'use'),
59
+ content: serializeInnerXml(b),
60
+ }));
61
+ }
62
+
63
+ function parseItemRefs(sectionEl: Element): ParsedQuestionRef[] | undefined {
64
+ const itemRefs = Array.from(sectionEl.childNodes)
65
+ .filter((n): n is Element => n.nodeType === 1)
66
+ .filter((el) => (el as Element).localName === 'assessmentItemRef');
67
+
68
+ if (itemRefs.length === 0) return undefined;
69
+
70
+ return itemRefs.map((el) => {
71
+ const identifier = getAttr(el, 'identifier') ?? 'item';
72
+ const href = getAttr(el, 'href');
73
+ const requiredRaw = getAttr(el, 'required');
74
+ const required = requiredRaw === undefined ? undefined : requiredRaw !== 'false';
75
+ return {
76
+ identifier,
77
+ href,
78
+ title: getAttr(el, 'title'),
79
+ required,
80
+ };
81
+ });
82
+ }
83
+
84
+ function parseSection(sectionEl: Element): ParsedAssessmentSection {
85
+ const identifier = getAttr(sectionEl, 'identifier') ?? 'section';
86
+ const title = getAttr(sectionEl, 'title') ?? undefined;
87
+ const visibleRaw = getAttr(sectionEl, 'visible');
88
+ const visible = visibleRaw === undefined ? undefined : visibleRaw !== 'false';
89
+
90
+ const rubricBlocks = parseRubricBlocks(sectionEl);
91
+ const questionRefs = parseItemRefs(sectionEl);
92
+
93
+ // Only parse direct child sections (not deep descendants)
94
+ const childSections = Array.from(sectionEl.childNodes)
95
+ .filter((n): n is Element => n.nodeType === 1)
96
+ .filter((el) => (el as Element).localName === 'assessmentSection')
97
+ .map(parseSection);
98
+
99
+ return {
100
+ identifier,
101
+ title,
102
+ visible,
103
+ rubricBlocks,
104
+ questionRefs,
105
+ sections: childSections.length ? childSections : undefined,
106
+ };
107
+ }
108
+
109
+ function parseTestPart(testPartEl: Element): ParsedTestPart {
110
+ const identifier = getAttr(testPartEl, 'identifier') ?? 'part-1';
111
+ const navigationMode = (getAttr(testPartEl, 'navigationMode') ?? 'nonlinear') as ParsedTestPart['navigationMode'];
112
+ const submissionMode = (getAttr(testPartEl, 'submissionMode') ?? 'simultaneous') as ParsedTestPart['submissionMode'];
113
+
114
+ // Only direct child sections
115
+ const sections = Array.from(testPartEl.childNodes)
116
+ .filter((n): n is Element => n.nodeType === 1)
117
+ .filter((el) => (el as Element).localName === 'assessmentSection')
118
+ .map(parseSection);
119
+
120
+ return {
121
+ identifier,
122
+ navigationMode,
123
+ submissionMode,
124
+ sections,
125
+ };
126
+ }
127
+
128
+ export function parseAssessmentTestXml(xml: string): ParsedAssessmentTest {
129
+ const doc = new DOMParserImpl().parseFromString(xml, 'application/xml' as any);
130
+ const parserError = firstByLocalName(doc as ParentNode, 'parsererror');
131
+ if (parserError) {
132
+ throw new Error('Failed to parse assessmentTest XML');
133
+ }
134
+
135
+ const assessmentTestEl = firstByLocalName(doc as ParentNode, 'assessmentTest') ?? doc.documentElement;
136
+ if (!assessmentTestEl || assessmentTestEl.localName !== 'assessmentTest') {
137
+ throw new Error('No <assessmentTest> root element found');
138
+ }
139
+
140
+ const identifier = getAttr(assessmentTestEl as Element, 'identifier');
141
+ const title = getAttr(assessmentTestEl as Element, 'title');
142
+
143
+ // Prefer explicit testPart(s); if missing, synthesize one from top-level sections
144
+ const testPartsEls = Array.from(assessmentTestEl.childNodes)
145
+ .filter((n): n is Element => (n as any).nodeType === 1)
146
+ .filter((el) => (el as Element).localName === 'testPart');
147
+
148
+ let testParts: ParsedTestPart[] | undefined;
149
+ if (testPartsEls.length > 0) {
150
+ testParts = testPartsEls.map(parseTestPart);
151
+ } else {
152
+ const topSections = Array.from(assessmentTestEl.childNodes)
153
+ .filter((n): n is Element => (n as any).nodeType === 1)
154
+ .filter((el) => (el as Element).localName === 'assessmentSection')
155
+ .map(parseSection);
156
+
157
+ testParts = [
158
+ {
159
+ identifier: 'part-1',
160
+ navigationMode: 'nonlinear',
161
+ submissionMode: 'simultaneous',
162
+ sections: topSections,
163
+ },
164
+ ];
165
+ }
166
+
167
+ return {
168
+ identifier,
169
+ title,
170
+ testParts,
171
+ };
172
+ }
173
+
174
+
@@ -0,0 +1,94 @@
1
+ import type { ParsedAssessmentSection, ParsedAssessmentTest, ParsedQuestionRef, ParsedTestPart } from './types.js';
2
+
3
+ export type QtiItemMap = Record<string, string>;
4
+
5
+ function collectQuestionRefsFromSections(sections: ParsedAssessmentSection[] | undefined): ParsedQuestionRef[] {
6
+ if (!sections) return [];
7
+ const out: ParsedQuestionRef[] = [];
8
+ for (const s of sections) {
9
+ if (s.questionRefs) out.push(...s.questionRefs);
10
+ if (s.sections) out.push(...collectQuestionRefsFromSections(s.sections));
11
+ }
12
+ return out;
13
+ }
14
+
15
+ function collectQuestionRefs(assessment: ParsedAssessmentTest): ParsedQuestionRef[] {
16
+ const parts = assessment.testParts ?? [];
17
+ const out: ParsedQuestionRef[] = [];
18
+ for (const p of parts) {
19
+ out.push(...collectQuestionRefsFromSections(p.sections));
20
+ }
21
+ return out;
22
+ }
23
+
24
+ function setQuestionRefItemXmlInPlace(
25
+ assessment: ParsedAssessmentTest,
26
+ identifier: string,
27
+ href: string | undefined,
28
+ itemXml: string,
29
+ ) {
30
+ const parts = assessment.testParts ?? [];
31
+ for (const p of parts) {
32
+ const stack: ParsedAssessmentSection[] = [...(p.sections ?? [])];
33
+ while (stack.length) {
34
+ const s = stack.pop()!;
35
+ if (s.questionRefs) {
36
+ for (const q of s.questionRefs) {
37
+ if (q.identifier === identifier || (href && q.href === href)) {
38
+ q.itemXml = itemXml;
39
+ }
40
+ }
41
+ }
42
+ if (s.sections) stack.push(...s.sections);
43
+ }
44
+ }
45
+ }
46
+
47
+ function normalizeBaseUrl(baseUrl: string) {
48
+ try {
49
+ return new URL(baseUrl, window.location.href).toString();
50
+ } catch {
51
+ return baseUrl;
52
+ }
53
+ }
54
+
55
+ export async function resolveItemsForAssessment(options: {
56
+ assessment: ParsedAssessmentTest;
57
+ itemBaseUrl?: string;
58
+ items?: QtiItemMap;
59
+ }): Promise<ParsedAssessmentTest> {
60
+ const { assessment, itemBaseUrl, items } = options;
61
+ const baseUrl = itemBaseUrl ? normalizeBaseUrl(itemBaseUrl) : undefined;
62
+
63
+ // Mutate in-place (questionRefs are nested); return same reference.
64
+ const refs = collectQuestionRefs(assessment);
65
+
66
+ const tasks = refs.map(async (q) => {
67
+ if (q.itemXml) return;
68
+
69
+ // A) fallback convenience: host provides item XML map by href or identifier
70
+ if (items) {
71
+ const fromHref = q.href ? items[q.href] : undefined;
72
+ const fromId = items[q.identifier];
73
+ const xml = fromHref ?? fromId;
74
+ if (xml) {
75
+ q.itemXml = xml;
76
+ return;
77
+ }
78
+ }
79
+
80
+ // B) standard: fetch item XML using href relative to a base URL
81
+ if (baseUrl && q.href) {
82
+ const url = new URL(q.href, baseUrl).toString();
83
+ const res = await fetch(url);
84
+ if (!res.ok) throw new Error(`Failed to fetch QTI item: ${url} (${res.status})`);
85
+ const xml = await res.text();
86
+ setQuestionRefItemXmlInPlace(assessment, q.identifier, q.href, xml);
87
+ }
88
+ });
89
+
90
+ await Promise.all(tasks);
91
+ return assessment;
92
+ }
93
+
94
+
@@ -0,0 +1,33 @@
1
+ import type { RubricBlock } from '@pie-qti/assessment-player';
2
+
3
+ export interface ParsedQuestionRef {
4
+ identifier: string;
5
+ title?: string;
6
+ href?: string;
7
+ required?: boolean;
8
+ itemXml?: string;
9
+ }
10
+
11
+ export interface ParsedAssessmentSection {
12
+ identifier: string;
13
+ title?: string;
14
+ visible?: boolean;
15
+ rubricBlocks?: RubricBlock[];
16
+ questionRefs?: ParsedQuestionRef[];
17
+ sections?: ParsedAssessmentSection[];
18
+ }
19
+
20
+ export interface ParsedTestPart {
21
+ identifier: string;
22
+ navigationMode: 'linear' | 'nonlinear';
23
+ submissionMode: 'individual' | 'simultaneous';
24
+ sections: ParsedAssessmentSection[];
25
+ }
26
+
27
+ export interface ParsedAssessmentTest {
28
+ identifier?: string;
29
+ title?: string;
30
+ testParts: ParsedTestPart[];
31
+ }
32
+
33
+
@@ -0,0 +1,7 @@
1
+ import { defineQtiPlayerElements } from './define.js';
2
+
3
+ defineQtiPlayerElements();
4
+
5
+ export { defineQtiPlayerElements } from './define.js';
6
+
7
+
@@ -0,0 +1,10 @@
1
+ export function safeJsonParse<T>(value: string | null | undefined): T | undefined {
2
+ if (!value) return undefined;
3
+ try {
4
+ return JSON.parse(value) as T;
5
+ } catch {
6
+ return undefined;
7
+ }
8
+ }
9
+
10
+
@@ -0,0 +1,14 @@
1
+ /** @type {import('@sveltejs/vite-plugin-svelte').SvelteConfig} */
2
+ const config = {
3
+ compilerOptions: {
4
+ // Required to compile components that declare `<svelte:options customElement="...">`.
5
+ customElement: true,
6
+ },
7
+ vitePlugin: {
8
+ include: ['**/*.svelte'],
9
+ },
10
+ };
11
+
12
+ export default config;
13
+
14
+
@@ -0,0 +1,125 @@
1
+ import { describe, expect, test } from 'bun:test';
2
+ import { parseAssessmentTestXml } from '../src/qti/parseAssessmentTest.js';
3
+ import { resolveItemsForAssessment } from '../src/qti/resolveItems.js';
4
+
5
+ const ITEM_1_XML = `<?xml version="1.0" encoding="UTF-8"?>
6
+ <assessmentItem xmlns="http://www.imsglobal.org/xsd/imsqti_v2p2" identifier="ITEM-1" title="Item 1">
7
+ <itemBody>
8
+ <p>Hello</p>
9
+ </itemBody>
10
+ </assessmentItem>`;
11
+
12
+ describe('parseAssessmentTestXml', () => {
13
+ test('parses a basic QTI assessmentTest with testPart/section/itemRef/rubricBlock', () => {
14
+ const xml = `<?xml version="1.0" encoding="UTF-8"?>
15
+ <assessmentTest xmlns="http://www.imsglobal.org/xsd/imsqti_v2p2" identifier="TEST-1" title="Sample Test">
16
+ <testPart identifier="P1" navigationMode="nonlinear" submissionMode="simultaneous">
17
+ <assessmentSection identifier="S1" title="Section 1">
18
+ <rubricBlock view="candidate" use="passage">
19
+ <p>Passage <strong>content</strong></p>
20
+ </rubricBlock>
21
+ <assessmentItemRef identifier="ITEM-1" href="items/item1.xml" title="Item 1" />
22
+ </assessmentSection>
23
+ </testPart>
24
+ </assessmentTest>`;
25
+
26
+ const parsed = parseAssessmentTestXml(xml);
27
+ expect(parsed.identifier).toBe('TEST-1');
28
+ expect(parsed.title).toBe('Sample Test');
29
+ expect(parsed.testParts?.length).toBe(1);
30
+
31
+ const part = parsed.testParts?.[0];
32
+ expect(part?.identifier).toBe('P1');
33
+ expect(part?.navigationMode).toBe('nonlinear');
34
+ expect(part?.submissionMode).toBe('simultaneous');
35
+ expect(part?.sections.length).toBe(1);
36
+
37
+ const section = part?.sections[0];
38
+ expect(section?.identifier).toBe('S1');
39
+ expect(section?.title).toBe('Section 1');
40
+ expect(section?.rubricBlocks?.length).toBe(1);
41
+ expect(section?.rubricBlocks?.[0]?.use).toBe('passage');
42
+ expect(section?.rubricBlocks?.[0]?.view).toEqual(['candidate']);
43
+ expect(section?.rubricBlocks?.[0]?.content).toContain('<p>Passage');
44
+
45
+ expect(section?.questionRefs?.length).toBe(1);
46
+ expect(section?.questionRefs?.[0]?.identifier).toBe('ITEM-1');
47
+ expect(section?.questionRefs?.[0]?.href).toBe('items/item1.xml');
48
+ expect(section?.questionRefs?.[0]?.title).toBe('Item 1');
49
+ });
50
+
51
+ test('synthesizes a default testPart when assessmentTest has top-level sections only', () => {
52
+ const xml = `<?xml version="1.0" encoding="UTF-8"?>
53
+ <assessmentTest xmlns="http://www.imsglobal.org/xsd/imsqti_v2p2" identifier="TEST-2" title="No Parts">
54
+ <assessmentSection identifier="S1" title="Section 1">
55
+ <assessmentItemRef identifier="ITEM-1" href="items/item1.xml" />
56
+ </assessmentSection>
57
+ </assessmentTest>`;
58
+
59
+ const parsed = parseAssessmentTestXml(xml);
60
+ expect(parsed.testParts?.length).toBe(1);
61
+ expect(parsed.testParts?.[0]?.identifier).toBe('part-1');
62
+ expect(parsed.testParts?.[0]?.sections.length).toBe(1);
63
+ });
64
+ });
65
+
66
+ describe('resolveItemsForAssessment', () => {
67
+ test('A) resolves assessmentItemRef via in-memory items map (by href)', async () => {
68
+ const xml = `<?xml version="1.0" encoding="UTF-8"?>
69
+ <assessmentTest xmlns="http://www.imsglobal.org/xsd/imsqti_v2p2" identifier="TEST-3" title="Map">
70
+ <testPart identifier="P1" navigationMode="nonlinear" submissionMode="simultaneous">
71
+ <assessmentSection identifier="S1">
72
+ <assessmentItemRef identifier="ITEM-1" href="items/item1.xml" />
73
+ </assessmentSection>
74
+ </testPart>
75
+ </assessmentTest>`;
76
+
77
+ const assessment = parseAssessmentTestXml(xml);
78
+ await resolveItemsForAssessment({
79
+ assessment,
80
+ items: {
81
+ 'items/item1.xml': ITEM_1_XML,
82
+ },
83
+ });
84
+
85
+ const q = assessment.testParts?.[0]?.sections?.[0]?.questionRefs?.[0];
86
+ expect(q?.itemXml).toContain('assessmentItem');
87
+ expect(q?.itemXml).toContain('identifier="ITEM-1"');
88
+ });
89
+
90
+ test('B) resolves assessmentItemRef by fetching href relative to base URL', async () => {
91
+ const xml = `<?xml version="1.0" encoding="UTF-8"?>
92
+ <assessmentTest xmlns="http://www.imsglobal.org/xsd/imsqti_v2p2" identifier="TEST-4" title="Fetch">
93
+ <testPart identifier="P1" navigationMode="nonlinear" submissionMode="simultaneous">
94
+ <assessmentSection identifier="S1">
95
+ <assessmentItemRef identifier="ITEM-1" href="items/item1.xml" />
96
+ </assessmentSection>
97
+ </testPart>
98
+ </assessmentTest>`;
99
+
100
+ const assessment = parseAssessmentTestXml(xml);
101
+
102
+ const origFetch = globalThis.fetch;
103
+ const calls: string[] = [];
104
+ (globalThis as any).fetch = async (url: string) => {
105
+ calls.push(url);
106
+ return new Response(ITEM_1_XML, { status: 200 });
107
+ };
108
+
109
+ try {
110
+ await resolveItemsForAssessment({
111
+ assessment,
112
+ itemBaseUrl: 'https://example.test/qti/',
113
+ });
114
+ } finally {
115
+ (globalThis as any).fetch = origFetch;
116
+ }
117
+
118
+ expect(calls.length).toBe(1);
119
+ expect(calls[0]).toBe('https://example.test/qti/items/item1.xml');
120
+ const q = assessment.testParts?.[0]?.sections?.[0]?.questionRefs?.[0];
121
+ expect(q?.itemXml).toContain('assessmentItem');
122
+ });
123
+ });
124
+
125
+