@pie-qti/item-player 0.1.6 → 0.1.8

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 (54) hide show
  1. package/dist/catalog/applyGlossaryTriggers.d.ts +2 -1
  2. package/dist/catalog/applyGlossaryTriggers.d.ts.map +1 -1
  3. package/dist/catalog/applyGlossaryTriggers.js +145 -30
  4. package/dist/catalog/glossaryAction.d.ts.map +1 -1
  5. package/dist/catalog/glossaryAction.js +14 -4
  6. package/dist/components/utils/stimulusRender.d.ts +17 -0
  7. package/dist/components/utils/stimulusRender.d.ts.map +1 -0
  8. package/dist/components/utils/stimulusRender.js +70 -0
  9. package/dist/components/utils/stylesheetRender.d.ts +4 -0
  10. package/dist/components/utils/stylesheetRender.d.ts.map +1 -0
  11. package/dist/components/utils/stylesheetRender.js +57 -0
  12. package/dist/core/Player.d.ts +37 -2
  13. package/dist/core/Player.d.ts.map +1 -1
  14. package/dist/core/Player.js +320 -48
  15. package/dist/core/sanitizer.d.ts.map +1 -1
  16. package/dist/core/sanitizer.js +60 -0
  17. package/dist/document/AssessmentItemDocument.d.ts +4 -0
  18. package/dist/document/AssessmentItemDocument.d.ts.map +1 -1
  19. package/dist/document/AssessmentItemDocument.js +53 -4
  20. package/dist/element.js +2027 -1532
  21. package/dist/element.js.map +1 -1
  22. package/dist/index.d.ts +1 -0
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/interactions/extended-text/extractor.d.ts +1 -0
  25. package/dist/interactions/extended-text/extractor.d.ts.map +1 -1
  26. package/dist/interactions/extended-text/extractor.js +2 -0
  27. package/dist/interactions/shared/types.d.ts +1 -0
  28. package/dist/interactions/shared/types.d.ts.map +1 -1
  29. package/dist/pnp/applyPnp.d.ts.map +1 -1
  30. package/dist/pnp/applyPnp.js +9 -2
  31. package/dist/pnp/parsePnpXml.d.ts.map +1 -1
  32. package/dist/pnp/parsePnpXml.js +91 -3
  33. package/dist/pnp/types.d.ts +24 -1
  34. package/dist/pnp/types.d.ts.map +1 -1
  35. package/dist/types/index.d.ts +47 -0
  36. package/dist/types/index.d.ts.map +1 -1
  37. package/package.json +6 -6
  38. package/src/catalog/applyGlossaryTriggers.ts +174 -34
  39. package/src/catalog/glossaryAction.ts +14 -4
  40. package/src/components/ItemBody.svelte +36 -27
  41. package/src/components/utils/stimulusRender.ts +93 -0
  42. package/src/components/utils/stylesheetRender.ts +58 -0
  43. package/src/core/Player.ts +355 -48
  44. package/src/core/sanitizer.ts +70 -0
  45. package/src/document/AssessmentItemDocument.ts +76 -7
  46. package/src/index.ts +1 -0
  47. package/src/interactions/extended-text/extractor.ts +3 -0
  48. package/src/interactions/shared/types.ts +1 -0
  49. package/src/pnp/applyPnp.ts +8 -2
  50. package/src/pnp/parsePnpXml.ts +102 -5
  51. package/src/pnp/types.ts +43 -1
  52. package/src/types/index.ts +53 -0
  53. package/src/__tests__/glossaryTriggers.test.ts +0 -411
  54. package/src/__tests__/pnp.test.ts +0 -250
@@ -25,6 +25,7 @@ import {
25
25
  toStringValue,
26
26
  } from '@pie-qti/qti-processing';
27
27
  import type { ElementNameMapper, AttributeNameMapper } from '@pie-qti/qti-common';
28
+ import type { ResolvedItemDeliveryContext } from '@pie-qti/ims-cp-core';
28
29
  import {
29
30
  Qti2xElementNameMapper,
30
31
  Qti2xAttributeNameMapper,
@@ -42,6 +43,8 @@ import type {
42
43
  AdaptiveAttemptResult,
43
44
  CompletionStatus,
44
45
  HtmlContent,
46
+ ItemLifecycleStatus,
47
+ ItemSessionActionResult,
45
48
  ItemSessionState,
46
49
  ModalFeedback,
47
50
  PlayerConfig,
@@ -49,6 +52,8 @@ import type {
49
52
  QTIRole,
50
53
  RubricBlock,
51
54
  ScoringResult,
55
+ SerializedItemSessionState,
56
+ SerializedItemSessionVariable,
52
57
  } from '../types/index.js';
53
58
  import type { InteractionData } from '../types/interactions.js';
54
59
  import type { ResponseValidationResult } from '../types/responseValidation.js';
@@ -57,10 +62,11 @@ import { createComponentRegistry } from './ComponentRegistry.js';
57
62
  import { createSeededRng } from './random.js';
58
63
  import { sanitizeHtml } from './sanitizer.js';
59
64
  import { toTrustedHtml } from './trustedTypes.js';
65
+ import { sanitizeResourceUrl } from './urlPolicy.js';
60
66
  import type { PnpProfile } from '../pnp/types.js';
61
67
  import { applyPnpToRoot } from '../pnp/applyPnp.js';
62
68
  import type { CatalogIndex } from '../catalog/types.js';
63
- import { extractCatalogFromItemXml, mergeCatalogs } from '../catalog/catalogExtractor.js';
69
+ import { extractCatalog, extractCatalogFromItemXml, mergeCatalogs } from '../catalog/catalogExtractor.js';
64
70
  import { getCatalogEntry } from '../catalog/catalogLookup.js';
65
71
  import { PciHost } from '../pci/PciHost.js';
66
72
  import type { ExtractedPci } from '../pci/types.js';
@@ -88,12 +94,20 @@ export class Player {
88
94
  private _pnp: PnpProfile | undefined;
89
95
  private _rootEl: HTMLElement | undefined;
90
96
  private _catalogIndex: CatalogIndex = new Map();
97
+ private _stimulusCatalogIndexes: Map<string, CatalogIndex> = new Map();
91
98
  private _pciHosts: Map<string, PciHost> = new Map();
99
+ private _pnpChangeListeners = new Set<(pnp: PnpProfile | undefined) => void>();
100
+ private sessionGuid: string;
101
+ private lifecycleStatus: ItemLifecycleStatus = 'initial';
102
+ private sessionStartedAt: number;
103
+ private accumulatedDurationMs = 0;
92
104
 
93
105
  constructor(config: PlayerConfig) {
94
106
  this.config = config;
95
107
  this.itemXml = config.itemXml ?? '';
96
108
  this.role = config.role ?? 'candidate';
109
+ this.sessionGuid = createSessionGuid();
110
+ this.sessionStartedAt = Date.now();
97
111
  this.rng = config.rng ?? (typeof config.seed === 'number' ? createSeededRng(config.seed) : Math.random);
98
112
 
99
113
  // Auto-detect QTI version and create appropriate mappers if not provided
@@ -214,15 +228,23 @@ export class Player {
214
228
  // Store PNP profile for later use (applyPnpToRoot is called once a root element is available).
215
229
  this._pnp = config.pnp;
216
230
 
217
- // Build catalog index from item XML and optional shared catalog.
218
- const itemCatalog = extractCatalogFromItemXml(this.itemXml);
231
+ // Build catalog index from resolved delivery context, legacy shared catalog XML, and item XML.
232
+ // Item/global entries are merged first; item-level entries win on global collisions.
233
+ // Stimulus entries are kept separately so rendered stimulus terms can avoid ID collisions.
234
+ let mergedCatalog: CatalogIndex = new Map();
235
+ for (const source of config.deliveryContext?.catalogSources ?? []) {
236
+ const sourceCatalog = extractCatalog(source.xml);
237
+ if (source.scope === 'stimulus' && source.stimulusIdentifier) {
238
+ const existing = this._stimulusCatalogIndexes.get(source.stimulusIdentifier) ?? new Map();
239
+ this._stimulusCatalogIndexes.set(source.stimulusIdentifier, mergeCatalogs(existing, sourceCatalog));
240
+ } else {
241
+ mergedCatalog = mergeCatalogs(mergedCatalog, sourceCatalog);
242
+ }
243
+ }
219
244
  if (config.catalogXml) {
220
- const sharedCatalog = extractCatalogFromItemXml(config.catalogXml);
221
- // Item-level wins on collision: merge shared first, then override with item entries.
222
- this._catalogIndex = mergeCatalogs(sharedCatalog, itemCatalog);
223
- } else {
224
- this._catalogIndex = itemCatalog;
245
+ mergedCatalog = mergeCatalogs(mergedCatalog, extractCatalogFromItemXml(config.catalogXml));
225
246
  }
247
+ this._catalogIndex = mergeCatalogs(mergedCatalog, extractCatalogFromItemXml(this.itemXml));
226
248
 
227
249
  // Check strict compliance if enabled
228
250
  if (this.config.strictQtiCompliance?.enabled) {
@@ -249,6 +271,9 @@ export class Player {
249
271
  if (this._rootEl) {
250
272
  applyPnpToRoot(this._rootEl, this._pnp);
251
273
  }
274
+ for (const listener of this._pnpChangeListeners) {
275
+ listener(this._pnp);
276
+ }
252
277
  }
253
278
 
254
279
  /** Return the current resolved PNP profile. */
@@ -256,14 +281,42 @@ export class Player {
256
281
  return this._pnp;
257
282
  }
258
283
 
284
+ public onPnpChange(listener: (pnp: PnpProfile | undefined) => void): () => void {
285
+ this._pnpChangeListeners.add(listener);
286
+ return () => this._pnpChangeListeners.delete(listener);
287
+ }
288
+
289
+ /** Return the package/assessment-resolved delivery context, if one was supplied. */
290
+ public getDeliveryContext(): ResolvedItemDeliveryContext | undefined {
291
+ return this.config.deliveryContext;
292
+ }
293
+
259
294
  /**
260
295
  * Look up a catalog entry by card identifier, usage type, and optional language.
261
296
  * Returns the HTML string for the matched entry, or null if not found.
262
297
  *
263
298
  * Language fallback: exact match → prefix match → no-lang entry → null.
264
299
  */
265
- public getCatalogEntry(idref: string, usage: string, lang?: string): string | null {
266
- return getCatalogEntry(this._catalogIndex, idref, usage, lang);
300
+ public getCatalogEntry(
301
+ idref: string,
302
+ usage: string,
303
+ lang?: string,
304
+ options?: { stimulusIdentifier?: string }
305
+ ): string | null {
306
+ const stimulusHtml = options?.stimulusIdentifier
307
+ ? getCatalogEntry(this._stimulusCatalogIndexes.get(options.stimulusIdentifier) ?? new Map(), idref, usage, lang)
308
+ : null;
309
+ const html = stimulusHtml ?? getCatalogEntry(this._catalogIndex, idref, usage, lang);
310
+ if (html === null) return null;
311
+ if (looksLikeCatalogUrl(html)) {
312
+ return sanitizeResourceUrl(html.trim(), this.config.security?.urlPolicy, 'img');
313
+ }
314
+ return this.sanitizeHtmlContent(html);
315
+ }
316
+
317
+ /** Sanitize externally resolved item-adjacent HTML before it reaches a rendering sink. */
318
+ public sanitizeHtmlContent(html: string): string {
319
+ return sanitizeHtml(html, { security: this.config.security });
267
320
  }
268
321
 
269
322
  /**
@@ -340,50 +393,121 @@ export class Player {
340
393
  }
341
394
 
342
395
  public processResponses(): ScoringResult {
343
- // Spec-aligned behavior: each processing run starts from outcome defaults.
344
- // This prevents stale outcomes when response/outcome processing doesn't set every variable.
345
- this.resetOutcomesToDefault();
396
+ return this.runResponseProcessing({ finalizeNonAdaptiveAttempt: true });
397
+ }
346
398
 
347
- // Execute response processing if present
348
- const rpEl = this.itemDocument.getProcessingElement('response');
349
- if (rpEl) {
350
- // If responseProcessing has explicit statements, run the compiled program.
351
- // Otherwise, fall back to template-based processing (responseProcessing@template).
352
- const hasStatements = childElements(rpEl).length > 0;
353
- if (hasStatements) {
354
- this.execResponseProcessingProgram();
355
- } else {
356
- const templateUrl = getAttr(rpEl, 'template');
357
- if (templateUrl) this.execResponseProcessingTemplate(templateUrl);
358
- }
359
- }
399
+ public saveItemSession(): SerializedItemSessionState {
400
+ this.freezeDuration();
401
+ return this.serializeItemSession();
402
+ }
360
403
 
361
-
362
- // Execute outcome processing if present (runs after responseProcessing)
363
- this.execOutcomeProcessingProgram();
404
+ public restoreItemSession(state: SerializedItemSessionState): void {
405
+ this.sessionGuid = state.sessionGuid;
406
+ this.lifecycleStatus = state.lifecycleStatus;
407
+ this.accumulatedDurationMs = Math.max(0, Number(state.duration) || 0);
408
+ this.sessionStartedAt = Date.now();
409
+ this.applySerializedVariables(state.responseVariables);
410
+ this.applySerializedVariables(state.outcomeVariables);
411
+ this.applySerializedVariables(state.templateVariables);
412
+ this.applySerializedVariables(state.contextVariables);
413
+ this.updateDuration();
414
+ }
364
415
 
365
- // For non-adaptive items, update completionStatus and numAttempts after processing
366
- if (!this.isAdaptive()) {
367
- // Set completionStatus to 'completed' for non-adaptive items (single submission)
368
- this.ctx.setValue('completionStatus', qtiValue('identifier', 'single', 'completed'));
369
- // Increment numAttempts for non-adaptive items (tracks total submissions, including retries)
370
- const currentAttempts = this.getNumAttempts();
371
- this.ctx.setValue('numAttempts', qtiValue('integer', 'single', currentAttempts + 1));
416
+ public suspendAttempt(): ItemSessionActionResult {
417
+ const validation = this.validateResponses(this.getResponses());
418
+ this.lifecycleStatus = 'suspended';
419
+ const sessionState = this.saveItemSession();
420
+
421
+ return {
422
+ action: 'suspendAttempt',
423
+ lifecycleStatus: this.lifecycleStatus,
424
+ completionStatus: this.getCompletionStatus(),
425
+ numAttempts: this.getNumAttempts(),
426
+ duration: sessionState.duration,
427
+ completed: this.isCompleted(),
428
+ sessionState,
429
+ validation,
430
+ };
431
+ }
432
+
433
+ public endAttempt(options: { countAttempt?: boolean; validateResponses?: boolean } = {}): ItemSessionActionResult {
434
+ const validate = options.validateResponses ?? false;
435
+ const validation = validate ? this.validateResponses(this.getResponses()) : undefined;
436
+ if (validation && !validation.valid) {
437
+ const sessionState = this.saveItemSession();
438
+ return {
439
+ action: 'endAttempt',
440
+ lifecycleStatus: this.lifecycleStatus,
441
+ completionStatus: this.getCompletionStatus(),
442
+ numAttempts: this.getNumAttempts(),
443
+ duration: sessionState.duration,
444
+ completed: this.isCompleted(),
445
+ sessionState,
446
+ validation,
447
+ };
372
448
  }
373
449
 
374
- const outcomes = this.collectOutcomes();
375
-
376
- const score = Number(outcomes.SCORE ?? 0);
377
- const maxScore = Number(outcomes.MAXSCORE ?? 1);
378
- const completionStatus = (outcomes.completionStatus as CompletionStatus | undefined) ?? 'not_attempted';
379
- const completed = completionStatus === 'completed' || !this.isAdaptive();
450
+ const scoring = this.isAdaptive()
451
+ ? this.submitAttempt(options.countAttempt ?? true)
452
+ : this.runResponseProcessing({
453
+ finalizeNonAdaptiveAttempt: true,
454
+ countAttempt: options.countAttempt ?? true,
455
+ });
456
+ this.lifecycleStatus = scoring.completed ? 'closed' : 'interacting';
457
+ const sessionState = this.saveItemSession();
380
458
 
381
459
  return {
382
- score,
383
- maxScore,
384
- completed,
385
- outcomeValues: outcomes,
386
- modalFeedback: this.getModalFeedback(outcomes),
460
+ action: 'endAttempt',
461
+ lifecycleStatus: this.lifecycleStatus,
462
+ completionStatus: this.getCompletionStatus(),
463
+ numAttempts: this.getNumAttempts(),
464
+ duration: sessionState.duration,
465
+ completed: scoring.completed,
466
+ sessionState,
467
+ validation,
468
+ scoring,
469
+ };
470
+ }
471
+
472
+ public scoreAttempt(): ItemSessionActionResult {
473
+ const scoring = this.runResponseProcessing({ finalizeNonAdaptiveAttempt: false });
474
+ const sessionState = this.saveItemSession();
475
+
476
+ return {
477
+ action: 'scoreAttempt',
478
+ lifecycleStatus: this.lifecycleStatus,
479
+ completionStatus: this.getCompletionStatus(),
480
+ numAttempts: this.getNumAttempts(),
481
+ duration: sessionState.duration,
482
+ completed: scoring.completed,
483
+ sessionState,
484
+ scoring,
485
+ };
486
+ }
487
+
488
+ public newTemplate(options: { resetResponses?: boolean } = {}): ItemSessionActionResult {
489
+ this.resetOutcomesToDefault();
490
+ if (options.resetResponses ?? true) {
491
+ this.resetResponsesToDefault();
492
+ }
493
+ this.resetTemplatesToDefault();
494
+ this.ctx.setValue('completionStatus', qtiValue('identifier', 'single', 'not_attempted'));
495
+ this.ctx.setValue('numAttempts', qtiValue('integer', 'single', 0));
496
+ this.execTemplateProcessing();
497
+ this.lifecycleStatus = 'initial';
498
+ this.accumulatedDurationMs = 0;
499
+ this.sessionStartedAt = Date.now();
500
+ this.updateDuration();
501
+ const sessionState = this.serializeItemSession();
502
+
503
+ return {
504
+ action: 'newTemplate',
505
+ lifecycleStatus: this.lifecycleStatus,
506
+ completionStatus: this.getCompletionStatus(),
507
+ numAttempts: this.getNumAttempts(),
508
+ duration: sessionState.duration,
509
+ completed: this.isCompleted(),
510
+ sessionState,
387
511
  };
388
512
  }
389
513
 
@@ -490,11 +614,78 @@ export class Player {
490
614
  if ((d as any).__kind !== 'outcome') continue;
491
615
  // Built-in stateful variables must survive across processing runs.
492
616
  // They are updated by the runtime (adaptive attempt tracking), not by outcome defaults.
493
- if (d.identifier === 'numAttempts' || d.identifier === 'completionStatus') continue;
617
+ if (d.identifier === 'numAttempts' || d.identifier === 'completionStatus' || d.identifier === 'duration') continue;
494
618
  this.ctx.resetToDefault(d.identifier);
495
619
  }
496
620
  }
497
621
 
622
+ private resetResponsesToDefault(): void {
623
+ for (const d of Object.values(this.decls)) {
624
+ if ((d as any).__kind !== 'response') continue;
625
+ this.ctx.resetToDefault(d.identifier);
626
+ this.setPciResponse(d.identifier, d.value.kind === 'value' ? d.value.value : null);
627
+ }
628
+ }
629
+
630
+ private resetTemplatesToDefault(): void {
631
+ for (const d of Object.values(this.decls)) {
632
+ if (!d.isTemplate) continue;
633
+ this.ctx.resetToDefault(d.identifier);
634
+ }
635
+ }
636
+
637
+ private runResponseProcessing(options: {
638
+ finalizeNonAdaptiveAttempt: boolean;
639
+ countAttempt?: boolean;
640
+ }): ScoringResult {
641
+ this.updateDuration();
642
+ // Spec-aligned behavior: each processing run starts from outcome defaults.
643
+ // This prevents stale outcomes when response/outcome processing doesn't set every variable.
644
+ this.resetOutcomesToDefault();
645
+
646
+ // Execute response processing if present
647
+ const rpEl = this.itemDocument.getProcessingElement('response');
648
+ if (rpEl) {
649
+ // If responseProcessing has explicit statements, run the compiled program.
650
+ // Otherwise, fall back to template-based processing (responseProcessing@template).
651
+ const hasStatements = childElements(rpEl).length > 0;
652
+ if (hasStatements) {
653
+ this.execResponseProcessingProgram();
654
+ } else {
655
+ const templateUrl = getAttr(rpEl, 'template');
656
+ if (templateUrl) this.execResponseProcessingTemplate(templateUrl);
657
+ }
658
+ }
659
+
660
+ // Execute outcome processing if present (runs after responseProcessing)
661
+ this.execOutcomeProcessingProgram();
662
+
663
+ // Compatibility: processResponses() has historically finalized non-adaptive items.
664
+ // New scoreAttempt() uses this same engine with finalization disabled.
665
+ if (!this.isAdaptive() && options.finalizeNonAdaptiveAttempt) {
666
+ this.ctx.setValue('completionStatus', qtiValue('identifier', 'single', 'completed'));
667
+ if (options.countAttempt ?? true) {
668
+ const currentAttempts = this.getNumAttempts();
669
+ this.ctx.setValue('numAttempts', qtiValue('integer', 'single', currentAttempts + 1));
670
+ }
671
+ }
672
+
673
+ const outcomes = this.collectOutcomes();
674
+
675
+ const score = Number(outcomes.SCORE ?? 0);
676
+ const maxScore = Number(outcomes.MAXSCORE ?? 1);
677
+ const completionStatus = (outcomes.completionStatus as CompletionStatus | undefined) ?? 'not_attempted';
678
+ const completed = completionStatus === 'completed' || (!this.isAdaptive() && options.finalizeNonAdaptiveAttempt);
679
+
680
+ return {
681
+ score,
682
+ maxScore,
683
+ completed,
684
+ outcomeValues: outcomes,
685
+ modalFeedback: this.getModalFeedback(outcomes),
686
+ };
687
+ }
688
+
498
689
  public getItemBodyHtml(): HtmlContent {
499
690
  const inner = this.itemDocument.serializeItemBodyChildren();
500
691
  if (!inner) return '';
@@ -1061,6 +1252,7 @@ export class Player {
1061
1252
  identifier: 'numAttempts',
1062
1253
  baseType: 'integer',
1063
1254
  cardinality: 'single',
1255
+ defaultValue: qtiValue('integer', 'single', 0),
1064
1256
  value: qtiValue('integer', 'single', 0),
1065
1257
  isTemplate: false,
1066
1258
  // @ts-expect-error internal marker
@@ -1068,6 +1260,19 @@ export class Player {
1068
1260
  };
1069
1261
  }
1070
1262
 
1263
+ if (!decls.duration) {
1264
+ decls.duration = {
1265
+ identifier: 'duration',
1266
+ baseType: 'duration',
1267
+ cardinality: 'single',
1268
+ defaultValue: qtiValue('duration', 'single', 0),
1269
+ value: qtiValue('duration', 'single', 0),
1270
+ isTemplate: false,
1271
+ // @ts-expect-error internal marker
1272
+ __kind: 'outcome',
1273
+ };
1274
+ }
1275
+
1071
1276
  // Common scoring defaults
1072
1277
  if (!decls.SCORE) {
1073
1278
  decls.SCORE = {
@@ -1099,6 +1304,95 @@ export class Player {
1099
1304
  if (!d) continue;
1100
1305
  d.value = this.coerceToDeclarationValue(d.baseType, d.cardinality, raw);
1101
1306
  }
1307
+ const restoredDuration = Number(state.duration);
1308
+ if (Number.isFinite(restoredDuration) && restoredDuration >= 0) {
1309
+ this.accumulatedDurationMs = restoredDuration;
1310
+ this.sessionStartedAt = Date.now();
1311
+ this.updateDuration();
1312
+ }
1313
+ }
1314
+
1315
+ private applySerializedVariables(vars: Record<string, SerializedItemSessionVariable>): void {
1316
+ for (const v of Object.values(vars)) {
1317
+ const d = this.decls[v.identifier];
1318
+ if (!d) continue;
1319
+ d.value = this.coerceToDeclarationValue(d.baseType, d.cardinality, v.value);
1320
+ if ((d as any).__kind === 'response') {
1321
+ this.setPciResponse(d.identifier, v.value);
1322
+ }
1323
+ }
1324
+ }
1325
+
1326
+ private serializeItemSession(): SerializedItemSessionState {
1327
+ const responseVariables: Record<string, SerializedItemSessionVariable> = {};
1328
+ const outcomeVariables: Record<string, SerializedItemSessionVariable> = {};
1329
+ const templateVariables: Record<string, SerializedItemSessionVariable> = {};
1330
+ const contextVariables: Record<string, SerializedItemSessionVariable> = {};
1331
+ const contextIds = new Set(['completionStatus', 'numAttempts', 'duration']);
1332
+
1333
+ for (const d of Object.values(this.decls)) {
1334
+ const variable = this.serializeVariable(d);
1335
+ if (d.isTemplate) {
1336
+ templateVariables[d.identifier] = { ...variable, kind: 'template' };
1337
+ } else if (contextIds.has(d.identifier)) {
1338
+ contextVariables[d.identifier] = { ...variable, kind: 'context' };
1339
+ } else if ((d as any).__kind === 'response') {
1340
+ responseVariables[d.identifier] = { ...variable, kind: 'response' };
1341
+ } else if ((d as any).__kind === 'outcome') {
1342
+ outcomeVariables[d.identifier] = { ...variable, kind: 'outcome' };
1343
+ }
1344
+ }
1345
+
1346
+ const validation = this.validateResponses(this.getResponses());
1347
+ return {
1348
+ itemIdentifier: this.itemDocument.getAssessmentItemAttribute('identifier') ?? undefined,
1349
+ sessionGuid: this.sessionGuid,
1350
+ lifecycleStatus: this.lifecycleStatus,
1351
+ completionStatus: this.getCompletionStatus(),
1352
+ numAttempts: this.getNumAttempts(),
1353
+ duration: this.getDuration(),
1354
+ responseVariables,
1355
+ outcomeVariables,
1356
+ templateVariables,
1357
+ contextVariables,
1358
+ validationMessages: validation.issues,
1359
+ savedAt: new Date().toISOString(),
1360
+ };
1361
+ }
1362
+
1363
+ private serializeVariable(d: DeclarationMap[string]): SerializedItemSessionVariable {
1364
+ return {
1365
+ identifier: d.identifier,
1366
+ kind: ((d as any).__kind ?? (d.isTemplate ? 'template' : 'context')) as SerializedItemSessionVariable['kind'],
1367
+ baseType: d.baseType,
1368
+ cardinality: d.cardinality,
1369
+ value: this.qtiValueToSerializable(d.value),
1370
+ defaultValue: this.qtiValueToSerializable(d.defaultValue),
1371
+ };
1372
+ }
1373
+
1374
+ private qtiValueToSerializable(value: QtiValue | undefined): any {
1375
+ if (!value || value.kind !== 'value') return null;
1376
+ return value.value;
1377
+ }
1378
+
1379
+ private updateDuration(): void {
1380
+ const elapsedMs = Math.max(0, Date.now() - this.sessionStartedAt);
1381
+ const durationMs = this.accumulatedDurationMs + elapsedMs;
1382
+ this.ctx.setValue('duration', qtiValue('duration', 'single', durationMs));
1383
+ }
1384
+
1385
+ private freezeDuration(): number {
1386
+ this.updateDuration();
1387
+ const duration = this.getDuration();
1388
+ this.accumulatedDurationMs = duration;
1389
+ this.sessionStartedAt = Date.now();
1390
+ return duration;
1391
+ }
1392
+
1393
+ private getDuration(): number {
1394
+ const value = this.ctx.getValue('duration');
1395
+ return Math.max(0, Math.floor(toNumber(value) || 0));
1102
1396
  }
1103
1397
 
1104
1398
  private parseDefaultValue(declEl: Element, baseType: BaseType, cardinality: Cardinality): QtiValue {
@@ -1309,3 +1603,16 @@ function mergePnp(base: PnpProfile | undefined, partial: Partial<PnpProfile>): P
1309
1603
  cognitive: { ...(base?.cognitive ?? {}), ...(partial.cognitive ?? {}) },
1310
1604
  };
1311
1605
  }
1606
+
1607
+ function createSessionGuid(): string {
1608
+ if (typeof crypto !== 'undefined' && 'randomUUID' in crypto) {
1609
+ return crypto.randomUUID();
1610
+ }
1611
+ return `item-session-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
1612
+ }
1613
+
1614
+ function looksLikeCatalogUrl(value: string): boolean {
1615
+ const trimmed = value.trim();
1616
+ return /^(https?:\/\/|\/\/|\/|\.{0,2}\/|data:|blob:)/i.test(trimmed) ||
1617
+ /\.(png|jpe?g|gif|webp|svg|mp3|wav|ogg|mp4|webm|pdf)(\?.*)?$/i.test(trimmed);
1618
+ }
@@ -40,6 +40,19 @@ function allowIframes(options?: SanitizeHtmlOptions): boolean {
40
40
  return options?.security?.allowIframes === true;
41
41
  }
42
42
 
43
+ function escapeAttr(value: string): string {
44
+ return value
45
+ .replace(/&/g, '&amp;')
46
+ .replace(/"/g, '&quot;')
47
+ .replace(/</g, '&lt;')
48
+ .replace(/>/g, '&gt;');
49
+ }
50
+
51
+ function getOptionalAttr(element: HTMLElement, attrName: string): string {
52
+ const value = element.getAttribute(attrName);
53
+ return value ? ` ${attrName}="${escapeAttr(value)}"` : '';
54
+ }
55
+
43
56
  function sanitizeUrlAttr(value: string, policy: UrlPolicyConfig | undefined, kind: 'img' | 'media' | 'object' | 'link' | 'any'): string {
44
57
  return sanitizeResourceUrl(value, policy, kind) ?? '#';
45
58
  }
@@ -99,6 +112,11 @@ function sanitizeElement(
99
112
  return;
100
113
  }
101
114
  if ((tagName === 'object' || tagName === 'embed') && !allowObjectEmbeds(options)) {
115
+ const replacementHtml = getSafeObjectReplacementHtml(element, policyFromOptions(options));
116
+ if (replacementHtml) {
117
+ element.replaceWith(replacementHtml);
118
+ return;
119
+ }
102
120
  element.remove();
103
121
  return;
104
122
  }
@@ -233,3 +251,55 @@ export function sanitizeTextContent(text: string, options?: SanitizeHtmlOptions)
233
251
  // Plain text - return as-is
234
252
  return text;
235
253
  }
254
+
255
+ function getSafeObjectReplacementHtml(element: HTMLElement, policy: UrlPolicyConfig | undefined): string | null {
256
+ if ((element as any).rawTagName?.toLowerCase() !== 'object') {
257
+ return null;
258
+ }
259
+
260
+ const rawType = element.getAttribute('type')?.trim().toLowerCase() ?? '';
261
+ const rawData = element.getAttribute('data')?.trim() ?? '';
262
+ if (!rawType || !rawData) {
263
+ return null;
264
+ }
265
+
266
+ const dimensions = `${getOptionalAttr(element, 'width')}${getOptionalAttr(element, 'height')}`;
267
+ const classes = getOptionalAttr(element, 'class');
268
+ const id = getOptionalAttr(element, 'id');
269
+
270
+ if (rawType.startsWith('image/')) {
271
+ const src = sanitizeResourceUrl(rawData, policy, 'img');
272
+ if (!src) {
273
+ return null;
274
+ }
275
+ const alt =
276
+ element.getAttribute('aria-label') ??
277
+ element.getAttribute('title') ??
278
+ element.textContent?.trim() ??
279
+ '';
280
+ return `<img src="${escapeAttr(src)}" alt="${escapeAttr(alt)}"${dimensions}${classes}${id}>`;
281
+ }
282
+
283
+ if (rawType.startsWith('audio/')) {
284
+ const src = sanitizeResourceUrl(rawData, policy, 'media');
285
+ if (!src) {
286
+ return null;
287
+ }
288
+ return `<audio controls${classes}${id}><source src="${escapeAttr(src)}" type="${escapeAttr(rawType)}"></audio>`;
289
+ }
290
+
291
+ if (rawType.startsWith('video/')) {
292
+ const src = sanitizeResourceUrl(rawData, policy, 'media');
293
+ if (!src) {
294
+ return null;
295
+ }
296
+ const rawPoster = element.getAttribute('poster')?.trim() ?? '';
297
+ const poster = rawPoster
298
+ ? sanitizeResourceUrl(rawPoster, policy, 'img')
299
+ : null;
300
+ const posterAttr = poster ? ` poster="${escapeAttr(poster)}"` : '';
301
+ return `<video controls${dimensions}${classes}${id}${posterAttr}><source src="${escapeAttr(src)}" type="${escapeAttr(rawType)}"></video>`;
302
+ }
303
+
304
+ return null;
305
+ }