@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
@@ -181,6 +181,9 @@ const DiagnosticCode = {
181
181
  QTI_PACKAGE_NO_CONTENT: "QTI_PACKAGE_NO_CONTENT",
182
182
  QTI_PACKAGE_DUPLICATE_IDENTIFIER: "QTI_PACKAGE_DUPLICATE_IDENTIFIER",
183
183
  QTI_ITEM_CONVERSION_FAILED: "QTI_ITEM_CONVERSION_FAILED",
184
+ QTI_ASSET_HREF_UNSAFE: "QTI_ASSET_HREF_UNSAFE",
185
+ QTI_ASSET_FILENAME_CONFLICT: "QTI_ASSET_FILENAME_CONFLICT",
186
+ QTI_ASSET_IDENTITY_BYTES_CONFLICT: "QTI_ASSET_IDENTITY_BYTES_CONFLICT",
184
187
  LRN_BUNDLE_WRITTEN: "LRN_BUNDLE_WRITTEN",
185
188
  QTI_DOWNGRADE_NAMESPACE: "QTI_DOWNGRADE_NAMESPACE",
186
189
  QTI_DOWNGRADE_SCHEMA_LOCATION: "QTI_DOWNGRADE_SCHEMA_LOCATION",
@@ -5840,14 +5843,14 @@ var DomHandler = class {
5840
5843
  //#endregion
5841
5844
  //#region ../../node_modules/.pnpm/entities@4.5.0/node_modules/entities/lib/esm/escape.js
5842
5845
  const xmlReplacer = /["&'<>$\x80-\uFFFF]/g;
5843
- const xmlCodeMap$1 = /* @__PURE__ */ new Map([
5846
+ const xmlCodeMap = /* @__PURE__ */ new Map([
5844
5847
  [34, "&quot;"],
5845
5848
  [38, "&amp;"],
5846
5849
  [39, "&apos;"],
5847
5850
  [60, "&lt;"],
5848
5851
  [62, "&gt;"]
5849
5852
  ]);
5850
- 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);
5853
+ 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);
5851
5854
  /**
5852
5855
  * Encodes all non-ASCII characters, as well as characters not valid in XML
5853
5856
  * documents using XML entities.
@@ -5862,12 +5865,12 @@ function encodeXML$1(str) {
5862
5865
  while ((match = xmlReplacer.exec(str)) !== null) {
5863
5866
  const i = match.index;
5864
5867
  const char = str.charCodeAt(i);
5865
- const next = xmlCodeMap$1.get(char);
5868
+ const next = xmlCodeMap.get(char);
5866
5869
  if (next !== void 0) {
5867
5870
  ret += str.substring(lastIdx, i) + next;
5868
5871
  lastIdx = i + 1;
5869
5872
  } else {
5870
- ret += `${str.substring(lastIdx, i)}&#x${getCodePoint$1(str, i).toString(16)};`;
5873
+ ret += `${str.substring(lastIdx, i)}&#x${getCodePoint(str, i).toString(16)};`;
5871
5874
  lastIdx = xmlReplacer.lastIndex += Number((char & 64512) === 55296);
5872
5875
  }
5873
5876
  }
@@ -5883,7 +5886,7 @@ function encodeXML$1(str) {
5883
5886
  * @returns Function that escapes all characters matched by the given regular
5884
5887
  * expression using the given map of characters to escape to their entities.
5885
5888
  */
5886
- function getEscaper$1(regex, map) {
5889
+ function getEscaper(regex, map) {
5887
5890
  return function escape(data) {
5888
5891
  let match;
5889
5892
  let lastIdx = 0;
@@ -5902,7 +5905,7 @@ function getEscaper$1(regex, map) {
5902
5905
  *
5903
5906
  * @param data String to escape.
5904
5907
  */
5905
- const escapeAttribute$1 = getEscaper$1(/["&\u00A0]/g, /* @__PURE__ */ new Map([
5908
+ const escapeAttribute$1 = getEscaper(/["&\u00A0]/g, /* @__PURE__ */ new Map([
5906
5909
  [34, "&quot;"],
5907
5910
  [38, "&amp;"],
5908
5911
  [160, "&nbsp;"]
@@ -5913,7 +5916,7 @@ const escapeAttribute$1 = getEscaper$1(/["&\u00A0]/g, /* @__PURE__ */ new Map([
5913
5916
  *
5914
5917
  * @param data String to escape.
5915
5918
  */
5916
- const escapeText$1 = getEscaper$1(/[&<>\u00A0]/g, /* @__PURE__ */ new Map([
5919
+ const escapeText$1 = getEscaper(/[&<>\u00A0]/g, /* @__PURE__ */ new Map([
5917
5920
  [38, "&amp;"],
5918
5921
  [60, "&lt;"],
5919
5922
  [62, "&gt;"],
@@ -8976,93 +8979,116 @@ function getElementsByTagType(type, nodes, recurse = true, limit = Number.POSITI
8976
8979
  return filter(Checks["tag_type"](type), nodes, recurse, limit);
8977
8980
  }
8978
8981
  //#endregion
8979
- //#region ../../node_modules/.pnpm/entities@8.0.0/node_modules/entities/dist/escape.js
8980
- const xmlCodeMap = /* @__PURE__ */ new Map([
8981
- [34, "&quot;"],
8982
- [38, "&amp;"],
8983
- [39, "&apos;"],
8984
- [60, "&lt;"],
8985
- [62, "&gt;"]
8986
- ]);
8982
+ //#region ../../node_modules/.pnpm/entities@8.1.0/node_modules/entities/dist/escape.js
8987
8983
  /**
8988
- * Read a code point at a given index.
8989
- * @param input Input string to encode or decode.
8990
- * @param index Current read position in the input string.
8984
+ * Get the named reference for an XML special character or U+00A0.
8985
+ * @param char Code unit matched by one of the escape regexes.
8991
8986
  */
8992
- 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);
8987
+ function getEscape(char) {
8988
+ return char === 34 ? "&quot;" : char === 38 ? "&amp;" : char === 39 ? "&apos;" : char === 60 ? "&lt;" : char === 62 ? "&gt;" : "&nbsp;";
8989
+ }
8990
+ /**
8991
+ * Matches exactly the characters `encodeXML` escapes: the five XML special
8992
+ * characters plus every non-ASCII code unit (lone surrogates included — no
8993
+ * `u` flag). Kept in sync with `XML_BITSET_VALUE`.
8994
+ *
8995
+ * Shared with `encodeNonAsciiHTML` in `encode.ts`. Because the regex is
8996
+ * stateful (`g` flag), every call site must set `lastIndex` before use.
8997
+ */
8998
+ const xmlEncodeRegex = /["&'<>\u0080-\uFFFF]/g;
8999
+ /**
9000
+ * Whether `code` (a UTF-16 code unit) is escaped by {@link encodeXML}: a
9001
+ * non-ASCII unit, or one of the five XML specials flagged in
9002
+ * `XML_BITSET_VALUE` (which is only meaningful for code units 32-63).
9003
+ * @param code Code unit to test.
9004
+ */
9005
+ function isXmlEscapable(code) {
9006
+ return code >= 128 || code >= 32 && code < 64 && (1342177476 >>> code & 1) === 1;
9007
+ }
8993
9008
  /**
8994
9009
  * Encodes all non-ASCII characters, as well as characters not valid in XML
8995
- * documents using XML entities. Uses a fast bitset scan instead of RegExp.
9010
+ * documents using XML entities.
8996
9011
  *
8997
9012
  * If a character has no equivalent entity, a numeric hexadecimal reference
8998
9013
  * (eg. `&#xfc;`) will be used.
8999
- * @param input Input string to encode or decode.
9014
+ * @param input Input string to encode.
9000
9015
  */
9001
9016
  function encodeXML(input) {
9017
+ const { length } = input;
9002
9018
  let out;
9003
9019
  let last = 0;
9004
- const { length } = input;
9005
- for (let index = 0; index < length; index++) {
9020
+ let index = 0;
9021
+ while (index < length) {
9006
9022
  const char = input.charCodeAt(index);
9007
- if (char < 128 && ((1342177476 >>> char & 1) === 0 || char >= 64 || char < 32)) continue;
9023
+ if (!isXmlEscapable(char)) {
9024
+ const bound = Math.min(index + 32, length);
9025
+ let next = index + 1;
9026
+ while (next < bound && !isXmlEscapable(input.charCodeAt(next))) next++;
9027
+ if (next < bound) {
9028
+ index = next;
9029
+ continue;
9030
+ }
9031
+ if (next >= length) break;
9032
+ xmlEncodeRegex.lastIndex = next;
9033
+ if (!xmlEncodeRegex.test(input)) break;
9034
+ index = xmlEncodeRegex.lastIndex - 1;
9035
+ continue;
9036
+ }
9008
9037
  if (out === void 0) out = input.substring(0, index);
9009
9038
  else if (last !== index) out += input.substring(last, index);
9010
9039
  if (char < 64) {
9011
- out += xmlCodeMap.get(char);
9012
- last = index + 1;
9040
+ out += getEscape(char);
9041
+ last = index += 1;
9013
9042
  continue;
9014
9043
  }
9015
- const cp = getCodePoint(input, index);
9044
+ const cp = input.codePointAt(index);
9016
9045
  out += `&#x${cp.toString(16)};`;
9017
9046
  if (cp !== char) index++;
9018
- last = index + 1;
9047
+ last = index += 1;
9019
9048
  }
9020
9049
  if (out === void 0) return input;
9021
9050
  if (last < length) out += input.substr(last);
9022
9051
  return out;
9023
9052
  }
9024
9053
  /**
9025
- * Creates a function that escapes all characters matched by the given regular
9026
- * expression using the given map of characters to escape to their entities.
9027
- * @param regex Regular expression to match characters to escape.
9028
- * @param map Map of characters to escape to their entities.
9029
- * @returns Function that escapes all characters matched by the given regular
9030
- * expression using the given map of characters to escape to their entities.
9054
+ * Escape `data` using `re`, mapping each matched character to its entity.
9055
+ * Every match is one UTF-16 code unit, so its index is `lastIndex - 1`.
9056
+ * @param re Global regex matching exactly the characters to escape
9057
+ * (`"`, `&`, `'`, `<`, `>`, `\u00A0` at most).
9058
+ * @param data String to escape.
9031
9059
  */
9032
- function getEscaper(regex, map) {
9033
- return function escape(data) {
9034
- let match;
9035
- let lastIndex = 0;
9036
- let result = "";
9037
- while (match = regex.exec(data)) {
9038
- if (lastIndex !== match.index) result += data.substring(lastIndex, match.index);
9039
- result += map.get(match[0].charCodeAt(0));
9040
- lastIndex = match.index + 1;
9041
- }
9042
- return result + data.substring(lastIndex);
9043
- };
9060
+ function escapeWithRegex(re, data) {
9061
+ re.lastIndex = 0;
9062
+ if (!re.test(data)) return data;
9063
+ let out = "";
9064
+ let last = 0;
9065
+ do {
9066
+ const index = re.lastIndex - 1;
9067
+ if (last !== index) out += data.substring(last, index);
9068
+ const char = data.charCodeAt(index);
9069
+ out += getEscape(char);
9070
+ last = index + 1;
9071
+ } while (re.test(data));
9072
+ return out + data.substring(last);
9044
9073
  }
9074
+ const attributeEscapeRegex = /["&\u{A0}]/gu;
9045
9075
  /**
9046
9076
  * Encodes all characters that have to be escaped in HTML attributes,
9047
9077
  * following {@link https://html.spec.whatwg.org/multipage/parsing.html#escapingString}.
9048
9078
  * @param data String to escape.
9049
9079
  */
9050
- const escapeAttribute = /* #__PURE__ */ getEscaper(/["&\u00A0]/g, /* @__PURE__ */ new Map([
9051
- [34, "&quot;"],
9052
- [38, "&amp;"],
9053
- [160, "&nbsp;"]
9054
- ]));
9080
+ function escapeAttribute(data) {
9081
+ return escapeWithRegex(attributeEscapeRegex, data);
9082
+ }
9083
+ const textEscapeRegex = /[&<>\u{A0}]/gu;
9055
9084
  /**
9056
9085
  * Encodes all characters that have to be escaped in HTML text,
9057
9086
  * following {@link https://html.spec.whatwg.org/multipage/parsing.html#escapingString}.
9058
9087
  * @param data String to escape.
9059
9088
  */
9060
- const escapeText = /* #__PURE__ */ getEscaper(/[&<>\u00A0]/g, /* @__PURE__ */ new Map([
9061
- [38, "&amp;"],
9062
- [60, "&lt;"],
9063
- [62, "&gt;"],
9064
- [160, "&nbsp;"]
9065
- ]));
9089
+ function escapeText(data) {
9090
+ return escapeWithRegex(textEscapeRegex, data);
9091
+ }
9066
9092
  //#endregion
9067
9093
  //#region ../../node_modules/.pnpm/dom-serializer@3.1.1/node_modules/dom-serializer/dist/foreign-names.js
9068
9094
  /**
@@ -22973,6 +22999,33 @@ function md5hex(input) {
22973
22999
  return hex;
22974
23000
  }
22975
23001
  //#endregion
23002
+ //#region src/qti-to-learnosity/utils/mediaFeature.ts
23003
+ /**
23004
+ * Build a stable UUID-shaped identifier for a media feature.
23005
+ *
23006
+ * Feature output must remain identical for equivalent directory and ZIP
23007
+ * package conversions, so the identifier is derived from the final media URL
23008
+ * rather than generated randomly. The UUID version and variant bits are set
23009
+ * to keep the value compatible with consumers expecting a v4-shaped UUID.
23010
+ */
23011
+ function buildMediaFeatureId(transformedUrl) {
23012
+ const hash = md5hex(transformedUrl).split("");
23013
+ const variant = [
23014
+ "8",
23015
+ "9",
23016
+ "a",
23017
+ "b"
23018
+ ][parseInt(hash[16], 16) & 3];
23019
+ hash[12] = "4";
23020
+ hash[16] = variant;
23021
+ 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("")}`;
23022
+ }
23023
+ /** Build a Learnosity simple-feature span for audio or hosted video. */
23024
+ function buildMediaFeatureSpan(transformedUrl, kind, featureId = buildMediaFeatureId(transformedUrl)) {
23025
+ if (kind === "audio") return `<span class="learnosity-feature" data-player="button" data-simplefeature_id="${featureId}" data-src="${transformedUrl}" data-type="audioplayer"></span>`;
23026
+ 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>`;
23027
+ }
23028
+ //#endregion
22976
23029
  //#region src/qti-to-learnosity/utils/convertObjectElement.ts
22977
23030
  /**
22978
23031
  * Convert QTI <object> elements to appropriate Learnosity HTML elements
@@ -23024,7 +23077,7 @@ function buildDeterministicFeatureId(transformedUrl) {
23024
23077
  * <object data="video.mp4" type="video/mp4"/>
23025
23078
  * → <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>
23026
23079
  */
23027
- function convertObjectToElement(objectTag, organisationId, mediaVault = false, customAssetUrl) {
23080
+ function convertObjectToElement(objectTag, organisationId, mediaVault = false, customAssetUrl, assetContext = {}) {
23028
23081
  const dataMatch = objectTag.match(/data=["']([^"']+)["']/i);
23029
23082
  const srcMatch = objectTag.match(/src=["']([^"']+)["']/i);
23030
23083
  const typeMatch = objectTag.match(/type=["']([^"']+)["']/i);
@@ -23034,11 +23087,11 @@ function convertObjectToElement(objectTag, organisationId, mediaVault = false, c
23034
23087
  if (!urlMatch) return objectTag;
23035
23088
  const sourceUrl = urlMatch[1];
23036
23089
  const category = getMimeTypeCategory(typeMatch ? typeMatch[1] : "");
23037
- const transformedUrl = transformUrl(sourceUrl, organisationId, mediaVault, customAssetUrl);
23090
+ const transformedUrl = transformUrl(sourceUrl, organisationId, mediaVault, customAssetUrl, assetContext);
23038
23091
  switch (category) {
23039
23092
  case "image": return buildImageTag(transformedUrl, heightMatch, widthMatch);
23040
- case "audio": return `<span class="learnosity-feature" data-player="button" data-simplefeature_id="${buildDeterministicFeatureId(transformedUrl)}" data-src="${transformedUrl}" data-type="audioplayer"></span>`;
23041
- 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>`;
23093
+ case "audio": return buildMediaFeatureSpan(transformedUrl, "audio", buildDeterministicFeatureId(transformedUrl));
23094
+ case "video": return buildMediaFeatureSpan(transformedUrl, "video", buildDeterministicFeatureId(transformedUrl));
23042
23095
  default: return objectTag.replace(sourceUrl, transformedUrl);
23043
23096
  }
23044
23097
  }
@@ -23082,55 +23135,139 @@ function normalizeTableClass(html) {
23082
23135
  });
23083
23136
  }
23084
23137
  //#endregion
23085
- //#region src/qti-to-learnosity/utils/assetUrlTransform.ts
23138
+ //#region src/qti-to-learnosity/utils/assetIdentity.ts
23086
23139
  /**
23087
- * Asset URL transformation for Learnosity CDN
23088
- * TASK 030
23140
+ * Browser-safe helpers for identifying package-local QTI assets.
23089
23141
  *
23090
- * Transforms asset URLs in HTML content to use Learnosity CDN URLs.
23142
+ * QTI asset references are package-relative paths, not filesystem paths. Keeping
23143
+ * their canonical form here makes directory and ZIP inputs produce the same
23144
+ * identity while rejecting references that could escape the package root.
23091
23145
  */
23146
+ /** Asset extensions copied and rewritten by QTI → Learnosity conversion. */
23147
+ const QTI_ASSET_EXTENSIONS = [
23148
+ ".png",
23149
+ ".jpg",
23150
+ ".jpeg",
23151
+ ".gif",
23152
+ ".svg",
23153
+ ".webp",
23154
+ ".bmp",
23155
+ ".ico",
23156
+ ".mp3",
23157
+ ".mp4",
23158
+ ".wav",
23159
+ ".ogg",
23160
+ ".webm",
23161
+ ".ogv",
23162
+ ".m4a",
23163
+ ".m4v",
23164
+ ".css",
23165
+ ".woff",
23166
+ ".woff2",
23167
+ ".ttf",
23168
+ ".eot",
23169
+ ".pdf",
23170
+ ".json"
23171
+ ];
23172
+ function isSupportedQtiAssetPath(path) {
23173
+ const lowerPath = path.toLowerCase();
23174
+ return !lowerPath.endsWith(".html") && !lowerPath.endsWith(".htm") && QTI_ASSET_EXTENSIONS.some((extension) => lowerPath.endsWith(extension));
23175
+ }
23176
+ function isUnsafeQtiAssetHrefError(error) {
23177
+ return error instanceof Error && (error.message.startsWith("Unsafe QTI asset href:") || error.message.startsWith("QTI asset href has no filename:"));
23178
+ }
23092
23179
  /**
23093
- * Supported asset file extensions
23094
- */
23095
- const SUPPORTED_EXTENSIONS = /* @__PURE__ */ new Set([
23096
- "jpg",
23097
- "jpeg",
23098
- "png",
23099
- "gif",
23100
- "svg",
23101
- "webp",
23102
- "mp3",
23103
- "wav",
23104
- "ogg",
23105
- "m4a",
23106
- "mp4",
23107
- "webm",
23108
- "ogv",
23109
- "m4v"
23110
- ]);
23180
+ * Canonicalize a package-relative QTI asset href.
23181
+ *
23182
+ * Query strings and fragments are URL metadata and do not identify a different
23183
+ * package asset. Path separators are normalized to `/`, dot segments are
23184
+ * resolved, and traversal above the package root is rejected.
23185
+ */
23186
+ function stripHrefMetadata(href) {
23187
+ const metadataStart = href.search(/[?#]/);
23188
+ return (metadataStart === -1 ? href : href.slice(0, metadataStart)).replaceAll("\\", "/");
23189
+ }
23190
+ function assertPackageRelativePath(path, href) {
23191
+ const isAbsolute = path.startsWith("/") || /^[A-Za-z]:/.test(path) || /^[A-Za-z][A-Za-z\d+.-]*:/.test(path);
23192
+ if (!path || path.includes("\0") || isAbsolute) throw new Error(`Unsafe QTI asset href: ${href}`);
23193
+ if (path.endsWith("/")) throw new Error(`QTI asset href has no filename: ${href}`);
23194
+ }
23195
+ function normalizePathSegments(path, href) {
23196
+ const segments = [];
23197
+ for (const segment of path.split("/")) {
23198
+ if (!segment || segment === ".") continue;
23199
+ if (segment === "..") {
23200
+ if (segments.length === 0) throw new Error(`Unsafe QTI asset href: ${href}`);
23201
+ segments.pop();
23202
+ continue;
23203
+ }
23204
+ segments.push(segment);
23205
+ }
23206
+ if (segments.length === 0) throw new Error(`QTI asset href has no filename: ${href}`);
23207
+ return segments.join("/");
23208
+ }
23209
+ function canonicalizeQtiAssetHref(href) {
23210
+ if (typeof href !== "string") throw new TypeError("QTI asset href must be a string");
23211
+ const path = stripHrefMetadata(href);
23212
+ assertPackageRelativePath(path, href);
23213
+ return normalizePathSegments(path, href);
23214
+ }
23215
+ /** Return the final filename from a canonicalized package-relative href. */
23216
+ function extractQtiAssetBasename(href) {
23217
+ const canonicalHref = canonicalizeQtiAssetHref(href);
23218
+ return canonicalHref.slice(canonicalHref.lastIndexOf("/") + 1);
23219
+ }
23111
23220
  /**
23112
- * Patterns that detect any asset reference in HTML (object[data] or
23113
- * img/audio/video/source[src]). Precompiled once; used only with
23114
- * `RegExp.prototype.test` on non-global regexes, so they are safe to share.
23221
+ * Return the final filename extension, including its leading dot.
23222
+ * Dotfiles and filenames ending in a dot have no extension.
23115
23223
  */
23116
- const ASSET_REFERENCE_PATTERNS = [
23117
- /<object\s+[^>]*data=/i,
23118
- /<img\s+[^>]*src=/i,
23119
- /<audio\s+[^>]*src=/i,
23120
- /<video\s+[^>]*src=/i,
23121
- /<source\s+[^>]*src=/i
23122
- ];
23123
- /** Matches `<object ...>` (optionally with its closing tag) for element conversion. */
23124
- const OBJECT_TAG_PATTERN = /<object\s+[^>]*>(?:<\/object>)?/gi;
23224
+ function extractQtiAssetExtension(href) {
23225
+ const basename = extractQtiAssetBasename(href);
23226
+ const extensionStart = basename.lastIndexOf(".");
23227
+ return extensionStart > 0 && extensionStart < basename.length - 1 ? basename.slice(extensionStart) : "";
23228
+ }
23125
23229
  /**
23126
- * src-attribute capture pattern for media elements (img/audio/video/source).
23230
+ * Serialize the item-scoped asset identity using an ordered JSON tuple.
23127
23231
  *
23128
- * Hardcoded literal (rather than built with `new RegExp`) so the pattern cannot
23129
- * be influenced at runtime. Global regex used only with
23130
- * `String.prototype.replace`, which resets lastIndex on completion, so sharing
23131
- * a single compiled instance across calls is safe.
23232
+ * JSON serialization is intentional: unlike delimiter-based concatenation, it
23233
+ * keeps the item reference and canonical href unambiguous when either value
23234
+ * contains punctuation that could otherwise be mistaken for a separator.
23132
23235
  */
23133
- const MEDIA_SRC_PATTERN = /(<(?:img|audio|video|source)\s+[^>]*src=["'])([^"']+)(["'][^>]*>)/gi;
23236
+ function serializeQtiAssetIdentity(finalItemReference, qtiAssetHref) {
23237
+ const canonicalHref = canonicalizeQtiAssetHref(qtiAssetHref);
23238
+ return JSON.stringify([finalItemReference, canonicalHref]);
23239
+ }
23240
+ /** Derive the lowercase MD5 hex hash for a canonical item-scoped identity. */
23241
+ function hashQtiAssetIdentity(finalItemReference, qtiAssetHref) {
23242
+ return md5hex(serializeQtiAssetIdentity(finalItemReference, qtiAssetHref));
23243
+ }
23244
+ /**
23245
+ * Select the output filename for a package-local QTI asset.
23246
+ *
23247
+ * Hashed naming is the default so the full item-scoped identity, rather than a
23248
+ * globally ambiguous source basename, determines the output name. Only the
23249
+ * canonical source extension is retained after the digest. Preserve mode is
23250
+ * an explicit compatibility opt-out and returns the canonical final basename.
23251
+ */
23252
+ function selectQtiAssetFilename(finalItemReference, qtiAssetHref, preserveAssetFilenames = false) {
23253
+ const canonicalHref = canonicalizeQtiAssetHref(qtiAssetHref);
23254
+ if (preserveAssetFilenames) return extractQtiAssetBasename(canonicalHref);
23255
+ return `${hashQtiAssetIdentity(finalItemReference, canonicalHref)}${extractQtiAssetExtension(canonicalHref)}`;
23256
+ }
23257
+ //#endregion
23258
+ //#region src/qti-to-learnosity/utils/assetUrlTransform.ts
23259
+ /**
23260
+ * Asset URL transformation for Learnosity CDN
23261
+ * TASK 030
23262
+ *
23263
+ * Transforms asset URLs in HTML content to use Learnosity CDN URLs.
23264
+ */
23265
+ /** Matches supported asset-bearing HTML attributes on any element. */
23266
+ const ASSET_ATTRIBUTE_PATTERN = /(<[A-Za-z][^>]*?\b(?:src|data|href)\s*=\s*["'])([^"']+)(["'][^>]*>)/gi;
23267
+ /** Matches <object ...> (optionally with its closing tag) for element conversion. */
23268
+ const OBJECT_TAG_PATTERN = /<object\s+[^>]*>(?:<\/object>)?/gi;
23269
+ /** Matches anchors whose href points to inline audio/video media. */
23270
+ const INLINE_MEDIA_LINK_PATTERN = /<a\b([^>]*?)\bhref\s*=\s*(["'])([^"']+)\2([^>]*)>([\s\S]*?)<\/a\s*>/gi;
23134
23271
  /**
23135
23272
  * Extract filename from a URL path
23136
23273
  * Examples:
@@ -23142,12 +23279,26 @@ function extractFilename$1(url) {
23142
23279
  const segments = url.split("?")[0].split("#")[0].split("/");
23143
23280
  return segments[segments.length - 1];
23144
23281
  }
23145
- /**
23146
- * Check if a filename has a supported asset extension
23147
- */
23148
23282
  function isSupportedAsset(filename) {
23149
- const ext = filename.split(".").pop()?.toLowerCase();
23150
- return ext ? SUPPORTED_EXTENSIONS.has(ext) : false;
23283
+ return isSupportedQtiAssetPath(filename);
23284
+ }
23285
+ function getInlineMediaKind(url, attributes) {
23286
+ const mimeType = attributes.match(/\btype\s*=\s*(["'])([^"']+)\1/i)?.[2].toLowerCase();
23287
+ if (mimeType?.startsWith("audio/")) return "audio";
23288
+ if (mimeType?.startsWith("video/")) return "video";
23289
+ const filename = extractFilename$1(url).toLowerCase();
23290
+ if ([
23291
+ ".mp3",
23292
+ ".wav",
23293
+ ".ogg",
23294
+ ".m4a"
23295
+ ].some((extension) => filename.endsWith(extension))) return "audio";
23296
+ if ([
23297
+ ".mp4",
23298
+ ".webm",
23299
+ ".ogv",
23300
+ ".m4v"
23301
+ ].some((extension) => filename.endsWith(extension))) return "video";
23151
23302
  }
23152
23303
  /**
23153
23304
  * Build Learnosity CDN URL for an asset
@@ -23157,17 +23308,24 @@ function buildLearnosityAssetUrl(filename, organisationId, mediaVault = false, c
23157
23308
  if (customAssetUrl) return `${customAssetUrl.endsWith("/") ? customAssetUrl.slice(0, -1) : customAssetUrl}/${filename}`;
23158
23309
  return `https://${mediaVault ? "media-vault" : "assets"}.learnosity.com/organisations/${organisationId}/${filename}`;
23159
23310
  }
23311
+ function resolveQtiAssetHref(url, sourceHrefBase) {
23312
+ const normalizedUrl = url.split(/[?#]/, 1)[0].replaceAll("\\", "/");
23313
+ const isItemRelative = /^\.\.?\//.test(normalizedUrl) || !normalizedUrl.includes("/");
23314
+ if (!sourceHrefBase || !isItemRelative) return canonicalizeQtiAssetHref(url);
23315
+ const baseHref = canonicalizeQtiAssetHref(sourceHrefBase);
23316
+ return canonicalizeQtiAssetHref(`${baseHref.slice(0, baseHref.lastIndexOf("/") + 1)}${normalizedUrl}`);
23317
+ }
23160
23318
  /**
23161
23319
  * Transform a single URL to Learnosity CDN format
23162
23320
  * Exported for use in image object source fields
23163
23321
  */
23164
- function transformUrl(url, organisationId, mediaVault = false, customAssetUrl) {
23322
+ function transformUrl(url, organisationId, mediaVault = false, customAssetUrl, context = {}) {
23165
23323
  if (url.includes("assets.learnosity.com") || url.includes("media-vault.learnosity.com")) return url;
23166
- if (url.match(/^https?:\/\//i)) return url;
23324
+ if (/^https?:\/\//i.test(url) || url.startsWith("//")) return url;
23167
23325
  if (url.startsWith("data:")) return url;
23168
23326
  const filename = extractFilename$1(url);
23169
23327
  if (!isSupportedAsset(filename)) return url;
23170
- return buildLearnosityAssetUrl(filename, organisationId, mediaVault, customAssetUrl);
23328
+ return buildLearnosityAssetUrl(context.finalItemReference ? selectQtiAssetFilename(context.finalItemReference, resolveQtiAssetHref(url, context.sourceHrefBase), context.preserveAssetFilenames ?? false) : filename, organisationId, mediaVault, customAssetUrl);
23171
23329
  }
23172
23330
  /**
23173
23331
  * Transform asset URLs in HTML content
@@ -23185,14 +23343,24 @@ function transformUrl(url, organisationId, mediaVault = false, customAssetUrl) {
23185
23343
  */
23186
23344
  function transformAssetUrls(html, options) {
23187
23345
  if (!html) return html;
23188
- 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.");
23346
+ if (Array.from(html.matchAll(ASSET_ATTRIBUTE_PATTERN)).some((match) => isSupportedAsset(extractFilename$1(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.");
23189
23347
  if (!options.organisationId) return normalizeTableClass(html);
23190
23348
  const orgId = options.organisationId;
23191
23349
  const mediaVault = options.mediaVault ?? false;
23192
23350
  const customAssetUrl = options.customAssetUrl;
23351
+ const assetContext = {
23352
+ finalItemReference: options.finalItemReference,
23353
+ preserveAssetFilenames: options.preserveAssetFilenames,
23354
+ sourceHrefBase: options.sourceHrefBase
23355
+ };
23193
23356
  let result = html;
23194
- result = result.replace(OBJECT_TAG_PATTERN, (match) => convertObjectToElement(match, orgId, mediaVault, customAssetUrl));
23195
- result = result.replace(MEDIA_SRC_PATTERN, (_match, prefix, url, suffix) => prefix + transformUrl(url, orgId, mediaVault, customAssetUrl) + suffix);
23357
+ result = result.replace(OBJECT_TAG_PATTERN, (match) => convertObjectToElement(match, orgId, mediaVault, customAssetUrl, assetContext));
23358
+ result = result.replace(INLINE_MEDIA_LINK_PATTERN, (match, beforeAttributes, _quote, url, afterAttributes) => {
23359
+ const kind = getInlineMediaKind(url, `${beforeAttributes}${afterAttributes}`);
23360
+ if (!kind) return match;
23361
+ return buildMediaFeatureSpan(transformUrl(url, orgId, mediaVault, customAssetUrl, assetContext), kind);
23362
+ });
23363
+ result = result.replace(ASSET_ATTRIBUTE_PATTERN, (_match, prefix, url, suffix) => prefix + transformUrl(url, orgId, mediaVault, customAssetUrl, assetContext) + suffix);
23196
23364
  result = normalizeHtmlWhitespace(result);
23197
23365
  result = normalizeTableClass(result);
23198
23366
  return result;
@@ -23338,23 +23506,30 @@ function mapCorrectPairsToValidation(correctPairs, stemIdToIndex, optionIdToInde
23338
23506
  /**
23339
23507
  * Convert matchInteraction to Learnosity choicematrix
23340
23508
  */
23341
- function convertMatchToLearnosity(inputXml, diagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource) {
23509
+ function convertMatchToLearnosity(inputXml, diagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource, _stimulusOverride, assetTransformContext) {
23342
23510
  const parsed = readAssessmentItemMatch(inputXml);
23343
23511
  const updatedDiagnostics = addFileContextIfProvided(parsed.diagnostics, sourceFile);
23344
23512
  diagnostics.push(...updatedDiagnostics);
23345
23513
  if (hasErrors(diagnostics)) return { diagnostics };
23346
23514
  if (!parsed.identifier || parsed.stems.length === 0 || parsed.options.length === 0) return { diagnostics };
23347
- const itemRef = generateItemReference(parsed.identifier, itemReferenceSource, sourceFile);
23515
+ const itemRef = assetTransformContext?.finalItemReference ?? generateItemReference(parsed.identifier, itemReferenceSource, sourceFile);
23516
+ const transformContext = {
23517
+ finalItemReference: itemRef,
23518
+ preserveAssetFilenames: assetTransformContext?.preserveAssetFilenames ?? false,
23519
+ sourceHrefBase: assetTransformContext?.sourceHrefBase
23520
+ };
23348
23521
  const questionRef = md5hex(itemRef);
23349
23522
  const stems = parsed.stems.map((stem) => transformAssetUrls(stem.text, {
23350
23523
  organisationId,
23351
23524
  mediaVault,
23352
- customAssetUrl
23525
+ customAssetUrl,
23526
+ ...transformContext
23353
23527
  }));
23354
23528
  const options = parsed.options.map((option) => transformAssetUrls(option.text, {
23355
23529
  organisationId,
23356
23530
  mediaVault,
23357
- customAssetUrl
23531
+ customAssetUrl,
23532
+ ...transformContext
23358
23533
  }));
23359
23534
  const stemIdToIndex = /* @__PURE__ */ new Map();
23360
23535
  parsed.stems.forEach((stem, index) => {
@@ -23372,7 +23547,8 @@ function convertMatchToLearnosity(inputXml, diagnostics, lomTags, organisationId
23372
23547
  const stimulus = transformAssetUrls(parsed.stimulusText ? `<p>${parsed.stimulusText}</p>` : "", {
23373
23548
  organisationId,
23374
23549
  mediaVault,
23375
- customAssetUrl
23550
+ customAssetUrl,
23551
+ ...transformContext
23376
23552
  });
23377
23553
  const item = {
23378
23554
  item: {
@@ -23752,25 +23928,32 @@ function buildGapValidation(gaps, gapIdToGapTextIds, gapTextIdToContent, sourceF
23752
23928
  /**
23753
23929
  * Convert gapMatchInteraction to Learnosity clozeassociation
23754
23930
  */
23755
- function convertGapMatchToLearnosity(inputXml, diagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource) {
23931
+ function convertGapMatchToLearnosity(inputXml, diagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource, _stimulusOverride, assetTransformContext) {
23756
23932
  const parsed = readAssessmentItemGapMatch(inputXml);
23757
23933
  const updatedDiagnostics = addFileContextIfProvided(parsed.diagnostics, sourceFile);
23758
23934
  diagnostics.push(...updatedDiagnostics);
23759
23935
  if (hasErrors(diagnostics)) return { diagnostics };
23760
23936
  if (!parsed.identifier || parsed.gapTexts.length === 0 || parsed.gaps.length === 0) return { diagnostics };
23761
- const itemRef = generateItemReference(parsed.identifier, itemReferenceSource, sourceFile);
23937
+ const itemRef = assetTransformContext?.finalItemReference ?? generateItemReference(parsed.identifier, itemReferenceSource, sourceFile);
23938
+ const transformContext = {
23939
+ finalItemReference: itemRef,
23940
+ preserveAssetFilenames: assetTransformContext?.preserveAssetFilenames ?? false,
23941
+ sourceHrefBase: assetTransformContext?.sourceHrefBase
23942
+ };
23762
23943
  const questionRef = md5hex(itemRef);
23763
23944
  const possibleResponses = parsed.gapTexts.map((gt) => transformAssetUrls(gt.text, {
23764
23945
  organisationId,
23765
23946
  mediaVault,
23766
- customAssetUrl
23947
+ customAssetUrl,
23948
+ ...transformContext
23767
23949
  }));
23768
23950
  const gapTextIdToContent = /* @__PURE__ */ new Map();
23769
23951
  parsed.gapTexts.forEach((gt) => {
23770
23952
  const transformedText = transformAssetUrls(gt.text, {
23771
23953
  organisationId,
23772
23954
  mediaVault,
23773
- customAssetUrl
23955
+ customAssetUrl,
23956
+ ...transformContext
23774
23957
  });
23775
23958
  gapTextIdToContent.set(gt.identifier, transformedText);
23776
23959
  });
@@ -23788,7 +23971,8 @@ function convertGapMatchToLearnosity(inputXml, diagnostics, lomTags, organisatio
23788
23971
  template: transformAssetUrls(parsed.templateHtml ?? "", {
23789
23972
  organisationId,
23790
23973
  mediaVault,
23791
- customAssetUrl
23974
+ customAssetUrl,
23975
+ ...transformContext
23792
23976
  }),
23793
23977
  possible_responses: possibleResponses,
23794
23978
  shuffle_options: parsed.shuffle ?? false,
@@ -23803,7 +23987,8 @@ function convertGapMatchToLearnosity(inputXml, diagnostics, lomTags, organisatio
23803
23987
  if (parsed.promptHtml) questionData.stimulus = transformAssetUrls(parsed.promptHtml, {
23804
23988
  organisationId,
23805
23989
  mediaVault,
23806
- customAssetUrl
23990
+ customAssetUrl,
23991
+ ...transformContext
23807
23992
  });
23808
23993
  if (maxResponsesPerZone > 1) questionData.max_response_per_zone = maxResponsesPerZone;
23809
23994
  const choiceCounts = /* @__PURE__ */ new Map();
@@ -24208,19 +24393,22 @@ function buildValidationValues(interactions, responseDeclarations, diagnostics,
24208
24393
  * Convert inlineChoiceInteraction to Learnosity clozedropdown
24209
24394
  * TASK 036: Added stimulusOverride parameter for composite items
24210
24395
  */
24211
- function convertInlineChoiceToLearnosity(inputXml, diagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource, stimulusOverride) {
24396
+ function convertInlineChoiceToLearnosity(inputXml, diagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource, stimulusOverride, assetTransformContext) {
24212
24397
  const parsed = readAssessmentItemInlineChoice(inputXml);
24213
24398
  const updatedDiagnostics = addFileContextIfProvided(parsed.diagnostics, sourceFile);
24214
24399
  diagnostics.push(...updatedDiagnostics);
24215
24400
  if (hasErrors(diagnostics)) return { diagnostics };
24216
24401
  if (!parsed.identifier || parsed.interactions.length === 0) return { diagnostics };
24217
- const itemRef = generateItemReference(parsed.identifier, itemReferenceSource, sourceFile);
24218
- const questionRef = md5hex(itemRef);
24402
+ const itemRef = assetTransformContext?.finalItemReference ?? generateItemReference(parsed.identifier, itemReferenceSource, sourceFile);
24219
24403
  const transformOpts = {
24220
24404
  organisationId,
24221
24405
  mediaVault,
24222
- customAssetUrl
24406
+ customAssetUrl,
24407
+ finalItemReference: itemRef,
24408
+ preserveAssetFilenames: assetTransformContext?.preserveAssetFilenames ?? false,
24409
+ sourceHrefBase: assetTransformContext?.sourceHrefBase
24223
24410
  };
24411
+ const questionRef = md5hex(itemRef);
24224
24412
  const possibleResponses = parsed.interactions.map((interaction) => interaction.choices.map((choice) => transformAssetUrls(choice.text, transformOpts)));
24225
24413
  const validationValue = buildValidationValues(parsed.interactions, parsed.responseDeclarations, diagnostics, transformOpts, sourceFile);
24226
24414
  if (!validationValue) return { diagnostics };
@@ -24344,6 +24532,7 @@ function readAssessmentItemOrder(inputXml) {
24344
24532
  } else if (localName === "value" && capture === "correct") {}
24345
24533
  if (capture === "stimulus" && stack.length > stimulusCaptureDepth && localName !== "orderInteraction") stimulusBuf.push(buildOpeningTag$3(tag, localName));
24346
24534
  else if (capture === "prompt" && localName !== "prompt") promptBuf.push(buildOpeningTag$3(tag, localName));
24535
+ else if (capture === "choice" && localName !== "simpleChoice") choiceBuf.push(buildOpeningTag$3(tag, localName));
24347
24536
  });
24348
24537
  parser.on("text", (text) => {
24349
24538
  if (capture === "stimulus") stimulusBuf.push(text);
@@ -24367,6 +24556,8 @@ function readAssessmentItemOrder(inputXml) {
24367
24556
  capture = null;
24368
24557
  } else if (capture === "prompt" && localName !== "prompt") {
24369
24558
  if (!QTI_VOID_ELEMENTS.has(localName.toLowerCase())) promptBuf.push(`</${localName}>`);
24559
+ } else if (capture === "choice" && localName !== "simpleChoice") {
24560
+ if (!QTI_VOID_ELEMENTS.has(localName.toLowerCase())) choiceBuf.push(`</${localName}>`);
24370
24561
  } else if (localName === "simpleChoice" && capture === "choice") {
24371
24562
  const text = normalizeWhitespace(choiceBuf.join(""));
24372
24563
  if (currentChoiceId) {
@@ -24484,23 +24675,30 @@ function readAssessmentItemOrder(inputXml) {
24484
24675
  /**
24485
24676
  * Convert orderInteraction to Learnosity orderlist
24486
24677
  */
24487
- function convertOrderToLearnosity(inputXml, diagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource) {
24678
+ function convertOrderToLearnosity(inputXml, diagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource, _stimulusOverride, assetTransformContext) {
24488
24679
  const parsed = readAssessmentItemOrder(inputXml);
24489
24680
  const updatedDiagnostics = addFileContextIfProvided(parsed.diagnostics, sourceFile);
24490
24681
  diagnostics.push(...updatedDiagnostics);
24491
24682
  if (hasErrors(diagnostics)) return { diagnostics };
24492
24683
  if (!parsed.identifier || !parsed.responseIdentifier || parsed.choices.length === 0) return { diagnostics };
24493
- const itemRef = generateItemReference(parsed.identifier, itemReferenceSource, sourceFile);
24684
+ const itemRef = assetTransformContext?.finalItemReference ?? generateItemReference(parsed.identifier, itemReferenceSource, sourceFile);
24685
+ const transformContext = {
24686
+ finalItemReference: itemRef,
24687
+ preserveAssetFilenames: assetTransformContext?.preserveAssetFilenames ?? false,
24688
+ sourceHrefBase: assetTransformContext?.sourceHrefBase
24689
+ };
24494
24690
  const questionRef = md5hex(itemRef);
24495
24691
  const stimulus = transformAssetUrls(parsed.stimulusText ?? "", {
24496
24692
  organisationId,
24497
24693
  mediaVault,
24498
- customAssetUrl
24694
+ customAssetUrl,
24695
+ ...transformContext
24499
24696
  });
24500
24697
  const list = parsed.choices.map((choice) => transformAssetUrls(choice.text, {
24501
24698
  organisationId,
24502
24699
  mediaVault,
24503
- customAssetUrl
24700
+ customAssetUrl,
24701
+ ...transformContext
24504
24702
  }));
24505
24703
  let validationValue;
24506
24704
  if (parsed.correctOrder && parsed.correctOrder.length > 0) {
@@ -24769,14 +24967,14 @@ function readAssessmentItemHotspot(inputXml) {
24769
24967
  * Convert QTI shape coordinates to Learnosity polygon coordinates
24770
24968
  * QTI uses absolute pixel coordinates, Learnosity uses percentage coordinates
24771
24969
  */
24772
- function convertShapeToPolygon(choice, imageWidth, imageHeight, diagnostics) {
24970
+ function convertShapeToPolygon(choice, imageWidth, imageHeight, diagnostics, sourceFile) {
24773
24971
  const coords = choice.coords.split(",").map((c) => parseFloat(c.trim()));
24774
24972
  if (choice.shape === "circle") {
24775
24973
  if (coords.length !== 3) {
24776
24974
  diagnostics.push({
24777
24975
  code: DiagnosticCode.LRN_SCHEMA_INVALID,
24778
24976
  level: "error",
24779
- file: `hotspotChoice[@identifier="${choice.identifier}"]`,
24977
+ file: sourceFile ?? `hotspotChoice[@identifier="${choice.identifier}"]`,
24780
24978
  message: `Invalid circle coords for ${choice.identifier}: expected 3 values (x,y,radius), got ${coords.length}`
24781
24979
  });
24782
24980
  return null;
@@ -24799,7 +24997,7 @@ function convertShapeToPolygon(choice, imageWidth, imageHeight, diagnostics) {
24799
24997
  diagnostics.push({
24800
24998
  code: DiagnosticCode.LRN_SCHEMA_INVALID,
24801
24999
  level: "error",
24802
- file: `hotspotChoice[@identifier="${choice.identifier}"]`,
25000
+ file: sourceFile ?? `hotspotChoice[@identifier="${choice.identifier}"]`,
24803
25001
  message: `Invalid rect coords for ${choice.identifier}: expected 4 values (x1,y1,x2,y2), got ${coords.length}`
24804
25002
  });
24805
25003
  return null;
@@ -24828,7 +25026,7 @@ function convertShapeToPolygon(choice, imageWidth, imageHeight, diagnostics) {
24828
25026
  diagnostics.push({
24829
25027
  code: DiagnosticCode.LRN_SCHEMA_INVALID,
24830
25028
  level: "error",
24831
- file: `hotspotChoice[@identifier="${choice.identifier}"]`,
25029
+ file: sourceFile ?? `hotspotChoice[@identifier="${choice.identifier}"]`,
24832
25030
  message: `Invalid poly coords for ${choice.identifier}: expected at least 6 values (3 points) in pairs, got ${coords.length}`
24833
25031
  });
24834
25032
  return null;
@@ -24844,7 +25042,7 @@ function convertShapeToPolygon(choice, imageWidth, imageHeight, diagnostics) {
24844
25042
  diagnostics.push({
24845
25043
  code: DiagnosticCode.LRN_SCHEMA_INVALID,
24846
25044
  level: "error",
24847
- file: `hotspotChoice[@identifier="${choice.identifier}"]`,
25045
+ file: sourceFile ?? `hotspotChoice[@identifier="${choice.identifier}"]`,
24848
25046
  message: `Invalid ellipse coords for ${choice.identifier}: expected 4 values (cx,cy,rx,ry), got ${coords.length}`
24849
25047
  });
24850
25048
  return null;
@@ -24866,7 +25064,7 @@ function convertShapeToPolygon(choice, imageWidth, imageHeight, diagnostics) {
24866
25064
  diagnostics.push({
24867
25065
  code: DiagnosticCode.LRN_SCHEMA_INVALID,
24868
25066
  level: "error",
24869
- file: `hotspotChoice[@identifier="${choice.identifier}"]`,
25067
+ file: sourceFile ?? `hotspotChoice[@identifier="${choice.identifier}"]`,
24870
25068
  message: `Unsupported shape type: ${choice.shape}`
24871
25069
  });
24872
25070
  return null;
@@ -24875,17 +25073,19 @@ function convertShapeToPolygon(choice, imageWidth, imageHeight, diagnostics) {
24875
25073
  /**
24876
25074
  * Build the combined stimulus HTML from parsed stimulusText and promptText
24877
25075
  */
24878
- function buildHotspotStimulus(parsed, organisationId, mediaVault, customAssetUrl) {
25076
+ function buildHotspotStimulus(parsed, organisationId, mediaVault, customAssetUrl, assetTransformContext) {
24879
25077
  let stimulus = "";
24880
25078
  if (parsed.stimulusText) stimulus += transformAssetUrls(parsed.stimulusText, {
24881
25079
  organisationId,
24882
25080
  mediaVault,
24883
- customAssetUrl
25081
+ customAssetUrl,
25082
+ ...assetTransformContext
24884
25083
  });
24885
25084
  if (parsed.promptText) stimulus += `<p>${transformAssetUrls(parsed.promptText, {
24886
25085
  organisationId,
24887
25086
  mediaVault,
24888
- customAssetUrl
25087
+ customAssetUrl,
25088
+ ...assetTransformContext
24889
25089
  })}</p>`;
24890
25090
  return stimulus;
24891
25091
  }
@@ -24910,7 +25110,7 @@ function buildHotspotValidation(correctResponses, choiceIdToIndex) {
24910
25110
  /**
24911
25111
  * Convert hotspotInteraction to Learnosity hotspot
24912
25112
  */
24913
- function convertHotspotToLearnosity(inputXml, diagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource, fileAccess, packageRoot) {
25113
+ function convertHotspotToLearnosity(inputXml, diagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource, fileAccess, packageRoot, assetTransformContext) {
24914
25114
  const parsed = readAssessmentItemHotspot(inputXml);
24915
25115
  const updatedDiagnostics = addFileContextIfProvided(parsed.diagnostics, sourceFile);
24916
25116
  diagnostics.push(...updatedDiagnostics);
@@ -24932,14 +25132,19 @@ function convertHotspotToLearnosity(inputXml, diagnostics, lomTags, organisation
24932
25132
  return { diagnostics };
24933
25133
  }
24934
25134
  }
24935
- const itemRef = generateItemReference(parsed.identifier, itemReferenceSource, sourceFile);
25135
+ const itemRef = assetTransformContext?.finalItemReference ?? generateItemReference(parsed.identifier, itemReferenceSource, sourceFile);
25136
+ const transformContext = {
25137
+ finalItemReference: itemRef,
25138
+ preserveAssetFilenames: assetTransformContext?.preserveAssetFilenames ?? false,
25139
+ sourceHrefBase: assetTransformContext?.sourceHrefBase
25140
+ };
24936
25141
  const questionRef = md5hex(itemRef);
24937
- const stimulus = buildHotspotStimulus(parsed, organisationId, mediaVault, customAssetUrl);
24938
- const imageSource = organisationId ? transformUrl(parsed.imageSource, organisationId, mediaVault, customAssetUrl) : parsed.imageSource;
25142
+ const stimulus = buildHotspotStimulus(parsed, organisationId, mediaVault, customAssetUrl, transformContext);
25143
+ const imageSource = organisationId ? transformUrl(parsed.imageSource, organisationId, mediaVault, customAssetUrl, transformContext) : parsed.imageSource;
24939
25144
  const areas = [];
24940
25145
  const choiceIdToIndex = /* @__PURE__ */ new Map();
24941
25146
  for (const choice of parsed.hotspotChoices) {
24942
- const polygon = convertShapeToPolygon(choice, parsed.imageWidth, parsed.imageHeight, diagnostics);
25147
+ const polygon = convertShapeToPolygon(choice, parsed.imageWidth, parsed.imageHeight, diagnostics, sourceFile);
24943
25148
  if (polygon) {
24944
25149
  choiceIdToIndex.set(choice.identifier, areas.length);
24945
25150
  areas.push(polygon);
@@ -25218,14 +25423,19 @@ function readAssessmentItemHottext(inputXml) {
25218
25423
  /**
25219
25424
  * Convert hottextInteraction to Learnosity tokenhighlight
25220
25425
  */
25221
- function convertHottextToLearnosity(inputXml, diagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource) {
25426
+ function convertHottextToLearnosity(inputXml, diagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource, _stimulusOverride, assetTransformContext) {
25222
25427
  const parsed = readAssessmentItemHottext(inputXml);
25223
25428
  const updatedDiagnostics = addFileContextIfProvided(parsed.diagnostics, sourceFile);
25224
25429
  diagnostics.push(...updatedDiagnostics);
25225
25430
  if (hasErrors(diagnostics)) return { diagnostics };
25226
25431
  if (!parsed.identifier || !parsed.responseIdentifier || !parsed.templateHtml) return { diagnostics };
25227
25432
  if (parsed.hottextElements.length === 0) return { diagnostics };
25228
- const itemRef = generateItemReference(parsed.identifier, itemReferenceSource, sourceFile);
25433
+ const itemRef = assetTransformContext?.finalItemReference ?? generateItemReference(parsed.identifier, itemReferenceSource, sourceFile);
25434
+ const transformContext = {
25435
+ finalItemReference: itemRef,
25436
+ preserveAssetFilenames: assetTransformContext?.preserveAssetFilenames ?? false,
25437
+ sourceHrefBase: assetTransformContext?.sourceHrefBase
25438
+ };
25229
25439
  const questionRef = md5hex(itemRef);
25230
25440
  if (parsed.shuffle) diagnostics.push({
25231
25441
  code: DiagnosticCode.QTI_SHUFFLE_NOT_SUPPORTED,
@@ -25237,7 +25447,8 @@ function convertHottextToLearnosity(inputXml, diagnostics, lomTags, organisation
25237
25447
  if (stimulus) stimulus = transformAssetUrls(stimulus, {
25238
25448
  organisationId,
25239
25449
  mediaVault,
25240
- customAssetUrl
25450
+ customAssetUrl,
25451
+ ...transformContext
25241
25452
  });
25242
25453
  let template = parsed.templateHtml || "";
25243
25454
  const identifierToIndex = /* @__PURE__ */ new Map();
@@ -25250,7 +25461,8 @@ function convertHottextToLearnosity(inputXml, diagnostics, lomTags, organisation
25250
25461
  template = transformAssetUrls(template, {
25251
25462
  organisationId,
25252
25463
  mediaVault,
25253
- customAssetUrl
25464
+ customAssetUrl,
25465
+ ...transformContext
25254
25466
  });
25255
25467
  let validation = void 0;
25256
25468
  if (parsed.correctResponses && parsed.correctResponses.length > 0) {
@@ -25717,7 +25929,7 @@ function readAssessmentItemMcq(inputXml, stimulusOverride) {
25717
25929
  * Supports both single and composite (multiple) choiceInteractions
25718
25930
  * TASK 036: Added stimulusOverride parameter for composite items
25719
25931
  */
25720
- function convertMcqToLearnosity(inputXml, diagnostics, lomTags, sourceFile, organisationId, mediaVault, customAssetUrl, itemReferenceSource, stimulusOverride) {
25932
+ function convertMcqToLearnosity(inputXml, diagnostics, lomTags, sourceFile, organisationId, mediaVault, customAssetUrl, itemReferenceSource, stimulusOverride, assetTransformContext) {
25721
25933
  const parsed = readAssessmentItemMcq(inputXml, stimulusOverride);
25722
25934
  const contextualDiagnostics = sourceFile ? parsed.diagnostics.map((d) => ({
25723
25935
  ...d,
@@ -25726,7 +25938,12 @@ function convertMcqToLearnosity(inputXml, diagnostics, lomTags, sourceFile, orga
25726
25938
  diagnostics.push(...contextualDiagnostics);
25727
25939
  if (diagnostics.some((d) => d.level === "error")) return { diagnostics };
25728
25940
  if (!parsed.identifier || parsed.interactions.length === 0) return { diagnostics };
25729
- const itemRef = generateItemReference(parsed.identifier, itemReferenceSource, sourceFile);
25941
+ const itemRef = assetTransformContext?.finalItemReference ?? generateItemReference(parsed.identifier, itemReferenceSource, sourceFile);
25942
+ const transformContext = {
25943
+ finalItemReference: itemRef,
25944
+ preserveAssetFilenames: assetTransformContext?.preserveAssetFilenames ?? false,
25945
+ sourceHrefBase: assetTransformContext?.sourceHrefBase
25946
+ };
25730
25947
  const isComposite = parsed.interactions.length > 1;
25731
25948
  const questions = [];
25732
25949
  const widgets = [];
@@ -25736,7 +25953,8 @@ function convertMcqToLearnosity(inputXml, diagnostics, lomTags, sourceFile, orga
25736
25953
  const stimulus = interaction.stimulusText ? transformAssetUrls(interaction.stimulusText, {
25737
25954
  organisationId,
25738
25955
  mediaVault,
25739
- customAssetUrl
25956
+ customAssetUrl,
25957
+ ...transformContext
25740
25958
  }) : void 0;
25741
25959
  const choiceMapping = /* @__PURE__ */ new Map();
25742
25960
  const options = interaction.choices.map((choice) => {
@@ -25745,7 +25963,8 @@ function convertMcqToLearnosity(inputXml, diagnostics, lomTags, sourceFile, orga
25745
25963
  label: transformAssetUrls(choice.text, {
25746
25964
  organisationId,
25747
25965
  mediaVault,
25748
- customAssetUrl
25966
+ customAssetUrl,
25967
+ ...transformContext
25749
25968
  }),
25750
25969
  value: choice.identifier
25751
25970
  };
@@ -25782,7 +26001,8 @@ function convertMcqToLearnosity(inputXml, diagnostics, lomTags, sourceFile, orga
25782
26001
  const instructorStimulus = parsed.instructorStimulus ? transformAssetUrls(parsed.instructorStimulus, {
25783
26002
  organisationId,
25784
26003
  mediaVault,
25785
- customAssetUrl
26004
+ customAssetUrl,
26005
+ ...transformContext
25786
26006
  }) : void 0;
25787
26007
  questions.push({
25788
26008
  reference: questionRef,
@@ -26150,7 +26370,7 @@ function stripWrapperDiv(html) {
26150
26370
  * Convert textEntry (textEntryInteraction) to Learnosity clozetext or shorttext
26151
26371
  * TASK 036: Added stimulusOverride parameter for composite items
26152
26372
  */
26153
- function convertTextEntryToLearnosity(inputXml, diagnostics, lomTags, sourceFile, organisationId, mediaVault, customAssetUrl, itemReferenceSource, stimulusOverride) {
26373
+ function convertTextEntryToLearnosity(inputXml, diagnostics, lomTags, sourceFile, organisationId, mediaVault, customAssetUrl, itemReferenceSource, stimulusOverride, assetTransformContext) {
26154
26374
  const parsed = readAssessmentItemTextEntry(inputXml, stimulusOverride);
26155
26375
  const contextualDiagnostics = sourceFile ? parsed.diagnostics.map((d) => ({
26156
26376
  ...d,
@@ -26160,24 +26380,31 @@ function convertTextEntryToLearnosity(inputXml, diagnostics, lomTags, sourceFile
26160
26380
  if (diagnostics.some((d) => d.level === "error")) return { diagnostics };
26161
26381
  if (!parsed.identifier || parsed.textEntries.length === 0) return { diagnostics };
26162
26382
  if (typeof parsed.templateText === "string") parsed.templateText = stripWrapperDiv(parsed.templateText);
26163
- if (parsed.textEntries.length === 1 && /{{response}}(?:\s*<\/[^>]+>)*\s*$/.test(parsed.templateText.trim())) return convertShorttextToLearnosity(parsed, diagnostics, lomTags, organisationId, mediaVault, customAssetUrl, itemReferenceSource, sourceFile);
26164
- else return convertClozetextToLearnosity(parsed, diagnostics, lomTags, organisationId, mediaVault, customAssetUrl, itemReferenceSource, sourceFile);
26383
+ if (parsed.textEntries.length === 1 && /{{response}}(?:\s*<\/[^>]+>)*\s*$/.test(parsed.templateText.trim())) return convertShorttextToLearnosity(parsed, diagnostics, lomTags, organisationId, mediaVault, customAssetUrl, itemReferenceSource, sourceFile, assetTransformContext);
26384
+ else return convertClozetextToLearnosity(parsed, diagnostics, lomTags, organisationId, mediaVault, customAssetUrl, itemReferenceSource, sourceFile, assetTransformContext);
26165
26385
  }
26166
26386
  /**
26167
26387
  * Convert single textEntry to Learnosity shorttext
26168
26388
  */
26169
- function convertShorttextToLearnosity(parsed, diagnostics, lomTags, organisationId, mediaVault, customAssetUrl, itemReferenceSource, sourceFile) {
26170
- const itemRef = generateItemReference(parsed.identifier, itemReferenceSource, sourceFile);
26389
+ function convertShorttextToLearnosity(parsed, diagnostics, lomTags, organisationId, mediaVault, customAssetUrl, itemReferenceSource, sourceFile, assetTransformContext) {
26390
+ const itemRef = assetTransformContext?.finalItemReference ?? generateItemReference(parsed.identifier, itemReferenceSource, sourceFile);
26391
+ const transformContext = {
26392
+ finalItemReference: itemRef,
26393
+ preserveAssetFilenames: assetTransformContext?.preserveAssetFilenames ?? false,
26394
+ sourceHrefBase: assetTransformContext?.sourceHrefBase
26395
+ };
26171
26396
  const questionRef = md5hex(parsed.responseIdentifier ?? parsed.identifier);
26172
26397
  const stimulus = normalizeFinalText(transformAssetUrls((parsed.templateText || "").replace(/{{response}}(?:\s*<\/[^>]+>)*\s*$/, "").trim(), {
26173
26398
  organisationId,
26174
26399
  mediaVault,
26175
- customAssetUrl
26400
+ customAssetUrl,
26401
+ ...transformContext
26176
26402
  }));
26177
26403
  const instructorStimulus = parsed.instructorStimulus ? transformAssetUrls(parsed.instructorStimulus, {
26178
26404
  organisationId,
26179
26405
  mediaVault,
26180
- customAssetUrl
26406
+ customAssetUrl,
26407
+ ...transformContext
26181
26408
  }) : void 0;
26182
26409
  const entry = parsed.textEntries[0];
26183
26410
  const correctResponses = entry.correctResponses || (entry.correctResponse ? [entry.correctResponse] : []);
@@ -26251,25 +26478,33 @@ function convertShorttextToLearnosity(parsed, diagnostics, lomTags, organisation
26251
26478
  /**
26252
26479
  * Convert textEntry with template to Learnosity clozetext
26253
26480
  */
26254
- function convertClozetextToLearnosity(parsed, diagnostics, lomTags, organisationId, mediaVault, customAssetUrl, itemReferenceSource, sourceFile) {
26481
+ function convertClozetextToLearnosity(parsed, diagnostics, lomTags, organisationId, mediaVault, customAssetUrl, itemReferenceSource, sourceFile, assetTransformContext) {
26255
26482
  const correctResponses = [];
26256
26483
  for (const entry of parsed.textEntries) if (entry.correctResponse) correctResponses.push(entry.correctResponse);
26257
- const itemRef = generateItemReference(parsed.identifier, itemReferenceSource, sourceFile);
26484
+ const itemRef = assetTransformContext?.finalItemReference ?? generateItemReference(parsed.identifier, itemReferenceSource, sourceFile);
26485
+ const transformContext = {
26486
+ finalItemReference: itemRef,
26487
+ preserveAssetFilenames: assetTransformContext?.preserveAssetFilenames ?? false,
26488
+ sourceHrefBase: assetTransformContext?.sourceHrefBase
26489
+ };
26258
26490
  const questionRef = md5hex(parsed.responseIdentifier ?? parsed.identifier);
26259
26491
  const stimulus = parsed.stimulusText ? normalizeFinalText(transformAssetUrls(parsed.stimulusText, {
26260
26492
  organisationId,
26261
26493
  mediaVault,
26262
- customAssetUrl
26494
+ customAssetUrl,
26495
+ ...transformContext
26263
26496
  })) : void 0;
26264
26497
  const template = normalizeFinalText(transformAssetUrls(parsed.templateText, {
26265
26498
  organisationId,
26266
26499
  mediaVault,
26267
- customAssetUrl
26500
+ customAssetUrl,
26501
+ ...transformContext
26268
26502
  }));
26269
26503
  const instructorStimulus = parsed.instructorStimulus ? transformAssetUrls(parsed.instructorStimulus, {
26270
26504
  organisationId,
26271
26505
  mediaVault,
26272
- customAssetUrl
26506
+ customAssetUrl,
26507
+ ...transformContext
26273
26508
  }) : void 0;
26274
26509
  const validation = {
26275
26510
  scoring_type: "exactMatch",
@@ -26502,8 +26737,13 @@ function readAssessmentItemExtendedText(inputXml) {
26502
26737
  /**
26503
26738
  * Build multi-interaction extended text item (multiple longtextV2 questions)
26504
26739
  */
26505
- function buildMultiExtendedTextItem(parsed, inputXml, stimulusOverride, diagnostics, lomTags, organisationId, mediaVault, customAssetUrl, itemReferenceSource, sourceFile) {
26506
- const itemRef = generateItemReference(parsed.identifier ?? "unknown", itemReferenceSource, sourceFile);
26740
+ function buildMultiExtendedTextItem(parsed, inputXml, stimulusOverride, diagnostics, lomTags, organisationId, mediaVault, customAssetUrl, itemReferenceSource, sourceFile, assetTransformContext) {
26741
+ const itemRef = assetTransformContext?.finalItemReference ?? generateItemReference(parsed.identifier ?? "unknown", itemReferenceSource, sourceFile);
26742
+ const transformContext = {
26743
+ finalItemReference: itemRef,
26744
+ preserveAssetFilenames: assetTransformContext?.preserveAssetFilenames ?? false,
26745
+ sourceHrefBase: assetTransformContext?.sourceHrefBase
26746
+ };
26507
26747
  const questions = [];
26508
26748
  const widgets = [];
26509
26749
  const questionSpans = [];
@@ -26513,7 +26753,8 @@ function buildMultiExtendedTextItem(parsed, inputXml, stimulusOverride, diagnost
26513
26753
  const stimulus = transformAssetUrls(stimulusOverride[i], {
26514
26754
  organisationId,
26515
26755
  mediaVault,
26516
- customAssetUrl
26756
+ customAssetUrl,
26757
+ ...transformContext
26517
26758
  });
26518
26759
  widgets.push({
26519
26760
  reference: questionRef,
@@ -26563,19 +26804,25 @@ function extractResponseIdentifiers(inputXml, interactionTag) {
26563
26804
  * Convert extended text (extendedTextInteraction) to Learnosity longtextV2
26564
26805
  * TASK 036: Added stimulusOverride parameter for composite items
26565
26806
  */
26566
- function convertExtendedTextToLearnosity(inputXml, diagnostics, lomTags, sourceFile, organisationId, mediaVault, customAssetUrl, itemReferenceSource, stimulusOverride) {
26807
+ function convertExtendedTextToLearnosity(inputXml, diagnostics, lomTags, sourceFile, organisationId, mediaVault, customAssetUrl, itemReferenceSource, stimulusOverride, assetTransformContext) {
26567
26808
  const parsed = readAssessmentItemExtendedText(inputXml);
26568
26809
  const contextualDiagnostics = addFileContextIfProvided(stimulusOverride ? filterOutCodes(parsed.diagnostics, [DiagnosticCode.QTI_EXTENDED_TEXT_MULTIPLE_INTERACTIONS]) : parsed.diagnostics, sourceFile);
26569
26810
  diagnostics.push(...contextualDiagnostics);
26570
26811
  if (hasErrors(diagnostics)) return { diagnostics };
26571
- if (stimulusOverride && stimulusOverride.length > 1) return buildMultiExtendedTextItem(parsed, inputXml, stimulusOverride, diagnostics, lomTags, organisationId, mediaVault, customAssetUrl, itemReferenceSource, sourceFile);
26572
- const itemRef = generateItemReference(parsed.identifier ?? "unknown", itemReferenceSource, sourceFile);
26812
+ if (stimulusOverride && stimulusOverride.length > 1) return buildMultiExtendedTextItem(parsed, inputXml, stimulusOverride, diagnostics, lomTags, organisationId, mediaVault, customAssetUrl, itemReferenceSource, sourceFile, assetTransformContext);
26813
+ const itemRef = assetTransformContext?.finalItemReference ?? generateItemReference(parsed.identifier ?? "unknown", itemReferenceSource, sourceFile);
26814
+ const transformContext = {
26815
+ finalItemReference: itemRef,
26816
+ preserveAssetFilenames: assetTransformContext?.preserveAssetFilenames ?? false,
26817
+ sourceHrefBase: assetTransformContext?.sourceHrefBase
26818
+ };
26573
26819
  const questionRef = md5hex(parsed.responseIdentifier ?? parsed.identifier ?? "unknown");
26574
26820
  const stimulusRaw = stimulusOverride && stimulusOverride.length === 1 ? stimulusOverride[0] : parsed.stimulusText;
26575
26821
  const stimulus = stimulusRaw ? transformAssetUrls(stimulusRaw, {
26576
26822
  organisationId,
26577
26823
  mediaVault,
26578
- customAssetUrl
26824
+ customAssetUrl,
26825
+ ...transformContext
26579
26826
  }) : void 0;
26580
26827
  const instructorStimulus = parsed.instructorStimulus ? transformAssetUrls(parsed.instructorStimulus, {
26581
26828
  organisationId,
@@ -26870,7 +27117,7 @@ function buildValidationValue$1(hotspots, correctPairs, gapImgIdToResponse) {
26870
27117
  /**
26871
27118
  * Convert QTI graphicGapMatchInteraction to Learnosity imageclozeassociationV2
26872
27119
  */
26873
- function convertGraphicGapMatchToLearnosity(inputXml, diagnostics, _lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource) {
27120
+ function convertGraphicGapMatchToLearnosity(inputXml, diagnostics, _lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource, _stimulusOverride, assetTransformContext) {
26874
27121
  const parsed = readAssessmentItemGraphicGapMatch(inputXml);
26875
27122
  const contextualDiagnostics = addFileContextIfProvided(parsed.diagnostics, sourceFile);
26876
27123
  diagnostics.push(...contextualDiagnostics);
@@ -26886,6 +27133,12 @@ function convertGraphicGapMatchToLearnosity(inputXml, diagnostics, _lomTags, org
26886
27133
  }
26887
27134
  const bgWidth = parsed.backgroundImage.width;
26888
27135
  const bgHeight = parsed.backgroundImage.height;
27136
+ const itemRef = assetTransformContext?.finalItemReference ?? generateItemReference(parsed.identifier ?? "item", itemReferenceSource, sourceFile);
27137
+ const transformContext = {
27138
+ finalItemReference: itemRef,
27139
+ preserveAssetFilenames: assetTransformContext?.preserveAssetFilenames ?? false,
27140
+ sourceHrefBase: assetTransformContext?.sourceHrefBase
27141
+ };
26889
27142
  const gapImgIdToResponse = /* @__PURE__ */ new Map();
26890
27143
  const possible_responses = parsed.gapImages.map((g) => {
26891
27144
  if (g.text !== void 0) {
@@ -26904,7 +27157,8 @@ function convertGraphicGapMatchToLearnosity(inputXml, diagnostics, _lomTags, org
26904
27157
  const transformedImgTag = transformAssetUrls(imgTag, {
26905
27158
  organisationId,
26906
27159
  mediaVault,
26907
- customAssetUrl
27160
+ customAssetUrl,
27161
+ ...transformContext
26908
27162
  });
26909
27163
  gapImgIdToResponse.set(g.identifier, transformedImgTag);
26910
27164
  return transformedImgTag;
@@ -26942,7 +27196,7 @@ function convertGraphicGapMatchToLearnosity(inputXml, diagnostics, _lomTags, org
26942
27196
  const question = {
26943
27197
  type: "imageclozeassociationV2",
26944
27198
  image: {
26945
- src: organisationId ? transformUrl(parsed.backgroundImage.src, organisationId, mediaVault, customAssetUrl) : parsed.backgroundImage.src,
27199
+ src: organisationId ? transformUrl(parsed.backgroundImage.src, organisationId, mediaVault, customAssetUrl, transformContext) : parsed.backgroundImage.src,
26946
27200
  width: bgWidth,
26947
27201
  height: bgHeight
26948
27202
  },
@@ -26966,11 +27220,12 @@ function convertGraphicGapMatchToLearnosity(inputXml, diagnostics, _lomTags, org
26966
27220
  if (parsed.stimulus) question.stimulus = transformAssetUrls(parsed.stimulus, {
26967
27221
  organisationId,
26968
27222
  mediaVault,
26969
- customAssetUrl
27223
+ customAssetUrl,
27224
+ ...transformContext
26970
27225
  });
26971
27226
  const item = {
26972
27227
  item: {
26973
- reference: generateItemReference(parsed.identifier ?? "item", itemReferenceSource, sourceFile),
27228
+ reference: itemRef,
26974
27229
  title: parsed.title ?? void 0,
26975
27230
  definition: { widgets: [{
26976
27231
  reference: questionRef,
@@ -27260,35 +27515,38 @@ const readAssessmentItemDrawing = createAssessmentItemReader({
27260
27515
  /**
27261
27516
  * Build drawing stimulus from parsed QTI data
27262
27517
  */
27263
- function buildDrawingStimulus(parsed, organisationId, mediaVault, customAssetUrl) {
27518
+ function buildDrawingStimulus(parsed, organisationId, mediaVault, customAssetUrl, assetTransformContext) {
27264
27519
  if (!parsed.stimulusText && !parsed.promptText) return;
27265
27520
  const stimulus = parsed.promptText || parsed.stimulusText || "";
27266
27521
  try {
27267
27522
  return transformAssetUrls(stimulus, {
27268
27523
  organisationId,
27269
27524
  mediaVault,
27270
- customAssetUrl
27525
+ customAssetUrl,
27526
+ ...assetTransformContext
27271
27527
  });
27272
- } catch {
27528
+ } catch (error) {
27529
+ if (isUnsafeQtiAssetHrefError(error)) throw error;
27273
27530
  return stimulus;
27274
27531
  }
27275
27532
  }
27276
27533
  /**
27277
27534
  * Transform a single image source URL
27278
27535
  */
27279
- function transformImageSource(imageSource, organisationId, mediaVault, customAssetUrl) {
27536
+ function transformImageSource(imageSource, organisationId, mediaVault, customAssetUrl, assetTransformContext) {
27280
27537
  try {
27281
- return organisationId ? transformUrl(imageSource, organisationId, mediaVault, customAssetUrl) : imageSource;
27282
- } catch {
27538
+ return organisationId ? transformUrl(imageSource, organisationId, mediaVault, customAssetUrl, assetTransformContext) : imageSource;
27539
+ } catch (error) {
27540
+ if (isUnsafeQtiAssetHrefError(error)) throw error;
27283
27541
  return imageSource;
27284
27542
  }
27285
27543
  }
27286
27544
  /**
27287
27545
  * Build drawing image data from parsed QTI data
27288
27546
  */
27289
- function buildDrawingImage(parsed, organisationId, mediaVault, customAssetUrl) {
27547
+ function buildDrawingImage(parsed, organisationId, mediaVault, customAssetUrl, assetTransformContext) {
27290
27548
  if (!parsed.imageSource) return;
27291
- const image = { source: transformImageSource(parsed.imageSource, organisationId, mediaVault, customAssetUrl) };
27549
+ const image = { source: transformImageSource(parsed.imageSource, organisationId, mediaVault, customAssetUrl, assetTransformContext) };
27292
27550
  if (parsed.imageWidth) image.width = parsed.imageWidth;
27293
27551
  if (parsed.imageHeight) image.height = parsed.imageHeight;
27294
27552
  if (parsed.imageAlt) image.alt = parsed.imageAlt;
@@ -27297,21 +27555,27 @@ function buildDrawingImage(parsed, organisationId, mediaVault, customAssetUrl) {
27297
27555
  /**
27298
27556
  * Convert QTI drawingInteraction to Learnosity drawing question
27299
27557
  */
27300
- function convertDrawingToLearnosity(inputXml, diagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource) {
27558
+ function convertDrawingToLearnosity(inputXml, diagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource, _stimulusOverride, assetTransformContext) {
27301
27559
  const parsed = readAssessmentItemDrawing(inputXml);
27302
27560
  diagnostics.push(...parsed.diagnostics);
27303
27561
  if (parsed.diagnostics.some((d) => d.level === "error")) return { diagnostics };
27304
- const itemRef = generateItemReference(parsed.identifier ?? "item", itemReferenceSource, sourceFile);
27562
+ const generatedItemRef = generateItemReference(parsed.identifier ?? "item", itemReferenceSource, sourceFile);
27563
+ const itemRef = assetTransformContext?.finalItemReference ?? parsed.identifier ?? generatedItemRef;
27564
+ const transformContext = {
27565
+ finalItemReference: itemRef,
27566
+ preserveAssetFilenames: assetTransformContext?.preserveAssetFilenames ?? false,
27567
+ sourceHrefBase: assetTransformContext?.sourceHrefBase
27568
+ };
27305
27569
  const questionRef = md5hex(itemRef + (parsed.responseIdentifier ?? "drawing"));
27306
27570
  const questionData = { type: "drawing" };
27307
- const stimulus = buildDrawingStimulus(parsed, organisationId, mediaVault, customAssetUrl);
27571
+ const stimulus = buildDrawingStimulus(parsed, organisationId, mediaVault, customAssetUrl, transformContext);
27308
27572
  if (stimulus !== void 0) questionData.stimulus = stimulus;
27309
- const image = buildDrawingImage(parsed, organisationId, mediaVault, customAssetUrl);
27573
+ const image = buildDrawingImage(parsed, organisationId, mediaVault, customAssetUrl, transformContext);
27310
27574
  if (image) questionData.image = image;
27311
27575
  const content = `<span class="learnosity-response question-${questionRef}"></span>`;
27312
27576
  const item = {
27313
27577
  item: {
27314
- reference: parsed.identifier ?? itemRef,
27578
+ reference: itemRef,
27315
27579
  title: parsed.title ?? void 0,
27316
27580
  content,
27317
27581
  definition: { widgets: [{
@@ -27601,7 +27865,7 @@ function buildValidationValue(choices, correctPairs, diagnostics, sourceFile) {
27601
27865
  * This reflects the undirected-pair nature of associateInteraction: no choice is
27602
27866
  * inherently a "category" or a "draggable" — both sides of a pair are equivalent.
27603
27867
  */
27604
- function convertAssociationToLearnosity(inputXml, diagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource) {
27868
+ function convertAssociationToLearnosity(inputXml, diagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource, _stimulusOverride, assetTransformContext) {
27605
27869
  const parsed = readAssessmentItemAssociation(inputXml);
27606
27870
  const updatedDiagnostics = addFileContextIfProvided(parsed.diagnostics, sourceFile);
27607
27871
  diagnostics.push(...updatedDiagnostics);
@@ -27609,17 +27873,24 @@ function convertAssociationToLearnosity(inputXml, diagnostics, lomTags, organisa
27609
27873
  if (!parsed.identifier || parsed.choices.length === 0) return { diagnostics };
27610
27874
  const validationValue = buildValidationValue(parsed.choices, parsed.correctPairs, diagnostics, sourceFile);
27611
27875
  if (hasErrors(diagnostics)) return { diagnostics };
27612
- const itemRef = generateItemReference(parsed.identifier, itemReferenceSource, sourceFile);
27876
+ const itemRef = assetTransformContext?.finalItemReference ?? generateItemReference(parsed.identifier, itemReferenceSource, sourceFile);
27877
+ const transformContext = {
27878
+ finalItemReference: itemRef,
27879
+ preserveAssetFilenames: assetTransformContext?.preserveAssetFilenames ?? false,
27880
+ sourceHrefBase: assetTransformContext?.sourceHrefBase
27881
+ };
27613
27882
  const questionRef = md5hex(itemRef);
27614
27883
  const stimulus = transformAssetUrls(parsed.stimulusText ? `<p>${parsed.stimulusText}</p>` : "", {
27615
27884
  organisationId,
27616
27885
  mediaVault,
27617
- customAssetUrl
27886
+ customAssetUrl,
27887
+ ...transformContext
27618
27888
  });
27619
27889
  const possibleResponses = parsed.choices.map((c) => transformAssetUrls(c.text, {
27620
27890
  organisationId,
27621
27891
  mediaVault,
27622
- customAssetUrl
27892
+ customAssetUrl,
27893
+ ...transformContext
27623
27894
  }));
27624
27895
  const pairCount = validationValue.length > 0 ? validationValue.length : Math.round(parsed.maxAssociations ?? parsed.choices.length / 2);
27625
27896
  const columnHeaders = Array.from({ length: pairCount }, (_, i) => `Pair ${i + 1}`);
@@ -28035,8 +28306,8 @@ function computeClosingTags(html) {
28035
28306
  * Converters with different parameter orders are wrapped to normalize the signature.
28036
28307
  */
28037
28308
  function getConverterMap() {
28038
- const wrapSourceFirst = (fn) => (xml, diag, tags, orgId, sf, mv, cau, irs, stimuli) => fn(xml, diag, tags, sf, orgId, mv, cau, irs, stimuli);
28039
- const hotspotConverter = (xml, diag, tags, orgId, sf, mv, cau, irs, _stimuli, fileAccess, packageRoot) => convertHotspotToLearnosity(xml, diag, tags, orgId, sf, mv, cau, irs, fileAccess, packageRoot);
28309
+ const wrapSourceFirst = (fn) => (xml, diag, tags, orgId, sf, mv, cau, irs, stimuli, assetTransformContext) => fn(xml, diag, tags, sf, orgId, mv, cau, irs, stimuli, assetTransformContext);
28310
+ 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);
28040
28311
  return {
28041
28312
  choiceInteraction: wrapSourceFirst(convertMcqToLearnosity),
28042
28313
  textEntryInteraction: wrapSourceFirst(convertTextEntryToLearnosity),
@@ -28059,8 +28330,14 @@ const CONVERTER_MAP = getConverterMap();
28059
28330
  * Strategy: Call each individual converter for its interaction type,
28060
28331
  * then combine all questions and widgets into a single composite item
28061
28332
  */
28062
- function convertMixedInteractionsToLearnosity(inputXml, diagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource, fileAccess, packageRoot) {
28333
+ function convertMixedInteractionsToLearnosity(inputXml, diagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource, fileAccess, packageRoot, assetTransformContext) {
28063
28334
  const metadata = extractItemMetadata(inputXml);
28335
+ const itemRef = assetTransformContext?.finalItemReference ?? generateItemReference(metadata.identifier ?? "mixed_item", itemReferenceSource, sourceFile);
28336
+ const transformContext = {
28337
+ finalItemReference: itemRef,
28338
+ preserveAssetFilenames: assetTransformContext?.preserveAssetFilenames ?? false,
28339
+ sourceHrefBase: assetTransformContext?.sourceHrefBase
28340
+ };
28064
28341
  const { segments } = segmentItemBodyByInteractions(inputXml);
28065
28342
  const stimuliByType = /* @__PURE__ */ new Map();
28066
28343
  for (const segment of segments) {
@@ -28142,7 +28419,8 @@ function convertMixedInteractionsToLearnosity(inputXml, diagnostics, lomTags, or
28142
28419
  const template = normalizeFinalText(transformAssetUrls(rawTemplate, {
28143
28420
  organisationId,
28144
28421
  mediaVault,
28145
- customAssetUrl
28422
+ customAssetUrl,
28423
+ ...transformContext
28146
28424
  }));
28147
28425
  if (groupEntries.length === 1 && /{{response}}(?:<\/[^>]+>|\s)*$/.test(rawTemplate.trim())) {
28148
28426
  let stimulusRaw = rawTemplate.replace(/{{response}}(?:<\/[^>]+>|\s)*$/, "").trim();
@@ -28150,7 +28428,8 @@ function convertMixedInteractionsToLearnosity(inputXml, diagnostics, lomTags, or
28150
28428
  const stimulus = normalizeFinalText(transformAssetUrls(stimulusRaw, {
28151
28429
  organisationId,
28152
28430
  mediaVault,
28153
- customAssetUrl
28431
+ customAssetUrl,
28432
+ ...transformContext
28154
28433
  }));
28155
28434
  const entry = groupEntries[0];
28156
28435
  const allCorrectResponses = entry.correctResponses ?? (entry.correctResponse ? [entry.correctResponse] : []);
@@ -28276,7 +28555,7 @@ function convertMixedInteractionsToLearnosity(inputXml, diagnostics, lomTags, or
28276
28555
  continue;
28277
28556
  }
28278
28557
  const converter = CONVERTER_MAP[group.type];
28279
- if (converter) processResult(converter(inputXml, subDiagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource, group.stimuli, fileAccess, packageRoot), subDiagnostics);
28558
+ if (converter) processResult(converter(inputXml, subDiagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource, group.stimuli, transformContext, fileAccess, packageRoot), subDiagnostics);
28280
28559
  }
28281
28560
  if (allQuestions.length === 0) {
28282
28561
  diagnostics.push({
@@ -28299,9 +28578,16 @@ function convertMixedInteractionsToLearnosity(inputXml, diagnostics, lomTags, or
28299
28578
  passageContent = transformAssetUrls(rawContent, {
28300
28579
  organisationId,
28301
28580
  mediaVault,
28302
- customAssetUrl
28581
+ customAssetUrl,
28582
+ ...transformContext
28583
+ });
28584
+ } catch (error) {
28585
+ if (isUnsafeQtiAssetHrefError(error)) diagnostics.push({
28586
+ code: DiagnosticCode.QTI_ASSET_HREF_UNSAFE,
28587
+ level: "error",
28588
+ file: sourceFile ?? "passage",
28589
+ message: error.message
28303
28590
  });
28304
- } catch {
28305
28591
  passageContent = rawContent;
28306
28592
  }
28307
28593
  allFeatures.push({
@@ -28333,7 +28619,7 @@ function convertMixedInteractionsToLearnosity(inputXml, diagnostics, lomTags, or
28333
28619
  const content = `<div class="row"><div class="col-xs-12">${[...featureSpans, ...questionSpans].join("")}</div></div>`;
28334
28620
  const item = {
28335
28621
  item: {
28336
- reference: generateItemReference(metadata.identifier ?? "mixed_item", itemReferenceSource, sourceFile),
28622
+ reference: itemRef,
28337
28623
  title: metadata.title ?? void 0,
28338
28624
  content,
28339
28625
  definition: { widgets: allWidgets },
@@ -28379,8 +28665,13 @@ function resolvePassageObjects(html, sourceFile, resolvePassageFile) {
28379
28665
  /**
28380
28666
  * Convert passage-only item to Learnosity format with sharedpassage feature
28381
28667
  */
28382
- function convertPassageToLearnosity(parsed, diagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource, fileAccess) {
28383
- const itemRef = generateItemReference(parsed.identifier, itemReferenceSource, sourceFile);
28668
+ function convertPassageToLearnosity(parsed, diagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource, fileAccess, assetTransformContext) {
28669
+ const itemRef = assetTransformContext?.finalItemReference ?? generateItemReference(parsed.identifier, itemReferenceSource, sourceFile);
28670
+ const transformContext = {
28671
+ finalItemReference: itemRef,
28672
+ preserveAssetFilenames: assetTransformContext?.preserveAssetFilenames ?? false,
28673
+ sourceHrefBase: assetTransformContext?.sourceHrefBase
28674
+ };
28384
28675
  const featureRef = `passage-${md5hex(getPassageDataPath(parsed.content) ?? itemRef).substring(0, 8)}`;
28385
28676
  const resolvedContent = resolvePassageObjects(parsed.content, sourceFile, fileAccess?.resolvePassageFile.bind(fileAccess));
28386
28677
  let content;
@@ -28388,11 +28679,12 @@ function convertPassageToLearnosity(parsed, diagnostics, lomTags, organisationId
28388
28679
  content = transformAssetUrls(resolvedContent, {
28389
28680
  organisationId,
28390
28681
  mediaVault,
28391
- customAssetUrl
28682
+ customAssetUrl,
28683
+ ...transformContext
28392
28684
  });
28393
28685
  } catch (error) {
28394
28686
  diagnostics.push({
28395
- code: DiagnosticCode.LRN_SCHEMA_INVALID,
28687
+ code: isUnsafeQtiAssetHrefError(error) ? DiagnosticCode.QTI_ASSET_HREF_UNSAFE : DiagnosticCode.LRN_SCHEMA_INVALID,
28396
28688
  level: "error",
28397
28689
  file: sourceFile ?? "assessmentItem",
28398
28690
  message: error instanceof Error ? error.message : "Failed to transform asset URLs"
@@ -28782,20 +29074,28 @@ function readAssessmentItemUpload(inputXml) {
28782
29074
  * and the file limit from `maxChoices` (see readAssessmentItemUpload / the
28783
29075
  * serializer). fileupload questions are unscored, so there is no validation.
28784
29076
  */
28785
- function convertUploadToLearnosity(inputXml, diagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource) {
29077
+ function convertUploadToLearnosity(inputXml, diagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource, _stimulusOverride, assetTransformContext) {
28786
29078
  const parsed = readAssessmentItemUpload(inputXml);
28787
29079
  diagnostics.push(...parsed.diagnostics);
28788
29080
  if (parsed.diagnostics.some((d) => d.level === "error")) return { diagnostics };
28789
- const itemRef = generateItemReference(parsed.identifier ?? "item", itemReferenceSource, sourceFile);
29081
+ const generatedItemRef = generateItemReference(parsed.identifier ?? "item", itemReferenceSource, sourceFile);
29082
+ const itemRef = assetTransformContext?.finalItemReference ?? parsed.identifier ?? generatedItemRef;
29083
+ const transformContext = {
29084
+ finalItemReference: itemRef,
29085
+ preserveAssetFilenames: assetTransformContext?.preserveAssetFilenames ?? false,
29086
+ sourceHrefBase: assetTransformContext?.sourceHrefBase
29087
+ };
28790
29088
  const questionRef = md5hex(itemRef + (parsed.responseIdentifier ?? "fileupload"));
28791
29089
  const questionData = { type: "fileupload" };
28792
29090
  if (parsed.stimulus) try {
28793
29091
  questionData.stimulus = transformAssetUrls(parsed.stimulus, {
28794
29092
  organisationId,
28795
29093
  mediaVault,
28796
- customAssetUrl
29094
+ customAssetUrl,
29095
+ ...transformContext
28797
29096
  });
28798
- } catch {
29097
+ } catch (error) {
29098
+ if (isUnsafeQtiAssetHrefError(error)) throw error;
28799
29099
  questionData.stimulus = parsed.stimulus;
28800
29100
  }
28801
29101
  for (const suffix of parsed.allowedFileTypes) questionData[`allow_${suffix}`] = true;
@@ -28803,7 +29103,7 @@ function convertUploadToLearnosity(inputXml, diagnostics, lomTags, organisationI
28803
29103
  const content = `<span class="learnosity-response question-${questionRef}"></span>`;
28804
29104
  const item = {
28805
29105
  item: {
28806
- reference: parsed.identifier ?? itemRef,
29106
+ reference: itemRef,
28807
29107
  title: parsed.title ?? void 0,
28808
29108
  content,
28809
29109
  definition: { widgets: [{
@@ -28838,9 +29138,19 @@ function convertUploadToLearnosity(inputXml, diagnostics, lomTags, organisationI
28838
29138
  * - Rejects DOCTYPE / ENTITY declarations up-front (DTD not allowed).
28839
29139
  * - Uses streaming parsers for all interaction types.
28840
29140
  */
29141
+ function getAssetSourceHrefBase(opts) {
29142
+ if (opts.sourceHrefBase) return opts.sourceHrefBase;
29143
+ const source = opts.sourceFile ?? opts.inputPath;
29144
+ if (!source) return;
29145
+ const normalized = source.replaceAll("\\", "/");
29146
+ return normalized.startsWith("/") || /^[A-Za-z]:/.test(normalized) || /^[A-Za-z][A-Za-z\d+.-]*:/.test(normalized) ? normalized.slice(normalized.lastIndexOf("/") + 1) : normalized;
29147
+ }
28841
29148
  /**
28842
29149
  * Supported interaction type names for counting
28843
29150
  */
29151
+ function isUnsafeAssetHrefError$1(error) {
29152
+ return error instanceof Error && (error.message.startsWith("Unsafe QTI asset href:") || error.message.startsWith("QTI asset href has no filename:"));
29153
+ }
28844
29154
  const INTERACTION_NAMES = [
28845
29155
  "choiceInteraction",
28846
29156
  "textEntryInteraction",
@@ -28906,19 +29216,71 @@ function countAllInteractions(xml) {
28906
29216
  };
28907
29217
  }
28908
29218
  const SINGLE_INTERACTION_CONVERTERS = /* @__PURE__ */ new Map([
28909
- ["choiceInteraction", (xml, diag, lom, opts, stim) => convertMcqToLearnosity(xml, diag, lom, opts.sourceFile, opts.organisationId, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource, stim)],
28910
- ["textEntryInteraction", (xml, diag, lom, opts, stim) => convertTextEntryToLearnosity(xml, diag, lom, opts.sourceFile, opts.organisationId, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource, stim)],
28911
- ["extendedTextInteraction", (xml, diag, lom, opts, stim) => convertExtendedTextToLearnosity(xml, diag, lom, opts.sourceFile, opts.organisationId, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource, stim)],
28912
- ["inlineChoiceInteraction", (xml, diag, lom, opts) => convertInlineChoiceToLearnosity(xml, diag, lom, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource)],
28913
- ["matchInteraction", (xml, diag, lom, opts) => convertMatchToLearnosity(xml, diag, lom, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource)],
28914
- ["gapMatchInteraction", (xml, diag, lom, opts) => convertGapMatchToLearnosity(xml, diag, lom, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource)],
28915
- ["orderInteraction", (xml, diag, lom, opts) => convertOrderToLearnosity(xml, diag, lom, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource)],
28916
- ["hotspotInteraction", (xml, diag, lom, opts) => convertHotspotToLearnosity(xml, diag, lom, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource, opts.fileAccess, opts.packageRoot)],
28917
- ["hottextInteraction", (xml, diag, lom, opts) => convertHottextToLearnosity(xml, diag, lom, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource)],
28918
- ["graphicGapMatchInteraction", (xml, diag, lom, opts) => convertGraphicGapMatchToLearnosity(xml, diag, lom, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource)],
28919
- ["drawingInteraction", (xml, diag, lom, opts) => convertDrawingToLearnosity(xml, diag, lom, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource)],
28920
- ["associateInteraction", (xml, diag, lom, opts) => convertAssociationToLearnosity(xml, diag, lom, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource)],
28921
- ["uploadInteraction", (xml, diag, lom, opts) => convertUploadToLearnosity(xml, diag, lom, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource)]
29219
+ ["choiceInteraction", (xml, diag, lom, opts, stim) => convertMcqToLearnosity(xml, diag, lom, opts.sourceFile, opts.organisationId, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource, stim, {
29220
+ finalItemReference: opts.finalItemReference,
29221
+ preserveAssetFilenames: opts.preserveAssetFilenames ?? false,
29222
+ sourceHrefBase: getAssetSourceHrefBase(opts)
29223
+ })],
29224
+ ["textEntryInteraction", (xml, diag, lom, opts, stim) => convertTextEntryToLearnosity(xml, diag, lom, opts.sourceFile, opts.organisationId, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource, stim, {
29225
+ finalItemReference: opts.finalItemReference,
29226
+ preserveAssetFilenames: opts.preserveAssetFilenames ?? false,
29227
+ sourceHrefBase: getAssetSourceHrefBase(opts)
29228
+ })],
29229
+ ["extendedTextInteraction", (xml, diag, lom, opts, stim) => convertExtendedTextToLearnosity(xml, diag, lom, opts.sourceFile, opts.organisationId, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource, stim, {
29230
+ finalItemReference: opts.finalItemReference,
29231
+ preserveAssetFilenames: opts.preserveAssetFilenames ?? false,
29232
+ sourceHrefBase: getAssetSourceHrefBase(opts)
29233
+ })],
29234
+ ["inlineChoiceInteraction", (xml, diag, lom, opts) => convertInlineChoiceToLearnosity(xml, diag, lom, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource, void 0, {
29235
+ finalItemReference: opts.finalItemReference,
29236
+ preserveAssetFilenames: opts.preserveAssetFilenames ?? false,
29237
+ sourceHrefBase: getAssetSourceHrefBase(opts)
29238
+ })],
29239
+ ["matchInteraction", (xml, diag, lom, opts) => convertMatchToLearnosity(xml, diag, lom, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource, void 0, {
29240
+ finalItemReference: opts.finalItemReference,
29241
+ preserveAssetFilenames: opts.preserveAssetFilenames ?? false,
29242
+ sourceHrefBase: getAssetSourceHrefBase(opts)
29243
+ })],
29244
+ ["gapMatchInteraction", (xml, diag, lom, opts) => convertGapMatchToLearnosity(xml, diag, lom, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource, void 0, {
29245
+ finalItemReference: opts.finalItemReference,
29246
+ preserveAssetFilenames: opts.preserveAssetFilenames ?? false,
29247
+ sourceHrefBase: getAssetSourceHrefBase(opts)
29248
+ })],
29249
+ ["orderInteraction", (xml, diag, lom, opts) => convertOrderToLearnosity(xml, diag, lom, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource, void 0, {
29250
+ finalItemReference: opts.finalItemReference,
29251
+ preserveAssetFilenames: opts.preserveAssetFilenames ?? false,
29252
+ sourceHrefBase: getAssetSourceHrefBase(opts)
29253
+ })],
29254
+ ["hotspotInteraction", (xml, diag, lom, opts) => convertHotspotToLearnosity(xml, diag, lom, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource, opts.fileAccess, opts.packageRoot, {
29255
+ finalItemReference: opts.finalItemReference,
29256
+ preserveAssetFilenames: opts.preserveAssetFilenames ?? false,
29257
+ sourceHrefBase: getAssetSourceHrefBase(opts)
29258
+ })],
29259
+ ["hottextInteraction", (xml, diag, lom, opts) => convertHottextToLearnosity(xml, diag, lom, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource, void 0, {
29260
+ finalItemReference: opts.finalItemReference,
29261
+ preserveAssetFilenames: opts.preserveAssetFilenames ?? false,
29262
+ sourceHrefBase: getAssetSourceHrefBase(opts)
29263
+ })],
29264
+ ["graphicGapMatchInteraction", (xml, diag, lom, opts) => convertGraphicGapMatchToLearnosity(xml, diag, lom, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource, void 0, {
29265
+ finalItemReference: opts.finalItemReference,
29266
+ preserveAssetFilenames: opts.preserveAssetFilenames ?? false,
29267
+ sourceHrefBase: getAssetSourceHrefBase(opts)
29268
+ })],
29269
+ ["drawingInteraction", (xml, diag, lom, opts) => convertDrawingToLearnosity(xml, diag, lom, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource, void 0, {
29270
+ finalItemReference: opts.finalItemReference,
29271
+ preserveAssetFilenames: opts.preserveAssetFilenames ?? false,
29272
+ sourceHrefBase: getAssetSourceHrefBase(opts)
29273
+ })],
29274
+ ["associateInteraction", (xml, diag, lom, opts) => convertAssociationToLearnosity(xml, diag, lom, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource, void 0, {
29275
+ finalItemReference: opts.finalItemReference,
29276
+ preserveAssetFilenames: opts.preserveAssetFilenames ?? false,
29277
+ sourceHrefBase: getAssetSourceHrefBase(opts)
29278
+ })],
29279
+ ["uploadInteraction", (xml, diag, lom, opts) => convertUploadToLearnosity(xml, diag, lom, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource, void 0, {
29280
+ finalItemReference: opts.finalItemReference,
29281
+ preserveAssetFilenames: opts.preserveAssetFilenames ?? false,
29282
+ sourceHrefBase: getAssetSourceHrefBase(opts)
29283
+ })]
28922
29284
  ]);
28923
29285
  /**
28924
29286
  * Dispatch to the appropriate single-interaction converter
@@ -28944,9 +29306,18 @@ function dispatchSingleInteractionConverter(interactionType, inputXml, count, di
28944
29306
  passageContent = transformAssetUrls(rawContent, {
28945
29307
  organisationId: opts.organisationId,
28946
29308
  mediaVault: opts.mediaVault,
28947
- customAssetUrl: opts.customAssetUrl
29309
+ customAssetUrl: opts.customAssetUrl,
29310
+ finalItemReference: opts.finalItemReference ?? result.item.item.reference,
29311
+ preserveAssetFilenames: opts.preserveAssetFilenames ?? false,
29312
+ sourceHrefBase: getAssetSourceHrefBase(opts)
29313
+ });
29314
+ } catch (error) {
29315
+ if (isUnsafeAssetHrefError$1(error)) diagnostics.push({
29316
+ code: DiagnosticCode.QTI_ASSET_HREF_UNSAFE,
29317
+ level: "error",
29318
+ file: opts.sourceFile ?? "passage",
29319
+ message: error.message
28948
29320
  });
28949
- } catch {
28950
29321
  passageContent = rawContent;
28951
29322
  }
28952
29323
  result.item.features = [...result.item.features, {
@@ -28994,8 +29365,16 @@ function handleNoInteractions(inputXml, diagnostics, allInteractions, lomTags, o
28994
29365
  }
28995
29366
  const passageResult = readAssessmentItemPassage(inputXml);
28996
29367
  diagnostics.push(...addFileContextIfProvided(passageResult.diagnostics, opts.sourceFile));
28997
- if (passageResult.data) return convertPassageToLearnosity(passageResult.data, diagnostics, lomTags, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource, opts.fileAccess);
28998
- const mcqResult = convertMcqToLearnosity(inputXml, diagnostics, lomTags, opts.sourceFile, opts.organisationId, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource);
29368
+ if (passageResult.data) return convertPassageToLearnosity(passageResult.data, diagnostics, lomTags, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource, opts.fileAccess, {
29369
+ finalItemReference: opts.finalItemReference,
29370
+ preserveAssetFilenames: opts.preserveAssetFilenames ?? false,
29371
+ sourceHrefBase: getAssetSourceHrefBase(opts)
29372
+ });
29373
+ const mcqResult = convertMcqToLearnosity(inputXml, diagnostics, lomTags, opts.sourceFile, opts.organisationId, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource, void 0, {
29374
+ finalItemReference: opts.finalItemReference,
29375
+ preserveAssetFilenames: opts.preserveAssetFilenames ?? false,
29376
+ sourceHrefBase: getAssetSourceHrefBase(opts)
29377
+ });
28999
29378
  if (diagnostics.some((d) => d.code === DiagnosticCode.LRN_SCHEMA_INVALID)) return mcqResult;
29000
29379
  return { diagnostics };
29001
29380
  }
@@ -29041,14 +29420,18 @@ function convertQtiAssessmentItemToLearnosity(inputXml, opts = {}) {
29041
29420
  const { counts, allInteractions } = countAllInteractions(inputXml);
29042
29421
  const presentTypes = INTERACTION_NAMES.filter((name) => counts[name] > 0);
29043
29422
  if (presentTypes.reduce((sum, name) => sum + counts[name], 0) === 0) return handleNoInteractions(inputXml, diagnostics, allInteractions, lomTags, opts);
29044
- if (presentTypes.length > 1) return convertMixedInteractionsToLearnosity(inputXml, diagnostics, lomTags, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource, opts.fileAccess, opts.packageRoot);
29423
+ if (presentTypes.length > 1) return convertMixedInteractionsToLearnosity(inputXml, diagnostics, lomTags, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource, opts.fileAccess, opts.packageRoot, {
29424
+ finalItemReference: opts.finalItemReference,
29425
+ preserveAssetFilenames: opts.preserveAssetFilenames ?? false,
29426
+ sourceHrefBase: getAssetSourceHrefBase(opts)
29427
+ });
29045
29428
  return dispatchSingleInteractionConverter(presentTypes[0], inputXml, counts[presentTypes[0]], diagnostics, lomTags, opts);
29046
29429
  } catch (error) {
29047
29430
  diagnostics.push({
29048
- code: DiagnosticCode.LRN_SCHEMA_INVALID,
29431
+ code: isUnsafeAssetHrefError$1(error) ? DiagnosticCode.QTI_ASSET_HREF_UNSAFE : DiagnosticCode.LRN_SCHEMA_INVALID,
29049
29432
  level: "error",
29050
- file: "root",
29051
- message: `Failed to parse QTI XML: ${error instanceof Error ? error.message : "Unknown error"}`
29433
+ file: opts.sourceFile ?? "root",
29434
+ message: isUnsafeAssetHrefError$1(error) ? error.message : `Failed to parse QTI XML: ${error instanceof Error ? error.message : "Unknown error"}`
29052
29435
  });
29053
29436
  return { diagnostics };
29054
29437
  }
@@ -29164,6 +29547,7 @@ function convertQtiToLearnosity(input, opts) {
29164
29547
  organisationId: opts.organisationId,
29165
29548
  mediaVault: opts.mediaVault,
29166
29549
  customAssetUrl: opts.customAssetUrl,
29550
+ preserveAssetFilenames: opts.preserveAssetFilenames ?? false,
29167
29551
  itemReferenceSource: opts.itemReferenceSource,
29168
29552
  fileAccess: opts.fileAccess
29169
29553
  });
@@ -31382,6 +31766,108 @@ function textToBytes(text) {
31382
31766
  return strToU8(text);
31383
31767
  }
31384
31768
  //#endregion
31769
+ //#region src/qti-to-learnosity/utils/assetFilenameRegistry.ts
31770
+ /**
31771
+ * Browser-safe registry for item-scoped QTI asset filenames.
31772
+ *
31773
+ * Filename selection belongs to asset identity, not package traversal. Keeping
31774
+ * both identity and filename indexes here lets URL and bundle seams validate
31775
+ * the same contract before either one can overwrite a physical asset.
31776
+ */
31777
+ var AssetFilenameConflictError = class extends Error {
31778
+ kind;
31779
+ mode;
31780
+ filename;
31781
+ existing;
31782
+ incoming;
31783
+ constructor(kind, mode, filename, existing, incoming) {
31784
+ const existingIdentity = existing.serializedIdentity;
31785
+ const incomingIdentity = incoming.serializedIdentity;
31786
+ const message = kind === "identity-bytes" ? `Asset identity conflict in ${mode} mode for ${incomingIdentity}: filename "${filename}" was registered with different bytes.` : `Asset filename conflict in ${mode} mode: filename "${filename}" is assigned to both ${existingIdentity} and ${incomingIdentity}.`;
31787
+ super(message);
31788
+ this.name = "AssetFilenameConflictError";
31789
+ this.kind = kind;
31790
+ this.mode = mode;
31791
+ this.filename = filename;
31792
+ this.existing = existing;
31793
+ this.incoming = incoming;
31794
+ }
31795
+ };
31796
+ function bytesEqual(left, right) {
31797
+ if (left.length !== right.length) return false;
31798
+ for (let index = 0; index < left.length; index += 1) if (left[index] !== right[index]) return false;
31799
+ return true;
31800
+ }
31801
+ function cloneBytes(bytes) {
31802
+ return new Uint8Array(bytes);
31803
+ }
31804
+ /**
31805
+ * Track selected asset names and their bytes for one conversion.
31806
+ *
31807
+ * Registering an equivalent identity repeatedly is idempotent when its bytes
31808
+ * agree. A filename can never silently change owners, and an identity can
31809
+ * never silently change bytes, in either hashed or preserve mode.
31810
+ */
31811
+ var AssetFilenameRegistry = class {
31812
+ preserveAssetFilenames;
31813
+ byIdentity = /* @__PURE__ */ new Map();
31814
+ byFilename = /* @__PURE__ */ new Map();
31815
+ constructor(preserveAssetFilenames = false) {
31816
+ this.preserveAssetFilenames = preserveAssetFilenames;
31817
+ }
31818
+ get mode() {
31819
+ return this.preserveAssetFilenames ? "preserve" : "hashed";
31820
+ }
31821
+ get size() {
31822
+ return this.byIdentity.size;
31823
+ }
31824
+ /**
31825
+ * Register an asset and return its selected filename and bytes.
31826
+ *
31827
+ * The input href is canonicalized before both indexes are consulted, so
31828
+ * equivalent directory and ZIP representations reuse one registration.
31829
+ */
31830
+ register(finalItemReference, qtiAssetHref, bytes) {
31831
+ const canonicalHref = canonicalizeQtiAssetHref(qtiAssetHref);
31832
+ const serializedIdentity = serializeQtiAssetIdentity(finalItemReference, canonicalHref);
31833
+ const filename = selectQtiAssetFilename(finalItemReference, canonicalHref, this.preserveAssetFilenames);
31834
+ const incoming = {
31835
+ finalItemReference,
31836
+ qtiAssetHref: canonicalHref,
31837
+ serializedIdentity,
31838
+ filename,
31839
+ bytes: cloneBytes(bytes)
31840
+ };
31841
+ const existingIdentity = this.byIdentity.get(serializedIdentity);
31842
+ if (existingIdentity) {
31843
+ if (!bytesEqual(existingIdentity.bytes, incoming.bytes)) throw new AssetFilenameConflictError("identity-bytes", this.mode, filename, existingIdentity, incoming);
31844
+ return existingIdentity;
31845
+ }
31846
+ const existingFilename = this.byFilename.get(filename);
31847
+ if (existingFilename) throw new AssetFilenameConflictError("filename-identity", this.mode, filename, existingFilename, incoming);
31848
+ this.byIdentity.set(serializedIdentity, incoming);
31849
+ this.byFilename.set(filename, incoming);
31850
+ return incoming;
31851
+ }
31852
+ /** Look up a previously registered canonical identity without registering it. */
31853
+ get(finalItemReference, qtiAssetHref) {
31854
+ return this.byIdentity.get(serializeQtiAssetIdentity(finalItemReference, qtiAssetHref));
31855
+ }
31856
+ /** Look up an asset by its selected bundle-relative filename. */
31857
+ getByFilename(filename) {
31858
+ return this.byFilename.get(filename);
31859
+ }
31860
+ /** Iterate registrations in deterministic registration order. */
31861
+ entries() {
31862
+ return this.byIdentity.values();
31863
+ }
31864
+ /** Remove all registrations so the registry can be reused for a new conversion. */
31865
+ clear() {
31866
+ this.byIdentity.clear();
31867
+ this.byFilename.clear();
31868
+ }
31869
+ };
31870
+ //#endregion
31385
31871
  //#region src/qti-to-learnosity/convertQtiPackageToLearnosityBundle.ts
31386
31872
  /**
31387
31873
  * QTI Content Package → Learnosity Bundle converter (v1)
@@ -31429,57 +31915,69 @@ function ensureFailedItemDiagnostic(itemDiagnostics, href) {
31429
31915
  }];
31430
31916
  }
31431
31917
  /**
31432
- * Normalize a forward-slash relative path (collapse `.`/`//`, resolve `..`).
31433
- * Pure replacement for `node:path`'s `normalize(...).split(sep).join('/')` on
31434
- * the forward-slash paths used as entry keys.
31435
- */
31436
- function normalizePosix(p) {
31437
- const parts = [];
31438
- for (const seg of p.split("/")) {
31439
- if (seg === "" || seg === ".") continue;
31440
- if (seg === "..") {
31441
- parts.pop();
31442
- continue;
31443
- }
31444
- parts.push(seg);
31445
- }
31446
- return parts.join("/");
31447
- }
31448
- /**
31449
31918
  * Normalize href path by removing leading ./ sequences
31450
31919
  * This ensures manifest hrefs like "./items/foo.xml" match entries stored as "items/foo.xml"
31451
31920
  */
31452
31921
  function normalizeHref(href) {
31453
31922
  return href.replace(/^(\.\/)+/, "");
31454
31923
  }
31455
- /**
31456
- * File extensions treated as copyable assets (images, audio, video, styles,
31457
- * fonts, etc.). Undeclared files with these extensions are copied to the bundle
31458
- * even if the manifest omits them.
31459
- */
31460
- const ASSET_EXTENSIONS = [
31461
- ".png",
31462
- ".jpg",
31463
- ".jpeg",
31464
- ".gif",
31465
- ".svg",
31466
- ".webp",
31467
- ".bmp",
31468
- ".ico",
31469
- ".mp3",
31470
- ".mp4",
31471
- ".wav",
31472
- ".ogg",
31473
- ".webm",
31474
- ".m4a",
31475
- ".css",
31476
- ".woff",
31477
- ".woff2",
31478
- ".ttf",
31479
- ".eot",
31480
- ".pdf",
31481
- ".json"
31482
- ];
31924
+ function readAssessmentItemIdentifier(inputXml, fallback) {
31925
+ let identifier = fallback;
31926
+ const parser = new import_saxes.SaxesParser({ xmlns: true });
31927
+ parser.on("opentag", (tag) => {
31928
+ if ((tag.local ?? tag.name) === "assessmentItem") identifier = getAttr$5(tag, "identifier") ?? fallback;
31929
+ });
31930
+ try {
31931
+ parser.write(inputXml).close();
31932
+ } catch {}
31933
+ return identifier;
31934
+ }
31935
+ function uniqueItemReference(baseReference, sourceHref, items) {
31936
+ if (!items.has(baseReference)) return baseReference;
31937
+ const readableCandidate = `${baseReference}_${normalizeHref(sourceHref).split("/").at(-1)?.replace(/\.xml$/i, "") ?? "item"}`;
31938
+ if (!items.has(readableCandidate)) return readableCandidate;
31939
+ const sourceDigest = md5hex(normalizeHref(sourceHref));
31940
+ let candidate = `${readableCandidate}_${sourceDigest}`;
31941
+ let suffix = 1;
31942
+ while (items.has(candidate)) {
31943
+ candidate = `${readableCandidate}_${sourceDigest}_${suffix}`;
31944
+ suffix += 1;
31945
+ }
31946
+ return candidate;
31947
+ }
31948
+ function isUnsafeAssetHrefError(error) {
31949
+ return error instanceof Error && (error.message.startsWith("Unsafe QTI asset href:") || error.message.startsWith("QTI asset href has no filename:"));
31950
+ }
31951
+ function hasAssetNamingDiagnostic(diagnostics) {
31952
+ return diagnostics.some((diagnostic) => diagnostic.code === DiagnosticCode.QTI_ASSET_HREF_UNSAFE || diagnostic.code === DiagnosticCode.QTI_ASSET_FILENAME_CONFLICT || diagnostic.code === DiagnosticCode.QTI_ASSET_IDENTITY_BYTES_CONFLICT);
31953
+ }
31954
+ /**
31955
+ * Resolve a local QTI reference exactly as asset URL transformation does.
31956
+ * References without a leading dot segment are already package-relative;
31957
+ * `./` and `../` references are resolved from the item source directory.
31958
+ */
31959
+ function resolvePackageAssetHref(href, sourceHrefBase) {
31960
+ const cleanHref = href.split(/[?#]/, 1)[0].replaceAll("\\", "/");
31961
+ if (!cleanHref || /^https?:\/\//i.test(cleanHref) || cleanHref.startsWith("//") || cleanHref.startsWith("data:") || cleanHref.includes("assets.learnosity.com") || cleanHref.includes("media-vault.learnosity.com")) return;
31962
+ if (!(/^\.\.?\//.test(cleanHref) || !cleanHref.includes("/"))) return canonicalizeQtiAssetHref(cleanHref);
31963
+ const baseHref = canonicalizeQtiAssetHref(sourceHrefBase);
31964
+ return canonicalizeQtiAssetHref(`${baseHref.slice(0, baseHref.lastIndexOf("/") + 1)}${cleanHref}`);
31965
+ }
31966
+ /** Extract local asset-bearing attributes from item XML or resolved passage HTML. */
31967
+ function extractAssetHrefs(content) {
31968
+ const hrefs = [];
31969
+ const seen = /* @__PURE__ */ new Set();
31970
+ const attributePattern = /\b(?:src|data|href)\s*=\s*["']([^"']+)["']/gi;
31971
+ let match;
31972
+ while ((match = attributePattern.exec(content)) !== null) if (!seen.has(match[1])) {
31973
+ seen.add(match[1]);
31974
+ hrefs.push(match[1]);
31975
+ }
31976
+ return hrefs;
31977
+ }
31978
+ function isCopyableAssetPath(path) {
31979
+ return isSupportedQtiAssetPath(path);
31980
+ }
31483
31981
  /**
31484
31982
  * Merge two tag objects, combining tag values for each tag type
31485
31983
  * Source tags are merged into base tags, avoiding duplicates
@@ -31550,7 +32048,7 @@ function convertQtiPackageToLearnosityBundle(input, opts) {
31550
32048
  if (needed.has(normalized)) return true;
31551
32049
  const lower = normalized.toLowerCase();
31552
32050
  if (lower.endsWith(".html")) return false;
31553
- return lower.endsWith(".xml") || ASSET_EXTENSIONS.some((ext) => lower.endsWith(ext));
32051
+ return lower.endsWith(".xml") || isSupportedQtiAssetPath(normalized);
31554
32052
  };
31555
32053
  }
31556
32054
  const unzipped = unzipToEntries(input.zipBytes, label, filter ? { filter } : void 0);
@@ -31585,6 +32083,7 @@ function convertQtiPackageToLearnosityBundle(input, opts) {
31585
32083
  }
31586
32084
  const items = /* @__PURE__ */ new Map();
31587
32085
  const itemFilenames = /* @__PURE__ */ new Map();
32086
+ const itemAssetContexts = [];
31588
32087
  const qtiRefToMd5Refs = /* @__PURE__ */ new Map();
31589
32088
  const convertedSourceFiles = [];
31590
32089
  const failedSourceFiles = [];
@@ -31647,23 +32146,33 @@ function convertQtiPackageToLearnosityBundle(input, opts) {
31647
32146
  }
31648
32147
  const itemXml = decodeUtf8(itemEntry.data);
31649
32148
  const itemFilePath = opts?.sourceDir ? posixJoin(opts.sourceDir, itemResource.href) : itemResource.href;
32149
+ const baseItemReference = generateItemReference(readAssessmentItemIdentifier(itemXml, itemResource.identifier), opts?.itemReferenceSource, itemFilePath);
32150
+ const finalItemReference = uniqueItemReference(baseItemReference, itemResource.href, items);
31650
32151
  const itemResult = convertQtiAssessmentItemToLearnosity(itemXml, {
31651
32152
  inputPath: itemFilePath,
31652
32153
  sourceFile: itemFilePath,
31653
32154
  organisationId: opts?.organisationId,
31654
32155
  mediaVault: opts?.mediaVault,
31655
32156
  customAssetUrl: opts?.customAssetUrl,
32157
+ preserveAssetFilenames: opts?.preserveAssetFilenames ?? false,
31656
32158
  itemReferenceSource: opts?.itemReferenceSource,
31657
32159
  fileAccess: opts?.fileAccess,
31658
- packageRoot: opts?.sourceDir
32160
+ packageRoot: opts?.sourceDir,
32161
+ finalItemReference,
32162
+ sourceHrefBase: itemResource.href
31659
32163
  });
31660
32164
  diagnostics.push(...itemResult.diagnostics);
31661
32165
  if (itemResult.item) {
31662
32166
  let md5Ref = itemResult.item.item.reference;
32167
+ if (finalItemReference !== baseItemReference) diagnostics.push({
32168
+ code: DiagnosticCode.QTI_PACKAGE_DUPLICATE_IDENTIFIER,
32169
+ level: "warning",
32170
+ file: itemResource.href,
32171
+ message: `Duplicate item reference "${finalItemReference}" disambiguated from "${baseItemReference}" (source: ${itemResource.href})`
32172
+ });
31663
32173
  if (items.has(md5Ref)) {
31664
- const hrefParts = itemResource.href.split("/");
31665
- const filename = hrefParts[hrefParts.length - 1].replace(/\.xml$/i, "");
31666
- md5Ref = `${md5Ref}_${filename}`;
32174
+ const originalRef = md5Ref;
32175
+ md5Ref = uniqueItemReference(finalItemReference, itemResource.href, items);
31667
32176
  itemResult.item.item.reference = md5Ref;
31668
32177
  for (const question of itemResult.item.questions) {
31669
32178
  const oldRef = question.reference;
@@ -31677,7 +32186,7 @@ function convertQtiPackageToLearnosityBundle(input, opts) {
31677
32186
  code: DiagnosticCode.QTI_PACKAGE_DUPLICATE_IDENTIFIER,
31678
32187
  level: "warning",
31679
32188
  file: itemResource.href,
31680
- message: `Duplicate item reference "${itemResult.item.item.reference}" disambiguated from "${md5Ref.replace(`_${filename}`, "")}" (source: ${itemResource.href})`
32189
+ message: `Duplicate item reference "${md5Ref}" disambiguated from "${originalRef}" (source: ${itemResource.href})`
31681
32190
  });
31682
32191
  }
31683
32192
  if (itemResource.metadataXml) try {
@@ -31697,9 +32206,15 @@ function convertQtiPackageToLearnosityBundle(input, opts) {
31697
32206
  });
31698
32207
  }
31699
32208
  items.set(md5Ref, itemResult.item);
32209
+ itemAssetContexts.push({
32210
+ finalItemReference: md5Ref,
32211
+ sourceHref: itemResource.href,
32212
+ sourceFile: itemFilePath,
32213
+ inputXml: itemXml
32214
+ });
31700
32215
  const filenameSource = opts?.itemFilenameSource;
31701
32216
  if (filenameSource && filenameSource !== (opts.itemReferenceSource ?? "sourceFilename")) {
31702
- const filename = generateItemReference(itemXml.match(/<assessmentItem[^>]+identifier="([^"]+)"/)?.[1] ?? md5Ref, filenameSource, itemFilePath);
32217
+ const filename = generateItemReference(readAssessmentItemIdentifier(itemXml, md5Ref), filenameSource, itemFilePath);
31703
32218
  itemFilenames.set(md5Ref, filename);
31704
32219
  }
31705
32220
  if (!qtiRefToMd5Refs.has(itemResource.identifier)) qtiRefToMd5Refs.set(itemResource.identifier, []);
@@ -31710,6 +32225,12 @@ function convertQtiPackageToLearnosityBundle(input, opts) {
31710
32225
  diagnostics.push(...ensureFailedItemDiagnostic(itemResult.diagnostics, itemResource.href));
31711
32226
  }
31712
32227
  }
32228
+ if (hasAssetNamingDiagnostic(diagnostics)) return {
32229
+ diagnostics,
32230
+ convertedSourceFiles,
32231
+ failedSourceFiles,
32232
+ convertedActivityFiles
32233
+ };
31713
32234
  if (items.size === 0 && itemResourcesToConvert.length > 0) {
31714
32235
  diagnostics.push({
31715
32236
  code: DiagnosticCode.QTI_PACKAGE_ITEM_NOT_FOUND,
@@ -31814,24 +32335,39 @@ function convertQtiPackageToLearnosityBundle(input, opts) {
31814
32335
  activitiesManifest[activityId] = { items: activityItems };
31815
32336
  }
31816
32337
  const assets = /* @__PURE__ */ new Map();
31817
- const copiedPaths = /* @__PURE__ */ new Set();
31818
- for (const resource of resources) if (resource.type === "webcontent" || resource.type.includes("associated")) {
31819
- if (resource.href.toLowerCase().endsWith(".html")) continue;
31820
- const assetEntry = entries.get(resource.href);
31821
- if (assetEntry) {
31822
- const normalizedPath = normalizePosix(resource.href);
31823
- assets.set(normalizedPath, new Uint8Array(assetEntry.data));
31824
- copiedPaths.add(resource.href);
31825
- }
32338
+ const assetCandidates = /* @__PURE__ */ new Map();
32339
+ const addAssetCandidate = (href, data) => {
32340
+ try {
32341
+ const canonicalHref = canonicalizeQtiAssetHref(href);
32342
+ if (isCopyableAssetPath(canonicalHref)) assetCandidates.set(canonicalHref, new Uint8Array(data));
32343
+ } catch {}
32344
+ };
32345
+ for (const resource of resources) if (resource.type === "webcontent" || resource.type.includes("associated")) for (const href of [resource.href, ...resource.files ?? []]) {
32346
+ const assetEntry = entries.get(normalizeHref(href));
32347
+ if (assetEntry) addAssetCandidate(href, assetEntry.data);
31826
32348
  }
31827
32349
  for (const [path, entry] of entries) {
31828
- if (copiedPaths.has(path)) continue;
31829
- if (path === "imsmanifest.xml" || path.endsWith(".xml")) continue;
31830
- const lowerPath = path.toLowerCase();
31831
- if (ASSET_EXTENSIONS.some((ext) => lowerPath.endsWith(ext))) {
31832
- const normalizedPath = normalizePosix(path);
31833
- assets.set(normalizedPath, new Uint8Array(entry.data));
31834
- copiedPaths.add(path);
32350
+ if (path === "imsmanifest.xml" || path.toLowerCase().endsWith(".xml")) continue;
32351
+ addAssetCandidate(path, entry.data);
32352
+ }
32353
+ const registry = new AssetFilenameRegistry(opts?.preserveAssetFilenames ?? false);
32354
+ const registerContextAsset = (context, rawHref, sourceHrefBase) => {
32355
+ const canonicalHref = resolvePackageAssetHref(rawHref, sourceHrefBase);
32356
+ if (!canonicalHref) return;
32357
+ const bytes = assetCandidates.get(canonicalHref);
32358
+ if (!bytes) return;
32359
+ const registration = registry.register(context.finalItemReference, canonicalHref, bytes);
32360
+ assets.set(registration.filename, registration.bytes);
32361
+ };
32362
+ for (const context of itemAssetContexts) {
32363
+ for (const rawHref of extractAssetHrefs(context.inputXml)) registerContextAsset(context, rawHref, context.sourceHref);
32364
+ for (const passagePath of getAllPassageDataPaths(context.inputXml)) {
32365
+ const passageContent = opts?.fileAccess?.resolvePassageFile(passagePath, context.sourceFile);
32366
+ const passageHref = resolvePackageAssetHref(passagePath, context.sourceHref);
32367
+ const entryContent = passageHref ? entries.get(passageHref) : void 0;
32368
+ const resolvedPassageContent = passageContent ?? (entryContent ? decodeUtf8(entryContent.data) : void 0);
32369
+ if (!resolvedPassageContent) continue;
32370
+ for (const rawHref of extractAssetHrefs(resolvedPassageContent)) registerContextAsset(context, rawHref, context.sourceHref);
31835
32371
  }
31836
32372
  }
31837
32373
  return {
@@ -31844,6 +32380,7 @@ function convertQtiPackageToLearnosityBundle(input, opts) {
31844
32380
  organisationId: opts?.organisationId,
31845
32381
  mediaVault: opts?.mediaVault ?? false,
31846
32382
  customAssetUrl: opts?.customAssetUrl,
32383
+ preserveAssetFilenames: opts?.preserveAssetFilenames ?? false,
31847
32384
  itemReferenceSource: opts?.itemReferenceSource ?? "sourceFilename"
31848
32385
  }
31849
32386
  },
@@ -31865,7 +32402,25 @@ function convertQtiPackageToLearnosityBundle(input, opts) {
31865
32402
  convertedActivityFiles
31866
32403
  };
31867
32404
  } catch (error) {
31868
- diagnostics.push({
32405
+ if (error instanceof AssetFilenameConflictError) diagnostics.push({
32406
+ code: error.kind === "identity-bytes" ? DiagnosticCode.QTI_ASSET_IDENTITY_BYTES_CONFLICT : DiagnosticCode.QTI_ASSET_FILENAME_CONFLICT,
32407
+ level: "error",
32408
+ file: opts?.sourceLabel ?? opts?.sourceDir ?? "package",
32409
+ message: error.message,
32410
+ context: {
32411
+ mode: error.mode,
32412
+ filename: error.filename,
32413
+ existingIdentity: error.existing.serializedIdentity,
32414
+ incomingIdentity: error.incoming.serializedIdentity
32415
+ }
32416
+ });
32417
+ else if (isUnsafeAssetHrefError(error)) diagnostics.push({
32418
+ code: DiagnosticCode.QTI_ASSET_HREF_UNSAFE,
32419
+ level: "error",
32420
+ file: opts?.sourceLabel ?? opts?.sourceDir ?? "package",
32421
+ message: error.message
32422
+ });
32423
+ else diagnostics.push({
31869
32424
  code: DiagnosticCode.LRN_SCHEMA_INVALID,
31870
32425
  level: "error",
31871
32426
  file: "root",
@@ -32134,17 +32689,20 @@ function resolveImageDimensions(objectDataPath, sourceFile, packageRoot) {
32134
32689
  if (!sourceFile || !objectDataPath) return;
32135
32690
  const sourceDir = dirname(sourceFile);
32136
32691
  let root = sourceDir;
32692
+ let shouldTryPackageRoot = false;
32137
32693
  if (packageRoot) {
32138
32694
  const resolvedRoot = resolve(packageRoot);
32139
32695
  const resolvedSourceDir = resolve(sourceDir);
32140
32696
  const rel = relative(resolvedRoot, resolvedSourceDir);
32141
- root = rel === "" || !isAbsolute(rel) && rel.split(sep)[0] !== ".." ? resolvedRoot : resolvedSourceDir;
32697
+ const sourceInsideRoot = rel === "" || !isAbsolute(rel) && rel.split(sep)[0] !== "..";
32698
+ root = sourceInsideRoot ? resolvedRoot : resolvedSourceDir;
32699
+ shouldTryPackageRoot = sourceInsideRoot && resolvedRoot !== resolvedSourceDir;
32142
32700
  }
32143
32701
  const candidates = [];
32144
32702
  if (isAbsolute(objectDataPath)) candidates.push(objectDataPath);
32145
32703
  else {
32146
32704
  candidates.push(join(sourceDir, objectDataPath));
32147
- if (resolve(root) !== resolve(sourceDir)) candidates.push(join(root, objectDataPath));
32705
+ if (shouldTryPackageRoot) candidates.push(join(root, objectDataPath));
32148
32706
  }
32149
32707
  for (const candidate of candidates) {
32150
32708
  const imagePath = containedPath(candidate, root);
@@ -32789,6 +33347,22 @@ function stringifyDeterministic(obj) {
32789
33347
  }, 2);
32790
33348
  }
32791
33349
  /**
33350
+ * Return an asset key relative to the bundle's `assets/` root.
33351
+ *
33352
+ * New callers provide selected filenames or other root-relative keys. Strip
33353
+ * legacy leading `assets/` segments so the writer remains compatible with
33354
+ * source-relative keys without producing `assets/assets/...` paths.
33355
+ */
33356
+ function normalizeBundleAssetPath(assetPath) {
33357
+ let normalized = assetPath.replaceAll("\\", "/");
33358
+ while (normalized.startsWith("./")) normalized = normalized.slice(2);
33359
+ while (normalized.startsWith("assets/")) normalized = normalized.slice(7);
33360
+ const segments = normalized.split("/").filter((segment) => segment && segment !== ".");
33361
+ const isAbsolute = normalized.startsWith("/") || /^[A-Za-z]:/.test(normalized) || /^[A-Za-z][A-Za-z\d+.-]*:/.test(normalized);
33362
+ if (!normalized || isAbsolute || segments.some((segment) => segment === "..")) throw new Error(`Unsafe bundle asset path: ${assetPath}`);
33363
+ return segments.join("/");
33364
+ }
33365
+ /**
32792
33366
  * Write Learnosity Bundle to directory or ZIP
32793
33367
  */
32794
33368
  async function writeLearnosityBundle(bundle, options) {
@@ -32812,10 +33386,13 @@ async function writeLearnosityBundle(bundle, options) {
32812
33386
  content: stringifyDeterministic(item)
32813
33387
  });
32814
33388
  }
32815
- for (const [assetPath, data] of bundle.assets) files.push({
32816
- path: `assets/${assetPath}`,
32817
- content: Buffer.from(data)
32818
- });
33389
+ for (const [assetPath, data] of bundle.assets) {
33390
+ const relativeAssetPath = normalizeBundleAssetPath(assetPath);
33391
+ files.push({
33392
+ path: `assets/${relativeAssetPath}`,
33393
+ content: Buffer.from(data)
33394
+ });
33395
+ }
32819
33396
  writeZip(outDir, files);
32820
33397
  } else {
32821
33398
  await mkdir(outDir, { recursive: true });
@@ -32834,7 +33411,8 @@ async function writeLearnosityBundle(bundle, options) {
32834
33411
  await writeFile(itemPath, stringifyDeterministic(item));
32835
33412
  }
32836
33413
  for (const [assetPath, data] of bundle.assets) {
32837
- const fullPath = join$1(outDir, "assets", assetPath);
33414
+ const relativeAssetPath = normalizeBundleAssetPath(assetPath);
33415
+ const fullPath = join$1(outDir, "assets", relativeAssetPath);
32838
33416
  const assetDir = join$1(fullPath, "..");
32839
33417
  await mkdir(assetDir, { recursive: true });
32840
33418
  await writeFile(fullPath, data);
@@ -33230,6 +33808,7 @@ async function convertQtiPackageToLearnosity(opts) {
33230
33808
  organisationId: opts.organisationId,
33231
33809
  mediaVault: opts.mediaVault,
33232
33810
  customAssetUrl: opts.customAssetUrl,
33811
+ preserveAssetFilenames: opts.preserveAssetFilenames ?? false,
33233
33812
  itemReferenceSource: opts.itemReferenceSource,
33234
33813
  itemFilenameSource: opts.itemFilenameSource,
33235
33814
  truncateTags: opts.truncateTags,