@pie-qti/assessment-player 0.1.27 → 1.0.0-beta.0
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.
- package/README.md +13 -0
- package/dist/core/AssessmentPlayer.d.ts +54 -14
- package/dist/core/AssessmentPlayer.js +204 -166
- package/dist/core/AssessmentPlayer.js.map +1 -1
- package/dist/core/AssessmentSessionCoordinator.d.ts +10 -2
- package/dist/core/AssessmentSessionCoordinator.js +24 -3
- package/dist/core/AssessmentSessionCoordinator.js.map +1 -1
- package/dist/core/ItemSessionController.d.ts +14 -3
- package/dist/core/ItemSessionController.js +31 -12
- package/dist/core/ItemSessionController.js.map +1 -1
- package/dist/core/TimeManager.d.ts +20 -7
- package/dist/core/TimeManager.js +20 -18
- package/dist/core/TimeManager.js.map +1 -1
- package/dist/core/testStructure.d.ts +65 -0
- package/dist/core/testStructure.js +336 -0
- package/dist/core/testStructure.js.map +1 -0
- package/dist/index.d.ts +2 -1
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/integration/ReferenceBackendAdapter.d.ts +53 -5
- package/dist/integration/ReferenceBackendAdapter.js +317 -230
- package/dist/integration/ReferenceBackendAdapter.js.map +1 -1
- package/dist/integration/api-contract.d.ts +92 -49
- package/dist/integration/api-contract.js.map +1 -1
- package/dist/integration/assessment-item-scorer.d.ts +11 -1
- package/dist/integration/assessment-item-scorer.js +102 -12
- package/dist/integration/assessment-item-scorer.js.map +1 -1
- package/dist/integration/index.d.ts +1 -1
- package/dist/integration/index.js.map +1 -1
- package/dist/integration/toSectionComposition.js +1 -0
- package/dist/integration/toSectionComposition.js.map +1 -1
- package/dist/types/index.d.ts +10 -0
- package/dist/types/index.js.map +1 -1
- package/package.json +10 -10
|
@@ -38,11 +38,25 @@ export interface InitSessionRequest {
|
|
|
38
38
|
export interface InitSessionResponse {
|
|
39
39
|
/** Unique session identifier for all subsequent requests */
|
|
40
40
|
sessionId: SessionId;
|
|
41
|
-
/** Assessment structure
|
|
41
|
+
/** Assessment structure without sensitive data, as drawn for this session; a resume returns the same draw. */
|
|
42
42
|
assessment: SecureAssessment;
|
|
43
43
|
/** Restored state if resuming, undefined if new session */
|
|
44
44
|
restoredState?: AssessmentSessionState;
|
|
45
|
+
/**
|
|
46
|
+
* Item delivery starts at in a new session: the first item whose preconditions hold. A resumed
|
|
47
|
+
* session carries it in `restoredState`.
|
|
48
|
+
*/
|
|
49
|
+
currentItemIdentifier?: string;
|
|
50
|
+
/** Test-level outcome values of a resumed session, once outcome processing has run */
|
|
51
|
+
outcomes?: TestOutcomeValues;
|
|
45
52
|
}
|
|
53
|
+
/**
|
|
54
|
+
* A test-level outcome value: a scalar for single cardinality, an array for multiple and ordered,
|
|
55
|
+
* an object for record, and `null` for NULL.
|
|
56
|
+
*/
|
|
57
|
+
export type TestOutcomeValue = string | number | boolean | null | Array<string | number | boolean | null> | Record<string, unknown>;
|
|
58
|
+
/** Test-level outcome values keyed by outcome identifier (e.g. "PASS", "GRADE"). */
|
|
59
|
+
export type TestOutcomeValues = Record<string, TestOutcomeValue>;
|
|
46
60
|
/**
|
|
47
61
|
* Assessment structure safe for client consumption
|
|
48
62
|
*
|
|
@@ -52,9 +66,15 @@ export interface TestFeedbackItem {
|
|
|
52
66
|
identifier: string;
|
|
53
67
|
/** Outcome variable name to evaluate (e.g. "PASS", "GRADE") */
|
|
54
68
|
outcomeIdentifier: string;
|
|
55
|
-
/**
|
|
69
|
+
/**
|
|
70
|
+
* 'show' = show when the outcome matches identifier (equality for a single value, membership
|
|
71
|
+
* for multiple and ordered); 'hide' = show when it does not
|
|
72
|
+
*/
|
|
56
73
|
showHide: 'show' | 'hide';
|
|
57
|
-
/**
|
|
74
|
+
/**
|
|
75
|
+
* 'atEnd' = once the test (or, for test-part feedback, the part) has ended;
|
|
76
|
+
* 'during' = whenever outcome processing has run
|
|
77
|
+
*/
|
|
58
78
|
access: 'atEnd' | 'during';
|
|
59
79
|
/** HTML content to display */
|
|
60
80
|
content: string;
|
|
@@ -86,7 +106,7 @@ export interface SecureAssessment {
|
|
|
86
106
|
outcomeProcessingXml?: string;
|
|
87
107
|
/** Base URL/path for resolving relative hrefs (e.g. assessmentSectionRef) */
|
|
88
108
|
baseUrl?: string;
|
|
89
|
-
/** QTI testFeedback blocks
|
|
109
|
+
/** QTI assessmentTest testFeedback blocks */
|
|
90
110
|
testFeedback?: TestFeedbackItem[];
|
|
91
111
|
}
|
|
92
112
|
export interface SecureTestPart {
|
|
@@ -100,19 +120,17 @@ export interface SecureTestPart {
|
|
|
100
120
|
timeLimits?: SecureTimeLimits;
|
|
101
121
|
/** Candidate instructions (safe for display) */
|
|
102
122
|
rubricBlocks?: AssessmentRubricBlock[];
|
|
123
|
+
/** QTI testPart testFeedback blocks */
|
|
124
|
+
testFeedback?: TestFeedbackItem[];
|
|
103
125
|
/**
|
|
104
|
-
* Item session control (QTI testPart/itemSessionControl).
|
|
105
|
-
*
|
|
126
|
+
* Item session control (QTI testPart/itemSessionControl). Each attribute cascades through every
|
|
127
|
+
* enclosing section to the item ref; the backend enforces maxAttempts.
|
|
106
128
|
*/
|
|
107
|
-
itemSessionControl?:
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
allowComment?: boolean;
|
|
113
|
-
allowSkipping?: boolean;
|
|
114
|
-
validateResponses?: boolean;
|
|
115
|
-
};
|
|
129
|
+
itemSessionControl?: SecureItemSessionControl;
|
|
130
|
+
/** Serialized direct preCondition expressions, evaluated by the backend on entering the part. */
|
|
131
|
+
preConditions?: string[];
|
|
132
|
+
/** Branch rules the backend evaluates after the part's last item, in linear navigation. */
|
|
133
|
+
branchRule?: SecureBranchRule[];
|
|
116
134
|
}
|
|
117
135
|
export interface SecureSection {
|
|
118
136
|
identifier: string;
|
|
@@ -121,7 +139,7 @@ export interface SecureSection {
|
|
|
121
139
|
fixed?: boolean;
|
|
122
140
|
/** Visible determines if section appears in navigation */
|
|
123
141
|
visible: boolean;
|
|
124
|
-
/** Assessment item references
|
|
142
|
+
/** Assessment item references, in the order the backend drew for this session. */
|
|
125
143
|
assessmentItemRefs: SecureItemRef[];
|
|
126
144
|
/** Nested QTI sections, retained instead of being flattened during XML ingestion. */
|
|
127
145
|
sections?: SecureSection[];
|
|
@@ -135,36 +153,49 @@ export interface SecureSection {
|
|
|
135
153
|
/** Candidate instructions (safe for display) */
|
|
136
154
|
rubricBlocks?: AssessmentRubricBlock[];
|
|
137
155
|
/**
|
|
138
|
-
* QTI selection: how many
|
|
139
|
-
*
|
|
156
|
+
* QTI selection: how many children to present from this section. Backends draw selection when
|
|
157
|
+
* the session starts and return the drawn assessment without it; the client never draws.
|
|
140
158
|
*/
|
|
141
159
|
selection?: {
|
|
142
160
|
/** Number of items selected for this session */
|
|
143
161
|
select: number;
|
|
144
162
|
withReplacement?: boolean;
|
|
145
163
|
};
|
|
146
|
-
/**
|
|
147
|
-
* QTI ordering: whether items were shuffled.
|
|
148
|
-
* When true the server has already shuffled assessmentItemRefs.
|
|
149
|
-
*/
|
|
164
|
+
/** QTI ordering: whether non-fixed children are shuffled. Backends apply it with selection. */
|
|
150
165
|
ordering?: {
|
|
151
166
|
shuffle: boolean;
|
|
152
167
|
};
|
|
153
168
|
/** Serialized direct preCondition expressions, evaluated by the backend. */
|
|
154
169
|
preConditions?: string[];
|
|
170
|
+
/** Branch rules the backend evaluates after the section's last item, in linear navigation. */
|
|
171
|
+
branchRule?: SecureBranchRule[];
|
|
155
172
|
/**
|
|
156
|
-
*
|
|
157
|
-
*
|
|
173
|
+
* QTI keepTogether, default true. An invisible section with keepTogether false has its children
|
|
174
|
+
* mixed into the parent's ordering; the backend applies it while drawing.
|
|
158
175
|
*/
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
176
|
+
keepTogether?: boolean;
|
|
177
|
+
/**
|
|
178
|
+
* Item session control (QTI assessmentSection/itemSessionControl). Attributes set here override
|
|
179
|
+
* the enclosing section's and test part's.
|
|
180
|
+
*/
|
|
181
|
+
itemSessionControl?: SecureItemSessionControl;
|
|
182
|
+
}
|
|
183
|
+
/** QTI itemSessionControl. Absent attributes inherit from the enclosing section or test part. */
|
|
184
|
+
export interface SecureItemSessionControl {
|
|
185
|
+
/** Default 1; 0 means unlimited. Adaptive items are unlimited whatever the value. */
|
|
186
|
+
maxAttempts?: number;
|
|
187
|
+
showFeedback?: boolean;
|
|
188
|
+
allowReview?: boolean;
|
|
189
|
+
showSolution?: boolean;
|
|
190
|
+
allowComment?: boolean;
|
|
191
|
+
allowSkipping?: boolean;
|
|
192
|
+
validateResponses?: boolean;
|
|
193
|
+
}
|
|
194
|
+
export interface SecureBranchRule {
|
|
195
|
+
/** Identifier of the target item, section or test part, or EXIT_TEST, EXIT_TESTPART or EXIT_SECTION. */
|
|
196
|
+
target: string;
|
|
197
|
+
/** Serialised QTI expression XML (the child of <branchRule>). Absent means unconditional. */
|
|
198
|
+
conditionXml?: string;
|
|
168
199
|
}
|
|
169
200
|
export type SecureSectionComponent = {
|
|
170
201
|
type: 'item';
|
|
@@ -188,17 +219,10 @@ export interface SecureItemRef {
|
|
|
188
219
|
/** Optional resolved QTI 3 delivery context. Additive; itemXml remains the compatibility path. */
|
|
189
220
|
deliveryContext?: ResolvedItemDeliveryContext;
|
|
190
221
|
/**
|
|
191
|
-
* QTI branchRule: ordered
|
|
192
|
-
*
|
|
193
|
-
* Carried here so reference/demo adapters can evaluate them client-side.
|
|
222
|
+
* QTI branchRule: ordered branch rules on this item. The backend evaluates them after scoring, in
|
|
223
|
+
* linear navigation, and returns the resolved target as nextItemIdentifier.
|
|
194
224
|
*/
|
|
195
|
-
branchRule?:
|
|
196
|
-
/** Identifier of the target item, section, testPart, or one of the special values:
|
|
197
|
-
* EXIT_TEST | EXIT_TESTPART | EXIT_SECTION */
|
|
198
|
-
target: string;
|
|
199
|
-
/** Serialised QTI expression XML (the child of <branchRule>). Absent means unconditional. */
|
|
200
|
-
conditionXml?: string;
|
|
201
|
-
}>;
|
|
225
|
+
branchRule?: SecureBranchRule[];
|
|
202
226
|
/** Serialized direct preCondition expressions, evaluated by the backend. */
|
|
203
227
|
preConditions?: string[];
|
|
204
228
|
/** QTI item-ref weights, preserved for backend outcome processing. */
|
|
@@ -206,6 +230,23 @@ export interface SecureItemRef {
|
|
|
206
230
|
identifier: string;
|
|
207
231
|
value: number;
|
|
208
232
|
}>;
|
|
233
|
+
/** QTI item-ref categories, matched by includeCategory/excludeCategory in outcome processing. */
|
|
234
|
+
categories?: string[];
|
|
235
|
+
/** Item session control (assessmentItemRef/itemSessionControl), the innermost cascade level. */
|
|
236
|
+
itemSessionControl?: SecureItemSessionControl;
|
|
237
|
+
/** QTI variableMapping: item variables the test reads under another identifier. */
|
|
238
|
+
variableMappings?: Array<{
|
|
239
|
+
sourceIdentifier: string;
|
|
240
|
+
targetIdentifier: string;
|
|
241
|
+
}>;
|
|
242
|
+
/**
|
|
243
|
+
* QTI templateDefault: serialized expressions, evaluated against test outcomes, that replace a
|
|
244
|
+
* template variable's default before template processing.
|
|
245
|
+
*/
|
|
246
|
+
templateDefaults?: Array<{
|
|
247
|
+
templateIdentifier: string;
|
|
248
|
+
expressionXml: string;
|
|
249
|
+
}>;
|
|
209
250
|
}
|
|
210
251
|
export interface AssessmentRubricBlock {
|
|
211
252
|
/** Optional rubric identifier (QTI rubricBlock@identifier) */
|
|
@@ -239,6 +280,8 @@ export interface SubmitResponsesRequest {
|
|
|
239
280
|
* Production backends should treat this as a client save format and validate against server-owned state.
|
|
240
281
|
*/
|
|
241
282
|
itemSession?: SerializedItemSessionState;
|
|
283
|
+
/** Candidate comment, accepted only when the item's allowComment is on. */
|
|
284
|
+
comment?: string;
|
|
242
285
|
}
|
|
243
286
|
export interface SubmitTimingEvidence {
|
|
244
287
|
scope: 'assessment' | 'testPart' | 'section' | 'item';
|
|
@@ -266,6 +309,8 @@ export interface SubmitResponsesResponse {
|
|
|
266
309
|
* If provided, client should replace its local state with this.
|
|
267
310
|
*/
|
|
268
311
|
updatedState?: AssessmentSessionState;
|
|
312
|
+
/** Test-level outcome values after the outcome processing this submission triggers */
|
|
313
|
+
outcomes?: TestOutcomeValues;
|
|
269
314
|
/** Error message if success=false */
|
|
270
315
|
error?: string;
|
|
271
316
|
}
|
|
@@ -323,6 +368,8 @@ export interface AssessmentSessionState {
|
|
|
323
368
|
itemSessionStates?: Record<string, AssessmentItemSessionState>;
|
|
324
369
|
/** Rich QTI item session snapshots, used to restore variables and score saved sessions. */
|
|
325
370
|
itemSessions?: Record<string, SerializedItemSessionState>;
|
|
371
|
+
/** Candidate comments per item, captured where allowComment is on. */
|
|
372
|
+
itemComments?: Record<string, string>;
|
|
326
373
|
/** Time tracking */
|
|
327
374
|
timing: {
|
|
328
375
|
/** Session start time */
|
|
@@ -367,12 +414,8 @@ export interface FinalizeAssessmentResponse {
|
|
|
367
414
|
itemScores: Record<string, AssessmentScoringResult>;
|
|
368
415
|
/** Assessment-level feedback (legacy: single string; prefer outcomes + assessment.testFeedback) */
|
|
369
416
|
feedback?: string;
|
|
370
|
-
/**
|
|
371
|
-
|
|
372
|
-
* Used to evaluate testFeedback visibility via string equality.
|
|
373
|
-
* Keys are outcome identifiers (e.g. "PASS", "GRADE"); values are their string representations.
|
|
374
|
-
*/
|
|
375
|
-
outcomes?: Record<string, string>;
|
|
417
|
+
/** Test-level outcome values after outcomeProcessing; testFeedback visibility reads them. */
|
|
418
|
+
outcomes?: TestOutcomeValues;
|
|
376
419
|
/** Server timestamp */
|
|
377
420
|
finalizedAt: number;
|
|
378
421
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"api-contract.js","sourceRoot":"","sources":["../../src/integration/api-contract.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG","sourcesContent":["/**\n * QTI 2.2 Assessment Player - Backend Integration API Contract\n *\n * This file defines the secure API boundary between the client-side player\n * and backend services. The design prioritizes security by ensuring sensitive\n * data (correct answers, scoring rules) never reaches the client.\n *\n * ## Security Model\n *\n * - **Client-side**: Collects and submits candidate responses only\n * - **Server-side**: Stores QTI XML, performs scoring, validates submissions\n * - **Role-based**: Server controls what data client receives based on QTI role\n *\n * ## Reference Implementation\n *\n * See `ReferenceBackendAdapter.ts` for a simple localStorage-based implementation\n * that demonstrates the API contract without requiring a real backend.\n */\n\nimport type { QTIRole, ResolvedItemDeliveryContext, SerializedItemSessionState } from '@pie-qti/item-player';\n\n// ============================================================================\n// SESSION MANAGEMENT\n// ============================================================================\n\n/**\n * Unique identifier for an assessment session\n * Format: \"{assessmentId}:{candidateId}:{timestamp}\" or similar\n */\nexport type SessionId = string;\n\n/**\n * Initialize a new assessment session\n *\n * Security: Server validates candidate identity and assessment access\n */\nexport interface InitSessionRequest {\n\t/** Assessment identifier (QTI assessmentTest identifier) */\n\tassessmentId: string;\n\t/** Candidate identifier (from authentication system) */\n\tcandidateId: string;\n\t/** Optional: Resume from existing session */\n\tresumeSessionId?: SessionId;\n}\n\nexport interface InitSessionResponse {\n\t/** Unique session identifier for all subsequent requests */\n\tsessionId: SessionId;\n\t/** Assessment structure WITHOUT sensitive data */\n\tassessment: SecureAssessment;\n\t/** Restored state if resuming, undefined if new session */\n\trestoredState?: AssessmentSessionState;\n}\n\n// ============================================================================\n// ASSESSMENT STRUCTURE (CLIENT-SAFE)\n// ============================================================================\n\n/**\n * Assessment structure safe for client consumption\n *\n * Security: NO correct answers, NO scoring rules, NO sensitive rubrics\n */\nexport interface TestFeedbackItem {\n\tidentifier: string;\n\t/** Outcome variable name to evaluate (e.g. \"PASS\", \"GRADE\") */\n\toutcomeIdentifier: string;\n\t/** 'show' = show when outcome equals identifier; 'hide' = show when it does not */\n\tshowHide: 'show' | 'hide';\n\t/** 'atEnd' = only after submission; 'during' = also during attempt */\n\taccess: 'atEnd' | 'during';\n\t/** HTML content to display */\n\tcontent: string;\n}\n\nexport interface SecureTimeLimits {\n\tminTime?: number;\n\tmaxTime?: number;\n\tallowLateSubmission?: boolean;\n}\n\nexport interface SecureAssessment {\n\tidentifier: string;\n\ttitle: string;\n\t/** Navigation mode affects UI */\n\tnavigationMode: 'linear' | 'nonlinear';\n\t/** Submission mode affects when responses are finalized */\n\tsubmissionMode: 'individual' | 'simultaneous';\n\t/** Test parts contain sections */\n\ttestParts: SecureTestPart[];\n\t/** Overall time limit in seconds (optional) */\n\ttimeLimits?: SecureTimeLimits;\n\t/** QTI outcomeDeclarations for test-level variables */\n\toutcomeDeclarations?: Array<{\n\t\tidentifier: string;\n\t\tbaseType: string;\n\t\tcardinality: string;\n\t\tdefaultValue?: unknown;\n\t}>;\n\t/** Raw <outcomeProcessing> XML string, if present */\n\toutcomeProcessingXml?: string;\n\t/** Base URL/path for resolving relative hrefs (e.g. assessmentSectionRef) */\n\tbaseUrl?: string;\n\t/** QTI testFeedback blocks for post-submission display */\n\ttestFeedback?: TestFeedbackItem[];\n}\n\nexport interface SecureTestPart {\n\tidentifier: string;\n\t/** Navigation and submission modes are scoped to each QTI testPart. */\n\tnavigationMode?: 'linear' | 'nonlinear';\n\tsubmissionMode?: 'individual' | 'simultaneous';\n\t/** Sections contain items */\n\tsections: SecureSection[];\n\t/** TestPart-level time limit. */\n\ttimeLimits?: SecureTimeLimits;\n\t/** Candidate instructions (safe for display) */\n\trubricBlocks?: AssessmentRubricBlock[];\n\t/**\n\t * Item session control (QTI testPart/itemSessionControl).\n\t * Server is authoritative; client uses this for UI hints only.\n\t */\n\titemSessionControl?: {\n\t\tmaxAttempts?: number;\n\t\tshowFeedback?: boolean;\n\t\tallowReview?: boolean;\n\t\tshowSolution?: boolean;\n\t\tallowComment?: boolean;\n\t\tallowSkipping?: boolean;\n\t\tvalidateResponses?: boolean;\n\t};\n}\n\nexport interface SecureSection {\n\tidentifier: string;\n\ttitle?: string;\n\trequired?: boolean;\n\tfixed?: boolean;\n\t/** Visible determines if section appears in navigation */\n\tvisible: boolean;\n\t/** Assessment item references (order reflects selection/ordering already applied server-side) */\n\tassessmentItemRefs: SecureItemRef[];\n\t/** Nested QTI sections, retained instead of being flattened during XML ingestion. */\n\tsections?: SecureSection[];\n\t/**\n\t * Direct delivery components in document order. When present, this is the\n\t * authoritative order for mixed item/section children.\n\t */\n\tchildren?: SecureSectionComponent[];\n\t/** Section-level time limit */\n\ttimeLimits?: SecureTimeLimits;\n\t/** Candidate instructions (safe for display) */\n\trubricBlocks?: AssessmentRubricBlock[];\n\t/**\n\t * QTI selection: how many items to present from this section.\n\t * When present the server has already applied selection; client uses this for progress display.\n\t */\n\tselection?: {\n\t\t/** Number of items selected for this session */\n\t\tselect: number;\n\t\twithReplacement?: boolean;\n\t};\n\t/**\n\t * QTI ordering: whether items were shuffled.\n\t * When true the server has already shuffled assessmentItemRefs.\n\t */\n\tordering?: {\n\t\tshuffle: boolean;\n\t};\n\t/** Serialized direct preCondition expressions, evaluated by the backend. */\n\tpreConditions?: string[];\n\t/**\n\t * Item session control (QTI assessmentSection/itemSessionControl).\n\t * Section-level values take precedence over testPart-level when present.\n\t */\n\titemSessionControl?: {\n\t\tmaxAttempts?: number;\n\t\tshowFeedback?: boolean;\n\t\tallowReview?: boolean;\n\t\tshowSolution?: boolean;\n\t\tallowComment?: boolean;\n\t\tallowSkipping?: boolean;\n\t\tvalidateResponses?: boolean;\n\t};\n}\n\nexport type SecureSectionComponent =\n\t| { type: 'item'; item: SecureItemRef }\n\t| { type: 'section'; section: SecureSection };\n\nexport interface SecureItemRef {\n\t/** Unique item identifier */\n\tidentifier: string;\n\t/** Item XML WITHOUT responseProcessing if role is 'candidate' */\n\titemXml: string;\n\t/** QTI role determines what's visible in itemXml */\n\trole: QTIRole;\n\t/** Required=true means item must be attempted */\n\trequired?: boolean;\n\tfixed?: boolean;\n\t/** Item-ref-level time limit. */\n\ttimeLimits?: SecureTimeLimits;\n\t/** Optional resolved QTI 3 delivery context. Additive; itemXml remains the compatibility path. */\n\tdeliveryContext?: ResolvedItemDeliveryContext;\n\t/**\n\t * QTI branchRule: ordered list of branch rules on this item.\n\t * The backend evaluates these after scoring and returns nextItemIdentifier in SubmitResponsesResponse.\n\t * Carried here so reference/demo adapters can evaluate them client-side.\n\t */\n\tbranchRule?: Array<{\n\t\t/** Identifier of the target item, section, testPart, or one of the special values:\n\t\t * EXIT_TEST | EXIT_TESTPART | EXIT_SECTION */\n\t\ttarget: string;\n\t\t/** Serialised QTI expression XML (the child of <branchRule>). Absent means unconditional. */\n\t\tconditionXml?: string;\n\t}>;\n\t/** Serialized direct preCondition expressions, evaluated by the backend. */\n\tpreConditions?: string[];\n\t/** QTI item-ref weights, preserved for backend outcome processing. */\n\tweights?: Array<{ identifier: string; value: number }>;\n}\n\nexport interface AssessmentRubricBlock {\n\t/** Optional rubric identifier (QTI rubricBlock@identifier) */\n\tidentifier?: string;\n\t/** Rubric content (HTML) */\n\tcontent: string;\n\t/** View controls when rubric is shown */\n\tview: QTIRole[];\n\t/** Optional rubric use (QTI rubricBlock@use), e.g. \"passage\" */\n\tuse?: string;\n}\n\n// ============================================================================\n// RESPONSE SUBMISSION\n// ============================================================================\n\n/**\n * Submit responses for scoring\n *\n * Security: Client sends responses only, server performs scoring\n */\nexport interface SubmitResponsesRequest {\n\tsessionId: SessionId;\n\t/** Item identifier */\n\titemIdentifier: string;\n\t/** Response data keyed by responseIdentifier */\n\tresponses: Record<string, ResponseValue>;\n\t/** Client timestamp for analytics */\n\tsubmittedAt: number;\n\t/** Time spent on item (ms) for analytics */\n\ttimeSpent?: number;\n\t/** Optional client timing evidence; production backends remain authoritative. */\n\ttiming?: SubmitTimingEvidence;\n\t/**\n\t * Serialized item session used by backends to restore template/context variables while scoring.\n\t * Production backends should treat this as a client save format and validate against server-owned state.\n\t */\n\titemSession?: SerializedItemSessionState;\n}\n\nexport interface SubmitTimingEvidence {\n\tscope: 'assessment' | 'testPart' | 'section' | 'item';\n\telapsedMs: number;\n\tlimitSeconds?: number;\n\texpired?: boolean;\n\tallowLateSubmission?: boolean;\n}\n\n/**\n * Response value can be string, string[], or complex types\n */\nexport type ResponseValue = string | string[] | Record<string, any>;\n\nexport interface SubmitResponsesResponse {\n\t/** Was submission accepted? */\n\tsuccess: boolean;\n\t/** Scoring result (if submission mode allows immediate scoring) */\n\tresult?: AssessmentScoringResult;\n\t/**\n\t * Backend-authoritative next item (branching/navigation decision).\n\t * If omitted, client may fall back to linear next/previous UI navigation.\n\t */\n\tnextItemIdentifier?: string;\n\t/**\n\t * Backend-authoritative session state snapshot after applying the submission.\n\t * If provided, client should replace its local state with this.\n\t */\n\tupdatedState?: AssessmentSessionState;\n\t/** Error message if success=false */\n\terror?: string;\n}\n\n// ============================================================================\n// SCORING RESULTS\n// ============================================================================\n\n/**\n * Scoring result returned from server\n *\n * Security: Server computes this, client never sees scoring rules\n */\nexport interface AssessmentScoringResult {\n\t/** Item identifier */\n\titemIdentifier: string;\n\t/** Normalized score 0.0-1.0 */\n\tscore: number;\n\t/** Maximum possible score (usually 1.0) */\n\tmaxScore: number;\n\t/** Was item completed? */\n\tcompleted: boolean;\n\t/** QTI outcome variables */\n\toutcomeValues: Record<string, any>;\n\t/** Feedback to display (role-dependent) */\n\tfeedback?: FeedbackItem[];\n\t/** Correct response (only if role allows) */\n\tcorrectResponse?: Record<string, ResponseValue>;\n}\n\nexport interface FeedbackItem {\n\t/** Feedback content (HTML) */\n\tcontent: string;\n\t/** Feedback type */\n\ttype: 'correct' | 'incorrect' | 'hint' | 'solution';\n}\n\n// ============================================================================\n// STATE PERSISTENCE\n// ============================================================================\n\n/**\n * Save assessment state\n *\n * Security: State includes responses but not scores (until finalized)\n */\nexport interface SaveAssessmentStateRequest {\n\tsessionId: SessionId;\n\tstate: AssessmentSessionState;\n}\n\nexport interface SaveAssessmentStateResponse {\n\tsuccess: boolean;\n\t/** Server timestamp of save */\n\tsavedAt: number;\n}\n\nexport interface AssessmentSessionState {\n\t/** Current item identifier */\n\tcurrentItemIdentifier: string;\n\t/** Visited items (for navigation) */\n\tvisitedItems: string[];\n\t/** Submitted responses per item */\n\titemResponses: Record<string, Record<string, ResponseValue>>;\n\t/** Scoring results per item (populated after submission) */\n\titemScores?: Record<string, AssessmentScoringResult>;\n\t/** ItemSession lifecycle hints per item, used to restore attempt/review UI state */\n\titemSessionStates?: Record<string, AssessmentItemSessionState>;\n\t/** Rich QTI item session snapshots, used to restore variables and score saved sessions. */\n\titemSessions?: Record<string, SerializedItemSessionState>;\n\t/** Time tracking */\n\ttiming: {\n\t\t/** Session start time */\n\t\tstartedAt: number;\n\t\t/** Time spent per item (ms) */\n\t\titemTimes: Record<string, number>;\n\t\t/** Time spent per assessment section (ms). */\n\t\tsectionTimes?: Record<string, number>;\n\t\t/** Time spent per testPart (ms). */\n\t\ttestPartTimes?: Record<string, number>;\n\t\t/** Total elapsed time (ms) */\n\t\ttotalTime: number;\n\t\t/** Active scope identifiers retained for save/resume timing continuity. */\n\t\tcurrentItemIdentifier?: string;\n\t\tcurrentSectionIdentifier?: string;\n\t\tcurrentTestPartIdentifier?: string;\n\t\tisPaused?: boolean;\n\t};\n}\n\nexport interface AssessmentItemSessionState {\n\titemIdentifier: string;\n\tattemptCount: number;\n\tisAnswered: boolean;\n\tisSubmitted: boolean;\n\tlastSubmissionTime?: number;\n}\n\n// ============================================================================\n// FINALIZE ASSESSMENT\n// ============================================================================\n\n/**\n * Finalize assessment and get full results\n *\n * Security: Server computes final scores, applies late penalties, etc.\n */\nexport interface FinalizeAssessmentRequest {\n\tsessionId: SessionId;\n}\n\nexport interface FinalizeAssessmentResponse {\n\tsuccess: boolean;\n\t/** Overall assessment score */\n\ttotalScore: number;\n\t/** Maximum possible score */\n\tmaxScore: number;\n\t/** Per-item results */\n\titemScores: Record<string, AssessmentScoringResult>;\n\t/** Assessment-level feedback (legacy: single string; prefer outcomes + assessment.testFeedback) */\n\tfeedback?: string;\n\t/**\n\t * Test-level outcome variable values after outcomeProcessing.\n\t * Used to evaluate testFeedback visibility via string equality.\n\t * Keys are outcome identifiers (e.g. \"PASS\", \"GRADE\"); values are their string representations.\n\t */\n\toutcomes?: Record<string, string>;\n\t/** Server timestamp */\n\tfinalizedAt: number;\n}\n\n// ============================================================================\n// ITEM BANK QUERIES\n// ============================================================================\n\n/**\n * Request items from an item bank for random selection\n *\n * Security: Server validates candidate access to bank\n */\nexport interface QueryItemBankRequest {\n\t/** Unique session identifier */\n\tsessionId: SessionId;\n\t/** Item bank identifier (from selection/@fromBank attribute) */\n\tbankId: string;\n\t/** Number of items to select */\n\tcount: number;\n\t/** Whether to allow selecting same item multiple times */\n\twithReplacement?: boolean;\n\t/** Optional filtering criteria (difficulty, topic, etc.) */\n\tfilters?: {\n\t\tdifficulty?: 'easy' | 'medium' | 'hard';\n\t\ttopics?: string[];\n\t\t[key: string]: unknown;\n\t};\n}\n\n/**\n * Items selected from item bank\n *\n * Security: Returns items WITHOUT correct answers or scoring rules\n */\nexport interface QueryItemBankResponse {\n\t/** Selected item references (client-safe) */\n\titems: SecureItemRef[];\n\t/** Server timestamp */\n\tselectedAt: number;\n}\n\n// ============================================================================\n// BACKEND ADAPTER INTERFACE\n// ============================================================================\n\n/**\n * Backend adapter interface - implement this for your backend\n *\n * @example\n * ```typescript\n * class MyBackendAdapter implements BackendAdapter {\n * async initSession(req: InitSessionRequest): Promise<InitSessionResponse> {\n * const response = await fetch('/api/qti/init', {\n * method: 'POST',\n * body: JSON.stringify(req)\n * });\n * return response.json();\n * }\n * // ... implement other methods\n * }\n * ```\n */\nexport interface BackendAdapter {\n\t/**\n\t * Initialize new assessment session\n\t */\n\tinitSession(request: InitSessionRequest): Promise<InitSessionResponse>;\n\n\t/**\n\t * Submit item responses for scoring\n\t */\n\tsubmitResponses(request: SubmitResponsesRequest): Promise<SubmitResponsesResponse>;\n\n\t/**\n\t * Save session state (auto-save during assessment)\n\t */\n\tsaveState(request: SaveAssessmentStateRequest): Promise<SaveAssessmentStateResponse>;\n\n\t/**\n\t * Finalize assessment and get results\n\t */\n\tfinalizeAssessment(request: FinalizeAssessmentRequest): Promise<FinalizeAssessmentResponse>;\n\n\t/**\n\t * Resume session (optional - can reuse initSession)\n\t */\n\tresumeSession?(sessionId: SessionId): Promise<InitSessionResponse>;\n\n\t/**\n\t * Query item bank for random item selection\n\t *\n\t * Security: Server validates access and returns items WITHOUT sensitive data\n\t */\n\tqueryItemBank?(request: QueryItemBankRequest): Promise<QueryItemBankResponse>;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"api-contract.js","sourceRoot":"","sources":["../../src/integration/api-contract.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG","sourcesContent":["/**\n * QTI 2.2 Assessment Player - Backend Integration API Contract\n *\n * This file defines the secure API boundary between the client-side player\n * and backend services. The design prioritizes security by ensuring sensitive\n * data (correct answers, scoring rules) never reaches the client.\n *\n * ## Security Model\n *\n * - **Client-side**: Collects and submits candidate responses only\n * - **Server-side**: Stores QTI XML, performs scoring, validates submissions\n * - **Role-based**: Server controls what data client receives based on QTI role\n *\n * ## Reference Implementation\n *\n * See `ReferenceBackendAdapter.ts` for a simple localStorage-based implementation\n * that demonstrates the API contract without requiring a real backend.\n */\n\nimport type { QTIRole, ResolvedItemDeliveryContext, SerializedItemSessionState } from '@pie-qti/item-player';\n\n// ============================================================================\n// SESSION MANAGEMENT\n// ============================================================================\n\n/**\n * Unique identifier for an assessment session\n * Format: \"{assessmentId}:{candidateId}:{timestamp}\" or similar\n */\nexport type SessionId = string;\n\n/**\n * Initialize a new assessment session\n *\n * Security: Server validates candidate identity and assessment access\n */\nexport interface InitSessionRequest {\n\t/** Assessment identifier (QTI assessmentTest identifier) */\n\tassessmentId: string;\n\t/** Candidate identifier (from authentication system) */\n\tcandidateId: string;\n\t/** Optional: Resume from existing session */\n\tresumeSessionId?: SessionId;\n}\n\nexport interface InitSessionResponse {\n\t/** Unique session identifier for all subsequent requests */\n\tsessionId: SessionId;\n\t/** Assessment structure without sensitive data, as drawn for this session; a resume returns the same draw. */\n\tassessment: SecureAssessment;\n\t/** Restored state if resuming, undefined if new session */\n\trestoredState?: AssessmentSessionState;\n\t/**\n\t * Item delivery starts at in a new session: the first item whose preconditions hold. A resumed\n\t * session carries it in `restoredState`.\n\t */\n\tcurrentItemIdentifier?: string;\n\t/** Test-level outcome values of a resumed session, once outcome processing has run */\n\toutcomes?: TestOutcomeValues;\n}\n\n/**\n * A test-level outcome value: a scalar for single cardinality, an array for multiple and ordered,\n * an object for record, and `null` for NULL.\n */\nexport type TestOutcomeValue =\n\t| string\n\t| number\n\t| boolean\n\t| null\n\t| Array<string | number | boolean | null>\n\t| Record<string, unknown>;\n\n/** Test-level outcome values keyed by outcome identifier (e.g. \"PASS\", \"GRADE\"). */\nexport type TestOutcomeValues = Record<string, TestOutcomeValue>;\n\n// ============================================================================\n// ASSESSMENT STRUCTURE (CLIENT-SAFE)\n// ============================================================================\n\n/**\n * Assessment structure safe for client consumption\n *\n * Security: NO correct answers, NO scoring rules, NO sensitive rubrics\n */\nexport interface TestFeedbackItem {\n\tidentifier: string;\n\t/** Outcome variable name to evaluate (e.g. \"PASS\", \"GRADE\") */\n\toutcomeIdentifier: string;\n\t/**\n\t * 'show' = show when the outcome matches identifier (equality for a single value, membership\n\t * for multiple and ordered); 'hide' = show when it does not\n\t */\n\tshowHide: 'show' | 'hide';\n\t/**\n\t * 'atEnd' = once the test (or, for test-part feedback, the part) has ended;\n\t * 'during' = whenever outcome processing has run\n\t */\n\taccess: 'atEnd' | 'during';\n\t/** HTML content to display */\n\tcontent: string;\n}\n\nexport interface SecureTimeLimits {\n\tminTime?: number;\n\tmaxTime?: number;\n\tallowLateSubmission?: boolean;\n}\n\nexport interface SecureAssessment {\n\tidentifier: string;\n\ttitle: string;\n\t/** Navigation mode affects UI */\n\tnavigationMode: 'linear' | 'nonlinear';\n\t/** Submission mode affects when responses are finalized */\n\tsubmissionMode: 'individual' | 'simultaneous';\n\t/** Test parts contain sections */\n\ttestParts: SecureTestPart[];\n\t/** Overall time limit in seconds (optional) */\n\ttimeLimits?: SecureTimeLimits;\n\t/** QTI outcomeDeclarations for test-level variables */\n\toutcomeDeclarations?: Array<{\n\t\tidentifier: string;\n\t\tbaseType: string;\n\t\tcardinality: string;\n\t\tdefaultValue?: unknown;\n\t}>;\n\t/** Raw <outcomeProcessing> XML string, if present */\n\toutcomeProcessingXml?: string;\n\t/** Base URL/path for resolving relative hrefs (e.g. assessmentSectionRef) */\n\tbaseUrl?: string;\n\t/** QTI assessmentTest testFeedback blocks */\n\ttestFeedback?: TestFeedbackItem[];\n}\n\nexport interface SecureTestPart {\n\tidentifier: string;\n\t/** Navigation and submission modes are scoped to each QTI testPart. */\n\tnavigationMode?: 'linear' | 'nonlinear';\n\tsubmissionMode?: 'individual' | 'simultaneous';\n\t/** Sections contain items */\n\tsections: SecureSection[];\n\t/** TestPart-level time limit. */\n\ttimeLimits?: SecureTimeLimits;\n\t/** Candidate instructions (safe for display) */\n\trubricBlocks?: AssessmentRubricBlock[];\n\t/** QTI testPart testFeedback blocks */\n\ttestFeedback?: TestFeedbackItem[];\n\t/**\n\t * Item session control (QTI testPart/itemSessionControl). Each attribute cascades through every\n\t * enclosing section to the item ref; the backend enforces maxAttempts.\n\t */\n\titemSessionControl?: SecureItemSessionControl;\n\t/** Serialized direct preCondition expressions, evaluated by the backend on entering the part. */\n\tpreConditions?: string[];\n\t/** Branch rules the backend evaluates after the part's last item, in linear navigation. */\n\tbranchRule?: SecureBranchRule[];\n}\n\nexport interface SecureSection {\n\tidentifier: string;\n\ttitle?: string;\n\trequired?: boolean;\n\tfixed?: boolean;\n\t/** Visible determines if section appears in navigation */\n\tvisible: boolean;\n\t/** Assessment item references, in the order the backend drew for this session. */\n\tassessmentItemRefs: SecureItemRef[];\n\t/** Nested QTI sections, retained instead of being flattened during XML ingestion. */\n\tsections?: SecureSection[];\n\t/**\n\t * Direct delivery components in document order. When present, this is the\n\t * authoritative order for mixed item/section children.\n\t */\n\tchildren?: SecureSectionComponent[];\n\t/** Section-level time limit */\n\ttimeLimits?: SecureTimeLimits;\n\t/** Candidate instructions (safe for display) */\n\trubricBlocks?: AssessmentRubricBlock[];\n\t/**\n\t * QTI selection: how many children to present from this section. Backends draw selection when\n\t * the session starts and return the drawn assessment without it; the client never draws.\n\t */\n\tselection?: {\n\t\t/** Number of items selected for this session */\n\t\tselect: number;\n\t\twithReplacement?: boolean;\n\t};\n\t/** QTI ordering: whether non-fixed children are shuffled. Backends apply it with selection. */\n\tordering?: {\n\t\tshuffle: boolean;\n\t};\n\t/** Serialized direct preCondition expressions, evaluated by the backend. */\n\tpreConditions?: string[];\n\t/** Branch rules the backend evaluates after the section's last item, in linear navigation. */\n\tbranchRule?: SecureBranchRule[];\n\t/**\n\t * QTI keepTogether, default true. An invisible section with keepTogether false has its children\n\t * mixed into the parent's ordering; the backend applies it while drawing.\n\t */\n\tkeepTogether?: boolean;\n\t/**\n\t * Item session control (QTI assessmentSection/itemSessionControl). Attributes set here override\n\t * the enclosing section's and test part's.\n\t */\n\titemSessionControl?: SecureItemSessionControl;\n}\n\n/** QTI itemSessionControl. Absent attributes inherit from the enclosing section or test part. */\nexport interface SecureItemSessionControl {\n\t/** Default 1; 0 means unlimited. Adaptive items are unlimited whatever the value. */\n\tmaxAttempts?: number;\n\tshowFeedback?: boolean;\n\tallowReview?: boolean;\n\tshowSolution?: boolean;\n\tallowComment?: boolean;\n\tallowSkipping?: boolean;\n\tvalidateResponses?: boolean;\n}\n\nexport interface SecureBranchRule {\n\t/** Identifier of the target item, section or test part, or EXIT_TEST, EXIT_TESTPART or EXIT_SECTION. */\n\ttarget: string;\n\t/** Serialised QTI expression XML (the child of <branchRule>). Absent means unconditional. */\n\tconditionXml?: string;\n}\n\nexport type SecureSectionComponent =\n\t| { type: 'item'; item: SecureItemRef }\n\t| { type: 'section'; section: SecureSection };\n\nexport interface SecureItemRef {\n\t/** Unique item identifier */\n\tidentifier: string;\n\t/** Item XML WITHOUT responseProcessing if role is 'candidate' */\n\titemXml: string;\n\t/** QTI role determines what's visible in itemXml */\n\trole: QTIRole;\n\t/** Required=true means item must be attempted */\n\trequired?: boolean;\n\tfixed?: boolean;\n\t/** Item-ref-level time limit. */\n\ttimeLimits?: SecureTimeLimits;\n\t/** Optional resolved QTI 3 delivery context. Additive; itemXml remains the compatibility path. */\n\tdeliveryContext?: ResolvedItemDeliveryContext;\n\t/**\n\t * QTI branchRule: ordered branch rules on this item. The backend evaluates them after scoring, in\n\t * linear navigation, and returns the resolved target as nextItemIdentifier.\n\t */\n\tbranchRule?: SecureBranchRule[];\n\t/** Serialized direct preCondition expressions, evaluated by the backend. */\n\tpreConditions?: string[];\n\t/** QTI item-ref weights, preserved for backend outcome processing. */\n\tweights?: Array<{ identifier: string; value: number }>;\n\t/** QTI item-ref categories, matched by includeCategory/excludeCategory in outcome processing. */\n\tcategories?: string[];\n\t/** Item session control (assessmentItemRef/itemSessionControl), the innermost cascade level. */\n\titemSessionControl?: SecureItemSessionControl;\n\t/** QTI variableMapping: item variables the test reads under another identifier. */\n\tvariableMappings?: Array<{ sourceIdentifier: string; targetIdentifier: string }>;\n\t/**\n\t * QTI templateDefault: serialized expressions, evaluated against test outcomes, that replace a\n\t * template variable's default before template processing.\n\t */\n\ttemplateDefaults?: Array<{ templateIdentifier: string; expressionXml: string }>;\n}\n\nexport interface AssessmentRubricBlock {\n\t/** Optional rubric identifier (QTI rubricBlock@identifier) */\n\tidentifier?: string;\n\t/** Rubric content (HTML) */\n\tcontent: string;\n\t/** View controls when rubric is shown */\n\tview: QTIRole[];\n\t/** Optional rubric use (QTI rubricBlock@use), e.g. \"passage\" */\n\tuse?: string;\n}\n\n// ============================================================================\n// RESPONSE SUBMISSION\n// ============================================================================\n\n/**\n * Submit responses for scoring\n *\n * Security: Client sends responses only, server performs scoring\n */\nexport interface SubmitResponsesRequest {\n\tsessionId: SessionId;\n\t/** Item identifier */\n\titemIdentifier: string;\n\t/** Response data keyed by responseIdentifier */\n\tresponses: Record<string, ResponseValue>;\n\t/** Client timestamp for analytics */\n\tsubmittedAt: number;\n\t/** Time spent on item (ms) for analytics */\n\ttimeSpent?: number;\n\t/** Optional client timing evidence; production backends remain authoritative. */\n\ttiming?: SubmitTimingEvidence;\n\t/**\n\t * Serialized item session used by backends to restore template/context variables while scoring.\n\t * Production backends should treat this as a client save format and validate against server-owned state.\n\t */\n\titemSession?: SerializedItemSessionState;\n\t/** Candidate comment, accepted only when the item's allowComment is on. */\n\tcomment?: string;\n}\n\nexport interface SubmitTimingEvidence {\n\tscope: 'assessment' | 'testPart' | 'section' | 'item';\n\telapsedMs: number;\n\tlimitSeconds?: number;\n\texpired?: boolean;\n\tallowLateSubmission?: boolean;\n}\n\n/**\n * Response value can be string, string[], or complex types\n */\nexport type ResponseValue = string | string[] | Record<string, any>;\n\nexport interface SubmitResponsesResponse {\n\t/** Was submission accepted? */\n\tsuccess: boolean;\n\t/** Scoring result (if submission mode allows immediate scoring) */\n\tresult?: AssessmentScoringResult;\n\t/**\n\t * Backend-authoritative next item (branching/navigation decision).\n\t * If omitted, client may fall back to linear next/previous UI navigation.\n\t */\n\tnextItemIdentifier?: string;\n\t/**\n\t * Backend-authoritative session state snapshot after applying the submission.\n\t * If provided, client should replace its local state with this.\n\t */\n\tupdatedState?: AssessmentSessionState;\n\t/** Test-level outcome values after the outcome processing this submission triggers */\n\toutcomes?: TestOutcomeValues;\n\t/** Error message if success=false */\n\terror?: string;\n}\n\n// ============================================================================\n// SCORING RESULTS\n// ============================================================================\n\n/**\n * Scoring result returned from server\n *\n * Security: Server computes this, client never sees scoring rules\n */\nexport interface AssessmentScoringResult {\n\t/** Item identifier */\n\titemIdentifier: string;\n\t/** Normalized score 0.0-1.0 */\n\tscore: number;\n\t/** Maximum possible score (usually 1.0) */\n\tmaxScore: number;\n\t/** Was item completed? */\n\tcompleted: boolean;\n\t/** QTI outcome variables */\n\toutcomeValues: Record<string, any>;\n\t/** Feedback to display (role-dependent) */\n\tfeedback?: FeedbackItem[];\n\t/** Correct response (only if role allows) */\n\tcorrectResponse?: Record<string, ResponseValue>;\n}\n\nexport interface FeedbackItem {\n\t/** Feedback content (HTML) */\n\tcontent: string;\n\t/** Feedback type */\n\ttype: 'correct' | 'incorrect' | 'hint' | 'solution';\n}\n\n// ============================================================================\n// STATE PERSISTENCE\n// ============================================================================\n\n/**\n * Save assessment state\n *\n * Security: State includes responses but not scores (until finalized)\n */\nexport interface SaveAssessmentStateRequest {\n\tsessionId: SessionId;\n\tstate: AssessmentSessionState;\n}\n\nexport interface SaveAssessmentStateResponse {\n\tsuccess: boolean;\n\t/** Server timestamp of save */\n\tsavedAt: number;\n}\n\nexport interface AssessmentSessionState {\n\t/** Current item identifier */\n\tcurrentItemIdentifier: string;\n\t/** Visited items (for navigation) */\n\tvisitedItems: string[];\n\t/** Submitted responses per item */\n\titemResponses: Record<string, Record<string, ResponseValue>>;\n\t/** Scoring results per item (populated after submission) */\n\titemScores?: Record<string, AssessmentScoringResult>;\n\t/** ItemSession lifecycle hints per item, used to restore attempt/review UI state */\n\titemSessionStates?: Record<string, AssessmentItemSessionState>;\n\t/** Rich QTI item session snapshots, used to restore variables and score saved sessions. */\n\titemSessions?: Record<string, SerializedItemSessionState>;\n\t/** Candidate comments per item, captured where allowComment is on. */\n\titemComments?: Record<string, string>;\n\t/** Time tracking */\n\ttiming: {\n\t\t/** Session start time */\n\t\tstartedAt: number;\n\t\t/** Time spent per item (ms) */\n\t\titemTimes: Record<string, number>;\n\t\t/** Time spent per assessment section (ms). */\n\t\tsectionTimes?: Record<string, number>;\n\t\t/** Time spent per testPart (ms). */\n\t\ttestPartTimes?: Record<string, number>;\n\t\t/** Total elapsed time (ms) */\n\t\ttotalTime: number;\n\t\t/** Active scope identifiers retained for save/resume timing continuity. */\n\t\tcurrentItemIdentifier?: string;\n\t\tcurrentSectionIdentifier?: string;\n\t\tcurrentTestPartIdentifier?: string;\n\t\tisPaused?: boolean;\n\t};\n}\n\nexport interface AssessmentItemSessionState {\n\titemIdentifier: string;\n\tattemptCount: number;\n\tisAnswered: boolean;\n\tisSubmitted: boolean;\n\tlastSubmissionTime?: number;\n}\n\n// ============================================================================\n// FINALIZE ASSESSMENT\n// ============================================================================\n\n/**\n * Finalize assessment and get full results\n *\n * Security: Server computes final scores, applies late penalties, etc.\n */\nexport interface FinalizeAssessmentRequest {\n\tsessionId: SessionId;\n}\n\nexport interface FinalizeAssessmentResponse {\n\tsuccess: boolean;\n\t/** Overall assessment score */\n\ttotalScore: number;\n\t/** Maximum possible score */\n\tmaxScore: number;\n\t/** Per-item results */\n\titemScores: Record<string, AssessmentScoringResult>;\n\t/** Assessment-level feedback (legacy: single string; prefer outcomes + assessment.testFeedback) */\n\tfeedback?: string;\n\t/** Test-level outcome values after outcomeProcessing; testFeedback visibility reads them. */\n\toutcomes?: TestOutcomeValues;\n\t/** Server timestamp */\n\tfinalizedAt: number;\n}\n\n// ============================================================================\n// ITEM BANK QUERIES\n// ============================================================================\n\n/**\n * Request items from an item bank for random selection\n *\n * Security: Server validates candidate access to bank\n */\nexport interface QueryItemBankRequest {\n\t/** Unique session identifier */\n\tsessionId: SessionId;\n\t/** Item bank identifier (from selection/@fromBank attribute) */\n\tbankId: string;\n\t/** Number of items to select */\n\tcount: number;\n\t/** Whether to allow selecting same item multiple times */\n\twithReplacement?: boolean;\n\t/** Optional filtering criteria (difficulty, topic, etc.) */\n\tfilters?: {\n\t\tdifficulty?: 'easy' | 'medium' | 'hard';\n\t\ttopics?: string[];\n\t\t[key: string]: unknown;\n\t};\n}\n\n/**\n * Items selected from item bank\n *\n * Security: Returns items WITHOUT correct answers or scoring rules\n */\nexport interface QueryItemBankResponse {\n\t/** Selected item references (client-safe) */\n\titems: SecureItemRef[];\n\t/** Server timestamp */\n\tselectedAt: number;\n}\n\n// ============================================================================\n// BACKEND ADAPTER INTERFACE\n// ============================================================================\n\n/**\n * Backend adapter interface - implement this for your backend\n *\n * @example\n * ```typescript\n * class MyBackendAdapter implements BackendAdapter {\n * async initSession(req: InitSessionRequest): Promise<InitSessionResponse> {\n * const response = await fetch('/api/qti/init', {\n * method: 'POST',\n * body: JSON.stringify(req)\n * });\n * return response.json();\n * }\n * // ... implement other methods\n * }\n * ```\n */\nexport interface BackendAdapter {\n\t/**\n\t * Initialize new assessment session\n\t */\n\tinitSession(request: InitSessionRequest): Promise<InitSessionResponse>;\n\n\t/**\n\t * Submit item responses for scoring\n\t */\n\tsubmitResponses(request: SubmitResponsesRequest): Promise<SubmitResponsesResponse>;\n\n\t/**\n\t * Save session state (auto-save during assessment)\n\t */\n\tsaveState(request: SaveAssessmentStateRequest): Promise<SaveAssessmentStateResponse>;\n\n\t/**\n\t * Finalize assessment and get results\n\t */\n\tfinalizeAssessment(request: FinalizeAssessmentRequest): Promise<FinalizeAssessmentResponse>;\n\n\t/**\n\t * Resume session (optional - can reuse initSession)\n\t */\n\tresumeSession?(sessionId: SessionId): Promise<InitSessionResponse>;\n\n\t/**\n\t * Query item bank for random item selection\n\t *\n\t * Security: Server validates access and returns items WITHOUT sensitive data\n\t */\n\tqueryItemBank?(request: QueryItemBankRequest): Promise<QueryItemBankResponse>;\n}\n"]}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { type SerializedItemSessionState } from '@pie-qti/item-player';
|
|
2
|
+
import { type TestItemState } from '@pie-qti/qti-processing';
|
|
2
3
|
import type { AssessmentScoringResult, ResponseValue } from './api-contract.js';
|
|
3
4
|
export interface AssessmentItemScoringInput {
|
|
4
5
|
itemXml: string;
|
|
@@ -6,8 +7,17 @@ export interface AssessmentItemScoringInput {
|
|
|
6
7
|
itemSession?: SerializedItemSessionState;
|
|
7
8
|
}
|
|
8
9
|
export declare function getAssessmentItemIdentifier(itemXml: string): string;
|
|
10
|
+
/** The item-derived part of a test-level TestItemState; the backend adds the item-ref context. */
|
|
11
|
+
export type ItemTestState = Pick<TestItemState, 'variables' | 'outcomeBounds' | 'responded' | 'correct'>;
|
|
9
12
|
/**
|
|
10
13
|
* Runs QTI ResponseProcessing for one AssessmentItem and normalizes the result
|
|
11
14
|
* to the BackendAdapter scoring shape used by AssessmentPlayer.
|
|
12
15
|
*/
|
|
13
|
-
export declare function scoreAssessmentItem(
|
|
16
|
+
export declare function scoreAssessmentItem(input: AssessmentItemScoringInput): AssessmentScoringResult;
|
|
17
|
+
/** Scores one item and snapshots the variables and flags test-level outcome processing reads. */
|
|
18
|
+
export declare function scoreAssessmentItemForTest({ itemXml, responses, itemSession, }: AssessmentItemScoringInput): {
|
|
19
|
+
result: AssessmentScoringResult;
|
|
20
|
+
testState?: ItemTestState;
|
|
21
|
+
};
|
|
22
|
+
/** Variables of an item nobody has attempted: declared defaults, with no response processing run. */
|
|
23
|
+
export declare function defaultItemTestState(itemXml: string): ItemTestState | undefined;
|
|
@@ -1,13 +1,18 @@
|
|
|
1
1
|
import { createAssessmentItemDefinition, } from '@pie-qti/item-player';
|
|
2
|
+
import { parseXml, qtiNull, qtiValue } from '@pie-qti/qti-processing';
|
|
2
3
|
export function getAssessmentItemIdentifier(itemXml) {
|
|
3
|
-
const identifierMatch = itemXml.match(
|
|
4
|
+
const identifierMatch = itemXml.match(/<(?:assessmentItem|qti-assessment-item)\b[^>]*\sidentifier=["']([^"']+)["']/);
|
|
4
5
|
return identifierMatch?.[1] || 'unknown';
|
|
5
6
|
}
|
|
6
7
|
/**
|
|
7
8
|
* Runs QTI ResponseProcessing for one AssessmentItem and normalizes the result
|
|
8
9
|
* to the BackendAdapter scoring shape used by AssessmentPlayer.
|
|
9
10
|
*/
|
|
10
|
-
export function scoreAssessmentItem(
|
|
11
|
+
export function scoreAssessmentItem(input) {
|
|
12
|
+
return scoreAssessmentItemForTest(input).result;
|
|
13
|
+
}
|
|
14
|
+
/** Scores one item and snapshots the variables and flags test-level outcome processing reads. */
|
|
15
|
+
export function scoreAssessmentItemForTest({ itemXml, responses, itemSession, }) {
|
|
11
16
|
const itemIdentifier = getAssessmentItemIdentifier(itemXml);
|
|
12
17
|
try {
|
|
13
18
|
// Use a scorer-grade view of the item for accurate scoring.
|
|
@@ -19,33 +24,118 @@ export function scoreAssessmentItem({ itemXml, responses, itemSession, }) {
|
|
|
19
24
|
});
|
|
20
25
|
const session = definition.openSession(itemSession ? { restore: itemSession } : { responses });
|
|
21
26
|
let result;
|
|
27
|
+
let testState;
|
|
22
28
|
try {
|
|
23
29
|
result = session.dispatch(itemSession
|
|
24
30
|
? { action: 'scoreAttempt' }
|
|
25
31
|
: { action: 'endAttempt', countAttempt: false, validateResponses: false }).result?.scoring;
|
|
26
32
|
if (!result)
|
|
27
33
|
throw new Error('QTI scoring produced no result');
|
|
34
|
+
testState = snapshotTestState(itemXml, session, result.correct);
|
|
28
35
|
}
|
|
29
36
|
finally {
|
|
30
37
|
session.dispose();
|
|
31
38
|
}
|
|
32
39
|
return {
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
40
|
+
result: {
|
|
41
|
+
itemIdentifier,
|
|
42
|
+
score: result.score,
|
|
43
|
+
maxScore: result.maxScore,
|
|
44
|
+
completed: result.completed,
|
|
45
|
+
outcomeValues: result.outcomeValues,
|
|
46
|
+
},
|
|
47
|
+
testState,
|
|
38
48
|
};
|
|
39
49
|
}
|
|
40
50
|
catch (error) {
|
|
41
51
|
console.error('Scoring error:', error);
|
|
42
52
|
return {
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
53
|
+
result: {
|
|
54
|
+
itemIdentifier,
|
|
55
|
+
score: 0,
|
|
56
|
+
maxScore: 1,
|
|
57
|
+
completed: false,
|
|
58
|
+
outcomeValues: {},
|
|
59
|
+
},
|
|
48
60
|
};
|
|
49
61
|
}
|
|
50
62
|
}
|
|
63
|
+
const defaultTestStates = new Map();
|
|
64
|
+
/** Variables of an item nobody has attempted: declared defaults, with no response processing run. */
|
|
65
|
+
export function defaultItemTestState(itemXml) {
|
|
66
|
+
if (!defaultTestStates.has(itemXml)) {
|
|
67
|
+
let state;
|
|
68
|
+
try {
|
|
69
|
+
const session = createAssessmentItemDefinition({ itemXml, role: 'scorer' }).openSession({ responses: {} });
|
|
70
|
+
try {
|
|
71
|
+
state = { ...snapshotTestState(itemXml, session, undefined), responded: false };
|
|
72
|
+
}
|
|
73
|
+
finally {
|
|
74
|
+
session.dispose();
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
catch {
|
|
78
|
+
state = undefined;
|
|
79
|
+
}
|
|
80
|
+
defaultTestStates.set(itemXml, state);
|
|
81
|
+
}
|
|
82
|
+
return defaultTestStates.get(itemXml);
|
|
83
|
+
}
|
|
84
|
+
function snapshotTestState(itemXml, session, correct) {
|
|
85
|
+
const serialized = session.serialize();
|
|
86
|
+
const responses = Object.values(serialized.responseVariables);
|
|
87
|
+
const variables = {};
|
|
88
|
+
for (const group of [
|
|
89
|
+
serialized.contextVariables,
|
|
90
|
+
serialized.templateVariables,
|
|
91
|
+
serialized.outcomeVariables,
|
|
92
|
+
serialized.responseVariables,
|
|
93
|
+
]) {
|
|
94
|
+
for (const variable of Object.values(group))
|
|
95
|
+
variables[variable.identifier] = toQtiValue(variable);
|
|
96
|
+
}
|
|
97
|
+
return {
|
|
98
|
+
variables,
|
|
99
|
+
outcomeBounds: readOutcomeBounds(itemXml),
|
|
100
|
+
responded: responses.some((r) => JSON.stringify(r.value ?? null) !== JSON.stringify(r.defaultValue ?? null)),
|
|
101
|
+
correct,
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
function toQtiValue({ baseType, cardinality, value }) {
|
|
105
|
+
if (value === null || value === undefined)
|
|
106
|
+
return qtiNull(baseType, cardinality);
|
|
107
|
+
if (cardinality !== 'record')
|
|
108
|
+
return qtiValue(baseType, cardinality, value);
|
|
109
|
+
const fields = {};
|
|
110
|
+
for (const [id, field] of Object.entries(value))
|
|
111
|
+
fields[id] = toQtiValue(field);
|
|
112
|
+
return qtiValue(undefined, 'record', fields);
|
|
113
|
+
}
|
|
114
|
+
/** Declared normalMinimum/normalMaximum per outcome, in either QTI 2 or QTI 3 spelling. */
|
|
115
|
+
function readOutcomeBounds(itemXml) {
|
|
116
|
+
const bounds = {};
|
|
117
|
+
const visit = (el) => {
|
|
118
|
+
const name = el.localName ?? el.nodeName;
|
|
119
|
+
if (name === 'outcomeDeclaration' || name === 'qti-outcome-declaration') {
|
|
120
|
+
const identifier = el.getAttribute('identifier');
|
|
121
|
+
const min = Number.parseFloat(el.getAttribute('normalMinimum') || el.getAttribute('normal-minimum') || '');
|
|
122
|
+
const max = Number.parseFloat(el.getAttribute('normalMaximum') || el.getAttribute('normal-maximum') || '');
|
|
123
|
+
if (identifier && (Number.isFinite(min) || Number.isFinite(max))) {
|
|
124
|
+
bounds[identifier] = {
|
|
125
|
+
...(Number.isFinite(min) ? { normalMinimum: min } : {}),
|
|
126
|
+
...(Number.isFinite(max) ? { normalMaximum: max } : {}),
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
for (let child = el.firstChild; child; child = child.nextSibling) {
|
|
132
|
+
if (child.nodeType === 1)
|
|
133
|
+
visit(child);
|
|
134
|
+
}
|
|
135
|
+
};
|
|
136
|
+
const root = parseXml(itemXml).documentElement;
|
|
137
|
+
if (root)
|
|
138
|
+
visit(root);
|
|
139
|
+
return Object.keys(bounds).length > 0 ? bounds : undefined;
|
|
140
|
+
}
|
|
51
141
|
//# sourceMappingURL=assessment-item-scorer.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"assessment-item-scorer.js","sourceRoot":"","sources":["../../src/integration/assessment-item-scorer.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,8BAA8B,GAE9B,MAAM,sBAAsB,CAAC;AAS9B,MAAM,UAAU,2BAA2B,CAAC,OAAe;IAC1D,MAAM,eAAe,GAAG,OAAO,CAAC,KAAK,CAAC,gDAAgD,CAAC,CAAC;IACxF,OAAO,eAAe,EAAE,CAAC,CAAC,CAAC,IAAI,SAAS,CAAC;AAC1C,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,mBAAmB,CAAC,EACnC,OAAO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H,CAAC;AACF,CAAC","sourcesContent":["import {\n\tcreateAssessmentItemDefinition,\n\ttype SerializedItemSessionState,\n} from '@pie-qti/item-player';\nimport type { AssessmentScoringResult, ResponseValue } from './api-contract.js';\n\nexport interface AssessmentItemScoringInput {\n\titemXml: string;\n\tresponses: Record<string, ResponseValue>;\n\titemSession?: SerializedItemSessionState;\n}\n\nexport function getAssessmentItemIdentifier(itemXml: string): string {\n\tconst identifierMatch = itemXml.match(/assessmentItem[^>]+identifier=[\"']([^\"']+)[\"']/);\n\treturn identifierMatch?.[1] || 'unknown';\n}\n\n/**\n * Runs QTI ResponseProcessing for one AssessmentItem and normalizes the result\n * to the BackendAdapter scoring shape used by AssessmentPlayer.\n */\nexport function scoreAssessmentItem({\n\titemXml,\n\tresponses,\n\titemSession,\n}: AssessmentItemScoringInput): AssessmentScoringResult {\n\tconst itemIdentifier = getAssessmentItemIdentifier(itemXml);\n\n\ttry {\n\t\t// Use a scorer-grade view of the item for accurate scoring.\n\t\t// NOTE: This reference scorer is intentionally insecure and runs client-side.\n\t\t// In production, scoring must happen server-side with secured item content.\n\t\tconst definition = createAssessmentItemDefinition({\n\t\t\titemXml,\n\t\t\trole: 'scorer',\n\t\t});\n\t\tconst session = definition.openSession(\n\t\t\titemSession ? { restore: itemSession } : { responses },\n\t\t);\n\t\tlet result;\n\t\ttry {\n\t\t\tresult = session.dispatch(\n\t\t\t\titemSession\n\t\t\t\t\t? { action: 'scoreAttempt' }\n\t\t\t\t\t: { action: 'endAttempt', countAttempt: false, validateResponses: false },\n\t\t\t).result?.scoring;\n\t\t\tif (!result) throw new Error('QTI scoring produced no result');\n\t\t} finally {\n\t\t\tsession.dispose();\n\t\t}\n\n\t\treturn {\n\t\t\titemIdentifier,\n\t\t\tscore: result.score,\n\t\t\tmaxScore: result.maxScore,\n\t\t\tcompleted: result.completed,\n\t\t\toutcomeValues: result.outcomeValues,\n\t\t};\n\t} catch (error) {\n\t\tconsole.error('Scoring error:', error);\n\t\treturn {\n\t\t\titemIdentifier,\n\t\t\tscore: 0,\n\t\t\tmaxScore: 1,\n\t\t\tcompleted: false,\n\t\t\toutcomeValues: {},\n\t\t};\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"assessment-item-scorer.js","sourceRoot":"","sources":["../../src/integration/assessment-item-scorer.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,8BAA8B,GAI9B,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,QAAQ,EAAiB,OAAO,EAAE,QAAQ,EAAsB,MAAM,yBAAyB,CAAC;AASzG,MAAM,UAAU,2BAA2B,CAAC,OAAe;IAC1D,MAAM,eAAe,GAAG,OAAO,CAAC,KAAK,CAAC,6EAA6E,CAAC,CAAC;IACrH,OAAO,eAAe,EAAE,CAAC,CAAC,CAAC,IAAI,SAAS,CAAC;AAC1C,CAAC;AAKD;;;GAGG;AACH,MAAM,UAAU,mBAAmB,CAAC,KAAiC;IACpE,OAAO,0BAA0B,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC;AACjD,CAAC;AAED,iGAAiG;AACjG,MAAM,UAAU,0BAA0B,CAAC,EAC1C,OAAO,EACP,SAAS,EACT,WAAW,GACiB;IAC5B,MAAM,cAAc,GAAG,2BAA2B,CAAC,OAAO,CAAC,CAAC;IAE5D,IAAI,CAAC;QACJ,4DAA4D;QAC5D,8EAA8E;QAC9E,4EAA4E;QAC5E,MAAM,UAAU,GAAG,8BAA8B,CAAC;YACjD,OAAO;YACP,IAAI,EAAE,QAAQ;SACd,CAAC,CAAC;QACH,MAAM,OAAO,GAAG,UAAU,CAAC,WAAW,CACrC,WAAW,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,WAAW,EAAE,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,CACtD,CAAC;QACF,IAAI,MAAM,CAAC;QACX,IAAI,SAAwB,CAAC;QAC7B,IAAI,CAAC;YACJ,MAAM,GAAG,OAAO,CAAC,QAAQ,CACxB,WAAW;gBACV,CAAC,CAAC,EAA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CAAC,YAAY,CAAC,gBAAgB,CAAC,IAAI,EAAE,CAAC,CAAC;YAC3G,IAAI,UAAU,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC,IAAI,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC;gBAClE,MAAM,CAAC,UAAU,CAAC,GAAG;oBACpB,GAAG,CAAC,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,aAAa,EAAE,GAAG,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;oBACvD,GAAG,CAAC,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,aAAa,EAAE,GAAG,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;iBACvD,CAAC;YACH,CAAC;YACD,OAAO;QACR,CAAC;QACD,KAAK,IAAI,KAAK,GAAG,EAAE,CAAC,UAAU,EAAE,KAAK,EAAE,KAAK,GAAG,KAAK,CAAC,WAAW,EAAE,CAAC;YAClE,IAAI,KAAK,CAAC,QAAQ,KAAK,CAAC;gBAAE,KAAK,CAAC,KAAgB,CAAC,CAAC;QACnD,CAAC;IACF,CAAC,CAAC;IACF,MAAM,IAAI,GAAG,QAAQ,CAAC,OAAO,CAAC,CAAC,eAAe,CAAC;IAC/C,IAAI,IAAI;QAAE,KAAK,CAAC,IAAI,CAAC,CAAC;IACtB,OAAO,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC;AAC5D,CAAC","sourcesContent":["import {\n\tcreateAssessmentItemDefinition,\n\ttype ItemSession,\n\ttype SerializedItemSessionState,\n\ttype SerializedItemSessionVariable,\n} from '@pie-qti/item-player';\nimport { parseXml, type QtiValue, qtiNull, qtiValue, type TestItemState } from '@pie-qti/qti-processing';\nimport type { AssessmentScoringResult, ResponseValue } from './api-contract.js';\n\nexport interface AssessmentItemScoringInput {\n\titemXml: string;\n\tresponses: Record<string, ResponseValue>;\n\titemSession?: SerializedItemSessionState;\n}\n\nexport function getAssessmentItemIdentifier(itemXml: string): string {\n\tconst identifierMatch = itemXml.match(/<(?:assessmentItem|qti-assessment-item)\\b[^>]*\\sidentifier=[\"']([^\"']+)[\"']/);\n\treturn identifierMatch?.[1] || 'unknown';\n}\n\n/** The item-derived part of a test-level TestItemState; the backend adds the item-ref context. */\nexport type ItemTestState = Pick<TestItemState, 'variables' | 'outcomeBounds' | 'responded' | 'correct'>;\n\n/**\n * Runs QTI ResponseProcessing for one AssessmentItem and normalizes the result\n * to the BackendAdapter scoring shape used by AssessmentPlayer.\n */\nexport function scoreAssessmentItem(input: AssessmentItemScoringInput): AssessmentScoringResult {\n\treturn scoreAssessmentItemForTest(input).result;\n}\n\n/** Scores one item and snapshots the variables and flags test-level outcome processing reads. */\nexport function scoreAssessmentItemForTest({\n\titemXml,\n\tresponses,\n\titemSession,\n}: AssessmentItemScoringInput): { result: AssessmentScoringResult; testState?: ItemTestState } {\n\tconst itemIdentifier = getAssessmentItemIdentifier(itemXml);\n\n\ttry {\n\t\t// Use a scorer-grade view of the item for accurate scoring.\n\t\t// NOTE: This reference scorer is intentionally insecure and runs client-side.\n\t\t// In production, scoring must happen server-side with secured item content.\n\t\tconst definition = createAssessmentItemDefinition({\n\t\t\titemXml,\n\t\t\trole: 'scorer',\n\t\t});\n\t\tconst session = definition.openSession(\n\t\t\titemSession ? { restore: itemSession } : { responses },\n\t\t);\n\t\tlet result;\n\t\tlet testState: ItemTestState;\n\t\ttry {\n\t\t\tresult = session.dispatch(\n\t\t\t\titemSession\n\t\t\t\t\t? { action: 'scoreAttempt' }\n\t\t\t\t\t: { action: 'endAttempt', countAttempt: false, validateResponses: false },\n\t\t\t).result?.scoring;\n\t\t\tif (!result) throw new Error('QTI scoring produced no result');\n\t\t\ttestState = snapshotTestState(itemXml, session, result.correct);\n\t\t} finally {\n\t\t\tsession.dispose();\n\t\t}\n\n\t\treturn {\n\t\t\tresult: {\n\t\t\t\titemIdentifier,\n\t\t\t\tscore: result.score,\n\t\t\t\tmaxScore: result.maxScore,\n\t\t\t\tcompleted: result.completed,\n\t\t\t\toutcomeValues: result.outcomeValues,\n\t\t\t},\n\t\t\ttestState,\n\t\t};\n\t} catch (error) {\n\t\tconsole.error('Scoring error:', error);\n\t\treturn {\n\t\t\tresult: {\n\t\t\t\titemIdentifier,\n\t\t\t\tscore: 0,\n\t\t\t\tmaxScore: 1,\n\t\t\t\tcompleted: false,\n\t\t\t\toutcomeValues: {},\n\t\t\t},\n\t\t};\n\t}\n}\n\nconst defaultTestStates = new Map<string, ItemTestState | undefined>();\n\n/** Variables of an item nobody has attempted: declared defaults, with no response processing run. */\nexport function defaultItemTestState(itemXml: string): ItemTestState | undefined {\n\tif (!defaultTestStates.has(itemXml)) {\n\t\tlet state: ItemTestState | undefined;\n\t\ttry {\n\t\t\tconst session = createAssessmentItemDefinition({ itemXml, role: 'scorer' }).openSession({ responses: {} });\n\t\t\ttry {\n\t\t\t\tstate = { ...snapshotTestState(itemXml, session, undefined), responded: false };\n\t\t\t} finally {\n\t\t\t\tsession.dispose();\n\t\t\t}\n\t\t} catch {\n\t\t\tstate = undefined;\n\t\t}\n\t\tdefaultTestStates.set(itemXml, state);\n\t}\n\treturn defaultTestStates.get(itemXml);\n}\n\nfunction snapshotTestState(itemXml: string, session: ItemSession, correct: boolean | undefined): ItemTestState {\n\tconst serialized = session.serialize();\n\tconst responses = Object.values(serialized.responseVariables);\n\tconst variables: Record<string, QtiValue> = {};\n\tfor (const group of [\n\t\tserialized.contextVariables,\n\t\tserialized.templateVariables,\n\t\tserialized.outcomeVariables,\n\t\tserialized.responseVariables,\n\t]) {\n\t\tfor (const variable of Object.values(group)) variables[variable.identifier] = toQtiValue(variable);\n\t}\n\treturn {\n\t\tvariables,\n\t\toutcomeBounds: readOutcomeBounds(itemXml),\n\t\tresponded: responses.some((r) => JSON.stringify(r.value ?? null) !== JSON.stringify(r.defaultValue ?? null)),\n\t\tcorrect,\n\t};\n}\n\nfunction toQtiValue({ baseType, cardinality, value }: Pick<SerializedItemSessionVariable, 'baseType' | 'cardinality' | 'value'>): QtiValue {\n\tif (value === null || value === undefined) return qtiNull(baseType as any, cardinality as any);\n\tif (cardinality !== 'record') return qtiValue(baseType as any, cardinality as any, value);\n\tconst fields: Record<string, QtiValue> = {};\n\tfor (const [id, field] of Object.entries(value as Record<string, any>)) fields[id] = toQtiValue(field);\n\treturn qtiValue(undefined, 'record', fields);\n}\n\n/** Declared normalMinimum/normalMaximum per outcome, in either QTI 2 or QTI 3 spelling. */\nfunction readOutcomeBounds(itemXml: string): ItemTestState['outcomeBounds'] {\n\tconst bounds: NonNullable<ItemTestState['outcomeBounds']> = {};\n\tconst visit = (el: Element): void => {\n\t\tconst name = el.localName ?? el.nodeName;\n\t\tif (name === 'outcomeDeclaration' || name === 'qti-outcome-declaration') {\n\t\t\tconst identifier = el.getAttribute('identifier');\n\t\t\tconst min = Number.parseFloat(el.getAttribute('normalMinimum') || el.getAttribute('normal-minimum') || '');\n\t\t\tconst max = Number.parseFloat(el.getAttribute('normalMaximum') || el.getAttribute('normal-maximum') || '');\n\t\t\tif (identifier && (Number.isFinite(min) || Number.isFinite(max))) {\n\t\t\t\tbounds[identifier] = {\n\t\t\t\t\t...(Number.isFinite(min) ? { normalMinimum: min } : {}),\n\t\t\t\t\t...(Number.isFinite(max) ? { normalMaximum: max } : {}),\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tfor (let child = el.firstChild; child; child = child.nextSibling) {\n\t\t\tif (child.nodeType === 1) visit(child as Element);\n\t\t}\n\t};\n\tconst root = parseXml(itemXml).documentElement;\n\tif (root) visit(root);\n\treturn Object.keys(bounds).length > 0 ? bounds : undefined;\n}\n"]}
|
|
@@ -41,7 +41,7 @@
|
|
|
41
41
|
*
|
|
42
42
|
* See BACKEND-INTEGRATION.md for complete implementation guide.
|
|
43
43
|
*/
|
|
44
|
-
export type { BackendAdapter, FeedbackItem, AssessmentSessionState, AssessmentScoringResult, AssessmentRubricBlock, FinalizeAssessmentRequest, FinalizeAssessmentResponse, InitSessionRequest, InitSessionResponse, ResponseValue, SaveAssessmentStateRequest, SaveAssessmentStateResponse, SecureAssessment, SecureItemRef, SecureSection, SecureTestPart, SecureTimeLimits, SessionId, SubmitTimingEvidence, SubmitResponsesRequest, SubmitResponsesResponse, } from './api-contract.js';
|
|
44
|
+
export type { BackendAdapter, FeedbackItem, AssessmentSessionState, AssessmentScoringResult, AssessmentRubricBlock, FinalizeAssessmentRequest, FinalizeAssessmentResponse, InitSessionRequest, InitSessionResponse, ResponseValue, SaveAssessmentStateRequest, SaveAssessmentStateResponse, SecureAssessment, SecureItemRef, SecureSection, SecureTestPart, SecureTimeLimits, SessionId, SubmitTimingEvidence, SubmitResponsesRequest, SubmitResponsesResponse, TestFeedbackItem, TestOutcomeValue, TestOutcomeValues, } from './api-contract.js';
|
|
45
45
|
export { ReferenceBackendAdapter } from './ReferenceBackendAdapter.js';
|
|
46
46
|
export { getAssessmentItemIdentifier, scoreAssessmentItem, type AssessmentItemScoringInput, } from './assessment-item-scorer.js';
|
|
47
47
|
export { toSectionComposition } from './toSectionComposition.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/integration/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0CG;
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/integration/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0CG;AA8BH,0DAA0D;AAC1D,OAAO,EAAE,uBAAuB,EAAE,MAAM,8BAA8B,CAAC;AACvE,OAAO,EACN,2BAA2B,EAC3B,mBAAmB,GAEnB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,oBAAoB,EAAE,MAAM,2BAA2B,CAAC","sourcesContent":["/**\n * QTI 2.2 Assessment Player - Backend Integration\n *\n * ## Reference/demo behavior\n *\n * AssessmentPlayer always requires an explicit BackendAdapter. Demos can opt in\n * to ReferenceBackendAdapter, which stores and scores client-side.\n *\n * @example\n * ```typescript\n * import { AssessmentPlayer } from '@pie-qti/assessment-player';\n * import { ReferenceBackendAdapter } from '@pie-qti/assessment-player/integration';\n *\n * const backend = new ReferenceBackendAdapter();\n * backend.registerAssessment('preview', secureAssessment);\n * const player = await AssessmentPlayer.create({\n * backend,\n * initSession: { assessmentId: 'preview', candidateId: 'local' }\n * });\n * ```\n *\n * ## Production: Backend Integration\n *\n * For production deployments, implement BackendAdapter for:\n * - Server-side scoring (secure)\n * - Persistent session storage\n * - Authentication/authorization\n * - Sensitive data protection\n *\n * @example\n * ```typescript\n * import { AssessmentPlayer } from '@pie-qti/assessment-player';\n * import { MyBackendAdapter } from './adapters/MyBackendAdapter';\n *\n * // Production mode with backend\n * const player = await AssessmentPlayer.create({\n * backend: new MyBackendAdapter('https://api.example.com', authToken),\n * initSession: { assessmentId: 'test-001', candidateId: 'student-123' }\n * });\n * ```\n *\n * See BACKEND-INTEGRATION.md for complete implementation guide.\n */\n\n// Export API contract (TypeScript interfaces)\nexport type {\n\tBackendAdapter,\n\tFeedbackItem,\n\tAssessmentSessionState,\n\tAssessmentScoringResult,\n\tAssessmentRubricBlock,\n\tFinalizeAssessmentRequest,\n\tFinalizeAssessmentResponse,\n\tInitSessionRequest,\n\tInitSessionResponse,\n\tResponseValue,\n\tSaveAssessmentStateRequest,\n\tSaveAssessmentStateResponse,\n\tSecureAssessment,\n\tSecureItemRef,\n\tSecureSection,\n\tSecureTestPart,\n\tSecureTimeLimits,\n\tSessionId,\n\tSubmitTimingEvidence,\n\tSubmitResponsesRequest,\n\tSubmitResponsesResponse,\n\tTestFeedbackItem,\n\tTestOutcomeValue,\n\tTestOutcomeValues,\n} from './api-contract.js';\n\n// Export reference implementation (for development/demos)\nexport { ReferenceBackendAdapter } from './ReferenceBackendAdapter.js';\nexport {\n\tgetAssessmentItemIdentifier,\n\tscoreAssessmentItem,\n\ttype AssessmentItemScoringInput,\n} from './assessment-item-scorer.js';\nexport { toSectionComposition } from './toSectionComposition.js';\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"toSectionComposition.js","sourceRoot":"","sources":["../../src/integration/toSectionComposition.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,yBAAyB,EAAE,MAAM,6BAA6B,CAAC;AACxE,OAAO,EACN,4BAA4B,GAK5B,MAAM,yBAAyB,CAAC;AAGjC,SAAS,aAAa,CAAC,IAA2C;IACjE,QAAQ,IAAI,EAAE,CAAC;QACd,KAAK,QAAQ,CAAC;QACd,KAAK,WAAW,CAAC;QACjB,KAAK,SAAS,CAAC;QACf,KAAK,QAAQ,CAAC;QACd,KAAK,iBAAiB,CAAC;QACvB,KAAK,OAAO;YACX,OAAO,IAAI,CAAC;QACb;YACC,OAAO,WAAW,CAAC;IACrB,CAAC;AACF,CAAC;AAED,SAAS,WAAW,CAAC,KAAyC,EAAE,KAAoC;IACnG,IAAI,CAAC,KAAK,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,SAAS,CAAC;IACnD,OAAO,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,EAAE,GAAG,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC;AAClD,CAAC;AAED,MAAM,UAAU,oBAAoB,CACnC,MAAwB,EACxB,SAAiD,EAAE;IAEnD,MAAM,QAAQ,GAAG,MAAM,CAAC,kBAAkB,EAAE,CAAC;IAC7C,MAAM,WAAW,GAAG,MAAM,CAAC,cAAc,EAAE,CAAC;IAC5C,MAAM,IAAI,GAAG,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;IACxC,MAAM,aAAa,GAAG,yBAAyB,CAAC;QAC/C,YA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YAAY;YACtB,aAAa;SACb;QACD,oBAAoB,EAAE,WAAW,EAAE,UAAU;QAC7C,WAAW,EAAE,QAAQ,CAAC,WAAW;QACjC,OAAO,EAAE,QAAQ,CAAC,OAAO;QACzB,QAAQ,EAAE,MAAM,CAAC,QAAQ;QACzB,IAAI,EAAE,MAAM,CAAC,WAAW;QACxB,GAAG,EAAE,MAAM,CAAC,GAAG;KACf,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { normalizeQtiSharedContext } from '@pie-qti/assessment-toolkit';\nimport {\n\tresolveQtiSectionComposition,\n\ttype QtiSectionItemRef,\n\ttype QtiSectionRole,\n\ttype QtiSectionToolConfig,\n\ttype ResolvedQtiSectionComposition,\n} from '@pie-qti/section-player';\nimport type { AssessmentPlayer, BackendAssessmentPlayerConfig } from '../core/AssessmentPlayer.js';\n\nfunction toSectionRole(role: BackendAssessmentPlayerConfig['role']): QtiSectionRole {\n\tswitch (role) {\n\t\tcase 'author':\n\t\tcase 'candidate':\n\t\tcase 'proctor':\n\t\tcase 'scorer':\n\t\tcase 'testConstructor':\n\t\tcase 'tutor':\n\t\t\treturn role;\n\t\tdefault:\n\t\t\treturn 'candidate';\n\t}\n}\n\nfunction scopedTools(tools: QtiSectionToolConfig[] | undefined, scope: QtiSectionToolConfig['scope']): QtiSectionToolConfig[] | undefined {\n\tif (!tools || tools.length === 0) return undefined;\n\treturn tools.map((tool) => ({ ...tool, scope }));\n}\n\nexport function toSectionComposition(\n\tplayer: AssessmentPlayer,\n\tconfig: Partial<BackendAssessmentPlayerConfig> = {}\n): ResolvedQtiSectionComposition {\n\tconst navState = player.getNavigationState();\n\tconst currentItem = player.getCurrentItem();\n\tconst role = toSectionRole(config.role);\n\tconst sharedContext = normalizeQtiSharedContext({\n\t\trubricBlocks: player.getCurrentSharedRubricBlocks(),\n\t\trole,\n\t\tpassageTools: scopedTools(config.passageTools, 'passage'),\n\t});\n\tconst activeSession = player.getCurrentItemSession();\n\tconst sectionItems: QtiSectionItemRef[] = player.getCurrentSectionItemRefs().map((item) => {\n\t\tconst common = {\n\t\t\tidentifier: item.identifier,\n\t\t\thref: item.href,\n\t\t\ttitle: item.title,\n\t\t\titemXml: item.itemXml,\n\t\t\tdeliveryContext: item.deliveryContext,\n\t\t\ttools: scopedTools(config.itemTools, 'item'),\n\t\t};\n\t\treturn item.identifier === currentItem?.identifier && activeSession\n\t\t\t? { ...common, session: activeSession }\n\t\t\t: { ...common, responses: player.getResponsesForItem(item.identifier) };\n\t});\n\n\treturn resolveQtiSectionComposition({\n\t\tsection: {\n\t\t\tidentifier: navState.currentSection?.id ?? 'active-section',\n\t\t\ttitle: navState.currentSection?.title ?? currentItem?.title,\n\t\t\trole,\n\t\t\tlayoutPreference: sharedContext.passages.length > 0 ? 'split-pane' : 'vertical',\n\t\t\ttools: scopedTools(config.sectionTools, 'section'),\n\t\t\titemRefs: sectionItems,\n\t\t\tsharedContext,\n\t\t},\n\t\tactiveItemIdentifier: currentItem?.identifier,\n\t\tcanPrevious: navState.canPrevious,\n\t\tcanNext: navState.canNext,\n\t\tsecurity: config.security,\n\t\thost: config.sectionHost,\n\t\tpnp: config.pnp,\n\t});\n}\n"]}
|
package/dist/types/index.d.ts
CHANGED
|
@@ -51,3 +51,13 @@ export interface AssessmentResults {
|
|
|
51
51
|
itemResults: ItemResult[];
|
|
52
52
|
completedAt: Date;
|
|
53
53
|
}
|
|
54
|
+
/** A test feedback block `AssessmentPlayer.getVisibleFeedback()` shows now. */
|
|
55
|
+
export interface VisibleTestFeedback {
|
|
56
|
+
/** Unique across the test; feedback identifiers repeat, for example in show/hide pairs. */
|
|
57
|
+
key: string;
|
|
58
|
+
identifier: string;
|
|
59
|
+
content: string;
|
|
60
|
+
access: 'atEnd' | 'during';
|
|
61
|
+
/** Set for feedback authored on a test part. */
|
|
62
|
+
testPartIdentifier?: string;
|
|
63
|
+
}
|