@learnosity/lib-qti-converter 0.12.7 → 0.13.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.
Files changed (38) hide show
  1. package/docs/GETTING_STARTED.md +71 -18
  2. package/docs/LEARNOSITY_BUNDLE_FORMAT.md +23 -7
  3. package/package.json +8 -8
  4. package/packages/cli/dist/{batchProcessors-DU1HwpHY.js → batchProcessors-DgiDpfpP.js} +271 -77
  5. package/packages/cli/dist/batchProcessors-DgiDpfpP.js.map +1 -0
  6. package/packages/cli/dist/batchWorker.js +1 -1
  7. package/packages/cli/dist/{create-prompt-DU9wLVhI.js → create-prompt-DyNnKXYU.js} +63 -53
  8. package/packages/cli/dist/create-prompt-DyNnKXYU.js.map +1 -0
  9. package/packages/cli/dist/{dist-DjpU2mIj.js → dist-D3v6G5F8.js} +6 -6
  10. package/packages/cli/dist/{dist-DjpU2mIj.js.map → dist-D3v6G5F8.js.map} +1 -1
  11. package/packages/cli/dist/{learnosityToQti-BSbH3jyx.js → learnosityToQti-CIj5603P.js} +4 -4
  12. package/packages/cli/dist/{learnosityToQti-BSbH3jyx.js.map → learnosityToQti-CIj5603P.js.map} +1 -1
  13. package/packages/cli/dist/{learnosityToQtiPackage-B0xRzYmy.js → learnosityToQtiPackage-n6nGGr32.js} +7 -7
  14. package/packages/cli/dist/{learnosityToQtiPackage-B0xRzYmy.js.map → learnosityToQtiPackage-n6nGGr32.js.map} +1 -1
  15. package/packages/cli/dist/main.js +5 -5
  16. package/packages/cli/dist/{nodeFileAccess-BkzSHCOh.js → nodeFileAccess-BhCoGDOi.js} +6 -3
  17. package/packages/cli/dist/{nodeFileAccess-BkzSHCOh.js.map → nodeFileAccess-BhCoGDOi.js.map} +1 -1
  18. package/packages/cli/dist/{pathUtils-B9yPTlVF.js → pathUtils-mTQZ0wYS.js} +36 -20
  19. package/packages/cli/dist/pathUtils-mTQZ0wYS.js.map +1 -0
  20. package/packages/cli/dist/{qtiPackageToLearnosity-C7JaaUDU.js → qtiPackageToLearnosity-B4cD8jUw.js} +13 -7
  21. package/packages/cli/dist/qtiPackageToLearnosity-B4cD8jUw.js.map +1 -0
  22. package/packages/cli/dist/{qtiToLearnosity-CYoG2aIX.js → qtiToLearnosity-DDjcpShJ.js} +7 -6
  23. package/packages/cli/dist/qtiToLearnosity-DDjcpShJ.js.map +1 -0
  24. package/packages/cli/dist/{resolveOptions-CW80R2EQ.js → resolveOptions-Czapkfc1.js} +22 -8
  25. package/packages/cli/dist/resolveOptions-Czapkfc1.js.map +1 -0
  26. package/packages/cli/dist/{table-DjOn2Tsk.js → table-DTSv0atR.js} +619 -236
  27. package/packages/cli/dist/table-DTSv0atR.js.map +1 -0
  28. package/packages/core/dist/index.d.ts +197 -184
  29. package/packages/core/dist/index.js +858 -303
  30. package/packages/core/dist/node.d.ts +211 -196
  31. package/packages/core/dist/node.js +889 -310
  32. package/packages/cli/dist/batchProcessors-DU1HwpHY.js.map +0 -1
  33. package/packages/cli/dist/create-prompt-DU9wLVhI.js.map +0 -1
  34. package/packages/cli/dist/pathUtils-B9yPTlVF.js.map +0 -1
  35. package/packages/cli/dist/qtiPackageToLearnosity-C7JaaUDU.js.map +0 -1
  36. package/packages/cli/dist/qtiToLearnosity-CYoG2aIX.js.map +0 -1
  37. package/packages/cli/dist/resolveOptions-CW80R2EQ.js.map +0 -1
  38. package/packages/cli/dist/table-DjOn2Tsk.js.map +0 -1
@@ -144,6 +144,9 @@ const DiagnosticCode = {
144
144
  QTI_PACKAGE_NO_CONTENT: "QTI_PACKAGE_NO_CONTENT",
145
145
  QTI_PACKAGE_DUPLICATE_IDENTIFIER: "QTI_PACKAGE_DUPLICATE_IDENTIFIER",
146
146
  QTI_ITEM_CONVERSION_FAILED: "QTI_ITEM_CONVERSION_FAILED",
147
+ QTI_ASSET_HREF_UNSAFE: "QTI_ASSET_HREF_UNSAFE",
148
+ QTI_ASSET_FILENAME_CONFLICT: "QTI_ASSET_FILENAME_CONFLICT",
149
+ QTI_ASSET_IDENTITY_BYTES_CONFLICT: "QTI_ASSET_IDENTITY_BYTES_CONFLICT",
147
150
  LRN_BUNDLE_WRITTEN: "LRN_BUNDLE_WRITTEN",
148
151
  QTI_DOWNGRADE_NAMESPACE: "QTI_DOWNGRADE_NAMESPACE",
149
152
  QTI_DOWNGRADE_SCHEMA_LOCATION: "QTI_DOWNGRADE_SCHEMA_LOCATION",
@@ -5737,14 +5740,14 @@ var DomHandler = class {
5737
5740
  //#endregion
5738
5741
  //#region ../../node_modules/.pnpm/entities@4.5.0/node_modules/entities/lib/esm/escape.js
5739
5742
  const xmlReplacer = /["&'<>$\x80-\uFFFF]/g;
5740
- const xmlCodeMap$1 = /* @__PURE__ */ new Map([
5743
+ const xmlCodeMap = /* @__PURE__ */ new Map([
5741
5744
  [34, "&quot;"],
5742
5745
  [38, "&amp;"],
5743
5746
  [39, "&apos;"],
5744
5747
  [60, "&lt;"],
5745
5748
  [62, "&gt;"]
5746
5749
  ]);
5747
- const getCodePoint$1 = String.prototype.codePointAt != null ? (str, index) => str.codePointAt(index) : (c, index) => (c.charCodeAt(index) & 64512) === 55296 ? (c.charCodeAt(index) - 55296) * 1024 + c.charCodeAt(index + 1) - 56320 + 65536 : c.charCodeAt(index);
5750
+ const getCodePoint = String.prototype.codePointAt != null ? (str, index) => str.codePointAt(index) : (c, index) => (c.charCodeAt(index) & 64512) === 55296 ? (c.charCodeAt(index) - 55296) * 1024 + c.charCodeAt(index + 1) - 56320 + 65536 : c.charCodeAt(index);
5748
5751
  /**
5749
5752
  * Encodes all non-ASCII characters, as well as characters not valid in XML
5750
5753
  * documents using XML entities.
@@ -5759,12 +5762,12 @@ function encodeXML$1(str) {
5759
5762
  while ((match = xmlReplacer.exec(str)) !== null) {
5760
5763
  const i = match.index;
5761
5764
  const char = str.charCodeAt(i);
5762
- const next = xmlCodeMap$1.get(char);
5765
+ const next = xmlCodeMap.get(char);
5763
5766
  if (next !== void 0) {
5764
5767
  ret += str.substring(lastIdx, i) + next;
5765
5768
  lastIdx = i + 1;
5766
5769
  } else {
5767
- ret += `${str.substring(lastIdx, i)}&#x${getCodePoint$1(str, i).toString(16)};`;
5770
+ ret += `${str.substring(lastIdx, i)}&#x${getCodePoint(str, i).toString(16)};`;
5768
5771
  lastIdx = xmlReplacer.lastIndex += Number((char & 64512) === 55296);
5769
5772
  }
5770
5773
  }
@@ -5780,7 +5783,7 @@ function encodeXML$1(str) {
5780
5783
  * @returns Function that escapes all characters matched by the given regular
5781
5784
  * expression using the given map of characters to escape to their entities.
5782
5785
  */
5783
- function getEscaper$1(regex, map) {
5786
+ function getEscaper(regex, map) {
5784
5787
  return function escape(data) {
5785
5788
  let match;
5786
5789
  let lastIdx = 0;
@@ -5799,7 +5802,7 @@ function getEscaper$1(regex, map) {
5799
5802
  *
5800
5803
  * @param data String to escape.
5801
5804
  */
5802
- const escapeAttribute$1 = getEscaper$1(/["&\u00A0]/g, /* @__PURE__ */ new Map([
5805
+ const escapeAttribute$1 = getEscaper(/["&\u00A0]/g, /* @__PURE__ */ new Map([
5803
5806
  [34, "&quot;"],
5804
5807
  [38, "&amp;"],
5805
5808
  [160, "&nbsp;"]
@@ -5810,7 +5813,7 @@ const escapeAttribute$1 = getEscaper$1(/["&\u00A0]/g, /* @__PURE__ */ new Map([
5810
5813
  *
5811
5814
  * @param data String to escape.
5812
5815
  */
5813
- const escapeText$1 = getEscaper$1(/[&<>\u00A0]/g, /* @__PURE__ */ new Map([
5816
+ const escapeText$1 = getEscaper(/[&<>\u00A0]/g, /* @__PURE__ */ new Map([
5814
5817
  [38, "&amp;"],
5815
5818
  [60, "&lt;"],
5816
5819
  [62, "&gt;"],
@@ -8873,93 +8876,116 @@ function getElementsByTagType(type, nodes, recurse = true, limit = Number.POSITI
8873
8876
  return filter(Checks["tag_type"](type), nodes, recurse, limit);
8874
8877
  }
8875
8878
  //#endregion
8876
- //#region ../../node_modules/.pnpm/entities@8.0.0/node_modules/entities/dist/escape.js
8877
- const xmlCodeMap = /* @__PURE__ */ new Map([
8878
- [34, "&quot;"],
8879
- [38, "&amp;"],
8880
- [39, "&apos;"],
8881
- [60, "&lt;"],
8882
- [62, "&gt;"]
8883
- ]);
8879
+ //#region ../../node_modules/.pnpm/entities@8.1.0/node_modules/entities/dist/escape.js
8884
8880
  /**
8885
- * Read a code point at a given index.
8886
- * @param input Input string to encode or decode.
8887
- * @param index Current read position in the input string.
8881
+ * Get the named reference for an XML special character or U+00A0.
8882
+ * @param char Code unit matched by one of the escape regexes.
8888
8883
  */
8889
- const getCodePoint = typeof String.prototype.codePointAt === "function" ? (input, index) => input.codePointAt(index) : (c, index) => (c.charCodeAt(index) & 64512) === 55296 ? (c.charCodeAt(index) - 55296) * 1024 + c.charCodeAt(index + 1) - 56320 + 65536 : c.charCodeAt(index);
8884
+ function getEscape(char) {
8885
+ return char === 34 ? "&quot;" : char === 38 ? "&amp;" : char === 39 ? "&apos;" : char === 60 ? "&lt;" : char === 62 ? "&gt;" : "&nbsp;";
8886
+ }
8887
+ /**
8888
+ * Matches exactly the characters `encodeXML` escapes: the five XML special
8889
+ * characters plus every non-ASCII code unit (lone surrogates included — no
8890
+ * `u` flag). Kept in sync with `XML_BITSET_VALUE`.
8891
+ *
8892
+ * Shared with `encodeNonAsciiHTML` in `encode.ts`. Because the regex is
8893
+ * stateful (`g` flag), every call site must set `lastIndex` before use.
8894
+ */
8895
+ const xmlEncodeRegex = /["&'<>\u0080-\uFFFF]/g;
8896
+ /**
8897
+ * Whether `code` (a UTF-16 code unit) is escaped by {@link encodeXML}: a
8898
+ * non-ASCII unit, or one of the five XML specials flagged in
8899
+ * `XML_BITSET_VALUE` (which is only meaningful for code units 32-63).
8900
+ * @param code Code unit to test.
8901
+ */
8902
+ function isXmlEscapable(code) {
8903
+ return code >= 128 || code >= 32 && code < 64 && (1342177476 >>> code & 1) === 1;
8904
+ }
8890
8905
  /**
8891
8906
  * Encodes all non-ASCII characters, as well as characters not valid in XML
8892
- * documents using XML entities. Uses a fast bitset scan instead of RegExp.
8907
+ * documents using XML entities.
8893
8908
  *
8894
8909
  * If a character has no equivalent entity, a numeric hexadecimal reference
8895
8910
  * (eg. `&#xfc;`) will be used.
8896
- * @param input Input string to encode or decode.
8911
+ * @param input Input string to encode.
8897
8912
  */
8898
8913
  function encodeXML(input) {
8914
+ const { length } = input;
8899
8915
  let out;
8900
8916
  let last = 0;
8901
- const { length } = input;
8902
- for (let index = 0; index < length; index++) {
8917
+ let index = 0;
8918
+ while (index < length) {
8903
8919
  const char = input.charCodeAt(index);
8904
- if (char < 128 && ((1342177476 >>> char & 1) === 0 || char >= 64 || char < 32)) continue;
8920
+ if (!isXmlEscapable(char)) {
8921
+ const bound = Math.min(index + 32, length);
8922
+ let next = index + 1;
8923
+ while (next < bound && !isXmlEscapable(input.charCodeAt(next))) next++;
8924
+ if (next < bound) {
8925
+ index = next;
8926
+ continue;
8927
+ }
8928
+ if (next >= length) break;
8929
+ xmlEncodeRegex.lastIndex = next;
8930
+ if (!xmlEncodeRegex.test(input)) break;
8931
+ index = xmlEncodeRegex.lastIndex - 1;
8932
+ continue;
8933
+ }
8905
8934
  if (out === void 0) out = input.substring(0, index);
8906
8935
  else if (last !== index) out += input.substring(last, index);
8907
8936
  if (char < 64) {
8908
- out += xmlCodeMap.get(char);
8909
- last = index + 1;
8937
+ out += getEscape(char);
8938
+ last = index += 1;
8910
8939
  continue;
8911
8940
  }
8912
- const cp = getCodePoint(input, index);
8941
+ const cp = input.codePointAt(index);
8913
8942
  out += `&#x${cp.toString(16)};`;
8914
8943
  if (cp !== char) index++;
8915
- last = index + 1;
8944
+ last = index += 1;
8916
8945
  }
8917
8946
  if (out === void 0) return input;
8918
8947
  if (last < length) out += input.substr(last);
8919
8948
  return out;
8920
8949
  }
8921
8950
  /**
8922
- * Creates a function that escapes all characters matched by the given regular
8923
- * expression using the given map of characters to escape to their entities.
8924
- * @param regex Regular expression to match characters to escape.
8925
- * @param map Map of characters to escape to their entities.
8926
- * @returns Function that escapes all characters matched by the given regular
8927
- * expression using the given map of characters to escape to their entities.
8951
+ * Escape `data` using `re`, mapping each matched character to its entity.
8952
+ * Every match is one UTF-16 code unit, so its index is `lastIndex - 1`.
8953
+ * @param re Global regex matching exactly the characters to escape
8954
+ * (`"`, `&`, `'`, `<`, `>`, `\u00A0` at most).
8955
+ * @param data String to escape.
8928
8956
  */
8929
- function getEscaper(regex, map) {
8930
- return function escape(data) {
8931
- let match;
8932
- let lastIndex = 0;
8933
- let result = "";
8934
- while (match = regex.exec(data)) {
8935
- if (lastIndex !== match.index) result += data.substring(lastIndex, match.index);
8936
- result += map.get(match[0].charCodeAt(0));
8937
- lastIndex = match.index + 1;
8938
- }
8939
- return result + data.substring(lastIndex);
8940
- };
8957
+ function escapeWithRegex(re, data) {
8958
+ re.lastIndex = 0;
8959
+ if (!re.test(data)) return data;
8960
+ let out = "";
8961
+ let last = 0;
8962
+ do {
8963
+ const index = re.lastIndex - 1;
8964
+ if (last !== index) out += data.substring(last, index);
8965
+ const char = data.charCodeAt(index);
8966
+ out += getEscape(char);
8967
+ last = index + 1;
8968
+ } while (re.test(data));
8969
+ return out + data.substring(last);
8941
8970
  }
8971
+ const attributeEscapeRegex = /["&\u{A0}]/gu;
8942
8972
  /**
8943
8973
  * Encodes all characters that have to be escaped in HTML attributes,
8944
8974
  * following {@link https://html.spec.whatwg.org/multipage/parsing.html#escapingString}.
8945
8975
  * @param data String to escape.
8946
8976
  */
8947
- const escapeAttribute = /* #__PURE__ */ getEscaper(/["&\u00A0]/g, /* @__PURE__ */ new Map([
8948
- [34, "&quot;"],
8949
- [38, "&amp;"],
8950
- [160, "&nbsp;"]
8951
- ]));
8977
+ function escapeAttribute(data) {
8978
+ return escapeWithRegex(attributeEscapeRegex, data);
8979
+ }
8980
+ const textEscapeRegex = /[&<>\u{A0}]/gu;
8952
8981
  /**
8953
8982
  * Encodes all characters that have to be escaped in HTML text,
8954
8983
  * following {@link https://html.spec.whatwg.org/multipage/parsing.html#escapingString}.
8955
8984
  * @param data String to escape.
8956
8985
  */
8957
- const escapeText = /* #__PURE__ */ getEscaper(/[&<>\u00A0]/g, /* @__PURE__ */ new Map([
8958
- [38, "&amp;"],
8959
- [60, "&lt;"],
8960
- [62, "&gt;"],
8961
- [160, "&nbsp;"]
8962
- ]));
8986
+ function escapeText(data) {
8987
+ return escapeWithRegex(textEscapeRegex, data);
8988
+ }
8963
8989
  //#endregion
8964
8990
  //#region ../../node_modules/.pnpm/dom-serializer@3.1.1/node_modules/dom-serializer/dist/foreign-names.js
8965
8991
  /**
@@ -22873,6 +22899,33 @@ function md5hex(input) {
22873
22899
  return hex;
22874
22900
  }
22875
22901
  //#endregion
22902
+ //#region ../core/src/qti-to-learnosity/utils/mediaFeature.ts
22903
+ /**
22904
+ * Build a stable UUID-shaped identifier for a media feature.
22905
+ *
22906
+ * Feature output must remain identical for equivalent directory and ZIP
22907
+ * package conversions, so the identifier is derived from the final media URL
22908
+ * rather than generated randomly. The UUID version and variant bits are set
22909
+ * to keep the value compatible with consumers expecting a v4-shaped UUID.
22910
+ */
22911
+ function buildMediaFeatureId(transformedUrl) {
22912
+ const hash = md5hex(transformedUrl).split("");
22913
+ const variant = [
22914
+ "8",
22915
+ "9",
22916
+ "a",
22917
+ "b"
22918
+ ][parseInt(hash[16], 16) & 3];
22919
+ hash[12] = "4";
22920
+ hash[16] = variant;
22921
+ return `${hash.slice(0, 8).join("")}-${hash.slice(8, 12).join("")}-${hash.slice(12, 16).join("")}-${hash.slice(16, 20).join("")}-${hash.slice(20).join("")}`;
22922
+ }
22923
+ /** Build a Learnosity simple-feature span for audio or hosted video. */
22924
+ function buildMediaFeatureSpan(transformedUrl, kind, featureId = buildMediaFeatureId(transformedUrl)) {
22925
+ if (kind === "audio") return `<span class="learnosity-feature" data-player="button" data-simplefeature_id="${featureId}" data-src="${transformedUrl}" data-type="audioplayer"></span>`;
22926
+ return `<span class="learnosity-feature" data-player_type="hosted-video" data-simplefeature_id="${featureId}" data-src="${transformedUrl}" data-text_alternative.caption.src="" data-type="videoplayer"></span>`;
22927
+ }
22928
+ //#endregion
22876
22929
  //#region ../core/src/qti-to-learnosity/utils/convertObjectElement.ts
22877
22930
  /**
22878
22931
  * Convert QTI <object> elements to appropriate Learnosity HTML elements
@@ -22924,7 +22977,7 @@ function buildDeterministicFeatureId(transformedUrl) {
22924
22977
  * <object data="video.mp4" type="video/mp4"/>
22925
22978
  * → <span class="learnosity-feature" data-player_type="hosted-video" data-simplefeature_id="..." data-src="[cdn-url]" data-text_alternative.caption.src="" data-type="videoplayer"></span>
22926
22979
  */
22927
- function convertObjectToElement(objectTag, organisationId, mediaVault = false, customAssetUrl) {
22980
+ function convertObjectToElement(objectTag, organisationId, mediaVault = false, customAssetUrl, assetContext = {}) {
22928
22981
  const dataMatch = objectTag.match(/data=["']([^"']+)["']/i);
22929
22982
  const srcMatch = objectTag.match(/src=["']([^"']+)["']/i);
22930
22983
  const typeMatch = objectTag.match(/type=["']([^"']+)["']/i);
@@ -22934,11 +22987,11 @@ function convertObjectToElement(objectTag, organisationId, mediaVault = false, c
22934
22987
  if (!urlMatch) return objectTag;
22935
22988
  const sourceUrl = urlMatch[1];
22936
22989
  const category = getMimeTypeCategory(typeMatch ? typeMatch[1] : "");
22937
- const transformedUrl = transformUrl(sourceUrl, organisationId, mediaVault, customAssetUrl);
22990
+ const transformedUrl = transformUrl(sourceUrl, organisationId, mediaVault, customAssetUrl, assetContext);
22938
22991
  switch (category) {
22939
22992
  case "image": return buildImageTag(transformedUrl, heightMatch, widthMatch);
22940
- case "audio": return `<span class="learnosity-feature" data-player="button" data-simplefeature_id="${buildDeterministicFeatureId(transformedUrl)}" data-src="${transformedUrl}" data-type="audioplayer"></span>`;
22941
- case "video": return `<span class="learnosity-feature" data-player_type="hosted-video" data-simplefeature_id="${buildDeterministicFeatureId(transformedUrl)}" data-src="${transformedUrl}" data-text_alternative.caption.src="" data-type="videoplayer"></span>`;
22993
+ case "audio": return buildMediaFeatureSpan(transformedUrl, "audio", buildDeterministicFeatureId(transformedUrl));
22994
+ case "video": return buildMediaFeatureSpan(transformedUrl, "video", buildDeterministicFeatureId(transformedUrl));
22942
22995
  default: return objectTag.replace(sourceUrl, transformedUrl);
22943
22996
  }
22944
22997
  }
@@ -22982,55 +23035,139 @@ function normalizeTableClass(html) {
22982
23035
  });
22983
23036
  }
22984
23037
  //#endregion
22985
- //#region ../core/src/qti-to-learnosity/utils/assetUrlTransform.ts
23038
+ //#region ../core/src/qti-to-learnosity/utils/assetIdentity.ts
22986
23039
  /**
22987
- * Asset URL transformation for Learnosity CDN
22988
- * TASK 030
23040
+ * Browser-safe helpers for identifying package-local QTI assets.
22989
23041
  *
22990
- * Transforms asset URLs in HTML content to use Learnosity CDN URLs.
23042
+ * QTI asset references are package-relative paths, not filesystem paths. Keeping
23043
+ * their canonical form here makes directory and ZIP inputs produce the same
23044
+ * identity while rejecting references that could escape the package root.
23045
+ */
23046
+ /** Asset extensions copied and rewritten by QTI → Learnosity conversion. */
23047
+ const QTI_ASSET_EXTENSIONS = [
23048
+ ".png",
23049
+ ".jpg",
23050
+ ".jpeg",
23051
+ ".gif",
23052
+ ".svg",
23053
+ ".webp",
23054
+ ".bmp",
23055
+ ".ico",
23056
+ ".mp3",
23057
+ ".mp4",
23058
+ ".wav",
23059
+ ".ogg",
23060
+ ".webm",
23061
+ ".ogv",
23062
+ ".m4a",
23063
+ ".m4v",
23064
+ ".css",
23065
+ ".woff",
23066
+ ".woff2",
23067
+ ".ttf",
23068
+ ".eot",
23069
+ ".pdf",
23070
+ ".json"
23071
+ ];
23072
+ function isSupportedQtiAssetPath(path) {
23073
+ const lowerPath = path.toLowerCase();
23074
+ return !lowerPath.endsWith(".html") && !lowerPath.endsWith(".htm") && QTI_ASSET_EXTENSIONS.some((extension) => lowerPath.endsWith(extension));
23075
+ }
23076
+ function isUnsafeQtiAssetHrefError(error) {
23077
+ return error instanceof Error && (error.message.startsWith("Unsafe QTI asset href:") || error.message.startsWith("QTI asset href has no filename:"));
23078
+ }
23079
+ /**
23080
+ * Canonicalize a package-relative QTI asset href.
23081
+ *
23082
+ * Query strings and fragments are URL metadata and do not identify a different
23083
+ * package asset. Path separators are normalized to `/`, dot segments are
23084
+ * resolved, and traversal above the package root is rejected.
22991
23085
  */
23086
+ function stripHrefMetadata(href) {
23087
+ const metadataStart = href.search(/[?#]/);
23088
+ return (metadataStart === -1 ? href : href.slice(0, metadataStart)).replaceAll("\\", "/");
23089
+ }
23090
+ function assertPackageRelativePath(path, href) {
23091
+ const isAbsolute = path.startsWith("/") || /^[A-Za-z]:/.test(path) || /^[A-Za-z][A-Za-z\d+.-]*:/.test(path);
23092
+ if (!path || path.includes("\0") || isAbsolute) throw new Error(`Unsafe QTI asset href: ${href}`);
23093
+ if (path.endsWith("/")) throw new Error(`QTI asset href has no filename: ${href}`);
23094
+ }
23095
+ function normalizePathSegments(path, href) {
23096
+ const segments = [];
23097
+ for (const segment of path.split("/")) {
23098
+ if (!segment || segment === ".") continue;
23099
+ if (segment === "..") {
23100
+ if (segments.length === 0) throw new Error(`Unsafe QTI asset href: ${href}`);
23101
+ segments.pop();
23102
+ continue;
23103
+ }
23104
+ segments.push(segment);
23105
+ }
23106
+ if (segments.length === 0) throw new Error(`QTI asset href has no filename: ${href}`);
23107
+ return segments.join("/");
23108
+ }
23109
+ function canonicalizeQtiAssetHref(href) {
23110
+ if (typeof href !== "string") throw new TypeError("QTI asset href must be a string");
23111
+ const path = stripHrefMetadata(href);
23112
+ assertPackageRelativePath(path, href);
23113
+ return normalizePathSegments(path, href);
23114
+ }
23115
+ /** Return the final filename from a canonicalized package-relative href. */
23116
+ function extractQtiAssetBasename(href) {
23117
+ const canonicalHref = canonicalizeQtiAssetHref(href);
23118
+ return canonicalHref.slice(canonicalHref.lastIndexOf("/") + 1);
23119
+ }
22992
23120
  /**
22993
- * Supported asset file extensions
22994
- */
22995
- const SUPPORTED_EXTENSIONS = /* @__PURE__ */ new Set([
22996
- "jpg",
22997
- "jpeg",
22998
- "png",
22999
- "gif",
23000
- "svg",
23001
- "webp",
23002
- "mp3",
23003
- "wav",
23004
- "ogg",
23005
- "m4a",
23006
- "mp4",
23007
- "webm",
23008
- "ogv",
23009
- "m4v"
23010
- ]);
23121
+ * Return the final filename extension, including its leading dot.
23122
+ * Dotfiles and filenames ending in a dot have no extension.
23123
+ */
23124
+ function extractQtiAssetExtension(href) {
23125
+ const basename = extractQtiAssetBasename(href);
23126
+ const extensionStart = basename.lastIndexOf(".");
23127
+ return extensionStart > 0 && extensionStart < basename.length - 1 ? basename.slice(extensionStart) : "";
23128
+ }
23011
23129
  /**
23012
- * Patterns that detect any asset reference in HTML (object[data] or
23013
- * img/audio/video/source[src]). Precompiled once; used only with
23014
- * `RegExp.prototype.test` on non-global regexes, so they are safe to share.
23130
+ * Serialize the item-scoped asset identity using an ordered JSON tuple.
23131
+ *
23132
+ * JSON serialization is intentional: unlike delimiter-based concatenation, it
23133
+ * keeps the item reference and canonical href unambiguous when either value
23134
+ * contains punctuation that could otherwise be mistaken for a separator.
23015
23135
  */
23016
- const ASSET_REFERENCE_PATTERNS = [
23017
- /<object\s+[^>]*data=/i,
23018
- /<img\s+[^>]*src=/i,
23019
- /<audio\s+[^>]*src=/i,
23020
- /<video\s+[^>]*src=/i,
23021
- /<source\s+[^>]*src=/i
23022
- ];
23023
- /** Matches `<object ...>` (optionally with its closing tag) for element conversion. */
23024
- const OBJECT_TAG_PATTERN = /<object\s+[^>]*>(?:<\/object>)?/gi;
23136
+ function serializeQtiAssetIdentity(finalItemReference, qtiAssetHref) {
23137
+ const canonicalHref = canonicalizeQtiAssetHref(qtiAssetHref);
23138
+ return JSON.stringify([finalItemReference, canonicalHref]);
23139
+ }
23140
+ /** Derive the lowercase MD5 hex hash for a canonical item-scoped identity. */
23141
+ function hashQtiAssetIdentity(finalItemReference, qtiAssetHref) {
23142
+ return md5hex(serializeQtiAssetIdentity(finalItemReference, qtiAssetHref));
23143
+ }
23025
23144
  /**
23026
- * src-attribute capture pattern for media elements (img/audio/video/source).
23145
+ * Select the output filename for a package-local QTI asset.
23027
23146
  *
23028
- * Hardcoded literal (rather than built with `new RegExp`) so the pattern cannot
23029
- * be influenced at runtime. Global regex used only with
23030
- * `String.prototype.replace`, which resets lastIndex on completion, so sharing
23031
- * a single compiled instance across calls is safe.
23147
+ * Hashed naming is the default so the full item-scoped identity, rather than a
23148
+ * globally ambiguous source basename, determines the output name. Only the
23149
+ * canonical source extension is retained after the digest. Preserve mode is
23150
+ * an explicit compatibility opt-out and returns the canonical final basename.
23032
23151
  */
23033
- const MEDIA_SRC_PATTERN = /(<(?:img|audio|video|source)\s+[^>]*src=["'])([^"']+)(["'][^>]*>)/gi;
23152
+ function selectQtiAssetFilename(finalItemReference, qtiAssetHref, preserveAssetFilenames = false) {
23153
+ const canonicalHref = canonicalizeQtiAssetHref(qtiAssetHref);
23154
+ if (preserveAssetFilenames) return extractQtiAssetBasename(canonicalHref);
23155
+ return `${hashQtiAssetIdentity(finalItemReference, canonicalHref)}${extractQtiAssetExtension(canonicalHref)}`;
23156
+ }
23157
+ //#endregion
23158
+ //#region ../core/src/qti-to-learnosity/utils/assetUrlTransform.ts
23159
+ /**
23160
+ * Asset URL transformation for Learnosity CDN
23161
+ * TASK 030
23162
+ *
23163
+ * Transforms asset URLs in HTML content to use Learnosity CDN URLs.
23164
+ */
23165
+ /** Matches supported asset-bearing HTML attributes on any element. */
23166
+ const ASSET_ATTRIBUTE_PATTERN = /(<[A-Za-z][^>]*?\b(?:src|data|href)\s*=\s*["'])([^"']+)(["'][^>]*>)/gi;
23167
+ /** Matches <object ...> (optionally with its closing tag) for element conversion. */
23168
+ const OBJECT_TAG_PATTERN = /<object\s+[^>]*>(?:<\/object>)?/gi;
23169
+ /** Matches anchors whose href points to inline audio/video media. */
23170
+ const INLINE_MEDIA_LINK_PATTERN = /<a\b([^>]*?)\bhref\s*=\s*(["'])([^"']+)\2([^>]*)>([\s\S]*?)<\/a\s*>/gi;
23034
23171
  /**
23035
23172
  * Extract filename from a URL path
23036
23173
  * Examples:
@@ -23042,12 +23179,26 @@ function extractFilename$2(url) {
23042
23179
  const segments = url.split("?")[0].split("#")[0].split("/");
23043
23180
  return segments[segments.length - 1];
23044
23181
  }
23045
- /**
23046
- * Check if a filename has a supported asset extension
23047
- */
23048
23182
  function isSupportedAsset(filename) {
23049
- const ext = filename.split(".").pop()?.toLowerCase();
23050
- return ext ? SUPPORTED_EXTENSIONS.has(ext) : false;
23183
+ return isSupportedQtiAssetPath(filename);
23184
+ }
23185
+ function getInlineMediaKind(url, attributes) {
23186
+ const mimeType = attributes.match(/\btype\s*=\s*(["'])([^"']+)\1/i)?.[2].toLowerCase();
23187
+ if (mimeType?.startsWith("audio/")) return "audio";
23188
+ if (mimeType?.startsWith("video/")) return "video";
23189
+ const filename = extractFilename$2(url).toLowerCase();
23190
+ if ([
23191
+ ".mp3",
23192
+ ".wav",
23193
+ ".ogg",
23194
+ ".m4a"
23195
+ ].some((extension) => filename.endsWith(extension))) return "audio";
23196
+ if ([
23197
+ ".mp4",
23198
+ ".webm",
23199
+ ".ogv",
23200
+ ".m4v"
23201
+ ].some((extension) => filename.endsWith(extension))) return "video";
23051
23202
  }
23052
23203
  /**
23053
23204
  * Build Learnosity CDN URL for an asset
@@ -23057,17 +23208,24 @@ function buildLearnosityAssetUrl(filename, organisationId, mediaVault = false, c
23057
23208
  if (customAssetUrl) return `${customAssetUrl.endsWith("/") ? customAssetUrl.slice(0, -1) : customAssetUrl}/${filename}`;
23058
23209
  return `https://${mediaVault ? "media-vault" : "assets"}.learnosity.com/organisations/${organisationId}/${filename}`;
23059
23210
  }
23211
+ function resolveQtiAssetHref(url, sourceHrefBase) {
23212
+ const normalizedUrl = url.split(/[?#]/, 1)[0].replaceAll("\\", "/");
23213
+ const isItemRelative = /^\.\.?\//.test(normalizedUrl) || !normalizedUrl.includes("/");
23214
+ if (!sourceHrefBase || !isItemRelative) return canonicalizeQtiAssetHref(url);
23215
+ const baseHref = canonicalizeQtiAssetHref(sourceHrefBase);
23216
+ return canonicalizeQtiAssetHref(`${baseHref.slice(0, baseHref.lastIndexOf("/") + 1)}${normalizedUrl}`);
23217
+ }
23060
23218
  /**
23061
23219
  * Transform a single URL to Learnosity CDN format
23062
23220
  * Exported for use in image object source fields
23063
23221
  */
23064
- function transformUrl(url, organisationId, mediaVault = false, customAssetUrl) {
23222
+ function transformUrl(url, organisationId, mediaVault = false, customAssetUrl, context = {}) {
23065
23223
  if (url.includes("assets.learnosity.com") || url.includes("media-vault.learnosity.com")) return url;
23066
- if (url.match(/^https?:\/\//i)) return url;
23224
+ if (/^https?:\/\//i.test(url) || url.startsWith("//")) return url;
23067
23225
  if (url.startsWith("data:")) return url;
23068
23226
  const filename = extractFilename$2(url);
23069
23227
  if (!isSupportedAsset(filename)) return url;
23070
- return buildLearnosityAssetUrl(filename, organisationId, mediaVault, customAssetUrl);
23228
+ return buildLearnosityAssetUrl(context.finalItemReference ? selectQtiAssetFilename(context.finalItemReference, resolveQtiAssetHref(url, context.sourceHrefBase), context.preserveAssetFilenames ?? false) : filename, organisationId, mediaVault, customAssetUrl);
23071
23229
  }
23072
23230
  /**
23073
23231
  * Transform asset URLs in HTML content
@@ -23085,14 +23243,24 @@ function transformUrl(url, organisationId, mediaVault = false, customAssetUrl) {
23085
23243
  */
23086
23244
  function transformAssetUrls(html, options) {
23087
23245
  if (!html) return html;
23088
- if (ASSET_REFERENCE_PATTERNS.some((pattern) => pattern.test(html)) && !options.organisationId) throw new Error("Asset references found in QTI content but no --organisation_id provided. Please provide --organisation_id to convert assets to Learnosity CDN URLs.");
23246
+ if (Array.from(html.matchAll(ASSET_ATTRIBUTE_PATTERN)).some((match) => isSupportedAsset(extractFilename$2(match[2]))) && !options.organisationId) throw new Error("Asset references found in QTI content but no --organisation_id provided. Please provide --organisation_id to convert assets to Learnosity CDN URLs.");
23089
23247
  if (!options.organisationId) return normalizeTableClass(html);
23090
23248
  const orgId = options.organisationId;
23091
23249
  const mediaVault = options.mediaVault ?? false;
23092
23250
  const customAssetUrl = options.customAssetUrl;
23251
+ const assetContext = {
23252
+ finalItemReference: options.finalItemReference,
23253
+ preserveAssetFilenames: options.preserveAssetFilenames,
23254
+ sourceHrefBase: options.sourceHrefBase
23255
+ };
23093
23256
  let result = html;
23094
- result = result.replace(OBJECT_TAG_PATTERN, (match) => convertObjectToElement(match, orgId, mediaVault, customAssetUrl));
23095
- result = result.replace(MEDIA_SRC_PATTERN, (_match, prefix, url, suffix) => prefix + transformUrl(url, orgId, mediaVault, customAssetUrl) + suffix);
23257
+ result = result.replace(OBJECT_TAG_PATTERN, (match) => convertObjectToElement(match, orgId, mediaVault, customAssetUrl, assetContext));
23258
+ result = result.replace(INLINE_MEDIA_LINK_PATTERN, (match, beforeAttributes, _quote, url, afterAttributes) => {
23259
+ const kind = getInlineMediaKind(url, `${beforeAttributes}${afterAttributes}`);
23260
+ if (!kind) return match;
23261
+ return buildMediaFeatureSpan(transformUrl(url, orgId, mediaVault, customAssetUrl, assetContext), kind);
23262
+ });
23263
+ result = result.replace(ASSET_ATTRIBUTE_PATTERN, (_match, prefix, url, suffix) => prefix + transformUrl(url, orgId, mediaVault, customAssetUrl, assetContext) + suffix);
23096
23264
  result = normalizeHtmlWhitespace(result);
23097
23265
  result = normalizeTableClass(result);
23098
23266
  return result;
@@ -23238,23 +23406,30 @@ function mapCorrectPairsToValidation(correctPairs, stemIdToIndex, optionIdToInde
23238
23406
  /**
23239
23407
  * Convert matchInteraction to Learnosity choicematrix
23240
23408
  */
23241
- function convertMatchToLearnosity(inputXml, diagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource) {
23409
+ function convertMatchToLearnosity(inputXml, diagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource, _stimulusOverride, assetTransformContext) {
23242
23410
  const parsed = readAssessmentItemMatch(inputXml);
23243
23411
  const updatedDiagnostics = addFileContextIfProvided(parsed.diagnostics, sourceFile);
23244
23412
  diagnostics.push(...updatedDiagnostics);
23245
23413
  if (hasErrors(diagnostics)) return { diagnostics };
23246
23414
  if (!parsed.identifier || parsed.stems.length === 0 || parsed.options.length === 0) return { diagnostics };
23247
- const itemRef = generateItemReference(parsed.identifier, itemReferenceSource, sourceFile);
23415
+ const itemRef = assetTransformContext?.finalItemReference ?? generateItemReference(parsed.identifier, itemReferenceSource, sourceFile);
23416
+ const transformContext = {
23417
+ finalItemReference: itemRef,
23418
+ preserveAssetFilenames: assetTransformContext?.preserveAssetFilenames ?? false,
23419
+ sourceHrefBase: assetTransformContext?.sourceHrefBase
23420
+ };
23248
23421
  const questionRef = md5hex(itemRef);
23249
23422
  const stems = parsed.stems.map((stem) => transformAssetUrls(stem.text, {
23250
23423
  organisationId,
23251
23424
  mediaVault,
23252
- customAssetUrl
23425
+ customAssetUrl,
23426
+ ...transformContext
23253
23427
  }));
23254
23428
  const options = parsed.options.map((option) => transformAssetUrls(option.text, {
23255
23429
  organisationId,
23256
23430
  mediaVault,
23257
- customAssetUrl
23431
+ customAssetUrl,
23432
+ ...transformContext
23258
23433
  }));
23259
23434
  const stemIdToIndex = /* @__PURE__ */ new Map();
23260
23435
  parsed.stems.forEach((stem, index) => {
@@ -23272,7 +23447,8 @@ function convertMatchToLearnosity(inputXml, diagnostics, lomTags, organisationId
23272
23447
  const stimulus = transformAssetUrls(parsed.stimulusText ? `<p>${parsed.stimulusText}</p>` : "", {
23273
23448
  organisationId,
23274
23449
  mediaVault,
23275
- customAssetUrl
23450
+ customAssetUrl,
23451
+ ...transformContext
23276
23452
  });
23277
23453
  const item = {
23278
23454
  item: {
@@ -23652,25 +23828,32 @@ function buildGapValidation(gaps, gapIdToGapTextIds, gapTextIdToContent, sourceF
23652
23828
  /**
23653
23829
  * Convert gapMatchInteraction to Learnosity clozeassociation
23654
23830
  */
23655
- function convertGapMatchToLearnosity(inputXml, diagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource) {
23831
+ function convertGapMatchToLearnosity(inputXml, diagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource, _stimulusOverride, assetTransformContext) {
23656
23832
  const parsed = readAssessmentItemGapMatch(inputXml);
23657
23833
  const updatedDiagnostics = addFileContextIfProvided(parsed.diagnostics, sourceFile);
23658
23834
  diagnostics.push(...updatedDiagnostics);
23659
23835
  if (hasErrors(diagnostics)) return { diagnostics };
23660
23836
  if (!parsed.identifier || parsed.gapTexts.length === 0 || parsed.gaps.length === 0) return { diagnostics };
23661
- const itemRef = generateItemReference(parsed.identifier, itemReferenceSource, sourceFile);
23837
+ const itemRef = assetTransformContext?.finalItemReference ?? generateItemReference(parsed.identifier, itemReferenceSource, sourceFile);
23838
+ const transformContext = {
23839
+ finalItemReference: itemRef,
23840
+ preserveAssetFilenames: assetTransformContext?.preserveAssetFilenames ?? false,
23841
+ sourceHrefBase: assetTransformContext?.sourceHrefBase
23842
+ };
23662
23843
  const questionRef = md5hex(itemRef);
23663
23844
  const possibleResponses = parsed.gapTexts.map((gt) => transformAssetUrls(gt.text, {
23664
23845
  organisationId,
23665
23846
  mediaVault,
23666
- customAssetUrl
23847
+ customAssetUrl,
23848
+ ...transformContext
23667
23849
  }));
23668
23850
  const gapTextIdToContent = /* @__PURE__ */ new Map();
23669
23851
  parsed.gapTexts.forEach((gt) => {
23670
23852
  const transformedText = transformAssetUrls(gt.text, {
23671
23853
  organisationId,
23672
23854
  mediaVault,
23673
- customAssetUrl
23855
+ customAssetUrl,
23856
+ ...transformContext
23674
23857
  });
23675
23858
  gapTextIdToContent.set(gt.identifier, transformedText);
23676
23859
  });
@@ -23688,7 +23871,8 @@ function convertGapMatchToLearnosity(inputXml, diagnostics, lomTags, organisatio
23688
23871
  template: transformAssetUrls(parsed.templateHtml ?? "", {
23689
23872
  organisationId,
23690
23873
  mediaVault,
23691
- customAssetUrl
23874
+ customAssetUrl,
23875
+ ...transformContext
23692
23876
  }),
23693
23877
  possible_responses: possibleResponses,
23694
23878
  shuffle_options: parsed.shuffle ?? false,
@@ -23703,7 +23887,8 @@ function convertGapMatchToLearnosity(inputXml, diagnostics, lomTags, organisatio
23703
23887
  if (parsed.promptHtml) questionData.stimulus = transformAssetUrls(parsed.promptHtml, {
23704
23888
  organisationId,
23705
23889
  mediaVault,
23706
- customAssetUrl
23890
+ customAssetUrl,
23891
+ ...transformContext
23707
23892
  });
23708
23893
  if (maxResponsesPerZone > 1) questionData.max_response_per_zone = maxResponsesPerZone;
23709
23894
  const choiceCounts = /* @__PURE__ */ new Map();
@@ -24108,19 +24293,22 @@ function buildValidationValues(interactions, responseDeclarations, diagnostics,
24108
24293
  * Convert inlineChoiceInteraction to Learnosity clozedropdown
24109
24294
  * TASK 036: Added stimulusOverride parameter for composite items
24110
24295
  */
24111
- function convertInlineChoiceToLearnosity(inputXml, diagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource, stimulusOverride) {
24296
+ function convertInlineChoiceToLearnosity(inputXml, diagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource, stimulusOverride, assetTransformContext) {
24112
24297
  const parsed = readAssessmentItemInlineChoice(inputXml);
24113
24298
  const updatedDiagnostics = addFileContextIfProvided(parsed.diagnostics, sourceFile);
24114
24299
  diagnostics.push(...updatedDiagnostics);
24115
24300
  if (hasErrors(diagnostics)) return { diagnostics };
24116
24301
  if (!parsed.identifier || parsed.interactions.length === 0) return { diagnostics };
24117
- const itemRef = generateItemReference(parsed.identifier, itemReferenceSource, sourceFile);
24118
- const questionRef = md5hex(itemRef);
24302
+ const itemRef = assetTransformContext?.finalItemReference ?? generateItemReference(parsed.identifier, itemReferenceSource, sourceFile);
24119
24303
  const transformOpts = {
24120
24304
  organisationId,
24121
24305
  mediaVault,
24122
- customAssetUrl
24306
+ customAssetUrl,
24307
+ finalItemReference: itemRef,
24308
+ preserveAssetFilenames: assetTransformContext?.preserveAssetFilenames ?? false,
24309
+ sourceHrefBase: assetTransformContext?.sourceHrefBase
24123
24310
  };
24311
+ const questionRef = md5hex(itemRef);
24124
24312
  const possibleResponses = parsed.interactions.map((interaction) => interaction.choices.map((choice) => transformAssetUrls(choice.text, transformOpts)));
24125
24313
  const validationValue = buildValidationValues(parsed.interactions, parsed.responseDeclarations, diagnostics, transformOpts, sourceFile);
24126
24314
  if (!validationValue) return { diagnostics };
@@ -24244,6 +24432,7 @@ function readAssessmentItemOrder(inputXml) {
24244
24432
  } else if (localName === "value" && capture === "correct") {}
24245
24433
  if (capture === "stimulus" && stack.length > stimulusCaptureDepth && localName !== "orderInteraction") stimulusBuf.push(buildOpeningTag$2(tag, localName));
24246
24434
  else if (capture === "prompt" && localName !== "prompt") promptBuf.push(buildOpeningTag$2(tag, localName));
24435
+ else if (capture === "choice" && localName !== "simpleChoice") choiceBuf.push(buildOpeningTag$2(tag, localName));
24247
24436
  });
24248
24437
  parser.on("text", (text) => {
24249
24438
  if (capture === "stimulus") stimulusBuf.push(text);
@@ -24267,6 +24456,8 @@ function readAssessmentItemOrder(inputXml) {
24267
24456
  capture = null;
24268
24457
  } else if (capture === "prompt" && localName !== "prompt") {
24269
24458
  if (!QTI_VOID_ELEMENTS.has(localName.toLowerCase())) promptBuf.push(`</${localName}>`);
24459
+ } else if (capture === "choice" && localName !== "simpleChoice") {
24460
+ if (!QTI_VOID_ELEMENTS.has(localName.toLowerCase())) choiceBuf.push(`</${localName}>`);
24270
24461
  } else if (localName === "simpleChoice" && capture === "choice") {
24271
24462
  const text = normalizeWhitespace(choiceBuf.join(""));
24272
24463
  if (currentChoiceId) {
@@ -24384,23 +24575,30 @@ function readAssessmentItemOrder(inputXml) {
24384
24575
  /**
24385
24576
  * Convert orderInteraction to Learnosity orderlist
24386
24577
  */
24387
- function convertOrderToLearnosity(inputXml, diagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource) {
24578
+ function convertOrderToLearnosity(inputXml, diagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource, _stimulusOverride, assetTransformContext) {
24388
24579
  const parsed = readAssessmentItemOrder(inputXml);
24389
24580
  const updatedDiagnostics = addFileContextIfProvided(parsed.diagnostics, sourceFile);
24390
24581
  diagnostics.push(...updatedDiagnostics);
24391
24582
  if (hasErrors(diagnostics)) return { diagnostics };
24392
24583
  if (!parsed.identifier || !parsed.responseIdentifier || parsed.choices.length === 0) return { diagnostics };
24393
- const itemRef = generateItemReference(parsed.identifier, itemReferenceSource, sourceFile);
24584
+ const itemRef = assetTransformContext?.finalItemReference ?? generateItemReference(parsed.identifier, itemReferenceSource, sourceFile);
24585
+ const transformContext = {
24586
+ finalItemReference: itemRef,
24587
+ preserveAssetFilenames: assetTransformContext?.preserveAssetFilenames ?? false,
24588
+ sourceHrefBase: assetTransformContext?.sourceHrefBase
24589
+ };
24394
24590
  const questionRef = md5hex(itemRef);
24395
24591
  const stimulus = transformAssetUrls(parsed.stimulusText ?? "", {
24396
24592
  organisationId,
24397
24593
  mediaVault,
24398
- customAssetUrl
24594
+ customAssetUrl,
24595
+ ...transformContext
24399
24596
  });
24400
24597
  const list = parsed.choices.map((choice) => transformAssetUrls(choice.text, {
24401
24598
  organisationId,
24402
24599
  mediaVault,
24403
- customAssetUrl
24600
+ customAssetUrl,
24601
+ ...transformContext
24404
24602
  }));
24405
24603
  let validationValue;
24406
24604
  if (parsed.correctOrder && parsed.correctOrder.length > 0) {
@@ -24669,14 +24867,14 @@ function readAssessmentItemHotspot(inputXml) {
24669
24867
  * Convert QTI shape coordinates to Learnosity polygon coordinates
24670
24868
  * QTI uses absolute pixel coordinates, Learnosity uses percentage coordinates
24671
24869
  */
24672
- function convertShapeToPolygon(choice, imageWidth, imageHeight, diagnostics) {
24870
+ function convertShapeToPolygon(choice, imageWidth, imageHeight, diagnostics, sourceFile) {
24673
24871
  const coords = choice.coords.split(",").map((c) => parseFloat(c.trim()));
24674
24872
  if (choice.shape === "circle") {
24675
24873
  if (coords.length !== 3) {
24676
24874
  diagnostics.push({
24677
24875
  code: DiagnosticCode.LRN_SCHEMA_INVALID,
24678
24876
  level: "error",
24679
- file: `hotspotChoice[@identifier="${choice.identifier}"]`,
24877
+ file: sourceFile ?? `hotspotChoice[@identifier="${choice.identifier}"]`,
24680
24878
  message: `Invalid circle coords for ${choice.identifier}: expected 3 values (x,y,radius), got ${coords.length}`
24681
24879
  });
24682
24880
  return null;
@@ -24699,7 +24897,7 @@ function convertShapeToPolygon(choice, imageWidth, imageHeight, diagnostics) {
24699
24897
  diagnostics.push({
24700
24898
  code: DiagnosticCode.LRN_SCHEMA_INVALID,
24701
24899
  level: "error",
24702
- file: `hotspotChoice[@identifier="${choice.identifier}"]`,
24900
+ file: sourceFile ?? `hotspotChoice[@identifier="${choice.identifier}"]`,
24703
24901
  message: `Invalid rect coords for ${choice.identifier}: expected 4 values (x1,y1,x2,y2), got ${coords.length}`
24704
24902
  });
24705
24903
  return null;
@@ -24728,7 +24926,7 @@ function convertShapeToPolygon(choice, imageWidth, imageHeight, diagnostics) {
24728
24926
  diagnostics.push({
24729
24927
  code: DiagnosticCode.LRN_SCHEMA_INVALID,
24730
24928
  level: "error",
24731
- file: `hotspotChoice[@identifier="${choice.identifier}"]`,
24929
+ file: sourceFile ?? `hotspotChoice[@identifier="${choice.identifier}"]`,
24732
24930
  message: `Invalid poly coords for ${choice.identifier}: expected at least 6 values (3 points) in pairs, got ${coords.length}`
24733
24931
  });
24734
24932
  return null;
@@ -24744,7 +24942,7 @@ function convertShapeToPolygon(choice, imageWidth, imageHeight, diagnostics) {
24744
24942
  diagnostics.push({
24745
24943
  code: DiagnosticCode.LRN_SCHEMA_INVALID,
24746
24944
  level: "error",
24747
- file: `hotspotChoice[@identifier="${choice.identifier}"]`,
24945
+ file: sourceFile ?? `hotspotChoice[@identifier="${choice.identifier}"]`,
24748
24946
  message: `Invalid ellipse coords for ${choice.identifier}: expected 4 values (cx,cy,rx,ry), got ${coords.length}`
24749
24947
  });
24750
24948
  return null;
@@ -24766,7 +24964,7 @@ function convertShapeToPolygon(choice, imageWidth, imageHeight, diagnostics) {
24766
24964
  diagnostics.push({
24767
24965
  code: DiagnosticCode.LRN_SCHEMA_INVALID,
24768
24966
  level: "error",
24769
- file: `hotspotChoice[@identifier="${choice.identifier}"]`,
24967
+ file: sourceFile ?? `hotspotChoice[@identifier="${choice.identifier}"]`,
24770
24968
  message: `Unsupported shape type: ${choice.shape}`
24771
24969
  });
24772
24970
  return null;
@@ -24775,17 +24973,19 @@ function convertShapeToPolygon(choice, imageWidth, imageHeight, diagnostics) {
24775
24973
  /**
24776
24974
  * Build the combined stimulus HTML from parsed stimulusText and promptText
24777
24975
  */
24778
- function buildHotspotStimulus(parsed, organisationId, mediaVault, customAssetUrl) {
24976
+ function buildHotspotStimulus(parsed, organisationId, mediaVault, customAssetUrl, assetTransformContext) {
24779
24977
  let stimulus = "";
24780
24978
  if (parsed.stimulusText) stimulus += transformAssetUrls(parsed.stimulusText, {
24781
24979
  organisationId,
24782
24980
  mediaVault,
24783
- customAssetUrl
24981
+ customAssetUrl,
24982
+ ...assetTransformContext
24784
24983
  });
24785
24984
  if (parsed.promptText) stimulus += `<p>${transformAssetUrls(parsed.promptText, {
24786
24985
  organisationId,
24787
24986
  mediaVault,
24788
- customAssetUrl
24987
+ customAssetUrl,
24988
+ ...assetTransformContext
24789
24989
  })}</p>`;
24790
24990
  return stimulus;
24791
24991
  }
@@ -24810,7 +25010,7 @@ function buildHotspotValidation(correctResponses, choiceIdToIndex) {
24810
25010
  /**
24811
25011
  * Convert hotspotInteraction to Learnosity hotspot
24812
25012
  */
24813
- function convertHotspotToLearnosity(inputXml, diagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource, fileAccess, packageRoot) {
25013
+ function convertHotspotToLearnosity(inputXml, diagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource, fileAccess, packageRoot, assetTransformContext) {
24814
25014
  const parsed = readAssessmentItemHotspot(inputXml);
24815
25015
  const updatedDiagnostics = addFileContextIfProvided(parsed.diagnostics, sourceFile);
24816
25016
  diagnostics.push(...updatedDiagnostics);
@@ -24832,14 +25032,19 @@ function convertHotspotToLearnosity(inputXml, diagnostics, lomTags, organisation
24832
25032
  return { diagnostics };
24833
25033
  }
24834
25034
  }
24835
- const itemRef = generateItemReference(parsed.identifier, itemReferenceSource, sourceFile);
25035
+ const itemRef = assetTransformContext?.finalItemReference ?? generateItemReference(parsed.identifier, itemReferenceSource, sourceFile);
25036
+ const transformContext = {
25037
+ finalItemReference: itemRef,
25038
+ preserveAssetFilenames: assetTransformContext?.preserveAssetFilenames ?? false,
25039
+ sourceHrefBase: assetTransformContext?.sourceHrefBase
25040
+ };
24836
25041
  const questionRef = md5hex(itemRef);
24837
- const stimulus = buildHotspotStimulus(parsed, organisationId, mediaVault, customAssetUrl);
24838
- const imageSource = organisationId ? transformUrl(parsed.imageSource, organisationId, mediaVault, customAssetUrl) : parsed.imageSource;
25042
+ const stimulus = buildHotspotStimulus(parsed, organisationId, mediaVault, customAssetUrl, transformContext);
25043
+ const imageSource = organisationId ? transformUrl(parsed.imageSource, organisationId, mediaVault, customAssetUrl, transformContext) : parsed.imageSource;
24839
25044
  const areas = [];
24840
25045
  const choiceIdToIndex = /* @__PURE__ */ new Map();
24841
25046
  for (const choice of parsed.hotspotChoices) {
24842
- const polygon = convertShapeToPolygon(choice, parsed.imageWidth, parsed.imageHeight, diagnostics);
25047
+ const polygon = convertShapeToPolygon(choice, parsed.imageWidth, parsed.imageHeight, diagnostics, sourceFile);
24843
25048
  if (polygon) {
24844
25049
  choiceIdToIndex.set(choice.identifier, areas.length);
24845
25050
  areas.push(polygon);
@@ -25118,14 +25323,19 @@ function readAssessmentItemHottext(inputXml) {
25118
25323
  /**
25119
25324
  * Convert hottextInteraction to Learnosity tokenhighlight
25120
25325
  */
25121
- function convertHottextToLearnosity(inputXml, diagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource) {
25326
+ function convertHottextToLearnosity(inputXml, diagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource, _stimulusOverride, assetTransformContext) {
25122
25327
  const parsed = readAssessmentItemHottext(inputXml);
25123
25328
  const updatedDiagnostics = addFileContextIfProvided(parsed.diagnostics, sourceFile);
25124
25329
  diagnostics.push(...updatedDiagnostics);
25125
25330
  if (hasErrors(diagnostics)) return { diagnostics };
25126
25331
  if (!parsed.identifier || !parsed.responseIdentifier || !parsed.templateHtml) return { diagnostics };
25127
25332
  if (parsed.hottextElements.length === 0) return { diagnostics };
25128
- const itemRef = generateItemReference(parsed.identifier, itemReferenceSource, sourceFile);
25333
+ const itemRef = assetTransformContext?.finalItemReference ?? generateItemReference(parsed.identifier, itemReferenceSource, sourceFile);
25334
+ const transformContext = {
25335
+ finalItemReference: itemRef,
25336
+ preserveAssetFilenames: assetTransformContext?.preserveAssetFilenames ?? false,
25337
+ sourceHrefBase: assetTransformContext?.sourceHrefBase
25338
+ };
25129
25339
  const questionRef = md5hex(itemRef);
25130
25340
  if (parsed.shuffle) diagnostics.push({
25131
25341
  code: DiagnosticCode.QTI_SHUFFLE_NOT_SUPPORTED,
@@ -25137,7 +25347,8 @@ function convertHottextToLearnosity(inputXml, diagnostics, lomTags, organisation
25137
25347
  if (stimulus) stimulus = transformAssetUrls(stimulus, {
25138
25348
  organisationId,
25139
25349
  mediaVault,
25140
- customAssetUrl
25350
+ customAssetUrl,
25351
+ ...transformContext
25141
25352
  });
25142
25353
  let template = parsed.templateHtml || "";
25143
25354
  const identifierToIndex = /* @__PURE__ */ new Map();
@@ -25150,7 +25361,8 @@ function convertHottextToLearnosity(inputXml, diagnostics, lomTags, organisation
25150
25361
  template = transformAssetUrls(template, {
25151
25362
  organisationId,
25152
25363
  mediaVault,
25153
- customAssetUrl
25364
+ customAssetUrl,
25365
+ ...transformContext
25154
25366
  });
25155
25367
  let validation = void 0;
25156
25368
  if (parsed.correctResponses && parsed.correctResponses.length > 0) {
@@ -25617,7 +25829,7 @@ function readAssessmentItemMcq(inputXml, stimulusOverride) {
25617
25829
  * Supports both single and composite (multiple) choiceInteractions
25618
25830
  * TASK 036: Added stimulusOverride parameter for composite items
25619
25831
  */
25620
- function convertMcqToLearnosity(inputXml, diagnostics, lomTags, sourceFile, organisationId, mediaVault, customAssetUrl, itemReferenceSource, stimulusOverride) {
25832
+ function convertMcqToLearnosity(inputXml, diagnostics, lomTags, sourceFile, organisationId, mediaVault, customAssetUrl, itemReferenceSource, stimulusOverride, assetTransformContext) {
25621
25833
  const parsed = readAssessmentItemMcq(inputXml, stimulusOverride);
25622
25834
  const contextualDiagnostics = sourceFile ? parsed.diagnostics.map((d) => ({
25623
25835
  ...d,
@@ -25626,7 +25838,12 @@ function convertMcqToLearnosity(inputXml, diagnostics, lomTags, sourceFile, orga
25626
25838
  diagnostics.push(...contextualDiagnostics);
25627
25839
  if (diagnostics.some((d) => d.level === "error")) return { diagnostics };
25628
25840
  if (!parsed.identifier || parsed.interactions.length === 0) return { diagnostics };
25629
- const itemRef = generateItemReference(parsed.identifier, itemReferenceSource, sourceFile);
25841
+ const itemRef = assetTransformContext?.finalItemReference ?? generateItemReference(parsed.identifier, itemReferenceSource, sourceFile);
25842
+ const transformContext = {
25843
+ finalItemReference: itemRef,
25844
+ preserveAssetFilenames: assetTransformContext?.preserveAssetFilenames ?? false,
25845
+ sourceHrefBase: assetTransformContext?.sourceHrefBase
25846
+ };
25630
25847
  const isComposite = parsed.interactions.length > 1;
25631
25848
  const questions = [];
25632
25849
  const widgets = [];
@@ -25636,7 +25853,8 @@ function convertMcqToLearnosity(inputXml, diagnostics, lomTags, sourceFile, orga
25636
25853
  const stimulus = interaction.stimulusText ? transformAssetUrls(interaction.stimulusText, {
25637
25854
  organisationId,
25638
25855
  mediaVault,
25639
- customAssetUrl
25856
+ customAssetUrl,
25857
+ ...transformContext
25640
25858
  }) : void 0;
25641
25859
  const choiceMapping = /* @__PURE__ */ new Map();
25642
25860
  const options = interaction.choices.map((choice) => {
@@ -25645,7 +25863,8 @@ function convertMcqToLearnosity(inputXml, diagnostics, lomTags, sourceFile, orga
25645
25863
  label: transformAssetUrls(choice.text, {
25646
25864
  organisationId,
25647
25865
  mediaVault,
25648
- customAssetUrl
25866
+ customAssetUrl,
25867
+ ...transformContext
25649
25868
  }),
25650
25869
  value: choice.identifier
25651
25870
  };
@@ -25682,7 +25901,8 @@ function convertMcqToLearnosity(inputXml, diagnostics, lomTags, sourceFile, orga
25682
25901
  const instructorStimulus = parsed.instructorStimulus ? transformAssetUrls(parsed.instructorStimulus, {
25683
25902
  organisationId,
25684
25903
  mediaVault,
25685
- customAssetUrl
25904
+ customAssetUrl,
25905
+ ...transformContext
25686
25906
  }) : void 0;
25687
25907
  questions.push({
25688
25908
  reference: questionRef,
@@ -26050,7 +26270,7 @@ function stripWrapperDiv(html) {
26050
26270
  * Convert textEntry (textEntryInteraction) to Learnosity clozetext or shorttext
26051
26271
  * TASK 036: Added stimulusOverride parameter for composite items
26052
26272
  */
26053
- function convertTextEntryToLearnosity(inputXml, diagnostics, lomTags, sourceFile, organisationId, mediaVault, customAssetUrl, itemReferenceSource, stimulusOverride) {
26273
+ function convertTextEntryToLearnosity(inputXml, diagnostics, lomTags, sourceFile, organisationId, mediaVault, customAssetUrl, itemReferenceSource, stimulusOverride, assetTransformContext) {
26054
26274
  const parsed = readAssessmentItemTextEntry(inputXml, stimulusOverride);
26055
26275
  const contextualDiagnostics = sourceFile ? parsed.diagnostics.map((d) => ({
26056
26276
  ...d,
@@ -26060,24 +26280,31 @@ function convertTextEntryToLearnosity(inputXml, diagnostics, lomTags, sourceFile
26060
26280
  if (diagnostics.some((d) => d.level === "error")) return { diagnostics };
26061
26281
  if (!parsed.identifier || parsed.textEntries.length === 0) return { diagnostics };
26062
26282
  if (typeof parsed.templateText === "string") parsed.templateText = stripWrapperDiv(parsed.templateText);
26063
- if (parsed.textEntries.length === 1 && /{{response}}(?:\s*<\/[^>]+>)*\s*$/.test(parsed.templateText.trim())) return convertShorttextToLearnosity(parsed, diagnostics, lomTags, organisationId, mediaVault, customAssetUrl, itemReferenceSource, sourceFile);
26064
- else return convertClozetextToLearnosity(parsed, diagnostics, lomTags, organisationId, mediaVault, customAssetUrl, itemReferenceSource, sourceFile);
26283
+ if (parsed.textEntries.length === 1 && /{{response}}(?:\s*<\/[^>]+>)*\s*$/.test(parsed.templateText.trim())) return convertShorttextToLearnosity(parsed, diagnostics, lomTags, organisationId, mediaVault, customAssetUrl, itemReferenceSource, sourceFile, assetTransformContext);
26284
+ else return convertClozetextToLearnosity(parsed, diagnostics, lomTags, organisationId, mediaVault, customAssetUrl, itemReferenceSource, sourceFile, assetTransformContext);
26065
26285
  }
26066
26286
  /**
26067
26287
  * Convert single textEntry to Learnosity shorttext
26068
26288
  */
26069
- function convertShorttextToLearnosity(parsed, diagnostics, lomTags, organisationId, mediaVault, customAssetUrl, itemReferenceSource, sourceFile) {
26070
- const itemRef = generateItemReference(parsed.identifier, itemReferenceSource, sourceFile);
26289
+ function convertShorttextToLearnosity(parsed, diagnostics, lomTags, organisationId, mediaVault, customAssetUrl, itemReferenceSource, sourceFile, assetTransformContext) {
26290
+ const itemRef = assetTransformContext?.finalItemReference ?? generateItemReference(parsed.identifier, itemReferenceSource, sourceFile);
26291
+ const transformContext = {
26292
+ finalItemReference: itemRef,
26293
+ preserveAssetFilenames: assetTransformContext?.preserveAssetFilenames ?? false,
26294
+ sourceHrefBase: assetTransformContext?.sourceHrefBase
26295
+ };
26071
26296
  const questionRef = md5hex(parsed.responseIdentifier ?? parsed.identifier);
26072
26297
  const stimulus = normalizeFinalText(transformAssetUrls((parsed.templateText || "").replace(/{{response}}(?:\s*<\/[^>]+>)*\s*$/, "").trim(), {
26073
26298
  organisationId,
26074
26299
  mediaVault,
26075
- customAssetUrl
26300
+ customAssetUrl,
26301
+ ...transformContext
26076
26302
  }));
26077
26303
  const instructorStimulus = parsed.instructorStimulus ? transformAssetUrls(parsed.instructorStimulus, {
26078
26304
  organisationId,
26079
26305
  mediaVault,
26080
- customAssetUrl
26306
+ customAssetUrl,
26307
+ ...transformContext
26081
26308
  }) : void 0;
26082
26309
  const entry = parsed.textEntries[0];
26083
26310
  const correctResponses = entry.correctResponses || (entry.correctResponse ? [entry.correctResponse] : []);
@@ -26151,25 +26378,33 @@ function convertShorttextToLearnosity(parsed, diagnostics, lomTags, organisation
26151
26378
  /**
26152
26379
  * Convert textEntry with template to Learnosity clozetext
26153
26380
  */
26154
- function convertClozetextToLearnosity(parsed, diagnostics, lomTags, organisationId, mediaVault, customAssetUrl, itemReferenceSource, sourceFile) {
26381
+ function convertClozetextToLearnosity(parsed, diagnostics, lomTags, organisationId, mediaVault, customAssetUrl, itemReferenceSource, sourceFile, assetTransformContext) {
26155
26382
  const correctResponses = [];
26156
26383
  for (const entry of parsed.textEntries) if (entry.correctResponse) correctResponses.push(entry.correctResponse);
26157
- const itemRef = generateItemReference(parsed.identifier, itemReferenceSource, sourceFile);
26384
+ const itemRef = assetTransformContext?.finalItemReference ?? generateItemReference(parsed.identifier, itemReferenceSource, sourceFile);
26385
+ const transformContext = {
26386
+ finalItemReference: itemRef,
26387
+ preserveAssetFilenames: assetTransformContext?.preserveAssetFilenames ?? false,
26388
+ sourceHrefBase: assetTransformContext?.sourceHrefBase
26389
+ };
26158
26390
  const questionRef = md5hex(parsed.responseIdentifier ?? parsed.identifier);
26159
26391
  const stimulus = parsed.stimulusText ? normalizeFinalText(transformAssetUrls(parsed.stimulusText, {
26160
26392
  organisationId,
26161
26393
  mediaVault,
26162
- customAssetUrl
26394
+ customAssetUrl,
26395
+ ...transformContext
26163
26396
  })) : void 0;
26164
26397
  const template = normalizeFinalText(transformAssetUrls(parsed.templateText, {
26165
26398
  organisationId,
26166
26399
  mediaVault,
26167
- customAssetUrl
26400
+ customAssetUrl,
26401
+ ...transformContext
26168
26402
  }));
26169
26403
  const instructorStimulus = parsed.instructorStimulus ? transformAssetUrls(parsed.instructorStimulus, {
26170
26404
  organisationId,
26171
26405
  mediaVault,
26172
- customAssetUrl
26406
+ customAssetUrl,
26407
+ ...transformContext
26173
26408
  }) : void 0;
26174
26409
  const validation = {
26175
26410
  scoring_type: "exactMatch",
@@ -26402,8 +26637,13 @@ function readAssessmentItemExtendedText(inputXml) {
26402
26637
  /**
26403
26638
  * Build multi-interaction extended text item (multiple longtextV2 questions)
26404
26639
  */
26405
- function buildMultiExtendedTextItem(parsed, inputXml, stimulusOverride, diagnostics, lomTags, organisationId, mediaVault, customAssetUrl, itemReferenceSource, sourceFile) {
26406
- const itemRef = generateItemReference(parsed.identifier ?? "unknown", itemReferenceSource, sourceFile);
26640
+ function buildMultiExtendedTextItem(parsed, inputXml, stimulusOverride, diagnostics, lomTags, organisationId, mediaVault, customAssetUrl, itemReferenceSource, sourceFile, assetTransformContext) {
26641
+ const itemRef = assetTransformContext?.finalItemReference ?? generateItemReference(parsed.identifier ?? "unknown", itemReferenceSource, sourceFile);
26642
+ const transformContext = {
26643
+ finalItemReference: itemRef,
26644
+ preserveAssetFilenames: assetTransformContext?.preserveAssetFilenames ?? false,
26645
+ sourceHrefBase: assetTransformContext?.sourceHrefBase
26646
+ };
26407
26647
  const questions = [];
26408
26648
  const widgets = [];
26409
26649
  const questionSpans = [];
@@ -26413,7 +26653,8 @@ function buildMultiExtendedTextItem(parsed, inputXml, stimulusOverride, diagnost
26413
26653
  const stimulus = transformAssetUrls(stimulusOverride[i], {
26414
26654
  organisationId,
26415
26655
  mediaVault,
26416
- customAssetUrl
26656
+ customAssetUrl,
26657
+ ...transformContext
26417
26658
  });
26418
26659
  widgets.push({
26419
26660
  reference: questionRef,
@@ -26463,19 +26704,25 @@ function extractResponseIdentifiers(inputXml, interactionTag) {
26463
26704
  * Convert extended text (extendedTextInteraction) to Learnosity longtextV2
26464
26705
  * TASK 036: Added stimulusOverride parameter for composite items
26465
26706
  */
26466
- function convertExtendedTextToLearnosity(inputXml, diagnostics, lomTags, sourceFile, organisationId, mediaVault, customAssetUrl, itemReferenceSource, stimulusOverride) {
26707
+ function convertExtendedTextToLearnosity(inputXml, diagnostics, lomTags, sourceFile, organisationId, mediaVault, customAssetUrl, itemReferenceSource, stimulusOverride, assetTransformContext) {
26467
26708
  const parsed = readAssessmentItemExtendedText(inputXml);
26468
26709
  const contextualDiagnostics = addFileContextIfProvided(stimulusOverride ? filterOutCodes(parsed.diagnostics, [DiagnosticCode.QTI_EXTENDED_TEXT_MULTIPLE_INTERACTIONS]) : parsed.diagnostics, sourceFile);
26469
26710
  diagnostics.push(...contextualDiagnostics);
26470
26711
  if (hasErrors(diagnostics)) return { diagnostics };
26471
- if (stimulusOverride && stimulusOverride.length > 1) return buildMultiExtendedTextItem(parsed, inputXml, stimulusOverride, diagnostics, lomTags, organisationId, mediaVault, customAssetUrl, itemReferenceSource, sourceFile);
26472
- const itemRef = generateItemReference(parsed.identifier ?? "unknown", itemReferenceSource, sourceFile);
26712
+ if (stimulusOverride && stimulusOverride.length > 1) return buildMultiExtendedTextItem(parsed, inputXml, stimulusOverride, diagnostics, lomTags, organisationId, mediaVault, customAssetUrl, itemReferenceSource, sourceFile, assetTransformContext);
26713
+ const itemRef = assetTransformContext?.finalItemReference ?? generateItemReference(parsed.identifier ?? "unknown", itemReferenceSource, sourceFile);
26714
+ const transformContext = {
26715
+ finalItemReference: itemRef,
26716
+ preserveAssetFilenames: assetTransformContext?.preserveAssetFilenames ?? false,
26717
+ sourceHrefBase: assetTransformContext?.sourceHrefBase
26718
+ };
26473
26719
  const questionRef = md5hex(parsed.responseIdentifier ?? parsed.identifier ?? "unknown");
26474
26720
  const stimulusRaw = stimulusOverride && stimulusOverride.length === 1 ? stimulusOverride[0] : parsed.stimulusText;
26475
26721
  const stimulus = stimulusRaw ? transformAssetUrls(stimulusRaw, {
26476
26722
  organisationId,
26477
26723
  mediaVault,
26478
- customAssetUrl
26724
+ customAssetUrl,
26725
+ ...transformContext
26479
26726
  }) : void 0;
26480
26727
  const instructorStimulus = parsed.instructorStimulus ? transformAssetUrls(parsed.instructorStimulus, {
26481
26728
  organisationId,
@@ -26770,7 +27017,7 @@ function buildValidationValue$1(hotspots, correctPairs, gapImgIdToResponse) {
26770
27017
  /**
26771
27018
  * Convert QTI graphicGapMatchInteraction to Learnosity imageclozeassociationV2
26772
27019
  */
26773
- function convertGraphicGapMatchToLearnosity(inputXml, diagnostics, _lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource) {
27020
+ function convertGraphicGapMatchToLearnosity(inputXml, diagnostics, _lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource, _stimulusOverride, assetTransformContext) {
26774
27021
  const parsed = readAssessmentItemGraphicGapMatch(inputXml);
26775
27022
  const contextualDiagnostics = addFileContextIfProvided(parsed.diagnostics, sourceFile);
26776
27023
  diagnostics.push(...contextualDiagnostics);
@@ -26786,6 +27033,12 @@ function convertGraphicGapMatchToLearnosity(inputXml, diagnostics, _lomTags, org
26786
27033
  }
26787
27034
  const bgWidth = parsed.backgroundImage.width;
26788
27035
  const bgHeight = parsed.backgroundImage.height;
27036
+ const itemRef = assetTransformContext?.finalItemReference ?? generateItemReference(parsed.identifier ?? "item", itemReferenceSource, sourceFile);
27037
+ const transformContext = {
27038
+ finalItemReference: itemRef,
27039
+ preserveAssetFilenames: assetTransformContext?.preserveAssetFilenames ?? false,
27040
+ sourceHrefBase: assetTransformContext?.sourceHrefBase
27041
+ };
26789
27042
  const gapImgIdToResponse = /* @__PURE__ */ new Map();
26790
27043
  const possible_responses = parsed.gapImages.map((g) => {
26791
27044
  if (g.text !== void 0) {
@@ -26804,7 +27057,8 @@ function convertGraphicGapMatchToLearnosity(inputXml, diagnostics, _lomTags, org
26804
27057
  const transformedImgTag = transformAssetUrls(imgTag, {
26805
27058
  organisationId,
26806
27059
  mediaVault,
26807
- customAssetUrl
27060
+ customAssetUrl,
27061
+ ...transformContext
26808
27062
  });
26809
27063
  gapImgIdToResponse.set(g.identifier, transformedImgTag);
26810
27064
  return transformedImgTag;
@@ -26842,7 +27096,7 @@ function convertGraphicGapMatchToLearnosity(inputXml, diagnostics, _lomTags, org
26842
27096
  const question = {
26843
27097
  type: "imageclozeassociationV2",
26844
27098
  image: {
26845
- src: organisationId ? transformUrl(parsed.backgroundImage.src, organisationId, mediaVault, customAssetUrl) : parsed.backgroundImage.src,
27099
+ src: organisationId ? transformUrl(parsed.backgroundImage.src, organisationId, mediaVault, customAssetUrl, transformContext) : parsed.backgroundImage.src,
26846
27100
  width: bgWidth,
26847
27101
  height: bgHeight
26848
27102
  },
@@ -26866,11 +27120,12 @@ function convertGraphicGapMatchToLearnosity(inputXml, diagnostics, _lomTags, org
26866
27120
  if (parsed.stimulus) question.stimulus = transformAssetUrls(parsed.stimulus, {
26867
27121
  organisationId,
26868
27122
  mediaVault,
26869
- customAssetUrl
27123
+ customAssetUrl,
27124
+ ...transformContext
26870
27125
  });
26871
27126
  const item = {
26872
27127
  item: {
26873
- reference: generateItemReference(parsed.identifier ?? "item", itemReferenceSource, sourceFile),
27128
+ reference: itemRef,
26874
27129
  title: parsed.title ?? void 0,
26875
27130
  definition: { widgets: [{
26876
27131
  reference: questionRef,
@@ -27160,35 +27415,38 @@ const readAssessmentItemDrawing = createAssessmentItemReader({
27160
27415
  /**
27161
27416
  * Build drawing stimulus from parsed QTI data
27162
27417
  */
27163
- function buildDrawingStimulus(parsed, organisationId, mediaVault, customAssetUrl) {
27418
+ function buildDrawingStimulus(parsed, organisationId, mediaVault, customAssetUrl, assetTransformContext) {
27164
27419
  if (!parsed.stimulusText && !parsed.promptText) return;
27165
27420
  const stimulus = parsed.promptText || parsed.stimulusText || "";
27166
27421
  try {
27167
27422
  return transformAssetUrls(stimulus, {
27168
27423
  organisationId,
27169
27424
  mediaVault,
27170
- customAssetUrl
27425
+ customAssetUrl,
27426
+ ...assetTransformContext
27171
27427
  });
27172
- } catch {
27428
+ } catch (error) {
27429
+ if (isUnsafeQtiAssetHrefError(error)) throw error;
27173
27430
  return stimulus;
27174
27431
  }
27175
27432
  }
27176
27433
  /**
27177
27434
  * Transform a single image source URL
27178
27435
  */
27179
- function transformImageSource(imageSource, organisationId, mediaVault, customAssetUrl) {
27436
+ function transformImageSource(imageSource, organisationId, mediaVault, customAssetUrl, assetTransformContext) {
27180
27437
  try {
27181
- return organisationId ? transformUrl(imageSource, organisationId, mediaVault, customAssetUrl) : imageSource;
27182
- } catch {
27438
+ return organisationId ? transformUrl(imageSource, organisationId, mediaVault, customAssetUrl, assetTransformContext) : imageSource;
27439
+ } catch (error) {
27440
+ if (isUnsafeQtiAssetHrefError(error)) throw error;
27183
27441
  return imageSource;
27184
27442
  }
27185
27443
  }
27186
27444
  /**
27187
27445
  * Build drawing image data from parsed QTI data
27188
27446
  */
27189
- function buildDrawingImage(parsed, organisationId, mediaVault, customAssetUrl) {
27447
+ function buildDrawingImage(parsed, organisationId, mediaVault, customAssetUrl, assetTransformContext) {
27190
27448
  if (!parsed.imageSource) return;
27191
- const image = { source: transformImageSource(parsed.imageSource, organisationId, mediaVault, customAssetUrl) };
27449
+ const image = { source: transformImageSource(parsed.imageSource, organisationId, mediaVault, customAssetUrl, assetTransformContext) };
27192
27450
  if (parsed.imageWidth) image.width = parsed.imageWidth;
27193
27451
  if (parsed.imageHeight) image.height = parsed.imageHeight;
27194
27452
  if (parsed.imageAlt) image.alt = parsed.imageAlt;
@@ -27197,21 +27455,27 @@ function buildDrawingImage(parsed, organisationId, mediaVault, customAssetUrl) {
27197
27455
  /**
27198
27456
  * Convert QTI drawingInteraction to Learnosity drawing question
27199
27457
  */
27200
- function convertDrawingToLearnosity(inputXml, diagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource) {
27458
+ function convertDrawingToLearnosity(inputXml, diagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource, _stimulusOverride, assetTransformContext) {
27201
27459
  const parsed = readAssessmentItemDrawing(inputXml);
27202
27460
  diagnostics.push(...parsed.diagnostics);
27203
27461
  if (parsed.diagnostics.some((d) => d.level === "error")) return { diagnostics };
27204
- const itemRef = generateItemReference(parsed.identifier ?? "item", itemReferenceSource, sourceFile);
27462
+ const generatedItemRef = generateItemReference(parsed.identifier ?? "item", itemReferenceSource, sourceFile);
27463
+ const itemRef = assetTransformContext?.finalItemReference ?? parsed.identifier ?? generatedItemRef;
27464
+ const transformContext = {
27465
+ finalItemReference: itemRef,
27466
+ preserveAssetFilenames: assetTransformContext?.preserveAssetFilenames ?? false,
27467
+ sourceHrefBase: assetTransformContext?.sourceHrefBase
27468
+ };
27205
27469
  const questionRef = md5hex(itemRef + (parsed.responseIdentifier ?? "drawing"));
27206
27470
  const questionData = { type: "drawing" };
27207
- const stimulus = buildDrawingStimulus(parsed, organisationId, mediaVault, customAssetUrl);
27471
+ const stimulus = buildDrawingStimulus(parsed, organisationId, mediaVault, customAssetUrl, transformContext);
27208
27472
  if (stimulus !== void 0) questionData.stimulus = stimulus;
27209
- const image = buildDrawingImage(parsed, organisationId, mediaVault, customAssetUrl);
27473
+ const image = buildDrawingImage(parsed, organisationId, mediaVault, customAssetUrl, transformContext);
27210
27474
  if (image) questionData.image = image;
27211
27475
  const content = `<span class="learnosity-response question-${questionRef}"></span>`;
27212
27476
  const item = {
27213
27477
  item: {
27214
- reference: parsed.identifier ?? itemRef,
27478
+ reference: itemRef,
27215
27479
  title: parsed.title ?? void 0,
27216
27480
  content,
27217
27481
  definition: { widgets: [{
@@ -27501,7 +27765,7 @@ function buildValidationValue(choices, correctPairs, diagnostics, sourceFile) {
27501
27765
  * This reflects the undirected-pair nature of associateInteraction: no choice is
27502
27766
  * inherently a "category" or a "draggable" — both sides of a pair are equivalent.
27503
27767
  */
27504
- function convertAssociationToLearnosity(inputXml, diagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource) {
27768
+ function convertAssociationToLearnosity(inputXml, diagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource, _stimulusOverride, assetTransformContext) {
27505
27769
  const parsed = readAssessmentItemAssociation(inputXml);
27506
27770
  const updatedDiagnostics = addFileContextIfProvided(parsed.diagnostics, sourceFile);
27507
27771
  diagnostics.push(...updatedDiagnostics);
@@ -27509,17 +27773,24 @@ function convertAssociationToLearnosity(inputXml, diagnostics, lomTags, organisa
27509
27773
  if (!parsed.identifier || parsed.choices.length === 0) return { diagnostics };
27510
27774
  const validationValue = buildValidationValue(parsed.choices, parsed.correctPairs, diagnostics, sourceFile);
27511
27775
  if (hasErrors(diagnostics)) return { diagnostics };
27512
- const itemRef = generateItemReference(parsed.identifier, itemReferenceSource, sourceFile);
27776
+ const itemRef = assetTransformContext?.finalItemReference ?? generateItemReference(parsed.identifier, itemReferenceSource, sourceFile);
27777
+ const transformContext = {
27778
+ finalItemReference: itemRef,
27779
+ preserveAssetFilenames: assetTransformContext?.preserveAssetFilenames ?? false,
27780
+ sourceHrefBase: assetTransformContext?.sourceHrefBase
27781
+ };
27513
27782
  const questionRef = md5hex(itemRef);
27514
27783
  const stimulus = transformAssetUrls(parsed.stimulusText ? `<p>${parsed.stimulusText}</p>` : "", {
27515
27784
  organisationId,
27516
27785
  mediaVault,
27517
- customAssetUrl
27786
+ customAssetUrl,
27787
+ ...transformContext
27518
27788
  });
27519
27789
  const possibleResponses = parsed.choices.map((c) => transformAssetUrls(c.text, {
27520
27790
  organisationId,
27521
27791
  mediaVault,
27522
- customAssetUrl
27792
+ customAssetUrl,
27793
+ ...transformContext
27523
27794
  }));
27524
27795
  const pairCount = validationValue.length > 0 ? validationValue.length : Math.round(parsed.maxAssociations ?? parsed.choices.length / 2);
27525
27796
  const columnHeaders = Array.from({ length: pairCount }, (_, i) => `Pair ${i + 1}`);
@@ -27935,8 +28206,8 @@ function computeClosingTags(html) {
27935
28206
  * Converters with different parameter orders are wrapped to normalize the signature.
27936
28207
  */
27937
28208
  function getConverterMap() {
27938
- const wrapSourceFirst = (fn) => (xml, diag, tags, orgId, sf, mv, cau, irs, stimuli) => fn(xml, diag, tags, sf, orgId, mv, cau, irs, stimuli);
27939
- const hotspotConverter = (xml, diag, tags, orgId, sf, mv, cau, irs, _stimuli, fileAccess, packageRoot) => convertHotspotToLearnosity(xml, diag, tags, orgId, sf, mv, cau, irs, fileAccess, packageRoot);
28209
+ const wrapSourceFirst = (fn) => (xml, diag, tags, orgId, sf, mv, cau, irs, stimuli, assetTransformContext) => fn(xml, diag, tags, sf, orgId, mv, cau, irs, stimuli, assetTransformContext);
28210
+ const hotspotConverter = (xml, diag, tags, orgId, sf, mv, cau, irs, _stimuli, assetTransformContext, fileAccess, packageRoot) => convertHotspotToLearnosity(xml, diag, tags, orgId, sf, mv, cau, irs, fileAccess, packageRoot, assetTransformContext);
27940
28211
  return {
27941
28212
  choiceInteraction: wrapSourceFirst(convertMcqToLearnosity),
27942
28213
  textEntryInteraction: wrapSourceFirst(convertTextEntryToLearnosity),
@@ -27959,8 +28230,14 @@ const CONVERTER_MAP = getConverterMap();
27959
28230
  * Strategy: Call each individual converter for its interaction type,
27960
28231
  * then combine all questions and widgets into a single composite item
27961
28232
  */
27962
- function convertMixedInteractionsToLearnosity(inputXml, diagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource, fileAccess, packageRoot) {
28233
+ function convertMixedInteractionsToLearnosity(inputXml, diagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource, fileAccess, packageRoot, assetTransformContext) {
27963
28234
  const metadata = extractItemMetadata(inputXml);
28235
+ const itemRef = assetTransformContext?.finalItemReference ?? generateItemReference(metadata.identifier ?? "mixed_item", itemReferenceSource, sourceFile);
28236
+ const transformContext = {
28237
+ finalItemReference: itemRef,
28238
+ preserveAssetFilenames: assetTransformContext?.preserveAssetFilenames ?? false,
28239
+ sourceHrefBase: assetTransformContext?.sourceHrefBase
28240
+ };
27964
28241
  const { segments } = segmentItemBodyByInteractions(inputXml);
27965
28242
  const stimuliByType = /* @__PURE__ */ new Map();
27966
28243
  for (const segment of segments) {
@@ -28042,7 +28319,8 @@ function convertMixedInteractionsToLearnosity(inputXml, diagnostics, lomTags, or
28042
28319
  const template = normalizeFinalText(transformAssetUrls(rawTemplate, {
28043
28320
  organisationId,
28044
28321
  mediaVault,
28045
- customAssetUrl
28322
+ customAssetUrl,
28323
+ ...transformContext
28046
28324
  }));
28047
28325
  if (groupEntries.length === 1 && /{{response}}(?:<\/[^>]+>|\s)*$/.test(rawTemplate.trim())) {
28048
28326
  let stimulusRaw = rawTemplate.replace(/{{response}}(?:<\/[^>]+>|\s)*$/, "").trim();
@@ -28050,7 +28328,8 @@ function convertMixedInteractionsToLearnosity(inputXml, diagnostics, lomTags, or
28050
28328
  const stimulus = normalizeFinalText(transformAssetUrls(stimulusRaw, {
28051
28329
  organisationId,
28052
28330
  mediaVault,
28053
- customAssetUrl
28331
+ customAssetUrl,
28332
+ ...transformContext
28054
28333
  }));
28055
28334
  const entry = groupEntries[0];
28056
28335
  const allCorrectResponses = entry.correctResponses ?? (entry.correctResponse ? [entry.correctResponse] : []);
@@ -28176,7 +28455,7 @@ function convertMixedInteractionsToLearnosity(inputXml, diagnostics, lomTags, or
28176
28455
  continue;
28177
28456
  }
28178
28457
  const converter = CONVERTER_MAP[group.type];
28179
- if (converter) processResult(converter(inputXml, subDiagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource, group.stimuli, fileAccess, packageRoot), subDiagnostics);
28458
+ if (converter) processResult(converter(inputXml, subDiagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource, group.stimuli, transformContext, fileAccess, packageRoot), subDiagnostics);
28180
28459
  }
28181
28460
  if (allQuestions.length === 0) {
28182
28461
  diagnostics.push({
@@ -28199,9 +28478,16 @@ function convertMixedInteractionsToLearnosity(inputXml, diagnostics, lomTags, or
28199
28478
  passageContent = transformAssetUrls(rawContent, {
28200
28479
  organisationId,
28201
28480
  mediaVault,
28202
- customAssetUrl
28481
+ customAssetUrl,
28482
+ ...transformContext
28483
+ });
28484
+ } catch (error) {
28485
+ if (isUnsafeQtiAssetHrefError(error)) diagnostics.push({
28486
+ code: DiagnosticCode.QTI_ASSET_HREF_UNSAFE,
28487
+ level: "error",
28488
+ file: sourceFile ?? "passage",
28489
+ message: error.message
28203
28490
  });
28204
- } catch {
28205
28491
  passageContent = rawContent;
28206
28492
  }
28207
28493
  allFeatures.push({
@@ -28233,7 +28519,7 @@ function convertMixedInteractionsToLearnosity(inputXml, diagnostics, lomTags, or
28233
28519
  const content = `<div class="row"><div class="col-xs-12">${[...featureSpans, ...questionSpans].join("")}</div></div>`;
28234
28520
  const item = {
28235
28521
  item: {
28236
- reference: generateItemReference(metadata.identifier ?? "mixed_item", itemReferenceSource, sourceFile),
28522
+ reference: itemRef,
28237
28523
  title: metadata.title ?? void 0,
28238
28524
  content,
28239
28525
  definition: { widgets: allWidgets },
@@ -28279,8 +28565,13 @@ function resolvePassageObjects(html, sourceFile, resolvePassageFile) {
28279
28565
  /**
28280
28566
  * Convert passage-only item to Learnosity format with sharedpassage feature
28281
28567
  */
28282
- function convertPassageToLearnosity(parsed, diagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource, fileAccess) {
28283
- const itemRef = generateItemReference(parsed.identifier, itemReferenceSource, sourceFile);
28568
+ function convertPassageToLearnosity(parsed, diagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource, fileAccess, assetTransformContext) {
28569
+ const itemRef = assetTransformContext?.finalItemReference ?? generateItemReference(parsed.identifier, itemReferenceSource, sourceFile);
28570
+ const transformContext = {
28571
+ finalItemReference: itemRef,
28572
+ preserveAssetFilenames: assetTransformContext?.preserveAssetFilenames ?? false,
28573
+ sourceHrefBase: assetTransformContext?.sourceHrefBase
28574
+ };
28284
28575
  const featureRef = `passage-${md5hex(getPassageDataPath(parsed.content) ?? itemRef).substring(0, 8)}`;
28285
28576
  const resolvedContent = resolvePassageObjects(parsed.content, sourceFile, fileAccess?.resolvePassageFile.bind(fileAccess));
28286
28577
  let content;
@@ -28288,11 +28579,12 @@ function convertPassageToLearnosity(parsed, diagnostics, lomTags, organisationId
28288
28579
  content = transformAssetUrls(resolvedContent, {
28289
28580
  organisationId,
28290
28581
  mediaVault,
28291
- customAssetUrl
28582
+ customAssetUrl,
28583
+ ...transformContext
28292
28584
  });
28293
28585
  } catch (error) {
28294
28586
  diagnostics.push({
28295
- code: DiagnosticCode.LRN_SCHEMA_INVALID,
28587
+ code: isUnsafeQtiAssetHrefError(error) ? DiagnosticCode.QTI_ASSET_HREF_UNSAFE : DiagnosticCode.LRN_SCHEMA_INVALID,
28296
28588
  level: "error",
28297
28589
  file: sourceFile ?? "assessmentItem",
28298
28590
  message: error instanceof Error ? error.message : "Failed to transform asset URLs"
@@ -28682,20 +28974,28 @@ function readAssessmentItemUpload(inputXml) {
28682
28974
  * and the file limit from `maxChoices` (see readAssessmentItemUpload / the
28683
28975
  * serializer). fileupload questions are unscored, so there is no validation.
28684
28976
  */
28685
- function convertUploadToLearnosity(inputXml, diagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource) {
28977
+ function convertUploadToLearnosity(inputXml, diagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource, _stimulusOverride, assetTransformContext) {
28686
28978
  const parsed = readAssessmentItemUpload(inputXml);
28687
28979
  diagnostics.push(...parsed.diagnostics);
28688
28980
  if (parsed.diagnostics.some((d) => d.level === "error")) return { diagnostics };
28689
- const itemRef = generateItemReference(parsed.identifier ?? "item", itemReferenceSource, sourceFile);
28981
+ const generatedItemRef = generateItemReference(parsed.identifier ?? "item", itemReferenceSource, sourceFile);
28982
+ const itemRef = assetTransformContext?.finalItemReference ?? parsed.identifier ?? generatedItemRef;
28983
+ const transformContext = {
28984
+ finalItemReference: itemRef,
28985
+ preserveAssetFilenames: assetTransformContext?.preserveAssetFilenames ?? false,
28986
+ sourceHrefBase: assetTransformContext?.sourceHrefBase
28987
+ };
28690
28988
  const questionRef = md5hex(itemRef + (parsed.responseIdentifier ?? "fileupload"));
28691
28989
  const questionData = { type: "fileupload" };
28692
28990
  if (parsed.stimulus) try {
28693
28991
  questionData.stimulus = transformAssetUrls(parsed.stimulus, {
28694
28992
  organisationId,
28695
28993
  mediaVault,
28696
- customAssetUrl
28994
+ customAssetUrl,
28995
+ ...transformContext
28697
28996
  });
28698
- } catch {
28997
+ } catch (error) {
28998
+ if (isUnsafeQtiAssetHrefError(error)) throw error;
28699
28999
  questionData.stimulus = parsed.stimulus;
28700
29000
  }
28701
29001
  for (const suffix of parsed.allowedFileTypes) questionData[`allow_${suffix}`] = true;
@@ -28703,7 +29003,7 @@ function convertUploadToLearnosity(inputXml, diagnostics, lomTags, organisationI
28703
29003
  const content = `<span class="learnosity-response question-${questionRef}"></span>`;
28704
29004
  const item = {
28705
29005
  item: {
28706
- reference: parsed.identifier ?? itemRef,
29006
+ reference: itemRef,
28707
29007
  title: parsed.title ?? void 0,
28708
29008
  content,
28709
29009
  definition: { widgets: [{
@@ -28738,9 +29038,19 @@ function convertUploadToLearnosity(inputXml, diagnostics, lomTags, organisationI
28738
29038
  * - Rejects DOCTYPE / ENTITY declarations up-front (DTD not allowed).
28739
29039
  * - Uses streaming parsers for all interaction types.
28740
29040
  */
29041
+ function getAssetSourceHrefBase(opts) {
29042
+ if (opts.sourceHrefBase) return opts.sourceHrefBase;
29043
+ const source = opts.sourceFile ?? opts.inputPath;
29044
+ if (!source) return;
29045
+ const normalized = source.replaceAll("\\", "/");
29046
+ return normalized.startsWith("/") || /^[A-Za-z]:/.test(normalized) || /^[A-Za-z][A-Za-z\d+.-]*:/.test(normalized) ? normalized.slice(normalized.lastIndexOf("/") + 1) : normalized;
29047
+ }
28741
29048
  /**
28742
29049
  * Supported interaction type names for counting
28743
29050
  */
29051
+ function isUnsafeAssetHrefError(error) {
29052
+ return error instanceof Error && (error.message.startsWith("Unsafe QTI asset href:") || error.message.startsWith("QTI asset href has no filename:"));
29053
+ }
28744
29054
  const INTERACTION_NAMES = [
28745
29055
  "choiceInteraction",
28746
29056
  "textEntryInteraction",
@@ -28806,19 +29116,71 @@ function countAllInteractions(xml) {
28806
29116
  };
28807
29117
  }
28808
29118
  const SINGLE_INTERACTION_CONVERTERS = /* @__PURE__ */ new Map([
28809
- ["choiceInteraction", (xml, diag, lom, opts, stim) => convertMcqToLearnosity(xml, diag, lom, opts.sourceFile, opts.organisationId, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource, stim)],
28810
- ["textEntryInteraction", (xml, diag, lom, opts, stim) => convertTextEntryToLearnosity(xml, diag, lom, opts.sourceFile, opts.organisationId, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource, stim)],
28811
- ["extendedTextInteraction", (xml, diag, lom, opts, stim) => convertExtendedTextToLearnosity(xml, diag, lom, opts.sourceFile, opts.organisationId, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource, stim)],
28812
- ["inlineChoiceInteraction", (xml, diag, lom, opts) => convertInlineChoiceToLearnosity(xml, diag, lom, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource)],
28813
- ["matchInteraction", (xml, diag, lom, opts) => convertMatchToLearnosity(xml, diag, lom, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource)],
28814
- ["gapMatchInteraction", (xml, diag, lom, opts) => convertGapMatchToLearnosity(xml, diag, lom, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource)],
28815
- ["orderInteraction", (xml, diag, lom, opts) => convertOrderToLearnosity(xml, diag, lom, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource)],
28816
- ["hotspotInteraction", (xml, diag, lom, opts) => convertHotspotToLearnosity(xml, diag, lom, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource, opts.fileAccess, opts.packageRoot)],
28817
- ["hottextInteraction", (xml, diag, lom, opts) => convertHottextToLearnosity(xml, diag, lom, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource)],
28818
- ["graphicGapMatchInteraction", (xml, diag, lom, opts) => convertGraphicGapMatchToLearnosity(xml, diag, lom, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource)],
28819
- ["drawingInteraction", (xml, diag, lom, opts) => convertDrawingToLearnosity(xml, diag, lom, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource)],
28820
- ["associateInteraction", (xml, diag, lom, opts) => convertAssociationToLearnosity(xml, diag, lom, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource)],
28821
- ["uploadInteraction", (xml, diag, lom, opts) => convertUploadToLearnosity(xml, diag, lom, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource)]
29119
+ ["choiceInteraction", (xml, diag, lom, opts, stim) => convertMcqToLearnosity(xml, diag, lom, opts.sourceFile, opts.organisationId, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource, stim, {
29120
+ finalItemReference: opts.finalItemReference,
29121
+ preserveAssetFilenames: opts.preserveAssetFilenames ?? false,
29122
+ sourceHrefBase: getAssetSourceHrefBase(opts)
29123
+ })],
29124
+ ["textEntryInteraction", (xml, diag, lom, opts, stim) => convertTextEntryToLearnosity(xml, diag, lom, opts.sourceFile, opts.organisationId, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource, stim, {
29125
+ finalItemReference: opts.finalItemReference,
29126
+ preserveAssetFilenames: opts.preserveAssetFilenames ?? false,
29127
+ sourceHrefBase: getAssetSourceHrefBase(opts)
29128
+ })],
29129
+ ["extendedTextInteraction", (xml, diag, lom, opts, stim) => convertExtendedTextToLearnosity(xml, diag, lom, opts.sourceFile, opts.organisationId, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource, stim, {
29130
+ finalItemReference: opts.finalItemReference,
29131
+ preserveAssetFilenames: opts.preserveAssetFilenames ?? false,
29132
+ sourceHrefBase: getAssetSourceHrefBase(opts)
29133
+ })],
29134
+ ["inlineChoiceInteraction", (xml, diag, lom, opts) => convertInlineChoiceToLearnosity(xml, diag, lom, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource, void 0, {
29135
+ finalItemReference: opts.finalItemReference,
29136
+ preserveAssetFilenames: opts.preserveAssetFilenames ?? false,
29137
+ sourceHrefBase: getAssetSourceHrefBase(opts)
29138
+ })],
29139
+ ["matchInteraction", (xml, diag, lom, opts) => convertMatchToLearnosity(xml, diag, lom, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource, void 0, {
29140
+ finalItemReference: opts.finalItemReference,
29141
+ preserveAssetFilenames: opts.preserveAssetFilenames ?? false,
29142
+ sourceHrefBase: getAssetSourceHrefBase(opts)
29143
+ })],
29144
+ ["gapMatchInteraction", (xml, diag, lom, opts) => convertGapMatchToLearnosity(xml, diag, lom, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource, void 0, {
29145
+ finalItemReference: opts.finalItemReference,
29146
+ preserveAssetFilenames: opts.preserveAssetFilenames ?? false,
29147
+ sourceHrefBase: getAssetSourceHrefBase(opts)
29148
+ })],
29149
+ ["orderInteraction", (xml, diag, lom, opts) => convertOrderToLearnosity(xml, diag, lom, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource, void 0, {
29150
+ finalItemReference: opts.finalItemReference,
29151
+ preserveAssetFilenames: opts.preserveAssetFilenames ?? false,
29152
+ sourceHrefBase: getAssetSourceHrefBase(opts)
29153
+ })],
29154
+ ["hotspotInteraction", (xml, diag, lom, opts) => convertHotspotToLearnosity(xml, diag, lom, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource, opts.fileAccess, opts.packageRoot, {
29155
+ finalItemReference: opts.finalItemReference,
29156
+ preserveAssetFilenames: opts.preserveAssetFilenames ?? false,
29157
+ sourceHrefBase: getAssetSourceHrefBase(opts)
29158
+ })],
29159
+ ["hottextInteraction", (xml, diag, lom, opts) => convertHottextToLearnosity(xml, diag, lom, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource, void 0, {
29160
+ finalItemReference: opts.finalItemReference,
29161
+ preserveAssetFilenames: opts.preserveAssetFilenames ?? false,
29162
+ sourceHrefBase: getAssetSourceHrefBase(opts)
29163
+ })],
29164
+ ["graphicGapMatchInteraction", (xml, diag, lom, opts) => convertGraphicGapMatchToLearnosity(xml, diag, lom, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource, void 0, {
29165
+ finalItemReference: opts.finalItemReference,
29166
+ preserveAssetFilenames: opts.preserveAssetFilenames ?? false,
29167
+ sourceHrefBase: getAssetSourceHrefBase(opts)
29168
+ })],
29169
+ ["drawingInteraction", (xml, diag, lom, opts) => convertDrawingToLearnosity(xml, diag, lom, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource, void 0, {
29170
+ finalItemReference: opts.finalItemReference,
29171
+ preserveAssetFilenames: opts.preserveAssetFilenames ?? false,
29172
+ sourceHrefBase: getAssetSourceHrefBase(opts)
29173
+ })],
29174
+ ["associateInteraction", (xml, diag, lom, opts) => convertAssociationToLearnosity(xml, diag, lom, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource, void 0, {
29175
+ finalItemReference: opts.finalItemReference,
29176
+ preserveAssetFilenames: opts.preserveAssetFilenames ?? false,
29177
+ sourceHrefBase: getAssetSourceHrefBase(opts)
29178
+ })],
29179
+ ["uploadInteraction", (xml, diag, lom, opts) => convertUploadToLearnosity(xml, diag, lom, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource, void 0, {
29180
+ finalItemReference: opts.finalItemReference,
29181
+ preserveAssetFilenames: opts.preserveAssetFilenames ?? false,
29182
+ sourceHrefBase: getAssetSourceHrefBase(opts)
29183
+ })]
28822
29184
  ]);
28823
29185
  /**
28824
29186
  * Dispatch to the appropriate single-interaction converter
@@ -28844,9 +29206,18 @@ function dispatchSingleInteractionConverter(interactionType, inputXml, count, di
28844
29206
  passageContent = transformAssetUrls(rawContent, {
28845
29207
  organisationId: opts.organisationId,
28846
29208
  mediaVault: opts.mediaVault,
28847
- customAssetUrl: opts.customAssetUrl
29209
+ customAssetUrl: opts.customAssetUrl,
29210
+ finalItemReference: opts.finalItemReference ?? result.item.item.reference,
29211
+ preserveAssetFilenames: opts.preserveAssetFilenames ?? false,
29212
+ sourceHrefBase: getAssetSourceHrefBase(opts)
29213
+ });
29214
+ } catch (error) {
29215
+ if (isUnsafeAssetHrefError(error)) diagnostics.push({
29216
+ code: DiagnosticCode.QTI_ASSET_HREF_UNSAFE,
29217
+ level: "error",
29218
+ file: opts.sourceFile ?? "passage",
29219
+ message: error.message
28848
29220
  });
28849
- } catch {
28850
29221
  passageContent = rawContent;
28851
29222
  }
28852
29223
  result.item.features = [...result.item.features, {
@@ -28894,8 +29265,16 @@ function handleNoInteractions(inputXml, diagnostics, allInteractions, lomTags, o
28894
29265
  }
28895
29266
  const passageResult = readAssessmentItemPassage(inputXml);
28896
29267
  diagnostics.push(...addFileContextIfProvided(passageResult.diagnostics, opts.sourceFile));
28897
- if (passageResult.data) return convertPassageToLearnosity(passageResult.data, diagnostics, lomTags, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource, opts.fileAccess);
28898
- const mcqResult = convertMcqToLearnosity(inputXml, diagnostics, lomTags, opts.sourceFile, opts.organisationId, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource);
29268
+ if (passageResult.data) return convertPassageToLearnosity(passageResult.data, diagnostics, lomTags, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource, opts.fileAccess, {
29269
+ finalItemReference: opts.finalItemReference,
29270
+ preserveAssetFilenames: opts.preserveAssetFilenames ?? false,
29271
+ sourceHrefBase: getAssetSourceHrefBase(opts)
29272
+ });
29273
+ const mcqResult = convertMcqToLearnosity(inputXml, diagnostics, lomTags, opts.sourceFile, opts.organisationId, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource, void 0, {
29274
+ finalItemReference: opts.finalItemReference,
29275
+ preserveAssetFilenames: opts.preserveAssetFilenames ?? false,
29276
+ sourceHrefBase: getAssetSourceHrefBase(opts)
29277
+ });
28899
29278
  if (diagnostics.some((d) => d.code === DiagnosticCode.LRN_SCHEMA_INVALID)) return mcqResult;
28900
29279
  return { diagnostics };
28901
29280
  }
@@ -28941,14 +29320,18 @@ function convertQtiAssessmentItemToLearnosity(inputXml, opts = {}) {
28941
29320
  const { counts, allInteractions } = countAllInteractions(inputXml);
28942
29321
  const presentTypes = INTERACTION_NAMES.filter((name) => counts[name] > 0);
28943
29322
  if (presentTypes.reduce((sum, name) => sum + counts[name], 0) === 0) return handleNoInteractions(inputXml, diagnostics, allInteractions, lomTags, opts);
28944
- if (presentTypes.length > 1) return convertMixedInteractionsToLearnosity(inputXml, diagnostics, lomTags, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource, opts.fileAccess, opts.packageRoot);
29323
+ if (presentTypes.length > 1) return convertMixedInteractionsToLearnosity(inputXml, diagnostics, lomTags, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource, opts.fileAccess, opts.packageRoot, {
29324
+ finalItemReference: opts.finalItemReference,
29325
+ preserveAssetFilenames: opts.preserveAssetFilenames ?? false,
29326
+ sourceHrefBase: getAssetSourceHrefBase(opts)
29327
+ });
28945
29328
  return dispatchSingleInteractionConverter(presentTypes[0], inputXml, counts[presentTypes[0]], diagnostics, lomTags, opts);
28946
29329
  } catch (error) {
28947
29330
  diagnostics.push({
28948
- code: DiagnosticCode.LRN_SCHEMA_INVALID,
29331
+ code: isUnsafeAssetHrefError(error) ? DiagnosticCode.QTI_ASSET_HREF_UNSAFE : DiagnosticCode.LRN_SCHEMA_INVALID,
28949
29332
  level: "error",
28950
- file: "root",
28951
- message: `Failed to parse QTI XML: ${error instanceof Error ? error.message : "Unknown error"}`
29333
+ file: opts.sourceFile ?? "root",
29334
+ message: isUnsafeAssetHrefError(error) ? error.message : `Failed to parse QTI XML: ${error instanceof Error ? error.message : "Unknown error"}`
28952
29335
  });
28953
29336
  return { diagnostics };
28954
29337
  }
@@ -31292,6 +31675,6 @@ function formatDiagnosticsSummaryTable(diagnostics) {
31292
31675
  return table.toString();
31293
31676
  }
31294
31677
  //#endregion
31295
- export { mapLearnosityToAst as _, require_cli_table3 as a, parseLearnosityItem as b, transformForwardAssetUrlsInXml as c, generateItemReference as d, md5hex as f, downgradeAssessmentTestToQti21 as g, escapeXml as h, chalk as i, convertQtiAssessmentItemToLearnosity as l, serializeAssessmentItem as m, formatDiagnosticsSummaryTable as n, require_string_width as o, require_saxes as p, formatDiagnosticsTable as r, writeDiagnostics as s, countErrors as t, parseMetadataTags as u, normalizeXhtmlVoidElements as v, DiagnosticCode as x, sanitizeHtmlContent as y };
31678
+ export { mapLearnosityToAst as C, DiagnosticCode as D, parseLearnosityItem as E, downgradeAssessmentTestToQti21 as S, sanitizeHtmlContent as T, md5hex as _, require_cli_table3 as a, serializeAssessmentItem as b, transformForwardAssetUrlsInXml as c, getAllPassageDataPaths as d, generateItemReference as f, serializeQtiAssetIdentity as g, selectQtiAssetFilename as h, chalk as i, convertQtiAssessmentItemToLearnosity as l, isSupportedQtiAssetPath as m, formatDiagnosticsSummaryTable as n, require_string_width as o, canonicalizeQtiAssetHref as p, formatDiagnosticsTable as r, writeDiagnostics as s, countErrors as t, parseMetadataTags as u, getAttr$3 as v, normalizeXhtmlVoidElements as w, escapeXml as x, require_saxes as y };
31296
31679
 
31297
- //# sourceMappingURL=table-DjOn2Tsk.js.map
31680
+ //# sourceMappingURL=table-DTSv0atR.js.map