@pie-qti/assessment-player 0.1.14 → 0.1.16

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.
@@ -27,7 +27,7 @@
27
27
  * - Filters sensitive data based on role
28
28
  */
29
29
  import { buildExpression, buildOutcomeProcessingAst, DeclarationContext, evalExpr, execProgram, OperatorRegistry, parseXml, serializeXml, qtiNull, qtiValue, } from '@pie-qti/qti-processing';
30
- import { createResolvedItemDeliveryContext, extractAssessmentStimulusRefs, extractQtiStylesheets, parseAssessmentStimulusXml, resolveCheckedPackagePath, resolveCheckedPackagePathFromFile, resolveRelativePath as resolveQtiRelativePath, } from '@pie-qti/ims-cp-core';
30
+ import { createResolvedItemDeliveryContext, extractAssessmentStimulusRefs, extractQtiStylesheets, parseAssessmentStimulusXml, resolveCheckedPackagePath, resolveCheckedPackagePathFromFile, } from '@pie-qti/ims-cp-core';
31
31
  import { scoreAssessmentItem } from './assessment-item-scorer.js';
32
32
  /**
33
33
  * Storage key prefix for localStorage
@@ -37,6 +37,8 @@ const STORAGE_PREFIX = 'qti_session_';
37
37
  * Cache key for item bank queries
38
38
  */
39
39
  const BANK_CACHE_PREFIX = 'qti_bank_cache_';
40
+ class AssessmentSectionReferenceLimitError extends Error {
41
+ }
40
42
  function toCanonicalQtiName(name) {
41
43
  const withoutPrefix = (name ?? '').replace(/^qti-/, '');
42
44
  return withoutPrefix.replace(/-([a-z])/g, (_, char) => char.toUpperCase());
@@ -118,8 +120,9 @@ export class ReferenceBackendAdapter {
118
120
  //
119
121
  // For reference implementation, we'll use demo data
120
122
  const assessment = this.getAssessment(request.assessmentId);
123
+ const firstItemIdentifier = this.getItemOrder(assessment)[0] ?? '';
121
124
  const state = {
122
- currentItemIdentifier: assessment.testParts[0].sections[0].assessmentItemRefs[0].identifier,
125
+ currentItemIdentifier: firstItemIdentifier,
123
126
  visitedItems: [],
124
127
  itemResponses: {},
125
128
  itemScores: {},
@@ -464,25 +467,45 @@ export class ReferenceBackendAdapter {
464
467
  }
465
468
  }
466
469
  findItemXml(assessment, itemIdentifier) {
470
+ const findInSection = (section) => {
471
+ for (const item of section.assessmentItemRefs) {
472
+ if (item.identifier === itemIdentifier)
473
+ return item.itemXml;
474
+ }
475
+ for (const child of section.sections ?? []) {
476
+ const found = findInSection(child);
477
+ if (found !== null)
478
+ return found;
479
+ }
480
+ return null;
481
+ };
467
482
  for (const part of assessment.testParts) {
468
483
  for (const section of part.sections) {
469
- for (const item of section.assessmentItemRefs) {
470
- if (item.identifier === itemIdentifier) {
471
- return item.itemXml;
472
- }
473
- }
484
+ const found = findInSection(section);
485
+ if (found !== null)
486
+ return found;
474
487
  }
475
488
  }
476
489
  return null;
477
490
  }
478
491
  findItemRef(assessment, itemIdentifier) {
492
+ const findInSection = (section) => {
493
+ for (const item of section.assessmentItemRefs) {
494
+ if (item.identifier === itemIdentifier)
495
+ return item;
496
+ }
497
+ for (const child of section.sections ?? []) {
498
+ const found = findInSection(child);
499
+ if (found)
500
+ return found;
501
+ }
502
+ return null;
503
+ };
479
504
  for (const part of assessment.testParts) {
480
505
  for (const section of part.sections) {
481
- for (const item of section.assessmentItemRefs) {
482
- if (item.identifier === itemIdentifier) {
483
- return item;
484
- }
485
- }
506
+ const found = findInSection(section);
507
+ if (found)
508
+ return found;
486
509
  }
487
510
  }
488
511
  return null;
@@ -625,6 +648,10 @@ export class ReferenceBackendAdapter {
625
648
  */
626
649
  static async parseAssessmentTestXml(testXml, options = {}) {
627
650
  const { role = 'candidate', itemXmlMap = {}, fileResolver, baseUrl } = options;
651
+ const maxSectionDepth = options.sectionReferenceLimits?.maxDepth ?? 32;
652
+ if (!Number.isInteger(maxSectionDepth) || maxSectionDepth < 1) {
653
+ throw new Error('sectionReferenceLimits.maxDepth must be a positive integer');
654
+ }
628
655
  const doc = parseXml(testXml);
629
656
  const root = doc.documentElement;
630
657
  if (!root)
@@ -682,22 +709,56 @@ export class ReferenceBackendAdapter {
682
709
  allowLateSubmission: boolAttr('allowLateSubmission'),
683
710
  };
684
711
  };
685
- const resolveAgainstBase = (href) => {
686
- if (!href)
712
+ const parseConditionExpressions = (el, tag) => {
713
+ const expressions = childrenByTag(el, tag)
714
+ .map((condition) => childElements(condition)[0])
715
+ .filter((expression) => Boolean(expression))
716
+ .map((expression) => serializeXml(expression));
717
+ return expressions.length > 0 ? expressions : undefined;
718
+ };
719
+ const parseBranchRules = (el) => {
720
+ const rules = childrenByTag(el, 'branchRule').flatMap((rule) => {
721
+ const target = getAttr(rule, 'target');
722
+ if (!target)
723
+ return [];
724
+ const expression = childElements(rule)[0];
725
+ return [{ target, conditionXml: expression ? serializeXml(expression) : undefined }];
726
+ });
727
+ return rules.length > 0 ? rules : undefined;
728
+ };
729
+ const parseSelection = (el) => {
730
+ const selection = childrenByTag(el, 'selection')[0];
731
+ if (!selection)
687
732
  return undefined;
688
- return baseUrl ? resolveQtiRelativePath(baseUrl, href) : href;
733
+ const select = Number.parseInt(getAttr(selection, 'select') ?? '', 10);
734
+ if (!Number.isInteger(select) || select < 0)
735
+ return undefined;
736
+ const withReplacementRaw = getAttr(selection, 'withReplacement');
737
+ return {
738
+ select,
739
+ withReplacement: withReplacementRaw === undefined ? undefined : withReplacementRaw === 'true',
740
+ };
689
741
  };
690
- const resolveCheckedHref = (href) => {
742
+ const parseOrdering = (el) => {
743
+ const ordering = childrenByTag(el, 'ordering')[0];
744
+ if (!ordering)
745
+ return undefined;
746
+ return { shuffle: getAttr(ordering, 'shuffle') === 'true' };
747
+ };
748
+ const resolveCheckedHref = (href, sourceHref) => {
691
749
  if (!href)
692
750
  return undefined;
751
+ if (sourceHref) {
752
+ return resolveCheckedPackagePathFromFile(sourceHref, href) ?? undefined;
753
+ }
693
754
  return baseUrl
694
755
  ? resolveCheckedPackagePathFromFile(baseUrl, href) ?? undefined
695
756
  : resolveCheckedPackagePath(undefined, href) ?? undefined;
696
757
  };
697
- const loadText = async (href) => {
758
+ const loadText = async (href, sourceHref) => {
698
759
  if (!href)
699
760
  return undefined;
700
- const candidates = [href, resolveAgainstBase(href)].filter((value, index, all) => Boolean(value) && all.indexOf(value) === index);
761
+ const candidates = [href, resolveCheckedHref(href, sourceHref)].filter((value, index, all) => Boolean(value) && all.indexOf(value) === index);
701
762
  for (const candidate of candidates) {
702
763
  if (itemXmlMap[candidate] !== undefined) {
703
764
  return itemXmlMap[candidate];
@@ -751,12 +812,49 @@ export class ReferenceBackendAdapter {
751
812
  readText: (path) => packageTextByPath[path] ?? stimulusXmlByPath[path] ?? itemXmlMap[path],
752
813
  });
753
814
  };
754
- // Parse a single assessmentSection element
755
- const parseSection = async (sectionEl) => {
815
+ let resolveSectionRef;
816
+ const parseItemRef = async (ref, sourceHref) => {
817
+ const itemId = getAttr(ref, 'identifier') ?? 'item';
818
+ const href = getAttr(ref, 'href');
819
+ const itemHref = resolveCheckedHref(href, sourceHref);
820
+ const resolvedXml = href && !itemHref
821
+ ? ''
822
+ : itemXmlMap[itemId] ??
823
+ (href ? itemXmlMap[href] : undefined) ??
824
+ (itemHref ? itemXmlMap[itemHref] : undefined) ??
825
+ (await loadText(itemHref)) ??
826
+ '';
827
+ const requiredRaw = getAttr(ref, 'required');
828
+ const fixedRaw = getAttr(ref, 'fixed');
829
+ const weights = childrenByTag(ref, 'weight').flatMap((weight) => {
830
+ const identifier = getAttr(weight, 'identifier');
831
+ const value = Number(getAttr(weight, 'value'));
832
+ return identifier && Number.isFinite(value) ? [{ identifier, value }] : [];
833
+ });
834
+ return {
835
+ identifier: itemId,
836
+ itemXml: resolvedXml,
837
+ role,
838
+ required: requiredRaw === undefined ? undefined : requiredRaw !== 'false',
839
+ fixed: fixedRaw === undefined ? undefined : fixedRaw !== 'false',
840
+ timeLimits: parseTimeLimits(ref),
841
+ deliveryContext: await buildDeliveryContext(resolvedXml, itemHref),
842
+ branchRule: parseBranchRules(ref),
843
+ preConditions: parseConditionExpressions(ref, 'preCondition'),
844
+ weights: weights.length > 0 ? weights : undefined,
845
+ };
846
+ };
847
+ // Parse a single assessmentSection element without flattening nested sections.
848
+ const parseSection = async (sectionEl, sourceHref, ancestorHrefs = [], depth = 1) => {
756
849
  const identifier = getAttr(sectionEl, 'identifier') ?? 'section';
850
+ if (depth > maxSectionDepth) {
851
+ throw new AssessmentSectionReferenceLimitError(`assessmentSection nesting exceeds maxDepth (${maxSectionDepth}) at "${identifier}"`);
852
+ }
757
853
  const title = getAttr(sectionEl, 'title');
758
854
  const visibleRaw = getAttr(sectionEl, 'visible');
759
855
  const visible = visibleRaw === undefined ? true : visibleRaw !== 'false';
856
+ const requiredRaw = getAttr(sectionEl, 'required');
857
+ const fixedRaw = getAttr(sectionEl, 'fixed');
760
858
  const itemSessionControl = parseItemSessionControl(sectionEl);
761
859
  const timeLimits = parseTimeLimits(sectionEl);
762
860
  // rubricBlocks
@@ -769,44 +867,48 @@ export class ReferenceBackendAdapter {
769
867
  content: serializeXml(b),
770
868
  }))
771
869
  : undefined;
772
- // assessmentItemRefs
773
- const itemRefEls = childrenByTag(sectionEl, 'assessmentItemRef');
774
870
  const assessmentItemRefs = [];
775
- for (const ref of itemRefEls) {
776
- const itemId = getAttr(ref, 'identifier') ?? 'item';
777
- const href = getAttr(ref, 'href');
778
- const itemHref = resolveCheckedHref(href);
779
- // Look up pre-loaded XML by identifier or href
780
- const resolvedXml = href && !itemHref
781
- ? ''
782
- : itemXmlMap[itemId] ??
783
- (href ? itemXmlMap[href] : undefined) ??
784
- (itemHref ? itemXmlMap[itemHref] : undefined) ??
785
- (await loadText(itemHref)) ??
786
- '';
787
- const requiredRaw = getAttr(ref, 'required');
788
- const required = requiredRaw === undefined ? undefined : requiredRaw !== 'false';
789
- assessmentItemRefs.push({
790
- identifier: itemId,
791
- itemXml: resolvedXml,
792
- role,
793
- required,
794
- timeLimits: parseTimeLimits(ref),
795
- deliveryContext: await buildDeliveryContext(resolvedXml, itemHref),
796
- });
871
+ const sections = [];
872
+ const children = [];
873
+ for (const child of childElements(sectionEl)) {
874
+ const name = toCanonicalQtiName(child.localName);
875
+ if (name === 'assessmentItemRef') {
876
+ const item = await parseItemRef(child, sourceHref);
877
+ assessmentItemRefs.push(item);
878
+ children.push({ type: 'item', item });
879
+ }
880
+ else if (name === 'assessmentSection') {
881
+ const section = await parseSection(child, sourceHref, ancestorHrefs, depth + 1);
882
+ sections.push(section);
883
+ children.push({ type: 'section', section });
884
+ }
885
+ else if (name === 'assessmentSectionRef') {
886
+ const section = await resolveSectionRef(child, sourceHref, ancestorHrefs, depth + 1);
887
+ if (section) {
888
+ sections.push(section);
889
+ children.push({ type: 'section', section });
890
+ }
891
+ }
797
892
  }
798
893
  return {
799
894
  identifier,
800
895
  title,
801
896
  visible,
897
+ required: requiredRaw === undefined ? undefined : requiredRaw !== 'false',
898
+ fixed: fixedRaw === undefined ? undefined : fixedRaw !== 'false',
802
899
  assessmentItemRefs,
900
+ sections: sections.length > 0 ? sections : undefined,
901
+ children: children.length > 0 ? children : undefined,
803
902
  rubricBlocks,
804
903
  itemSessionControl,
805
904
  timeLimits,
905
+ selection: parseSelection(sectionEl),
906
+ ordering: parseOrdering(sectionEl),
907
+ preConditions: parseConditionExpressions(sectionEl, 'preCondition'),
806
908
  };
807
909
  };
808
910
  // Resolve assessmentSectionRef: load and parse referenced section file
809
- const resolveSectionRef = async (sectionRefEl) => {
911
+ resolveSectionRef = async (sectionRefEl, sourceHref, ancestorHrefs = [], depth = 1) => {
810
912
  const href = getAttr(sectionRefEl, 'href');
811
913
  if (!href) {
812
914
  console.warn('[ReferenceBackendAdapter] assessmentSectionRef missing href, skipping');
@@ -817,11 +919,17 @@ export class ReferenceBackendAdapter {
817
919
  return null;
818
920
  }
819
921
  try {
820
- const resolvedHref = resolveCheckedHref(href);
922
+ const resolvedHref = resolveCheckedHref(href, sourceHref);
821
923
  if (!resolvedHref) {
822
924
  console.warn(`[ReferenceBackendAdapter] assessmentSectionRef href="${href}" is unsafe, skipping`);
823
925
  return null;
824
926
  }
927
+ if (ancestorHrefs.includes(resolvedHref)) {
928
+ throw new AssessmentSectionReferenceLimitError(`Cyclic assessmentSectionRef detected: ${[...ancestorHrefs, resolvedHref].join(' -> ')}`);
929
+ }
930
+ if (depth > maxSectionDepth) {
931
+ throw new AssessmentSectionReferenceLimitError(`assessmentSectionRef nesting exceeds maxDepth (${maxSectionDepth}) at "${resolvedHref}"`);
932
+ }
825
933
  const sectionXml = await fileResolver(resolvedHref);
826
934
  const secDoc = parseXml(sectionXml);
827
935
  const secRoot = secDoc.documentElement;
@@ -829,9 +937,11 @@ export class ReferenceBackendAdapter {
829
937
  console.warn(`[ReferenceBackendAdapter] assessmentSectionRef href="${href}": root element is not <assessmentSection>, skipping`);
830
938
  return null;
831
939
  }
832
- return parseSection(secRoot);
940
+ return parseSection(secRoot, resolvedHref, [...ancestorHrefs, resolvedHref], depth);
833
941
  }
834
942
  catch (err) {
943
+ if (err instanceof AssessmentSectionReferenceLimitError)
944
+ throw err;
835
945
  console.warn(`[ReferenceBackendAdapter] Failed to load assessmentSectionRef href="${href}":`, err);
836
946
  return null;
837
947
  }
@@ -901,17 +1011,33 @@ export class ReferenceBackendAdapter {
901
1011
  const outcomeProcessingXml = outcomeProcessingEl
902
1012
  ? serializeXml(outcomeProcessingEl)
903
1013
  : undefined;
1014
+ const testFeedback = childrenByTag(root, 'testFeedback').flatMap((feedback, index) => {
1015
+ const outcomeIdentifier = getAttr(feedback, 'outcomeIdentifier');
1016
+ if (!outcomeIdentifier)
1017
+ return [];
1018
+ const content = Array.from(feedback.childNodes).map((node) => serializeXml(node)).join('');
1019
+ return [{
1020
+ identifier: getAttr(feedback, 'identifier') ?? `test-feedback-${index + 1}`,
1021
+ outcomeIdentifier,
1022
+ showHide: (getAttr(feedback, 'showHide') ?? 'show'),
1023
+ access: (getAttr(feedback, 'access') ?? 'atEnd'),
1024
+ content,
1025
+ }];
1026
+ });
904
1027
  // Extract assessment-level timeLimits.
905
1028
  const timeLimits = parseTimeLimits(root);
906
1029
  // Parse testParts
907
1030
  const testPartEls = childrenByTag(root, 'testPart');
908
1031
  const firstTestPart = testPartEls[0];
909
- // Navigation/submission mode from first testPart (QTI 2.2 spec)
1032
+ // Retain top-level compatibility fields while preserving the authoritative
1033
+ // mode on every testPart below.
910
1034
  const navigationMode = (getAttr(firstTestPart ?? root, 'navigationMode') ?? 'nonlinear');
911
1035
  const submissionMode = (getAttr(firstTestPart ?? root, 'submissionMode') ?? 'simultaneous');
912
1036
  const testParts = [];
913
1037
  for (const tp of testPartEls) {
914
1038
  const tpIdentifier = getAttr(tp, 'identifier') ?? 'part-1';
1039
+ const tpNavigationMode = (getAttr(tp, 'navigationMode') ?? 'nonlinear');
1040
+ const tpSubmissionMode = (getAttr(tp, 'submissionMode') ?? 'simultaneous');
915
1041
  const tpItemSessionControl = parseTestPartItemSessionControl(tp);
916
1042
  const tpTimeLimits = parseTimeLimits(tp);
917
1043
  const tpRubricBlockEls = childrenByTag(tp, 'rubricBlock');
@@ -926,6 +1052,8 @@ export class ReferenceBackendAdapter {
926
1052
  const sections = await parseSectionsForTestPart(tp);
927
1053
  testParts.push({
928
1054
  identifier: tpIdentifier,
1055
+ navigationMode: tpNavigationMode,
1056
+ submissionMode: tpSubmissionMode,
929
1057
  sections,
930
1058
  rubricBlocks: tpRubricBlocks,
931
1059
  itemSessionControl: tpItemSessionControl,
@@ -948,6 +1076,8 @@ export class ReferenceBackendAdapter {
948
1076
  if (topSections.length > 0) {
949
1077
  testParts.push({
950
1078
  identifier: 'part-1',
1079
+ navigationMode,
1080
+ submissionMode,
951
1081
  sections: topSections,
952
1082
  });
953
1083
  }
@@ -961,6 +1091,7 @@ export class ReferenceBackendAdapter {
961
1091
  timeLimits,
962
1092
  outcomeDeclarations: outcomeDeclarations.length > 0 ? outcomeDeclarations : undefined,
963
1093
  outcomeProcessingXml,
1094
+ testFeedback: testFeedback.length > 0 ? testFeedback : undefined,
964
1095
  baseUrl,
965
1096
  };
966
1097
  }
@@ -995,11 +1126,21 @@ export class ReferenceBackendAdapter {
995
1126
  }
996
1127
  getItemOrder(assessment) {
997
1128
  const out = [];
1129
+ const visit = (section) => {
1130
+ const components = section.children ?? [
1131
+ ...(section.assessmentItemRefs ?? []).map((item) => ({ type: 'item', item })),
1132
+ ...(section.sections ?? []).map((child) => ({ type: 'section', section: child })),
1133
+ ];
1134
+ for (const component of components) {
1135
+ if (component.type === 'item')
1136
+ out.push(component.item.identifier);
1137
+ else
1138
+ visit(component.section);
1139
+ }
1140
+ };
998
1141
  for (const part of assessment.testParts || []) {
999
1142
  for (const section of part.sections || []) {
1000
- for (const item of section.assessmentItemRefs || []) {
1001
- out.push(item.identifier);
1002
- }
1143
+ visit(section);
1003
1144
  }
1004
1145
  }
1005
1146
  return out;
@@ -1198,7 +1339,7 @@ export class ReferenceBackendAdapter {
1198
1339
  }
1199
1340
  else {
1200
1341
  // No duplicates - shuffle and take first N
1201
- const shuffled = [...filteredItems].sort(() => Math.random() - 0.5);
1342
+ const shuffled = shuffleArray(filteredItems, Math.random);
1202
1343
  return shuffled.slice(0, Math.min(count, shuffled.length));
1203
1344
  }
1204
1345
  }
@@ -1222,4 +1363,20 @@ export class ReferenceBackendAdapter {
1222
1363
  return new Promise((resolve) => setTimeout(resolve, ms));
1223
1364
  }
1224
1365
  }
1366
+ /**
1367
+ * Fisher-Yates shuffle using a provided RNG (returns a new array).
1368
+ *
1369
+ * Mirrors the helper of the same name in `core/AssessmentPlayer.ts`. Replaces a
1370
+ * `sort(() => Math.random() - 0.5)` comparator, which is not a uniform shuffle: the
1371
+ * comparator is inconsistent, so the result depends on the sort algorithm and leaves
1372
+ * elements biased toward their original positions.
1373
+ */
1374
+ function shuffleArray(arr, rng) {
1375
+ const out = [...arr];
1376
+ for (let i = out.length - 1; i > 0; i--) {
1377
+ const j = Math.floor(rng() * (i + 1));
1378
+ [out[i], out[j]] = [out[j], out[i]];
1379
+ }
1380
+ return out;
1381
+ }
1225
1382
  //# sourceMappingURL=ReferenceBackendAdapter.js.map