{"version":3,"file":"scorm-again.min.cjs","sources":["../../src/utilities/core.ts","../../src/utilities/url.ts","../../src/cmi/common/base_cmi.ts","../../src/exceptions/base_exceptions.ts","../../src/constants/api_constants.ts","../../src/exceptions/scorm12_exceptions.ts","../../src/exceptions/scorm2004_exceptions.ts","../../src/constants/error_codes.ts","../../src/cmi/common/array.ts","../../src/constants/enums.ts","../../src/constants/default_settings.ts","../../src/constants/regex.ts","../../src/constants/response_constants.ts","../../src/types/scheduled_commit.ts","../../src/types/sequencing_types.ts","../../src/cmi/scorm2004/sequencing/delivery_generation.ts","../../src/cmi/scorm2004/sequencing/time_conditions.ts","../../src/cmi/scorm2004/sequencing/sequencing_rules.ts","../../src/cmi/scorm2004/sequencing/rules/sequencing_request_types.ts","../../src/cmi/scorm2004/sequencing/rules/rule_evaluation_engine.ts","../../src/cmi/scorm2004/sequencing/validation/delivery_validator.ts","../../src/cmi/scorm2004/sequencing/utils/activity_tree_queries.ts","../../src/cmi/scorm2004/sequencing/validators/choice_constraint_validator.ts","../../src/cmi/scorm2004/sequencing/sequencing_controls.ts","../../src/cmi/scorm2004/sequencing/selection_randomization.ts","../../src/cmi/scorm2004/sequencing/traversal/flow_traversal_service.ts","../../src/cmi/scorm2004/sequencing/handlers/flow_request_handler.ts","../../src/cmi/scorm2004/sequencing/handlers/choice_request_handler.ts","../../src/cmi/scorm2004/sequencing/handlers/exit_request_handler.ts","../../src/cmi/scorm2004/sequencing/handlers/retry_request_handler.ts","../../src/cmi/scorm2004/sequencing/sequencing_process.ts","../../src/services/ActivityDeliveryService.ts","../../src/services/AsynchronousHttpService.ts","../../src/services/CMIValueAccessService.ts","../../src/services/LoggingService.ts","../../src/services/ErrorHandlingService.ts","../../src/services/EventService.ts","../../src/services/SynchronousHttpService.ts","../../src/services/OfflineStorageService.ts","../../src/cmi/common/validation.ts","../../src/cmi/scorm2004/validation.ts","../../src/cmi/scorm2004/sequencing/rollup_rules.ts","../../src/cmi/scorm2004/sequencing/activity.ts","../../src/cmi/scorm2004/sequencing/rollup/rollup_child_filter.ts","../../src/cmi/scorm2004/sequencing/rollup/rollup_rule_evaluator.ts","../../src/cmi/scorm2004/sequencing/rollup/measure_rollup.ts","../../src/cmi/scorm2004/sequencing/rollup/objective_rollup.ts","../../src/cmi/scorm2004/sequencing/rollup/progress_rollup.ts","../../src/cmi/scorm2004/sequencing/rollup/duration_rollup.ts","../../src/cmi/scorm2004/sequencing/objectives/global_objective_synchronizer.ts","../../src/cmi/scorm2004/sequencing/validation/rollup_state_validator.ts","../../src/cmi/scorm2004/sequencing/rollup_process.ts","../../src/cmi/scorm2004/sequencing/objectives/objective_evaluation_context.ts","../../src/cmi/scorm2004/completion_status_evaluation.ts","../../src/cmi/scorm2004/sequencing/handlers/rte_data_transfer.ts","../../src/cmi/scorm2004/sequencing/handlers/termination_handler.ts","../../src/cmi/scorm2004/sequencing/handlers/delivery_handler.ts","../../src/cmi/scorm2004/sequencing/navigation_look_ahead.ts","../../src/cmi/scorm2004/sequencing/services/navigation_validity_service.ts","../../src/cmi/scorm2004/sequencing/services/global_objective_service.ts","../../src/cmi/scorm2004/sequencing/state/sequencing_state_manager.ts","../../src/cmi/scorm2004/sequencing/overall_sequencing_process.ts","../../src/cmi/scorm2004/sequencing/activity_tree.ts","../../src/cmi/scorm2004/sequencing/utils/clone_preview_state.ts","../../src/services/SequencingService.ts","../../src/services/SerializationService.ts","../../src/cmi/scorm12/validation.ts","../../src/services/ValidationService.ts","../../src/BaseAPI.ts","../../src/cmi/common/score.ts","../../src/cmi/scorm12/core.ts","../../src/cmi/scorm12/objectives.ts","../../src/cmi/scorm12/student_data.ts","../../src/cmi/scorm12/student_preference.ts","../../src/cmi/scorm12/interactions.ts","../../src/cmi/scorm12/cmi.ts","../../src/cmi/scorm12/nav.ts","../../src/Scorm12API.ts","../../src/cmi/scorm2004/learner_preference.ts","../../src/cmi/scorm2004/interaction_delimiters.ts","../../src/cmi/scorm2004/interactions.ts","../../src/cmi/scorm2004/score.ts","../../src/cmi/scorm2004/comments.ts","../../src/cmi/scorm2004/objectives.ts","../../src/cmi/scorm2004/metadata.ts","../../src/cmi/scorm2004/learner.ts","../../src/cmi/scorm2004/status.ts","../../src/cmi/scorm2004/session.ts","../../src/cmi/scorm2004/content.ts","../../src/cmi/scorm2004/settings.ts","../../src/cmi/scorm2004/thresholds.ts","../../src/cmi/scorm2004/cmi.ts","../../src/cmi/scorm2004/adl.ts","../../src/cmi/scorm2004/sequencing/sequencing.ts","../../src/handlers/scorm2004/response_validator.ts","../../src/handlers/scorm2004/cmi_handler.ts","../../src/configuration/sequencing_configuration_builder.ts","../../src/configuration/activity_tree_builder.ts","../../src/objectives/global_objective_manager.ts","../../src/persistence/sequencing_state_persistence.ts","../../src/serialization/scorm2004_data_serializer.ts","../../src/Scorm2004API.ts","../../src/ScormAgain.ts","../../src/CrossFrameAPI.ts","../../src/CrossFrameLMS.ts"],"sourcesContent":["/**\n * Constants for time conversion calculations.\n * These are used throughout the codebase for converting between different time formats.\n */\nexport const SECONDS_PER_SECOND = 1.0;\nexport const SECONDS_PER_MINUTE = 60;\nexport const SECONDS_PER_HOUR = 60 * SECONDS_PER_MINUTE;\nexport const SECONDS_PER_DAY = 24 * SECONDS_PER_HOUR;\n\ntype Designation = {\n  [key: string]: number;\n};\n\n/**\n * A record with string keys and unknown values.\n * This is a more type-safe alternative to using `any`.\n */\nexport type StringKeyMap = Record<string, unknown>;\n\nconst CORS_SAFELISTED_CONTENT_TYPES = [\n  \"text/plain\",\n  \"application/x-www-form-urlencoded\",\n  \"multipart/form-data\",\n];\n\nexport function isCorsSafelistedContentType(contentType: string): boolean {\n  const essence = ((contentType || \"\").split(\";\")[0] ?? \"\").trim().toLowerCase();\n  return CORS_SAFELISTED_CONTENT_TYPES.includes(essence);\n}\n\nexport function isCrossOriginUrl(url: string): boolean {\n  if (typeof location === \"undefined\" || !location || !location.origin) return false;\n  try {\n    return new URL(url, location.href).origin !== location.origin;\n  } catch {\n    return false;\n  }\n}\n\nconst designations: Designation = {\n  D: SECONDS_PER_DAY,\n  H: SECONDS_PER_HOUR,\n  M: SECONDS_PER_MINUTE,\n  S: SECONDS_PER_SECOND,\n};\n\n/**\n * Converts a number of seconds to a formatted time string in HH:MM:SS format.\n * This function handles decimal seconds and ensures proper formatting with leading zeros.\n *\n * @param {number|null} totalSeconds - The total number of seconds to convert. If null or negative, returns \"00:00:00\".\n * @return {string} A formatted time string in HH:MM:SS format, with up to 2 decimal places for seconds if applicable.\n *\n * @example\n * // Returns \"01:30:45\"\n * getSecondsAsHHMMSS(5445);\n *\n * @example\n * // Returns \"00:00:30.5\"\n * getSecondsAsHHMMSS(30.5);\n *\n * @example\n * // Returns \"00:00:00\"\n * getSecondsAsHHMMSS(null);\n */\nexport const getSecondsAsHHMMSS = (totalSeconds: number | null): string => {\n  // SCORM spec does not deal with negative durations, give zero back\n  if (!totalSeconds || totalSeconds <= 0) {\n    return \"00:00:00\";\n  }\n\n  const hours = Math.floor(totalSeconds / SECONDS_PER_HOUR);\n  const dateObj = new Date(totalSeconds * 1000);\n  const minutes = dateObj.getUTCMinutes();\n  // make sure we add any possible decimal value\n  const seconds = dateObj.getSeconds();\n  const ms = totalSeconds % 1.0;\n  let msStr = \"\";\n\n  if (countDecimals(ms) > 0) {\n    if (countDecimals(ms) > 2) {\n      msStr = ms.toFixed(2);\n    } else {\n      msStr = String(ms);\n    }\n\n    msStr = \".\" + msStr.split(\".\")[1];\n  }\n\n  return (hours + \":\" + minutes + \":\" + seconds).replace(/\\b\\d\\b/g, \"0$&\") + msStr;\n};\n\n/**\n * Converts a number of seconds to an ISO 8601 duration string (e.g., \"PT1H30M45S\").\n * This function handles the complexity of formatting according to the ISO 8601 standard,\n * including the proper placement of the \"T\" separator for time components.\n *\n * @param {number|null} seconds - The number of seconds to convert. If null or negative, returns \"PT0S\".\n * @return {string} An ISO 8601 formatted duration string.\n *\n * @example\n * // Returns \"PT1H30M45S\" (1 hour, 30 minutes, 45 seconds)\n * getSecondsAsISODuration(5445);\n *\n * @example\n * // Returns \"PT30.5S\" (30.5 seconds)\n * getSecondsAsISODuration(30.5);\n *\n * @example\n * // Returns \"P1DT1H\" (1 day, 1 hour)\n * getSecondsAsISODuration(90000);\n *\n * @example\n * // Returns \"PT0S\" (0 seconds)\n * getSecondsAsISODuration(null);\n */\nexport const getSecondsAsISODuration = (seconds: number | null): string => {\n  // SCORM spec does not deal with negative durations, give zero back\n  if (!seconds || seconds <= 0) {\n    return \"PT0S\";\n  }\n\n  let duration = \"P\";\n  let remainder = seconds;\n\n  // Convert to array of entries and use functional methods\n  const designationEntries = Object.entries(designations);\n\n  // Process each time designation\n  designationEntries.forEach(([designationsKey, current_seconds]) => {\n    let value = Math.floor(remainder / current_seconds);\n    remainder = remainder % current_seconds;\n\n    // Limit decimal places\n    if (countDecimals(remainder) > 2) {\n      remainder = Number(Number(remainder).toFixed(2));\n    }\n\n    // If we have anything left in the remainder, and we're currently adding\n    // seconds to the duration, go ahead and add the decimal to the seconds.\n    // Round the sum, not just the remainder: adding a whole-number `value` to a\n    // rounded-but-still-binary-imprecise `remainder` (e.g. 108 + 0.74) can itself\n    // reintroduce floating-point noise (e.g. 108.74000000000001).\n    if (designationsKey === \"S\" && remainder > 0) {\n      value = Number((value + remainder).toFixed(2));\n    }\n\n    if (value) {\n      // Add the 'T' separator for time components if needed\n      const needsTimeSeparator =\n        (duration.indexOf(\"D\") > 0 || [\"H\", \"M\", \"S\"].includes(designationsKey)) &&\n        duration.indexOf(\"T\") === -1;\n\n      if (needsTimeSeparator) {\n        duration += \"T\";\n      }\n\n      duration += `${value}${designationsKey}`;\n    }\n  });\n\n  return duration;\n};\n\n/**\n * Converts a time string in HH:MM:SS format to the equivalent number of seconds.\n * This function is flexible and can handle various input types, converting them to strings as needed.\n *\n * @param {string|number|boolean|null} timeString - The time string to convert, typically in HH:MM:SS format.\n *                                                 If not a string, it will be converted to one.\n *                                                 If null, invalid, or doesn't match the regex, returns 0.\n * @param {RegExp|string} timeRegex - The regular expression used to validate the time string format.\n *                                    If a string is provided, it will be converted to a RegExp.\n * @return {number} The total number of seconds represented by the time string.\n *\n * @example\n * // Returns 5445 (1 hour, 30 minutes, 45 seconds)\n * getTimeAsSeconds(\"01:30:45\", /^(\\d+):(\\d+):(\\d+)$/);\n *\n * @example\n * // Returns 0 (invalid format)\n * getTimeAsSeconds(\"invalid\", /^(\\d+):(\\d+):(\\d+)$/);\n *\n * @example\n * // Returns 30 (converts number to string \"30\" then parses as 0:0:30)\n * getTimeAsSeconds(30, /^(\\d+):(\\d+):(\\d+)$/);\n */\nexport const getTimeAsSeconds = memoize(\n  (timeString: string | number | boolean | null, timeRegex: RegExp | string): number => {\n    if (typeof timeString === \"number\" || typeof timeString === \"boolean\") {\n      timeString = String(timeString);\n    }\n    if (typeof timeRegex === \"string\") {\n      timeRegex = new RegExp(timeRegex);\n    }\n    if (!timeString) {\n      return 0;\n    }\n\n    if (!timeString.match(timeRegex)) {\n      // If the string represents a simple number, treat it as seconds\n      if (/^\\d+(?:\\.\\d+)?$/.test(timeString)) {\n        return Number(timeString);\n      }\n      return 0;\n    }\n\n    const parts = timeString.split(\":\");\n    const hours = Number(parts[0]);\n    const minutes = Number(parts[1]);\n    const seconds = Number(parts[2]);\n    return hours * 3600 + minutes * 60 + seconds;\n  },\n  // Custom key function to handle RegExp objects which can't be stringified\n  (timeString, timeRegex) => {\n    const timeStr = typeof timeString === \"string\" ? timeString : String(timeString ?? \"\");\n    const regexStr = typeof timeRegex === \"string\" ? timeRegex : (timeRegex?.toString() ?? \"\");\n    return `${timeStr}:${regexStr}`;\n  },\n);\n\n/**\n * Converts an ISO 8601 duration string (e.g., \"PT1H30M45S\") to the equivalent number of seconds.\n * This function parses the duration string using a regular expression to extract years, days,\n * hours, minutes, and seconds components.\n *\n * @param {string|null} duration - The ISO 8601 duration string to convert.\n *                                If null, invalid, or doesn't match the regex, returns 0.\n * @param {RegExp|string} durationRegex - The regular expression used to parse the duration components.\n *                                       If a string is provided, it will be converted to a RegExp.\n *                                       The regex should have capture groups for years, days, hours, minutes, and seconds.\n * @return {number} The total number of seconds represented by the duration string.\n *\n * @example\n * // Returns 5445 (1 hour, 30 minutes, 45 seconds)\n * getDurationAsSeconds(\"PT1H30M45S\", /^P(?:(\\d+)Y)?(?:(\\d+)M)?(?:(\\d+)D)?(?:T(?:(\\d+)H)?(?:(\\d+)M)?(?:(\\d+(?:\\.\\d+)?)S)?)?$/);\n *\n * @example\n * // Returns 90000 (1 day, 1 hour)\n * getDurationAsSeconds(\"P1DT1H\", /^P(?:(\\d+)Y)?(?:(\\d+)M)?(?:(\\d+)D)?(?:T(?:(\\d+)H)?(?:(\\d+)M)?(?:(\\d+(?:\\.\\d+)?)S)?)?$/);\n *\n * @example\n * // Returns 0 (invalid format)\n * getDurationAsSeconds(\"invalid\", /^P(?:(\\d+)Y)?(?:(\\d+)M)?(?:(\\d+)D)?(?:T(?:(\\d+)H)?(?:(\\d+)M)?(?:(\\d+(?:\\.\\d+)?)S)?)?$/);\n */\nexport const getDurationAsSeconds = memoize(\n  (duration: string | null, durationRegex: RegExp | string): number => {\n    if (typeof durationRegex === \"string\") {\n      durationRegex = new RegExp(durationRegex);\n    }\n\n    if (!duration || !duration?.match?.(durationRegex)) {\n      return 0;\n    }\n\n    // Extract all duration components from ISO 8601 format\n    // Regex capture groups: [full, years, months, weeks, days, hours, minutes, seconds]\n    const [, years, months, weeks, days, hours, minutes, seconds] =\n      new RegExp(durationRegex).exec?.(duration) ?? [];\n\n    let result = 0.0;\n    result += Number(seconds) || 0.0;\n    result += Number(minutes) * 60.0 || 0.0;\n    result += Number(hours) * 3600.0 || 0.0;\n    result += Number(days) * (60 * 60 * 24.0) || 0.0;\n    result += Number(weeks) * (60 * 60 * 24 * 7.0) || 0.0;\n    // Note: Months are approximate (30 days) as specified in SCORM 2004\n    result += Number(months) * (60 * 60 * 24 * 30.0) || 0.0;\n    result += Number(years) * (60 * 60 * 24 * 365.0) || 0.0;\n    return result;\n  },\n  // Custom key function to handle RegExp objects which can't be stringified\n  (duration, durationRegex) => {\n    const durationStr = duration ?? \"\";\n    const regexStr =\n      typeof durationRegex === \"string\" ? durationRegex : (durationRegex?.toString() ?? \"\");\n    return `${durationStr}:${regexStr}`;\n  },\n);\n\n/**\n * Validates ISO 8601 duration format according to SCORM 2004 specification\n * @param {string} duration - The duration string to validate\n * @return {boolean} - True if valid ISO 8601 duration format\n */\nexport const validateISO8601Duration = memoize(\n  (duration: string, durationRegex: RegExp | string): boolean => {\n    if (typeof durationRegex === \"string\") {\n      durationRegex = new RegExp(durationRegex);\n    }\n\n    return !(!duration || !duration?.match?.(durationRegex));\n  },\n);\n\n/**\n * Adds together two ISO 8601 duration strings and returns the result as a new ISO 8601 duration string.\n * This function works by converting both durations to seconds, adding them together, and then\n * converting the result back to an ISO 8601 duration string.\n *\n * @param {string} first - The first ISO 8601 duration string.\n * @param {string} second - The second ISO 8601 duration string.\n * @param {RegExp|string} durationRegex - The regular expression used to parse the duration components.\n *                                       If a string is provided, it will be converted to a RegExp.\n * @return {string} A new ISO 8601 duration string representing the sum of the two input durations.\n *\n * @example\n * // Returns \"PT2H\" (1 hour + 1 hour = 2 hours)\n * addTwoDurations(\"PT1H\", \"PT1H\", /^P(?:(\\d+)Y)?(?:(\\d+)M)?(?:(\\d+)D)?(?:T(?:(\\d+)H)?(?:(\\d+)M)?(?:(\\d+(?:\\.\\d+)?)S)?)?$/);\n *\n * @example\n * // Returns \"PT1H30M\" (1 hour + 30 minutes = 1 hour and 30 minutes)\n * addTwoDurations(\"PT1H\", \"PT30M\", /^P(?:(\\d+)Y)?(?:(\\d+)M)?(?:(\\d+)D)?(?:T(?:(\\d+)H)?(?:(\\d+)M)?(?:(\\d+(?:\\.\\d+)?)S)?)?$/);\n *\n * @example\n * // Returns \"P1DT1H30M\" (1 day + 1 hour and 30 minutes = 1 day, 1 hour, and 30 minutes)\n * addTwoDurations(\"P1D\", \"PT1H30M\", /^P(?:(\\d+)Y)?(?:(\\d+)M)?(?:(\\d+)D)?(?:T(?:(\\d+)H)?(?:(\\d+)M)?(?:(\\d+(?:\\.\\d+)?)S)?)?$/);\n */\nexport function addTwoDurations(\n  first: string,\n  second: string,\n  durationRegex: RegExp | string,\n): string {\n  const regex: RegExp =\n    typeof durationRegex === \"string\" ? new RegExp(durationRegex) : durationRegex;\n  return getSecondsAsISODuration(\n    getDurationAsSeconds(first, regex) + getDurationAsSeconds(second, regex),\n  );\n}\n\n/**\n * Adds together two time strings in HH:MM:SS format and returns the result as a new time string.\n * This function works by converting both time strings to seconds, adding them together, and then\n * converting the result back to an HH:MM:SS format.\n *\n * @param {string} first - The first time string in HH:MM:SS format.\n * @param {string} second - The second time string in HH:MM:SS format.\n * @param {RegExp|string} timeRegex - The regular expression used to validate and parse the time strings.\n *                                   If a string is provided, it will be converted to a RegExp.\n * @return {string} A new time string in HH:MM:SS format representing the sum of the two input times.\n *\n * @example\n * // Returns \"02:00:00\" (1 hour + 1 hour = 2 hours)\n * addHHMMSSTimeStrings(\"01:00:00\", \"01:00:00\", /^(\\d+):(\\d+):(\\d+)$/);\n *\n * @example\n * // Returns \"01:30:00\" (1 hour + 30 minutes = 1 hour and 30 minutes)\n * addHHMMSSTimeStrings(\"01:00:00\", \"00:30:00\", /^(\\d+):(\\d+):(\\d+)$/);\n *\n * @example\n * // Returns \"01:30:45\" (1 hour + 30 minutes and 45 seconds = 1 hour, 30 minutes, and 45 seconds)\n * addHHMMSSTimeStrings(\"01:00:00\", \"00:30:45\", /^(\\d+):(\\d+):(\\d+)$/);\n */\nexport function addHHMMSSTimeStrings(\n  first: string,\n  second: string,\n  timeRegex: RegExp | string,\n): string {\n  if (typeof timeRegex === \"string\") {\n    timeRegex = new RegExp(timeRegex);\n  }\n  return getSecondsAsHHMMSS(\n    getTimeAsSeconds(first, timeRegex) + getTimeAsSeconds(second, timeRegex),\n  );\n}\n\n/**\n * Flattens a nested JSON object into a flat object with dot notation for nested properties.\n * This function recursively traverses the object and creates new keys using dot notation\n * for nested objects and bracket notation for arrays.\n *\n * @param {StringKeyMap} data - The nested object to flatten.\n * @return {StringKeyMap} A flattened object where nested properties are represented with dot notation.\n *\n * @example\n * // Returns { \"a\": 1, \"b.c\": 2, \"b.d\": 3, \"e[0]\": 4, \"e[1]\": 5 }\n * flatten({\n *   a: 1,\n *   b: { c: 2, d: 3 },\n *   e: [4, 5]\n * });\n *\n * @example\n * // Returns { \"\": [] } for an empty array\n * flatten([]);\n *\n * @example\n * // Returns { \"\": {} } for an empty object\n * flatten({});\n */\nexport function flatten(data: StringKeyMap): StringKeyMap {\n  const result: StringKeyMap = {};\n\n  /**\n   * Recurse through the object\n   * @param {*} cur\n   * @param {*} prop\n   */\n  function recurse(cur: any, prop: any) {\n    if (Object(cur) !== cur) {\n      result[prop] = cur;\n    } else if (Array.isArray(cur)) {\n      // Use forEach instead of for loop\n      cur.forEach((item, i) => {\n        recurse(item, `${prop}[${i}]`);\n      });\n\n      if (cur.length === 0) result[prop] = [];\n    } else {\n      const keys = Object.keys(cur).filter((p) => Object.prototype.hasOwnProperty.call(cur, p));\n\n      const isEmpty = keys.length === 0;\n\n      // Use forEach instead of for...in loop\n      keys.forEach((p) => {\n        recurse(cur[p], prop ? `${prop}.${p}` : p);\n      });\n\n      if (isEmpty && prop) result[prop] = {};\n    }\n  }\n\n  recurse(data, \"\");\n  return result;\n}\n\n/**\n * Converts a flattened object back into a nested object structure.\n * This function is the inverse of `flatten()`. It parses dot notation and bracket notation\n * in property names to recreate the original nested structure.\n *\n * @param {StringKeyMap} data - The flattened object to unflatten.\n * @return {object} A nested object recreated from the flattened structure.\n *\n * @example\n * // Returns { a: 1, b: { c: 2, d: 3 }, e: [4, 5] }\n * unflatten({\n *   \"a\": 1,\n *   \"b.c\": 2,\n *   \"b.d\": 3,\n *   \"e[0]\": 4,\n *   \"e[1]\": 5\n * });\n *\n * @example\n * // Handles array indices correctly\n * unflatten({\n *   \"users[0].name\": \"John\",\n *   \"users[0].email\": \"john@example.com\",\n *   \"users[1].name\": \"Jane\",\n *   \"users[1].email\": \"jane@example.com\"\n * });\n * // Returns:\n * // {\n * //   users: [\n * //     { name: \"John\", email: \"john@example.com\" },\n * //     { name: \"Jane\", email: \"jane@example.com\" }\n * //   ]\n * // }\n */\nexport function unflatten(data: StringKeyMap): object {\n  \"use strict\";\n\n  if (Object(data) !== data || Array.isArray(data)) return data;\n  const result: StringKeyMap = {};\n\n  // Regex pattern for parsing property paths\n  const pattern = /\\.?([^.[\\]]+)|\\[(\\d+)]/g;\n\n  // Get all own properties and process them\n  Object.keys(data)\n    .filter((p) => Object.prototype.hasOwnProperty.call(data, p))\n    .forEach((p) => {\n      let cur = result;\n      let prop = \"\";\n\n      // Create a new regex instance for each property to reset lastIndex\n      const regex = new RegExp(pattern);\n\n      // Process all matches in the property path\n      Array.from({ length: p.match(new RegExp(pattern, \"g\"))?.length ?? 0 }, () =>\n        regex.exec(p),\n      ).forEach((m) => {\n        if (m) {\n          // Create array or object as needed\n          cur = (cur[prop] ?? (cur[prop] = m[2] ? [] : ({} as StringKeyMap))) as StringKeyMap;\n          prop = m[2] || m[1] || \"\";\n        }\n      });\n\n      cur[prop] = data[p];\n    });\n\n  return (result[\"\"] ?? result) as object;\n}\n\n/**\n * Counts the number of decimal places in a number.\n * This function handles both integer and floating-point numbers.\n *\n * @param {number} num - The number to analyze.\n * @return {number} The number of decimal places. Returns 0 for integers or if the number doesn't have a decimal point.\n *\n * @example\n * // Returns 0\n * countDecimals(42);\n *\n * @example\n * // Returns 2\n * countDecimals(3.14);\n *\n * @example\n * // Returns 5\n * countDecimals(1.23456);\n */\nexport function countDecimals(num: number): number {\n  if (Math.floor(num) === num || String(num)?.indexOf?.(\".\") < 0) return 0;\n  const parts = num.toString().split(\".\")?.[1];\n  return parts?.length ?? 0;\n}\n\n/**\n * Formats SCORM messages for consistent and readable logging.\n * This function pads the function name and CMI element to create aligned log messages\n * that are easier to read in log files or console output.\n *\n * @param {string} functionName - The name of the function that generated the message.\n * @param {string} message - The message content to be logged.\n * @param {string} [CMIElement] - Optional. The CMI element related to the message.\n * @return {string} A formatted message string with consistent padding.\n *\n * @example\n * // Returns \"initialize          : Successfully initialized\"\n * formatMessage(\"initialize\", \"Successfully initialized\");\n *\n * @example\n * // Returns \"getValue            : cmi.core.student_id                                             : 12345\"\n * formatMessage(\"getValue\", \"12345\", \"cmi.core.student_id\");\n *\n * @example\n * // Returns \"setValue            : cmi.core.lesson_status                                          : completed\"\n * formatMessage(\"setValue\", \"completed\", \"cmi.core.lesson_status\");\n */\nexport function formatMessage(functionName: string, message: string, CMIElement?: string): string {\n  const baseLength = 20;\n\n  // Use string padding instead of loops - handle undefined/null functionName\n  let messageString = functionName ? `${String(functionName).padEnd(baseLength)}: ` : \"\";\n\n  if (CMIElement) {\n    const CMIElementBaseLength = 70;\n    // Add CMIElement and pad to the required length\n    messageString += CMIElement;\n    messageString = messageString.padEnd(CMIElementBaseLength);\n  }\n\n  // Add the message (or empty string if null/undefined)\n  messageString += message ?? \"\";\n\n  return messageString;\n}\n\n/**\n * Checks if a string contains a specific pattern using regular expression matching.\n * This function is a wrapper around JavaScript's String.match() method that handles\n * null/undefined values gracefully.\n *\n * @param {string} str - The string to search within. If null or undefined, returns false.\n * @param {string} tester - The pattern to search for. Can be a regular expression pattern.\n * @return {boolean} True if the pattern is found in the string, false otherwise.\n *\n * @example\n * // Returns true\n * stringMatches(\"Hello, world!\", \"world\");\n *\n * @example\n * // Returns true\n * stringMatches(\"The quick brown fox\", \"\\\\w+\\\\s+\\\\w+\");\n *\n * @example\n * // Returns false\n * stringMatches(\"Hello, world!\", \"universe\");\n *\n * @example\n * // Returns false (handles null gracefully)\n * stringMatches(null, \"test\");\n */\nexport function stringMatches(str: string | null | undefined, tester: string): boolean {\n  if (typeof str !== \"string\") {\n    return false;\n  }\n  return new RegExp(tester).test(str);\n}\n\n/**\n * Creates a memoized (cached) version of a function for performance optimization.\n * This function caches the results of previous calls with the same arguments,\n * avoiding redundant calculations for repeated calls with the same input.\n *\n * @template T - The type of the function to memoize\n * @param {T} fn - The function to memoize\n * @param {Function} [keyFn] - Optional function to generate a custom cache key.\n *                           Useful for functions with complex arguments that can't be serialized.\n * @param {Object} [options] - Optional cache bounds. `maxEntries` applies FIFO eviction,\n *                             while keys longer than `maxKeyLength` bypass the cache.\n * @return {T} A memoized version of the input function with the same signature\n *\n * @example\n * // Basic usage with a simple function\n * const memoizedAdd = memoize((a, b) => {\n *   console.log('Calculating...');\n *   return a + b;\n * });\n *\n * memoizedAdd(1, 2); // Logs \"Calculating...\" and returns 3\n * memoizedAdd(1, 2); // Returns 3 without logging (uses cached result)\n *\n * @example\n * // Using a custom key function for objects that can't be serialized\n * const memoizedProcessUser = memoize(\n *   (user) => {\n *     console.log('Processing user...');\n *     return { ...user, processed: true };\n *   },\n *   (user) => user.id // Use user.id as the cache key\n * );\n *\n * memoizedProcessUser({ id: 123, name: 'John' }); // Logs and processes\n * memoizedProcessUser({ id: 123, name: 'John' }); // Uses cached result\n */\nexport function memoize<T extends (...args: any[]) => any>(\n  fn: T,\n  keyFn?: (...args: Parameters<T>) => string,\n  options?: { maxEntries?: number; maxKeyLength?: number },\n): T {\n  const cache = new Map<string, ReturnType<T>>();\n\n  return ((...args: Parameters<T>): ReturnType<T> => {\n    const key = keyFn ? keyFn(...args) : JSON.stringify(args);\n\n    if (options?.maxKeyLength !== undefined && key.length > options.maxKeyLength) {\n      return fn(...args);\n    }\n\n    return cache.has(key)\n      ? (cache.get(key) as ReturnType<T>)\n      : (() => {\n          const result = fn(...args);\n          if (options?.maxEntries !== undefined && cache.size >= options.maxEntries) {\n            cache.delete(cache.keys().next().value as string);\n          }\n          cache.set(key, result);\n          return result;\n        })();\n  }) as T;\n}\n\n/**\n * Represents a parsed navigation request from the LMS\n */\nexport type ParsedNavigationRequest = {\n  /**\n   * The navigation request type (one of the valid SCORM 2004 navigation commands)\n   */\n  command: string;\n  /**\n   * The target activity ID for choice/jump commands (null for other commands)\n   */\n  targetActivityId: string | null;\n  /**\n   * Whether the navigation request was valid\n   */\n  valid: boolean;\n  /**\n   * Error message if invalid\n   */\n  error?: string;\n};\n\n/**\n * Securely parses a navigation request string from the LMS into a validated command and target.\n * This function implements a whitelist-based approach to prevent code injection attacks.\n *\n * Valid SCORM 2004 navigation commands:\n * - start, resumeAll, continue, previous, exit, exitAll, abandon, abandonAll, suspendAll\n * - choice.{targetActivityId} - Navigate to specific activity\n * - jump.{targetActivityId} - Jump to specific activity\n * - _none_ - No navigation (special case)\n *\n * @param {string} navRequest - The navigation request string from the LMS\n * @return {ParsedNavigationRequest} Parsed command with validation status\n *\n * @example\n * // Simple navigation command\n * parseNavigationRequest(\"continue\")\n * // => { command: \"continue\", targetActivityId: null, valid: true }\n *\n * @example\n * // Choice navigation with target\n * parseNavigationRequest(\"choice.activity_123\")\n * // => { command: \"choice\", targetActivityId: \"activity_123\", valid: true }\n *\n * @example\n * // Invalid/malicious input\n * parseNavigationRequest(\"alert('XSS')\")\n * // => { command: \"_none_\", targetActivityId: null, valid: false, error: \"...\" }\n */\nexport function parseNavigationRequest(navRequest: string): ParsedNavigationRequest {\n  // Whitelist of valid navigation commands (SCORM 2004 spec)\n  const validCommands = new Set([\n    \"start\",\n    \"resumeAll\",\n    \"continue\",\n    \"previous\",\n    \"choice\",\n    \"jump\",\n    \"exit\",\n    \"exitAll\",\n    \"abandon\",\n    \"abandonAll\",\n    \"suspendAll\",\n    \"_none_\",\n  ]);\n\n  // Trim and handle empty strings\n  const trimmed = navRequest.trim();\n  if (!trimmed) {\n    return {\n      command: \"_none_\",\n      targetActivityId: null,\n      valid: false,\n      error: \"Empty navigation request\",\n    };\n  }\n\n  // Check for simple commands (no target)\n  if (validCommands.has(trimmed)) {\n    return {\n      command: trimmed,\n      targetActivityId: null,\n      valid: true,\n    };\n  }\n\n  // Check for choice/jump commands with target (format: \"choice.targetId\" or \"jump.targetId\")\n  const dotIndex = trimmed.indexOf(\".\");\n  if (dotIndex > 0) {\n    const command = trimmed.substring(0, dotIndex);\n    const targetActivityId = trimmed.substring(dotIndex + 1);\n\n    // Only \"choice\" and \"jump\" commands can have targets\n    if ((command === \"choice\" || command === \"jump\") && targetActivityId) {\n      // Validate target activity ID: alphanumeric, hyphens, underscores, dots only\n      // This prevents injection via the target ID parameter\n      if (/^[a-zA-Z0-9._-]+$/.test(targetActivityId)) {\n        return {\n          command,\n          targetActivityId,\n          valid: true,\n        };\n      } else {\n        return {\n          command: \"_none_\",\n          targetActivityId: null,\n          valid: false,\n          error: `Invalid target activity ID: contains disallowed characters`,\n        };\n      }\n    }\n  }\n\n  // If we get here, the navigation request is not recognized\n  return {\n    command: \"_none_\",\n    targetActivityId: null,\n    valid: false,\n    error: `Unrecognized navigation command: \"${trimmed}\"`,\n  };\n}\n","/**\n * Appends an encoded query-string parameter to a URL.\n *\n * @param url - URL to update\n * @param name - Query-string parameter name\n * @param value - Query-string parameter value\n * @returns The URL with the query-string parameter appended\n */\nexport const appendQueryParam = (\n  url: string,\n  name: string,\n  value: string | number | boolean,\n): string => {\n  const fragmentIndex = url.indexOf(\"#\");\n  const baseUrl = fragmentIndex === -1 ? url : url.slice(0, fragmentIndex);\n  const fragment = fragmentIndex === -1 ? \"\" : url.slice(fragmentIndex);\n  const separator = baseUrl.includes(\"?\")\n    ? baseUrl.endsWith(\"?\") || baseUrl.endsWith(\"&\")\n      ? \"\"\n      : \"&\"\n    : \"?\";\n  const queryParam = `${encodeURIComponent(name)}=${encodeURIComponent(String(value))}`;\n  return `${baseUrl}${separator}${queryParam}${fragment}`;\n};\n","/**\n * Base class for API cmi objects\n */\nexport abstract class BaseCMI {\n  /**\n   * Flag used during JSON serialization to allow getter access without initialization checks.\n   * When true, getters can be accessed before the API is initialized, which is necessary\n   * for serializing the CMI data structure to JSON format.\n   */\n  jsonString = false;\n  protected readonly _cmi_element: string;\n  protected _initialized = false;\n\n  /**\n   * Constructor for BaseCMI\n   * @param {string} cmi_element\n   */\n  constructor(cmi_element: string) {\n    this._cmi_element = cmi_element;\n  }\n\n  /**\n   * Getter for _initialized\n   * @return {boolean}\n   */\n  get initialized(): boolean {\n    return this._initialized;\n  }\n\n  /**\n   * Called when the API has been initialized after the CMI has been created\n   */\n  initialize(): void {\n    this._initialized = true;\n  }\n\n  abstract reset(): void;\n}\n\n/**\n * Base class for cmi root objects\n */\nexport abstract class BaseRootCMI extends BaseCMI {\n  protected _start_time: number | undefined;\n\n  /**\n   * Start time of the session\n   * @type {number | undefined}\n   * @protected\n   */\n  get start_time(): number | undefined {\n    return this._start_time;\n  }\n\n  /**\n   * Setter for start_time. Can only be called once.\n   */\n  setStartTime(): void {\n    if (this._start_time === undefined) {\n      this._start_time = new Date().getTime();\n    } else {\n      throw new Error(\"Start time has already been set.\");\n    }\n  }\n\n  abstract getCurrentTotalTime(): string;\n}\n","type APIError = {\n  errorCode: number;\n  errorMessage: string;\n  detailedMessage: string;\n};\n\nexport class BaseScormValidationError extends Error {\n  constructor(CMIElement: string, errorCode: number) {\n    super(`${CMIElement} : ${errorCode.toString()}`);\n    this._errorCode = errorCode;\n\n    // Set the prototype explicitly.\n    Object.setPrototypeOf(this, BaseScormValidationError.prototype);\n  }\n\n  private readonly _errorCode: number;\n\n  /**\n   * Getter for _errorCode\n   * @return {number}\n   */\n  get errorCode(): number {\n    return this._errorCode;\n  }\n}\n\n/**\n * Base Validation Exception\n */\nexport class ValidationError extends BaseScormValidationError implements APIError {\n  /**\n   * Constructor to take in an error message and code\n   * @param {string} CMIElement\n   * @param {number} errorCode\n   * @param {string} errorMessage\n   * @param {string} detailedMessage\n   */\n  constructor(\n    CMIElement: string,\n    errorCode: number,\n    errorMessage: string,\n    detailedMessage?: string,\n  ) {\n    super(CMIElement, errorCode);\n    this.message = `${CMIElement} : ${errorMessage}`;\n    this._errorMessage = errorMessage;\n    if (detailedMessage) {\n      this._detailedMessage = detailedMessage;\n    }\n\n    // Set the prototype explicitly.\n    Object.setPrototypeOf(this, ValidationError.prototype);\n  }\n\n  private readonly _errorMessage: string;\n  private readonly _detailedMessage: string = \"\";\n\n  /**\n   * Getter for _errorMessage\n   * @return {string}\n   */\n  get errorMessage(): string {\n    return this._errorMessage;\n  }\n\n  /**\n   * Getter for _detailedMessage\n   * @return {string}\n   */\n  get detailedMessage(): string {\n    return this._detailedMessage;\n  }\n}\n","interface ErrorDescription {\n  basicMessage: string;\n  detailMessage: string;\n}\n\ninterface ErrorDescriptions {\n  [key: string]: ErrorDescription;\n}\n\ninterface ScormConstants {\n  cmi_children: string;\n  core_children: string;\n  score_children: string;\n  comments_children: string;\n  objectives_children: string;\n  correct_responses_children: string;\n  student_data_children: string;\n  student_preference_children: string;\n  interactions_children: string;\n  error_descriptions: ErrorDescriptions;\n}\n\ninterface Scorm2004Constants {\n  cmi_children: string;\n  comments_children: string;\n  score_children: string;\n  objectives_children: string;\n  correct_responses_children: string;\n  student_data_children: string;\n  student_preference_children: string;\n  interactions_children: string;\n  adl_data_children: string;\n  error_descriptions: ErrorDescriptions;\n}\n\ninterface GlobalConstants {\n  SCORM_TRUE: string;\n  SCORM_FALSE: string;\n  STATE_NOT_INITIALIZED: number;\n  STATE_INITIALIZED: number;\n  STATE_TERMINATED: number;\n}\n\nexport const global_constants: GlobalConstants = {\n  SCORM_TRUE: \"true\",\n  SCORM_FALSE: \"false\",\n  STATE_NOT_INITIALIZED: 0,\n  STATE_INITIALIZED: 1,\n  STATE_TERMINATED: 2,\n};\n\nexport const scorm12_constants: ScormConstants = {\n  // Children lists\n  cmi_children:\n    \"core,suspend_data,launch_data,comments,objectives,student_data,student_preference,interactions\",\n  core_children:\n    \"student_id,student_name,lesson_location,credit,lesson_status,entry,score,total_time,lesson_mode,exit,session_time\",\n  score_children: \"raw,min,max\",\n  comments_children: \"content,location,time\",\n  objectives_children: \"id,score,status\",\n  correct_responses_children: \"pattern\",\n  student_data_children: \"mastery_score,max_time_allowed,time_limit_action\",\n  student_preference_children: \"audio,language,speed,text\",\n  interactions_children:\n    \"id,objectives,time,type,correct_responses,weighting,student_response,result,latency\",\n  error_descriptions: {\n    \"0\": {\n      basicMessage: \"No Error\",\n      detailMessage: \"No error occurred, the previous API call was successful.\",\n    },\n    \"101\": {\n      basicMessage: \"General Exception\",\n      detailMessage: \"No specific error code exists to describe the error.\",\n    },\n    \"201\": {\n      basicMessage: \"Invalid argument error\",\n      detailMessage:\n        \"Indicates that an argument represents an invalid data model element or is otherwise incorrect.\",\n    },\n    \"202\": {\n      basicMessage: \"Element cannot have children\",\n      detailMessage:\n        'Indicates that LMSGetValue was called with a data model element name that ends in \"_children\" for a data model element that does not support the \"_children\" suffix.',\n    },\n    \"203\": {\n      basicMessage: \"Element not an array - cannot have count\",\n      detailMessage:\n        'Indicates that LMSGetValue was called with a data model element name that ends in \"_count\" for a data model element that does not support the \"_count\" suffix.',\n    },\n    \"301\": {\n      basicMessage: \"Not initialized\",\n      detailMessage: \"Indicates that an API call was made before the call to lmsInitialize.\",\n    },\n    \"401\": {\n      basicMessage: \"Not implemented error\",\n      detailMessage:\n        \"The data model element indicated in a call to LMSGetValue or LMSSetValue is valid, but was not implemented by this LMS. SCORM 1.2 defines a set of data model elements as being optional for an LMS to implement.\",\n    },\n    \"402\": {\n      basicMessage: \"Invalid set value, element is a keyword\",\n      detailMessage:\n        'Indicates that LMSSetValue was called on a data model element that represents a keyword (elements that end in \"_children\" and \"_count\").',\n    },\n    \"403\": {\n      basicMessage: \"Element is read only\",\n      detailMessage: \"LMSSetValue was called with a data model element that can only be read.\",\n    },\n    \"404\": {\n      basicMessage: \"Element is write only\",\n      detailMessage: \"LMSGetValue was called on a data model element that can only be written to.\",\n    },\n    \"405\": {\n      basicMessage: \"Incorrect Data Type\",\n      detailMessage:\n        \"LMSSetValue was called with a value that is not consistent with the data format of the supplied data model element.\",\n    },\n    \"407\": {\n      basicMessage: \"Element Value Out Of Range\",\n      detailMessage:\n        \"The numeric value supplied to a LMSSetValue call is outside of the numeric range allowed for the supplied data model element.\",\n    },\n    \"408\": {\n      basicMessage: \"Data Model Dependency Not Established\",\n      detailMessage:\n        \"Some data model elements cannot be set until another data model element was set. This error condition indicates that the prerequisite element was not set before the dependent element.\",\n    },\n  },\n};\n\nexport const scorm2004_constants: Scorm2004Constants = {\n  // Children lists\n  cmi_children:\n    \"_version,comments_from_learner,comments_from_lms,completion_status,completion_threshold,credit,entry,exit,interactions,launch_data,learner_id,learner_name,learner_preference,location,max_time_allowed,mode,objectives,progress_measure,scaled_passing_score,score,session_time,success_status,suspend_data,time_limit_action,total_time\",\n  comments_children: \"comment,timestamp,location\",\n  score_children: \"max,raw,scaled,min\",\n  objectives_children: \"progress_measure,completion_status,success_status,description,score,id\",\n  correct_responses_children: \"pattern\",\n  student_data_children: \"mastery_score,max_time_allowed,time_limit_action\",\n  student_preference_children: \"audio_level,audio_captioning,delivery_speed,language\",\n  interactions_children:\n    \"id,type,objectives,timestamp,correct_responses,weighting,learner_response,result,latency,description\",\n  adl_data_children: \"id,store\",\n  error_descriptions: {\n    \"0\": {\n      basicMessage: \"No Error\",\n      detailMessage: \"No error occurred, the previous API call was successful.\",\n    },\n    \"101\": {\n      basicMessage: \"General Exception\",\n      detailMessage: \"No specific error code exists to describe the error.\",\n    },\n    \"102\": {\n      basicMessage: \"General Initialization Failure\",\n      detailMessage: \"Call to Initialize failed for an unknown reason.\",\n    },\n    \"103\": {\n      basicMessage: \"Already Initialized\",\n      detailMessage: \"Call to Initialize failed because Initialize was already called.\",\n    },\n    \"104\": {\n      basicMessage: \"Content Instance Terminated\",\n      detailMessage: \"Call to Initialize failed because Terminate was already called.\",\n    },\n    \"111\": {\n      basicMessage: \"General Termination Failure\",\n      detailMessage: \"Call to Terminate failed for an unknown reason.\",\n    },\n    \"112\": {\n      basicMessage: \"Termination Before Initialization\",\n      detailMessage: \"Call to Terminate failed because it was made before the call to Initialize.\",\n    },\n    \"113\": {\n      basicMessage: \"Termination After Termination\",\n      detailMessage: \"Call to Terminate failed because Terminate was already called.\",\n    },\n    \"122\": {\n      basicMessage: \"Retrieve Data Before Initialization\",\n      detailMessage: \"Call to GetValue failed because it was made before the call to Initialize.\",\n    },\n    \"123\": {\n      basicMessage: \"Retrieve Data After Termination\",\n      detailMessage: \"Call to GetValue failed because it was made after the call to Terminate.\",\n    },\n    \"132\": {\n      basicMessage: \"Store Data Before Initialization\",\n      detailMessage: \"Call to SetValue failed because it was made before the call to Initialize.\",\n    },\n    \"133\": {\n      basicMessage: \"Store Data After Termination\",\n      detailMessage: \"Call to SetValue failed because it was made after the call to Terminate.\",\n    },\n    \"142\": {\n      basicMessage: \"Commit Before Initialization\",\n      detailMessage: \"Call to Commit failed because it was made before the call to Initialize.\",\n    },\n    \"143\": {\n      basicMessage: \"Commit After Termination\",\n      detailMessage: \"Call to Commit failed because it was made after the call to Terminate.\",\n    },\n    \"201\": {\n      basicMessage: \"General Argument Error\",\n      detailMessage:\n        \"An invalid argument was passed to an API method (usually indicates that Initialize, Commit or Terminate did not receive the expected empty string argument.\",\n    },\n    \"301\": {\n      basicMessage: \"General Get Failure\",\n      detailMessage:\n        \"Indicates a failed GetValue call where no other specific error code is applicable. Use GetDiagnostic for more information.\",\n    },\n    \"351\": {\n      basicMessage: \"General Set Failure\",\n      detailMessage:\n        \"Indicates a failed SetValue call where no other specific error code is applicable. Use GetDiagnostic for more information.\",\n    },\n    \"391\": {\n      basicMessage: \"General Commit Failure\",\n      detailMessage:\n        \"Indicates a failed Commit call where no other specific error code is applicable. Use GetDiagnostic for more information.\",\n    },\n    \"401\": {\n      basicMessage: \"Undefined Data Model Element\",\n      detailMessage:\n        \"The data model element name passed to GetValue or SetValue is not a valid SCORM data model element.\",\n    },\n    \"402\": {\n      basicMessage: \"Unimplemented Data Model Element\",\n      detailMessage:\n        \"The data model element indicated in a call to GetValue or SetValue is valid, but was not implemented by this LMS. In SCORM 2004, this error would indicate an LMS that is not fully SCORM conformant.\",\n    },\n    \"403\": {\n      basicMessage: \"Data Model Element Value Not Initialized\",\n      detailMessage:\n        \"Attempt to read a data model element that has not been initialized by the LMS or through a SetValue call. This error condition is often reached during normal execution of a SCO.\",\n    },\n    \"404\": {\n      basicMessage: \"Data Model Element Is Read Only\",\n      detailMessage: \"SetValue was called with a data model element that can only be read.\",\n    },\n    \"405\": {\n      basicMessage: \"Data Model Element Is Write Only\",\n      detailMessage: \"GetValue was called on a data model element that can only be written to.\",\n    },\n    \"406\": {\n      basicMessage: \"Data Model Element Type Mismatch\",\n      detailMessage:\n        \"SetValue was called with a value that is not consistent with the data format of the supplied data model element.\",\n    },\n    \"407\": {\n      basicMessage: \"Data Model Element Value Out Of Range\",\n      detailMessage:\n        \"The numeric value supplied to a SetValue call is outside of the numeric range allowed for the supplied data model element.\",\n    },\n    \"408\": {\n      basicMessage: \"Data Model Dependency Not Established\",\n      detailMessage:\n        \"Some data model elements cannot be set until another data model element was set. This error condition indicates that the prerequisite element was not set before the dependent element.\",\n    },\n  },\n};\n","import { ValidationError } from \"./base_exceptions\";\nimport { scorm12_constants } from \"../constants/api_constants\";\n\nconst scorm12_errors = scorm12_constants.error_descriptions;\n\n/**\n * SCORM 1.2 Validation Error\n */\nexport class Scorm12ValidationError extends ValidationError {\n  /**\n   * Constructor to take in an error code\n   * @param {string} CMIElement\n   * @param {number} errorCode\n   */\n  constructor(CMIElement: string, errorCode: number) {\n    if ({}.hasOwnProperty.call(scorm12_errors, String(errorCode))) {\n      super(\n        CMIElement,\n        errorCode,\n        scorm12_errors[String(errorCode)]?.basicMessage || \"Unknown error\",\n        scorm12_errors[String(errorCode)]?.detailMessage,\n      );\n    } else {\n      super(\n        CMIElement,\n        101,\n        scorm12_errors[\"101\"]?.basicMessage ?? \"General error\",\n        scorm12_errors[\"101\"]?.detailMessage,\n      );\n    }\n\n    // Set the prototype explicitly.\n    Object.setPrototypeOf(this, Scorm12ValidationError.prototype);\n  }\n}\n","import { ValidationError } from \"./base_exceptions\";\nimport { scorm2004_constants } from \"../constants/api_constants\";\n\nconst scorm2004_errors = scorm2004_constants.error_descriptions;\n\n/**\n * SCORM 2004 Validation Error\n */\nexport class Scorm2004ValidationError extends ValidationError {\n  /**\n   * Constructor to take in an error code\n   * @param {string} CMIElement\n   * @param {number} errorCode\n   */\n  constructor(CMIElement: string, errorCode: number) {\n    if ({}.hasOwnProperty.call(scorm2004_errors, String(errorCode))) {\n      super(\n        CMIElement,\n        errorCode,\n        scorm2004_errors[String(errorCode)]?.basicMessage || \"Unknown error\",\n        scorm2004_errors[String(errorCode)]?.detailMessage,\n      );\n    } else {\n      super(\n        CMIElement,\n        101,\n        scorm2004_errors[\"101\"]?.basicMessage || \"General error\",\n        scorm2004_errors[\"101\"]?.detailMessage,\n      );\n    }\n\n    // Set the prototype explicitly.\n    Object.setPrototypeOf(this, Scorm2004ValidationError.prototype);\n  }\n}\n","export type ErrorCode = {\n  [key: string]: number;\n};\n\nexport const global_errors: ErrorCode = {\n  GENERAL: 101,\n  INITIALIZATION_FAILED: 101,\n  INITIALIZED: 101,\n  TERMINATED: 101,\n  TERMINATION_FAILURE: 101,\n  TERMINATION_BEFORE_INIT: 101,\n  MULTIPLE_TERMINATION: 101,\n  RETRIEVE_BEFORE_INIT: 101,\n  RETRIEVE_AFTER_TERM: 101,\n  STORE_BEFORE_INIT: 101,\n  STORE_AFTER_TERM: 101,\n  COMMIT_BEFORE_INIT: 101,\n  COMMIT_AFTER_TERM: 101,\n  ARGUMENT_ERROR: 101,\n  CHILDREN_ERROR: 101,\n  COUNT_ERROR: 101,\n  GENERAL_GET_FAILURE: 101,\n  GENERAL_SET_FAILURE: 101,\n  GENERAL_COMMIT_FAILURE: 101,\n  UNDEFINED_DATA_MODEL: 101,\n  UNIMPLEMENTED_ELEMENT: 101,\n  VALUE_NOT_INITIALIZED: 101,\n  INVALID_SET_VALUE: 101,\n  READ_ONLY_ELEMENT: 101,\n  WRITE_ONLY_ELEMENT: 101,\n  TYPE_MISMATCH: 101,\n  VALUE_OUT_OF_RANGE: 101,\n  DEPENDENCY_NOT_ESTABLISHED: 101,\n};\n\nexport const scorm12_errors: ErrorCode = {\n  ...global_errors,\n  TERMINATION_BEFORE_INIT: 301,\n  RETRIEVE_BEFORE_INIT: 301,\n  STORE_BEFORE_INIT: 301,\n  COMMIT_BEFORE_INIT: 301,\n  ARGUMENT_ERROR: 201,\n  CHILDREN_ERROR: 202,\n  COUNT_ERROR: 203,\n  UNDEFINED_DATA_MODEL: 401,\n  UNIMPLEMENTED_ELEMENT: 401,\n  VALUE_NOT_INITIALIZED: 301,\n  INVALID_SET_VALUE: 402,\n  READ_ONLY_ELEMENT: 403,\n  WRITE_ONLY_ELEMENT: 404,\n  TYPE_MISMATCH: 405,\n  // SCORM 1.2 has no out-of-range error code; an out-of-range value is reported\n  // as 405 (incorrect data type), per the SCORM 1.2 RTE error table and the ADL\n  // 1.2 CTS (DataModelValidator.checkScoreDecimal failure -> CMICategory 405).\n  VALUE_OUT_OF_RANGE: 405,\n  DEPENDENCY_NOT_ESTABLISHED: 408,\n};\n\nexport const scorm2004_errors: ErrorCode = {\n  ...global_errors,\n  INITIALIZATION_FAILED: 102,\n  INITIALIZED: 103,\n  TERMINATED: 104,\n  TERMINATION_FAILURE: 111,\n  TERMINATION_BEFORE_INIT: 112,\n  MULTIPLE_TERMINATION: 113,\n  MULTIPLE_TERMINATIONS: 113,\n  RETRIEVE_BEFORE_INIT: 122,\n  RETRIEVE_AFTER_TERM: 123,\n  STORE_BEFORE_INIT: 132,\n  STORE_AFTER_TERM: 133,\n  COMMIT_BEFORE_INIT: 142,\n  COMMIT_AFTER_TERM: 143,\n  ARGUMENT_ERROR: 201,\n  GENERAL_GET_FAILURE: 301,\n  GENERAL_SET_FAILURE: 351,\n  GENERAL_COMMIT_FAILURE: 391,\n  UNDEFINED_DATA_MODEL: 401,\n  UNIMPLEMENTED_ELEMENT: 402,\n  VALUE_NOT_INITIALIZED: 403,\n  READ_ONLY_ELEMENT: 404,\n  WRITE_ONLY_ELEMENT: 405,\n  TYPE_MISMATCH: 406,\n  VALUE_OUT_OF_RANGE: 407,\n  DEPENDENCY_NOT_ESTABLISHED: 408,\n};\n","import { BaseCMI } from \"./base_cmi\";\nimport { BaseScormValidationError } from \"../../exceptions\";\nimport { scorm12_errors } from \"../../constants/error_codes\";\n\n/**\n * Base class for cmi *.n objects\n */\nexport class CMIArray extends BaseCMI {\n  private readonly _errorCode: number;\n  private readonly _errorClass: typeof BaseScormValidationError;\n  private readonly __children: string;\n  public childArray: BaseCMI[];\n\n  /**\n   * Constructor cmi *.n arrays\n   * @param {object} params\n   */\n  constructor(params: {\n    CMIElement: string;\n    children: string;\n    errorCode?: number;\n    errorClass?: typeof BaseScormValidationError;\n  }) {\n    super(params.CMIElement);\n    this.__children = params.children;\n    this._errorCode = params.errorCode ?? (scorm12_errors.GENERAL as number);\n    this._errorClass = params.errorClass || BaseScormValidationError;\n    this.childArray = [];\n  }\n\n  /**\n   * Called when the API has been reset\n   */\n  reset(wipe: boolean = false): void {\n    this._initialized = false;\n    if (wipe) {\n      this.childArray = [];\n    } else {\n      // Reset all children\n      for (let i = 0; i < this.childArray.length; i++) {\n        this.childArray[i]?.reset();\n      }\n    }\n  }\n\n  /**\n   * Getter for _children\n   * @return {string}\n   */\n  get _children(): string {\n    return this.__children;\n  }\n\n  /**\n   * Setter for _children. Just throws an error.\n   * @param {string} _children\n   */\n  set _children(_children: string) {\n    throw new this._errorClass(this._cmi_element + \"._children\", this._errorCode);\n  }\n\n  /**\n   * Getter for _count\n   * @return {number}\n   */\n  get _count(): number {\n    return this.childArray.length;\n  }\n\n  /**\n   * Setter for _count. Just throws an error.\n   * @param {number} _count\n   */\n  set _count(_count: number) {\n    throw new this._errorClass(this._cmi_element + \"._count\", this._errorCode);\n  }\n\n  /**\n   * toJSON for *.n arrays\n   * @return {object}\n   */\n  toJSON(): object {\n    this.jsonString = true;\n    const result: { [key: string]: any } = {};\n    for (let i = 0; i < this.childArray.length; i++) {\n      result[i + \"\"] = this.childArray[i];\n    }\n    this.jsonString = false;\n    return result;\n  }\n}\n","// Using plain objects instead of enums for better compatibility with strip-only mode\n// This approach avoids TypeScript enum runtime code while maintaining the same API\n\n// NAVBoolean values\nexport const NAVBoolean = {\n  UNKNOWN: \"unknown\",\n  TRUE: \"true\",\n  FALSE: \"false\",\n};\n\n// Type for NAVBoolean values\nexport type NAVBoolean = (typeof NAVBoolean)[keyof typeof NAVBoolean];\n\n// SuccessStatus values\nexport const SuccessStatus = {\n  PASSED: \"passed\",\n  FAILED: \"failed\",\n  UNKNOWN: \"unknown\",\n};\n\n// Type for SuccessStatus values\nexport type SuccessStatus = (typeof SuccessStatus)[keyof typeof SuccessStatus];\n\n// CompletionStatus values\nexport const CompletionStatus = {\n  COMPLETED: \"completed\",\n  INCOMPLETE: \"incomplete\",\n  UNKNOWN: \"unknown\",\n};\n\n// Type for CompletionStatus values\nexport type CompletionStatus = (typeof CompletionStatus)[keyof typeof CompletionStatus];\n\n// LogLevelEnum values\nexport const LogLevelEnum = {\n  _: 0,\n  DEBUG: 1,\n  INFO: 2,\n  WARN: 3,\n  ERROR: 4,\n  NONE: 5,\n};\n\n// Type for LogLevelEnum values\nexport type LogLevelEnum = (typeof LogLevelEnum)[keyof typeof LogLevelEnum];\n","import { InternalSettings, LogLevel, ResultObject } from \"../types/api_types\";\nimport { global_constants } from \"./api_constants\";\nimport { LogLevelEnum } from \"./enums\";\n\n/**\n * Default settings for the SCORM API\n */\nexport const DefaultSettings: InternalSettings = {\n  autocommit: false,\n  autocommitSeconds: 10,\n  throttleCommits: false,\n  useAsynchronousCommits: false,\n  sendFullCommit: true,\n  lmsCommitUrl: false,\n  dataCommitFormat: \"json\",\n  commitRequestDataType: \"application/json;charset=UTF-8\",\n  terminationCommitContentType: \"text/plain;charset=UTF-8\",\n  autoProgress: false,\n  logLevel: LogLevelEnum.ERROR,\n  uninitializedGetLogLevel: LogLevelEnum.WARN,\n  selfReportSessionTime: false,\n  alwaysSendTotalTime: false,\n  accumulateSessionTimeOnTerminate: false,\n  renderCommonCommitFields: false,\n  autoCompleteLessonStatus: false,\n  strict_errors: true,\n  xhrHeaders: {},\n  xhrWithCredentials: false,\n  fetchMode: \"cors\",\n  asyncModeBeaconBehavior: \"never\",\n  includeCommitSequence: false,\n  responseHandler: async function (response: Response): Promise<ResultObject> {\n    if (typeof response !== \"undefined\") {\n      let httpResult = null;\n\n      // Handle both text() and json() response methods\n      try {\n        if (typeof response.json === \"function\") {\n          // Try to get JSON directly if the method exists\n          httpResult = await response.json();\n        } else if (typeof response.text === \"function\") {\n          // Fall back to text() if json() is not available\n          const responseText = await response.text();\n          if (responseText) {\n            httpResult = JSON.parse(responseText);\n          }\n        }\n      } catch (e) {\n        // If parsing fails, continue with null httpResult\n      }\n\n      if (httpResult === null || !{}.hasOwnProperty.call(httpResult, \"result\")) {\n        if (response.status === 200) {\n          return {\n            result: global_constants.SCORM_TRUE,\n            errorCode: 0,\n          };\n        } else {\n          return {\n            result: global_constants.SCORM_FALSE,\n            errorCode: 101,\n          };\n        }\n      } else {\n        return {\n          result: httpResult.result,\n          errorCode:\n            typeof httpResult.errorCode === \"number\"\n              ? httpResult.errorCode\n              : httpResult.result === true || httpResult.result === global_constants.SCORM_TRUE\n                ? 0\n                : 101,\n        };\n      }\n    }\n    return {\n      result: global_constants.SCORM_FALSE,\n      errorCode: 101,\n    };\n  },\n  xhrResponseHandler: function (xhr: XMLHttpRequest): ResultObject {\n    if (typeof xhr !== \"undefined\") {\n      let httpResult = null;\n\n      if (xhr.status >= 200 && xhr.status <= 299) {\n        try {\n          httpResult = JSON.parse(xhr.responseText);\n        } catch (e) {\n          // Parsing failed, but status was success\n        }\n\n        if (httpResult === null || !{}.hasOwnProperty.call(httpResult, \"result\")) {\n          return { result: global_constants.SCORM_TRUE, errorCode: 0 };\n        }\n        return {\n          result: httpResult.result,\n          errorCode:\n            typeof httpResult.errorCode === \"number\"\n              ? httpResult.errorCode\n              : httpResult.result === true || httpResult.result === global_constants.SCORM_TRUE\n                ? 0\n                : 101,\n        };\n      } else {\n        return { result: global_constants.SCORM_FALSE, errorCode: 101 };\n      }\n    }\n    return { result: global_constants.SCORM_FALSE, errorCode: 101 };\n  },\n  requestHandler: function (commitObject) {\n    return commitObject;\n  },\n  onLogMessage: defaultLogHandler,\n  mastery_override: false,\n  score_overrides_status: false,\n  completion_status_on_failed: \"completed\",\n  scoItemIds: [],\n  scoItemIdValidator: false,\n  globalObjectiveIds: [],\n\n  // Offline support settings\n  enableOfflineSupport: false,\n  courseId: \"\",\n  syncOnInitialize: true,\n  syncOnTerminate: true,\n  maxSyncAttempts: 5,\n\n  // Multi-SCO support settings\n  scoId: \"\",\n  autoPopulateCommitMetadata: false,\n\n  // HTTP service settings\n  httpService: null,\n\n  // Global learner preferences settings\n  globalStudentPreferences: false,\n};\n\nexport function defaultLogHandler(messageLevel: LogLevel, logMessage: string): void {\n  switch (messageLevel) {\n    case \"4\":\n    case 4:\n    case \"ERROR\":\n    case LogLevelEnum.ERROR:\n      console.error(logMessage);\n      break;\n    case \"3\":\n    case 3:\n    case \"WARN\":\n    case LogLevelEnum.WARN:\n      console.warn(logMessage);\n      break;\n    case \"2\":\n    case 2:\n    case \"INFO\":\n    case LogLevelEnum.INFO:\n      console.info(logMessage);\n      break;\n    case \"1\":\n    case 1:\n    case \"DEBUG\":\n    case LogLevelEnum.DEBUG:\n      if (console.debug) {\n        console.debug(logMessage);\n      } else {\n        console.log(logMessage);\n      }\n      break;\n  }\n}\n","/**\n * SCORM 1.2 Data Type Definitions\n * Per SCORM 1.2 RTE Appendix A: Data Type Standards\n */\nexport const scorm12_regex = {\n  /** CMIString256 - Character string, max 255 chars (RTE A.1) */\n  CMIString256: \"^[\\\\s\\\\S]{0,255}$\",\n  /** CMIString4096 - Character string, max 4096 chars (RTE A.1) */\n  CMIString4096: \"^[\\\\s\\\\S]{0,4096}$\",\n  /**\n   * CMIString64000 - Extended character string, max 64000 chars\n   *\n   * SPEC COMPLIANCE NOTE:\n   * The SCORM 1.2 specification defines cmi.suspend_data as CMIString4096 (max 4096 chars).\n   * This implementation intentionally increases the limit to 64000 chars (matching SCORM 2004)\n   * for the following reasons:\n   *\n   * 1. Modern content frequently exceeds 4096 chars due to JSON state serialization,\n   *    base64 encoding, complex bookmark data, and rich interaction tracking\n   * 2. The 4096 limit was set in 2001 when content was simpler; modern authoring tools\n   *    routinely generate larger suspend_data\n   * 3. Most LMS systems can handle larger values - the API shouldn't be the bottleneck\n   * 4. Content that gets rejected has no recovery path, causing data loss\n   * 5. Aligns with SCORM 2004's more practical 64000 char limit\n   *\n   * Used by: cmi.suspend_data (SCORM 1.2)\n   *\n   * Strict spec pattern would be: ^[\\s\\S]{0,4096}$\n   */\n  CMIString64000: \"^[\\\\s\\\\S]{0,64000}$\",\n  /**\n   * CMITime - Clock time in HH:MM:SS.SS format (RTE A.2)\n   * Optional centiseconds (1-2 decimal digits) per spec.\n   */\n  CMITime: \"^(?:[01]\\\\d|2[0123]):(?:[012345]\\\\d):(?:[012345]\\\\d)(\\\\.\\\\d{1,2})?$\",\n  /**\n   * CMITimespan - Time interval in HHHH:MM:SS.SS format (RTE A.3)\n   * We allow more digits for the hour to support values generated\n   * by getSecondsAsHHMMSS which can produce larger hour values\n   * (e.g., 17496:00:00 for very long durations).\n   * Changed from minimum 2 digits to 1+ digits with no upper limit.\n   */\n  CMITimespan: \"^([0-9]+):([0-9]{2}):([0-9]{2})(\\\\.\\\\d{1,2})?$\",\n\n  /**\n   * CMIInteger - Non-negative integer (RTE A.4)\n   *\n   * SPEC COMPLIANCE NOTE:\n   * The SCORM 1.2 specification defines CMIInteger as 0-65536 range.\n   * This implementation intentionally omits range validation to support\n   * legacy content that may exceed this limit in _count fields or other\n   * integer values. Real-world content often violates the spec by storing\n   * larger values, and strict enforcement would break compatibility.\n   *\n   * Affected elements:\n   * - cmi.objectives._count\n   * - cmi.interactions._count\n   * - cmi.interactions.n.objectives._count\n   * - cmi.interactions.n.correct_responses._count\n   */\n  CMIInteger: \"^\\\\d+$\",\n  /** CMISInteger - Signed integer (RTE A.5) */\n  CMISInteger: \"^-?([0-9]+)$\",\n  /**\n   * CMIDecimal - Signed decimal (RTE A.6)\n   * We set practical limits on decimals to prevent abuse while maintaining\n   * broad compatibility with legacy content.\n   * Increased from 3 to 10 digits before decimal to match SCORM 2004 behavior.\n   */\n  CMIDecimal: \"^-?(?=\\\\.?[0-9])([0-9]{0,10})(\\\\.[0-9]*)?$\",\n\n  /**\n   * CMIIdentifier - Printable ASCII characters, max 255 chars (RTE A.7)\n   *\n   * SPEC COMPLIANCE NOTE:\n   * The SCORM 1.2 specification defines CMIIdentifier as alphanumeric only:\n   * letters (a-z, A-Z), numbers (0-9), hyphens (-), and underscores (_).\n   * Spaces and periods are explicitly NOT allowed per spec.\n   *\n   * This implementation intentionally relaxes validation to accept all\n   * printable ASCII characters (0x21-0x7E) plus whitespace to support\n   * legacy content. Many real-world LMS systems and content packages use\n   * identifiers that violate the strict spec (e.g., student IDs with spaces,\n   * objective IDs with periods or special characters).\n   *\n   * Strict spec pattern would be: ^[A-Za-z0-9_-]{0,255}$\n   *\n   * Affected elements:\n   * - cmi.core.student_id\n   * - cmi.objectives.n.id\n   * - cmi.interactions.n.id\n   * - cmi.interactions.n.objectives.n.id\n   */\n  CMIIdentifier: \"^[\\\\u0021-\\\\u007E\\\\s]{0,255}$\",\n  /** CMICredit - Vocabulary: credit or no-credit (RTE 3.4.2.1.3) */\n  CMICredit: \"^(credit|no-credit)$\",\n  /** CMIEntry - Vocabulary: ab-initio, resume, or empty (RTE 3.4.2.1.4) */\n  CMIEntry: \"^(ab-initio|resume|)$\",\n  /** CMILessonMode - Vocabulary: normal, browse, or review (RTE 3.4.2.1.10) */\n  CMILessonMode: \"^(normal|browse|review)$\",\n  /** CMITimeLimitAction - Vocabulary: action combinations (RTE 3.4.2.1.11) */\n  CMITimeLimitAction: \"^(exit,message|exit,no message|continue,message|continue,no message)$\",\n  /**\n   * CMIFeedback - Relaxed for compatibility (normally CMIString255)\n   *\n   * SPEC COMPLIANCE NOTE:\n   * The SCORM 1.2 specification defines CMIFeedback as CMIString255 (max 255 chars)\n   * with format varying by interaction type (see RTE 3.4.2.7.5, 3.4.2.7.7).\n   *\n   * This implementation intentionally relaxes validation for two reasons:\n   *\n   * 1. LENGTH: Many legacy content packages store responses exceeding 255 chars,\n   *    especially for fill-in and performance interaction types. Strict enforcement\n   *    would break existing content with no user-facing benefit.\n   *\n   * 2. FORMAT: The spec requires type-specific formats (e.g., true-false accepts\n   *    only \"0\"/\"1\"/\"t\"/\"f\", choice accepts comma-separated single chars). However:\n   *    - Format validation requires knowing interaction type at validation time\n   *    - Legacy content often uses non-standard formats\n   *    - The SCO is responsible for response evaluation, not the API\n   *    - Strict format validation provides minimal benefit vs. compatibility cost\n   *\n   * Affected elements:\n   * - cmi.interactions.n.student_response\n   * - cmi.interactions.n.correct_responses.n.pattern\n   *\n   * Strict spec pattern would be: ^[\\s\\S]{0,255}$ with type-specific subpatterns\n   */\n  CMIFeedback: \"^[\\\\s\\\\S]*$\",\n  /** CMIIndex - Pattern for array index extraction */\n  CMIIndex: \"[._](\\\\d+).\",\n  /** CMIStatus - Lesson status vocabulary (RTE 3.4.2.2.3) */\n  CMIStatus: \"^(passed|completed|failed|incomplete|browsed)$\",\n  /** CMIStatus2 - Extended status vocabulary with \"not attempted\" (RTE 3.4.2.6.2) */\n  CMIStatus2: \"^(passed|completed|failed|incomplete|browsed|not attempted)$\",\n  /** CMIExit - Exit vocabulary (RTE 3.4.2.1.5) */\n  CMIExit: \"^(time-out|suspend|logout|)$\",\n  /** CMIType - Interaction type vocabulary (RTE 3.4.2.7.2) */\n  CMIType: \"^(true-false|choice|fill-in|matching|performance|sequencing|likert|numeric)$\",\n  /** CMIResult - Interaction result vocabulary (RTE 3.4.2.7.6) */\n  CMIResult: \"^(correct|wrong|unanticipated|neutral|-?(?=\\\\.?[0-9])[0-9]{0,10}(?:\\\\.[0-9]*)?)$\",\n  /** NAVEvent - Navigation event vocabulary (SCORM 1.2 extension) */\n  NAVEvent:\n    \"^(_?(previous|continue|start|resumeAll|exit|exitAll|abandon|abandonAll|suspendAll|retry|retryAll)|choice|jump|_none_)$\",\n  /** score_range - Valid score range 0-100 (RTE 3.4.2.2.2) */\n  score_range: \"0#100\",\n  /** audio_range - Audio level range -1 to 100 (RTE 3.4.2.3.1) */\n  audio_range: \"-1#100\",\n  /** speed_range - Playback speed range -100 to 100 (RTE 3.4.2.3.2) */\n  speed_range: \"-100#100\",\n  /**\n   * weighting_range - No longer used: SCORM 1.2 sets no range for\n   * cmi.interactions.n.weighting. Kept because scorm12_regex is public API.\n   * @deprecated\n   */\n  weighting_range: \"-100#100\",\n  /** text_range - Text display preference -1 to 1 (RTE 3.4.2.3.3) */\n  text_range: \"-1#1\",\n};\n\n/**\n * SCORM 2004 Data Type Definitions\n * Per SCORM 2004 4th Edition RTE Appendix C: Data Type Standards\n */\nexport const scorm2004_regex = {\n  /** CMIString200 - Character string, max 200 chars (RTE C.1.1) */\n  CMIString200: \"^[\\\\u0000-\\\\uFFFF]{0,200}$\",\n  /** CMIString250 - Character string, max 250 chars (RTE C.1.1) */\n  CMIString250: \"^[\\\\u0000-\\\\uFFFF]{0,250}$\",\n  /** CMIString1000 - Character string, max 1000 chars (RTE C.1.1) */\n  CMIString1000: \"^[\\\\u0000-\\\\uFFFF]{0,1000}$\",\n  /** CMIString4000 - Character string, max 4000 chars (RTE C.1.1) */\n  CMIString4000: \"^[\\\\u0000-\\\\uFFFF]{0,4000}$\",\n  /** CMIString64000 - Character string, max 64000 chars (RTE C.1.1) */\n  CMIString64000: \"^[\\\\u0000-\\\\uFFFF]{0,64000}$\",\n  /**\n   * CMILang - Language code per RFC 1766/RFC 3066 (RTE C.1.2)\n   * Primary tag: 1-8 characters (ISO 639-1: 2, ISO 639-2: 3, or i/x for IANA/private)\n   * Subtag: 1-8 alphanumeric characters\n   */\n  CMILang: \"^([a-zA-Z]{1,8}|i|x)(-[a-zA-Z0-9]{1,8})*$|^$\",\n\n  /** CMILangString250 - String with optional language tag, max 250 chars (RTE C.1.3) */\n  CMILangString250:\n    \"^({lang=([a-zA-Z]{1,8}|i|x)(-[a-zA-Z0-9]{1,8})*})?((?!\\\\{lang=)[\\\\s\\\\S]{0,250}$)?$\",\n\n  /** CMILangString - Optional language tag, no length cap; RTE C.1.3 SPM is a floor and is deliberately not enforced */\n  CMILangString: \"^({lang=([a-zA-Z]{1,8}|i|x)(-[a-zA-Z0-9]{1,8})*})?((?!\\\\{lang=)[\\\\s\\\\S]*$)?$\",\n\n  /** CMILangcr - Language tag pattern with content */\n  CMILangcr: \"^(({lang=([a-zA-Z]{1,8}|i|x)?(-[a-zA-Z0-9]{1,8})*}))([\\\\s\\\\S]*?)$\",\n\n  /** CMILangString250cr - String with optional language tag (carriage return variant) */\n  CMILangString250cr: \"^(({lang=([a-zA-Z]{1,8}|i|x)?(-[a-zA-Z0-9]{1,8})*})?([\\\\s\\\\S]{0,250})?)?$\",\n\n  /** CMILangString4000 - String with optional language tag, max 4000 chars (RTE C.1.3) */\n  CMILangString4000:\n    \"^({lang=([a-zA-Z]{1,8}|i|x)(-[a-zA-Z0-9]{1,8})*})?((?!\\\\{lang=)[\\\\s\\\\S]{0,4000}$)?$\",\n\n  /**\n   * CMITime - ISO 8601 timestamp format (RTE C.1.4)\n   * Year range expanded from 1970-2038 to 1970-9999 to support future dates\n   */\n  CMITime:\n    \"^(19[7-9][0-9]|[2-9][0-9]{3})(?:-(0[1-9]|1[0-2])(?:-(0[1-9]|[1-2][0-9]|3[0-1])(?:T([0-1][0-9]|2[0-3])(?::[0-5][0-9](?::[0-5][0-9](?:\\\\.[0-9]{1,6})?)?(?:Z|[+-]([0-1][0-9]|2[0-3])(?::[0-5][0-9])?)?)?)?)?)?$\",\n  /** CMITimespan - ISO 8601 duration format (RTE C.1.5) */\n  CMITimespan:\n    \"^P(?:([.,\\\\d]+)Y)?(?:([.,\\\\d]+)M)?(?:([.,\\\\d]+)W)?(?:([.,\\\\d]+)D)?(?:T?(?:([.,\\\\d]+)H)?(?:([.,\\\\d]+)M)?(?:(\\\\d+(?:\\\\.\\\\d{1,2})?)S)?)?$\",\n  /** CMIInteger - Non-negative integer (RTE C.1.6) */\n  CMIInteger: \"^\\\\d+$\",\n  /** CMISInteger - Signed integer (RTE C.1.7) */\n  CMISInteger: \"^-?([0-9]+)$\",\n  /**\n   * CMIDecimal - Signed decimal (RTE C.1.8)\n   * Spec allows unlimited digits, but we set practical limits to prevent abuse\n   * while maintaining broad compatibility:\n   * - Up to 10 digits before decimal (supports values up to 10 billion)\n   * - Up to 18 digits after decimal (maintains precision for scientific use)\n   */\n  CMIDecimal: \"^-?([0-9]{1,10})(\\\\.[0-9]{1,18})?$\",\n  /**\n   * CMIIdentifier - Identifier with alphanumeric ending, max 250 chars (RTE C.1.9)\n   * Must contain at least one word character (\\w) and only allow: letters,\n   * numbers, - ( ) + . : = @ ; $ _ ! * ' % / #\n   * URN format is validated separately if string starts with \"urn:\"\n   */\n  CMIIdentifier: \"^(?=.*\\\\w)[\\\\w\\\\-\\\\(\\\\)\\\\+\\\\.\\\\:\\\\=\\\\@\\\\;\\\\$\\\\_\\\\!\\\\*\\\\'\\\\%\\\\/\\\\#]{1,250}$\",\n  /** CMIShortIdentifier - Short identifier conforming to URI syntax, max 250 chars (RTE C.1.10) */\n  CMIShortIdentifier: \"^(?=.*\\\\w)[\\\\w\\\\-\\\\(\\\\)\\\\+\\\\.\\\\:\\\\=\\\\@\\\\;\\\\$\\\\_\\\\!\\\\*\\\\'\\\\%\\\\/\\\\#]{1,250}$\",\n  /** CMILongIdentifier - Long identifier supporting URN format, max 4000 chars (RTE C.1.11) */\n  CMILongIdentifier: \"^(?:(?!urn:)\\\\S{1,4000}|urn:[A-Za-z0-9-]{1,31}:\\\\S{1,4000}|.{1,4000})$\",\n  /** CMIFeedback - Unrestricted feedback text (RTE C.1.12) */\n  CMIFeedback: \"^[\\\\s\\\\S]*$\",\n  /** CMIIndex - Pattern for array index extraction */\n  CMIIndex: \"[._](\\\\d+).\",\n  /** CMIIndexStore - Pattern for stored index notation */\n  CMIIndexStore: \".N(\\\\d+).\",\n  /** CMICStatus - Completion status vocabulary (RTE 4.1.4) */\n  CMICStatus: \"^(completed|incomplete|not attempted|unknown)$\",\n  /** CMISStatus - Success status vocabulary (RTE 4.1.11) */\n  CMISStatus: \"^(passed|failed|unknown)$\",\n  /** CMIExit - Exit vocabulary (RTE 4.1.3) */\n  CMIExit: \"^(time-out|suspend|logout|normal)$\",\n  /** CMIType - Interaction type vocabulary (RTE 4.1.6.2) */\n  CMIType:\n    \"^(true-false|choice|fill-in|long-fill-in|matching|performance|sequencing|likert|numeric|other)$\",\n  /** CMIResult - Interaction result vocabulary (RTE 4.1.6.8) */\n  CMIResult: \"^(correct|incorrect|unanticipated|neutral|-?([0-9]{1,10})(\\\\.[0-9]{1,18})?)$\",\n  /** NAVEvent - Navigation event vocabulary (SN Book Table 4.4.2) */\n  NAVEvent:\n    \"^(_?(start|resumeAll|previous|continue|exit|exitAll|abandon|abandonAll|suspendAll|retry|retryAll)|_none_|(\\\\{target=(?<choice_target>[^{}\\\\s]+)})?choice|(\\\\{target=(?<jump_target>[^{}\\\\s]+)})?jump)$\",\n\n  /** NAVBoolean - Navigation boolean vocabulary (SN Book) */\n  NAVBoolean: \"^(unknown|true|false)$\",\n  /** NAVTarget - Navigation target pattern (SN Book) */\n  NAVTarget: \"^{target=[^{}\\\\s]+}$\",\n  /** scaled_range - Scaled score range -1 to 1 (RTE 4.1.10.1) */\n  scaled_range: \"-1#1\",\n  /** audio_range - Audio level range 0 to unbounded (RTE 4.1.7.1) */\n  audio_range: \"0#*\",\n  /** speed_range - Playback speed range 0 to unbounded (RTE 4.1.7.4) */\n  speed_range: \"0#*\",\n  /** text_range - Text display preference -1 to 1 (RTE 4.1.7.5) */\n  text_range: \"-1#1\",\n  /** progress_range - Progress measure range 0 to 1 (RTE 4.1.8) */\n  progress_range: \"0#1\",\n};\n","import { scorm2004_regex } from \"./regex\";\n\n/**\n * SCORM 2004 `performance` interaction step patterns (RTE 4.2.9.1 / 4.2.9.7).\n *\n * A record is `<step_name>[.]<step_answer>`; either side is optional (but not\n * both). The reserved bracketed tokens `[,]` `[.]` `[:]` are the delimiters, so\n * a `step_answer` characterstring may not contain them - a bare `.` `,` `:` is\n * literal data. Spaces are valid characterstring content (SPM 250).\n */\n// step_name: optional short_identifier_type\nconst PERFORMANCE_STEP_NAME = \"^$|\" + scorm2004_regex.CMIShortIdentifier;\n// step_answer characterstring: 1-250 chars, no reserved bracketed tokens\nconst PERFORMANCE_CHARACTERSTRING = \"(?![\\\\s\\\\S]*(?:\\\\[,\\\\]|\\\\[\\\\.\\\\]|\\\\[:\\\\]))[\\\\s\\\\S]{1,250}\";\n// step_answer numeric range: <min>[:]<max>, with open-ended bounds allowed\nconst PERFORMANCE_NUMERIC_RANGE = \"(?:-?\\\\d+(?:\\\\.\\\\d+)?)?\\\\[:\\\\](?:-?\\\\d+(?:\\\\.\\\\d+)?)?\";\n// correct_responses step_answer: empty | numeric range | characterstring\nconst CR_PERFORMANCE_STEP_ANSWER =\n  \"^(?:|\" + PERFORMANCE_NUMERIC_RANGE + \"|\" + PERFORMANCE_CHARACTERSTRING + \")$\";\n// learner_response step_answer: empty | characterstring (a single real value is\n// just a characterstring; learner responses have no numeric *range* per spec)\nconst LR_PERFORMANCE_STEP_ANSWER = \"^(?:|\" + PERFORMANCE_CHARACTERSTRING + \")$\";\n\nexport const LearnerResponses: Responses = {\n  \"true-false\": {\n    format: \"^true$|^false$\",\n    max: 1,\n    delimiter: \"\",\n    unique: false,\n  },\n  choice: {\n    format: scorm2004_regex.CMILongIdentifier,\n    max: 36,\n    delimiter: \"[,]\",\n    unique: true,\n  },\n  \"fill-in\": {\n    // No 250-char cap: the RTE SPM is a floor, and a learner's free-text\n    // answer may contain literal commas, so it is one item, not several.\n    format: scorm2004_regex.CMILangString,\n    max: 10,\n    delimiter: \"[,]\",\n    unique: false,\n  },\n  \"long-fill-in\": {\n    format: scorm2004_regex.CMILangString4000,\n    max: 1,\n    delimiter: \"\",\n    unique: false,\n  },\n  matching: {\n    format: scorm2004_regex.CMIShortIdentifier,\n    format2: scorm2004_regex.CMIShortIdentifier,\n    max: 36,\n    delimiter: \"[,]\",\n    delimiter2: \"[.]\",\n    unique: false,\n  },\n  performance: {\n    format: PERFORMANCE_STEP_NAME,\n    format2: LR_PERFORMANCE_STEP_ANSWER,\n    max: 250,\n    delimiter: \"[,]\",\n    delimiter2: \"[.]\",\n    unique: false,\n  },\n  sequencing: {\n    format: scorm2004_regex.CMIShortIdentifier,\n    max: 36,\n    delimiter: \"[,]\",\n    unique: false,\n  },\n  likert: {\n    format: scorm2004_regex.CMIShortIdentifier,\n    max: 1,\n    delimiter: \"\",\n    unique: false,\n  },\n  numeric: {\n    format: scorm2004_regex.CMIDecimal,\n    max: 1,\n    delimiter: \"\",\n    unique: false,\n  },\n  other: {\n    format: scorm2004_regex.CMIString4000,\n    max: 1,\n    delimiter: \"\",\n    unique: false,\n  },\n};\nexport const CorrectResponses: Responses = {\n  \"true-false\": {\n    max: 1,\n    delimiter: \"\",\n    unique: false,\n    duplicate: false,\n    format: \"^true$|^false$\",\n    limit: 1,\n  },\n  choice: {\n    max: 36,\n    delimiter: \"[,]\",\n    unique: true,\n    duplicate: false,\n    format: scorm2004_regex.CMILongIdentifier,\n  },\n  \"fill-in\": {\n    max: 10,\n    delimiter: \"[,]\",\n    unique: false,\n    duplicate: false,\n    format: scorm2004_regex.CMILangString250cr,\n  },\n  \"long-fill-in\": {\n    max: 1,\n    delimiter: \"\",\n    unique: false,\n    duplicate: true,\n    format: scorm2004_regex.CMILangString4000,\n  },\n  matching: {\n    max: 36,\n    delimiter: \"[,]\",\n    delimiter2: \"[.]\",\n    unique: false,\n    duplicate: false,\n    format: scorm2004_regex.CMIShortIdentifier,\n    format2: scorm2004_regex.CMIShortIdentifier,\n  },\n  performance: {\n    max: 250,\n    delimiter: \"[,]\",\n    delimiter2: \"[.]\",\n    unique: false,\n    duplicate: false,\n    // step_name: optional short_identifier_type\n    format: PERFORMANCE_STEP_NAME,\n    // step_answer: optional characterstring (spaces allowed) or numeric range\n    format2: CR_PERFORMANCE_STEP_ANSWER,\n  },\n  sequencing: {\n    max: 36,\n    delimiter: \"[,]\",\n    unique: false,\n    duplicate: false,\n    format: scorm2004_regex.CMIShortIdentifier,\n  },\n  likert: {\n    max: 1,\n    delimiter: \"\",\n    unique: false,\n    duplicate: false,\n    format: scorm2004_regex.CMIShortIdentifier,\n    limit: 1,\n  },\n  numeric: {\n    max: 2,\n    delimiter: \"[:]\",\n    unique: false,\n    duplicate: false,\n    format: scorm2004_regex.CMIDecimal,\n    limit: 1,\n  },\n  other: {\n    max: 1,\n    delimiter: \"\",\n    unique: false,\n    duplicate: false,\n    format: scorm2004_regex.CMIString4000,\n    limit: 1,\n  },\n};\n\nexport type ResponseType = {\n  format: string;\n  max: number;\n  delimiter: string;\n  unique: boolean;\n  duplicate?: boolean;\n  format2?: string;\n  delimiter2?: string;\n  limit?: number;\n};\n\nexport type Responses = {\n  [key: string]: ResponseType;\n};\n","import BaseAPI from \"../BaseAPI\";\n\n/**\n * Private class that wraps a timeout call to the commit() function\n */\nexport class ScheduledCommit {\n  private _API;\n  private _cancelled = false;\n  private readonly _timeout;\n  private readonly _callback;\n\n  /**\n   * Constructor for ScheduledCommit\n   * @param {BaseAPI} API\n   * @param {number} when\n   * @param {string} callback\n   */\n  constructor(API: BaseAPI, when: number, callback: string) {\n    this._API = API;\n    this._timeout = setTimeout(this.wrapper.bind(this), when);\n    this._callback = callback;\n  }\n\n  /**\n   * Cancel any currently scheduled commit\n   */\n  cancel() {\n    this._cancelled = true;\n    if (this._timeout) {\n      clearTimeout(this._timeout);\n    }\n  }\n\n  /**\n   * Wrap the API commit call to check if the call has already been canceled\n   */\n  wrapper() {\n    if (!this._cancelled) {\n      // Only proceed with scheduled commit if API is properly initialized\n      if (this._API.isInitialized()) {\n        this._API.commit(this._callback, false, \"autocommit\");\n      }\n    }\n  }\n}\n","/**\n * Types for SCORM 2004 sequencing configuration\n */\n\nimport type { Activity } from \"../cmi/scorm2004/sequencing/activity\";\nimport { IActivity } from \"./activity_types\";\nimport {\n  RuleActionType,\n  RuleConditionOperator,\n  RuleConditionType,\n} from \"../cmi/scorm2004/sequencing/sequencing_rules\";\nimport {\n  RollupActionType,\n  RollupConditionCombination,\n  RollupConditionOperator,\n  RollupConditionType,\n  RollupConsiderationType,\n} from \"../cmi/scorm2004/sequencing/rollup_rules\";\nimport {\n  RandomizationTiming,\n  SelectionTiming,\n} from \"../cmi/scorm2004/sequencing/sequencing_controls\";\n\nexport const HIDE_LMS_UI_TOKENS = [\n  \"continue\",\n  \"previous\",\n  \"exit\",\n  \"exitAll\",\n  \"abandon\",\n  \"abandonAll\",\n  \"suspendAll\",\n] as const;\n\nexport type HideLmsUiItem = (typeof HIDE_LMS_UI_TOKENS)[number];\n\nexport type AuxiliaryResourceSettings = {\n  resourceId: string;\n  purpose: string;\n};\n\nexport type AuxiliaryResource = AuxiliaryResourceSettings;\n\n/**\n * Settings for an activity in the activity tree\n */\nexport type AdlRollupConsiderationRequirement =\n  \"always\" | \"ifAttempted\" | \"ifNotSkipped\" | \"ifNotSuspended\";\n\nexport type AdlRollupConsiderationsSettings = {\n  requiredForSatisfied?: AdlRollupConsiderationRequirement;\n  requiredForNotSatisfied?: AdlRollupConsiderationRequirement;\n  requiredForCompleted?: AdlRollupConsiderationRequirement;\n  requiredForIncomplete?: AdlRollupConsiderationRequirement;\n  measureSatisfactionIfActive?: boolean;\n};\n\nexport type CompletionThresholdSettings = {\n  completedByMeasure?: boolean;\n  minProgressMeasure?: number;\n  progressWeight?: number;\n};\n\nexport type DeliveryControlsSettings = {\n  tracked?: boolean;\n  completionSetByContent?: boolean;\n  objectiveSetByContent?: boolean;\n};\n\n/** Configuration for an activity's SCORM 2004 shared-data bucket mappings. */\nexport type SharedDataMapSettings = {\n  targetID: string;\n  readSharedData?: boolean;\n  writeSharedData?: boolean;\n};\n\nexport type ActivitySettings = {\n  id: string;\n  title: string;\n  children?: ActivitySettings[];\n  isVisible?: boolean;\n  isActive?: boolean;\n  isSuspended?: boolean;\n  isCompleted?: boolean;\n  isHiddenFromChoice?: boolean;\n  isAvailable?: boolean;\n  attemptLimit?: number | null;\n  attemptAbsoluteDurationLimit?: string | null;\n  activityAbsoluteDurationLimit?: string | null;\n  timeLimitAction?: string | null;\n  timeLimitDuration?: string | null;\n  beginTimeLimit?: string | null;\n  endTimeLimit?: string | null;\n  primaryObjective?: ObjectiveSettings;\n  objectives?: ObjectiveSettings[];\n  // Optional per-activity sequencing configuration\n  sequencingRules?: SequencingRulesSettings;\n  sequencingControls?: SequencingControlsSettings;\n  deliveryControls?: DeliveryControlsSettings;\n  rollupRules?: RollupRulesSettings;\n  rollupConsiderations?: AdlRollupConsiderationsSettings;\n  completionThreshold?: CompletionThresholdSettings;\n  selectionRandomizationState?: SelectionRandomizationStateSettings;\n  hideLmsUi?: HideLmsUiItem[];\n  sequencingCollectionRefs?: string | string[];\n  sequencingIdRef?: string | string[];\n  auxiliaryResources?: AuxiliaryResourceSettings[];\n  sharedDataMaps?: SharedDataMapSettings[];\n};\n\n/**\n * Settings for objective map info entries\n */\nexport type ObjectiveMapInfoSettings = {\n  targetObjectiveID: string;\n  readSatisfiedStatus?: boolean;\n  readNormalizedMeasure?: boolean;\n  writeSatisfiedStatus?: boolean;\n  writeNormalizedMeasure?: boolean;\n  readCompletionStatus?: boolean;\n  writeCompletionStatus?: boolean;\n  readProgressMeasure?: boolean;\n  writeProgressMeasure?: boolean;\n  readRawScore?: boolean;\n  writeRawScore?: boolean;\n  readMinScore?: boolean;\n  writeMinScore?: boolean;\n  readMaxScore?: boolean;\n  writeMaxScore?: boolean;\n  updateAttemptData?: boolean;\n};\n\n/**\n * Settings for activity objectives\n */\nexport type ObjectiveSettings = {\n  objectiveID: string;\n  description?: string;\n  isPrimary?: boolean;\n  satisfiedByMeasure?: boolean;\n  minNormalizedMeasure?: number | null;\n  mapInfo?: ObjectiveMapInfoSettings[];\n};\n\n/**\n * Settings for a rule condition\n */\nexport type RuleConditionSettings = {\n  condition: RuleConditionType;\n  operator?: RuleConditionOperator;\n  referencedObjective?: string;\n  parameters?: Record<string, any>;\n};\n\n/**\n * Settings for a sequencing rule\n */\nexport type SequencingRuleSettings = {\n  action: RuleActionType;\n  conditionCombination?: RuleConditionOperator | \"all\" | \"any\";\n  conditions: RuleConditionSettings[];\n};\n\n/**\n * Settings for sequencing rules\n */\nexport type SequencingRulesSettings = {\n  preConditionRules?: SequencingRuleSettings[];\n  exitConditionRules?: SequencingRuleSettings[];\n  postConditionRules?: SequencingRuleSettings[];\n};\n\n/**\n * Settings for sequencing controls\n */\nexport type SequencingControlsSettings = {\n  enabled?: boolean;\n  choice?: boolean;\n  choiceExit?: boolean;\n  flow?: boolean;\n  forwardOnly?: boolean;\n  useCurrentAttemptObjectiveInfo?: boolean;\n  useCurrentAttemptProgressInfo?: boolean;\n  preventActivation?: boolean;\n  constrainChoice?: boolean;\n  stopForwardTraversal?: boolean;\n  rollupObjectiveSatisfied?: boolean;\n  rollupProgressCompletion?: boolean;\n  objectiveMeasureWeight?: number;\n  selectionTiming?: SelectionTiming;\n  selectCount?: number | null;\n  randomizeChildren?: boolean;\n  randomizationTiming?: RandomizationTiming;\n  selectionCountStatus?: boolean;\n  reorderChildren?: boolean;\n  completionSetByContent?: boolean;\n  objectiveSetByContent?: boolean;\n  tracked?: boolean;\n};\n\nexport type SelectionRandomizationStateSettings = {\n  childOrder?: string[];\n  selectedChildIds?: string[];\n  hiddenFromChoiceChildIds?: string[];\n  selectionCountStatus?: boolean;\n  reorderChildren?: boolean;\n};\n\nexport type SequencingCollectionSettings = {\n  id?: string;\n  primaryObjective?: ObjectiveSettings;\n  objectives?: ObjectiveSettings[];\n  sequencingControls?: SequencingControlsSettings;\n  sequencingRules?: SequencingRulesSettings;\n  rollupRules?: RollupRulesSettings;\n  rollupConsiderations?: AdlRollupConsiderationsSettings;\n  selectionRandomizationState?: SelectionRandomizationStateSettings;\n  hideLmsUi?: HideLmsUiItem[];\n  auxiliaryResources?: AuxiliaryResourceSettings[];\n};\n\n/**\n * Settings for a rollup condition\n */\nexport type RollupConditionSettings = {\n  condition: RollupConditionType;\n  operator?: RollupConditionOperator;\n  parameters?: Record<string, any>;\n};\n\n/**\n * Settings for a rollup rule\n */\nexport type RollupRuleSettings = {\n  action: RollupActionType;\n  conditionCombination?: RollupConditionCombination;\n  consideration?: RollupConsiderationType;\n  minimumCount?: number;\n  minimumPercent?: number;\n  conditions: RollupConditionSettings[];\n};\n\n/**\n * Settings for rollup rules\n */\nexport type RollupRulesSettings = {\n  rules: RollupRuleSettings[];\n};\n\n/**\n * Settings for SCORM 2004 sequencing\n */\nexport type SequencingSettings = {\n  activityTree?: ActivitySettings;\n  sequencingRules?: SequencingRulesSettings;\n  sequencingControls?: SequencingControlsSettings;\n  rollupRules?: RollupRulesSettings;\n  hideLmsUi?: HideLmsUiItem[];\n  auxiliaryResources?: AuxiliaryResourceSettings[];\n  collections?: Record<string, SequencingCollectionSettings> | SequencingCollectionSettings[];\n\n  // Runtime sequencing configuration\n  /**\n   * Returns the seconds elapsed in the activity's current attempt, as tracked by\n   * the LMS. Only timeLimitExceeded rule conditions use this value,\n   * including 0, in place of attemptExperiencedDuration or attemptAbsoluteStartTime.\n   * A thrown error or a negative or non-numeric result falls back to those values.\n   */\n  getAttemptElapsedSeconds?: (activity: Activity) => number;\n  autoRollupOnCMIChange?: boolean;\n  autoProgressOnCompletion?: boolean;\n  validateNavigationRequests?: boolean;\n  enableEventSystem?: boolean;\n  logLevel?: \"debug\" | \"info\" | \"warn\" | \"error\";\n  eventListeners?: SequencingEventListeners;\n};\n\n/** Navigation availability emitted after delivery and sequencing state changes. */\nexport type NavigationValidityUpdate = {\n  continue: boolean;\n  previous: boolean;\n  choice: Record<string, \"true\" | \"false\">;\n  jump: Record<string, \"true\" | \"false\">;\n  hideLmsUi: HideLmsUiItem[];\n  auxiliaryResources: AuxiliaryResource[];\n};\n\n/**\n * Interface for sequencing event listeners.\n * Uses IActivity interface to provide type safety without circular dependencies.\n */\nexport interface SequencingEventListeners {\n  onSequencingStart?: (activity: IActivity) => void;\n  onSequencingEnd?: () => void;\n  onActivityDelivery?: (activity: IActivity) => void;\n  /**\n   * On same-activity resume, this listener and the ActivityUnload event receive the\n   * Activity after DB.2 has already prepared it for the new delivery.\n   */\n  onActivityUnload?: (activity: IActivity) => void;\n  onNavigationRequest?: (request: string, target?: string) => void;\n  onRollupComplete?: (activity: IActivity) => void;\n  onSequencingError?: (error: string, context?: string) => void;\n  onSequencingSessionEnd?: (data: {\n    reason: string;\n    exception?: string | null;\n    navigationRequest?: string;\n  }) => void;\n  onAutoCompletion?: (data: { activity: string; completionStatus: string }) => void;\n  onAutoSatisfaction?: (data: { activity: string; satisfiedStatus: boolean }) => void;\n  onPostConditionExitParent?: (data: { activity: string }) => void;\n  onPostConditionExitAll?: (data: { activity: string }) => void;\n  onTerminationRequestProcessing?: (data: {\n    request: string;\n    hasSequencingRequest: boolean;\n    currentActivity: string;\n  }) => void;\n  onNavigationRequestProcessing?: (data: {\n    request: string;\n    targetActivityId: string | null;\n  }) => void;\n  onPostConditionEvaluated?: (data: {\n    activity: string;\n    result: string;\n    iteration: number;\n  }) => void;\n  onMultiLevelExitAction?: (data: { activity: string }) => void;\n  onSuspendedActivityCleanup?: (data: { activity: string }) => void;\n  onSuspendError?: (data: { activity: string; error: string }) => void;\n  onActivitySuspended?: (data: { activity: string }) => void;\n  onDeliveryRequestProcessing?: (data: { request: string; target: string | null }) => void;\n  onNavigationValidityUpdate?: (data: NavigationValidityUpdate) => void;\n  onLimitConditionCheck?: (activity: IActivity, result: boolean) => void;\n  onStateInconsistency?: (data: { activity: string; issue: string }) => void;\n  onGlobalObjectiveMapInitialized?: (data: { count: number }) => void;\n  onGlobalObjectiveMapError?: (data: { error: string }) => void;\n  onGlobalObjectiveUpdated?: (data: { objectiveId: string; field: string; value: any }) => void;\n  onGlobalObjectiveUpdateError?: (data: { objectiveId: string; error: string }) => void;\n  onSequencingDebug?: (event: string, data?: any) => void;\n  // Enhanced debugging events\n  onActivityAttemptStart?: (activity: IActivity) => void;\n  onActivityAttemptEnd?: (activity: IActivity) => void;\n  onSequencingStateChange?: (state: any) => void;\n}\n/** A host navigation preview; this does not replace adl.nav.request_valid. */\nexport interface NavigationPreview {\n  outcome: \"allowed\" | \"blocked\" | \"unknown\";\n  targetActivityId: string | null;\n  endSequencingSession: boolean;\n  exception: string | null;\n}\n","import { Activity } from \"./activity\";\n\n// Runtime-only delivery identity: never part of Activity or persisted sequencing state.\nconst deliveryGenerations = new WeakMap<Activity, number>();\n\n/**\n * Get how many times DB.2 has delivered the activity in this runtime.\n * @param {Activity} activity - The delivered activity\n * @return {number} - The delivery generation, or 0 if it has never been delivered\n */\nexport function getDeliveryGeneration(activity: Activity): number {\n  return deliveryGenerations.get(activity) ?? 0;\n}\n\n/**\n * Record a new DB.2 delivery of the activity.\n * @param {Activity} activity - The activity being delivered\n */\nexport function advanceDeliveryGeneration(activity: Activity): void {\n  // @spec SCORM 2004 4th Ed. SN DB.2: each delivery launches content, including\n  // a resumed attempt; SCORM 2004 4th Ed. RTE 4.2.7: that launch has entry=resume.\n  deliveryGenerations.set(activity, getDeliveryGeneration(activity) + 1);\n}\n","import { Activity } from \"./activity\";\nimport { getDurationAsSeconds } from \"../../../utilities\";\nimport { scorm2004_regex } from \"../../../constants/regex\";\n\n/**\n * Reports how many seconds of an activity's current attempt have elapsed,\n * as configured through the `getAttemptElapsedSeconds` sequencing option.\n */\nexport type AttemptElapsedSecondsHook = (activity: Activity) => number;\n\n/**\n * Time-based condition evaluation shared by sequencing rule conditions and\n * rollup conditions, so both read the same limits the same way.\n *\n * @spec SCORM 2004 4th Ed. SN UP.2.1 (Sequencing Rule Check), RB.1.4.1\n * (Evaluate Rollup Conditions) — timeLimitExceeded, outsideAvailableTimeRange\n */\n\n/**\n * Whether the activity's time limit has been exceeded.\n *\n * The limit is `timeLimitDuration`, falling back to\n * `attemptAbsoluteDurationLimit`. The elapsed time comes from the hook when it\n * reports a valid value, otherwise from `attemptExperiencedDuration`, otherwise\n * from `attemptAbsoluteStartTime` measured against the clock.\n *\n * @param {Activity} activity - The activity to evaluate\n * @param {() => Date} now - The clock of the evaluating process\n * @param {AttemptElapsedSecondsHook | null} [getElapsedSeconds] - Elapsed-time hook\n * @return {boolean} True when the elapsed time is strictly greater than the limit\n */\nexport function isTimeLimitExceeded(\n  activity: Activity,\n  now: () => Date,\n  getElapsedSeconds?: AttemptElapsedSecondsHook | null,\n): boolean {\n  // Check timeLimitDuration (primary time limit)\n  let limit = activity.timeLimitDuration;\n\n  // Fallback to attemptAbsoluteDurationLimit if timeLimitDuration is not set\n  if (!limit && activity.attemptAbsoluteDurationLimit) {\n    limit = activity.attemptAbsoluteDurationLimit;\n  }\n\n  // No limit means condition is false\n  if (!limit) {\n    return false;\n  }\n\n  // Parse limit to seconds\n  const limitSeconds = getDurationAsSeconds(limit, scorm2004_regex.CMITimespan);\n\n  // Invalid or zero limit means condition is false\n  if (limitSeconds <= 0) {\n    return false;\n  }\n\n  let elapsedSeconds = 0;\n  let hasHookValue = false;\n\n  // Strategy 1: Use hook if available (preferred for LMS integration)\n  if (getElapsedSeconds) {\n    try {\n      const hookResult = getElapsedSeconds(activity);\n      if (typeof hookResult === \"number\" && !Number.isNaN(hookResult) && hookResult >= 0) {\n        elapsedSeconds = hookResult;\n        hasHookValue = true;\n      }\n    } catch {\n      elapsedSeconds = 0;\n    }\n  }\n\n  // Strategy 2: Try to use attemptExperiencedDuration if hook not available\n  if (!hasHookValue && elapsedSeconds === 0 && activity.attemptExperiencedDuration) {\n    const attemptDurationSeconds = getDurationAsSeconds(\n      activity.attemptExperiencedDuration,\n      scorm2004_regex.CMITimespan,\n    );\n    if (attemptDurationSeconds > 0) {\n      elapsedSeconds = attemptDurationSeconds;\n    }\n  }\n\n  // Strategy 3: Calculate from attemptAbsoluteStartTime if duration not available\n  if (!hasHookValue && elapsedSeconds === 0 && activity.attemptAbsoluteStartTime) {\n    try {\n      const start = new Date(activity.attemptAbsoluteStartTime).getTime();\n      const nowMs = now().getTime();\n\n      // Validate timestamps before calculating\n      if (!Number.isNaN(start) && !Number.isNaN(nowMs) && nowMs >= start) {\n        elapsedSeconds = (nowMs - start) / 1000;\n      }\n    } catch {\n      elapsedSeconds = 0;\n    }\n  }\n\n  // Time limit is exceeded if elapsed time is strictly greater than limit\n  return elapsedSeconds > limitSeconds;\n}\n\n/**\n * Whether the clock is before the activity's `beginTimeLimit` or after its\n * `endTimeLimit`.\n *\n * @param {Activity} activity - The activity to evaluate\n * @param {() => Date} clock - The clock of the evaluating process\n * @return {boolean}\n */\nexport function isOutsideAvailableTimeRange(activity: Activity, clock: () => Date): boolean {\n  const beginTime = activity.beginTimeLimit;\n  const endTime = activity.endTimeLimit;\n\n  if (!beginTime && !endTime) {\n    return false;\n  }\n\n  const now = clock();\n\n  if (beginTime) {\n    const beginDate = new Date(beginTime);\n    if (now < beginDate) {\n      return true;\n    }\n  }\n\n  if (endTime) {\n    const endDate = new Date(endTime);\n    if (now > endDate) {\n      return true;\n    }\n  }\n\n  return false;\n}\n","import { BaseCMI } from \"../../common/base_cmi\";\nimport { Activity, ActivityObjective } from \"./activity\";\nimport { Scorm2004ValidationError } from \"../../../exceptions/scorm2004_exceptions\";\nimport { scorm2004_errors } from \"../../../constants/error_codes\";\nimport { SuccessStatus, CompletionStatus } from \"../../../constants/enums\";\nimport { getDurationAsSeconds } from \"../../../utilities\";\nimport { scorm2004_regex } from \"../../../constants/regex\";\nimport { isOutsideAvailableTimeRange, isTimeLimitExceeded } from \"./time_conditions\";\n\n/**\n * Enum for rule condition operators\n */\nexport enum RuleConditionOperator {\n  NO_OP = \"noOp\",\n  NOT = \"not\",\n  AND = \"and\",\n  OR = \"or\",\n}\n\n/**\n * Enum for rule condition types\n */\nexport enum RuleConditionType {\n  SATISFIED = \"satisfied\",\n  OBJECTIVE_SATISFIED = \"objectiveSatisfied\",\n  OBJECTIVE_STATUS_KNOWN = \"objectiveStatusKnown\",\n  OBJECTIVE_MEASURE_KNOWN = \"objectiveMeasureKnown\",\n  OBJECTIVE_MEASURE_GREATER_THAN = \"objectiveMeasureGreaterThan\",\n  OBJECTIVE_MEASURE_LESS_THAN = \"objectiveMeasureLessThan\",\n  COMPLETED = \"completed\",\n  ACTIVITY_COMPLETED = \"activityCompleted\",\n  PROGRESS_KNOWN = \"progressKnown\",\n  ACTIVITY_PROGRESS_KNOWN = \"activityProgressKnown\",\n  ATTEMPTED = \"attempted\",\n  ATTEMPT_LIMIT_EXCEEDED = \"attemptLimitExceeded\",\n  TIME_LIMIT_EXCEEDED = \"timeLimitExceeded\",\n  OUTSIDE_AVAILABLE_TIME_RANGE = \"outsideAvailableTimeRange\",\n  ALWAYS = \"always\",\n  NEVER = \"never\",\n}\n\n/**\n * Enum for rule action types\n */\nexport enum RuleActionType {\n  SKIP = \"skip\",\n  DISABLED = \"disabled\",\n  HIDE_FROM_CHOICE = \"hiddenFromChoice\",\n  STOP_FORWARD_TRAVERSAL = \"stopForwardTraversal\",\n  EXIT_PARENT = \"exitParent\",\n  EXIT_ALL = \"exitAll\",\n  RETRY = \"retry\",\n  RETRY_ALL = \"retryAll\",\n  CONTINUE = \"continue\",\n  PREVIOUS = \"previous\",\n  EXIT = \"exit\",\n}\n\nexport type RuleConditionEvaluation = boolean | \"unknown\";\n\nconst OBJECTIVE_TRACKING_CONDITIONS = new Set<RuleConditionType>([\n  RuleConditionType.SATISFIED,\n  RuleConditionType.OBJECTIVE_SATISFIED,\n  RuleConditionType.OBJECTIVE_STATUS_KNOWN,\n  RuleConditionType.OBJECTIVE_MEASURE_KNOWN,\n  RuleConditionType.OBJECTIVE_MEASURE_GREATER_THAN,\n  RuleConditionType.OBJECTIVE_MEASURE_LESS_THAN,\n]);\n\nexport function kleeneNot(value: RuleConditionEvaluation): RuleConditionEvaluation {\n  if (value === \"unknown\") {\n    return \"unknown\";\n  }\n\n  return !value;\n}\n\nexport function kleeneAnd(values: RuleConditionEvaluation[]): RuleConditionEvaluation {\n  let hasUnknown = false;\n\n  for (const value of values) {\n    if (value === false) {\n      return false;\n    }\n    if (value === \"unknown\") {\n      hasUnknown = true;\n    }\n  }\n\n  return hasUnknown ? \"unknown\" : true;\n}\n\nexport function kleeneOr(values: RuleConditionEvaluation[]): RuleConditionEvaluation {\n  let hasUnknown = false;\n\n  for (const value of values) {\n    if (value === true) {\n      return true;\n    }\n    if (value === \"unknown\") {\n      hasUnknown = true;\n    }\n  }\n\n  return hasUnknown ? \"unknown\" : false;\n}\n\nexport function combineRuleConditionResults(\n  values: RuleConditionEvaluation[],\n  conditionCombination: string | RuleConditionOperator,\n): RuleConditionEvaluation {\n  if (values.length === 0) {\n    return false;\n  }\n\n  if (conditionCombination === \"all\" || conditionCombination === RuleConditionOperator.AND) {\n    return kleeneAnd(values);\n  }\n\n  if (conditionCombination === \"any\" || conditionCombination === RuleConditionOperator.OR) {\n    return kleeneOr(values);\n  }\n\n  return false;\n}\n\n/**\n * Class representing a sequencing rule condition\n */\nexport class RuleCondition extends BaseCMI {\n  private _condition: RuleConditionType = RuleConditionType.ALWAYS;\n  private _operator: RuleConditionOperator | null = null;\n  private _parameters: Map<string, any> = new Map();\n  private _referencedObjective: string | null = null;\n  // Optional, overridable provider for current time (LMS may set via SequencingService)\n  private static _now: () => Date = () => new Date();\n  // Optional, overridable hook for getting elapsed seconds\n  private static _getElapsedSecondsHook: ((activity: Activity) => number) | undefined = undefined;\n\n  /**\n   * Constructor for RuleCondition\n   * @param {RuleConditionType} condition - The condition type\n   * @param {RuleConditionOperator | null} operator - The operator (null for no operator)\n   * @param {Map<string, any>} parameters - Additional parameters for the condition\n   */\n  constructor(\n    condition: RuleConditionType = RuleConditionType.ALWAYS,\n    operator: RuleConditionOperator | null = null,\n    parameters: Map<string, any> = new Map(),\n  ) {\n    super(\"ruleCondition\");\n    this._condition = condition;\n    this._operator = operator;\n    this._parameters = parameters;\n  }\n\n  /**\n   * Allow integrators to override the clock used for time-based rules.\n   */\n  public static setNowProvider(now: () => Date) {\n    if (typeof now === \"function\") {\n      RuleCondition._now = now;\n    }\n  }\n\n  /**\n   * Allow integrators to set an elapsed seconds hook for time limit calculations\n   */\n  public static setElapsedSecondsHook(hook: ((activity: Activity) => number) | undefined) {\n    RuleCondition._getElapsedSecondsHook = hook;\n  }\n\n  /**\n   * Called when the API needs to be reset\n   */\n  reset() {\n    this._initialized = false;\n    this._condition = RuleConditionType.ALWAYS;\n    this._operator = null;\n    this._parameters = new Map();\n  }\n\n  /**\n   * Getter for condition\n   * @return {RuleConditionType}\n   */\n  get condition(): RuleConditionType {\n    return this._condition;\n  }\n\n  /**\n   * Setter for condition\n   * @param {RuleConditionType} condition\n   */\n  set condition(condition: RuleConditionType) {\n    this._condition = condition;\n  }\n\n  /**\n   * Getter for operator\n   * @return {RuleConditionOperator | null}\n   */\n  get operator(): RuleConditionOperator | null {\n    return this._operator;\n  }\n\n  /**\n   * Setter for operator\n   * @param {RuleConditionOperator | null} operator\n   */\n  set operator(operator: RuleConditionOperator | null) {\n    this._operator = operator;\n  }\n\n  /**\n   * Getter for parameters\n   * @return {Map<string, any>}\n   */\n  get parameters(): Map<string, any> {\n    return this._parameters;\n  }\n\n  /**\n   * Setter for parameters\n   * @param {Map<string, any>} parameters\n   */\n  set parameters(parameters: Map<string, any>) {\n    this._parameters = parameters;\n  }\n\n  get referencedObjective(): string | null {\n    return this._referencedObjective;\n  }\n\n  set referencedObjective(objectiveId: string | null) {\n    this._referencedObjective = objectiveId;\n  }\n\n  private resolveReferencedObjective(activity: Activity): ActivityObjective | null {\n    if (!this._referencedObjective) {\n      return null;\n    }\n    if (activity.primaryObjective?.id === this._referencedObjective) {\n      return activity.primaryObjective;\n    }\n    const objectives = activity.objectives || [];\n    return objectives.find((obj) => obj.id === this._referencedObjective) || null;\n  }\n\n  /**\n   * Evaluate the condition for an activity\n   * @param {Activity} activity - The activity to evaluate the condition for\n   * @return {RuleConditionEvaluation} - True, false, or unknown per SCORM 2004 4th Ed.\n   */\n  // Explicit null suppresses the legacy static hook for per-process evaluation.\n  evaluate(activity: Activity, now: () => Date = RuleCondition._now, getElapsedSeconds: ((activity: Activity) => number) | null | undefined = RuleCondition._getElapsedSecondsHook): RuleConditionEvaluation {\n    let result: RuleConditionEvaluation;\n    const hasReferencedObjective = this._referencedObjective !== null;\n    const referencedObjective = this.resolveReferencedObjective(activity);\n\n    // @spec SCORM 2004 SN: objective tracking information for an activity with\n    // deliveryControls.tracked=false is unavailable to its sequencing rules.\n    // The SM.1 useCurrentAttempt* flags govern whether child tracking participates in\n    // parent rollup; they do not hide an activity's own mapped/preserved tracking from\n    // that activity's UP.2.1 precondition evaluation.\n    // @spec SCORM 2004 4th Ed. TR OB-03b steps 6-7 and SN UP.2.1/SB.2.2\n    if (\n      (activity.sequencingControls?.tracked === false &&\n        OBJECTIVE_TRACKING_CONDITIONS.has(this._condition))\n    ) {\n      result = \"unknown\";\n    } else\n      switch (this._condition) {\n        case RuleConditionType.SATISFIED:\n        case RuleConditionType.OBJECTIVE_SATISFIED:\n          if (hasReferencedObjective && !referencedObjective) {\n            result = false;\n          } else if (referencedObjective) {\n            result =\n              referencedObjective.satisfiedStatusKnown || referencedObjective.progressStatus\n                ? referencedObjective.satisfiedStatus === true\n                : \"unknown\";\n          } else if (activity.objectiveSatisfiedStatusKnown) {\n            result = activity.objectiveSatisfiedStatus === true;\n          } else if (\n            !activity.primaryObjective &&\n            activity.successStatus !== SuccessStatus.UNKNOWN\n          ) {\n            result = activity.successStatus === SuccessStatus.PASSED;\n          } else {\n            result = \"unknown\";\n          }\n          break;\n        case RuleConditionType.OBJECTIVE_STATUS_KNOWN:\n          // noinspection PointlessBooleanExpressionJS\n          result =\n            hasReferencedObjective && !referencedObjective\n              ? false\n              : referencedObjective\n                ? !!referencedObjective.satisfiedStatusKnown\n                : !!activity.objectiveSatisfiedStatusKnown;\n          break;\n        case RuleConditionType.OBJECTIVE_MEASURE_KNOWN:\n          // noinspection PointlessBooleanExpressionJS\n          result =\n            hasReferencedObjective && !referencedObjective\n              ? false\n              : referencedObjective\n                ? !!referencedObjective.measureStatus\n                : !!activity.objectiveMeasureStatus;\n          break;\n        case RuleConditionType.OBJECTIVE_MEASURE_GREATER_THAN: {\n          if (hasReferencedObjective && !referencedObjective) {\n            result = false;\n            break;\n          }\n          const greaterThanValue = this._parameters.get(\"threshold\") || 0;\n          const measureStatus = referencedObjective\n            ? referencedObjective.measureStatus\n            : activity.objectiveMeasureStatus;\n          const measureValue = referencedObjective\n            ? referencedObjective.normalizedMeasure\n            : activity.objectiveNormalizedMeasure;\n          result = measureStatus ? measureValue > greaterThanValue : \"unknown\";\n          break;\n        }\n        case RuleConditionType.OBJECTIVE_MEASURE_LESS_THAN: {\n          if (hasReferencedObjective && !referencedObjective) {\n            result = false;\n            break;\n          }\n          const lessThanValue = this._parameters.get(\"threshold\") || 0;\n          const measureStatus = referencedObjective\n            ? referencedObjective.measureStatus\n            : activity.objectiveMeasureStatus;\n          const measureValue = referencedObjective\n            ? referencedObjective.normalizedMeasure\n            : activity.objectiveNormalizedMeasure;\n          result = measureStatus ? measureValue < lessThanValue : \"unknown\";\n          break;\n        }\n        case RuleConditionType.COMPLETED:\n        case RuleConditionType.ACTIVITY_COMPLETED:\n          // SCORM 2004 4th Edition: When referencedObjective is specified,\n          // check the objective's completion status instead of the activity's\n          if (hasReferencedObjective && !referencedObjective) {\n            result = false;\n          } else if (referencedObjective) {\n            result =\n              referencedObjective.completionStatus === CompletionStatus.UNKNOWN\n                ? \"unknown\"\n                : referencedObjective.completionStatus === CompletionStatus.COMPLETED;\n          } else if (activity.completionStatus === CompletionStatus.UNKNOWN) {\n            result = \"unknown\";\n          } else {\n            result = activity.completionStatus === CompletionStatus.COMPLETED;\n          }\n          break;\n        case RuleConditionType.PROGRESS_KNOWN:\n        case RuleConditionType.ACTIVITY_PROGRESS_KNOWN:\n          // SCORM 2004 4th Edition: When referencedObjective is specified,\n          // check the objective's completion status instead of the activity's\n          if (hasReferencedObjective && !referencedObjective) {\n            result = false;\n          } else if (referencedObjective) {\n            result = referencedObjective.completionStatus !== CompletionStatus.UNKNOWN;\n          } else {\n            result = activity.completionStatus !== \"unknown\";\n          }\n          break;\n        case RuleConditionType.ATTEMPTED:\n          result = activity.attemptCount > 0;\n          break;\n        case RuleConditionType.ATTEMPT_LIMIT_EXCEEDED:\n          // Use activity's hasAttemptLimitExceeded() which properly checks\n          // if the activity has an attempt limit set\n          result = activity.hasAttemptLimitExceeded();\n          break;\n        case RuleConditionType.TIME_LIMIT_EXCEEDED:\n          result = isTimeLimitExceeded(activity, now, getElapsedSeconds);\n          break;\n        case RuleConditionType.OUTSIDE_AVAILABLE_TIME_RANGE:\n          result = isOutsideAvailableTimeRange(activity, now);\n          break;\n        case RuleConditionType.ALWAYS:\n          result = true;\n          break;\n        case RuleConditionType.NEVER:\n          result = false;\n          break;\n        default:\n          result = false;\n          break;\n      }\n\n    if (this._operator === RuleConditionOperator.NOT) {\n      result = kleeneNot(result);\n    }\n\n    return result;\n  }\n\n  /**\n   * Parse ISO 8601 duration to milliseconds\n   * Uses the standard getDurationAsSeconds utility which supports full ISO 8601 format\n   * including date components (years, months, weeks, days) and time components (hours, minutes, seconds).\n   * @param {string} duration - ISO 8601 duration string (e.g., \"PT1H30M\", \"P1D\", \"P1Y2M3DT4H5M6S\")\n   * @return {number} - Duration in milliseconds\n   * @private\n   */\n  private parseISO8601Duration(duration: string): number {\n    // Use the standard utility function which handles full ISO 8601 duration format\n    // including years (Y), months (M), weeks (W), days (D), hours (H), minutes (M), and seconds (S)\n    const seconds = getDurationAsSeconds(duration, scorm2004_regex.CMITimespan);\n    // Convert seconds to milliseconds\n    return seconds * 1000;\n  }\n\n  /**\n   * toJSON for RuleCondition\n   * @return {object}\n   */\n  toJSON(): object {\n    this.jsonString = true;\n    const result = {\n      condition: this._condition,\n      operator: this._operator,\n      parameters: Object.fromEntries(this._parameters),\n    };\n    this.jsonString = false;\n    return result;\n  }\n}\n\n/**\n * Class representing a sequencing rule\n */\nexport class SequencingRule extends BaseCMI {\n  private _conditions: RuleCondition[] = [];\n  private _action: RuleActionType = RuleActionType.SKIP;\n  private _conditionCombination: string | RuleConditionOperator = RuleConditionOperator.AND;\n\n  /**\n   * Constructor for SequencingRule\n   * @param {RuleActionType} action - The action to take when the rule conditions are met\n   * @param {string | RuleConditionOperator} conditionCombination - How to combine multiple conditions (\"all\"/\"and\" or \"any\"/\"or\")\n   */\n  constructor(\n    action: RuleActionType = RuleActionType.SKIP,\n    conditionCombination: string | RuleConditionOperator = RuleConditionOperator.AND,\n  ) {\n    super(\"sequencingRule\");\n    this._action = action;\n    this._conditionCombination = conditionCombination;\n  }\n\n  /**\n   * Called when the API needs to be reset\n   */\n  reset() {\n    this._initialized = false;\n    this._conditions = [];\n    this._action = RuleActionType.SKIP;\n    this._conditionCombination = RuleConditionOperator.AND;\n  }\n\n  /**\n   * Getter for conditions\n   * @return {RuleCondition[]}\n   */\n  get conditions(): RuleCondition[] {\n    return this._conditions;\n  }\n\n  /**\n   * Add a condition to the rule\n   * @param {RuleCondition} condition - The condition to add\n   */\n  addCondition(condition: RuleCondition): void {\n    // noinspection SuspiciousTypeOfGuard\n    if (!(condition instanceof RuleCondition)) {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".conditions\",\n        scorm2004_errors.TYPE_MISMATCH as number,\n      );\n    }\n    // Check if the condition is already in the array\n    if (!this._conditions.includes(condition)) {\n      this._conditions.push(condition);\n    }\n  }\n\n  /**\n   * Remove a condition from the rule\n   * @param {RuleCondition} condition - The condition to remove\n   * @return {boolean} - True if the condition was removed, false otherwise\n   */\n  removeCondition(condition: RuleCondition): boolean {\n    // noinspection SuspiciousTypeOfGuard\n    if (!(condition instanceof RuleCondition)) {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".conditions\",\n        scorm2004_errors.TYPE_MISMATCH as number,\n      );\n    }\n    const index = this._conditions.indexOf(condition);\n    if (index !== -1) {\n      this._conditions.splice(index, 1);\n      return true;\n    }\n    return false;\n  }\n\n  /**\n   * Getter for action\n   * @return {RuleActionType}\n   */\n  get action(): RuleActionType {\n    return this._action;\n  }\n\n  /**\n   * Setter for action\n   * @param {RuleActionType} action\n   */\n  set action(action: RuleActionType) {\n    this._action = action;\n  }\n\n  /**\n   * Getter for conditionCombination\n   * @return {string | RuleConditionOperator}\n   */\n  get conditionCombination(): string | RuleConditionOperator {\n    return this._conditionCombination;\n  }\n\n  /**\n   * Setter for conditionCombination\n   * @param {string | RuleConditionOperator} conditionCombination\n   */\n  set conditionCombination(conditionCombination: string | RuleConditionOperator) {\n    this._conditionCombination = conditionCombination;\n  }\n\n  /**\n   * Evaluate the rule for an activity\n   * @param {Activity} activity - The activity to evaluate the rule for\n   * @return {boolean} - True if the rule conditions are met, false otherwise\n   */\n  evaluate(activity: Activity, now?: () => Date, getElapsedSeconds?: ((activity: Activity) => number) | null): boolean {\n    return (\n      combineRuleConditionResults(\n        this._conditions.map((condition) => condition.evaluate(activity, now, getElapsedSeconds)),\n        this._conditionCombination,\n      ) === true\n    );\n  }\n\n  /**\n   * toJSON for SequencingRule\n   * @return {object}\n   */\n  toJSON(): object {\n    this.jsonString = true;\n    const result = {\n      conditions: this._conditions,\n      action: this._action,\n      conditionCombination: this._conditionCombination,\n    };\n    this.jsonString = false;\n    return result;\n  }\n}\n\n/**\n * Class representing a collection of sequencing rules\n */\nexport class SequencingRules extends BaseCMI {\n  private _preConditionRules: SequencingRule[] = [];\n  private _exitConditionRules: SequencingRule[] = [];\n  private _postConditionRules: SequencingRule[] = [];\n\n  /**\n   * Constructor for SequencingRules\n   */\n  constructor() {\n    super(\"sequencingRules\");\n  }\n\n  /**\n   * Called when the API needs to be reset\n   */\n  reset() {\n    this._initialized = false;\n    this._preConditionRules = [];\n    this._exitConditionRules = [];\n    this._postConditionRules = [];\n  }\n\n  /**\n   * Getter for preConditionRules\n   * @return {SequencingRule[]}\n   */\n  get preConditionRules(): SequencingRule[] {\n    return this._preConditionRules;\n  }\n\n  /**\n   * Add a pre-condition rule\n   * @param {SequencingRule} rule - The rule to add\n   */\n  addPreConditionRule(rule: SequencingRule): void {\n    // noinspection SuspiciousTypeOfGuard\n    if (!(rule instanceof SequencingRule)) {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".preConditionRules\",\n        scorm2004_errors.TYPE_MISMATCH as number,\n      );\n    }\n    this._preConditionRules.push(rule);\n  }\n\n  /**\n   * Getter for exitConditionRules\n   * @return {SequencingRule[]}\n   */\n  get exitConditionRules(): SequencingRule[] {\n    return this._exitConditionRules;\n  }\n\n  /**\n   * Add an exit condition rule\n   * @param {SequencingRule} rule - The rule to add\n   */\n  addExitConditionRule(rule: SequencingRule): void {\n    // noinspection SuspiciousTypeOfGuard\n    if (!(rule instanceof SequencingRule)) {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".exitConditionRules\",\n        scorm2004_errors.TYPE_MISMATCH as number,\n      );\n    }\n    this._exitConditionRules.push(rule);\n  }\n\n  /**\n   * Getter for postConditionRules\n   * @return {SequencingRule[]}\n   */\n  get postConditionRules(): SequencingRule[] {\n    return this._postConditionRules;\n  }\n\n  /**\n   * Add a post-condition rule\n   * @param {SequencingRule} rule - The rule to add\n   */\n  addPostConditionRule(rule: SequencingRule): void {\n    // noinspection SuspiciousTypeOfGuard\n    if (!(rule instanceof SequencingRule)) {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".postConditionRules\",\n        scorm2004_errors.TYPE_MISMATCH as number,\n      );\n    }\n    this._postConditionRules.push(rule);\n  }\n\n  /**\n   * Evaluate pre-condition rules for an activity\n   * @param {Activity} activity - The activity to evaluate the rules for\n   * @return {RuleActionType | null} - The action to take, or null if no rules are met\n   */\n  evaluatePreConditionRules(activity: Activity, now?: () => Date, getElapsedSeconds?: ((activity: Activity) => number) | null): RuleActionType | null {\n    for (const rule of this._preConditionRules) {\n      if (rule.evaluate(activity, now, getElapsedSeconds)) {\n        return rule.action;\n      }\n    }\n    return null;\n  }\n\n  /**\n   * Evaluate exit condition rules for an activity\n   * @param {Activity} activity - The activity to evaluate the rules for\n   * @return {RuleActionType | null} - The action to take, or null if no rules are met\n   */\n  evaluateExitConditionRules(activity: Activity, now?: () => Date, getElapsedSeconds?: ((activity: Activity) => number) | null): RuleActionType | null {\n    for (const rule of this._exitConditionRules) {\n      if (rule.evaluate(activity, now, getElapsedSeconds)) {\n        return rule.action;\n      }\n    }\n    return null;\n  }\n\n  /**\n   * Evaluate post-condition rules for an activity\n   * @param {Activity} activity - The activity to evaluate the rules for\n   * @return {RuleActionType | null} - The action to take, or null if no rules are met\n   */\n  evaluatePostConditionRules(activity: Activity, now?: () => Date, getElapsedSeconds?: ((activity: Activity) => number) | null): RuleActionType | null {\n    for (const rule of this._postConditionRules) {\n      if (rule.evaluate(activity, now, getElapsedSeconds)) {\n        return rule.action;\n      }\n    }\n    return null;\n  }\n\n  /**\n   * toJSON for SequencingRules\n   * @return {object}\n   */\n  toJSON(): object {\n    this.jsonString = true;\n    const result = {\n      preConditionRules: this._preConditionRules,\n      exitConditionRules: this._exitConditionRules,\n      postConditionRules: this._postConditionRules,\n    };\n    this.jsonString = false;\n    return result;\n  }\n}\n","import { Activity } from \"../activity\";\n\n/**\n * Enum for sequencing request types\n * These represent the various navigation requests that can be made in SCORM 2004\n */\nexport enum SequencingRequestType {\n  START = \"start\",\n  RESUME_ALL = \"resumeAll\",\n  CONTINUE = \"continue\",\n  PREVIOUS = \"previous\",\n  CHOICE = \"choice\",\n  JUMP = \"jump\",\n  EXIT = \"exit\",\n  EXIT_PARENT = \"exitParent\",\n  EXIT_ALL = \"exitAll\",\n  ABANDON = \"abandon\",\n  ABANDON_ALL = \"abandonAll\",\n  SUSPEND_ALL = \"suspendAll\",\n  RETRY = \"retry\",\n  RETRY_ALL = \"retryAll\",\n}\n\n/**\n * Enum for delivery request types\n */\nexport enum DeliveryRequestType {\n  DELIVER = \"deliver\",\n  DO_NOT_DELIVER = \"doNotDeliver\",\n}\n\n/**\n * Class representing the result of a sequencing process\n */\nexport class SequencingResult {\n  public deliveryRequest: DeliveryRequestType;\n  public targetActivity: Activity | null;\n  public exception: string | null;\n  public endSequencingSession: boolean;\n\n  constructor(\n    deliveryRequest: DeliveryRequestType = DeliveryRequestType.DO_NOT_DELIVER,\n    targetActivity: Activity | null = null,\n    exception: string | null = null,\n    endSequencingSession: boolean = false\n  ) {\n    this.deliveryRequest = deliveryRequest;\n    this.targetActivity = targetActivity;\n    this.exception = exception;\n    this.endSequencingSession = endSequencingSession;\n  }\n}\n\n/**\n * Result of Flow Subprocess (SB.2.3)\n * Used internally to propagate endSequencingSession flag through flow processes\n */\nexport class FlowSubprocessResult {\n  public identifiedActivity: Activity | null;\n  public deliverable: boolean;\n  public exception: string | null;\n  public endSequencingSession: boolean;\n\n  constructor(\n    identifiedActivity: Activity | null,\n    deliverable: boolean,\n    exception: string | null = null,\n    endSequencingSession: boolean = false\n  ) {\n    this.identifiedActivity = identifiedActivity;\n    this.deliverable = deliverable;\n    this.exception = exception;\n    this.endSequencingSession = endSequencingSession;\n  }\n}\n\n/**\n * Result of Choice Traversal Subprocess (SB.2.4)\n * Used internally to propagate exception information from choice traversal\n */\nexport class ChoiceTraversalResult {\n  public activity: Activity | null;\n  public exception: string | null;\n\n  constructor(activity: Activity | null, exception: string | null = null) {\n    this.activity = activity;\n    this.exception = exception;\n  }\n}\n\n/**\n * Enum for flow subprocess modes\n */\nexport enum FlowSubprocessMode {\n  FORWARD = \"forward\",\n  BACKWARD = \"backward\",\n}\n","import { Activity } from \"../activity\";\nimport {\n  SequencingRule,\n  RuleActionType,\n} from \"../sequencing_rules\";\nimport { SequencingRequestType } from \"./sequencing_request_types\";\nimport { getDurationAsSeconds } from \"../../../../utilities\";\nimport { scorm2004_regex } from \"../../../../constants/regex\";\n\n// Re-export for convenience\nexport { SequencingRequestType };\n\n/**\n * Result of post-condition rule evaluation\n */\nexport interface PostConditionResult {\n  sequencingRequest: SequencingRequestType | null;\n  terminationRequest: SequencingRequestType | null;\n}\n\n/**\n * Options for RuleEvaluationEngine\n */\nexport interface RuleEvaluationOptions {\n  now?: (() => Date) | undefined;\n  getAttemptElapsedSecondsHook?: ((activity: Activity) => number) | undefined;\n}\n\n/**\n * RuleEvaluationEngine - Centralized rule evaluation for SCORM 2004 sequencing\n *\n * This class extracts and consolidates all rule evaluation logic from SequencingProcess:\n * - Pre-condition rule evaluation (UP.2)\n * - Exit condition rule evaluation (TB.2.1)\n * - Post-condition rule evaluation (TB.2.2)\n * - Limit conditions checking (UP.1)\n * - Individual condition evaluation\n *\n * Key SCORM 2004 processes implemented:\n * - UP.1: Limit Conditions Check Process\n * - UP.2: Sequencing Rules Check Process\n * - UP.2.1: Sequencing Rules Check Subprocess\n * - TB.2.1: Exit Action Rules Subprocess\n * - TB.2.2: Post Condition Rules Subprocess\n */\nexport class RuleEvaluationEngine {\n  private now: () => Date;\n  private getAttemptElapsedSecondsHook: ((activity: Activity) => number) | null;\n\n  constructor(options: RuleEvaluationOptions = {}) {\n    this.now = options.now || (() => new Date());\n    this.getAttemptElapsedSecondsHook = options.getAttemptElapsedSecondsHook || null;\n  }\n\n  /**\n   * Sequencing Rules Check Process (UP.2)\n   * General process for evaluating a set of sequencing rules\n   * @param {Activity} activity - The activity to evaluate rules for\n   * @param {SequencingRule[]} rules - The rules to evaluate\n   * @return {RuleActionType | null} - The action to take, or null if no rules apply\n   */\n  public checkSequencingRules(\n    activity: Activity,\n    rules: SequencingRule[]\n  ): RuleActionType | null {\n    for (const rule of rules) {\n      if (this.checkRuleSubprocess(activity, rule)) {\n        return rule.action;\n      }\n    }\n    return null;\n  }\n\n  /**\n   * Sequencing Rules Check Subprocess (UP.2.1)\n   * Evaluates individual sequencing rule conditions\n   * @param {Activity} activity - The activity to evaluate the rule for\n   * @param {SequencingRule} rule - The rule to evaluate\n   * @return {boolean} - True only when the rule evaluates to definite true\n   */\n  public checkRuleSubprocess(activity: Activity, rule: SequencingRule): boolean {\n    return rule.evaluate(activity, this.now, this.getAttemptElapsedSecondsHook);\n  }\n\n  /**\n   * Exit Action Rules Subprocess (TB.2.1)\n   * Evaluates the exit condition rules for an activity\n   * @param {Activity} activity - The activity to evaluate exit rules for\n   * @return {RuleActionType | null} - The exit action to process, if any\n   */\n  public evaluateExitRules(activity: Activity): RuleActionType | null {\n    const exitAction = this.checkSequencingRules(\n      activity,\n      activity.sequencingRules.exitConditionRules\n    );\n\n    // Only certain actions are valid for exit condition rules\n    if (\n      exitAction === RuleActionType.EXIT ||\n      exitAction === RuleActionType.EXIT_PARENT ||\n      exitAction === RuleActionType.EXIT_ALL\n    ) {\n      return exitAction;\n    }\n\n    return null;\n  }\n\n  /**\n   * Post Condition Rules Subprocess (TB.2.2)\n   * Evaluates the post-condition rules for an activity after delivery\n   * @param {Activity} activity - The activity to evaluate post-condition rules for\n   * @return {RuleActionType | null} - The action to take, if any\n   */\n  public evaluatePostConditionAction(activity: Activity): RuleActionType | null {\n    const postAction = this.checkSequencingRules(\n      activity,\n      activity.sequencingRules.postConditionRules\n    );\n\n    // Only certain actions are valid for post-condition rules\n    const validActions = [\n      RuleActionType.EXIT_PARENT,\n      RuleActionType.EXIT_ALL,\n      RuleActionType.RETRY,\n      RuleActionType.RETRY_ALL,\n      RuleActionType.CONTINUE,\n      RuleActionType.PREVIOUS,\n      RuleActionType.STOP_FORWARD_TRAVERSAL\n    ];\n\n    if (postAction && validActions.includes(postAction)) {\n      return postAction;\n    }\n\n    return null;\n  }\n\n  /**\n   * Evaluate post-condition rules and map to sequencing/termination requests\n   * @param {Activity} activity - The activity to evaluate\n   * @return {PostConditionResult} - The post-condition result with sequencing and termination requests\n   */\n  public evaluatePostConditions(activity: Activity): PostConditionResult {\n    const postAction = this.evaluatePostConditionAction(activity);\n\n    if (!postAction) {\n      return {\n        sequencingRequest: null,\n        terminationRequest: null\n      };\n    }\n\n    switch (postAction) {\n      case RuleActionType.EXIT_PARENT:\n        return {\n          sequencingRequest: null,\n          terminationRequest: SequencingRequestType.EXIT_PARENT\n        };\n\n      case RuleActionType.EXIT_ALL:\n        return {\n          sequencingRequest: null,\n          terminationRequest: SequencingRequestType.EXIT_ALL\n        };\n\n      case RuleActionType.RETRY:\n        return {\n          sequencingRequest: SequencingRequestType.RETRY,\n          terminationRequest: null\n        };\n\n      case RuleActionType.RETRY_ALL:\n        return {\n          sequencingRequest: SequencingRequestType.RETRY,\n          terminationRequest: SequencingRequestType.EXIT_ALL\n        };\n\n      case RuleActionType.CONTINUE:\n        return {\n          sequencingRequest: SequencingRequestType.CONTINUE,\n          terminationRequest: null\n        };\n\n      case RuleActionType.PREVIOUS:\n        return {\n          sequencingRequest: SequencingRequestType.PREVIOUS,\n          terminationRequest: null\n        };\n\n      case RuleActionType.STOP_FORWARD_TRAVERSAL:\n        // Set traversal limiter on controls; not a navigation request\n        activity.sequencingControls.stopForwardTraversal = true;\n        return {\n          sequencingRequest: null,\n          terminationRequest: null\n        };\n\n      default:\n        return {\n          sequencingRequest: null,\n          terminationRequest: null\n        };\n    }\n  }\n\n  /**\n   * Limit Conditions Check Process (UP.1)\n   * Checks if an activity has exceeded its limit conditions\n   * @param {Activity} activity - The activity to check\n   * @return {boolean} - True if limit conditions are violated\n   */\n  public checkLimitConditions(activity: Activity): boolean {\n    // @spec SCORM 2004 4th Ed. SN UP.1 step 1: a suspended activity has an attempt in progress\n    // and is not subject to limit conditions; only a new attempt is (SB.2.6 Resume All, DB.2).\n    if (activity.isSuspended) {\n      return false;\n    }\n\n    // Check attempt limit\n    if (activity.attemptLimit !== null && activity.attemptCount >= activity.attemptLimit) {\n      return true;\n    }\n\n    // Check attempt absolute duration limit\n    if (activity.attemptAbsoluteDurationLimit !== null) {\n      const attemptLimitMs = this.parseDuration(activity.attemptAbsoluteDurationLimit);\n      if (attemptLimitMs > 0) {\n        const attemptDurationMs = this.parseDuration(activity.attemptExperiencedDuration);\n        if (attemptDurationMs >= attemptLimitMs) {\n          return true;\n        }\n      }\n    }\n\n    // Check activity absolute duration limit\n    if (activity.activityAbsoluteDurationLimit !== null) {\n      const activityLimitMs = this.parseDuration(activity.activityAbsoluteDurationLimit);\n      if (activityLimitMs > 0) {\n        const activityDurationMs = this.parseDuration(activity.activityExperiencedDuration);\n        if (activityDurationMs >= activityLimitMs) {\n          return true;\n        }\n      }\n    }\n\n    return false;\n  }\n\n  /**\n   * Parse ISO 8601 duration to milliseconds\n   * @param {string} duration - ISO 8601 duration string\n   * @return {number} - Duration in milliseconds\n   */\n  public parseDuration(duration: string): number {\n    if (!duration || typeof duration !== \"string\") {\n      return 0;\n    }\n\n    // Full ISO 8601 duration regex\n    const regex =\n      /^P(?:(\\d+(?:\\.\\d+)?)Y)?(?:(\\d+(?:\\.\\d+)?)M)?(?:(\\d+(?:\\.\\d+)?)W)?(?:(\\d+(?:\\.\\d+)?)D)?(?:T(?:(\\d+(?:\\.\\d+)?)H)?(?:(\\d+(?:\\.\\d+)?)M)?(?:(\\d+(?:\\.\\d+)?)S)?)?$/;\n\n    const matches = duration.match(regex);\n    if (!matches || duration === \"P\" || duration.endsWith(\"T\")) {\n      return 0;\n    }\n\n    const years = parseFloat(matches[1] || \"0\");\n    const months = parseFloat(matches[2] || \"0\");\n    const weeks = parseFloat(matches[3] || \"0\");\n    const days = parseFloat(matches[4] || \"0\");\n    const hours = parseFloat(matches[5] || \"0\");\n    const minutes = parseFloat(matches[6] || \"0\");\n    const seconds = parseFloat(matches[7] || \"0\");\n\n    let totalMs = 0;\n    totalMs += years * 365.25 * 24 * 3600 * 1000;\n    totalMs += months * 30.44 * 24 * 3600 * 1000;\n    totalMs += weeks * 7 * 24 * 3600 * 1000;\n    totalMs += days * 24 * 3600 * 1000;\n    totalMs += hours * 3600 * 1000;\n    totalMs += minutes * 60 * 1000;\n    totalMs += seconds * 1000;\n\n    return totalMs;\n  }\n\n  /**\n   * Get elapsed attempt seconds for an activity\n   * @param {Activity} activity - The activity\n   * @return {number} - Elapsed seconds\n   */\n  public getElapsedSeconds(activity: Activity): number {\n    if (this.getAttemptElapsedSecondsHook) {\n      try {\n        return this.getAttemptElapsedSecondsHook(activity) || 0;\n      } catch {\n        return 0;\n      }\n    }\n\n    if (activity.attemptAbsoluteStartTime) {\n      const start = new Date(activity.attemptAbsoluteStartTime).getTime();\n      const nowMs = this.now().getTime();\n      if (!Number.isNaN(start) && nowMs > start) {\n        return Math.max(0, (nowMs - start) / 1000);\n      }\n    }\n\n    return 0;\n  }\n\n  /**\n   * Check if time limit has been exceeded\n   * @param {Activity} activity - The activity to check\n   * @return {boolean} - True if time limit exceeded\n   */\n  public isTimeLimitExceeded(activity: Activity): boolean {\n    let limit = activity.timeLimitDuration;\n    if (!limit && activity.attemptAbsoluteDurationLimit) {\n      limit = activity.attemptAbsoluteDurationLimit;\n    }\n\n    if (!limit) {\n      return false;\n    }\n\n    const limitSeconds = getDurationAsSeconds(limit, scorm2004_regex.CMITimespan);\n    if (limitSeconds <= 0) {\n      return false;\n    }\n\n    const elapsedSeconds = this.getElapsedSeconds(activity);\n    return elapsedSeconds > limitSeconds;\n  }\n\n  /**\n   * Check if activity is outside available time range\n   * @param {Activity} activity - The activity to check\n   * @return {boolean} - True if outside time range\n   */\n  public isOutsideAvailableTimeRange(activity: Activity): boolean {\n    const now = this.now();\n\n    if (activity.beginTimeLimit) {\n      try {\n        const beginDate = new Date(activity.beginTimeLimit);\n        if (!Number.isNaN(beginDate.getTime()) && now < beginDate) {\n          return true;\n        }\n      } catch {\n        // Invalid date format\n      }\n    }\n\n    if (activity.endTimeLimit) {\n      try {\n        const endDate = new Date(activity.endTimeLimit);\n        if (!Number.isNaN(endDate.getTime()) && now > endDate) {\n          return true;\n        }\n      } catch {\n        // Invalid date format\n      }\n    }\n\n    return false;\n  }\n\n  /**\n   * Evaluate pre-condition rules and check if activity can be delivered\n   * @param {Activity} activity - The activity to check\n   * @return {{ canDeliver: boolean; wasSkipped: boolean }} - Delivery check result\n   */\n  public canDeliverActivity(activity: Activity): { canDeliver: boolean; wasSkipped: boolean } {\n    // Check limit conditions first\n    if (this.checkLimitConditions(activity)) {\n      return { canDeliver: false, wasSkipped: false };\n    }\n\n    // Check pre-condition rules\n    const preConditionResult = this.checkSequencingRules(\n      activity,\n      activity.sequencingRules.preConditionRules\n    );\n\n    const wasSkipped = preConditionResult === RuleActionType.SKIP;\n\n    return {\n      canDeliver: preConditionResult !== RuleActionType.SKIP &&\n                  preConditionResult !== RuleActionType.DISABLED,\n      wasSkipped\n    };\n  }\n}\n","import { Activity } from \"../activity\";\nimport { ActivityTree } from \"../activity_tree\";\nimport { RuleEvaluationEngine } from \"../rules/rule_evaluation_engine\";\nimport { RuleActionType } from \"../sequencing_rules\";\nimport { getDurationAsSeconds } from \"../../../../utilities\";\nimport { scorm2004_regex } from \"../../../../constants/regex\";\n\n/**\n * Result of activity tree state consistency check\n */\nexport interface StateConsistencyResult {\n  consistent: boolean;\n  exception: string | null;\n}\n\n/**\n * Result of resource constraint check\n */\nexport interface ResourceConstraintResult {\n  available: boolean;\n  exception: string | null;\n}\n\n/**\n * Result of concurrent delivery check\n */\nexport interface ConcurrentDeliveryResult {\n  allowed: boolean;\n  exception: string | null;\n}\n\n/**\n * Result of activity dependency check\n */\nexport interface DependencyResult {\n  satisfied: boolean;\n  exception: string | null;\n}\n\n/**\n * DeliveryValidator\n *\n * Handles all delivery validation for the SCORM 2004 sequencing engine.\n * Extracted from OverallSequencingProcess to follow Single Responsibility Principle.\n *\n * Responsibilities:\n * - Validate activity tree state consistency\n * - Validate resource constraints\n * - Prevent concurrent delivery\n * - Validate activity dependencies\n * - Check activity process (UP.5)\n * - Limit conditions check process (UP.1)\n *\n * @spec SN Book: DB.1.1 (Delivery Request Process)\n * @spec SN Book: UP.1 (Limit Conditions Check Process)\n * @spec SN Book: UP.5 (Check Activity Process)\n */\nexport class DeliveryValidator {\n  private activityTree: ActivityTree;\n  private eventCallback: ((eventType: string, data?: any) => void) | null;\n  private now: () => Date;\n  private contentDeliveredGetter: (() => boolean) | null = null;\n  private ruleEngineProvider: () => RuleEvaluationEngine;\n\n  constructor(\n    activityTree: ActivityTree,\n    eventCallback: ((eventType: string, data?: any) => void) | null = null,\n    options?: { now?: () => Date },\n    ruleEngineProvider?: () => RuleEvaluationEngine\n  ) {\n    this.activityTree = activityTree;\n    this.eventCallback = eventCallback;\n    this.now = options?.now || (() => new Date());\n    if (ruleEngineProvider) {\n      this.ruleEngineProvider = ruleEngineProvider;\n    } else {\n      // Without a provider, evaluate rules on the same clock as the limit checks.\n      const ruleEngine = new RuleEvaluationEngine({ now: this.now });\n      this.ruleEngineProvider = () => ruleEngine;\n    }\n  }\n\n  /**\n   * Set getter for content delivered flag\n   */\n  public setContentDeliveredGetter(getter: () => boolean): void {\n    this.contentDeliveredGetter = getter;\n  }\n\n  /**\n   * Validate Activity Tree State Consistency\n   * @param {Activity} activity - Activity to validate\n   * @return {StateConsistencyResult} - Consistency result\n   */\n  public validateTreeConsistency(activity: Activity): StateConsistencyResult {\n    // Check that the activity tree is in a consistent state for delivery\n    if (!this.activityTree.root) {\n      return { consistent: false, exception: \"DB.1.1-4\" }; // No activity tree\n    }\n\n    // Validate activity is part of the current tree\n    if (!this.isActivityPartOfTree(activity, this.activityTree.root)) {\n      return { consistent: false, exception: \"DB.1.1-5\" }; // Activity not in tree\n    }\n\n    // Check for conflicting active activities\n    const activeActivities = this.getActiveActivities();\n    if (activeActivities.length > 1) {\n      // Multiple active activities indicate inconsistent state\n      this.fireEvent(\"onStateInconsistency\", {\n        activeActivities: activeActivities.map((a) => a.id),\n        targetActivity: activity.id,\n      });\n      return { consistent: false, exception: \"DB.1.1-6\" }; // State inconsistency\n    }\n\n    // Validate parent-child relationships are intact\n    let current: Activity | null = activity;\n    while (current?.parent) {\n      if (!current.parent.children.includes(current)) {\n        return { consistent: false, exception: \"DB.1.1-7\" }; // Broken parent-child relationship\n      }\n      current = current.parent;\n    }\n\n    return { consistent: true, exception: null };\n  }\n\n  /**\n   * Validate Resource Constraints\n   * @param {Activity} activity - Activity to validate\n   * @return {ResourceConstraintResult} - Resource availability result\n   */\n  public validateResources(activity: Activity): ResourceConstraintResult {\n    // Check if required resources are available\n    const requiredResources = this.getRequiredResources(activity);\n    for (const resource of requiredResources) {\n      if (!this.isResourceAvailable(resource)) {\n        return {\n          available: false,\n          exception: \"DB.1.1-8\", // Resource not available\n        };\n      }\n    }\n\n    // Check system resource limits\n    const systemResourceCheck = this.checkSystemLimits();\n    if (!systemResourceCheck.adequate) {\n      return {\n        available: false,\n        exception: \"DB.1.1-9\", // Insufficient system resources\n      };\n    }\n\n    return { available: true, exception: null };\n  }\n\n  /**\n   * Validate Concurrent Delivery Prevention\n   * @param {Activity} activity - Activity to validate\n   * @return {ConcurrentDeliveryResult} - Concurrency check result\n   */\n  public validateConcurrentDelivery(activity: Activity): ConcurrentDeliveryResult {\n    const contentDelivered = this.contentDeliveredGetter\n      ? this.contentDeliveredGetter()\n      : false;\n\n    // Check if another delivery is currently in progress\n    if (\n      contentDelivered &&\n      this.activityTree.currentActivity &&\n      this.activityTree.currentActivity !== activity\n    ) {\n      return {\n        allowed: false,\n        exception: \"DB.1.1-10\", // Another activity is currently being delivered\n      };\n    }\n\n    // Check for pending delivery requests in queue\n    if (this.hasPendingDeliveryRequests()) {\n      return {\n        allowed: false,\n        exception: \"DB.1.1-11\", // Delivery request already in queue\n      };\n    }\n\n    // Validate delivery lock status\n    if (this.isDeliveryLocked()) {\n      return {\n        allowed: false,\n        exception: \"DB.1.1-12\", // Delivery is currently locked\n      };\n    }\n\n    return { allowed: true, exception: null };\n  }\n\n  /**\n   * Validate Activity Dependencies\n   * @param {Activity} activity - Activity to validate\n   * @return {DependencyResult} - Dependency check result\n   */\n  public validateDependencies(activity: Activity): DependencyResult {\n    // Check prerequisite activities\n    const prerequisites = this.getPrerequisites(activity);\n    for (const prerequisite of prerequisites) {\n      if (!this.isPrerequisiteSatisfied(prerequisite, activity)) {\n        return {\n          satisfied: false,\n          exception: \"DB.1.1-13\", // Prerequisites not satisfied\n        };\n      }\n    }\n\n    // Check objective dependencies\n    const objectiveDependencies = this.getObjectiveDependencies(activity);\n    for (const dependency of objectiveDependencies) {\n      if (!this.isObjectiveDependencySatisfied(dependency)) {\n        return {\n          satisfied: false,\n          exception: \"DB.1.1-14\", // Objective dependencies not met\n        };\n      }\n    }\n\n    // Check sequencing rule dependencies\n    const sequencingDependencies = this.getSequencingRuleDependencies(activity);\n    if (!sequencingDependencies.satisfied) {\n      return {\n        satisfied: false,\n        exception: \"DB.1.1-15\", // Sequencing dependencies not met\n      };\n    }\n\n    return { satisfied: true, exception: null };\n  }\n\n  /**\n   * Check Activity Process (UP.5)\n   * Validates if an activity can be delivered based on sequencing rules and limit conditions\n   * Note: Cluster/leaf validation is handled in DB.1.1 Step 1, not here\n   * @param {Activity} activity - The activity to check\n   * @return {boolean} - True if activity is valid (not disabled, limits not violated)\n   */\n  public checkActivity(activity: Activity, evaluationActivity = activity, emitEvent = true): boolean {\n    // Retain the availability check in addition to the UP.5 rule checks.\n    if (!activity.isAvailable) {\n      return false;\n    }\n\n    // UP.5 Step 1: Apply only Disabled rules so other actions cannot mask them.\n    const disabledRules = activity.sequencingRules.preConditionRules.filter(\n      (rule) => rule.action === RuleActionType.DISABLED\n    );\n    if (this.ruleEngineProvider().checkSequencingRules(evaluationActivity, disabledRules) !== null) {\n      return false;\n    }\n\n    // UP.5 Step 2: Check limit conditions (UP.1)\n    if (!this.checkLimitConditions(activity, emitEvent)) {\n      return false;\n    }\n\n    // Note: We intentionally do NOT check isHiddenFromChoice or cluster status here\n    // - isHiddenFromChoice is validated in navigation/choice processes\n    // - Cluster validation is handled in DB.1.1 Step 1 (only target activity)\n\n    // Activity passes all checks\n    return true;\n  }\n\n  /**\n   * Limit Conditions Check Process (UP.1)\n   * Checks if any limit conditions are violated for the activity\n   * @param {Activity} activity - The activity to check limit conditions for\n   * @return {boolean} - True if limit conditions are met, false if violated\n   */\n  public checkLimitConditions(activity: Activity, emitEvent = true): boolean {\n    let result = true;\n    let failureReason = \"\";\n\n    // @spec SCORM 2004 4th Ed. SN UP.1 step 1: a suspended activity has an attempt in progress;\n    // limit conditions only apply to activities that will begin a new attempt, so they are not\n    // violated by the attempt being continued (SB.2.6 Resume All, DB.2 step 5).\n    if (activity.isSuspended) {\n      if (emitEvent) this.fireEvent(\"onLimitConditionCheck\", {\n        activity: activity,\n        result: true,\n        failureReason: \"\",\n        attemptInProgress: true,\n      });\n      return true;\n    }\n\n    // Check attempt limit\n    if (activity.attemptLimit !== null && activity.attemptLimit > 0) {\n      if (activity.attemptCount >= activity.attemptLimit) {\n        result = false;\n        failureReason = \"Attempt limit exceeded\";\n      }\n    }\n\n    // Check attempt absolute duration limit\n    // A limit of 0 (or \"PT0H0M0S\") is treated as \"no limit\" per IMS SS spec\n    if (result && activity.attemptAbsoluteDurationLimit) {\n      const limitDuration = getDurationAsSeconds(\n        activity.attemptAbsoluteDurationLimit,\n        scorm2004_regex.CMITimespan\n      );\n      // Only check if there's an actual non-zero limit\n      if (limitDuration > 0) {\n        const currentDuration = getDurationAsSeconds(\n          activity.attemptAbsoluteDuration || \"PT0H0M0S\",\n          scorm2004_regex.CMITimespan\n        );\n        if (currentDuration >= limitDuration) {\n          result = false;\n          failureReason = \"Attempt duration limit exceeded\";\n        }\n      }\n    }\n\n    // Check activity absolute duration limit\n    // A limit of 0 (or \"PT0H0M0S\") is treated as \"no limit\" per IMS SS spec\n    if (result && activity.activityAbsoluteDurationLimit) {\n      const limitDuration = getDurationAsSeconds(\n        activity.activityAbsoluteDurationLimit,\n        scorm2004_regex.CMITimespan\n      );\n      // Only check if there's an actual non-zero limit\n      if (limitDuration > 0) {\n        const currentDuration = getDurationAsSeconds(\n          activity.activityAbsoluteDuration || \"PT0H0M0S\",\n          scorm2004_regex.CMITimespan\n        );\n        if (currentDuration >= limitDuration) {\n          result = false;\n          failureReason = \"Activity duration limit exceeded\";\n        }\n      }\n    }\n\n    // Check begin time limit\n    if (result && activity.beginTimeLimit) {\n      const currentTime = this.now();\n      const beginTime = new Date(activity.beginTimeLimit);\n      if (currentTime < beginTime) {\n        result = false;\n        failureReason = \"Not yet time to begin\";\n      }\n    }\n\n    // Check end time limit\n    if (result && activity.endTimeLimit) {\n      const currentTime = this.now();\n      const endTime = new Date(activity.endTimeLimit);\n      if (currentTime > endTime) {\n        result = false;\n        failureReason = \"Time limit expired\";\n      }\n    }\n\n    // Fire limit condition check event\n    if (emitEvent) this.fireEvent(\"onLimitConditionCheck\", {\n      activity: activity,\n      result: result,\n      failureReason: failureReason,\n      checks: {\n        attemptLimit: activity.attemptLimit,\n        attemptCount: activity.attemptCount,\n        attemptDurationLimit: activity.attemptAbsoluteDurationLimit,\n        activityDurationLimit: activity.activityAbsoluteDurationLimit,\n        beginTimeLimit: activity.beginTimeLimit,\n        endTimeLimit: activity.endTimeLimit,\n      },\n    });\n\n    return result;\n  }\n\n  /**\n   * Check if activity is part of tree\n   */\n  private isActivityPartOfTree(activity: Activity, root: Activity): boolean {\n    if (activity === root) {\n      return true;\n    }\n\n    for (const child of root.children) {\n      if (this.isActivityPartOfTree(activity, child)) {\n        return true;\n      }\n    }\n\n    return false;\n  }\n\n  /**\n   * Get all active activities in the tree\n   */\n  private getActiveActivities(): Activity[] {\n    const activeActivities: Activity[] = [];\n    if (this.activityTree.root) {\n      this.collectActiveActivities(this.activityTree.root, activeActivities);\n    }\n    return activeActivities;\n  }\n\n  private collectActiveActivities(\n    activity: Activity,\n    activeActivities: Activity[]\n  ): void {\n    if (activity.isActive) {\n      activeActivities.push(activity);\n    }\n    for (const child of activity.children) {\n      this.collectActiveActivities(child, activeActivities);\n    }\n  }\n\n  /**\n   * Get required resources for activity\n   */\n  public getRequiredResources(activity: Activity): string[] {\n    // Parse activity metadata for resource requirements\n    const resources: string[] = [];\n\n    // Check for multimedia requirements based on activity title and location\n    const activityInfo = (activity.title + \" \" + activity.location).toLowerCase();\n    if (activityInfo.includes(\"video\") || activityInfo.includes(\"multimedia\")) {\n      resources.push(\"video-codec\");\n    }\n    if (activityInfo.includes(\"audio\") || activityInfo.includes(\"sound\")) {\n      resources.push(\"audio-codec\");\n    }\n\n    // Check for plugin requirements from activity location/title\n    if (activityInfo.includes(\"flash\") || activityInfo.includes(\".swf\")) {\n      resources.push(\"flash-plugin\");\n    }\n    if (activityInfo.includes(\"java\") || activityInfo.includes(\"applet\")) {\n      resources.push(\"java-runtime\");\n    }\n\n    // Check for bandwidth requirements based on activity type\n    if (activity.children && activity.children.length > 0) {\n      resources.push(\"high-bandwidth\"); // Container activities may need more bandwidth\n    }\n\n    // Check for storage requirements based on duration limits\n    if (\n      activity.attemptAbsoluteDurationLimit &&\n      this.parseDurationToMinutes(activity.attemptAbsoluteDurationLimit) > 60\n    ) {\n      resources.push(\"extended-storage\"); // Long duration activities need more storage\n    }\n\n    // Check for specific SCORM requirements\n    if (activity.attemptLimit && activity.attemptLimit > 1) {\n      resources.push(\"persistent-storage\"); // Multiple attempts need storage\n    }\n\n    return resources;\n  }\n\n  /**\n   * Check if resource is available\n   */\n  public isResourceAvailable(resource: string): boolean {\n    try {\n      switch (resource) {\n        case \"video-codec\":\n          // Check if HTML5 video is supported\n          return !!(document.createElement(\"video\").canPlayType);\n\n        case \"audio-codec\":\n          // Check if HTML5 audio is supported\n          return !!(document.createElement(\"audio\").canPlayType);\n\n        case \"flash-plugin\":\n          // Check for Flash plugin (legacy support)\n          return (\n            navigator.plugins &&\n            Array.from(navigator.plugins).some(\n              (plugin) => plugin.name === \"Shockwave Flash\"\n            )\n          );\n\n        case \"java-runtime\":\n          // Check for Java support (mostly deprecated in modern browsers)\n          return (\n            navigator.plugins &&\n            Array.from(navigator.plugins).some((plugin) => plugin.name === \"Java\")\n          );\n\n        case \"high-bandwidth\":\n          // Check network connection (basic heuristic)\n          if (\"connection\" in navigator) {\n            const connection = (navigator as any).connection;\n            return connection.effectiveType === \"4g\" || connection.downlink > 5;\n          }\n          return true; // Assume available if can't detect\n\n        case \"extended-storage\":\n          // Assume storage is available for SCORM content\n          return true;\n\n        case \"persistent-storage\":\n          // Check for persistent storage capabilities\n          return \"localStorage\" in window && \"sessionStorage\" in window;\n\n        default:\n          // Unknown resource, assume available\n          return true;\n      }\n    } catch (error) {\n      // If any check fails, assume resource is unavailable\n      return false;\n    }\n  }\n\n  /**\n   * Check system resource limits\n   */\n  public checkSystemLimits(): { adequate: boolean } {\n    try {\n      let adequate = true;\n\n      // Check memory usage if available (Chrome/Edge only)\n      if (\"memory\" in performance) {\n        const memory = (performance as any).memory;\n        const memoryUsagePercent = memory.usedJSHeapSize / memory.jsHeapSizeLimit;\n        if (memoryUsagePercent > 0.8) {\n          // More than 80% memory used\n          adequate = false;\n        }\n      }\n\n      // Check for device memory hint (modern browsers)\n      if (\"deviceMemory\" in navigator) {\n        const deviceMemory = (navigator as any).deviceMemory;\n        if (deviceMemory < 2) {\n          // Less than 2GB device memory\n          adequate = false;\n        }\n      }\n\n      // Check hardware concurrency (rough CPU check)\n      if (\"hardwareConcurrency\" in navigator) {\n        const cores = navigator.hardwareConcurrency;\n        if (cores < 2) {\n          // Single core devices might struggle\n          adequate = false;\n        }\n      }\n\n      // Check connection quality for network-intensive activities\n      if (\"connection\" in navigator) {\n        const connection = (navigator as any).connection;\n        if (connection.saveData || connection.effectiveType === \"slow-2g\") {\n          adequate = false;\n        }\n      }\n\n      return { adequate };\n    } catch (error) {\n      // If checks fail, assume resources are adequate\n      return { adequate: true };\n    }\n  }\n\n  private hasPendingDeliveryRequests(): boolean {\n    // Check if there are pending delivery requests in the system\n    if (this.activityTree && (this.activityTree as any).pendingRequests) {\n      return (this.activityTree as any).pendingRequests.length > 0;\n    }\n\n    // Check for any pending fetch operations (if using fetch API)\n    if (typeof window !== \"undefined\" && (window as any).pendingScormRequests) {\n      return (window as any).pendingScormRequests > 0;\n    }\n\n    return false;\n  }\n\n  private isDeliveryLocked(): boolean {\n    // Check for navigation lock\n    if (this.activityTree && (this.activityTree as any).navigationLocked) {\n      return true;\n    }\n\n    // Check for active termination process\n    if (this.activityTree && (this.activityTree as any).terminationInProgress) {\n      return true;\n    }\n\n    // Check system resource limits\n    const resourceCheck = this.checkSystemLimits();\n    if (!resourceCheck.adequate) {\n      return true;\n    }\n\n    // Check for maintenance mode (would be set by LMS)\n    return !!(\n      typeof window !== \"undefined\" && (window as any).scormMaintenanceMode\n    );\n  }\n\n  /**\n   * Get activity prerequisites\n   */\n  public getPrerequisites(activity: Activity): string[] {\n    const prerequisites: string[] = [];\n\n    // Check for preCondition rules that reference other activities\n    if (activity.sequencingRules && activity.sequencingRules.preConditionRules) {\n      for (const rule of activity.sequencingRules.preConditionRules) {\n        if (rule.conditions && rule.conditions.length > 0) {\n          for (const condition of rule.conditions) {\n            if (\n              (condition as any).referencedObjectiveID &&\n              (condition as any).referencedObjectiveID !== activity.id\n            ) {\n              prerequisites.push((condition as any).referencedObjectiveID);\n            }\n          }\n        }\n      }\n    }\n\n    // Check for sequencing control dependencies\n    if (\n      activity.parent &&\n      activity.sequencingControls &&\n      !activity.sequencingControls.choiceExit\n    ) {\n      const siblings = activity.parent.children;\n      if (siblings) {\n        const activityIndex = siblings.indexOf(activity);\n\n        // Add previous siblings as prerequisites for sequential flow\n        for (let i = 0; i < activityIndex; i++) {\n          const sibling = siblings[i];\n          if (sibling) {\n            prerequisites.push(sibling.id);\n          }\n        }\n      }\n    }\n\n    // Check for explicit prerequisite metadata (if defined in activity)\n    if ((activity as any).prerequisiteActivities) {\n      prerequisites.push(...(activity as any).prerequisiteActivities);\n    }\n\n    return Array.from(new Set(prerequisites)); // Remove duplicates\n  }\n\n  /**\n   * Check if prerequisite is satisfied\n   */\n  public isPrerequisiteSatisfied(\n    prerequisiteId: string,\n    _activity: Activity\n  ): boolean {\n    const prerequisite = this.activityTree.getActivity(prerequisiteId);\n    if (!prerequisite) {\n      return false;\n    }\n\n    return prerequisite.completionStatus === \"completed\";\n  }\n\n  /**\n   * Get objective dependencies\n   */\n  public getObjectiveDependencies(activity: Activity): string[] {\n    const dependencies: string[] = [];\n\n    // Check activity's objective mappings for global objective references\n    const objectives = (activity as any).objectives;\n    if (objectives && objectives.length > 0) {\n      for (const objective of objectives) {\n        if ((objective as any).globalObjectiveID) {\n          dependencies.push((objective as any).globalObjectiveID);\n        }\n\n        if (\n          !(objective as any).satisfiedByMeasure &&\n          (objective as any).readNormalizedMeasure\n        ) {\n          dependencies.push(objective.id + \"_measure\");\n        }\n      }\n    }\n\n    // Check sequencing rules for objective references\n    if (activity.sequencingRules) {\n      const allRules = [\n        ...(activity.sequencingRules.preConditionRules || []),\n        ...(activity.sequencingRules.exitConditionRules || []),\n        ...(activity.sequencingRules.postConditionRules || []),\n      ];\n\n      for (const rule of allRules) {\n        if (rule.conditions && rule.conditions.length > 0) {\n          for (const condition of rule.conditions) {\n            if (\n              (condition as any).objectiveReference &&\n              (condition as any).objectiveReference !== activity.id\n            ) {\n              dependencies.push((condition as any).objectiveReference);\n            }\n          }\n        }\n      }\n    }\n\n    return Array.from(new Set(dependencies)); // Remove duplicates\n  }\n\n  /**\n   * Check if objective dependency is satisfied\n   */\n  public isObjectiveDependencySatisfied(objectiveId: string): boolean {\n    // Handle global objective references\n    if (this.activityTree && (this.activityTree as any).globalObjectives) {\n      const globalObjectives = (this.activityTree as any).globalObjectives;\n      const globalObjective = globalObjectives[objectiveId];\n\n      if (globalObjective) {\n        return (\n          globalObjective.satisfied === true &&\n          globalObjective.statusKnown === true\n        );\n      }\n    }\n\n    // Handle measure-based dependencies\n    if (objectiveId.endsWith(\"_measure\")) {\n      const baseObjectiveId = objectiveId.replace(\"_measure\", \"\");\n      if (this.activityTree && (this.activityTree as any).globalObjectives) {\n        const globalObjectives = (this.activityTree as any).globalObjectives;\n        const globalObjective = globalObjectives[baseObjectiveId];\n\n        if (globalObjective) {\n          return (\n            globalObjective.measureKnown === true &&\n            globalObjective.normalizedMeasure >= 0\n          );\n        }\n      }\n    }\n\n    // Handle activity-specific objective references\n    const referencedActivity = this.activityTree.getActivity(objectiveId);\n    if (referencedActivity) {\n      return (\n        referencedActivity.objectiveSatisfiedStatus &&\n        referencedActivity.objectiveMeasureStatus\n      );\n    }\n\n    // If objective is not found or cannot be evaluated, assume not satisfied\n    return false;\n  }\n\n  private getSequencingRuleDependencies(activity: Activity): { satisfied: boolean } {\n    let satisfied = true;\n\n    try {\n      // Check pre-condition rule dependencies\n      if (activity.sequencingRules && activity.sequencingRules.preConditionRules) {\n        for (const rule of activity.sequencingRules.preConditionRules) {\n          if (rule.conditions && rule.conditions.length > 0) {\n            for (const condition of rule.conditions) {\n              const conditionType =\n                (condition as any).conditionType || condition.condition;\n\n              switch (conditionType) {\n                case \"activityProgressKnown\":\n                  if (!activity.progressMeasureStatus) satisfied = false;\n                  break;\n\n                case \"objectiveStatusKnown\":\n                case \"objectiveSatisfied\": {\n                  const objectiveId =\n                    (condition as any).referencedObjectiveID || activity.id;\n                  if (!this.isObjectiveDependencySatisfied(objectiveId))\n                    satisfied = false;\n                  break;\n                }\n\n                case \"attemptLimitExceeded\":\n                  if (activity.attemptLimit === null) satisfied = false;\n                  break;\n\n                case \"timeLimitExceeded\":\n                  if (\n                    !activity.attemptAbsoluteDurationLimit &&\n                    !activity.activityAbsoluteDurationLimit\n                  )\n                    satisfied = false;\n                  break;\n\n                case \"always\":\n                case \"never\":\n                  // These conditions have no dependencies\n                  break;\n\n                default:\n                  // Unknown condition type, assume dependency not satisfied\n                  satisfied = false;\n              }\n            }\n          }\n        }\n      }\n\n      // Check exit condition rule dependencies (similar logic)\n      if (activity.sequencingRules && activity.sequencingRules.exitConditionRules) {\n        for (const rule of activity.sequencingRules.exitConditionRules) {\n          if (rule.conditions && rule.conditions.length > 0) {\n            for (const condition of rule.conditions) {\n              const conditionType =\n                (condition as any).conditionType || condition.condition;\n\n              if (\n                [\"objectiveStatusKnown\", \"objectiveSatisfied\"].includes(\n                  conditionType\n                )\n              ) {\n                const objectiveId =\n                  (condition as any).referencedObjectiveID || activity.id;\n                if (!this.isObjectiveDependencySatisfied(objectiveId))\n                  satisfied = false;\n              }\n            }\n          }\n        }\n      }\n\n      // Check rollup rule dependencies\n      if (activity.rollupRules && activity.rollupRules.rules) {\n        for (const rule of activity.rollupRules.rules) {\n          if (rule.conditions && rule.conditions.length > 0) {\n            // Rollup rules depend on child activity completion\n            if (activity.children && activity.children.length > 0) {\n              for (const child of activity.children) {\n                if (!child.isCompleted) {\n                  satisfied = false;\n                  break;\n                }\n              }\n            }\n          }\n        }\n      }\n    } catch (error) {\n      // If any error occurs during dependency check, mark as not satisfied\n      satisfied = false;\n    }\n\n    return { satisfied };\n  }\n\n  /**\n   * Helper method to parse ISO 8601 duration to minutes\n   */\n  private parseDurationToMinutes(duration: string): number {\n    return getDurationAsSeconds(duration, scorm2004_regex.CMITimespan) / 60;\n  }\n\n  /**\n   * Fire a sequencing event\n   * @param {string} eventType - The type of event\n   * @param {any} data - Event data\n   */\n  private fireEvent(eventType: string, data?: any): void {\n    try {\n      if (this.eventCallback) {\n        this.eventCallback(eventType, data);\n      }\n    } catch (error) {\n      console.warn(`Failed to fire delivery validator event ${eventType}: ${error}`);\n    }\n  }\n}\n","import { Activity } from \"../activity\";\nimport { ActivityTree } from \"../activity_tree\";\n\n/**\n * Utility class for querying and traversing the activity tree\n * Extracted from SequencingProcess to reduce class size and improve maintainability\n *\n * This class provides helper methods for:\n * - Tree traversal and ancestor lookups\n * - Activity relationship queries (parent/child/sibling)\n * - Activity state and completion checks\n * - Common ancestor calculations\n */\nexport class ActivityTreeQueries {\n  constructor(private activityTree: ActivityTree) {}\n\n  /**\n   * Check if activity is in the activity tree\n   * @param {Activity} activity - Activity to check\n   * @return {boolean} - True if activity is in the tree\n   */\n  public isInTree(activity: Activity): boolean {\n    return this.activityTree.getAllActivities().includes(activity);\n  }\n\n  /**\n   * Check if activity1 is a parent (ancestor) of activity2\n   * Used for choiceExit validation to determine if target is within a subtree\n   * @param {Activity} ancestor - Potential parent/ancestor activity\n   * @param {Activity} descendant - Potential child/descendant activity\n   * @return {boolean} - True if ancestor is an ancestor of descendant\n   */\n  public isAncestorOf(ancestor: Activity, descendant: Activity): boolean {\n    let current: Activity | null = descendant;\n    while (current) {\n      if (current === ancestor) {\n        return true;\n      }\n      current = current.parent;\n    }\n    return false;\n  }\n\n  /**\n   * Find common ancestor of two activities\n   * @param {Activity | null} activity1 - First activity\n   * @param {Activity | null} activity2 - Second activity\n   * @return {Activity | null} - Common ancestor or null\n   */\n  public findCommonAncestor(\n    activity1: Activity | null,\n    activity2: Activity | null\n  ): Activity | null {\n    if (!activity1 || !activity2) {\n      return null;\n    }\n\n    // Get ancestors of activity1\n    const ancestors1: Activity[] = [];\n    let current: Activity | null = activity1;\n    while (current) {\n      ancestors1.push(current);\n      current = current.parent;\n    }\n\n    // Find first common ancestor\n    current = activity2;\n    while (current) {\n      if (ancestors1.includes(current)) {\n        return current;\n      }\n      current = current.parent;\n    }\n\n    return null;\n  }\n\n  /**\n   * Find which child of ancestor is in the path to the target activity\n   * Used for multi-level constraint validation\n   * @param {Activity} ancestor - The ancestor activity\n   * @param {Activity} target - The target activity\n   * @return {Activity | null} - The child in the path, or null\n   */\n  public findChildInPath(ancestor: Activity, target: Activity): Activity | null {\n    let current: Activity | null = target;\n\n    while (current && current.parent) {\n      if (current.parent === ancestor) {\n        return current;\n      }\n      current = current.parent;\n    }\n\n    return null;\n  }\n\n  /**\n   * Check if activity is the last activity in a forward preorder tree traversal\n   * Per SB.2.1 step 3.1: An activity is last overall if it's a leaf with no next siblings\n   * anywhere in its ancestor chain\n   * @param {Activity} activity - The activity to check\n   * @return {boolean} - True if this is the last activity in the tree\n   */\n  public isLastInTree(activity: Activity): boolean {\n    // An activity is last overall if:\n    // 1. It's a leaf (no children)\n    // 2. It has no next sibling\n    // 3. None of its ancestors have next siblings\n\n    if (activity.children.length > 0) {\n      return false; // Not a leaf\n    }\n\n    let current: Activity | null = activity;\n    while (current) {\n      if (this.activityTree.getNextSibling(current)) {\n        return false; // Has a next sibling somewhere in the ancestor chain\n      }\n      current = current.parent;\n    }\n\n    return true; // No next siblings anywhere - this is the last activity\n  }\n\n  /**\n   * Find the currently active activity within a parent's children\n   * @param {Activity} parent - The parent activity\n   * @return {Activity | null} - The active child or null\n   */\n  public getCurrentInParent(parent: Activity): Activity | null {\n    if (parent.children) {\n      for (const child of parent.children) {\n        if (child.isActive) {\n          return child;\n        }\n      }\n    }\n    return null;\n  }\n\n  /**\n   * Check if activity is mandatory (cannot be skipped)\n   * In SCORM 2004, this is typically determined by sequencing rules\n   * @param {Activity} activity - Activity to check\n   * @return {boolean} - True if activity is mandatory\n   */\n  public isMandatory(activity: Activity): boolean {\n    // Check if activity has an unconditional skip rule (not mandatory)\n    if (activity.sequencingRules && activity.sequencingRules.preConditionRules) {\n      for (const rule of activity.sequencingRules.preConditionRules) {\n        if (rule.action === \"skip\" && rule.conditions && rule.conditions.length === 0) {\n          return false; // Has unconditional skip rule, not mandatory\n        }\n      }\n    }\n\n    // Check for explicit mandatory flag. Default to false (not mandatory) unless explicitly set\n    // Activities are only mandatory if explicitly marked as such\n    return (activity as any).mandatory === true;\n  }\n\n  /**\n   * Check if activity is completed\n   * @param {Activity} activity - Activity to check\n   * @return {boolean} - True if activity is completed\n   */\n  public isCompleted(activity: Activity): boolean {\n    return (\n      activity.completionStatus === \"completed\" ||\n      activity.completionStatus === \"passed\" ||\n      activity.successStatus === \"passed\"\n    );\n  }\n\n  /**\n   * Check if activity is available for choice according to SCORM 2004 rules\n   * @param {Activity} activity - Activity to check\n   * @return {boolean} - True if activity is available for choice\n   */\n  public isAvailableForChoice(activity: Activity): boolean {\n    return (\n      activity.isVisible &&\n      !activity.isHiddenFromChoice &&\n      activity.isAvailable &&\n      (activity.sequencingControls ? activity.sequencingControls.choice : true)\n    );\n  }\n\n  /**\n   * Get all ancestors of an activity from child to root\n   * @param {Activity} activity - The activity to get ancestors for\n   * @return {Activity[]} - Array of ancestors from immediate parent to root\n   */\n  public getAncestors(activity: Activity): Activity[] {\n    const ancestors: Activity[] = [];\n    let current = activity.parent;\n    while (current) {\n      ancestors.push(current);\n      current = current.parent;\n    }\n    return ancestors;\n  }\n\n  /**\n   * Get the path from an activity to the root\n   * @param {Activity} activity - The activity\n   * @return {Activity[]} - Array from the activity to root (inclusive)\n   */\n  public getPathToRoot(activity: Activity): Activity[] {\n    const path: Activity[] = [activity];\n    let current = activity.parent;\n    while (current) {\n      path.push(current);\n      current = current.parent;\n    }\n    return path;\n  }\n\n  /**\n   * Check if an activity is a leaf (has no children)\n   * @param {Activity} activity - Activity to check\n   * @return {boolean} - True if activity is a leaf\n   */\n  public isLeaf(activity: Activity): boolean {\n    return activity.children.length === 0;\n  }\n\n  /**\n   * Check if an activity is a cluster (has children)\n   * @param {Activity} activity - Activity to check\n   * @return {boolean} - True if activity is a cluster\n   */\n  public isCluster(activity: Activity): boolean {\n    return activity.children.length > 0;\n  }\n\n  /**\n   * Get the depth of an activity in the tree (root = 0)\n   * @param {Activity} activity - Activity to get depth for\n   * @return {number} - Depth in tree\n   */\n  public getDepth(activity: Activity): number {\n    let depth = 0;\n    let current = activity.parent;\n    while (current) {\n      depth++;\n      current = current.parent;\n    }\n    return depth;\n  }\n}\n","import { Activity } from \"../activity\";\nimport { ActivityTree } from \"../activity_tree\";\nimport { ActivityTreeQueries } from \"../utils/activity_tree_queries\";\n\n/**\n * Result of constraint validation\n */\nexport interface ConstraintValidationResult {\n  valid: boolean;\n  exception: string | null;\n}\n\n/**\n * Options for choice validation\n */\nexport interface ChoiceValidationOptions {\n  checkAvailability?: boolean;\n}\n\n/**\n * ChoiceConstraintValidator - Consolidates ALL choice constraint validation logic\n *\n * This class extracts and unifies the constraint validation logic that was previously\n * duplicated in 5+ places within SequencingProcess. It provides a single source of truth\n * for validating choice navigation requests.\n *\n * Key validations performed:\n * - Path to root validation (hidden from choice, choice control)\n * - choiceExit constraint checking at all ancestor levels\n * - forwardOnly constraint validation\n * - constrainChoice boundary validation\n * - preventActivation constraint checking\n * - Mandatory activity skipping detection\n */\nexport class ChoiceConstraintValidator {\n  constructor(\n    private activityTree: ActivityTree,\n    private treeQueries: ActivityTreeQueries\n  ) {}\n\n  /**\n   * Main entry point - consolidates ALL constraint validation for choice navigation\n   * @param {Activity | null} currentActivity - Current activity (may be null if no session started)\n   * @param {Activity} targetActivity - Target activity for the choice\n   * @param {ChoiceValidationOptions} options - Validation options\n   * @return {ConstraintValidationResult} - Validation result with exception if invalid\n   */\n  public validateChoice(\n    currentActivity: Activity | null,\n    targetActivity: Activity,\n    options: ChoiceValidationOptions = {}\n  ): ConstraintValidationResult {\n    // Step 1: Basic tree membership check\n    if (!this.treeQueries.isInTree(targetActivity)) {\n      return { valid: false, exception: \"SB.2.9-2\" };\n    }\n\n    // Step 2: Path to root validation - check hidden from choice and choice control.\n    // The root is a valid Choice target; SB.2.9 flows from a chosen cluster to\n    // its first deliverable descendant.\n    const pathValidation = this.validatePathToRoot(targetActivity);\n    if (!pathValidation.valid) {\n      return pathValidation;\n    }\n\n    // Step 3: Check availability if requested\n    if (options.checkAvailability && !targetActivity.isAvailable) {\n      return { valid: false, exception: \"SB.2.9-7\" };\n    }\n\n    // Step 4: If no current activity, basic validation is sufficient\n    if (!currentActivity) {\n      return { valid: true, exception: null };\n    }\n\n    // Step 5: Check choiceExit constraints at all ancestor levels\n    const choiceExitValidation = this.validateChoiceExit(currentActivity, targetActivity);\n    if (!choiceExitValidation.valid) {\n      return choiceExitValidation;\n    }\n\n    // Step 6: Validate constraints at all ancestor levels\n    const ancestorValidation = this.validateAncestorConstraints(\n      currentActivity,\n      targetActivity\n    );\n    if (!ancestorValidation.valid) {\n      return ancestorValidation;\n    }\n\n    return { valid: true, exception: null };\n  }\n\n  /**\n   * Validate path to root - check hidden from choice and choice control\n   * @param {Activity} targetActivity - Target activity\n   * @return {ConstraintValidationResult} - Validation result\n   */\n  public validatePathToRoot(targetActivity: Activity): ConstraintValidationResult {\n    // @spec SCORM 2004 SN 4th Ed. SB.2.9: the target's immediate parent\n    // controls choice among that parent's children.\n    if (\n      targetActivity.parent &&\n      !targetActivity.parent.sequencingControls.choice\n    ) {\n      return { valid: false, exception: \"SB.2.9-5\" };\n    }\n\n    let activity: Activity | null = targetActivity;\n    while (activity) {\n      // Check if activity is hidden from choice\n      if (activity.isHiddenFromChoice) {\n        return { valid: false, exception: \"SB.2.9-4\" };\n      }\n\n      // Check preventActivation constraint at parent level\n      // This applies even when there's no current activity\n      if (activity.parent && activity.parent.sequencingControls.preventActivation) {\n        // Target must have been previously attempted\n        if (targetActivity.attemptCount === 0 && !targetActivity.isActive) {\n          return { valid: false, exception: \"SB.2.9-6\" };\n        }\n      }\n\n      activity = activity.parent;\n    }\n\n    return { valid: true, exception: null };\n  }\n\n  /**\n   * Validate choiceExit constraint at all ancestor levels\n   * Per SCORM spec: choiceExit only applies when we're actively IN that ancestor's subtree\n   * @param {Activity} currentActivity - Current activity\n   * @param {Activity} targetActivity - Target activity\n   * @return {ConstraintValidationResult} - Validation result\n   */\n  public validateChoiceExit(\n    currentActivity: Activity,\n    targetActivity: Activity\n  ): ConstraintValidationResult {\n    // Walk from current activity to root, checking for choiceExit=false\n    let currentAncestor: Activity | null = currentActivity.parent;\n\n    while (currentAncestor) {\n      // choiceExit only applies when the ancestor is ACTIVE\n      if (currentAncestor.isActive && !currentAncestor.sequencingControls.choiceExit) {\n        // choiceExit is false at this active ancestor\n        // Check if target is a descendant of this ancestor\n        if (!this.treeQueries.isAncestorOf(currentAncestor, targetActivity)) {\n          return { valid: false, exception: \"SB.2.9-8\" };\n        }\n        // If target is within this subtree, we can stop checking higher levels\n        break;\n      }\n      currentAncestor = currentAncestor.parent;\n    }\n\n    return { valid: true, exception: null };\n  }\n\n  /**\n   * Validate constraints at all ancestor levels\n   * Checks forwardOnly, constrainChoice, preventActivation\n   * @param {Activity} currentActivity - Current activity\n   * @param {Activity} targetActivity - Target activity\n   * @return {ConstraintValidationResult} - Validation result\n   */\n  public validateAncestorConstraints(\n    currentActivity: Activity,\n    targetActivity: Activity\n  ): ConstraintValidationResult {\n    let ancestorActivity: Activity | null = targetActivity.parent;\n\n    while (ancestorActivity) {\n      const validation = this.validateConstraintsAtLevel(\n        ancestorActivity,\n        currentActivity,\n        targetActivity\n      );\n      if (!validation.valid) {\n        return validation;\n      }\n      ancestorActivity = ancestorActivity.parent;\n    }\n\n    return { valid: true, exception: null };\n  }\n\n  /**\n   * Validate constraints at a specific ancestor level\n   * @param {Activity} ancestor - The ancestor to check\n   * @param {Activity} currentActivity - Current activity\n   * @param {Activity} targetActivity - Target activity\n   * @return {ConstraintValidationResult} - Validation result\n   */\n  private validateConstraintsAtLevel(\n    ancestor: Activity,\n    currentActivity: Activity,\n    targetActivity: Activity\n  ): ConstraintValidationResult {\n    // Find which children of this ancestor contain current and target\n    const targetChild = this.treeQueries.findChildInPath(ancestor, targetActivity);\n    const currentChild = this.treeQueries.findChildInPath(ancestor, currentActivity);\n\n    // Only validate if both current and target are descendants of this ancestor\n    if (!targetChild || !currentChild) {\n      return { valid: true, exception: null };\n    }\n\n    const siblings = ancestor.children;\n    const targetIndex = siblings.indexOf(targetChild);\n    const currentIndex = siblings.indexOf(currentChild);\n\n    if (targetIndex === -1 || currentIndex === -1) {\n      return { valid: true, exception: null };\n    }\n\n    // Priority 1: Check forwardOnly constraint (highest priority)\n    // Per SCORM spec, forwardOnly blocks ALL backward navigation\n    if (ancestor.sequencingControls.forwardOnly && targetIndex < currentIndex) {\n      return { valid: false, exception: \"SB.2.9-5\" };\n    }\n\n    // Priority 2: Check mandatory activities being skipped (forward direction)\n    if (targetIndex > currentIndex) {\n      for (let i = currentIndex + 1; i < targetIndex; i++) {\n        const intermediateChild = siblings[i];\n        if (\n          intermediateChild &&\n          this.treeQueries.isMandatory(intermediateChild) &&\n          !this.treeQueries.isCompleted(intermediateChild)\n        ) {\n          return { valid: false, exception: \"SB.2.9-6\" };\n        }\n      }\n    }\n\n    // Priority 3: Check constrainChoice constraint\n    if (ancestor.sequencingControls.constrainChoice) {\n      // Cannot skip forward beyond next sibling\n      if (targetIndex > currentIndex + 1) {\n        return { valid: false, exception: \"SB.2.9-7\" };\n      }\n\n      // Cannot go backward to incomplete activity\n      if (targetIndex < currentIndex) {\n        if (\n          targetActivity.completionStatus !== \"completed\" &&\n          (targetActivity.completionStatus as string) !== \"passed\"\n        ) {\n          return { valid: false, exception: \"SB.2.9-7\" };\n        }\n      }\n    }\n\n    // Check preventActivation constraint\n    if (ancestor.sequencingControls.preventActivation) {\n      if (targetActivity.attemptCount === 0 && !targetActivity.isActive) {\n        return { valid: false, exception: \"SB.2.9-6\" };\n      }\n    }\n\n    return { valid: true, exception: null };\n  }\n\n  /**\n   * Check forwardOnly violation at ALL ancestor levels\n   * This is critical for Previous request validation\n   * @param {Activity} fromActivity - The activity to check from\n   * @return {ConstraintValidationResult} - Violation info or valid result\n   */\n  public checkForwardOnlyViolation(fromActivity: Activity): ConstraintValidationResult {\n    // Walk up the ancestor chain checking forwardOnly at each level\n    let current: Activity | null = fromActivity.parent;\n\n    while (current) {\n      if (current.sequencingControls.forwardOnly) {\n        return { valid: false, exception: \"SB.2.9-5\" };\n      }\n      current = current.parent;\n    }\n\n    return { valid: true, exception: null };\n  }\n\n  /**\n   * Validate activity is available for choice navigation\n   * @param {Activity} activity - Activity to check\n   * @return {boolean} - True if available for choice\n   */\n  public isAvailableForChoice(activity: Activity): boolean {\n    return this.treeQueries.isAvailableForChoice(activity);\n  }\n\n  /**\n   * Validate choice flow constraints for flow tree traversal\n   * @param {Activity} fromActivity - Activity to traverse from\n   * @param {Activity[]} children - Available children\n   * @return {{ valid: boolean; validChildren: Activity[] }} - Valid children that meet constraints\n   */\n  public validateFlowConstraints(\n    fromActivity: Activity,\n    children: Activity[]\n  ): { valid: boolean; validChildren: Activity[] } {\n    const validChildren: Activity[] = [];\n\n    for (const child of children) {\n      if (this.meetsFlowConstraints(child, fromActivity)) {\n        validChildren.push(child);\n      }\n    }\n\n    return {\n      valid: validChildren.length > 0,\n      validChildren\n    };\n  }\n\n  /**\n   * Check if activity meets flow constraints\n   * @param {Activity} activity - Activity to check\n   * @param {Activity} parent - Parent activity\n   * @return {boolean} - True if constraints are met\n   */\n  public meetsFlowConstraints(activity: Activity, parent: Activity): boolean {\n    // Check basic availability\n    if (!activity.isAvailable || activity.isHiddenFromChoice) {\n      return false;\n    }\n\n    // Check parent constraint controls\n    if (parent.sequencingControls.constrainChoice) {\n      return this.validateConstrainChoiceForFlow(activity, parent);\n    }\n\n    return true;\n  }\n\n  /**\n   * Validate constrainChoice for flow scenarios\n   * @param {Activity} activity - Activity to validate\n   * @param {Activity} parent - Parent activity\n   * @return {boolean} - True if valid\n   */\n  private validateConstrainChoiceForFlow(activity: Activity, parent: Activity): boolean {\n    // If constrainChoice is false, no restrictions apply\n    if (!parent.sequencingControls || !parent.sequencingControls.constrainChoice) {\n      return true;\n    }\n\n    const children = parent.children;\n    if (!children || children.length === 0) {\n      return true;\n    }\n\n    const targetIndex = children.indexOf(activity);\n    if (targetIndex === -1) {\n      return false;\n    }\n\n    // Get the current activity within this parent's children\n    const currentActivity = this.treeQueries.getCurrentInParent(parent);\n    if (!currentActivity) {\n      // No current activity in this cluster, allow choice to first available\n      return this.isAvailableForChoice(activity);\n    }\n\n    const currentIndex = children.indexOf(currentActivity);\n    if (currentIndex === -1) {\n      return true;\n    }\n\n    // Check flow direction constraints\n    if (parent.sequencingControls.flow) {\n      // forwardOnly check\n      if (parent.sequencingControls.forwardOnly && targetIndex < currentIndex) {\n        // Allow if previously completed\n        if (activity.completionStatus === \"completed\" ||\n            (activity.completionStatus as string) === \"passed\") {\n          return true;\n        }\n        return false;\n      }\n\n      // Forward direction - can only choose immediate next sibling or current\n      if (targetIndex >= currentIndex) {\n        if (targetIndex === currentIndex || targetIndex === currentIndex + 1) {\n          return this.isAvailableForChoice(activity);\n        }\n        return false;\n      }\n\n      // Backward direction (forwardOnly is false)\n      if (targetIndex < currentIndex) {\n        return (\n          (activity.completionStatus === \"completed\" ||\n           (activity.completionStatus as string) === \"passed\") &&\n          this.isAvailableForChoice(activity)\n        );\n      }\n\n      return false;\n    } else {\n      // Non-flow mode with constrainChoice\n      return (\n        this.isAvailableForChoice(activity) &&\n        (activity.completionStatus === \"completed\" ||\n         activity.completionStatus === \"unknown\" ||\n         activity.completionStatus === \"incomplete\")\n      );\n    }\n  }\n\n  /**\n   * Validate traversal constraints for choice navigation\n   * @param {Activity} activity - Activity to validate\n   * @return {{ canTraverse: boolean; canTraverseInto: boolean }} - Traversal permissions\n   */\n  public validateTraversalConstraints(activity: Activity): {\n    canTraverse: boolean;\n    canTraverseInto: boolean;\n  } {\n    let canTraverse = true;\n    let canTraverseInto = true;\n\n    // Check constrainChoice control\n    if (activity.parent?.sequencingControls.constrainChoice) {\n      canTraverse = this.evaluateConstrainChoiceForTraversal(activity);\n    }\n\n    // Check stopForwardTraversal control\n    if (activity.sequencingControls && activity.sequencingControls.stopForwardTraversal) {\n      canTraverseInto = false;\n    }\n\n    // Check forwardOnly control in parent context\n    if (activity.parent?.sequencingControls.forwardOnly) {\n      canTraverseInto = this.evaluateForwardOnlyForChoice(activity);\n    }\n\n    return { canTraverse, canTraverseInto };\n  }\n\n  /**\n   * Evaluate constrainChoice for traversal\n   * @param {Activity} activity - Activity to evaluate\n   * @return {boolean} - True if traversal is allowed\n   */\n  private evaluateConstrainChoiceForTraversal(activity: Activity): boolean {\n    if (!activity.parent) {\n      return true;\n    }\n\n    // Check constraint at ALL ancestor levels\n    let currentAncestor: Activity | null = activity.parent;\n    while (currentAncestor) {\n      if (\n        currentAncestor.sequencingControls &&\n        currentAncestor.sequencingControls.constrainChoice\n      ) {\n        const ancestorChildren = currentAncestor.children;\n        const childInPath = this.treeQueries.findChildInPath(currentAncestor, activity);\n\n        if (childInPath) {\n          const childIndex = ancestorChildren.indexOf(childInPath);\n          const currentAtLevel = this.treeQueries.getCurrentInParent(currentAncestor);\n\n          if (currentAtLevel) {\n            const currentIndex = ancestorChildren.indexOf(currentAtLevel);\n\n            if (currentIndex !== -1 && childIndex !== -1) {\n              // Check mandatory intermediate activities\n              if (currentIndex < childIndex) {\n                for (let i = currentIndex + 1; i < childIndex; i++) {\n                  const intermediateActivity = ancestorChildren[i];\n                  if (\n                    intermediateActivity &&\n                    this.treeQueries.isMandatory(intermediateActivity) &&\n                    !this.treeQueries.isCompleted(intermediateActivity)\n                  ) {\n                    return false;\n                  }\n                }\n              }\n\n              // Check forwardOnly constraint\n              if (currentAncestor.sequencingControls.forwardOnly && childIndex < currentIndex) {\n                if (!this.treeQueries.isCompleted(activity)) {\n                  return false;\n                }\n              }\n            }\n          }\n        }\n      }\n      currentAncestor = currentAncestor.parent;\n    }\n\n    return this.isAvailableForChoice(activity);\n  }\n\n  /**\n   * Evaluate forwardOnly for choice scenarios\n   * @param {Activity} activity - Activity to evaluate\n   * @return {boolean} - True if allowed\n   */\n  private evaluateForwardOnlyForChoice(activity: Activity): boolean {\n    if (!activity.parent) {\n      return true;\n    }\n\n    const parent = activity.parent;\n    if (!parent.sequencingControls || !parent.sequencingControls.forwardOnly) {\n      return true;\n    }\n\n    const siblings = parent.children;\n    if (!siblings || siblings.length === 0) {\n      return true;\n    }\n\n    const targetIndex = siblings.indexOf(activity);\n    if (targetIndex === -1) {\n      return false;\n    }\n\n    const currentActivity = this.treeQueries.getCurrentInParent(parent);\n    if (!currentActivity) {\n      return this.isAvailableForChoice(activity);\n    }\n\n    const currentIndex = siblings.indexOf(currentActivity);\n    if (currentIndex === -1) {\n      return true;\n    }\n\n    // ForwardOnly: only allow activities at or after current position\n    if (targetIndex < currentIndex) {\n      // Allow if completed and choice-enabled\n      if (activity.completionStatus === \"completed\" ||\n          (activity.completionStatus as string) === \"passed\") {\n        if (activity.sequencingControls && activity.sequencingControls.choice) {\n          return true;\n        }\n      }\n      return false;\n    }\n\n    return this.isAvailableForChoice(activity);\n  }\n\n  /**\n   * Check for time-based constraint boundary violations\n   * @param {Activity} targetActivity - Target activity\n   * @param {Date} now - Current time\n   * @return {boolean} - True if there is a boundary violation\n   */\n  public hasTimeBoundaryViolation(targetActivity: Activity, now: Date): boolean {\n    // Check begin time limit\n    if (targetActivity.beginTimeLimit) {\n      try {\n        const beginTime = new Date(targetActivity.beginTimeLimit);\n        if (now < beginTime) {\n          return true; // Not yet available\n        }\n      } catch {\n        // Invalid date format, no violation\n      }\n    }\n\n    // Check end time limit\n    if (targetActivity.endTimeLimit) {\n      try {\n        const endTime = new Date(targetActivity.endTimeLimit);\n        if (now > endTime) {\n          return true; // No longer available\n        }\n      } catch {\n        // Invalid date format, no violation\n      }\n    }\n\n    return false;\n  }\n\n  /**\n   * Check for attempt limit violations\n   * @param {Activity} targetActivity - Target activity\n   * @return {boolean} - True if attempt limit exceeded\n   */\n  public hasAttemptLimitViolation(targetActivity: Activity): boolean {\n    return !!(\n      targetActivity.attemptLimit &&\n      targetActivity.attemptCount >= targetActivity.attemptLimit\n    );\n  }\n}\n","import { BaseCMI } from \"../../common/base_cmi\";\n\n/**\n * Enum for selection timing\n */\nexport enum SelectionTiming {\n  NEVER = \"never\",\n  ONCE = \"once\",\n  ON_EACH_NEW_ATTEMPT = \"onEachNewAttempt\",\n}\n\n/**\n * Enum for randomization timing\n */\nexport enum RandomizationTiming {\n  NEVER = \"never\",\n  ONCE = \"once\",\n  ON_EACH_NEW_ATTEMPT = \"onEachNewAttempt\",\n}\n\n/**\n * Class representing SCORM 2004 sequencing controls\n */\nexport class SequencingControls extends BaseCMI {\n  // Sequencing Control Modes\n  private _enabled: boolean = true;\n  private _choice: boolean = true;\n  private _choiceExit: boolean = true;\n  // Per SCORM 2004 Sequencing & Navigation, flow defaults to true\n  private _flow: boolean = true;\n  private _forwardOnly: boolean = false;\n  private _useCurrentAttemptObjectiveInfo: boolean = true;\n  private _useCurrentAttemptProgressInfo: boolean = true;\n\n  // Constrain Choice Controls\n  private _preventActivation: boolean = false;\n  private _constrainChoice: boolean = false;\n  // Rule-driven traversal limiter (e.g., post-condition stopForwardTraversal)\n  private _stopForwardTraversal: boolean = false;\n\n  // Rollup Controls\n  private _rollupObjectiveSatisfied: boolean = true;\n  private _rollupProgressCompletion: boolean = true;\n  private _objectiveMeasureWeight: number = 1.0;\n\n  // Selection Controls\n  private _selectionTiming: SelectionTiming = SelectionTiming.NEVER;\n  private _selectCount: number | null = null;\n  private _selectionCountStatus: boolean = false;\n  private _randomizeChildren: boolean = false;\n\n  // Randomization Controls\n  private _randomizationTiming: RandomizationTiming = RandomizationTiming.NEVER;\n  private _reorderChildren: boolean = false;\n\n  // Auto-completion/satisfaction controls\n  private _completionSetByContent: boolean = false;\n  private _objectiveSetByContent: boolean = false;\n\n  // Delivery Controls\n  private _tracked: boolean = true;\n\n  /**\n   * Constructor for SequencingControls\n   */\n  constructor() {\n    super(\"sequencingControls\");\n  }\n\n  /**\n   * Reset the sequencing controls to their default values\n   */\n  reset() {\n    this._initialized = false;\n    this._enabled = true;\n    this._choice = true;\n    this._choiceExit = true;\n    this._flow = true;\n    this._forwardOnly = false;\n    this._useCurrentAttemptObjectiveInfo = true;\n    this._useCurrentAttemptProgressInfo = true;\n    this._preventActivation = false;\n    this._constrainChoice = false;\n    this._stopForwardTraversal = false;\n    this._rollupObjectiveSatisfied = true;\n    this._rollupProgressCompletion = true;\n    this._objectiveMeasureWeight = 1.0;\n    this._selectionTiming = SelectionTiming.NEVER;\n    this._selectCount = null;\n    this._selectionCountStatus = false;\n    this._randomizeChildren = false;\n    this._randomizationTiming = RandomizationTiming.NEVER;\n    this._reorderChildren = false;\n    this._completionSetByContent = false;\n    this._objectiveSetByContent = false;\n    this._tracked = true;\n  }\n\n  /**\n   * Getter for enabled\n   * @return {boolean}\n   */\n  get enabled(): boolean {\n    return this._enabled;\n  }\n\n  /**\n   * Setter for enabled\n   * @param {boolean} enabled\n   */\n  set enabled(enabled: boolean) {\n    this._enabled = enabled;\n  }\n\n  /**\n   * Getter for choice\n   * @return {boolean}\n   */\n  get choice(): boolean {\n    return this._choice;\n  }\n\n  /**\n   * Setter for choice\n   * @param {boolean} choice\n   */\n  set choice(choice: boolean) {\n    this._choice = choice;\n  }\n\n  /**\n   * Getter for choiceExit\n   * @return {boolean}\n   */\n  get choiceExit(): boolean {\n    return this._choiceExit;\n  }\n\n  /**\n   * Setter for choiceExit\n   * @param {boolean} choiceExit\n   */\n  set choiceExit(choiceExit: boolean) {\n    this._choiceExit = choiceExit;\n  }\n\n  /**\n   * Getter for flow\n   * @return {boolean}\n   */\n  get flow(): boolean {\n    return this._flow;\n  }\n\n  /**\n   * Setter for flow\n   * @param {boolean} flow\n   */\n  set flow(flow: boolean) {\n    this._flow = flow;\n  }\n\n  /**\n   * Getter for forwardOnly\n   * @return {boolean}\n   */\n  get forwardOnly(): boolean {\n    return this._forwardOnly;\n  }\n\n  /**\n   * Setter for forwardOnly\n   * @param {boolean} forwardOnly\n   */\n  set forwardOnly(forwardOnly: boolean) {\n    this._forwardOnly = forwardOnly;\n  }\n\n  /**\n   * Getter for useCurrentAttemptObjectiveInfo\n   * @return {boolean}\n   */\n  get useCurrentAttemptObjectiveInfo(): boolean {\n    return this._useCurrentAttemptObjectiveInfo;\n  }\n\n  /**\n   * Setter for useCurrentAttemptObjectiveInfo\n   * @param {boolean} useCurrentAttemptObjectiveInfo\n   */\n  set useCurrentAttemptObjectiveInfo(useCurrentAttemptObjectiveInfo: boolean) {\n    this._useCurrentAttemptObjectiveInfo = useCurrentAttemptObjectiveInfo;\n  }\n\n  /**\n   * Getter for useCurrentAttemptProgressInfo\n   * @return {boolean}\n   */\n  get useCurrentAttemptProgressInfo(): boolean {\n    return this._useCurrentAttemptProgressInfo;\n  }\n\n  /**\n   * Setter for useCurrentAttemptProgressInfo\n   * @param {boolean} useCurrentAttemptProgressInfo\n   */\n  set useCurrentAttemptProgressInfo(useCurrentAttemptProgressInfo: boolean) {\n    this._useCurrentAttemptProgressInfo = useCurrentAttemptProgressInfo;\n  }\n\n  /**\n   * Getter for preventActivation\n   * @return {boolean}\n   */\n  get preventActivation(): boolean {\n    return this._preventActivation;\n  }\n\n  /**\n   * Setter for preventActivation\n   * @param {boolean} preventActivation\n   */\n  set preventActivation(preventActivation: boolean) {\n    this._preventActivation = preventActivation;\n  }\n\n  /**\n   * Getter for constrainChoice\n   * @return {boolean}\n   */\n  get constrainChoice(): boolean {\n    return this._constrainChoice;\n  }\n\n  /**\n   * Setter for constrainChoice\n   * @param {boolean} constrainChoice\n   */\n  set constrainChoice(constrainChoice: boolean) {\n    this._constrainChoice = constrainChoice;\n  }\n\n  /**\n   * Getter for stopForwardTraversal\n   * @return {boolean}\n   */\n  get stopForwardTraversal(): boolean {\n    return this._stopForwardTraversal;\n  }\n\n  /**\n   * Setter for stopForwardTraversal\n   * @param {boolean} stopForwardTraversal\n   */\n  set stopForwardTraversal(stopForwardTraversal: boolean) {\n    this._stopForwardTraversal = stopForwardTraversal;\n  }\n\n  /**\n   * Getter for rollupObjectiveSatisfied\n   * @return {boolean}\n   */\n  get rollupObjectiveSatisfied(): boolean {\n    return this._rollupObjectiveSatisfied;\n  }\n\n  /**\n   * Setter for rollupObjectiveSatisfied\n   * @param {boolean} rollupObjectiveSatisfied\n   */\n  set rollupObjectiveSatisfied(rollupObjectiveSatisfied: boolean) {\n    this._rollupObjectiveSatisfied = rollupObjectiveSatisfied;\n  }\n\n  /**\n   * Getter for rollupProgressCompletion\n   * @return {boolean}\n   */\n  get rollupProgressCompletion(): boolean {\n    return this._rollupProgressCompletion;\n  }\n\n  /**\n   * Setter for rollupProgressCompletion\n   * @param {boolean} rollupProgressCompletion\n   */\n  set rollupProgressCompletion(rollupProgressCompletion: boolean) {\n    this._rollupProgressCompletion = rollupProgressCompletion;\n  }\n\n  /**\n   * Getter for objectiveMeasureWeight\n   * @return {number}\n   */\n  get objectiveMeasureWeight(): number {\n    return this._objectiveMeasureWeight;\n  }\n\n  /**\n   * Setter for objectiveMeasureWeight\n   * @param {number} objectiveMeasureWeight\n   */\n  set objectiveMeasureWeight(objectiveMeasureWeight: number) {\n    // According to SCORM 2004, weight must be >= 0 but there's no upper limit\n    if (objectiveMeasureWeight >= 0) {\n      this._objectiveMeasureWeight = objectiveMeasureWeight;\n    }\n  }\n\n  /**\n   * Check if choice navigation is allowed\n   * @return {boolean} - True if choice navigation is allowed, false otherwise\n   */\n  isChoiceNavigationAllowed(): boolean {\n    return this._enabled && !this._constrainChoice;\n  }\n\n  /**\n   * Check if flow navigation is allowed\n   * @return {boolean} - True if flow navigation is allowed, false otherwise\n   */\n  isFlowNavigationAllowed(): boolean {\n    return this._enabled && this._flow;\n  }\n\n  /**\n   * Check if forward navigation is allowed\n   * @return {boolean} - True if forward navigation is allowed, false otherwise\n   */\n  isForwardNavigationAllowed(): boolean {\n    // Forward navigation (Continue request) is only valid when flow mode is\n    // enabled. The forwardOnly flag simply restricts backward navigation and\n    // does not affect the ability to move forward when flow is disabled.\n    return this._enabled && this._flow;\n  }\n\n  /**\n   * Check if backward navigation is allowed\n   * @return {boolean} - True if backward navigation is allowed, false otherwise\n   */\n  isBackwardNavigationAllowed(): boolean {\n    // Previous navigation is also part of flow based navigation and should only\n    // be permitted when flow mode is enabled and forwardOnly does not restrict\n    // going backwards.\n    return this._enabled && this._flow && !this._forwardOnly;\n  }\n\n  /**\n   * Getter for selectionTiming\n   * @return {SelectionTiming}\n   */\n  get selectionTiming(): SelectionTiming {\n    return this._selectionTiming;\n  }\n\n  /**\n   * Setter for selectionTiming\n   * @param {SelectionTiming} selectionTiming\n   */\n  set selectionTiming(selectionTiming: SelectionTiming) {\n    this._selectionTiming = selectionTiming;\n  }\n\n  /**\n   * Getter for selectCount\n   * @return {number | null}\n   */\n  get selectCount(): number | null {\n    return this._selectCount;\n  }\n\n  /**\n   * Setter for selectCount\n   * @param {number | null} selectCount\n   */\n  set selectCount(selectCount: number | null) {\n    if (selectCount === null || selectCount > 0) {\n      this._selectCount = selectCount;\n    }\n  }\n\n  /**\n   * Getter for selectionCountStatus\n   * @return {boolean}\n   */\n  get selectionCountStatus(): boolean {\n    return this._selectionCountStatus;\n  }\n\n  /**\n   * Setter for selectionCountStatus\n   * @param {boolean} selectionCountStatus\n   */\n  set selectionCountStatus(selectionCountStatus: boolean) {\n    this._selectionCountStatus = selectionCountStatus;\n  }\n\n  /**\n   * Getter for randomizeChildren\n   * @return {boolean}\n   */\n  get randomizeChildren(): boolean {\n    return this._randomizeChildren;\n  }\n\n  /**\n   * Setter for randomizeChildren\n   * @param {boolean} randomizeChildren\n   */\n  set randomizeChildren(randomizeChildren: boolean) {\n    this._randomizeChildren = randomizeChildren;\n  }\n\n  /**\n   * Getter for randomizationTiming\n   * @return {RandomizationTiming}\n   */\n  get randomizationTiming(): RandomizationTiming {\n    return this._randomizationTiming;\n  }\n\n  /**\n   * Setter for randomizationTiming\n   * @param {RandomizationTiming} randomizationTiming\n   */\n  set randomizationTiming(randomizationTiming: RandomizationTiming) {\n    this._randomizationTiming = randomizationTiming;\n  }\n\n  /**\n   * Getter for reorderChildren\n   * @return {boolean}\n   */\n  get reorderChildren(): boolean {\n    return this._reorderChildren;\n  }\n\n  /**\n   * Setter for reorderChildren\n   * @param {boolean} reorderChildren\n   */\n  set reorderChildren(reorderChildren: boolean) {\n    this._reorderChildren = reorderChildren;\n  }\n\n  /**\n   * Getter for completionSetByContent\n   * @return {boolean}\n   */\n  get completionSetByContent(): boolean {\n    return this._completionSetByContent;\n  }\n\n  /**\n   * Setter for completionSetByContent\n   * @param {boolean} completionSetByContent\n   */\n  set completionSetByContent(completionSetByContent: boolean) {\n    this._completionSetByContent = completionSetByContent;\n  }\n\n  /**\n   * Getter for objectiveSetByContent\n   * @return {boolean}\n   */\n  get objectiveSetByContent(): boolean {\n    return this._objectiveSetByContent;\n  }\n\n  /**\n   * Setter for objectiveSetByContent\n   * @param {boolean} objectiveSetByContent\n   */\n  set objectiveSetByContent(objectiveSetByContent: boolean) {\n    this._objectiveSetByContent = objectiveSetByContent;\n  }\n\n  /**\n   * Getter for tracked\n   * @return {boolean}\n   */\n  get tracked(): boolean {\n    return this._tracked;\n  }\n\n  /**\n   * Setter for tracked\n   * @param {boolean} tracked\n   */\n  set tracked(tracked: boolean) {\n    this._tracked = tracked;\n  }\n\n  /**\n   * toJSON for SequencingControls\n   * @return {object}\n   */\n  toJSON(): object {\n    this.jsonString = true;\n    const result = {\n      enabled: this._enabled,\n      choice: this._choice,\n      choiceExit: this._choiceExit,\n      flow: this._flow,\n      forwardOnly: this._forwardOnly,\n      useCurrentAttemptObjectiveInfo: this._useCurrentAttemptObjectiveInfo,\n      useCurrentAttemptProgressInfo: this._useCurrentAttemptProgressInfo,\n      preventActivation: this._preventActivation,\n      constrainChoice: this._constrainChoice,\n      stopForwardTraversal: this._stopForwardTraversal,\n      rollupObjectiveSatisfied: this._rollupObjectiveSatisfied,\n      rollupProgressCompletion: this._rollupProgressCompletion,\n      objectiveMeasureWeight: this._objectiveMeasureWeight,\n      selectionTiming: this._selectionTiming,\n      selectCount: this._selectCount,\n      selectionCountStatus: this._selectionCountStatus,\n      randomizeChildren: this._randomizeChildren,\n      randomizationTiming: this._randomizationTiming,\n      reorderChildren: this._reorderChildren,\n      completionSetByContent: this._completionSetByContent,\n      objectiveSetByContent: this._objectiveSetByContent,\n      tracked: this._tracked,\n    };\n    this.jsonString = false;\n    return result;\n  }\n}\n","import { Activity } from \"./activity\";\nimport { SelectionTiming, RandomizationTiming } from \"./sequencing_controls\";\n\n/**\n * Class implementing SCORM 2004 Selection and Randomization processes (SR.1 and SR.2)\n */\nexport class SelectionRandomization {\n  /**\n   * Select Children Process (SR.1)\n   * Selects a subset of child activities based on selection controls\n   * @param {Activity} activity - The parent activity whose children need to be selected\n   * @return {Activity[]} - The selected child activities\n   */\n  public static selectChildrenProcess(activity: Activity): Activity[] {\n    const controls = activity.sequencingControls;\n    const children = [...activity.children]; // Create a copy to avoid mutating original\n\n    // Check if selection should occur\n    if (controls.selectionTiming === SelectionTiming.NEVER) {\n      return children;\n    }\n\n    // Check if selection has already been done (for ONCE timing)\n    if (controls.selectionTiming === SelectionTiming.ONCE && controls.selectionCountStatus) {\n      return children;\n    }\n\n    // For non-ONCE timing, Selection Count Status must be True for selection to occur (per SCORM spec)\n    if (controls.selectionTiming !== SelectionTiming.ONCE && !controls.selectionCountStatus) {\n      return children;\n    }\n\n    // Check if we need to select children\n    const selectCount = controls.selectCount;\n    if (selectCount === null || selectCount >= children.length) {\n      // Mark selection as done if timing is ONCE\n      if (controls.selectionTiming === SelectionTiming.ONCE) {\n        controls.selectionCountStatus = true;\n      }\n      return children;\n    }\n\n    // Perform selection\n    const selectedChildren: Activity[] = [];\n    const availableIndices = children.map((_, index) => index);\n\n    // Randomly select children\n    for (let i = 0; i < selectCount; i++) {\n      if (availableIndices.length === 0) break;\n\n      const randomIndex = Math.floor(Math.random() * availableIndices.length);\n      const childIndex = availableIndices[randomIndex];\n      if (childIndex !== undefined && children[childIndex]) {\n        selectedChildren.push(children[childIndex]);\n      }\n\n      // Remove selected index from available indices\n      availableIndices.splice(randomIndex, 1);\n    }\n\n    // Mark selection as done only if timing is ONCE\n    if (controls.selectionTiming === SelectionTiming.ONCE) {\n      controls.selectionCountStatus = true;\n    }\n\n    // Hide non-selected children from choice\n    for (const child of children) {\n      if (!selectedChildren.includes(child)) {\n        child.isHiddenFromChoice = true;\n        child.isAvailable = false;\n      }\n    }\n\n    return selectedChildren;\n  }\n\n  /**\n   * Randomize Children Process (SR.2)\n   * Randomizes the order of child activities based on randomization controls\n   * @param {Activity} activity - The parent activity whose children need to be randomized\n   * @return {Activity[]} - The randomized child activities\n   */\n  public static randomizeChildrenProcess(activity: Activity): Activity[] {\n    const controls = activity.sequencingControls;\n    const children = [...activity.children]; // Create a copy to avoid mutating original\n\n    // Check if randomization should occur\n    if (controls.randomizationTiming === RandomizationTiming.NEVER) {\n      return children;\n    }\n\n    // Check if randomization has already been done (for ONCE timing)\n    if (controls.randomizationTiming === RandomizationTiming.ONCE && controls.reorderChildren) {\n      return children;\n    }\n\n    // Check if we need to randomize\n    if (!controls.randomizeChildren) {\n      return children;\n    }\n\n    // Perform Fisher-Yates shuffle\n    const randomizedChildren = [...children];\n    for (let i = randomizedChildren.length - 1; i > 0; i--) {\n      const j = Math.floor(Math.random() * (i + 1));\n      const tempI = randomizedChildren[i];\n      const tempJ = randomizedChildren[j];\n      if (tempI && tempJ) {\n        randomizedChildren[i] = tempJ;\n        randomizedChildren[j] = tempI;\n      }\n    }\n\n    // Mark randomization as done only if timing is ONCE\n    if (controls.randomizationTiming === RandomizationTiming.ONCE) {\n      controls.reorderChildren = true;\n    }\n\n    // Update the activity's children array with the new order\n    activity.children.length = 0;\n    activity.children.push(...randomizedChildren);\n\n    return randomizedChildren;\n  }\n\n  /**\n   * Apply selection and randomization to an activity\n   * This combines both SR.1 and SR.2 processes\n   * @param {Activity} activity - The parent activity\n   * @param {boolean} isNewAttempt - Whether this is a new attempt on the activity\n   * @return {Activity[]} - The processed child activities\n   */\n  public static applySelectionAndRandomization(\n    activity: Activity,\n    isNewAttempt: boolean = false,\n  ): Activity[] {\n    const controls = activity.sequencingControls;\n\n    // Exit if activity is active or suspended AND this is not a new attempt (per SCORM spec SR.1, SR.2)\n    // On a new attempt, we DO apply selection/randomization even though the activity becomes active\n    if (!isNewAttempt && (activity.isActive || activity.isSuspended)) {\n      if (controls.selectionTiming === SelectionTiming.NEVER) {\n        const processedChildren = activity.getAvailableChildren();\n        const childIds = new Set(activity.children.map((child) => child.id));\n        const processedIds = new Set(processedChildren.map((child) => child.id));\n\n        // A partial processed list cannot represent selection when selection is\n        // disabled. It is usually the result of transient availability during a\n        // prior attempt. Preserve a complete list's order for randomization, but\n        // restore an incomplete list to the current child order.\n        if (\n          processedChildren.length !== activity.children.length ||\n          processedIds.size !== childIds.size ||\n          [...childIds].some((id) => !processedIds.has(id))\n        ) {\n          activity.setProcessedChildren([...activity.children]);\n        }\n      }\n      return activity.getAvailableChildren();\n    }\n\n    // Check if we should apply selection/randomization\n    let shouldApplySelection = false;\n    let shouldApplyRandomization = false;\n\n    // For ON_EACH_NEW_ATTEMPT timing, only apply on new attempts\n    if (controls.selectionTiming === SelectionTiming.ON_EACH_NEW_ATTEMPT) {\n      shouldApplySelection = isNewAttempt;\n      if (isNewAttempt) {\n        controls.selectionCountStatus = true; // Enable selection for new attempt\n      }\n    } else if (controls.selectionTiming === SelectionTiming.ONCE) {\n      shouldApplySelection = !controls.selectionCountStatus;\n      // selectionCountStatus will be set to true by selectChildrenProcess after selection\n    }\n\n    if (controls.randomizationTiming === RandomizationTiming.ON_EACH_NEW_ATTEMPT) {\n      shouldApplyRandomization = isNewAttempt;\n      if (isNewAttempt) {\n        controls.reorderChildren = false;\n      }\n    } else if (controls.randomizationTiming === RandomizationTiming.ONCE) {\n      shouldApplyRandomization = !controls.reorderChildren;\n    }\n\n    // Apply selection first if needed\n    if (shouldApplySelection) {\n      this.selectChildrenProcess(activity);\n    }\n\n    // Then apply randomization if needed\n    if (shouldApplyRandomization) {\n      this.randomizeChildrenProcess(activity);\n    }\n\n    // Availability is also used by sequencing rules as a transient disabled state.\n    // Without selection controls, it must not become a persisted child subset on a\n    // new attempt: those rules are re-evaluated as progress changes. On a resume,\n    // retain an already processed order/subset, including explicit collection state.\n    let processedChildren: Activity[];\n    if (controls.selectionTiming === SelectionTiming.NEVER) {\n      if (isNewAttempt || shouldApplyRandomization) {\n        processedChildren = [...activity.children];\n      } else {\n        processedChildren = activity.getAvailableChildren();\n      }\n    } else {\n      processedChildren = activity.children.filter((child) => child.isAvailable);\n    }\n\n    // Store the processed children on the activity\n    activity.setProcessedChildren(processedChildren);\n\n    return processedChildren;\n  }\n\n  /**\n   * Check if selection is needed for an activity\n   * @param {Activity} activity - The activity to check\n   * @return {boolean} - True if selection is needed\n   */\n  public static isSelectionNeeded(activity: Activity): boolean {\n    const controls = activity.sequencingControls;\n\n    if (controls.selectionTiming === SelectionTiming.NEVER) {\n      return false;\n    }\n\n    if (controls.selectionTiming === SelectionTiming.ONCE && controls.selectionCountStatus) {\n      return false;\n    }\n\n    return controls.selectCount !== null && controls.selectCount < activity.children.length;\n  }\n\n  /**\n   * Check if randomization is needed for an activity\n   * @param {Activity} activity - The activity to check\n   * @return {boolean} - True if randomization is needed\n   */\n  public static isRandomizationNeeded(activity: Activity): boolean {\n    const controls = activity.sequencingControls;\n\n    if (controls.randomizationTiming === RandomizationTiming.NEVER) {\n      return false;\n    }\n\n    if (controls.randomizationTiming === RandomizationTiming.ONCE && controls.reorderChildren) {\n      return false;\n    }\n\n    return controls.randomizeChildren;\n  }\n}\n","import { Activity } from \"../activity\";\nimport { ActivityTree } from \"../activity_tree\";\nimport { RuleEvaluationEngine } from \"../rules/rule_evaluation_engine\";\nimport { FlowSubprocessResult, FlowSubprocessMode } from \"../rules/sequencing_request_types\";\nimport { RuleActionType } from \"../sequencing_rules\";\nimport { SelectionRandomization } from \"../selection_randomization\";\n\n/**\n * Result of flow tree traversal\n */\nexport interface FlowTreeTraversalResult {\n  activity: Activity | null;\n  endSequencingSession: boolean;\n  exception?: string;\n  direction?: FlowSubprocessMode;\n  forwardOnlyCluster?: Activity;\n}\n\n/**\n * FlowTraversalService - Handles tree traversal for flow-based navigation\n *\n * This class extracts the flow traversal logic from SequencingProcess:\n * - SB.2.1: Flow Tree Traversal Subprocess\n * - SB.2.2: Flow Activity Traversal Subprocess\n * - SB.2.3: Flow Subprocess\n * - Activity checking and delivery validation\n *\n * Flow traversal is used for:\n * - CONTINUE navigation (forward flow)\n * - PREVIOUS navigation (backward flow)\n * - Finding the first deliverable activity from a cluster\n */\nexport class FlowTraversalService {\n  private activityEvaluationCallback:\n    | ((activity: Activity, target: Activity) => Activity)\n    | null = null;\n\n  constructor(\n    private activityTree: ActivityTree,\n    private ruleEngine: RuleEvaluationEngine,\n  ) {}\n\n  /**\n   * Supply a disposable objective view for candidate preconditions.\n   * @spec SCORM 2004 SN 4th Ed. SB.2.2 / SM.7 - evaluate mapped objectives without ending attempts.\n   */\n  public setActivityEvaluationCallback(\n    callback: (activity: Activity, target: Activity) => Activity,\n  ): void {\n    this.activityEvaluationCallback = callback;\n  }\n\n  /** @spec SCORM 2004 SN 4th Ed. SB.2.2 / SB.2.9 - speculative rules use projected objective state. */\n  public getActivityForEvaluation(activity: Activity, target: Activity = activity): Activity {\n    return this.activityEvaluationCallback?.(activity, target) ?? activity;\n  }\n\n  /**\n   * Flow Subprocess (SB.2.3)\n   * Traverses the activity tree in the specified direction to find a deliverable activity\n   * @param {Activity} fromActivity - The activity to flow from\n   * @param {FlowSubprocessMode} direction - The flow direction\n   * @return {FlowSubprocessResult} - Result containing the deliverable activity\n   * @spec SN Book: SB.2.3 step 4.3 - returns the SB.2.2 result without retrying a blocked candidate.\n   * @spec SN Book: SB.2.3 (Flow Subprocess) - preserves the SB.2.1 effective traversal direction for SB.2.2.\n   * @spec SN Book: SB.2.2 (Flow Activity Traversal Subprocess) - evaluates candidates using the effective direction returned by SB.2.1.\n   * @spec SN Book: SB.2.2 (Flow Activity Traversal Subprocess) - skipped candidates keep children bypassed when SB.2.3 resumes traversal.\n   */\n  public flowSubprocess(\n    fromActivity: Activity,\n    direction: FlowSubprocessMode,\n  ): FlowSubprocessResult {\n    return this.continueFlowActivityTraversal(fromActivity, direction, true, null);\n  }\n\n  /**\n   * Flow Tree Traversal Subprocess (SB.2.1)\n   * Traverses the activity tree to find the next activity in the specified direction\n   * @param {Activity} fromActivity - The activity to traverse from\n   * @param {FlowSubprocessMode} direction - The traversal direction\n   * @param {boolean} skipChildren - Whether to skip checking children\n   * @param {Activity | null} forwardTraversalBoundary - Cluster boundary for an SB.2.1 forwardOnly direction reversal\n   * @return {FlowTreeTraversalResult} - The next activity and flags\n   * @spec SN Book: SB.2.1 (Flow Tree Traversal Subprocess) - backward traversal into a forwardOnly cluster selects the first available child and reverses traversal direction to Forward.\n   * @spec SN Book: SB.2.2 (Flow Activity Traversal Subprocess) - cluster descent is delegated to SB.2.1 with Consider Children true.\n   */\n  public flowTreeTraversalSubprocess(\n    fromActivity: Activity,\n    direction: FlowSubprocessMode,\n    skipChildren: boolean = false,\n    forwardTraversalBoundary: Activity | null = null,\n  ): FlowTreeTraversalResult {\n    if (direction === FlowSubprocessMode.FORWARD) {\n      return this.traverseForward(fromActivity, skipChildren, forwardTraversalBoundary);\n    } else {\n      return this.traverseBackward(fromActivity, skipChildren);\n    }\n  }\n\n  /**\n   * Traverse forward in the activity tree\n   * @param {Activity} fromActivity - Starting activity\n   * @param {boolean} skipChildren - Whether to skip children\n   * @param {Activity | null} forwardTraversalBoundary - Cluster boundary for an SB.2.1 forwardOnly direction reversal\n   * @return {FlowTreeTraversalResult}\n   * @spec SCORM 2004 SN 4th Ed. SB.2.1 / SB.2.2 - candidate traversal preserves attempts until DB.2 accepts delivery.\n   * @spec SN Book: SB.2.1 (Flow Tree Traversal Subprocess) - a reversed Forward traversal from a forwardOnly cluster remains within that cluster.\n   */\n  private traverseForward(\n    fromActivity: Activity,\n    skipChildren: boolean,\n    forwardTraversalBoundary: Activity | null = null,\n  ): FlowTreeTraversalResult {\n    if (\n      forwardTraversalBoundary &&\n      !this.isDescendantOfOrSelf(fromActivity, forwardTraversalBoundary)\n    ) {\n      return { activity: null, endSequencingSession: false };\n    }\n\n    // Check if we're at the last activity\n    if (!forwardTraversalBoundary && skipChildren && this.isActivityLastOverall(fromActivity)) {\n      // Terminate all descendent attempts at root\n      if (this.activityTree.root) {\n        this.terminateDescendentAttempts(this.activityTree.root);\n      }\n      return { activity: null, endSequencingSession: true };\n    }\n\n    // Check children first\n    if (!skipChildren) {\n      this.ensureSelectionAndRandomization(fromActivity);\n      const children = fromActivity.getAvailableChildren();\n      if (children.length > 0) {\n        return { activity: children[0] || null, endSequencingSession: false };\n      }\n    }\n\n    // No children, try to get next sibling\n    let current: Activity | null = fromActivity;\n    while (current) {\n      const nextSibling = this.activityTree.getNextSibling(current);\n      if (nextSibling) {\n        return { activity: nextSibling, endSequencingSession: false };\n      }\n      if (\n        forwardTraversalBoundary &&\n        (current === forwardTraversalBoundary || current.parent === forwardTraversalBoundary)\n      ) {\n        return { activity: null, endSequencingSession: false };\n      }\n      current = current.parent;\n    }\n\n    // Reached end of tree\n    if (this.activityTree.root) {\n      this.terminateDescendentAttempts(this.activityTree.root);\n    }\n    return { activity: null, endSequencingSession: true };\n  }\n\n  /**\n   * Traverse backward in the activity tree\n   * @param {Activity} fromActivity - Starting activity\n   * @param {boolean} skipChildren - Whether to skip children\n   * @return {FlowTreeTraversalResult}\n   * @spec SN Book: SB.2.1 (Flow Tree Traversal Subprocess) - backward traversal with Consider Children true enters the last available child.\n   * @spec SN Book: SB.2.1 (Flow Tree Traversal Subprocess) - backward traversal into a forwardOnly cluster selects the first available child and reverses traversal direction to Forward.\n   */\n  private traverseBackward(fromActivity: Activity, skipChildren: boolean): FlowTreeTraversalResult {\n    // Check forwardOnly constraint\n    if (fromActivity.parent && fromActivity.parent.sequencingControls.forwardOnly) {\n      return { activity: null, endSequencingSession: false, exception: \"SB.2.1-4\" };\n    }\n\n    if (!skipChildren) {\n      this.ensureSelectionAndRandomization(fromActivity);\n      const children = fromActivity.getAvailableChildren();\n      if (children.length > 0) {\n        if (fromActivity.sequencingControls.forwardOnly) {\n          // @spec SN Book: SB.2.1 (Flow Tree Traversal Subprocess) - a Backward traversal entering a forwardOnly cluster starts at the first available child and reverses direction.\n          return {\n            activity: children[0] || null,\n            endSequencingSession: false,\n            direction: FlowSubprocessMode.FORWARD,\n            forwardOnlyCluster: fromActivity,\n          };\n        }\n\n        return {\n          activity: children[children.length - 1] || null,\n          endSequencingSession: false,\n        };\n      }\n    }\n\n    // Try to get previous sibling\n    const previousSibling = this.activityTree.getPreviousSibling(fromActivity);\n    if (previousSibling) {\n      return this.getBackwardTraversalEntry(previousSibling);\n    }\n\n    // No previous sibling, try going up to parent\n    let current: Activity | null = fromActivity;\n    let ancestorIterations = 0;\n    const maxIterations = 10000;\n\n    while (current && current.parent) {\n      if (++ancestorIterations > maxIterations) {\n        throw new Error(\"Infinite loop detected in backward traversal\");\n      }\n\n      const parentPreviousSibling = this.activityTree.getPreviousSibling(current.parent);\n      if (parentPreviousSibling) {\n        return this.getBackwardTraversalEntry(parentPreviousSibling);\n      }\n      current = current.parent;\n    }\n\n    // Reached beginning of tree\n    return { activity: null, endSequencingSession: false };\n  }\n\n  /**\n   * Get the activity entered by backward traversal.\n   * @param {Activity} activity - The activity\n   * @return {FlowTreeTraversalResult} - The entered activity and effective direction\n   * @spec SN Book: SB.2.1 (Flow Tree Traversal Subprocess) - backward traversal selects the previous sibling candidate before SB.2.2 evaluates cluster traversal rules.\n   * @spec SN Book: SB.2.1 (Flow Tree Traversal Subprocess) - entering a forwardOnly cluster while moving Backward uses the first available child and changes direction to Forward.\n   */\n  private getBackwardTraversalEntry(activity: Activity): FlowTreeTraversalResult {\n    this.ensureSelectionAndRandomization(activity);\n    const children = activity.getAvailableChildren();\n\n    if (children.length > 0 && activity.sequencingControls.forwardOnly) {\n      // @spec SN Book: SB.2.1 (Flow Tree Traversal Subprocess) - a Backward traversal entering a forwardOnly cluster starts at the first available child and reverses direction.\n      return {\n        activity: children[0] || null,\n        endSequencingSession: false,\n        direction: FlowSubprocessMode.FORWARD,\n        forwardOnlyCluster: activity,\n      };\n    }\n\n    return {\n      activity,\n      endSequencingSession: false,\n    };\n  }\n\n  /**\n   * Check whether an activity is the same as or beneath an ancestor.\n   * @param {Activity} activity - The activity to check\n   * @param {Activity} ancestor - The expected ancestor\n   * @return {boolean} - True when activity is within ancestor\n   * @spec SN Book: SB.2.1 (Flow Tree Traversal Subprocess) - bounds Forward traversal after a forwardOnly direction reversal to the entered cluster.\n   */\n  private isDescendantOfOrSelf(activity: Activity, ancestor: Activity): boolean {\n    let current: Activity | null = activity;\n    while (current) {\n      if (current === ancestor) {\n        return true;\n      }\n      current = current.parent;\n    }\n\n    return false;\n  }\n\n  /**\n   * Flow Activity Traversal Subprocess (SB.2.2)\n   * Checks if an activity can be delivered and flows into clusters if needed\n   * @param {Activity} activity - The activity to check\n   * @param {boolean} _direction - Direction (unused but part of spec)\n   * @param {boolean} considerChildren - Whether to consider children\n   * @param {FlowSubprocessMode} mode - The flow mode\n   * @param {Activity | null} forwardTraversalBoundary - Cluster boundary for an SB.2.1 forwardOnly direction reversal\n   * @return {Activity | null} - The deliverable activity or null\n   * @spec SN Book: SB.2.2 (Flow Activity Traversal Subprocess) - checks the Skipped rule set before considering children.\n   * @spec SN Book: SB.2.2 (Flow Activity Traversal Subprocess) - clusters enter children through SB.2.1 using the active traversal direction.\n   */\n  public flowActivityTraversalSubprocess(\n    activity: Activity,\n    _direction: boolean,\n    considerChildren: boolean,\n    mode: FlowSubprocessMode,\n    forwardTraversalBoundary: Activity | null = null,\n  ): Activity | null {\n    const result = this.evaluateFlowActivity(\n      activity,\n      considerChildren,\n      mode,\n      forwardTraversalBoundary,\n    );\n    return result.deliverable ? result.identifiedActivity : null;\n  }\n\n  /**\n   * Evaluate a flow candidate while retaining its exception and session-end result.\n   * @spec SN Book: SB.2.2 steps 3, 5.1, 6 - only skipped candidates traverse onward; blocked candidates stop before cluster descent.\n   */\n  private evaluateFlowActivity(\n    activity: Activity,\n    considerChildren: boolean,\n    mode: FlowSubprocessMode,\n    forwardTraversalBoundary: Activity | null,\n  ): FlowSubprocessResult {\n    const parent = activity.parent;\n    if (parent && !parent.sequencingControls.flow) {\n      return new FlowSubprocessResult(activity, false, \"SB.2.2-1\");\n    }\n\n    if (this.checkSkippedRuleSet(activity)) {\n      return this.continueFlowActivityTraversal(activity, mode, true, forwardTraversalBoundary);\n    }\n\n    if (mode === FlowSubprocessMode.FORWARD && activity.sequencingControls.stopForwardTraversal) {\n      return new FlowSubprocessResult(activity, false, \"SB.2.2-2\");\n    }\n\n    // checkActivityProcess returns true for deliverable activities (the inverse of UP.5).\n    if (!this.checkActivityProcess(activity)) {\n      return new FlowSubprocessResult(activity, false, \"SB.2.2-2\");\n    }\n\n    if (activity.children.length === 0) {\n      return new FlowSubprocessResult(activity, true);\n    }\n\n    if (considerChildren) {\n      return this.continueFlowActivityTraversal(activity, mode, false, forwardTraversalBoundary);\n    }\n\n    return new FlowSubprocessResult(activity, false);\n  }\n\n  /**\n   * Continue SB.2.2 evaluation from the next SB.2.1 flow candidate.\n   * @param {Activity} fromActivity - The activity to flow from\n   * @param {FlowSubprocessMode} mode - The flow mode\n   * @param {boolean} skipChildren - Whether SB.2.1 should skip children of the start activity\n   * @param {Activity | null} forwardTraversalBoundary - Cluster boundary for an SB.2.1 forwardOnly direction reversal\n   * @return {FlowSubprocessResult} - The candidate evaluation or tree traversal failure\n   * @spec SN Book: SB.2.2 (Flow Activity Traversal Subprocess) - recursively evaluates successive SB.2.1 candidates when a candidate cannot be delivered.\n   * @spec SN Book: SB.2.2 steps 3, 6.3.3; SB.2.3 step 4.3 - propagate recursive results; only skip and cluster descent request another candidate.\n   * @spec SN Book: SB.2.1 step 3.1 - preserve session end on genuine tree exhaustion.\n   */\n  private continueFlowActivityTraversal(\n    fromActivity: Activity,\n    mode: FlowSubprocessMode,\n    skipChildren: boolean,\n    forwardTraversalBoundary: Activity | null,\n  ): FlowSubprocessResult {\n    const traversalResult = this.flowTreeTraversalSubprocess(\n      fromActivity,\n      mode,\n      skipChildren,\n      forwardTraversalBoundary,\n    );\n\n    if (!traversalResult.activity) {\n      const exception =\n        traversalResult.exception ||\n        (mode === FlowSubprocessMode.BACKWARD\n          ? \"SB.2.1-3\"\n          : fromActivity.children.length > 0 && fromActivity.getAvailableChildren().length === 0\n            ? \"SB.2.1-2\"\n            : null);\n      return new FlowSubprocessResult(\n        fromActivity,\n        false,\n        exception,\n        traversalResult.endSequencingSession,\n      );\n    }\n\n    return this.evaluateFlowActivity(\n      traversalResult.activity,\n      true,\n      traversalResult.direction || mode,\n      traversalResult.forwardOnlyCluster || forwardTraversalBoundary,\n    );\n  }\n\n  /**\n   * Check whether the Skipped pre-condition rule set applies to an activity.\n   * @param {Activity} activity - The activity to check\n   * @return {boolean} - True when the Skipped rule set applies\n   * @spec SN Book: SB.2.2 (Flow Activity Traversal Subprocess) - evaluates only the Skipped sequencing rule set before cluster descent.\n   */\n  private checkSkippedRuleSet(activity: Activity): boolean {\n    const skippedRules = activity.sequencingRules.preConditionRules.filter(\n      (rule) => rule.action === RuleActionType.SKIP,\n    );\n    const wasSkipped =\n      this.ruleEngine.checkSequencingRules(this.getActivityForEvaluation(activity), skippedRules) ===\n      RuleActionType.SKIP;\n\n    activity.wasSkipped = wasSkipped;\n\n    return wasSkipped;\n  }\n\n  /**\n   * Check Activity Process (SB.2.3)\n   * Validates if an activity can be delivered\n   * @param {Activity} activity - The activity to check\n   * @return {boolean} - True if activity can be delivered\n   */\n  public checkActivityProcess(activity: Activity): boolean {\n    // Check availability\n    if (!activity.isAvailable) {\n      return false;\n    }\n\n    // Check limit conditions\n    if (this.ruleEngine.checkLimitConditions(activity)) {\n      return false;\n    }\n\n    // Check pre-condition rules\n    const deliveryCheck = this.ruleEngine.canDeliverActivity(\n      this.getActivityForEvaluation(activity),\n    );\n    activity.wasSkipped = deliveryCheck.wasSkipped;\n\n    return deliveryCheck.canDeliver;\n  }\n\n  /**\n   * Ensure selection and randomization is applied to an activity\n   * @param {Activity} activity - The activity to process\n   */\n  public ensureSelectionAndRandomization(activity: Activity): void {\n    if (\n      activity.getAvailableChildren() === activity.children &&\n      (SelectionRandomization.isSelectionNeeded(activity) ||\n        SelectionRandomization.isRandomizationNeeded(activity))\n    ) {\n      SelectionRandomization.applySelectionAndRandomization(activity, activity.isNewAttempt);\n    }\n  }\n\n  /**\n   * Check if activity is the last activity in the tree (forward preorder)\n   * @param {Activity} activity - The activity to check\n   * @return {boolean} - True if last in tree\n   */\n  private isActivityLastOverall(activity: Activity): boolean {\n    if (activity.children.length > 0) {\n      return false;\n    }\n\n    let current: Activity | null = activity;\n    while (current) {\n      if (this.activityTree.getNextSibling(current)) {\n        return false;\n      }\n      current = current.parent;\n    }\n\n    return true;\n  }\n\n  /**\n   * Terminate descendent attempts (simplified version)\n   * Full version with exit rules is in SequencingProcess\n   * @param {Activity} activity - The activity\n   */\n  private terminateDescendentAttempts(activity: Activity): void {\n    activity.isActive = false;\n    for (const child of activity.children) {\n      this.terminateDescendentAttempts(child);\n    }\n  }\n\n  /**\n   * Find the first deliverable activity from a cluster\n   * Used for START and RETRY_ALL requests\n   * @param {Activity} cluster - The cluster activity\n   * @return {Activity | null} - The first deliverable activity\n   * @spec SN Book: SB.2.5 step 3.2; SB.2.2 steps 3, 5.1 - only Skipped candidates permit traversal past a failed candidate.\n   */\n  public findFirstDeliverableActivity(cluster: Activity): Activity | null {\n    const result = this.findFirstDeliverableActivityResult(cluster);\n    return result.deliverable ? result.identifiedActivity : null;\n  }\n\n  /**\n   * Enter a cluster through one Flow Subprocess, retaining any traversal exception.\n   * @param {Activity} cluster - The activity to enter\n   * @param {Activity | null} boundary - Optional boundary for a cluster Retry\n   * @return {FlowSubprocessResult} - Delivery candidate or the original flow failure\n   * @spec SN Book: SB.2.5 steps 3.2, 3.2.1 (Start Sequencing Request Process) - flow Forward with Consider Children true exactly once.\n   * @spec SN Book: SB.2.10 step 3 (Retry Sequencing Request Process) - enter the retried cluster and retain the Flow Subprocess result.\n   * @spec SN Book: SB.2.1 (Flow Tree Traversal Subprocess) - child selection and randomization occur when traversal enters the cluster.\n   */\n  public findFirstDeliverableActivityResult(\n    cluster: Activity,\n    boundary: Activity | null = null,\n  ): FlowSubprocessResult {\n    // If the cluster itself is a leaf (no children), check if it can be delivered\n    // @spec SN Book: SB.2.2 step 5; UP.5 (Check Activity Process) - preserve direct leaf delivery checks.\n    // @spec SN Book: SB.2.2 step 5.1 - a blocked leaf fails with SB.2.2-2, as in child traversal.\n    if (cluster.children.length === 0) {\n      const deliverable = this.checkActivityProcess(cluster);\n      return new FlowSubprocessResult(cluster, deliverable, deliverable ? null : \"SB.2.2-2\");\n    }\n\n    // @spec SN Book: SB.2.3 step 4.3; SB.2.2 steps 3, 5.1 - propagate a blocked candidate; only Skip traverses onward.\n    return this.continueFlowActivityTraversal(cluster, FlowSubprocessMode.FORWARD, false, boundary);\n  }\n\n  /**\n   * Can activity be delivered (public wrapper)\n   * @param {Activity} activity - The activity\n   * @return {boolean} - True if can be delivered\n   */\n  public canDeliver(activity: Activity): boolean {\n    return this.checkActivityProcess(activity);\n  }\n}\n","import { Activity } from \"../activity\";\nimport { ActivityTree } from \"../activity_tree\";\nimport { FlowTraversalService } from \"../traversal/flow_traversal_service\";\nimport {\n  SequencingResult,\n  DeliveryRequestType,\n  FlowSubprocessMode\n} from \"../rules/sequencing_request_types\";\n\n/**\n * FlowRequestHandler - Handles flow-based sequencing requests\n *\n * This handler manages:\n * - START: Start a new sequencing session\n * - RESUME_ALL: Resume a suspended sequencing session\n * - CONTINUE: Navigate to the next activity (forward flow)\n * - PREVIOUS: Navigate to the previous activity (backward flow)\n */\nexport class FlowRequestHandler {\n  constructor(\n    private activityTree: ActivityTree,\n    private traversalService: FlowTraversalService\n  ) {}\n\n  /**\n   * Start Sequencing Request Process (SB.2.5)\n   * Initiates a new sequencing session from the root\n   * @return {SequencingResult}\n   * @spec SN Book: SB.2.5 steps 3.2, 3.2.1 (Start Sequencing Request Process) - apply Flow once and preserve its exception.\n   */\n  public handleStart(): SequencingResult {\n    const result = new SequencingResult();\n\n    // SB.2.5-1: Check if there's a root (activity tree)\n    if (!this.activityTree.root) {\n      result.exception = \"SB.2.5-1\";\n      return result;\n    }\n\n    // SB.2.5-2: Check if sequencing session has already begun\n    if (this.activityTree.currentActivity) {\n      result.exception = \"SB.2.5-2\";\n      return result;\n    }\n\n    // Find the first deliverable activity\n    const flowResult = this.traversalService.findFirstDeliverableActivityResult(\n      this.activityTree.root,\n    );\n\n    // @spec SN Book: SB.2.5 step 3.2.1 - return the exception identified by the Flow Subprocess.\n    if (!flowResult.deliverable || !flowResult.identifiedActivity) {\n      result.exception = flowResult.exception || \"SB.2.5-3\";\n      return result;\n    }\n\n    result.deliveryRequest = DeliveryRequestType.DELIVER;\n    result.targetActivity = flowResult.identifiedActivity;\n    return result;\n  }\n\n  /**\n   * Resume All Sequencing Request Process (SB.2.6)\n   * Resumes a suspended sequencing session\n   * @return {SequencingResult}\n   */\n  public handleResumeAll(): SequencingResult {\n    const result = new SequencingResult();\n\n    // Check if there's a suspended activity\n    if (!this.activityTree.suspendedActivity) {\n      result.exception = \"SB.2.6-1\";\n      return result;\n    }\n\n    // Check if there's already a current activity\n    if (this.activityTree.currentActivity) {\n      result.exception = \"SB.2.6-2\";\n      return result;\n    }\n\n    // Resume the suspended activity\n    result.deliveryRequest = DeliveryRequestType.DELIVER;\n    result.targetActivity = this.activityTree.suspendedActivity;\n    return result;\n  }\n\n  /**\n   * Continue Sequencing Request Process (SB.2.7)\n   * Navigates to the next activity in forward flow\n   * @param {Activity} currentActivity - The current activity\n   * @return {SequencingResult}\n   */\n  public handleContinue(currentActivity: Activity): SequencingResult {\n    const result = new SequencingResult();\n\n    // SB.2.7-1: Activity must be terminated (not active)\n    if (currentActivity.isActive) {\n      result.exception = \"SB.2.7-1\";\n      return result;\n    }\n\n    // SB.2.7-2: Check flow control\n    if (currentActivity.parent && !currentActivity.parent.sequencingControls.flow) {\n      result.exception = \"SB.2.7-2\";\n      return result;\n    }\n\n    // Use flow subprocess to find next deliverable\n    const flowResult = this.traversalService.flowSubprocess(\n      currentActivity,\n      FlowSubprocessMode.FORWARD\n    );\n\n    // Propagate endSequencingSession flag\n    result.endSequencingSession = flowResult.endSequencingSession;\n\n    // Check if we found a deliverable activity\n    if (!flowResult.deliverable || !flowResult.identifiedActivity) {\n      // SB.2.7-2 when no activity available (regardless of endSequencingSession)\n      result.exception = flowResult.exception || \"SB.2.7-2\";\n      return result;\n    }\n\n    result.deliveryRequest = DeliveryRequestType.DELIVER;\n    result.targetActivity = flowResult.identifiedActivity;\n    return result;\n  }\n\n  /**\n   * Previous Sequencing Request Process (SB.2.8)\n   * Navigates to the previous activity in backward flow\n   * @param {Activity} currentActivity - The current activity\n   * @return {SequencingResult}\n   */\n  public handlePrevious(currentActivity: Activity): SequencingResult {\n    const result = new SequencingResult();\n\n    // SB.2.8-1: Activity must be terminated (not active)\n    if (currentActivity.isActive) {\n      result.exception = \"SB.2.8-1\";\n      return result;\n    }\n\n    // SB.2.8-2: Check flow control\n    if (currentActivity.parent && !currentActivity.parent.sequencingControls.flow) {\n      result.exception = \"SB.2.8-2\";\n      return result;\n    }\n\n    // Check forwardOnly at all ancestor levels\n    const forwardOnlyViolation = this.checkForwardOnlyViolation(currentActivity);\n    if (forwardOnlyViolation) {\n      result.exception = forwardOnlyViolation;\n      return result;\n    }\n\n    // Use flow subprocess to find previous deliverable\n    const flowResult = this.traversalService.flowSubprocess(\n      currentActivity,\n      FlowSubprocessMode.BACKWARD\n    );\n\n    // Check if we found a deliverable activity\n    if (!flowResult.deliverable || !flowResult.identifiedActivity) {\n      result.exception = flowResult.exception || \"SB.2.8-3\";\n      return result;\n    }\n\n    result.deliveryRequest = DeliveryRequestType.DELIVER;\n    result.targetActivity = flowResult.identifiedActivity;\n    return result;\n  }\n\n  /**\n   * Check forwardOnly violation at all ancestor levels\n   * @param {Activity} activity - The activity to check\n   * @return {string | null} - Exception code or null\n   */\n  private checkForwardOnlyViolation(activity: Activity): string | null {\n    let current: Activity | null = activity.parent;\n\n    while (current) {\n      if (current.sequencingControls.forwardOnly) {\n        return \"SB.2.9-5\";\n      }\n      current = current.parent;\n    }\n\n    return null;\n  }\n}\n","import { Activity } from \"../activity\";\nimport { ActivityTree } from \"../activity_tree\";\nimport { ActivityTreeQueries } from \"../utils/activity_tree_queries\";\nimport { ChoiceConstraintValidator } from \"../validators/choice_constraint_validator\";\nimport { FlowTraversalService } from \"../traversal/flow_traversal_service\";\nimport { RuleActionType } from \"../sequencing_rules\";\nimport {\n  SequencingResult,\n  DeliveryRequestType,\n  ChoiceTraversalResult,\n} from \"../rules/sequencing_request_types\";\n\n/**\n * ChoiceRequestHandler - Handles choice-based sequencing requests\n *\n * This handler manages:\n * - CHOICE: Navigate to a specific activity selected by the learner\n * - JUMP: Navigate directly to a specific activity (4th Edition)\n *\n * Choice navigation is more complex than flow navigation because it must\n * validate many constraints at each ancestor level.\n */\nexport class ChoiceRequestHandler {\n  constructor(\n    private activityTree: ActivityTree,\n    private constraintValidator: ChoiceConstraintValidator,\n    private traversalService: FlowTraversalService,\n    private treeQueries: ActivityTreeQueries,\n    private getNow?: () => () => Date,\n    private getElapsedSeconds?: () => ((activity: Activity) => number) | null | undefined,\n  ) {}\n\n  /**\n   * Choice Sequencing Request Process (SB.2.9)\n   * Processes a choice navigation request to a specific activity\n   * @param {string} targetActivityId - The target activity ID\n   * @param {Activity | null} currentActivity - Current activity (may be null)\n   * @return {SequencingResult}\n   */\n  public handleChoice(\n    targetActivityId: string,\n    currentActivity: Activity | null,\n  ): SequencingResult {\n    const result = new SequencingResult();\n\n    // Find the target activity\n    const targetActivity = this.activityTree.getActivity(targetActivityId);\n    if (!targetActivity) {\n      result.exception = \"SB.2.9-1\";\n      return result;\n    }\n\n    // SB.2.9-6: Check if current activity is terminated\n    if (currentActivity && currentActivity.isActive) {\n      result.exception = \"SB.2.9-6\";\n      return result;\n    }\n\n    // Validate choice constraints\n    const validation = this.constraintValidator.validateChoice(currentActivity, targetActivity, {\n      checkAvailability: true,\n    });\n\n    if (!validation.valid) {\n      result.exception = validation.exception;\n      return result;\n    }\n\n    // @spec SCORM 2004 SN 4th Ed. SB.2.9 / DB.2 - defer UP.3 until delivery succeeds.\n    // @spec SCORM 2004 SN 4th Ed. SB.2.9 steps 3-4: the root-to-target path\n    // is checked only for Hide from Choice rules. Skip rules apply to flow,\n    // not to a learner explicitly choosing a descendant activity.\n    for (const pathActivity of this.treeQueries.getPathToRoot(targetActivity)) {\n      const evaluationActivity = this.traversalService.getActivityForEvaluation(\n        pathActivity,\n        targetActivity,\n      );\n      const hiddenByRule = pathActivity.sequencingRules.preConditionRules.some(\n        (rule) =>\n          rule.action === RuleActionType.HIDE_FROM_CHOICE &&\n          rule.evaluate(\n            evaluationActivity,\n            this.getNow?.() ?? (() => new Date()),\n            this.getElapsedSeconds?.() ?? null,\n          ) === true,\n      );\n      if (hiddenByRule) {\n        result.exception = \"SB.2.9-4\";\n        return result;\n      }\n    }\n\n    // The root-to-target visibility pass does not apply general preconditions to\n    // ancestors, but the explicitly selected activity must itself be deliverable.\n    // @spec SCORM 2004 SN 4th Ed. SB.2.9 choice traversal cases\n    if (!this.traversalService.checkActivityProcess(targetActivity)) {\n      result.exception = \"SB.2.9-5\";\n      return result;\n    }\n\n    // If target is not a leaf, use choice flow to find a deliverable leaf\n    let deliveryTarget = targetActivity;\n    if (targetActivity.children.length > 0) {\n      const flowResult = this.choiceFlowSubprocess(targetActivity);\n\n      if (!flowResult) {\n        result.exception = \"SB.2.9-7\";\n        return result;\n      }\n\n      deliveryTarget = flowResult;\n    }\n\n    // Deliver the identified activity\n    result.deliveryRequest = DeliveryRequestType.DELIVER;\n    result.targetActivity = deliveryTarget;\n    return result;\n  }\n\n  /**\n   * Jump Sequencing Request Process (SB.2.13)\n   * Processes a jump navigation request (SCORM 2004 4th Edition)\n   * Jump bypasses most sequencing rules\n   * @param {string} targetActivityId - The target activity ID\n   * @return {SequencingResult}\n   */\n  public handleJump(targetActivityId: string): SequencingResult {\n    const result = new SequencingResult();\n\n    // Find the target activity\n    const targetActivity = this.activityTree.getActivity(targetActivityId);\n    if (!targetActivity) {\n      result.exception = \"SB.2.13-1\";\n      return result;\n    }\n\n    // Check if target is in the activity tree\n    if (!this.treeQueries.isInTree(targetActivity)) {\n      result.exception = \"SB.2.13-2\";\n      return result;\n    }\n\n    // Check if target is available\n    if (!targetActivity.isAvailable) {\n      result.exception = \"SB.2.13-3\";\n      return result;\n    }\n\n    // Deliver the target activity directly\n    result.deliveryRequest = DeliveryRequestType.DELIVER;\n    result.targetActivity = targetActivity;\n    return result;\n  }\n\n  /**\n   * Get all activities available for choice navigation\n   * @return {Activity[]} - Array of available activities\n   */\n  public getAvailableChoices(): Activity[] {\n    const allActivities = this.activityTree.getAllActivities();\n    const currentActivity = this.activityTree.currentActivity;\n    const availableActivities: Activity[] = [];\n\n    for (const activity of allActivities) {\n      // Skip if hidden, unavailable, or invisible\n      if (activity.isHiddenFromChoice || !activity.isAvailable || !activity.isVisible) {\n        continue;\n      }\n\n      // Check if choice is allowed by parent\n      if (activity.parent && !activity.parent.sequencingControls.choice) {\n        continue;\n      }\n\n      // Validate the full choice path\n      const validation = this.constraintValidator.validateChoice(currentActivity, activity);\n      if (validation.valid) {\n        availableActivities.push(activity);\n      }\n    }\n\n    return availableActivities;\n  }\n\n  /**\n   * Choice Flow Subprocess (SB.2.9.1)\n   * Handles the flow logic specific to choice navigation requests\n   * @param {Activity} targetActivity - The target activity for the choice\n   * @return {Activity | null} - The activity to deliver, or null if flow fails\n   */\n  private choiceFlowSubprocess(targetActivity: Activity): Activity | null {\n    // If target is a leaf, it's the delivery candidate\n    if (targetActivity.children.length === 0) {\n      return targetActivity;\n    }\n\n    // If target is a cluster, traverse to find a deliverable leaf\n    return this.choiceFlowTreeTraversal(targetActivity);\n  }\n\n  /**\n   * Choice Flow Tree Traversal (SB.2.9.2)\n   * Traverses into a cluster to find a deliverable leaf\n   * @param {Activity} fromActivity - The cluster to traverse from\n   * @return {Activity | null} - A leaf activity for delivery, or null\n   */\n  private choiceFlowTreeTraversal(fromActivity: Activity): Activity | null {\n    this.traversalService.ensureSelectionAndRandomization(fromActivity);\n    const children = fromActivity.getAvailableChildren();\n\n    // Validate children against constraints\n    const validChildren = this.constraintValidator.validateFlowConstraints(fromActivity, children);\n\n    if (!validChildren.valid) {\n      return null;\n    }\n\n    // Find the first deliverable child\n    for (const child of validChildren.validChildren) {\n      const traversalResult = this.enhancedChoiceTraversal(child);\n      if (traversalResult.activity) {\n        return traversalResult.activity;\n      }\n    }\n\n    return null;\n  }\n\n  /**\n   * Enhanced Choice Activity Traversal (SB.2.4)\n   * Traverses with stopForwardTraversal and forwardOnly checks\n   * @param {Activity} activity - The activity to traverse\n   * @param {boolean} isBackwardTraversal - Whether this is backward traversal\n   * @return {ChoiceTraversalResult} - Result with activity or exception\n   */\n  private enhancedChoiceTraversal(\n    activity: Activity,\n    isBackwardTraversal: boolean = false,\n  ): ChoiceTraversalResult {\n    // Cannot walk backward from root\n    if (isBackwardTraversal && activity === this.activityTree.root) {\n      return new ChoiceTraversalResult(null, \"SB.2.4-3\");\n    }\n\n    // Check availability\n    if (!activity.isAvailable) {\n      return new ChoiceTraversalResult(null, null);\n    }\n\n    // Check hidden from choice\n    if (activity.isHiddenFromChoice) {\n      return new ChoiceTraversalResult(null, null);\n    }\n\n    // Check stopForwardTraversal\n    if (activity.sequencingControls && activity.sequencingControls.stopForwardTraversal) {\n      return new ChoiceTraversalResult(null, \"SB.2.4-1\");\n    }\n\n    // Validate traversal constraints\n    const traversalValidation = this.constraintValidator.validateTraversalConstraints(activity);\n    if (!traversalValidation.canTraverse) {\n      return new ChoiceTraversalResult(null, null);\n    }\n\n    // If it's a leaf, check if it can be delivered\n    if (activity.children.length === 0) {\n      if (this.traversalService.checkActivityProcess(activity)) {\n        return new ChoiceTraversalResult(activity, null);\n      }\n      return new ChoiceTraversalResult(null, null);\n    }\n\n    // Check constrainChoice for clusters\n    if (\n      activity.parent?.sequencingControls.constrainChoice &&\n      !traversalValidation.canTraverseInto\n    ) {\n      return new ChoiceTraversalResult(null, \"SB.2.4-2\");\n    }\n\n    // Traverse into cluster\n    if (traversalValidation.canTraverseInto) {\n      const flowResult = this.choiceFlowTreeTraversal(activity);\n      return new ChoiceTraversalResult(flowResult, null);\n    }\n\n    return new ChoiceTraversalResult(null, null);\n  }\n}\n","import { Activity } from \"../activity\";\nimport { ActivityTree } from \"../activity_tree\";\nimport { RuleEvaluationEngine } from \"../rules/rule_evaluation_engine\";\nimport { SequencingResult } from \"../rules/sequencing_request_types\";\nimport { RuleActionType } from \"../sequencing_rules\";\n\n/**\n * ExitRequestHandler - Handles exit and termination sequencing requests\n *\n * This handler manages:\n * - EXIT: Exit the current activity\n * - EXIT_ALL: Exit all activities\n * - ABANDON: Abandon the current activity\n * - ABANDON_ALL: Abandon all activities\n * - SUSPEND_ALL: Suspend all activities\n */\nexport class ExitRequestHandler {\n  constructor(\n    private activityTree: ActivityTree,\n    private ruleEngine: RuleEvaluationEngine\n  ) {}\n\n  /**\n   * Exit Sequencing Request Process (SB.2.11)\n   * @param {Activity} currentActivity - The current activity\n   * @return {SequencingResult}\n   */\n  public handleExit(currentActivity: Activity): SequencingResult {\n    const result = new SequencingResult();\n\n    // Check if exit is allowed\n    if (!currentActivity.parent) {\n      result.exception = \"SB.2.11-1\";\n      return result;\n    }\n\n    // Check parent's sequencing controls\n    if (!currentActivity.parent.sequencingControls.choiceExit) {\n      result.exception = \"SB.2.11-2\";\n      return result;\n    }\n\n    // Terminate current activity\n    this.terminateDescendentAttempts(currentActivity);\n\n    return result;\n  }\n\n  /**\n   * Exit All Sequencing Request Process\n   * @return {SequencingResult}\n   */\n  public handleExitAll(): SequencingResult {\n    const result = new SequencingResult();\n\n    // Terminate all activities\n    if (this.activityTree.root) {\n      this.terminateDescendentAttempts(this.activityTree.root);\n    }\n\n    return result;\n  }\n\n  /**\n   * Abandon Sequencing Request Process\n   * @param {Activity} currentActivity - The current activity\n   * @return {SequencingResult}\n   */\n  public handleAbandon(currentActivity: Activity): SequencingResult {\n    const result = new SequencingResult();\n\n    // Set current activity as abandoned\n    currentActivity.isActive = false;\n    this.activityTree.currentActivity = currentActivity.parent;\n\n    return result;\n  }\n\n  /**\n   * Abandon All Sequencing Request Process\n   * @return {SequencingResult}\n   */\n  public handleAbandonAll(): SequencingResult {\n    const result = new SequencingResult();\n\n    // Abandon all activities\n    this.activityTree.currentActivity = null;\n\n    return result;\n  }\n\n  /**\n   * Suspend All Sequencing Request Process (SB.2.15)\n   * @param {Activity} currentActivity - The current activity\n   * @return {SequencingResult}\n   */\n  public handleSuspendAll(currentActivity: Activity): SequencingResult {\n    const result = new SequencingResult();\n\n    // Cannot suspend root\n    if (currentActivity === this.activityTree.root) {\n      result.exception = \"SB.2.15-1\";\n      return result;\n    }\n\n    // Suspend the current activity\n    currentActivity.isSuspended = true;\n    this.activityTree.suspendedActivity = currentActivity;\n    this.activityTree.currentActivity = null;\n\n    return result;\n  }\n\n  /**\n   * Terminate descendent attempts with exit rule evaluation\n   * @param {Activity} activity - The activity\n   * @param {boolean} skipExitRules - Whether to skip exit rules\n   */\n  public terminateDescendentAttempts(\n    activity: Activity,\n    skipExitRules: boolean = false\n  ): void {\n    // Apply Exit Action Rules (TB.2.1)\n    let exitAction = null;\n    if (!skipExitRules) {\n      exitAction = this.ruleEngine.evaluateExitRules(activity);\n    }\n\n    // End attempt on the activity\n    activity.isActive = false;\n\n    // Recursively terminate descendants\n    for (const child of activity.children) {\n      this.terminateDescendentAttempts(child, skipExitRules);\n    }\n\n    // Process deferred exit actions\n    if (exitAction && !skipExitRules) {\n      this.processDeferredExitAction(exitAction, activity);\n    }\n  }\n\n  /**\n   * Process deferred exit action\n   * @param {RuleActionType} exitAction - The exit action\n   * @param {Activity} activity - The activity\n   */\n  private processDeferredExitAction(exitAction: RuleActionType, activity: Activity): void {\n    switch (exitAction) {\n      case RuleActionType.EXIT:\n        // Already handled by terminateDescendentAttempts\n        break;\n\n      case RuleActionType.EXIT_PARENT:\n        if (activity.parent && activity.parent.isActive) {\n          this.terminateDescendentAttempts(activity.parent, true);\n        }\n        break;\n\n      case RuleActionType.EXIT_ALL:\n        if (this.activityTree.root && this.activityTree.root !== activity) {\n          const allActivities = this.activityTree.getAllActivities();\n          const anyActive = allActivities.some((a) => a.isActive);\n          if (anyActive) {\n            this.terminateDescendentAttempts(this.activityTree.root, true);\n          }\n        }\n        break;\n    }\n  }\n}\n","import { Activity } from \"../activity\";\nimport { ActivityTree } from \"../activity_tree\";\nimport { FlowTraversalService } from \"../traversal/flow_traversal_service\";\nimport {\n  SequencingResult,\n  DeliveryRequestType\n} from \"../rules/sequencing_request_types\";\n\n/**\n * RetryRequestHandler - Handles retry sequencing requests\n *\n * This handler manages:\n * - RETRY: Retry the current activity\n * - RETRY_ALL: Retry from the beginning\n */\nexport class RetryRequestHandler {\n  constructor(\n    private activityTree: ActivityTree,\n    private traversalService: FlowTraversalService\n  ) {}\n\n  /**\n   * Retry Sequencing Request Process (SB.2.10)\n   * @param {Activity} currentActivity - The current activity\n   * @return {SequencingResult}\n   * @spec SN Book: SB.2.10 step 3 (Retry Sequencing Request Process) - apply Flow once to a cluster and preserve its failure.\n   */\n  public handleRetry(currentActivity: Activity): SequencingResult {\n    const result = new SequencingResult();\n\n    // SB.2.10 step 2: Check if activity is still active or suspended\n    if (currentActivity.isActive || currentActivity.isSuspended) {\n      result.exception = \"SB.2.10-2\";\n      return result;\n    }\n\n    // SB.2.10 step 3: If current activity is not a leaf (is a cluster)\n    // @spec SN Book: SB.2.10 step 3; SB.2.2 steps 3, 5.1 - only Skip may advance past a candidate within the retried cluster.\n    if (currentActivity.children.length > 0) {\n      const flowResult = this.traversalService.findFirstDeliverableActivityResult(\n        currentActivity,\n        currentActivity,\n      );\n\n      // @spec SN Book: SB.2.10 step 3.2 - preserve the Flow Subprocess exception when present.\n      if (!flowResult.deliverable || !flowResult.identifiedActivity) {\n        result.exception = flowResult.exception || \"SB.2.10-3\";\n        return result;\n      }\n\n      // SB.2.10 step 3.3: Deliver the activity identified by flow subprocess\n      result.deliveryRequest = DeliveryRequestType.DELIVER;\n      result.targetActivity = flowResult.identifiedActivity;\n      return result;\n    }\n\n    // SB.2.10 step 4: Activity is a leaf - terminate and deliver it again\n    this.terminateDescendentAttempts(currentActivity);\n\n    // Deliver the activity again\n    result.deliveryRequest = DeliveryRequestType.DELIVER;\n    result.targetActivity = currentActivity;\n    return result;\n  }\n\n  /**\n   * Retry All Sequencing Request Process\n   * Clears current activity and restarts from the root\n   * @return {SequencingResult}\n   * @spec SN Book: SB.2.10; SB.2.5 steps 3.2, 3.2.1 - restart with one Forward Flow Subprocess and retain its exception.\n   */\n  public handleRetryAll(): SequencingResult {\n    // Clear current activity to allow restart\n    this.activityTree.currentActivity = null;\n\n    // Find first deliverable activity from root\n    if (!this.activityTree.root) {\n      const result = new SequencingResult();\n      result.exception = \"SB.2.10-1\";\n      return result;\n    }\n\n    const flowResult = this.traversalService.findFirstDeliverableActivityResult(\n      this.activityTree.root,\n    );\n\n    const result = new SequencingResult();\n    // @spec SN Book: SB.2.10 step 3.2; SB.2.2 step 5.1 - report blocked flow instead of trying a later child.\n    if (!flowResult.deliverable || !flowResult.identifiedActivity) {\n      result.exception = flowResult.exception || \"SB.2.10-3\";\n      return result;\n    }\n\n    result.deliveryRequest = DeliveryRequestType.DELIVER;\n    result.targetActivity = flowResult.identifiedActivity;\n    return result;\n  }\n\n  /**\n   * Terminate descendent attempts (simplified)\n   * @param {Activity} activity - The activity\n   */\n  private terminateDescendentAttempts(activity: Activity): void {\n    activity.isActive = false;\n    for (const child of activity.children) {\n      this.terminateDescendentAttempts(child);\n    }\n  }\n}\n","import { DeliveryValidator } from \"./validation/delivery_validator\";\nimport { Activity } from \"./activity\";\nimport { ActivityTree } from \"./activity_tree\";\nimport { SequencingRules, RuleActionType, RuleCondition } from \"./sequencing_rules\";\nimport { SequencingControls } from \"./sequencing_controls\";\nimport { ADLNav } from \"../adl\";\n\n// Import extracted services\nimport { ActivityTreeQueries } from \"./utils/activity_tree_queries\";\nimport { ChoiceConstraintValidator } from \"./validators/choice_constraint_validator\";\nimport { RuleEvaluationEngine } from \"./rules/rule_evaluation_engine\";\nimport type { PostConditionResult } from \"./rules/rule_evaluation_engine\";\nimport { FlowTraversalService } from \"./traversal/flow_traversal_service\";\nimport {\n  FlowRequestHandler,\n  ChoiceRequestHandler,\n  ExitRequestHandler,\n  RetryRequestHandler,\n} from \"./handlers\";\nimport {\n  SequencingRequestType,\n  DeliveryRequestType,\n  SequencingResult,\n} from \"./rules/sequencing_request_types\";\n\n// Re-export types for backward compatibility\nexport { SequencingRequestType, DeliveryRequestType, SequencingResult };\n\n/**\n * Result of Post-Condition Rule Evaluation (TB.2.2)\n * Re-exported for backward compatibility\n */\nexport type { PostConditionResult };\n\n/**\n * Options for SequencingProcess\n */\nexport interface SequencingProcessOptions {\n  now?: () => Date;\n  getAttemptElapsedSeconds?: (activity: Activity) => number;\n  getActivityElapsedSeconds?: (activity: Activity) => number;\n}\n\n/**\n * SequencingProcess - Refactored as a coordinator\n *\n * This class has been refactored from 3,036 lines and 66 methods to ~200 lines\n * by extracting functionality into focused, single-responsibility modules:\n *\n * - ActivityTreeQueries: Tree traversal and query utilities\n * - ChoiceConstraintValidator: Choice constraint validation (consolidated from 5 duplicated places)\n * - RuleEvaluationEngine: Sequencing rule evaluation\n * - FlowTraversalService: Flow-based tree traversal\n * - FlowRequestHandler: START, RESUME_ALL, CONTINUE, PREVIOUS requests\n * - ChoiceRequestHandler: CHOICE, JUMP requests\n * - ExitRequestHandler: EXIT, EXIT_ALL, ABANDON, ABANDON_ALL, SUSPEND_ALL requests\n * - RetryRequestHandler: RETRY, RETRY_ALL requests\n *\n * Benefits:\n * - Single source of truth for constraint validation\n * - Improved testability (unit tests per module)\n * - Better maintainability\n * - Reduced cognitive load\n */\nexport class SequencingProcess {\n  private activityTree: ActivityTree;\n\n  // Extracted services\n  private treeQueries: ActivityTreeQueries;\n  private constraintValidator: ChoiceConstraintValidator;\n  private ruleEngine: RuleEvaluationEngine;\n  private traversalService: FlowTraversalService;\n  private activityEvaluationCallback:\n    | ((activity: Activity, target: Activity) => Activity)\n    | null = null;\n\n  // Request handlers\n  private flowHandler: FlowRequestHandler;\n  private choiceHandler: ChoiceRequestHandler;\n  private exitHandler: ExitRequestHandler;\n  private retryHandler: RetryRequestHandler;\n\n  // Time function (exposed for testing)\n  private _now: () => Date;\n\n  /**\n   * Get/set the current time function (used for testing time-dependent logic)\n   */\n  public get now(): () => Date {\n    return this._now;\n  }\n\n  public set now(fn: () => Date) {\n    this._now = fn;\n    // Update the static RuleCondition time provider for condition evaluation\n    RuleCondition.setNowProvider(fn);\n    // Update the rule engine with the new time function\n    this.ruleEngine = new RuleEvaluationEngine({\n      now: fn,\n      getAttemptElapsedSecondsHook: this._getAttemptElapsedSecondsHook,\n    });\n    // Recreate traversal service with updated rule engine\n    this.traversalService = new FlowTraversalService(this.activityTree, this.ruleEngine);\n    this.applyTraversalCallbacks();\n    // Update handlers that depend on traversal service\n    this.flowHandler = new FlowRequestHandler(this.activityTree, this.traversalService);\n    this.choiceHandler = new ChoiceRequestHandler(\n      this.activityTree,\n      this.constraintValidator,\n      this.traversalService,\n      this.treeQueries,\n      () => this.now,\n      () => this.getAttemptElapsedSecondsHook,\n    );\n    this.retryHandler = new RetryRequestHandler(this.activityTree, this.traversalService);\n    this.exitHandler = new ExitRequestHandler(this.activityTree, this.ruleEngine);\n  }\n\n  private _getAttemptElapsedSecondsHook: ((activity: Activity) => number) | undefined;\n\n  /**\n   * Get/set the elapsed seconds hook (used for time-based rules)\n   */\n  // Null, not undefined, so RuleCondition.evaluate skips another process's static hook.\n  public get getAttemptElapsedSecondsHook(): ((activity: Activity) => number) | null {\n    return this._getAttemptElapsedSecondsHook ?? null;\n  }\n\n  public set getAttemptElapsedSecondsHook(fn: ((activity: Activity) => number) | undefined) {\n    this._getAttemptElapsedSecondsHook = fn;\n    // Update the static RuleCondition elapsed seconds hook\n    RuleCondition.setElapsedSecondsHook(fn);\n    // Update the rule engine\n    this.ruleEngine = new RuleEvaluationEngine({\n      now: this._now,\n      getAttemptElapsedSecondsHook: fn,\n    });\n    // Recreate traversal service with updated rule engine\n    this.traversalService = new FlowTraversalService(this.activityTree, this.ruleEngine);\n    this.applyTraversalCallbacks();\n    // Update handlers that depend on traversal service\n    this.flowHandler = new FlowRequestHandler(this.activityTree, this.traversalService);\n    this.choiceHandler = new ChoiceRequestHandler(\n      this.activityTree,\n      this.constraintValidator,\n      this.traversalService,\n      this.treeQueries,\n      () => this.now,\n      () => this.getAttemptElapsedSecondsHook,\n    );\n    this.retryHandler = new RetryRequestHandler(this.activityTree, this.traversalService);\n    this.exitHandler = new ExitRequestHandler(this.activityTree, this.ruleEngine);\n  }\n\n  constructor(\n    activityTree: ActivityTree,\n    _sequencingRules?: SequencingRules | null,\n    _sequencingControls?: SequencingControls | null,\n    _adlNav: ADLNav | null = null,\n    options?: SequencingProcessOptions,\n  ) {\n    this.activityTree = activityTree;\n\n    // Store options for later use\n    this._now = options?.now || (() => new Date());\n    this._getAttemptElapsedSecondsHook = options?.getAttemptElapsedSeconds;\n\n    // Initialize extracted services\n    this.treeQueries = new ActivityTreeQueries(activityTree);\n    this.ruleEngine = new RuleEvaluationEngine({\n      now: this._now,\n      getAttemptElapsedSecondsHook: this._getAttemptElapsedSecondsHook,\n    });\n    this.constraintValidator = new ChoiceConstraintValidator(activityTree, this.treeQueries);\n    this.traversalService = new FlowTraversalService(activityTree, this.ruleEngine);\n\n    // Initialize request handlers with dependencies\n    this.flowHandler = new FlowRequestHandler(activityTree, this.traversalService);\n    this.choiceHandler = new ChoiceRequestHandler(\n      activityTree,\n      this.constraintValidator,\n      this.traversalService,\n      this.treeQueries,\n      () => this.now,\n      () => this.getAttemptElapsedSecondsHook,\n    );\n    this.exitHandler = new ExitRequestHandler(activityTree, this.ruleEngine);\n    this.retryHandler = new RetryRequestHandler(activityTree, this.traversalService);\n  }\n\n  /**\n   * Main Sequencing Request Process (SB.2.12)\n   * This is the main entry point for all navigation requests\n   * @param {SequencingRequestType} request - The sequencing request\n   * @param {string | null} targetActivityId - Target activity ID (for CHOICE and JUMP)\n   * @return {SequencingResult}\n   */\n  public sequencingRequestProcess(\n    request: SequencingRequestType,\n    targetActivityId: string | null = null,\n  ): SequencingResult {\n    const currentActivity = this.activityTree.currentActivity;\n\n    switch (request) {\n      case SequencingRequestType.START:\n        return this.flowHandler.handleStart();\n\n      case SequencingRequestType.RESUME_ALL:\n        return this.flowHandler.handleResumeAll();\n\n      case SequencingRequestType.CONTINUE:\n        if (!currentActivity) {\n          return new SequencingResult(DeliveryRequestType.DO_NOT_DELIVER, null, \"SB.2.12-1\");\n        }\n        return this.flowHandler.handleContinue(currentActivity);\n\n      case SequencingRequestType.PREVIOUS:\n        if (!currentActivity) {\n          return new SequencingResult(DeliveryRequestType.DO_NOT_DELIVER, null, \"SB.2.12-1\");\n        }\n        return this.flowHandler.handlePrevious(currentActivity);\n\n      case SequencingRequestType.CHOICE:\n        if (!targetActivityId) {\n          return new SequencingResult(DeliveryRequestType.DO_NOT_DELIVER, null, \"SB.2.12-5\");\n        }\n        return this.choiceHandler.handleChoice(targetActivityId, currentActivity);\n\n      case SequencingRequestType.JUMP:\n        if (!targetActivityId) {\n          return new SequencingResult(DeliveryRequestType.DO_NOT_DELIVER, null, \"SB.2.12-5\");\n        }\n        return this.choiceHandler.handleJump(targetActivityId);\n\n      case SequencingRequestType.EXIT:\n        if (!currentActivity) {\n          return new SequencingResult(DeliveryRequestType.DO_NOT_DELIVER, null, \"SB.2.12-1\");\n        }\n        return this.exitHandler.handleExit(currentActivity);\n\n      case SequencingRequestType.EXIT_ALL:\n        if (!currentActivity) {\n          return new SequencingResult(DeliveryRequestType.DO_NOT_DELIVER, null, \"SB.2.12-1\");\n        }\n        return this.exitHandler.handleExitAll();\n\n      case SequencingRequestType.ABANDON:\n        if (!currentActivity) {\n          return new SequencingResult(DeliveryRequestType.DO_NOT_DELIVER, null, \"SB.2.12-1\");\n        }\n        return this.exitHandler.handleAbandon(currentActivity);\n\n      case SequencingRequestType.ABANDON_ALL:\n        if (!currentActivity) {\n          return new SequencingResult(DeliveryRequestType.DO_NOT_DELIVER, null, \"SB.2.12-1\");\n        }\n        return this.exitHandler.handleAbandonAll();\n\n      case SequencingRequestType.SUSPEND_ALL:\n        if (!currentActivity) {\n          return new SequencingResult(DeliveryRequestType.DO_NOT_DELIVER, null, \"SB.2.12-1\");\n        }\n        return this.exitHandler.handleSuspendAll(currentActivity);\n\n      case SequencingRequestType.RETRY:\n        if (!currentActivity) {\n          return new SequencingResult(DeliveryRequestType.DO_NOT_DELIVER, null, \"SB.2.12-1\");\n        }\n        return this.retryHandler.handleRetry(currentActivity);\n\n      case SequencingRequestType.RETRY_ALL:\n        return this.retryHandler.handleRetryAll();\n\n      default:\n        return new SequencingResult(DeliveryRequestType.DO_NOT_DELIVER, null, \"SB.2.12-6\");\n    }\n  }\n\n  /**\n   * Evaluate post-condition rules for the current activity\n   * @param {Activity} activity - The activity to evaluate\n   * @return {PostConditionResult} - The post-condition result\n   */\n  public evaluatePostConditionRules(activity: Activity): PostConditionResult {\n    return this.ruleEngine.evaluatePostConditions(activity);\n  }\n\n  /**\n   * Check if an activity can be delivered\n   * @param {Activity} activity - The activity to check\n   * @return {boolean} - True if the activity can be delivered\n   */\n  public canActivityBeDelivered(activity: Activity): boolean {\n    return this.traversalService.canDeliver(activity);\n  }\n\n  /**\n   * Validate navigation request before expensive operations\n   * @param {SequencingRequestType} request - The navigation request\n   * @param {string | null} targetActivityId - Target activity ID\n   * @param {Activity | null} currentActivity - Current activity\n   * @return {{valid: boolean, exception: string | null}} - Validation result\n   */\n  public validateNavigationRequest(\n    request: SequencingRequestType,\n    targetActivityId: string | null = null,\n    currentActivity: Activity | null = null,\n  ): { valid: boolean; exception: string | null } {\n    // Basic request type validation\n    const validRequestTypes = Object.values(SequencingRequestType);\n    if (!validRequestTypes.includes(request)) {\n      return { valid: false, exception: \"SB.2.12-6\" };\n    }\n\n    // Validate based on request type\n    switch (request) {\n      case SequencingRequestType.CONTINUE:\n      case SequencingRequestType.PREVIOUS: {\n        if (!currentActivity) {\n          return { valid: false, exception: \"SB.2.12-1\" };\n        }\n        if (currentActivity.isActive) {\n          return {\n            valid: false,\n            exception: request === SequencingRequestType.CONTINUE ? \"SB.2.7-1\" : \"SB.2.8-1\",\n          };\n        }\n        if (currentActivity.parent && !currentActivity.parent.sequencingControls.flow) {\n          return {\n            valid: false,\n            exception: request === SequencingRequestType.CONTINUE ? \"SB.2.7-2\" : \"SB.2.8-2\",\n          };\n        }\n        if (request === SequencingRequestType.PREVIOUS) {\n          const forwardOnlyViolation =\n            this.constraintValidator.checkForwardOnlyViolation(currentActivity);\n          if (!forwardOnlyViolation.valid) {\n            return forwardOnlyViolation;\n          }\n        }\n        break;\n      }\n\n      case SequencingRequestType.CHOICE: {\n        if (!targetActivityId) {\n          return { valid: false, exception: \"SB.2.12-5\" };\n        }\n        const targetActivity = this.activityTree.getActivity(targetActivityId);\n        if (!targetActivity) {\n          return { valid: false, exception: \"SB.2.9-1\" };\n        }\n        const choiceValidation = this.constraintValidator.validateChoice(\n          currentActivity,\n          targetActivity,\n          { checkAvailability: true },\n        );\n        if (!choiceValidation.valid) {\n          return choiceValidation;\n        }\n        if (!this.traversalService.canDeliver(targetActivity)) {\n          return { valid: false, exception: \"SB.2.9-6\" };\n        }\n        // Check for hiddenFromChoice precondition rule\n        const preConditionResult = this.ruleEngine.checkSequencingRules(\n          targetActivity,\n          targetActivity.sequencingRules.preConditionRules,\n        );\n        if (preConditionResult === RuleActionType.HIDE_FROM_CHOICE) {\n          return { valid: false, exception: \"SB.2.9-4\" };\n        }\n        break;\n      }\n\n      case SequencingRequestType.JUMP: {\n        if (!targetActivityId) {\n          return { valid: false, exception: \"SB.2.12-5\" };\n        }\n        const jumpTarget = this.activityTree.getActivity(targetActivityId);\n        if (!jumpTarget) {\n          return { valid: false, exception: \"SB.2.13-1\" };\n        }\n        if (!this.treeQueries.isInTree(jumpTarget)) {\n          return { valid: false, exception: \"SB.2.13-2\" };\n        }\n        if (!jumpTarget.isAvailable) {\n          return { valid: false, exception: \"SB.2.13-3\" };\n        }\n        if (jumpTarget.children.length > 0) {\n          return { valid: false, exception: \"DB.1.1-1\" };\n        }\n        // Reuse delivery checks without firing limit-check events during prediction.\n        const validator = new DeliveryValidator(\n          this.activityTree,\n          null,\n          { now: () => this.now() },\n          () => this.ruleEngine,\n        );\n        for (let activity: Activity | null = jumpTarget; activity; activity = activity.parent) {\n          const evaluationActivity = this.traversalService.getActivityForEvaluation(activity, jumpTarget);\n          if (!validator.checkActivity(activity, evaluationActivity, false)) {\n            return { valid: false, exception: \"DB.1.1-3\" };\n          }\n        }\n        break;\n      }\n\n      default:\n        break;\n    }\n\n    return { valid: true, exception: null };\n  }\n\n  /**\n   * Get all available activities that can be selected via choice navigation\n   * @return {Activity[]} - Array of activities available for choice\n   */\n  public getAvailableChoices(): Activity[] {\n    return this.choiceHandler.getAvailableChoices();\n  }\n\n  // Expose services for advanced use cases\n  public getTreeQueries(): ActivityTreeQueries {\n    return this.treeQueries;\n  }\n\n  public getConstraintValidator(): ChoiceConstraintValidator {\n    return this.constraintValidator;\n  }\n\n  public getRuleEngine(): RuleEvaluationEngine {\n    return this.ruleEngine;\n  }\n\n  public getTraversalService(): FlowTraversalService {\n    return this.traversalService;\n  }\n\n  /** @spec SCORM 2004 SN 4th Ed. SB.2.2 / SB.2.9 / SM.7 - candidate evaluation uses a disposable objective view. */\n  public setActivityEvaluationCallback(\n    callback: (activity: Activity, target: Activity) => Activity,\n  ): void {\n    this.activityEvaluationCallback = callback;\n    this.applyTraversalCallbacks();\n  }\n\n  private applyTraversalCallbacks(): void {\n    if (this.activityEvaluationCallback) {\n      this.traversalService.setActivityEvaluationCallback(this.activityEvaluationCallback);\n    }\n  }\n}\n","import { getDeliveryGeneration } from \"../cmi/scorm2004/sequencing/delivery_generation\";\nimport { Activity } from \"../cmi/scorm2004/sequencing/activity\";\nimport {\n  SequencingResult,\n  DeliveryRequestType,\n} from \"../cmi/scorm2004/sequencing/sequencing_process\";\nimport { EventService } from \"./EventService\";\nimport { LoggingService } from \"./LoggingService\";\nimport { IEventService, ILoggingService } from \"../interfaces/services\";\n\n/**\n * Interface for activity delivery callbacks\n */\nexport interface ActivityDeliveryCallbacks {\n  onDeliverActivity?: (activity: Activity) => void;\n  onUnloadActivity?: (activity: Activity) => void;\n  onSequencingComplete?: (result: SequencingResult) => void;\n  onSequencingError?: (error: string) => void;\n}\n\n/**\n * Service for managing activity delivery in SCORM 2004\n */\nexport class ActivityDeliveryService {\n  private eventService: IEventService;\n  private loggingService: ILoggingService;\n  private callbacks: ActivityDeliveryCallbacks;\n  private currentDeliveredActivity: Activity | null = null;\n  private currentDeliveredAttemptCount: number | null = null;\n  private currentDeliveredGeneration: number | null = null;\n  private pendingDelivery: Activity | null = null;\n\n  constructor(\n    eventService: IEventService,\n    loggingService: ILoggingService,\n    callbacks: ActivityDeliveryCallbacks = {},\n  ) {\n    this.eventService = eventService;\n    this.loggingService = loggingService;\n    this.callbacks = callbacks;\n  }\n\n  /**\n   * Process a sequencing result and handle activity delivery\n   * @param {SequencingResult} result - The sequencing result to process\n   */\n  public processSequencingResult(result: SequencingResult): void {\n    // Log the sequencing result\n    if (result.exception) {\n      this.loggingService.error(`Sequencing error: ${result.exception}`);\n      this.callbacks.onSequencingError?.(result.exception);\n      return;\n    }\n\n    // Handle delivery request\n    if (result.deliveryRequest === DeliveryRequestType.DELIVER && result.targetActivity) {\n      this.deliverActivity(result.targetActivity);\n    } else {\n      // No delivery requested\n      this.loggingService.info(\"Sequencing completed with no delivery request\");\n    }\n\n    // Notify sequencing complete\n    this.callbacks.onSequencingComplete?.(result);\n  }\n\n  /**\n   * Unload the previous content and notify the host once per DB.2 delivery,\n   * including resumed deliveries of the same attempt. Duplicate processing is skipped.\n   * @param {Activity} activity - The activity to deliver\n   */\n  private deliverActivity(activity: Activity): void {\n    const generation = getDeliveryGeneration(activity);\n    // @spec SCORM 2004 4th Ed. SN DB.2: every delivery launches content, including\n    // a resumed attempt (SCORM 2004 4th Ed. RTE 4.2.7: entry=resume). Only skip\n    // repeated processing when no new DB.2 delivery has occurred.\n    if (\n      this.currentDeliveredActivity === activity &&\n      this.currentDeliveredAttemptCount === activity.attemptCount &&\n      this.currentDeliveredGeneration === generation\n    ) {\n      this.loggingService.info(`Skipping delivery - activity already delivered: ${activity.id}`);\n      return;\n    }\n\n    // Host contract: release the previously delivered content before announcing the new\n    // delivery. This also applies when DB.2 resumes the same activity's attempt, because the\n    // host must relaunch its content (SCORM 2004 4th Ed. RTE 4.2.7: entry=resume).\n    if (this.currentDeliveredActivity) {\n      this.unloadActivity(this.currentDeliveredActivity);\n    }\n\n    // Mark the activity as pending delivery\n    this.pendingDelivery = activity;\n\n    // Log delivery\n    this.loggingService.info(`Delivering activity: ${activity.id} - ${activity.title}`);\n\n    // Publish the delivery state before either callback or event observers run. Generic\n    // ActivityDelivery listeners may inspect both the activity and this service's state.\n    this.currentDeliveredActivity = activity;\n    this.currentDeliveredAttemptCount = activity.attemptCount;\n    this.currentDeliveredGeneration = generation;\n    this.pendingDelivery = null;\n    activity.isActive = true;\n\n    // Let API-owned delivery bookkeeping install the new activity's launch-static state before\n    // generic ActivityDelivery observers inspect the public API model.\n    this.callbacks.onDeliverActivity?.(activity);\n\n    // Fire delivery event\n    this.eventService.processListeners(\"ActivityDelivery\", activity.id, activity);\n  }\n\n  /**\n   * Unload an activity\n   * @param {Activity} activity - The activity to unload\n   */\n  private unloadActivity(activity: Activity): void {\n    // Log unload\n    this.loggingService.info(`Unloading activity: ${activity.id} - ${activity.title}`);\n\n    // Fire unload event\n    this.eventService.processListeners(\"ActivityUnload\", activity.id, activity);\n\n    // Call unload callback\n    this.callbacks.onUnloadActivity?.(activity);\n\n    // Mark activity as inactive\n    activity.isActive = false;\n  }\n\n  /**\n   * Get the currently delivered activity\n   * @return {Activity | null}\n   */\n  public getCurrentDeliveredActivity(): Activity | null {\n    return this.currentDeliveredActivity;\n  }\n\n  /**\n   * Get the pending delivery activity\n   * @return {Activity | null}\n   */\n  public getPendingDelivery(): Activity | null {\n    return this.pendingDelivery;\n  }\n\n  /**\n   * Update delivery callbacks\n   * @param {ActivityDeliveryCallbacks} callbacks - The new callbacks\n   */\n  public updateCallbacks(callbacks: ActivityDeliveryCallbacks): void {\n    this.callbacks = { ...this.callbacks, ...callbacks };\n  }\n\n  /**\n   * Reset the delivery service\n   */\n  public reset(): void {\n    if (this.currentDeliveredActivity) {\n      this.unloadActivity(this.currentDeliveredActivity);\n    }\n    this.currentDeliveredActivity = null;\n    this.currentDeliveredAttemptCount = null;\n    this.currentDeliveredGeneration = null;\n    this.pendingDelivery = null;\n  }\n}\n","import { CommitMetadata, CommitObject, InternalSettings, ResultObject } from \"../types/api_types\";\nimport { global_constants } from \"../constants/api_constants\";\nimport { LogLevelEnum } from \"../constants/enums\";\nimport { IHttpService } from \"../interfaces/services\";\nimport { ErrorCode } from \"../constants/error_codes\";\nimport { isCorsSafelistedContentType, isCrossOriginUrl, StringKeyMap } from \"../utilities\";\n\n/**\n * Service for handling asynchronous HTTP communication with the LMS\n * WARNING: Not SCORM-compliant - always returns immediate success\n *\n * Subclasses inherit reportsRequestCompletion = true. An override of processHttpRequest must\n * therefore forward onRequestComplete to the asynchronous work, or at minimum forward\n * processListeners so the eventual CommitSuccess or CommitError event can settle the request.\n */\nexport class AsynchronousHttpService implements IHttpService {\n  readonly reportsRequestCompletion = true;\n\n  private settings: InternalSettings;\n  private error_codes: ErrorCode;\n\n  /**\n   * Constructor for AsynchronousHttpService\n   * @param {Settings} settings - The settings object\n   * @param {ErrorCode} error_codes - The error codes object\n   */\n  constructor(settings: InternalSettings, error_codes: ErrorCode) {\n    this.settings = settings;\n    this.error_codes = error_codes;\n  }\n\n  /**\n   * Sends HTTP requests asynchronously to the LMS\n   * Returns immediate success - actual result handled via events\n   *\n   * WARNING: This is NOT SCORM-compliant. Always returns optimistic success immediately.\n   * The actual HTTP request happens in the background, and success/failure is reported\n   * via CommitSuccess/CommitError events, but NOT to the SCO's commit call.\n   *\n   * @param {string} url - The URL endpoint to send the request to\n   * @param {CommitObject|StringKeyMap|Array} params - The data to send to the LMS\n   * @param {boolean} immediate - Whether to send the request immediately without waiting\n   * @param {Function} apiLog - Function to log API messages with appropriate levels\n   * @param {Function} processListeners - Function to trigger event listeners for commit events\n   * @param {CommitMetadata} metadata - Metadata describing the captured commit\n   * @param {Function} onRequestComplete - Callback invoked after the background request settles\n   * @return {ResultObject} - Immediate optimistic success result\n   */\n  processHttpRequest(\n    url: string,\n    params: CommitObject | StringKeyMap | Array<any>,\n    immediate: boolean = false,\n    apiLog: (\n      functionName: string,\n      message: any,\n      messageLevel: LogLevelEnum,\n      CMIElement?: string,\n    ) => void,\n    processListeners: (functionName: string, CMIElement?: string, value?: any) => void,\n    metadata?: CommitMetadata,\n    onRequestComplete?: () => void,\n  ): ResultObject {\n    // Fire request in background - don't wait for result\n    void this._performAsyncRequest(\n      url,\n      params,\n      immediate,\n      apiLog,\n      processListeners,\n      metadata,\n      onRequestComplete,\n    );\n\n    // Immediately return optimistic success\n    return {\n      result: global_constants.SCORM_TRUE,\n      errorCode: 0,\n    };\n  }\n\n  /**\n   * Performs the async request in the background\n   * @param {string} url - The URL to send the request to\n   * @param {CommitObject|StringKeyMap|Array} params - The parameters to include in the request\n   * @param {boolean} immediate - Whether this is an immediate request\n   * @param apiLog - Function to log API messages\n   * @param {Function} processListeners - Function to process event listeners\n   * @param {CommitMetadata} metadata - Metadata describing the captured commit\n   * @param {Function} onRequestComplete - Callback invoked after the request settles\n   * @private\n   */\n  private async _performAsyncRequest(\n    url: string,\n    params: CommitObject | StringKeyMap | Array<any>,\n    immediate: boolean,\n    apiLog: (\n      functionName: string,\n      message: any,\n      messageLevel: LogLevelEnum,\n      CMIElement?: string,\n    ) => void,\n    processListeners: (functionName: string, CMIElement?: string, value?: any) => void,\n    metadata?: CommitMetadata,\n    onRequestComplete?: () => void,\n  ): Promise<void> {\n    try {\n      const handledParams =\n        metadata === undefined\n          ? this.settings.requestHandler(params)\n          : this.settings.requestHandler(params, metadata);\n      const processedParams = handledParams as CommitObject | StringKeyMap | Array<any>;\n\n      let response: Response;\n      if (immediate && this.settings.asyncModeBeaconBehavior !== \"never\") {\n        response = await this.performBeacon(url, processedParams);\n      } else {\n        response = await this.performFetch(url, processedParams);\n      }\n\n      const result = await this.transformResponse(response, processListeners);\n\n      // Trigger listeners based on actual result (after API method returns)\n      if (this._isSuccessResponse(response, result)) {\n        processListeners(\"CommitSuccess\");\n      } else {\n        processListeners(\"CommitError\", undefined, result.errorCode);\n      }\n    } catch (e: unknown) {\n      const message = e instanceof Error ? e.message : String(e);\n      apiLog(\"processHttpRequest\", `Async request failed: ${message}`, LogLevelEnum.ERROR);\n      processListeners(\"CommitError\", undefined, this.error_codes.GENERAL_COMMIT_FAILURE || 391);\n    } finally {\n      onRequestComplete?.();\n    }\n  }\n\n  /**\n   * Prepares the request body and content type based on params type\n   * @param {CommitObject|StringKeyMap|Array} params - The parameters to include in the request\n   * @return {Object} - Object containing body and contentType\n   * @private\n   */\n  private _prepareRequestBody(params: CommitObject | StringKeyMap | Array<any>): {\n    body: string;\n    contentType: string;\n  } {\n    const body = params instanceof Array ? params.join(\"&\") : JSON.stringify(params);\n    const contentType =\n      params instanceof Array\n        ? \"application/x-www-form-urlencoded\"\n        : this.settings.commitRequestDataType;\n\n    return { body, contentType };\n  }\n\n  /**\n   * Perform the fetch request to the LMS\n   * @param {string} url - The URL to send the request to\n   * @param {StringKeyMap|Array} params - The parameters to include in the request\n   * @return {Promise<Response>} - The response from the LMS\n   * @private\n   */\n  private async performFetch(url: string, params: StringKeyMap | Array<any>): Promise<Response> {\n    // Use Beacon API if specified in settings\n    if (this.settings.asyncModeBeaconBehavior === \"always\") {\n      return this.performBeacon(url, params);\n    }\n\n    return this._sendFetch(url, params);\n  }\n\n  /**\n   * Send the request to the LMS with fetch\n   * @param {string} url - The URL to send the request to\n   * @param {StringKeyMap|Array} params - The parameters to include in the request\n   * @return {Promise<Response>} - The response from the LMS\n   * @private\n   */\n  private _sendFetch(url: string, params: StringKeyMap | Array<any>): Promise<Response> {\n    const { body, contentType } = this._prepareRequestBody(params);\n    const init = {\n      method: \"POST\",\n      mode: this.settings.fetchMode,\n      body,\n      headers: {\n        ...this.settings.xhrHeaders,\n        \"Content-Type\": contentType,\n      },\n      keepalive: true,\n    } as RequestInit;\n\n    if (this.settings.xhrWithCredentials) {\n      init.credentials = \"include\";\n    }\n\n    return fetch(url, init);\n  }\n\n  /**\n   * Perform the beacon request to the LMS\n   * @param {string} url - The URL to send the request to\n   * @param {StringKeyMap|Array} params - The parameters to include in the request\n   * @return {Promise<Response>} - A promise that resolves with a mock Response object\n   * @private\n   */\n  private async performBeacon(url: string, params: StringKeyMap | Array<any>): Promise<Response> {\n    // Browsers without sendBeacon (such as IE11) send the commit with fetch instead. This calls\n    // _sendFetch, not performFetch, which calls back here when asyncModeBeaconBehavior is \"always\".\n    if (typeof navigator === \"undefined\" || typeof navigator.sendBeacon !== \"function\") {\n      return this._sendFetch(url, params);\n    }\n\n    const { body, contentType } = this._prepareRequestBody(params);\n    const beaconContentType = Array.isArray(params)\n      ? contentType\n      : this.settings.terminationCommitContentType;\n    this._warnIfBeaconContentTypeUnsafe(url, beaconContentType);\n\n    // Send the beacon request\n    const beaconSuccess = navigator.sendBeacon(url, new Blob([body], { type: beaconContentType }));\n\n    // Create a mock Response object since sendBeacon doesn't return a Response\n    return Promise.resolve({\n      status: beaconSuccess ? 200 : 0,\n      ok: beaconSuccess,\n      json: async () => ({\n        result: beaconSuccess ? \"true\" : \"false\",\n        errorCode: beaconSuccess ? 0 : this.error_codes.GENERAL_COMMIT_FAILURE || 391,\n      }),\n      text: async () =>\n        JSON.stringify({\n          result: beaconSuccess ? \"true\" : \"false\",\n          errorCode: beaconSuccess ? 0 : this.error_codes.GENERAL_COMMIT_FAILURE || 391,\n        }),\n    } as Response);\n  }\n\n  private _warnIfBeaconContentTypeUnsafe(url: string, contentType: string): void {\n    if (isCrossOriginUrl(url) && !isCorsSafelistedContentType(contentType)) {\n      this.settings.onLogMessage?.(\n        LogLevelEnum.WARN,\n        `sendBeacon to cross-origin URL with non-CORS-safelisted Content-Type \"${contentType}\" ` +\n          `may be silently dropped by the browser (Beacon cannot preflight). Use fetch ` +\n          `(useAsynchronousCommits + asyncModeBeaconBehavior:\"never\") for cross-origin JSON/auth on terminate.`,\n      );\n    }\n  }\n\n  /**\n   * Transforms the response from the LMS to a ResultObject\n   * @param {Response} response - The response from the LMS\n   * @param {Function} processListeners - Function to process event listeners\n   * @return {Promise<ResultObject>} - The transformed response\n   * @private\n   */\n  private async transformResponse(\n    response: Response,\n    processListeners: (functionName: string, CMIElement?: string, value?: any) => void,\n  ): Promise<ResultObject> {\n    let result: any;\n\n    try {\n      // Parse the response using the configured handler or default to json\n      result =\n        typeof this.settings.responseHandler === \"function\"\n          ? await this.settings.responseHandler(response)\n          : await response.json();\n    } catch (parseError) {\n      // If we can't parse the response, log the raw response for debugging\n      const responseText = await response.text().catch(() => \"Unable to read response text\");\n\n      // SECURITY NOTE: Error details include response text truncated to 500 chars.\n      // In production environments with untrusted LMS responses, consider:\n      // 1. Further limiting responseText length or omitting it entirely\n      // 2. Sanitizing responseText to remove PII, credentials, or sensitive data\n      // 3. Using a custom responseHandler to pre-sanitize before this point\n      // 4. Implementing server-side log filtering to prevent sensitive data leakage\n      //\n      // This detailed error information is valuable for debugging integration issues,\n      // but may expose internal LMS details or error messages to client-side code.\n      // Balance security concerns with debugging needs based on your deployment model.\n      return {\n        result: global_constants.SCORM_FALSE,\n        errorCode: this.error_codes.GENERAL_COMMIT_FAILURE || 391,\n        errorMessage: `Failed to parse LMS response: ${parseError instanceof Error ? parseError.message : String(parseError)}`,\n        errorDetails: JSON.stringify({\n          status: response.status,\n          statusText: response.statusText,\n          url: response.url,\n          responseText: responseText.substring(0, 500), // Limit response text to avoid huge logs\n          parseError: parseError instanceof Error ? parseError.message : String(parseError),\n        }),\n      };\n    }\n\n    // Ensure result has an errorCode property\n    if (!Object.hasOwnProperty.call(result, \"errorCode\")) {\n      result.errorCode = this._isSuccessResponse(response, result)\n        ? 0\n        : this.error_codes.GENERAL_COMMIT_FAILURE || 391;\n    }\n\n    // Add response details for failed requests\n    if (!this._isSuccessResponse(response, result)) {\n      result.errorDetails = {\n        status: response.status,\n        statusText: response.statusText,\n        url: response.url,\n        ...result.errorDetails, // Preserve any existing error details\n      };\n    }\n\n    // Note: Event triggering is handled by _performAsyncRequest\n    return result;\n  }\n\n  /**\n   * Determines if a response is successful based on status code and result\n   * @param {Response} response - The HTTP response\n   * @param {ResultObject} result - The parsed result object\n   * @return {boolean} - Whether the response is successful\n   * @private\n   */\n  private _isSuccessResponse(response: Response, result: ResultObject): boolean {\n    const value = (result as any).result;\n    return (\n      response.status >= 200 &&\n      response.status <= 299 &&\n      (value === true || value === \"true\" || value === global_constants.SCORM_TRUE)\n    );\n  }\n\n  /**\n   * Updates the service settings\n   * @param {Settings} settings - The new settings\n   */\n  updateSettings(settings: InternalSettings): void {\n    this.settings = settings;\n  }\n}\n","import { BaseCMI } from \"../cmi/common/base_cmi\";\nimport { CMIArray } from \"../cmi/common/array\";\nimport { global_constants, LogLevelEnum } from \"../constants\";\nimport { StringKeyMap, stringMatches } from \"../utilities\";\nimport { ErrorCode } from \"../constants/error_codes\";\n\n/** Prefix for SCORM 2004 target attribute syntax */\nconst TARGET_ATTRIBUTE_PREFIX = \"{target=\";\n\n/**\n * Helper function to safely get an error code with validation.\n * Returns the error code value, or falls back to GENERAL error code if key is missing.\n * Logs a warning for unknown keys to help catch typos during development.\n */\nfunction getErrorCode(errorCodes: ErrorCode, key: string): number {\n  const code = errorCodes[key];\n  if (code === undefined) {\n    // Log warning in development to catch typos in error code keys\n    if (typeof console !== \"undefined\" && console.warn) {\n      console.warn(`CMIValueAccessService: Unknown error code key: ${key}`);\n    }\n    return errorCodes[\"GENERAL\"] ?? 0;\n  }\n  return code;\n}\n\n/**\n * Context interface for CMI value access operations.\n *\n * Provides callbacks to the API for error handling, validation, and data model access.\n * All callbacks are invoked synchronously during CMI path traversal.\n * Error states should be communicated through the API's error handling mechanism\n * (throwSCORMError and setLastErrorCode).\n *\n * @remarks\n * This interface enables dependency injection, making the CMIValueAccessService\n * testable in isolation without requiring a full API instance.\n */\nexport interface CMIValueAccessContext {\n  /** Error codes for the API (SCORM 1.2 or 2004) */\n  readonly errorCodes: ErrorCode;\n\n  /** Get the last error code as a string */\n  getLastErrorCode: () => string;\n\n  /** Set the last error code */\n  setLastErrorCode: (errorCode: string) => void;\n\n  /** Throw a SCORM error - sets error code and optionally logs diagnostic info */\n  throwSCORMError: (element: string, errorCode: number, message?: string) => void;\n\n  /** Check if the API is initialized (LMSInitialize/Initialize called) */\n  isInitialized: () => boolean;\n\n  /** Validate a correct response value for SCORM 2004 interactions */\n  validateCorrectResponse: (CMIElement: string, value: string) => void;\n\n  /** Check for duplicate IDs in objective collections */\n  checkForDuplicateId: (CMIElement: string, value: string) => boolean;\n\n  /** Get or create a child element for array operations */\n  getChildElement: (CMIElement: string, value: string, foundFirstIndex: boolean) => BaseCMI | null;\n\n  /** Log an API message at the specified level */\n  apiLog: (methodName: string, message: string, level: LogLevelEnum) => void;\n\n  /** Check if an object has a property (safe prototype-aware check) */\n  checkObjectHasProperty: (obj: StringKeyMap, attr: string) => boolean;\n\n  /** Get the CMI/ADL data model root object */\n  getDataModel: () => StringKeyMap;\n}\n\n/**\n * CMIValueAccessService\n *\n * Handles the complex traversal logic for getting and setting CMI values.\n * Extracted from BaseAPI to reduce god class complexity.\n *\n * Responsibilities:\n * - Navigate CMI element paths (e.g., \"cmi.objectives.0.id\")\n * - Handle array indexing and dynamic child creation\n * - Validate element paths and handle errors\n * - Support both SCORM 1.2 and SCORM 2004 data models\n */\nexport class CMIValueAccessService {\n  private context: CMIValueAccessContext;\n\n  constructor(context: CMIValueAccessContext) {\n    this.context = context;\n  }\n\n  /**\n   * Gets the appropriate error code for undefined data model elements.\n   * Both SCORM 2004 and SCORM 1.2 use UNDEFINED_DATA_MODEL (401): an\n   * unrecognized element is \"Not implemented\", not a general exception. SCORM\n   * 1.2 previously returned GENERAL (101) here, which is non-conformant — the\n   * ADL 1.2 CTS and the SCORM 1.2 RTE spec expect 401 for an unknown element.\n   */\n  private getUndefinedDataModelErrorCode(): number {\n    return getErrorCode(this.context.errorCodes, \"UNDEFINED_DATA_MODEL\");\n  }\n\n  /**\n   * Sets a value on a CMI element path\n   *\n   * @param {string} methodName - The API method name for logging\n   * @param {boolean} scorm2004 - Whether this is SCORM 2004\n   * @param {string} CMIElement - The CMI element path\n   * @param {string} value - The value to set (all SCORM values are strings)\n   * @return {string} \"true\" or \"false\"\n   */\n  setCMIValue(methodName: string, scorm2004: boolean, CMIElement: string, value: string): string {\n    if (!CMIElement || CMIElement === \"\") {\n      if (scorm2004) {\n        this.context.throwSCORMError(\n          CMIElement,\n          getErrorCode(this.context.errorCodes, \"GENERAL_SET_FAILURE\"),\n          \"The data model element was not specified\",\n        );\n      }\n      return global_constants.SCORM_FALSE;\n    }\n\n    this.context.setLastErrorCode(\"0\");\n\n    const structure = splitCMIElement(CMIElement);\n    let refObject: StringKeyMap | BaseCMI = this.context.getDataModel();\n    let returnValue = global_constants.SCORM_FALSE;\n    let foundFirstIndex = false;\n\n    const invalidErrorMessage = `The data model element passed to ${methodName} (${CMIElement}) is not a valid SCORM data model element.`;\n    const invalidErrorCode = this.getUndefinedDataModelErrorCode();\n\n    for (let idx = 0; idx < structure.length; idx++) {\n      const attribute = structure[idx]!;\n\n      if (idx === structure.length - 1) {\n        // Final attribute - set the value\n        returnValue = this.setFinalAttribute(\n          refObject,\n          attribute,\n          value,\n          CMIElement,\n          scorm2004,\n          invalidErrorCode,\n          invalidErrorMessage,\n        );\n        break;\n      } else {\n        // Intermediate attribute - traverse\n        const traverseResult = this.traverseToNextLevel(\n          refObject,\n          structure,\n          idx,\n          value,\n          CMIElement,\n          scorm2004,\n          foundFirstIndex,\n          invalidErrorCode,\n          invalidErrorMessage,\n        );\n\n        if (traverseResult.error) {\n          break;\n        }\n\n        refObject = traverseResult.refObject;\n        idx = traverseResult.idx;\n        foundFirstIndex = traverseResult.foundFirstIndex;\n      }\n    }\n\n    if (returnValue === global_constants.SCORM_FALSE) {\n      this.context.apiLog(\n        methodName,\n        `There was an error setting the value for: ${CMIElement}, value of: ${value}`,\n        LogLevelEnum.WARN,\n      );\n    }\n\n    return returnValue;\n  }\n\n  /**\n   * Gets a value from a CMI element path\n   *\n   * @param {string} methodName - The API method name for logging\n   * @param {boolean} scorm2004 - Whether this is SCORM 2004\n   * @param {string} CMIElement - The CMI element path\n   * @return The value at the element path, or empty string on error (per SCORM spec)\n   */\n  getCMIValue(\n    methodName: string,\n    scorm2004: boolean,\n    CMIElement: string,\n  ): string | StringKeyMap | BaseCMI {\n    if (!CMIElement || CMIElement === \"\") {\n      if (scorm2004) {\n        this.context.throwSCORMError(\n          CMIElement,\n          getErrorCode(this.context.errorCodes, \"GENERAL_GET_FAILURE\"),\n          \"The data model element was not specified\",\n        );\n      }\n      return \"\";\n    }\n\n    // SCORM 2004: Validate ._version keyword usage - only valid on cmi._version\n    if (scorm2004 && CMIElement.endsWith(\"._version\") && CMIElement !== \"cmi._version\") {\n      this.context.throwSCORMError(\n        CMIElement,\n        getErrorCode(this.context.errorCodes, \"GENERAL_GET_FAILURE\"),\n        \"The _version keyword was used incorrectly\",\n      );\n      return \"\";\n    }\n\n    // Per IEEE 1484.11.2 / SCORM 2004 RTE, a GetValue resolves to a fresh error\n    // code: a successful read must end at \"0\" even if a prior call left a stale\n    // error. Reset here (mirroring setCMIValue) before resolving the element, so\n    // failures below still set their own code via throwSCORMError.\n    this.context.setLastErrorCode(\"0\");\n\n    const structure = splitCMIElement(CMIElement);\n    let refObject: StringKeyMap = this.context.getDataModel();\n    let attribute: string | null = null;\n    let foundFirstIndex = false;\n\n    const uninitializedErrorMessage = `The data model element passed to ${methodName} (${CMIElement}) has not been initialized.`;\n    const invalidErrorMessage = `The data model element passed to ${methodName} (${CMIElement}) is not a valid SCORM data model element.`;\n    const invalidErrorCode = this.getUndefinedDataModelErrorCode();\n\n    for (let idx = 0; idx < structure.length; idx++) {\n      attribute = structure[idx]!;\n\n      // Validate attribute existence\n      const validationResult = this.validateGetAttribute(\n        refObject,\n        attribute,\n        CMIElement,\n        scorm2004,\n        invalidErrorCode,\n        invalidErrorMessage,\n        idx === structure.length - 1,\n      );\n\n      if (validationResult.returnValue !== undefined) {\n        return validationResult.returnValue;\n      }\n\n      if (validationResult.error) {\n        return \"\";\n      }\n\n      // Traverse to the next level\n      if (attribute !== undefined && attribute !== null) {\n        refObject = refObject[attribute] as StringKeyMap;\n        if (refObject === undefined) {\n          this.context.throwSCORMError(CMIElement, invalidErrorCode, invalidErrorMessage);\n          break;\n        }\n      } else {\n        this.context.throwSCORMError(CMIElement, invalidErrorCode, invalidErrorMessage);\n        break;\n      }\n\n      // Handle array access\n      if (refObject instanceof CMIArray) {\n        const arrayResult = this.handleGetArrayAccess(\n          refObject,\n          structure,\n          idx,\n          CMIElement,\n          scorm2004,\n          foundFirstIndex,\n          uninitializedErrorMessage,\n        );\n\n        if (arrayResult.error) {\n          return \"\";\n        }\n\n        refObject = arrayResult.refObject;\n        idx = arrayResult.idx;\n        foundFirstIndex = arrayResult.foundFirstIndex;\n      }\n    }\n\n    if (refObject === null || refObject === undefined) {\n      if (!scorm2004) {\n        // SCORM 1.2: Use specific keyword error codes\n        if (attribute === \"_children\") {\n          this.context.throwSCORMError(\n            CMIElement,\n            getErrorCode(this.context.errorCodes, \"CHILDREN_ERROR\"),\n            undefined,\n          );\n        } else if (attribute === \"_count\") {\n          this.context.throwSCORMError(\n            CMIElement,\n            getErrorCode(this.context.errorCodes, \"COUNT_ERROR\"),\n            undefined,\n          );\n        }\n      }\n      // SCORM 2004 keyword errors are handled during traversal\n      return \"\";\n    }\n\n    return refObject;\n  }\n\n  /**\n   * Sets the final attribute value in the CMI path\n   */\n  private setFinalAttribute(\n    refObject: StringKeyMap | BaseCMI,\n    attribute: string,\n    value: string,\n    CMIElement: string,\n    scorm2004: boolean,\n    invalidErrorCode: number,\n    invalidErrorMessage: string,\n  ): string {\n    // Handle SCORM 2004 target attribute syntax: {target=identifier}\n    // Target attributes are used for global objective mapping and are read-only after initialization\n    if (scorm2004 && attribute?.startsWith(TARGET_ATTRIBUTE_PREFIX)) {\n      if (this.context.isInitialized()) {\n        this.context.throwSCORMError(\n          CMIElement,\n          getErrorCode(this.context.errorCodes, \"READ_ONLY_ELEMENT\"),\n        );\n        return global_constants.SCORM_FALSE;\n      }\n      // Request validity helpers accept validated LMS entries before initialization.\n      if (\"setStaticValue\" in refObject && typeof refObject.setStaticValue === \"function\") {\n        refObject.setStaticValue(attribute, value);\n      }\n      // Other target writes remain a no-op (targets are resolved during read).\n      return global_constants.SCORM_TRUE;\n    }\n\n    // Validate attribute exists\n    if (\n      typeof attribute === \"undefined\" ||\n      !this.context.checkObjectHasProperty(refObject as StringKeyMap, attribute)\n    ) {\n      this.context.throwSCORMError(CMIElement, invalidErrorCode, invalidErrorMessage);\n      return global_constants.SCORM_FALSE;\n    }\n\n    // Validate correct response\n    if (\n      stringMatches(CMIElement, \"\\\\.correct_responses\\\\.\\\\d+$\") &&\n      this.context.isInitialized() &&\n      attribute !== \"pattern\"\n    ) {\n      this.context.validateCorrectResponse(CMIElement, value);\n      if (this.context.getLastErrorCode() !== \"0\") {\n        this.context.throwSCORMError(\n          CMIElement,\n          getErrorCode(this.context.errorCodes, \"TYPE_MISMATCH\"),\n        );\n        return global_constants.SCORM_FALSE;\n      }\n    }\n\n    // Check for errors before setting\n    if (!scorm2004 || this.context.getLastErrorCode() === \"0\") {\n      // Validate attribute is safe\n      if (\n        typeof attribute === \"undefined\" ||\n        attribute === \"__proto__\" ||\n        attribute === \"constructor\"\n      ) {\n        this.context.throwSCORMError(CMIElement, invalidErrorCode, invalidErrorMessage);\n        return global_constants.SCORM_FALSE;\n      }\n\n      // SCORM 2004: Check for duplicate IDs in objective collections.\n      if (scorm2004 && attribute === \"id\" && this.context.isInitialized()) {\n        const duplicateError = this.context.checkForDuplicateId(CMIElement, value);\n        if (duplicateError) {\n          this.context.throwSCORMError(\n            CMIElement,\n            getErrorCode(this.context.errorCodes, \"GENERAL_SET_FAILURE\"),\n          );\n          return global_constants.SCORM_FALSE;\n        }\n      }\n\n      // Set the value\n      (refObject as StringKeyMap)[attribute] = value;\n      return global_constants.SCORM_TRUE;\n    }\n\n    return global_constants.SCORM_FALSE;\n  }\n\n  /**\n   * Traverses to the next level in the CMI path\n   */\n  private traverseToNextLevel(\n    refObject: StringKeyMap | BaseCMI,\n    structure: string[],\n    idx: number,\n    value: string,\n    CMIElement: string,\n    scorm2004: boolean,\n    foundFirstIndex: boolean,\n    invalidErrorCode: number,\n    invalidErrorMessage: string,\n  ): { refObject: StringKeyMap | BaseCMI; idx: number; foundFirstIndex: boolean; error: boolean } {\n    const attribute = structure[idx];\n\n    if (\n      typeof attribute === \"undefined\" ||\n      !this.context.checkObjectHasProperty(refObject as StringKeyMap, attribute)\n    ) {\n      this.context.throwSCORMError(CMIElement, invalidErrorCode, invalidErrorMessage);\n      return { refObject, idx, foundFirstIndex, error: true };\n    }\n\n    refObject = (refObject as StringKeyMap)[attribute] as StringKeyMap;\n    if (!refObject) {\n      this.context.throwSCORMError(CMIElement, invalidErrorCode, invalidErrorMessage);\n      return { refObject, idx, foundFirstIndex, error: true };\n    }\n\n    // Handle array access\n    if (refObject instanceof CMIArray) {\n      const arrayResult = this.handleSetArrayAccess(\n        refObject,\n        structure,\n        idx,\n        value,\n        CMIElement,\n        scorm2004,\n        foundFirstIndex,\n        invalidErrorCode,\n        invalidErrorMessage,\n      );\n\n      if (arrayResult.error) {\n        return { refObject, idx, foundFirstIndex, error: true };\n      }\n\n      return arrayResult;\n    }\n\n    return { refObject, idx, foundFirstIndex, error: false };\n  }\n\n  /**\n   * Handles array access during set operations\n   */\n  private handleSetArrayAccess(\n    refObject: CMIArray,\n    structure: string[],\n    idx: number,\n    value: string,\n    CMIElement: string,\n    scorm2004: boolean,\n    foundFirstIndex: boolean,\n    invalidErrorCode: number,\n    invalidErrorMessage: string,\n  ): { refObject: StringKeyMap | BaseCMI; idx: number; foundFirstIndex: boolean; error: boolean } {\n    const index = parseInt(structure[idx + 1] || \"0\", 10);\n\n    if (!isNaN(index)) {\n      const item = refObject.childArray[index];\n\n      if (item) {\n        return {\n          refObject: item,\n          idx: idx + 1,\n          foundFirstIndex: true,\n          error: false,\n        };\n      } else {\n        // SCORM spec requires sequential array indices\n        if (index > refObject.childArray.length) {\n          const errorCode = scorm2004\n            ? getErrorCode(this.context.errorCodes, \"GENERAL_SET_FAILURE\")\n            : getErrorCode(this.context.errorCodes, \"ARGUMENT_ERROR\");\n          this.context.throwSCORMError(\n            CMIElement,\n            errorCode,\n            `Cannot set array element at index ${index}. Array indices must be sequential. Current array length is ${refObject.childArray.length}, expected index ${refObject.childArray.length}.`,\n          );\n          return { refObject, idx, foundFirstIndex, error: true };\n        }\n\n        // Create new child element\n        const newChild = this.context.getChildElement(CMIElement, value, foundFirstIndex);\n\n        if (!newChild) {\n          if (this.context.getLastErrorCode() === \"0\") {\n            this.context.throwSCORMError(CMIElement, invalidErrorCode, invalidErrorMessage);\n          }\n          return { refObject, idx, foundFirstIndex, error: true };\n        } else {\n          if (refObject.initialized) newChild.initialize();\n          refObject.childArray[index] = newChild;\n          return {\n            refObject: newChild,\n            idx: idx + 1,\n            foundFirstIndex: true,\n            error: false,\n          };\n        }\n      }\n    }\n\n    return { refObject, idx, foundFirstIndex, error: false };\n  }\n\n  /**\n   * Validates an attribute during get operations\n   */\n  private validateGetAttribute(\n    refObject: StringKeyMap,\n    attribute: string,\n    CMIElement: string,\n    scorm2004: boolean,\n    invalidErrorCode: number,\n    invalidErrorMessage: string,\n    isFinalAttribute: boolean,\n  ): { error: boolean; returnValue?: any } {\n    if (!scorm2004) {\n      if (isFinalAttribute) {\n        if (\n          typeof attribute === \"undefined\" ||\n          !this.context.checkObjectHasProperty(refObject, attribute)\n        ) {\n          if (attribute === \"_children\") {\n            this.context.throwSCORMError(\n              CMIElement,\n              getErrorCode(this.context.errorCodes, \"CHILDREN_ERROR\"),\n            );\n          } else if (attribute === \"_count\") {\n            this.context.throwSCORMError(\n              CMIElement,\n              getErrorCode(this.context.errorCodes, \"COUNT_ERROR\"),\n            );\n          } else {\n            this.context.throwSCORMError(CMIElement, invalidErrorCode, invalidErrorMessage);\n          }\n          return { error: true };\n        }\n      }\n    } else {\n      // Handle SCORM 2004 target validation\n      const attrStr = String(attribute);\n      if (\n        attrStr.startsWith(TARGET_ATTRIBUTE_PREFIX) &&\n        typeof refObject._isTargetValid == \"function\"\n      ) {\n        const target = attrStr.substring(TARGET_ATTRIBUTE_PREFIX.length, attrStr.length - 1);\n        return { error: false, returnValue: refObject._isTargetValid(target) };\n      } else if (\n        typeof attribute === \"undefined\" ||\n        !this.context.checkObjectHasProperty(refObject, attribute)\n      ) {\n        // Check for keyword errors with specific diagnostics\n        if (attribute === \"_children\") {\n          this.context.throwSCORMError(\n            CMIElement,\n            getErrorCode(this.context.errorCodes, \"GENERAL_GET_FAILURE\"),\n            \"The data model element does not have children\",\n          );\n          return { error: true };\n        } else if (attribute === \"_count\") {\n          this.context.throwSCORMError(\n            CMIElement,\n            getErrorCode(this.context.errorCodes, \"GENERAL_GET_FAILURE\"),\n            \"The data model element is not a collection and therefore does not have a count\",\n          );\n          return { error: true };\n        }\n        this.context.throwSCORMError(CMIElement, invalidErrorCode, invalidErrorMessage);\n        return { error: true };\n      }\n    }\n\n    return { error: false };\n  }\n\n  /**\n   * Handles array access during get operations\n   */\n  private handleGetArrayAccess(\n    refObject: CMIArray,\n    structure: string[],\n    idx: number,\n    CMIElement: string,\n    scorm2004: boolean,\n    foundFirstIndex: boolean,\n    uninitializedErrorMessage: string,\n  ): {\n    refObject: StringKeyMap;\n    idx: number;\n    foundFirstIndex: boolean;\n    error: boolean;\n  } {\n    const index = parseInt(structure[idx + 1] || \"\", 10);\n\n    if (!isNaN(index)) {\n      const item = refObject.childArray[index];\n\n      // A readable record exists only when the requested index is within _count.\n      // Never construct a data-bearing child for an out-of-range read: constructor\n      // defaults would be indistinguishable from persisted learner data.\n      if (index < refObject.childArray.length && item) {\n        return {\n          refObject: item as unknown as StringKeyMap,\n          idx: idx + 1,\n          foundFirstIndex: true,\n          error: false,\n        };\n      } else if (scorm2004) {\n        this.context.throwSCORMError(\n          CMIElement,\n          getErrorCode(this.context.errorCodes, \"VALUE_NOT_INITIALIZED\"),\n          uninitializedErrorMessage,\n        );\n        return {\n          refObject: refObject as unknown as StringKeyMap,\n          idx,\n          foundFirstIndex,\n          error: true,\n        };\n      } else {\n        const collectionPath = structure.slice(0, idx + 1).join(\".\");\n        const interactionSubcollectionCount =\n          collectionPath === \"cmi.interactions\" &&\n          index === refObject.childArray.length &&\n          /^cmi\\.interactions\\.\\d+\\.(objectives|correct_responses)\\._count$/.test(CMIElement);\n\n        if (interactionSubcollectionCount) {\n          // ADL sco07.htm expects an implemented interaction subcollection count\n          // to read as zero even when the interaction record does not yet exist.\n          const child = this.context.getChildElement(CMIElement, \"\", foundFirstIndex);\n          if (child) {\n            if (refObject.initialized) child.initialize();\n            return {\n              refObject: child as unknown as StringKeyMap,\n              idx: idx + 1,\n              foundFirstIndex: true,\n              error: false,\n            };\n          }\n        }\n\n        const interactionCollection =\n          collectionPath === \"cmi.interactions\" ||\n          /^cmi\\.interactions\\.\\d+\\.(objectives|correct_responses)$/.test(collectionPath);\n        // Interaction records and their nested entries are write-only (404).\n        // Readable objective records use 201, the collection argument error also\n        // used by ADL for an out-of-range SetValue.\n        this.context.throwSCORMError(\n          CMIElement,\n          getErrorCode(\n            this.context.errorCodes,\n            interactionCollection ? \"WRITE_ONLY_ELEMENT\" : \"ARGUMENT_ERROR\",\n          ),\n        );\n        return {\n          refObject: refObject as unknown as StringKeyMap,\n          idx,\n          foundFirstIndex,\n          error: true,\n        };\n      }\n    }\n\n    return {\n      refObject: refObject as unknown as StringKeyMap,\n      idx,\n      foundFirstIndex,\n      error: false,\n    };\n  }\n}\n\n/** Preserve periods within a trailing navigation target identifier. */\nfunction splitCMIElement(element: string): string[] {\n  const targetPath = element.match(/^(.*)\\.(\\{target=[^{}]*\\})$/);\n  return targetPath ? [...targetPath[1]!.split(\".\"), targetPath[2]!] : element.split(\".\");\n}\n","import { LogLevel } from \"../types/api_types\";\nimport { LogLevelEnum } from \"../constants/enums\";\nimport { ILoggingService } from \"../interfaces/services\";\nimport { defaultLogHandler } from \"../constants/default_settings\";\n\n/**\n * Centralized logging service implemented as a singleton\n * Provides methods for logging at different levels and configuring the log level.\n * Supports custom log handlers via the `customLogHandler` setting to integrate with\n * external logging systems or implement custom logging behavior.\n */\nexport class LoggingService implements ILoggingService {\n  private static _instance: LoggingService;\n  private _logLevel: LogLevel = LogLevelEnum.ERROR;\n  private _logHandler: (messageLevel: LogLevel, logMessage: string) => void;\n\n  /**\n   * Private constructor to prevent direct instantiation\n   */\n  private constructor() {\n    // Default log handler uses console methods based on log level\n    this._logHandler = defaultLogHandler;\n  }\n\n  /**\n   * Get the singleton instance of LoggingService\n   *\n   * @returns {LoggingService} The singleton instance\n   */\n  public static getInstance(): LoggingService {\n    if (!LoggingService._instance) {\n      LoggingService._instance = new LoggingService();\n    }\n    return LoggingService._instance;\n  }\n\n  /**\n   * Set the log level\n   *\n   * @param {LogLevel} level - The log level to set\n   */\n  public setLogLevel(level: LogLevel): void {\n    this._logLevel = level;\n  }\n\n  /**\n   * Get the current log level\n   *\n   * @returns {LogLevel} The current log level\n   */\n  public getLogLevel(): LogLevel {\n    return this._logLevel;\n  }\n\n  /**\n   * Set a custom log handler\n   *\n   * @param {Function} handler - The function to handle log messages\n   */\n  public setLogHandler(handler: (messageLevel: LogLevel, logMessage: string) => void): void {\n    this._logHandler = handler;\n  }\n\n  /**\n   * Log a message if the message level is greater than or equal to the current log level\n   *\n   * @param {LogLevel} messageLevel - The level of the message\n   * @param {string} logMessage - The message to log\n   *\n   * @security LOG-INJECTION\n   * Be aware that logMessage is passed through to the log handler without sanitization.\n   * When logging user-controlled data (e.g., SCORM CMI values from content, URL parameters,\n   * postMessage payloads), consider the following risks:\n   *\n   * 1. Log injection: Malicious input containing newlines or ANSI codes could pollute logs\n   *    or create fake log entries that mislead security monitoring.\n   *\n   * 2. Information disclosure: Sensitive data in logs may be exposed to unauthorized viewers\n   *    with log access (developers, support staff, aggregation systems).\n   *\n   * 3. Log storage exhaustion: Extremely large or repeated values could fill disk space\n   *    or cause performance degradation in log processing systems.\n   *\n   * Defensive patterns:\n   * - Truncate long values before logging (e.g., logMessage.substring(0, 500))\n   * - Strip or escape newlines and control characters\n   * - Redact sensitive fields (PII, credentials, session tokens)\n   * - Implement custom log handlers that sanitize before writing to external systems\n   * - Use structured logging formats (JSON) that escape values properly\n   *\n   * Example of safe logging for user-controlled data:\n   * ```typescript\n   * const sanitized = userInput.replace(/[\\r\\n\\x00-\\x1F\\x7F]/g, '').substring(0, 200);\n   * loggingService.info(`User input: ${sanitized}`);\n   * ```\n   */\n  public log(messageLevel: LogLevel, logMessage: string): void {\n    if (this.shouldLog(messageLevel)) {\n      this._logHandler(messageLevel, logMessage);\n    }\n  }\n\n  /**\n   * Log a message at ERROR level\n   *\n   * @param {string} logMessage - The message to log\n   */\n  public error(logMessage: string): void {\n    this.log(LogLevelEnum.ERROR, logMessage);\n  }\n\n  /**\n   * Log a message at WARN level\n   *\n   * @param {string} logMessage - The message to log\n   */\n  public warn(logMessage: string): void {\n    this.log(LogLevelEnum.WARN, logMessage);\n  }\n\n  /**\n   * Log a message at INFO level\n   *\n   * @param {string} logMessage - The message to log\n   */\n  public info(logMessage: string): void {\n    this.log(LogLevelEnum.INFO, logMessage);\n  }\n\n  /**\n   * Log a message at DEBUG level\n   *\n   * @param {string} logMessage - The message to log\n   */\n  public debug(logMessage: string): void {\n    this.log(LogLevelEnum.DEBUG, logMessage);\n  }\n\n  /**\n   * Determine if a message should be logged based on its level and the current log level\n   *\n   * @param {LogLevel} messageLevel - The level of the message\n   * @returns {boolean} Whether the message should be logged\n   */\n  private shouldLog(messageLevel: LogLevel): boolean {\n    // Convert string levels to numbers for comparison\n    const numericMessageLevel = this.getNumericLevel(messageLevel);\n    const numericLogLevel = this.getNumericLevel(this._logLevel);\n\n    return numericMessageLevel >= numericLogLevel;\n  }\n\n  /**\n   * Convert a log level to its numeric value\n   *\n   * @param {LogLevel} level - The log level to convert\n   * @returns {number} The numeric value of the log level\n   */\n  private getNumericLevel(level: LogLevel): number {\n    if (level === undefined) return LogLevelEnum.NONE;\n\n    if (typeof level === \"number\") return level;\n\n    // Accept named levels in any case (e.g. \"debug\", \"Info\") — the public\n    // NamedLogLevel type documents uppercase, but tolerating common casings\n    // avoids silently coercing to ERROR when integrators pass lowercase.\n    const normalized = typeof level === \"string\" ? level.toUpperCase() : level;\n\n    switch (normalized) {\n      case \"1\":\n      case \"DEBUG\":\n        return LogLevelEnum.DEBUG;\n      case \"2\":\n      case \"INFO\":\n        return LogLevelEnum.INFO;\n      case \"3\":\n      case \"WARN\":\n        return LogLevelEnum.WARN;\n      case \"4\":\n      case \"ERROR\":\n        return LogLevelEnum.ERROR;\n      case \"5\":\n      case \"NONE\":\n        return LogLevelEnum.NONE;\n      default:\n        return LogLevelEnum.ERROR; // Default to ERROR if unknown\n    }\n  }\n}\n\n// Export a function to get the singleton instance\nexport function getLoggingService(): LoggingService {\n  return LoggingService.getInstance();\n}\n","import { LogLevelEnum } from \"../constants/enums\";\nimport { global_constants } from \"../constants/api_constants\";\nimport { ErrorCode } from \"../constants/error_codes\";\nimport { ValidationError } from \"../exceptions\";\nimport { IErrorHandlingService, ILoggingService } from \"../interfaces/services\";\nimport { LogLevel } from \"../types/api_types\";\nimport { getLoggingService } from \"./LoggingService\";\n\n/**\n * Service for handling SCORM errors\n */\nexport class ErrorHandlingService implements IErrorHandlingService {\n  private _lastErrorCode: string = \"0\";\n  private _lastDiagnostic: string = \"\";\n  private readonly _errorCodes: ErrorCode;\n  private readonly _apiLog: (\n    functionName: string,\n    message: string,\n    logLevel?: LogLevel,\n    CMIElement?: string,\n  ) => void;\n  private readonly _getLmsErrorMessageDetails: (errorCode: number, detail: boolean) => string;\n  private readonly _loggingService: ILoggingService;\n\n  /**\n   * Constructor for ErrorHandlingService\n   *\n   * @param {ErrorCode} errorCodes - The error codes object\n   * @param {Function} apiLog - Function for logging API calls\n   * @param {Function} getLmsErrorMessageDetails - Function for getting error message details\n   * @param {ILoggingService} loggingService - Optional logging service instance\n   */\n  constructor(\n    errorCodes: ErrorCode,\n    apiLog: (\n      functionName: string,\n      message: string,\n      logLevel?: LogLevel,\n      CMIElement?: string,\n    ) => void,\n    getLmsErrorMessageDetails: (errorCode: number, detail: boolean) => string,\n    loggingService?: ILoggingService,\n  ) {\n    this._errorCodes = errorCodes;\n    this._apiLog = apiLog;\n    this._getLmsErrorMessageDetails = getLmsErrorMessageDetails;\n    this._loggingService = loggingService || getLoggingService();\n  }\n\n  /**\n   * Get the last error code\n   *\n   * @return {string} - The last error code\n   */\n  get lastErrorCode(): string {\n    return this._lastErrorCode;\n  }\n\n  /**\n   * Set the last error code\n   *\n   * @param {string} errorCode - The error code to set\n   */\n  set lastErrorCode(errorCode: string) {\n    this._lastErrorCode = errorCode;\n  }\n\n  /**\n   * Get the last custom diagnostic message\n   *\n   * @return {string} - The last custom diagnostic message, or empty string if none\n   */\n  get lastDiagnostic(): string {\n    return this._lastDiagnostic;\n  }\n\n  /**\n   * Throws a SCORM error\n   *\n   * @param {string} CMIElement\n   * @param {number} errorNumber - The error number\n   * @param {string} message - The error message\n   * @throws {ValidationError} - If throwException is true, throws a ValidationError\n   */\n  throwSCORMError(\n    CMIElement: string | undefined,\n    errorNumber: number,\n    message?: string,\n    messageLevel: LogLevel = LogLevelEnum.ERROR,\n  ): void {\n    // Store custom diagnostic if provided, otherwise clear it\n    this._lastDiagnostic = message || \"\";\n\n    if (!message) {\n      message = this._getLmsErrorMessageDetails(errorNumber, true);\n    }\n\n    // Format a more descriptive error message with context\n    const formattedMessage = `SCORM Error ${errorNumber}: ${message}${CMIElement ? ` [Element: ${CMIElement}]` : \"\"}`;\n\n    // Log using both the API log and the logging service for consistency\n    this._apiLog(\"throwSCORMError\", errorNumber + \": \" + message, messageLevel, CMIElement);\n    this._loggingService.log(messageLevel, formattedMessage);\n\n    this._lastErrorCode = String(errorNumber);\n  }\n\n  /**\n   * Clears the last SCORM error code on success.\n   *\n   * @param {string} success - Whether the operation was successful\n   */\n  clearSCORMError(success: string): void {\n    if (success !== undefined && success !== global_constants.SCORM_FALSE) {\n      this._lastErrorCode = \"0\";\n    }\n  }\n\n  /**\n   * Handles exceptions that occur when accessing or setting CMI values.\n   *\n   * This method provides centralized error handling for exceptions that occur during\n   * CMI data operations. It differentiates between different types of errors and\n   * handles them appropriately:\n   *\n   * 1. ValidationError: These are expected errors from the validation system that\n   *    indicate a specific SCORM error condition (like invalid data format or range).\n   *    For these errors, the method:\n   *    - Sets the lastErrorCode to the error code from the ValidationError\n   *    - Returns SCORM_FALSE to indicate failure to the caller\n   *\n   * 2. Standard JavaScript Error: For general JavaScript errors (like TypeError,\n   *    ReferenceError, etc.), the method:\n   *    - Logs the error message with stack trace to the logging service\n   *    - Sets a general SCORM error\n   *    - Returns SCORM_FALSE to indicate failure\n   *\n   * 3. Unknown exceptions: For any other type of exception that doesn't match the\n   *    above categories, the method:\n   *    - Logs the entire exception object to the logging service\n   *    - Sets a general SCORM error\n   *    - Returns SCORM_FALSE to indicate failure\n   *\n   * This method is critical for maintaining SCORM compliance by ensuring that\n   * all errors are properly translated into the appropriate SCORM error codes.\n   *\n   * @param {string} CMIElement\n   * @param {ValidationError|Error|unknown} e - The exception that was thrown\n   * @param {string} returnValue - The default return value (typically an empty string)\n   * @return {string} - Either the original returnValue or SCORM_FALSE if an error occurred\n   *\n   * @example\n   * try {\n   *   const value = getCMIValue(\"cmi.core.score.raw\");\n   *   return value;\n   * } catch (e) {\n   *   return handleValueAccessException(e, \"\");\n   * }\n   */\n  handleValueAccessException(CMIElement: string, e: unknown, returnValue: string): string {\n    if (e instanceof ValidationError) {\n      const validationError = e as ValidationError;\n      this._lastErrorCode = String(validationError.errorCode);\n      this._lastDiagnostic = \"\";\n\n      // Log validation errors at WARN level with context\n      const errorMessage = `Validation Error ${validationError.errorCode}: ${validationError.message} [Element: ${CMIElement}]`;\n      this._loggingService.warn(errorMessage);\n\n      returnValue = global_constants.SCORM_FALSE;\n    } else if (e instanceof Error) {\n      // For standard JS errors, include the stack trace and error type\n      const errorType = e.constructor.name; // Gets the error type (e.g., TypeError, ReferenceError)\n      const errorMessage = `${errorType}: ${e.message} [Element: ${CMIElement}]`;\n      const stackTrace = e.stack || \"\";\n\n      // Log the detailed error with stack trace\n      this._loggingService.error(`${errorMessage}\\n${stackTrace}`);\n\n      this.throwSCORMError(\n        CMIElement,\n        this._errorCodes.GENERAL as number,\n        `${errorType}: ${e.message}`,\n      );\n\n      // SVC-ERR-01: Set returnValue to SCORM_FALSE for all error types\n      returnValue = global_constants.SCORM_FALSE;\n    } else {\n      // For unknown errors, provide as much context as possible\n      const errorMessage = `Unknown error occurred while accessing [Element: ${CMIElement}]`;\n\n      this._loggingService.error(errorMessage);\n\n      try {\n        // Try to stringify the error object for more details\n        const errorDetails = JSON.stringify(e);\n        this._loggingService.error(`Error details: ${errorDetails}`);\n      } catch (jsonError) {\n        // If stringify fails, log that we couldn't get more details\n        this._loggingService.error(\"Could not stringify error object for details\");\n      }\n\n      this.throwSCORMError(CMIElement, this._errorCodes.GENERAL as number, \"Unknown error\");\n\n      // SVC-ERR-01: Set returnValue to SCORM_FALSE for all error types\n      returnValue = global_constants.SCORM_FALSE;\n    }\n    return returnValue;\n  }\n\n  /**\n   * Get the error codes object\n   *\n   * @return {ErrorCode} - The error codes object\n   */\n  get errorCodes(): ErrorCode {\n    return this._errorCodes;\n  }\n}\n\n// Export a factory function to create the service\nexport function createErrorHandlingService(\n  errorCodes: ErrorCode,\n  apiLog: (functionName: string, message: string, logLevel?: LogLevel, CMIElement?: string) => void,\n  getLmsErrorMessageDetails: (errorCode: number, detail: boolean) => string,\n  loggingService?: ILoggingService,\n): ErrorHandlingService {\n  return new ErrorHandlingService(errorCodes, apiLog, getLmsErrorMessageDetails, loggingService);\n}\n","import { CommitEventContext, LogLevel } from \"../types/api_types\";\nimport { LogLevelEnum } from \"../constants/enums\";\nimport { IEventService, ScormEventCallback } from \"../interfaces/services\";\n\n/**\n * Interface for a listener object\n */\ninterface Listener {\n  functionName: string;\n  CMIElement: string | null;\n  callback: ScormEventCallback;\n}\n\n/**\n * Type for parsed listener information\n */\ninterface ParsedListener {\n  functionName: string;\n  CMIElement: string | null;\n}\n\n/**\n * Service for handling event listeners and event processing\n */\nexport class EventService implements IEventService {\n  // Map of function names to listeners for faster lookups\n  private listenerMap: Map<string, Listener[]> = new Map();\n  // Total count of listeners for logging\n  private listenerCount = 0;\n  // Function to log API messages\n  private readonly apiLog: (\n    functionName: string,\n    message: string,\n    messageLevel: LogLevel,\n    CMIElement?: string,\n  ) => void;\n\n  /**\n   * Constructor for EventService\n   * @param {Function} apiLog - Function to log API messages\n   */\n  constructor(\n    apiLog: (\n      functionName: string,\n      message: string,\n      messageLevel: LogLevel,\n      CMIElement?: string,\n    ) => void,\n  ) {\n    this.apiLog = apiLog;\n  }\n\n  /**\n   * Parses a listener name into its components\n   *\n   * @param {string} listenerName - The name of the listener\n   * @returns {ParsedListener|null} - The parsed listener information or null if invalid\n   */\n  private parseListenerName(listenerName: string): ParsedListener | null {\n    // SVC-EVT-01: Handle empty string input\n    if (!listenerName) return null;\n\n    const listenerSplit = listenerName.split(\".\");\n\n    const functionName = listenerSplit[0];\n    let CMIElement: string | null = null;\n\n    if (listenerSplit.length > 1) {\n      CMIElement = listenerName.replace(`${functionName}.`, \"\");\n    }\n\n    return { functionName: functionName ?? listenerName, CMIElement };\n  }\n\n  /**\n   * Provides a mechanism for attaching to a specific SCORM event\n   *\n   * @param {string} listenerName - The name of the listener\n   * @param {Function} callback - The callback function to execute when the event occurs\n   */\n  on(listenerName: string, callback: ScormEventCallback) {\n    if (!callback) return;\n\n    const listenerFunctions = listenerName.split(\" \");\n    for (const listenerFunction of listenerFunctions) {\n      const parsedListener = this.parseListenerName(listenerFunction);\n      if (!parsedListener) continue;\n\n      const { functionName, CMIElement } = parsedListener;\n\n      // Get or create the array for this function name\n      const listeners = this.listenerMap.get(functionName) ?? [];\n\n      // Add the new listener\n      listeners.push({\n        functionName,\n        CMIElement,\n        callback,\n      });\n\n      // Update the map and count\n      this.listenerMap.set(functionName, listeners);\n      this.listenerCount++;\n\n      this.apiLog(\n        \"on\",\n        `Added event listener: ${this.listenerCount}`,\n        LogLevelEnum.INFO,\n        functionName,\n      );\n    }\n  }\n\n  /**\n   * Provides a mechanism for detaching a specific SCORM event listener\n   *\n   * @param {string} listenerName - The name of the listener to remove\n   * @param {Function} callback - The callback function to remove\n   */\n  off(listenerName: string, callback: ScormEventCallback) {\n    if (!callback) return;\n\n    const listenerFunctions = listenerName.split(\" \");\n    for (const listenerFunction of listenerFunctions) {\n      const parsedListener = this.parseListenerName(listenerFunction);\n      if (!parsedListener) continue;\n\n      const { functionName, CMIElement } = parsedListener;\n\n      // Get the listeners for this function name\n      const listeners = this.listenerMap.get(functionName);\n      if (!listeners) continue;\n\n      // Find the index of the listener to remove\n      const removeIndex = listeners.findIndex(\n        (obj) => obj.CMIElement === CMIElement && obj.callback === callback,\n      );\n\n      if (removeIndex !== -1) {\n        // Remove the listener (modifies array in-place)\n        listeners.splice(removeIndex, 1);\n        this.listenerCount--;\n\n        // Remove the map entry if no listeners remain\n        // Note: No need to update the map otherwise, as we modified the array by reference\n        if (listeners.length === 0) {\n          this.listenerMap.delete(functionName);\n        }\n\n        this.apiLog(\n          \"off\",\n          `Removed event listener: ${this.listenerCount}`,\n          LogLevelEnum.INFO,\n          functionName,\n        );\n      }\n    }\n  }\n\n  /**\n   * Provides a mechanism for clearing all listeners from a specific SCORM event\n   *\n   * Note: clear() differs from off() in CMIElement matching behavior:\n   * - clear() with CMIElement=null removes ALL listeners for the function\n   * - off() requires exact CMIElement match AND callback match\n   * This allows clear() to remove all listeners at once, while off() is surgical.\n   *\n   * @param {string} listenerName - The name of the listener to clear\n   */\n  clear(listenerName: string) {\n    const listenerFunctions = listenerName.split(\" \");\n    for (const listenerFunction of listenerFunctions) {\n      const parsedListener = this.parseListenerName(listenerFunction);\n      if (!parsedListener) continue;\n\n      const { functionName, CMIElement } = parsedListener;\n\n      // If we have listeners for this function name\n      if (this.listenerMap.has(functionName)) {\n        const listeners = this.listenerMap.get(functionName)!;\n\n        // When CMIElement is null (no specific element provided), clear ALL listeners for this function.\n        // When CMIElement is specified, only clear listeners matching that exact CMIElement.\n        const newListeners =\n          CMIElement === null ? [] : listeners.filter((obj) => obj.CMIElement !== CMIElement);\n\n        // Update the count and map\n        this.listenerCount -= listeners.length - newListeners.length;\n\n        if (newListeners.length === 0) {\n          this.listenerMap.delete(functionName);\n        } else {\n          this.listenerMap.set(functionName, newListeners);\n        }\n      }\n    }\n  }\n\n  /**\n   * Processes any 'on' listeners that have been created\n   *\n   * @param {string} functionName - The name of the function that triggered the event\n   * @param {string} CMIElement - The CMI element that was affected\n   * @param {any} value - The value that was set\n   * @param {CommitEventContext} context - Optional context for commit lifecycle events\n   */\n  processListeners(\n    functionName: string,\n    CMIElement?: string,\n    value?: any,\n    context?: CommitEventContext,\n  ) {\n    this.apiLog(functionName, value, LogLevelEnum.INFO, CMIElement);\n\n    // Get listeners for this function name\n    const listeners = this.listenerMap.get(functionName);\n    if (!listeners) return;\n\n    for (const listener of listeners) {\n      const listenerHasCMIElement = !!listener.CMIElement;\n      let CMIElementsMatch = false;\n\n      // Match CMI elements: supports wildcard (*) for prefix matching or exact string comparison.\n      // Listeners with no CMIElement (null) match all events for this function.\n      if (CMIElement && listener.CMIElement) {\n        if (listener.CMIElement.endsWith(\"*\")) {\n          // For wildcard matches, check if the CMI element starts with the prefix\n          const prefix = listener.CMIElement.slice(0, -1);\n          CMIElementsMatch = CMIElement.startsWith(prefix);\n        } else {\n          // For exact matches, compare the strings directly\n          CMIElementsMatch = listener.CMIElement === CMIElement;\n        }\n      }\n\n      // If the listener matches, call the callback\n      if (!listenerHasCMIElement || CMIElementsMatch) {\n        this.apiLog(\n          \"processListeners\",\n          `Processing listener: ${listener.functionName}`,\n          LogLevelEnum.DEBUG,\n          CMIElement,\n        );\n\n        // Dispatch to callback with appropriate arguments based on event type\n        // Different event types have different callback signatures:\n        // - Sequence events: callback(target)\n        // - CommitError: callback(errorCode, context?)\n        // - CommitSuccess: callback(context?)\n        // - Regular events: callback(CMIElement, value)\n        if (functionName.startsWith(\"Sequence\")) {\n          // For sequence events, pass the target as the first argument\n          listener.callback(value);\n        } else if (functionName === \"CommitError\") {\n          // Keep the error code at argument zero and append context when available.\n          if (context !== undefined) {\n            listener.callback(value, context);\n          } else {\n            listener.callback(value);\n          }\n        } else if (functionName === \"CommitSuccess\") {\n          // Legacy listeners receive zero arguments when no context is available.\n          if (context !== undefined) {\n            listener.callback(context);\n          } else {\n            listener.callback();\n          }\n        } else {\n          // For regular events, pass CMIElement and value\n          listener.callback(CMIElement, value);\n        }\n      }\n    }\n  }\n\n  /**\n   * Resets the event service by clearing all listeners\n   */\n  reset() {\n    this.listenerMap.clear();\n    this.listenerCount = 0;\n  }\n}\n","import { CommitMetadata, CommitObject, InternalSettings, ResultObject } from \"../types/api_types\";\nimport { global_constants } from \"../constants/api_constants\";\nimport { LogLevelEnum } from \"../constants/enums\";\nimport { IHttpService } from \"../interfaces/services\";\nimport { ErrorCode } from \"../constants/error_codes\";\nimport { isCorsSafelistedContentType, isCrossOriginUrl, StringKeyMap } from \"../utilities\";\n\n/**\n * Service for handling synchronous HTTP communication with the LMS\n * Uses synchronous XMLHttpRequest for SCORM-compliant error reporting\n *\n * @spec SCORM 2004 RTE 4.1.7 - API calls must be synchronous\n * @spec SCORM 1.2 RTE 3.1.x - API calls must be synchronous\n */\nexport class SynchronousHttpService implements IHttpService {\n  private settings: InternalSettings;\n  private error_codes: ErrorCode;\n\n  /**\n   * Constructor for SynchronousHttpService\n   * @param {InternalSettings} settings - The settings object\n   * @param {ErrorCode} error_codes - The error codes object\n   */\n  constructor(settings: InternalSettings, error_codes: ErrorCode) {\n    this.settings = settings;\n    this.error_codes = error_codes;\n  }\n\n  /**\n   * Sends synchronous HTTP requests to the LMS\n   * @param {string} url - The URL endpoint to send the request to\n   * @param {CommitObject|StringKeyMap|Array} params - The data to send to the LMS\n   * @param {boolean} immediate - Whether this is a termination commit (use sendBeacon)\n   * @param {Function} _apiLog - Function to log API messages (unused in synchronous mode - errors returned directly)\n   * @param {Function} _processListeners - Function to trigger event listeners (unused in synchronous mode - no async events)\n   * @param {CommitMetadata} metadata - Metadata describing the captured commit\n   * @param {Function} _onRequestComplete - Completion callback (unused because requests settle before return)\n   * @return {ResultObject} - The result of the request (synchronous)\n   *\n   * @remarks\n   * The apiLog and processListeners parameters are part of the IHttpService interface contract\n   * but are not used by SynchronousHttpService because:\n   * - Synchronous XHR blocks until complete, so errors are returned directly to the caller\n   * - No async events need to be triggered (CommitSuccess/CommitError) since results are synchronous\n   * - AsynchronousHttpService uses these parameters to handle background request results\n   */\n  processHttpRequest(\n    url: string,\n    params: CommitObject | StringKeyMap | Array<any>,\n    immediate: boolean = false,\n    _apiLog: (\n      functionName: string,\n      message: any,\n      messageLevel: number,\n      CMIElement?: string,\n    ) => void,\n    _processListeners: (functionName: string, CMIElement?: string, value?: any) => void,\n    metadata?: CommitMetadata,\n    _onRequestComplete?: () => void,\n  ): ResultObject {\n    if (immediate) {\n      // Termination: use sendBeacon (fire-and-forget, best effort)\n      // @spec SCORM 2004 RTE 4.1.7 - API calls must be synchronous\n      return this._handleImmediateRequest(url, params, metadata);\n    }\n\n    // Standard commit: synchronous XHR (blocks until complete)\n    // @spec SCORM 2004 RTE 4.1.7 - API calls must be synchronous\n    return this._performSyncXHR(url, params, metadata);\n  }\n\n  /**\n   * Handles an immediate request using sendBeacon, or a synchronous XHR when sendBeacon is missing\n   * @param {string} url - The URL to send the request to\n   * @param {CommitObject|StringKeyMap|Array} params - The parameters to include in the request\n   * @param {CommitMetadata} metadata - Metadata describing the captured commit\n   * @return {ResultObject} - The result based on beacon success\n   * @private\n   */\n  private _handleImmediateRequest(\n    url: string,\n    params: CommitObject | StringKeyMap | Array<any>,\n    metadata?: CommitMetadata,\n  ): ResultObject {\n    // Browsers without sendBeacon (such as IE11) send the termination commit with a synchronous XHR.\n    if (typeof navigator === \"undefined\" || typeof navigator.sendBeacon !== \"function\") {\n      return this._performSyncXHR(url, params, metadata);\n    }\n\n    const handledPayload =\n      metadata === undefined\n        ? this.settings.requestHandler(params)\n        : this.settings.requestHandler(params, metadata);\n    const requestPayload = (handledPayload ?? params) as CommitObject | StringKeyMap | Array<any>;\n    const { body } = this._prepareRequestBody(requestPayload);\n    const beaconContentType = this.settings.terminationCommitContentType;\n    this._warnIfBeaconContentTypeUnsafe(url, beaconContentType);\n\n    // See terminationCommitContentType for the configurable Beacon Content-Type.\n    // @spec W3C Beacon - sendBeacon for reliable unload data transmission\n    const beaconSuccess = navigator.sendBeacon(url, new Blob([body], { type: beaconContentType }));\n\n    return {\n      result: beaconSuccess ? \"true\" : \"false\",\n      errorCode: beaconSuccess ? 0 : this.error_codes.GENERAL_COMMIT_FAILURE || 391,\n    };\n  }\n\n  private _warnIfBeaconContentTypeUnsafe(url: string, contentType: string): void {\n    if (isCrossOriginUrl(url) && !isCorsSafelistedContentType(contentType)) {\n      this.settings.onLogMessage?.(\n        LogLevelEnum.WARN,\n        `sendBeacon to cross-origin URL with non-CORS-safelisted Content-Type \"${contentType}\" ` +\n          `may be silently dropped by the browser (Beacon cannot preflight). Use fetch ` +\n          `(useAsynchronousCommits + asyncModeBeaconBehavior:\"never\") for cross-origin JSON/auth on terminate.`,\n      );\n    }\n  }\n\n  /**\n   * Performs a synchronous XMLHttpRequest\n   * @param {string} url - The URL to send the request to\n   * @param {CommitObject|StringKeyMap|Array} params - The parameters to include in the request\n   * @param {CommitMetadata} metadata - Metadata describing the captured commit\n   * @return {ResultObject} - The result of the request\n   * @private\n   */\n  private _performSyncXHR(\n    url: string,\n    params: CommitObject | StringKeyMap | Array<any>,\n    metadata?: CommitMetadata,\n  ): ResultObject {\n    const handledPayload =\n      metadata === undefined\n        ? this.settings.requestHandler(params)\n        : this.settings.requestHandler(params, metadata);\n    const requestPayload = (handledPayload ?? params) as CommitObject | StringKeyMap | Array<any>;\n    const { body, contentType } = this._prepareRequestBody(requestPayload);\n\n    const xhr = new XMLHttpRequest();\n    xhr.open(\"POST\", url, false); // false = synchronous!\n\n    // Set headers\n    xhr.setRequestHeader(\"Content-Type\", contentType);\n    Object.entries(this.settings.xhrHeaders).forEach(([key, value]) => {\n      xhr.setRequestHeader(key, String(value));\n    });\n\n    // Set credentials\n    if (this.settings.xhrWithCredentials) {\n      xhr.withCredentials = true;\n    }\n\n    try {\n      xhr.send(body);\n      return this.settings.xhrResponseHandler(xhr);\n    } catch (e) {\n      const message = e instanceof Error ? e.message : String(e);\n      return {\n        result: global_constants.SCORM_FALSE,\n        errorCode: this.error_codes.GENERAL_COMMIT_FAILURE || 391,\n        errorMessage: message,\n      };\n    }\n  }\n\n  performAsyncRequest(\n    url: string,\n    params: CommitObject | StringKeyMap | Array<any>,\n    metadata?: CommitMetadata,\n  ): Promise<ResultObject> {\n    return new Promise((resolve) => {\n      const failure = (error?: unknown) =>\n        resolve({\n          result: global_constants.SCORM_FALSE,\n          errorCode: this.error_codes.GENERAL_COMMIT_FAILURE || 391,\n          ...(error instanceof Error ? { errorMessage: error.message } : {}),\n        });\n      try {\n        const handledPayload =\n          metadata === undefined\n            ? this.settings.requestHandler(params)\n            : this.settings.requestHandler(params, metadata);\n        const requestPayload = (handledPayload ?? params) as\n          CommitObject | StringKeyMap | Array<any>;\n        const { body, contentType } = this._prepareRequestBody(requestPayload);\n        const xhr = new XMLHttpRequest();\n        xhr.open(\"POST\", url, true);\n        xhr.setRequestHeader(\"Content-Type\", contentType);\n        Object.entries(this.settings.xhrHeaders).forEach(([key, value]) => {\n          xhr.setRequestHeader(key, String(value));\n        });\n        if (this.settings.xhrWithCredentials) {\n          xhr.withCredentials = true;\n        }\n        xhr.onload = () => {\n          try {\n            resolve(this.settings.xhrResponseHandler(xhr));\n          } catch (error) {\n            failure(error);\n          }\n        };\n        xhr.onerror = () => failure();\n        xhr.ontimeout = () => failure();\n        xhr.send(body);\n      } catch (error) {\n        failure(error);\n      }\n    });\n  }\n\n  /**\n   * Prepares the request body and content type based on params type\n   * @param {CommitObject|StringKeyMap|Array} params - The parameters to include in the request\n   * @return {Object} - Object containing body and contentType\n   * @private\n   */\n  private _prepareRequestBody(params: CommitObject | StringKeyMap | Array<any>): {\n    body: string;\n    contentType: string;\n  } {\n    const body = params instanceof Array ? params.join(\"&\") : JSON.stringify(params);\n    const contentType =\n      params instanceof Array\n        ? \"application/x-www-form-urlencoded\"\n        : this.settings.commitRequestDataType;\n\n    return { body, contentType };\n  }\n\n  /**\n   * Updates the service settings\n   * @param {InternalSettings} settings - The new settings\n   */\n  updateSettings(settings: InternalSettings): void {\n    this.settings = settings;\n  }\n}\n","import { CommitObject, InternalSettings, ResultObject } from \"../types/api_types\";\nimport { global_constants } from \"../constants/api_constants\";\nimport { LogLevelEnum } from \"../constants/enums\";\nimport { ErrorCode } from \"../constants/error_codes\";\nimport { SynchronousHttpService } from \"./SynchronousHttpService\";\nimport { IHttpService } from \"../interfaces/services\";\nimport { appendQueryParam, StringKeyMap } from \"../utilities\";\n\ntype OfflinePayload = CommitObject | StringKeyMap | Array<any>;\n\ntype OfflineCommitMetadata = {\n  learnerId?: string;\n  isTerminateCommit?: boolean;\n  sequence?: number;\n};\n\n/**\n * Interface for sync queue item\n */\ninterface SyncQueueItem {\n  id: string;\n  courseId: string;\n  learnerId?: string;\n  timestamp: number;\n  data: OfflinePayload;\n  syncAttempts: number;\n  isTerminateCommit?: boolean;\n  sequence?: number;\n}\n\n/**\n * Service for handling offline storage and synchronization of SCORM data\n */\nexport class OfflineStorageService {\n  private settings: InternalSettings;\n  private error_codes: ErrorCode;\n  private storeName: string = \"scorm_again_offline_data\";\n  private syncQueue: string = \"scorm_again_sync_queue\";\n  private isOnline: boolean = navigator.onLine;\n  private syncInProgress: boolean = false;\n  private boundOnlineStatusChangeHandler: () => void;\n  private boundCustomNetworkStatusHandler: (event: Event) => void;\n\n  /**\n   * Constructor for OfflineStorageService\n   * @param {Settings} settings - The settings object\n   * @param {ErrorCode} error_codes - The error codes object\n   * @param {Function} apiLog - The logging function\n   */\n  constructor(\n    settings: InternalSettings,\n    error_codes: ErrorCode,\n    private apiLog: (\n      functionName: string,\n      message: any,\n      messageLevel: LogLevelEnum,\n      CMIElement?: string,\n    ) => void,\n    private httpService?: IHttpService,\n    private getLearnerId: () => string = () => \"\",\n    private processListeners: (event: string) => void = () => {},\n  ) {\n    this.settings = settings;\n    this.error_codes = error_codes;\n\n    // Store bound handlers for cleanup\n    this.boundOnlineStatusChangeHandler = this.handleOnlineStatusChange.bind(this);\n    this.boundCustomNetworkStatusHandler = this.handleCustomNetworkStatus.bind(this);\n\n    // Initialize listeners for online/offline events\n    window.addEventListener(\"online\", this.boundOnlineStatusChangeHandler);\n    window.addEventListener(\"offline\", this.boundOnlineStatusChangeHandler);\n\n    // Initialize listener for custom network status events\n    window.addEventListener(\"scorm-again:network-status\", this.boundCustomNetworkStatusHandler);\n  }\n\n  /**\n   * Handle changes in online status\n   */\n  private handleOnlineStatusChange() {\n    const wasOnline = this.isOnline;\n    this.isOnline = navigator.onLine;\n\n    // If we've come back online, trigger sync process\n    if (!wasOnline && this.isOnline) {\n      this.syncAfterReconnect();\n    } else if (wasOnline && !this.isOnline) {\n      this.apiLog(\n        \"OfflineStorageService\",\n        \"Device is offline, data will be stored locally\",\n        LogLevelEnum.INFO,\n      );\n    }\n  }\n\n  /**\n   * Handle custom network status events from external code\n   * This allows mobile apps or other external code to programmatically update network status\n   * @param {Event} event - The custom event containing network status\n   */\n  private handleCustomNetworkStatus(event: Event) {\n    if (!(event instanceof CustomEvent)) {\n      this.apiLog(\n        \"OfflineStorageService\",\n        \"Invalid network status event received\",\n        LogLevelEnum.WARN,\n      );\n      return;\n    }\n\n    const { online } = event.detail;\n\n    if (typeof online !== \"boolean\") {\n      this.apiLog(\n        \"OfflineStorageService\",\n        \"Invalid online status value in custom event\",\n        LogLevelEnum.WARN,\n      );\n      return;\n    }\n\n    const wasOnline = this.isOnline;\n    this.isOnline = online;\n\n    this.apiLog(\n      \"OfflineStorageService\",\n      `Network status updated via custom event: ${online ? \"online\" : \"offline\"}`,\n      LogLevelEnum.INFO,\n    );\n\n    // If we've come back online, trigger sync process\n    if (!wasOnline && this.isOnline) {\n      this.syncAfterReconnect();\n    } else if (wasOnline && !this.isOnline) {\n      this.apiLog(\n        \"OfflineStorageService\",\n        \"Device is offline, data will be stored locally\",\n        LogLevelEnum.INFO,\n      );\n    }\n  }\n\n  /**\n   * Sync queued data when the device comes back online.\n   */\n  private syncAfterReconnect(): void {\n    if (!this.hasQueuedData(this.settings.courseId)) {\n      this.apiLog(\n        \"OfflineStorageService\",\n        \"Device is back online, nothing to sync\",\n        LogLevelEnum.INFO,\n      );\n      return;\n    }\n\n    this.apiLog(\n      \"OfflineStorageService\",\n      \"Device is back online, attempting to sync...\",\n      LogLevelEnum.INFO,\n    );\n    this.syncOfflineData().then(\n      (success) => {\n        if (success) {\n          this.apiLog(\"OfflineStorageService\", \"Sync completed successfully\", LogLevelEnum.INFO);\n        } else {\n          this.apiLog(\"OfflineStorageService\", \"Sync failed\", LogLevelEnum.ERROR);\n        }\n      },\n      (error) => {\n        this.apiLog(\"OfflineStorageService\", `Error during sync: ${error}`, LogLevelEnum.ERROR);\n      },\n    );\n  }\n\n  /**\n   * Store commit data offline\n   * @param {string} courseId - Identifier for the course\n   * @param {CommitObject} commitData - The data to store offline\n   * @param {OfflineCommitMetadata} metadata - Metadata captured with the original commit\n   * @returns {ResultObject} - Result of the storage operation\n   */\n  storeOffline(\n    courseId: string,\n    commitData: OfflinePayload,\n    metadata?: OfflineCommitMetadata,\n  ): ResultObject {\n    try {\n      // Store the data in the sync queue with timestamp and unique ID\n      const queueItem: SyncQueueItem = {\n        id: `${courseId}_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`,\n        courseId,\n        learnerId: metadata?.learnerId ?? this.getLearnerId(),\n        timestamp: Date.now(),\n        data: commitData,\n        syncAttempts: 0,\n        ...(metadata?.isTerminateCommit !== undefined\n          ? { isTerminateCommit: metadata.isTerminateCommit }\n          : {}),\n        ...(metadata?.sequence !== undefined ? { sequence: metadata.sequence } : {}),\n      };\n\n      // Get current queue\n      const currentQueue = this.getFromStorage<SyncQueueItem[]>(this.syncQueue) || [];\n      currentQueue.push(queueItem);\n\n      // Save updated queue\n      this.saveToStorage(this.syncQueue, currentQueue);\n\n      // Also update the current state in the main storage (latest known state)\n      this.saveToStorage(`${this.storeName}_${courseId}`, commitData);\n\n      this.apiLog(\n        \"OfflineStorageService\",\n        `Stored data offline for course ${courseId}`,\n        LogLevelEnum.INFO,\n      );\n\n      return {\n        result: global_constants.SCORM_TRUE,\n        errorCode: 0,\n      };\n    } catch (error) {\n      const errorMessage = error instanceof Error ? error.message : String(error);\n      const isQuotaError = errorMessage.includes(\"storage quota\");\n\n      this.apiLog(\n        \"OfflineStorageService\",\n        isQuotaError\n          ? `storage quota exceeded - cannot store offline data for course ${courseId}`\n          : `Error storing offline data: ${error}`,\n        LogLevelEnum.ERROR,\n      );\n      return {\n        result: global_constants.SCORM_FALSE,\n        errorCode: this.error_codes.GENERAL ?? 0,\n      };\n    }\n  }\n\n  /**\n   * Get the stored offline data for a course\n   * @param {string} courseId - Identifier for the course\n   * @returns {Promise<CommitObject|null>} - The stored data or null if not found\n   */\n  async getOfflineData(courseId: string): Promise<OfflinePayload | null> {\n    try {\n      const data = this.getFromStorage<OfflinePayload>(`${this.storeName}_${courseId}`);\n      return data || null;\n    } catch (error) {\n      this.apiLog(\n        \"OfflineStorageService\",\n        `Error retrieving offline data: ${error}`,\n        LogLevelEnum.ERROR,\n      );\n      return null;\n    }\n  }\n\n  getPendingOfflineData(courseId: string, learnerId: string): OfflinePayload[] {\n    const queue = this.getFromStorage<SyncQueueItem[]>(this.syncQueue) || [];\n    return queue\n      .filter((item) => item.courseId === courseId && item.learnerId === learnerId)\n      .map((item) => item.data);\n  }\n\n  /**\n   * Synchronize offline data with the LMS when connection is available\n   * @returns {Promise<boolean>} - Success status of synchronization\n   */\n  async syncOfflineData(): Promise<boolean> {\n    // Don't run multiple sync processes at once\n    if (this.syncInProgress || !this.isOnline) {\n      return false;\n    }\n\n    this.syncInProgress = true;\n    let started = false;\n    let success = false;\n\n    try {\n      // Get the queue of items to sync\n      const syncQueue = this.getFromStorage<SyncQueueItem[]>(this.syncQueue) || [];\n      const learnerId = this.getLearnerId();\n      const matches = (item: SyncQueueItem) =>\n        item.courseId === this.settings.courseId &&\n        (item.learnerId === undefined || item.learnerId === learnerId);\n      const matchingCount = syncQueue.filter(matches).length;\n\n      if (matchingCount === 0) {\n        return false;\n      }\n\n      // An online, nonoverlapping run with items for this course and learner emits Syncing once,\n      // then exactly one Synced (all items accepted) or SyncFailed (queued, dropped, or thrown).\n      started = true;\n      this.processListeners(\"OfflineDataSyncing\");\n      let allAccepted = true;\n\n      this.apiLog(\n        \"OfflineStorageService\",\n        `Found ${matchingCount} items to sync`,\n        LogLevelEnum.INFO,\n      );\n\n      // Keep track of successful and failed sync attempts\n      const remainingQueue: SyncQueueItem[] = [];\n\n      // Process each queue item\n      for (const item of syncQueue) {\n        if (!matches(item)) {\n          remainingQueue.push(item);\n          continue;\n        }\n        const maxAttempts = this.settings.maxSyncAttempts ?? 5;\n\n        // Remove items that have exceeded max sync attempts (abandon them)\n        if (item.syncAttempts >= maxAttempts) {\n          this.apiLog(\n            \"OfflineStorageService\",\n            `Removing abandoned item ${item.id} after ${maxAttempts} failed sync attempts`,\n            LogLevelEnum.WARN,\n          );\n          allAccepted = false;\n          // Don't add to remainingQueue - item is abandoned\n          continue;\n        }\n\n        try {\n          // Attempt to sync this item\n          const syncResult = await this.sendDataToLMS(item.data, {\n            ...(item.isTerminateCommit !== undefined\n              ? { isTerminateCommit: item.isTerminateCommit }\n              : {}),\n            ...(item.sequence !== undefined ? { sequence: item.sequence } : {}),\n          });\n\n          if (\n            (syncResult.result as unknown) === true ||\n            syncResult.result === global_constants.SCORM_TRUE\n          ) {\n            // Sync was successful, no need to keep this item\n            this.apiLog(\n              \"OfflineStorageService\",\n              `Successfully synced item ${item.id}`,\n              LogLevelEnum.INFO,\n            );\n          } else {\n            allAccepted = false;\n            // Sync failed, increment attempts and keep in queue\n            item.syncAttempts++;\n            remainingQueue.push(item);\n            this.apiLog(\n              \"OfflineStorageService\",\n              `Failed to sync item ${item.id}, attempt #${item.syncAttempts}`,\n              LogLevelEnum.WARN,\n            );\n          }\n        } catch (error) {\n          allAccepted = false;\n          // On error, increment attempts and keep in queue\n          item.syncAttempts++;\n          remainingQueue.push(item);\n          this.apiLog(\n            \"OfflineStorageService\",\n            `Error syncing item ${item.id}: ${error}`,\n            LogLevelEnum.ERROR,\n          );\n        }\n      }\n\n      // Update the queue with remaining items\n      this.saveToStorage(this.syncQueue, remainingQueue);\n      for (const courseId of new Set(syncQueue.filter(matches).map((item) => item.courseId))) {\n        if (!remainingQueue.some((item) => item.courseId === courseId)) {\n          this.removeFromStorage(`${this.storeName}_${courseId}`);\n        }\n      }\n\n      this.apiLog(\n        \"OfflineStorageService\",\n        `Sync completed. ${syncQueue.length - remainingQueue.length} items synced, ${remainingQueue.length} items remaining`,\n        LogLevelEnum.INFO,\n      );\n\n      success = allAccepted;\n      return success;\n    } catch (error) {\n      if (!started) {\n        started = true;\n        this.processListeners(\"OfflineDataSyncing\");\n      }\n      this.apiLog(\n        \"OfflineStorageService\",\n        `Error during sync process: ${error}`,\n        LogLevelEnum.ERROR,\n      );\n      return false;\n    } finally {\n      this.syncInProgress = false;\n      if (started) {\n        this.processListeners(success ? \"OfflineDataSynced\" : \"OfflineDataSyncFailed\");\n      }\n    }\n  }\n\n  /**\n   * Send data to the LMS when online\n   * @param {CommitObject} data - The data to send to the LMS\n   * @param {OfflineCommitMetadata} metadata - Metadata captured with the original commit\n   * @returns {Promise<ResultObject>} - Result of the sync operation\n   */\n  private async sendDataToLMS(\n    data: OfflinePayload,\n    metadata?: OfflineCommitMetadata,\n  ): Promise<ResultObject> {\n    const configuredCommitUrl = this.settings.lmsCommitUrl;\n    if (!configuredCommitUrl) {\n      return {\n        result: global_constants.SCORM_FALSE,\n        errorCode: this.error_codes.GENERAL || 101,\n      };\n    }\n\n    try {\n      const lmsCommitUrl = String(configuredCommitUrl);\n\n      const requestUrl =\n        metadata?.isTerminateCommit && this.settings.terminateCommitParam\n          ? appendQueryParam(lmsCommitUrl, this.settings.terminateCommitParam, \"true\")\n          : lmsCommitUrl;\n      const commitMetadata = {\n        isTerminateCommit: metadata?.isTerminateCommit ?? false,\n        trigger: \"offline-replay\" as const,\n        ...(metadata?.sequence !== undefined ? { sequence: metadata.sequence } : {}),\n      };\n      const httpService = this.httpService;\n      if (\n        httpService instanceof SynchronousHttpService &&\n        !(\"reportsRequestCompletion\" in httpService && httpService.reportsRequestCompletion)\n      ) {\n        return await httpService.performAsyncRequest(requestUrl, data, commitMetadata);\n      }\n      if (httpService) {\n        return await new Promise<ResultObject>((resolve, reject) => {\n          try {\n            const result = httpService.processHttpRequest(\n              requestUrl,\n              data,\n              false,\n              this.apiLog,\n              (event, _element, errorCode) => {\n                if (event === \"CommitSuccess\") resolve({ result: \"true\", errorCode: 0 });\n                if (event === \"CommitError\") resolve({ result: \"false\", errorCode });\n              },\n              commitMetadata,\n              // A deferring service settles each request through this callback. If it sent\n              // no commit event first, the replay counts as failed and stays queued.\n              () =>\n                resolve({\n                  result: \"false\",\n                  errorCode: this.error_codes.GENERAL_COMMIT_FAILURE || 391,\n                }),\n            );\n            if (!httpService.reportsRequestCompletion) resolve(result);\n          } catch (error) {\n            reject(error);\n          }\n        });\n      }\n      const processedData = this.settings.requestHandler(data, commitMetadata) ?? data;\n\n      // Send the data to the LMS\n      const init = {\n        method: \"POST\",\n        mode: this.settings.fetchMode,\n        body: Array.isArray(processedData)\n          ? processedData.join(\"&\")\n          : JSON.stringify(processedData),\n        headers: {\n          ...this.settings.xhrHeaders,\n          \"Content-Type\": Array.isArray(processedData)\n            ? \"application/x-www-form-urlencoded\"\n            : this.settings.commitRequestDataType,\n        },\n      } as RequestInit;\n\n      if (this.settings.xhrWithCredentials) {\n        init.credentials = \"include\";\n      }\n\n      const response = await fetch(requestUrl, init);\n\n      // Process the response using the configured handler\n      const result =\n        typeof this.settings.responseHandler === \"function\"\n          ? await this.settings.responseHandler(response)\n          : await response.json();\n\n      if (\n        response.status >= 200 &&\n        response.status <= 299 &&\n        ((result.result as unknown) === true || result.result === global_constants.SCORM_TRUE)\n      ) {\n        if (!Object.hasOwnProperty.call(result, \"errorCode\")) {\n          result.errorCode = 0;\n        }\n        return result;\n      } else {\n        if (!Object.hasOwnProperty.call(result, \"errorCode\")) {\n          result.errorCode = this.error_codes.GENERAL;\n        }\n        return result;\n      }\n    } catch (error) {\n      this.apiLog(\n        \"OfflineStorageService\",\n        `Error sending data to LMS: ${error}`,\n        LogLevelEnum.ERROR,\n      );\n      return {\n        result: global_constants.SCORM_FALSE,\n        errorCode: this.error_codes.GENERAL || 101,\n      };\n    }\n  }\n\n  /**\n   * Check if the device is currently online\n   * @returns {boolean} - Online status\n   */\n  isDeviceOnline(): boolean {\n    return this.isOnline;\n  }\n\n  // noinspection JSValidateJSDoc\n  /**\n   * Get item from localStorage\n   * @param {string} key - The key to retrieve\n   * @returns {T|null} - The retrieved data\n   */\n  private getFromStorage<T>(key: string): T | null {\n    const storedData = localStorage.getItem(key);\n    if (storedData) {\n      try {\n        return JSON.parse(storedData) as T;\n      } catch (e) {\n        return null;\n      }\n    }\n    return null;\n  }\n\n  /**\n   * Save item to localStorage\n   * @param {string} key - The key to store under\n   * @param {any} data - The data to store\n   * @returns {void}\n   * @throws {Error} Re-throws QuotaExceededError for handling upstream\n   */\n  private saveToStorage(key: string, data: any): void {\n    try {\n      localStorage.setItem(key, JSON.stringify(data));\n    } catch (error) {\n      if (error instanceof DOMException && error.name === \"QuotaExceededError\") {\n        throw new Error(\"storage quota exceeded - localStorage is full\", { cause: error });\n      }\n      throw error;\n    }\n  }\n\n  private removeFromStorage(key: string): void {\n    try {\n      localStorage.removeItem(key);\n    } catch (error) {\n      if (error instanceof DOMException && error.name === \"QuotaExceededError\") {\n        throw new Error(\"storage quota exceeded - localStorage is full\", { cause: error });\n      }\n      throw error;\n    }\n  }\n\n  /**\n   * Check if there is pending offline data for a course\n   * @param {string} courseId - Identifier for the course\n   * @returns {Promise<boolean>} - Whether there is pending data\n   */\n  async hasPendingOfflineData(courseId: string): Promise<boolean> {\n    return this.hasQueuedData(courseId);\n  }\n\n  /**\n   * Check for queued data matching the course and current learner.\n   */\n  private hasQueuedData(courseId: string | undefined): boolean {\n    const queue = this.getFromStorage<SyncQueueItem[]>(this.syncQueue) || [];\n    const learnerId = this.getLearnerId();\n    // Match what syncOfflineData would send: this learner's items and legacy items without one.\n    return queue.some(\n      (item) =>\n        item.courseId === courseId &&\n        (item.learnerId === undefined || item.learnerId === learnerId),\n    );\n  }\n\n  /**\n   * Update the service settings\n   * @param {Settings} settings - The new settings\n   */\n  updateSettings(settings: InternalSettings): void {\n    this.settings = settings;\n  }\n\n  /**\n   * Clean up event listeners\n   * Should be called when the service is no longer needed\n   */\n  destroy(): void {\n    window.removeEventListener(\"online\", this.boundOnlineStatusChangeHandler);\n    window.removeEventListener(\"offline\", this.boundOnlineStatusChangeHandler);\n    window.removeEventListener(\"scorm-again:network-status\", this.boundCustomNetworkStatusHandler);\n  }\n}\n","import { BaseScormValidationError } from \"../../exceptions\";\nimport { memoize } from \"../../utilities\";\n\n/**\n * Check if the value matches the proper format. If not, throw proper error code.\n *\n * @param {string} value\n * @param {string} regexPattern\n * @param {number} errorCode\n * @param {typeof BaseScormValidationError} errorClass\n * @param {boolean} [allowEmptyString]\n * @return {boolean}\n */\nexport const checkValidFormat = memoize(\n  (\n    CMIElement: string,\n    value: string,\n    regexPattern: string | RegExp, // We accept either a string or a RegExp object to allow the usage of flags.\n    errorCode: number,\n    errorClass: typeof BaseScormValidationError,\n    allowEmptyString?: boolean,\n  ): boolean => {\n    // noinspection SuspiciousTypeOfGuard\n    if (typeof value !== \"string\") {\n      return false;\n    }\n    const formatRegex = new RegExp(regexPattern);\n    const matches = value.match(formatRegex);\n    if (allowEmptyString && value === \"\") {\n      return true;\n    }\n    // COM-VAL-01: Removed redundant value === undefined check (already handled by typeof above)\n    if (!matches || matches[0] === \"\") {\n      throw new errorClass(CMIElement, errorCode);\n    }\n    return true;\n  },\n  // Custom key function that excludes the error class from the cache key\n  // since it can't be stringified and doesn't affect the validation result\n  (CMIElement, value, regexPattern, errorCode, _errorClass, allowEmptyString) => {\n    // Use typeof for non-string values to ensure consistent cache keys\n    const valueKey = typeof value === \"string\" ? value : `[${typeof value}]`;\n    return `${CMIElement}:${valueKey}:${regexPattern}:${errorCode}:${allowEmptyString || false}`;\n  },\n  // Normal capped CMI values and regexes fit within 2000 characters; large uncapped values bypass caching.\n  { maxEntries: 1000, maxKeyLength: 2000 },\n);\n\n/**\n * Check if the value matches the proper range. If not, throw proper error code.\n *\n * Range pattern format per SCORM RTE specifications:\n * - \"min#max\": bounded range (e.g., \"0#100\" = 0 to 100)\n * - \"min#*\": unbounded maximum (e.g., \"-1#*\" = -1 to infinity)\n * - \"#max\": no minimum bound (e.g., \"#100\" = up to 100)\n *\n * @param {any} value\n * @param {string} rangePattern\n * @param {number} errorCode\n * @param {typeof BaseScormValidationError} errorClass\n * @return {boolean}\n */\nexport const checkValidRange = memoize(\n  (\n    CMIElement: string,\n    value: any,\n    rangePattern: string,\n    errorCode: number,\n    errorClass: typeof BaseScormValidationError,\n  ): boolean => {\n    const ranges = rangePattern.split(\"#\");\n    value = Number(value);\n\n    // If value is not a valid number, throw error\n    if (isNaN(value)) {\n      throw new errorClass(CMIElement, errorCode);\n    }\n\n    // COM-VAL-02: Handle empty minimum (no lower bound) and empty/wildcard maximum (no upper bound)\n    // This structure uses independent bound checks rather than nested conditionals to:\n    // 1. Correctly handle all SCORM range patterns (\"#max\", \"min#\", \"min#*\", \"min#max\")\n    // 2. Make the validation logic explicit and testable for each boundary condition\n    // 3. Avoid the complexity and error-proneness of deeply nested if-else statements\n    const minBound = ranges[0];\n    const maxBound = ranges[1];\n    const hasMinimum = minBound !== undefined && minBound !== \"\";\n    const hasMaximum = maxBound !== undefined && maxBound !== \"\" && maxBound !== \"*\";\n\n    // Check minimum bound if it exists\n    if (hasMinimum && value < Number(minBound)) {\n      throw new errorClass(CMIElement, errorCode);\n    }\n\n    // Check maximum bound if it exists\n    if (hasMaximum && value > Number(maxBound)) {\n      throw new errorClass(CMIElement, errorCode);\n    }\n\n    return true;\n  },\n  // Custom key function that excludes the error class from the cache key\n  // since it can't be stringified and doesn't affect the validation result\n  (CMIElement, value, rangePattern, errorCode, _errorClass) =>\n    `${CMIElement}:${value}:${rangePattern}:${errorCode}`,\n  { maxEntries: 1000 },\n);\n","import { checkValidFormat, checkValidRange } from \"../common/validation\";\nimport { scorm2004_errors } from \"../../constants/error_codes\";\nimport { Scorm2004ValidationError } from \"../../exceptions/scorm2004_exceptions\";\n\n/**\n * Helper method, no reason to have to pass the same error codes every time\n * @param {string} CMIElement\n * @param {string} value\n * @param {string} regexPattern\n * @param {boolean} allowEmptyString\n * @return {boolean}\n */\nexport function check2004ValidFormat(\n  CMIElement: string,\n  value: string,\n  regexPattern: string,\n  allowEmptyString?: boolean,\n): boolean {\n  return checkValidFormat(\n    CMIElement,\n    value,\n    regexPattern,\n    scorm2004_errors.TYPE_MISMATCH as number,\n    Scorm2004ValidationError,\n    allowEmptyString,\n  );\n}\n\n/**\n * Helper method, no reason to have to pass the same error codes every time\n * @param {string} CMIElement\n * @param {string} value\n * @param {string} rangePattern\n * @return {boolean}\n */\nexport function check2004ValidRange(\n  CMIElement: string,\n  value: string,\n  rangePattern: string,\n): boolean {\n  return checkValidRange(\n    CMIElement,\n    value,\n    rangePattern,\n    scorm2004_errors.VALUE_OUT_OF_RANGE as number,\n    Scorm2004ValidationError,\n  );\n}\n","import { BaseCMI } from \"../../common/base_cmi\";\nimport { Activity } from \"./activity\";\nimport { Scorm2004ValidationError } from \"../../../exceptions/scorm2004_exceptions\";\nimport { scorm2004_errors } from \"../../../constants/error_codes\";\nimport { CompletionStatus, SuccessStatus } from \"../../../constants/enums\";\nimport {\n  AttemptElapsedSecondsHook,\n  isOutsideAvailableTimeRange,\n  isTimeLimitExceeded,\n} from \"./time_conditions\";\nimport { RuleConditionEvaluation, kleeneNot } from \"./sequencing_rules\";\n\n/**\n * Enum for rollup action types\n */\nexport enum RollupActionType {\n  SATISFIED = \"satisfied\",\n  NOT_SATISFIED = \"notSatisfied\",\n  COMPLETED = \"completed\",\n  INCOMPLETE = \"incomplete\",\n}\n\n/**\n * Enum for rollup condition types\n */\nexport enum RollupConditionType {\n  SATISFIED = \"satisfied\",\n  OBJECTIVE_STATUS_KNOWN = \"objectiveStatusKnown\",\n  OBJECTIVE_MEASURE_KNOWN = \"objectiveMeasureKnown\",\n  OBJECTIVE_MEASURE_GREATER_THAN = \"objectiveMeasureGreaterThan\",\n  OBJECTIVE_MEASURE_LESS_THAN = \"objectiveMeasureLessThan\",\n  COMPLETED = \"completed\",\n  PROGRESS_KNOWN = \"progressKnown\",\n  ACTIVITY_PROGRESS_KNOWN = \"activityProgressKnown\",\n  ATTEMPTED = \"attempted\",\n  ATTEMPT_LIMIT_EXCEEDED = \"attemptLimitExceeded\",\n  TIME_LIMIT_EXCEEDED = \"timeLimitExceeded\",\n  OUTSIDE_AVAILABLE_TIME_RANGE = \"outsideAvailableTimeRange\",\n  NOT_ATTEMPTED = \"notAttempted\",\n  ALWAYS = \"always\",\n}\n\n/**\n * Enum for operators applied to individual rollup conditions\n */\nexport enum RollupConditionOperator {\n  NO_OP = \"noOp\",\n  NOT = \"not\",\n}\n\n/**\n * Enum for combining the conditions within one rollup rule\n */\nexport enum RollupConditionCombination {\n  ALL = \"all\",\n  ANY = \"any\",\n}\n\n/**\n * Enum for rollup consideration types\n */\nexport enum RollupConsiderationType {\n  ALL = \"all\",\n  ANY = \"any\",\n  NONE = \"none\",\n  AT_LEAST_COUNT = \"atLeastCount\",\n  AT_LEAST_PERCENT = \"atLeastPercent\",\n}\n\n/**\n * Read a rollup rule's minimumPercent as a fraction.\n * IMS SS minimumPercent is 0.0-1.0; values above 1 are whole percents, kept for backward\n * compatibility.\n * @param {number} minimumPercent\n * @return {number}\n */\nexport function normalizeMinimumPercent(minimumPercent: number): number {\n  return minimumPercent > 1 ? minimumPercent / 100 : minimumPercent;\n}\n\n/**\n * Class representing a rollup condition\n */\nexport class RollupCondition extends BaseCMI {\n  private _condition: RollupConditionType = RollupConditionType.ALWAYS;\n  private _parameters: Map<string, any> = new Map();\n  private _operator: RollupConditionOperator = RollupConditionOperator.NO_OP;\n\n  /**\n   * Constructor for RollupCondition\n   * @param {RollupConditionType} condition - The condition type\n   * @param {Map<string, any>} parameters - Additional parameters for the condition\n   * @param {RollupConditionOperator} operator - The operator applied to the condition result\n   */\n  constructor(\n    condition: RollupConditionType = RollupConditionType.ALWAYS,\n    parameters: Map<string, any> = new Map(),\n    operator: RollupConditionOperator = RollupConditionOperator.NO_OP,\n  ) {\n    super(\"rollupCondition\");\n    this._condition = condition;\n    this._parameters = parameters;\n    this._operator = operator;\n  }\n\n  /**\n   * Called when the API needs to be reset\n   */\n  reset() {\n    this._initialized = false;\n  }\n\n  /**\n   * Getter for condition\n   * @return {RollupConditionType}\n   */\n  get condition(): RollupConditionType {\n    return this._condition;\n  }\n\n  /**\n   * Setter for condition\n   * @param {RollupConditionType} condition\n   */\n  set condition(condition: RollupConditionType) {\n    this._condition = condition;\n  }\n\n  /**\n   * Getter for parameters\n   * @return {Map<string, any>}\n   */\n  get parameters(): Map<string, any> {\n    return this._parameters;\n  }\n\n  /**\n   * Setter for parameters\n   * @param {Map<string, any>} parameters\n   */\n  set parameters(parameters: Map<string, any>) {\n    this._parameters = parameters;\n  }\n\n  /**\n   * Getter for the condition operator\n   * @return {RollupConditionOperator}\n   */\n  get operator(): RollupConditionOperator {\n    return this._operator;\n  }\n\n  /**\n   * Setter for the condition operator\n   * @param {RollupConditionOperator} operator\n   */\n  set operator(operator: RollupConditionOperator) {\n    this._operator = operator;\n  }\n\n  /**\n   * Evaluate the condition for an activity\n   * @param {Activity} activity - The activity to evaluate the condition for\n   * @param {() => Date} [now] - The clock of the evaluating process (time-based conditions)\n   * @param {AttemptElapsedSecondsHook | null} [getElapsedSeconds] - Elapsed-time hook (timeLimitExceeded)\n   * @return {boolean} - True if the condition is met, false otherwise\n   */\n  evaluate(\n    activity: Activity,\n    now: () => Date = () => new Date(),\n    getElapsedSeconds: AttemptElapsedSecondsHook | null = null,\n  ): boolean {\n    return this.evaluateThreeValued(activity, now, getElapsedSeconds) === true;\n  }\n\n  /**\n   * Evaluate without collapsing unknown tracking information to false.\n   * @spec SCORM 2004 4th Ed. SN RB.1.4.1\n   */\n  evaluateThreeValued(\n    activity: Activity,\n    now: () => Date = () => new Date(),\n    getElapsedSeconds: AttemptElapsedSecondsHook | null = null,\n  ): RuleConditionEvaluation {\n    // Current-attempt controls make prior tracking data unknown to the parent without removing the\n    // child from the rollup rule's population.\n    // @spec SCORM 2004 SN 4th Ed. SM.1 useCurrentAttemptObjectiveInfo and\n    // useCurrentAttemptProgressInfo\n    const objectiveInfoAvailable = activity.objectiveInfoAvailableInCurrentParentAttempt !== false;\n    const progressInfoAvailable = activity.progressInfoAvailableInCurrentParentAttempt !== false;\n\n    let result: RuleConditionEvaluation;\n\n    switch (this._condition) {\n      case RollupConditionType.SATISFIED:\n        // Per SCORM 2004 SN Book RB.1.4.1, the \"satisfied\" condition checks the\n        // objective satisfaction status from the activity's tracked objective.\n        // This is populated via global objective mapping (readSatisfiedStatus).\n        // successStatus is a fallback only for activities without a primary objective, matching the\n        // sequencing-rule condition; otherwise a stale successStatus could mask an unknown status.\n        if (!objectiveInfoAvailable) {\n          result = \"unknown\";\n        } else if (activity.objectiveSatisfiedStatusKnown) {\n          result = activity.objectiveSatisfiedStatus === true;\n        } else if (!activity.primaryObjective && activity.successStatus !== SuccessStatus.UNKNOWN) {\n          result = activity.successStatus === SuccessStatus.PASSED;\n        } else {\n          result = \"unknown\";\n        }\n        break;\n      case RollupConditionType.OBJECTIVE_STATUS_KNOWN:\n        // Per SCORM 2004 SN Book RB.1.4.1, objectiveStatusKnown checks if\n        // the objective's satisfaction status has been explicitly determined\n        result = objectiveInfoAvailable && activity.objectiveSatisfiedStatusKnown;\n        break;\n      case RollupConditionType.OBJECTIVE_MEASURE_KNOWN:\n        // Per SCORM 2004 SN Book RB.1.4.1, objectiveMeasureKnown checks if\n        // the objective has a valid measure value\n        result = objectiveInfoAvailable && activity.objectiveMeasureStatus;\n        break;\n      case RollupConditionType.OBJECTIVE_MEASURE_GREATER_THAN: {\n        const greaterThanValue = this._parameters.get(\"threshold\") || 0;\n        result =\n          objectiveInfoAvailable && activity.objectiveMeasureStatus\n            ? activity.objectiveNormalizedMeasure > greaterThanValue\n            : \"unknown\";\n        break;\n      }\n      case RollupConditionType.OBJECTIVE_MEASURE_LESS_THAN: {\n        const lessThanValue = this._parameters.get(\"threshold\") || 0;\n        result =\n          objectiveInfoAvailable && activity.objectiveMeasureStatus\n            ? activity.objectiveNormalizedMeasure < lessThanValue\n            : \"unknown\";\n        break;\n      }\n      case RollupConditionType.COMPLETED:\n        result =\n          progressInfoAvailable && activity.completionStatus !== CompletionStatus.UNKNOWN\n            ? activity.isCompleted\n            : \"unknown\";\n        break;\n      case RollupConditionType.PROGRESS_KNOWN:\n      case RollupConditionType.ACTIVITY_PROGRESS_KNOWN:\n        result =\n          progressInfoAvailable && activity.completionStatus !== CompletionStatus.UNKNOWN;\n        break;\n      case RollupConditionType.ATTEMPTED:\n        result = progressInfoAvailable && activity.attemptCount > 0;\n        break;\n      case RollupConditionType.ATTEMPT_LIMIT_EXCEEDED:\n        result = activity.hasAttemptLimitExceeded();\n        break;\n      case RollupConditionType.TIME_LIMIT_EXCEEDED:\n        result = isTimeLimitExceeded(activity, now, getElapsedSeconds);\n        break;\n      case RollupConditionType.OUTSIDE_AVAILABLE_TIME_RANGE:\n        result = isOutsideAvailableTimeRange(activity, now);\n        break;\n      case RollupConditionType.NOT_ATTEMPTED:\n        result = !progressInfoAvailable || activity.attemptCount === 0;\n        break;\n      case RollupConditionType.ALWAYS:\n        result = true;\n        break;\n      default:\n        result = false;\n    }\n\n    return this._operator === RollupConditionOperator.NOT ? kleeneNot(result) : result;\n  }\n\n  /**\n   * toJSON for RollupCondition\n   * @return {object}\n   */\n  toJSON(): object {\n    this.jsonString = true;\n    const result = {\n      condition: this._condition,\n      operator: this._operator,\n      parameters: Object.fromEntries(this._parameters),\n    };\n    this.jsonString = false;\n    return result;\n  }\n}\n\n/**\n * Class representing a rollup rule\n */\nexport class RollupRule extends BaseCMI {\n  private _conditions: RollupCondition[] = [];\n  private _action: RollupActionType = RollupActionType.SATISFIED;\n  private _consideration: RollupConsiderationType = RollupConsiderationType.ALL;\n  private _minimumCount: number = 0;\n  private _minimumPercent: number = 0;\n  public conditionCombination?: RollupConditionCombination = RollupConditionCombination.ANY;\n\n  /**\n   * Constructor for RollupRule\n   * @param {RollupActionType} action - The action to take when the rule conditions are met\n   * @param {RollupConsiderationType} consideration - How to consider child activities\n   * @param {number} minimumCount - The minimum count for AT_LEAST_COUNT consideration\n   * @param {number} minimumPercent - The minimum percent for AT_LEAST_PERCENT consideration\n   * @param {RollupConditionCombination} conditionCombination - How this rule's conditions combine\n   */\n  constructor(\n    action: RollupActionType = RollupActionType.SATISFIED,\n    consideration: RollupConsiderationType = RollupConsiderationType.ALL,\n    minimumCount: number = 0,\n    minimumPercent: number = 0,\n    conditionCombination: RollupConditionCombination = RollupConditionCombination.ANY,\n  ) {\n    super(\"rollupRule\");\n    this._action = action;\n    this._consideration = consideration;\n    this._minimumCount = minimumCount;\n    this._minimumPercent = minimumPercent;\n    this.conditionCombination = conditionCombination;\n  }\n\n  /**\n   * Called when the API needs to be reset\n   */\n  reset() {\n    this._initialized = false;\n    this._conditions = [];\n  }\n\n  /**\n   * Getter for conditions\n   * @return {RollupCondition[]}\n   */\n  get conditions(): RollupCondition[] {\n    return this._conditions;\n  }\n\n  /**\n   * Add a condition to the rule\n   * @param {RollupCondition} condition - The condition to add\n   */\n  addCondition(condition: RollupCondition): void {\n    // noinspection SuspiciousTypeOfGuard\n    if (!(condition instanceof RollupCondition)) {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".conditions\",\n        scorm2004_errors.TYPE_MISMATCH as number,\n      );\n    }\n    this._conditions.push(condition);\n  }\n\n  /**\n   * Remove a condition from the rule\n   * @param {RollupCondition} condition - The condition to remove\n   * @return {boolean} - True if the condition was removed, false otherwise\n   */\n  removeCondition(condition: RollupCondition): boolean {\n    const index = this._conditions.indexOf(condition);\n    if (index !== -1) {\n      this._conditions.splice(index, 1);\n      return true;\n    }\n    return false;\n  }\n\n  /**\n   * Getter for action\n   * @return {RollupActionType}\n   */\n  get action(): RollupActionType {\n    return this._action;\n  }\n\n  /**\n   * Setter for action\n   * @param {RollupActionType} action\n   */\n  set action(action: RollupActionType) {\n    this._action = action;\n  }\n\n  /**\n   * Getter for consideration\n   * @return {RollupConsiderationType}\n   */\n  get consideration(): RollupConsiderationType {\n    return this._consideration;\n  }\n\n  /**\n   * Setter for consideration\n   * @param {RollupConsiderationType} consideration\n   */\n  set consideration(consideration: RollupConsiderationType) {\n    this._consideration = consideration;\n  }\n\n  /**\n   * Getter for minimumCount\n   * @return {number}\n   */\n  get minimumCount(): number {\n    return this._minimumCount;\n  }\n\n  /**\n   * Setter for minimumCount\n   * @param {number} minimumCount\n   */\n  set minimumCount(minimumCount: number) {\n    if (minimumCount >= 0) {\n      this._minimumCount = minimumCount;\n    }\n  }\n\n  /**\n   * Getter for minimumPercent\n   * @return {number}\n   */\n  get minimumPercent(): number {\n    return this._minimumPercent;\n  }\n\n  /**\n   * Setter for minimumPercent\n   * @param {number} minimumPercent\n   */\n  set minimumPercent(minimumPercent: number) {\n    if (minimumPercent >= 0 && minimumPercent <= 100) {\n      this._minimumPercent = minimumPercent;\n    }\n  }\n\n  /**\n   * Evaluate the rule for a set of child activities\n   * @param {Activity[]} children - The child activities to evaluate the rule for\n   * @param {() => Date} [now] - The clock of the evaluating process (time-based conditions)\n   * @param {AttemptElapsedSecondsHook | null} [getElapsedSeconds] - Elapsed-time hook (timeLimitExceeded)\n   * @return {boolean} - True if the rule conditions are met, false otherwise\n   */\n  evaluate(\n    children: Activity[],\n    now?: () => Date,\n    getElapsedSeconds?: AttemptElapsedSecondsHook | null,\n  ): boolean {\n    if (children.length === 0) {\n      return false;\n    }\n\n    // Filter children that meet all conditions\n    const matchingChildren = children.filter((child) => {\n      if (this._conditions.length === 0) {\n        return true;\n      }\n      return this.conditionCombination === RollupConditionCombination.ALL\n        ? this._conditions.every((condition) => condition.evaluate(child, now, getElapsedSeconds))\n        : this._conditions.some((condition) => condition.evaluate(child, now, getElapsedSeconds));\n    });\n\n    // Apply consideration\n    switch (this._consideration) {\n      case RollupConsiderationType.ALL:\n        return matchingChildren.length === children.length;\n      case RollupConsiderationType.ANY:\n        return matchingChildren.length > 0;\n      case RollupConsiderationType.NONE:\n        return matchingChildren.length === 0;\n      case RollupConsiderationType.AT_LEAST_COUNT:\n        return matchingChildren.length >= this._minimumCount;\n      case RollupConsiderationType.AT_LEAST_PERCENT: {\n        const fraction = matchingChildren.length / children.length;\n        return fraction >= normalizeMinimumPercent(this._minimumPercent);\n      }\n      default:\n        return false;\n    }\n  }\n\n  /**\n   * toJSON for RollupRule\n   * @return {object}\n   */\n  toJSON(): object {\n    this.jsonString = true;\n    const result = {\n      conditions: this._conditions,\n      action: this._action,\n      consideration: this._consideration,\n      minimumCount: this._minimumCount,\n      minimumPercent: this._minimumPercent,\n      conditionCombination: this.conditionCombination,\n    };\n    this.jsonString = false;\n    return result;\n  }\n}\n\n/**\n * Class representing a collection of rollup rules\n */\nexport class RollupRules extends BaseCMI {\n  private _rules: RollupRule[] = [];\n\n  /**\n   * Constructor for RollupRules\n   */\n  constructor() {\n    super(\"rollupRules\");\n  }\n\n  /**\n   * Called when the API needs to be reset\n   */\n  reset() {\n    this._initialized = false;\n    this._rules = [];\n  }\n\n  /**\n   * Getter for rules\n   * @return {RollupRule[]}\n   */\n  get rules(): RollupRule[] {\n    return this._rules;\n  }\n\n  /**\n   * Add a rule\n   * @param {RollupRule} rule - The rule to add\n   */\n  addRule(rule: RollupRule): void {\n    // noinspection SuspiciousTypeOfGuard\n    if (!(rule instanceof RollupRule)) {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".rules\",\n        scorm2004_errors.TYPE_MISMATCH as number,\n      );\n    }\n    this._rules.push(rule);\n  }\n\n  /**\n   * Remove a rule\n   * @param {RollupRule} rule - The rule to remove\n   * @return {boolean} - True if the rule was removed, false otherwise\n   */\n  removeRule(rule: RollupRule): boolean {\n    const index = this._rules.indexOf(rule);\n    if (index !== -1) {\n      this._rules.splice(index, 1);\n      return true;\n    }\n    return false;\n  }\n\n  /**\n   * Process rollup for an activity\n   * @param {Activity} activity - The activity to process rollup for\n   */\n  processRollup(activity: Activity): void {\n    if (!activity || activity.children.length === 0) {\n      return;\n    }\n\n    const children = activity.getAvailableChildren();\n    let completionRollup = false;\n    let successRollup = false;\n\n    // First, check if we should use measure rollup (RB.1.2.a)\n    if (activity.sequencingControls.rollupObjectiveSatisfied) {\n      const measureRollupResult = this._objectiveRollupUsingMeasure(activity, children);\n      if (measureRollupResult !== null) {\n        successRollup = true;\n        // Skip rule-based rollup if measure rollup was successful\n      }\n    }\n\n    // Process each rule (RB.1.2.b)\n    if (!successRollup) {\n      for (const rule of this._rules) {\n        if (rule.evaluate(children)) {\n          switch (rule.action) {\n            case RollupActionType.SATISFIED:\n              activity.successStatus = SuccessStatus.PASSED;\n              successRollup = true;\n              break;\n            case RollupActionType.NOT_SATISFIED:\n              activity.successStatus = SuccessStatus.FAILED;\n              successRollup = true;\n              break;\n            case RollupActionType.COMPLETED:\n              activity.completionStatus = CompletionStatus.COMPLETED;\n              activity.isCompleted = true;\n              completionRollup = true;\n              break;\n            case RollupActionType.INCOMPLETE:\n              activity.completionStatus = CompletionStatus.INCOMPLETE;\n              activity.isCompleted = false;\n              completionRollup = true;\n              break;\n          }\n        }\n      }\n    }\n\n    // If no rules applied for completion, use default rollup\n    if (!completionRollup) {\n      this._defaultCompletionRollup(activity, children);\n    }\n\n    // If no rules applied for success, use default rollup (RB.1.2.c)\n    if (!successRollup) {\n      this._defaultSuccessRollup(activity, children);\n    }\n  }\n\n  /**\n   * Default completion rollup\n   * @param {Activity} activity - The activity to process rollup for\n   * @param {Activity[]} children - The child activities\n   * @private\n   */\n  private _defaultCompletionRollup(activity: Activity, children: Activity[]): void {\n    // If all children are completed, mark the parent as completed\n    const allCompleted = children.every((child) => child.isCompleted);\n    if (allCompleted) {\n      activity.completionStatus = CompletionStatus.COMPLETED;\n      activity.isCompleted = true;\n    } else {\n      // If any child is incomplete, mark the parent as incomplete\n      const anyIncomplete = children.some(\n        (child) => child.completionStatus === CompletionStatus.INCOMPLETE,\n      );\n      if (anyIncomplete) {\n        activity.completionStatus = CompletionStatus.INCOMPLETE;\n        activity.isCompleted = false;\n      }\n    }\n  }\n\n  /**\n   * Objective Rollup Using Measure Process (RB.1.2.a)\n   * @param {Activity} activity - The activity to process rollup for\n   * @param {Activity[]} children - The child activities\n   * @return {boolean | null} - True if satisfied, false if not satisfied, null if measure rollup not applicable\n   * @private\n   */\n  private _objectiveRollupUsingMeasure(activity: Activity, children: Activity[]): boolean | null {\n    if (!activity.primaryObjective?.satisfiedByMeasure || activity.scaledPassingScore === null) {\n      return null;\n    }\n\n    // Check if objective measure weight is properly configured\n    const objectiveMeasureWeight = activity.sequencingControls.objectiveMeasureWeight;\n    if (objectiveMeasureWeight <= 0) {\n      return null; // Measure rollup not applicable\n    }\n\n    // Calculate weighted average of child objective measures\n    let totalWeight = 0;\n    let weightedSum = 0;\n    let hasValidMeasures = false;\n\n    for (const child of children) {\n      // Only include children that should contribute to rollup\n      if (!child.sequencingControls.rollupObjectiveSatisfied) {\n        continue;\n      }\n\n      // Check if child has a valid objective measure\n      if (child.objectiveMeasureStatus && child.objectiveMeasureStatus === true) {\n        const childWeight = child.sequencingControls.objectiveMeasureWeight;\n        if (childWeight > 0) {\n          weightedSum += child.objectiveNormalizedMeasure * childWeight;\n          totalWeight += childWeight;\n          hasValidMeasures = true;\n        }\n      }\n    }\n\n    // If no valid measures found, measure rollup is not applicable\n    if (!hasValidMeasures || totalWeight === 0) {\n      return null;\n    }\n\n    // Calculate the normalized measure for the parent activity\n    const normalizedMeasure = weightedSum / totalWeight;\n    activity.objectiveNormalizedMeasure = normalizedMeasure;\n    activity.objectiveMeasureStatus = true;\n\n    // Determine satisfaction based on scaled passing score\n    if (normalizedMeasure >= activity.scaledPassingScore) {\n      activity.successStatus = SuccessStatus.PASSED;\n      activity.objectiveSatisfiedStatus = true;\n      return true;\n    } else {\n      activity.successStatus = SuccessStatus.FAILED;\n      activity.objectiveSatisfiedStatus = false;\n      return false;\n    }\n  }\n\n  /**\n   * Default success rollup\n   * @param {Activity} activity - The activity to process rollup for\n   * @param {Activity[]} children - The child activities\n   * @private\n   */\n  private _defaultSuccessRollup(activity: Activity, children: Activity[]): void {\n    // If all children are satisfied, mark the parent as satisfied\n    const allSatisfied = children.every((child) => child.successStatus === SuccessStatus.PASSED);\n    if (allSatisfied) {\n      activity.successStatus = SuccessStatus.PASSED;\n    } else {\n      // If any child is not satisfied, mark the parent as not satisfied\n      const anyNotSatisfied = children.some(\n        (child) => child.successStatus === SuccessStatus.FAILED,\n      );\n      if (anyNotSatisfied) {\n        activity.successStatus = SuccessStatus.FAILED;\n      }\n    }\n  }\n\n  /**\n   * toJSON for RollupRules\n   * @return {object}\n   */\n  toJSON(): object {\n    this.jsonString = true;\n    const result = {\n      rules: this._rules,\n    };\n    this.jsonString = false;\n    return result;\n  }\n}\n","import { BaseCMI } from \"../../common/base_cmi\";\nimport { scorm2004_regex } from \"../../../constants/regex\";\nimport { check2004ValidFormat } from \"../validation\";\nimport { Scorm2004ValidationError } from \"../../../exceptions/scorm2004_exceptions\";\nimport { scorm2004_errors } from \"../../../constants/error_codes\";\nimport { CompletionStatus, SuccessStatus } from \"../../../constants/enums\";\nimport { SequencingControls } from \"./sequencing_controls\";\nimport { SequencingRules } from \"./sequencing_rules\";\nimport { RollupRules } from \"./rollup_rules\";\nimport { validateISO8601Duration } from \"../../../utilities\";\nimport {\n  AuxiliaryResource,\n  HideLmsUiItem,\n  HIDE_LMS_UI_TOKENS,\n} from \"../../../types/sequencing_types\";\n\nexport interface ObjectiveMapInfo {\n  targetObjectiveID: string;\n  readSatisfiedStatus?: boolean;\n  readNormalizedMeasure?: boolean;\n  writeSatisfiedStatus?: boolean;\n  writeNormalizedMeasure?: boolean;\n  readCompletionStatus?: boolean;\n  writeCompletionStatus?: boolean;\n  readProgressMeasure?: boolean;\n  writeProgressMeasure?: boolean;\n  readRawScore?: boolean;\n  writeRawScore?: boolean;\n  readMinScore?: boolean;\n  writeMinScore?: boolean;\n  readMaxScore?: boolean;\n  writeMaxScore?: boolean;\n  updateAttemptData?: boolean;\n}\n\nexport interface SharedDataMapInfo {\n  targetID: string;\n  readSharedData: boolean;\n  writeSharedData: boolean;\n}\n\nexport interface ActivityObjectiveOptions {\n  description?: string | null;\n  satisfiedByMeasure?: boolean;\n  minNormalizedMeasure?: number | null;\n  mapInfo?: ObjectiveMapInfo[];\n  isPrimary?: boolean;\n}\n\nexport interface ActivityObjectiveState {\n  id: string;\n  satisfiedStatus: boolean;\n  measureStatus: boolean;\n  normalizedMeasure: number;\n  rawScore: string;\n  rawScoreKnown: boolean;\n  minScore: string;\n  minScoreKnown: boolean;\n  maxScore: string;\n  maxScoreKnown: boolean;\n  progressMeasure: number;\n  progressMeasureStatus: boolean;\n  completionStatus: CompletionStatus;\n  satisfiedByMeasure?: boolean;\n  minNormalizedMeasure?: number | null;\n  progressStatus: boolean;\n}\n\nexport interface ActivityObjectiveScoreState {\n  rawScore?: string;\n  minScore?: string;\n  maxScore?: string;\n}\n\nexport interface ActivityObjectiveReadState extends ActivityObjectiveScoreState {\n  satisfiedStatus?: boolean;\n  satisfiedStatusKnown?: boolean;\n  normalizedMeasure?: number;\n  normalizedMeasureKnown?: boolean;\n  progressMeasure?: number;\n  completionStatus?: CompletionStatus;\n}\n\nexport type ActivityObjectiveDirtyProperty =\n  | \"satisfiedStatus\"\n  | \"normalizedMeasure\"\n  | \"completionStatus\"\n  | \"progressMeasure\"\n  | \"rawScore\"\n  | \"minScore\"\n  | \"maxScore\";\n\nexport type RollupConsiderationRequirement =\n  \"always\" | \"ifAttempted\" | \"ifNotSkipped\" | \"ifNotSuspended\";\n\nexport interface RollupConsiderationsConfig {\n  requiredForSatisfied: RollupConsiderationRequirement;\n  requiredForNotSatisfied: RollupConsiderationRequirement;\n  requiredForCompleted: RollupConsiderationRequirement;\n  requiredForIncomplete: RollupConsiderationRequirement;\n  measureSatisfactionIfActive: boolean;\n}\n\n/**\n * Snapshot of rollup status for optimization comparison\n * Used by Overall Rollup Process (RB.1.5) to detect when status stops changing\n */\nexport interface RollupStatusSnapshot {\n  measureStatus: boolean;\n  normalizedMeasure: number;\n  objectiveProgressStatus: boolean;\n  objectiveSatisfiedStatus: boolean;\n  attemptProgressStatus: boolean;\n  attemptCompletionStatus: boolean;\n  attemptCompletionAmount: number;\n  attemptCompletionAmountStatus: boolean;\n}\n\nexport class ActivityObjective {\n  private _id: string;\n  private _description: string | null;\n  private _satisfiedByMeasure: boolean;\n  private _minNormalizedMeasure: number | null;\n  private _mapInfo: ObjectiveMapInfo[];\n  private _isPrimary: boolean;\n\n  private _satisfiedStatus: boolean = false;\n  private _satisfiedStatusKnown: boolean = false;\n  // Note: measureStatus has no dirty flag because it is not synchronized to global\n  // objectives. It serves as a validity gate for other synced properties.\n  private _measureStatus: boolean = false;\n  private _normalizedMeasure: number = 0;\n  private _rawScore: string = \"\";\n  private _rawScoreKnown: boolean = false;\n  private _minScore: string = \"\";\n  private _minScoreKnown: boolean = false;\n  private _maxScore: string = \"\";\n  private _maxScoreKnown: boolean = false;\n  private _progressMeasure: number = 0;\n  private _progressMeasureStatus: boolean = false;\n  private _completionStatus: CompletionStatus = CompletionStatus.UNKNOWN;\n  private _progressStatus: boolean = false;\n\n  // Dirty flags for tracking which properties have been modified locally\n  private _satisfiedStatusDirty: boolean = false;\n  private _normalizedMeasureDirty: boolean = false;\n  private _completionStatusDirty: boolean = false;\n  private _progressMeasureDirty: boolean = false;\n  private _rawScoreDirty: boolean = false;\n  private _minScoreDirty: boolean = false;\n  private _maxScoreDirty: boolean = false;\n\n  constructor(id: string, options: ActivityObjectiveOptions = {}) {\n    this._id = id;\n    this._description = options.description ?? null;\n    this._satisfiedByMeasure = options.satisfiedByMeasure ?? false;\n    this._minNormalizedMeasure = options.minNormalizedMeasure ?? null;\n    this._mapInfo = options.mapInfo ? [...options.mapInfo] : [];\n    this._isPrimary = options.isPrimary ?? false;\n  }\n\n  get id(): string {\n    return this._id;\n  }\n\n  get description(): string | null {\n    return this._description;\n  }\n\n  get satisfiedByMeasure(): boolean {\n    return this._satisfiedByMeasure;\n  }\n\n  set satisfiedByMeasure(value: boolean) {\n    this._satisfiedByMeasure = value;\n  }\n\n  get minNormalizedMeasure(): number | null {\n    return this._minNormalizedMeasure;\n  }\n\n  set minNormalizedMeasure(value: number | null) {\n    this._minNormalizedMeasure = value;\n  }\n\n  get mapInfo(): ObjectiveMapInfo[] {\n    return this._mapInfo;\n  }\n\n  set mapInfo(mapInfo: ObjectiveMapInfo[]) {\n    this._mapInfo = [...mapInfo];\n  }\n\n  get isPrimary(): boolean {\n    return this._isPrimary;\n  }\n\n  set isPrimary(value: boolean) {\n    this._isPrimary = value;\n  }\n\n  get satisfiedStatus(): boolean {\n    return this._satisfiedStatus;\n  }\n\n  set satisfiedStatus(value: boolean) {\n    if (this._satisfiedStatus !== value) {\n      this._satisfiedStatus = value;\n      this._satisfiedStatusDirty = true;\n      this._satisfiedStatusKnown = true;\n      this._progressStatus = true;\n    }\n  }\n\n  get satisfiedStatusKnown(): boolean {\n    return this._satisfiedStatusKnown;\n  }\n\n  set satisfiedStatusKnown(value: boolean) {\n    this._satisfiedStatusKnown = value;\n  }\n\n  get measureStatus(): boolean {\n    return this._measureStatus;\n  }\n\n  set measureStatus(value: boolean) {\n    this._measureStatus = value;\n  }\n\n  get normalizedMeasure(): number {\n    return this._normalizedMeasure;\n  }\n\n  set normalizedMeasure(value: number) {\n    if (this._normalizedMeasure !== value) {\n      this._normalizedMeasure = value;\n      this._normalizedMeasureDirty = true;\n    }\n  }\n\n  /**\n   * Return the known raw score value held for ADLSEQ objective score mapping.\n   *\n   * @spec SCORM 2004 4th Ed. ADLSEQ objectives extension - raw score mapInfo\n   */\n  get rawScore(): string {\n    return this._rawScore;\n  }\n\n  /**\n   * Store the RTE raw score associated with this objective.\n   *\n   * @spec SCORM 2004 4th Ed. SN 3.10.3 / ADLSEQ objectives extension - raw score mapInfo\n   */\n  set rawScore(value: string) {\n    if (this._rawScore !== value) {\n      this._rawScore = value;\n      this._rawScoreDirty = true;\n    }\n    this._rawScoreKnown = value !== \"\";\n  }\n\n  /**\n   * Return whether this objective's raw score is known.\n   *\n   * @spec SCORM 2004 4th Ed. ADLSEQ objectives extension - raw score known state\n   */\n  get rawScoreKnown(): boolean {\n    return this._rawScoreKnown;\n  }\n\n  /**\n   * Set whether this objective's raw score is known.\n   *\n   * @spec SCORM 2004 4th Ed. ADLSEQ objectives extension - raw score known state\n   */\n  set rawScoreKnown(value: boolean) {\n    this._rawScoreKnown = value;\n  }\n\n  /**\n   * Return the known minimum score value held for ADLSEQ objective score mapping.\n   *\n   * @spec SCORM 2004 4th Ed. ADLSEQ objectives extension - min score mapInfo\n   */\n  get minScore(): string {\n    return this._minScore;\n  }\n\n  /**\n   * Store the RTE minimum score associated with this objective.\n   *\n   * @spec SCORM 2004 4th Ed. SN 3.10.3 / ADLSEQ objectives extension - min score mapInfo\n   */\n  set minScore(value: string) {\n    if (this._minScore !== value) {\n      this._minScore = value;\n      this._minScoreDirty = true;\n    }\n    this._minScoreKnown = value !== \"\";\n  }\n\n  /**\n   * Return whether this objective's minimum score is known.\n   *\n   * @spec SCORM 2004 4th Ed. ADLSEQ objectives extension - min score known state\n   */\n  get minScoreKnown(): boolean {\n    return this._minScoreKnown;\n  }\n\n  /**\n   * Set whether this objective's minimum score is known.\n   *\n   * @spec SCORM 2004 4th Ed. ADLSEQ objectives extension - min score known state\n   */\n  set minScoreKnown(value: boolean) {\n    this._minScoreKnown = value;\n  }\n\n  /**\n   * Return the known maximum score value held for ADLSEQ objective score mapping.\n   *\n   * @spec SCORM 2004 4th Ed. ADLSEQ objectives extension - max score mapInfo\n   */\n  get maxScore(): string {\n    return this._maxScore;\n  }\n\n  /**\n   * Store the RTE maximum score associated with this objective.\n   *\n   * @spec SCORM 2004 4th Ed. SN 3.10.3 / ADLSEQ objectives extension - max score mapInfo\n   */\n  set maxScore(value: string) {\n    if (this._maxScore !== value) {\n      this._maxScore = value;\n      this._maxScoreDirty = true;\n    }\n    this._maxScoreKnown = value !== \"\";\n  }\n\n  /**\n   * Return whether this objective's maximum score is known.\n   *\n   * @spec SCORM 2004 4th Ed. ADLSEQ objectives extension - max score known state\n   */\n  get maxScoreKnown(): boolean {\n    return this._maxScoreKnown;\n  }\n\n  /**\n   * Set whether this objective's maximum score is known.\n   *\n   * @spec SCORM 2004 4th Ed. ADLSEQ objectives extension - max score known state\n   */\n  set maxScoreKnown(value: boolean) {\n    this._maxScoreKnown = value;\n  }\n\n  get progressMeasure(): number {\n    return this._progressMeasure;\n  }\n\n  set progressMeasure(value: number) {\n    if (this._progressMeasure !== value) {\n      this._progressMeasure = value;\n      this._progressMeasureDirty = true;\n    }\n  }\n\n  get progressMeasureStatus(): boolean {\n    return this._progressMeasureStatus;\n  }\n\n  set progressMeasureStatus(value: boolean) {\n    this._progressMeasureStatus = value;\n  }\n\n  get completionStatus(): CompletionStatus {\n    return this._completionStatus;\n  }\n\n  set completionStatus(value: CompletionStatus) {\n    if (this._completionStatus !== value) {\n      this._completionStatus = value;\n      this._completionStatusDirty = true;\n    }\n  }\n\n  get progressStatus(): boolean {\n    return this._progressStatus;\n  }\n\n  set progressStatus(value: boolean) {\n    this._progressStatus = value;\n  }\n\n  /**\n   * Report whether a local objective field has changed since the last global write.\n   *\n   * @spec SCORM 2004 4th Ed. SN 3.10.3 / ADLSEQ objectives extension - write maps use known local objective data\n   */\n  public isDirty(property: ActivityObjectiveDirtyProperty): boolean {\n    switch (property) {\n      case \"satisfiedStatus\":\n        return this._satisfiedStatusDirty;\n      case \"normalizedMeasure\":\n        return this._normalizedMeasureDirty;\n      case \"completionStatus\":\n        return this._completionStatusDirty;\n      case \"progressMeasure\":\n        return this._progressMeasureDirty;\n      case \"rawScore\":\n        return this._rawScoreDirty;\n      case \"minScore\":\n        return this._minScoreDirty;\n      case \"maxScore\":\n        return this._maxScoreDirty;\n    }\n  }\n\n  /**\n   * Clear a local objective dirty flag after a successful global write.\n   *\n   * @spec SCORM 2004 4th Ed. SN 3.10.3 / ADLSEQ objectives extension - write maps update global objective state\n   */\n  public clearDirty(property: ActivityObjectiveDirtyProperty): void {\n    switch (property) {\n      case \"satisfiedStatus\":\n        this._satisfiedStatusDirty = false;\n        break;\n      case \"normalizedMeasure\":\n        this._normalizedMeasureDirty = false;\n        break;\n      case \"completionStatus\":\n        this._completionStatusDirty = false;\n        break;\n      case \"progressMeasure\":\n        this._progressMeasureDirty = false;\n        break;\n      case \"rawScore\":\n        this._rawScoreDirty = false;\n        break;\n      case \"minScore\":\n        this._minScoreDirty = false;\n        break;\n      case \"maxScore\":\n        this._maxScoreDirty = false;\n        break;\n    }\n  }\n\n  /**\n   * Clear all write-map dirty flags for this objective.\n   *\n   * @spec SCORM 2004 4th Ed. SN 3.10.3 - objective mapInfo writes are field-specific\n   * @spec SCORM 2004 4th Ed. ADLSEQ objectives extension - score mapInfo writes are field-specific\n   */\n  public clearAllDirty(): void {\n    this._satisfiedStatusDirty = false;\n    this._normalizedMeasureDirty = false;\n    this._completionStatusDirty = false;\n    this._progressMeasureDirty = false;\n    this._rawScoreDirty = false;\n    this._minScoreDirty = false;\n    this._maxScoreDirty = false;\n  }\n\n  /**\n   * Initialize objective values from CMI data transfer\n   * This method always marks values as dirty since CMI data should be written to global objectives,\n   * even if the values match the current defaults (e.g., satisfiedStatus = false, normalizedMeasure = 0)\n   * Note: Callers must separately set satisfiedStatusKnown based on CMI data availability.\n   * @param satisfiedStatus - The satisfied status from CMI\n   * @param normalizedMeasure - The normalized measure from CMI\n   * @param measureStatus - Whether measure is valid\n   *\n   * @spec SCORM 2004 4th Ed. RTE-to-SN Data Transfer - objective satisfaction and measure transfer\n   */\n  public initializeFromCMI(\n    satisfiedStatus: boolean,\n    normalizedMeasure: number,\n    measureStatus: boolean,\n  ): void {\n    this._satisfiedStatus = satisfiedStatus;\n    this._satisfiedStatusDirty = true;\n    this._normalizedMeasure = normalizedMeasure;\n    this._normalizedMeasureDirty = true;\n    this._measureStatus = measureStatus;\n  }\n\n  /**\n   * Record a content-written unknown satisfied status for objective-map transfer.\n   *\n   * @spec SCORM 2004 4th Ed. RTE 4.2.17 / SN 3.10.3 - Objective Progress\n   *   Status is independent from Objective Measure Status, and a mapped unknown\n   *   satisfaction value replaces a previously known value.\n   */\n  public initializeUnknownSatisfiedStatusFromCMI(): void {\n    this._satisfiedStatus = false;\n    this._satisfiedStatusKnown = false;\n    this._progressStatus = false;\n    this._satisfiedStatusDirty = true;\n  }\n\n  /**\n   * Record a content-written unknown completion status for objective-map transfer.\n   *\n   * A fresh attempt's local objective is already unknown, so the normal setter\n   * cannot distinguish that default from content explicitly clearing a known\n   * read-mapped value exposed through the RTE.\n   *\n   * @spec SCORM 2004 4th Ed. RTE 4.2.17 / SN 3.10.3 - an explicit\n   *   objective completion status of unknown replaces mapped global state.\n   */\n  public initializeUnknownCompletionStatusFromCMI(): void {\n    this._completionStatus = CompletionStatus.UNKNOWN;\n    this._completionStatusDirty = true;\n  }\n\n  /**\n   * Initialize raw/min/max objective score values from RTE data transfer.\n   *\n   * @spec SCORM 2004 4th Ed. RTE-to-SN Data Transfer - objective score transfer\n   * @spec SCORM 2004 4th Ed. ADLSEQ objectives extension - raw/min/max score mapInfo writes\n   */\n  public initializeScoreFromCMI(score: ActivityObjectiveScoreState): void {\n    if (score.rawScore !== undefined && score.rawScore !== \"\") {\n      this._rawScore = score.rawScore;\n      this._rawScoreKnown = true;\n      this._rawScoreDirty = true;\n    }\n\n    if (score.minScore !== undefined && score.minScore !== \"\") {\n      this._minScore = score.minScore;\n      this._minScoreKnown = true;\n      this._minScoreDirty = true;\n    }\n\n    if (score.maxScore !== undefined && score.maxScore !== \"\") {\n      this._maxScore = score.maxScore;\n      this._maxScoreKnown = true;\n      this._maxScoreDirty = true;\n    }\n  }\n\n  /**\n   * Apply read-mapped global objective state without marking the values dirty.\n   *\n   * @spec SCORM 2004 4th Ed. SN 3.10.3 - read maps provide access to global objective state\n   * @spec SCORM 2004 4th Ed. ADLSEQ objectives extension - score read maps are access-only\n   */\n  public applyReadMappedState(state: ActivityObjectiveReadState): void {\n    if (state.satisfiedStatusKnown !== undefined) {\n      this._satisfiedStatusKnown = state.satisfiedStatusKnown;\n      this._progressStatus = state.satisfiedStatusKnown;\n      if (!state.satisfiedStatusKnown) {\n        this._satisfiedStatus = false;\n      }\n    }\n\n    if (state.satisfiedStatus !== undefined) {\n      this._satisfiedStatus = state.satisfiedStatus;\n      this._satisfiedStatusKnown = true;\n      this._progressStatus = true;\n    }\n\n    if (state.normalizedMeasureKnown !== undefined) {\n      this._measureStatus = state.normalizedMeasureKnown;\n      if (!state.normalizedMeasureKnown) {\n        this._normalizedMeasure = 0;\n      }\n    }\n\n    if (state.normalizedMeasure !== undefined) {\n      this._normalizedMeasure = state.normalizedMeasure;\n      this._measureStatus = true;\n    }\n\n    if (state.completionStatus !== undefined) {\n      this._completionStatus = state.completionStatus;\n    }\n\n    if (state.progressMeasure !== undefined) {\n      this._progressMeasure = state.progressMeasure;\n      this._progressMeasureStatus = true;\n    }\n\n    if (state.rawScore !== undefined) {\n      this._rawScore = state.rawScore;\n      this._rawScoreKnown = true;\n    }\n\n    if (state.minScore !== undefined) {\n      this._minScore = state.minScore;\n      this._minScoreKnown = true;\n    }\n\n    if (state.maxScore !== undefined) {\n      this._maxScore = state.maxScore;\n      this._maxScoreKnown = true;\n    }\n  }\n\n  /**\n   * Reset local objective state for a fresh activity attempt.\n   *\n   * @spec SCORM 2004 4th Ed. SN 3.10 Objective Description - unknown objective state before tracking data exists\n   * @spec SCORM 2004 4th Ed. ADLSEQ objectives extension - score map fields are unknown until transferred or read\n   */\n  resetState(): void {\n    this._satisfiedStatus = false;\n    this._satisfiedStatusKnown = false;\n    this._measureStatus = false;\n    this._normalizedMeasure = 0;\n    this._rawScore = \"\";\n    this._rawScoreKnown = false;\n    this._minScore = \"\";\n    this._minScoreKnown = false;\n    this._maxScore = \"\";\n    this._maxScoreKnown = false;\n    this._progressMeasure = 0;\n    this._progressMeasureStatus = false;\n    this._completionStatus = CompletionStatus.UNKNOWN;\n    this._progressStatus = false;\n    this.clearAllDirty();\n  }\n\n  /**\n   * Copy primary activity objective state back into the primary objective model.\n   *\n   * @spec SCORM 2004 4th Ed. RTE-to-SN Data Transfer - primary objective state is available to sequencing\n   */\n  updateFromActivity(activity: Activity): void {\n    if (this._satisfiedStatus !== activity.objectiveSatisfiedStatus) {\n      this._satisfiedStatus = activity.objectiveSatisfiedStatus;\n      this._satisfiedStatusDirty = true;\n    }\n    this._satisfiedStatusKnown = activity.objectiveSatisfiedStatusKnown;\n    this._measureStatus = activity.objectiveMeasureStatus;\n    if (this._normalizedMeasure !== activity.objectiveNormalizedMeasure) {\n      this._normalizedMeasure = activity.objectiveNormalizedMeasure;\n      this._normalizedMeasureDirty = true;\n    }\n    if (this._progressMeasure !== activity.progressMeasure) {\n      this._progressMeasure = activity.progressMeasure;\n      this._progressMeasureDirty = true;\n    }\n    this._progressMeasureStatus = activity.progressMeasureStatus;\n    if (this._completionStatus !== activity.completionStatus) {\n      this._completionStatus = activity.completionStatus as CompletionStatus;\n      this._completionStatusDirty = true;\n    }\n  }\n\n  /**\n   * Apply primary objective state to the owning activity for sequencing rules and rollup.\n   *\n   * @spec SCORM 2004 4th Ed. SN 3.10 Objective Description - primary objective contributes activity state\n   */\n  applyToActivity(activity: Activity): void {\n    if (!this._isPrimary) {\n      return;\n    }\n\n    activity.setPrimaryObjectiveState(\n      this._satisfiedStatus,\n      this._measureStatus,\n      this._normalizedMeasure,\n      this._progressMeasure,\n      this._progressMeasureStatus,\n      this._completionStatus,\n      this._progressStatus || this._satisfiedStatusKnown,\n    );\n  }\n}\n\n/**\n * Class representing a single activity in the SCORM 2004 activity tree\n */\nexport class Activity extends BaseCMI {\n  private _id: string = \"\";\n  private _title: string = \"\";\n  private _children: Activity[] = [];\n  private _parent: Activity | null = null;\n  private _isVisible: boolean = true;\n  private _isActive: boolean = false;\n  private _isSuspended: boolean = false;\n  // Transient delivery context. This is deliberately excluded from persisted activity state.\n  private _deliveryWasResumed: boolean = false;\n  private _isCompleted: boolean = false;\n  private _completionStatus: CompletionStatus = CompletionStatus.UNKNOWN;\n  private _successStatus: SuccessStatus = SuccessStatus.UNKNOWN;\n  private _attemptCount: number = 0;\n  private _objectiveInfoAvailableInCurrentParentAttempt: boolean = true;\n  private _progressInfoAvailableInCurrentParentAttempt: boolean = true;\n  private _attemptCompletionAmount: number = 0;\n  private _attemptAbsoluteDuration: string = \"PT0H0M0S\";\n  private _attemptExperiencedDuration: string = \"PT0H0M0S\";\n  private _activityAbsoluteDuration: string = \"PT0H0M0S\";\n  private _activityExperiencedDuration: string = \"PT0H0M0S\";\n\n  // Duration tracking fields (separate from limits) - actual calculated values\n  private _attemptAbsoluteDurationValue: string = \"PT0H0M0S\";\n  private _attemptExperiencedDurationValue: string = \"PT0H0M0S\";\n  private _activityAbsoluteDurationValue: string = \"PT0H0M0S\";\n  private _activityExperiencedDurationValue: string = \"PT0H0M0S\";\n\n  // Timestamp tracking for duration calculation\n  private _activityStartTimestampUtc: string | null = null;\n  private _attemptStartTimestampUtc: string | null = null;\n  private _activityEndedDate: Date | null = null;\n\n  private _objectiveSatisfiedStatus: boolean = false;\n  private _objectiveSatisfiedStatusKnown: boolean = false;\n  private _objectiveMeasureStatus: boolean = false;\n  private _objectiveNormalizedMeasure: number = 0;\n  private _scaledPassingScore: number = 1.0; // SCORM default minimum normalized measure\n\n  // Dirty flags for tracking which activity-level objective properties have been modified locally\n  private _objectiveSatisfiedStatusDirty: boolean = false;\n  private _objectiveNormalizedMeasureDirty: boolean = false;\n  private _objectiveMeasureStatusDirty: boolean = false;\n  private _progressMeasure: number = 0;\n  private _progressMeasureStatus: boolean = false;\n  private _location: string = \"\";\n  private _attemptAbsoluteStartTime: string = \"\";\n  private _learnerPrefs: any = null;\n  private _activityAttemptActive: boolean = false;\n  private _isHiddenFromChoice: boolean = false;\n  private _isAvailable: boolean = true;\n  private _hideLmsUi: HideLmsUiItem[] = [];\n  private _auxiliaryResources: AuxiliaryResource[] = [];\n  private _sharedDataMaps: SharedDataMapInfo[] = [];\n  private _attemptLimit: number | null = null;\n  private _attemptAbsoluteDurationLimit: string | null = null;\n  private _activityAbsoluteDurationLimit: string | null = null;\n  private _timeLimitAction: string | null = null;\n  private _timeLimitDuration: string | null = null;\n  private _beginTimeLimit: string | null = null;\n  private _endTimeLimit: string | null = null;\n  private _launchData: string = \"\";\n  private _credit: string = \"credit\";\n  private _maxTimeAllowed: string = \"\";\n  private _completionThreshold: string = \"\";\n  private _sequencingControls: SequencingControls;\n  private _sequencingRules: SequencingRules;\n  private _rollupRules: RollupRules;\n  private _processedChildren: Activity[] | null = null;\n  private _isNewAttempt: boolean = false;\n  private _primaryObjective: ActivityObjective | null = null;\n  private _objectives: ActivityObjective[] = [];\n  private _rollupConsiderations: RollupConsiderationsConfig = {\n    requiredForSatisfied: \"always\",\n    requiredForNotSatisfied: \"always\",\n    requiredForCompleted: \"always\",\n    requiredForIncomplete: \"always\",\n    measureSatisfactionIfActive: true,\n  };\n  private _wasSkipped: boolean = false;\n  private _attemptProgressStatus: boolean = false;\n  private _wasAutoCompleted: boolean = false;\n  private _wasAutoSatisfied: boolean = false;\n  private _completedByMeasure: boolean = false;\n  private _minProgressMeasure: number = 1.0;\n  private _progressWeight: number = 1.0;\n  private _attemptCompletionAmountStatus: boolean = false;\n\n  /**\n   * Constructor for Activity\n   * @param {string} id - The unique identifier for this activity\n   * @param {string} title - The title of this activity\n   */\n  constructor(id: string = \"\", title: string = \"\") {\n    super(\"activity\");\n    this._id = id;\n    this._title = title;\n    this._sequencingControls = new SequencingControls();\n    this._sequencingRules = new SequencingRules();\n    this._rollupRules = new RollupRules();\n    this._primaryObjective = null;\n    this._objectives = [];\n  }\n\n  /**\n   * Called when the API has been initialized after the CMI has been created\n   */\n  override initialize() {\n    super.initialize();\n    // Initialize children\n    for (const child of this._children) {\n      child.initialize();\n    }\n  }\n\n  /**\n   * Called when the API needs to be reset\n   */\n  reset() {\n    this._initialized = false;\n    this._isActive = false;\n    this._isSuspended = false;\n    this._deliveryWasResumed = false;\n    this._isCompleted = false;\n    this._completionStatus = CompletionStatus.UNKNOWN;\n    this._successStatus = SuccessStatus.UNKNOWN;\n    this._attemptCount = 0;\n    this._objectiveInfoAvailableInCurrentParentAttempt = true;\n    this._progressInfoAvailableInCurrentParentAttempt = true;\n    this._attemptCompletionAmount = 0;\n    this._attemptAbsoluteDuration = \"PT0H0M0S\";\n    this._attemptExperiencedDuration = \"PT0H0M0S\";\n    this._activityAbsoluteDuration = \"PT0H0M0S\";\n    this._activityExperiencedDuration = \"PT0H0M0S\";\n    this._attemptAbsoluteDurationValue = \"PT0H0M0S\";\n    this._attemptExperiencedDurationValue = \"PT0H0M0S\";\n    this._activityAbsoluteDurationValue = \"PT0H0M0S\";\n    this._activityExperiencedDurationValue = \"PT0H0M0S\";\n    this._activityStartTimestampUtc = null;\n    this._attemptStartTimestampUtc = null;\n    this._activityEndedDate = null;\n    this._objectiveSatisfiedStatus = false;\n    this._objectiveSatisfiedStatusKnown = false;\n    this._objectiveMeasureStatus = false;\n    this._objectiveNormalizedMeasure = 0;\n    this._progressMeasure = 0;\n    this._progressMeasureStatus = false;\n    this._location = \"\";\n    this._attemptAbsoluteStartTime = \"\";\n    this._learnerPrefs = null;\n    this._activityAttemptActive = false;\n\n    if (this._primaryObjective) {\n      this._primaryObjective.resetState();\n      this._primaryObjective.updateFromActivity(this);\n    }\n\n    for (const objective of this._objectives) {\n      objective.resetState();\n    }\n\n    // Reset children\n    for (const child of this._children) {\n      child.reset();\n    }\n\n    this._wasSkipped = false;\n    this._attemptProgressStatus = false;\n    this._wasAutoCompleted = false;\n    this._wasAutoSatisfied = false;\n    this._completedByMeasure = false;\n    this._minProgressMeasure = 1.0;\n    this._progressWeight = 1.0;\n    this._attemptCompletionAmountStatus = false;\n    this.clearAllObjectiveDirty();\n  }\n\n  /**\n   * Getter for id\n   * @return {string}\n   */\n  get id(): string {\n    return this._id;\n  }\n\n  /**\n   * Setter for id\n   * @param {string} id\n   */\n  set id(id: string) {\n    if (check2004ValidFormat(this._cmi_element + \".id\", id, scorm2004_regex.CMILongIdentifier)) {\n      this._id = id;\n    }\n  }\n\n  /**\n   * Getter for title\n   * @return {string}\n   */\n  get title(): string {\n    return this._title;\n  }\n\n  /**\n   * Setter for title\n   * @param {string} title\n   */\n  set title(title: string) {\n    if (\n      check2004ValidFormat(this._cmi_element + \".title\", title, scorm2004_regex.CMILangString250)\n    ) {\n      this._title = title;\n    }\n  }\n\n  /**\n   * Getter for children\n   * @return {Activity[]}\n   */\n  get children(): Activity[] {\n    return this._children;\n  }\n\n  /**\n   * Add a child activity to this activity\n   * @param {Activity} child - The child activity to add\n   */\n  addChild(child: Activity): void {\n    // noinspection SuspiciousTypeOfGuard\n    if (!(child instanceof Activity)) {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".children\",\n        scorm2004_errors.TYPE_MISMATCH as number,\n      );\n    }\n    child._parent = this;\n    this._children.push(child);\n  }\n\n  /**\n   * Reorder child activities based on provided identifier order\n   * @param {string[]} order - Ordered list of child activity IDs\n   */\n  setChildOrder(order: string[]): void {\n    if (order.length === 0) {\n      return;\n    }\n\n    const childMap = new Map(this._children.map((child) => [child.id, child] as const));\n    const reordered: Activity[] = [];\n\n    for (const id of order) {\n      const child = childMap.get(id);\n      if (child) {\n        reordered.push(child);\n        childMap.delete(id);\n      }\n    }\n\n    if (childMap.size > 0) {\n      for (const child of this._children) {\n        if (childMap.has(child.id)) {\n          reordered.push(child);\n          childMap.delete(child.id);\n        }\n      }\n    }\n\n    if (reordered.length === this._children.length) {\n      this._children.splice(0, this._children.length, ...reordered);\n    }\n  }\n\n  /**\n   * Remove a child activity from this activity\n   * @param {Activity} child - The child activity to remove\n   * @return {boolean} - True if the child was removed, false otherwise\n   */\n  removeChild(child: Activity): boolean {\n    const index = this._children.indexOf(child);\n    if (index !== -1) {\n      this._children.splice(index, 1);\n      child._parent = null;\n      return true;\n    }\n    return false;\n  }\n\n  /**\n   * Getter for parent\n   * @return {Activity | null}\n   */\n  get parent(): Activity | null {\n    return this._parent;\n  }\n\n  /**\n   * Getter for isVisible\n   * @return {boolean}\n   */\n  get isVisible(): boolean {\n    return this._isVisible;\n  }\n\n  /**\n   * Setter for isVisible\n   * @param {boolean} isVisible\n   */\n  set isVisible(isVisible: boolean) {\n    this._isVisible = isVisible;\n  }\n\n  /**\n   * Getter for isActive\n   * @return {boolean}\n   */\n  get isActive(): boolean {\n    return this._isActive;\n  }\n\n  /**\n   * Setter for isActive\n   * @param {boolean} isActive\n   */\n  set isActive(isActive: boolean) {\n    this._isActive = isActive;\n  }\n\n  /**\n   * Getter for isSuspended\n   * @return {boolean}\n   */\n  get isSuspended(): boolean {\n    return this._isSuspended;\n  }\n\n  /**\n   * Setter for isSuspended\n   * @param {boolean} isSuspended\n   */\n  set isSuspended(isSuspended: boolean) {\n    this._isSuspended = isSuspended;\n  }\n\n  /** Whether the current delivery resumed this activity's suspended attempt. */\n  get deliveryWasResumed(): boolean {\n    return this._deliveryWasResumed;\n  }\n\n  set deliveryWasResumed(deliveryWasResumed: boolean) {\n    this._deliveryWasResumed = deliveryWasResumed;\n  }\n\n  /**\n   * Getter for isCompleted\n   * @return {boolean}\n   */\n  get isCompleted(): boolean {\n    return this._isCompleted;\n  }\n\n  /**\n   * Setter for isCompleted\n   * @param {boolean} isCompleted\n   */\n  set isCompleted(isCompleted: boolean) {\n    this._isCompleted = isCompleted;\n    // Update completion status based on boolean value\n    if (isCompleted) {\n      this._completionStatus = CompletionStatus.COMPLETED;\n    } else {\n      this._completionStatus = CompletionStatus.INCOMPLETE;\n    }\n  }\n\n  /**\n   * Getter for completionStatus\n   * @return {CompletionStatus}\n   */\n  get completionStatus(): CompletionStatus {\n    return this._completionStatus;\n  }\n\n  /**\n   * Setter for completionStatus\n   * @param {CompletionStatus} completionStatus\n   */\n  set completionStatus(completionStatus: CompletionStatus) {\n    this._completionStatus = completionStatus;\n    this._isCompleted = completionStatus === CompletionStatus.COMPLETED;\n    this.updatePrimaryObjectiveFromActivity();\n  }\n\n  /**\n   * Getter for successStatus\n   * @return {SuccessStatus}\n   */\n  get successStatus(): SuccessStatus {\n    return this._successStatus;\n  }\n\n  /**\n   * Setter for successStatus\n   * @param {SuccessStatus} successStatus\n   */\n  set successStatus(successStatus: SuccessStatus) {\n    this._successStatus = successStatus;\n  }\n\n  /**\n   * Getter for attemptCount\n   * @return {number}\n   */\n  get attemptCount(): number {\n    return this._attemptCount;\n  }\n\n  /**\n   * Setter for attemptCount\n   * @param {number} value\n   */\n  set attemptCount(value: number) {\n    this._attemptCount = value;\n  }\n\n  /**\n   * Whether this activity's objective tracking belongs to its parent's current attempt.\n   *\n   * @spec SCORM 2004 SN 4th Ed. SM.1 useCurrentAttemptObjectiveInfo\n   */\n  get objectiveInfoAvailableInCurrentParentAttempt(): boolean {\n    return this._objectiveInfoAvailableInCurrentParentAttempt;\n  }\n\n  set objectiveInfoAvailableInCurrentParentAttempt(value: boolean) {\n    this._objectiveInfoAvailableInCurrentParentAttempt = value;\n  }\n\n  /**\n   * Whether this activity's progress tracking belongs to its parent's current attempt.\n   *\n   * @spec SCORM 2004 SN 4th Ed. SM.1 useCurrentAttemptProgressInfo\n   */\n  get progressInfoAvailableInCurrentParentAttempt(): boolean {\n    return this._progressInfoAvailableInCurrentParentAttempt;\n  }\n\n  set progressInfoAvailableInCurrentParentAttempt(value: boolean) {\n    this._progressInfoAvailableInCurrentParentAttempt = value;\n  }\n\n  /**\n   * Getter for attemptCompletionAmount\n   * @return {number}\n   */\n  get attemptCompletionAmount(): number {\n    return this._attemptCompletionAmount;\n  }\n\n  /**\n   * Setter for attemptCompletionAmount\n   * @param {number} value\n   */\n  set attemptCompletionAmount(value: number) {\n    this._attemptCompletionAmount = value;\n  }\n\n  /**\n   * Increment the attempt count\n   */\n  incrementAttemptCount(): void {\n    this._attemptCount++;\n    this._isNewAttempt = true;\n    // Reset processed children on new attempt if needed\n    const controls = this._sequencingControls;\n    if (\n      controls.selectionTiming === \"onEachNewAttempt\" ||\n      controls.randomizationTiming === \"onEachNewAttempt\"\n    ) {\n      this._processedChildren = null;\n    }\n  }\n\n  /**\n   * Initialize the objective progress information for a new activity attempt.\n   * Activity progress information, such as the cumulative attempt count, is retained.\n   *\n   * @spec SCORM 2004 SN 4th Ed. DB.2 step 5.1.1.2.2\n   * @spec SCORM 2004 SN 4th Ed. TM.1.1\n   */\n  initializeObjectiveProgressForNewAttempt(): void {\n    this._objectiveSatisfiedStatus = false;\n    this._objectiveSatisfiedStatusKnown = false;\n    this._objectiveMeasureStatus = false;\n    this._objectiveNormalizedMeasure = 0;\n    this._successStatus = SuccessStatus.UNKNOWN;\n\n    this._primaryObjective?.resetState();\n    for (const objective of this._objectives) {\n      objective.resetState();\n    }\n\n    this.clearAllObjectiveDirty();\n  }\n\n  /**\n   * Initialize the attempt progress information for a new activity attempt.\n   * Definition-model controls and cumulative activity duration remain unchanged.\n   *\n   * @spec SCORM 2004 SN 4th Ed. DB.2 step 5.1.1.2.2\n   * @spec SCORM 2004 SN 4th Ed. TM.1.2.2\n   */\n  initializeAttemptProgressForNewAttempt(): void {\n    this._isCompleted = false;\n    this._completionStatus = CompletionStatus.UNKNOWN;\n    this._attemptCompletionAmount = 0;\n    this._attemptCompletionAmountStatus = false;\n    this._attemptProgressStatus = false;\n    this._progressMeasure = 0;\n    this._progressMeasureStatus = false;\n    this._attemptAbsoluteDurationValue = \"PT0H0M0S\";\n    this._attemptExperiencedDurationValue = \"PT0H0M0S\";\n    this._attemptStartTimestampUtc = null;\n    this._attemptAbsoluteStartTime = \"\";\n    this._location = \"\";\n    this._activityAttemptActive = false;\n    this._wasSkipped = false;\n    this._wasAutoCompleted = false;\n    this._wasAutoSatisfied = false;\n  }\n\n  /**\n   * Initialize all tracking information scoped to a new activity attempt.\n   *\n   * @spec SCORM 2004 SN 4th Ed. DB.2 step 5.1.1.2.2\n   */\n  initializeTrackingForNewAttempt(): void {\n    this.initializeObjectiveProgressForNewAttempt();\n    this.initializeAttemptProgressForNewAttempt();\n  }\n\n  /**\n   * Getter for objectiveSatisfiedStatus\n   * @return {boolean}\n   */\n  get objectiveSatisfiedStatus(): boolean {\n    return this._objectiveSatisfiedStatus;\n  }\n\n  /**\n   * Setter for objectiveSatisfiedStatus\n   * @param {boolean} objectiveSatisfiedStatus\n   */\n  set objectiveSatisfiedStatus(objectiveSatisfiedStatus: boolean) {\n    if (this._objectiveSatisfiedStatus !== objectiveSatisfiedStatus) {\n      this._objectiveSatisfiedStatus = objectiveSatisfiedStatus;\n      this._objectiveSatisfiedStatusDirty = true;\n    }\n    this._objectiveSatisfiedStatusKnown = true; // Mark as known when explicitly set\n    // Update success status based on objective satisfaction\n    if (objectiveSatisfiedStatus) {\n      this._successStatus = SuccessStatus.PASSED;\n    } else {\n      this._successStatus = SuccessStatus.FAILED;\n    }\n    this.updatePrimaryObjectiveFromActivity();\n  }\n\n  /**\n   * Getter for objectiveSatisfiedStatusKnown\n   * Indicates whether the objective satisfied status has been explicitly set\n   * @return {boolean}\n   */\n  get objectiveSatisfiedStatusKnown(): boolean {\n    return this._objectiveSatisfiedStatusKnown;\n  }\n\n  /**\n   * Setter for objectiveSatisfiedStatusKnown\n   * @param {boolean} value\n   */\n  set objectiveSatisfiedStatusKnown(value: boolean) {\n    this._objectiveSatisfiedStatusKnown = value;\n  }\n\n  /**\n   * Getter for objectiveMeasureStatus\n   * @return {boolean}\n   */\n  get objectiveMeasureStatus(): boolean {\n    return this._objectiveMeasureStatus;\n  }\n\n  /**\n   * Setter for objectiveMeasureStatus\n   * @param {boolean} objectiveMeasureStatus\n   */\n  set objectiveMeasureStatus(objectiveMeasureStatus: boolean) {\n    if (this._objectiveMeasureStatus !== objectiveMeasureStatus) {\n      this._objectiveMeasureStatus = objectiveMeasureStatus;\n      this._objectiveMeasureStatusDirty = true;\n    }\n    this.updatePrimaryObjectiveFromActivity();\n  }\n\n  /**\n   * Getter for objectiveNormalizedMeasure\n   * @return {number}\n   */\n  get objectiveNormalizedMeasure(): number {\n    return this._objectiveNormalizedMeasure;\n  }\n\n  /**\n   * Setter for objectiveNormalizedMeasure\n   * @param {number} objectiveNormalizedMeasure\n   */\n  set objectiveNormalizedMeasure(objectiveNormalizedMeasure: number) {\n    if (this._objectiveNormalizedMeasure !== objectiveNormalizedMeasure) {\n      this._objectiveNormalizedMeasure = objectiveNormalizedMeasure;\n      this._objectiveNormalizedMeasureDirty = true;\n    }\n    this.updatePrimaryObjectiveFromActivity();\n  }\n\n  /**\n   * Getter for scaledPassingScore\n   * @return {number}\n   */\n  get scaledPassingScore(): number {\n    return this._scaledPassingScore;\n  }\n\n  /**\n   * Setter for scaledPassingScore\n   * @param {number} scaledPassingScore\n   */\n  set scaledPassingScore(scaledPassingScore: number) {\n    if (scaledPassingScore >= -1 && scaledPassingScore <= 1) {\n      this._scaledPassingScore = scaledPassingScore;\n    }\n  }\n\n  /**\n   * Getter for progressMeasure\n   * @return {number}\n   */\n  get progressMeasure(): number {\n    return this._progressMeasure;\n  }\n\n  /**\n   * Setter for progressMeasure\n   * @param {number} progressMeasure\n   */\n  set progressMeasure(progressMeasure: number) {\n    this._progressMeasure = progressMeasure;\n    this.updatePrimaryObjectiveFromActivity();\n  }\n\n  /**\n   * Getter for progressMeasureStatus\n   * @return {boolean}\n   */\n  get progressMeasureStatus(): boolean {\n    return this._progressMeasureStatus;\n  }\n\n  /**\n   * Setter for progressMeasureStatus\n   * @param {boolean} progressMeasureStatus\n   */\n  set progressMeasureStatus(progressMeasureStatus: boolean) {\n    this._progressMeasureStatus = progressMeasureStatus;\n    this.updatePrimaryObjectiveFromActivity();\n  }\n\n  /**\n   * Getter for location\n   * @return {string}\n   */\n  get location(): string {\n    return this._location;\n  }\n\n  /**\n   * Setter for location\n   * @param {string} location\n   */\n  set location(location: string) {\n    this._location = location;\n  }\n\n  /**\n   * Getter for attemptAbsoluteStartTime\n   * @return {string}\n   */\n  get attemptAbsoluteStartTime(): string {\n    return this._attemptAbsoluteStartTime;\n  }\n\n  /**\n   * Setter for attemptAbsoluteStartTime\n   * @param {string} attemptAbsoluteStartTime\n   */\n  set attemptAbsoluteStartTime(attemptAbsoluteStartTime: string) {\n    this._attemptAbsoluteStartTime = attemptAbsoluteStartTime;\n  }\n\n  /**\n   * Getter for learnerPrefs\n   * @return {any}\n   */\n  get learnerPrefs(): any {\n    return this._learnerPrefs;\n  }\n\n  /**\n   * Setter for learnerPrefs\n   * @param {any} learnerPrefs\n   */\n  set learnerPrefs(learnerPrefs: any) {\n    this._learnerPrefs = learnerPrefs;\n  }\n\n  /**\n   * Getter for activityAttemptActive\n   * @return {boolean}\n   */\n  get activityAttemptActive(): boolean {\n    return this._activityAttemptActive;\n  }\n\n  /**\n   * Setter for activityAttemptActive\n   * @param {boolean} activityAttemptActive\n   */\n  set activityAttemptActive(activityAttemptActive: boolean) {\n    this._activityAttemptActive = activityAttemptActive;\n  }\n\n  /**\n   * Getter for isHiddenFromChoice\n   * @return {boolean}\n   */\n  get isHiddenFromChoice(): boolean {\n    return this._isHiddenFromChoice;\n  }\n\n  /**\n   * Setter for isHiddenFromChoice\n   * @param {boolean} isHiddenFromChoice\n   */\n  set isHiddenFromChoice(isHiddenFromChoice: boolean) {\n    this._isHiddenFromChoice = isHiddenFromChoice;\n  }\n\n  /**\n   * Getter for isAvailable\n   * @return {boolean}\n   */\n  get isAvailable(): boolean {\n    return this._isAvailable;\n  }\n\n  /**\n   * Setter for isAvailable\n   * @param {boolean} isAvailable\n   */\n  set isAvailable(isAvailable: boolean) {\n    this._isAvailable = isAvailable;\n  }\n\n  /**\n   * Getter for attemptLimit\n   * @return {number | null}\n   */\n  get attemptLimit(): number | null {\n    return this._attemptLimit;\n  }\n\n  /**\n   * Setter for attemptLimit\n   * @param {number | null} attemptLimit\n   */\n  set attemptLimit(attemptLimit: number | null) {\n    this._attemptLimit = attemptLimit;\n  }\n\n  /**\n   * Check if attempt limit has been exceeded\n   *\n   * A suspended activity has an attempt in progress. Resuming it (SB.2.6 Resume All, DB.2)\n   * continues that attempt rather than beginning a new one, so the attempt already counted\n   * against the limit is the one being resumed and the limit is not exceeded by it.\n   *\n   * @spec SCORM 2004 4th Ed. SN UP.1 step 1 (Limit Conditions Check Process): a suspended\n   * activity is not checked because only activities that will begin a new attempt are subject\n   * to limit conditions\n   * @spec SCORM 2004 4th Ed. SN DB.2 step 5 (Content Delivery Environment Process): a\n   * suspended activity's attempt count is not incremented when it is delivered again\n   * @return {boolean}\n   */\n  hasAttemptLimitExceeded(): boolean {\n    if (this._attemptLimit === null) {\n      return false;\n    }\n    if (this._isSuspended) {\n      return false;\n    }\n    return this._attemptCount >= this._attemptLimit;\n  }\n\n  /**\n   * Getter for timeLimitDuration\n   * @return {string | null}\n   */\n  get timeLimitDuration(): string | null {\n    return this._timeLimitDuration;\n  }\n\n  /**\n   * Setter for timeLimitDuration\n   * @param {string | null} timeLimitDuration\n   */\n  set timeLimitDuration(timeLimitDuration: string | null) {\n    this._timeLimitDuration = timeLimitDuration;\n  }\n\n  /**\n   * Getter for timeLimitAction\n   * @return {string | null}\n   */\n  get timeLimitAction(): string | null {\n    return this._timeLimitAction;\n  }\n\n  /**\n   * Setter for timeLimitAction\n   * @param {string | null} timeLimitAction\n   */\n  set timeLimitAction(timeLimitAction: string | null) {\n    this._timeLimitAction = timeLimitAction;\n  }\n\n  /**\n   * Getter for beginTimeLimit\n   * @return {string | null}\n   */\n  get beginTimeLimit(): string | null {\n    return this._beginTimeLimit;\n  }\n\n  /**\n   * Setter for beginTimeLimit\n   * @param {string | null} beginTimeLimit\n   */\n  set beginTimeLimit(beginTimeLimit: string | null) {\n    this._beginTimeLimit = beginTimeLimit;\n  }\n\n  /**\n   * Getter for endTimeLimit\n   * @return {string | null}\n   */\n  get endTimeLimit(): string | null {\n    return this._endTimeLimit;\n  }\n\n  /**\n   * Setter for endTimeLimit\n   * @param {string | null} endTimeLimit\n   */\n  set endTimeLimit(endTimeLimit: string | null) {\n    this._endTimeLimit = endTimeLimit;\n  }\n\n  /**\n   * Getter for attemptAbsoluteDurationLimit\n   * @return {string | null}\n   */\n  get attemptAbsoluteDurationLimit(): string | null {\n    return this._attemptAbsoluteDurationLimit;\n  }\n\n  /**\n   * Setter for attemptAbsoluteDurationLimit\n   * @param {string | null} attemptAbsoluteDurationLimit\n   */\n  set attemptAbsoluteDurationLimit(attemptAbsoluteDurationLimit: string | null) {\n    if (attemptAbsoluteDurationLimit !== null) {\n      if (!validateISO8601Duration(attemptAbsoluteDurationLimit, scorm2004_regex.CMITimespan)) {\n        throw new Scorm2004ValidationError(\n          this._cmi_element + \".attemptAbsoluteDurationLimit\",\n          scorm2004_errors.TYPE_MISMATCH as number,\n        );\n      }\n    }\n    this._attemptAbsoluteDurationLimit = attemptAbsoluteDurationLimit;\n  }\n\n  /**\n   * Getter for attemptExperiencedDuration\n   * @return {string}\n   */\n  get attemptExperiencedDuration(): string {\n    return this._attemptExperiencedDuration;\n  }\n\n  /**\n   * Setter for attemptExperiencedDuration\n   * @param {string} attemptExperiencedDuration\n   */\n  set attemptExperiencedDuration(attemptExperiencedDuration: string) {\n    if (!validateISO8601Duration(attemptExperiencedDuration, scorm2004_regex.CMITimespan)) {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".attemptExperiencedDuration\",\n        scorm2004_errors.TYPE_MISMATCH as number,\n      );\n    }\n    this._attemptExperiencedDuration = attemptExperiencedDuration;\n  }\n\n  /**\n   * Getter for activityAbsoluteDurationLimit\n   * @return {string | null}\n   */\n  get activityAbsoluteDurationLimit(): string | null {\n    return this._activityAbsoluteDurationLimit;\n  }\n\n  /**\n   * Setter for activityAbsoluteDurationLimit\n   * @param {string | null} activityAbsoluteDurationLimit\n   */\n  set activityAbsoluteDurationLimit(activityAbsoluteDurationLimit: string | null) {\n    if (activityAbsoluteDurationLimit !== null) {\n      if (!validateISO8601Duration(activityAbsoluteDurationLimit, scorm2004_regex.CMITimespan)) {\n        throw new Scorm2004ValidationError(\n          this._cmi_element + \".activityAbsoluteDurationLimit\",\n          scorm2004_errors.TYPE_MISMATCH as number,\n        );\n      }\n    }\n    this._activityAbsoluteDurationLimit = activityAbsoluteDurationLimit;\n  }\n\n  /**\n   * Getter for activityExperiencedDuration\n   * @return {string}\n   */\n  get activityExperiencedDuration(): string {\n    return this._activityExperiencedDuration;\n  }\n\n  /**\n   * Setter for activityExperiencedDuration\n   * @param {string} activityExperiencedDuration\n   */\n  set activityExperiencedDuration(activityExperiencedDuration: string) {\n    if (!validateISO8601Duration(activityExperiencedDuration, scorm2004_regex.CMITimespan)) {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".activityExperiencedDuration\",\n        scorm2004_errors.TYPE_MISMATCH as number,\n      );\n    }\n    this._activityExperiencedDuration = activityExperiencedDuration;\n  }\n\n  /**\n   * Getter for attemptAbsoluteDuration (alias for limit)\n   * @return {string}\n   */\n  get attemptAbsoluteDuration(): string {\n    return this._attemptAbsoluteDurationLimit || \"PT0H0M0S\";\n  }\n\n  /**\n   * Setter for attemptAbsoluteDuration\n   * @param {string} duration\n   */\n  set attemptAbsoluteDuration(duration: string) {\n    this._attemptAbsoluteDurationLimit = duration;\n  }\n\n  /**\n   * Getter for activityAbsoluteDuration (alias for limit)\n   * @return {string}\n   */\n  get activityAbsoluteDuration(): string {\n    return this._activityAbsoluteDurationLimit || \"PT0H0M0S\";\n  }\n\n  /**\n   * Setter for activityAbsoluteDuration\n   * @param {string} duration\n   */\n  set activityAbsoluteDuration(duration: string) {\n    this._activityAbsoluteDurationLimit = duration;\n  }\n\n  /**\n   * Getter for attemptAbsoluteDurationValue (actual calculated duration)\n   * @return {string}\n   */\n  get attemptAbsoluteDurationValue(): string {\n    return this._attemptAbsoluteDurationValue;\n  }\n\n  /**\n   * Setter for attemptAbsoluteDurationValue\n   * @param {string} duration\n   */\n  set attemptAbsoluteDurationValue(duration: string) {\n    if (!validateISO8601Duration(duration, scorm2004_regex.CMITimespan)) {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".attemptAbsoluteDurationValue\",\n        scorm2004_errors.TYPE_MISMATCH as number,\n      );\n    }\n    this._attemptAbsoluteDurationValue = duration;\n  }\n\n  /**\n   * Getter for attemptExperiencedDurationValue (actual calculated duration)\n   * @return {string}\n   */\n  get attemptExperiencedDurationValue(): string {\n    return this._attemptExperiencedDurationValue;\n  }\n\n  /**\n   * Setter for attemptExperiencedDurationValue\n   * @param {string} duration\n   */\n  set attemptExperiencedDurationValue(duration: string) {\n    if (!validateISO8601Duration(duration, scorm2004_regex.CMITimespan)) {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".attemptExperiencedDurationValue\",\n        scorm2004_errors.TYPE_MISMATCH as number,\n      );\n    }\n    this._attemptExperiencedDurationValue = duration;\n  }\n\n  /**\n   * Getter for activityAbsoluteDurationValue (actual calculated duration)\n   * @return {string}\n   */\n  get activityAbsoluteDurationValue(): string {\n    return this._activityAbsoluteDurationValue;\n  }\n\n  /**\n   * Setter for activityAbsoluteDurationValue\n   * @param {string} duration\n   */\n  set activityAbsoluteDurationValue(duration: string) {\n    if (!validateISO8601Duration(duration, scorm2004_regex.CMITimespan)) {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".activityAbsoluteDurationValue\",\n        scorm2004_errors.TYPE_MISMATCH as number,\n      );\n    }\n    this._activityAbsoluteDurationValue = duration;\n  }\n\n  /**\n   * Getter for activityExperiencedDurationValue (actual calculated duration)\n   * @return {string}\n   */\n  get activityExperiencedDurationValue(): string {\n    return this._activityExperiencedDurationValue;\n  }\n\n  /**\n   * Setter for activityExperiencedDurationValue\n   * @param {string} duration\n   */\n  set activityExperiencedDurationValue(duration: string) {\n    if (!validateISO8601Duration(duration, scorm2004_regex.CMITimespan)) {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".activityExperiencedDurationValue\",\n        scorm2004_errors.TYPE_MISMATCH as number,\n      );\n    }\n    this._activityExperiencedDurationValue = duration;\n  }\n\n  /**\n   * Getter for activityStartTimestampUtc\n   * @return {string | null}\n   */\n  get activityStartTimestampUtc(): string | null {\n    return this._activityStartTimestampUtc;\n  }\n\n  /**\n   * Setter for activityStartTimestampUtc\n   * @param {string | null} timestamp\n   */\n  set activityStartTimestampUtc(timestamp: string | null) {\n    this._activityStartTimestampUtc = timestamp;\n  }\n\n  /**\n   * Getter for attemptStartTimestampUtc\n   * @return {string | null}\n   */\n  get attemptStartTimestampUtc(): string | null {\n    return this._attemptStartTimestampUtc;\n  }\n\n  /**\n   * Setter for attemptStartTimestampUtc\n   * @param {string | null} timestamp\n   */\n  set attemptStartTimestampUtc(timestamp: string | null) {\n    this._attemptStartTimestampUtc = timestamp;\n  }\n\n  /**\n   * Getter for activityEndedDate\n   * @return {Date | null}\n   */\n  get activityEndedDate(): Date | null {\n    return this._activityEndedDate;\n  }\n\n  /**\n   * Setter for activityEndedDate\n   * @param {Date | null} date\n   */\n  set activityEndedDate(date: Date | null) {\n    this._activityEndedDate = date;\n  }\n\n  /**\n   * Getter for sequencingControls\n   * @return {SequencingControls}\n   */\n  get sequencingControls(): SequencingControls {\n    return this._sequencingControls;\n  }\n\n  /**\n   * Setter for sequencingControls\n   * @param {SequencingControls} sequencingControls\n   */\n  set sequencingControls(sequencingControls: SequencingControls) {\n    this._sequencingControls = sequencingControls;\n  }\n\n  /**\n   * Getter for sequencingRules\n   * @return {SequencingRules}\n   */\n  get sequencingRules(): SequencingRules {\n    return this._sequencingRules;\n  }\n\n  /**\n   * Setter for sequencingRules\n   * @param {SequencingRules} sequencingRules\n   */\n  set sequencingRules(sequencingRules: SequencingRules) {\n    this._sequencingRules = sequencingRules;\n  }\n\n  /**\n   * Getter for rollupRules\n   * @return {RollupRules}\n   */\n  get rollupRules(): RollupRules {\n    return this._rollupRules;\n  }\n\n  /**\n   * Setter for rollupRules\n   * @param {RollupRules} rollupRules\n   */\n  set rollupRules(rollupRules: RollupRules) {\n    this._rollupRules = rollupRules;\n  }\n\n  get rollupConsiderations(): RollupConsiderationsConfig {\n    return { ...this._rollupConsiderations };\n  }\n\n  set rollupConsiderations(config: RollupConsiderationsConfig) {\n    this._rollupConsiderations = { ...config };\n  }\n\n  applyRollupConsiderations(settings: Partial<RollupConsiderationsConfig>): void {\n    this._rollupConsiderations = {\n      ...this._rollupConsiderations,\n      ...settings,\n    };\n  }\n\n  /**\n   * Individual rollup consideration getters/setters (RB.1.4.2)\n   * These control when THIS activity is included in parent rollup\n   */\n  get requiredForSatisfied(): RollupConsiderationRequirement {\n    return this._rollupConsiderations.requiredForSatisfied;\n  }\n\n  set requiredForSatisfied(value: RollupConsiderationRequirement) {\n    this._rollupConsiderations.requiredForSatisfied = value;\n  }\n\n  get requiredForNotSatisfied(): RollupConsiderationRequirement {\n    return this._rollupConsiderations.requiredForNotSatisfied;\n  }\n\n  set requiredForNotSatisfied(value: RollupConsiderationRequirement) {\n    this._rollupConsiderations.requiredForNotSatisfied = value;\n  }\n\n  get requiredForCompleted(): RollupConsiderationRequirement {\n    return this._rollupConsiderations.requiredForCompleted;\n  }\n\n  set requiredForCompleted(value: RollupConsiderationRequirement) {\n    this._rollupConsiderations.requiredForCompleted = value;\n  }\n\n  get requiredForIncomplete(): RollupConsiderationRequirement {\n    return this._rollupConsiderations.requiredForIncomplete;\n  }\n\n  set requiredForIncomplete(value: RollupConsiderationRequirement) {\n    this._rollupConsiderations.requiredForIncomplete = value;\n  }\n\n  get wasSkipped(): boolean {\n    return this._wasSkipped;\n  }\n\n  set wasSkipped(value: boolean) {\n    this._wasSkipped = value;\n  }\n\n  get attemptProgressStatus(): boolean {\n    return this._attemptProgressStatus;\n  }\n\n  set attemptProgressStatus(value: boolean) {\n    this._attemptProgressStatus = value;\n  }\n\n  get wasAutoCompleted(): boolean {\n    return this._wasAutoCompleted;\n  }\n\n  set wasAutoCompleted(value: boolean) {\n    this._wasAutoCompleted = value;\n  }\n\n  get wasAutoSatisfied(): boolean {\n    return this._wasAutoSatisfied;\n  }\n\n  set wasAutoSatisfied(value: boolean) {\n    this._wasAutoSatisfied = value;\n  }\n\n  get completedByMeasure(): boolean {\n    return this._completedByMeasure;\n  }\n\n  set completedByMeasure(value: boolean) {\n    this._completedByMeasure = value;\n  }\n\n  get minProgressMeasure(): number {\n    return this._minProgressMeasure;\n  }\n\n  set minProgressMeasure(value: number) {\n    if (value < 0.0 || value > 1.0) {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".minProgressMeasure\",\n        scorm2004_errors.TYPE_MISMATCH as number,\n      );\n    }\n    this._minProgressMeasure = value;\n  }\n\n  get progressWeight(): number {\n    return this._progressWeight;\n  }\n\n  set progressWeight(value: number) {\n    if (value < 0.0) {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".progressWeight\",\n        scorm2004_errors.TYPE_MISMATCH as number,\n      );\n    }\n    this._progressWeight = value;\n  }\n\n  get attemptCompletionAmountStatus(): boolean {\n    return this._attemptCompletionAmountStatus;\n  }\n\n  set attemptCompletionAmountStatus(value: boolean) {\n    this._attemptCompletionAmountStatus = value;\n  }\n\n  /**\n   * Getter for primary objective\n   * @return {ActivityObjective | null}\n   */\n  get primaryObjective(): ActivityObjective | null {\n    return this._primaryObjective;\n  }\n\n  /**\n   * Setter for primary objective\n   * @param {ActivityObjective | null} objective\n   */\n  set primaryObjective(objective: ActivityObjective | null) {\n    this._primaryObjective = objective;\n    if (this._primaryObjective) {\n      this._primaryObjective.isPrimary = true;\n      if (this._primaryObjective.minNormalizedMeasure !== null) {\n        this._scaledPassingScore =\n          this._primaryObjective.minNormalizedMeasure ?? this._scaledPassingScore;\n      }\n      this._primaryObjective.updateFromActivity(this);\n    }\n    this.syncPrimaryObjectiveCollection();\n  }\n\n  /**\n   * Get additional objectives (excludes primary objective)\n   * @return {ActivityObjective[]}\n   */\n  get objectives(): ActivityObjective[] {\n    return this._objectives.filter((obj) => obj.id !== this._primaryObjective?.id);\n  }\n\n  /**\n   * Replace objectives collection\n   * @param {ActivityObjective[]} objectives\n   */\n  set objectives(objectives: ActivityObjective[]) {\n    this._objectives = [...objectives];\n    this.syncPrimaryObjectiveCollection();\n  }\n\n  /**\n   * Add an objective\n   * @param {ActivityObjective} objective\n   */\n  addObjective(objective: ActivityObjective): void {\n    if (!this._objectives.find((obj) => obj.id === objective.id)) {\n      this._objectives.push(objective);\n    }\n  }\n\n  /**\n   * Ensure the primary objective is represented within the objectives collection.\n   */\n  private syncPrimaryObjectiveCollection(): void {\n    if (!this._primaryObjective) {\n      this._objectives = this._objectives.filter((objective) => !objective.isPrimary);\n      return;\n    }\n\n    const existingIndex = this._objectives.findIndex(\n      (objective) => objective.id === this._primaryObjective?.id,\n    );\n\n    if (existingIndex >= 0) {\n      this._objectives[existingIndex] = this._primaryObjective;\n      return;\n    }\n\n    this._objectives = [this._primaryObjective, ...this._objectives];\n  }\n\n  /**\n   * Get objective by ID\n   * @param {string} objectiveId\n   * @return {{ objective: ActivityObjective, isPrimary: boolean } | null}\n   */\n  getObjectiveById(objectiveId: string): {\n    objective: ActivityObjective;\n    isPrimary: boolean;\n  } | null {\n    if (this._primaryObjective?.id === objectiveId) {\n      return { objective: this._primaryObjective, isPrimary: true };\n    }\n    const additional = this._objectives.find((obj) => obj.id === objectiveId);\n    if (additional) {\n      return { objective: additional, isPrimary: false };\n    }\n    return null;\n  }\n\n  /**\n   * Get all objectives including primary\n   * @return {ActivityObjective[]}\n   */\n  getAllObjectives(): ActivityObjective[] {\n    const objectives: ActivityObjective[] = [];\n    if (this._primaryObjective) {\n      objectives.push(this._primaryObjective);\n    }\n    // Filter out the primary objective from _objectives to avoid duplicates\n    // since syncPrimaryObjectiveCollection() adds it to _objectives\n    const additionalObjectives = this._objectives.filter(\n      (obj) => obj !== this._primaryObjective && obj.id !== this._primaryObjective?.id,\n    );\n    return objectives.concat(additionalObjectives);\n  }\n\n  /**\n   * Copy only the state that objective read maps can change during rule evaluation.\n   * Tree links and rule definitions remain shared and read-only in this view.\n   * @spec SCORM 2004 SN 4th Ed. SB.2.2 / SB.2.9 / SM.7 - speculative reads must not change live tracking or dirty flags.\n   */\n  public createObjectiveEvaluationView(): Activity {\n    const view: Activity = Object.assign(Object.create(Activity.prototype), this);\n    const copyObjective = (objective: ActivityObjective): ActivityObjective =>\n      Object.assign(Object.create(ActivityObjective.prototype), objective);\n    view._primaryObjective = this._primaryObjective ? copyObjective(this._primaryObjective) : null;\n    view._objectives = this._objectives.map((objective) =>\n      objective === this._primaryObjective ? view._primaryObjective! : copyObjective(objective),\n    );\n    return view;\n  }\n\n  private updatePrimaryObjectiveFromActivity(): void {\n    if (this._primaryObjective) {\n      this._primaryObjective.updateFromActivity(this);\n    }\n  }\n\n  public isObjectiveDirty(\n    property: \"satisfiedStatus\" | \"normalizedMeasure\" | \"measureStatus\",\n  ): boolean {\n    switch (property) {\n      case \"satisfiedStatus\":\n        return this._objectiveSatisfiedStatusDirty;\n      case \"normalizedMeasure\":\n        return this._objectiveNormalizedMeasureDirty;\n      case \"measureStatus\":\n        return this._objectiveMeasureStatusDirty;\n    }\n  }\n\n  public clearObjectiveDirty(\n    property: \"satisfiedStatus\" | \"normalizedMeasure\" | \"measureStatus\",\n  ): void {\n    switch (property) {\n      case \"satisfiedStatus\":\n        this._objectiveSatisfiedStatusDirty = false;\n        break;\n      case \"normalizedMeasure\":\n        this._objectiveNormalizedMeasureDirty = false;\n        break;\n      case \"measureStatus\":\n        this._objectiveMeasureStatusDirty = false;\n        break;\n    }\n  }\n\n  public clearAllObjectiveDirty(): void {\n    this._objectiveSatisfiedStatusDirty = false;\n    this._objectiveNormalizedMeasureDirty = false;\n    this._objectiveMeasureStatusDirty = false;\n  }\n\n  public setPrimaryObjectiveState(\n    satisfiedStatus: boolean,\n    measureStatus: boolean,\n    normalizedMeasure: number,\n    progressMeasure: number,\n    progressMeasureStatus: boolean,\n    completionStatus: CompletionStatus,\n    objectiveProgressStatus: boolean = true,\n  ): void {\n    if (this._objectiveSatisfiedStatus !== satisfiedStatus) {\n      this._objectiveSatisfiedStatus = satisfiedStatus;\n      this._objectiveSatisfiedStatusDirty = true;\n    }\n    this._objectiveSatisfiedStatusKnown = objectiveProgressStatus;\n    if (objectiveProgressStatus) {\n      this._successStatus = satisfiedStatus ? SuccessStatus.PASSED : SuccessStatus.FAILED;\n    }\n    if (this._objectiveMeasureStatus !== measureStatus) {\n      this._objectiveMeasureStatus = measureStatus;\n      this._objectiveMeasureStatusDirty = true;\n    }\n    if (this._objectiveNormalizedMeasure !== normalizedMeasure) {\n      this._objectiveNormalizedMeasure = normalizedMeasure;\n      this._objectiveNormalizedMeasureDirty = true;\n    }\n    this._progressMeasure = progressMeasure;\n    this._progressMeasureStatus = progressMeasureStatus;\n    this._completionStatus = completionStatus;\n\n    if (this._primaryObjective) {\n      this._primaryObjective.satisfiedStatus = satisfiedStatus;\n      this._primaryObjective.measureStatus = measureStatus;\n      this._primaryObjective.normalizedMeasure = normalizedMeasure;\n      this._primaryObjective.progressMeasure = progressMeasure;\n      this._primaryObjective.progressMeasureStatus = progressMeasureStatus;\n      this._primaryObjective.completionStatus = completionStatus;\n      this._primaryObjective.satisfiedStatusKnown = objectiveProgressStatus;\n      this._primaryObjective.progressStatus = objectiveProgressStatus;\n    }\n  }\n\n  /**\n   * Snapshot objective state for sequencing persistence.\n   *\n   * @spec SCORM 2004 4th Ed. SN 3.10 Objective Description - objective state persists across attempts\n   * @spec SCORM 2004 4th Ed. ADLSEQ objectives extension - score-map state persists with objective state\n   */\n  public getObjectiveStateSnapshot(): {\n    primary: ActivityObjectiveState | null;\n    objectives: ActivityObjectiveState[];\n  } {\n    const primarySnapshot: ActivityObjectiveState | null = this._primaryObjective\n      ? {\n          id: this._primaryObjective.id,\n          satisfiedStatus: this.objectiveSatisfiedStatus,\n          measureStatus: this.objectiveMeasureStatus,\n          normalizedMeasure: this.objectiveNormalizedMeasure,\n          rawScore: this._primaryObjective.rawScore,\n          rawScoreKnown: this._primaryObjective.rawScoreKnown,\n          minScore: this._primaryObjective.minScore,\n          minScoreKnown: this._primaryObjective.minScoreKnown,\n          maxScore: this._primaryObjective.maxScore,\n          maxScoreKnown: this._primaryObjective.maxScoreKnown,\n          progressMeasure: this.progressMeasure ?? 0,\n          progressMeasureStatus: this.progressMeasureStatus,\n          progressStatus: this._primaryObjective.progressStatus,\n          completionStatus: this.completionStatus as CompletionStatus,\n          satisfiedByMeasure: this._primaryObjective.satisfiedByMeasure,\n          minNormalizedMeasure: this._primaryObjective.minNormalizedMeasure,\n        }\n      : null;\n\n    const additionalSnapshots: ActivityObjectiveState[] = this._objectives.map((objective) => ({\n      id: objective.id,\n      satisfiedStatus: objective.satisfiedStatus,\n      measureStatus: objective.measureStatus,\n      normalizedMeasure: objective.normalizedMeasure,\n      rawScore: objective.rawScore,\n      rawScoreKnown: objective.rawScoreKnown,\n      minScore: objective.minScore,\n      minScoreKnown: objective.minScoreKnown,\n      maxScore: objective.maxScore,\n      maxScoreKnown: objective.maxScoreKnown,\n      progressMeasure: objective.progressMeasure,\n      progressMeasureStatus: objective.progressMeasureStatus,\n      progressStatus: objective.progressStatus,\n      completionStatus: objective.completionStatus as CompletionStatus,\n      satisfiedByMeasure: objective.satisfiedByMeasure,\n      minNormalizedMeasure: objective.minNormalizedMeasure,\n    }));\n\n    return {\n      primary: primarySnapshot,\n      objectives: additionalSnapshots,\n    };\n  }\n\n  /**\n   * Restore objective state from a sequencing persistence snapshot.\n   *\n   * Restored values are cleared of their write-map dirty flags. The snapshot is state that was\n   * already written out, and it is persisted alongside the global objective map that those same\n   * writes produced, so re-flagging it as locally modified is wrong: the write pass of\n   * processGlobalObjectiveMapping walks every activity in the tree, and dirty restored values from\n   * an earlier attempt would be written back over the global objectives just restored from the same\n   * snapshot, silently rolling shared objectives back a generation.\n   *\n   * @spec SCORM 2004 4th Ed. SN 3.10.3 - write mapInfo transfers only local objective data the\n   *   content has modified during the current attempt\n   * @spec SCORM 2004 4th Ed. SN 3.10 Objective Description - persisted objective state restores sequencing state\n   * @spec SCORM 2004 4th Ed. ADLSEQ objectives extension - persisted score-map state restores objective score fields\n   */\n  public applyObjectiveStateSnapshot(snapshot: {\n    primary: ActivityObjectiveState | null;\n    objectives: ActivityObjectiveState[];\n  }): void {\n    if (snapshot.primary) {\n      const primary = this.getObjectiveById(snapshot.primary.id);\n      if (primary && primary.isPrimary) {\n        const state = snapshot.primary;\n        primary.objective.satisfiedByMeasure =\n          state.satisfiedByMeasure ?? primary.objective.satisfiedByMeasure;\n        primary.objective.minNormalizedMeasure =\n          state.minNormalizedMeasure !== undefined\n            ? state.minNormalizedMeasure\n            : primary.objective.minNormalizedMeasure;\n        this.setPrimaryObjectiveState(\n          state.satisfiedStatus,\n          state.measureStatus,\n          state.normalizedMeasure,\n          state.progressMeasure,\n          state.progressMeasureStatus,\n          state.completionStatus,\n          state.progressStatus,\n        );\n        this.applyObjectiveScoreSnapshot(primary.objective, state);\n        primary.objective.clearAllDirty();\n      }\n    }\n\n    for (const state of snapshot.objectives) {\n      const match = this.getObjectiveById(state.id);\n      if (match && !match.isPrimary) {\n        const objective = match.objective;\n        objective.satisfiedStatus = state.satisfiedStatus;\n        objective.measureStatus = state.measureStatus;\n        objective.normalizedMeasure = state.normalizedMeasure;\n        objective.progressMeasure = state.progressMeasure;\n        objective.progressMeasureStatus = state.progressMeasureStatus;\n        objective.completionStatus = state.completionStatus;\n        this.applyObjectiveScoreSnapshot(objective, state);\n        objective.satisfiedByMeasure = state.satisfiedByMeasure ?? objective.satisfiedByMeasure;\n        objective.minNormalizedMeasure =\n          state.minNormalizedMeasure !== undefined\n            ? state.minNormalizedMeasure\n            : objective.minNormalizedMeasure;\n        objective.clearAllDirty();\n      }\n    }\n  }\n\n  /**\n   * Restore known raw/min/max score fields from an objective state snapshot.\n   *\n   * @spec SCORM 2004 4th Ed. ADLSEQ objectives extension - raw/min/max score known flags restore independently\n   */\n  private applyObjectiveScoreSnapshot(\n    objective: ActivityObjective,\n    state: ActivityObjectiveState,\n  ): void {\n    const scoreState: ActivityObjectiveReadState = {};\n\n    if (state.rawScoreKnown) {\n      scoreState.rawScore = state.rawScore;\n    }\n    if (state.minScoreKnown) {\n      scoreState.minScore = state.minScore;\n    }\n    if (state.maxScoreKnown) {\n      scoreState.maxScore = state.maxScore;\n    }\n\n    objective.applyReadMappedState(scoreState);\n  }\n\n  /**\n   * Get available children with selection and randomization applied\n   * @return {Activity[]}\n   */\n  getAvailableChildren(): Activity[] {\n    // If no children, return empty array\n    if (this._children.length === 0) {\n      return [];\n    }\n\n    // If processed children already exist and no new attempt, return them\n    if (this._processedChildren !== null) {\n      return this._processedChildren;\n    }\n\n    // If no processing has been done yet, return all children\n    // The sequencing process will call applySelectionAndRandomization when needed\n    return this._children;\n  }\n\n  /**\n   * Set the processed children (called by SelectionRandomization)\n   * @param {Activity[]} processedChildren\n   */\n  setProcessedChildren(processedChildren: Activity[]): void {\n    this._processedChildren = processedChildren;\n  }\n\n  /**\n   * Reset processed children (used when configuration changes)\n   */\n  resetProcessedChildren(): void {\n    this._processedChildren = null;\n  }\n\n  /**\n   * Get whether this is a new attempt\n   * @return {boolean}\n   */\n  get isNewAttempt(): boolean {\n    return this._isNewAttempt;\n  }\n\n  /**\n   * Set whether this is a new attempt\n   * @param {boolean} isNewAttempt\n   */\n  set isNewAttempt(isNewAttempt: boolean) {\n    this._isNewAttempt = isNewAttempt;\n  }\n\n  /**\n   * Getter for launchData\n   * @return {string}\n   */\n  get launchData(): string {\n    return this._launchData;\n  }\n\n  /**\n   * Setter for launchData\n   * @param {string} launchData\n   */\n  set launchData(launchData: string) {\n    this._launchData = launchData;\n  }\n\n  /**\n   * Getter for credit\n   * @return {string}\n   */\n  get credit(): string {\n    return this._credit;\n  }\n\n  /**\n   * Setter for credit\n   * @param {string} credit\n   */\n  set credit(credit: string) {\n    this._credit = credit;\n  }\n\n  /**\n   * Getter for maxTimeAllowed\n   * @return {string}\n   */\n  get maxTimeAllowed(): string {\n    return this._maxTimeAllowed;\n  }\n\n  /**\n   * Setter for maxTimeAllowed\n   * @param {string} maxTimeAllowed\n   */\n  set maxTimeAllowed(maxTimeAllowed: string) {\n    this._maxTimeAllowed = maxTimeAllowed;\n  }\n\n  /**\n   * Getter for completionThreshold\n   * @return {string}\n   */\n  get completionThreshold(): string {\n    return this._completionThreshold;\n  }\n\n  /**\n   * Setter for completionThreshold\n   * @param {string} completionThreshold\n   */\n  set completionThreshold(completionThreshold: string) {\n    this._completionThreshold = completionThreshold;\n  }\n\n  /**\n   * Get suspension state for this activity and its descendants\n   * Captures all state needed to restore activity tree after suspend/resume\n   * @return {object} - Complete suspension state\n   */\n  getSuspensionState(): object {\n    return {\n      id: this._id,\n      title: this._title,\n      isVisible: this._isVisible,\n      isActive: this._isActive,\n      isSuspended: this._isSuspended,\n      isCompleted: this._isCompleted,\n      completionStatus: this._completionStatus,\n      successStatus: this._successStatus,\n      attemptCount: this._attemptCount,\n      objectiveInfoAvailableInCurrentParentAttempt:\n        this._objectiveInfoAvailableInCurrentParentAttempt,\n      progressInfoAvailableInCurrentParentAttempt:\n        this._progressInfoAvailableInCurrentParentAttempt,\n      attemptCompletionAmount: this._attemptCompletionAmount,\n      attemptAbsoluteDuration: this._attemptAbsoluteDuration,\n      attemptExperiencedDuration: this._attemptExperiencedDuration,\n      activityAbsoluteDuration: this._activityAbsoluteDuration,\n      activityExperiencedDuration: this._activityExperiencedDuration,\n      attemptAbsoluteDurationValue: this._attemptAbsoluteDurationValue,\n      attemptExperiencedDurationValue: this._attemptExperiencedDurationValue,\n      activityAbsoluteDurationValue: this._activityAbsoluteDurationValue,\n      activityExperiencedDurationValue: this._activityExperiencedDurationValue,\n      activityStartTimestampUtc: this._activityStartTimestampUtc,\n      attemptStartTimestampUtc: this._attemptStartTimestampUtc,\n      objectiveSatisfiedStatus: this._objectiveSatisfiedStatus,\n      objectiveSatisfiedStatusKnown: this._objectiveSatisfiedStatusKnown,\n      objectiveMeasureStatus: this._objectiveMeasureStatus,\n      objectiveNormalizedMeasure: this._objectiveNormalizedMeasure,\n      scaledPassingScore: this._scaledPassingScore,\n      progressMeasure: this._progressMeasure,\n      progressMeasureStatus: this._progressMeasureStatus,\n      location: this._location,\n      attemptAbsoluteStartTime: this._attemptAbsoluteStartTime,\n      activityAttemptActive: this._activityAttemptActive,\n      isHiddenFromChoice: this._isHiddenFromChoice,\n      isAvailable: this._isAvailable,\n      sharedDataMaps: this.sharedDataMaps,\n      rollupConsiderations: { ...this._rollupConsiderations },\n      wasSkipped: this._wasSkipped,\n      attemptProgressStatus: this._attemptProgressStatus,\n      wasAutoCompleted: this._wasAutoCompleted,\n      wasAutoSatisfied: this._wasAutoSatisfied,\n      completedByMeasure: this._completedByMeasure,\n      minProgressMeasure: this._minProgressMeasure,\n      progressWeight: this._progressWeight,\n      attemptCompletionAmountStatus: this._attemptCompletionAmountStatus,\n      // Selection/randomization state preservation\n      processedChildren: this._processedChildren ? this._processedChildren.map((c) => c.id) : null,\n      isNewAttempt: this._isNewAttempt,\n      selectionCountStatus: this._sequencingControls.selectionCountStatus,\n      reorderChildren: this._sequencingControls.reorderChildren,\n      // Objective state preservation\n      primaryObjective: this._primaryObjective\n        ? {\n            id: this._primaryObjective.id,\n            satisfiedStatus: this._primaryObjective.satisfiedStatus,\n            satisfiedStatusKnown: this._primaryObjective.satisfiedStatusKnown,\n            measureStatus: this._primaryObjective.measureStatus,\n            normalizedMeasure: this._primaryObjective.normalizedMeasure,\n            rawScore: this._primaryObjective.rawScore,\n            rawScoreKnown: this._primaryObjective.rawScoreKnown,\n            minScore: this._primaryObjective.minScore,\n            minScoreKnown: this._primaryObjective.minScoreKnown,\n            maxScore: this._primaryObjective.maxScore,\n            maxScoreKnown: this._primaryObjective.maxScoreKnown,\n            progressMeasure: this._primaryObjective.progressMeasure,\n            progressMeasureStatus: this._primaryObjective.progressMeasureStatus,\n            completionStatus: this._primaryObjective.completionStatus,\n            satisfiedByMeasure: this._primaryObjective.satisfiedByMeasure,\n            minNormalizedMeasure: this._primaryObjective.minNormalizedMeasure,\n            progressStatus: this._primaryObjective.progressStatus,\n            mapInfo: this._primaryObjective.mapInfo,\n          }\n        : null,\n      objectives: this._objectives.map((obj) => ({\n        id: obj.id,\n        satisfiedStatus: obj.satisfiedStatus,\n        satisfiedStatusKnown: obj.satisfiedStatusKnown,\n        measureStatus: obj.measureStatus,\n        normalizedMeasure: obj.normalizedMeasure,\n        rawScore: obj.rawScore,\n        rawScoreKnown: obj.rawScoreKnown,\n        minScore: obj.minScore,\n        minScoreKnown: obj.minScoreKnown,\n        maxScore: obj.maxScore,\n        maxScoreKnown: obj.maxScoreKnown,\n        progressMeasure: obj.progressMeasure,\n        progressMeasureStatus: obj.progressMeasureStatus,\n        completionStatus: obj.completionStatus,\n        satisfiedByMeasure: obj.satisfiedByMeasure,\n        minNormalizedMeasure: obj.minNormalizedMeasure,\n        progressStatus: obj.progressStatus,\n        mapInfo: obj.mapInfo,\n      })),\n      // Recursively save children state\n      children: this._children.map((child) => child.getSuspensionState()),\n    };\n  }\n\n  /**\n   * Restore suspension state for this activity and its descendants\n   * Restores all state needed to resume from suspended state\n   * @param {any} state - Suspension state to restore\n   */\n  restoreSuspensionState(state: any): void {\n    if (!state) return;\n\n    // Restore basic activity state\n    this._isVisible = state.isVisible ?? this._isVisible;\n    this._isActive = state.isActive ?? this._isActive;\n    this._isSuspended = state.isSuspended ?? this._isSuspended;\n    this._isCompleted = state.isCompleted ?? this._isCompleted;\n    this._completionStatus = state.completionStatus ?? this._completionStatus;\n    this._successStatus = state.successStatus ?? this._successStatus;\n    this._attemptCount = state.attemptCount ?? this._attemptCount;\n    this._objectiveInfoAvailableInCurrentParentAttempt =\n      state.objectiveInfoAvailableInCurrentParentAttempt ??\n      this._objectiveInfoAvailableInCurrentParentAttempt;\n    this._progressInfoAvailableInCurrentParentAttempt =\n      state.progressInfoAvailableInCurrentParentAttempt ??\n      this._progressInfoAvailableInCurrentParentAttempt;\n    this._attemptCompletionAmount = state.attemptCompletionAmount ?? this._attemptCompletionAmount;\n    this._attemptAbsoluteDuration = state.attemptAbsoluteDuration ?? this._attemptAbsoluteDuration;\n    this._attemptExperiencedDuration =\n      state.attemptExperiencedDuration ?? this._attemptExperiencedDuration;\n    this._activityAbsoluteDuration =\n      state.activityAbsoluteDuration ?? this._activityAbsoluteDuration;\n    this._activityExperiencedDuration =\n      state.activityExperiencedDuration ?? this._activityExperiencedDuration;\n    this._attemptAbsoluteDurationValue =\n      state.attemptAbsoluteDurationValue ?? this._attemptAbsoluteDurationValue;\n    this._attemptExperiencedDurationValue =\n      state.attemptExperiencedDurationValue ?? this._attemptExperiencedDurationValue;\n    this._activityAbsoluteDurationValue =\n      state.activityAbsoluteDurationValue ?? this._activityAbsoluteDurationValue;\n    this._activityExperiencedDurationValue =\n      state.activityExperiencedDurationValue ?? this._activityExperiencedDurationValue;\n    this._activityStartTimestampUtc =\n      state.activityStartTimestampUtc ?? this._activityStartTimestampUtc;\n    this._attemptStartTimestampUtc =\n      state.attemptStartTimestampUtc ?? this._attemptStartTimestampUtc;\n\n    // Restore tracking data\n    this._objectiveSatisfiedStatus =\n      state.objectiveSatisfiedStatus ?? this._objectiveSatisfiedStatus;\n    this._objectiveSatisfiedStatusKnown =\n      state.objectiveSatisfiedStatusKnown ?? this._objectiveSatisfiedStatusKnown;\n    this._objectiveMeasureStatus = state.objectiveMeasureStatus ?? this._objectiveMeasureStatus;\n    this._objectiveNormalizedMeasure =\n      state.objectiveNormalizedMeasure ?? this._objectiveNormalizedMeasure;\n    this._scaledPassingScore = state.scaledPassingScore ?? this._scaledPassingScore;\n    this._progressMeasure = state.progressMeasure ?? this._progressMeasure;\n    this._progressMeasureStatus = state.progressMeasureStatus ?? this._progressMeasureStatus;\n    this._location = state.location ?? this._location;\n    this._attemptAbsoluteStartTime =\n      state.attemptAbsoluteStartTime ?? this._attemptAbsoluteStartTime;\n    this._activityAttemptActive = state.activityAttemptActive ?? this._activityAttemptActive;\n    this._isHiddenFromChoice = state.isHiddenFromChoice ?? this._isHiddenFromChoice;\n    this._isAvailable = state.isAvailable ?? this._isAvailable;\n\n    // Restore rollup considerations\n    if (state.rollupConsiderations) {\n      this._rollupConsiderations = { ...state.rollupConsiderations };\n    }\n\n    // Restore other tracking state\n    this._wasSkipped = state.wasSkipped ?? this._wasSkipped;\n    this._attemptProgressStatus = state.attemptProgressStatus ?? this._attemptProgressStatus;\n    this._wasAutoCompleted = state.wasAutoCompleted ?? this._wasAutoCompleted;\n    this._wasAutoSatisfied = state.wasAutoSatisfied ?? this._wasAutoSatisfied;\n    this._completedByMeasure = state.completedByMeasure ?? this._completedByMeasure;\n    this._minProgressMeasure = state.minProgressMeasure ?? this._minProgressMeasure;\n    this._progressWeight = state.progressWeight ?? this._progressWeight;\n    this._attemptCompletionAmountStatus =\n      state.attemptCompletionAmountStatus ?? this._attemptCompletionAmountStatus;\n\n    // Restore selection/randomization state\n    this._isNewAttempt = state.isNewAttempt ?? this._isNewAttempt;\n    if (state.selectionCountStatus !== undefined) {\n      this._sequencingControls.selectionCountStatus = state.selectionCountStatus;\n    }\n    if (state.reorderChildren !== undefined) {\n      this._sequencingControls.reorderChildren = state.reorderChildren;\n    }\n\n    // Restore processedChildren - map IDs back to actual children\n    if (state.processedChildren) {\n      const childMap = new Map(this._children.map((c) => [c.id, c]));\n      this._processedChildren = state.processedChildren\n        .map((id: string) => childMap.get(id))\n        .filter((c: Activity | undefined) => c !== undefined) as Activity[];\n    } else {\n      this._processedChildren = null;\n    }\n\n    // Restore objective state\n    if (state.primaryObjective && this._primaryObjective) {\n      const objective = this._primaryObjective;\n      const objectiveState = state.primaryObjective;\n      objective.satisfiedStatus = objectiveState.satisfiedStatus ?? objective.satisfiedStatus;\n      objective.satisfiedStatusKnown =\n        objectiveState.satisfiedStatusKnown ?? objective.satisfiedStatusKnown;\n      objective.measureStatus = objectiveState.measureStatus ?? objective.measureStatus;\n      objective.normalizedMeasure = objectiveState.normalizedMeasure ?? objective.normalizedMeasure;\n      objective.progressMeasure = objectiveState.progressMeasure ?? objective.progressMeasure;\n      objective.progressMeasureStatus =\n        objectiveState.progressMeasureStatus ?? objective.progressMeasureStatus;\n      objective.completionStatus = objectiveState.completionStatus ?? objective.completionStatus;\n      objective.progressStatus = objectiveState.progressStatus ?? objective.progressStatus;\n      if (objectiveState.rawScore !== undefined) {\n        objective.rawScore = objectiveState.rawScore;\n        objective.rawScoreKnown = objectiveState.rawScoreKnown ?? objectiveState.rawScore !== \"\";\n      }\n      if (objectiveState.minScore !== undefined) {\n        objective.minScore = objectiveState.minScore;\n        objective.minScoreKnown = objectiveState.minScoreKnown ?? objectiveState.minScore !== \"\";\n      }\n      if (objectiveState.maxScore !== undefined) {\n        objective.maxScore = objectiveState.maxScore;\n        objective.maxScoreKnown = objectiveState.maxScoreKnown ?? objectiveState.maxScore !== \"\";\n      }\n      objective.clearAllDirty();\n    }\n\n    if (state.objectives) {\n      for (const objState of state.objectives) {\n        const objective = this._objectives.find((o) => o.id === objState.id);\n        if (objective) {\n          objective.satisfiedStatus = objState.satisfiedStatus ?? objective.satisfiedStatus;\n          objective.satisfiedStatusKnown =\n            objState.satisfiedStatusKnown ?? objective.satisfiedStatusKnown;\n          objective.measureStatus = objState.measureStatus ?? objective.measureStatus;\n          objective.normalizedMeasure = objState.normalizedMeasure ?? objective.normalizedMeasure;\n          objective.progressMeasure = objState.progressMeasure ?? objective.progressMeasure;\n          objective.progressMeasureStatus =\n            objState.progressMeasureStatus ?? objective.progressMeasureStatus;\n          objective.completionStatus = objState.completionStatus ?? objective.completionStatus;\n          objective.progressStatus = objState.progressStatus ?? objective.progressStatus;\n          if (objState.rawScore !== undefined) {\n            objective.rawScore = objState.rawScore;\n            objective.rawScoreKnown = objState.rawScoreKnown ?? objState.rawScore !== \"\";\n          }\n          if (objState.minScore !== undefined) {\n            objective.minScore = objState.minScore;\n            objective.minScoreKnown = objState.minScoreKnown ?? objState.minScore !== \"\";\n          }\n          if (objState.maxScore !== undefined) {\n            objective.maxScore = objState.maxScore;\n            objective.maxScoreKnown = objState.maxScoreKnown ?? objState.maxScore !== \"\";\n          }\n          objective.clearAllDirty();\n        }\n      }\n    }\n\n    // Recursively restore children state\n    if (state.children && Array.isArray(state.children)) {\n      this.setChildOrder(state.children.map((childState: any) => childState.id));\n      for (let i = 0; i < state.children.length && i < this._children.length; i++) {\n        const childState = state.children[i];\n        const child = this._children.find((c) => c.id === childState.id);\n        if (child) {\n          child.restoreSuspensionState(childState);\n        }\n      }\n    }\n  }\n\n  /**\n   * toJSON for Activity\n   * @return {object}\n   */\n  toJSON(): object {\n    this.jsonString = true;\n    const result = {\n      id: this._id,\n      title: this._title,\n      isVisible: this._isVisible,\n      isActive: this._isActive,\n      isSuspended: this._isSuspended,\n      isCompleted: this._isCompleted,\n      completionStatus: this._completionStatus,\n      successStatus: this._successStatus,\n      attemptCount: this._attemptCount,\n      objectiveInfoAvailableInCurrentParentAttempt:\n        this._objectiveInfoAvailableInCurrentParentAttempt,\n      progressInfoAvailableInCurrentParentAttempt:\n        this._progressInfoAvailableInCurrentParentAttempt,\n      attemptCompletionAmount: this._attemptCompletionAmount,\n      attemptAbsoluteDuration: this._attemptAbsoluteDuration,\n      attemptExperiencedDuration: this._attemptExperiencedDuration,\n      activityAbsoluteDuration: this._activityAbsoluteDuration,\n      activityExperiencedDuration: this._activityExperiencedDuration,\n      objectiveSatisfiedStatus: this._objectiveSatisfiedStatus,\n      objectiveSatisfiedStatusKnown: this._objectiveSatisfiedStatusKnown,\n      objectiveMeasureStatus: this._objectiveMeasureStatus,\n      objectiveNormalizedMeasure: this._objectiveNormalizedMeasure,\n      rollupConsiderations: { ...this._rollupConsiderations },\n      wasSkipped: this._wasSkipped,\n      completedByMeasure: this._completedByMeasure,\n      minProgressMeasure: this._minProgressMeasure,\n      progressWeight: this._progressWeight,\n      attemptCompletionAmountStatus: this._attemptCompletionAmountStatus,\n      hideLmsUi: [...this._hideLmsUi],\n      auxiliaryResources: this._auxiliaryResources.map((resource) => ({ ...resource })),\n      sharedDataMaps: this.sharedDataMaps,\n      children: this._children.map((child) => child.toJSON()),\n    };\n    this.jsonString = false;\n    return result;\n  }\n\n  get auxiliaryResources(): AuxiliaryResource[] {\n    return this._auxiliaryResources.map((resource) => ({ ...resource }));\n  }\n\n  /** SCORM 2004 shared-data bucket mappings for this activity. */\n  get sharedDataMaps(): SharedDataMapInfo[] {\n    return this._sharedDataMaps.map((map) => ({ ...map }));\n  }\n\n  set sharedDataMaps(maps: SharedDataMapInfo[]) {\n    this._sharedDataMaps = (maps || [])\n      .filter((map) => map && typeof map.targetID === \"string\" && map.targetID.length > 0)\n      .map((map) => ({\n        targetID: map.targetID,\n        readSharedData: map.readSharedData,\n        writeSharedData: map.writeSharedData,\n      }));\n  }\n\n  set auxiliaryResources(resources: AuxiliaryResource[]) {\n    const sanitized: AuxiliaryResource[] = [];\n    const seen = new Set<string>();\n    for (const resource of resources || []) {\n      if (!resource) continue;\n      const resourceId = typeof resource.resourceId === \"string\" ? resource.resourceId.trim() : \"\";\n      const purpose = typeof resource.purpose === \"string\" ? resource.purpose.trim() : \"\";\n      if (!resourceId || seen.has(resourceId)) {\n        continue;\n      }\n      seen.add(resourceId);\n      sanitized.push({ resourceId, purpose });\n    }\n    this._auxiliaryResources = sanitized;\n  }\n\n  addAuxiliaryResource(resource: AuxiliaryResource): void {\n    this.auxiliaryResources = [...this._auxiliaryResources, resource];\n  }\n\n  /**\n   * Capture current rollup status for optimization comparison\n   * Used by Overall Rollup Process (RB.1.5) to detect when status stops changing\n   * @return {RollupStatusSnapshot} - Snapshot of current rollup-relevant status\n   */\n  captureRollupStatus(): RollupStatusSnapshot {\n    return {\n      measureStatus: this._objectiveMeasureStatus,\n      normalizedMeasure: this._objectiveNormalizedMeasure,\n      objectiveProgressStatus: this._objectiveSatisfiedStatusKnown,\n      objectiveSatisfiedStatus: this._objectiveSatisfiedStatus,\n      attemptProgressStatus: this._completionStatus !== CompletionStatus.UNKNOWN,\n      attemptCompletionStatus: this._completionStatus === CompletionStatus.COMPLETED,\n      attemptCompletionAmount: this._attemptCompletionAmount,\n      attemptCompletionAmountStatus: this._attemptCompletionAmountStatus,\n    };\n  }\n\n  /**\n   * Compare two rollup status snapshots for equality\n   * Uses epsilon comparison for floating point normalizedMeasure\n   * @param {RollupStatusSnapshot} prior - Previous status snapshot\n   * @param {RollupStatusSnapshot} current - Current status snapshot\n   * @return {boolean} - True if statuses are equal (no change), false if different\n   */\n  static compareRollupStatus(prior: RollupStatusSnapshot, current: RollupStatusSnapshot): boolean {\n    const EPSILON = 0.0001; // Floating point comparison tolerance\n\n    return (\n      prior.measureStatus === current.measureStatus &&\n      Math.abs(prior.normalizedMeasure - current.normalizedMeasure) < EPSILON &&\n      prior.objectiveProgressStatus === current.objectiveProgressStatus &&\n      prior.objectiveSatisfiedStatus === current.objectiveSatisfiedStatus &&\n      prior.attemptProgressStatus === current.attemptProgressStatus &&\n      prior.attemptCompletionStatus === current.attemptCompletionStatus &&\n      prior.attemptCompletionAmount === current.attemptCompletionAmount &&\n      prior.attemptCompletionAmountStatus === current.attemptCompletionAmountStatus\n    );\n  }\n\n  /**\n   * Getter for hideLmsUi directives\n   * @return {HideLmsUiItem[]}\n   */\n  get hideLmsUi(): HideLmsUiItem[] {\n    return [...this._hideLmsUi];\n  }\n\n  /**\n   * Setter for hideLmsUi directives\n   * @param {HideLmsUiItem[]} hideLmsUi\n   */\n  set hideLmsUi(hideLmsUi: HideLmsUiItem[]) {\n    const valid = new Set(HIDE_LMS_UI_TOKENS);\n    const seen = new Set<HideLmsUiItem>();\n    const sanitized: HideLmsUiItem[] = [];\n    for (const directive of hideLmsUi) {\n      if (valid.has(directive) && !seen.has(directive)) {\n        seen.add(directive);\n        sanitized.push(directive);\n      }\n    }\n    this._hideLmsUi = sanitized;\n  }\n}\n","import { Activity } from \"../activity\";\nimport { CompletionStatus } from \"../../../../constants/enums\";\n\n/**\n * Type of rollup operation being performed\n */\nexport type RollupType = \"objective\" | \"progress\";\n\n/**\n * Rollup action for consideration filtering\n */\nexport type RollupAction = \"satisfied\" | \"notSatisfied\" | \"completed\" | \"incomplete\";\n\n/**\n * RollupChildFilter - Handles child activity filtering for rollup operations\n * Implements SCORM 2004 RB.1.4.2 (Check Child For Rollup Subprocess)\n *\n * This class is responsible for determining which child activities should\n * contribute to rollup calculations based on their tracking settings and\n * rollup consideration requirements.\n *\n * @spec SN Book: RB.1.4.2 (Check Child For Rollup Subprocess)\n */\nexport class RollupChildFilter {\n  /**\n   * Check Child For Rollup Subprocess\n   * Determines if a child activity contributes to rollup based on its individual consideration settings\n   * This implements the full SCORM 2004 RB.1.4.2 specification\n   *\n   * @spec SN Book: RB.1.4.2 (Check Child For Rollup Subprocess)\n   * @param child - The child activity to check\n   * @param rollupType - Type of rollup (\"objective\", \"progress\")\n   * @param rollupAction - Specific rollup action (satisfied, notSatisfied, completed, incomplete)\n   * @returns True if child contributes to rollup\n   */\n  public checkChildForRollupSubprocess(\n    child: Activity,\n    rollupType: RollupType,\n    rollupAction?: RollupAction,\n  ): boolean {\n    // First check if child is tracked\n    if (child.sequencingControls.tracked === false) {\n      return false;\n    }\n\n    let included = false;\n\n    // RB.1.4.2 Step 2: Check for objective rollup (satisfied/notSatisfied)\n    if (rollupType === \"objective\") {\n      // Step 2.1: Check if child tracks objective rollup\n      if (!child.sequencingControls.rollupObjectiveSatisfied) {\n        return false;\n      }\n\n      // Step 2.1.1: Default to included\n      included = true;\n\n      // Get the child's individual consideration requirements\n      const requiredForSatisfied = child.requiredForSatisfied;\n      const requiredForNotSatisfied = child.requiredForNotSatisfied;\n\n      // Step 2.1.2: Check ifNotSuspended consideration\n      if (\n        (rollupAction === \"satisfied\" && requiredForSatisfied === \"ifNotSuspended\") ||\n        (rollupAction === \"notSatisfied\" && requiredForNotSatisfied === \"ifNotSuspended\")\n      ) {\n        // Step 2.1.2.1: Exclude if not attempted or if attempted and suspended\n        if (!child.attemptProgressStatus || (child.attemptCount > 0 && child.isSuspended)) {\n          included = false;\n        }\n      }\n      // Step 2.1.3: Check ifAttempted consideration\n      else if (\n        (rollupAction === \"satisfied\" && requiredForSatisfied === \"ifAttempted\") ||\n        (rollupAction === \"notSatisfied\" && requiredForNotSatisfied === \"ifAttempted\")\n      ) {\n        // Step 2.1.3.1.1: Exclude if not attempted\n        if (!child.attemptProgressStatus || child.attemptCount === 0) {\n          included = false;\n        }\n      }\n      // Step 2.1.3.2: Check ifNotSkipped consideration\n      else if (\n        (rollupAction === \"satisfied\" && requiredForSatisfied === \"ifNotSkipped\") ||\n        (rollupAction === \"notSatisfied\" && requiredForNotSatisfied === \"ifNotSkipped\")\n      ) {\n        // Step 2.1.3.2.1: Exclude if activity is skipped\n        if (child.wasSkipped) {\n          included = false;\n        }\n      }\n      // \"always\" is the default - activity is included\n    }\n\n    // RB.1.4.2 Step 3: Check for progress rollup (completed/incomplete)\n    if (rollupType === \"progress\") {\n      // Step 3.1: Check if child tracks progress rollup\n      if (!child.sequencingControls.rollupProgressCompletion) {\n        return false;\n      }\n\n      // Step 3.1.1: Default to included\n      included = true;\n\n      // Get the child's individual consideration requirements\n      const requiredForCompleted = child.requiredForCompleted;\n      const requiredForIncomplete = child.requiredForIncomplete;\n\n      // Step 3.1.2: Check ifNotSuspended consideration\n      if (\n        (rollupAction === \"completed\" && requiredForCompleted === \"ifNotSuspended\") ||\n        (rollupAction === \"incomplete\" && requiredForIncomplete === \"ifNotSuspended\")\n      ) {\n        // Step 3.1.2.1: Exclude if not attempted or if attempted and suspended\n        if (!child.attemptProgressStatus || (child.attemptCount > 0 && child.isSuspended)) {\n          included = false;\n        }\n      }\n      // Step 3.1.3: Check ifAttempted consideration\n      else if (\n        (rollupAction === \"completed\" && requiredForCompleted === \"ifAttempted\") ||\n        (rollupAction === \"incomplete\" && requiredForIncomplete === \"ifAttempted\")\n      ) {\n        // Step 3.1.3.1.1: Exclude if not attempted\n        if (!child.attemptProgressStatus || child.attemptCount === 0) {\n          included = false;\n        }\n      }\n      // Step 3.1.3.2: Check ifNotSkipped consideration\n      else if (\n        (rollupAction === \"completed\" && requiredForCompleted === \"ifNotSkipped\") ||\n        (rollupAction === \"incomplete\" && requiredForIncomplete === \"ifNotSkipped\")\n      ) {\n        // Step 3.1.3.2.1: Exclude if activity is skipped\n        if (child.wasSkipped) {\n          included = false;\n        }\n      }\n      // \"always\" is the default - activity is included\n    }\n\n    // Check if child is available for rollup (additional safety check)\n    if (included && !child.isAvailable) {\n      return false;\n    }\n\n    return included;\n  }\n\n  /**\n   * Filter children based on rollup type and mode\n   *\n   * @param children - Child activities to filter\n   * @param rollupType - Type of rollup (\"objective\" | \"progress\")\n   * @param mode - Rollup action mode\n   * @returns Filtered array of children that should contribute to rollup\n   */\n  public filterChildrenForRequirement(\n    children: Activity[],\n    rollupType: \"objective\" | \"progress\",\n    mode: RollupAction,\n  ): Activity[] {\n    return children.filter((child) => this.shouldIncludeChildForRollup(child, rollupType, mode));\n  }\n\n  /**\n   * Check if a specific child should be included in rollup\n   *\n   * @param child - Child activity to check\n   * @param rollupType - Type of rollup (\"objective\" | \"progress\")\n   * @param mode - Rollup action mode\n   * @returns True if child should be included\n   */\n  public shouldIncludeChildForRollup(\n    child: Activity,\n    rollupType: \"objective\" | \"progress\",\n    mode: RollupAction,\n  ): boolean {\n    // Use the enhanced RB.1.4.2 implementation with rollupAction parameter\n    return this.checkChildForRollupSubprocess(child, rollupType, mode);\n  }\n\n  /**\n   * Check if child is satisfied for rollup\n   * Evaluates objective satisfaction status for the current parent attempt\n   *\n   * @param child - Child activity to check\n   * @returns True if child is considered satisfied\n   */\n  public isChildSatisfiedForRollup(child: Activity): boolean {\n    if (child.objectiveInfoAvailableInCurrentParentAttempt === false) {\n      return false;\n    }\n\n    return child.objectiveSatisfiedStatus;\n  }\n\n  /**\n   * Check if a child's objective satisfaction status is actually KNOWN, as opposed\n   * to simply defaulting to \"not satisfied\" because the child was never attempted\n   * in this parent attempt.\n   *\n   * `Activity.objectiveSatisfiedStatus` is a plain boolean that defaults to\n   * `false`, so an untouched child and a child that has genuinely failed both\n   * read as `false` from {@link isChildSatisfiedForRollup}. The default objective\n   * rollup subprocess (RB.1.2.c) must not treat those two cases the same way -\n   * an unknown child contributes no information, while a known-not-satisfied\n   * child forces the parent to \"not satisfied\". `objectiveSatisfiedStatusKnown`\n   * is the flag the rest of the codebase already treats as authoritative for\n   * that distinction (see the identical known/not-known guard in\n   * `SequencingStateManager.deserializeActivities`), so it is used here rather\n   * than the raw boolean.\n   *\n   * @spec SN Book: RB.1.4.2 (Check Child For Rollup Subprocess)\n   * @spec SN Book: RB.1.2.c (Objective Rollup Using Default) and RB.1.4 (Rollup\n   * Rule Check: an unknown status must not evaluate True for either the \"any not\n   * satisfied\" or \"all satisfied\" default checks)\n   * @param child - Child activity to check\n   * @returns True if the child's objective satisfaction status is known for this parent attempt\n   */\n  public isChildObjectiveStatusKnownForRollup(child: Activity): boolean {\n    // @spec SCORM 2004 SN 4th Ed. SM.1 useCurrentAttemptObjectiveInfo: when the\n    // child's objective data is not visible to the current parent attempt, the\n    // parent has no information at all, not a known \"not satisfied\" status.\n    if (child.objectiveInfoAvailableInCurrentParentAttempt === false) {\n      return false;\n    }\n\n    return child.objectiveSatisfiedStatusKnown;\n  }\n\n  /**\n   * Check if child is completed for rollup\n   * Evaluates completion status\n   *\n   * @param child - Child activity to check\n   * @returns True if child is considered completed\n   */\n  public isChildCompletedForRollup(child: Activity): boolean {\n    if (child.progressInfoAvailableInCurrentParentAttempt === false) {\n      return false;\n    }\n\n    if (child.completionStatus === \"completed\" || child.isCompleted) {\n      return true;\n    }\n\n    return false;\n  }\n\n  /**\n   * Check if a child's completion status is actually KNOWN, as opposed to\n   * defaulting to \"incomplete\" because the child was never attempted in this\n   * parent attempt.\n   *\n   * Unlike objective satisfaction, `Activity.completionStatus` already has a\n   * distinct `CompletionStatus.UNKNOWN` value, so \"known\" is simply \"not\n   * unknown\" here - but that distinction is lost by\n   * {@link isChildCompletedForRollup}, which folds \"unknown\" and \"incomplete\"\n   * together into `false`. The default progress rollup subprocess (RB.1.3) must\n   * not let an untouched sibling's unknown completion status masquerade as a\n   * known \"incomplete\" that forces the parent incomplete.\n   *\n   * @spec SN Book: RB.1.4.2 (Check Child For Rollup Subprocess)\n   * @spec SN Book: RB.1.3 (Activity Progress Rollup Using Default: completed if\n   * all children completed, incomplete if any child incomplete - unknown does\n   * not count as either) and RB.1.4 (Rollup Rule Check: unknown does not\n   * evaluate True for \"any\")\n   * @param child - Child activity to check\n   * @returns True if the child's completion status is known for this parent attempt\n   */\n  public isChildCompletionStatusKnownForRollup(child: Activity): boolean {\n    // @spec SCORM 2004 SN 4th Ed. SM.1 useCurrentAttemptProgressInfo: when the\n    // child's progress data is not visible to the current parent attempt, the\n    // parent has no information at all, not a known \"incomplete\" status.\n    if (child.progressInfoAvailableInCurrentParentAttempt === false) {\n      return false;\n    }\n\n    return child.completionStatus !== CompletionStatus.UNKNOWN;\n  }\n\n  /**\n   * Get trackable children for rollup operations\n   * Filters out activities with tracked=false from rollup calculations\n   *\n   * @param activity - The parent activity\n   * @returns Array of trackable children\n   */\n  public getTrackableChildren(activity: Activity): Activity[] {\n    return activity.children.filter((child) => child.sequencingControls.tracked !== false);\n  }\n}\n","import { Activity } from \"../activity\";\nimport {\n  normalizeMinimumPercent,\n  RollupActionType,\n  RollupConditionCombination,\n  RollupConsiderationType,\n  RollupRule,\n} from \"../rollup_rules\";\nimport { RollupChildFilter } from \"./rollup_child_filter\";\nimport { AttemptElapsedSecondsHook } from \"../time_conditions\";\nimport { RuleConditionEvaluation, kleeneAnd, kleeneOr } from \"../sequencing_rules\";\n\n/**\n * The clock time-based rollup conditions are evaluated with\n * (timeLimitExceeded, outsideAvailableTimeRange).\n */\nexport interface RollupClockOptions {\n  /** The evaluating process's clock; defaults to the system clock. */\n  now?: (() => Date) | undefined;\n  /** Reports elapsed attempt seconds; see the `getAttemptElapsedSeconds` setting. */\n  getAttemptElapsedSeconds?: AttemptElapsedSecondsHook | undefined;\n}\n\n/**\n * RollupRuleEvaluator - Handles evaluation of rollup rules\n * Implements SCORM 2004 RB.1.4 (Rollup Rule Check) and RB.1.4.1 (Evaluate Rollup Conditions Subprocess)\n *\n * This class is responsible for evaluating rollup rules against child activities\n * and determining if rule conditions are met.\n *\n * @spec SN Book: RB.1.4 (Rollup Rule Check)\n * @spec SN Book: RB.1.4.1 (Evaluate Rollup Conditions Subprocess)\n */\nexport class RollupRuleEvaluator {\n  private childFilter: RollupChildFilter;\n  private now: () => Date;\n  private getAttemptElapsedSeconds: AttemptElapsedSecondsHook | null;\n\n  /**\n   * Create a new RollupRuleEvaluator\n   *\n   * @param childFilter - RollupChildFilter instance for filtering children\n   * @param clock - Clock for time-based rollup conditions\n   */\n  constructor(childFilter: RollupChildFilter, clock: RollupClockOptions = {}) {\n    this.childFilter = childFilter;\n    this.now = clock.now || (() => new Date());\n    this.getAttemptElapsedSeconds = clock.getAttemptElapsedSeconds || null;\n  }\n\n  /**\n   * Evaluate a rollup rule\n   * Determines if a rollup rule applies to an activity based on its children\n   *\n   * @spec SN Book: RB.1.4 (Rollup Rule Check)\n   * @param activity - The parent activity\n   * @param rule - The rule to evaluate\n   * @returns True if the rule applies\n   */\n  public evaluateRollupRule(activity: Activity, rule: RollupRule): boolean {\n    const children = activity.getAvailableChildren();\n    let contributingChildren = 0;\n    let satisfiedCount = 0;\n    let unknownCount = 0;\n\n    // Count true and unknown results among included children.\n    for (const child of children) {\n      // Step 1: Check if child is included based on consideration settings (RB.1.4.2)\n      let isIncluded = false;\n      switch (rule.action) {\n        case RollupActionType.SATISFIED:\n          isIncluded = this.childFilter.checkChildForRollupSubprocess(\n            child,\n            \"objective\",\n            \"satisfied\",\n          );\n          break;\n        case RollupActionType.NOT_SATISFIED:\n          isIncluded = this.childFilter.checkChildForRollupSubprocess(\n            child,\n            \"objective\",\n            \"notSatisfied\",\n          );\n          break;\n        case RollupActionType.COMPLETED:\n          isIncluded = this.childFilter.checkChildForRollupSubprocess(\n            child,\n            \"progress\",\n            \"completed\",\n          );\n          break;\n        case RollupActionType.INCOMPLETE:\n          isIncluded = this.childFilter.checkChildForRollupSubprocess(\n            child,\n            \"progress\",\n            \"incomplete\",\n          );\n          break;\n      }\n\n      // Step 2: Only count if child is included by consideration settings\n      if (isIncluded) {\n        contributingChildren++;\n\n        // Step 3: Evaluate rule conditions for this child using RB.1.4.1\n        const result = this.evaluateRollupConditionsThreeValued(child, rule);\n        if (result === true) {\n          satisfiedCount++;\n        } else if (result === \"unknown\") {\n          unknownCount++;\n        }\n      }\n    }\n\n    // Apply childActivitySet independently from the atLeast thresholds. RollupRule initializes\n    // those numeric fields to zero, so treating their presence as the discriminator makes \"any\"\n    // and \"none\" rules vacuously true even when no child matches.\n    // @spec SCORM 2004 4th Ed. SN RB.1.4 and TR RU-02a / RU-02b\n    // RB.1.4 step 1.2.4: no rule fires when no child is included (the ADL fork returns true for\n    // \"all\" and \"none\" here).\n    switch (rule.consideration) {\n      case RollupConsiderationType.ALL:\n        return contributingChildren > 0 && satisfiedCount === contributingChildren;\n      case RollupConsiderationType.ANY:\n        return satisfiedCount > 0;\n      case RollupConsiderationType.NONE:\n        return contributingChildren > 0 && satisfiedCount === 0 && unknownCount === 0;\n      case RollupConsiderationType.AT_LEAST_COUNT:\n        return (\n          contributingChildren > 0 &&\n          unknownCount < contributingChildren &&\n          satisfiedCount >= rule.minimumCount\n        );\n      case RollupConsiderationType.AT_LEAST_PERCENT: {\n        const fraction = contributingChildren > 0 ? satisfiedCount / contributingChildren : 0;\n        return (\n          contributingChildren > 0 &&\n          unknownCount < contributingChildren &&\n          fraction >= normalizeMinimumPercent(rule.minimumPercent)\n        );\n      }\n      default:\n        return false;\n    }\n  }\n\n  /**\n   * Evaluate Rollup Conditions Subprocess\n   * Evaluates if rollup rule conditions are met for a given activity\n   *\n   * @spec SN Book: RB.1.4.1 (Evaluate Rollup Conditions Subprocess)\n   * @param child - The child activity to evaluate\n   * @param rule - The rollup rule containing conditions to evaluate\n   * @returns True if all conditions are met, false otherwise\n   */\n  public evaluateRollupConditionsSubprocess(child: Activity, rule: RollupRule): boolean {\n    return this.evaluateRollupConditionsThreeValued(child, rule) === true;\n  }\n\n  /**\n   * Combine conditions while preserving missing tracking information.\n   * @spec SCORM 2004 4th Ed. SN RB.1.4.1\n   */\n  public evaluateRollupConditionsThreeValued(\n    child: Activity,\n    rule: RollupRule,\n  ): RuleConditionEvaluation {\n    if (rule.conditions.length === 0) {\n      return true;\n    }\n\n    const results = rule.conditions.map((condition) =>\n      condition.evaluateThreeValued(child, this.now, this.getAttemptElapsedSeconds),\n    );\n    return rule.conditionCombination === RollupConditionCombination.ALL\n      ? kleeneAnd(results)\n      : kleeneOr(results);\n  }\n\n  /**\n   * Evaluate rules for a specific action type\n   * Finds and evaluates all rules matching the specified action\n   *\n   * @param activity - The parent activity\n   * @param rules - Array of rollup rules to evaluate\n   * @param actionType - The action type to filter by\n   * @returns True if any matching rule applies, false if none apply, null if no matching rules\n   */\n  public evaluateRulesForAction(\n    activity: Activity,\n    rules: RollupRule[],\n    actionType: RollupActionType,\n  ): boolean | null {\n    const matchingRules = rules.filter((rule) => rule.action === actionType);\n\n    if (matchingRules.length === 0) {\n      return null;\n    }\n\n    for (const rule of matchingRules) {\n      if (this.evaluateRollupRule(activity, rule)) {\n        return true;\n      }\n    }\n\n    return false;\n  }\n}\n","import { Activity } from \"../activity\";\nimport { RollupChildFilter } from \"./rollup_child_filter\";\n\n/**\n * Event callback function type\n */\nexport type EventCallback = (eventType: string, data?: unknown) => void;\n\n/**\n * MeasureRollupProcessor - Handles measure (score) rollup operations\n * Implements SCORM 2004 RB.1.1 (Measure Rollup Process) and RB.1.1.b (Completion Measure Rollup)\n *\n * This class is responsible for calculating rolled-up objective measures\n * from child activities to parent clusters using weighted averaging.\n *\n * @spec SN Book: RB.1.1 (Measure Rollup Process)\n * @spec SN Book: RB.1.1.b (Completion Measure Rollup Process)\n */\nexport class MeasureRollupProcessor {\n  /**\n   * Create a new MeasureRollupProcessor\n   *\n   * @param _childFilter - Retained for constructor compatibility\n   * @param _eventCallback - Retained for constructor compatibility\n   */\n  constructor(_childFilter: RollupChildFilter, _eventCallback?: EventCallback) {}\n\n  /**\n   * Measure Rollup Process\n   * Rolls up objective measure (score) from children to parent\n   * Uses each counted child's configured objective measure weight\n   *\n   * @spec SN Book: RB.1.1 (Measure Rollup Process)\n   * @param activity - The parent activity\n   */\n  public measureRollupProcess(activity: Activity): void {\n    const children = activity.getAvailableChildren();\n    if (children.length === 0) {\n      // No available child means no valid data, so the parent's measure is unknown.\n      activity.objectiveMeasureStatus = false;\n      return;\n    }\n\n    let counted = 0;\n    let total = 0;\n    let validData = false;\n\n    for (const child of children) {\n      if (child.sequencingControls.tracked === false) {\n        continue;\n      }\n      // RB.1.1 gates on Tracked only. Objective info from an earlier parent attempt is unknown\n      // (useCurrentAttemptObjectiveInfo): the child keeps its weight but not its score.\n      const hasKnownMeasure =\n        child.objectiveInfoAvailableInCurrentParentAttempt !== false &&\n        child.objectiveMeasureStatus &&\n        child.objectiveNormalizedMeasure !== null;\n      const weight = child.sequencingControls.objectiveMeasureWeight;\n      if (weight <= 0) {\n        continue;\n      }\n      counted += weight;\n      if (hasKnownMeasure) {\n        total += weight * child.objectiveNormalizedMeasure;\n        validData = true;\n      }\n    }\n\n    if (!validData) {\n      // No known child measure means the parent's measure is unknown (4th Ed valid-data step).\n      // The ADL SRTE sequencer has no such step and reports 0 here; we follow the spec text.\n      activity.objectiveMeasureStatus = false;\n    } else if (counted > 0) {\n      activity.objectiveNormalizedMeasure = total / counted;\n      activity.objectiveMeasureStatus = true;\n    } else {\n      activity.objectiveMeasureStatus = false;\n    }\n  }\n\n  /**\n   * Completion Measure Rollup Process\n   * Rolls up attemptCompletionAmount from children to parent using weighted averaging\n   * 4th Edition Addition: Supports completion measure rollup for progress tracking\n   *\n   * @spec SN Book: RB.1.1.b (Completion Measure Rollup Process)\n   * @param activity - The parent activity\n   */\n  public completionMeasureRollupProcess(activity: Activity): void {\n    const children = activity.getAvailableChildren();\n    if (children.length === 0) {\n      return;\n    }\n\n    const trackedChildren = children.filter((child) => child.sequencingControls.tracked);\n    const contributingChildren = trackedChildren.filter(\n      (child) =>\n        child.progressInfoAvailableInCurrentParentAttempt !== false &&\n        child.attemptCompletionAmountStatus,\n    );\n\n    if (contributingChildren.length === 0) {\n      activity.attemptCompletionAmountStatus = false;\n      return;\n    }\n\n    let totalWeightedMeasure = 0;\n    let totalWeight = 0;\n\n    // @spec SCORM 2004 4th Ed. SN RB.1.1.b: every tracked child's Progress\n    // Weight participates in the denominator. A child whose Attempt Completion\n    // Amount Status is false contributes no amount to the numerator.\n    for (const child of trackedChildren) {\n      if (\n        child.progressInfoAvailableInCurrentParentAttempt !== false &&\n        child.attemptCompletionAmountStatus\n      ) {\n        totalWeightedMeasure += child.attemptCompletionAmount * child.progressWeight;\n      }\n      totalWeight += child.progressWeight;\n    }\n\n    if (totalWeight > 0) {\n      activity.attemptCompletionAmount = totalWeightedMeasure / totalWeight;\n      activity.attemptCompletionAmountStatus = true;\n    }\n  }\n}\n","import { SuccessStatus } from \"../../../../constants/enums\";\nimport { Activity } from \"../activity\";\nimport { RollupActionType, RollupRule } from \"../rollup_rules\";\nimport { RollupChildFilter } from \"./rollup_child_filter\";\nimport { RollupRuleEvaluator } from \"./rollup_rule_evaluator\";\n\n/**\n * Event callback function type\n */\nexport type EventCallback = (eventType: string, data?: unknown) => void;\n\n/**\n * ObjectiveRollupProcessor - Handles objective satisfaction rollup operations\n * Implements SCORM 2004 RB.1.2 (Objective Rollup Process)\n *\n * This class is responsible for determining objective satisfaction status\n * for parent activities based on their children's states using rules,\n * measure-based evaluation, or default rollup logic.\n *\n * @spec SN Book: RB.1.2 (Objective Rollup Process)\n * @spec SN Book: RB.1.2.a (Objective Rollup Using Measure)\n * @spec SN Book: RB.1.2.b (Objective Rollup Using Rules)\n * @spec SN Book: RB.1.2.c (Objective Rollup Using Default)\n */\nexport class ObjectiveRollupProcessor {\n  private childFilter: RollupChildFilter;\n  private ruleEvaluator: RollupRuleEvaluator;\n  private eventCallback: EventCallback | null;\n\n  /**\n   * Create a new ObjectiveRollupProcessor\n   *\n   * @param childFilter - RollupChildFilter instance for filtering children\n   * @param ruleEvaluator - RollupRuleEvaluator instance for evaluating rules\n   * @param eventCallback - Optional callback for firing events\n   */\n  constructor(\n    childFilter: RollupChildFilter,\n    ruleEvaluator: RollupRuleEvaluator,\n    eventCallback?: EventCallback,\n  ) {\n    this.childFilter = childFilter;\n    this.ruleEvaluator = ruleEvaluator;\n    this.eventCallback = eventCallback || null;\n  }\n\n  /**\n   * Objective Rollup Process\n   * Determines objective satisfaction status using rules, measure, or default\n   *\n   * @spec SN Book: RB.1.2 (Objective Rollup Process)\n   * @param activity - The parent activity\n   */\n  public objectiveRollupProcess(activity: Activity): void {\n    const rollupRules = activity.rollupRules;\n\n    // @spec IMS Simple Sequencing 1.0 RB.1.2: \"measure-based computation, a\n    // rule-based computation or an alternative default rule-based computation,\n    // applied in that order\"; SM.6 Objective Satisfied by Measure: \"in place of\n    // any other method\". ADL SRTE SeqRollupRuleset.java ignores rule results\n    // when the measure threshold has already decided the status.\n    if (activity.primaryObjective?.satisfiedByMeasure) {\n      const measureResult = this.objectiveRollupUsingMeasure(activity);\n      if (measureResult === null) {\n        activity.objectiveSatisfiedStatusKnown = false;\n        activity.successStatus = SuccessStatus.UNKNOWN;\n      } else {\n        activity.objectiveSatisfiedStatus = measureResult;\n      }\n      this.syncPrimaryObjectiveFromActivity(activity);\n      return;\n    }\n\n    const ruleResult = this.objectiveRollupUsingRules(activity, rollupRules.rules);\n    if (ruleResult !== null) {\n      activity.objectiveSatisfiedStatus = ruleResult;\n      // Rule-based rollup determines satisfaction only, not measure status.\n      this.syncPrimaryObjectiveFromActivity(activity);\n    }\n\n    // @spec SN Book: RB.1.2.b - once the activity defines any satisfied or\n    // notSatisfied rollup rule, those rules alone determine satisfaction.\n    // Default rollup is not a fallback when the defined rules do not fire;\n    // in that case, the activity's satisfaction status is left unchanged.\n    if (\n      rollupRules.rules.some(\n        (rule) =>\n          rule.action === RollupActionType.SATISFIED ||\n          rule.action === RollupActionType.NOT_SATISFIED,\n      )\n    ) {\n      return;\n    }\n\n    // Finally, use default rollup (RB.1.2.c)\n    // @spec SN Book: RB.1.4 (Rollup Rule Check) - an unknown default-rollup result\n    // (null) means this subprocess has no information to contribute, so the\n    // activity's existing satisfaction status must be left untouched, exactly\n    // like the rules branch above.\n    const defaultResult = this.objectiveRollupUsingDefault(activity);\n    if (defaultResult !== null) {\n      activity.objectiveSatisfiedStatus = defaultResult;\n      // Do NOT set objectiveMeasureStatus here - default rollup doesn't involve measures\n      // Per SCORM 2004 SN Book RB.1.2.c, only satisfaction status is determined by default rollup\n      this.syncPrimaryObjectiveFromActivity(activity);\n    }\n  }\n\n  /**\n   * Objective Rollup Using Rules\n   * Evaluates rollup rules to determine objective satisfaction\n   *\n   * @spec SN Book: RB.1.2.b (Objective Rollup Using Rules)\n   * @param activity - The parent activity\n   * @param rules - The rollup rules to evaluate\n   * @returns True if satisfied, false if not, null if no rule applies\n   */\n  public objectiveRollupUsingRules(activity: Activity, rules: RollupRule[]): boolean | null {\n    // Get satisfied and not satisfied rules\n    const satisfiedRules = rules.filter((rule) => rule.action === RollupActionType.SATISFIED);\n\n    const notSatisfiedRules = rules.filter(\n      (rule) => rule.action === RollupActionType.NOT_SATISFIED,\n    );\n\n    // Evaluate satisfied rules first\n    for (const rule of satisfiedRules) {\n      if (this.ruleEvaluator.evaluateRollupRule(activity, rule)) {\n        return true;\n      }\n    }\n\n    // Then evaluate not satisfied rules\n    for (const rule of notSatisfiedRules) {\n      if (this.ruleEvaluator.evaluateRollupRule(activity, rule)) {\n        return false;\n      }\n    }\n\n    return null;\n  }\n\n  /**\n   * Objective Rollup Using Measure\n   * Determines satisfaction based on objective measure vs passing score\n   *\n   * @spec SN Book: RB.1.2.a (Objective Rollup Using Measure)\n   * @param activity - The parent activity\n   * @returns True if satisfied, false if not, null if no measure\n   */\n  public objectiveRollupUsingMeasure(activity: Activity): boolean | null {\n    const primaryObjective = activity.primaryObjective;\n    if (\n      !primaryObjective?.satisfiedByMeasure ||\n      !activity.objectiveMeasureStatus ||\n      activity.scaledPassingScore === null\n    ) {\n      return null;\n    }\n\n    // @spec SN Book: RB.1.2.a step 3.1.2.1 - defer measure satisfaction while active.\n    if (activity.isActive && !activity.rollupConsiderations.measureSatisfactionIfActive) {\n      return null;\n    }\n\n    return activity.objectiveNormalizedMeasure >= activity.scaledPassingScore;\n  }\n\n  /**\n   * Objective Rollup Using Default\n   * For default rollup (no explicit rules), the \"not satisfied\" check uses the\n   * children that pass requiredForNotSatisfied, and the \"satisfied\" check uses\n   * the children that pass requiredForSatisfied.\n   *\n   * A contributing child's objective status may itself be unknown (e.g. it has\n   * never been attempted in this parent attempt). Per RB.1.4 (Rollup Rule\n   * Check), an unknown status must not evaluate True for either the \"any not\n   * satisfied\" or the \"all satisfied\" check, so this returns `null` - \"no\n   * information\" - rather than collapsing an unknown child into \"not\n   * satisfied\".\n   *\n   * @spec SN Book: RB.1.2.c (Objective Rollup Using Default)\n   * @spec SN Book: RB.1.4 (Rollup Rule Check: unknown does not evaluate True for\n   * \"any\")\n   * @spec SN Book: RB.1.4.2 (Check Child For Rollup Subprocess)\n   * @param activity - The parent activity\n   * @returns True if every child included for \"satisfied\" is known-satisfied,\n   * otherwise false if any child included for \"not satisfied\" is\n   * known-not-satisfied, otherwise null (no information to roll up)\n   */\n  public objectiveRollupUsingDefault(activity: Activity): boolean | null {\n    const children = activity.getAvailableChildren();\n    // @spec SN Book: RB.1.2.c / RB.1.4 - with no children at all, this\n    // subprocess has no information to contribute.\n    if (children.length === 0) {\n      return null;\n    }\n\n    // @spec SN Book: RB.1.4.2 - filter children separately for each rollup action.\n    const notSatisfiedChildren = this.childFilter.filterChildrenForRequirement(\n      children,\n      \"objective\",\n      \"notSatisfied\",\n    );\n    const satisfiedChildren = this.childFilter.filterChildrenForRequirement(\n      children,\n      \"objective\",\n      \"satisfied\",\n    );\n\n    // @spec SN Book: RB.1.4 step 1.2.4 - an empty bag cannot fire an action.\n    if (notSatisfiedChildren.length === 0 && satisfiedChildren.length === 0) {\n      return null;\n    }\n\n    let result: boolean | null = null;\n    if (\n      notSatisfiedChildren.some(\n        (child) =>\n          this.childFilter.isChildObjectiveStatusKnownForRollup(child) &&\n          !this.childFilter.isChildSatisfiedForRollup(child),\n      )\n    ) {\n      result = false;\n    }\n\n    // @spec SN Book: RB.1.2.b - satisfied overrides not satisfied when both fire.\n    if (\n      satisfiedChildren.length > 0 &&\n      satisfiedChildren.every(\n        (child) =>\n          this.childFilter.isChildObjectiveStatusKnownForRollup(child) &&\n          this.childFilter.isChildSatisfiedForRollup(child),\n      )\n    ) {\n      result = true;\n    }\n\n    return result;\n  }\n\n  /**\n   * Sync primary objective status from activity properties\n   * Ensures the primary objective reflects the activity's rollup-derived status\n   *\n   * Note: This method is intentionally public as it is used by other rollup\n   * processors (e.g., ProgressRollupProcessor) to synchronize primary objective\n   * state after modifying activity completion status.\n   *\n   * @param activity - The activity to sync\n   */\n  public syncPrimaryObjectiveFromActivity(activity: Activity): void {\n    if (activity.primaryObjective) {\n      activity.primaryObjective.satisfiedStatus = activity.objectiveSatisfiedStatus;\n      activity.primaryObjective.satisfiedStatusKnown = activity.objectiveSatisfiedStatusKnown;\n      activity.primaryObjective.measureStatus = activity.objectiveMeasureStatus;\n      activity.primaryObjective.normalizedMeasure = activity.objectiveNormalizedMeasure;\n      activity.primaryObjective.progressMeasure = activity.progressMeasure;\n      activity.primaryObjective.progressMeasureStatus = activity.progressMeasureStatus;\n      activity.primaryObjective.completionStatus = activity.completionStatus;\n    }\n  }\n}\n","import { Activity } from \"../activity\";\nimport { RollupActionType } from \"../rollup_rules\";\nimport { CompletionStatus } from \"../../../../constants/enums\";\nimport { RollupChildFilter } from \"./rollup_child_filter\";\nimport { RollupRuleEvaluator } from \"./rollup_rule_evaluator\";\nimport { ObjectiveRollupProcessor } from \"./objective_rollup\";\n\n/**\n * Event callback function type\n */\nexport type EventCallback = (eventType: string, data?: unknown) => void;\n\n/**\n * ProgressRollupProcessor - Handles activity progress (completion) rollup operations\n * Implements SCORM 2004 RB.1.3 (Activity Progress Rollup Process)\n *\n * This class is responsible for determining completion status for parent\n * activities based on their children's states using measure-based evaluation,\n * rules, or default rollup logic.\n *\n * @spec SN Book: RB.1.3 (Activity Progress Rollup Process)\n * @spec SN Book: RB.1.3.a (Activity Progress Rollup Using Measure)\n */\nexport class ProgressRollupProcessor {\n  private childFilter: RollupChildFilter;\n  private ruleEvaluator: RollupRuleEvaluator;\n  private objectiveProcessor: ObjectiveRollupProcessor;\n  private eventCallback: EventCallback | null;\n\n  /**\n   * Create a new ProgressRollupProcessor\n   *\n   * @param childFilter - RollupChildFilter instance for filtering children\n   * @param ruleEvaluator - RollupRuleEvaluator instance for evaluating rules\n   * @param objectiveProcessor - ObjectiveRollupProcessor for syncing objectives\n   * @param eventCallback - Optional callback for firing events\n   */\n  constructor(\n    childFilter: RollupChildFilter,\n    ruleEvaluator: RollupRuleEvaluator,\n    objectiveProcessor: ObjectiveRollupProcessor,\n    eventCallback?: EventCallback,\n  ) {\n    this.childFilter = childFilter;\n    this.ruleEvaluator = ruleEvaluator;\n    this.objectiveProcessor = objectiveProcessor;\n    this.eventCallback = eventCallback || null;\n  }\n\n  /**\n   * Activity Progress Rollup Process\n   * Determines activity completion status\n   * Tries measure-based rollup first, then rules-based, then default\n   *\n   * @spec SN Book: RB.1.3 (Activity Progress Rollup Process)\n   * @param activity - The parent activity\n   */\n  public activityProgressRollupProcess(activity: Activity): void {\n    // Try measure-based rollup first (RB.1.3 a)\n    if (this.activityProgressRollupUsingMeasure(activity)) {\n      return;\n    }\n\n    // Continue with rules-based rollup (original implementation)\n    const rollupRules = activity.rollupRules;\n\n    // Get completion rules\n    const completedRules = rollupRules.rules.filter(\n      (rule) => rule.action === RollupActionType.COMPLETED,\n    );\n\n    const incompleteRules = rollupRules.rules.filter(\n      (rule) => rule.action === RollupActionType.INCOMPLETE,\n    );\n\n    // Evaluate completed rules first\n    for (const rule of completedRules) {\n      if (this.ruleEvaluator.evaluateRollupRule(activity, rule)) {\n        activity.completionStatus = CompletionStatus.COMPLETED;\n        this.objectiveProcessor.syncPrimaryObjectiveFromActivity(activity);\n        return;\n      }\n    }\n\n    // Then evaluate incomplete rules\n    for (const rule of incompleteRules) {\n      if (this.ruleEvaluator.evaluateRollupRule(activity, rule)) {\n        activity.completionStatus = CompletionStatus.INCOMPLETE;\n        this.objectiveProcessor.syncPrimaryObjectiveFromActivity(activity);\n        return;\n      }\n    }\n\n    // @spec SN Book: RB.1.3.b (Activity Progress Rollup Using Rules) - once the\n    // activity's manifest defines any completed/incomplete-action rollup rule,\n    // those rules are the sole determinant of this activity's progress status.\n    // Activity Progress Rollup Using Default only applies to an activity that\n    // defines NO completion-type rollup rules at all; it is not a fallback for\n    // a pass where the defined rules simply didn't fire. If neither rule fired\n    // this pass, the activity's completion status is left unchanged (same\n    // principle already enforced for the global-objective completion shortcut\n    // in GlobalObjectiveSynchronizer.updateActivityAttemptData's\n    // hasCompletionRollupRules guard).\n    if (completedRules.length > 0 || incompleteRules.length > 0) {\n      return;\n    }\n\n    // @spec SN Book: RB.1.4.2 - filter children separately for each rollup action.\n    const children = activity.getAvailableChildren();\n    const incompleteChildren = children.filter((child) =>\n      this.childFilter.checkChildForRollupSubprocess(child, \"progress\", \"incomplete\"),\n    );\n    const completedChildren = children.filter((child) =>\n      this.childFilter.checkChildForRollupSubprocess(child, \"progress\", \"completed\"),\n    );\n\n    // @spec SN Book: RB.1.4 step 1.2.4 - an empty bag cannot fire an action.\n    if (incompleteChildren.length === 0 && completedChildren.length === 0) {\n      return;\n    }\n\n    let result: CompletionStatus | null = null;\n    if (\n      incompleteChildren.some(\n        (child) =>\n          this.childFilter.isChildCompletionStatusKnownForRollup(child) &&\n          !this.childFilter.isChildCompletedForRollup(child),\n      )\n    ) {\n      result = CompletionStatus.INCOMPLETE;\n    }\n\n    // @spec SN Book: RB.1.3 - completed overrides incomplete when both fire.\n    if (\n      completedChildren.length > 0 &&\n      completedChildren.every(\n        (child) =>\n          this.childFilter.isChildCompletionStatusKnownForRollup(child) &&\n          this.childFilter.isChildCompletedForRollup(child),\n      )\n    ) {\n      result = CompletionStatus.COMPLETED;\n    }\n\n    if (result !== null) {\n      activity.completionStatus = result;\n      this.objectiveProcessor.syncPrimaryObjectiveFromActivity(activity);\n    }\n  }\n\n  /**\n   * Activity Progress Rollup Using Measure\n   * Determines completion status using attemptCompletionAmount threshold comparison\n   * 4th Edition Addition: Measure-based completion determination\n   *\n   * @spec SN Book: RB.1.3.a (Activity Progress Rollup Using Measure)\n   * @param activity - The activity to evaluate\n   * @returns True if measure-based evaluation was applied, false otherwise\n   */\n  public activityProgressRollupUsingMeasure(activity: Activity): boolean {\n    // Only apply if completedByMeasure is enabled\n    if (!activity.completedByMeasure) {\n      return false;\n    }\n\n    // Check if we have valid completion amount data\n    if (!activity.attemptCompletionAmountStatus) {\n      activity.completionStatus = CompletionStatus.UNKNOWN;\n      this.objectiveProcessor.syncPrimaryObjectiveFromActivity(activity);\n      return true;\n    }\n\n    // Compare completion amount against threshold\n    if (activity.attemptCompletionAmount >= activity.minProgressMeasure) {\n      activity.completionStatus = CompletionStatus.COMPLETED;\n    } else {\n      activity.completionStatus = CompletionStatus.INCOMPLETE;\n    }\n\n    this.objectiveProcessor.syncPrimaryObjectiveFromActivity(activity);\n    return true;\n  }\n}\n","import { Activity } from \"../activity\";\nimport { scorm2004_regex } from \"../../../../constants/regex\";\nimport { getDurationAsSeconds, getSecondsAsISODuration } from \"../../../../utilities\";\n\n/**\n * Event callback function type\n */\nexport type EventCallback = (eventType: string, data?: unknown) => void;\n\n/**\n * DurationRollupProcessor - Handles duration rollup operations\n * Implements SCORM 2004 RB.1.4 (Duration Rollup Process)\n *\n * This class is responsible for aggregating duration information from\n * child activities to parent clusters, including both absolute (wall clock)\n * and experienced (actual learning time) durations.\n *\n * @spec SN Book: RB.1.4 (Duration Rollup Process)\n * @spec Reference: Overall Rollup Process [RB.1.5] - duration rollup happens before optimization check\n */\nexport class DurationRollupProcessor {\n  private eventCallback: EventCallback | null;\n\n  /**\n   * Create a new DurationRollupProcessor\n   *\n   * @param eventCallback - Optional callback for firing events\n   */\n  constructor(eventCallback?: EventCallback) {\n    this.eventCallback = eventCallback || null;\n  }\n\n  /**\n   * Duration Rollup Process\n   * Aggregates duration information from child activities to parent cluster\n   * Called ALWAYS for cluster activities, even when other rollup is skipped due to optimization\n   *\n   * @spec SN Book: RB.1.4 (Duration Rollup Process)\n   * @spec Reference: Overall Rollup Process [RB.1.5] - duration rollup happens before optimization check\n   * @param activity - The parent cluster activity\n   */\n  public durationRollupProcess(activity: Activity): void {\n    // Only process cluster activities (non-leaf)\n    if (activity.children.length === 0) {\n      return;\n    }\n\n    const children = activity.getAvailableChildren();\n\n    // No children available, nothing to rollup\n    if (children.length === 0) {\n      return;\n    }\n\n    let earliestChildActivityStartTimestampUtc: string | null = null;\n    let earliestChildAttemptStartTimestampUtc: string | null = null;\n    let latestChildEndDate: Date | null = null;\n    let latestAttemptChildEndDate: Date | null = null;\n\n    // Aggregate experienced durations (in seconds for easier math)\n    let childrenActivityExperiencedDurationSeconds = 0;\n    let childrenAttemptExperiencedDurationSeconds = 0;\n\n    // Process each child\n    for (const child of children) {\n      // Track earliest activity start timestamp\n      if (child.activityStartTimestampUtc) {\n        if (\n          !earliestChildActivityStartTimestampUtc ||\n          child.activityStartTimestampUtc < earliestChildActivityStartTimestampUtc\n        ) {\n          earliestChildActivityStartTimestampUtc = child.activityStartTimestampUtc;\n        }\n      }\n\n      // Track latest activity end date\n      if (child.activityEndedDate) {\n        if (!latestChildEndDate || child.activityEndedDate > latestChildEndDate) {\n          latestChildEndDate = child.activityEndedDate;\n        }\n      }\n\n      // Aggregate activity experienced duration\n      // Use Value field if available (for cluster activities), otherwise use regular field (for leaf activities)\n      const activityDuration =\n        child.activityExperiencedDurationValue !== \"PT0H0M0S\"\n          ? child.activityExperiencedDurationValue\n          : child.activityExperiencedDuration;\n\n      if (activityDuration && activityDuration !== \"PT0H0M0S\") {\n        childrenActivityExperiencedDurationSeconds += getDurationAsSeconds(\n          activityDuration,\n          scorm2004_regex.CMITimespan,\n        );\n      }\n\n      // Check if child is in same attempt as parent\n      // (child attempt started after or at same time as parent attempt start)\n      const isChildInSameAttempt =\n        !activity.attemptStartTimestampUtc ||\n        (child.attemptStartTimestampUtc &&\n          child.attemptStartTimestampUtc >= activity.attemptStartTimestampUtc);\n\n      if (isChildInSameAttempt) {\n        // Track earliest attempt start timestamp\n        if (child.attemptStartTimestampUtc) {\n          if (\n            !earliestChildAttemptStartTimestampUtc ||\n            child.attemptStartTimestampUtc < earliestChildAttemptStartTimestampUtc\n          ) {\n            earliestChildAttemptStartTimestampUtc = child.attemptStartTimestampUtc;\n          }\n        }\n\n        // Track latest attempt end date\n        if (child.activityEndedDate) {\n          if (!latestAttemptChildEndDate || child.activityEndedDate > latestAttemptChildEndDate) {\n            latestAttemptChildEndDate = child.activityEndedDate;\n          }\n        }\n\n        // Aggregate attempt experienced duration\n        // Use Value field if available (for cluster activities), otherwise use regular field (for leaf activities)\n        const attemptDuration =\n          child.attemptExperiencedDurationValue !== \"PT0H0M0S\"\n            ? child.attemptExperiencedDurationValue\n            : child.attemptExperiencedDuration;\n\n        if (attemptDuration && attemptDuration !== \"PT0H0M0S\") {\n          childrenAttemptExperiencedDurationSeconds += getDurationAsSeconds(\n            attemptDuration,\n            scorm2004_regex.CMITimespan,\n          );\n        }\n      }\n    }\n\n    // Update parent activity timestamps and durations if we found any child data\n    if (earliestChildActivityStartTimestampUtc !== null) {\n      // Set earliest start timestamps\n      activity.activityStartTimestampUtc = earliestChildActivityStartTimestampUtc;\n\n      if (!activity.attemptStartTimestampUtc && earliestChildAttemptStartTimestampUtc) {\n        activity.attemptStartTimestampUtc = earliestChildAttemptStartTimestampUtc;\n      }\n\n      // Set latest end date\n      activity.activityEndedDate = latestChildEndDate;\n\n      // Calculate absolute durations (wall clock time)\n      if (latestChildEndDate && activity.activityStartTimestampUtc) {\n        const startDate = new Date(activity.activityStartTimestampUtc);\n        const durationMs = latestChildEndDate.getTime() - startDate.getTime();\n        const durationSeconds = Math.max(0, durationMs / 1000);\n        activity.activityAbsoluteDurationValue = getSecondsAsISODuration(durationSeconds);\n      }\n\n      if (latestAttemptChildEndDate && activity.attemptStartTimestampUtc) {\n        const startDate = new Date(activity.attemptStartTimestampUtc);\n        const durationMs = latestAttemptChildEndDate.getTime() - startDate.getTime();\n        const durationSeconds = Math.max(0, durationMs / 1000);\n        activity.attemptAbsoluteDurationValue = getSecondsAsISODuration(durationSeconds);\n      }\n\n      // Set aggregated experienced durations\n      activity.activityExperiencedDurationValue = getSecondsAsISODuration(\n        childrenActivityExperiencedDurationSeconds,\n      );\n      activity.attemptExperiencedDurationValue = getSecondsAsISODuration(\n        childrenAttemptExperiencedDurationSeconds,\n      );\n\n      // Fire event for monitoring\n      this.eventCallback?.(\"duration_rollup_completed\", {\n        activityId: activity.id,\n        activityAbsoluteDuration: activity.activityAbsoluteDurationValue,\n        attemptAbsoluteDuration: activity.attemptAbsoluteDurationValue,\n        activityExperiencedDuration: activity.activityExperiencedDurationValue,\n        attemptExperiencedDuration: activity.attemptExperiencedDurationValue,\n        childCount: children.length,\n      });\n    }\n  }\n}\n","import {\n  Activity,\n  ActivityObjective,\n  ActivityObjectiveDirtyProperty,\n  ActivityObjectiveReadState,\n  ObjectiveMapInfo,\n} from \"../activity\";\nimport { CompletionStatus } from \"../../../../constants/enums\";\n\n/**\n * Event callback function type\n */\nexport type EventCallback = (eventType: string, data?: unknown) => void;\n\n/**\n * Global objective state structure\n */\nexport interface GlobalObjective {\n  id: string;\n  satisfiedStatus: boolean;\n  satisfiedStatusKnown: boolean;\n  normalizedMeasure: number;\n  normalizedMeasureKnown: boolean;\n  rawScore: string;\n  rawScoreKnown: boolean;\n  minScore: string;\n  minScoreKnown: boolean;\n  maxScore: string;\n  maxScoreKnown: boolean;\n  progressMeasure: number;\n  progressMeasureKnown: boolean;\n  completionStatus: CompletionStatus;\n  completionStatusKnown: boolean;\n  satisfiedByMeasure: boolean;\n  minNormalizedMeasure: number | null;\n  attemptCount?: number;\n  attemptAbsoluteDuration?: string;\n  attemptExperiencedDuration?: string;\n  activityAbsoluteDuration?: string;\n  activityExperiencedDuration?: string;\n  location?: string;\n  suspendData?: string;\n  updateAttemptData?: boolean;\n}\n\n/** Objective-map fields written by a terminating activity, grouped by target objective. */\nexport interface GlobalObjectiveWriteTargets {\n  satisfiedStatus: Set<string>;\n  normalizedMeasure: Set<string>;\n}\n\ninterface GlobalObjectiveReadOptions {\n  restrictToFreshWrites: boolean;\n  allowSatisfiedStatus: boolean;\n  allowNormalizedMeasure: boolean;\n}\n\n/**\n * Local objective state for synchronization\n */\nexport interface LocalObjectiveState {\n  id: string;\n  satisfiedStatus: boolean;\n  measureStatus: boolean;\n  normalizedMeasure: number;\n  rawScore: string;\n  rawScoreKnown: boolean;\n  minScore: string;\n  minScoreKnown: boolean;\n  maxScore: string;\n  maxScoreKnown: boolean;\n  progressMeasure: number;\n  progressMeasureStatus: boolean;\n  completionStatus: CompletionStatus;\n  scaledPassingScore: number | null;\n}\n\n/**\n * GlobalObjectiveSynchronizer - Handles cross-activity global objective synchronization\n * Implements SCORM 2004 global objective mapping and shared objectives\n *\n * This class is responsible for synchronizing objective state between local\n * activity objectives and shared global objectives using a two-pass approach:\n * 1. WRITE pass: All activities write their local state TO global objectives\n * 2. READ pass: All activities read FROM global objectives into local state\n *\n * This ensures correct synchronization regardless of tree traversal order.\n *\n * @spec Priority 5 Gap: Comprehensive rollup with global objective mapping\n */\nexport class GlobalObjectiveSynchronizer {\n  private eventCallback: EventCallback | null;\n\n  /**\n   * Create a new GlobalObjectiveSynchronizer\n   *\n   * @param eventCallback - Optional callback for firing events\n   */\n  constructor(eventCallback?: EventCallback) {\n    this.eventCallback = eventCallback || null;\n  }\n\n  /**\n   * Process global objective mapping for shared objectives\n   * Handles cross-activity objective synchronization and global state management\n   *\n   * IMPORTANT: Uses two-pass approach to ensure correct synchronization order:\n   * 1. WRITE pass: All activities write their local state TO global objectives\n   * 2. READ pass: All activities read FROM global objectives into local state\n   *\n   * This ensures that when activity A writes to a global and activity B reads from it,\n   * B will see A's data regardless of tree traversal order.\n   *\n   * @param activity - The root activity to start processing from\n   * @param globalObjectives - Global objective map\n   */\n  public processGlobalObjectiveMapping(\n    activity: Activity,\n    globalObjectives: Map<string, GlobalObjective>,\n  ): Activity[] {\n    try {\n      this.eventCallback?.(\"global_objective_processing_started\", {\n        activityId: activity.id,\n        globalObjectiveCount: globalObjectives.size,\n      });\n\n      // Collect all activities in the tree for two-pass processing\n      const allActivities: Activity[] = [];\n      this.collectActivitiesRecursive(activity, allActivities);\n\n      // Pass 1: WRITE - All activities write their local state to global objectives\n      // This ensures all writes happen before any reads\n      for (const act of allActivities) {\n        this.syncGlobalObjectivesWritePhase(act, globalObjectives);\n      }\n\n      // Pass 2: READ - All activities read from global objectives into local state\n      // Now reads can see all writes from all activities\n      const changedActivities: Activity[] = [];\n      for (const act of allActivities) {\n        if (this.syncGlobalObjectivesReadPhase(act, globalObjectives)) {\n          changedActivities.push(act);\n        }\n      }\n\n      this.eventCallback?.(\"global_objective_processing_completed\", {\n        activityId: activity.id,\n        processedObjectives: globalObjectives.size,\n        changedActivityCount: changedActivities.length,\n      });\n      return changedActivities;\n    } catch (error) {\n      this.eventCallback?.(\"global_objective_processing_error\", {\n        activityId: activity.id,\n        error: error instanceof Error ? error.message : String(error),\n      });\n      return [];\n    }\n  }\n\n  /**\n   * Collect all activities in the tree recursively\n   *\n   * @param activity - Current activity\n   * @param result - Array to collect activities into\n   */\n  public collectActivitiesRecursive(activity: Activity, result: Activity[]): void {\n    result.push(activity);\n    for (const child of activity.children) {\n      this.collectActivitiesRecursive(child, result);\n    }\n  }\n\n  /**\n   * Write phase: Write local objective state TO global objectives\n   *\n   * @param activity - The activity to process\n   * @param globalObjectives - Global objective map\n   *\n   * @spec SCORM 2004 4th Ed. SN 3.10.3 - write mapInfo transfers local objective state to global objectives\n   * @spec SCORM 2004 4th Ed. ADLSEQ objectives extension - raw/min/max score write maps\n   */\n  public syncGlobalObjectivesWritePhase(\n    activity: Activity,\n    globalObjectives: Map<string, GlobalObjective>,\n  ): void {\n    // Objective maps write when an attempt terminates. An active cluster may\n    // already contain intermediate rollup state, but it is not yet a source\n    // for its mapped global objective.\n    // @spec SCORM 2004 SN 4th Ed. SM.7 Objective Map write timing\n    if (activity.isActive || !this.canWriteGlobalObjectives(activity)) {\n      return;\n    }\n\n    const objectives = activity.getAllObjectives();\n\n    for (const objective of objectives) {\n      const dirtyFieldsToClear = new Set<ActivityObjectiveDirtyProperty>();\n\n      // @spec SCORM 2004 4th Ed. SN 3.10.3: objectives without mapInfo are local\n      // and must not create or overwrite global objective state.\n      for (const mapInfo of objective.mapInfo) {\n        const targetId = mapInfo.targetObjectiveID || objective.id;\n        const globalObjective = this.ensureGlobalObjectiveEntry(\n          globalObjectives,\n          targetId,\n          objective,\n        );\n\n        // Only do WRITE operations in this phase\n        // Only write if the objective property has been modified (dirty flag set)\n        if (\n          mapInfo.writeSatisfiedStatus &&\n          this.hasKnownSatisfiedStatus(activity, objective) &&\n          objective.isDirty(\"satisfiedStatus\")\n        ) {\n          globalObjective.satisfiedStatus = objective.satisfiedStatus;\n          globalObjective.satisfiedStatusKnown = true;\n          dirtyFieldsToClear.add(\"satisfiedStatus\");\n        }\n\n        if (\n          mapInfo.writeNormalizedMeasure &&\n          objective.measureStatus &&\n          objective.isDirty(\"normalizedMeasure\")\n        ) {\n          globalObjective.normalizedMeasure = objective.normalizedMeasure;\n          globalObjective.normalizedMeasureKnown = true;\n          dirtyFieldsToClear.add(\"normalizedMeasure\");\n\n          // @spec SCORM 2004 4th Ed. SN 3.10.3 Table 3.10.3a - Write Normalized Measure\n          // and Write Objective Satisfied Status are independent mapInfo controls.\n          // @spec SCORM 2004 4th Ed. SN 3.10 Objective Description - Objective\n          // Satisfied By Measure derives satisfaction only for objectives that declare it.\n          if (mapInfo.writeSatisfiedStatus && objective.satisfiedByMeasure) {\n            const threshold = objective.minNormalizedMeasure ?? 1.0;\n            globalObjective.satisfiedStatus = objective.normalizedMeasure >= threshold;\n            globalObjective.satisfiedStatusKnown = true;\n            dirtyFieldsToClear.add(\"satisfiedStatus\");\n          }\n        }\n\n        if (mapInfo.writeCompletionStatus && objective.isDirty(\"completionStatus\")) {\n          // @spec SCORM 2004 4th Ed. SN 3.10.3 Table 3.10.3a - a local\n          // completion-status change is written through its map. Unknown clears\n          // the global status knowledge; default unknown is not dirty and does not write.\n          globalObjective.completionStatus = objective.completionStatus;\n          globalObjective.completionStatusKnown =\n            objective.completionStatus !== CompletionStatus.UNKNOWN;\n          dirtyFieldsToClear.add(\"completionStatus\");\n        }\n\n        // @spec SCORM 2004 4th Ed. ADLSEQ objectives extension - Write Raw Score\n        // only updates the mapped global objective when the corresponding map is true.\n        if (mapInfo.writeRawScore && objective.rawScoreKnown && objective.isDirty(\"rawScore\")) {\n          globalObjective.rawScore = objective.rawScore;\n          globalObjective.rawScoreKnown = true;\n          dirtyFieldsToClear.add(\"rawScore\");\n        }\n\n        // @spec SCORM 2004 4th Ed. ADLSEQ objectives extension - Write Min Score\n        // only updates the mapped global objective when the corresponding map is true.\n        if (mapInfo.writeMinScore && objective.minScoreKnown && objective.isDirty(\"minScore\")) {\n          globalObjective.minScore = objective.minScore;\n          globalObjective.minScoreKnown = true;\n          dirtyFieldsToClear.add(\"minScore\");\n        }\n\n        // @spec SCORM 2004 4th Ed. ADLSEQ objectives extension - Write Max Score\n        // only updates the mapped global objective when the corresponding map is true.\n        if (mapInfo.writeMaxScore && objective.maxScoreKnown && objective.isDirty(\"maxScore\")) {\n          globalObjective.maxScore = objective.maxScore;\n          globalObjective.maxScoreKnown = true;\n          dirtyFieldsToClear.add(\"maxScore\");\n        }\n\n        if (\n          mapInfo.writeProgressMeasure &&\n          objective.progressMeasureStatus &&\n          objective.isDirty(\"progressMeasure\")\n        ) {\n          globalObjective.progressMeasure = objective.progressMeasure;\n          globalObjective.progressMeasureKnown = true;\n          dirtyFieldsToClear.add(\"progressMeasure\");\n        }\n\n        if (mapInfo.updateAttemptData) {\n          this.updateActivityAttemptData(activity, globalObjective, objective);\n        }\n      }\n\n      for (const property of dirtyFieldsToClear) {\n        objective.clearDirty(property);\n      }\n    }\n  }\n\n  /**\n   * Transfer the terminating activity's final local objective state to its\n   * write-mapped globals. Unknown local state clears the corresponding global\n   * status instead of leaving a value from the prior attempt visible.\n   *\n   * @spec SCORM 2004 SN 4th Ed. SM.7 Objective Map\n   * @spec SCORM 2004 SN 4th Ed. TM.1.1 Objective Progress Information\n   */\n  public syncTerminatedActivityWritePhase(\n    activity: Activity,\n    globalObjectives: Map<string, GlobalObjective>,\n  ): GlobalObjectiveWriteTargets {\n    const writeTargets: GlobalObjectiveWriteTargets = {\n      satisfiedStatus: new Set<string>(),\n      normalizedMeasure: new Set<string>(),\n    };\n\n    if (!this.canWriteGlobalObjectives(activity)) {\n      return writeTargets;\n    }\n\n    for (const objective of activity.getAllObjectives()) {\n      for (const mapInfo of objective.mapInfo) {\n        const targetId = mapInfo.targetObjectiveID || objective.id;\n        const globalObjective = this.ensureGlobalObjectiveEntry(\n          globalObjectives,\n          targetId,\n          objective,\n        );\n\n        if (\n          mapInfo.writeSatisfiedStatus &&\n          !this.isMeasureSatisfactionDeferred(activity, objective)\n        ) {\n          writeTargets.satisfiedStatus.add(targetId);\n          if (this.hasKnownSatisfiedStatus(activity, objective)) {\n            globalObjective.satisfiedStatus = objective.satisfiedStatus;\n            globalObjective.satisfiedStatusKnown = true;\n          } else {\n            globalObjective.satisfiedStatus = false;\n            globalObjective.satisfiedStatusKnown = false;\n          }\n          objective.clearDirty(\"satisfiedStatus\");\n        }\n\n        if (mapInfo.writeNormalizedMeasure) {\n          writeTargets.normalizedMeasure.add(targetId);\n          if (objective.measureStatus) {\n            globalObjective.normalizedMeasure = objective.normalizedMeasure;\n            globalObjective.normalizedMeasureKnown = true;\n          } else {\n            globalObjective.normalizedMeasure = 0;\n            globalObjective.normalizedMeasureKnown = false;\n          }\n          objective.clearDirty(\"normalizedMeasure\");\n        }\n      }\n    }\n\n    return writeTargets;\n  }\n\n  /**\n   * Read phase: Read FROM global objectives into local state\n   *\n   * @param activity - The activity to process\n   * @param globalObjectives - Global objective map\n   *\n   * @spec SCORM 2004 4th Ed. SN 3.10.3 - read mapInfo transfers global objective state into the local view\n   * @spec SCORM 2004 4th Ed. ADLSEQ objectives extension - raw/min/max score read maps\n   */\n  public syncGlobalObjectivesReadPhase(\n    activity: Activity,\n    globalObjectives: Map<string, GlobalObjective>,\n  ): boolean {\n    return this.syncGlobalObjectivesReadPhaseInternal(activity, globalObjectives);\n  }\n\n  /**\n   * Read mapped global state into a newly initialized activity attempt.\n   *\n   * A read/write map normally suppresses reads while its activity is active so an in-progress\n   * attempt remains the source of the next write. During DB.2 delivery, however, the local\n   * attempt has just been initialized and must receive its mapped global state before content\n   * and sequencing inspect it.\n   *\n   * @spec SCORM 2004 SN 4th Ed. DB.2 and 3.10.3 Objective Map read timing\n   */\n  public syncGlobalObjectivesDeliveryReadPhase(\n    activity: Activity,\n    globalObjectives: Map<string, GlobalObjective>,\n  ): boolean {\n    return this.syncGlobalObjectivesReadPhaseInternal(\n      activity,\n      globalObjectives,\n      undefined,\n      true,\n    );\n  }\n\n  /**\n   * Read only objective fields freshly written by a terminating descendant.\n   *\n   * Active write-mapped objectives normally suppress reads so a new attempt cannot revive its\n   * predecessor's state. A descendant write is different: active ancestors need that new state\n   * before their own post-condition rules are evaluated.\n   *\n   * @spec SCORM 2004 SN 4th Ed. SM.7 Objective Map write timing\n   */\n  public syncFreshlyWrittenGlobalObjectivesReadPhase(\n    activity: Activity,\n    globalObjectives: Map<string, GlobalObjective>,\n    writeTargets: GlobalObjectiveWriteTargets,\n  ): boolean {\n    return this.syncGlobalObjectivesReadPhaseInternal(activity, globalObjectives, writeTargets);\n  }\n\n  private syncGlobalObjectivesReadPhaseInternal(\n    activity: Activity,\n    globalObjectives: Map<string, GlobalObjective>,\n    writeTargets?: GlobalObjectiveWriteTargets,\n    allowActiveWriteMappedRead = false,\n  ): boolean {\n    const beforeStatus = activity.captureRollupStatus();\n    const beforeObjectiveSatisfiedStatusKnown = activity.objectiveSatisfiedStatusKnown;\n    const objectives = activity.getAllObjectives();\n\n    for (const objective of objectives) {\n      // @spec SCORM 2004 4th Ed. SN 3.10.3: only explicitly mapped objectives\n      // participate in the global read phase.\n      for (const mapInfo of objective.mapInfo) {\n        const targetId = mapInfo.targetObjectiveID || objective.id;\n        const freshlyWroteSatisfiedStatus = writeTargets?.satisfiedStatus.has(targetId) ?? false;\n        const freshlyWroteNormalizedMeasure =\n          writeTargets?.normalizedMeasure.has(targetId) ?? false;\n        if (writeTargets && !freshlyWroteSatisfiedStatus && !freshlyWroteNormalizedMeasure) {\n          continue;\n        }\n        const globalObjective = globalObjectives.get(targetId);\n\n        if (!globalObjective) continue;\n\n        const isPrimary = objective.isPrimary;\n\n        const readState = GlobalObjectiveSynchronizer.getGlobalObjectiveReadState(\n          activity,\n          objective,\n          mapInfo,\n          globalObjective,\n          writeTargets\n            ? {\n                restrictToFreshWrites: true,\n                allowSatisfiedStatus: freshlyWroteSatisfiedStatus,\n                allowNormalizedMeasure: freshlyWroteNormalizedMeasure,\n              }\n            : allowActiveWriteMappedRead\n              ? {\n                  restrictToFreshWrites: false,\n                  allowSatisfiedStatus: true,\n                  allowNormalizedMeasure: true,\n                }\n              : undefined,\n        );\n        this.applyGlobalObjectiveReadState(objective, readState);\n\n        // Apply primary objective changes to activity\n        if (isPrimary) {\n          objective.applyToActivity(activity);\n        }\n\n        // Fire synchronization event for monitoring/logging\n        this.eventCallback?.(\"objective_synchronized\", {\n          activityId: activity.id,\n          objectiveId: objective.id,\n          globalState: globalObjective,\n          synchronizationTime: new Date().toISOString(),\n        });\n      }\n    }\n\n    // @spec SCORM 2004 4th Ed. SN 3.10.3 and RB.1.5 - a read-mapped primary\n    // objective changes the activity state that participates in ancestor rollup.\n    return (\n      !Activity.compareRollupStatus(beforeStatus, activity.captureRollupStatus()) ||\n      beforeObjectiveSatisfiedStatusKnown !== activity.objectiveSatisfiedStatusKnown\n    );\n  }\n\n  /**\n   * Synchronize global objectives with activity-specific objectives\n   * Combined read/write operation for backward compatibility\n   *\n   * @param activity - The activity to synchronize\n   * @param globalObjectives - Global objective map\n   */\n  public synchronizeGlobalObjectives(\n    activity: Activity,\n    globalObjectives: Map<string, GlobalObjective>,\n  ): void {\n    const objectives = activity.getAllObjectives();\n\n    for (const objective of objectives) {\n      // @spec SCORM 2004 4th Ed. SN 3.10.3: combined synchronization follows\n      // the same explicit-map boundary as the two-pass implementation.\n      for (const mapInfo of objective.mapInfo) {\n        const targetId = mapInfo.targetObjectiveID || objective.id;\n        const globalObjective = this.ensureGlobalObjectiveEntry(\n          globalObjectives,\n          targetId,\n          objective,\n        );\n        this.syncObjectiveState(activity, objective, mapInfo, globalObjective);\n      }\n    }\n  }\n\n  /**\n   * Synchronize objective state between local and global\n   * Full sync operation with both read and write\n   *\n   * @param activity - The activity\n   * @param objective - The objective to sync\n   * @param mapInfo - Map info for this objective\n   * @param globalObjective - The global objective\n   *\n   * @spec SCORM 2004 4th Ed. SN 3.10.3 - objective mapInfo read/write synchronization\n   * @spec SCORM 2004 4th Ed. ADLSEQ objectives extension - score mapInfo synchronization\n   */\n  public syncObjectiveState(\n    activity: Activity,\n    objective: ActivityObjective,\n    mapInfo: ObjectiveMapInfo,\n    globalObjective: GlobalObjective,\n  ): void {\n    try {\n      const isPrimary = objective.isPrimary;\n      const localObjective = this.getLocalObjectiveState(activity, objective, isPrimary);\n\n      const readState = GlobalObjectiveSynchronizer.getGlobalObjectiveReadState(\n        activity,\n        objective,\n        mapInfo,\n        globalObjective,\n      );\n      this.applyGlobalObjectiveReadState(objective, readState);\n\n      if (objective.isPrimary) {\n        objective.applyToActivity(activity);\n      }\n\n      if (this.canWriteGlobalObjectives(activity)) {\n        // Write from local to global using THIS ACTIVITY'S mapInfo directives\n        // Each activity has its own write permissions for the global objective\n        if (mapInfo.writeSatisfiedStatus && this.hasKnownSatisfiedStatus(activity, objective)) {\n          globalObjective.satisfiedStatus = objective.satisfiedStatus;\n          globalObjective.satisfiedStatusKnown = true;\n        }\n\n        if (mapInfo.writeNormalizedMeasure && objective.measureStatus) {\n          globalObjective.normalizedMeasure = objective.normalizedMeasure;\n          globalObjective.normalizedMeasureKnown = true;\n\n          // @spec SCORM 2004 4th Ed. SN 3.10.3 Table 3.10.3a - Write Normalized Measure\n          // and Write Objective Satisfied Status are independent mapInfo controls.\n          // @spec SCORM 2004 4th Ed. SN 3.10 Objective Description - Objective\n          // Satisfied By Measure derives satisfaction only for objectives that declare it.\n          if (\n            mapInfo.writeSatisfiedStatus &&\n            objective.satisfiedByMeasure &&\n            !this.isMeasureSatisfactionDeferred(activity, objective)\n          ) {\n            const threshold = objective.minNormalizedMeasure ?? 1.0;\n            globalObjective.satisfiedStatus = objective.normalizedMeasure >= threshold;\n            globalObjective.satisfiedStatusKnown = true;\n          }\n        }\n\n        if (\n          mapInfo.writeCompletionStatus &&\n          objective.completionStatus !== CompletionStatus.UNKNOWN\n        ) {\n          globalObjective.completionStatus = objective.completionStatus;\n          globalObjective.completionStatusKnown = true;\n        }\n\n        // @spec SCORM 2004 4th Ed. ADLSEQ objectives extension - Write Raw Score\n        // only updates the mapped global objective when the corresponding map is true.\n        if (mapInfo.writeRawScore && objective.rawScoreKnown) {\n          globalObjective.rawScore = objective.rawScore;\n          globalObjective.rawScoreKnown = true;\n        }\n\n        // @spec SCORM 2004 4th Ed. ADLSEQ objectives extension - Write Min Score\n        // only updates the mapped global objective when the corresponding map is true.\n        if (mapInfo.writeMinScore && objective.minScoreKnown) {\n          globalObjective.minScore = objective.minScore;\n          globalObjective.minScoreKnown = true;\n        }\n\n        // @spec SCORM 2004 4th Ed. ADLSEQ objectives extension - Write Max Score\n        // only updates the mapped global objective when the corresponding map is true.\n        if (mapInfo.writeMaxScore && objective.maxScoreKnown) {\n          globalObjective.maxScore = objective.maxScore;\n          globalObjective.maxScoreKnown = true;\n        }\n\n        if (mapInfo.writeProgressMeasure && objective.progressMeasureStatus) {\n          globalObjective.progressMeasure = objective.progressMeasure;\n          globalObjective.progressMeasureKnown = true;\n        }\n\n        if (mapInfo.updateAttemptData) {\n          this.updateActivityAttemptData(activity, globalObjective, objective);\n        }\n      }\n\n      // Fire synchronization event for monitoring/logging\n      this.eventCallback?.(\"objective_synchronized\", {\n        activityId: activity.id,\n        objectiveId: objective.id,\n        localState: localObjective,\n        globalState: globalObjective,\n        synchronizationTime: new Date().toISOString(),\n      });\n    } catch (error) {\n      // Log synchronization error but don't fail the rollup process\n      this.eventCallback?.(\"objective_sync_error\", {\n        activityId: activity.id,\n        objectiveId: objective.id,\n        error: error instanceof Error ? error.message : String(error),\n        timestamp: new Date().toISOString(),\n      });\n    }\n  }\n\n  /**\n   * Project a global objective through one local objective's read mapInfo.\n   *\n   * @spec SCORM 2004 4th Ed. SN 3.10.3 - read maps provide access to mapped global objective fields\n   * @spec SCORM 2004 4th Ed. ADLSEQ objectives extension - raw/min/max score read maps are independent fields\n   */\n  public static getGlobalObjectiveReadState(\n    activity: Activity,\n    objective: ActivityObjective,\n    mapInfo: ObjectiveMapInfo,\n    globalObjective: GlobalObjective,\n    options?: GlobalObjectiveReadOptions,\n  ): ActivityObjectiveReadState {\n    const readState: ActivityObjectiveReadState = {};\n\n    // A write-mapped objective in an active attempt is the source of the next\n    // global value. Reading that same field back would revive the prior\n    // attempt's state and overwrite the freshly initialized local attempt.\n    // @spec SCORM 2004 SN 4th Ed. DB.2 and SM.7\n    const suppressSatisfiedRead =\n      activity.isActive && mapInfo.writeSatisfiedStatus && !options?.allowSatisfiedStatus;\n    const suppressMeasureRead =\n      activity.isActive && mapInfo.writeNormalizedMeasure && !options?.allowNormalizedMeasure;\n\n    // @spec SCORM 2004 4th Ed. SN 3.10.3 Table 3.10.3a - Read Objective\n    // Satisfied Status exposes the mapped global status, including unknown.\n    if (\n      mapInfo.readSatisfiedStatus &&\n      (!options?.restrictToFreshWrites || options.allowSatisfiedStatus) &&\n      !suppressSatisfiedRead &&\n      !objective.satisfiedByMeasure\n    ) {\n      readState.satisfiedStatusKnown = globalObjective.satisfiedStatusKnown;\n      if (globalObjective.satisfiedStatusKnown) {\n        readState.satisfiedStatus = globalObjective.satisfiedStatus;\n      }\n    }\n\n    // @spec SCORM 2004 4th Ed. SN 3.10.3 Table 3.10.3a - Read Normalized\n    // Measure exposes the mapped global measure, including unknown, and does\n    // not require Read Objective Satisfied Status.\n    if (\n      mapInfo.readNormalizedMeasure &&\n      (!options?.restrictToFreshWrites || options.allowNormalizedMeasure) &&\n      !suppressMeasureRead\n    ) {\n      readState.normalizedMeasureKnown = globalObjective.normalizedMeasureKnown;\n      if (globalObjective.normalizedMeasureKnown) {\n        readState.normalizedMeasure = globalObjective.normalizedMeasure;\n      }\n\n      // @spec SCORM 2004 4th Ed. SN 3.10 Objective Description - local\n      // satisfiedByMeasure derives a local satisfied status from the read measure.\n      if (objective.satisfiedByMeasure) {\n        readState.satisfiedStatusKnown = globalObjective.normalizedMeasureKnown;\n        if (globalObjective.normalizedMeasureKnown) {\n          const threshold = objective.minNormalizedMeasure ?? 1.0;\n          readState.satisfiedStatus = globalObjective.normalizedMeasure >= threshold;\n        }\n      }\n    }\n\n    // @spec SCORM 2004 4th Ed. SN 3.10.3 Table 3.10.3a - Read Completion\n    // Status applies only when the mapped global completion status is known.\n    if (\n      !options?.restrictToFreshWrites &&\n      mapInfo.readCompletionStatus &&\n      globalObjective.completionStatusKnown\n    ) {\n      readState.completionStatus = globalObjective.completionStatus as CompletionStatus;\n    }\n\n    // @spec SCORM 2004 4th Ed. SN 3.10.3 Table 3.10.3a - Read Progress\n    // Measure applies only when the mapped global progress measure is known.\n    if (\n      !options?.restrictToFreshWrites &&\n      mapInfo.readProgressMeasure &&\n      globalObjective.progressMeasureKnown\n    ) {\n      readState.progressMeasure = globalObjective.progressMeasure;\n    }\n\n    // @spec SCORM 2004 4th Ed. ADLSEQ objectives extension - Read Raw Score\n    // applies only when the mapped global raw score is known.\n    if (!options?.restrictToFreshWrites && mapInfo.readRawScore && globalObjective.rawScoreKnown) {\n      readState.rawScore = globalObjective.rawScore;\n    }\n\n    // @spec SCORM 2004 4th Ed. ADLSEQ objectives extension - Read Min Score\n    // applies only when the mapped global min score is known.\n    if (!options?.restrictToFreshWrites && mapInfo.readMinScore && globalObjective.minScoreKnown) {\n      readState.minScore = globalObjective.minScore;\n    }\n\n    // @spec SCORM 2004 4th Ed. ADLSEQ objectives extension - Read Max Score\n    // applies only when the mapped global max score is known.\n    if (!options?.restrictToFreshWrites && mapInfo.readMaxScore && globalObjective.maxScoreKnown) {\n      readState.maxScore = globalObjective.maxScore;\n    }\n\n    return readState;\n  }\n\n  /**\n   * Apply read-mapped state to an objective without marking those fields dirty.\n   *\n   * @spec SCORM 2004 4th Ed. SN 3.10.3 - read maps are access to global state, not local writes\n   * @spec SCORM 2004 4th Ed. ADLSEQ objectives extension - score read maps do not imply score writes\n   */\n  private applyGlobalObjectiveReadState(\n    objective: ActivityObjective,\n    readState: ActivityObjectiveReadState,\n  ): void {\n    objective.applyReadMappedState(readState);\n  }\n\n  /**\n   * Ensure global objective entry exists\n   *\n   * @param globalObjectives - Global objectives map\n   * @param targetId - Target objective ID\n   * @param objective - Source objective\n   * @returns The global objective entry\n   *\n   * @spec SCORM 2004 4th Ed. SN 3.10.3 - global objective entries hold mapped objective state\n   * @spec SCORM 2004 4th Ed. ADLSEQ objectives extension - global entries hold score-map state\n   */\n  public ensureGlobalObjectiveEntry(\n    globalObjectives: Map<string, GlobalObjective>,\n    targetId: string,\n    objective: ActivityObjective,\n  ): GlobalObjective {\n    if (!globalObjectives.has(targetId)) {\n      // Create new entry if global objective doesn't exist\n      // NOTE: The read/write flags stored here are for reference only.\n      // Each activity uses its OWN mapInfo for read/write decisions in syncObjectiveState.\n      globalObjectives.set(targetId, {\n        id: targetId,\n        satisfiedStatus: false,\n        satisfiedStatusKnown: false,\n        normalizedMeasure: 0,\n        normalizedMeasureKnown: false,\n        // @spec SCORM 2004 4th Ed. ADLSEQ objectives extension - score fields\n        // remain unknown until their corresponding write map explicitly writes them.\n        rawScore: \"\",\n        rawScoreKnown: false,\n        minScore: \"\",\n        minScoreKnown: false,\n        maxScore: \"\",\n        maxScoreKnown: false,\n        progressMeasure: 0,\n        progressMeasureKnown: false,\n        completionStatus: CompletionStatus.UNKNOWN,\n        completionStatusKnown: false,\n        satisfiedByMeasure: objective.satisfiedByMeasure,\n        minNormalizedMeasure: objective.minNormalizedMeasure,\n      });\n    }\n\n    return globalObjectives.get(targetId)!;\n  }\n\n  /**\n   * Create default map info for an objective\n   * Default map info should only WRITE to global objectives, not READ\n   * Reading should only happen when explicitly configured via mapInfo\n   * This prevents unintended overwrites of RTE-transferred data\n   *\n   * @param objective - The objective to create default map info for\n   * @returns Default map info\n   *\n   * @spec SCORM 2004 4th Ed. SN 3.10.3 - mapInfo defaults are applied before objective synchronization\n   * @spec SCORM 2004 4th Ed. ADLSEQ objectives extension - score maps require explicit read/write flags\n   */\n  public createDefaultMapInfo(objective: ActivityObjective): ObjectiveMapInfo {\n    return {\n      targetObjectiveID: objective.id,\n      readSatisfiedStatus: false,\n      writeSatisfiedStatus: true,\n      readNormalizedMeasure: false,\n      writeNormalizedMeasure: true,\n      readCompletionStatus: false,\n      writeCompletionStatus: true,\n      readProgressMeasure: false,\n      writeProgressMeasure: true,\n      readRawScore: false,\n      writeRawScore: false,\n      readMinScore: false,\n      writeMinScore: false,\n      readMaxScore: false,\n      writeMaxScore: false,\n      updateAttemptData: objective.isPrimary,\n    };\n  }\n\n  private isMeasureSatisfactionDeferred(activity: Activity, objective: ActivityObjective): boolean {\n    // @spec SCORM 2004 SN 4th Ed. RB.1.2.a step 3.1.2.1\n    // Satisfaction is deferred while active when measure satisfaction is disabled.\n    return (\n      objective.satisfiedByMeasure &&\n      activity.isActive &&\n      !activity.rollupConsiderations.measureSatisfactionIfActive\n    );\n  }\n\n  /**\n   * Return whether the local objective has known satisfaction state to write.\n   *\n   * @spec SCORM 2004 4th Ed. SN 4.2.1 Tracking Model - Objective Progress\n   * Status identifies whether Objective Satisfied Status is known; Objective\n   * Measure Status is independent measure knowledge.\n   */\n  private hasKnownSatisfiedStatus(activity: Activity, objective: ActivityObjective): boolean {\n    if (this.isMeasureSatisfactionDeferred(activity, objective)) {\n      return false;\n    }\n    if (objective.satisfiedByMeasure) {\n      // @spec SCORM 2004 4th Ed. SN 3.10 Objective Description / 3.10.3\n      // Objective Map - a measure-controlled objective has a known satisfied\n      // status only when its normalized measure is known. End-attempt defaults\n      // must not publish satisfaction in place of a missing measure.\n      return objective.measureStatus;\n    }\n    return objective.progressStatus || objective.satisfiedStatusKnown;\n  }\n\n  /**\n   * Return whether this activity is allowed to write tracked state to globals.\n   *\n   * @spec SCORM 2004 4th Ed. SN 3.13.1 Tracked - when False, the LMS\n   * \"does not initialize, manage or access any tracking status information\".\n   */\n  private canWriteGlobalObjectives(activity: Activity): boolean {\n    return activity.sequencingControls.tracked !== false;\n  }\n\n  /**\n   * Get local objective state\n   *\n   * @param activity - The activity\n   * @param objective - The objective\n   * @param isPrimary - Whether this is the primary objective\n   * @returns Local objective state\n   *\n   * @spec SCORM 2004 4th Ed. SN 3.10 Objective Description - local objective state used for synchronization\n   * @spec SCORM 2004 4th Ed. ADLSEQ objectives extension - local score fields are part of mapped objective state\n   */\n  public getLocalObjectiveState(\n    activity: Activity,\n    objective: ActivityObjective,\n    isPrimary: boolean,\n  ): LocalObjectiveState {\n    if (isPrimary) {\n      return {\n        id: objective.id,\n        satisfiedStatus: activity.objectiveSatisfiedStatus,\n        measureStatus: activity.objectiveMeasureStatus,\n        normalizedMeasure: activity.objectiveNormalizedMeasure,\n        rawScore: objective.rawScore,\n        rawScoreKnown: objective.rawScoreKnown,\n        minScore: objective.minScore,\n        minScoreKnown: objective.minScoreKnown,\n        maxScore: objective.maxScore,\n        maxScoreKnown: objective.maxScoreKnown,\n        progressMeasure: activity.progressMeasure,\n        progressMeasureStatus: activity.progressMeasureStatus,\n        completionStatus: activity.completionStatus,\n        scaledPassingScore: activity.scaledPassingScore,\n      };\n    }\n\n    return {\n      id: objective.id,\n      satisfiedStatus: objective.satisfiedStatus,\n      measureStatus: objective.measureStatus,\n      normalizedMeasure: objective.normalizedMeasure,\n      rawScore: objective.rawScore,\n      rawScoreKnown: objective.rawScoreKnown,\n      minScore: objective.minScore,\n      minScoreKnown: objective.minScoreKnown,\n      maxScore: objective.maxScore,\n      maxScoreKnown: objective.maxScoreKnown,\n      progressMeasure: objective.progressMeasure,\n      progressMeasureStatus: objective.progressMeasureStatus,\n      completionStatus: objective.completionStatus,\n      scaledPassingScore: objective.minNormalizedMeasure,\n    };\n  }\n\n  /**\n   * Update activity attempt data based on global objective state\n   *\n   * @param activity - The activity to update\n   * @param globalObjective - Global objective state\n   * @param objective - The local objective\n   */\n  public updateActivityAttemptData(\n    activity: Activity,\n    globalObjective: GlobalObjective,\n    objective: ActivityObjective,\n  ): void {\n    try {\n      if (!objective.isPrimary && !globalObjective.updateAttemptData) {\n        return;\n      }\n\n      // Update attempt completion based on global objective satisfaction\n      // Only if completion is NOT controlled by rollup rules\n      const hasCompletionRollupRules = activity.rollupRules.rules.some(\n        (rule) => rule.action === \"completed\" || rule.action === \"incomplete\",\n      );\n\n      if (globalObjective.satisfiedStatusKnown && globalObjective.satisfiedStatus) {\n        // If global objective is satisfied, update local completion data\n        // UNLESS the activity has explicit rollup rules for completion\n        if (\n          !hasCompletionRollupRules &&\n          !activity.sequencingControls.completionSetByContent &&\n          !activity.attemptProgressStatus &&\n          (activity.completionStatus === CompletionStatus.UNKNOWN ||\n            activity.completionStatus === CompletionStatus.INCOMPLETE)\n        ) {\n          activity.completionStatus = CompletionStatus.COMPLETED;\n        }\n\n        // Update success status based on objective satisfaction\n        if (activity.successStatus === \"unknown\") {\n          activity.successStatus = \"passed\";\n        }\n      }\n\n      // Update attempt count if global objective indicates new attempt\n      if (globalObjective.attemptCount && globalObjective.attemptCount > activity.attemptCount) {\n        activity.attemptCount = globalObjective.attemptCount;\n      }\n\n      // Update completion amount based on progress measure\n      if (globalObjective.progressMeasureKnown && globalObjective.progressMeasure !== undefined) {\n        activity.attemptCompletionAmount = globalObjective.progressMeasure;\n      }\n\n      // Update absolute duration from global timing data\n      if (globalObjective.attemptAbsoluteDuration) {\n        activity.attemptAbsoluteDuration = globalObjective.attemptAbsoluteDuration;\n      }\n\n      if (globalObjective.attemptExperiencedDuration) {\n        activity.attemptExperiencedDuration = globalObjective.attemptExperiencedDuration;\n      }\n\n      // Update activity-level durations\n      if (globalObjective.activityAbsoluteDuration) {\n        activity.activityAbsoluteDuration = globalObjective.activityAbsoluteDuration;\n      }\n\n      if (globalObjective.activityExperiencedDuration) {\n        activity.activityExperiencedDuration = globalObjective.activityExperiencedDuration;\n      }\n\n      // Update location if provided by global state\n      if (globalObjective.location !== undefined) {\n        activity.location = globalObjective.location;\n      }\n\n      // Update suspension state based on global objective\n      if (globalObjective.suspendData !== undefined) {\n        activity.isSuspended = globalObjective.suspendData.length > 0;\n      }\n    } catch (error) {\n      // Log attempt data update error\n      this.eventCallback?.(\"attempt_data_update_error\", {\n        activityId: activity.id,\n        error: error instanceof Error ? error.message : String(error),\n        timestamp: new Date().toISOString(),\n      });\n    }\n  }\n}\n","import { Activity } from \"../activity\";\nimport { RollupChildFilter } from \"../rollup/rollup_child_filter\";\n\n/**\n * Event callback function type\n */\nexport type EventCallback = (eventType: string, data?: unknown) => void;\n\n/**\n * Rollup state log entry\n */\nexport interface RollupStateLogEntry {\n  activity: string;\n  timestamp: string;\n  state: {\n    measureStatus: boolean;\n    measure: number;\n    satisfiedStatus: boolean;\n    completionStatus: string;\n  };\n}\n\n/**\n * RollupStateValidator - Validates rollup state consistency across the activity tree\n * Implements SCORM 2004 rollup state validation\n *\n * This class is responsible for validating that rollup states are consistent\n * and valid before and after processing. It can detect inconsistencies between\n * parent and child activity states.\n *\n * @spec Priority 5 Gap: Rollup state validation\n */\nexport class RollupStateValidator {\n  private rollupStateLog: RollupStateLogEntry[] = [];\n  private childFilter: RollupChildFilter;\n  private eventCallback: EventCallback | null;\n\n  /**\n   * Create a new RollupStateValidator\n   *\n   * @param childFilter - RollupChildFilter instance for filtering children\n   * @param eventCallback - Optional callback for firing events\n   */\n  constructor(childFilter: RollupChildFilter, eventCallback?: EventCallback) {\n    this.childFilter = childFilter;\n    this.eventCallback = eventCallback || null;\n  }\n\n  /**\n   * Validate rollup state consistency across the activity tree\n   * Ensures that rollup states are consistent and valid before processing\n   *\n   * @param rootActivity - The root activity to validate from\n   * @returns True if state is consistent, false otherwise\n   */\n  public validateRollupStateConsistency(rootActivity: Activity): boolean {\n    try {\n      this.eventCallback?.(\"rollup_validation_started\", {\n        activityId: rootActivity.id,\n        timestamp: new Date().toISOString(),\n      });\n\n      const inconsistencies: string[] = [];\n\n      // Validate the entire tree recursively\n      this.validateActivityRollupState(rootActivity, inconsistencies);\n\n      if (inconsistencies.length > 0) {\n        this.eventCallback?.(\"rollup_state_inconsistencies\", {\n          activityId: rootActivity.id,\n          inconsistencies,\n          count: inconsistencies.length,\n        });\n        return false;\n      }\n\n      this.eventCallback?.(\"rollup_validation_completed\", {\n        activityId: rootActivity.id,\n        result: \"consistent\",\n      });\n      return true;\n    } catch (error) {\n      this.eventCallback?.(\"rollup_validation_error\", {\n        activityId: rootActivity.id,\n        error: error instanceof Error ? error.message : String(error),\n      });\n      return false;\n    }\n  }\n\n  /**\n   * Validate rollup state for a single activity\n   *\n   * @param activity - The activity to validate\n   * @param inconsistencies - Array to collect inconsistencies into\n   */\n  public validateActivityRollupState(activity: Activity, inconsistencies: string[]): void {\n    const activityId = activity.id;\n\n    // Check measure status consistency\n    if (activity.objectiveMeasureStatus && activity.objectiveNormalizedMeasure === null) {\n      inconsistencies.push(\n        `Activity ${activityId}: measure status true but normalized measure is null`,\n      );\n    }\n\n    // Check satisfaction status consistency with measure (only when success status is known)\n    if (\n      activity.primaryObjective?.satisfiedByMeasure === true &&\n      activity.objectiveMeasureStatus &&\n      activity.scaledPassingScore !== null &&\n      activity.successStatus !== \"unknown\"\n    ) {\n      const expectedSatisfied =\n        activity.objectiveNormalizedMeasure >= activity.scaledPassingScore;\n      if (activity.objectiveSatisfiedStatus !== expectedSatisfied) {\n        inconsistencies.push(\n          `Activity ${activityId}: satisfaction status inconsistent with measure`,\n        );\n      }\n    }\n\n    // Check rollup controls consistency\n    const controls = activity.sequencingControls;\n    // Note: Having rollup data without rollup controls enabled is valid (data from content).\n    // Clusters with measure data but rollup disabled could indicate an inconsistency,\n    // but this is unusual yet valid if set explicitly by content. We don't flag this\n    // as an error since it may be intentional.\n    //\n    // Rollup consideration states (RB.1.4 enhancement) are also valid and don't need\n    // flagging as inconsistencies:\n    // - \"ifAttempted\" with attemptCount=0: Activity will contribute once attempted\n    // - \"ifNotSuspended\" with isSuspended=true: Activity is temporarily excluded\n    // - \"ifNotSkipped\" with wasSkipped=true: Activity is excluded from rollup\n\n    // Check children consistency and their rollup contributions\n    const children = activity.getAvailableChildren();\n\n    // Validate parent's rolled-up state matches children's contributions\n    if (children.length > 0 && controls.rollupObjectiveSatisfied) {\n      const satisfiedChildren = children.filter(\n        (child) =>\n          this.childFilter.checkChildForRollupSubprocess(child, \"objective\", \"satisfied\") &&\n          this.childFilter.isChildSatisfiedForRollup(child),\n      );\n\n      const notSatisfiedChildren = children.filter(\n        (child) =>\n          this.childFilter.checkChildForRollupSubprocess(child, \"objective\", \"notSatisfied\") &&\n          !this.childFilter.isChildSatisfiedForRollup(child),\n      );\n\n      // If all contributing children are satisfied, parent should be satisfied\n      if (satisfiedChildren.length > 0 && notSatisfiedChildren.length === 0) {\n        if (\n          activity.objectiveSatisfiedStatus === false &&\n          activity.rollupRules.rules.length === 0\n        ) {\n          inconsistencies.push(\n            `Activity ${activityId}: all children satisfied but parent is not satisfied (no rollup rules to override)`,\n          );\n        }\n      }\n    }\n\n    if (children.length > 0 && controls.rollupProgressCompletion) {\n      const completedChildren = children.filter(\n        (child) =>\n          this.childFilter.checkChildForRollupSubprocess(child, \"progress\", \"completed\") &&\n          this.childFilter.isChildCompletedForRollup(child),\n      );\n\n      const incompleteChildren = children.filter(\n        (child) =>\n          this.childFilter.checkChildForRollupSubprocess(child, \"progress\", \"incomplete\") &&\n          !this.childFilter.isChildCompletedForRollup(child),\n      );\n\n      // If all contributing children are completed, parent should be completed\n      if (completedChildren.length > 0 && incompleteChildren.length === 0) {\n        if (\n          activity.completionStatus !== \"completed\" &&\n          activity.rollupRules.rules.length === 0\n        ) {\n          inconsistencies.push(\n            `Activity ${activityId}: all children completed but parent is incomplete (no rollup rules to override)`,\n          );\n        }\n      }\n    }\n\n    // Recursively validate children\n    for (const child of children) {\n      this.validateActivityRollupState(child, inconsistencies);\n    }\n\n    // Log validation state\n    this.rollupStateLog.push({\n      activity: activityId,\n      timestamp: new Date().toISOString(),\n      state: {\n        measureStatus: activity.objectiveMeasureStatus,\n        measure: activity.objectiveNormalizedMeasure,\n        satisfiedStatus: activity.objectiveSatisfiedStatus,\n        completionStatus: activity.completionStatus,\n      },\n    });\n  }\n\n  /**\n   * Get rollup state log\n   *\n   * @returns Array of rollup state log entries\n   */\n  public getRollupStateLog(): RollupStateLogEntry[] {\n    return [...this.rollupStateLog];\n  }\n\n  /**\n   * Clear rollup state log\n   */\n  public clearRollupStateLog(): void {\n    this.rollupStateLog = [];\n  }\n}\n","import { Activity } from \"./activity\";\nimport { RollupChildFilter } from \"./rollup/rollup_child_filter\";\nimport { RollupClockOptions, RollupRuleEvaluator } from \"./rollup/rollup_rule_evaluator\";\nimport { MeasureRollupProcessor } from \"./rollup/measure_rollup\";\nimport { ObjectiveRollupProcessor } from \"./rollup/objective_rollup\";\nimport { ProgressRollupProcessor } from \"./rollup/progress_rollup\";\nimport { DurationRollupProcessor } from \"./rollup/duration_rollup\";\nimport {\n  GlobalObjectiveSynchronizer,\n  GlobalObjective,\n  GlobalObjectiveWriteTargets,\n} from \"./objectives/global_objective_synchronizer\";\nimport { RollupStateValidator } from \"./validation/rollup_state_validator\";\n\n/**\n * Event callback function type\n */\nexport type EventCallback = (eventType: string, data?: unknown) => void;\n\n/**\n * Enhanced Rollup Process implementation for SCORM 2004 sequencing\n * Priority 5 Gap: Comprehensive rollup with global objective mapping and complex weighting\n *\n * This class serves as the orchestrator for all rollup operations, delegating\n * specific functionality to specialized processor classes:\n *\n * - RollupChildFilter: Child activity filtering for rollup\n * - RollupRuleEvaluator: Rollup rule evaluation\n * - MeasureRollupProcessor: Measure (score) rollup\n * - ObjectiveRollupProcessor: Objective satisfaction rollup\n * - ProgressRollupProcessor: Progress (completion) rollup\n * - DurationRollupProcessor: Duration aggregation rollup\n * - GlobalObjectiveSynchronizer: Global objective synchronization\n * - RollupStateValidator: State consistency validation\n *\n * @spec SN Book: RB.1.5 (Overall Rollup Process)\n */\nexport class RollupProcess {\n  /**\n   * Capability flag for hosts that supported older rollup behavior with a compatibility layer.\n   * Rollup contribution controls belong to an activity as a child of its parent; they do not gate\n   * calculation of the activity's own rolled-up state.\n   */\n  public readonly childContributionControlsApplyToParent = true;\n\n  private childFilter: RollupChildFilter;\n  private ruleEvaluator: RollupRuleEvaluator;\n  private measureProcessor: MeasureRollupProcessor;\n  private objectiveProcessor: ObjectiveRollupProcessor;\n  private progressProcessor: ProgressRollupProcessor;\n  private durationProcessor: DurationRollupProcessor;\n  private globalObjectiveSynchronizer: GlobalObjectiveSynchronizer;\n  private stateValidator: RollupStateValidator;\n  private eventCallback: EventCallback | null;\n\n  /**\n   * Create a new RollupProcess orchestrator\n   *\n   * @param eventCallback - Optional callback for firing events\n   * @param clock - Clock for time-based rollup conditions; pass the sequencing\n   *   process's `now` and `getAttemptElapsedSeconds` so rollup and sequencing rules agree\n   */\n  constructor(eventCallback?: EventCallback, clock: RollupClockOptions = {}) {\n    this.eventCallback = eventCallback || null;\n\n    // Initialize all processors with proper dependency injection\n    this.childFilter = new RollupChildFilter();\n    this.ruleEvaluator = new RollupRuleEvaluator(this.childFilter, clock);\n    this.measureProcessor = new MeasureRollupProcessor(this.childFilter, eventCallback);\n    this.objectiveProcessor = new ObjectiveRollupProcessor(\n      this.childFilter,\n      this.ruleEvaluator,\n      eventCallback,\n    );\n    this.progressProcessor = new ProgressRollupProcessor(\n      this.childFilter,\n      this.ruleEvaluator,\n      this.objectiveProcessor,\n      eventCallback,\n    );\n    this.durationProcessor = new DurationRollupProcessor(eventCallback);\n    this.globalObjectiveSynchronizer = new GlobalObjectiveSynchronizer(eventCallback);\n    this.stateValidator = new RollupStateValidator(this.childFilter, eventCallback);\n  }\n\n  /**\n   * Roll up one activity without duration rollup, ancestor traversal or global reads.\n   * @spec SCORM 2004 SN 4th Ed. RB.1.1 to RB.1.3\n   */\n  public rollupActivity(activity: Activity): void {\n    // Step 1: Measure Rollup Process (RB.1.1)\n    if (activity.children.length > 0) {\n      this.measureProcessor.measureRollupProcess(activity);\n      // Step 1b: Completion Measure Rollup Process (RB.1.1 b)\n      this.measureProcessor.completionMeasureRollupProcess(activity);\n    }\n\n    // The rollupObjectiveSatisfied and rollupProgressCompletion controls describe whether\n    // this activity contributes to its parent's rollup; they do not disable calculation of\n    // this activity's own rolled-up state. The child-filtering subprocess applies those\n    // controls to each contributing child (SCORM 2004 RB.1.4.2).\n\n    // Step 2: Objective Rollup Process (RB.1.2)\n    this.objectiveProcessor.objectiveRollupProcess(activity);\n\n    // Step 3: Activity Progress Rollup Process (RB.1.3)\n    this.progressProcessor.activityProgressRollupProcess(activity);\n  }\n\n  /**\n   * Overall Rollup Process\n   * Performs rollup from a given activity up through its ancestors\n   * OPTIMIZATION: Stops propagating rollup when status stops changing (SCORM 2004 4.6.1)\n   *\n   * @spec SN Book: RB.1.5 (Overall Rollup Process)\n   * @param activity - The activity to start rollup from\n   * @param globalObjectives - Shared global objectives\n   * @param includeActivity - Start with the activity itself instead of its parent\n   * @returns Array of activities that had status changes\n   */\n  public overallRollupProcess(\n    activity: Activity,\n    globalObjectives?: Map<string, GlobalObjective>,\n    includeActivity = false,\n  ): Activity[] {\n    const affectedActivities: Activity[] = [];\n    // Start from the activity when requested, otherwise from its parent.\n    let currentActivity: Activity | null = includeActivity ? activity : activity.parent;\n    let onlyDurationRollup = false;\n    let isFirst = true;\n\n    // Process rollup up the tree to the root\n    while (currentActivity) {\n      // Duration rollup happens FIRST, ALWAYS for cluster activities\n      // This happens even when optimization is active for other rollup types\n      if (currentActivity.children.length > 0) {\n        this.durationProcessor.durationRollupProcess(currentActivity);\n      }\n\n      if (!onlyDurationRollup) {\n        // Capture status BEFORE rollup\n        const beforeStatus = currentActivity.captureRollupStatus();\n\n        this.rollupActivity(currentActivity);\n\n        // A primary objective read map is the activity's view of the shared objective. Restore\n        // that view after calculating this cluster and before its parent evaluates the cluster as\n        // a rollup child. Without this step, a later descendant rollup can replace a previously\n        // satisfied test-out objective with the descendant aggregate even though the mapped\n        // global objective remains satisfied.\n        // @spec SCORM 2004 4th Ed. SN 3.10.3 and RB.1.5\n        if (globalObjectives) {\n          this.globalObjectiveSynchronizer.syncGlobalObjectivesReadPhase(\n            currentActivity,\n            globalObjectives,\n          );\n        }\n\n        // Capture status AFTER rollup\n        const afterStatus = currentActivity.captureRollupStatus();\n\n        // OPTIMIZATION: Check if anything changed (skip first iteration)\n        // The first activity always gets processed regardless of change\n        if (!isFirst) {\n          const changed = !Activity.compareRollupStatus(beforeStatus, afterStatus);\n          if (!changed) {\n            // No changes detected - activate optimization\n            this.eventCallback?.(\"rollup_optimization_activated\", {\n              activityId: currentActivity.id,\n              depth: affectedActivities.length,\n            });\n            onlyDurationRollup = true;\n          }\n        }\n\n        // Add to affected activities if status changed or is first iteration\n        if (isFirst || !Activity.compareRollupStatus(beforeStatus, afterStatus)) {\n          affectedActivities.push(currentActivity);\n        }\n      }\n\n      // Move up the tree\n      currentActivity = currentActivity.parent;\n      isFirst = false;\n    }\n\n    return affectedActivities;\n  }\n\n  // ============================================================================\n  // Public API Methods - Delegate to specialized processors\n  // ============================================================================\n\n  /**\n   * Validate rollup state consistency across the activity tree\n   *\n   * @param rootActivity - The root activity to validate from\n   * @returns True if state is consistent, false otherwise\n   */\n  public validateRollupStateConsistency(rootActivity: Activity): boolean {\n    return this.stateValidator.validateRollupStateConsistency(rootActivity);\n  }\n\n  /**\n   * Process global objective mapping for shared objectives\n   *\n   * @param activity - The root activity to start processing from\n   * @param globalObjectives - Global objective map\n   */\n  public processGlobalObjectiveMapping(\n    activity: Activity,\n    globalObjectives: Map<string, GlobalObjective>,\n  ): void {\n    const changedActivities = this.globalObjectiveSynchronizer.processGlobalObjectiveMapping(\n      activity,\n      globalObjectives,\n    );\n    const rolledUpParents = new Set<Activity>();\n\n    const activityDepth = (candidate: Activity): number => {\n      let depth = 0;\n      let parent = candidate.parent;\n      while (parent) {\n        depth += 1;\n        parent = parent.parent;\n      }\n      return depth;\n    };\n\n    // Descendant propagation can roll up through an activity whose own primary\n    // objective was populated by a read map. Process deepest-first, then refresh\n    // each directly mapped activity before propagating it so that mapped state\n    // remains authoritative over the intermediate descendant aggregate.\n    // @spec SCORM 2004 4th Ed. TR OB-03c / SN 3.10.3 and RB.1.1\n    changedActivities.sort((left, right) => activityDepth(right) - activityDepth(left));\n\n    // @spec SCORM 2004 4th Ed. SN 3.10.3 and RB.1.5 - read-mapped primary\n    // objective state participates in rollup before sequencing rules use the result.\n    for (const changedActivity of changedActivities) {\n      // @spec SCORM 2004 4th Ed. SN 3.13.1 Tracked - an untracked activity\n      // exposes read-mapped state to its SCO but does not participate in rollup.\n      if (!changedActivity.sequencingControls.tracked) {\n        continue;\n      }\n      this.globalObjectiveSynchronizer.syncGlobalObjectivesReadPhase(\n        changedActivity,\n        globalObjectives,\n      );\n      const parent = changedActivity.parent;\n      if (parent && !rolledUpParents.has(parent)) {\n        this.overallRollupProcess(changedActivity, globalObjectives);\n        rolledUpParents.add(parent);\n      }\n    }\n  }\n\n  /**\n   * Write the final objective status for one terminating activity before the\n   * tree-wide read phase runs.\n   *\n   * @spec SCORM 2004 SN 4th Ed. SM.7 Objective Map write timing\n   */\n  public syncTerminatedActivityObjectives(\n    activity: Activity,\n    globalObjectives: Map<string, GlobalObjective>,\n  ): GlobalObjectiveWriteTargets {\n    return this.globalObjectiveSynchronizer.syncTerminatedActivityWritePhase(\n      activity,\n      globalObjectives,\n    );\n  }\n\n  /**\n   * Restore an activity's read-mapped objective state after new-attempt initialization.\n   *\n   * DB.2 initializes attempt-scoped local objectives, while objective maps remain available\n   * across activities. Reapply the read phase before sequencing rules and navigation validity\n   * inspect the delivered attempt.\n   *\n   * @spec SCORM 2004 SN 4th Ed. DB.2 and 3.10.3 Objective Map read timing\n   */\n  public syncActivityObjectivesFromGlobals(\n    activity: Activity,\n    globalObjectives: Map<string, GlobalObjective>,\n  ): boolean {\n    return this.globalObjectiveSynchronizer.syncGlobalObjectivesDeliveryReadPhase(\n      activity,\n      globalObjectives,\n    );\n  }\n\n  /**\n   * Apply a terminating descendant's fresh objective writes to an active ancestor.\n   *\n   * @spec SCORM 2004 SN 4th Ed. SM.7 Objective Map write timing\n   */\n  public syncFreshlyWrittenObjectivesToActiveAncestor(\n    activity: Activity,\n    globalObjectives: Map<string, GlobalObjective>,\n    writeTargets: GlobalObjectiveWriteTargets,\n  ): boolean {\n    return this.globalObjectiveSynchronizer.syncFreshlyWrittenGlobalObjectivesReadPhase(\n      activity,\n      globalObjectives,\n      writeTargets,\n    );\n  }\n\n  // ============================================================================\n  // Accessor methods for individual processors (for advanced use cases)\n  // ============================================================================\n\n  /**\n   * Get the child filter processor\n   */\n  public getChildFilter(): RollupChildFilter {\n    return this.childFilter;\n  }\n\n  /**\n   * Get the rule evaluator processor\n   */\n  public getRuleEvaluator(): RollupRuleEvaluator {\n    return this.ruleEvaluator;\n  }\n\n  /**\n   * Get the measure rollup processor\n   */\n  public getMeasureProcessor(): MeasureRollupProcessor {\n    return this.measureProcessor;\n  }\n\n  /**\n   * Get the objective rollup processor\n   */\n  public getObjectiveProcessor(): ObjectiveRollupProcessor {\n    return this.objectiveProcessor;\n  }\n\n  /**\n   * Get the progress rollup processor\n   */\n  public getProgressProcessor(): ProgressRollupProcessor {\n    return this.progressProcessor;\n  }\n\n  /**\n   * Get the duration rollup processor\n   */\n  public getDurationProcessor(): DurationRollupProcessor {\n    return this.durationProcessor;\n  }\n\n  /**\n   * Get the global objective synchronizer\n   */\n  public getGlobalObjectiveSynchronizer(): GlobalObjectiveSynchronizer {\n    return this.globalObjectiveSynchronizer;\n  }\n\n  /**\n   * Get the state validator\n   */\n  public getStateValidator(): RollupStateValidator {\n    return this.stateValidator;\n  }\n}\n","import { Activity } from \"../activity\";\nimport { ActivityTree } from \"../activity_tree\";\nimport { ActivityTreeQueries } from \"../utils/activity_tree_queries\";\nimport { GlobalObjective, GlobalObjectiveSynchronizer } from \"./global_objective_synchronizer\";\n\n/**\n * Disposable objective state for evaluating a possible branch change.\n * @spec SCORM 2004 SN 4th Ed. SB.2.2 / SB.2.9 / DB.1.1 - validation must not commit UP.3/UP.4.\n * @spec SCORM 2004 SN 4th Ed. SM.7 - read maps see the departing clusters' current rolled-up values.\n */\nexport class ObjectiveEvaluationContext {\n  private synchronizer = new GlobalObjectiveSynchronizer();\n  private treeQueries: ActivityTreeQueries;\n\n  constructor(\n    private activityTree: ActivityTree,\n    private globalObjectives: Map<string, GlobalObjective>,\n  ) {\n    this.treeQueries = new ActivityTreeQueries(activityTree);\n  }\n\n  /**\n   * Overlay the old branch's write maps on copied global entries, then read them\n   * into a disposable candidate. No end-attempt, rollup or live writer runs here.\n   * @spec SCORM 2004 SN 4th Ed. UP.3 / SM.7 - exclude the common ancestor and preserve live attempt state.\n   */\n  public project(activity: Activity, target: Activity = activity): Activity {\n    const current = this.activityTree.currentActivity;\n    const commonAncestor = this.treeQueries.findCommonAncestor(current, target);\n    if (!current || current === commonAncestor) {\n      return activity;\n    }\n\n    const leaving: Activity[] = [];\n    let ancestor = current.parent;\n    while (ancestor && ancestor !== commonAncestor) {\n      if (ancestor.isActive) leaving.push(ancestor);\n      ancestor = ancestor.parent;\n    }\n    if (leaving.length === 0) return activity;\n\n    const projectedGlobals = new Map(this.globalObjectives);\n    for (const cluster of leaving) {\n      for (const objective of cluster.getAllObjectives()) {\n        for (const map of objective.mapInfo) {\n          const targetId = map.targetObjectiveID || objective.id;\n          const entry = projectedGlobals.get(targetId);\n          if (entry) projectedGlobals.set(targetId, { ...entry });\n        }\n      }\n      // Reuse SM.7 field/unknown semantics on copies of BOTH sides. The writer\n      // clears dirty flags only on this disposable objective view.\n      this.synchronizer.syncTerminatedActivityWritePhase(\n        cluster.createObjectiveEvaluationView(),\n        projectedGlobals,\n      );\n    }\n\n    const view = activity.createObjectiveEvaluationView();\n    this.synchronizer.syncGlobalObjectivesReadPhase(view, projectedGlobals);\n    return view;\n  }\n}\n","import { CompletionStatus } from \"../../constants/enums\";\n\nexport type CompletionStatusThresholdInput = {\n  completionThreshold?: number | string | null | undefined;\n  progressMeasure?: number | string | null | undefined;\n  storedCompletionStatus?: string | null | undefined;\n};\n\n/**\n * Evaluate cmi.completion_status from completion_threshold and progress_measure.\n *\n * @spec SCORM 2004 4th Ed. RTE 4.2.4.1a / RTE 4.2.9\n */\nexport function evaluateCompletionStatusFromThreshold({\n  completionThreshold,\n  progressMeasure,\n  storedCompletionStatus,\n}: CompletionStatusThresholdInput): string {\n  if (\n    completionThreshold !== \"\" &&\n    completionThreshold !== null &&\n    completionThreshold !== undefined\n  ) {\n    const thresholdValue = parseFloat(String(completionThreshold));\n\n    if (!isNaN(thresholdValue)) {\n      if (progressMeasure !== \"\" && progressMeasure !== null && progressMeasure !== undefined) {\n        const progressValue = parseFloat(String(progressMeasure));\n\n        if (!isNaN(progressValue)) {\n          return progressValue >= thresholdValue\n            ? CompletionStatus.COMPLETED\n            : CompletionStatus.INCOMPLETE;\n        }\n      }\n\n      return CompletionStatus.UNKNOWN;\n    }\n  }\n\n  return storedCompletionStatus || CompletionStatus.UNKNOWN;\n}\n","import { Activity, ActivityObjectiveScoreState } from \"../activity\";\nimport { CompletionStatus, SuccessStatus } from \"../../../../constants/enums\";\nimport { evaluateCompletionStatusFromThreshold } from \"../../completion_status_evaluation\";\n\n/**\n * Interface for CMI data provided for RTE data transfer\n */\nexport interface CMIDataForTransfer {\n  completion_status?: string;\n  completion_status_was_set?: boolean;\n  success_status?: string;\n  success_status_was_set?: boolean;\n  score_was_set?: boolean;\n  score?: {\n    scaled?: string;\n    raw?: string;\n    min?: string;\n    max?: string;\n  };\n  progress_measure?: string;\n  objectives?: Array<{\n    id: string;\n    success_status?: string;\n    success_status_was_set?: boolean;\n    score_was_set?: boolean;\n    completion_status?: string;\n    completion_status_was_set?: boolean;\n    score?: {\n      scaled?: string;\n      raw?: string;\n      min?: string;\n      max?: string;\n    };\n    progress_measure?: string;\n  }>;\n}\n\n/**\n * Score data structure for normalization\n */\nexport interface ScoreData {\n  scaled?: string;\n  raw?: string;\n  min?: string;\n  max?: string;\n}\n\n/**\n * Event data emitted during RTE data transfer operations\n */\nexport interface RteTransferEventData {\n  /** The activity ID that received the transferred data */\n  activityId: string;\n  /** ISO timestamp of when the transfer occurred */\n  timestamp: string;\n}\n\n/**\n * Context interface for RTE data transfer operations.\n *\n * Provides callbacks to access CMI data and fire events during transfer.\n * All callbacks are invoked synchronously during the transfer process.\n *\n * @remarks\n * This interface enables dependency injection, making the RteDataTransferService\n * testable in isolation without requiring a full TerminationHandler instance.\n */\nexport interface RteDataTransferContext {\n  /** Function to get CMI data from the runtime environment. May return null if no data available. */\n  getCMIData: (() => CMIDataForTransfer | null) | null;\n\n  /** Event callback for firing transfer events */\n  fireEvent: (eventType: string, data?: RteTransferEventData) => void;\n}\n\n/** Valid success status values per SCORM 2004 specification */\nconst VALID_SUCCESS_STATUSES: readonly string[] = [\n  SuccessStatus.PASSED,\n  SuccessStatus.FAILED,\n  SuccessStatus.UNKNOWN,\n];\n\n/**\n * Converts an RTE completion status into sequencing's completion state.\n *\n * @spec SCORM 2004 4th Ed. RTE-to-SN Data Transfer - a known RTE status other\n * than completed represents a known-false sequencing completion status.\n */\nfunction validateCompletionStatus(value: string | undefined): CompletionStatus | null {\n  if (value === CompletionStatus.COMPLETED) {\n    return CompletionStatus.COMPLETED;\n  }\n  if (value === CompletionStatus.INCOMPLETE || value === \"not attempted\") {\n    return CompletionStatus.INCOMPLETE;\n  }\n  if (value === CompletionStatus.UNKNOWN) {\n    return CompletionStatus.UNKNOWN;\n  }\n  return null;\n}\n\n/**\n * Validates and returns a SuccessStatus value, or null if invalid\n */\nfunction validateSuccessStatus(value: string | undefined): SuccessStatus | null {\n  if (value && VALID_SUCCESS_STATUSES.includes(value)) {\n    return value as SuccessStatus;\n  }\n  return null;\n}\n\n/**\n * RteDataTransferService\n *\n * Handles the transfer of CMI data from the runtime environment (RTE) to activity state.\n * Extracted from TerminationHandler to follow Single Responsibility Principle.\n *\n * Responsibilities:\n * - Transfer primary objective data (cmi.completion_status, cmi.success_status, cmi.score.*)\n * - Transfer non-primary objectives (cmi.objectives[n].*)\n * - Normalize scores from raw/min/max to scaled format\n * - Set dirty flags to ensure proper global objective mapping\n *\n * @spec SN Book: RTE Data Transfer (referenced in UP.4 End Attempt Process)\n */\nexport class RteDataTransferService {\n  private context: RteDataTransferContext;\n\n  constructor(context: RteDataTransferContext) {\n    this.context = context;\n  }\n\n  /**\n   * Transfer RTE Data to Activity\n   * Transfers CMI data from runtime environment to activity state\n   * Called at the start of endAttemptProcess to ensure proper data transfer\n   * @param {Activity} activity - The activity to transfer data to\n   */\n  public transferRteData(activity: Activity): void {\n    if (!this.context.getCMIData) {\n      // No CMI data provider, skip transfer\n      return;\n    }\n\n    const cmiData = this.context.getCMIData();\n    if (!cmiData) {\n      return;\n    }\n\n    // Transfer primary objective data (cmi.* level)\n    this.transferPrimaryObjective(activity, cmiData);\n\n    // Transfer non-primary objectives (cmi.objectives[n])\n    this.transferNonPrimaryObjectives(activity, cmiData);\n\n    this.context.fireEvent(\"onRteDataTransfer\", {\n      activityId: activity.id,\n      timestamp: new Date().toISOString(),\n    });\n  }\n\n  /**\n   * Transfer primary objective data from CMI to activity\n   * @param {Activity} activity - The activity to transfer data to\n   * @param {CMIDataForTransfer} cmiData - CMI data from runtime\n   *\n   * @spec SCORM 2004 4th Ed. RTE-to-SN Data Transfer - primary objective status and score data\n   * @spec SCORM 2004 4th Ed. ADLSEQ objectives extension - raw/min/max score write-map source data\n   */\n  public transferPrimaryObjective(activity: Activity, cmiData: CMIDataForTransfer): void {\n    // Transfer progress measure first so completedByMeasure completion derivation\n    // and measure rollup both see the latest value.\n    let hasProgressMeasure = false;\n    if (cmiData.progress_measure && cmiData.progress_measure !== \"\") {\n      const progressMeasure = parseFloat(cmiData.progress_measure);\n      if (!isNaN(progressMeasure)) {\n        hasProgressMeasure = true;\n        activity.progressMeasure = progressMeasure;\n        activity.progressMeasureStatus = true;\n        activity.attemptCompletionAmount = progressMeasure;\n        activity.attemptCompletionAmountStatus = true;\n\n        if (activity.primaryObjective) {\n          activity.primaryObjective.progressMeasure = progressMeasure;\n          activity.primaryObjective.progressMeasureStatus = true;\n        }\n      }\n    }\n\n    if (!hasProgressMeasure) {\n      activity.attemptCompletionAmountStatus = false;\n    }\n\n    // Transfer completion status\n    if (activity.completedByMeasure) {\n      const completionStatus = evaluateCompletionStatusFromThreshold({\n        completionThreshold: activity.minProgressMeasure,\n        progressMeasure: cmiData.progress_measure,\n        storedCompletionStatus: CompletionStatus.UNKNOWN,\n      });\n\n      activity.completionStatus = completionStatus as CompletionStatus;\n      activity.attemptProgressStatus = completionStatus !== CompletionStatus.UNKNOWN;\n    } else {\n      const validatedCompletionStatus = validateCompletionStatus(cmiData.completion_status);\n      if (validatedCompletionStatus && validatedCompletionStatus !== CompletionStatus.UNKNOWN) {\n        activity.completionStatus = validatedCompletionStatus;\n        activity.attemptProgressStatus = true;\n      }\n    }\n\n    // Collect values that need to be transferred\n    let hasSuccessStatus = false;\n    let successStatus = false;\n    let hasNormalizedMeasure = false;\n    let normalizedScore = 0;\n    const satisfiedByMeasure = activity.primaryObjective?.satisfiedByMeasure === true;\n\n    // Transfer success status\n    const validatedSuccessStatus = validateSuccessStatus(cmiData.success_status);\n    if (\n      !satisfiedByMeasure &&\n      validatedSuccessStatus &&\n      validatedSuccessStatus !== SuccessStatus.UNKNOWN\n    ) {\n      successStatus = validatedSuccessStatus === SuccessStatus.PASSED;\n      hasSuccessStatus = true;\n      activity.objectiveSatisfiedStatus = successStatus;\n      activity.objectiveSatisfiedStatusKnown = true; // Mark as known when transferred from CMI\n      activity.successStatus = validatedSuccessStatus;\n    }\n\n    // Transfer score (with normalization support)\n    if (cmiData.score) {\n      // @spec SCORM 2004 4th Ed. ADLSEQ objectives extension - raw/min/max\n      // score write maps use the RTE score values, independent of scaled score.\n      activity.primaryObjective?.initializeScoreFromCMI(this.getObjectiveScoreState(cmiData.score));\n\n      const normalized = this.normalizeScore(cmiData.score);\n      if (normalized !== null) {\n        normalizedScore = normalized;\n        hasNormalizedMeasure = true;\n        activity.objectiveNormalizedMeasure = normalizedScore;\n        activity.objectiveMeasureStatus = true;\n      }\n    }\n\n    if (satisfiedByMeasure && hasNormalizedMeasure) {\n      // @spec SCORM 2004 4th Ed. SN 3.10 Objective Description - when\n      // satisfiedByMeasure is true, satisfaction is derived from a known measure;\n      // the default minimum normalized measure is 1.0.\n      successStatus = normalizedScore >= (activity.primaryObjective?.minNormalizedMeasure ?? 1.0);\n      hasSuccessStatus = true;\n      activity.objectiveSatisfiedStatus = successStatus;\n      activity.objectiveSatisfiedStatusKnown = true;\n      activity.successStatus = successStatus ? SuccessStatus.PASSED : SuccessStatus.FAILED;\n    }\n\n    // Use initializeFromCMI to ensure dirty flags are set for primary objective\n    // This must be called after collecting both values to avoid overwriting\n    if (activity.primaryObjective && (hasSuccessStatus || hasNormalizedMeasure)) {\n      const finalStatus = hasSuccessStatus\n        ? successStatus\n        : activity.primaryObjective.satisfiedStatus;\n      const finalMeasure = hasNormalizedMeasure\n        ? normalizedScore\n        : activity.primaryObjective.normalizedMeasure;\n      const measureStatus = hasNormalizedMeasure;\n\n      activity.primaryObjective.initializeFromCMI(finalStatus, finalMeasure, measureStatus);\n\n      if (hasSuccessStatus) {\n        activity.primaryObjective.satisfiedStatusKnown = true; // Mark as known\n        activity.primaryObjective.progressStatus = true;\n      }\n    }\n  }\n\n  /**\n   * Transfer objective-array data from CMI to matching activity objectives.\n   * Only transfers changed values to protect global objectives.\n   * @param {Activity} activity - The activity to transfer data to\n   * @param {CMIDataForTransfer} cmiData - CMI data from runtime\n   *\n   * @spec SCORM 2004 4th Ed. RTE 4.2.17 - cmi.objectives.n data, including\n   * the primary objective entry, is part of the RTE objective data model.\n   * @spec SCORM 2004 4th Ed. SN 3.10.3 and ADLSEQ objectives extension -\n   * mapped objective status and raw/min/max score data transfer through\n   * objective maps to sequencing state.\n   */\n  public transferNonPrimaryObjectives(activity: Activity, cmiData: CMIDataForTransfer): void {\n    if (!cmiData.objectives || cmiData.objectives.length === 0) {\n      return;\n    }\n\n    for (const cmiObjective of cmiData.objectives) {\n      if (!cmiObjective.id) {\n        continue;\n      }\n\n      // Find matching activity objective by ID\n      const activityObjectiveMatch = activity.getObjectiveById(cmiObjective.id);\n      if (!activityObjectiveMatch) {\n        continue;\n      }\n\n      const activityObjective = activityObjectiveMatch.objective;\n      const isPrimaryObjective = activityObjectiveMatch.isPrimary;\n\n      // Track whether we need to initialize from CMI\n      let hasSuccessStatus = false;\n      let hasExplicitUnknownSuccessStatus = false;\n      let successStatus = false;\n      let hasNormalizedMeasure = false;\n      let normalizedScore = 0;\n      let hasCompletionStatus = false;\n      let hasProgressMeasure = false;\n\n      const topLevelCompletionStatus = validateCompletionStatus(cmiData.completion_status);\n      const topLevelPrimaryCompletionWasSet =\n        cmiData.completion_status_was_set === true ||\n        (cmiData.completion_status_was_set === undefined &&\n          topLevelCompletionStatus !== null &&\n          topLevelCompletionStatus !== CompletionStatus.UNKNOWN);\n      const topLevelSuccessStatus = validateSuccessStatus(cmiData.success_status);\n      const topLevelPrimarySuccessWasSet =\n        cmiData.success_status_was_set === true ||\n        (cmiData.success_status_was_set === undefined &&\n          topLevelSuccessStatus !== null &&\n          topLevelSuccessStatus !== SuccessStatus.UNKNOWN);\n      const topLevelPrimaryScoreWasSet =\n        cmiData.score_was_set === true ||\n        (cmiData.score_was_set === undefined &&\n          cmiData.score !== undefined &&\n          this.normalizeScore(cmiData.score) !== null);\n\n      // Transfer success status. Read-mapped values remain valid write-map\n      // sources even when the SCO leaves them untouched. The one conflicting\n      // case is a seeded primary objective row after content explicitly writes\n      // the top-level primary status; the content write is authoritative.\n      // @spec SCORM 2004 4th Ed. RTE 4.2.17 / SN 3.10.3\n      const validatedObjSuccessStatus = validateSuccessStatus(cmiObjective.success_status);\n      if (\n        !activityObjective.satisfiedByMeasure &&\n        validatedObjSuccessStatus &&\n        validatedObjSuccessStatus !== SuccessStatus.UNKNOWN &&\n        (cmiObjective.success_status_was_set !== false ||\n          !isPrimaryObjective ||\n          !topLevelPrimarySuccessWasSet)\n      ) {\n        successStatus = validatedObjSuccessStatus === SuccessStatus.PASSED;\n        hasSuccessStatus = true;\n        activityObjective.progressStatus = true;\n      } else if (\n        !activityObjective.satisfiedByMeasure &&\n        validatedObjSuccessStatus === SuccessStatus.UNKNOWN &&\n        cmiObjective.success_status_was_set === true\n      ) {\n        // An untouched launch default must not clear mapped state, but a SCO's\n        // explicit unknown replaces the prior known satisfaction value.\n        // @spec SCORM 2004 4th Ed. RTE 4.2.17 / SN 3.10.3\n        activityObjective.initializeUnknownSatisfiedStatusFromCMI();\n        hasExplicitUnknownSuccessStatus = true;\n      }\n\n      // Transfer completion status\n      const validatedObjCompletionStatus = validateCompletionStatus(cmiObjective.completion_status);\n      if (validatedObjCompletionStatus === CompletionStatus.UNKNOWN) {\n        if (cmiObjective.completion_status_was_set === true) {\n          // A fresh local attempt starts unknown even when its RTE view was\n          // initialized from a known global. Preserve the semantic write so it\n          // clears that mapped global rather than disappearing as a no-op.\n          // @spec SCORM 2004 4th Ed. RTE 4.2.17 / SN 3.10.3\n          activityObjective.initializeUnknownCompletionStatusFromCMI();\n          hasCompletionStatus = true;\n        }\n      } else if (\n        validatedObjCompletionStatus !== null &&\n        (cmiObjective.completion_status_was_set !== false ||\n          !isPrimaryObjective ||\n          !topLevelPrimaryCompletionWasSet)\n      ) {\n        // @spec SCORM 2004 4th Ed. RTE 4.2.17 / SN 3.10.3 - an objective\n        // completion status changed to unknown removes a previously known local\n        // status; an untouched default unknown does not create a mapped write.\n        // A launch-seeded primary objective row likewise cannot replace a later\n        // content write to the top-level primary completion status.\n        activityObjective.completionStatus = validatedObjCompletionStatus;\n        hasCompletionStatus = true;\n      }\n\n      // Transfer score (with normalization)\n      const objectiveScoreMayOverridePrimary =\n        cmiObjective.score_was_set !== false || !isPrimaryObjective || !topLevelPrimaryScoreWasSet;\n      if (cmiObjective.score && objectiveScoreMayOverridePrimary) {\n        // @spec SCORM 2004 4th Ed. ADLSEQ objectives extension - raw/min/max\n        // score write maps use the RTE objective score values, independent of scaled score.\n        activityObjective.initializeScoreFromCMI(this.getObjectiveScoreState(cmiObjective.score));\n\n        const normalized = this.normalizeScore(cmiObjective.score);\n        if (normalized !== null) {\n          normalizedScore = normalized;\n          hasNormalizedMeasure = true;\n        }\n      }\n\n      if (activityObjective.satisfiedByMeasure && hasNormalizedMeasure) {\n        // @spec SCORM 2004 4th Ed. SN 3.10 Objective Description - objective\n        // satisfaction is derived only from a known normalized measure.\n        successStatus = normalizedScore >= (activityObjective.minNormalizedMeasure ?? 1.0);\n        hasSuccessStatus = true;\n        activityObjective.progressStatus = true;\n      }\n\n      // If we have either success status or normalized measure from CMI, use initializeFromCMI\n      // to ensure dirty flags are set even if values match defaults\n      if (hasSuccessStatus || hasNormalizedMeasure) {\n        const finalStatus = hasSuccessStatus ? successStatus : activityObjective.satisfiedStatus;\n        const finalMeasure = hasNormalizedMeasure\n          ? normalizedScore\n          : activityObjective.normalizedMeasure;\n        const measureStatus = hasNormalizedMeasure;\n        activityObjective.initializeFromCMI(finalStatus, finalMeasure, measureStatus);\n\n        if (hasSuccessStatus) {\n          activityObjective.satisfiedStatusKnown = true;\n        }\n      }\n\n      // Transfer progress measure\n      if (cmiObjective.progress_measure && cmiObjective.progress_measure !== \"\") {\n        const progressMeasure = parseFloat(cmiObjective.progress_measure);\n        if (!isNaN(progressMeasure)) {\n          activityObjective.progressMeasure = progressMeasure;\n          activityObjective.progressMeasureStatus = true;\n          hasProgressMeasure = true;\n        }\n      }\n\n      if (\n        isPrimaryObjective &&\n        (hasSuccessStatus ||\n          hasExplicitUnknownSuccessStatus ||\n          hasNormalizedMeasure ||\n          hasCompletionStatus ||\n          hasProgressMeasure)\n      ) {\n        // @spec SCORM 2004 4th Ed. RTE 4.2.17 / SN 3.10.3 - a SCO may set\n        // the delivered primary objective through cmi.objectives.n; those\n        // values must become the activity's primary objective state before\n        // UP.4 End Attempt auto-satisfaction or mapped global writes run.\n        activityObjective.applyToActivity(activity);\n\n        if (hasSuccessStatus) {\n          activity.successStatus = successStatus ? SuccessStatus.PASSED : SuccessStatus.FAILED;\n        } else if (hasExplicitUnknownSuccessStatus) {\n          activity.successStatus = SuccessStatus.UNKNOWN;\n        }\n\n        if (hasCompletionStatus) {\n          activity.attemptProgressStatus =\n            activityObjective.completionStatus !== CompletionStatus.UNKNOWN;\n        }\n\n        if (hasProgressMeasure) {\n          activity.attemptCompletionAmount = activityObjective.progressMeasure;\n          activity.attemptCompletionAmountStatus = true;\n        }\n      }\n    }\n  }\n\n  /**\n   * Normalize score from raw/min/max if scaled is not available\n   * Implements ScaleRawScore process\n   * @param {ScoreData} score - Score object with scaled, raw, min, max\n   * @return {number | null} - Normalized score or null if cannot normalize\n   */\n  public normalizeScore(score: ScoreData): number | null {\n    // If scaled score exists, use it directly\n    if (score.scaled && score.scaled !== \"\") {\n      const scaled = parseFloat(score.scaled);\n      if (!isNaN(scaled)) {\n        return scaled;\n      }\n    }\n\n    // If no scaled score, try to calculate from raw/min/max\n    if (\n      score.raw &&\n      score.raw !== \"\" &&\n      score.min &&\n      score.min !== \"\" &&\n      score.max &&\n      score.max !== \"\"\n    ) {\n      const raw = parseFloat(score.raw);\n      const min = parseFloat(score.min);\n      const max = parseFloat(score.max);\n\n      if (!isNaN(raw) && !isNaN(min) && !isNaN(max) && max > min) {\n        // ScaleRawScore formula: scaled = (raw - min) / (max - min)\n        const normalized = (raw - min) / (max - min);\n\n        // Clamp to [-1, 1] range per SCORM spec\n        return Math.max(-1, Math.min(1, normalized));\n      }\n    }\n\n    return null;\n  }\n\n  /**\n   * Convert RTE score data into objective score-map state without numeric reformatting.\n   *\n   * @spec SCORM 2004 4th Ed. RTE-to-SN Data Transfer - score values transfer from RTE to sequencing state\n   * @spec SCORM 2004 4th Ed. ADLSEQ objectives extension - raw/min/max score map fields are independent\n   */\n  private getObjectiveScoreState(score: ScoreData): ActivityObjectiveScoreState {\n    const scoreState: ActivityObjectiveScoreState = {};\n\n    if (score.raw !== undefined) {\n      scoreState.rawScore = score.raw;\n    }\n    if (score.min !== undefined) {\n      scoreState.minScore = score.min;\n    }\n    if (score.max !== undefined) {\n      scoreState.maxScore = score.max;\n    }\n\n    return scoreState;\n  }\n}\n","import { Activity } from \"../activity\";\nimport { ActivityTree } from \"../activity_tree\";\nimport {\n  SequencingProcess,\n  SequencingRequestType,\n  PostConditionResult,\n} from \"../sequencing_process\";\nimport { RollupProcess } from \"../rollup_process\";\nimport { RuleActionType } from \"../sequencing_rules\";\nimport { SelectionRandomization } from \"../selection_randomization\";\nimport { RteDataTransferService } from \"./rte_data_transfer\";\nimport type { RteDataTransferContext, CMIDataForTransfer } from \"./rte_data_transfer\";\n\n// Re-export CMIDataForTransfer for backward compatibility\nexport type { CMIDataForTransfer } from \"./rte_data_transfer\";\n\n/**\n * Result of Termination Request Process\n * Contains the termination result, sequencing request, and validity\n * @spec SN Book: TB.2.3 (Termination Request Process)\n */\nexport interface TerminationResult {\n  terminationRequest: SequencingRequestType;\n  sequencingRequest: SequencingRequestType | null;\n  exception: string | null;\n  valid: boolean;\n}\n\n/**\n * Options for configuring the TerminationHandler\n */\nexport interface TerminationHandlerOptions {\n  getCMIData?: () => CMIDataForTransfer;\n  is4thEdition?: boolean;\n}\n\n/**\n * TerminationHandler\n *\n * Handles all termination-related processing for the SCORM 2004 sequencing engine.\n * Extracted from OverallSequencingProcess to follow Single Responsibility Principle.\n *\n * Responsibilities:\n * - Process termination requests (EXIT, EXIT_ALL, ABANDON, ABANDON_ALL, SUSPEND_ALL)\n * - Handle post-condition loops for EXIT_PARENT cascading\n * - End attempts and cleanup activity states\n * - Transfer RTE data to activity state\n *\n * @spec SN Book: TB.2.3 (Termination Request Process)\n */\nexport class TerminationHandler {\n  private activityTree: ActivityTree;\n  private sequencingProcess: SequencingProcess;\n  private rollupProcess: RollupProcess;\n  private globalObjectiveMap: Map<string, any>;\n  private eventCallback: ((eventType: string, data?: any) => void) | null;\n  private getCMIData: (() => CMIDataForTransfer) | null;\n  private is4thEdition: boolean;\n  private invalidateCacheCallback: (() => void) | null = null;\n  private _rteDataTransferService: RteDataTransferService;\n\n  constructor(\n    activityTree: ActivityTree,\n    sequencingProcess: SequencingProcess,\n    rollupProcess: RollupProcess,\n    globalObjectiveMap: Map<string, any>,\n    eventCallback: ((eventType: string, data?: any) => void) | null = null,\n    options?: TerminationHandlerOptions,\n  ) {\n    this.activityTree = activityTree;\n    this.sequencingProcess = sequencingProcess;\n    this.rollupProcess = rollupProcess;\n    this.globalObjectiveMap = globalObjectiveMap;\n    this.eventCallback = eventCallback;\n    this.getCMIData = options?.getCMIData || null;\n    this.is4thEdition = options?.is4thEdition || false;\n\n    // Initialize RTE data transfer service\n    const rteContext: RteDataTransferContext = {\n      getCMIData: this.getCMIData,\n      fireEvent: (eventType: string, data?: any) => this.fireEvent(eventType, data),\n    };\n    this._rteDataTransferService = new RteDataTransferService(rteContext);\n  }\n\n  /**\n   * Set callback to invalidate navigation cache after state changes\n   */\n  public setInvalidateCacheCallback(callback: () => void): void {\n    this.invalidateCacheCallback = callback;\n  }\n\n  /**\n   * Enhanced Termination Request Process\n   * Processes termination requests with post-condition loop for EXIT_PARENT handling\n   * Implements missing post-condition loop per SCORM 2004 3rd Edition TB.2.3\n   * @spec SN Book: TB.2.3 (Termination Request Process)\n   * @param {SequencingRequestType} request - The termination request\n   * @param {boolean} hasSequencingRequest - Whether a sequencing request follows\n   * @param {string} exitType - The cmi.exit value (logout, normal, suspend, time-out, or empty)\n   * @return {TerminationResult} - Termination result with sequencing request\n   */\n  public processTerminationRequest(\n    request: SequencingRequestType,\n    hasSequencingRequest: boolean = false,\n    exitType?: string,\n  ): TerminationResult {\n    const currentActivity = this.activityTree.currentActivity;\n\n    if (!currentActivity) {\n      return {\n        terminationRequest: request,\n        sequencingRequest: null,\n        exception: \"TB.2.3-1\",\n        valid: false,\n      };\n    }\n\n    // TB.2.3-2: Check if trying to terminate already-terminated activity\n    if (\n      (request === SequencingRequestType.EXIT || request === SequencingRequestType.ABANDON) &&\n      !currentActivity.isActive\n    ) {\n      return {\n        terminationRequest: request,\n        sequencingRequest: null,\n        exception: \"TB.2.3-2\",\n        valid: false,\n      };\n    }\n\n    // Enhanced logging for debugging\n    this.fireEvent(\"onTerminationRequestProcessing\", {\n      request,\n      hasSequencingRequest,\n      currentActivity: currentActivity.id,\n      exitType,\n    });\n\n    // REQ-NAV-025: Handle logout exit - treat as exitAll navigation request\n    if (exitType === \"logout\") {\n      this.fireEvent(\"onSequencingDebug\", {\n        message: \"cmi.exit='logout' detected, treating as EXIT_ALL\",\n        activityId: currentActivity.id,\n      });\n      return this.handleExitAll(currentActivity);\n    }\n\n    // cmi.exit=\"suspend\" preserves this SCO's attempt data for its next delivery. This is local\n    // activity suspension, not a Suspend All request, so do not set the tree's suspendedActivity.\n    // Mark it before UP.4 so auto-completion and auto-satisfaction do not replace content state.\n    // @spec SCORM 2004 4th Ed. RTE 4.2.8 cmi.exit and SN UP.4 End Attempt Process\n    if (exitType === \"suspend\" && request === SequencingRequestType.EXIT) {\n      currentActivity.isSuspended = true;\n    }\n\n    // Handle different termination types\n    switch (request) {\n      case SequencingRequestType.EXIT:\n        return this.handleExit(currentActivity, hasSequencingRequest);\n\n      case SequencingRequestType.EXIT_ALL:\n        return this.handleExitAll(currentActivity);\n\n      case SequencingRequestType.ABANDON:\n        return this.handleAbandon(currentActivity);\n\n      case SequencingRequestType.ABANDON_ALL:\n        return this.handleAbandonAll(currentActivity);\n\n      case SequencingRequestType.SUSPEND_ALL:\n        return this.handleSuspendAll(currentActivity);\n\n      default:\n        return {\n          terminationRequest: request,\n          sequencingRequest: null,\n          exception: \"TB.2.3-7\",\n          valid: false,\n        };\n    }\n  }\n\n  /**\n   * Handle EXIT termination with post-condition loop (TB.2.3 step 3)\n   * Implements the do-while loop for EXIT_PARENT cascading\n   * @param {Activity} currentActivity - The current activity\n   * @param {boolean} hasSequencingRequest - Whether a sequencing request follows\n   * @return {TerminationResult} - The termination result\n   */\n  /**\n   * Handle EXIT termination for an activity\n   * Made public for backward compatibility with tests\n   * @param {Activity} currentActivity - The activity being terminated\n   * @param {boolean} hasSequencingRequest - Whether a sequencing request follows\n   * @return {TerminationResult} - The termination result\n   */\n  public handleExitTermination(\n    currentActivity: Activity,\n    hasSequencingRequest: boolean,\n  ): TerminationResult {\n    return this.handleExit(currentActivity, hasSequencingRequest);\n  }\n\n  private handleExit(currentActivity: Activity, hasSequencingRequest: boolean): TerminationResult {\n    // TB.2.3 step 3.0: For cluster activities, terminate descendant attempts first\n    if (currentActivity.children.length > 0) {\n      this.terminateDescendants(currentActivity);\n    }\n\n    // TB.2.3 step 3.1: Apply End Attempt Process\n    this.endAttempt(currentActivity);\n\n    // TB.2.3 step 3.2: Apply Sequencing Exit Action Rules Subprocess\n    const exitActionResult = this.evaluateExitRules(currentActivity);\n    if (exitActionResult.action === \"EXIT_ALL\") {\n      // Exit action changed termination to EXIT_ALL\n      return this.handleExitAll(currentActivity);\n    } else if (exitActionResult.action === \"EXIT_PARENT\") {\n      // Exit action requests exit from parent\n      if (currentActivity.parent) {\n        // Move to parent and end its attempt\n        this.activityTree.currentActivity = currentActivity.parent;\n        this.endAttempt(this.activityTree.currentActivity);\n      }\n      // Continue to post-condition evaluation on the new current activity (parent or original)\n    }\n\n    // TB.2.1: Evaluate ancestor exit action rules from the root down to the\n    // parent of the terminating activity. A firing ancestor \"exit\" rule exits\n    // that cluster before TB.2.2 post-condition processing chooses the next\n    // sequencing request.\n    const ancestorExitResult = this.applyAncestorExitActionRules(currentActivity);\n    if (ancestorExitResult.action === \"EXIT_ALL\") {\n      return this.handleExitAll(ancestorExitResult.activity || currentActivity);\n    }\n    if (ancestorExitResult.exception) {\n      return {\n        terminationRequest: SequencingRequestType.EXIT,\n        sequencingRequest: null,\n        exception: ancestorExitResult.exception,\n        valid: false,\n      };\n    }\n\n    // TB.2.3 step 3.3: POST-CONDITION LOOP\n    let processedExit: boolean;\n    let postConditionResult: PostConditionResult;\n\n    do {\n      // TB.2.3 step 3.3.1: Set processedExit to false\n      processedExit = false;\n\n      // TB.2.3 step 3.3.2: Apply Sequencing Post Condition Rules Subprocess\n      postConditionResult = this.evaluatePostConditions(\n        this.activityTree.currentActivity || currentActivity,\n      );\n\n      // TB.2.3 step 3.3.3: If returns EXIT_ALL, change termination type and break\n      if (postConditionResult.terminationRequest === SequencingRequestType.EXIT_ALL) {\n        this.fireEvent(\"onPostConditionExitAll\", {\n          activity: (this.activityTree.currentActivity || currentActivity).id,\n        });\n        const exitAllResult = this.handleExitAll(this.activityTree.root!);\n\n        // @spec SCORM 2004 4th Ed. SN TB.2.2/TB.2.3: retryAll is\n        // represented by a Retry sequencing request paired with Exit All.\n        // Preserve that compound request after Exit All clears the current\n        // activity so sequencing restarts from the root instead of applying\n        // the current-activity-only Retry process.\n        if (postConditionResult.sequencingRequest === SequencingRequestType.RETRY) {\n          return {\n            ...exitAllResult,\n            sequencingRequest: SequencingRequestType.RETRY_ALL,\n          };\n        }\n\n        return exitAllResult;\n      }\n\n      // TB.2.3 step 3.3.4: If returns EXIT_PARENT, move up and continue loop\n      if (postConditionResult.terminationRequest === SequencingRequestType.EXIT_PARENT) {\n        const current = this.activityTree.currentActivity || currentActivity;\n\n        if (!current.parent) {\n          // TB.2.3-4: Cannot EXIT_PARENT from root\n          return {\n            terminationRequest: SequencingRequestType.EXIT_PARENT,\n            sequencingRequest: null,\n            exception: \"TB.2.3-4\",\n            valid: false,\n          };\n        } else {\n          // TB.2.3 step 3.3.4.1: Move to parent\n          this.activityTree.currentActivity = current.parent;\n\n          // TB.2.3 step 3.3.4.1.2: Apply End Attempt Process to parent\n          this.endAttempt(this.activityTree.currentActivity);\n\n          // TB.2.3 step 3.3.4.1.3: Set processedExit = true to continue loop\n          processedExit = true;\n\n          this.fireEvent(\"onPostConditionExitParent\", {\n            fromActivity: current.id,\n            toActivity: this.activityTree.currentActivity.id,\n          });\n        }\n      }\n\n      // TB.2.3 step 3.3.5: Check if at root without retry\n      // Only check atRoot when NOT in middle of EXIT_PARENT cascade (processedExit = false)\n      // If processedExit is true, we need to continue loop to evaluate the new activity's post-conditions\n      if (!processedExit) {\n        const atRoot =\n          (this.activityTree.currentActivity || currentActivity) === this.activityTree.root;\n        if (atRoot && postConditionResult.sequencingRequest !== SequencingRequestType.RETRY) {\n          // Return EXIT sequencing request (ends session)\n          return {\n            terminationRequest: SequencingRequestType.EXIT,\n            sequencingRequest: SequencingRequestType.EXIT,\n            exception: null,\n            valid: true,\n          };\n        }\n      }\n    } while (processedExit);\n\n    // TB.2.3 step 3.6: Return sequencing request from post-condition.\n    // Current Activity is only changed by explicit termination actions above.\n\n    return {\n      terminationRequest: SequencingRequestType.EXIT,\n      sequencingRequest: postConditionResult.sequencingRequest,\n      exception: null,\n      valid: true,\n    };\n  }\n\n  /**\n   * Handle EXIT_ALL termination (TB.2.3 step 4)\n   * @param {Activity} _currentActivity - The current activity (unused but kept for consistency)\n   * @return {TerminationResult} - The termination result\n   */\n  private handleExitAll(_currentActivity: Activity): TerminationResult {\n    // TB.2.3 step 4.1: Terminate descendant attempts from root\n    if (this.activityTree.root) {\n      this.handleMultiLevelExit(this.activityTree.root);\n    }\n\n    // TB.2.3 step 4.2: End attempt on root\n    if (this.activityTree.root) {\n      this.endAttempt(this.activityTree.root);\n    }\n\n    // TB.2.3 step 4.3: Clear current activity\n    this.activityTree.currentActivity = null;\n\n    // Clean up suspended activities\n    this.cleanupSuspendedActivity();\n\n    // TB.2.3 step 4.4: Return EXIT sequencing request (ends session)\n    return {\n      terminationRequest: SequencingRequestType.EXIT_ALL,\n      sequencingRequest: SequencingRequestType.EXIT,\n      exception: null,\n      valid: true,\n    };\n  }\n\n  /**\n   * Handle ABANDON termination (TB.2.3 step 6)\n   * @param {Activity} currentActivity - The current activity\n   * @return {TerminationResult} - The termination result\n   */\n  private handleAbandon(currentActivity: Activity): TerminationResult {\n    // TB.2.3 step 6.1: Set activity as not active (no attempt end)\n    currentActivity.isActive = false;\n\n    return {\n      terminationRequest: SequencingRequestType.ABANDON,\n      sequencingRequest: null,\n      exception: null,\n      valid: true,\n    };\n  }\n\n  /**\n   * Handle ABANDON_ALL termination (TB.2.3 step 7)\n   * @param {Activity} currentActivity - The current activity\n   * @return {TerminationResult} - The termination result\n   */\n  private handleAbandonAll(currentActivity: Activity): TerminationResult {\n    // TB.2.3 step 7.1: Form the activity path from current to root\n    const activityPath: Activity[] = [];\n    let current: Activity | null = currentActivity;\n    while (current !== null) {\n      activityPath.push(current);\n      current = current.parent;\n    }\n\n    // TB.2.3 step 7.2: If the activity path is empty\n    if (activityPath.length === 0) {\n      return {\n        terminationRequest: SequencingRequestType.ABANDON_ALL,\n        sequencingRequest: null,\n        exception: \"TB.2.3-6\",\n        valid: false,\n      };\n    }\n\n    // TB.2.3 step 7.3: For each activity in the activity path, set not active\n    for (const activity of activityPath) {\n      activity.isActive = false;\n    }\n\n    // TB.2.3 step 7.4: Clear current activity\n    this.activityTree.currentActivity = null;\n\n    // Clean up suspended activities\n    this.cleanupSuspendedActivity();\n\n    return {\n      terminationRequest: SequencingRequestType.ABANDON_ALL,\n      sequencingRequest: null,\n      exception: null,\n      valid: true,\n    };\n  }\n\n  /**\n   * Handle SUSPEND_ALL termination (TB.2.3 step 5)\n   * Implements TB.2.3 steps 5.1-5.7 for SUSPEND_ALL processing\n   * @param {Activity} currentActivity - The current activity\n   * @return {TerminationResult} - The termination result\n   */\n  private handleSuspendAll(currentActivity: Activity): TerminationResult {\n    // TB.2.3 steps 5.1-5.6: Suspend current activity and all ancestors, set current to root\n    const suspendResult = this.processSuspendAllRequest(currentActivity);\n\n    // Check if suspend failed\n    if (!suspendResult.valid) {\n      return suspendResult;\n    }\n\n    // TB.2.3 5.7: Return EXIT sequencing request to end session\n    // Note: Per SCORM spec, after SUSPEND_ALL returns EXIT, the session ends.\n    // The content unloads and currentActivity is cleared during termination.\n    // When RESUME_ALL is called in the next session, currentActivity will be null.\n\n    return {\n      terminationRequest: SequencingRequestType.SUSPEND_ALL,\n      sequencingRequest: SequencingRequestType.EXIT,\n      exception: null,\n      valid: true,\n    };\n  }\n\n  /**\n   * Handle Suspend All Request\n   * Implements TB.2.3 steps 5.1-5.6 from SCORM 2004 reference\n   * Suspends all activities in the path from current activity to root\n   * @spec SN Book: TB.2.3 (Termination Request Process) step 5.1\n   * @param {Activity} currentActivity - Current activity to suspend\n   * @return {TerminationResult} - Result with validation status\n   */\n  private processSuspendAllRequest(currentActivity: Activity): TerminationResult {\n    const rootActivity = this.activityTree.root;\n\n    // TB.2.3 5.1: Validation - Check if current activity is defined\n    if (!currentActivity || !rootActivity) {\n      this.fireEvent(\"onSuspendError\", {\n        exception: \"TB.2.3-1\",\n        message: \"No current activity to suspend\",\n        activity: currentActivity?.id,\n      });\n      return {\n        terminationRequest: SequencingRequestType.SUSPEND_ALL,\n        sequencingRequest: null,\n        exception: \"TB.2.3-1\",\n        valid: false,\n      };\n    }\n\n    // TB.2.3-3: Check if trying to suspend inactive/unsuspended root activity\n    if (\n      currentActivity === rootActivity &&\n      !currentActivity.isActive &&\n      !currentActivity.isSuspended\n    ) {\n      this.fireEvent(\"onSuspendError\", {\n        exception: \"TB.2.3-3\",\n        message: \"Nothing to suspend (root activity)\",\n        activity: currentActivity.id,\n      });\n      return {\n        terminationRequest: SequencingRequestType.SUSPEND_ALL,\n        sequencingRequest: null,\n        exception: \"TB.2.3-3\",\n        valid: false,\n      };\n    }\n\n    // @spec SN Book: TB.2.3 (Termination Request Process) step 5.1.1\n    // @spec SCORM 2004 SN 4th Ed. UP.4 End Attempt Process\n    // Transfer the active SCO's reported data without UP.4's attempt-ending defaults.\n    // Assets and early closes have no initialized RTE data to transfer.\n    if (currentActivity.isActive && currentActivity.children.length === 0 && this.getCMIData?.()) {\n      this._rteDataTransferService.transferRteData(currentActivity);\n\n      // @spec SCORM 2004 SN 4th Ed. SM.7 Objective Map write timing\n      // Publish the terminating SCO's objective values before ancestor rollup reads them.\n      this.rollupProcess.syncTerminatedActivityObjectives(currentActivity, this.globalObjectiveMap);\n    }\n\n    // @spec SN Book: TB.2.3 (Termination Request Process) step 5.1.1\n    // Roll up before recording suspension, without ending the resumable attempt.\n    if (currentActivity.isActive || currentActivity.isSuspended) {\n      this.rollupProcess.overallRollupProcess(currentActivity, this.globalObjectiveMap);\n    }\n\n    // TB.2.3 5.1-5.2: Set the suspended activity reference\n    this.activityTree.suspendedActivity = currentActivity;\n\n    // TB.2.3 5.3: Form activity path from current activity to root (inclusive)\n    // We walk up the tree from current to root\n    const suspendedActivity = currentActivity;\n    const activityPath: Activity[] = [];\n    let current: Activity | null = suspendedActivity;\n    while (current !== null) {\n      activityPath.push(current);\n      current = current.parent;\n    }\n\n    // TB.2.3 5.4: Check if path is empty\n    if (activityPath.length === 0) {\n      this.fireEvent(\"onSuspendError\", {\n        exception: \"TB.2.3-5\",\n        message: \"Activity path is empty\",\n        activity: suspendedActivity?.id,\n      });\n      return {\n        terminationRequest: SequencingRequestType.SUSPEND_ALL,\n        sequencingRequest: null,\n        exception: \"TB.2.3-5\",\n        valid: false,\n      };\n    }\n\n    // TB.2.3 5.5: For each activity in the path, suspend it\n    // 5.5.1: Set Activity is Active = false\n    // 5.5.2: Set Activity is Suspended = true\n    for (const activity of activityPath) {\n      activity.isActive = false;\n      activity.isSuspended = true;\n    }\n\n    // TB.2.3 5.6: Set current activity to root of activity tree\n    // Note: The ActivityTree setter automatically sets isActive = true,\n    // but we need root to remain suspended, so we override it\n    this.activityTree.currentActivity = rootActivity;\n    rootActivity.isActive = false; // Keep root suspended\n\n    // Log suspend event with full path information\n    this.fireEvent(\"onActivitySuspended\", {\n      activity: suspendedActivity?.id,\n      suspendedPath: activityPath.map((a) => a.id),\n      pathLength: activityPath.length,\n      timestamp: new Date().toISOString(),\n    });\n\n    // Return success\n    return {\n      terminationRequest: SequencingRequestType.SUSPEND_ALL,\n      sequencingRequest: null,\n      exception: null,\n      valid: true,\n    };\n  }\n\n  /**\n   * Enhanced Exit Action Rules Subprocess with recursion detection\n   * @param {Activity} activity - Activity to evaluate\n   * @param {number} recursionDepth - Current recursion depth\n   * @return {{action: string | null, recursionDepth: number}} - Exit action result\n   */\n  public evaluateExitRules(\n    activity: Activity,\n    recursionDepth: number = 0,\n  ): { action: string | null; recursionDepth: number } {\n    // Increment recursion depth to detect infinite loops\n    recursionDepth++;\n\n    // Check if activity has exit action rules\n    const exitRules = activity.sequencingRules.exitConditionRules;\n\n    for (const rule of exitRules) {\n      if (\n        rule.evaluate(\n          activity,\n          this.sequencingProcess.now,\n          this.sequencingProcess.getAttemptElapsedSecondsHook,\n        )\n      ) {\n        // Return the action to take with recursion tracking\n        if (rule.action === RuleActionType.EXIT) {\n          return { action: \"EXIT\", recursionDepth };\n        } else if (rule.action === RuleActionType.EXIT_PARENT) {\n          return { action: \"EXIT_PARENT\", recursionDepth };\n        } else if (rule.action === RuleActionType.EXIT_ALL) {\n          return { action: \"EXIT_ALL\", recursionDepth };\n        }\n      }\n    }\n\n    return { action: null, recursionDepth };\n  }\n\n  /**\n   * Integrate Post-Condition Rules Subprocess\n   * @param {Activity} activity - Activity to evaluate post-conditions for\n   * @return {PostConditionResult} - Post-condition result with sequencing and termination requests\n   */\n  public evaluatePostConditions(activity: Activity): PostConditionResult {\n    // Evaluate post-condition rules using the sequencing process\n    const postResult = this.sequencingProcess.evaluatePostConditionRules(activity);\n\n    if (postResult.sequencingRequest || postResult.terminationRequest) {\n      // Log the post-condition action for tracking\n      this.fireEvent(\"onPostConditionEvaluated\", {\n        activity: activity.id,\n        sequencingRequest: postResult.sequencingRequest,\n        terminationRequest: postResult.terminationRequest,\n        timestamp: new Date().toISOString(),\n      });\n    }\n\n    return postResult;\n  }\n\n  /**\n   * Handle Multi-Level Exit Actions\n   * @param {Activity} rootActivity - Root activity to start from\n   */\n  private handleMultiLevelExit(rootActivity: Activity): void {\n    // Process exit actions at each level systematically\n    this.processExitAtLevel(rootActivity, 0);\n\n    // Then terminate all activities\n    this.terminateAll(rootActivity);\n  }\n\n  /**\n   * Sequencing Exit Action Rules Subprocess (TB.2.1) ancestor walk\n   * @spec SN Book: TB.2.1 (Sequencing Exit Action Rules Subprocess)\n   * @param {Activity} terminatingActivity - The activity whose attempt just ended\n   * @return {{action: string | null, activity?: Activity, exception?: string}}\n   */\n  private applyAncestorExitActionRules(terminatingActivity: Activity): {\n    action: string | null;\n    activity?: Activity;\n    exception?: string;\n  } {\n    const activityPath: Activity[] = [];\n    let current: Activity | null = terminatingActivity.parent;\n\n    while (current) {\n      activityPath.unshift(current);\n      current = current.parent;\n    }\n\n    for (const activity of activityPath) {\n      const exitAction = this.exitActionRulesSubprocess(activity);\n\n      if (exitAction === \"EXIT_ALL\") {\n        this.fireEvent(\"onAncestorExitAction\", {\n          activity: activity.id,\n          action: exitAction,\n        });\n        return { action: \"EXIT_ALL\", activity };\n      }\n\n      if (exitAction === \"EXIT_PARENT\") {\n        if (!activity.parent) {\n          return { action: \"EXIT_PARENT\", activity, exception: \"TB.2.3-4\" };\n        }\n\n        this.terminateDescendants(activity.parent);\n        this.activityTree.currentActivity = activity.parent;\n        this.endAttempt(activity.parent);\n        this.fireEvent(\"onAncestorExitAction\", {\n          activity: activity.id,\n          action: exitAction,\n          currentActivity: activity.parent.id,\n        });\n        return { action: \"EXIT_PARENT\", activity: activity.parent };\n      }\n\n      if (exitAction === \"EXIT\") {\n        this.terminateDescendants(activity);\n        this.activityTree.currentActivity = activity;\n        this.endAttempt(activity);\n        this.fireEvent(\"onAncestorExitAction\", {\n          activity: activity.id,\n          action: exitAction,\n        });\n        return { action: \"EXIT\", activity };\n      }\n    }\n\n    return { action: null };\n  }\n\n  /**\n   * Process exit actions at specific level\n   * @param {Activity} activity - Activity to process\n   * @param {number} level - Current level in hierarchy\n   */\n  private processExitAtLevel(activity: Activity, level: number): void {\n    // Process exit actions for this activity\n    const exitAction = this.evaluateExitRules(activity, 0);\n\n    if (exitAction.action) {\n      this.fireEvent(\"onMultiLevelExitAction\", {\n        activity: activity.id,\n        level,\n        action: exitAction.action,\n      });\n    }\n\n    // Recursively process children\n    for (const child of activity.children) {\n      this.processExitAtLevel(child, level + 1);\n    }\n  }\n\n  /**\n   * Perform Complex Suspended Activity Cleanup\n   */\n  public cleanupSuspendedActivity(): void {\n    const suspendedActivity = this.activityTree.suspendedActivity;\n\n    if (suspendedActivity) {\n      // Clear suspended state from the activity and all its ancestors\n      let current: Activity | null = suspendedActivity;\n      const cleanedActivities: string[] = [];\n\n      while (current) {\n        if (current.isSuspended) {\n          current.isSuspended = false;\n          cleanedActivities.push(current.id);\n        }\n        current = current.parent;\n      }\n\n      // Clear suspended activity reference\n      this.activityTree.suspendedActivity = null;\n\n      // Fire cleanup event\n      this.fireEvent(\"onSuspendedActivityCleanup\", {\n        cleanedActivities,\n        originalSuspendedActivity: suspendedActivity.id,\n      });\n    }\n  }\n\n  /**\n   * Terminate all activities in the tree\n   * @param {Activity} activity - The activity to start from (usually root)\n   */\n  private terminateAll(activity: Activity): void {\n    // Recursively terminate all children first\n    for (const child of activity.children) {\n      this.terminateAll(child);\n    }\n\n    // Then terminate this activity\n    if (activity.isActive) {\n      this.endAttempt(activity);\n    }\n  }\n\n  /**\n   * Terminate Descendent Attempts Process (UP.3)\n   * Recursively terminates all active descendant attempts\n   * @param {Activity} activity - The activity whose descendants to terminate\n   */\n  public terminateDescendants(activity: Activity): void {\n    // Process all children\n    for (const child of activity.children) {\n      // Recursively terminate descendants first\n      if (child.children.length > 0) {\n        this.terminateDescendants(child);\n      }\n\n      // Check exit rules for the child\n      const exitAction = this.exitActionRulesSubprocess(child);\n\n      // Terminate the child if it's active\n      if (child.isActive) {\n        // Apply exit action if any\n        if (exitAction === \"EXIT_ALL\") {\n          // Recursively terminate all descendants\n          this.terminateDescendants(child);\n        }\n\n        // End the attempt\n        this.endAttempt(child);\n      }\n    }\n  }\n\n  /**\n   * Exit Action Rules Subprocess (TB.2.1)\n   * Evaluates exit action rules for the current activity\n   * @param {Activity} activity - The activity to evaluate\n   * @return {string | null} - The exit action to take, or null if none\n   */\n  private exitActionRulesSubprocess(activity: Activity): string | null {\n    // Check if activity has exit action rules\n    const exitRules = activity.sequencingRules.exitConditionRules;\n\n    for (const rule of exitRules) {\n      if (\n        rule.evaluate(\n          activity,\n          this.sequencingProcess.now,\n          this.sequencingProcess.getAttemptElapsedSecondsHook,\n        )\n      ) {\n        // Return the action to take\n        if (rule.action === RuleActionType.EXIT) {\n          return \"EXIT\";\n        } else if (rule.action === RuleActionType.EXIT_PARENT) {\n          return \"EXIT_PARENT\";\n        } else if (rule.action === RuleActionType.EXIT_ALL) {\n          return \"EXIT_ALL\";\n        }\n      }\n    }\n\n    return null;\n  }\n\n  /**\n   * Clear Suspended Activity Subprocess (DB.2.1)\n   * Clears the suspended activity state\n   */\n  public clearSuspendedActivity(): void {\n    if (this.activityTree.suspendedActivity) {\n      // Clear suspended state from the activity and all its ancestors\n      let current: Activity | null = this.activityTree.suspendedActivity;\n      while (current) {\n        current.isSuspended = false;\n        current = current.parent;\n      }\n      this.activityTree.suspendedActivity = null;\n    }\n  }\n\n  /**\n   * End Attempt Process\n   * Ends an attempt on an activity\n   * @spec SN Book: UP.4 (Utility Process - End Attempt Process)\n   * @param {Activity} activity - The activity to end attempt on\n   */\n  public endAttempt(activity: Activity): void {\n    if (!activity.isActive) {\n      return;\n    }\n\n    // Only a delivered leaf has RTE data. Cluster attempts end from sequencing\n    // traversal and must retain their rolled-up tracking state instead of\n    // consuming the last child's CMI values.\n    // @spec SCORM 2004 SN 4th Ed. UP.4 End Attempt Process\n    const contentCommunicatedObjectiveStatus =\n      activity.children.length === 0 && this.contentCommunicatedObjectiveStatus(activity);\n\n    if (activity.children.length === 0) {\n      this._rteDataTransferService.transferRteData(activity);\n    }\n\n    // Set activity as inactive\n    activity.isActive = false;\n    activity.activityAttemptActive = false;\n\n    // [UP.4]1. If the activity is a leaf Then\n    if (activity.children.length === 0) {\n      // [UP.4]1.1. If Tracked for the activity is True Then\n      // Note: In SCORM 2004, all leaf activities are tracked by default\n      const isTracked = true;\n\n      if (isTracked) {\n        // [UP.4]1.1.1. If the Activity is Suspended for the activity is False Then\n        // (The sequencer will not affect the state of suspended activities)\n        if (!activity.isSuspended) {\n          // [UP.4]1.1.1.1. Auto-Completion Logic\n          if (!activity.sequencingControls.completionSetByContent) {\n            // [UP.4]1.1.1.1.1. If the Attempt Progress Status for the activity is False Then\n            // (Did the content inform the sequencer of the activity's completion status?)\n            if (!activity.attemptProgressStatus) {\n              // [UP.4]1.1.1.1.1.1. Set the Attempt Progress Status for the activity to True\n              activity.attemptProgressStatus = true;\n\n              // [UP.4]1.1.1.1.1.2. Set the Attempt Completion Status for the activity to True\n              activity.completionStatus = \"completed\";\n\n              // Track that this was automatic\n              activity.wasAutoCompleted = true;\n\n              this.fireEvent(\"onAutoCompletion\", {\n                activityId: activity.id,\n                timestamp: new Date().toISOString(),\n              });\n            }\n          }\n\n          // [UP.4]1.1.1.2. Auto-Satisfaction Logic\n          if (!activity.sequencingControls.objectiveSetByContent) {\n            // [UP.4]1.1.1.2.1. Get the primary objective\n            const primaryObjective = activity.primaryObjective;\n            const objectiveProgressStatus = primaryObjective\n              ? primaryObjective.progressStatus\n              : activity.objectiveSatisfiedStatusKnown;\n\n            // [UP.4]1.1.1.2.1.1.1. If the Objective Progress Status for the objective is False Then\n            // (Did the content inform the sequencer of the activity's rolled-up objective status?)\n            // An explicit unknown is still communicated information. The LMS\n            // only supplies the automatic satisfied default for a SCO that did\n            // not communicate primary-objective success at all.\n            // @spec SCORM 2004 4th Ed. SN 3.13.3 / RTE 4.2.17\n            if (!objectiveProgressStatus && !contentCommunicatedObjectiveStatus) {\n              if (primaryObjective) {\n                // [UP.4]1.1.1.2.1.1.1.1. Set the Objective Progress Status for the objective to True\n                primaryObjective.progressStatus = true;\n\n                // [UP.4]1.1.1.2.1.1.1.2. Set the Objective Satisfied Status for the objective to True\n                primaryObjective.satisfiedStatus = true;\n              }\n\n              // @spec SCORM 2004 4th Ed. SN UP.4: attempt objective state exists\n              // even when the activity has no explicitly declared primaryObjective.\n              activity.objectiveSatisfiedStatus = true;\n              activity.successStatus = \"passed\";\n\n              // Track that this was automatic\n              activity.wasAutoSatisfied = true;\n\n              this.fireEvent(\"onAutoSatisfaction\", {\n                activityId: activity.id,\n                timestamp: new Date().toISOString(),\n              });\n            }\n          }\n        }\n      }\n    } else {\n      // [UP.4]2. Else (The activity has children)\n      // [UP.4]2.1. Update suspended status based on children\n      const hasSuspendedChildren = activity.children.some((child) => child.isSuspended);\n      activity.isSuspended = hasSuspendedChildren;\n    }\n\n    // Handle unknown statuses for activities that weren't auto-completed/satisfied\n    // Update attempt completion status if not already set\n    if (activity.completionStatus === \"unknown\") {\n      activity.completionStatus = \"incomplete\";\n    }\n\n    // Update success status if needed\n    if (activity.successStatus === \"unknown\" && activity.objectiveSatisfiedStatus) {\n      activity.successStatus = activity.objectiveSatisfiedStatus ? \"passed\" : \"failed\";\n    }\n\n    // @spec SCORM 2004 SN 4th Ed. RB.1.2.a / UP.4 / SM.7\n    // Decide the inactive cluster before its write map transfers the result.\n    // No read phase here: an inactive read/write map would restore the previous global value.\n    if (activity.children.length > 0) {\n      this.rollupProcess.rollupActivity(activity);\n    }\n\n    // A write map transfers the terminating attempt's final status, including\n    // unknown status, before other activities read the shared objective.\n    const writeTargets = this.rollupProcess.syncTerminatedActivityObjectives(\n      activity,\n      this.globalObjectiveMap,\n    );\n\n    // A terminating descendant's map writes are visible to active ancestors before their\n    // post-condition rules run. Limit the read to the fields written above so an active writer\n    // cannot revive unrelated state from its previous attempt.\n    // @spec SCORM 2004 SN 4th Ed. SM.7 Objective Map write timing\n    let activeAncestor = activity.parent;\n    while (activeAncestor) {\n      if (activeAncestor.isActive) {\n        this.rollupProcess.syncFreshlyWrittenObjectivesToActiveAncestor(\n          activeAncestor,\n          this.globalObjectiveMap,\n          writeTargets,\n        );\n      }\n      activeAncestor = activeAncestor.parent;\n    }\n\n    // Sync global objectives then trigger rollup\n    // This reads FROM global objectives INTO activities before rollup,\n    // so rollup can use global objective state when calculating activity status\n    const mappingRoot = this.activityTree.root || activity;\n    this.rollupProcess.processGlobalObjectiveMapping(mappingRoot, this.globalObjectiveMap);\n\n    // Trigger rollup after global objective sync\n    // Rollup calculates satisfaction and completion based on children and global state\n    // Roll up a cluster itself now that its attempt is inactive (RB.1.5, UP.4).\n    this.rollupProcess.overallRollupProcess(\n      activity,\n      this.globalObjectiveMap,\n      activity.children.length > 0,\n    );\n\n    // Rollup can recalculate an active cluster's primary objective from its\n    // children. Reapply only the fields written by this terminating descendant\n    // so the cluster's mapped primary reflects the fresh global value when its\n    // exit and post-condition rules run.\n    // @spec SCORM 2004 4th Ed. TR OB-16c / SN SM.7 Objective Map write timing\n    activeAncestor = activity.parent;\n    while (activeAncestor) {\n      if (activeAncestor.isActive) {\n        const mappedStateChanged = this.rollupProcess.syncFreshlyWrittenObjectivesToActiveAncestor(\n          activeAncestor,\n          this.globalObjectiveMap,\n          writeTargets,\n        );\n        if (mappedStateChanged) {\n          // The ancestor's read-mapped primary is authoritative over its descendant aggregate.\n          // Propagate that restored state through its parents after the descendant rollup above.\n          // @spec SCORM 2004 4th Ed. SN SM.7 and RB.1.5\n          this.rollupProcess.overallRollupProcess(activeAncestor, this.globalObjectiveMap);\n        }\n      }\n      activeAncestor = activeAncestor.parent;\n    }\n\n    // Do not run another tree-wide sync here: unrelated global values may be\n    // stale. Only the fresh write targets above are authoritative after rollup.\n\n    // Invalidate navigation predictions after rollup\n    if (this.invalidateCacheCallback) {\n      this.invalidateCacheCallback();\n    }\n\n    // INTEGRATION: Validate rollup state consistency after rollup\n    if (this.activityTree.root) {\n      this.rollupProcess.validateRollupStateConsistency(this.activityTree.root);\n    }\n\n    // Apply selection and randomization per SCORM 2004 3rd Edition UP.4\n    // (Randomization at specification-required process points)\n    // This occurs after rollup processing completes\n    SelectionRandomization.applySelectionAndRandomization(activity, false);\n  }\n\n  /**\n   * Return whether the delivered SCO wrote success information for its rolled-up objective.\n   */\n  private contentCommunicatedObjectiveStatus(activity: Activity): boolean {\n    const cmiData = this.getCMIData?.();\n    if (!cmiData) {\n      return false;\n    }\n\n    if (cmiData.success_status_was_set === true) {\n      return true;\n    }\n\n    const primaryObjectiveId = activity.primaryObjective?.id;\n    return Boolean(\n      primaryObjectiveId &&\n      cmiData.objectives?.some(\n        (objective) =>\n          objective.id === primaryObjectiveId && objective.success_status_was_set === true,\n      ),\n    );\n  }\n\n  /**\n   * Fire a sequencing event\n   * @param {string} eventType - The type of event\n   * @param {any} data - Event data\n   */\n  private fireEvent(eventType: string, data?: any): void {\n    try {\n      if (this.eventCallback) {\n        this.eventCallback(eventType, data);\n      }\n    } catch (error) {\n      console.warn(`Failed to fire sequencing event ${eventType}: ${error}`);\n    }\n  }\n}\n","import { Activity } from \"../activity\";\nimport { advanceDeliveryGeneration } from \"../delivery_generation\";\nimport { ActivityTreeQueries } from \"../utils/activity_tree_queries\";\nimport { ActivityTree } from \"../activity_tree\";\nimport { RollupProcess } from \"../rollup_process\";\nimport { SelectionRandomization } from \"../selection_randomization\";\nimport { ADLNav } from \"../../adl\";\nimport {\n  AuxiliaryResource,\n  HideLmsUiItem,\n  HIDE_LMS_UI_TOKENS,\n} from \"../../../../types/sequencing_types\";\n\n/**\n * Represents a delivery request result\n */\nexport class DeliveryRequest {\n  public valid: boolean;\n  public targetActivity: Activity | null;\n  public exception: string | null;\n\n  constructor(\n    valid: boolean = false,\n    targetActivity: Activity | null = null,\n    exception: string | null = null,\n  ) {\n    this.valid = valid;\n    this.targetActivity = targetActivity;\n    this.exception = exception;\n  }\n}\n\n/**\n * Content activity data for delivery\n */\nexport interface ContentActivityData {\n  hideLmsUi: HideLmsUiItem[];\n  auxiliaryResources: AuxiliaryResource[];\n  location: string;\n  credit: string;\n  launchData: string;\n  maxTimeAllowed: string;\n  completionThreshold: string;\n  timeLimitAction: string;\n}\n\n/**\n * Options for configuring the DeliveryHandler\n */\nexport interface DeliveryHandlerOptions {\n  now?: () => Date;\n  defaultHideLmsUi?: HideLmsUiItem[];\n  defaultAuxiliaryResources?: AuxiliaryResource[];\n}\n\n/**\n * DeliveryHandler\n *\n * Handles all delivery-related processing for the SCORM 2004 sequencing engine.\n * Extracted from OverallSequencingProcess to follow Single Responsibility Principle.\n *\n * Responsibilities:\n * - Process delivery requests (validate activity for delivery)\n * - Content delivery environment process (initialize activity for delivery)\n * - Get content activity data (hideLmsUi, auxiliary resources, etc.)\n * - Manage activity path processing\n *\n * @spec SN Book: DB.1.1 (Delivery Request Process)\n * @spec SN Book: DB.2 (Content Delivery Environment Process)\n */\nexport class DeliveryHandler {\n  private static readonly HIDE_LMS_UI_ORDER: HideLmsUiItem[] = [...HIDE_LMS_UI_TOKENS];\n  private activityTree: ActivityTree;\n  private rollupProcess: RollupProcess;\n  private globalObjectiveMap: Map<string, any>;\n  private adlNav: ADLNav | null;\n  private eventCallback: ((eventType: string, data?: any) => void) | null;\n  private now: () => Date;\n  private defaultHideLmsUi: HideLmsUiItem[];\n  private defaultAuxiliaryResources: AuxiliaryResource[];\n  private _deliveryInProgress: boolean = false;\n  private contentDelivered: boolean = false;\n  private endAttemptCallback: ((activity: Activity) => void) | null = null;\n  private checkActivityCallback: ((activity: Activity, target: Activity) => boolean) | null = null;\n  private invalidateCacheCallback: (() => void) | null = null;\n  private updateNavigationValidityCallback: (() => void) | null = null;\n  private clearSuspendedActivityCallback: (() => void) | null = null;\n\n  constructor(\n    activityTree: ActivityTree,\n    rollupProcess: RollupProcess,\n    globalObjectiveMap: Map<string, any>,\n    adlNav: ADLNav | null = null,\n    eventCallback: ((eventType: string, data?: any) => void) | null = null,\n    options?: DeliveryHandlerOptions,\n  ) {\n    this.activityTree = activityTree;\n    this.rollupProcess = rollupProcess;\n    this.globalObjectiveMap = globalObjectiveMap;\n    this.adlNav = adlNav;\n    this.eventCallback = eventCallback;\n    this.now = options?.now || (() => new Date());\n    this.defaultHideLmsUi = options?.defaultHideLmsUi ? [...options.defaultHideLmsUi] : [];\n    this.defaultAuxiliaryResources = options?.defaultAuxiliaryResources\n      ? options.defaultAuxiliaryResources.map((resource) => ({ ...resource }))\n      : [];\n  }\n\n  /** @spec SCORM 2004 SN 4th Ed. DB.2 / UP.4 - commit departed attempts through the coordinator. */\n  public setEndAttemptCallback(callback: (activity: Activity) => void): void {\n    this.endAttemptCallback = callback;\n  }\n\n  /**\n   * End active attempts on the path from current to common ancestor, exclusive.\n   * @spec SCORM 2004 SN 4th Ed. UP.3 - end the old path bottom-up, excluding the common ancestor.\n   * @param {Activity} currentActivity - The already-terminated current activity\n   * @param {Activity} commonAncestor - The ancestor whose attempt remains active\n   */\n  private terminateDescendentAttemptsProcess(\n    currentActivity: Activity,\n    commonAncestor: Activity | null,\n  ): void {\n    if (currentActivity === commonAncestor) {\n      return;\n    }\n\n    let activity = currentActivity.parent;\n    while (activity && activity !== commonAncestor) {\n      const parent = activity.parent;\n      if (activity.isActive) {\n        if (this.endAttemptCallback) {\n          this.endAttemptCallback(activity);\n        } else {\n          activity.isActive = false;\n        }\n      }\n      activity = parent;\n    }\n  }\n\n  /**\n   * Set callback to check activity validity\n   */\n  public setCheckActivityCallback(\n    callback: (activity: Activity, target: Activity) => boolean,\n  ): void {\n    this.checkActivityCallback = callback;\n  }\n\n  /**\n   * Set callback to invalidate navigation cache after state changes\n   */\n  public setInvalidateCacheCallback(callback: () => void): void {\n    this.invalidateCacheCallback = callback;\n  }\n\n  /**\n   * Set callback to update navigation validity\n   */\n  public setUpdateNavigationValidityCallback(callback: () => void): void {\n    this.updateNavigationValidityCallback = callback;\n  }\n\n  /**\n   * Set callback to clear suspended activity\n   */\n  public setClearSuspendedActivityCallback(callback: () => void): void {\n    this.clearSuspendedActivityCallback = callback;\n  }\n\n  /**\n   * Check if content delivery is currently in progress\n   * Used to prevent re-entrant termination requests during delivery\n   */\n  public isDeliveryInProgress(): boolean {\n    return this._deliveryInProgress;\n  }\n\n  /**\n   * Check if content has been delivered\n   */\n  public hasContentBeenDelivered(): boolean {\n    return this.contentDelivered;\n  }\n\n  /**\n   * Reset content delivered flag\n   */\n  public resetContentDelivered(): void {\n    this.contentDelivered = false;\n  }\n\n  /**\n   * Set content delivered flag\n   * @param {boolean} value - The value to set\n   */\n  public setContentDelivered(value: boolean): void {\n    this.contentDelivered = value;\n  }\n\n  /**\n   * Delivery Request Process\n   * Validates if an activity can be delivered\n   * @spec SN Book: DB.1.1 (Delivery Request Process)\n   * @param {Activity} activity - The activity to deliver\n   * @return {DeliveryRequest} - The delivery validation result\n   */\n  public processDeliveryRequest(activity: Activity): DeliveryRequest {\n    // Enhanced logging for debugging\n    this.fireEvent(\"onDeliveryRequestProcessing\", {\n      activity: activity.id,\n      timestamp: new Date().toISOString(),\n    });\n\n    // Check if activity is a cluster (has children)\n    // Note: Only activities with children are considered clusters. The 'flow' control\n    // is only relevant for controlling navigation through a parent's children and does\n    // not affect whether a leaf activity can be delivered.\n    if (activity.children.length > 0) {\n      return new DeliveryRequest(false, null, \"DB.1.1-1\");\n    }\n\n    // DB.1.1 Step 2: Form the activity path from root to target, inclusive\n    const activityPath = this.getActivityPath(activity, true);\n\n    // DB.1.1 Step 3: Check if path is empty (shouldn't happen with valid tree but per spec)\n    if (activityPath.length === 0) {\n      return new DeliveryRequest(false, null, \"DB.1.1-2\");\n    }\n\n    // DB.1.1 Step 4: For each activity in the path, apply Check Activity Process (UP.5)\n    // This ensures no ancestor violates limit conditions, preconditions, or is disabled\n    for (const pathActivity of activityPath) {\n      // Check Activity Process returns true if activity is VALID\n      const checkResult = this.checkActivityCallback\n        ? this.checkActivityCallback(pathActivity, activity)\n        : true;\n      if (!checkResult) {\n        // Activity check failed - cannot deliver\n        return new DeliveryRequest(false, null, \"DB.1.1-3\");\n      }\n    }\n\n    // Activity is a true leaf and passes all checks - can be delivered\n    return new DeliveryRequest(true, activity);\n  }\n\n  /**\n   * Content Delivery Environment Process\n   * Handles the delivery of content to the learner\n   * @spec SN Book: DB.2 (Content Delivery Environment Process)\n   * @param {Activity} activity - The activity to deliver\n   */\n  public contentDeliveryEnvironmentProcess(activity: Activity): void {\n    // Mark that delivery is in progress to prevent re-entrant termination requests\n    // This handles the case where the old content's unload handler fires during delivery\n    // and calls Terminate, which would otherwise re-terminate the newly delivered activity\n    this._deliveryInProgress = true;\n\n    try {\n      // @spec SCORM 2004 SN 4th Ed. DB.2 / UP.3 - end the departed branch only after DB.1.1 succeeds.\n      const currentActivity = this.activityTree.currentActivity;\n      if (currentActivity) {\n        const commonAncestor = new ActivityTreeQueries(this.activityTree).findCommonAncestor(\n          currentActivity,\n          activity,\n        );\n        this.terminateDescendentAttemptsProcess(currentActivity, commonAncestor);\n      }\n      this.rollupProcess?.processGlobalObjectiveMapping(activity, this.globalObjectiveMap);\n\n      // Step 1: Check if we're resuming before clearing suspended state\n      // Capture suspended state of delivered activity BEFORE clearSuspendedActivitySubprocess\n      const isResuming = activity.isSuspended;\n      const activityPath = this.getActivityPath(activity, true);\n      const suspendedPathActivities = new Set(\n        activityPath.filter((pathActivity) => pathActivity.isSuspended),\n      );\n      // @spec SCORM 2004 4th Ed. RTE 4.2.8 and SN DB.2: integrations must know\n      // whether to restore the delivered SCO's suspended local RTE data after DB.2.1\n      // clears the sequencing suspension flag.\n      activity.deliveryWasResumed = isResuming;\n\n      // Step 2: Clear Suspended Activity Subprocess (DB.2.1) if needed\n      // Clear suspended state whether we're resuming the suspended activity\n      // or delivering a different activity (abandoning the suspended session)\n      if (this.activityTree.suspendedActivity) {\n        if (this.clearSuspendedActivityCallback) {\n          this.clearSuspendedActivityCallback();\n        }\n      }\n\n      // Step 3: Process activity path and initialize tracking data (DB.2.2)\n      const newAttemptActivities: Activity[] = [];\n\n      // Process each activity in the path (root to leaf)\n      for (const pathActivity of activityPath) {\n        // Only process activities that are not already active\n        if (!pathActivity.isActive) {\n          const isPathActivityResuming = isResuming || suspendedPathActivities.has(pathActivity);\n          if (isPathActivityResuming) {\n            // Resuming: clear suspended flag but don't increment attempt\n            pathActivity.isSuspended = false;\n          } else {\n            // New attempt: increment the cumulative count, then initialize only\n            // the Objective and Attempt Progress Information scoped to this attempt.\n            pathActivity.incrementAttemptCount();\n            pathActivity.initializeTrackingForNewAttempt();\n            newAttemptActivities.push(pathActivity);\n            pathActivity.objectiveInfoAvailableInCurrentParentAttempt = true;\n            pathActivity.progressInfoAvailableInCurrentParentAttempt = true;\n\n            // The default useCurrentAttempt* controls make tracking from child attempts outside\n            // this new parent attempt unavailable to rollup. Preserve the child's tracking data:\n            // its own precondition rules still evaluate that data until the child starts again.\n            // @spec SCORM 2004 SN 4th Ed. SM.1 and TM.2\n            for (const child of pathActivity.children) {\n              if (pathActivity.sequencingControls.useCurrentAttemptObjectiveInfo) {\n                // A read map is evaluated from the shared global objective regardless of the\n                // child's prior local attempt. Keep known mapped objective information available\n                // to sequencing and rollup during the new parent attempt.\n                // @spec SCORM 2004 3rd Ed. Impact Summary 1.5-8\n                child.objectiveInfoAvailableInCurrentParentAttempt =\n                  this.hasKnownReadMappedObjective(child);\n              }\n              if (pathActivity.sequencingControls.useCurrentAttemptProgressInfo) {\n                child.progressInfoAvailableInCurrentParentAttempt = false;\n              }\n            }\n          }\n          pathActivity.isActive = true;\n\n          // Step 3.1: Apply selection and randomization per SCORM 2004 3rd Edition DB.2\n          // (Randomization at specification-required process points)\n          // This occurs after activity.isActive is set and attempt count is incremented\n          SelectionRandomization.applySelectionAndRandomization(\n            pathActivity,\n            !isPathActivityResuming,\n          );\n        }\n      }\n\n      // The global-objective read phase runs before delivery so prerequisites can be checked.\n      // New-attempt initialization above intentionally clears attempt-scoped local objectives,\n      // so restore each newly active activity's read maps before navigation validity is computed.\n      // @spec SCORM 2004 SN 4th Ed. DB.2 and 3.10.3 Objective Map read timing\n      for (const pathActivity of newAttemptActivities) {\n        this.rollupProcess?.syncActivityObjectivesFromGlobals(\n          pathActivity,\n          this.globalObjectiveMap,\n        );\n      }\n\n      // Step 4: Set the activity as current\n      this.activityTree.currentActivity = activity;\n\n      // Step 5: Initialize attempt for the delivered activity\n      this.initializeForDelivery(activity);\n\n      // Step 6: Set up activity attempt tracking information\n      this.setupAttemptTracking(activity);\n\n      // @spec SCORM 2004 4th Ed. SN DB.2: every accepted delivery launches content,\n      // including resumed attempts (SCORM 2004 4th Ed. RTE 4.2.7: entry=resume).\n      advanceDeliveryGeneration(activity);\n\n      // Step 7: Mark that content has been delivered\n      this.contentDelivered = true;\n\n      // Step 8: Update navigation validity if ADL nav is available\n      if (this.adlNav && this.updateNavigationValidityCallback) {\n        this.updateNavigationValidityCallback();\n      }\n\n      // Step 9: Fire activity delivery event\n      this.fireDeliveryEvent(activity);\n    } finally {\n      // Clear delivery in progress flag\n      this._deliveryInProgress = false;\n    }\n  }\n\n  private hasKnownReadMappedObjective(activity: Activity): boolean {\n    const primaryObjective = activity.primaryObjective;\n    if (!primaryObjective) {\n      return false;\n    }\n\n    return primaryObjective.mapInfo.some((mapInfo) => {\n      const targetId = mapInfo.targetObjectiveID || primaryObjective.id;\n      const globalObjective = this.globalObjectiveMap.get(targetId);\n\n      return (\n        (mapInfo.readSatisfiedStatus !== false && globalObjective?.satisfiedStatusKnown === true) ||\n        (mapInfo.readNormalizedMeasure !== false &&\n          globalObjective?.normalizedMeasureKnown === true)\n      );\n    });\n  }\n\n  /**\n   * Initialize Activity For Delivery (DB.2.2)\n   * Set up initial tracking states for a delivered activity\n   * @param {Activity} activity - The activity being delivered\n   */\n  private initializeForDelivery(activity: Activity): void {\n    // Set initial attempt states if not already set\n    if (activity.completionStatus === \"unknown\") {\n      // For leaf activities, set to \"not attempted\" initially\n      if (activity.children.length === 0) {\n        activity.completionStatus = \"not attempted\";\n      }\n    }\n\n    // Initialize objective satisfied status if not set\n    if (activity.objectiveSatisfiedStatus === null) {\n      activity.objectiveSatisfiedStatus = false;\n    }\n\n    // Initialize progress measure status\n    if (activity.progressMeasure === null) {\n      activity.progressMeasure = 0.0;\n      activity.progressMeasureStatus = false;\n    }\n\n    // Initialize objective measure if not set\n    if (activity.objectiveNormalizedMeasure === null) {\n      activity.objectiveNormalizedMeasure = 0.0;\n      activity.objectiveMeasureStatus = false;\n    }\n\n    // Set up activity attempt information\n    if (!activity.deliveryWasResumed) {\n      activity.attemptAbsoluteDuration = \"PT0H0M0S\";\n      activity.attemptExperiencedDuration = \"PT0H0M0S\";\n    }\n\n    // Mark as available for sequencing\n    activity.isAvailable = true;\n  }\n\n  /**\n   * Setup Activity Attempt Tracking\n   * Initialize attempt tracking information per SCORM 2004 4th Edition\n   * @param {Activity} activity - The activity being delivered\n   */\n  private setupAttemptTracking(activity: Activity): void {\n    // Note: Attempt count is now incremented in contentDeliveryEnvironmentProcess\n    // during activity path processing, so we don't increment it here\n\n    activity.wasSkipped = false;\n\n    // Set attempt start time (use injected clock). A resumed attempt keeps its start time.\n    if (!activity.deliveryWasResumed || !activity.attemptAbsoluteStartTime) {\n      activity.attemptAbsoluteStartTime = this.now().toISOString();\n    }\n\n    // Initialize location if not set\n    if (!activity.location) {\n      activity.location = \"\";\n    }\n\n    // Set up activity state\n    activity.activityAttemptActive = true;\n\n    // Initialize learner preferences if not set\n    if (!activity.learnerPrefs) {\n      activity.learnerPrefs = {\n        audioCaptioning: \"0\",\n        audioLevel: \"1\",\n        deliverySpeed: \"1\",\n        language: \"\",\n      };\n    }\n  }\n\n  /**\n   * Fire Activity Delivery Event\n   * Notify listeners that an activity has been delivered\n   * @param {Activity} activity - The activity that was delivered\n   */\n  private fireDeliveryEvent(activity: Activity): void {\n    // Fire event through callback if available\n    try {\n      if (this.eventCallback) {\n        this.eventCallback(\"onActivityDelivery\", activity);\n      }\n      console.debug(`Activity delivered: ${activity.id} - ${activity.title}`);\n    } catch (error) {\n      // Silently handle event firing errors to not disrupt sequencing\n      console.warn(`Failed to fire activity delivery event: ${error}`);\n    }\n  }\n\n  /**\n   * Get effective hideLmsUi for an activity\n   * Merges default and activity-specific hideLmsUi directives\n   * @param {Activity | null} activity - The activity\n   * @return {HideLmsUiItem[]} - Ordered list of hideLmsUi directives\n   */\n  public getEffectiveHideLmsUi(activity: Activity | null): HideLmsUiItem[] {\n    const seen = new Set<HideLmsUiItem>();\n\n    for (const directive of this.defaultHideLmsUi) {\n      seen.add(directive);\n    }\n\n    let current: Activity | null = activity;\n    while (current) {\n      for (const directive of current.hideLmsUi) {\n        seen.add(directive);\n      }\n      current = current.parent;\n    }\n\n    return DeliveryHandler.HIDE_LMS_UI_ORDER.filter((directive) => seen.has(directive));\n  }\n\n  /**\n   * Get effective auxiliary resources for an activity\n   * Merges default and activity-specific resources\n   * @param {Activity | null} activity - The activity\n   * @return {AuxiliaryResource[]} - Merged auxiliary resources\n   */\n  public getEffectiveAuxiliaryResources(activity: Activity | null): AuxiliaryResource[] {\n    const merged = new Map<string, AuxiliaryResource>();\n\n    for (const resource of this.defaultAuxiliaryResources) {\n      if (resource.resourceId) {\n        merged.set(resource.resourceId, { ...resource });\n      }\n    }\n\n    const lineage: Activity[] = [];\n    let current: Activity | null = activity;\n    while (current) {\n      lineage.push(current);\n      current = current.parent;\n    }\n\n    for (const node of lineage.reverse()) {\n      for (const resource of node.auxiliaryResources) {\n        if (resource.resourceId) {\n          merged.set(resource.resourceId, { ...resource });\n        }\n      }\n    }\n\n    return Array.from(merged.values());\n  }\n\n  /**\n   * Get content activity data for a delivered activity\n   * @param {Activity} activity - The activity\n   * @return {ContentActivityData} - Content activity data\n   */\n  public getContentActivityData(activity: Activity): ContentActivityData {\n    return {\n      hideLmsUi: this.getEffectiveHideLmsUi(activity),\n      auxiliaryResources: this.getEffectiveAuxiliaryResources(activity),\n      location: activity.location || \"\",\n      credit: activity.credit || \"credit\",\n      launchData: activity.launchData || \"\",\n      maxTimeAllowed: activity.attemptAbsoluteDurationLimit || \"\",\n      completionThreshold: activity.completionThreshold?.toString() || \"\",\n      timeLimitAction: activity.timeLimitAction || \"continue,no message\",\n    };\n  }\n\n  /**\n   * Get Activity Path (Helper for DB.1.1)\n   * Forms the activity path from root to target activity, inclusive\n   * @param {Activity} activity - The target activity\n   * @param {boolean} includeActivity - Whether to include the target in the path\n   * @return {Activity[]} - Array of activities from root to target\n   */\n  public getActivityPath(activity: Activity, includeActivity: boolean = true): Activity[] {\n    const path: Activity[] = [];\n    let current: Activity | null = activity;\n\n    // Walk up from target to root\n    while (current !== null) {\n      path.unshift(current); // Add to beginning of array\n      current = current.parent;\n    }\n\n    // Remove target activity if not included\n    if (!includeActivity && path.length > 0) {\n      path.pop();\n    }\n\n    return path;\n  }\n\n  /**\n   * Fire a sequencing event\n   * @param {string} eventType - The type of event\n   * @param {any} data - Event data\n   */\n  private fireEvent(eventType: string, data?: any): void {\n    try {\n      if (this.eventCallback) {\n        this.eventCallback(eventType, data);\n      }\n    } catch (error) {\n      console.warn(`Failed to fire sequencing event ${eventType}: ${error}`);\n    }\n  }\n}\n","import { Activity } from \"./activity\";\nimport { ActivityTree } from \"./activity_tree\";\nimport { SequencingProcess, SequencingRequestType } from \"./sequencing_process\";\nimport { RuleActionType } from \"./sequencing_rules\";\n\n/**\n * Interface for navigation prediction cache entry\n */\ninterface NavigationPredictionCache {\n  continueEnabled: boolean;\n  previousEnabled: boolean;\n  availableChoices: Set<string>;\n  choiceEnabledMap: Map<string, boolean>;\n  treeStateHash: string;\n}\n\n/**\n * Interface for navigation predictions result\n */\nexport interface NavigationPredictions {\n  continueEnabled: boolean;\n  previousEnabled: boolean;\n  availableChoices: string[];\n}\n\n/**\n * NavigationLookAhead class\n * Provides look-ahead navigation prediction for SCORM 2004 sequencing.\n * This allows UI to show correct button states before user clicks.\n *\n * Performance target: <10ms for full tree prediction on 50+ activity course\n */\nexport class NavigationLookAhead {\n  private activityTree: ActivityTree;\n  private sequencingProcess: SequencingProcess;\n  private cache: NavigationPredictionCache | null = null;\n  private isDirty: boolean = true;\n\n  constructor(activityTree: ActivityTree, sequencingProcess: SequencingProcess) {\n    this.activityTree = activityTree;\n    this.sequencingProcess = sequencingProcess;\n  }\n\n  /**\n   * Predict if Continue navigation would succeed from current activity\n   * @return {boolean} - True if Continue would succeed, false otherwise\n   */\n  public predictContinueEnabled(): boolean {\n    this.ensureCacheValid();\n    return this.cache?.continueEnabled ?? false;\n  }\n\n  /**\n   * Predict if Previous navigation would succeed from current activity\n   * @return {boolean} - True if Previous would succeed, false otherwise\n   */\n  public predictPreviousEnabled(): boolean {\n    this.ensureCacheValid();\n    return this.cache?.previousEnabled ?? false;\n  }\n\n  /**\n   * Predict if choice to specific activity would succeed\n   * @param {string} activityId - Target activity ID\n   * @return {boolean} - True if choice would succeed, false otherwise\n   */\n  public predictChoiceEnabled(activityId: string): boolean {\n    this.ensureCacheValid();\n    return this.cache?.choiceEnabledMap.get(activityId) ?? false;\n  }\n\n  /** Predict jump validity on demand because limit conditions can change over time. */\n  public predictJumpEnabled(activityId: string): boolean {\n    return this.sequencingProcess.validateNavigationRequest(\n      SequencingRequestType.JUMP,\n      activityId,\n      this.activityTree.currentActivity,\n    ).valid;\n  }\n\n  /**\n   * Get list of all activity IDs that can be chosen\n   * @return {string[]} - Array of activity IDs that can be chosen\n   */\n  public getAvailableChoices(): string[] {\n    this.ensureCacheValid();\n    return Array.from(this.cache?.availableChoices ?? []);\n  }\n\n  /**\n   * Get all navigation predictions at once\n   * @return {NavigationPredictions} - Navigation predictions object\n   */\n  public getAllPredictions(): NavigationPredictions {\n    this.ensureCacheValid();\n    return {\n      continueEnabled: this.cache?.continueEnabled ?? false,\n      previousEnabled: this.cache?.previousEnabled ?? false,\n      availableChoices: Array.from(this.cache?.availableChoices ?? []),\n    };\n  }\n\n  /**\n   * Invalidate the cache to force recalculation on next access\n   * Should be called after:\n   * - Activity change\n   * - Rollup process\n   * - Objective changes\n   * - Attempt changes\n   */\n  public invalidateCache(): void {\n    this.isDirty = true;\n  }\n\n  /**\n   * Force immediate cache update (useful for testing)\n   */\n  public updateCache(): void {\n    this.isDirty = true;\n    this.ensureCacheValid();\n  }\n\n  /**\n   * Ensure cache is valid, recalculating if needed\n   * @private\n   */\n  private ensureCacheValid(): void {\n    const currentTreeHash = this.calculateTreeStateHash();\n\n    if (this.isDirty || !this.cache || this.cache.treeStateHash !== currentTreeHash) {\n      this.recalculateCache(currentTreeHash);\n      this.isDirty = false;\n    }\n  }\n\n  /**\n   * Recalculate all navigation predictions\n   * @param {string} treeStateHash - Current tree state hash\n   * @private\n   */\n  private recalculateCache(treeStateHash: string): void {\n    const currentActivity = this.activityTree.currentActivity;\n\n    // Initialize cache\n    this.cache = {\n      continueEnabled: false,\n      previousEnabled: false,\n      availableChoices: new Set<string>(),\n      choiceEnabledMap: new Map<string, boolean>(),\n      treeStateHash,\n    };\n\n    // Edge case: no current activity\n    if (!currentActivity) {\n      // Can only choose activities from root level\n      this.calculateAvailableChoicesFromRoot();\n      return;\n    }\n\n    // Predict Continue\n    this.cache.continueEnabled = this.predictContinueInternal(currentActivity);\n\n    // Predict Previous\n    this.cache.previousEnabled = this.predictPreviousInternal(currentActivity);\n\n    // Calculate available choices for all activities\n    this.calculateAvailableChoices();\n  }\n\n  /**\n   * Predict if Continue would succeed from the given activity\n   * @param {Activity} currentActivity - Current activity\n   * @return {boolean} - True if Continue would succeed\n   * @private\n   */\n  private predictContinueInternal(currentActivity: Activity): boolean {\n    // NB.2.1 only requires the current activity to be in a flow-enabled\n    // cluster. Do not inspect the next activity here: ending the current\n    // attempt transfers its RTE data, writes global objectives, and can change\n    // the next activity's precondition result before flow traversal begins.\n    //\n    // The ADL Sample RTE follows the same rule and always exposes Continue for\n    // an activity in a flow cluster. Trying to predict the post-termination\n    // target from the pre-termination tree can otherwise deadlock content that\n    // relies on its final cmi.completion_status/cmi.success_status write to\n    // unlock the next SCO.\n    if (!currentActivity.parent) {\n      return false;\n    }\n\n    return currentActivity.parent.sequencingControls.flow;\n  }\n\n  /**\n   * Predict if Previous would succeed from the given activity\n   * @param {Activity} currentActivity - Current activity\n   * @return {boolean} - True if Previous would succeed\n   * @private\n   */\n  private predictPreviousInternal(currentActivity: Activity): boolean {\n    // Check basic flow control requirements\n    if (!currentActivity.parent) {\n      return false;\n    }\n\n    // Flow must be enabled on the parent to use Previous\n    if (!currentActivity.parent.sequencingControls.flow) {\n      return false;\n    }\n\n    // forwardOnly blocks Previous navigation\n    if (currentActivity.parent.sequencingControls.forwardOnly) {\n      return false;\n    }\n\n    // Check if there's a potential previous activity\n    return this.hasAvailablePreviousActivity(currentActivity);\n  }\n\n  /**\n   * Check if there's an available previous activity in flow\n   * @param {Activity} currentActivity - Current activity\n   * @return {boolean} - True if previous activity exists\n   * @private\n   */\n  private hasAvailablePreviousActivity(currentActivity: Activity): boolean {\n    const parent = currentActivity.parent;\n    if (!parent) {\n      return false;\n    }\n\n    const siblings = parent.children;\n    const currentIndex = siblings.indexOf(currentActivity);\n\n    if (currentIndex === -1) {\n      return false;\n    }\n\n    // Check if there's any sibling before current\n    if (currentIndex > 0) {\n      // Check if there's a deliverable activity before this one\n      // Uses simpler check for backward navigation (reviewing previously visited content)\n      for (let i = currentIndex - 1; i >= 0; i--) {\n        const sibling = siblings[i];\n        if (sibling && this.isActivityPotentiallyDeliverableBackward(sibling)) {\n          return true;\n        }\n      }\n    }\n\n    // Check if we can go to parent's previous sibling\n    if (parent.parent && parent.sequencingControls.flow && !parent.sequencingControls.forwardOnly) {\n      return this.hasAvailablePreviousActivity(parent);\n    }\n\n    return false;\n  }\n\n  /**\n   * Calculate available choices from root (when no current activity)\n   * @private\n   */\n  private calculateAvailableChoicesFromRoot(): void {\n    if (!this.cache || !this.activityTree.root) {\n      return;\n    }\n\n    // When no current activity, no choices are available yet\n    // User must start the course first\n    // Do not populate any choices\n  }\n\n  /**\n   * Calculate all available choices in the tree\n   * @private\n   */\n  private calculateAvailableChoices(): void {\n    if (!this.cache || !this.activityTree.root) {\n      return;\n    }\n\n    const root = this.activityTree.root;\n    this.recursivelyCheckChoiceAvailability(root);\n  }\n\n  /**\n   * Recursively check choice availability for activity and its descendants\n   * @param {Activity} activity - Activity to check\n   * @private\n   */\n  private recursivelyCheckChoiceAvailability(activity: Activity): void {\n    if (!this.cache) {\n      return;\n    }\n\n    const currentActivity = this.activityTree.currentActivity;\n\n    // Check if this activity can be chosen\n    const validation = this.sequencingProcess.validateNavigationRequest(\n      SequencingRequestType.CHOICE,\n      activity.id,\n      currentActivity,\n    );\n\n    const isChoiceEnabled = validation.valid;\n\n    this.cache.choiceEnabledMap.set(activity.id, isChoiceEnabled);\n\n    if (isChoiceEnabled) {\n      this.cache.availableChoices.add(activity.id);\n    }\n\n    // Recursively check children\n    if (activity.children) {\n      for (const child of activity.children) {\n        this.recursivelyCheckChoiceAvailability(child);\n      }\n    }\n  }\n\n  /**\n   * Check if activity is potentially deliverable for backward navigation (Previous)\n   * @param {Activity} activity - Activity to check\n   * @return {boolean} - True if potentially deliverable\n   * @spec SN Book: UP.2 (Sequencing Rules Check Process) - evaluates preconditions to exclude skipped and disabled backward flow candidates.\n   * @spec SN Book: SB.2.2 (Flow Activity Traversal Subprocess) - stopForwardTraversal does not block backward traversal.\n   * @private\n   */\n  private isActivityPotentiallyDeliverableBackward(activity: Activity): boolean {\n    // Visibility and hidden-from-choice only affect choice presentation. Flow\n    // navigation can still deliver the activity.\n    if (!activity.isAvailable) {\n      return false;\n    }\n\n    // Previous targets have settled state, so their preconditions can be checked.\n    // Continue is predicted before End Attempt, which can change its next target's state.\n    const preConditionResult = activity.sequencingRules.evaluatePreConditionRules(\n      activity,\n      this.sequencingProcess.now,\n      this.sequencingProcess.getAttemptElapsedSecondsHook,\n    );\n    if (\n      preConditionResult === RuleActionType.SKIP ||\n      preConditionResult === RuleActionType.DISABLED\n    ) {\n      return false;\n    }\n\n    if (activity.children.length === 0) {\n      return true;\n    }\n\n    // For clusters, check if any child is potentially deliverable\n    for (const child of activity.children) {\n      if (this.isActivityPotentiallyDeliverableBackward(child)) {\n        return true;\n      }\n    }\n\n    return false;\n  }\n\n  /**\n   * Calculate a hash of the tree state for cache invalidation\n   * @return {string} - Hash representing current tree state\n   * @private\n   */\n  private calculateTreeStateHash(): string {\n    const currentActivity = this.activityTree.currentActivity;\n    const suspendedActivity = this.activityTree.suspendedActivity;\n\n    // Create a simple hash from key state elements\n    const parts: string[] = [\n      currentActivity?.id ?? \"none\",\n      suspendedActivity?.id ?? \"none\",\n      this.getActivityTreeStateSignature(),\n    ];\n\n    return parts.join(\"|\");\n  }\n\n  /**\n   * Get a signature of the activity tree state\n   * @return {string} - Signature of tree state\n   * @private\n   */\n  private getActivityTreeStateSignature(): string {\n    if (!this.activityTree.root) {\n      return \"empty\";\n    }\n\n    // Create a signature based on important activity states\n    const signatures: string[] = [];\n    this.collectActivitySignatures(this.activityTree.root, signatures);\n\n    return signatures.join(\":\");\n  }\n\n  /**\n   * Recursively collect activity signatures\n   * @param {Activity} activity - Activity to process\n   * @param {string[]} signatures - Array to collect signatures\n   * @private\n   */\n  private collectActivitySignatures(activity: Activity, signatures: string[]): void {\n    // Include key state elements that affect navigation\n    const sig = [\n      activity.id,\n      activity.isActive ? \"A\" : \"-\",\n      activity.isSuspended ? \"S\" : \"-\",\n      activity.completionStatus,\n      activity.successStatus,\n      activity.attemptCount.toString(),\n    ].join(\"\");\n\n    signatures.push(sig);\n\n    // Process children\n    if (activity.children) {\n      for (const child of activity.children) {\n        this.collectActivitySignatures(child, signatures);\n      }\n    }\n  }\n}\n","import { Activity } from \"../activity\";\nimport { ActivityTree } from \"../activity_tree\";\nimport { SequencingProcess, SequencingRequestType } from \"../sequencing_process\";\nimport { RuleActionType } from \"../sequencing_rules\";\nimport { ADLNav } from \"../../adl\";\nimport { NavigationLookAhead, NavigationPredictions } from \"../navigation_look_ahead\";\nimport {\n  AuxiliaryResource,\n  HideLmsUiItem,\n  NavigationValidityUpdate,\n} from \"../../../../types/sequencing_types\";\n\n/**\n * Enum for navigation request types\n */\nexport enum NavigationRequestType {\n  START = \"start\",\n  RESUME_ALL = \"resumeAll\",\n  CONTINUE = \"continue\",\n  PREVIOUS = \"previous\",\n  CHOICE = \"choice\",\n  JUMP = \"jump\",\n  EXIT = \"exit\",\n  EXIT_ALL = \"exitAll\",\n  ABANDON = \"abandon\",\n  ABANDON_ALL = \"abandonAll\",\n  SUSPEND_ALL = \"suspendAll\",\n  NOT_VALID = \"_none_\",\n}\n\n/**\n * Class representing a navigation request result\n */\nexport class NavigationRequestResult {\n  public valid: boolean;\n  public terminationRequest: SequencingRequestType | null;\n  public sequencingRequest: SequencingRequestType | null;\n  public targetActivityId: string | null;\n  public exception: string | null;\n\n  constructor(\n    valid: boolean = false,\n    terminationRequest: SequencingRequestType | null = null,\n    sequencingRequest: SequencingRequestType | null = null,\n    targetActivityId: string | null = null,\n    exception: string | null = null\n  ) {\n    this.valid = valid;\n    this.terminationRequest = terminationRequest;\n    this.sequencingRequest = sequencingRequest;\n    this.targetActivityId = targetActivityId;\n    this.exception = exception;\n  }\n}\n\n/**\n * NavigationValidityService\n *\n * Handles all navigation validation for the SCORM 2004 sequencing engine.\n * Extracted from OverallSequencingProcess to follow Single Responsibility Principle.\n *\n * Responsibilities:\n * - Validate navigation requests\n * - Check choice path constraints\n * - Validate forward-only constraints\n * - Update navigation validity in ADL nav\n * - Manage navigation look-ahead predictions\n *\n * @spec SN Book: NB.2.1 (Navigation Request Process)\n */\nexport class NavigationValidityService {\n  private activityTree: ActivityTree;\n  private sequencingProcess: SequencingProcess;\n  private adlNav: ADLNav | null;\n  private eventCallback: ((eventType: string, data?: any) => void) | null;\n  private navigationLookAhead: NavigationLookAhead;\n  private getEffectiveHideLmsUiCallback:\n    | ((activity: Activity | null) => HideLmsUiItem[])\n    | null = null;\n  private getEffectiveAuxiliaryResourcesCallback:\n    | ((activity: Activity | null) => AuxiliaryResource[])\n    | null = null;\n\n  constructor(\n    activityTree: ActivityTree,\n    sequencingProcess: SequencingProcess,\n    adlNav: ADLNav | null = null,\n    eventCallback: ((eventType: string, data?: any) => void) | null = null\n  ) {\n    this.activityTree = activityTree;\n    this.sequencingProcess = sequencingProcess;\n    this.adlNav = adlNav;\n    this.eventCallback = eventCallback;\n    this.navigationLookAhead = new NavigationLookAhead(activityTree, sequencingProcess);\n  }\n\n  /**\n   * Set callback to get effective hideLmsUi\n   */\n  public setGetEffectiveHideLmsUiCallback(\n    callback: (activity: Activity | null) => HideLmsUiItem[]\n  ): void {\n    this.getEffectiveHideLmsUiCallback = callback;\n  }\n\n  /** Set callback used to resolve inherited auxiliary resources for the current activity. */\n  public setGetEffectiveAuxiliaryResourcesCallback(\n    callback: (activity: Activity | null) => AuxiliaryResource[],\n  ): void {\n    this.getEffectiveAuxiliaryResourcesCallback = callback;\n  }\n\n  /**\n   * Get the navigation look-ahead instance\n   */\n  public getNavigationLookAhead(): NavigationLookAhead {\n    return this.navigationLookAhead;\n  }\n\n  /**\n   * Navigation Request Process\n   * Validates navigation requests and converts them to termination/sequencing requests\n   * @spec SN Book: NB.2.1 (Navigation Request Process)\n   * @param {NavigationRequestType} request - The navigation request\n   * @param {string | null} targetActivityId - Target activity for choice/jump\n   * @return {NavigationRequestResult} - The validation result\n   */\n  public validateRequest(\n    request: NavigationRequestType,\n    targetActivityId: string | null = null\n  ): NavigationRequestResult {\n    // Enhanced logging for debugging\n    this.fireEvent(\"onNavigationRequestProcessing\", { request, targetActivityId });\n    const currentActivity = this.activityTree.currentActivity;\n\n    // Check if navigation request is valid\n    switch (request) {\n      case NavigationRequestType.START:\n        return this.validateStartRequest(currentActivity);\n\n      case NavigationRequestType.RESUME_ALL:\n        return this.validateResumeRequest(currentActivity);\n\n      case NavigationRequestType.CONTINUE:\n        return this.validateContinueRequest(currentActivity);\n\n      case NavigationRequestType.PREVIOUS:\n        return this.validatePreviousRequest(currentActivity);\n\n      case NavigationRequestType.CHOICE:\n        return this.validateChoiceRequest(currentActivity, targetActivityId);\n\n      case NavigationRequestType.JUMP:\n        return this.validateJumpRequest(targetActivityId);\n\n      case NavigationRequestType.EXIT:\n        return this.validateExitRequest(currentActivity);\n\n      case NavigationRequestType.EXIT_ALL:\n        return this.validateExitAllRequest(currentActivity);\n\n      case NavigationRequestType.ABANDON:\n        return this.validateAbandonRequest(currentActivity);\n\n      case NavigationRequestType.ABANDON_ALL:\n        return this.validateAbandonAllRequest(currentActivity);\n\n      case NavigationRequestType.SUSPEND_ALL:\n        return this.validateSuspendAllRequest(currentActivity);\n\n      default:\n        return new NavigationRequestResult(false, null, null, null, \"NB.2.1-18\");\n    }\n  }\n\n  /**\n   * Validate START request\n   */\n  private validateStartRequest(\n    currentActivity: Activity | null\n  ): NavigationRequestResult {\n    if (currentActivity !== null) {\n      return new NavigationRequestResult(false, null, null, null, \"NB.2.1-1\");\n    }\n    return new NavigationRequestResult(\n      true,\n      null,\n      SequencingRequestType.START,\n      null\n    );\n  }\n\n  /**\n   * Validate RESUME_ALL request\n   */\n  private validateResumeRequest(\n    currentActivity: Activity | null\n  ): NavigationRequestResult {\n    if (currentActivity !== null) {\n      return new NavigationRequestResult(false, null, null, null, \"NB.2.1-2\");\n    }\n    if (this.activityTree.suspendedActivity === null) {\n      return new NavigationRequestResult(false, null, null, null, \"NB.2.1-3\");\n    }\n    return new NavigationRequestResult(\n      true,\n      null,\n      SequencingRequestType.RESUME_ALL,\n      null\n    );\n  }\n\n  /**\n   * Validate CONTINUE request\n   */\n  private validateContinueRequest(\n    currentActivity: Activity | null\n  ): NavigationRequestResult {\n    if (!currentActivity) {\n      return new NavigationRequestResult(false, null, null, null, \"NB.2.1-4\");\n    }\n    if (\n      !currentActivity.parent ||\n      !currentActivity.parent.sequencingControls.flow\n    ) {\n      return new NavigationRequestResult(false, null, null, null, \"NB.2.1-5\");\n    }\n\n    // Per NB.2.1 Step 3.2.1: Only terminate if current activity is active\n    const continueTerminationRequest = currentActivity.isActive\n      ? SequencingRequestType.EXIT\n      : null;\n\n    return new NavigationRequestResult(\n      true,\n      continueTerminationRequest,\n      SequencingRequestType.CONTINUE,\n      null\n    );\n  }\n\n  /**\n   * Validate PREVIOUS request\n   */\n  private validatePreviousRequest(\n    currentActivity: Activity | null\n  ): NavigationRequestResult {\n    if (!currentActivity) {\n      return new NavigationRequestResult(false, null, null, null, \"NB.2.1-6\");\n    }\n    if (\n      !currentActivity.parent ||\n      !currentActivity.parent.sequencingControls.flow\n    ) {\n      return new NavigationRequestResult(false, null, null, null, \"NB.2.1-7\");\n    }\n\n    // Enhanced Forward-Only Navigation Constraints - Check at multiple cluster levels\n    const forwardOnlyValidation =\n      this.validateForwardOnlyConstraints(currentActivity);\n    if (!forwardOnlyValidation.valid) {\n      return new NavigationRequestResult(\n        false,\n        null,\n        null,\n        null,\n        forwardOnlyValidation.exception\n      );\n    }\n\n    // Per NB.2.1 Step 4.2.1.1: Only terminate if current activity is active\n    const previousTerminationRequest = currentActivity.isActive\n      ? SequencingRequestType.EXIT\n      : null;\n\n    return new NavigationRequestResult(\n      true,\n      previousTerminationRequest,\n      SequencingRequestType.PREVIOUS,\n      null\n    );\n  }\n\n  /**\n   * Validate CHOICE request\n   */\n  private validateChoiceRequest(\n    currentActivity: Activity | null,\n    targetActivityId: string | null\n  ): NavigationRequestResult {\n    if (!targetActivityId) {\n      return new NavigationRequestResult(false, null, null, null, \"NB.2.1-9\");\n    }\n    const targetActivity = this.activityTree.getActivity(targetActivityId);\n    if (!targetActivity) {\n      return new NavigationRequestResult(false, null, null, null, \"NB.2.1-10\");\n    }\n\n    // Enhanced Choice Path Validation\n    const choiceValidation = this.validateChoicePath(\n      currentActivity,\n      targetActivity\n    );\n    if (!choiceValidation.valid) {\n      return new NavigationRequestResult(\n        false,\n        null,\n        null,\n        null,\n        choiceValidation.exception\n      );\n    }\n\n    // Per NB.2.1 Step 7.1.1.4: Only return EXIT if current activity is active\n    return new NavigationRequestResult(\n      true,\n      currentActivity?.isActive ? SequencingRequestType.EXIT : null,\n      SequencingRequestType.CHOICE,\n      targetActivityId\n    );\n  }\n\n  /**\n   * Validate JUMP request\n   */\n  private validateJumpRequest(\n    targetActivityId: string | null\n  ): NavigationRequestResult {\n    if (!targetActivityId) {\n      return new NavigationRequestResult(false, null, null, null, \"NB.2.1-12\");\n    }\n    return new NavigationRequestResult(\n      true,\n      null,\n      SequencingRequestType.JUMP,\n      targetActivityId\n    );\n  }\n\n  /**\n   * Validate EXIT request\n   */\n  private validateExitRequest(\n    currentActivity: Activity | null\n  ): NavigationRequestResult {\n    if (!currentActivity) {\n      return new NavigationRequestResult(false, null, null, null, \"NB.2.1-13\");\n    }\n    if (currentActivity === this.activityTree.root) {\n      return new NavigationRequestResult(\n        true,\n        SequencingRequestType.EXIT_ALL,\n        null,\n        null\n      );\n    }\n    return new NavigationRequestResult(\n      true,\n      SequencingRequestType.EXIT,\n      null,\n      null\n    );\n  }\n\n  /**\n   * Validate EXIT_ALL request\n   */\n  private validateExitAllRequest(\n    currentActivity: Activity | null\n  ): NavigationRequestResult {\n    if (!currentActivity) {\n      return new NavigationRequestResult(false, null, null, null, \"NB.2.1-14\");\n    }\n    return new NavigationRequestResult(\n      true,\n      SequencingRequestType.EXIT_ALL,\n      null,\n      null\n    );\n  }\n\n  /**\n   * Validate ABANDON request\n   */\n  private validateAbandonRequest(\n    currentActivity: Activity | null\n  ): NavigationRequestResult {\n    if (!currentActivity) {\n      return new NavigationRequestResult(false, null, null, null, \"NB.2.1-15\");\n    }\n    return new NavigationRequestResult(\n      true,\n      SequencingRequestType.ABANDON,\n      null,\n      null\n    );\n  }\n\n  /**\n   * Validate ABANDON_ALL request\n   */\n  private validateAbandonAllRequest(\n    currentActivity: Activity | null\n  ): NavigationRequestResult {\n    if (!currentActivity) {\n      return new NavigationRequestResult(false, null, null, null, \"NB.2.1-16\");\n    }\n    return new NavigationRequestResult(\n      true,\n      SequencingRequestType.ABANDON_ALL,\n      null,\n      null\n    );\n  }\n\n  /**\n   * Validate SUSPEND_ALL request\n   */\n  private validateSuspendAllRequest(\n    currentActivity: Activity | null\n  ): NavigationRequestResult {\n    if (!currentActivity) {\n      return new NavigationRequestResult(false, null, null, null, \"NB.2.1-17\");\n    }\n    return new NavigationRequestResult(\n      true,\n      SequencingRequestType.SUSPEND_ALL,\n      null,\n      null\n    );\n  }\n\n  /**\n   * Enhanced Complex Choice Path Validation\n   * Implements comprehensive choice validation with nested hierarchy support\n   * @param {Activity | null} currentActivity - Current activity\n   * @param {Activity} targetActivity - Target activity for choice\n   * @return {{valid: boolean, exception: string | null}} - Validation result\n   */\n  public validateChoicePath(\n    currentActivity: Activity | null,\n    targetActivity: Activity\n  ): { valid: boolean; exception: string | null } {\n    // Check if target is hidden from choice or otherwise unavailable\n    // Per NB.2.1 Step 7.1.1.1: Only check static properties here, not preconditions\n    // Preconditions that depend on rollup state are evaluated later in SB.2.3 (Check Activity)\n    if (targetActivity.isHiddenFromChoice) {\n      return { valid: false, exception: \"NB.2.1-11\" };\n    }\n\n    // Check availability and precondition rules (DISABLED, HIDE_FROM_CHOICE)\n    // Per NB.2.1: Target activity must be available for choice navigation\n    if (!targetActivity.isAvailable) {\n      return { valid: false, exception: \"NB.2.1-11\" };\n    }\n\n    // Check if target is disabled by precondition rules (e.g., DISABLED action with ALWAYS condition)\n    if (this.isActivityDisabled(targetActivity)) {\n      return { valid: false, exception: \"NB.2.1-11\" };\n    }\n\n    if (currentActivity) {\n      const commonAncestor = this.findCommonAncestor(\n        currentActivity,\n        targetActivity\n      );\n      if (!commonAncestor) {\n        return { valid: false, exception: \"NB.2.1-11\" };\n      }\n\n      // Validate choiceExit controls along the current activity path\n      // Per NB.2.1 Step 7.1.1.2.3.1: Only check active ancestors from current to common ancestor (exclusive)\n      let node: Activity | null = currentActivity;\n      while (node && node !== commonAncestor) {\n        // Only validate choiceExit if the activity is active\n        if (\n          node.isActive === true &&\n          node.sequencingControls &&\n          node.sequencingControls.choiceExit === false\n        ) {\n          if (\n            targetActivity !== node &&\n            !this.activityContains(node, targetActivity)\n          ) {\n            return { valid: false, exception: \"NB.2.1-11\" };\n          }\n        }\n        node = node.parent;\n      }\n\n      // Enhanced constrainChoice control validation in nested hierarchies\n      const constrainChoiceValidation = this.validateConstrainChoice(\n        currentActivity,\n        targetActivity,\n        commonAncestor\n      );\n      if (!constrainChoiceValidation.valid) {\n        return constrainChoiceValidation;\n      }\n\n      // Validate choice sets with multiple targets\n      const choiceSetValidation = this.validateChoiceSet(\n        currentActivity,\n        targetActivity,\n        commonAncestor\n      );\n      if (!choiceSetValidation.valid) {\n        return choiceSetValidation;\n      }\n    }\n\n    // @spec SCORM 2004 SN 4th Ed. NB.2.1: choice control applies to the\n    // target's immediate parent; higher ancestors govern their own child sets.\n    if (\n      targetActivity.parent &&\n      !targetActivity.parent.sequencingControls.choice\n    ) {\n      return { valid: false, exception: \"NB.2.1-11\" };\n    }\n\n    return { valid: true, exception: null };\n  }\n\n  /**\n   * Enhanced Forward-Only Navigation Constraints\n   * Handles forward-only constraints at different cluster levels\n   * @param {Activity} currentActivity - Current activity\n   * @return {{valid: boolean, exception: string | null}} - Validation result\n   */\n  public validateForwardOnlyConstraints(currentActivity: Activity): {\n    valid: boolean;\n    exception: string | null;\n  } {\n    // Check forward-only constraint at immediate parent level\n    if (currentActivity.parent?.sequencingControls.forwardOnly) {\n      return { valid: false, exception: \"NB.2.1-8\" };\n    }\n\n    // Check forward-only constraints at higher cluster levels\n    let ancestor = currentActivity.parent?.parent;\n    while (ancestor) {\n      if (ancestor.sequencingControls.forwardOnly) {\n        // If any ancestor cluster has forwardOnly=true, previous navigation is blocked\n        return { valid: false, exception: \"NB.2.1-8\" };\n      }\n      ancestor = ancestor.parent;\n    }\n\n    return { valid: true, exception: null };\n  }\n\n  /**\n   * Enhanced constrainChoice Control Validation\n   * Implements proper constrainChoice validation in nested hierarchies\n   * @param {Activity} currentActivity - Current activity\n   * @param {Activity} targetActivity - Target activity\n   * @param {Activity} commonAncestor - Common ancestor\n   * @return {{valid: boolean, exception: string | null}} - Validation result\n   */\n  private validateConstrainChoice(\n    currentActivity: Activity,\n    targetActivity: Activity,\n    commonAncestor: Activity\n  ): { valid: boolean; exception: string | null } {\n    // Check constrainChoice at the common ancestor and above in the path\n    let ancestor: Activity | null = commonAncestor;\n    while (ancestor) {\n      if (\n        ancestor.sequencingControls?.constrainChoice ||\n        ancestor.sequencingControls?.preventActivation\n      ) {\n        const currentBranch = this.findChildContaining(\n          ancestor,\n          currentActivity\n        );\n        if (!currentBranch) {\n          return { valid: false, exception: \"NB.2.1-11\" };\n        }\n\n        if (targetActivity === ancestor) {\n          return { valid: false, exception: \"NB.2.1-11\" };\n        }\n\n        const targetBranch = this.findChildContaining(ancestor, targetActivity);\n        if (!targetBranch) {\n          return { valid: false, exception: \"NB.2.1-11\" };\n        }\n\n        if (\n          ancestor.sequencingControls?.constrainChoice &&\n          targetBranch !== currentBranch\n        ) {\n          return { valid: false, exception: \"NB.2.1-11\" };\n        }\n\n        if (\n          ancestor.sequencingControls?.preventActivation &&\n          targetBranch !== currentBranch\n        ) {\n          if (this.requiresNewActivation(targetBranch, targetActivity)) {\n            return { valid: false, exception: \"NB.2.1-11\" };\n          }\n        }\n      }\n\n      ancestor = ancestor.parent;\n    }\n\n    return this.validateAncestors(commonAncestor, currentActivity, targetActivity);\n  }\n\n  /**\n   * Validate Choice Set Constraints\n   * Validates choice sets with multiple targets\n   * @param {Activity} _currentActivity - Current activity (unused but part of interface)\n   * @param {Activity} targetActivity - Target activity\n   * @param {Activity} commonAncestor - Common ancestor\n   * @return {{valid: boolean, exception: string | null}} - Validation result\n   */\n  private validateChoiceSet(\n    _currentActivity: Activity,\n    targetActivity: Activity,\n    commonAncestor: Activity\n  ): { valid: boolean; exception: string | null } {\n    // Check if target is within the valid choice set\n    // Ensure the target is contained within the common ancestor's subtree\n    if (\n      !this.activityContains(commonAncestor, targetActivity) &&\n      targetActivity !== commonAncestor\n    ) {\n      return { valid: false, exception: \"NB.2.1-11\" };\n    }\n\n    // Walk from target up to (but not including) the common ancestor ensuring availability\n    // Per NB.2.1: Check availability, visibility, and precondition rules\n    let node: Activity | null = targetActivity;\n    while (node && node !== commonAncestor) {\n      if (\n        !node.isAvailable ||\n        node.isHiddenFromChoice ||\n        this.isActivityDisabled(node)\n      ) {\n        return { valid: false, exception: \"NB.2.1-11\" };\n      }\n      node = node.parent;\n    }\n\n    return { valid: true, exception: null };\n  }\n\n  /**\n   * Check if activity is disabled\n   * @param {Activity} activity - Activity to check\n   * @return {boolean} - True if disabled\n   */\n  public isActivityDisabled(activity: Activity): boolean {\n    if (!activity.isAvailable) {\n      return true;\n    }\n\n    if (activity.isHiddenFromChoice) {\n      return true;\n    }\n\n    const preConditionResult = this.evaluatePreConditionRulesForChoice(activity);\n    if (!preConditionResult) {\n      return false;\n    }\n\n    return (\n      preConditionResult === RuleActionType.DISABLED ||\n      preConditionResult === RuleActionType.HIDE_FROM_CHOICE ||\n      preConditionResult === RuleActionType.STOP_FORWARD_TRAVERSAL\n    );\n  }\n\n  /**\n   * Find child activity that contains the target activity\n   * @param {Activity} parent - Parent activity\n   * @param {Activity} target - Target activity to find\n   * @return {Activity | null} - Child activity containing target\n   */\n  public findChildContaining(\n    parent: Activity,\n    target: Activity\n  ): Activity | null {\n    for (const child of parent.children) {\n      if (child === target) {\n        return child;\n      }\n      if (this.activityContains(child, target)) {\n        return child;\n      }\n    }\n    return null;\n  }\n\n  /**\n   * Check if an activity contains another activity in its hierarchy\n   * @param {Activity} container - Container activity\n   * @param {Activity} target - Target activity\n   * @return {boolean} - True if container contains target\n   */\n  public activityContains(container: Activity, target: Activity): boolean {\n    let current: Activity | null = target;\n    while (current) {\n      if (current === container) {\n        return true;\n      }\n      current = current.parent;\n    }\n    return false;\n  }\n\n  /**\n   * Find common ancestor between two activities\n   */\n  public findCommonAncestor(\n    activity1: Activity,\n    activity2: Activity\n  ): Activity | null {\n    // Get ancestors of activity1\n    const ancestors1: Activity[] = [];\n    let current: Activity | null = activity1;\n    while (current) {\n      ancestors1.push(current);\n      current = current.parent;\n    }\n\n    // Find first common ancestor\n    current = activity2;\n    while (current) {\n      if (ancestors1.includes(current)) {\n        return current;\n      }\n      current = current.parent;\n    }\n\n    return null;\n  }\n\n  /**\n   * Validate ancestor-level constraints\n   * @param {Activity} ancestor - Ancestor activity\n   * @param {Activity} currentActivity - Current activity\n   * @param {Activity} targetActivity - Target activity\n   * @return {{valid: boolean, exception: string | null}} - Validation result\n   */\n  private validateAncestors(\n    ancestor: Activity,\n    currentActivity: Activity,\n    targetActivity: Activity\n  ): { valid: boolean; exception: string | null } {\n    // @spec SCORM 2004 SN 4th Ed. NB.2.1: the target of a choice request may be the\n    // common ancestor itself. Its parent's choice control governs that request; the\n    // target's own choice control only governs choices among its children.\n    if (targetActivity === ancestor) {\n      return { valid: true, exception: null };\n    }\n\n    // Enforce forwardOnly and mandatory activity constraints at ancestor level\n    const children = ancestor.children;\n    if (!children || children.length === 0) {\n      return { valid: true, exception: null };\n    }\n\n    const currentTop = this.findChildContaining(ancestor, currentActivity);\n    const targetTop = this.findChildContaining(ancestor, targetActivity);\n    if (!currentTop || !targetTop) {\n      return { valid: false, exception: \"NB.2.1-11\" };\n    }\n\n    const currentIndex = children.indexOf(currentTop);\n    const targetIndex = children.indexOf(targetTop);\n\n    // Forward-only prevents backwards choice under this ancestor\n    if (ancestor.sequencingControls.forwardOnly && targetIndex < currentIndex) {\n      return { valid: false, exception: \"NB.2.1-8\" };\n    }\n\n    const traversalStopIndex = children.findIndex(\n      (child) => child?.sequencingControls.stopForwardTraversal\n    );\n\n    // Current branch flagged stopForwardTraversal blocks moving past it\n    if (\n      currentTop.sequencingControls.stopForwardTraversal &&\n      targetIndex > currentIndex\n    ) {\n      return { valid: false, exception: \"NB.2.1-11\" };\n    }\n\n    // Stop forward traversal on siblings earlier than target also blocks progression\n    if (traversalStopIndex !== -1 && targetIndex > traversalStopIndex) {\n      return { valid: false, exception: \"NB.2.1-11\" };\n    }\n\n    // Do not skip mandatory incomplete siblings when moving forward ONLY if forwardOnly=true\n    // Per SCORM 2004 spec: When choice=true and forwardOnly=false, learner can select any activity\n    // The mandatory sibling constraint only applies to forced-sequential navigation patterns\n    if (targetIndex > currentIndex && ancestor.sequencingControls.forwardOnly) {\n      for (let i = currentIndex + 1; i < targetIndex; i++) {\n        const between = children[i];\n        if (!between) {\n          continue;\n        }\n\n        if (between.sequencingControls.stopForwardTraversal) {\n          return { valid: false, exception: \"NB.2.1-11\" };\n        }\n\n        if (\n          this.isActivityMandatory(between) &&\n          !this.isActivityCompleted(between)\n        ) {\n          return { valid: false, exception: \"NB.2.1-11\" };\n        }\n      }\n    }\n\n    return { valid: true, exception: null };\n  }\n\n  private requiresNewActivation(\n    branchRoot: Activity,\n    targetActivity: Activity\n  ): boolean {\n    if (this.branchHasActiveAttempt(branchRoot)) {\n      return false;\n    }\n\n    if (targetActivity.activityAttemptActive || targetActivity.isActive) {\n      return false;\n    }\n\n    return true;\n  }\n\n  private branchHasActiveAttempt(activity: Activity): boolean {\n    if (activity.activityAttemptActive || activity.isActive) {\n      return true;\n    }\n\n    for (const child of activity.children) {\n      if (this.branchHasActiveAttempt(child)) {\n        return true;\n      }\n    }\n\n    return false;\n  }\n\n  /** Helper: mandatory activity detection (mirrors SequencingProcess behavior) */\n  private isActivityMandatory(activity: Activity): boolean {\n    if (!activity.isAvailable || activity.isHiddenFromChoice) {\n      return false;\n    }\n\n    const preConditionResult = this.evaluatePreConditionRulesForChoice(activity);\n    if (\n      preConditionResult === RuleActionType.SKIP ||\n      preConditionResult === RuleActionType.DISABLED ||\n      preConditionResult === RuleActionType.HIDE_FROM_CHOICE ||\n      preConditionResult === RuleActionType.STOP_FORWARD_TRAVERSAL\n    ) {\n      return false;\n    }\n\n    if (this.isActivityDisabled(activity)) {\n      return false;\n    }\n\n    return (activity as any).mandatory !== false;\n  }\n\n  /** Helper: completed-state check (mirrors SequencingProcess behavior) */\n  private isActivityCompleted(activity: Activity): boolean {\n    if (!activity.isAvailable || activity.isHiddenFromChoice) {\n      return true;\n    }\n\n    const preConditionResult = this.evaluatePreConditionRulesForChoice(activity);\n    if (\n      preConditionResult === RuleActionType.SKIP ||\n      preConditionResult === RuleActionType.DISABLED ||\n      preConditionResult === RuleActionType.HIDE_FROM_CHOICE ||\n      preConditionResult === RuleActionType.STOP_FORWARD_TRAVERSAL\n    ) {\n      return true;\n    }\n\n    if (this.isActivityDisabled(activity)) {\n      return true;\n    }\n\n    return (\n      activity.completionStatus === \"completed\" ||\n      (activity as any).successStatus === \"passed\" ||\n      activity.successStatus === \"passed\"\n    );\n  }\n\n  /**\n   * Evaluate pre-condition rules for choice navigation\n   * @param {Activity} activity - Activity to evaluate\n   * @return {string | null} - Rule result or null\n   */\n  private evaluatePreConditionRulesForChoice(\n    activity: Activity\n  ): RuleActionType | string | null {\n    if (!activity.sequencingRules) {\n      return null;\n    }\n\n    const action = activity.sequencingRules.evaluatePreConditionRules(\n      activity,\n      this.sequencingProcess.now,\n      this.sequencingProcess.getAttemptElapsedSecondsHook,\n    );\n    if (action) {\n      return action;\n    }\n\n    return null;\n  }\n\n  /**\n   * Update navigation validity in ADL nav\n   * Called after activity delivery and after rollup to update navigation button states\n   */\n  public updateNavigationValidity(): void {\n    if (!this.adlNav || !this.activityTree.currentActivity) {\n      return;\n    }\n\n    // Invalidate look-ahead cache to ensure fresh calculations\n    this.navigationLookAhead.invalidateCache();\n\n    // Use NavigationLookAhead for Continue/Previous validity\n    // This properly evaluates preConditionRules on target activities\n    const continueValid = this.navigationLookAhead.predictContinueEnabled();\n    try {\n      this.adlNav.request_valid.continue = continueValid ? \"true\" : \"false\";\n    } catch (e) {\n      // Navigation validity might be read-only after init\n    }\n\n    const previousValid = this.navigationLookAhead.predictPreviousEnabled();\n    try {\n      this.adlNav.request_valid.previous = previousValid ? \"true\" : \"false\";\n    } catch (e) {\n      // Navigation validity might be read-only after init\n    }\n\n    // Compute per-target choice/jump validity and emit an event snapshot\n    const allActivities = this.activityTree.getAllActivities();\n    const choiceMap: Record<string, \"true\" | \"false\"> = {};\n    const jumpMap: Record<string, \"true\" | \"false\"> = {};\n    for (const act of allActivities) {\n      const choiceRes = this.validateRequest(\n        NavigationRequestType.CHOICE,\n        act.id\n      );\n      choiceMap[act.id] = choiceRes.valid ? \"true\" : \"false\";\n      jumpMap[act.id] = this.predictJumpEnabled(act.id) ? \"true\" : \"false\";\n    }\n    // Get effective hideLmsUi\n    const hideLmsUi = this.getEffectiveHideLmsUiCallback\n      ? this.getEffectiveHideLmsUiCallback(this.activityTree.currentActivity)\n      : [];\n    const auxiliaryResources = this.getEffectiveAuxiliaryResourcesCallback\n      ? this.getEffectiveAuxiliaryResourcesCallback(this.activityTree.currentActivity)\n      : [];\n\n    // Notify listeners so LMS can update UI regardless of read-only state\n    const update: NavigationValidityUpdate = {\n      continue: continueValid,\n      previous: previousValid,\n      choice: choiceMap,\n      jump: jumpMap,\n      hideLmsUi,\n      auxiliaryResources,\n    };\n    this.fireEvent(\"onNavigationValidityUpdate\", update);\n  }\n\n  /**\n   * Get navigation look-ahead predictions\n   * Provides UI with navigation button states before user interaction\n   * @return {NavigationPredictions} - Current navigation predictions\n   */\n  public getAllPredictions(): NavigationPredictions {\n    return this.navigationLookAhead.getAllPredictions();\n  }\n\n  /**\n   * Predict if Continue navigation would succeed\n   * @return {boolean} - True if Continue would succeed\n   */\n  public predictContinueEnabled(): boolean {\n    return this.navigationLookAhead.predictContinueEnabled();\n  }\n\n  /**\n   * Predict if Previous navigation would succeed\n   * @return {boolean} - True if Previous would succeed\n   */\n  public predictPreviousEnabled(): boolean {\n    return this.navigationLookAhead.predictPreviousEnabled();\n  }\n\n  /** Predict if jump to the target leaf would succeed. */\n  public predictJumpEnabled(activityId: string): boolean {\n    return this.navigationLookAhead.predictJumpEnabled(activityId);\n  }\n\n  /**\n   * Predict if choice to specific activity would succeed\n   * @param {string} activityId - Target activity ID\n   * @return {boolean} - True if choice would succeed\n   */\n  public predictChoiceEnabled(activityId: string): boolean {\n    return this.navigationLookAhead.predictChoiceEnabled(activityId);\n  }\n\n  /**\n   * Get list of all activities that can be chosen\n   * @return {string[]} - Array of activity IDs available for choice\n   */\n  public getAvailableChoices(): string[] {\n    return this.navigationLookAhead.getAvailableChoices();\n  }\n\n  /**\n   * Invalidate navigation prediction cache\n   * Called when state changes that affect navigation\n   */\n  public invalidateCache(): void {\n    this.navigationLookAhead.invalidateCache();\n  }\n\n  /**\n   * Fire a sequencing event\n   * @param {string} eventType - The type of event\n   * @param {any} data - Event data\n   */\n  private fireEvent(eventType: string, data?: any): void {\n    try {\n      if (this.eventCallback) {\n        this.eventCallback(eventType, data);\n      }\n    } catch (error) {\n      console.warn(`Failed to fire sequencing event ${eventType}: ${error}`);\n    }\n  }\n}\n","import { Activity } from \"../activity\";\nimport { RollupProcess } from \"../rollup_process\";\nimport { CompletionStatus } from \"../../../../constants/enums\";\n\n/**\n * GlobalObjectiveService\n *\n * Manages global objectives for the SCORM 2004 sequencing engine.\n * Extracted from OverallSequencingProcess to follow Single Responsibility Principle.\n *\n * Responsibilities:\n * - Initialize global objective map from activity tree\n * - Collect global objectives from activities\n * - Get/Set/Update global objectives\n * - Serialize/Restore global objective state for persistence\n * - Synchronize global objectives with activity states\n *\n * @spec SN Book: Global Objectives\n */\nexport class GlobalObjectiveService {\n  private globalObjectiveMap: Map<string, any> = new Map();\n  private eventCallback: ((eventType: string, data?: any) => void) | null = null;\n\n  constructor(eventCallback?: (eventType: string, data?: any) => void) {\n    this.eventCallback = eventCallback || null;\n  }\n\n  /**\n   * Initialize Global Objective Map\n   * Sets up the global objective map for cross-activity objective synchronization\n   * @param {Activity | null} root - Root activity to initialize from\n   */\n  public initialize(root: Activity | null): void {\n    try {\n      this.globalObjectiveMap.clear();\n\n      // Initialize global objectives from activity tree if available\n      if (root) {\n        this.collectObjectives(root);\n      }\n\n      this.fireEvent(\"onGlobalObjectiveMapInitialized\", {\n        objectiveCount: this.globalObjectiveMap.size,\n        timestamp: new Date().toISOString(),\n      });\n    } catch (error) {\n      this.fireEvent(\"onGlobalObjectiveMapError\", {\n        error: error instanceof Error ? error.message : String(error),\n        timestamp: new Date().toISOString(),\n      });\n    }\n  }\n\n  /**\n   * Collect Global Objectives\n   * Recursively collects global objectives from the activity tree\n   * @param {Activity} activity - Activity to collect objectives from\n   *\n   * @spec SCORM 2004 4th Ed. SN 3.10.3 - global objective map contains mapped objective state\n   * @spec SCORM 2004 4th Ed. ADLSEQ objectives extension - raw/min/max score fields are unknown until written\n   */\n  private collectObjectives(activity: Activity): void {\n    const objectives = activity.getAllObjectives();\n\n    for (const objective of objectives) {\n      // @spec SCORM 2004 4th Ed. SN 3.10.3: only an explicit objective map creates\n      // a global objective relationship. Local and synthesized default objectives\n      // remain local when they have no mapInfo.\n      for (const mapInfo of objective.mapInfo) {\n        const targetId = mapInfo.targetObjectiveID || objective.id;\n        if (!this.globalObjectiveMap.has(targetId)) {\n          this.globalObjectiveMap.set(targetId, {\n            id: targetId,\n            satisfiedStatus: objective.satisfiedStatus,\n            satisfiedStatusKnown: objective.satisfiedStatusKnown || objective.progressStatus,\n            normalizedMeasure: objective.normalizedMeasure,\n            normalizedMeasureKnown: objective.measureStatus,\n            rawScore: \"\",\n            rawScoreKnown: false,\n            minScore: \"\",\n            minScoreKnown: false,\n            maxScore: \"\",\n            maxScoreKnown: false,\n            progressMeasure: objective.progressMeasure,\n            progressMeasureKnown: objective.progressMeasureStatus,\n            completionStatus: objective.completionStatus,\n            completionStatusKnown: objective.completionStatus !== CompletionStatus.UNKNOWN,\n            readSatisfiedStatus: mapInfo.readSatisfiedStatus ?? false,\n            writeSatisfiedStatus: mapInfo.writeSatisfiedStatus ?? false,\n            readNormalizedMeasure: mapInfo.readNormalizedMeasure ?? false,\n            writeNormalizedMeasure: mapInfo.writeNormalizedMeasure ?? false,\n            readProgressMeasure: mapInfo.readProgressMeasure ?? false,\n            writeProgressMeasure: mapInfo.writeProgressMeasure ?? false,\n            readCompletionStatus: mapInfo.readCompletionStatus ?? false,\n            writeCompletionStatus: mapInfo.writeCompletionStatus ?? false,\n            readRawScore: mapInfo.readRawScore ?? false,\n            writeRawScore: mapInfo.writeRawScore ?? false,\n            readMinScore: mapInfo.readMinScore ?? false,\n            writeMinScore: mapInfo.writeMinScore ?? false,\n            readMaxScore: mapInfo.readMaxScore ?? false,\n            writeMaxScore: mapInfo.writeMaxScore ?? false,\n            satisfiedByMeasure: objective.satisfiedByMeasure,\n            minNormalizedMeasure: objective.minNormalizedMeasure,\n            updateAttemptData: mapInfo.updateAttemptData ?? objective.isPrimary,\n          });\n        }\n      }\n    }\n\n    // Process children recursively\n    for (const child of activity.children) {\n      this.collectObjectives(child);\n    }\n  }\n\n  /**\n   * Get Global Objective Map\n   * Returns the current global objective map for external access\n   * @return {Map<string, any>} - Current global objective map\n   */\n  public getMap(): Map<string, any> {\n    return this.globalObjectiveMap;\n  }\n\n  /**\n   * Snapshot the Global Objective Map\n   * Provides a serializable copy for persistence consumers\n   * @return {Record<string, any>} - Plain-object snapshot of global objectives\n   */\n  public getSnapshot(): Record<string, any> {\n    return this.serialize();\n  }\n\n  /**\n   * Restore Global Objective Map\n   * Replaces the current map contents with persisted data\n   * @param {Record<string, any>} snapshot - Serialized global objective map\n   */\n  public restoreSnapshot(snapshot: Record<string, any>): void {\n    this.restore(snapshot);\n  }\n\n  /**\n   * Update Global Objective\n   * Updates a specific global objective with new data\n   * @param {string} objectiveId - Objective ID to update\n   * @param {any} objectiveData - New objective data\n   */\n  public updateObjective(objectiveId: string, objectiveData: any): void {\n    try {\n      this.globalObjectiveMap.set(objectiveId, {\n        ...this.globalObjectiveMap.get(objectiveId),\n        ...objectiveData,\n        lastUpdated: new Date().toISOString(),\n      });\n\n      this.fireEvent(\"onGlobalObjectiveUpdated\", {\n        objectiveId,\n        data: objectiveData,\n        timestamp: new Date().toISOString(),\n      });\n    } catch (error) {\n      this.fireEvent(\"onGlobalObjectiveUpdateError\", {\n        objectiveId,\n        error: error instanceof Error ? error.message : String(error),\n        timestamp: new Date().toISOString(),\n      });\n    }\n  }\n\n  /**\n   * Synchronize global objectives from activity states\n   * Called after CMI changes that affect objective status to update global objective mappings\n   * This ensures that preconditions based on global objectives are properly evaluated\n   * @param {Activity | null} root - Root activity to synchronize from\n   * @param {RollupProcess} rollupProcess - Rollup process for mapping\n   */\n  public synchronize(root: Activity | null, rollupProcess: RollupProcess): void {\n    if (!root) {\n      return;\n    }\n\n    // Process global objective mapping from root to synchronize all activities\n    rollupProcess.processGlobalObjectiveMapping(root, this.globalObjectiveMap);\n  }\n\n  /**\n   * Get a specific global objective by ID\n   * @param {string} objectiveId - The objective ID\n   * @return {any | undefined} - The objective data or undefined\n   */\n  public getObjective(objectiveId: string): any {\n    return this.globalObjectiveMap.get(objectiveId);\n  }\n\n  /**\n   * Check if a global objective exists\n   * @param {string} objectiveId - The objective ID\n   * @return {boolean} - True if exists\n   */\n  public hasObjective(objectiveId: string): boolean {\n    return this.globalObjectiveMap.has(objectiveId);\n  }\n\n  /**\n   * Get all global objective IDs\n   * @return {string[]} - Array of objective IDs\n   */\n  public getObjectiveIds(): string[] {\n    return Array.from(this.globalObjectiveMap.keys());\n  }\n\n  /**\n   * Get the count of global objectives\n   * @return {number} - Number of global objectives\n   */\n  public getObjectiveCount(): number {\n    return this.globalObjectiveMap.size;\n  }\n\n  /**\n   * Clear all global objectives\n   */\n  public clear(): void {\n    this.globalObjectiveMap.clear();\n    this.fireEvent(\"onGlobalObjectiveMapCleared\", {\n      timestamp: new Date().toISOString(),\n    });\n  }\n\n  /**\n   * Serialize the global objective map\n   * @return {Record<string, any>} - Serialized global objectives\n   */\n  private serialize(): Record<string, any> {\n    const serialized: Record<string, any> = {};\n    this.globalObjectiveMap.forEach((data, id) => {\n      serialized[id] = { ...data };\n    });\n    return serialized;\n  }\n\n  /**\n   * Restore the global objective map from serialized data\n   * @param {Record<string, any>} mapData - Serialized global objective map\n   */\n  private restore(mapData: Record<string, any>): void {\n    this.globalObjectiveMap.clear();\n    if (!mapData) {\n      return;\n    }\n    for (const [id, data] of Object.entries(mapData)) {\n      this.globalObjectiveMap.set(id, { ...data });\n    }\n    this.fireEvent(\"onGlobalObjectiveMapRestored\", {\n      objectiveCount: this.globalObjectiveMap.size,\n      timestamp: new Date().toISOString(),\n    });\n  }\n\n  /**\n   * Fire a sequencing event\n   * @param {string} eventType - The type of event\n   * @param {any} data - Event data\n   */\n  private fireEvent(eventType: string, data?: any): void {\n    try {\n      if (this.eventCallback) {\n        this.eventCallback(eventType, data);\n      }\n    } catch (error) {\n      console.warn(`Failed to fire global objective event ${eventType}: ${error}`);\n    }\n  }\n}\n","import { Activity } from \"../activity\";\nimport { ActivityTree } from \"../activity_tree\";\nimport { GlobalObjectiveService } from \"../services/global_objective_service\";\nimport { RollupProcess } from \"../rollup_process\";\nimport { ADLNav } from \"../../adl\";\nimport { HideLmsUiItem, AuxiliaryResource } from \"../../../../types/sequencing_types\";\n\n/**\n * Activity state for serialization\n */\nexport interface ActivityStateData {\n  id: string;\n  title: string;\n  isActive: boolean;\n  isSuspended: boolean;\n  isCompleted: boolean;\n  completionStatus: string;\n  successStatus: string;\n  attemptCount: number;\n  objectiveInfoAvailableInCurrentParentAttempt?: boolean;\n  progressInfoAvailableInCurrentParentAttempt?: boolean;\n  attemptCompletionAmount: number;\n  /** @spec SN Book RB.1.1.b - completion measure rollup depends on whether the persisted measure is known. */\n  attemptCompletionAmountStatus: boolean;\n  attemptAbsoluteDuration: string;\n  attemptExperiencedDuration: string;\n  activityAbsoluteDuration: string;\n  activityExperiencedDuration: string;\n  objectiveSatisfiedStatus: boolean;\n  /** @spec SCORM 2004 4th Ed. SN TM.1: unknown objective progress must survive session restore. */\n  objectiveSatisfiedStatusKnown: boolean;\n  objectiveMeasureStatus: boolean;\n  objectiveNormalizedMeasure: number;\n  progressMeasure: number | null;\n  progressMeasureStatus: boolean;\n  isAvailable: boolean;\n  isHiddenFromChoice: boolean;\n  location: string;\n  attemptAbsoluteStartTime: string | null;\n  objectives: any;\n  auxiliaryResources: AuxiliaryResource[];\n  selectionRandomizationState: {\n    selectionCountStatus: boolean;\n    reorderChildren: boolean;\n    childOrder: string[];\n    selectedChildIds: string[];\n    hiddenFromChoiceChildIds: string[];\n  };\n}\n\n/**\n * Navigation state for serialization\n */\nexport interface NavigationState {\n  request: string;\n  requestValid: {\n    continue: string;\n    previous: string;\n    choice: string;\n    jump: string;\n    exit: string;\n    exitAll: string;\n    abandon: string;\n    abandonAll: string;\n    suspendAll: string;\n  };\n  hideLmsUi: HideLmsUiItem[];\n  auxiliaryResources: AuxiliaryResource[];\n}\n\n/**\n * Complete sequencing state for persistence\n */\nexport interface SequencingState {\n  version: string;\n  timestamp: string;\n  contentDelivered: boolean;\n  currentActivity: string | null;\n  suspendedActivity: string | null;\n  activityStates: Record<string, ActivityStateData>;\n  navigationState: NavigationState | null;\n  globalObjectiveMap: Record<string, any>;\n}\n\n/**\n * Suspension state for persistence\n */\nexport interface SuspensionState {\n  activityTree: any;\n  currentActivityId: string | null;\n  suspendedActivityId: string | null;\n  globalObjectives: Record<string, any>;\n  timestamp: string;\n}\n\n/**\n * SequencingStateManager\n *\n * Manages sequencing state persistence for the SCORM 2004 sequencing engine.\n * Extracted from OverallSequencingProcess to follow Single Responsibility Principle.\n *\n * Responsibilities:\n * - Get/Restore sequencing state for multi-session support\n * - Serialize/Deserialize activity states\n * - Get/Restore navigation state\n * - Get/Restore suspension state\n *\n * @spec SN Book: State Persistence\n */\nexport class SequencingStateManager {\n  private activityTree: ActivityTree;\n  private globalObjectiveService: GlobalObjectiveService;\n  private rollupProcess: RollupProcess;\n  private adlNav: ADLNav | null;\n  private eventCallback: ((eventType: string, data?: any) => void) | null;\n  private getEffectiveHideLmsUiCallback: ((activity: Activity | null) => HideLmsUiItem[]) | null =\n    null;\n  private getEffectiveAuxiliaryResourcesCallback:\n    ((activity: Activity | null) => AuxiliaryResource[]) | null = null;\n  private contentDeliveredGetter: (() => boolean) | null = null;\n  private contentDeliveredSetter: ((value: boolean) => void) | null = null;\n\n  constructor(\n    activityTree: ActivityTree,\n    globalObjectiveService: GlobalObjectiveService,\n    rollupProcess: RollupProcess,\n    adlNav: ADLNav | null = null,\n    eventCallback: ((eventType: string, data?: any) => void) | null = null,\n  ) {\n    this.activityTree = activityTree;\n    this.globalObjectiveService = globalObjectiveService;\n    this.rollupProcess = rollupProcess;\n    this.adlNav = adlNav;\n    this.eventCallback = eventCallback;\n  }\n\n  /**\n   * Set callback to get effective hideLmsUi\n   */\n  public setGetEffectiveHideLmsUiCallback(\n    callback: (activity: Activity | null) => HideLmsUiItem[],\n  ): void {\n    this.getEffectiveHideLmsUiCallback = callback;\n  }\n\n  /**\n   * Set callback to get effective auxiliary resources\n   */\n  public setGetEffectiveAuxiliaryResourcesCallback(\n    callback: (activity: Activity | null) => AuxiliaryResource[],\n  ): void {\n    this.getEffectiveAuxiliaryResourcesCallback = callback;\n  }\n\n  /**\n   * Set getter/setter for content delivered flag\n   */\n  public setContentDeliveredAccessors(\n    getter: () => boolean,\n    setter: (value: boolean) => void,\n  ): void {\n    this.contentDeliveredGetter = getter;\n    this.contentDeliveredSetter = setter;\n  }\n\n  /**\n   * Get Sequencing State for Persistence\n   * Returns the current state of the sequencing engine for multi-session support\n   * @return {SequencingState} - Serializable sequencing state\n   */\n  public getState(): SequencingState {\n    return {\n      version: \"1.0\",\n      timestamp: new Date().toISOString(),\n      contentDelivered: this.contentDeliveredGetter ? this.contentDeliveredGetter() : false,\n      currentActivity: this.activityTree.currentActivity?.id || null,\n      suspendedActivity: this.activityTree.suspendedActivity?.id || null,\n      activityStates: this.serializeActivities(),\n      navigationState: this.getNavigationState(),\n      globalObjectiveMap: this.globalObjectiveService.getSnapshot(),\n    };\n  }\n\n  /**\n   * Restore Sequencing State from Persistence\n   * Restores the sequencing engine state from a previous session\n   * @param {SequencingState} state - Previously saved sequencing state\n   * @return {boolean} - True if restoration was successful\n   */\n  public restoreState(state: SequencingState): boolean {\n    try {\n      if (!state || state.version !== \"1.0\") {\n        console.warn(\"Incompatible sequencing state version\");\n        return false;\n      }\n\n      // Restore basic flags\n      if (this.contentDeliveredSetter) {\n        this.contentDeliveredSetter(state.contentDelivered || false);\n      }\n\n      // Restore global objective map before applying local state so reads use persisted data\n      if (state.globalObjectiveMap) {\n        this.globalObjectiveService.restoreSnapshot(state.globalObjectiveMap);\n      }\n\n      // Restore activity states\n      if (state.activityStates) {\n        this.deserializeActivities(state.activityStates);\n      }\n\n      // Restore current activity. Explicit null clears a previously initialized\n      // pointer; undefined preserves compatibility with older partial states.\n      if (state.currentActivity) {\n        const currentActivity = this.activityTree.getActivity(state.currentActivity);\n        if (currentActivity) {\n          const currentActivityState = state.activityStates?.[state.currentActivity];\n          const isLegacySuspendedRootPointer =\n            currentActivity === this.activityTree.root &&\n            !!state.suspendedActivity &&\n            currentActivityState?.isActive === false &&\n            currentActivityState?.isSuspended === true;\n\n          // A pre-activityStates snapshot has no serialized flags to preserve, so retain the\n          // original setter behavior that activates the current activity and its ancestors.\n          if (isLegacySuspendedRootPointer) {\n            this.activityTree.setCurrentActivityWithoutActivation(null);\n          } else if (!state.activityStates) {\n            this.activityTree.currentActivity = currentActivity;\n            currentActivity.isActive = true;\n          } else {\n            // New snapshots must not reactivate an activity that was persisted as inactive,\n            // such as the suspended root after SUSPEND_ALL. Activity flags were restored above.\n            this.activityTree.setCurrentActivityWithoutActivation(currentActivity);\n            currentActivity.isActive = currentActivityState?.isActive ?? true;\n          }\n        }\n      } else if (state.currentActivity === null) {\n        this.activityTree.setCurrentActivityWithoutActivation(null);\n      }\n\n      // Restore suspended activity\n      if (state.suspendedActivity) {\n        const suspendedActivity = this.activityTree.getActivity(state.suspendedActivity);\n        if (suspendedActivity) {\n          this.activityTree.suspendedActivity = suspendedActivity;\n          suspendedActivity.isSuspended = true;\n        }\n      } else if (state.suspendedActivity === null) {\n        this.activityTree.suspendedActivity = null;\n      }\n\n      // Restore navigation state\n      if (state.navigationState) {\n        this.restoreNavigationState(state.navigationState);\n      }\n\n      // Re-run global objective synchronization to ensure map and activities align after restore\n      if (this.activityTree.root) {\n        this.globalObjectiveService.synchronize(this.activityTree.root, this.rollupProcess);\n      }\n\n      console.debug(\"Sequencing state restored successfully\");\n      return true;\n    } catch (error) {\n      console.error(`Failed to restore sequencing state: ${error}`);\n      return false;\n    }\n  }\n\n  /**\n   * Serialize Activity States\n   * Creates a serializable representation of all activity states\n   * @return {Record<string, ActivityStateData>} - Serialized activity states\n   */\n  private serializeActivities(): Record<string, ActivityStateData> {\n    const states: Record<string, ActivityStateData> = {};\n\n    const serializeActivity = (activity: Activity) => {\n      states[activity.id] = {\n        id: activity.id,\n        title: activity.title,\n        isActive: activity.isActive,\n        isSuspended: activity.isSuspended,\n        isCompleted: activity.isCompleted,\n        completionStatus: activity.completionStatus,\n        successStatus: activity.successStatus,\n        attemptCount: activity.attemptCount,\n        objectiveInfoAvailableInCurrentParentAttempt:\n          activity.objectiveInfoAvailableInCurrentParentAttempt,\n        progressInfoAvailableInCurrentParentAttempt:\n          activity.progressInfoAvailableInCurrentParentAttempt,\n        attemptCompletionAmount: activity.attemptCompletionAmount,\n        attemptCompletionAmountStatus: activity.attemptCompletionAmountStatus,\n        attemptAbsoluteDuration: activity.attemptAbsoluteDuration,\n        attemptExperiencedDuration: activity.attemptExperiencedDuration,\n        activityAbsoluteDuration: activity.activityAbsoluteDuration,\n        activityExperiencedDuration: activity.activityExperiencedDuration,\n        objectiveSatisfiedStatus: activity.objectiveSatisfiedStatus,\n        objectiveSatisfiedStatusKnown: activity.objectiveSatisfiedStatusKnown,\n        objectiveMeasureStatus: activity.objectiveMeasureStatus,\n        objectiveNormalizedMeasure: activity.objectiveNormalizedMeasure,\n        progressMeasure: activity.progressMeasure,\n        progressMeasureStatus: activity.progressMeasureStatus,\n        isAvailable: activity.isAvailable,\n        isHiddenFromChoice: activity.isHiddenFromChoice,\n        location: activity.location,\n        attemptAbsoluteStartTime: activity.attemptAbsoluteStartTime,\n        objectives: activity.getObjectiveStateSnapshot(),\n        auxiliaryResources: activity.auxiliaryResources,\n        selectionRandomizationState: {\n          selectionCountStatus: activity.sequencingControls.selectionCountStatus,\n          reorderChildren: activity.sequencingControls.reorderChildren,\n          childOrder: activity.children.map((child) => child.id),\n          selectedChildIds: activity.children\n            .filter((child) => child.isAvailable)\n            .map((child) => child.id),\n          hiddenFromChoiceChildIds: activity.children\n            .filter((child) => child.isHiddenFromChoice)\n            .map((child) => child.id),\n        },\n      };\n\n      // Recursively serialize children\n      for (const child of activity.children) {\n        serializeActivity(child);\n      }\n    };\n\n    if (this.activityTree.root) {\n      serializeActivity(this.activityTree.root);\n    }\n\n    return states;\n  }\n\n  /**\n   * Deserialize Activity States\n   * Restores activity states from serialized data\n   * @param {Record<string, ActivityStateData>} states - Serialized activity states\n   */\n  private deserializeActivities(states: Record<string, ActivityStateData>): void {\n    const restoreActivity = (activity: Activity) => {\n      const state = states[activity.id];\n      if (state) {\n        activity.isActive = state.isActive || false;\n        activity.isSuspended = state.isSuspended || false;\n        activity.isCompleted = state.isCompleted || false;\n        activity.completionStatus = state.completionStatus || \"unknown\";\n        activity.attemptCount = state.attemptCount || 0;\n        activity.objectiveInfoAvailableInCurrentParentAttempt =\n          state.objectiveInfoAvailableInCurrentParentAttempt ?? true;\n        activity.progressInfoAvailableInCurrentParentAttempt =\n          state.progressInfoAvailableInCurrentParentAttempt ?? true;\n        activity.attemptCompletionAmount = state.attemptCompletionAmount || 0;\n        activity.attemptCompletionAmountStatus = state.attemptCompletionAmountStatus ?? false;\n        activity.attemptAbsoluteDuration = state.attemptAbsoluteDuration || \"PT0H0M0S\";\n        activity.attemptExperiencedDuration = state.attemptExperiencedDuration || \"PT0H0M0S\";\n        activity.activityAbsoluteDuration = state.activityAbsoluteDuration || \"PT0H0M0S\";\n        activity.activityExperiencedDuration = state.activityExperiencedDuration || \"PT0H0M0S\";\n        activity.objectiveSatisfiedStatus = state.objectiveSatisfiedStatus || false;\n        // @spec SCORM 2004 4th Ed. SN TM.1: restoring a false value must not\n        // promote an unknown objective progress status to known-not-satisfied.\n        activity.objectiveSatisfiedStatusKnown =\n          state.objectiveSatisfiedStatusKnown ?? state.successStatus !== \"unknown\";\n        // The objective setter derives success as a side effect; serialized\n        // success is authoritative when restoring tracking state.\n        activity.successStatus = state.successStatus || \"unknown\";\n        activity.objectiveMeasureStatus = state.objectiveMeasureStatus || false;\n        activity.objectiveNormalizedMeasure = state.objectiveNormalizedMeasure || 0;\n        activity.progressMeasure = state.progressMeasure ?? 0;\n        activity.progressMeasureStatus = state.progressMeasureStatus || false;\n        activity.isAvailable = state.isAvailable !== false; // Default to true\n        activity.isHiddenFromChoice = state.isHiddenFromChoice === true;\n        activity.location = state.location || \"\";\n        activity.attemptAbsoluteStartTime = state.attemptAbsoluteStartTime || \"\";\n        if (Array.isArray(state.auxiliaryResources)) {\n          activity.auxiliaryResources = state.auxiliaryResources;\n        }\n        if (state.objectives) {\n          activity.applyObjectiveStateSnapshot(state.objectives);\n        }\n      }\n\n      // Recursively restore children\n      for (const child of activity.children) {\n        restoreActivity(child);\n      }\n\n      if (state?.selectionRandomizationState) {\n        const selectionState = state.selectionRandomizationState;\n        const sequencingControls = activity.sequencingControls;\n\n        if (selectionState.selectionCountStatus !== undefined) {\n          sequencingControls.selectionCountStatus = selectionState.selectionCountStatus;\n        }\n\n        if (selectionState.reorderChildren !== undefined) {\n          sequencingControls.reorderChildren = selectionState.reorderChildren;\n        }\n\n        if (selectionState.childOrder && selectionState.childOrder.length > 0) {\n          activity.setChildOrder(selectionState.childOrder);\n        }\n\n        const selectedSet = Array.isArray(selectionState.selectedChildIds)\n          ? new Set(selectionState.selectedChildIds)\n          : null;\n        const hiddenSet = Array.isArray(selectionState.hiddenFromChoiceChildIds)\n          ? new Set(selectionState.hiddenFromChoiceChildIds)\n          : null;\n\n        if (selectedSet || hiddenSet) {\n          for (const child of activity.children) {\n            if (selectedSet) {\n              const isSelected = selectedSet.has(child.id);\n              child.isAvailable = isSelected;\n              if (!hiddenSet) {\n                child.isHiddenFromChoice = !isSelected;\n              }\n            }\n\n            if (hiddenSet) {\n              child.isHiddenFromChoice = hiddenSet.has(child.id);\n            }\n          }\n        }\n\n        activity.setProcessedChildren(activity.children.filter((child) => child.isAvailable));\n      } else {\n        activity.resetProcessedChildren();\n      }\n    };\n\n    if (this.activityTree.root) {\n      restoreActivity(this.activityTree.root);\n    }\n  }\n\n  /**\n   * Get Navigation State\n   * Returns current navigation validity and ADL nav state\n   * @return {NavigationState | null} - Navigation state\n   */\n  private getNavigationState(): NavigationState | null {\n    if (!this.adlNav) {\n      return null;\n    }\n\n    const hideLmsUi = this.getEffectiveHideLmsUiCallback\n      ? this.getEffectiveHideLmsUiCallback(this.activityTree.currentActivity)\n      : [];\n\n    const auxiliaryResources = this.getEffectiveAuxiliaryResourcesCallback\n      ? this.getEffectiveAuxiliaryResourcesCallback(this.activityTree.currentActivity)\n      : [];\n\n    return {\n      request: this.adlNav.request || \"_none_\",\n      requestValid: {\n        continue: this.adlNav.request_valid?.continue || \"false\",\n        previous: this.adlNav.request_valid?.previous || \"false\",\n        // choice and jump are dynamically evaluated at runtime, so we store \"unknown\"\n        choice: \"unknown\",\n        jump: \"unknown\",\n        exit: this.adlNav.request_valid?.exit || \"false\",\n        exitAll: this.adlNav.request_valid?.exitAll || \"false\",\n        abandon: this.adlNav.request_valid?.abandon || \"false\",\n        abandonAll: this.adlNav.request_valid?.abandonAll || \"false\",\n        suspendAll: this.adlNav.request_valid?.suspendAll || \"false\",\n      },\n      hideLmsUi,\n      auxiliaryResources,\n    };\n  }\n\n  /**\n   * Restore Navigation State\n   * Restores ADL navigation state\n   * @param {NavigationState} navState - Navigation state to restore\n   */\n  private restoreNavigationState(navState: NavigationState): void {\n    if (!this.adlNav || !navState) {\n      return;\n    }\n\n    try {\n      // Restore navigation request validity\n      if (navState.requestValid) {\n        const requestValid = navState.requestValid;\n        this.adlNav.request_valid.continue = requestValid.continue || \"false\";\n        this.adlNav.request_valid.previous = requestValid.previous || \"false\";\n        // Note: choice and jump are class instances with dynamic behavior,\n        // they are evaluated at runtime based on the activity tree state,\n        // so we don't restore them from persisted state\n        this.adlNav.request_valid.exit = requestValid.exit || \"false\";\n        this.adlNav.request_valid.exitAll = requestValid.exitAll || \"false\";\n        this.adlNav.request_valid.abandon = requestValid.abandon || \"false\";\n        this.adlNav.request_valid.abandonAll = requestValid.abandonAll || \"false\";\n        this.adlNav.request_valid.suspendAll = requestValid.suspendAll || \"false\";\n      }\n    } catch (error) {\n      // Navigation properties might be read-only after initialization\n      console.warn(`Could not fully restore navigation state: ${error}`);\n    }\n  }\n\n  /**\n   * Get complete suspension state including activity tree and global objectives\n   * Captures all state needed to restore sequencing after suspend/resume\n   * @return {SuspensionState} - Complete suspension state\n   */\n  public getSuspensionState(): SuspensionState {\n    const state: SuspensionState = {\n      activityTree: this.activityTree.root ? this.activityTree.root.getSuspensionState() : null,\n      currentActivityId: this.activityTree.currentActivity?.id || null,\n      suspendedActivityId: this.activityTree.suspendedActivity?.id || null,\n      globalObjectives: this.globalObjectiveService.getSnapshot(),\n      timestamp: new Date().toISOString(),\n    };\n\n    this.fireEvent(\"onSuspensionStateCaptured\", {\n      hasActivityTree: !!state.activityTree,\n      currentActivityId: state.currentActivityId,\n      suspendedActivityId: state.suspendedActivityId,\n      globalObjectiveCount: Object.keys(state.globalObjectives).length,\n      timestamp: state.timestamp,\n    });\n\n    return state;\n  }\n\n  /**\n   * Restore complete suspension state including activity tree and global objectives\n   * Restores all state needed to resume from suspended state\n   * @param {SuspensionState} state - Suspension state to restore\n   */\n  public restoreSuspensionState(state: SuspensionState): void {\n    if (!state) {\n      this.fireEvent(\"onSuspensionStateRestoreError\", {\n        error: \"No suspension state provided\",\n        timestamp: new Date().toISOString(),\n      });\n      return;\n    }\n\n    try {\n      // Restore global objectives first\n      if (state.globalObjectives) {\n        this.globalObjectiveService.restoreSnapshot(state.globalObjectives);\n      }\n\n      // Restore activity tree state\n      if (state.activityTree && this.activityTree.root) {\n        this.activityTree.root.restoreSuspensionState(state.activityTree);\n      }\n\n      // Restore current and suspended activity references. Null is an explicit\n      // persisted value and must clear the pointer on an already initialized\n      // API; undefined remains the legacy \"not persisted\" value.\n      if (state.currentActivityId !== undefined) {\n        const currentActivity = state.currentActivityId\n          ? this.activityTree.getActivity(state.currentActivityId)\n          : null;\n        this.activityTree.currentActivity = currentActivity ?? null;\n      }\n\n      if (state.suspendedActivityId !== undefined) {\n        const suspendedActivity = state.suspendedActivityId\n          ? this.activityTree.getActivity(state.suspendedActivityId)\n          : null;\n        this.activityTree.suspendedActivity = suspendedActivity ?? null;\n      }\n\n      this.fireEvent(\"onSuspensionStateRestored\", {\n        currentActivityId: state.currentActivityId,\n        suspendedActivityId: state.suspendedActivityId,\n        globalObjectiveCount: state.globalObjectives\n          ? Object.keys(state.globalObjectives).length\n          : 0,\n        originalTimestamp: state.timestamp,\n        restoreTimestamp: new Date().toISOString(),\n      });\n    } catch (error) {\n      this.fireEvent(\"onSuspensionStateRestoreError\", {\n        error: error instanceof Error ? error.message : String(error),\n        timestamp: new Date().toISOString(),\n      });\n      throw error;\n    }\n  }\n\n  /**\n   * Fire a sequencing event\n   * @param {string} eventType - The type of event\n   * @param {any} data - Event data\n   */\n  private fireEvent(eventType: string, data?: any): void {\n    try {\n      if (this.eventCallback) {\n        this.eventCallback(eventType, data);\n      }\n    } catch (error) {\n      console.warn(`Failed to fire state manager event ${eventType}: ${error}`);\n    }\n  }\n}\n","import { ObjectiveEvaluationContext } from \"./objectives/objective_evaluation_context\";\nimport { Activity } from \"./activity\";\nimport { ActivityTree } from \"./activity_tree\";\nimport {\n  DeliveryRequestType,\n  SequencingProcess,\n  SequencingRequestType,\n} from \"./sequencing_process\";\nimport { RollupProcess } from \"./rollup_process\";\nimport { ADLNav } from \"../adl\";\nimport { CompletionStatus, SuccessStatus } from \"../../../constants/enums\";\nimport { AuxiliaryResource, HideLmsUiItem } from \"../../../types/sequencing_types\";\nimport { NavigationLookAhead, NavigationPredictions } from \"./navigation_look_ahead\";\n\n// Import extracted components\nimport {\n  TerminationHandler,\n  type TerminationResult,\n  type CMIDataForTransfer,\n} from \"./handlers/termination_handler\";\nimport {\n  DeliveryHandler,\n  DeliveryRequest,\n  type ContentActivityData,\n} from \"./handlers/delivery_handler\";\nimport {\n  NavigationValidityService,\n  NavigationRequestType,\n  type NavigationRequestResult,\n} from \"./services/navigation_validity_service\";\nimport { GlobalObjectiveService } from \"./services/global_objective_service\";\nimport {\n  SequencingStateManager,\n  type SequencingState,\n  type SuspensionState,\n} from \"./state/sequencing_state_manager\";\nimport { DeliveryValidator } from \"./validation/delivery_validator\";\n\n// Re-export types for backward compatibility\n// Using 'export type' for type-only exports since esbuild strips interfaces\nexport { NavigationRequestType, DeliveryRequest };\nexport type {\n  NavigationRequestResult,\n  CMIDataForTransfer,\n  ContentActivityData,\n  SequencingState,\n  SuspensionState,\n};\nexport type { TerminationResult as TerminationRequestResult };\n\n/**\n * Options for configuring the OverallSequencingProcess\n */\nexport interface OverallSequencingProcessOptions {\n  now?: () => Date;\n  enhancedDeliveryValidation?: boolean;\n  defaultHideLmsUi?: HideLmsUiItem[];\n  defaultAuxiliaryResources?: AuxiliaryResource[];\n  getCMIData?: () => CMIDataForTransfer;\n  is4thEdition?: boolean;\n}\n\n/**\n * Navigation state after NB.2.1 and TB.2.3 have run, but before SB.2.12 may\n * unload the current SCO and deliver another one.\n */\nexport interface PreparedNavigationRequest {\n  navigationRequest: NavigationRequestType;\n  navResult: NavigationRequestResult;\n  deliveryRequest: DeliveryRequest | null;\n  sessionEndReason: \"exit_all\" | \"abandon_all\" | \"suspend_all\" | null;\n}\n\n/**\n * Overall Sequencing Process\n *\n * Coordinates the overall execution of the SCORM 2004 sequencing loop.\n * This class has been refactored to delegate to specialized handlers and services:\n *\n * - TerminationHandler: Handles termination requests (EXIT, EXIT_ALL, SUSPEND_ALL, etc.)\n * - DeliveryHandler: Handles content delivery and environment setup\n * - NavigationValidityService: Validates navigation requests\n * - GlobalObjectiveService: Manages global objectives\n * - SequencingStateManager: Handles state persistence\n * - DeliveryValidator: Validates delivery preconditions\n *\n * @spec SN Book: OP.1 (Overall Sequencing Process)\n */\nexport class OverallSequencingProcess {\n  // Core dependencies\n  private activityTree: ActivityTree;\n  private sequencingProcess: SequencingProcess;\n  private rollupProcess: RollupProcess;\n  private adlNav: ADLNav | null;\n  private eventCallback: ((eventType: string, data?: any) => void) | null = null;\n\n  // Extracted services\n  private terminationHandler: TerminationHandler;\n  private deliveryHandler: DeliveryHandler;\n  private navigationValidityService: NavigationValidityService;\n  private globalObjectiveService: GlobalObjectiveService;\n  private stateManager: SequencingStateManager;\n  private deliveryValidator: DeliveryValidator;\n  private navigationLookAhead: NavigationLookAhead;\n\n  // Configuration\n  private enhancedDeliveryValidation: boolean;\n  private is4thEdition: boolean;\n\n  constructor(\n    activityTree: ActivityTree,\n    sequencingProcess: SequencingProcess,\n    rollupProcess: RollupProcess,\n    adlNav: ADLNav | null = null,\n    eventCallback: ((eventType: string, data?: any) => void) | null = null,\n    options?: OverallSequencingProcessOptions,\n  ) {\n    this.activityTree = activityTree;\n    this.sequencingProcess = sequencingProcess;\n    this.rollupProcess = rollupProcess;\n    this.adlNav = adlNav;\n    this.eventCallback = eventCallback;\n    this.enhancedDeliveryValidation = options?.enhancedDeliveryValidation === true;\n    this.is4thEdition = options?.is4thEdition || false;\n\n    // Initialize global objective service\n    this.globalObjectiveService = new GlobalObjectiveService(eventCallback || undefined);\n    this.globalObjectiveService.initialize(activityTree.root);\n\n    // Initialize delivery validator\n    // Build options object conditionally to satisfy exactOptionalPropertyTypes\n    const deliveryValidatorOptions: { now?: () => Date } = {};\n    if (options?.now) {\n      deliveryValidatorOptions.now = options.now;\n    }\n    this.deliveryValidator = new DeliveryValidator(\n      activityTree,\n      eventCallback,\n      deliveryValidatorOptions,\n      () => sequencingProcess.getRuleEngine(),\n    );\n\n    // Initialize termination handler\n    // Build options object conditionally to satisfy exactOptionalPropertyTypes\n    const terminationOptions: { getCMIData?: () => CMIDataForTransfer; is4thEdition?: boolean } =\n      {};\n    if (options?.getCMIData) {\n      terminationOptions.getCMIData = options.getCMIData;\n    }\n    if (options?.is4thEdition !== undefined) {\n      terminationOptions.is4thEdition = options.is4thEdition;\n    }\n    this.terminationHandler = new TerminationHandler(\n      activityTree,\n      sequencingProcess,\n      rollupProcess,\n      this.globalObjectiveService.getMap(),\n      eventCallback,\n      terminationOptions,\n    );\n\n    // Initialize delivery handler\n    // Build options object conditionally to satisfy exactOptionalPropertyTypes\n    const deliveryOptions: {\n      now?: () => Date;\n      defaultHideLmsUi?: HideLmsUiItem[];\n      defaultAuxiliaryResources?: AuxiliaryResource[];\n    } = {};\n    if (options?.now) {\n      deliveryOptions.now = options.now;\n    }\n    if (options?.defaultHideLmsUi) {\n      deliveryOptions.defaultHideLmsUi = options.defaultHideLmsUi;\n    }\n    if (options?.defaultAuxiliaryResources) {\n      deliveryOptions.defaultAuxiliaryResources = options.defaultAuxiliaryResources;\n    }\n    this.deliveryHandler = new DeliveryHandler(\n      activityTree,\n      rollupProcess,\n      this.globalObjectiveService.getMap(),\n      adlNav,\n      eventCallback,\n      deliveryOptions,\n    );\n\n    // Initialize navigation validity service\n    this.navigationValidityService = new NavigationValidityService(\n      activityTree,\n      sequencingProcess,\n      adlNav,\n      eventCallback,\n    );\n\n    // Initialize state manager\n    this.stateManager = new SequencingStateManager(\n      activityTree,\n      this.globalObjectiveService,\n      rollupProcess,\n      adlNav,\n      eventCallback,\n    );\n\n    // Use the shared navigation look-ahead from NavigationValidityService\n    // This ensures cache invalidation affects the same instance used for predictions\n    this.navigationLookAhead = this.navigationValidityService.getNavigationLookAhead();\n\n    // Set up cross-component callbacks\n    this.setupCallbacks();\n  }\n\n  /**\n   * Set up callbacks between components\n   */\n  private setupCallbacks(): void {\n    // Set up termination handler callbacks\n    this.terminationHandler.setInvalidateCacheCallback(() => {\n      this.navigationLookAhead.invalidateCache();\n    });\n\n    // @spec SCORM 2004 SN 4th Ed. SB.2.2 / SB.2.9 / DB.1.1 / SM.7 - project mapped objectives until delivery is accepted.\n    const evaluationContext = new ObjectiveEvaluationContext(\n      this.activityTree,\n      this.globalObjectiveService.getMap(),\n    );\n    this.sequencingProcess?.setActivityEvaluationCallback((activity, target) =>\n      evaluationContext.project(activity, target),\n    );\n\n    // Set up delivery handler callbacks\n    // @spec SCORM 2004 SN 4th Ed. DB.2 / UP.3 / UP.4 - commit old branch attempts once delivery succeeds.\n    this.deliveryHandler.setEndAttemptCallback((activity) =>\n      this.terminationHandler.endAttempt(activity),\n    );\n    this.deliveryHandler.setCheckActivityCallback((activity, target) =>\n      this.deliveryValidator.checkActivity(evaluationContext.project(activity, target)),\n    );\n    this.deliveryHandler.setInvalidateCacheCallback(() => {\n      this.navigationLookAhead.invalidateCache();\n    });\n    this.deliveryHandler.setUpdateNavigationValidityCallback(() => {\n      this.navigationValidityService.updateNavigationValidity();\n    });\n    this.deliveryHandler.setClearSuspendedActivityCallback(() => {\n      this.terminationHandler.clearSuspendedActivity();\n    });\n\n    // Set up delivery validator callbacks\n    this.deliveryValidator.setContentDeliveredGetter(() =>\n      this.deliveryHandler.hasContentBeenDelivered(),\n    );\n\n    // Set up navigation validity service callbacks\n    this.navigationValidityService.setGetEffectiveHideLmsUiCallback((activity) =>\n      this.deliveryHandler.getEffectiveHideLmsUi(activity),\n    );\n    this.navigationValidityService.setGetEffectiveAuxiliaryResourcesCallback((activity) =>\n      this.deliveryHandler.getEffectiveAuxiliaryResources(activity),\n    );\n\n    // Set up state manager callbacks\n    this.stateManager.setGetEffectiveHideLmsUiCallback((activity) =>\n      this.deliveryHandler.getEffectiveHideLmsUi(activity),\n    );\n    this.stateManager.setGetEffectiveAuxiliaryResourcesCallback((activity) =>\n      this.deliveryHandler.getEffectiveAuxiliaryResources(activity),\n    );\n    this.stateManager.setContentDeliveredAccessors(\n      () => this.deliveryHandler.hasContentBeenDelivered(),\n      (value) => this.deliveryHandler.setContentDelivered(value),\n    );\n  }\n\n  /**\n   * Overall Sequencing Process\n   * Main entry point for processing navigation requests\n   * @spec SN Book: OP.1 (Overall Sequencing Process)\n   * @param {NavigationRequestType} navigationRequest - The navigation request\n   * @param {string | null} targetActivityId - Target activity for choice/jump requests\n   * @param {string} exitType - The cmi.exit value (logout, normal, suspend, time-out, or empty)\n   * @return {DeliveryRequest} - The delivery request result\n   */\n  public processNavigationRequest(\n    navigationRequest: NavigationRequestType,\n    targetActivityId: string | null = null,\n    exitType?: string,\n  ): DeliveryRequest {\n    return this.completeNavigationRequest(\n      this.prepareNavigationRequest(navigationRequest, targetActivityId, exitType),\n    );\n  }\n\n  /**\n   * Run navigation validation and termination without starting the sequencing\n   * request that may unload or deliver content.\n   *\n   * @spec SCORM 2004 4th Ed. SN OP.1 steps 1.1-1.3 - termination precedes\n   *   sequencing and delivery.\n   */\n  public prepareNavigationRequest(\n    navigationRequest: NavigationRequestType,\n    targetActivityId: string | null = null,\n    exitType?: string,\n  ): PreparedNavigationRequest {\n    // Step 1: Navigation Request Process (NB.2.1)\n    const navResult = this.navigationValidityService.validateRequest(\n      navigationRequest,\n      targetActivityId,\n    );\n\n    if (!navResult.valid) {\n      return {\n        navigationRequest,\n        navResult,\n        deliveryRequest: new DeliveryRequest(false, null, navResult.exception),\n        sessionEndReason: null,\n      };\n    }\n\n    // Step 2: Termination Request Process (TB.2.3) if needed\n    if (navResult.terminationRequest) {\n      const hadSequencingRequest = !!navResult.sequencingRequest;\n      const termResult = this.terminationHandler.processTerminationRequest(\n        navResult.terminationRequest,\n        hadSequencingRequest,\n        exitType,\n      );\n\n      if (!termResult.valid) {\n        return {\n          navigationRequest,\n          navResult,\n          deliveryRequest: new DeliveryRequest(\n            false,\n            null,\n            termResult.exception || \"TB.2.3-1\",\n          ),\n          sessionEndReason: null,\n        };\n      }\n\n      // Per TB.2.3 Step 3.6/4.5: Post-condition sequencing request overrides navigation request\n      if (termResult.sequencingRequest !== null) {\n        if (hadSequencingRequest || termResult.sequencingRequest !== SequencingRequestType.EXIT) {\n          navResult.sequencingRequest = termResult.sequencingRequest;\n        }\n      }\n\n      // EXIT_ALL reached through an exit/post-condition cascade returns the EXIT\n      // sequencing request after it has already ended every activity attempt and\n      // cleared the current activity. Treat that pair as a terminal sequencing\n      // session instead of trying to process EXIT again without a current activity.\n      if (\n        termResult.terminationRequest === SequencingRequestType.EXIT_ALL &&\n        termResult.sequencingRequest === SequencingRequestType.EXIT\n      ) {\n        navResult.sequencingRequest = null;\n        return {\n          navigationRequest,\n          navResult,\n          deliveryRequest: null,\n          sessionEndReason: \"exit_all\",\n        };\n      }\n\n      // If this is a termination-only request (no sequencing request), return success\n      if (!navResult.sequencingRequest) {\n        const sessionEndReason =\n          navResult.terminationRequest === SequencingRequestType.EXIT_ALL\n            ? \"exit_all\"\n            : navResult.terminationRequest === SequencingRequestType.ABANDON_ALL\n              ? \"abandon_all\"\n              : navResult.terminationRequest === SequencingRequestType.SUSPEND_ALL\n                ? \"suspend_all\"\n                : null;\n        return {\n          navigationRequest,\n          navResult,\n          deliveryRequest: null,\n          sessionEndReason,\n        };\n      }\n    }\n\n    return {\n      navigationRequest,\n      navResult,\n      deliveryRequest: null,\n      sessionEndReason: null,\n    };\n  }\n\n  /**\n   * Finish a prepared navigation request with sequencing and delivery.\n   *\n   * @spec SCORM 2004 4th Ed. SN OP.1 steps 1.4-1.5 - sequencing and delivery\n   *   follow successful termination processing.\n   */\n  public completeNavigationRequest(prepared: PreparedNavigationRequest): DeliveryRequest {\n    const { navigationRequest, navResult } = prepared;\n\n    if (prepared.deliveryRequest) {\n      return prepared.deliveryRequest;\n    }\n\n    if (prepared.sessionEndReason) {\n      if (prepared.sessionEndReason === \"suspend_all\") {\n        // SUSPEND_ALL ends the current session while retaining the suspended\n        // activity path for RESUME_ALL in the next session. The root pointer\n        // installed by TB.2.3 is only an intermediate sequencing state and\n        // would make RESUME_ALL fail its currentActivity == null precondition.\n        this.activityTree.setCurrentActivityWithoutActivation(null);\n      }\n      this.fireEvent(\"onSequencingSessionEnd\", {\n        reason: prepared.sessionEndReason,\n        navigationRequest,\n      });\n      return new DeliveryRequest(true, null);\n    }\n\n    if (!navResult.sequencingRequest) {\n      return new DeliveryRequest(true, null);\n    }\n\n    // Step 3: Sequencing Request Process (SB.2.12)\n    const seqResult = this.sequencingProcess.sequencingRequestProcess(\n      navResult.sequencingRequest,\n      navResult.targetActivityId,\n    );\n\n    // OP.1 step 1.4.3: Check if sequencing session should end\n    if (seqResult.endSequencingSession) {\n      this.fireEvent(\"onSequencingSessionEnd\", {\n        reason: \"end_of_content\",\n        exception: seqResult.exception,\n        navigationRequest: navigationRequest,\n      });\n\n      // Reaching the end of forward flow successfully ends the sequencing session. The\n      // lower-level flow result may retain SB.2.7-2 to describe why no next activity was\n      // identified, but that diagnostic must not turn the successful session end into a\n      // learner-visible navigation failure.\n      return new DeliveryRequest(true, null);\n    }\n\n    if (seqResult.exception) {\n      return new DeliveryRequest(false, null, seqResult.exception);\n    }\n\n    if (seqResult.deliveryRequest === DeliveryRequestType.DELIVER && seqResult.targetActivity) {\n      // INTEGRATION: Validate rollup state consistency before delivery\n      if (this.activityTree.root) {\n        const isConsistent = this.rollupProcess.validateRollupStateConsistency(\n          this.activityTree.root,\n        );\n        if (!isConsistent) {\n          this.fireEvent(\"onSequencingDebug\", {\n            message: \"Rollup state inconsistency detected before delivery\",\n            activityId: this.activityTree.root.id,\n          });\n        }\n      }\n\n      // @spec SCORM 2004 SN 4th Ed. DB.1.1 / DB.2 - keep live objective mapping inside accepted delivery.\n      // Step 4: Delivery Request Process (DB.1.1)\n      return this.processDelivery(seqResult.targetActivity);\n    }\n\n    return new DeliveryRequest(false, null, \"OP.1-1\");\n  }\n\n  /**\n   * Process delivery of an activity\n   * @param {Activity} targetActivity - The activity to deliver\n   * @return {DeliveryRequest} - The delivery result\n   */\n  private processDelivery(targetActivity: Activity): DeliveryRequest {\n    // Enhanced delivery validation if enabled\n    if (this.enhancedDeliveryValidation) {\n      const stateCheck = this.deliveryValidator.validateTreeConsistency(targetActivity);\n      if (!stateCheck.consistent) {\n        return new DeliveryRequest(false, null, stateCheck.exception);\n      }\n\n      const resourceCheck = this.deliveryValidator.validateResources(targetActivity);\n      if (!resourceCheck.available) {\n        return new DeliveryRequest(false, null, resourceCheck.exception);\n      }\n\n      const concurrentCheck = this.deliveryValidator.validateConcurrentDelivery(targetActivity);\n      if (!concurrentCheck.allowed) {\n        return new DeliveryRequest(false, null, concurrentCheck.exception);\n      }\n\n      const dependencyCheck = this.deliveryValidator.validateDependencies(targetActivity);\n      if (!dependencyCheck.satisfied) {\n        return new DeliveryRequest(false, null, dependencyCheck.exception);\n      }\n    }\n\n    // Standard delivery request process\n    const deliveryResult = this.deliveryHandler.processDeliveryRequest(targetActivity);\n\n    if (deliveryResult.valid) {\n      // Step 5: Content Delivery Environment Process (DB.2)\n      this.deliveryHandler.contentDeliveryEnvironmentProcess(deliveryResult.targetActivity!);\n\n      // Invalidate navigation predictions after activity change\n      this.navigationLookAhead.invalidateCache();\n\n      // INTEGRATION: Validate rollup state consistency after delivery\n      if (this.activityTree.root) {\n        this.rollupProcess.validateRollupStateConsistency(this.activityTree.root);\n      }\n    }\n\n    return deliveryResult;\n  }\n\n  // ========== Public API Methods ==========\n\n  /**\n   * Check if content has been delivered\n   */\n  public hasContentBeenDelivered(): boolean {\n    return this.deliveryHandler.hasContentBeenDelivered();\n  }\n\n  /**\n   * Check if content delivery is currently in progress\n   */\n  public isDeliveryInProgress(): boolean {\n    return this.deliveryHandler.isDeliveryInProgress();\n  }\n\n  /**\n   * Reset content delivered flag\n   */\n  public resetContentDelivered(): void {\n    this.deliveryHandler.resetContentDelivered();\n  }\n\n  /**\n   * Set content delivered flag\n   * @param {boolean} value - The value to set\n   */\n  public setContentDelivered(value: boolean): void {\n    this.deliveryHandler.setContentDelivered(value);\n  }\n\n  /**\n   * Update navigation validity in ADL nav\n   */\n  public updateNavigationValidity(): void {\n    this.navigationValidityService.updateNavigationValidity();\n  }\n\n  /**\n   * Synchronize global objectives from activity states\n   */\n  public synchronizeGlobalObjectives(): void {\n    this.globalObjectiveService.synchronize(this.activityTree.root, this.rollupProcess);\n  }\n\n  /**\n   * Get the global objective map\n   * @return {Map<string, any>} - Current global objective map\n   */\n  public getGlobalObjectiveMap(): Map<string, any> {\n    return this.globalObjectiveService.getMap();\n  }\n\n  /**\n   * Get a snapshot of the global objective map\n   * @return {Record<string, any>} - Plain-object snapshot\n   */\n  public getGlobalObjectiveMapSnapshot(): Record<string, any> {\n    return this.globalObjectiveService.getSnapshot();\n  }\n\n  /**\n   * Restore global objective map from snapshot\n   * @param {Record<string, any>} snapshot - Snapshot to restore\n   */\n  public restoreGlobalObjectiveMapSnapshot(snapshot: Record<string, any>): void {\n    this.globalObjectiveService.restoreSnapshot(snapshot);\n  }\n\n  /**\n   * Update a specific global objective\n   * @param {string} objectiveId - Objective ID\n   * @param {any} objectiveData - New objective data\n   */\n  public updateGlobalObjective(objectiveId: string, objectiveData: any): void {\n    this.globalObjectiveService.updateObjective(objectiveId, objectiveData);\n  }\n\n  /**\n   * Get Sequencing State for Persistence\n   * @return {SequencingState} - Serializable sequencing state\n   */\n  public getSequencingState(): SequencingState {\n    return this.stateManager.getState();\n  }\n\n  /**\n   * Restore Sequencing State from Persistence\n   * @param {SequencingState} state - State to restore\n   * @return {boolean} - True if successful\n   */\n  public restoreSequencingState(state: SequencingState): boolean {\n    return this.stateManager.restoreState(state);\n  }\n\n  /**\n   * Get complete suspension state\n   * @return {SuspensionState} - Complete suspension state\n   */\n  public getSuspensionState(): SuspensionState {\n    return this.stateManager.getSuspensionState();\n  }\n\n  /**\n   * Restore complete suspension state\n   * @param {SuspensionState} state - Suspension state to restore\n   */\n  public restoreSuspensionState(state: SuspensionState): void {\n    this.stateManager.restoreSuspensionState(state);\n  }\n\n  /**\n   * Get navigation look-ahead predictions\n   * @return {NavigationPredictions} - Current navigation predictions\n   */\n  public getNavigationLookAhead(): NavigationPredictions {\n    return this.navigationValidityService.getAllPredictions();\n  }\n\n  /**\n   * Predict if Continue navigation would succeed\n   * @return {boolean} - True if Continue would succeed\n   */\n  public predictContinueEnabled(): boolean {\n    return this.navigationValidityService.predictContinueEnabled();\n  }\n\n  /**\n   * Predict if Previous navigation would succeed\n   * @return {boolean} - True if Previous would succeed\n   */\n  public predictPreviousEnabled(): boolean {\n    return this.navigationValidityService.predictPreviousEnabled();\n  }\n\n  /** Predict if jump to the target leaf would succeed. */\n  public predictJumpEnabled(activityId: string): boolean {\n    return this.navigationValidityService.predictJumpEnabled(activityId);\n  }\n\n  /**\n   * Predict if choice to specific activity would succeed\n   * @param {string} activityId - Target activity ID\n   * @return {boolean} - True if choice would succeed\n   */\n  public predictChoiceEnabled(activityId: string): boolean {\n    return this.navigationValidityService.predictChoiceEnabled(activityId);\n  }\n\n  /**\n   * Get list of all activities that can be chosen\n   * @return {string[]} - Array of activity IDs available for choice\n   */\n  public getAvailableChoices(): string[] {\n    return this.navigationValidityService.getAvailableChoices();\n  }\n\n  /**\n   * Invalidate navigation prediction cache\n   */\n  public invalidateNavigationCache(): void {\n    this.navigationValidityService.invalidateCache();\n  }\n\n  /**\n   * Apply delivery controls for auto-completion and auto-satisfaction\n   * @param {Activity} activity - The activity to apply delivery controls to\n   */\n  public applyDeliveryControls(activity: Activity): void {\n    // Auto-completion when completionSetByContent is false\n    if (!activity.sequencingControls.completionSetByContent) {\n      if (activity.completionStatus === CompletionStatus.UNKNOWN) {\n        activity.completionStatus = CompletionStatus.COMPLETED;\n        activity.wasAutoCompleted = true;\n      }\n    }\n\n    // Auto-satisfaction when objectiveSetByContent is false\n    if (!activity.sequencingControls.objectiveSetByContent) {\n      if (activity.successStatus === SuccessStatus.UNKNOWN) {\n        activity.successStatus = SuccessStatus.PASSED;\n        activity.wasAutoSatisfied = true;\n      }\n    }\n  }\n\n  /**\n   * Get effective hideLmsUi for an activity\n   * @param {Activity | null} activity - The activity\n   * @return {HideLmsUiItem[]} - Ordered list of hideLmsUi directives\n   */\n  public getEffectiveHideLmsUi(activity: Activity | null): HideLmsUiItem[] {\n    return this.deliveryHandler.getEffectiveHideLmsUi(activity);\n  }\n\n  /**\n   * Get effective auxiliary resources for an activity\n   * @param {Activity | null} activity - The activity\n   * @return {AuxiliaryResource[]} - Merged auxiliary resources\n   */\n  public getEffectiveAuxiliaryResources(activity: Activity | null): AuxiliaryResource[] {\n    return this.deliveryHandler.getEffectiveAuxiliaryResources(activity);\n  }\n\n  /**\n   * Get content activity data for a delivered activity\n   * @param {Activity} activity - The activity\n   * @return {ContentActivityData} - Content activity data\n   */\n  public getContentActivityData(activity: Activity): ContentActivityData {\n    return this.deliveryHandler.getContentActivityData(activity);\n  }\n\n  // ========== Backward Compatibility Delegations ==========\n  // These methods delegate to the extracted handlers for backward compatibility\n\n  /**\n   * Termination Request Process\n   * Delegates to TerminationHandler for backward compatibility\n   * @spec SN Book: TB.2.3 (Termination Request Process)\n   * @param {SequencingRequestType} request - The termination request\n   * @param {boolean} hasSequencingRequest - Whether a sequencing request follows\n   * @param {string} exitType - The cmi.exit value\n   * @return {TerminationResult} - Termination result with sequencing request\n   */\n  public terminationRequestProcess(\n    request: SequencingRequestType,\n    hasSequencingRequest: boolean,\n    exitType?: string,\n  ): TerminationResult {\n    return this.terminationHandler.processTerminationRequest(\n      request,\n      hasSequencingRequest,\n      exitType,\n    );\n  }\n\n  /**\n   * Content Delivery Environment Process\n   * Delegates to DeliveryHandler for backward compatibility\n   * @spec SN Book: DB.2 (Content Delivery Environment Process)\n   * @param {Activity} activity - The activity to initialize for delivery\n   */\n  public contentDeliveryEnvironmentProcess(activity: Activity): void {\n    this.deliveryHandler.contentDeliveryEnvironmentProcess(activity);\n  }\n\n  /**\n   * End Attempt Process\n   * Delegates to TerminationHandler for backward compatibility\n   * @spec SN Book: UP.4 (End Attempt Process)\n   * @param {Activity} activity - The activity whose attempt is ending\n   */\n  public endAttemptProcess(activity: Activity): void {\n    this.terminationHandler.endAttempt(activity);\n  }\n\n  /**\n   * Handle EXIT Termination\n   * Delegates to TerminationHandler for backward compatibility\n   * @param {Activity} currentActivity - The activity being terminated\n   * @param {boolean} hasSequencingRequest - Whether a sequencing request follows\n   * @return {TerminationResult} - The termination result\n   */\n  public handleExitTermination(\n    currentActivity: Activity,\n    hasSequencingRequest: boolean,\n  ): TerminationResult {\n    return this.terminationHandler.handleExitTermination(currentActivity, hasSequencingRequest);\n  }\n\n  /**\n   * Fire a sequencing event\n   * @param {string} eventType - The type of event\n   * @param {any} data - Event data\n   */\n  private fireEvent(eventType: string, data?: any): void {\n    try {\n      if (this.eventCallback) {\n        this.eventCallback(eventType, data);\n      }\n    } catch (error) {\n      console.warn(`Failed to fire sequencing event ${eventType}: ${error}`);\n    }\n  }\n}\n","import { BaseCMI } from \"../../common/base_cmi\";\nimport { Activity } from \"./activity\";\nimport { Scorm2004ValidationError } from \"../../../exceptions/scorm2004_exceptions\";\nimport { scorm2004_errors } from \"../../../constants/error_codes\";\n\n/**\n * Class representing the SCORM 2004 activity tree\n */\nexport class ActivityTree extends BaseCMI {\n  private _root: Activity | null = null;\n  private _currentActivity: Activity | null = null;\n  private _suspendedActivity: Activity | null = null;\n  private _activities: Map<string, Activity> = new Map();\n\n  /**\n   * Constructor for ActivityTree\n   */\n  constructor(root?: Activity) {\n    super(\"activityTree\");\n    if (root) {\n      this.root = root;\n    }\n  }\n\n  /**\n   * Called when the API has been initialized after the CMI has been created\n   */\n  override initialize() {\n    super.initialize();\n    if (this._root) {\n      this._root.initialize();\n    }\n  }\n\n  /**\n   * Called when the API needs to be reset\n   */\n  reset() {\n    this._initialized = false;\n    this._currentActivity = null;\n    this._suspendedActivity = null;\n    // Clear the activities map so it can be rebuilt\n    this._activities.clear();\n    if (this._root) {\n      this._root.reset();\n      // Re-populate the activities map with the root and its children\n      this._activities.set(this._root.id, this._root);\n      this._addActivitiesToMap(this._root);\n    }\n  }\n\n  /**\n   * Getter for root\n   * @return {Activity | null}\n   */\n  get root(): Activity | null {\n    return this._root;\n  }\n\n  /**\n   * Setter for root\n   * @param {Activity} root\n   */\n  set root(root: Activity | null) {\n    // noinspection SuspiciousTypeOfGuard\n    if (root !== null && !(root instanceof Activity)) {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".root\",\n        scorm2004_errors.TYPE_MISMATCH as number,\n      );\n    }\n    // Clear existing map when assigning a new root to avoid stale activities\n    this._activities.clear();\n    this._root = root;\n    if (root) {\n      this._activities.set(root.id, root);\n      this._addActivitiesToMap(root);\n    }\n  }\n\n  /**\n   * Recursively add activities to the activities map\n   * @param {Activity} activity\n   * @private\n   */\n  private _addActivitiesToMap(activity: Activity): void {\n    for (const child of activity.children) {\n      this._activities.set(child.id, child);\n      this._addActivitiesToMap(child);\n    }\n  }\n\n  /**\n   * Getter for currentActivity\n   * @return {Activity | null}\n   */\n  get currentActivity(): Activity | null {\n    return this._currentActivity;\n  }\n\n  /**\n   * Setter for currentActivity\n   * @param {Activity | null} activity\n   */\n  set currentActivity(activity: Activity | null) {\n    // noinspection SuspiciousTypeOfGuard\n    if (activity !== null && !(activity instanceof Activity)) {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".currentActivity\",\n        scorm2004_errors.TYPE_MISMATCH as number,\n      );\n    }\n\n    // Deactivate previous current activity and all its ancestors\n    if (this._currentActivity) {\n      this._currentActivity.isActive = false;\n      let ancestor = this._currentActivity.parent;\n      while (ancestor) {\n        ancestor.isActive = false;\n        ancestor = ancestor.parent;\n      }\n    }\n\n    this._currentActivity = activity;\n\n    // Set new current activity and mark all ancestors as active\n    if (activity) {\n      activity.isActive = true;\n      let ancestor = activity.parent;\n      while (ancestor) {\n        ancestor.isActive = true;\n        ancestor = ancestor.parent;\n      }\n    }\n  }\n\n  /**\n   * Set current activity without activating it\n   * This method is used when the sequencing process needs to update the current activity\n   * pointer without triggering the automatic activation behavior (e.g., after termination).\n   * Unlike the normal setter, this method only deactivates the old current activity (and\n   * non-shared ancestors) WITHOUT activating the new current activity.\n   * @param {Activity | null} activity - The activity to set as current\n   */\n  setCurrentActivityWithoutActivation(activity: Activity | null): void {\n    // noinspection SuspiciousTypeOfGuard\n    if (activity !== null && !(activity instanceof Activity)) {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".currentActivity\",\n        scorm2004_errors.TYPE_MISMATCH as number,\n      );\n    }\n\n    // Deactivate previous current activity, but NOT the new current activity\n    // or any shared ancestors (i.e., don't deactivate shared ancestors)\n    if (this._currentActivity) {\n      // Build set of activities to preserve (new current + its ancestors)\n      const activitiesToPreserve = new Set<Activity>();\n      if (activity) {\n        activitiesToPreserve.add(activity); // Include the new current itself!\n        let ancestor: Activity | null = activity.parent;\n        while (ancestor) {\n          activitiesToPreserve.add(ancestor);\n          ancestor = ancestor.parent;\n        }\n      }\n\n      // Deactivate old current\n      this._currentActivity.isActive = false;\n\n      // Deactivate old current's ancestors that are NOT in the preserve set\n      let ancestor = this._currentActivity.parent;\n      while (ancestor) {\n        if (!activitiesToPreserve.has(ancestor)) {\n          ancestor.isActive = false;\n        }\n        ancestor = ancestor.parent;\n      }\n    }\n\n    // Set new current activity WITHOUT activating it or its ancestors\n    // The caller is responsible for activation if needed\n    this._currentActivity = activity;\n  }\n\n  /**\n   * Getter for suspendedActivity\n   * @return {Activity | null}\n   */\n  get suspendedActivity(): Activity | null {\n    return this._suspendedActivity;\n  }\n\n  /**\n   * Setter for suspendedActivity\n   * @param {Activity | null} activity\n   */\n  set suspendedActivity(activity: Activity | null) {\n    // noinspection SuspiciousTypeOfGuard\n    if (activity !== null && !(activity instanceof Activity)) {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".suspendedActivity\",\n        scorm2004_errors.TYPE_MISMATCH as number,\n      );\n    }\n\n    // Unsuspend previous suspended activity and all its ancestors\n    if (this._suspendedActivity) {\n      this._suspendedActivity.isSuspended = false;\n      let ancestor = this._suspendedActivity.parent;\n      while (ancestor) {\n        ancestor.isSuspended = false;\n        ancestor = ancestor.parent;\n      }\n    }\n\n    this._suspendedActivity = activity;\n\n    // Set new suspended activity and mark all ancestors as suspended\n    if (activity) {\n      activity.isSuspended = true;\n      let ancestor = activity.parent;\n      while (ancestor) {\n        ancestor.isSuspended = true;\n        ancestor = ancestor.parent;\n      }\n    }\n  }\n\n  /**\n   * Get an activity by ID\n   * @param {string} id - The ID of the activity to get\n   * @return {Activity | null} - The activity with the given ID, or null if not found\n   */\n  getActivity(id: string): Activity | null {\n    return this._activities.get(id) || null;\n  }\n\n  /**\n   * Get all activities in the tree\n   * @return {Activity[]} - An array of all activities in the tree\n   */\n  getAllActivities(): Activity[] {\n    return Array.from(this._activities.values());\n  }\n\n  /**\n   * Get the parent of an activity\n   * @param {Activity} activity - The activity to get the parent of\n   * @return {Activity | null} - The parent of the activity, or null if it has no parent\n   */\n  getParent(activity: Activity): Activity | null {\n    return activity.parent;\n  }\n\n  /**\n   * Get the children of an activity\n   * @param {Activity} activity - The activity to get the children of\n   * @param {boolean} useAvailableChildren - Whether to use available children (with selection/randomization)\n   * @return {Activity[]} - An array of the activity's children\n   */\n  getChildren(activity: Activity, useAvailableChildren: boolean = true): Activity[] {\n    return useAvailableChildren ? activity.getAvailableChildren() : activity.children;\n  }\n\n  /**\n   * Get the siblings of an activity\n   * @param {Activity} activity - The activity to get the siblings of\n   * @return {Activity[]} - An array of the activity's siblings\n   */\n  getSiblings(activity: Activity): Activity[] {\n    if (!activity.parent) {\n      return [];\n    }\n    return activity.parent.children.filter((child) => child !== activity);\n  }\n\n  /**\n   * Get the next sibling of an activity\n   * @param {Activity} activity - The activity to get the next sibling of\n   * @param {boolean} useAvailableChildren - Whether to use available children (with selection/randomization)\n   * @return {Activity | null} - The next sibling of the activity, or null if it has no next sibling\n   */\n  getNextSibling(activity: Activity, useAvailableChildren: boolean = true): Activity | null {\n    if (!activity.parent) {\n      return null;\n    }\n    let siblings = useAvailableChildren \n      ? activity.parent.getAvailableChildren() \n      : activity.parent.children;\n    let index = siblings.indexOf(activity);\n    \n    // Fallback: if not found in available children, try raw children\n    if (index === -1 && useAvailableChildren) {\n      siblings = activity.parent.children;\n      index = siblings.indexOf(activity);\n    }\n    \n    if (index === -1 || index === siblings.length - 1) {\n      return null;\n    }\n    return siblings[index + 1] ?? null;\n  }\n\n  /**\n   * Get the previous sibling of an activity\n   * @param {Activity} activity - The activity to get the previous sibling of\n   * @param {boolean} useAvailableChildren - Whether to use available children (with selection/randomization)\n   * @return {Activity | null} - The previous sibling of the activity, or null if it has no previous sibling\n   */\n  getPreviousSibling(activity: Activity, useAvailableChildren: boolean = true): Activity | null {\n    if (!activity.parent) {\n      return null;\n    }\n    let siblings = useAvailableChildren \n      ? activity.parent.getAvailableChildren() \n      : activity.parent.children;\n    let index = siblings.indexOf(activity);\n    \n    // Fallback: if not found in available children, try raw children\n    if (index === -1 && useAvailableChildren) {\n      siblings = activity.parent.children;\n      index = siblings.indexOf(activity);\n    }\n    \n    if (index <= 0) {\n      return null;\n    }\n    return siblings[index - 1] ?? null;\n  }\n\n  /**\n   * Get the first child of an activity\n   * @param {Activity} activity - The activity to get the first child of\n   * @param {boolean} useAvailableChildren - Whether to use available children (with selection/randomization)\n   * @return {Activity | null} - The first child of the activity, or null if it has no children\n   */\n  getFirstChild(activity: Activity, useAvailableChildren: boolean = true): Activity | null {\n    const children = useAvailableChildren \n      ? activity.getAvailableChildren() \n      : activity.children;\n    if (children.length === 0) {\n      return null;\n    }\n    return children[0] ?? null;\n  }\n\n  /**\n   * Get the last child of an activity\n   * @param {Activity} activity - The activity to get the last child of\n   * @param {boolean} useAvailableChildren - Whether to use available children (with selection/randomization)\n   * @return {Activity | null} - The last child of the activity, or null if it has no children\n   */\n  getLastChild(activity: Activity, useAvailableChildren: boolean = true): Activity | null {\n    const children = useAvailableChildren \n      ? activity.getAvailableChildren() \n      : activity.children;\n    if (children.length === 0) {\n      return null;\n    }\n    return children[children.length - 1] ?? null;\n  }\n\n  /**\n   * Get the common ancestor of two activities\n   * @param {Activity} activity1 - The first activity\n   * @param {Activity} activity2 - The second activity\n   * @return {Activity | null} - The common ancestor of the two activities, or null if they have no common ancestor\n   */\n  getCommonAncestor(activity1: Activity, activity2: Activity): Activity | null {\n    // Get the path from the root to activity1\n    const path1: Activity[] = [];\n    let current: Activity | null = activity1;\n    while (current) {\n      path1.unshift(current);\n      current = current.parent;\n    }\n\n    // Check if activity2 is in the path from the root to activity1\n    current = activity2;\n    while (current) {\n      if (path1.includes(current)) {\n        return current;\n      }\n      current = current.parent;\n    }\n\n    return null;\n  }\n\n  /**\n   * toJSON for ActivityTree\n   * @return {object}\n   */\n  toJSON(): object {\n    this.jsonString = true;\n    const result = {\n      root: this._root,\n      currentActivity: this._currentActivity ? this._currentActivity.id : null,\n      suspendedActivity: this._suspendedActivity ? this._suspendedActivity.id : null,\n    };\n    this.jsonString = false;\n    return result;\n  }\n}\n","import { Activity, ActivityObjective } from \"../activity\";\nimport { ActivityTree } from \"../activity_tree\";\nimport { SequencingControls } from \"../sequencing_controls\";\nimport { RuleCondition, SequencingRule, SequencingRules } from \"../sequencing_rules\";\nimport { RollupCondition, RollupRule, RollupRules } from \"../rollup_rules\";\n\nconst modelPrototypes = new Set([\n  Object.prototype,\n  Activity.prototype,\n  ActivityObjective.prototype,\n  ActivityTree.prototype,\n  SequencingControls.prototype,\n  RuleCondition.prototype,\n  SequencingRule.prototype,\n  SequencingRules.prototype,\n  RollupCondition.prototype,\n  RollupRule.prototype,\n  RollupRules.prototype,\n]);\n\n/**\n * Copy engine-owned data without invoking serialization, getters or constructors.\n * Persistence snapshots intentionally omit transient tracking/dirty flags; preview\n * needs those too. Keep cyclic parent/current pointers and model methods, but never\n * copy host callbacks or unfamiliar objects into the speculative engine.\n */\nexport function clonePreviewState<T>(value: T): T {\n  const seen = new Map<object, any>();\n  const copy = (item: any): any => {\n    if (typeof item === \"function\") throw new Error(\"Preview cannot copy callbacks\");\n    if (item === null || typeof item !== \"object\") return item;\n    if (seen.has(item)) return seen.get(item);\n    const prototype = Object.getPrototypeOf(item);\n    if (\n      [Date.prototype, Map.prototype, Set.prototype].includes(prototype) &&\n      Reflect.ownKeys(item).length > 0\n    )\n      throw new Error(\"Preview cannot copy custom collection properties\");\n    if (prototype === Date.prototype) return new Date(Date.prototype.getTime.call(item));\n    if (prototype === Map.prototype) {\n      const result = new Map();\n      seen.set(item, result);\n      for (const [key, entry] of Map.prototype.entries.call(item))\n        result.set(copy(key), copy(entry));\n      return result;\n    }\n    if (prototype === Set.prototype) {\n      const result = new Set();\n      seen.set(item, result);\n      for (const entry of Set.prototype.values.call(item)) result.add(copy(entry));\n      return result;\n    }\n    if (prototype !== null && prototype !== Array.prototype && !modelPrototypes.has(prototype)) {\n      throw new Error(\"Preview cannot copy a custom model\");\n    }\n    const result = Array.isArray(item) ? [] : Object.create(prototype);\n    seen.set(item, result);\n    for (const key of Reflect.ownKeys(item)) {\n      const descriptor = Object.getOwnPropertyDescriptor(item, key)!;\n      if (!(\"value\" in descriptor)) throw new Error(\"Preview cannot copy accessors\");\n      Object.defineProperty(result, key, { ...descriptor, value: copy(descriptor.value) });\n    }\n    return result;\n  };\n  return copy(value);\n}\n","import { Activity } from \"../cmi/scorm2004/sequencing/activity\";\nimport { Sequencing } from \"../cmi/scorm2004/sequencing/sequencing\";\nimport { RollupProcess } from \"../cmi/scorm2004/sequencing/rollup_process\";\nimport { RollupClockOptions } from \"../cmi/scorm2004/sequencing/rollup/rollup_rule_evaluator\";\nimport {\n  DeliveryRequest,\n  NavigationRequestType,\n  OverallSequencingProcess,\n  type PreparedNavigationRequest,\n  type SequencingState,\n} from \"../cmi/scorm2004/sequencing/overall_sequencing_process\";\nimport {\n  DeliveryRequestType,\n  SequencingProcess,\n  SequencingResult,\n} from \"../cmi/scorm2004/sequencing/sequencing_process\";\nimport { IEventService, ILoggingService } from \"../interfaces/services\";\nimport { ActivityDeliveryCallbacks, ActivityDeliveryService } from \"./ActivityDeliveryService\";\nimport { CMI } from \"../cmi/scorm2004/cmi\";\nimport { CMIObjectivesObject } from \"../cmi/scorm2004/objectives\";\nimport { ADL } from \"../cmi/scorm2004/adl\";\nimport { global_constants } from \"../constants/api_constants\";\nimport { CompletionStatus, SuccessStatus } from \"../constants/enums\";\nimport { evaluateCompletionStatusFromThreshold } from \"../cmi/scorm2004/completion_status_evaluation\";\nimport { RuleCondition } from \"../cmi/scorm2004/sequencing/sequencing_rules\";\nimport { clonePreviewState } from \"../cmi/scorm2004/sequencing/utils/clone_preview_state\";\nimport {\n  AuxiliaryResource,\n  HideLmsUiItem,\n  SequencingEventListeners,\n  NavigationPreview,\n} from \"../types/sequencing_types\";\n\n/**\n * Interface for sequencing configuration\n */\nexport interface SequencingConfiguration {\n  autoRollupOnCMIChange?: boolean;\n  autoProgressOnCompletion?: boolean;\n  validateNavigationRequests?: boolean;\n  enableEventSystem?: boolean;\n  logLevel?: \"debug\" | \"info\" | \"warn\" | \"error\";\n  // Time providers/hooks (LMS can override)\n  now?: () => Date;\n  getAttemptElapsedSeconds?: (activity: Activity) => number;\n  getActivityElapsedSeconds?: (activity: Activity) => number;\n  wasCMIElementSetByContent?: (element: string) => boolean;\n}\n\nexport interface PreparedSequencingNavigation {\n  request: string;\n  operation: PreparedNavigationRequest;\n  rollbackState: SequencingState;\n}\n\n/**\n * Comprehensive SCORM 2004 Sequencing Service\n * Handles all aspects of sequencing integration with runtime API calls\n */\nexport class SequencingService {\n  private sequencing: Sequencing;\n  private cmi: CMI;\n  private adl: ADL;\n  private eventService: IEventService;\n  private loggingService: ILoggingService;\n  private activityDeliveryService: ActivityDeliveryService;\n  private rollupProcess: RollupProcess;\n  private overallSequencingProcess: OverallSequencingProcess | null = null;\n  private sequencingProcess: SequencingProcess | null = null;\n\n  private eventListeners: SequencingEventListeners = {};\n  private configuration: SequencingConfiguration;\n  private isInitialized: boolean = false;\n  private navigationPreviewConfiguration: SequencingConfiguration | null = null;\n  private isSequencingActive: boolean = false;\n  private deliveryNotificationsInProgress: boolean = false;\n  private lastCMIValues: Map<string, any> = new Map();\n  private lastSequencingResult: SequencingResult | null = null;\n\n  constructor(\n    sequencing: Sequencing,\n    cmi: CMI,\n    adl: ADL,\n    eventService: IEventService,\n    loggingService: ILoggingService,\n    configuration: SequencingConfiguration = {},\n  ) {\n    this.sequencing = sequencing;\n    this.cmi = cmi;\n    this.adl = adl;\n    this.eventService = eventService;\n    this.loggingService = loggingService;\n\n    // Default configuration\n    this.configuration = {\n      autoRollupOnCMIChange: false,\n      autoProgressOnCompletion: false,\n      validateNavigationRequests: true,\n      enableEventSystem: true,\n      logLevel: \"info\",\n      now: () => new Date(),\n      ...configuration,\n    };\n\n    // Create activity delivery service\n    const deliveryCallbacks: ActivityDeliveryCallbacks = {\n      onDeliverActivity: (activity) => this.handleActivityDelivery(activity),\n      onUnloadActivity: (activity) => this.handleActivityUnload(activity),\n      onSequencingComplete: (result) => this.handleSequencingComplete(result),\n      onSequencingError: (error) => this.handleSequencingError(error),\n    };\n\n    this.activityDeliveryService = new ActivityDeliveryService(\n      eventService,\n      loggingService,\n      deliveryCallbacks,\n    );\n\n    this.rollupProcess = new RollupProcess(undefined, this.rollupClock());\n    // Propagate time provider to rule evaluation (time-based conditions)\n    if (this.configuration.now) {\n      RuleCondition.setNowProvider(this.configuration.now);\n    }\n    this.setupCMIChangeWatchers();\n\n    // Create sequencing processes immediately so navigation requests work before SCO Initialize\n    this.createSequencingProcesses();\n  }\n\n  /**\n   * The clock time-based rollup conditions (timeLimitExceeded,\n   * outsideAvailableTimeRange) are evaluated with: the configured `now` and\n   * `getAttemptElapsedSeconds`, the same ones the sequencing rules use.\n   * Without an argument the providers are read from the current configuration\n   * on every evaluation, so `updateConfiguration()` reaches the live rollup\n   * process; the navigation preview passes its own snapshot.\n   * @param {SequencingConfiguration} [configuration] - A fixed configuration to read\n   * @return {RollupClockOptions}\n   */\n  private rollupClock(configuration?: SequencingConfiguration): RollupClockOptions {\n    const current = (): SequencingConfiguration => configuration ?? this.configuration;\n    return {\n      now: () => (current().now ?? (() => new Date()))(),\n      // NaN when no hook is configured: the time-limit check then falls back to\n      // the activity's recorded durations, as it does without a hook.\n      getAttemptElapsedSeconds: (activity) =>\n        current().getAttemptElapsedSeconds?.(activity) ?? Number.NaN,\n    };\n  }\n\n  /**\n   * Create sequencing processes\n   * Called from constructor to enable navigation before SCO Initialize\n   * @spec SCORM 2004 4th Ed. SN OP.1; RTE 3.1.6 - sequencing can precede Initialize.\n   */\n  private createSequencingProcesses(): void {\n    try {\n      // Initialize sequencing components if not already done\n      if (!this.sequencing.initialized) {\n        this.sequencing.initialize();\n      }\n\n      this.navigationPreviewConfiguration = this.configuration;\n\n      // Set up ADL Nav connection\n      this.sequencing.adlNav = this.adl.nav;\n\n      // Create sequencing processes if we have an activity tree\n      if (this.sequencing.activityTree.root) {\n        const seqOptions: {\n          now?: () => Date;\n          getAttemptElapsedSeconds?: (a: Activity) => number;\n          getActivityElapsedSeconds?: (a: Activity) => number;\n        } = {};\n        if (this.configuration.now) seqOptions.now = this.configuration.now;\n        if (this.configuration.getAttemptElapsedSeconds)\n          seqOptions.getAttemptElapsedSeconds = this.configuration.getAttemptElapsedSeconds;\n        if (this.configuration.getActivityElapsedSeconds)\n          seqOptions.getActivityElapsedSeconds = this.configuration.getActivityElapsedSeconds;\n\n        this.sequencingProcess = new SequencingProcess(\n          this.sequencing.activityTree,\n          this.sequencing.sequencingRules,\n          this.sequencing.sequencingControls,\n          this.adl.nav,\n          seqOptions,\n        );\n\n        const overallOptions: {\n          now?: () => Date;\n          enhancedDeliveryValidation?: boolean;\n          defaultHideLmsUi?: HideLmsUiItem[];\n          defaultAuxiliaryResources?: AuxiliaryResource[];\n          getCMIData?: () => any;\n          is4thEdition?: boolean;\n        } = {};\n        if (this.configuration.now) overallOptions.now = this.configuration.now;\n        overallOptions.defaultHideLmsUi = [...this.sequencing.hideLmsUi];\n        if (this.sequencing.auxiliaryResources.length > 0) {\n          overallOptions.defaultAuxiliaryResources = this.sequencing.auxiliaryResources.map(\n            (resource) => ({\n              resourceId: resource.resourceId,\n              purpose: resource.purpose,\n            }),\n          );\n        }\n\n        // @spec SCORM 2004 4th Ed. RTE 3.1.6 - transfer only initialized SCO data;\n        // asset delivery and an early Suspend All may have no RTE session.\n        overallOptions.getCMIData = () =>\n          this.cmi.initialized ? this.getCMIDataForTransfer() : null;\n\n        this.overallSequencingProcess = new OverallSequencingProcess(\n          this.sequencing.activityTree,\n          this.sequencingProcess,\n          this.rollupProcess,\n          this.adl.nav,\n          (eventType: string, data?: any) => this.handleSequencingProcessEvent(eventType, data),\n          overallOptions,\n        );\n\n        // Store reference on sequencing object for access from ADL nav\n        this.sequencing.overallSequencingProcess = this.overallSequencingProcess;\n\n        // Mark as initialized so navigation requests work\n        this.isInitialized = true;\n\n        this.log(\"info\", \"Sequencing processes created and ready for navigation\");\n      }\n    } catch (error) {\n      this.log(\"error\", `Failed to create sequencing processes: ${error}`);\n    }\n  }\n\n  /**\n   * Initialize the sequencing service\n   * Called when SCORM API Initialize() is called\n   * Note: Sequencing processes are created in constructor to enable pre-SCO navigation\n   */\n  public initialize(): string {\n    try {\n      this.log(\"info\", \"Initializing sequencing service for SCO session\");\n\n      // Ensure processes are created (should already be done in constructor)\n      if (!this.isInitialized) {\n        this.createSequencingProcesses();\n      }\n\n      // Start automatic sequencing if configured and not already started\n      if (this.shouldAutoStartSequencing() && !this.isSequencingActive) {\n        this.startSequencing();\n      }\n\n      // Initialize CMI tracking for the current activity\n      this.initializeCMITracking();\n      this.fireEvent(\"onSequencingStart\", this.sequencing.getCurrentActivity());\n\n      this.log(\"info\", \"Sequencing service initialized successfully\");\n      return global_constants.SCORM_TRUE;\n    } catch (error) {\n      const errorMsg = `Failed to initialize sequencing service: ${error}`;\n      this.log(\"error\", errorMsg);\n      this.fireEvent(\"onSequencingError\", errorMsg, \"initialization\");\n      return global_constants.SCORM_FALSE;\n    }\n  }\n\n  /**\n   * Terminate the sequencing service\n   * Called when SCORM API Terminate() is called\n   */\n  public terminate(): string {\n    try {\n      this.log(\"info\", \"Terminating sequencing service\");\n\n      // Trigger final rollup for the current activity\n      this.triggerFinalRollup();\n\n      // End sequencing session\n      this.endSequencing();\n\n      this.isInitialized = false;\n      this.fireEvent(\"onSequencingEnd\");\n\n      this.log(\"info\", \"Sequencing service terminated successfully\");\n      return global_constants.SCORM_TRUE;\n    } catch (error) {\n      const errorMsg = `Failed to terminate sequencing service: ${error}`;\n      this.log(\"error\", errorMsg);\n      this.fireEvent(\"onSequencingError\", errorMsg, \"termination\");\n      return global_constants.SCORM_FALSE;\n    }\n  }\n\n  /**\n   * Process a navigation request\n   * Implements the complete Overall Sequencing Process (OP.1)\n   * @param {string} request - The navigation request\n   * @param {string} targetActivityId - Optional target activity ID for choice/jump requests\n   * @param {string} exitType - Optional cmi.exit value (logout, normal, suspend, time-out, or empty)\n   */\n  public processNavigationRequest(\n    request: string,\n    targetActivityId?: string,\n    exitType?: string,\n  ): boolean {\n    const prepared = this.prepareNavigationRequest(request, targetActivityId, exitType);\n    return prepared ? this.completeNavigationRequest(prepared) : false;\n  }\n\n  /**\n   * Evaluate host flow navigation on isolated live tracking data. No runtime\n   * termination, host events, persistence or delivery callbacks are performed.\n   * @spec SCORM 2004 SN OP.1 / TB.2.3 / UP.4 / SB.2.2 - End Attempt and\n   * objective transfer must precede checking the next activity's preconditions.\n   */\n  public previewNavigationRequest(request: \"continue\" | \"previous\"): NavigationPreview {\n    const unknown: NavigationPreview = {\n      outcome: \"unknown\",\n      targetActivityId: null,\n      endSequencingSession: false,\n      exception: null,\n    };\n    if (\n      !this.isInitialized ||\n      !this.overallSequencingProcess ||\n      this.isDeliveryInProgress() ||\n      !this.sequencing.activityTree.currentActivity?.isActive ||\n      (request !== \"continue\" && request !== \"previous\")\n    )\n      return unknown;\n\n    try {\n      const configuration = this.navigationPreviewConfiguration!;\n      const tree = clonePreviewState(this.sequencing.activityTree);\n      // A speculative draw must not consume randomness or promise an outcome\n      // that a later real draw can change. Existing deterministic order is copied.\n      const pending = tree.root ? [tree.root] : [];\n      while (pending.length) {\n        const activity = pending.pop()!;\n        const controls = activity.sequencingControls;\n        if (\n          (controls.randomizeChildren && controls.randomizationTiming !== \"never\") ||\n          (controls.selectCount !== null && controls.selectionTiming !== \"never\")\n        ) {\n          return unknown;\n        }\n        pending.push(...activity.children);\n      }\n      const process = new SequencingProcess(tree, null, null, null, {\n        ...(configuration.now ? { now: configuration.now } : {}),\n        ...(configuration.getAttemptElapsedSeconds\n          ? { getAttemptElapsedSeconds: configuration.getAttemptElapsedSeconds }\n          : {}),\n        ...(configuration.getActivityElapsedSeconds\n          ? { getActivityElapsedSeconds: configuration.getActivityElapsedSeconds }\n          : {}),\n      });\n      const cmiData = this.getCMIDataForTransfer();\n      let ended = false;\n      const preview = new OverallSequencingProcess(\n        tree,\n        process,\n        new RollupProcess(undefined, this.rollupClock(configuration)),\n        null,\n        (event) => {\n          if (event === \"onSequencingSessionEnd\") ended = true;\n        },\n        {\n          getCMIData: () => cmiData,\n          ...(configuration.now ? { now: configuration.now } : {}),\n          defaultHideLmsUi: clonePreviewState(this.sequencing.hideLmsUi),\n          defaultAuxiliaryResources: clonePreviewState(this.sequencing.auxiliaryResources),\n        },\n      );\n      // Copy the map directly, retaining field-level known/dirty metadata without\n      // a persistence restore's normalization or synchronization side effects.\n      preview.getGlobalObjectiveMap().clear();\n      for (const [id, value] of this.overallSequencingProcess.getGlobalObjectiveMap()) {\n        preview.getGlobalObjectiveMap().set(id, clonePreviewState(value));\n      }\n      preview.setContentDelivered(this.overallSequencingProcess.hasContentBeenDelivered());\n      const result = preview.processNavigationRequest(\n        request === \"continue\" ? NavigationRequestType.CONTINUE : NavigationRequestType.PREVIOUS,\n        null,\n        this.cmi.getExitValueInternal() || \"\",\n      );\n      return {\n        outcome: result.valid ? \"allowed\" : \"blocked\",\n        targetActivityId: result.targetActivity?.id ?? null,\n        endSequencingSession: ended,\n        exception: result.exception ?? null,\n      };\n    } catch {\n      // Unsupported/custom state must not lock the learner out or alter API errors.\n      return unknown;\n    }\n  }\n\n  /**\n   * Run the navigation and termination phases without unloading or delivering a SCO.\n   *\n   * @spec SCORM 2004 4th Ed. SN OP.1 steps 1.1-1.3\n   */\n  public prepareNavigationRequest(\n    request: string,\n    targetActivityId?: string,\n    exitType?: string,\n  ): PreparedSequencingNavigation | null {\n    if (!this.isInitialized || !this.overallSequencingProcess) {\n      this.log(\"warn\", `Navigation request '${request}' ignored - sequencing not initialized`);\n      return null;\n    }\n\n    try {\n      this.log(\n        \"info\",\n        `Processing navigation request: ${request}${targetActivityId ? ` (target: ${targetActivityId})` : \"\"}${exitType ? ` (exit: ${exitType})` : \"\"}`,\n      );\n\n      // Fire navigation request event\n      this.fireEvent(\"onNavigationRequest\", request, targetActivityId);\n\n      // Parse the request to NavigationRequestType\n      const navRequestType = this.parseNavigationRequest(request);\n      if (navRequestType === null) {\n        this.log(\"warn\", `Invalid navigation request: ${request}`);\n        return null;\n      }\n\n      const rollbackState = this.overallSequencingProcess.getSequencingState();\n      const operation = this.overallSequencingProcess.prepareNavigationRequest(\n        navRequestType,\n        targetActivityId || null,\n        exitType,\n      );\n\n      return { request, operation, rollbackState };\n    } catch (error) {\n      const errorMsg = `Error preparing navigation request '${request}': ${error}`;\n      this.log(\"error\", errorMsg);\n      this.fireEvent(\"onSequencingError\", errorMsg, \"navigation\");\n      return null;\n    }\n  }\n\n  /**\n   * Run sequencing and delivery for a previously prepared navigation request.\n   *\n   * @spec SCORM 2004 4th Ed. SN OP.1 steps 1.4-1.5\n   */\n  public completeNavigationRequest(prepared: PreparedSequencingNavigation): boolean {\n    if (!this.overallSequencingProcess) {\n      return false;\n    }\n\n    try {\n      const deliveryRequest = this.overallSequencingProcess.completeNavigationRequest(\n        prepared.operation,\n      );\n      return this.handleNavigationDeliveryRequest(prepared.request, deliveryRequest);\n    } catch (error) {\n      const errorMsg = `Error completing navigation request '${prepared.request}': ${error}`;\n      this.log(\"error\", errorMsg);\n      this.fireEvent(\"onSequencingError\", errorMsg, \"navigation\");\n      return false;\n    }\n  }\n\n  /** Restore the tracking state when the runtime termination commit fails. */\n  public cancelPreparedNavigation(prepared: PreparedSequencingNavigation): void {\n    this.overallSequencingProcess?.restoreSequencingState(prepared.rollbackState);\n  }\n\n  private handleNavigationDeliveryRequest(\n    request: string,\n    deliveryRequest: DeliveryRequest,\n  ): boolean {\n    const sequencingResult: SequencingResult = {\n      deliveryRequest: deliveryRequest.valid\n        ? DeliveryRequestType.DELIVER\n        : DeliveryRequestType.DO_NOT_DELIVER,\n      targetActivity: deliveryRequest.targetActivity,\n      exception: deliveryRequest.exception || null,\n      endSequencingSession: false,\n    };\n\n    // Store the result\n    this.lastSequencingResult = sequencingResult;\n\n    // Handle the delivery request\n    if (deliveryRequest.valid && deliveryRequest.targetActivity) {\n      // Old content may synchronously Terminate from unload notifications after DB.2.\n      const wasInProgress = this.deliveryNotificationsInProgress;\n      this.deliveryNotificationsInProgress = true;\n      try {\n        this.activityDeliveryService.processSequencingResult(sequencingResult);\n        this.overallSequencingProcess?.updateNavigationValidity();\n      } finally {\n        this.deliveryNotificationsInProgress = wasInProgress;\n      }\n\n      this.log(\n        \"info\",\n        `Navigation request '${request}' resulted in activity delivery: ${deliveryRequest.targetActivity.id}`,\n      );\n      return true;\n    } else {\n      // No delivery requested or invalid\n      // End Attempt may have changed global objectives and therefore the\n      // validity of choice requests even when sequencing rejects the request\n      // or has no activity to deliver. Keep the current activity pointer in\n      // place, but refresh the derived navigation state for the LMS/UI.\n      this.overallSequencingProcess?.updateNavigationValidity();\n\n      if (deliveryRequest.exception) {\n        this.log(\"warn\", `Navigation request '${request}' failed: ${deliveryRequest.exception}`);\n        this.fireEvent(\"onSequencingError\", deliveryRequest.exception, \"navigation\");\n      } else {\n        this.log(\"info\", `Navigation request '${request}' completed with no activity delivery`);\n      }\n      return deliveryRequest.valid;\n    }\n  }\n\n  /**\n   * Trigger rollup when CMI values change\n   * Called automatically when tracked CMI values are updated\n   */\n  public triggerRollupOnCMIChange(cmiElement: string, oldValue: any, newValue: any): void {\n    if (!this.configuration.autoRollupOnCMIChange || !this.isInitialized) {\n      return;\n    }\n\n    // Only trigger rollup for specific CMI elements that affect sequencing\n    const rollupTriggeringElements = [\n      \"cmi.completion_status\",\n      \"cmi.success_status\",\n      \"cmi.score.scaled\",\n      \"cmi.score.raw\",\n      \"cmi.score.min\",\n      \"cmi.score.max\",\n      \"cmi.progress_measure\",\n      \"cmi.objectives.n.success_status\",\n      \"cmi.objectives.n.completion_status\",\n      \"cmi.objectives.n.score.scaled\",\n    ];\n\n    if (!rollupTriggeringElements.some((element) => cmiElement.startsWith(element))) {\n      return;\n    }\n\n    try {\n      this.log(\n        \"debug\",\n        `Triggering rollup due to CMI change: ${cmiElement} = ${newValue} (was ${oldValue})`,\n      );\n\n      // Get current activity\n      const currentActivity = this.sequencing.getCurrentActivity();\n      if (!currentActivity) {\n        this.log(\"debug\", \"No current activity for rollup\");\n        return;\n      }\n\n      // Update activity status based on CMI changes\n      this.updateActivityFromCMI(currentActivity);\n\n      // Trigger rollup process\n      this.rollupProcess.overallRollupProcess(currentActivity);\n\n      // Synchronize global objectives after rollup (required for cross-activity preconditions)\n      if (this.overallSequencingProcess) {\n        this.overallSequencingProcess.synchronizeGlobalObjectives();\n      }\n\n      // Update navigation validity after rollup (preconditions may have changed)\n      if (this.overallSequencingProcess) {\n        this.overallSequencingProcess.updateNavigationValidity();\n      }\n\n      this.fireEvent(\"onRollupComplete\", currentActivity);\n\n      this.log(\"debug\", `Rollup completed for activity: ${currentActivity.id}`);\n    } catch (error) {\n      const errorMsg = `Error during rollup on CMI change: ${error}`;\n      this.log(\"error\", errorMsg);\n      this.fireEvent(\"onSequencingError\", errorMsg, \"rollup\");\n    }\n  }\n\n  /**\n   * Set event listeners for sequencing events\n   */\n  public setEventListeners(listeners: SequencingEventListeners): void {\n    this.eventListeners = { ...this.eventListeners, ...listeners };\n    this.log(\"debug\", \"Sequencing event listeners updated\");\n  }\n\n  /**\n   * Update sequencing configuration\n   */\n  public updateConfiguration(config: Partial<SequencingConfiguration>): void {\n    this.configuration = { ...this.configuration, ...config };\n    // Keep running processes on the configured time providers, so sequencing\n    // and rollup rules keep reading the same clock. The sequencing process\n    // holds its own copies and the navigation preview works from a snapshot;\n    // the live rollup process reads the configuration (see rollupClock).\n    if (this.sequencingProcess) {\n      if (\"now\" in config) {\n        // Clearing `now` returns to the system clock, as rollup does.\n        this.sequencingProcess.now = config.now ?? (() => new Date());\n      }\n      if (\"getAttemptElapsedSeconds\" in config) {\n        this.sequencingProcess.getAttemptElapsedSecondsHook = config.getAttemptElapsedSeconds;\n      }\n    }\n    if (this.navigationPreviewConfiguration) {\n      this.navigationPreviewConfiguration = this.configuration;\n    }\n    this.log(\"debug\", \"Sequencing configuration updated\");\n  }\n\n  /**\n   * Get the current sequencing state\n   */\n  public getSequencingState(): {\n    isInitialized: boolean;\n    isActive: boolean;\n    currentActivity: Activity | null;\n    rootActivity: Activity | null;\n    lastSequencingResult: SequencingResult | null;\n  } {\n    return {\n      isInitialized: this.isInitialized,\n      isActive: this.isSequencingActive,\n      currentActivity: this.sequencing.getCurrentActivity(),\n      rootActivity: this.sequencing.getRootActivity(),\n      lastSequencingResult: this.lastSequencingResult,\n    };\n  }\n\n  /**\n   * Get the overall sequencing process instance\n   * @return {OverallSequencingProcess | null} The overall sequencing process or null if not initialized\n   */\n  public getOverallSequencingProcess(): OverallSequencingProcess | null {\n    return this.overallSequencingProcess;\n  }\n\n  /**\n   * Check if content delivery is currently in progress\n   * Used to prevent re-entrant termination requests during delivery\n   * @return {boolean} True if delivery is in progress\n   */\n  public isDeliveryInProgress(): boolean {\n    return (\n      this.deliveryNotificationsInProgress ||\n      (this.overallSequencingProcess?.isDeliveryInProgress() ?? false)\n    );\n  }\n\n  // Private helper methods\n\n  /**\n   * Set up watchers for CMI value changes\n   */\n  private setupCMIChangeWatchers(): void {\n    // We'll hook into the setter methods to detect changes\n    // This would typically be done by modifying the CMI setters\n    // For now, we'll track changes when values are set\n  }\n\n  /**\n   * Initialize CMI tracking by storing current values\n   */\n  private initializeCMITracking(): void {\n    // Store initial CMI values for change detection\n    this.lastCMIValues.set(\"cmi.completion_status\", this.cmi.completion_status);\n    this.lastCMIValues.set(\"cmi.success_status\", this.cmi.success_status);\n    this.lastCMIValues.set(\"cmi.progress_measure\", this.cmi.progress_measure);\n\n    if (this.cmi.score) {\n      this.lastCMIValues.set(\"cmi.score.scaled\", this.cmi.score.scaled);\n      this.lastCMIValues.set(\"cmi.score.raw\", this.cmi.score.raw);\n    }\n  }\n\n  /**\n   * Check if sequencing should auto-start\n   */\n  private shouldAutoStartSequencing(): boolean {\n    // Auto-start if we have a root activity and no current activity\n    return !!(this.sequencing.activityTree.root && !this.sequencing.getCurrentActivity());\n  }\n\n  /**\n   * Start automatic sequencing\n   */\n  private startSequencing(): void {\n    if (!this.overallSequencingProcess) {\n      return;\n    }\n\n    try {\n      // Process a \"start\" navigation request to begin sequencing\n      const startResult = this.processNavigationRequest(\"start\");\n      if (startResult) {\n        this.isSequencingActive = true;\n        this.log(\"info\", \"Automatic sequencing started\");\n      }\n    } catch (error) {\n      this.log(\"error\", `Failed to start automatic sequencing: ${error}`);\n    }\n  }\n\n  /**\n   * End sequencing session\n   */\n  private endSequencing(): void {\n    this.isSequencingActive = false;\n    this.activityDeliveryService.reset();\n  }\n\n  /**\n   * Trigger final rollup on termination\n   */\n  private triggerFinalRollup(): void {\n    try {\n      const currentActivity = this.sequencing.getCurrentActivity();\n      if (currentActivity) {\n        // Update activity with final CMI values\n        this.updateActivityFromCMI(currentActivity);\n\n        // Trigger rollup\n        this.rollupProcess.overallRollupProcess(currentActivity);\n\n        // Synchronize global objectives after final rollup\n        if (this.overallSequencingProcess) {\n          this.overallSequencingProcess.synchronizeGlobalObjectives();\n        }\n\n        this.log(\"info\", \"Final rollup completed\");\n      }\n    } catch (error) {\n      this.log(\"error\", `Error during final rollup: ${error}`);\n    }\n  }\n\n  /**\n   * Update activity properties from current CMI values\n   *\n   * @spec SCORM 2004 4th Ed. RTE-to-SN Data Transfer - current CMI values update activity objective state\n   * @spec SCORM 2004 4th Ed. ADLSEQ objectives extension - raw/min/max scores are available to objective write maps\n   */\n  private updateActivityFromCMI(activity: Activity): void {\n    // Update progress measure\n    let hasProgressMeasure = false;\n    if (this.cmi.progress_measure !== \"\") {\n      const progressMeasure = parseFloat(this.cmi.progress_measure);\n      if (!isNaN(progressMeasure)) {\n        hasProgressMeasure = true;\n        activity.progressMeasure = progressMeasure;\n        activity.progressMeasureStatus = true;\n        activity.attemptCompletionAmount = progressMeasure;\n        activity.attemptCompletionAmountStatus = true;\n      }\n    }\n\n    if (!hasProgressMeasure) {\n      activity.attemptCompletionAmountStatus = false;\n    }\n\n    // Update completion status\n    if (activity.completedByMeasure) {\n      const completionStatus = evaluateCompletionStatusFromThreshold({\n        completionThreshold: activity.minProgressMeasure,\n        progressMeasure: this.cmi.progress_measure,\n        storedCompletionStatus: CompletionStatus.UNKNOWN,\n      });\n\n      activity.completionStatus = completionStatus as\n        \"completed\" | \"incomplete\" | \"not attempted\" | \"unknown\";\n      activity.attemptProgressStatus = completionStatus !== CompletionStatus.UNKNOWN;\n    } else if (this.cmi.completion_status !== \"unknown\") {\n      activity.completionStatus = this.cmi.completion_status as\n        \"completed\" | \"incomplete\" | \"not attempted\" | \"unknown\";\n      // Mark that content has set completion status\n      activity.attemptProgressStatus = true;\n    }\n\n    const satisfiedByMeasure = activity.primaryObjective?.satisfiedByMeasure === true;\n\n    // Update success status. A measure-controlled objective ignores direct success status.\n    if (!satisfiedByMeasure && this.cmi.success_status !== \"unknown\") {\n      activity.successStatus = this.cmi.success_status as \"passed\" | \"failed\" | \"unknown\";\n      activity.objectiveSatisfiedStatus = this.cmi.success_status === \"passed\";\n      // Mark that content has set objective satisfaction status. Objective\n      // Measure Status remains independent unless score data is present.\n      if (activity.primaryObjective) {\n        activity.primaryObjective.progressStatus = true;\n      }\n    }\n\n    // Update score information\n    // @spec SCORM 2004 4th Ed. RTE-to-SN Data Transfer - scaled score updates\n    // the objective normalized measure for sequencing.\n    if (this.cmi.score && this.cmi.score.scaled !== \"\") {\n      const scaledScore = parseFloat(this.cmi.score.scaled);\n      if (!isNaN(scaledScore)) {\n        activity.objectiveNormalizedMeasure = scaledScore;\n        activity.objectiveMeasureStatus = true;\n        if (satisfiedByMeasure) {\n          // @spec SCORM 2004 4th Ed. SN 3.10 Objective Description - the\n          // default minimum normalized measure is 1.0 when none is declared.\n          const threshold = activity.primaryObjective?.minNormalizedMeasure ?? 1.0;\n          activity.objectiveSatisfiedStatus = scaledScore >= threshold;\n          activity.objectiveSatisfiedStatusKnown = true;\n          activity.successStatus =\n            scaledScore >= threshold ? SuccessStatus.PASSED : SuccessStatus.FAILED;\n        }\n        // @spec SCORM 2004 4th Ed. SN 3.10 Objective Description - Objective\n        // Measure Status and Objective Progress Status are independent unless\n        // satisfaction is explicitly determined by measure.\n      }\n    }\n\n    if (activity.primaryObjective && this.cmi.score) {\n      // @spec SCORM 2004 4th Ed. ADLSEQ objectives extension - raw/min/max\n      // score maps use their own field-level known state.\n      if (this.cmi.score.raw !== \"\") {\n        activity.primaryObjective.rawScore = this.cmi.score.raw;\n      }\n      if (this.cmi.score.min !== \"\") {\n        activity.primaryObjective.minScore = this.cmi.score.min;\n      }\n      if (this.cmi.score.max !== \"\") {\n        activity.primaryObjective.maxScore = this.cmi.score.max;\n      }\n    }\n\n    // Sync primary objective with activity state for global objective mapping\n    if (activity.primaryObjective) {\n      activity.primaryObjective.updateFromActivity(activity);\n    }\n  }\n\n  /**\n   * Get CMI data for RTE data transfer to activity state\n   * This method provides all CMI data to the sequencing process for transfer\n   * @return {Object} - CMI data formatted for transfer\n   */\n  private getCMIDataForTransfer(): any {\n    const cmiData: any = {\n      completion_status: this.cmi.completion_status,\n      completion_status_was_set:\n        this.configuration.wasCMIElementSetByContent?.(\"cmi.completion_status\") === true,\n      success_status: this.cmi.success_status,\n      // @spec SCORM 2004 4th Ed. SN 3.13.3 - auto-satisfaction applies only\n      // when content did not communicate primary-objective success information.\n      success_status_was_set:\n        this.configuration.wasCMIElementSetByContent?.(\"cmi.success_status\") === true,\n      // @spec SCORM 2004 4th Ed. TR OB-03b / SN UP.4 - a SCO-provided\n      // primary score is objective information for the End Attempt process.\n      score_was_set: [\"scaled\", \"raw\", \"min\", \"max\"].some(\n        (field) => this.configuration.wasCMIElementSetByContent?.(`cmi.score.${field}`) === true,\n      ),\n      progress_measure: this.cmi.progress_measure,\n      score: {\n        scaled: this.cmi.score?.scaled || \"\",\n        raw: this.cmi.score?.raw || \"\",\n        min: this.cmi.score?.min || \"\",\n        max: this.cmi.score?.max || \"\",\n      },\n      objectives: [],\n    };\n\n    // Transfer all CMI objectives\n    if (this.cmi.objectives && this.cmi.objectives.childArray) {\n      for (const [objectiveIndex, baseCmiObj] of this.cmi.objectives.childArray.entries()) {\n        const cmiObjective = baseCmiObj as CMIObjectivesObject;\n        if (cmiObjective.id) {\n          cmiData.objectives.push({\n            id: cmiObjective.id,\n            success_status: cmiObjective.success_status,\n            // @spec SCORM 2004 4th Ed. RTE 4.2.17 - distinguish launch-time\n            // unknown from a SCO explicitly replacing objective satisfaction with unknown.\n            success_status_was_set:\n              this.configuration.wasCMIElementSetByContent?.(\n                `cmi.objectives.${objectiveIndex}.success_status`,\n              ) === true,\n            score_was_set: [\"scaled\", \"raw\", \"min\", \"max\"].some(\n              (field) =>\n                this.configuration.wasCMIElementSetByContent?.(\n                  `cmi.objectives.${objectiveIndex}.score.${field}`,\n                ) === true,\n            ),\n            completion_status: cmiObjective.completion_status,\n            // @spec SCORM 2004 4th Ed. RTE 4.2.17 - distinguish launch-time\n            // initialization from a SCO's explicit objective status write.\n            completion_status_was_set:\n              this.configuration.wasCMIElementSetByContent?.(\n                `cmi.objectives.${objectiveIndex}.completion_status`,\n              ) === true,\n            progress_measure: cmiObjective.progress_measure,\n            score: {\n              scaled: cmiObjective.score?.scaled || \"\",\n              raw: cmiObjective.score?.raw || \"\",\n              min: cmiObjective.score?.min || \"\",\n              max: cmiObjective.score?.max || \"\",\n            },\n          });\n        }\n      }\n    }\n\n    return cmiData;\n  }\n\n  /**\n   * Parse navigation request string to NavigationRequestType\n   */\n  private parseNavigationRequest(request: string): NavigationRequestType | null {\n    // Normalize SCORM nav request tokens (e.g., _continue, _previous)\n    let normalizedRequest = request;\n    if (normalizedRequest.startsWith(\"_\") && normalizedRequest !== \"_none_\") {\n      normalizedRequest = normalizedRequest.substring(1);\n    }\n\n    // Handle choice and jump with targets\n    if (request.includes(\"choice\")) {\n      return NavigationRequestType.CHOICE;\n    }\n    if (request.includes(\"jump\")) {\n      return NavigationRequestType.JUMP;\n    }\n\n    // Handle standard navigation requests\n    switch (normalizedRequest) {\n      case \"start\":\n        return NavigationRequestType.START;\n      case \"resumeAll\":\n        return NavigationRequestType.RESUME_ALL;\n      case \"continue\":\n        return NavigationRequestType.CONTINUE;\n      case \"previous\":\n        return NavigationRequestType.PREVIOUS;\n      case \"exit\":\n        return NavigationRequestType.EXIT;\n      case \"exitAll\":\n        return NavigationRequestType.EXIT_ALL;\n      case \"abandon\":\n        return NavigationRequestType.ABANDON;\n      case \"abandonAll\":\n        return NavigationRequestType.ABANDON_ALL;\n      case \"suspendAll\":\n        return NavigationRequestType.SUSPEND_ALL;\n      case \"_none_\":\n        return NavigationRequestType.NOT_VALID;\n      default:\n        return null;\n    }\n  }\n\n  /**\n   * Handle activity delivery event\n   */\n  private handleActivityDelivery(activity: Activity): void {\n    this.log(\"info\", `Activity delivered: ${activity.id} - ${activity.title}`);\n    this.fireEvent(\"onActivityDelivery\", activity);\n  }\n\n  /**\n   * Handle activity unload event\n   */\n  private handleActivityUnload(activity: Activity): void {\n    this.log(\"info\", `Activity unloaded: ${activity.id} - ${activity.title}`);\n    this.fireEvent(\"onActivityUnload\", activity);\n  }\n\n  /**\n   * Handle sequencing completion event\n   */\n  private handleSequencingComplete(result: SequencingResult): void {\n    this.log(\"debug\", \"Sequencing completed\", result);\n  }\n\n  /**\n   * Handle sequencing error event\n   */\n  private handleSequencingError(error: string): void {\n    this.log(\"error\", `Sequencing error: ${error}`);\n    this.fireEvent(\"onSequencingError\", error, \"sequencing\");\n  }\n\n  /**\n   * Fire an event to registered listeners with enhanced error handling\n   */\n  private fireEvent(eventType: keyof SequencingEventListeners, ...args: any[]): void {\n    if (!this.configuration.enableEventSystem) {\n      return;\n    }\n\n    // Only fire debug event for non-debug events to prevent recursion\n    if (eventType !== \"onSequencingDebug\") {\n      this.fireDebugEvent(`${eventType} fired`, { eventType, argsLength: args.length });\n    }\n\n    try {\n      // Fire to internal listeners first\n      const listener = this.eventListeners[eventType];\n      if (listener && typeof listener === \"function\") {\n        try {\n          (listener as any)(...args);\n          this.log(\"debug\", `Internal listener for ${eventType} executed successfully`);\n        } catch (listenerError) {\n          this.log(\"error\", `Internal listener for ${eventType} failed: ${listenerError}`);\n          // Don't let listener errors stop event propagation\n        }\n      }\n\n      // Fire through the event service for broader integration\n      try {\n        this.eventService.processListeners(`Sequencing.${eventType}`, args[0], ...args.slice(1));\n        this.log(\"debug\", `Event service listeners for ${eventType} processed`);\n      } catch (eventServiceError) {\n        // Event service might not be properly initialized in test contexts\n        // This is not a critical error for sequencing functionality\n        this.log(\"warn\", `Event service failed for ${eventType}: ${eventServiceError}`);\n      }\n\n      // Fire to external global listeners if available\n      try {\n        if (typeof window !== \"undefined\" && (window as any).scormSequencingEvents) {\n          const globalListeners = (window as any).scormSequencingEvents;\n          if (globalListeners[eventType] && typeof globalListeners[eventType] === \"function\") {\n            globalListeners[eventType](...args);\n            this.log(\"debug\", `Global listener for ${eventType} executed`);\n          }\n        }\n      } catch (globalError) {\n        this.log(\"warn\", `Global listener for ${eventType} failed: ${globalError}`);\n      }\n    } catch (error) {\n      this.log(\"error\", `Critical error firing event ${eventType}: ${error}`);\n    }\n  }\n\n  /**\n   * Fire a debug event with detailed information\n   */\n  private fireDebugEvent(event: string, data?: any): void {\n    try {\n      // Direct execution to avoid recursion through fireEvent\n      const listener = this.eventListeners[\"onSequencingDebug\"];\n      if (listener && typeof listener === \"function\") {\n        listener(event, {\n          timestamp: new Date().toISOString(),\n          ...data,\n        });\n      }\n\n      // Also fire through event service directly\n      try {\n        this.eventService.processListeners(\"Sequencing.onSequencingDebug\", event, {\n          timestamp: new Date().toISOString(),\n          ...data,\n        });\n      } catch (eventServiceError) {\n        // Silent fail for event service debug events\n      }\n    } catch (error) {\n      // Silent fail for debug events to avoid recursion\n      console.debug(`Debug event failed: ${error}`);\n    }\n  }\n\n  /**\n   * Fire activity attempt start event\n   */\n  public fireActivityAttemptStart(activity: Activity): void {\n    this.fireEvent(\"onActivityAttemptStart\", activity);\n    this.fireDebugEvent(\"Activity attempt started\", {\n      activityId: activity.id,\n      title: activity.title,\n      attemptCount: activity.attemptCount,\n    });\n  }\n\n  /**\n   * Fire activity attempt end event\n   */\n  public fireActivityAttemptEnd(activity: Activity): void {\n    this.fireEvent(\"onActivityAttemptEnd\", activity);\n    this.fireDebugEvent(\"Activity attempt ended\", {\n      activityId: activity.id,\n      title: activity.title,\n      completionStatus: activity.completionStatus,\n      successStatus: activity.successStatus,\n    });\n  }\n\n  /**\n   * Fire limit condition check event\n   */\n  public fireLimitConditionCheck(activity: Activity, result: boolean): void {\n    this.fireEvent(\"onLimitConditionCheck\", activity, result);\n    this.fireDebugEvent(\"Limit condition check\", {\n      activityId: activity.id,\n      result,\n      attemptCount: activity.attemptCount,\n      attemptLimit: activity.attemptLimit,\n    });\n  }\n\n  /**\n   * Fire navigation validity update event\n   */\n  public fireNavigationValidityUpdate(validity: any): void {\n    this.fireEvent(\"onNavigationValidityUpdate\", validity);\n    this.fireDebugEvent(\"Navigation validity updated\", { validity });\n  }\n\n  /**\n   * Fire sequencing state change event\n   */\n  public fireSequencingStateChange(state: any): void {\n    this.fireEvent(\"onSequencingStateChange\", state);\n    this.fireDebugEvent(\"Sequencing state changed\", { stateKeys: Object.keys(state) });\n  }\n\n  /**\n   * Handle events from the sequencing process\n   */\n  private handleSequencingProcessEvent(eventType: string, data?: any): void {\n    try {\n      switch (eventType) {\n        case \"onActivityDelivery\":\n          // DeliveryHandler reports the selection while OP.1 is still running. Host-facing\n          // delivery is emitted later by ActivityDeliveryService, after it unloads the prior SCO.\n          // @spec SCORM 2004 4th Ed. SN DB.2 - the content delivery environment unloads the\n          //   current activity before delivering the selected activity, with one delivery event.\n          this.fireDebugEvent(\"Sequencing process selected activity for delivery\", data);\n          break;\n        case \"onLimitConditionCheck\":\n          this.fireLimitConditionCheck(data.activity, data.result);\n          break;\n        case \"onActivityAttemptStart\":\n          this.fireActivityAttemptStart(data);\n          break;\n        case \"onActivityAttemptEnd\":\n          this.fireActivityAttemptEnd(data);\n          break;\n        case \"onNavigationValidityUpdate\":\n          this.fireNavigationValidityUpdate(data);\n          break;\n        case \"onSequencingSessionEnd\":\n          this.fireEvent(\"onSequencingSessionEnd\", data);\n          break;\n        default:\n          // Pass through unknown events as debug events\n          this.fireDebugEvent(`Sequencing process event: ${eventType}`, data);\n      }\n    } catch (error) {\n      this.log(\"error\", `Error handling sequencing process event ${eventType}: ${error}`);\n    }\n  }\n\n  /**\n   * Log message with appropriate level\n   */\n  private log(level: \"debug\" | \"info\" | \"warn\" | \"error\", message: string, data?: any): void {\n    const logLevels = [\"debug\", \"info\", \"warn\", \"error\"];\n    const configLevel = this.configuration.logLevel || \"info\";\n\n    if (logLevels.indexOf(level) >= logLevels.indexOf(configLevel)) {\n      switch (level) {\n        case \"debug\":\n          this.loggingService.debug(\n            `[Sequencing] ${message}${data ? ` - ${JSON.stringify(data)}` : \"\"}`,\n          );\n          break;\n        case \"info\":\n          this.loggingService.info(\n            `[Sequencing] ${message}${data ? ` - ${JSON.stringify(data)}` : \"\"}`,\n          );\n          break;\n        case \"warn\":\n          this.loggingService.warn(\n            `[Sequencing] ${message}${data ? ` - ${JSON.stringify(data)}` : \"\"}`,\n          );\n          break;\n        case \"error\":\n          this.loggingService.error(\n            `[Sequencing] ${message}${data ? ` - ${JSON.stringify(data)}` : \"\"}`,\n          );\n          break;\n      }\n    }\n  }\n}\n","import { CommitObject, LogLevel } from \"../types/api_types\";\nimport { StringKeyMap, unflatten } from \"../utilities\";\nimport { LogLevelEnum } from \"../constants/enums\";\nimport { BaseCMI } from \"../cmi/common/base_cmi\";\nimport { ISerializationService } from \"../interfaces/services\";\n\n/**\n * Service for handling data serialization and deserialization in scorm-again\n */\nexport class SerializationService implements ISerializationService {\n  /**\n   * Loads CMI data from a flattened JSON object with special handling for arrays and ordering.\n   *\n   * This method implements a complex algorithm for loading flattened JSON data into the CMI\n   * object structure. It handles several key challenges:\n   *\n   * 1. Ordering dependencies: Some CMI elements (like interactions and objectives) must be\n   *    loaded in a specific order to ensure proper initialization.\n   *\n   * 2. Array handling: Interactions and objectives are stored as arrays, and their properties\n   *    must be loaded in the correct order (e.g., 'id' and 'type' must be set before other properties).\n   *\n   * 3. Unflattening: The method converts flattened dot notation (e.g., \"cmi.objectives.0.id\")\n   *    back into nested objects before loading.\n   *\n   * The algorithm works by:\n   * - Categorizing keys into interactions, objectives, and other properties\n   * - Sorting interactions to prioritize 'id' and 'type' fields within each index\n   * - Sorting objectives to prioritize 'id' fields within each index\n   * - Processing each category in order: interactions, objectives, then other properties\n   *\n   * @param {StringKeyMap} json - The flattened JSON object with dot notation keys\n   * @param {string} CMIElement - The CMI element to start from (usually empty or \"cmi\")\n   * @param {Function} setCMIValue - Function to set CMI value\n   * @param {Function} isNotInitialized - Function to check if API is not initialized\n   *\n   * @param setStartingData\n   * @example\n   * // Example of flattened JSON input:\n   * // {\n   * //   \"cmi.objectives.0.id\": \"obj1\",\n   * //   \"cmi.objectives.0.score.raw\": \"80\",\n   * //   \"cmi.interactions.0.id\": \"int1\",\n   * //   \"cmi.interactions.0.type\": \"choice\",\n   * //   \"cmi.interactions.0.result\": \"correct\"\n   * // }\n   */\n  loadFromFlattenedJSON(\n    json: StringKeyMap,\n    CMIElement: string = \"\",\n    setCMIValue: (CMIElement: string, value: any) => void,\n    isNotInitialized: () => boolean,\n    setStartingData: (data: StringKeyMap) => void,\n    onInvalidValue?: (element: string, error: unknown) => void,\n  ): void {\n    if (!isNotInitialized()) {\n      console.error(\"loadFromFlattenedJSON can only be called before the call to lmsInitialize.\");\n      return;\n    }\n\n    const int_pattern = /^(cmi\\.interactions\\.)(\\d+)\\.(.*)$/;\n    const obj_pattern = /^(cmi\\.objectives\\.)(\\d+)\\.(.*)$/;\n\n    // Extract and categorize keys for better sorting\n    const interactions: {\n      key: string;\n      value: any;\n      index: number;\n      field: string;\n    }[] = [];\n    const objectives: {\n      key: string;\n      value: any;\n      index: number;\n      field: string;\n    }[] = [];\n    const others: { key: string; value: any }[] = [];\n\n    // Categorize keys\n    for (const key in json) {\n      if (Object.prototype.hasOwnProperty.call(json, key)) {\n        const intMatch = key.match(int_pattern);\n        if (intMatch) {\n          interactions.push({\n            key,\n            value: json[key],\n            index: Number(intMatch[2]),\n            field: intMatch[3] || \"\",\n          });\n          continue;\n        }\n\n        const objMatch = key.match(obj_pattern);\n        if (objMatch) {\n          objectives.push({\n            key,\n            value: json[key],\n            index: Number(objMatch[2]),\n            field: objMatch[3] || \"\",\n          });\n          continue;\n        }\n\n        others.push({ key, value: json[key] });\n      }\n    }\n\n    // Sort interactions: first by index, then prioritize 'id' and 'type' fields\n    interactions.sort((a, b) => {\n      if (a.index !== b.index) {\n        return a.index - b.index;\n      }\n\n      // Same index, prioritize id and type\n      if (a.field === \"id\") return -1;\n      if (b.field === \"id\") return 1;\n      if (a.field === \"type\") return -1;\n      if (b.field === \"type\") return 1;\n\n      return a.field.localeCompare(b.field, undefined, { numeric: true });\n    });\n\n    // Sort objectives: first by index, then prioritize 'id' field\n    objectives.sort((a, b) => {\n      if (a.index !== b.index) {\n        return a.index - b.index;\n      }\n\n      // Same index, prioritize id\n      if (a.field === \"id\") return -1;\n      if (b.field === \"id\") return 1;\n\n      return a.field.localeCompare(b.field, undefined, { numeric: true });\n    });\n\n    // Sort other keys alphabetically, comparing numeric list indexes as numbers\n    others.sort((a, b) => a.key.localeCompare(b.key, undefined, { numeric: true }));\n\n    // Process all items in the correct order\n    const processItems = (items: { key: string; value: any }[]) => {\n      items.forEach((item) => {\n        const obj: StringKeyMap = {};\n        obj[item.key] = item.value;\n        this.loadFromJSON(\n          unflatten(obj) as StringKeyMap,\n          CMIElement,\n          setCMIValue,\n          isNotInitialized,\n          setStartingData,\n          onInvalidValue,\n        );\n      });\n    };\n\n    // Process in order: interactions, objectives, others\n    processItems(interactions);\n    processItems(objectives);\n    processItems(others);\n  }\n\n  /**\n   * Loads CMI data from a nested JSON object with recursive traversal.\n   *\n   * This method implements a recursive algorithm for loading nested JSON data into the CMI\n   * object structure. It handles several key aspects:\n   *\n   * 1. Recursive traversal: The method recursively traverses the nested JSON structure,\n   *    building CMI element paths as it goes (e.g., \"cmi.core.student_id\").\n   *\n   * 2. Type-specific handling: Different data types are handled differently:\n   *    - Arrays: Each array element is processed individually with its index in the path\n   *    - Objects: Recursively processed with updated path\n   *    - Primitives: Set directly using setCMIValue\n   *\n   * 3. Initialization check: Ensures the method is only called before API initialization\n   *\n   * 4. Starting data storage: Stores the original JSON data for potential future use\n   *\n   * The algorithm works by:\n   * - First storing the complete JSON object via setStartingData\n   * - Iterating through each property in the JSON object\n   * - For each property, determining its type and handling it accordingly\n   * - Building the CMI element path as it traverses the structure\n   * - Setting values at the appropriate paths using setCMIValue\n   *\n   * @param {{[key: string]: any}} json - The nested JSON object to load\n   * @param {string} CMIElement - The CMI element to start from (usually empty or \"cmi\")\n   * @param {Function} setCMIValue - Function to set CMI value at a specific path\n   * @param {Function} isNotInitialized - Function to check if API is not initialized\n   * @param {Function} setStartingData - Function to store the original JSON data\n   *\n   * @example\n   * // Example of nested JSON input:\n   * // {\n   * //   \"core\": {\n   * //     \"student_id\": \"12345\",\n   * //     \"student_name\": \"John Doe\"\n   * //   },\n   * //   \"objectives\": [\n   * //     { \"id\": \"obj1\", \"score\": { \"raw\": 80 } },\n   * //     { \"id\": \"obj2\", \"score\": { \"raw\": 90 } }\n   * //   ]\n   * // }\n   */\n  loadFromJSON(\n    json: { [key: string]: any },\n    CMIElement: string = \"\",\n    setCMIValue: (CMIElement: string, value: any) => void,\n    isNotInitialized: () => boolean,\n    setStartingData: (data: StringKeyMap) => void,\n    onInvalidValue?: (element: string, error: unknown) => void,\n  ): void {\n    if (!isNotInitialized()) {\n      console.error(\"loadFromJSON can only be called before the call to lmsInitialize.\");\n      return;\n    }\n\n    CMIElement = CMIElement !== undefined ? CMIElement : \"cmi\";\n\n    setStartingData(json);\n\n    const setLeaf = (element: string, value: any) => {\n      try {\n        setCMIValue(element, value);\n      } catch (error) {\n        if (onInvalidValue === undefined) {\n          throw error;\n        }\n        onInvalidValue(element, error);\n      }\n    };\n\n    // could this be refactored down to flatten(json) then setCMIValue on each?\n    for (const key in json) {\n      if (Object.prototype.hasOwnProperty.call(json, key) && json[key]) {\n        const currentCMIElement = (CMIElement ? CMIElement + \".\" : \"\") + key;\n        const value = json[key];\n\n        if (value.constructor === Array) {\n          for (let i = 0; i < value.length; i++) {\n            if (value[i]) {\n              const item = value[i];\n              const tempCMIElement = `${currentCMIElement}.${i}`;\n\n              if (item.constructor === Object) {\n                this.loadFromJSON(\n                  item,\n                  tempCMIElement,\n                  setCMIValue,\n                  isNotInitialized,\n                  setStartingData,\n                  onInvalidValue,\n                );\n              } else {\n                setLeaf(tempCMIElement, item);\n              }\n            }\n          }\n        } else if (value.constructor === Object) {\n          this.loadFromJSON(\n            value,\n            currentCMIElement,\n            setCMIValue,\n            isNotInitialized,\n            setStartingData,\n            onInvalidValue,\n          );\n        } else {\n          setLeaf(currentCMIElement, value);\n        }\n      }\n    }\n  }\n\n  /**\n   * Render the CMI object to JSON for sending to an LMS.\n   *\n   * @param {BaseCMI|StringKeyMap} cmi - The CMI object\n   * @param {boolean} sendFullCommit - Whether to send the full commit\n   * @return {string}\n   */\n  renderCMIToJSONString(cmi: BaseCMI | StringKeyMap, sendFullCommit: boolean): string {\n    // Do we want/need to return fields that have no set value?\n    if (sendFullCommit) {\n      return JSON.stringify({ cmi });\n    }\n    return JSON.stringify({ cmi }, (k, v) => (v === undefined ? null : v), 2);\n  }\n\n  /**\n   * Returns a JS object representing the current cmi\n   * @param {BaseCMI|StringKeyMap} cmi - The CMI object\n   * @param {boolean} sendFullCommit - Whether to send the full commit\n   * @return {object}\n   */\n  renderCMIToJSONObject(cmi: BaseCMI | StringKeyMap, sendFullCommit: boolean): StringKeyMap {\n    // Revert to the original implementation to maintain compatibility with tests\n    return JSON.parse(this.renderCMIToJSONString(cmi, sendFullCommit));\n  }\n\n  /**\n   * Builds the commit object to be sent to the LMS\n   * @param {boolean} terminateCommit - Whether this is a termination commit\n   * @param {boolean} alwaysSendTotalTime - Whether to always send total time\n   * @param {boolean|Function} renderCommonCommitFields - Whether to render common commit fields\n   * @param {Function} renderCommitObject - Function to render commit object\n   * @param {Function} renderCommitCMI - Function to render commit CMI\n   * @param {LogLevel} apiLogLevel - The API log level\n   * @return {CommitObject|StringKeyMap|Array<any>}\n   */\n  getCommitObject(\n    terminateCommit: boolean,\n    alwaysSendTotalTime: boolean,\n    renderCommonCommitFields: boolean | ((commitObject: CommitObject) => boolean),\n    renderCommitObject: (terminateCommit: boolean, includeTotalTime?: boolean) => CommitObject,\n    renderCommitCMI: (\n      terminateCommit: boolean,\n      includeTotalTime?: boolean,\n    ) => StringKeyMap | Array<any>,\n    apiLogLevel: LogLevel,\n  ): CommitObject | StringKeyMap | Array<any> {\n    // Fix for issue: total time is being calculated incorrectly across multiple sessions\n    // when selfReportSessionTime and alwaysSendTotalTime are enabled.\n    //\n    // Previously, we were using a single variable (shouldTerminateCommit) that combined\n    // both concerns: whether this is a termination commit and whether to include total time.\n    // This caused the total time to be calculated as if every commit was a terminate commit\n    // when alwaysSendTotalTime was true, leading to incorrect time calculations.\n    //\n    // Now we pass the actual terminateCommit value and a separate parameter for whether\n    // to include total time, allowing the rendering functions to handle these concerns separately.\n    const includeTotalTime = alwaysSendTotalTime || terminateCommit;\n\n    const commitObject = renderCommonCommitFields\n      ? renderCommitObject(terminateCommit, includeTotalTime)\n      : renderCommitCMI(terminateCommit, includeTotalTime);\n\n    if ([LogLevelEnum.DEBUG, \"1\", 1, \"DEBUG\"].includes(apiLogLevel)) {\n      console.debug(\"Commit (terminated: \" + (terminateCommit ? \"yes\" : \"no\") + \"): \");\n      console.debug(commitObject);\n    }\n    return commitObject;\n  }\n}\n","import { checkValidFormat, checkValidRange } from \"../common/validation\";\nimport { Scorm12ValidationError } from \"../../exceptions/scorm12_exceptions\";\nimport { scorm12_errors } from \"../../constants\";\n\n/**\n * Helper method, no reason to have to pass the same error codes every time\n *\n * @spec RTE - Validates CMI element format per SCORM 1.2 data model requirements\n * @param {string} CMIElement\n * @param {string} value\n * @param {string} regexPattern\n * @param {boolean} allowEmptyString\n * @return {boolean}\n */\nexport function check12ValidFormat(\n  CMIElement: string,\n  value: string,\n  regexPattern: string | RegExp, // We accept either a string or a RegExp object to allow the usage of flags.\n  allowEmptyString?: boolean,\n): boolean {\n  return checkValidFormat(\n    CMIElement,\n    value,\n    regexPattern,\n    scorm12_errors.TYPE_MISMATCH as number,\n    Scorm12ValidationError,\n    allowEmptyString,\n  );\n}\n\n/**\n * Helper method, no reason to have to pass the same error codes every time\n *\n * @spec RTE - Validates CMI element range per SCORM 1.2 data model requirements\n * @param {string} CMIElement\n * @param {string} value\n * @param {string} rangePattern\n * @param {boolean} allowEmptyString\n * @return {boolean}\n */\nexport function check12ValidRange(\n  CMIElement: string,\n  value: any,\n  rangePattern: string,\n  allowEmptyString?: boolean,\n): boolean {\n  if (value === \"\") {\n    if (!allowEmptyString) {\n      throw new Scorm12ValidationError(CMIElement, scorm12_errors.VALUE_OUT_OF_RANGE as number);\n    }\n    return true; // VAL-01: Early return for empty string when allowEmptyString is true\n  }\n\n  return checkValidRange(\n    CMIElement,\n    value,\n    rangePattern,\n    scorm12_errors.VALUE_OUT_OF_RANGE as number,\n    Scorm12ValidationError,\n  );\n}\n","import { BaseScormValidationError } from \"../exceptions\";\nimport { checkValidFormat, checkValidRange } from \"../cmi/common/validation\";\nimport { check12ValidFormat, check12ValidRange } from \"../cmi/scorm12/validation\";\nimport { scorm12_regex } from \"../constants/regex\";\nimport { scorm12_errors } from \"../constants/error_codes\";\nimport { Scorm12ValidationError } from \"../exceptions/scorm12_exceptions\";\n\n/**\n * Service for validating CMI data model properties\n */\nexport class ValidationService {\n  /**\n   * Validates a score property (raw, min, max)\n   *\n   * @param {string} CMIElement\n   * @param {string} value - The value to validate\n   * @param {string} decimalRegex - The regex pattern for decimal validation\n   * @param {string | false} scoreRange - The range pattern for score validation, or false if no range validation is needed\n   * @param {number} invalidTypeCode - The error code for invalid type\n   * @param {number} invalidRangeCode - The error code for invalid range\n   * @param {typeof BaseScormValidationError} errorClass - The error class to use for validation errors\n   * @param {boolean} allowEmptyString - When true, an empty string is accepted (clears the value).\n   *                                     SCORM 1.2 score elements may be blank per the ADL 1.2 CTS\n   *                                     (DataModelValidator.checkScoreDecimal treats blank as valid).\n   * @return {boolean} - True if validation passes, throws an error otherwise\n   */\n  validateScore(\n    CMIElement: string,\n    value: string,\n    decimalRegex: string,\n    scoreRange: string | false,\n    invalidTypeCode: number,\n    invalidRangeCode: number,\n    errorClass: typeof BaseScormValidationError,\n    allowEmptyString = false,\n  ): boolean {\n    if (allowEmptyString && value === \"\") {\n      return true;\n    }\n    return (\n      checkValidFormat(CMIElement, value, decimalRegex, invalidTypeCode, errorClass) &&\n      (!scoreRange || checkValidRange(CMIElement, value, scoreRange, invalidRangeCode, errorClass))\n    );\n  }\n\n  /**\n   * Validates a SCORM 1.2 audio property\n   *\n   * @spec SCORM 1.2 RTE 3.4.2.3.1 - Audio preference validation\n   * @param {string} CMIElement\n   * @param {string} value - The value to validate\n   * @return {boolean} - True if validation passes, throws an error otherwise\n   */\n  validateScorm12Audio(CMIElement: string, value: string): boolean {\n    return (\n      check12ValidFormat(CMIElement, value, scorm12_regex.CMISInteger) &&\n      check12ValidRange(CMIElement, value, scorm12_regex.audio_range)\n    );\n  }\n\n  /**\n   * Validates a SCORM 1.2 language property\n   *\n   * @spec SCORM 1.2 RTE 3.4.2.3.2 - Language preference validation\n   * @param {string} CMIElement\n   * @param {string} value - The value to validate\n   * @return {boolean} - True if validation passes, throws an error otherwise\n   */\n  validateScorm12Language(CMIElement: string, value: string): boolean {\n    // ADL SCORM 1.2 CTS sco08.htm checkAllPossibleCMIString255 treats blank as valid.\n    if (value === \"\") {\n      return true;\n    }\n    return check12ValidFormat(CMIElement, value, scorm12_regex.CMIString256);\n  }\n\n  /**\n   * Validates a SCORM 1.2 speed property\n   *\n   * @spec SCORM 1.2 RTE 3.4.2.3.3 - Speed preference validation\n   * @param {string} CMIElement\n   * @param {string} value - The value to validate\n   * @return {boolean} - True if validation passes, throws an error otherwise\n   */\n  validateScorm12Speed(CMIElement: string, value: string): boolean {\n    return (\n      check12ValidFormat(CMIElement, value, scorm12_regex.CMISInteger) &&\n      check12ValidRange(CMIElement, value, scorm12_regex.speed_range)\n    );\n  }\n\n  /**\n   * Validates a SCORM 1.2 text property\n   *\n   * @spec SCORM 1.2 RTE 3.4.2.3.4 - Text preference validation\n   * @param {string} CMIElement\n   * @param {string} value - The value to validate\n   * @return {boolean} - True if validation passes, throws an error otherwise\n   */\n  validateScorm12Text(CMIElement: string, value: string): boolean {\n    return (\n      check12ValidFormat(CMIElement, value, scorm12_regex.CMISInteger) &&\n      check12ValidRange(CMIElement, value, scorm12_regex.text_range)\n    );\n  }\n\n  /**\n   * Validates if a property is read-only\n   *\n   * @param {string} CMIElement\n   * @param {boolean} initialized - Whether the object is initialized\n   * @throws {BaseScormValidationError} - Throws an error if the object is initialized\n   */\n  validateReadOnly(CMIElement: string, initialized: boolean): void {\n    if (initialized) {\n      throw new Scorm12ValidationError(CMIElement, scorm12_errors.READ_ONLY_ELEMENT as number);\n    }\n  }\n}\n\n// Export a singleton instance of the ValidationService\nexport const validationService = new ValidationService();\n","import { appendQueryParam, flatten, formatMessage, StringKeyMap, stringMatches } from \"./utilities\";\nimport { BaseCMI, BaseRootCMI } from \"./cmi/common/base_cmi\";\nimport { CMIArray } from \"./cmi/common/array\";\nimport { ValidationError } from \"./exceptions\";\nimport {\n  DefaultSettings,\n  defaultLogHandler,\n  ErrorCode,\n  global_constants,\n  LogLevelEnum,\n} from \"./constants\";\nimport {\n  CommitEventContext,\n  CommitMetadata,\n  CommitObject,\n  CommitTrigger,\n  InternalSettings,\n  LogLevel,\n  ResetOptions,\n  ResultObject,\n  ScheduledCommit,\n  Settings,\n} from \"./types\";\nimport {\n  IBaseAPI,\n  ICMIDataService,\n  IErrorHandlingService,\n  IEventService,\n  IHttpService,\n  ILoggingService,\n  IOfflineStorageService,\n  ISerializationService,\n  ScormEventCallback,\n} from \"./interfaces\";\nimport {\n  AsynchronousHttpService,\n  CMIValueAccessService,\n  CMIValueAccessContext,\n  createErrorHandlingService,\n  EventService,\n  getLoggingService,\n  OfflineStorageService,\n  SerializationService,\n  SynchronousHttpService,\n} from \"./services\";\n\ntype CommitSettleWaiter = {\n  resolve: () => void;\n  timeoutId?: ReturnType<typeof setTimeout>;\n};\n\n/**\n * Base API class for SCORM 1.2 and SCORM 2004. Should be considered\n * abstract, and never initialized on its own.\n */\nexport default abstract class BaseAPI implements IBaseAPI {\n  private _timeout?: ScheduledCommit | undefined;\n  protected readonly _error_codes: ErrorCode;\n  private _settings: InternalSettings = DefaultSettings;\n  private readonly _httpService: IHttpService;\n  private _eventService: IEventService;\n  private _serializationService: ISerializationService;\n  private readonly _errorHandlingService: IErrorHandlingService;\n  private readonly _loggingService: ILoggingService;\n  private readonly _offlineStorageService?: IOfflineStorageService;\n  private readonly _cmiValueAccessService: CMIValueAccessService;\n  private _courseId: string = \"\";\n  private _pendingCommitCount = 0;\n\n  /**\n   * Monotonic sequence for commits captured by this API instance. It is\n   * intentionally not reset by reset().\n   */\n  private _commitSequence = 0;\n\n  private readonly _commitSettleWaiters: CommitSettleWaiter[] = [];\n\n  /**\n   * Canonical paths of every CMI element that has been explicitly assigned a\n   * value via SetValue / loadFromJSON (both funnel through _commonSetCMIValue).\n   * Used by standards that must tell \"implemented but never set\" apart from a\n   * legitimately empty value when answering GetValue (SCORM 2004 error 403).\n   * Cleared on reset so a fresh SCO attempt starts with nothing \"set\".\n   */\n  protected readonly _setCMIElements: Set<string> = new Set<string>();\n\n  /**\n   * Constructor for Base API class. Sets some shared API fields, as well as\n   * sets up options for the API.\n   * @param {ErrorCode} error_codes - The error codes object\n   * @param {Settings} settings - Optional settings for the API\n   * @param {IHttpService} httpService - Optional HTTP service instance\n   * @param {IEventService} eventService - Optional Event service instance\n   * @param {ISerializationService} serializationService - Optional Serialization service instance\n   * @param {ICMIDataService} cmiDataService - Optional CMI Data service instance\n   * @param {IErrorHandlingService} errorHandlingService - Optional Error Handling service instance\n   * @param {ILoggingService} loggingService - Optional Logging service instance\n   * @param {IOfflineStorageService} offlineStorageService - Optional Offline Storage service instance\n   */\n  protected constructor(\n    error_codes: ErrorCode,\n    settings?: Settings,\n    httpService?: IHttpService,\n    eventService?: IEventService,\n    serializationService?: ISerializationService,\n    cmiDataService?: ICMIDataService,\n    errorHandlingService?: IErrorHandlingService,\n    loggingService?: ILoggingService,\n    offlineStorageService?: IOfflineStorageService,\n  ) {\n    if (new.target === BaseAPI) {\n      throw new TypeError(\"Cannot construct BaseAPI instances directly\");\n    }\n    this.currentState = global_constants.STATE_NOT_INITIALIZED;\n\n    this._error_codes = error_codes;\n\n    if (settings) {\n      this.settings = {\n        ...DefaultSettings,\n        ...settings,\n      } as InternalSettings;\n    }\n\n    // BACKWARDS COMPATIBILITY: Handle deprecated asyncCommit setting\n    if (\n      settings?.asyncCommit !== undefined &&\n      settings.useAsynchronousCommits === undefined &&\n      settings.throttleCommits === undefined\n    ) {\n      console.warn(\n        \"DEPRECATED: 'asyncCommit' setting is deprecated and will be removed in a future version. \" +\n          \"Use 'useAsynchronousCommits: true' and 'throttleCommits: true' instead.\",\n      );\n      if (settings.asyncCommit) {\n        this.settings.useAsynchronousCommits = true;\n        this.settings.throttleCommits = true;\n      }\n    }\n\n    // VALIDATION: Enforce throttleCommits incompatibility with sync commits\n    if (!this.settings.useAsynchronousCommits && this.settings.throttleCommits) {\n      console.warn(\n        \"throttleCommits cannot be used with synchronous commits. Setting throttleCommits to false.\",\n      );\n      this.settings.throttleCommits = false;\n    }\n\n    // Initialize and configure LoggingService\n    this._loggingService = loggingService || getLoggingService();\n    this._loggingService.setLogLevel(this.settings.logLevel);\n\n    // If settings include a custom onLogMessage function, use it as the log handler\n    if (this.settings.onLogMessage) {\n      this._loggingService.setLogHandler(this.settings.onLogMessage);\n    } else {\n      this._loggingService.setLogHandler(defaultLogHandler);\n    }\n\n    // HTTP SERVICE SELECTION\n    if (httpService) {\n      // Constructor injection (for tests)\n      this._httpService = httpService;\n    } else if (this.settings.httpService) {\n      // Settings injection (advanced users)\n      this._httpService = this.settings.httpService;\n    } else {\n      // Auto-select based on useAsynchronousCommits\n      if (this.settings.useAsynchronousCommits) {\n        console.warn(\n          \"WARNING: useAsynchronousCommits=true is not SCORM compliant. \" +\n            \"Commit failures will not be reported to the SCO, which may cause data loss. \" +\n            \"This setting should only be used for specific legacy compatibility cases.\",\n        );\n        this._httpService = new AsynchronousHttpService(this.settings, this._error_codes);\n      } else {\n        this._httpService = new SynchronousHttpService(this.settings, this._error_codes);\n      }\n    }\n\n    // Initialize Event service\n    this._eventService =\n      eventService ||\n      new EventService((functionName, message, level, element) =>\n        this.apiLog(functionName, message, level, element),\n      );\n\n    // Initialize Serialization service\n    this._serializationService = serializationService || new SerializationService();\n\n    // Initialize Error Handling service\n    this._errorHandlingService =\n      errorHandlingService ||\n      createErrorHandlingService(\n        this._error_codes,\n        (functionName, message, level, element) =>\n          this.apiLog(functionName, message, level || LogLevelEnum.ERROR, element),\n        (errorNumber, detail) => this.getLmsErrorMessageDetails(errorNumber, detail),\n      );\n\n    // Initialize Offline Storage service if enabled\n    if (this.settings.enableOfflineSupport) {\n      this._offlineStorageService =\n        offlineStorageService ||\n        new OfflineStorageService(\n          this.settings,\n          this._error_codes,\n          (functionName, message, level, element) =>\n            this.apiLog(functionName, message, level, element),\n          this._httpService,\n          () => this.getOfflineLearnerId(),\n          (event) => this.processListeners(event),\n        );\n\n      if (this.settings.courseId) {\n        this._courseId = this.settings.courseId;\n      }\n\n      // Set up offline sync on BeforeTerminate event\n      if (this.settings.syncOnTerminate) {\n        this._eventService.on(\"BeforeTerminate\", () => {\n          if (this._offlineStorageService?.isDeviceOnline() && this._courseId) {\n            this._offlineStorageService\n              .hasPendingOfflineData(this._courseId)\n              .then((hasPendingData) => {\n                if (hasPendingData) {\n                  this.apiLog(\n                    \"BeforeTerminate\",\n                    \"Syncing pending offline data before termination\",\n                    LogLevelEnum.INFO,\n                  );\n                  return this._offlineStorageService?.syncOfflineData();\n                }\n              })\n              .catch((error) => {\n                this.apiLog(\n                  \"BeforeTerminate\",\n                  `Error syncing offline data: ${error}`,\n                  LogLevelEnum.ERROR,\n                );\n              });\n          }\n        });\n      }\n    }\n\n    // Initialize CMI Value Access service\n    const cmiValueAccessContext: CMIValueAccessContext = {\n      errorCodes: this._error_codes,\n      getLastErrorCode: () => this.lastErrorCode,\n      setLastErrorCode: (errorCode: string) => {\n        this.lastErrorCode = errorCode;\n      },\n      throwSCORMError: (element: string, errorCode: number, message?: string) =>\n        this.throwSCORMError(element, errorCode, message),\n      isInitialized: () => this.isInitialized(),\n      validateCorrectResponse: (CMIElement: string, value: string) =>\n        this.validateCorrectResponse(CMIElement, value),\n      checkForDuplicateId: (CMIElement: string, value: string) =>\n        this._checkForDuplicateId(CMIElement, value),\n      getChildElement: (CMIElement: string, value: string, foundFirstIndex: boolean) =>\n        this.getChildElement(CMIElement, value, foundFirstIndex),\n      apiLog: (methodName: string, message: string, level: LogLevelEnum) =>\n        this.apiLog(methodName, message, level),\n      checkObjectHasProperty: (obj: StringKeyMap, attr: string) =>\n        this._checkObjectHasProperty(obj, attr),\n      getDataModel: () => this as unknown as StringKeyMap,\n    };\n    this._cmiValueAccessService = new CMIValueAccessService(cmiValueAccessContext);\n  }\n\n  public abstract cmi: BaseCMI;\n  public startingData?: StringKeyMap;\n\n  public currentState: number;\n\n  /**\n   * Get the last error code\n   * @return {string}\n   */\n  get lastErrorCode(): string {\n    return this._errorHandlingService?.lastErrorCode ?? \"0\";\n  }\n\n  /**\n   * Set the last error code\n   * @param {string} errorCode\n   */\n  set lastErrorCode(errorCode: string) {\n    if (this._errorHandlingService) {\n      this._errorHandlingService.lastErrorCode = errorCode;\n    }\n  }\n\n  /**\n   * Protected getter for eventService\n   * @return {IEventService}\n   */\n  protected get eventService(): IEventService {\n    return this._eventService;\n  }\n\n  /**\n   * Protected getter for loggingService\n   * @return {ILoggingService}\n   */\n  protected get loggingService(): ILoggingService {\n    return this._loggingService;\n  }\n\n  /**\n   * Reset the API to its initial state.\n   * This method clears all current data and resets the API to an uninitialized state.\n   * It can optionally accept new settings to configure the API after reset.\n   *\n   * @param {Settings} settings - Optional new settings to apply after reset\n   * @param {ResetOptions} options - Behavior for this reset only\n   */\n  abstract reset(settings?: Settings, options?: ResetOptions): void;\n\n  /**\n   * Common reset method for all APIs. New settings are merged with the existing settings.\n   * @param {Settings} settings\n   * @param {ResetOptions} options\n   * @protected\n   */\n  commonReset(settings?: Settings, options?: ResetOptions): void {\n    this.apiLog(\"reset\", \"Called\", LogLevelEnum.INFO);\n\n    this.settings = { ...this.settings, ...settings };\n\n    this.clearScheduledCommit();\n    this.currentState = global_constants.STATE_NOT_INITIALIZED;\n    this.lastErrorCode = \"0\";\n    if (options?.preserveListeners !== true) {\n      this._eventService.reset();\n    }\n    this.startingData = {};\n    this._setCMIElements.clear();\n\n    // Update offline storage service with new settings if it exists\n    if (this._offlineStorageService) {\n      this._offlineStorageService.updateSettings(this.settings);\n\n      if (settings?.courseId) {\n        this._courseId = settings.courseId;\n      }\n    }\n  }\n\n  protected getOfflineLearnerId(): string {\n    return this.getCMIValue(\"core\" in this.cmi ? \"cmi.core.student_id\" : \"cmi.learner_id\") || \"\";\n  }\n\n  protected restoreOfflineData(): void {\n    if (!this.settings.enableOfflineSupport || !this._courseId || !this.isNotInitialized()) {\n      return;\n    }\n    try {\n      const pending =\n        this._offlineStorageService?.getPendingOfflineData?.(\n          this._courseId,\n          this.getOfflineLearnerId(),\n        ) ?? [];\n      // Enforce the CMI setters' SCO write restrictions during offline restore.\n      if (pending.length) this.cmi.initialize();\n      const restoreValue = (element: string, value: any) => {\n        // Existing LMS comment children do not inherit the array's initialized flag.\n        if (\n          !/^cmi\\.(core\\.)?(session_time|exit)$/.test(element) &&\n          !/^cmi\\.comments_from_lms(\\.|$)/.test(element)\n        ) {\n          try {\n            this.setCMIValue(element, value);\n          } catch {\n            // Read-only or invalid values must not prevent other values from restoring.\n          }\n        }\n      };\n      for (const data of pending) {\n        try {\n          const runtimeData = (Array.isArray(data) ? data : (data.runtimeData ?? data)) as\n            StringKeyMap | any[];\n          if (Array.isArray(runtimeData)) {\n            this.apiLog(\"Initialize\", \"Skipping restore of params payload\", LogLevelEnum.WARN);\n          } else if (runtimeData.cmi) {\n            this._serializationService.loadFromFlattenedJSON(\n              flatten({ cmi: runtimeData.cmi }),\n              \"\",\n              restoreValue,\n              () => true,\n              () => {},\n            );\n          } else {\n            const cmiData = Object.fromEntries(\n              Object.entries(runtimeData).filter(([key]) => key.startsWith(\"cmi.\")),\n            );\n            this._serializationService.loadFromFlattenedJSON(\n              cmiData,\n              \"\",\n              restoreValue,\n              () => true,\n              () => {},\n            );\n          }\n        } catch (error) {\n          this.apiLog(\"Initialize\", `Error restoring offline data: ${error}`, LogLevelEnum.ERROR);\n        }\n      }\n    } catch (error) {\n      this.apiLog(\"Initialize\", `Error restoring offline data: ${error}`, LogLevelEnum.ERROR);\n    }\n  }\n\n  /**\n   * Initialize the API\n   * @param {string} callbackName\n   * @param {string} initializeMessage\n   * @param {string} terminationMessage\n   * @return {string}\n   */\n  initialize(\n    callbackName: string,\n    initializeMessage?: string,\n    terminationMessage?: string,\n  ): string {\n    let returnValue = global_constants.SCORM_FALSE;\n\n    if (this.isInitialized()) {\n      this.throwSCORMError(\"api\", this._error_codes.INITIALIZED, initializeMessage);\n    } else if (this.isTerminated()) {\n      this.throwSCORMError(\"api\", this._error_codes.TERMINATED, terminationMessage);\n    } else {\n      if (this.settings.selfReportSessionTime) {\n        (this.cmi as BaseRootCMI).setStartTime();\n      }\n\n      this.currentState = global_constants.STATE_INITIALIZED;\n      this.lastErrorCode = \"0\";\n      returnValue = global_constants.SCORM_TRUE;\n      this.processListeners(callbackName);\n\n      // If enabled, attempt to sync offline data on initialization\n      if (\n        this.settings.enableOfflineSupport &&\n        this._offlineStorageService &&\n        this._courseId &&\n        this.settings.syncOnInitialize &&\n        this._offlineStorageService.isDeviceOnline()\n      ) {\n        void this._offlineStorageService\n          .hasPendingOfflineData(this._courseId)\n          .then((hasPendingData) => {\n            if (hasPendingData) {\n              this.apiLog(\n                callbackName,\n                \"Syncing pending offline data on initialization\",\n                LogLevelEnum.INFO,\n              );\n              void this._offlineStorageService?.syncOfflineData().then((syncSuccess) => {\n                if (syncSuccess) {\n                  this.apiLog(callbackName, \"Successfully synced offline data\", LogLevelEnum.INFO);\n                }\n              });\n            }\n          });\n      }\n    }\n\n    this.apiLog(callbackName, \"returned: \" + returnValue, LogLevelEnum.INFO);\n    this.clearSCORMError(returnValue);\n\n    return returnValue;\n  }\n\n  /**\n   * Initialize the LMS API - Begins a communication session\n   *\n   * SCORM 1.2 per RTE Section 3.4.3.1 (LMSInitialize):\n   * - Parameter must be empty string (\"\")\n   * - Returns \"true\" on success, \"false\" on failure\n   * - Sets error 101 if already initialized\n   * - Sets error 101 if already terminated\n   *\n   * SCORM 2004 per RTE Section 3.1.2.1 (Initialize):\n   * - Parameter must be empty string (\"\")\n   * - Returns \"true\" on success, \"false\" on failure\n   * - Sets error 103 if already initialized\n   * - Sets error 104 if already terminated\n   *\n   * @param {string} parameter - Must be an empty string per SCORM specification\n   * @return {string} \"true\" if successful, \"false\" otherwise\n   */\n  abstract lmsInitialize(parameter?: string): string;\n\n  /**\n   * Finish the current LMS API session - Ends a communication session\n   *\n   * SCORM 1.2 per RTE Section 3.4.3.2 (LMSFinish):\n   * - Parameter must be empty string (\"\")\n   * - Returns \"true\" on success, \"false\" on failure\n   * - Commits all data to persistent storage\n   * - Sets error 101 if not initialized\n   * - Sets error 101 if already terminated\n   *\n   * SCORM 2004 per RTE Section 3.1.2.2 (Terminate):\n   * - Parameter must be empty string (\"\")\n   * - Returns \"true\" on success, \"false\" on failure\n   * - Commits all data to persistent storage\n   * - Sets error 112 if not initialized\n   * - Sets error 113 if already terminated\n   *\n   * @param {string} parameter - Must be an empty string per SCORM specification\n   * @return {string} \"true\" if successful, \"false\" otherwise\n   */\n  abstract lmsFinish(parameter?: string): string;\n\n  /**\n   * Get the value of a CMI element from the LMS\n   *\n   * SCORM 1.2 per RTE Section 3.4.3.3 (LMSGetValue):\n   * - Returns the value of the specified CMI data model element\n   * - Returns empty string if element has no value\n   * - Sets error 101 if not initialized\n   * - Sets error 301 if invalid element specified\n   * - Sets error 201 if element is write-only\n   *\n   * SCORM 2004 per RTE Section 3.1.2.3 (GetValue):\n   * - Returns the value of the specified CMI data model element\n   * - Returns empty string if element has no value\n   * - Sets error 122 if not initialized\n   * - Sets error 123 if terminated\n   * - Sets error 401 if invalid element specified\n   * - Sets error 405 if element is write-only\n   *\n   * @param {string} CMIElement - The CMI element to get the value of\n   * @return {string} The value of the CMI element\n   */\n  abstract lmsGetValue(CMIElement: string): string;\n\n  /**\n   * Set the value of a CMI element in the LMS\n   *\n   * SCORM 1.2 per RTE Section 3.4.3.4 (LMSSetValue):\n   * - Sets the value of the specified CMI data model element\n   * - Returns \"true\" on success, \"false\" on failure\n   * - Sets error 101 if not initialized\n   * - Sets error 301 if invalid element specified\n   * - Sets error 351 if element exceeds maximum length\n   * - Sets error 201 if element is read-only\n   * - Sets error 405 if incorrect data type\n   *\n   * SCORM 2004 per RTE Section 3.1.2.4 (SetValue):\n   * - Sets the value of the specified CMI data model element\n   * - Returns \"true\" on success, \"false\" on failure\n   * - Sets error 132 if not initialized\n   * - Sets error 133 if terminated\n   * - Sets error 401 if invalid element specified\n   * - Sets error 403 if element is read-only\n   * - Sets error 406 if incorrect data type\n   *\n   * @param {string} CMIElement - The CMI element to set the value of\n   * @param {any} value - The value to set\n   * @return {string} \"true\" if successful, \"false\" otherwise\n   */\n  abstract lmsSetValue(CMIElement: string, value: any): string;\n\n  /**\n   * Commit the current data to the LMS - Persists data to storage\n   *\n   * SCORM 1.2 per RTE Section 3.4.4.1 (LMSCommit):\n   * - Parameter must be empty string (\"\")\n   * - Requests immediate persistence of all data since last commit\n   * - Returns \"true\" on success, \"false\" on failure\n   * - Sets error 101 if not initialized\n   * - Sets error 391 if commit failed\n   *\n   * SCORM 2004 per RTE Section 3.1.2.5 (Commit):\n   * - Parameter must be empty string (\"\")\n   * - Requests immediate persistence of all data since last commit\n   * - Returns \"true\" on success, \"false\" on failure\n   * - Sets error 142 if not initialized\n   * - Sets error 143 if terminated\n   * - Sets error 391 if commit failed\n   *\n   * @param {string} parameter - Must be an empty string per SCORM specification\n   * @return {string} \"true\" if successful, \"false\" otherwise\n   */\n  abstract lmsCommit(parameter?: string): string;\n\n  /**\n   * Get the last error code from the LMS\n   *\n   * SCORM 1.2 per RTE Section 3.4.4.2 (LMSGetLastError):\n   * - Returns the error code from the last API call\n   * - Returns \"0\" if no error occurred\n   * - Can be called at any time (even before initialization)\n   * - Does not change the current error state\n   *\n   * SCORM 2004 per RTE Section 3.1.2.6 (GetLastError):\n   * - Returns the error code from the last API call\n   * - Returns \"0\" if no error occurred\n   * - Can be called at any time (even before initialization)\n   * - Does not change the current error state\n   *\n   * @return {string} The last error code\n   */\n  abstract lmsGetLastError(): string;\n\n  /**\n   * Get the error string for a specific error code\n   *\n   * SCORM 1.2 per RTE Section 3.4.4.3 (LMSGetErrorString):\n   * - Returns a short textual description for the specified error code\n   * - Returns empty string if error code is not recognized\n   * - Can be called at any time (even before initialization)\n   * - Does not change the current error state\n   *\n   * SCORM 2004 per RTE Section 3.1.2.7 (GetErrorString):\n   * - Returns a short textual description for the specified error code\n   * - Returns empty string if error code is not recognized\n   * - Can be called at any time (even before initialization)\n   * - Does not change the current error state\n   *\n   * @param {string|number} CMIErrorCode - The error code to get the string for\n   * @return {string} The error string\n   */\n  abstract lmsGetErrorString(CMIErrorCode: string | number): string;\n\n  /**\n   * Get diagnostic information for a specific error code\n   *\n   * SCORM 1.2 per RTE Section 3.4.4.4 (LMSGetDiagnostic):\n   * - Returns detailed diagnostic information for the specified error code\n   * - Implementation-specific; can include additional context or debugging info\n   * - Returns empty string if no diagnostic information is available\n   * - Can be called at any time (even before initialization)\n   * - Does not change the current error state\n   *\n   * SCORM 2004 per RTE Section 3.1.2.8 (GetDiagnostic):\n   * - Returns detailed diagnostic information for the specified error code\n   * - Implementation-specific; can include additional context or debugging info\n   * - Returns empty string if no diagnostic information is available\n   * - Can be called at any time (even before initialization)\n   * - Does not change the current error state\n   *\n   * @param {string|number} CMIErrorCode - The error code to get diagnostic information for\n   * @return {string} The diagnostic information\n   */\n  abstract lmsGetDiagnostic(CMIErrorCode: string | number): string;\n\n  /**\n   * Abstract method for validating that a response is correct.\n   * This method is used to validate the format and content of a response\n   * before it is set in the CMI data model.\n   *\n   * @param {string} _CMIElement - The CMI element path to validate\n   * @param {any} _value - The value to validate\n   * @throws {Error} If the response format is invalid\n   */\n  abstract validateCorrectResponse(_CMIElement: string, _value: any): void;\n\n  /**\n   * Gets or builds a new child element to add to the array.\n   * APIs that inherit BaseAPI should override this method.\n   *\n   * @param {string} _CMIElement - unused\n   * @param {*} _value - unused\n   * @param {boolean} _foundFirstIndex - unused\n   * @return {BaseCMI|null}\n   * @abstract\n   */\n  abstract getChildElement(\n    _CMIElement: string,\n    _value: any,\n    _foundFirstIndex: boolean,\n  ): BaseCMI | null;\n\n  /**\n   * Attempts to store the data to the LMS, logs data if no LMS configured\n   * APIs that inherit BaseAPI should override this function\n   *\n   * @param {boolean} _calculateTotalTime\n   * @param {CommitTrigger} [_trigger] - What initiated the commit\n   * @return {ResultObject}\n   * @abstract\n   */\n  abstract storeData(_calculateTotalTime: boolean, _trigger?: CommitTrigger): ResultObject;\n\n  /**\n   * Render the cmi object to the proper format for LMS commit\n   *\n   * @param {boolean} _terminateCommit - Whether this commit is part of the termination process\n   * @param {boolean} [_includeTotalTime] - Whether to include total time in the commit data\n   * @return {StringKeyMap|Array}\n   * @abstract\n   */\n  abstract renderCommitCMI(\n    _terminateCommit: boolean,\n    _includeTotalTime?: boolean,\n  ): StringKeyMap | Array<string>;\n\n  /**\n   * Render the commit object to the shortened format for LMS commit.\n   * This method transforms the CMI data into a format suitable for sending to the LMS.\n   * It is called during the commit process to prepare the data for transmission.\n   *\n   * @param {boolean} _terminateCommit - Whether this commit is part of the termination process\n   * @param {boolean} [_includeTotalTime] - Whether to include total time in the commit data\n   * @return {CommitObject} A formatted object containing the data to be sent to the LMS\n   * @example\n   * // Example of a commit object structure\n   * {\n   *   method: \"POST\",\n   *   params: {\n   *     cmi: { ... },\n   *     finishState: \"COMPLETED\"\n   *   }\n   * }\n   */\n  abstract renderCommitObject(_terminateCommit: boolean, _includeTotalTime?: boolean): CommitObject;\n\n  /**\n   * Logging for all SCORM actions\n   *\n   * @param {string} functionName\n   * @param {string} logMessage\n   * @param {number} messageLevel\n   * @param {string} CMIElement\n   */\n  apiLog(functionName: string, logMessage: string, messageLevel: LogLevel, CMIElement?: string) {\n    logMessage = formatMessage(functionName, logMessage, CMIElement);\n\n    // Delegate to LoggingService which handles log level comparison properly\n    this._loggingService.log(messageLevel, logMessage);\n  }\n\n  /**\n   * Getter for _settings\n   * @return {InternalSettings}\n   */\n  get settings(): InternalSettings {\n    return this._settings;\n  }\n\n  /**\n   * Setter for _settings\n   * @param {Settings} settings\n   */\n  set settings(settings: Settings) {\n    const previousSettings = this._settings;\n    // Merge the incoming settings with the existing settings\n    this._settings = { ...this._settings, ...settings } as InternalSettings;\n\n    // Update HTTP service settings\n    this._httpService?.updateSettings(this._settings);\n\n    // The following properties are duplicated as class properties for easier access\n    // and need to be manually updated to stay in sync with the settings object\n\n    // Update log level if it changed\n    if (settings.logLevel !== undefined && settings.logLevel !== previousSettings.logLevel) {\n      this._loggingService?.setLogLevel(settings.logLevel);\n    }\n\n    // Update log handler if onLogMessage changed\n    if (\n      settings.onLogMessage !== undefined &&\n      settings.onLogMessage !== previousSettings.onLogMessage\n    ) {\n      this._loggingService?.setLogHandler(settings.onLogMessage);\n    }\n  }\n\n  /**\n   * Gets the number of captured commit requests that have not yet settled.\n   *\n   * @return {number} The number of in-flight commits\n   */\n  get pendingCommitCount(): number {\n    return this._pendingCommitCount;\n  }\n\n  /**\n   * Resolves when all currently in-flight commits have settled. A timeout is\n   * best-effort: the promise resolves when it elapses even if commits remain,\n   * and callers can inspect pendingCommitCount afterward to detect that case.\n   *\n   * @param {Object} [options] - Settle options\n   * @param {number} [options.timeoutMs] - Maximum time to wait in milliseconds\n   * @return {Promise<void>} A promise that resolves after the drain or timeout\n   */\n  whenCommitsSettled(options?: { timeoutMs?: number }): Promise<void> {\n    if (this._pendingCommitCount === 0) {\n      return Promise.resolve();\n    }\n\n    return new Promise<void>((resolve) => {\n      const waiter: CommitSettleWaiter = { resolve };\n\n      if (options?.timeoutMs !== undefined) {\n        waiter.timeoutId = setTimeout(() => {\n          const waiterIndex = this._commitSettleWaiters.indexOf(waiter);\n          if (waiterIndex === -1) {\n            return;\n          }\n\n          this._commitSettleWaiters.splice(waiterIndex, 1);\n          resolve();\n        }, options.timeoutMs);\n      }\n\n      this._commitSettleWaiters.push(waiter);\n    });\n  }\n\n  /** Resolve and clear every waiter after the pending count reaches zero. */\n  private _flushCommitSettleWaiters(): void {\n    const waiters = this._commitSettleWaiters.splice(0);\n    for (const waiter of waiters) {\n      if (waiter.timeoutId !== undefined) {\n        clearTimeout(waiter.timeoutId);\n      }\n      waiter.resolve();\n    }\n  }\n\n  /**\n   * Terminates the current run of the API\n   * @param {string} callbackName\n   * @param {boolean} checkTerminated\n   * @return {string}\n   */\n  terminate(callbackName: string, checkTerminated: boolean): string {\n    // Per SCORM 2004 3rd Edition RTE Section 3.1.3.2:\n    // Return \"false\" for all error conditions (112, 113, 111, 201)\n    let returnValue = global_constants.SCORM_TRUE;\n    let stateCheckPassed = false;\n\n    // Check if not initialized first\n    if (this.isNotInitialized()) {\n      const errorCode = this._error_codes.TERMINATION_BEFORE_INIT ?? 0;\n      this.throwSCORMError(\"api\", errorCode);\n      // Terminating before initializing always fails, under every standard we\n      // implement: SCORM 2004 3rd Ed RTE 3.1.3.2 (error 112) and SCORM 1.2 per\n      // ADL CTS sco03.htm (error 301) both require \"false\". Unlike the branch\n      // below for a repeated termination, no error table treats this as a\n      // successful call, so the result does not depend on the code.\n      returnValue = global_constants.SCORM_FALSE;\n    } else if (checkTerminated && this.isTerminated()) {\n      const errorCode = this._error_codes.MULTIPLE_TERMINATION ?? 0;\n      this.throwSCORMError(\"api\", errorCode);\n      // Per SCORM 2004 3rd Ed RTE 3.1.3.2: return \"false\" for error 113\n      // SCORM 1.2 (error 101) returns \"true\" for error conditions\n      if (errorCode === 113) returnValue = global_constants.SCORM_FALSE;\n    } else {\n      stateCheckPassed = true;\n\n      // Fire BeforeTerminate event for offline sync\n      this.processListeners(\"BeforeTerminate\");\n\n      const result: ResultObject = this.storeData(true, \"terminate\");\n      if ((result.errorCode ?? 0) > 0) {\n        // Log detailed error information before throwing SCORM error\n        if (result.errorMessage) {\n          this.apiLog(\n            \"terminate\",\n            `Terminate failed with error: ${result.errorMessage}`,\n            LogLevelEnum.ERROR,\n          );\n        }\n        if (result.errorDetails) {\n          this.apiLog(\n            \"terminate\",\n            `Error details: ${JSON.stringify(result.errorDetails)}`,\n            LogLevelEnum.DEBUG,\n          );\n        }\n        // Per SCORM spec: on error 111, state remains \"Running\" and return \"false\"\n        this.throwSCORMError(\"api\", result.errorCode ?? 0);\n        returnValue = global_constants.SCORM_FALSE;\n      } else {\n        // Only transition to Terminated state after successful storeData\n        // Per SCORM 2004 3rd Edition RTE Section 3.1.3.2\n        this.currentState = global_constants.STATE_TERMINATED;\n        // Only clear error if there was no error\n        if (checkTerminated) this.lastErrorCode = \"0\";\n        const resultValue = result?.result ?? global_constants.SCORM_TRUE;\n        returnValue = typeof resultValue === \"boolean\" ? String(resultValue) : resultValue;\n      }\n\n      this.processListeners(callbackName);\n    }\n\n    this.apiLog(callbackName, \"returned: \" + returnValue, LogLevelEnum.INFO);\n\n    // Only clear error if state check passed\n    if (stateCheckPassed) {\n      this.clearSCORMError(returnValue);\n    }\n\n    return returnValue;\n  }\n\n  /**\n   * Get the value of the CMIElement.\n   *\n   * @param {string} callbackName\n   * @param {boolean} checkTerminated\n   * @param {string} CMIElement\n   * @return {string}\n   */\n  getValue(callbackName: string, checkTerminated: boolean, CMIElement: string): string {\n    let returnValue: string = \"\";\n\n    if (\n      this.checkState(\n        checkTerminated,\n        this._error_codes.RETRIEVE_BEFORE_INIT ?? 0,\n        this._error_codes.RETRIEVE_AFTER_TERM ?? 0,\n      )\n    ) {\n      // Only reset the error code if there's no error and checkTerminated is true\n      // This is a no-op if lastErrorCode is already \"0\"\n      try {\n        returnValue = this.getCMIValue(CMIElement);\n      } catch (e) {\n        returnValue = this.handleValueAccessException(CMIElement, e, returnValue);\n      }\n      // Standards that must report 403 (value not initialized) for an\n      // implemented, no-default element read before being set hook in here,\n      // but only after an otherwise-successful resolution. Gating at this public\n      // boundary (never in the getters) keeps serialization/commit/rollup, which\n      // read the getters directly, unaffected.\n      if (this.lastErrorCode === \"0\") {\n        this.checkUninitializedGet(CMIElement, returnValue);\n      }\n      this.processListeners(callbackName, CMIElement);\n    }\n\n    this.apiLog(callbackName, \": returned: \" + returnValue, LogLevelEnum.INFO, CMIElement);\n\n    if (returnValue === undefined) {\n      return \"\";\n    }\n\n    // Only clear the error code if there's no error\n    if (this.lastErrorCode === \"0\") {\n      this.clearSCORMError(returnValue);\n    }\n\n    // Per IEEE 1484.11.2, GetValue must return a characterstring. Coerce numeric/\n    // boolean data-model values (e.g. *._count) so the public API is string-safe.\n    const rawReturn: unknown = returnValue;\n    if (typeof rawReturn === \"number\" || typeof rawReturn === \"boolean\") {\n      return String(rawReturn);\n    }\n\n    return returnValue;\n  }\n\n  /**\n   * Sets the value of the CMIElement.\n   *\n   * @param {string} callbackName\n   * @param {string} commitCallback\n   * @param {boolean} checkTerminated\n   * @param {string} CMIElement\n   * @param {*} value\n   * @return {string}\n   */\n  setValue(\n    callbackName: string,\n    commitCallback: string,\n    checkTerminated: boolean,\n    CMIElement: string,\n    value: any,\n  ): string {\n    if (value !== undefined) {\n      value = String(value);\n    }\n    let returnValue: string = global_constants.SCORM_FALSE;\n\n    if (\n      this.checkState(\n        checkTerminated,\n        this._error_codes.STORE_BEFORE_INIT ?? 0,\n        this._error_codes.STORE_AFTER_TERM ?? 0,\n      )\n    ) {\n      // Only reset the error code if there's no error and checkTerminated is true\n      // This is a no-op if lastErrorCode is already \"0\"\n      try {\n        returnValue = this.setCMIValue(CMIElement, value);\n      } catch (e) {\n        returnValue = this.handleValueAccessException(CMIElement, e, returnValue);\n      }\n      this.processListeners(callbackName, CMIElement, value);\n    }\n\n    if (returnValue === undefined) {\n      returnValue = global_constants.SCORM_FALSE;\n    }\n\n    // If we didn't have any errors while setting the data, go ahead and\n    // schedule a commit, if autocommit is turned on\n    if (String(this.lastErrorCode) === \"0\") {\n      if (this.settings.autocommit) {\n        this.scheduleCommit(this.settings.autocommitSeconds * 1000, commitCallback);\n      }\n    }\n\n    this.apiLog(\n      callbackName,\n      \": \" + value + \": result: \" + returnValue,\n      LogLevelEnum.INFO,\n      CMIElement,\n    );\n\n    // Only clear the error code if there's no error\n    if (this.lastErrorCode === \"0\") {\n      this.clearSCORMError(returnValue);\n    }\n\n    return returnValue;\n  }\n\n  /**\n   * Orders LMS to store all content parameters\n   * @param {string} callbackName\n   * @param {boolean} checkTerminated\n   * @param {CommitTrigger} trigger - What initiated the commit\n   * @return {string}\n   */\n  commit(\n    callbackName: string,\n    checkTerminated: boolean = false,\n    trigger: CommitTrigger = \"manual\",\n  ): string {\n    this.clearScheduledCommit();\n\n    // Per SCORM 2004 3rd Edition RTE Section 3.1.4.3:\n    // Return \"false\" for all error conditions (142, 143, 391, 201)\n    let returnValue = global_constants.SCORM_TRUE;\n\n    // Check if not initialized first\n    if (this.isNotInitialized()) {\n      const errorCode = this._error_codes.COMMIT_BEFORE_INIT ?? 0;\n      this.throwSCORMError(\"api\", errorCode);\n      // Committing before initializing always fails, under every standard we\n      // implement: SCORM 2004 3rd Ed RTE 3.1.4.3 (error 142) and SCORM 1.2 per\n      // ADL CTS sco03.htm (error 301) both require \"false\". Unlike the branch\n      // below for a commit after terminate, no error table treats this as a\n      // successful call, so the result does not depend on the code.\n      returnValue = global_constants.SCORM_FALSE;\n    } else if (checkTerminated && this.isTerminated()) {\n      const errorCode = this._error_codes.COMMIT_AFTER_TERM ?? 0;\n      this.throwSCORMError(\"api\", errorCode);\n      // Per SCORM 2004 3rd Ed RTE 3.1.4.3: return \"false\" for error 143\n      if (errorCode === 143) returnValue = global_constants.SCORM_FALSE;\n    } else {\n      const result = this.storeData(false, trigger);\n      const errorCode = result.errorCode ?? 0;\n      if (errorCode > 0) {\n        // Log detailed error information before throwing SCORM error\n        if (result.errorMessage) {\n          this.apiLog(\n            \"commit\",\n            `Commit failed with error: ${result.errorMessage}`,\n            LogLevelEnum.ERROR,\n          );\n        }\n        if (result.errorDetails) {\n          this.apiLog(\n            \"commit\",\n            `Error details: ${JSON.stringify(result.errorDetails)}`,\n            LogLevelEnum.DEBUG,\n          );\n        }\n        this.throwSCORMError(\"api\", errorCode);\n      }\n      const resultValue = result?.result ?? global_constants.SCORM_FALSE;\n      returnValue = typeof resultValue === \"boolean\" ? String(resultValue) : resultValue;\n\n      this.apiLog(callbackName, \" Result: \" + returnValue, LogLevelEnum.DEBUG, \"HttpRequest\");\n\n      if (checkTerminated && errorCode === 0) this.lastErrorCode = \"0\";\n\n      this.processListeners(callbackName);\n\n      // Fire async offline sync in background if needed\n      if (\n        this.settings.enableOfflineSupport &&\n        this._offlineStorageService &&\n        this._offlineStorageService.isDeviceOnline() &&\n        this._courseId\n      ) {\n        void this._offlineStorageService\n          .hasPendingOfflineData(this._courseId)\n          .then((hasPendingData) => {\n            if (hasPendingData) {\n              this.apiLog(callbackName, \"Syncing pending offline data\", LogLevelEnum.INFO);\n              void this._offlineStorageService?.syncOfflineData().then((syncSuccess) => {\n                if (syncSuccess) {\n                  this.apiLog(callbackName, \"Successfully synced offline data\", LogLevelEnum.INFO);\n                } else {\n                  this.apiLog(callbackName, \"Failed to sync some offline data\", LogLevelEnum.WARN);\n                }\n              });\n            }\n          });\n      }\n    }\n\n    this.apiLog(callbackName, \"returned: \" + returnValue, LogLevelEnum.INFO);\n\n    // Only clear error if we actually performed a commit (not a state error)\n    if (!this.isNotInitialized() && !(checkTerminated && this.isTerminated())) {\n      this.clearSCORMError(returnValue);\n    }\n\n    return returnValue;\n  }\n\n  /**\n   * Returns last error code\n   * @param {string} callbackName\n   * @return {string}\n   */\n  getLastError(callbackName: string): string {\n    const returnValue = String(this.lastErrorCode);\n\n    this.processListeners(callbackName);\n\n    this.apiLog(callbackName, \"returned: \" + returnValue, LogLevelEnum.INFO);\n\n    return returnValue;\n  }\n\n  /**\n   * Returns the errorNumber error description\n   *\n   * @param {string} callbackName\n   * @param {(string|number)} CMIErrorCode\n   * @return {string} - Error description string (max 255 chars per spec)\n   */\n  getErrorString(callbackName: string, CMIErrorCode: string | number): string {\n    let returnValue = \"\";\n\n    if (CMIErrorCode !== null && CMIErrorCode !== \"\") {\n      returnValue = this.getLmsErrorMessageDetails(CMIErrorCode);\n      this.processListeners(callbackName);\n    }\n\n    // Per SCORM spec: GetErrorString return value max length is 255 characters\n    if (returnValue.length > 255) {\n      returnValue = returnValue.substring(0, 255);\n    }\n\n    this.apiLog(callbackName, \"returned: \" + returnValue, LogLevelEnum.INFO);\n\n    return returnValue;\n  }\n\n  /**\n   * Returns a comprehensive description of the errorNumber error.\n   *\n   * @param {string} callbackName\n   * @param {(string|number)} CMIErrorCode\n   * @return {string}\n   */\n  getDiagnostic(callbackName: string, CMIErrorCode: string | number): string {\n    let returnValue = \"\";\n\n    // Per SCORM spec: empty string requests diagnostic for the last error\n    const errorCode = CMIErrorCode === \"\" ? String(this.lastErrorCode) : CMIErrorCode;\n\n    if (errorCode !== null && errorCode !== \"\") {\n      // Check for custom diagnostic message first (set by throwSCORMError)\n      // Only use custom diagnostic if requesting info about the last error\n      const customDiagnostic = this._errorHandlingService.lastDiagnostic;\n      if (customDiagnostic && String(errorCode) === String(this.lastErrorCode)) {\n        returnValue = customDiagnostic;\n      } else {\n        returnValue = this.getLmsErrorMessageDetails(errorCode, true);\n      }\n      this.processListeners(callbackName);\n    }\n\n    // Per SCORM spec: GetDiagnostic return value max length is 255 characters\n    if (returnValue.length > 255) {\n      returnValue = returnValue.substring(0, 255);\n    }\n\n    this.apiLog(callbackName, \"returned: \" + returnValue, LogLevelEnum.INFO);\n\n    return returnValue;\n  }\n\n  /**\n   * Checks the LMS state and ensures it has been initialized.\n   *\n   * @param {boolean} checkTerminated\n   * @param {number} beforeInitError\n   * @param {number} afterTermError\n   * @return {boolean}\n   */\n  checkState(checkTerminated: boolean, beforeInitError: number, afterTermError: number): boolean {\n    if (this.isNotInitialized()) {\n      this.throwSCORMError(\"api\", beforeInitError);\n      return false;\n    } else if (checkTerminated && this.isTerminated()) {\n      this.throwSCORMError(\"api\", afterTermError);\n      return false;\n    }\n\n    return true;\n  }\n\n  /**\n   * Checks ID uniqueness in the objectives and interaction-objectives collections.\n   * SCORM 2004 RTE 4.2.9 permits repeated interaction IDs for journaling; only\n   * the objective IDs within each interaction must be unique. RTE 4.2.17 also\n   * requires unique IDs in the top-level objectives collection.\n   *\n   * @param {string} CMIElement - The element path (e.g., \"cmi.objectives.0.id\")\n   * @param {string} value - The ID value being set\n   * @return {boolean} - True if a duplicate would be created, false otherwise\n   * @protected\n   */\n  protected _checkForDuplicateId(CMIElement: string, value: string): boolean {\n    /**\n     * Helper to safely get a CMIArray property from an object\n     * @param obj - Object to check\n     * @param prop - Property name to get\n     * @returns The CMIArray if it exists, undefined otherwise\n     */\n    const getCMIArrayProperty = (obj: unknown, prop: string): CMIArray | undefined => {\n      if (obj && typeof obj === \"object\" && prop in obj) {\n        const value = (obj as Record<string, unknown>)[prop];\n        return value instanceof CMIArray ? value : undefined;\n      }\n      return undefined;\n    };\n\n    /**\n     * Helper to check for duplicate ID in a CMIArray\n     * @param array - The CMIArray to check\n     * @param currentIndex - Index to skip (the current item being set)\n     * @param idValue - The ID value to check for duplicates\n     * @returns True if a duplicate is found, false otherwise\n     */\n    const hasDuplicateId = (array: CMIArray, currentIndex: number, idValue: string): boolean => {\n      for (let i = 0; i < array.childArray.length; i++) {\n        if (i !== currentIndex) {\n          const child = array.childArray[i];\n          if (child && typeof child === \"object\" && \"id\" in child && child.id === idValue) {\n            return true;\n          }\n        }\n      }\n      return false;\n    };\n\n    // Match objectives: cmi.objectives.n.id\n    const objectivesMatch = CMIElement.match(/^cmi\\.objectives\\.(\\d+)\\.id$/);\n    if (objectivesMatch && objectivesMatch[1]) {\n      const currentIndex = parseInt(objectivesMatch[1], 10);\n      const objectives = getCMIArrayProperty(this.cmi, \"objectives\");\n      if (objectives) {\n        return hasDuplicateId(objectives, currentIndex, value);\n      }\n      return false;\n    }\n\n    // Match interaction objectives: cmi.interactions.n.objectives.m.id\n    const interactionObjectivesMatch = CMIElement.match(\n      /^cmi\\.interactions\\.(\\d+)\\.objectives\\.(\\d+)\\.id$/,\n    );\n    if (\n      interactionObjectivesMatch &&\n      interactionObjectivesMatch[1] &&\n      interactionObjectivesMatch[2]\n    ) {\n      const interactionIndex = parseInt(interactionObjectivesMatch[1], 10);\n      const currentObjIndex = parseInt(interactionObjectivesMatch[2], 10);\n      const interactions = getCMIArrayProperty(this.cmi, \"interactions\");\n      if (interactions) {\n        const interaction = interactions.childArray[interactionIndex];\n        if (interaction) {\n          const objectives = getCMIArrayProperty(interaction, \"objectives\");\n          if (objectives) {\n            return hasDuplicateId(objectives, currentObjIndex, value);\n          }\n        }\n      }\n      return false;\n    }\n\n    return false;\n  }\n\n  /**\n   * Returns the message that corresponds to errorNumber\n   * APIs that inherit BaseAPI should override this function\n   *\n   * @param {(string|number)} _errorNumber\n   * @param {boolean} _detail\n   * @return {string}\n   * @abstract\n   */\n  getLmsErrorMessageDetails(_errorNumber: string | number, _detail: boolean = false): string {\n    throw new Error(\"The getLmsErrorMessageDetails method has not been implemented\");\n  }\n\n  /**\n   * Gets the value for the specific element.\n   * APIs that inherit BaseAPI should override this function\n   *\n   * @param {string} _CMIElement\n   * @return {string}\n   * @abstract\n   */\n  getCMIValue(_CMIElement: string): string {\n    throw new Error(\"The getCMIValue method has not been implemented\");\n  }\n\n  /**\n   * Sets the value for the specific element.\n   * APIs that inherit BaseAPI should override this function\n   *\n   * @param {string} _CMIElement\n   * @param {any} _value\n   * @return {string}\n   * @abstract\n   */\n  setCMIValue(_CMIElement: string, _value: any): string {\n    throw new Error(\"The setCMIValue method has not been implemented\");\n  }\n\n  /**\n   * Shared API method to set a value for a given element.\n   * Delegates to CMIValueAccessService for the complex traversal logic.\n   *\n   * @param {string} methodName\n   * @param {boolean} scorm2004\n   * @param {string} CMIElement\n   * @param {any} value\n   * @return {string}\n   */\n  _commonSetCMIValue(\n    methodName: string,\n    scorm2004: boolean,\n    CMIElement: string,\n    value: any,\n  ): string {\n    const result = this._cmiValueAccessService.setCMIValue(\n      methodName,\n      scorm2004,\n      CMIElement,\n      value,\n    );\n    // Record a successful write so GetValue can distinguish \"never set\" from an\n    // explicit empty value (e.g. SetValue(x, \"\")). Tracking here covers both the\n    // public SetValue path and loadFromJSON, which also routes through here.\n    if (result === global_constants.SCORM_TRUE) {\n      this._setCMIElements.add(CMIElement);\n    }\n    return result;\n  }\n\n  /**\n   * Gets a value from the CMI Object.\n   * Delegates to CMIValueAccessService for the complex traversal logic.\n   *\n   * @param {string} methodName\n   * @param {boolean} scorm2004\n   * @param {string} CMIElement\n   * @return {any}\n   */\n  _commonGetCMIValue(methodName: string, scorm2004: boolean, CMIElement: string): any {\n    return this._cmiValueAccessService.getCMIValue(methodName, scorm2004, CMIElement);\n  }\n\n  /**\n   * Hook invoked by getValue after a successful resolution. Standards that must\n   * distinguish \"implemented but never set, no default value\" from a\n   * legitimately empty value override this to raise VALUE_NOT_INITIALIZED.\n   * Default is a no-op, so SCORM 1.2 / AICC keep returning \"\" with code 0.\n   *\n   * @param {string} _CMIElement - the element that was read\n   * @param {any} _returnValue - the value getCMIValue resolved\n   * @protected\n   */\n  protected checkUninitializedGet(_CMIElement: string, _returnValue: any): void {\n    // No-op by default; see Scorm2004API for the 403 (value not initialized) gate.\n  }\n\n  /**\n   * Returns true if the API's current state is STATE_INITIALIZED\n   *\n   * @return {boolean}\n   */\n  isInitialized(): boolean {\n    return this.currentState === global_constants.STATE_INITIALIZED;\n  }\n\n  /**\n   * Returns true if the API's current state is STATE_NOT_INITIALIZED\n   *\n   * @return {boolean}\n   */\n  isNotInitialized(): boolean {\n    return this.currentState === global_constants.STATE_NOT_INITIALIZED;\n  }\n\n  /**\n   * Returns true if the API's current state is STATE_TERMINATED\n   *\n   * @return {boolean}\n   */\n  isTerminated(): boolean {\n    return this.currentState === global_constants.STATE_TERMINATED;\n  }\n\n  /**\n   * Provides a mechanism for attaching to a specific SCORM event.\n   * This method allows you to register a callback function that will be executed\n   * when the specified event occurs.\n   *\n   * @param {string} listenerName - The name of the event to listen for (e.g., \"Initialize\", \"Terminate\", \"GetValue\", \"SetValue\", \"Commit\")\n   * @param {function} callback - The function to execute when the event occurs. The callback will receive relevant event data.\n   * @example\n   * // Listen for Initialize events\n   * api.on(\"Initialize\", function() {\n   *   console.log(\"API has been initialized\");\n   * });\n   *\n   * // Listen for SetValue events\n   * api.on(\"SetValue\", function(element, value) {\n   *   console.log(\"Setting \" + element + \" to \" + value);\n   * });\n   */\n  on(listenerName: string, callback: ScormEventCallback) {\n    this._eventService.on(listenerName, callback);\n  }\n\n  /**\n   * Provides a mechanism for detaching a specific SCORM event listener.\n   * This method removes a previously registered callback for an event.\n   * Both the event name and the callback reference must match what was used in the 'on' method.\n   *\n   * @param {string} listenerName - The name of the event to stop listening for\n   * @param {function} callback - The callback function to remove\n   * @example\n   * // Remove a specific listener\n   * const myCallback = function() { console.log(\"API initialized\"); };\n   * api.on(\"Initialize\", myCallback);\n   * // Later, when you want to remove it:\n   * api.off(\"Initialize\", myCallback);\n   */\n  off(listenerName: string, callback: ScormEventCallback) {\n    this._eventService.off(listenerName, callback);\n  }\n\n  /**\n   * Provides a mechanism for clearing all listeners from a specific SCORM event.\n   * This method removes all callbacks registered for the specified event.\n   *\n   * @param {string} listenerName - The name of the event to clear all listeners for\n   * @example\n   * // Remove all listeners for the Initialize event\n   * api.clear(\"Initialize\");\n   */\n  clear(listenerName: string) {\n    this._eventService.clear(listenerName);\n  }\n\n  /**\n   * Processes any 'on' listeners that have been created for a specific event.\n   * This method is called internally when SCORM events occur to notify all registered listeners.\n   * It triggers all callback functions registered for the specified event.\n   *\n   * @param {string} functionName - The name of the function/event that occurred\n   * @param {string} CMIElement - Optional CMI element involved in the event\n   * @param {any} value - Optional value associated with the event\n   * @param {CommitEventContext} context - Optional context for commit lifecycle events\n   */\n  processListeners(\n    functionName: string,\n    CMIElement?: string,\n    value?: any,\n    context?: CommitEventContext,\n  ) {\n    if (context !== undefined) {\n      this._eventService.processListeners(functionName, CMIElement, value, context);\n    } else {\n      this._eventService.processListeners(functionName, CMIElement, value);\n    }\n  }\n\n  /**\n   * Throws a SCORM error with the specified error number and optional message.\n   * This method sets the last error code and can be used to indicate that an operation failed.\n   * The error number should correspond to one of the standard SCORM error codes.\n   *\n   * @param {string} CMIElement\n   * @param {number} errorNumber - The SCORM error code to set\n   * @param {string} message - Optional custom error message to provide additional context\n   * @example\n   * // Throw a \"not initialized\" error\n   * this.throwSCORMError(301, \"The API must be initialized before calling GetValue\");\n   */\n  throwSCORMError(\n    CMIElement: string | undefined,\n    errorNumber: number | undefined,\n    message?: string,\n    messageLevel?: LogLevel,\n  ) {\n    this._errorHandlingService.throwSCORMError(CMIElement, errorNumber ?? 0, message, messageLevel);\n  }\n\n  /**\n   * Clears the last SCORM error code when an operation succeeds.\n   * This method is typically called after successful API operations to reset the error state.\n   * It only clears the error if the success parameter is \"true\".\n   *\n   * @param {string} success - A string indicating whether the operation succeeded (\"true\" or \"false\")\n   * @example\n   * // Clear error after successful operation\n   * this.clearSCORMError(\"true\");\n   */\n  clearSCORMError(success: string) {\n    this._errorHandlingService.clearSCORMError(success);\n  }\n\n  /**\n   * Sets one value during loadFromJSON / loadFromFlattenedJSON. Throws when the\n   * value is rejected so the loader can skip it, and leaves lastErrorCode as it\n   * was before the call either way.\n   */\n  private loadCMIValue(CMIElement: string, value: any): void {\n    const previousErrorCode = this.lastErrorCode;\n    this.lastErrorCode = \"0\";\n    try {\n      this.setCMIValue(CMIElement, value);\n      if (this.lastErrorCode !== \"0\") {\n        throw new Error(`SCORM error ${this.lastErrorCode}`);\n      }\n    } finally {\n      this.lastErrorCode = previousErrorCode;\n    }\n  }\n\n  /**\n   * Load the CMI from a flattened JSON object.\n   * This method populates the CMI data model from a flattened JSON structure\n   * where keys represent CMI element paths (e.g., \"cmi.core.student_id\").\n   *\n   * @param {StringKeyMap} json - The flattened JSON object containing CMI data\n   * @param {string} CMIElement - Optional base CMI element path to prepend to all keys\n   * @example\n   * // Load data from a flattened JSON structure\n   * api.loadFromFlattenedJSON({\n   *   \"cmi.core.student_id\": \"12345\",\n   *   \"cmi.core.student_name\": \"John Doe\",\n   *   \"cmi.core.lesson_status\": \"incomplete\"\n   * });\n   */\n  loadFromFlattenedJSON(json: StringKeyMap, CMIElement?: string) {\n    if (!CMIElement) {\n      // by default, we start from a blank string because we're expecting each element to start with `cmi`\n      CMIElement = \"\";\n    }\n\n    this._serializationService.loadFromFlattenedJSON(\n      json,\n      CMIElement,\n      (CMIElement, value) => this.loadCMIValue(CMIElement, value),\n      () => this.isNotInitialized(),\n      (data: StringKeyMap) => {\n        this.startingData = data;\n      },\n      (element, error) => {\n        this.apiLog(\n          \"loadFromJSON\",\n          `Skipped invalid value for ${element}: ${String(error)}`,\n          LogLevelEnum.WARN,\n        );\n      },\n    );\n  }\n\n  /**\n   * Returns a flattened JSON object representing the current CMI data.\n   */\n  getFlattenedCMI(): StringKeyMap {\n    return flatten(this.renderCMIToJSONObject());\n  }\n\n  /**\n   * Loads CMI data from a hierarchical JSON object.\n   * This method populates the CMI data model from a nested JSON structure\n   * that mirrors the CMI object hierarchy.\n   *\n   * @param {StringKeyMap} json - The hierarchical JSON object containing CMI data\n   * @param {string} CMIElement - Optional base CMI element path to prepend to all keys\n   * @example\n   * // Load data from a hierarchical JSON structure\n   * api.loadFromJSON({\n   *   core: {\n   *     student_id: \"12345\",\n   *     student_name: \"John Doe\",\n   *     lesson_status: \"incomplete\"\n   *   },\n   *   objectives: [\n   *     { id: \"obj1\", score: { raw: 85 } }\n   *   ]\n   * });\n   */\n  loadFromJSON(json: StringKeyMap, CMIElement: string = \"\") {\n    if (\n      (!CMIElement || CMIElement === \"\") &&\n      !Object.hasOwnProperty.call(json, \"cmi\") &&\n      !Object.hasOwnProperty.call(json, \"adl\")\n    ) {\n      // providing a backward compatibility for the old v1 API\n      CMIElement = \"cmi\";\n    }\n    this._serializationService.loadFromJSON(\n      json,\n      CMIElement,\n      (CMIElement, value) => this.loadCMIValue(CMIElement, value),\n      () => this.isNotInitialized(),\n      (data: StringKeyMap) => {\n        this.startingData = data;\n      },\n      (element, error) => {\n        this.apiLog(\n          \"loadFromJSON\",\n          `Skipped invalid value for ${element}: ${String(error)}`,\n          LogLevelEnum.WARN,\n        );\n      },\n    );\n  }\n\n  /**\n   * Render the CMI object to a JSON string for sending to an LMS.\n   * This method serializes the current CMI data model to a JSON string.\n   * The output format is controlled by the sendFullCommit setting.\n   *\n   * @return {string} A JSON string representation of the CMI data\n   * @example\n   * // Get the current CMI data as a JSON string\n   * const jsonString = api.renderCMIToJSONString();\n   * console.log(jsonString); // '{\"core\":{\"student_id\":\"12345\",...}}'\n   */\n  renderCMIToJSONString(): string {\n    return this._serializationService.renderCMIToJSONString(this.cmi, this.settings.sendFullCommit);\n  }\n\n  /**\n   * Returns a JavaScript object representing the current CMI data.\n   * This method creates a plain JavaScript object that mirrors the\n   * structure of the CMI data model, suitable for further processing.\n   *\n   * @return {StringKeyMap} A JavaScript object representing the CMI data\n   * @example\n   * // Get the current CMI data as a JavaScript object\n   * const cmiObject = api.renderCMIToJSONObject();\n   * console.log(cmiObject.core.student_id); // \"12345\"\n   */\n  renderCMIToJSONObject(): StringKeyMap {\n    return this._serializationService.renderCMIToJSONObject(this.cmi, this.settings.sendFullCommit);\n  }\n\n  /**\n   * Process an HTTP request\n   *\n   * @param {string} url - The URL to send the request to\n   * @param {CommitObject | StringKeyMap | Array<any>} params - The parameters to send\n   * @param {boolean} immediate - Whether to send the request immediately without waiting\n   * @param {CommitTrigger} [trigger] - What initiated the commit\n   * @returns {ResultObject} - The result of the request\n   */\n  processHttpRequest(\n    url: string,\n    params: CommitObject | StringKeyMap | Array<any>,\n    immediate: boolean = false,\n    trigger?: CommitTrigger,\n  ): ResultObject {\n    const sequence = ++this._commitSequence;\n    this._pendingCommitCount += 1;\n\n    let settled = false;\n    let completionDeferred = false;\n    const settle = (): void => {\n      if (settled) {\n        return;\n      }\n\n      settled = true;\n      this._pendingCommitCount -= 1;\n      if (this._pendingCommitCount === 0) {\n        this._flushCommitSettleWaiters();\n      }\n    };\n\n    try {\n      const resolvedTrigger: CommitTrigger = trigger ?? (immediate ? \"terminate\" : \"manual\");\n      let finalParams: CommitObject | StringKeyMap | Array<any> = params;\n\n      if (immediate && this.settings.terminateCommitPayloadField) {\n        const field = this.settings.terminateCommitPayloadField;\n        if (Array.isArray(finalParams)) {\n          finalParams = [...finalParams, `${encodeURIComponent(field)}=true`];\n        } else if (finalParams && typeof finalParams === \"object\") {\n          finalParams = { ...finalParams, [field]: true };\n        }\n      }\n\n      if (this.settings.includeCommitSequence === true) {\n        if (Array.isArray(finalParams)) {\n          finalParams = [...finalParams, `commitSequence=${sequence}`];\n        } else if (finalParams && typeof finalParams === \"object\") {\n          finalParams = { ...finalParams, commitSequence: sequence };\n        }\n      }\n\n      const finalUrl =\n        immediate && this.settings.terminateCommitParam\n          ? appendQueryParam(url, this.settings.terminateCommitParam, \"true\")\n          : url;\n      const metadata: CommitMetadata = {\n        isTerminateCommit: immediate,\n        trigger: resolvedTrigger,\n        sequence,\n      };\n      const context: CommitEventContext = {\n        url: finalUrl,\n        trigger: resolvedTrigger,\n        isTerminateCommit: immediate,\n        sequence,\n      };\n\n      // If offline support is enabled and device is offline, store data locally instead of sending\n      if (\n        this.settings.enableOfflineSupport &&\n        this._offlineStorageService &&\n        !this._offlineStorageService.isDeviceOnline() &&\n        this._courseId\n      ) {\n        this.apiLog(\n          \"processHttpRequest\",\n          \"Device is offline, storing data locally\",\n          LogLevelEnum.INFO,\n        );\n\n        return this._offlineStorageService.storeOffline(this._courseId, finalParams, {\n          learnerId: this.getOfflineLearnerId(),\n          isTerminateCommit: immediate,\n          sequence,\n        });\n      }\n\n      // Otherwise, proceed with HTTP request (synchronous or async based on service)\n      const apiLog = (functionName: string, message: any, level: LogLevelEnum, element?: string) =>\n        this.apiLog(functionName, message, level, element);\n      const processListeners = (functionName: string, CMIElement?: string, value?: any) => {\n        if (functionName === \"CommitSuccess\" || functionName === \"CommitError\") {\n          if (functionName === \"CommitError\" && typeof value === \"number\") {\n            context.errorCode = value;\n          }\n          settle();\n          this.processListeners(functionName, CMIElement, value, context);\n        } else {\n          this.processListeners(functionName, CMIElement, value);\n        }\n      };\n      const result = this._httpService.processHttpRequest(\n        finalUrl,\n        finalParams,\n        immediate,\n        apiLog,\n        processListeners,\n        metadata,\n        settle,\n      );\n      completionDeferred = this._httpService.reportsRequestCompletion === true;\n      return result;\n    } finally {\n      if (!completionDeferred) {\n        settle();\n      }\n    }\n  }\n\n  /**\n   * Schedules a commit operation to occur after a specified delay.\n   * This method is used to implement auto-commit functionality, where data\n   * is periodically sent to the LMS without requiring explicit commit calls.\n   *\n   * @param {number} when - The number of milliseconds to wait before committing\n   * @param {string} callback - The name of the commit event callback\n   * @example\n   * // Schedule a commit to happen in 60 seconds\n   * api.scheduleCommit(60000, \"commit\");\n   */\n  scheduleCommit(when: number, callback: string) {\n    if (!this._timeout) {\n      this._timeout = new ScheduledCommit(this, when, callback);\n      this.apiLog(\"scheduleCommit\", \"scheduled\", LogLevelEnum.DEBUG, \"\");\n    }\n  }\n\n  /**\n   * Clears and cancels any currently scheduled commits.\n   * This method is typically called when an explicit commit is performed\n   * or when the API is terminated, to prevent redundant commits.\n   *\n   * @example\n   * // Cancel any pending scheduled commits\n   * api.clearScheduledCommit();\n   */\n  clearScheduledCommit() {\n    if (this._timeout) {\n      this._timeout.cancel();\n      this._timeout = undefined;\n      this.apiLog(\"clearScheduledCommit\", \"cleared\", LogLevelEnum.DEBUG, \"\");\n    }\n  }\n\n  /**\n   * Checks if an object has a specific property, using multiple detection methods.\n   * This method performs a thorough check for property existence by:\n   * 1. Checking if it's an own property using Object.hasOwnProperty\n   * 2. Checking if it's defined in the prototype with a property descriptor\n   * 3. Checking if it's accessible via the 'in' operator (includes inherited properties)\n   *\n   * @param {StringKeyMap} StringKeyMap - The object to check for the property\n   * @param {string} attribute - The property name to look for\n   * @return {boolean} True if the property exists on the object or its prototype chain\n   * @private\n   *\n   * @example\n   * // Check for an own property\n   * const obj = { name: \"John\" };\n   * this._checkObjectHasProperty(obj, \"name\"); // Returns true\n   *\n   * @example\n   * // Check for an inherited property\n   * class Parent { get type() { return \"parent\"; } }\n   * const child = Object.create(new Parent());\n   * this._checkObjectHasProperty(child, \"type\"); // Returns true\n   *\n   * @example\n   * // Check for a non-existent property\n   * const obj = { name: \"John\" };\n   * this._checkObjectHasProperty(obj, \"age\"); // Returns false\n   */\n  private _checkObjectHasProperty(obj: StringKeyMap, attribute: string): boolean {\n    // Handle primitives - they don't have custom properties and 'in' operator throws on them\n    if (obj === null || obj === undefined || typeof obj !== \"object\") {\n      return false;\n    }\n    return (\n      Object.hasOwnProperty.call(obj, attribute) ||\n      Object.getOwnPropertyDescriptor(Object.getPrototypeOf(obj), attribute) != null ||\n      attribute in obj\n    );\n  }\n\n  /**\n   * Handles exceptions that occur when accessing CMI values.\n   * This method delegates to the ErrorHandlingService to process exceptions\n   * that occur during CMI data operations, ensuring consistent error handling\n   * throughout the API.\n   *\n   * @param {string} CMIElement\n   * @param {any} e - The exception that was thrown\n   * @param {string} returnValue - The default return value to use if an error occurs\n   * @return {string} Either the original returnValue or SCORM_FALSE if an error occurred\n   * @private\n   *\n   * @example\n   * // Handle a validation error when getting a CMI value\n   * try {\n   *   return this.getCMIValue(\"cmi.core.score.raw\");\n   * } catch (e) {\n   *   return this.handleValueAccessException(e, \"\");\n   * }\n   *\n   * @example\n   * // Handle a general error when setting a CMI value\n   * try {\n   *   this.setCMIValue(\"cmi.core.lesson_status\", \"completed\");\n   *   return \"true\";\n   * } catch (e) {\n   *   return this.handleValueAccessException(e, \"false\");\n   * }\n   */\n  private handleValueAccessException(CMIElement: string, e: any, returnValue: string): string {\n    if (e instanceof ValidationError) {\n      this.lastErrorCode = String(e.errorCode);\n      // Per SCORM spec: GetValue returns \"\" on error, SetValue returns \"false\"\n      // The caller passes the appropriate default, so we preserve it\n      // Only override to \"false\" if returnValue wasn't already set to \"\"\n      if (returnValue !== \"\") {\n        returnValue = global_constants.SCORM_FALSE;\n      }\n      this.throwSCORMError(CMIElement, e.errorCode, e.errorMessage);\n    } else {\n      if (e instanceof Error && e.message) {\n        this.throwSCORMError(CMIElement, this._error_codes.GENERAL, e.message);\n      } else {\n        this.throwSCORMError(CMIElement, this._error_codes.GENERAL, \"Unknown error\");\n      }\n    }\n    return returnValue;\n  }\n\n  /**\n   * Builds the commit object to be sent to the LMS.\n   * This method delegates to the SerializationService to create a properly\n   * formatted object containing the CMI data that needs to be sent to the LMS.\n   * The format and content of the commit object depend on whether this is a\n   * regular commit or a termination commit.\n   *\n   * @param {boolean} terminateCommit - Whether this is a termination commit\n   * @return {CommitObject|StringKeyMap|Array} The formatted commit object\n   * @protected\n   *\n   * @example\n   * // Create a regular commit object\n   * const regularCommit = this.getCommitObject(false);\n   * // Result might be: { cmi: { core: { lesson_status: \"incomplete\" } } }\n   *\n   * @example\n   * // Create a termination commit object (includes total_time)\n   * const terminationCommit = this.getCommitObject(true);\n   * // Result might be: { cmi: { core: { lesson_status: \"completed\", total_time: \"PT1H30M\" } } }\n   */\n  protected getCommitObject(terminateCommit: boolean): CommitObject | StringKeyMap | Array<any> {\n    return this._serializationService.getCommitObject(\n      terminateCommit,\n      this.settings.alwaysSendTotalTime,\n      this.settings.renderCommonCommitFields,\n      (terminateCommit: boolean, includeTotalTime?: boolean) =>\n        this.renderCommitObject(terminateCommit, includeTotalTime),\n      (terminateCommit: boolean, includeTotalTime?: boolean) =>\n        this.renderCommitCMI(terminateCommit, includeTotalTime),\n      this.settings.logLevel,\n    );\n  }\n}\n","import { BaseCMI } from \"./base_cmi\";\nimport { BaseScormValidationError } from \"../../exceptions\";\nimport {\n  scorm12_constants,\n  scorm12_errors,\n  scorm12_regex,\n} from \"../../constants\";\nimport { validationService } from \"../../services\";\nimport { ScoreObject } from \"../../types\";\n\n/**\n * Base class for cmi *.score objects\n */\nexport class CMIScore extends BaseCMI {\n  private readonly __children: string;\n  /**\n   * Score range validation pattern (e.g., \"0#100\" for SCORM 1.2).\n   * Set to `false` to disable range validation (e.g., for SCORM 2004 where scores have no upper bound).\n   * This property is intentionally unused in the base class but provides subclass flexibility.\n   */\n  private readonly __score_range: string | false;\n  private readonly __invalid_error_code: number;\n  private readonly __invalid_type_code: number;\n  private readonly __invalid_range_code: number;\n  private readonly __decimal_regex: string;\n  private readonly __error_class: typeof BaseScormValidationError;\n  /**\n   * When true, an empty string is a valid value (clears the element). SCORM 1.2\n   * score elements may be blank per the ADL 1.2 CTS; SCORM 2004 leaves this off.\n   */\n  private readonly __allow_empty_string: boolean;\n  protected _raw = \"\";\n  protected _min = \"\";\n  protected _max: string;\n\n  /**\n   * Constructor for *.score\n   *\n   * SPEC COMPLIANCE NOTE for _max default:\n   * The SCORM 1.2 specification defines the default value for score.max as empty string (\"\").\n   * This implementation defaults to \"100\" instead for the following reasons:\n   *\n   * 1. Most SCOs expect a 0-100 scale and don't explicitly set max\n   * 2. An empty max creates ambiguity in score interpretation\n   * 3. \"100\" is the most common expected value and simplifies SCO development\n   * 4. This matches real-world LMS behavior (most default to 100)\n   * 5. SCOs can still explicitly set max=\"\" if needed\n   *\n   * Strict spec default would be: \"\"\n   *\n   * @param params - Configuration parameters\n   * @param params.score_range - Optional range pattern. When provided, uses scorm12_regex.score_range.\n   *                             When omitted or falsy, disables range validation (sets to false).\n   *                             SCORM 1.2 passes a truthy value to enable \"0#100\" validation.\n   *                             SCORM 2004 omits this to allow unbounded scores.\n   */\n  constructor(params: {\n    CMIElement: string;\n    score_children?: string;\n    score_range?: string;\n    max?: string;\n    invalidErrorCode?: number;\n    invalidTypeCode?: number;\n    invalidRangeCode?: number;\n    decimalRegex?: string;\n    errorClass: typeof BaseScormValidationError;\n    allowEmptyString?: boolean;\n  }) {\n    super(params.CMIElement);\n\n    this.__children = params.score_children || scorm12_constants.score_children;\n    // score_range parameter controls whether range validation is enabled:\n    // - Truthy value (e.g., \"0#100\"): enables range validation using scorm12_regex.score_range\n    // - Falsy/omitted: disables range validation by setting to false\n    this.__score_range = !params.score_range ? false : scorm12_regex.score_range;\n    // See SPEC COMPLIANCE NOTE above for why default is \"100\" instead of \"\"\n    this._max = params.max || params.max === \"\" ? params.max : \"100\";\n    this.__invalid_error_code =\n      params.invalidErrorCode || (scorm12_errors.INVALID_SET_VALUE as number);\n    this.__invalid_type_code = params.invalidTypeCode || (scorm12_errors.TYPE_MISMATCH as number);\n    this.__invalid_range_code =\n      params.invalidRangeCode || (scorm12_errors.VALUE_OUT_OF_RANGE as number);\n    this.__decimal_regex = params.decimalRegex || scorm12_regex.CMIDecimal;\n    this.__error_class = params.errorClass;\n    this.__allow_empty_string = params.allowEmptyString ?? false;\n  }\n\n  /**\n   * Called when the API has been reset\n   *\n   * SCORE-01: Resets _raw and _min to empty strings to match subclass behavior.\n   * _max is NOT reset here as it has a non-trivial default (\"100\") that is\n   * handled by the constructor or reinitialization logic.\n   */\n  reset(): void {\n    this._initialized = false;\n    this._raw = \"\";\n    this._min = \"\";\n  }\n\n  /**\n   * Getter for _children\n   * @return {string}\n   */\n  get _children(): string {\n    return this.__children;\n  }\n\n  /**\n   * Setter for _children. Just throws an error.\n   * @param {string} _children\n   */\n  set _children(_children: string) {\n    throw new this.__error_class(this._cmi_element + \"._children\", this.__invalid_error_code);\n  }\n\n  /**\n   * Getter for _raw\n   * @return {string}\n   */\n  get raw(): string {\n    return this._raw;\n  }\n\n  /**\n   * Setter for _raw\n   * @param {string} raw\n   */\n  set raw(raw: string) {\n    if (\n      validationService.validateScore(\n        this._cmi_element + \".raw\",\n        raw,\n        this.__decimal_regex,\n        this.__score_range,\n        this.__invalid_type_code,\n        this.__invalid_range_code,\n        this.__error_class,\n        this.__allow_empty_string,\n      )\n    ) {\n      this._raw = raw;\n    }\n  }\n\n  /**\n   * Getter for _min\n   * @return {string}\n   */\n  get min(): string {\n    return this._min;\n  }\n\n  /**\n   * Setter for _min\n   * @param {string} min\n   */\n  set min(min: string) {\n    if (\n      validationService.validateScore(\n        this._cmi_element + \".min\",\n        min,\n        this.__decimal_regex,\n        this.__score_range,\n        this.__invalid_type_code,\n        this.__invalid_range_code,\n        this.__error_class,\n        this.__allow_empty_string,\n      )\n    ) {\n      this._min = min;\n    }\n  }\n\n  /**\n   * Getter for _max\n   * @return {string}\n   */\n  get max(): string {\n    return this._max;\n  }\n\n  /**\n   * Setter for _max\n   * @param {string} max\n   */\n  set max(max: string) {\n    if (\n      validationService.validateScore(\n        this._cmi_element + \".max\",\n        max,\n        this.__decimal_regex,\n        this.__score_range,\n        this.__invalid_type_code,\n        this.__invalid_range_code,\n        this.__error_class,\n        this.__allow_empty_string,\n      )\n    ) {\n      this._max = max;\n    }\n  }\n\n  /**\n   * Gets score object with numeric values\n   * @return {ScoreObject}\n   */\n  public getScoreObject(): ScoreObject {\n    const scoreObject: ScoreObject = {};\n    if (!Number.isNaN(Number.parseFloat(this.raw))) {\n      scoreObject.raw = Number.parseFloat(this.raw);\n    }\n    if (!Number.isNaN(Number.parseFloat(this.min))) {\n      scoreObject.min = Number.parseFloat(this.min);\n    }\n    if (!Number.isNaN(Number.parseFloat(this.max))) {\n      scoreObject.max = Number.parseFloat(this.max);\n    }\n    return scoreObject;\n  }\n\n  /**\n   * toJSON for *.score\n   * @return {\n   *    {\n   *      min: string,\n   *      max: string,\n   *      raw: string\n   *    }\n   *    }\n   */\n  toJSON(): {\n    min: string;\n    max: string;\n    raw: string;\n  } {\n    this.jsonString = true;\n    const result = {\n      raw: this.raw,\n      min: this.min,\n      max: this.max,\n    };\n    this.jsonString = false;\n    return result;\n  }\n}\n","import { BaseCMI } from \"../common/base_cmi\";\nimport { CMIScore } from \"../common/score\";\nimport { Scorm12ValidationError } from \"../../exceptions/scorm12_exceptions\";\nimport { check12ValidFormat } from \"../scorm12/validation\";\nimport {\n  scorm12_constants,\n  scorm12_errors,\n  scorm12_regex,\n} from \"../../constants\";\nimport {\n  addHHMMSSTimeStrings,\n  getSecondsAsHHMMSS,\n  getTimeAsSeconds,\n} from \"../../utilities\";\n\n/**\n * Class representing the `cmi.core` object\n * @extends BaseCMI\n */\nexport class CMICore extends BaseCMI {\n  /**\n   * Constructor for `cmi.core`\n   */\n  constructor() {\n    super(\"cmi.core\");\n    this.score = new CMIScore({\n      CMIElement: \"cmi.core.score\",\n      score_children: scorm12_constants.score_children,\n      score_range: scorm12_regex.score_range,\n      invalidErrorCode: scorm12_errors.INVALID_SET_VALUE as number,\n      invalidTypeCode: scorm12_errors.TYPE_MISMATCH as number,\n      invalidRangeCode: scorm12_errors.VALUE_OUT_OF_RANGE as number,\n      errorClass: Scorm12ValidationError,\n      // SCORM 1.2 score elements may be set blank (clears the value), per ADL 1.2 CTS.\n      allowEmptyString: true,\n    });\n  }\n\n  public readonly score: CMIScore;\n\n  /**\n   * Called when the API has been initialized after the CMI has been created\n   */\n  override initialize() {\n    super.initialize();\n    this.score?.initialize();\n  }\n\n  private readonly __children = scorm12_constants.core_children;\n  private _student_id = \"\";\n  private _student_name = \"\";\n  private _lesson_location = \"\";\n  private _credit = \"\";\n  private _lesson_status = \"not attempted\";\n  private _entry = \"\";\n  private _total_time = \"\";\n  private _lesson_mode = \"normal\";\n  private _exit = \"\";\n  private _session_time = \"00:00:00\";\n  private _suspend_data = \"\";\n\n  /**\n   * Called when the API has been reset\n   */\n  reset(): void {\n    this._initialized = false;\n\n    this._exit = \"\";\n    this._entry = \"\";\n\n    /**\n     * Resetting ensures we accurately track the time spent on each SCO session independently.\n     * Each new session should start from zero, so we can reset cmi.core.session_time at the beginning of each session.\n     */\n    this._session_time = \"00:00:00\";\n\n    this.score?.reset();\n  }\n\n  /**\n   * Getter for __children\n   * @return {string}\n   * @private\n   */\n  get _children(): string {\n    return this.__children;\n  }\n\n  /**\n   * Setter for __children. Just throws an error.\n   * @param {string} _children\n   * @private\n   */\n  set _children(_children: string) {\n    throw new Scorm12ValidationError(\n      this._cmi_element + \"._children\",\n      scorm12_errors.INVALID_SET_VALUE as number,\n    );\n  }\n\n  /**\n   * Getter for _student_id\n   * @return {string}\n   */\n  get student_id(): string {\n    return this._student_id;\n  }\n\n  /**\n   * Setter for _student_id. Can only be called before  initialization.\n   * @param {string} student_id\n   */\n  set student_id(student_id: string) {\n    if (this.initialized) {\n      throw new Scorm12ValidationError(\n        this._cmi_element + \".student_id\",\n        scorm12_errors.READ_ONLY_ELEMENT as number,\n      );\n    } else {\n      this._student_id = student_id;\n    }\n  }\n\n  /**\n   * Getter for _student_name\n   * @return {string}\n   */\n  get student_name(): string {\n    return this._student_name;\n  }\n\n  /**\n   * Setter for _student_name. Can only be called before  initialization.\n   * @param {string} student_name\n   */\n  set student_name(student_name: string) {\n    if (this.initialized) {\n      throw new Scorm12ValidationError(\n        this._cmi_element + \".student_name\",\n        scorm12_errors.READ_ONLY_ELEMENT as number,\n      );\n    } else {\n      this._student_name = student_name;\n    }\n  }\n\n  /**\n   * Getter for _lesson_location\n   * @return {string}\n   */\n  get lesson_location(): string {\n    return this._lesson_location;\n  }\n\n  /**\n   * Setter for _lesson_location\n   * @param {string} lesson_location\n   */\n  set lesson_location(lesson_location: string) {\n    if (\n      check12ValidFormat(\n        this._cmi_element + \".lesson_location\",\n        lesson_location,\n        scorm12_regex.CMIString256,\n        true,\n      )\n    ) {\n      this._lesson_location = lesson_location;\n    }\n  }\n\n  /**\n   * Getter for _credit\n   * @return {string}\n   */\n  get credit(): string {\n    return this._credit;\n  }\n\n  /**\n   * Setter for _credit. Can only be called before  initialization.\n   * @param {string} credit\n   */\n  set credit(credit: string) {\n    if (this.initialized) {\n      throw new Scorm12ValidationError(\n        this._cmi_element + \".credit\",\n        scorm12_errors.READ_ONLY_ELEMENT as number,\n      );\n    } else {\n      if (\n        check12ValidFormat(this._cmi_element + \".credit\", credit, scorm12_regex.CMICredit, true)\n      ) {\n        this._credit = credit;\n      }\n    }\n  }\n\n  /**\n   * Getter for _lesson_status\n   * @spec RTE 3.4.2.1.7 - cmi.core.lesson_status\n   * @return {string}\n   */\n  get lesson_status(): string {\n    return this._lesson_status;\n  }\n\n  /**\n   * Setter for _lesson_status\n   * @spec RTE 3.4.2.1.7 - cmi.core.lesson_status\n   * @param {string} lesson_status\n   */\n  set lesson_status(lesson_status: string) {\n    if (this.initialized) {\n      if (\n        check12ValidFormat(\n          this._cmi_element + \".lesson_status\",\n          lesson_status,\n          scorm12_regex.CMIStatus,\n        )\n      ) {\n        this._lesson_status = lesson_status;\n      }\n    } else {\n      if (\n        check12ValidFormat(\n          this._cmi_element + \".lesson_status\",\n          lesson_status,\n          scorm12_regex.CMIStatus2,\n        )\n      ) {\n        this._lesson_status = lesson_status;\n      }\n    }\n  }\n\n  /**\n   * Getter for _entry\n   * @return {string}\n   */\n  get entry(): string {\n    return this._entry;\n  }\n\n  /**\n   * Setter for _entry. Can only be called before  initialization.\n   * @param {string} entry\n   */\n  set entry(entry: string) {\n    if (this.initialized) {\n      throw new Scorm12ValidationError(\n        this._cmi_element + \".entry\",\n        scorm12_errors.READ_ONLY_ELEMENT as number,\n      );\n    } else {\n      if (check12ValidFormat(this._cmi_element + \".entry\", entry, scorm12_regex.CMIEntry, true)) {\n        this._entry = entry;\n      }\n    }\n  }\n\n  /**\n   * Getter for _total_time\n   * @spec RTE 3.4.2.1.13 - cmi.core.total_time\n   * @return {string}\n   */\n  get total_time(): string {\n    return this._total_time;\n  }\n\n  /**\n   * Setter for _total_time. Can only be called before  initialization.\n   * @spec RTE 3.4.2.1.13 - cmi.core.total_time\n   * @param {string} total_time\n   */\n  set total_time(total_time: string) {\n    if (this.initialized) {\n      throw new Scorm12ValidationError(\n        this._cmi_element + \".total_time\",\n        scorm12_errors.READ_ONLY_ELEMENT as number,\n      );\n    } else {\n      if (\n        check12ValidFormat(\n          this._cmi_element + \".total_time\",\n          total_time,\n          scorm12_regex.CMITimespan,\n          true,\n        )\n      ) {\n        if (total_time) {\n          const totalSeconds = getTimeAsSeconds(total_time, scorm12_regex.CMITimespan);\n          this._total_time = getSecondsAsHHMMSS(totalSeconds);\n        } else {\n          this._total_time = total_time;\n        }\n      }\n    }\n  }\n\n  /**\n   * Getter for _lesson_mode\n   * @return {string}\n   */\n  get lesson_mode(): string {\n    return this._lesson_mode;\n  }\n\n  /**\n   * Setter for _lesson_mode. Can only be called before  initialization.\n   * @param {string} lesson_mode\n   */\n  set lesson_mode(lesson_mode: string) {\n    if (this.initialized) {\n      throw new Scorm12ValidationError(\n        this._cmi_element + \".lesson_mode\",\n        scorm12_errors.READ_ONLY_ELEMENT as number,\n      );\n    } else {\n      if (\n        check12ValidFormat(this._cmi_element + \".lesson_mode\", lesson_mode, scorm12_regex.CMILessonMode)\n      ) {\n        this._lesson_mode = lesson_mode;\n      }\n    }\n  }\n\n  /**\n   * Getter for _exit. Should only be called during JSON export.\n   * @return {string}\n   */\n  get exit(): string {\n    if (!this.jsonString) {\n      throw new Scorm12ValidationError(\n        this._cmi_element + \".exit\",\n        scorm12_errors.WRITE_ONLY_ELEMENT as number,\n      );\n    }\n    return this._exit;\n  }\n\n  /**\n   * Setter for _exit\n   *\n   * @spec RTE 3.4.2.1.4 - cmi.core.exit\n   *\n   * SPEC COMPLIANCE NOTE:\n   * The SCORM 1.2 specification defines exit vocabulary as: \"time-out\", \"suspend\", \"logout\", or \"\"\n   * The value \"normal\" is NOT part of the SCORM 1.2 vocabulary (it's a SCORM 2004 value).\n   *\n   * This implementation accepts \"normal\" and normalizes it to \"\" (empty string) for the\n   * following reasons:\n   *\n   * 1. Legacy content authored for SCORM 2004 sometimes runs in SCORM 1.2 mode\n   * 2. Some authoring tools incorrectly use \"normal\" for SCORM 1.2 content\n   * 3. Rejecting \"normal\" would break content with no user benefit\n   * 4. Empty string (\"\") has the same semantic meaning as \"normal\" (regular exit)\n   * 5. A console warning is logged to help developers identify the issue\n   *\n   * Strict spec vocabulary: \"time-out\" | \"suspend\" | \"logout\" | \"\"\n   *\n   * @param {string} exit\n   */\n  set exit(exit: string) {\n    if (exit === \"normal\") {\n      console.warn(\n        \"SCORM 1.2: Received non-standard value 'normal' for cmi.core.exit; normalizing to empty string.\",\n      );\n      exit = \"\";\n    }\n    if (check12ValidFormat(this._cmi_element + \".exit\", exit, scorm12_regex.CMIExit, true)) {\n      this._exit = exit;\n    }\n  }\n\n  /**\n   * Getter for _session_time. Should only be called during JSON export.\n   * @return {string}\n   */\n  get session_time(): string {\n    if (!this.jsonString) {\n      throw new Scorm12ValidationError(\n        this._cmi_element + \".session_time\",\n        scorm12_errors.WRITE_ONLY_ELEMENT as number,\n      );\n    }\n    return this._session_time;\n  }\n\n  /**\n   * Setter for _session_time\n   * @param {string} session_time\n   */\n  set session_time(session_time: string) {\n    // ADL accepts blank timespans; preserve any previously recorded session time.\n    if (session_time === \"\") {\n      return;\n    }\n\n    if (\n      check12ValidFormat(\n        this._cmi_element + \".session_time\",\n        session_time,\n        scorm12_regex.CMITimespan,\n      )\n    ) {\n      const totalSeconds = getTimeAsSeconds(session_time, scorm12_regex.CMITimespan);\n      this._session_time = getSecondsAsHHMMSS(totalSeconds);\n    }\n  }\n\n  /**\n   * Getter for _suspend_data\n   * @return {string}\n   */\n  get suspend_data(): string {\n    return this._suspend_data;\n  }\n\n  /**\n   * Setter for _suspend_data\n   *\n   * SPEC COMPLIANCE NOTE:\n   * Uses CMIString64000 (64000 char limit) instead of spec-defined CMIString4096.\n   * See scorm12_regex.CMIString64000 documentation for rationale.\n   *\n   * @param {string} suspend_data\n   */\n  set suspend_data(suspend_data: string) {\n    if (\n      check12ValidFormat(\n        this._cmi_element + \".suspend_data\",\n        suspend_data,\n        scorm12_regex.CMIString64000,\n        true,\n      )\n    ) {\n      this._suspend_data = suspend_data;\n    }\n  }\n\n  /**\n   * Adds the current session time to the existing total time.\n   * @param {number} start_time\n   * @return {string}\n   */\n  getCurrentTotalTime(start_time: number | undefined): string {\n    let sessionTime = this._session_time;\n    if (typeof start_time !== \"undefined\") {\n      const seconds = new Date().getTime() - start_time;\n      sessionTime = getSecondsAsHHMMSS(seconds / 1000);\n    }\n\n    return addHHMMSSTimeStrings(\n      this._total_time,\n      sessionTime,\n      new RegExp(scorm12_regex.CMITimespan),\n    );\n  }\n\n  /**\n   * toJSON for cmi.core\n   *\n   * @return {\n   *    {\n   *      student_name: string,\n   *      entry: string,\n   *      exit: string,\n   *      score: CMIScore,\n   *      student_id: string,\n   *      lesson_mode: string,\n   *      lesson_location: string,\n   *      lesson_status: string,\n   *      credit: string,\n   *      session_time: string\n   *    }\n   *  }\n   */\n  toJSON(): {\n    student_name: string;\n    entry: string;\n    exit: string;\n    score: CMIScore;\n    student_id: string;\n    lesson_mode: string;\n    lesson_location: string;\n    lesson_status: string;\n    credit: string;\n    session_time: string;\n  } {\n    this.jsonString = true;\n    const result = {\n      student_id: this.student_id,\n      student_name: this.student_name,\n      lesson_location: this.lesson_location,\n      credit: this.credit,\n      lesson_status: this.lesson_status,\n      entry: this.entry,\n      lesson_mode: this.lesson_mode,\n      exit: this.exit,\n      session_time: this.session_time,\n      score: this.score,\n    };\n    this.jsonString = false;\n    return result;\n  }\n}\n","import { BaseCMI } from \"../common/base_cmi\";\nimport { CMIScore } from \"../common/score\";\nimport { CMIArray } from \"../common/array\";\nimport { Scorm12ValidationError } from \"../../exceptions/scorm12_exceptions\";\nimport { check12ValidFormat } from \"./validation\";\nimport {\n  scorm12_constants,\n  scorm12_errors,\n  scorm12_regex,\n} from \"../../constants\";\n\n/**\n * Class representing SCORM 1.2's `cmi.objectives` object\n *\n * Per SCORM 1.2 RTE Section 3.4.2.6:\n * - Array of objective records for tracking learning goals\n * - Each objective contains: id, score (raw, min, max), status\n * - Indices must be sequential starting at 0\n * - SCO can define multiple objectives to track sub-goals\n *\n * @extends CMIArray\n */\nexport class CMIObjectives extends CMIArray {\n  /**\n   * Constructor for `cmi.objectives`\n   */\n  constructor() {\n    super({\n      CMIElement: \"cmi.objectives\",\n      children: scorm12_constants.objectives_children,\n      errorCode: scorm12_errors.INVALID_SET_VALUE as number,\n      errorClass: Scorm12ValidationError,\n    });\n  }\n}\n\n/**\n * Class representing SCORM 1.2's cmi.objectives.n object\n *\n * Per SCORM 1.2 RTE Section 3.4.2.6:\n * - Individual objective record\n * - id: Unique identifier for the objective (CMIIdentifier)\n * - score: Learner's score for this objective (raw, min, max)\n * - status: Achievement status (passed, completed, failed, incomplete, browsed, not attempted)\n * - Used to track progress toward specific learning goals\n *\n * @extends BaseCMI\n */\nexport class CMIObjectivesObject extends BaseCMI {\n  /**\n   * Constructor for cmi.objectives.n\n   */\n  constructor() {\n    super(\"cmi.objectives.n\");\n    this.score = new CMIScore({\n      CMIElement: \"cmi.objectives.n.score\",\n      score_children: scorm12_constants.score_children,\n      score_range: scorm12_regex.score_range,\n      invalidErrorCode: scorm12_errors.INVALID_SET_VALUE as number,\n      invalidTypeCode: scorm12_errors.TYPE_MISMATCH as number,\n      invalidRangeCode: scorm12_errors.VALUE_OUT_OF_RANGE as number,\n      errorClass: Scorm12ValidationError,\n      // SCORM 1.2 score elements may be set blank (clears the value), per ADL 1.2 CTS.\n      allowEmptyString: true,\n    });\n  }\n\n  public readonly score: CMIScore;\n\n  private _id = \"\";\n  private _status = \"\";\n\n  /**\n   * Called when the API has been reset\n   */\n  reset(): void {\n    this._initialized = false;\n    this._id = \"\";\n    this._status = \"\";\n    this.score?.reset();\n  }\n\n  /**\n   * Getter for _id\n   * @spec RTE 3.4.2.6.1 - cmi.objectives.n.id\n   * @return {string}\n   */\n  get id(): string {\n    return this._id;\n  }\n\n  /**\n   * Setter for _id\n   * @spec RTE 3.4.2.6.1 - cmi.objectives.n.id\n   * @param {string} id\n   */\n  set id(id: string) {\n    if (check12ValidFormat(this._cmi_element + \".id\", id, scorm12_regex.CMIIdentifier)) {\n      this._id = id;\n    }\n  }\n\n  /**\n   * Getter for _status\n   * @spec RTE 3.4.2.6.3 - cmi.objectives.n.status\n   * @return {string}\n   */\n  get status(): string {\n    return this._status;\n  }\n\n  /**\n   * Setter for _status\n   * @spec RTE 3.4.2.6.3 - cmi.objectives.n.status\n   * @param {string} status\n   */\n  set status(status: string) {\n    if (check12ValidFormat(this._cmi_element + \".status\", status, scorm12_regex.CMIStatus2)) {\n      this._status = status;\n    }\n  }\n\n  /**\n   * toJSON for cmi.objectives.n\n   *\n   * The `jsonString` flag pattern used here serves a specific purpose:\n   * - Setting `jsonString = true` before accessing properties bypasses initialization checks\n   * - This allows JSON serialization to read write-only or uninitialized properties\n   * - Without this flag, accessing certain properties would throw SCORM validation errors\n   * - The flag is reset to `false` after serialization to restore normal validation behavior\n   * - This pattern is used throughout SCORM-Again for controlled property access during export\n   *\n   * @return {\n   *    {\n   *      id: string,\n   *      status: string,\n   *      score: CMIScore\n   *    }\n   *  }\n   */\n  toJSON(): {\n    id: string;\n    status: string;\n    score: CMIScore;\n  } {\n    this.jsonString = true;\n    const result = {\n      id: this.id,\n      status: this.status,\n      score: this.score,\n    };\n    this.jsonString = false;\n    return result;\n  }\n}\n","import { BaseCMI } from \"../common/base_cmi\";\nimport { Scorm12ValidationError } from \"../../exceptions/scorm12_exceptions\";\nimport { check12ValidFormat, check12ValidRange } from \"./validation\";\nimport {\n  scorm12_constants,\n  scorm12_errors,\n  scorm12_regex,\n  scorm2004_regex,\n} from \"../../constants\";\nimport { validationService } from \"../../services\";\nimport {\n  getDurationAsSeconds,\n  getSecondsAsHHMMSS,\n  getTimeAsSeconds,\n} from \"../../utilities\";\n\n/**\n * Parses time values in either SCORM 1.2 (HH:MM:SS) or ISO 8601 (PT...) format\n * and converts them to normalized SCORM 1.2 format.\n *\n * @param {string} value - The time value to parse\n * @param {string} fieldName - The CMI element name for error messages\n * @returns {string} Normalized time in HH:MM:SS format\n * @throws {Scorm12ValidationError} If value doesn't match either format\n */\nfunction parseTimeAllowed(value: string, fieldName: string): string {\n  // @spec RTE 3.4.2.2.3 - cmi.student_data.max_time_allowed\n  // Spec requires CMITimespan format (HH:MM:SS.cc), but some LMS implementations\n  // use ISO 8601 durations in manifests. We support both for interoperability.\n\n  // First try SCORM 1.2 HH:MM:SS(.cc) format\n  try {\n    check12ValidFormat(fieldName, value, scorm12_regex.CMITimespan, true);\n    const totalSeconds = getTimeAsSeconds(value, scorm12_regex.CMITimespan);\n    return getSecondsAsHHMMSS(totalSeconds);\n  } catch (e) {\n    // fall through and attempt other encodings\n  }\n\n  // Next try ISO 8601 durations (common in legacy manifests)\n  try {\n    check12ValidFormat(fieldName, value, scorm2004_regex.CMITimespan, true);\n    const totalSeconds = getDurationAsSeconds(value, scorm2004_regex.CMITimespan);\n    return getSecondsAsHHMMSS(totalSeconds);\n  } catch (e) {\n    // fall through to error\n  }\n\n  throw new Scorm12ValidationError(fieldName, scorm12_errors.TYPE_MISMATCH as number);\n}\n\n/**\n * Class representing the SCORM 1.2 cmi.student_data object\n * @extends BaseCMI\n */\nexport class CMIStudentData extends BaseCMI {\n  private readonly __children;\n  private _mastery_score = \"\";\n  private _max_time_allowed = \"\";\n  private _time_limit_action = \"\";\n\n  /**\n   * Constructor for cmi.student_data\n   * @param {string} student_data_children\n   */\n  constructor(student_data_children?: string) {\n    super(\"cmi.student_data\");\n    this.__children = student_data_children\n      ? student_data_children\n      : scorm12_constants.student_data_children;\n  }\n\n  /**\n   * Called when the API has been reset\n   */\n  reset(): void {\n    this._initialized = false;\n  }\n\n  /**\n   * Getter for __children\n   * @return {string}\n   * @private\n   */\n  get _children(): string {\n    return this.__children;\n  }\n\n  /**\n   * Setter for __children. Just throws an error.\n   * @param {string} _children\n   * @private\n   */\n  set _children(_children: string) {\n    throw new Scorm12ValidationError(\n      this._cmi_element + \"._children\",\n      scorm12_errors.INVALID_SET_VALUE as number,\n    );\n  }\n\n  /**\n   * Getter for _mastery_score\n   * @return {string}\n   */\n  get mastery_score(): string {\n    return this._mastery_score;\n  }\n\n  /**\n   * Setter for _mastery_score. Can only be called before initialization.\n   * @param {string} mastery_score\n   */\n  set mastery_score(mastery_score: string) {\n    validationService.validateReadOnly(this._cmi_element + \".mastery_score\", this.initialized);\n    if (mastery_score === undefined || mastery_score === null) {\n      return;\n    }\n\n    let normalizedMasteryScore = mastery_score;\n    if (typeof normalizedMasteryScore !== \"string\") {\n      normalizedMasteryScore = String(normalizedMasteryScore);\n    }\n\n    if (normalizedMasteryScore === \"\") {\n      this._mastery_score = mastery_score;\n      return;\n    }\n\n    if (\n      check12ValidFormat(\n        this._cmi_element + \".mastery_score\",\n        normalizedMasteryScore,\n        scorm12_regex.CMIDecimal,\n      ) &&\n      check12ValidRange(\n        this._cmi_element + \".mastery_score\",\n        normalizedMasteryScore,\n        scorm12_regex.score_range,\n      )\n    ) {\n      this._mastery_score = normalizedMasteryScore;\n    }\n  }\n\n  /**\n   * Getter for _max_time_allowed\n   * @return {string}\n   */\n  get max_time_allowed(): string {\n    return this._max_time_allowed;\n  }\n\n  /**\n   * Setter for _max_time_allowed. Can only be called before initialization.\n   * @param {string} max_time_allowed\n   */\n  set max_time_allowed(max_time_allowed: string) {\n    validationService.validateReadOnly(this._cmi_element + \".max_time_allowed\", this.initialized);\n    if (max_time_allowed === undefined || max_time_allowed === null) {\n      return;\n    }\n\n    const normalizedValue =\n      typeof max_time_allowed === \"string\" ? max_time_allowed : String(max_time_allowed);\n\n    if (normalizedValue === \"\") {\n      this._max_time_allowed = \"\";\n      return;\n    }\n\n    this._max_time_allowed = parseTimeAllowed(\n      normalizedValue,\n      this._cmi_element + \".max_time_allowed\",\n    );\n  }\n\n  /**\n   * Getter for _time_limit_action\n   * @return {string}\n   */\n  get time_limit_action(): string {\n    return this._time_limit_action;\n  }\n\n  /**\n   * Setter for _time_limit_action. Can only be called before initialization.\n   * @param {string} time_limit_action\n   */\n  set time_limit_action(time_limit_action: string) {\n    validationService.validateReadOnly(this._cmi_element + \".time_limit_action\", this.initialized);\n    if (time_limit_action === undefined || time_limit_action === null) {\n      return;\n    }\n\n    const normalizedValue =\n      typeof time_limit_action === \"string\" ? time_limit_action : String(time_limit_action);\n\n    if (\n      check12ValidFormat(\n        this._cmi_element + \".time_limit_action\",\n        normalizedValue,\n        scorm12_regex.CMITimeLimitAction,\n        true,\n      )\n    ) {\n      this._time_limit_action = normalizedValue;\n    }\n  }\n\n  /**\n   * toJSON for cmi.student_data\n   *\n   * @return {\n   *    {\n   *      max_time_allowed: string,\n   *      time_limit_action: string,\n   *      mastery_score: string\n   *    }\n   *  }\n   */\n  toJSON(): {\n    mastery_score: string;\n    max_time_allowed: string;\n    time_limit_action: string;\n  } {\n    this.jsonString = true;\n    const result = {\n      mastery_score: this.mastery_score,\n      max_time_allowed: this.max_time_allowed,\n      time_limit_action: this.time_limit_action,\n    };\n    this.jsonString = false;\n    return result;\n  }\n}\n","import { BaseCMI } from \"../common/base_cmi\";\nimport { Scorm12ValidationError } from \"../../exceptions/scorm12_exceptions\";\nimport { scorm12_constants, scorm12_errors } from \"../../constants\";\nimport { validationService } from \"../../services\";\n\n/**\n * Class representing the SCORM 1.2 cmi.student_preference object\n * @extends BaseCMI\n */\nexport class CMIStudentPreference extends BaseCMI {\n  private readonly __children;\n\n  /**\n   * Constructor for cmi.student_preference\n   * @param {string} student_preference_children\n   */\n  constructor(student_preference_children?: string) {\n    super(\"cmi.student_preference\");\n    this.__children = student_preference_children\n      ? student_preference_children\n      : scorm12_constants.student_preference_children;\n  }\n\n  private _audio = \"\";\n  private _language = \"\";\n  private _speed = \"\";\n  private _text = \"\";\n\n  /**\n   * Called when the API has been reset\n   */\n  reset(): void {\n    this._initialized = false;\n  }\n\n  /**\n   * Getter for __children\n   * @return {string}\n   * @private\n   */\n  get _children(): string {\n    return this.__children;\n  }\n\n  /**\n   * Setter for __children. Just throws an error.\n   * @param {string} _children\n   * @private\n   */\n  set _children(_children: string) {\n    throw new Scorm12ValidationError(\n      this._cmi_element + \"._children\",\n      scorm12_errors.INVALID_SET_VALUE as number,\n    );\n  }\n\n  /**\n   * Getter for _audio\n   * @spec RTE 3.4.2.3.1 - cmi.student_preference.audio\n   * @return {string}\n   */\n  get audio(): string {\n    return this._audio;\n  }\n\n  /**\n   * Setter for _audio\n   * @spec RTE 3.4.2.3.1 - cmi.student_preference.audio\n   * @param {string} audio\n   */\n  set audio(audio: string) {\n    if (validationService.validateScorm12Audio(this._cmi_element + \".audio\", audio)) {\n      this._audio = audio;\n    }\n  }\n\n  /**\n   * Getter for _language\n   * @spec RTE 3.4.2.3.2 - cmi.student_preference.language\n   * @return {string}\n   */\n  get language(): string {\n    return this._language;\n  }\n\n  /**\n   * Setter for _language\n   * @spec RTE 3.4.2.3.2 - cmi.student_preference.language\n   * @param {string} language\n   */\n  set language(language: string) {\n    if (validationService.validateScorm12Language(this._cmi_element + \".language\", language)) {\n      this._language = language;\n    }\n  }\n\n  /**\n   * Getter for _speed\n   * @spec RTE 3.4.2.3.3 - cmi.student_preference.speed\n   * @return {string}\n   */\n  get speed(): string {\n    return this._speed;\n  }\n\n  /**\n   * Setter for _speed\n   * @spec RTE 3.4.2.3.3 - cmi.student_preference.speed\n   * @param {string} speed\n   */\n  set speed(speed: string) {\n    if (validationService.validateScorm12Speed(this._cmi_element + \".speed\", speed)) {\n      this._speed = speed;\n    }\n  }\n\n  /**\n   * Getter for _text\n   * @spec RTE 3.4.2.3.4 - cmi.student_preference.text\n   * @return {string}\n   */\n  get text(): string {\n    return this._text;\n  }\n\n  /**\n   * Setter for _text\n   * @spec RTE 3.4.2.3.4 - cmi.student_preference.text\n   * @param {string} text\n   */\n  set text(text: string) {\n    if (validationService.validateScorm12Text(this._cmi_element + \".text\", text)) {\n      this._text = text;\n    }\n  }\n\n  /**\n   * toJSON for cmi.student_preference\n   *\n   * @return {\n   *    {\n   *      audio: string,\n   *      language: string,\n   *      speed: string,\n   *      text: string\n   *    }\n   *  }\n   */\n  toJSON(): {\n    audio: string;\n    language: string;\n    speed: string;\n    text: string;\n  } {\n    this.jsonString = true;\n    const result = {\n      audio: this.audio,\n      language: this.language,\n      speed: this.speed,\n      text: this.text,\n    };\n    this.jsonString = false;\n    return result;\n  }\n}\n","import { CMIArray } from \"../common/array\";\nimport { BaseCMI } from \"../common/base_cmi\";\nimport { Scorm12ValidationError } from \"../../exceptions/scorm12_exceptions\";\nimport { check12ValidFormat } from \"./validation\";\nimport { scorm12_constants, scorm12_errors, scorm12_regex } from \"../../constants\";\nimport { getSecondsAsHHMMSS, getTimeAsSeconds } from \"../../utilities\";\n\n/**\n * Class representing the SCORM 1.2 `cmi.interactions`\n *\n * Per SCORM 1.2 RTE Section 3.4.2.7:\n * - Array of interaction records tracking learner responses to questions\n * - Each interaction: id, time, type, weighting, student_response, result, latency\n * - Supports objectives and correct_responses sub-arrays\n * - All interaction data is write-only (except during JSON export)\n *\n * @extends CMIArray\n */\nexport class CMIInteractions extends CMIArray {\n  /**\n   * Constructor for `cmi.interactions`\n   */\n  constructor() {\n    super({\n      CMIElement: \"cmi.interactions\",\n      children: scorm12_constants.interactions_children,\n      errorCode: scorm12_errors.INVALID_SET_VALUE as number,\n      errorClass: Scorm12ValidationError,\n    });\n  }\n}\n\n/**\n * Class representing SCORM 1.2's cmi.interactions.n object\n *\n * Per SCORM 1.2 RTE Section 3.4.2.7:\n * - Individual interaction record\n * - id: Unique identifier for the interaction (CMIIdentifier)\n * - type: Interaction type (true-false, choice, fill-in, matching, performance, sequencing, likert, numeric)\n * - weighting: Weight assigned to the interaction (CMIDecimal)\n * - student_response: Learner's response (format depends on type)\n * - result: Outcome (correct, wrong, unanticipated, neutral, or numeric score)\n * - latency: Time from presentation to response (CMITimespan)\n *\n * @extends BaseCMI\n */\nexport class CMIInteractionsObject extends BaseCMI {\n  /**\n   * Constructor for cmi.interactions.n object\n   */\n  constructor() {\n    super(\"cmi.interactions.n\");\n    this.objectives = new CMIArray({\n      CMIElement: \"cmi.interactions.n.objectives\",\n      errorCode: scorm12_errors.INVALID_SET_VALUE as number,\n      errorClass: Scorm12ValidationError,\n      children: scorm12_constants.objectives_children,\n    });\n    this.correct_responses = new CMIArray({\n      CMIElement: \"cmi.interactions.correct_responses\",\n      errorCode: scorm12_errors.INVALID_SET_VALUE as number,\n      errorClass: Scorm12ValidationError,\n      children: scorm12_constants.correct_responses_children,\n    });\n  }\n\n  public readonly objectives: CMIArray;\n  public readonly correct_responses: CMIArray;\n\n  /**\n   * Called when the API has been initialized after the CMI has been created\n   */\n  override initialize() {\n    super.initialize();\n    this.objectives?.initialize();\n    this.correct_responses?.initialize();\n  }\n\n  private _id = \"\";\n  private _time = \"\";\n  private _type = \"\";\n  private _weighting = \"\";\n  private _student_response = \"\";\n  private _result = \"\";\n  private _latency = \"\";\n\n  /**\n   * Called when the API has been reset\n   */\n  override reset(): void {\n    this._initialized = false;\n\n    this._id = \"\";\n    this._time = \"\";\n    this._type = \"\";\n    this._weighting = \"\";\n    this._student_response = \"\";\n    this._result = \"\";\n    this._latency = \"\";\n\n    this.objectives?.reset();\n    this.correct_responses?.reset();\n  }\n\n  /**\n   * Getter for _id. Should only be called during JSON export.\n   * @return {string}\n   */\n  get id(): string {\n    if (!this.jsonString) {\n      throw new Scorm12ValidationError(\n        this._cmi_element + \".id\",\n        scorm12_errors.WRITE_ONLY_ELEMENT as number,\n      );\n    }\n    return this._id;\n  }\n\n  /**\n   * Setter for _id\n   * @param {string} id\n   */\n  set id(id: string) {\n    if (check12ValidFormat(this._cmi_element + \".id\", id, scorm12_regex.CMIIdentifier)) {\n      this._id = id;\n    }\n  }\n\n  /**\n   * Getter for _time. Should only be called during JSON export.\n   * @return {string}\n   */\n  get time(): string {\n    if (!this.jsonString) {\n      throw new Scorm12ValidationError(\n        this._cmi_element + \".time\",\n        scorm12_errors.WRITE_ONLY_ELEMENT as number,\n      );\n    }\n    return this._time;\n  }\n\n  /**\n   * Setter for _time\n   * @param {string} time\n   */\n  set time(time: string) {\n    if (check12ValidFormat(this._cmi_element + \".time\", time, scorm12_regex.CMITime)) {\n      this._time = time;\n    }\n  }\n\n  /**\n   * Getter for _type. Should only be called during JSON export.\n   * @return {string}\n   */\n  get type(): string {\n    if (!this.jsonString) {\n      throw new Scorm12ValidationError(\n        this._cmi_element + \".type\",\n        scorm12_errors.WRITE_ONLY_ELEMENT as number,\n      );\n    }\n    return this._type;\n  }\n\n  /**\n   * Setter for _type\n   * @param {string} type\n   */\n  set type(type: string) {\n    if (check12ValidFormat(this._cmi_element + \".type\", type, scorm12_regex.CMIType)) {\n      this._type = type;\n    }\n  }\n\n  /**\n   * Getter for _weighting. Should only be called during JSON export.\n   * @return {string}\n   */\n  get weighting(): string {\n    if (!this.jsonString) {\n      throw new Scorm12ValidationError(\n        this._cmi_element + \".weighting\",\n        scorm12_errors.WRITE_ONLY_ELEMENT as number,\n      );\n    }\n    return this._weighting;\n  }\n\n  /**\n   * Setter for _weighting\n   * @param {string} weighting\n   */\n  set weighting(weighting: string) {\n    if (\n      check12ValidFormat(\n        this._cmi_element + \".weighting\",\n        weighting,\n        scorm12_regex.CMIDecimal,\n        true,\n      )\n    ) {\n      this._weighting = weighting;\n    }\n  }\n\n  /**\n   * Getter for _student_response. Should only be called during JSON export.\n   * @return {string}\n   */\n  get student_response(): string {\n    if (!this.jsonString) {\n      throw new Scorm12ValidationError(\n        this._cmi_element + \".student_response\",\n        scorm12_errors.WRITE_ONLY_ELEMENT as number,\n      );\n    }\n    return this._student_response;\n  }\n\n  /**\n   * Setter for _student_response\n   * @param {string} student_response\n   */\n  set student_response(student_response: string) {\n    if (\n      check12ValidFormat(\n        this._cmi_element + \".student_response\",\n        student_response,\n        scorm12_regex.CMIFeedback,\n        true,\n      )\n    ) {\n      this._student_response = student_response;\n    }\n  }\n\n  /**\n   * Getter for _result. Should only be called during JSON export.\n   * @return {string}\n   */\n  get result(): string {\n    if (!this.jsonString) {\n      throw new Scorm12ValidationError(\n        this._cmi_element + \".result\",\n        scorm12_errors.WRITE_ONLY_ELEMENT as number,\n      );\n    }\n    return this._result;\n  }\n\n  /**\n   * Setter for _result\n   * @spec RTE 3.4.2.7.6 - cmi.interactions.n.result\n   * Per SCORM 1.2 spec, valid values are \"correct\", \"wrong\", \"unanticipated\", \"neutral\", or a numeric score.\n   * The spec requires \"wrong\" not \"incorrect\" for failed interactions.\n   * @param {string} result\n   */\n  set result(result: string) {\n    // SCORM 1.2 clarification: Normalize 'incorrect' to 'wrong'\n    // The SCORM 1.2 specification (RTE 3.4.2.7.6) defines \"wrong\" as the valid result value\n    // for incorrect responses, not \"incorrect\". Some content may use \"incorrect\" due to\n    // confusion with SCORM 2004 or common language, so we normalize it here for compatibility.\n    let normalizedResult = result;\n    if (result === \"incorrect\") {\n      normalizedResult = \"wrong\";\n      console.warn(\n        \"SCORM 1.2: Received non-standard value 'incorrect' for cmi.interactions.n.result; normalizing to 'wrong'.\",\n      );\n    }\n\n    if (\n      check12ValidFormat(\n        this._cmi_element + \".result\",\n        normalizedResult,\n        scorm12_regex.CMIResult,\n        // ADL's 1.2 CTS checks the numeric form with checkDecimal, which accepts blank\n        true,\n      )\n    ) {\n      this._result = normalizedResult;\n    }\n  }\n\n  /**\n   * Getter for _latency. Should only be called during JSON export.\n   * @return {string}\n   */\n  get latency(): string {\n    if (!this.jsonString) {\n      throw new Scorm12ValidationError(\n        this._cmi_element + \".latency\",\n        scorm12_errors.WRITE_ONLY_ELEMENT as number,\n      );\n    }\n    return this._latency;\n  }\n\n  /**\n   * Setter for _latency\n   * @param {string} latency\n   */\n  set latency(latency: string) {\n    if (check12ValidFormat(this._cmi_element + \".latency\", latency, scorm12_regex.CMITimespan)) {\n      const totalSeconds = getTimeAsSeconds(latency, scorm12_regex.CMITimespan);\n      this._latency = getSecondsAsHHMMSS(totalSeconds);\n    }\n  }\n\n  /**\n   * toJSON for cmi.interactions.n\n   *\n   * @return {\n   *    {\n   *      id: string,\n   *      time: string,\n   *      type: string,\n   *      weighting: string,\n   *      student_response: string,\n   *      result: string,\n   *      latency: string,\n   *      objectives: CMIArray,\n   *      correct_responses: CMIArray\n   *    }\n   *  }\n   */\n  toJSON(): {\n    id: string;\n    time: string;\n    type: string;\n    weighting: string;\n    student_response: string;\n    result: string;\n    latency: string;\n    objectives: CMIArray;\n    correct_responses: CMIArray;\n  } {\n    this.jsonString = true;\n    const result = {\n      id: this.id,\n      time: this.time,\n      type: this.type,\n      weighting: this.weighting,\n      student_response: this.student_response,\n      result: this.result,\n      latency: this.latency,\n      objectives: this.objectives,\n      correct_responses: this.correct_responses,\n    };\n    this.jsonString = false;\n    return result;\n  }\n}\n\n/**\n * Class representing SCORM 1.2's cmi.interactions.n.objectives.n object\n *\n * Per SCORM 1.2 RTE Section 3.4.2.7.3:\n * - Associates an interaction with one or more objectives\n * - id: Identifier matching an objective in cmi.objectives\n * - Write-only data element\n *\n * @extends BaseCMI\n */\nexport class CMIInteractionsObjectivesObject extends BaseCMI {\n  /**\n   * Constructor for cmi.interactions.n.objectives.n\n   */\n  constructor() {\n    super(\"cmi.interactions.n.objectives.n\");\n  }\n\n  private _id = \"\";\n\n  /**\n   * Called when the API has been reset\n   */\n  reset(): void {\n    this._initialized = false;\n    this._id = \"\";\n  }\n\n  /**\n   * Getter for _id. Should only be called during JSON export.\n   * @return {string}\n   */\n  get id(): string {\n    if (!this.jsonString) {\n      throw new Scorm12ValidationError(\n        this._cmi_element + \".id\",\n        scorm12_errors.WRITE_ONLY_ELEMENT as number,\n      );\n    }\n    return this._id;\n  }\n\n  /**\n   * Setter for _id\n   * @param {string} id\n   */\n  set id(id: string) {\n    if (check12ValidFormat(this._cmi_element + \".id\", id, scorm12_regex.CMIIdentifier)) {\n      this._id = id;\n    }\n  }\n\n  /**\n   * toJSON for cmi.interactions.n.objectives.n\n   * @return {\n   *    {\n   *      id: string\n   *    }\n   *  }\n   */\n  toJSON(): {\n    id: string;\n  } {\n    this.jsonString = true;\n    const result = {\n      id: this.id,\n    };\n    this.jsonString = false;\n    return result;\n  }\n}\n\n/**\n * Class representing SCORM 1.2's cmi.interactions.correct_responses.n object\n *\n * Per SCORM 1.2 RTE Section 3.4.2.7.4:\n * - Defines correct response patterns for an interaction\n * - pattern: Expected correct response (format depends on interaction type)\n * - Multiple patterns allowed for interactions with multiple correct answers\n * - Write-only data element\n *\n * @extends BaseCMI\n */\nexport class CMIInteractionsCorrectResponsesObject extends BaseCMI {\n  /**\n   * Constructor for cmi.interactions.correct_responses.n\n   */\n  constructor() {\n    super(\"cmi.interactions.correct_responses.n\");\n  }\n\n  private _pattern = \"\";\n\n  /**\n   * Called when the API has been reset\n   */\n  reset(): void {\n    this._initialized = false;\n    this._pattern = \"\";\n  }\n\n  /**\n   * Getter for _pattern\n   * @return {string}\n   */\n  get pattern(): string {\n    if (!this.jsonString) {\n      throw new Scorm12ValidationError(\n        this._cmi_element + \".pattern\",\n        scorm12_errors.WRITE_ONLY_ELEMENT as number,\n      );\n    }\n    return this._pattern;\n  }\n\n  /**\n   * Setter for _pattern\n   * @param {string} pattern\n   */\n  set pattern(pattern: string) {\n    if (\n      check12ValidFormat(this._cmi_element + \".pattern\", pattern, scorm12_regex.CMIFeedback, true)\n    ) {\n      this._pattern = pattern;\n    }\n  }\n\n  /**\n   * toJSON for cmi.interactions.correct_responses.n\n   * @return {\n   *    {\n   *      pattern: string\n   *    }\n   *  }\n   */\n  toJSON(): {\n    pattern: string;\n  } {\n    this.jsonString = true;\n    const result = {\n      pattern: this._pattern,\n    };\n    this.jsonString = false;\n    return result;\n  }\n}\n","import { BaseRootCMI } from \"../common/base_cmi\";\nimport { Scorm12ValidationError } from \"../../exceptions/scorm12_exceptions\";\nimport { check12ValidFormat } from \"./validation\";\nimport { CMICore } from \"./core\";\nimport { CMIObjectives } from \"./objectives\";\nimport { CMIStudentData } from \"./student_data\";\nimport { CMIStudentPreference } from \"./student_preference\";\nimport { CMIInteractions } from \"./interactions\";\nimport {\n  scorm12_constants,\n  scorm12_errors,\n  scorm12_regex,\n} from \"../../constants\";\n\n/**\n * Class representing the cmi object for SCORM 1.2\n *\n * Per SCORM 1.2 RTE Section 3.4:\n * - Core data model for tracking learner progress\n * - Contains core (session data), objectives, student_data, student_preference, interactions\n * - All elements accessible via GetValue/SetValue API\n * - Data persistence managed by LMS between sessions\n *\n * @extends BaseRootCMI\n */\nexport class CMI extends BaseRootCMI {\n  private readonly __children: string = \"\";\n  private __version: string = \"3.4\";\n  private _launch_data: string = \"\";\n  private _comments: string = \"\";\n  private _comments_from_lms: string = \"\";\n\n  /**\n   * Constructor for the SCORM 1.2 cmi object\n   * @param {string} cmi_children\n   * @param {(CMIStudentData)} student_data\n   * @param {boolean} initialized\n   */\n  constructor(cmi_children?: string, student_data?: CMIStudentData, initialized?: boolean) {\n    super(\"cmi\");\n    if (initialized) this.initialize();\n    this.__children = cmi_children ? cmi_children : scorm12_constants.cmi_children;\n    this.core = new CMICore();\n    this.objectives = new CMIObjectives();\n    this.student_data = student_data ? student_data : new CMIStudentData();\n    this.student_preference = new CMIStudentPreference();\n    this.interactions = new CMIInteractions();\n  }\n\n  public core: CMICore;\n  public objectives: CMIObjectives;\n  public student_data: CMIStudentData;\n  public student_preference: CMIStudentPreference;\n  public interactions: CMIInteractions;\n\n  /**\n   * Called when the API has been reset\n   *\n   * CMI-03: Uses consistent ?.reset() pattern for all child objects.\n   * Objectives and interactions use reset(true) to clear arrays completely.\n   */\n  reset(): void {\n    this._initialized = false;\n    this._start_time = undefined;\n\n    this._launch_data = \"\";\n    this._comments = \"\";\n    this.core?.reset();\n    this.objectives?.reset(true);\n    this.interactions?.reset(true);\n    this.student_data?.reset();\n    this.student_preference?.reset();\n  }\n\n  /**\n   * Called when the API has been initialized after the CMI has been created\n   */\n  override initialize() {\n    super.initialize();\n    this.core?.initialize();\n    this.objectives?.initialize();\n    this.student_data?.initialize();\n    this.student_preference?.initialize();\n    this.interactions?.initialize();\n  }\n\n  /**\n   * toJSON for cmi\n   *\n   * @return {\n   *    {\n   *      suspend_data: string,\n   *      launch_data: string,\n   *      comments: string,\n   *      comments_from_lms: string,\n   *      core: CMICore,\n   *      objectives: CMIObjectives,\n   *      student_data: CMIStudentData,\n   *      student_preference: CMIStudentPreference,\n   *      interactions: CMIInteractions\n   *    }\n   *  }\n   */\n  toJSON(): {\n    suspend_data: string;\n    launch_data: string;\n    comments: string;\n    comments_from_lms: string;\n    core: CMICore;\n    objectives: CMIObjectives;\n    student_data: CMIStudentData;\n    student_preference: CMIStudentPreference;\n    interactions: CMIInteractions;\n  } {\n    this.jsonString = true;\n    const result = {\n      suspend_data: this.suspend_data,\n      launch_data: this.launch_data,\n      comments: this.comments,\n      comments_from_lms: this.comments_from_lms,\n      core: this.core,\n      objectives: this.objectives,\n      student_data: this.student_data,\n      student_preference: this.student_preference,\n      interactions: this.interactions\n    };\n    this.jsonString = false;\n    return result;\n  }\n\n  /**\n   * Getter for __version\n   * @return {string}\n   */\n  get _version(): string {\n    return this.__version;\n  }\n\n  /**\n   * Setter for __version. Just throws an error.\n   * @param {string} _version\n   */\n  set _version(_version: string) {\n    throw new Scorm12ValidationError(\n      this._cmi_element + \"._version\",\n      scorm12_errors.INVALID_SET_VALUE as number\n    );\n  }\n\n  /**\n   * Getter for __children\n   * @return {string}\n   */\n  get _children(): string {\n    return this.__children;\n  }\n\n  /**\n   * Setter for __version. Just throws an error.\n   * @param {string} _children\n   */\n  set _children(_children: string) {\n    throw new Scorm12ValidationError(\n      this._cmi_element + \"._children\",\n      scorm12_errors.INVALID_SET_VALUE as number\n    );\n  }\n\n  /**\n   * Getter for _suspend_data\n   * @return {string}\n   */\n  get suspend_data(): string {\n    return this.core?.suspend_data;\n  }\n\n  /**\n   * Setter for _suspend_data\n   * @param {string} suspend_data\n   */\n  set suspend_data(suspend_data: string) {\n    if (this.core) {\n      this.core.suspend_data = suspend_data;\n    }\n  }\n\n  /**\n   * Getter for _launch_data\n   * @return {string}\n   */\n  get launch_data(): string {\n    return this._launch_data;\n  }\n\n  /**\n   * Setter for _launch_data. Can only be called before initialization.\n   *\n   * SPEC COMPLIANCE NOTE:\n   * The SCORM 1.2 specification defines launch_data as CMIString4096 (max 4096 chars).\n   * This implementation intentionally omits length validation because:\n   *\n   * 1. launch_data is LMS-provided data, not SCO-provided - the LMS is responsible\n   *    for ensuring valid data is provided to content\n   * 2. This setter is only callable before API initialization (read-only to SCO)\n   * 3. Real-world LMS systems may provide launch_data exceeding 4096 chars\n   * 4. Rejecting oversized LMS data would break content with no recovery path\n   *\n   * Unlike cmi.suspend_data and cmi.comments (which SCOs write), launch_data\n   * comes from the LMS manifest/configuration, so strict validation here would\n   * penalize content for LMS decisions outside SCO control.\n   *\n   * @param {string} launch_data\n   */\n  set launch_data(launch_data: string) {\n    if (this.initialized) {\n      throw new Scorm12ValidationError(\n        this._cmi_element + \".launch_data\",\n        scorm12_errors.READ_ONLY_ELEMENT as number\n      );\n    } else {\n      this._launch_data = launch_data;\n    }\n  }\n\n  /**\n   * Getter for _comments\n   * @return {string}\n   */\n  get comments(): string {\n    return this._comments;\n  }\n\n  /**\n   * Setter for _comments\n   * @param {string} comments\n   */\n  set comments(comments: string) {\n    if (\n      check12ValidFormat(\n        this._cmi_element + \".comments\",\n        comments,\n        scorm12_regex.CMIString4096,\n        true\n      )\n    ) {\n      this._comments = comments;\n    }\n  }\n\n  /**\n   * Getter for _comments_from_lms\n   * @return {string}\n   */\n  get comments_from_lms(): string {\n    return this._comments_from_lms;\n  }\n\n  /**\n   * Setter for _comments_from_lms. Can only be called before  initialization.\n   * @param {string} comments_from_lms\n   */\n  set comments_from_lms(comments_from_lms: string) {\n    if (this.initialized) {\n      throw new Scorm12ValidationError(\n        this._cmi_element + \".comments_from_lms\",\n        scorm12_errors.READ_ONLY_ELEMENT as number\n      );\n    } else {\n      this._comments_from_lms = comments_from_lms;\n    }\n  }\n\n  /**\n   * Adds the current session time to the existing total time.\n   *\n   * @return {string}\n   */\n  getCurrentTotalTime(): string {\n    return this.core.getCurrentTotalTime(this.start_time);\n  }\n}\n","import { BaseCMI } from \"../common/base_cmi\";\nimport { check12ValidFormat } from \"./validation\";\nimport { scorm12_regex } from \"../../constants\";\n\n/**\n * Class for SCORM 1.2 Navigation object\n *\n * @spec NON-STANDARD EXTENSION - cmi.nav is not part of the official SCORM 1.2 specification.\n * This is a common extension supported by some LMS implementations to provide\n * navigation control. It is not guaranteed to work across all SCORM 1.2 platforms.\n */\nexport class NAV extends BaseCMI {\n  /**\n   * Constructor for NAV object\n   */\n  constructor() {\n    super(\"cmi.nav\");\n  }\n\n  /**\n   * Called when the API has been reset\n   *\n   * This method is invoked during the following session lifecycle events:\n   * - When the API is reset via LMSFinish() followed by a new LMSInitialize()\n   * - Between SCO transitions in multi-SCO courses (when one SCO ends and another begins)\n   * - When the LMS explicitly resets the API instance\n   * - During API cleanup and reinitialization cycles\n   *\n   * Resets all navigation state to prepare for a new session.\n   */\n  reset(): void {\n    this._event = \"\";\n    this._initialized = false;\n  }\n\n  private _event = \"\";\n\n  /**\n   * Getter for _event\n   * @return {string}\n   */\n  get event(): string {\n    return this._event;\n  }\n\n  /**\n   * Setter for _event\n   * @param {string} event\n   */\n  set event(event: string) {\n    if (\n      event === \"\" ||\n      check12ValidFormat(this._cmi_element + \".event\", event, scorm12_regex.NAVEvent)\n    ) {\n      this._event = event;\n    }\n  }\n\n  /**\n   * toJSON for nav object\n   * @return {\n   *    {\n   *      event: string\n   *    }\n   *  }\n   */\n  toJSON(): {\n    event: string;\n  } {\n    this.jsonString = true;\n    const result = {\n      event: this.event,\n    };\n    this.jsonString = false;\n    return result;\n  }\n}\n","import BaseAPI from \"./BaseAPI\";\nimport { flatten, getTimeAsSeconds, StringKeyMap, stringMatches } from \"./utilities\";\nimport { BaseCMI } from \"./cmi/common/base_cmi\";\nimport { CMI } from \"./cmi/scorm12/cmi\";\nimport { CMIObjectivesObject } from \"./cmi/scorm12/objectives\";\nimport {\n  CMIInteractionsCorrectResponsesObject,\n  CMIInteractionsObject,\n  CMIInteractionsObjectivesObject,\n} from \"./cmi/scorm12/interactions\";\nimport { NAV } from \"./cmi/scorm12/nav\";\nimport {\n  CompletionStatus,\n  global_constants,\n  scorm12_constants,\n  scorm12_errors,\n  scorm12_regex,\n  SuccessStatus,\n} from \"./constants\";\nimport {\n  CommitObject,\n  CommitTrigger,\n  ResetOptions,\n  ResultObject,\n  ScoreObject,\n  Settings,\n} from \"./types\";\nimport { IHttpService } from \"./interfaces\";\n\n/**\n * API class for SCORM 1.2\n */\nclass Scorm12API extends BaseAPI {\n  /**\n   * Static global storage for learner preferences\n   * When globalStudentPreferences is enabled, preferences persist across SCO instances\n   * @private\n   */\n  private static _globalLearnerPrefs: {\n    audio: string;\n    language: string;\n    speed: string;\n    text: string;\n  } | null = null;\n\n  /**\n   * Clear the global learner preferences storage\n   * @public\n   */\n  public static clearGlobalPreferences(): void {\n    Scorm12API._globalLearnerPrefs = null;\n  }\n\n  /**\n   * Constructor for SCORM 1.2 API\n   * @param {object} settings\n   * @param {IHttpService} httpService - Optional HTTP service instance\n   */\n  constructor(settings?: Settings, httpService?: IHttpService) {\n    const settingsCopy = settings ? { ...settings } : undefined;\n    if (settingsCopy) {\n      // Per SCORM 1.2 spec, LMS may override lesson_status based on mastery score\n      // Default to true for spec compliance; set to false for conservative behavior\n      if (settingsCopy.mastery_override === undefined) {\n        settingsCopy.mastery_override = true;\n      }\n    }\n\n    super(scorm12_errors, settingsCopy, httpService);\n\n    this.cmi = new CMI();\n    this.nav = new NAV();\n\n    // Initialize preferences from global storage if enabled\n    // Only set non-empty values to avoid validation errors\n    if (this.settings.globalStudentPreferences && Scorm12API._globalLearnerPrefs) {\n      if (Scorm12API._globalLearnerPrefs.audio !== \"\") {\n        this.cmi.student_preference.audio = Scorm12API._globalLearnerPrefs.audio;\n      }\n      if (Scorm12API._globalLearnerPrefs.language !== \"\") {\n        this.cmi.student_preference.language = Scorm12API._globalLearnerPrefs.language;\n      }\n      if (Scorm12API._globalLearnerPrefs.speed !== \"\") {\n        this.cmi.student_preference.speed = Scorm12API._globalLearnerPrefs.speed;\n      }\n      if (Scorm12API._globalLearnerPrefs.text !== \"\") {\n        this.cmi.student_preference.text = Scorm12API._globalLearnerPrefs.text;\n      }\n    }\n\n    // Rename functions to match 1.2 Spec and expose to modules\n    this.LMSInitialize = this.lmsInitialize;\n    this.LMSFinish = this.lmsFinish;\n    this.LMSGetValue = this.lmsGetValue;\n    this.LMSSetValue = this.lmsSetValue;\n    this.LMSCommit = this.lmsCommit;\n    this.LMSGetLastError = this.lmsGetLastError;\n    this.LMSGetErrorString = this.lmsGetErrorString;\n    this.LMSGetDiagnostic = this.lmsGetDiagnostic;\n  }\n\n  public statusSetByModule = false;\n\n  cmi: CMI;\n  nav: NAV;\n\n  LMSInitialize: (parameter?: string) => string;\n  LMSFinish: (parameter?: string) => string;\n  LMSGetValue: (CMIElement: string) => string;\n  LMSSetValue: (CMIElement: string, value: any) => string;\n  LMSCommit: (parameter?: string) => string;\n  LMSGetLastError: () => string;\n  LMSGetErrorString: (CMIErrorCode: string) => string;\n  LMSGetDiagnostic: (CMIErrorCode: string) => string;\n\n  /**\n   * Called when the API needs to be reset\n   * @param {Settings} settings - Optional new settings to merge with existing settings\n   * @param {ResetOptions} options - Behavior for this reset only\n   */\n  reset(settings?: Settings, options?: ResetOptions) {\n    this.commonReset(settings, options);\n\n    this.cmi?.reset();\n    if (options?.resetTotalTime === true) {\n      this.cmi.core.total_time = \"00:00:00\";\n    }\n    this.nav?.reset();\n    this.statusSetByModule = false;\n  }\n\n  /**\n   * LMSInitialize - Begins a communication session with the LMS\n   *\n   * Per SCORM 1.2 RTE Section 3.4.3.1:\n   * - Parameter must be empty string (\"\")\n   * - Returns \"true\" on success, \"false\" on failure\n   * - Sets error 101 if already initialized\n   * - Sets error 101 if already terminated\n   * - Initializes cmi.core.lesson_status to \"not attempted\" if not already set\n   *\n   * @param {string} parameter - Must be an empty string per SCORM 1.2 specification\n   * @return {string} \"true\" or \"false\"\n   */\n  lmsInitialize(parameter: string = \"\"): string {\n    // SCORM 1.2 RTE 3.4.3.1: Parameter must be an empty string\n    if (parameter !== \"\") {\n      this.throwSCORMError(\"api\", this._error_codes.ARGUMENT_ERROR);\n      return global_constants.SCORM_FALSE;\n    }\n\n    this.restoreOfflineData();\n    this.cmi.initialize();\n    if (this.cmi.core.lesson_status) {\n      this.statusSetByModule = true;\n    } else {\n      this.cmi.core.lesson_status = \"not attempted\";\n    }\n    return this.initialize(\n      \"LMSInitialize\",\n      \"LMS was already initialized!\",\n      \"LMS is already finished!\",\n    );\n  }\n\n  /**\n   * LMSFinish - Ends the communication session and persists data\n   *\n   * Per SCORM 1.2 RTE Section 3.4.3.2:\n   * - Parameter must be empty string (\"\")\n   * - Returns \"true\" on success, \"false\" on failure\n   * - Commits all data to persistent storage\n   * - Sets error 301 if not initialized\n   * - Sets error 101 if already terminated\n   * - Processes navigation events (continue/previous) if nav.event is set\n   *\n   * @param {string} parameter - Must be an empty string per SCORM 1.2 specification\n   * @return {string} \"true\" or \"false\"\n   */\n  lmsFinish(parameter: string = \"\"): string {\n    // SCORM 1.2 RTE 3.4.3.2: Parameter must be an empty string\n    if (parameter !== \"\") {\n      this.throwSCORMError(\"api\", this._error_codes.ARGUMENT_ERROR);\n      return global_constants.SCORM_FALSE;\n    }\n\n    const result = this.terminate(\"LMSFinish\", true);\n\n    if (result === global_constants.SCORM_TRUE) {\n      if (this.nav.event !== \"\") {\n        if (this.nav.event === \"continue\") {\n          this.processListeners(\"SequenceNext\");\n        } else {\n          this.processListeners(\"SequencePrevious\");\n        }\n      } else if (this.settings.autoProgress) {\n        this.processListeners(\"SequenceNext\");\n      }\n    }\n\n    return result;\n  }\n\n  /**\n   * LMSGetValue - Retrieves a value from the CMI data model\n   *\n   * Per SCORM 1.2 RTE Section 3.4.3.3:\n   * - Returns the value of the specified CMI element\n   * - Returns empty string if element has no value\n   * - Sets error 101 if not initialized\n   * - Sets error 301 if element is not implemented (invalid element)\n   * - Sets error 201 if element is write-only\n   * - Sets error 202 if element is not initialized\n   *\n   * @param {string} CMIElement - The CMI element path (e.g., \"cmi.core.score.raw\")\n   * @return {string} The value of the element, or empty string\n   */\n  lmsGetValue(CMIElement: string): string {\n    return this.getValue(\"LMSGetValue\", false, CMIElement);\n  }\n\n  /**\n   * LMSSetValue - Sets a value in the CMI data model\n   *\n   * Per SCORM 1.2 RTE Section 3.4.3.4:\n   * - Sets the value of the specified CMI element\n   * - Returns \"true\" on success, \"false\" on failure\n   * - Sets error 101 if not initialized\n   * - Sets error 301 if element is not implemented (invalid element)\n   * - Sets error 351 if element exceeds maximum length\n   * - Sets error 201 if element is read-only\n   * - Sets error 405 if incorrect data type\n   * - Triggers autocommit if enabled\n   *\n   * @param {string} CMIElement - The CMI element path (e.g., \"cmi.core.lesson_status\")\n   * @param {any} value - The value to set\n   * @return {string} \"true\" or \"false\"\n   */\n  lmsSetValue(CMIElement: string, value: any): string {\n    if (CMIElement === \"cmi.core.lesson_status\") {\n      this.statusSetByModule = true;\n    }\n    return this.setValue(\"LMSSetValue\", \"LMSCommit\", false, CMIElement, value);\n  }\n\n  /**\n   * LMSCommit - Requests immediate persistence of data to the LMS\n   *\n   * Per SCORM 1.2 RTE Section 3.4.4.1:\n   * - Parameter must be empty string (\"\")\n   * - Requests persistence of all data set since last successful commit\n   * - Returns \"true\" on success, \"false\" on failure\n   * - Sets error 301 if not initialized\n   * - Sets error 391 if commit failed\n   * - Does not terminate the communication session\n   *\n   * @param {string} parameter - Must be an empty string per SCORM 1.2 specification\n   * @return {string} \"true\" or \"false\"\n   */\n  lmsCommit(parameter: string = \"\"): string {\n    // SCORM 1.2 RTE 3.4.4.1: Parameter must be an empty string\n    if (parameter !== \"\") {\n      this.throwSCORMError(\"api\", this._error_codes.ARGUMENT_ERROR);\n      return global_constants.SCORM_FALSE;\n    }\n\n    // Preserve the required false/301 state result even when commits are throttled.\n    if (this.isNotInitialized()) {\n      return this.commit(\"LMSCommit\", false);\n    }\n\n    if (this.settings.throttleCommits) {\n      this.scheduleCommit(500, \"LMSCommit\");\n      return global_constants.SCORM_TRUE;\n    } else {\n      return this.commit(\"LMSCommit\", false);\n    }\n  }\n\n  /**\n   * LMSGetLastError - Returns the error code from the last API call\n   *\n   * Per SCORM 1.2 RTE Section 3.4.4.2:\n   * - Returns the error code that resulted from the last API call\n   * - Returns \"0\" if no error occurred\n   * - Can be called at any time (even before LMSInitialize)\n   * - Does not change the current error state\n   * - Should be called after each API call to check for errors\n   *\n   * @return {string} Error code as a string (e.g., \"0\", \"101\", \"301\")\n   */\n  lmsGetLastError(): string {\n    return this.getLastError(\"LMSGetLastError\");\n  }\n\n  /**\n   * LMSGetErrorString - Returns a short description for an error code\n   *\n   * Per SCORM 1.2 RTE Section 3.4.4.3:\n   * - Returns a textual description for the specified error code\n   * - Returns empty string if error code is not recognized\n   * - Can be called at any time (even before LMSInitialize)\n   * - Does not change the current error state\n   * - Used to provide user-friendly error messages\n   *\n   * @param {string} CMIErrorCode - The error code to get the description for\n   * @return {string} Short error description\n   */\n  lmsGetErrorString(CMIErrorCode: string): string {\n    return this.getErrorString(\"LMSGetErrorString\", CMIErrorCode);\n  }\n\n  /**\n   * LMSGetDiagnostic - Returns detailed diagnostic information for an error\n   *\n   * Per SCORM 1.2 RTE Section 3.4.4.4:\n   * - Returns detailed diagnostic information for the specified error code\n   * - Implementation-specific; can include additional context or debugging info\n   * - Returns empty string if no diagnostic information is available\n   * - Can be called at any time (even before LMSInitialize)\n   * - Does not change the current error state\n   * - Used for debugging and troubleshooting\n   *\n   * @param {string} CMIErrorCode - The error code to get diagnostic information for\n   * @return {string} Detailed diagnostic information\n   */\n  lmsGetDiagnostic(CMIErrorCode: string): string {\n    return this.getDiagnostic(\"LMSGetDiagnostic\", CMIErrorCode);\n  }\n\n  /**\n   * Sets a value on the CMI Object\n   *\n   * @param {string} CMIElement\n   * @param {*} value\n   * @return {string}\n   */\n  override setCMIValue(CMIElement: string, value: any): string {\n    const result = this._commonSetCMIValue(\"LMSSetValue\", false, CMIElement, value);\n\n    // Update global learner preferences if enabled and the set succeeded\n    if (result === global_constants.SCORM_TRUE && this.settings.globalStudentPreferences) {\n      if (CMIElement === \"cmi.student_preference.audio\") {\n        this._updateGlobalPreference(\"audio\", value);\n      } else if (CMIElement === \"cmi.student_preference.language\") {\n        this._updateGlobalPreference(\"language\", value);\n      } else if (CMIElement === \"cmi.student_preference.speed\") {\n        this._updateGlobalPreference(\"speed\", value);\n      } else if (CMIElement === \"cmi.student_preference.text\") {\n        this._updateGlobalPreference(\"text\", value);\n      }\n    }\n\n    return result;\n  }\n\n  /**\n   * Updates a specific field in the global learner preferences storage\n   * @param {string} field - The preference field to update\n   * @param {string} value - The value to set\n   * @private\n   */\n  private _updateGlobalPreference(\n    field: \"audio\" | \"language\" | \"speed\" | \"text\",\n    value: string,\n  ): void {\n    if (!Scorm12API._globalLearnerPrefs) {\n      Scorm12API._globalLearnerPrefs = { audio: \"\", language: \"\", speed: \"\", text: \"\" };\n    }\n    Scorm12API._globalLearnerPrefs[field] = value;\n  }\n\n  /**\n   * Gets a value from the CMI Object\n   *\n   * @param {string} CMIElement\n   * @return {*}\n   */\n  override getCMIValue(CMIElement: string): any {\n    return this._commonGetCMIValue(\"getCMIValue\", false, CMIElement);\n  }\n\n  /**\n   * Gets or builds a new child element to add to the array.\n   *\n   * @param {string} CMIElement\n   * @param {*} _value\n   * @param {boolean} foundFirstIndex\n   * @return {BaseCMI|null}\n   */\n  getChildElement(CMIElement: string, _value: any, foundFirstIndex: boolean): BaseCMI | null {\n    if (stringMatches(CMIElement, \"cmi\\\\.objectives\\\\.\\\\d+\")) {\n      return new CMIObjectivesObject();\n    } else if (\n      foundFirstIndex &&\n      stringMatches(CMIElement, \"cmi\\\\.interactions\\\\.\\\\d+\\\\.correct_responses\\\\.\\\\d+\")\n    ) {\n      return new CMIInteractionsCorrectResponsesObject();\n    } else if (\n      foundFirstIndex &&\n      stringMatches(CMIElement, \"cmi\\\\.interactions\\\\.\\\\d+\\\\.objectives\\\\.\\\\d+\")\n    ) {\n      return new CMIInteractionsObjectivesObject();\n    } else if (!foundFirstIndex && stringMatches(CMIElement, \"cmi\\\\.interactions\\\\.\\\\d+\")) {\n      return new CMIInteractionsObject();\n    }\n\n    return null;\n  }\n\n  /**\n   * Validates Correct Response values\n   *\n   * @param {string} _CMIElement\n   * @param {*} _value\n   */\n  validateCorrectResponse(_CMIElement: string, _value: any) {\n    // do nothing\n  }\n\n  /**\n   * Returns the message that corresponds to errorNumber.\n   *\n   * @param {number|string} errorNumber\n   * @param {boolean} detail\n   * @return {string}\n   */\n  override getLmsErrorMessageDetails(errorNumber: number | string, detail: boolean): string {\n    let basicMessage = \"No Error\";\n    let detailMessage = \"No Error\";\n\n    // Set error number to string since inconsistent from modules if string or number\n    errorNumber = String(errorNumber);\n    if (scorm12_constants.error_descriptions[errorNumber]) {\n      basicMessage =\n        scorm12_constants.error_descriptions[errorNumber]?.basicMessage || basicMessage;\n      detailMessage =\n        scorm12_constants.error_descriptions[errorNumber]?.detailMessage || detailMessage;\n    }\n\n    return detail ? detailMessage : basicMessage;\n  }\n\n  /**\n   * Replace the whole API with another\n   *\n   * @param {Scorm12API} newAPI\n   */\n  replaceWithAnotherScormAPI(newAPI: Scorm12API) {\n    // Data Model\n    this.cmi = newAPI.cmi;\n  }\n\n  /**\n   * Render the cmi object to the proper format for LMS commit\n   *\n   * @param {boolean} terminateCommit - Whether this is a termination commit\n   * @param {boolean} includeTotalTime - Whether to include total time in the commit data\n   * @return {object|Array}\n   */\n  renderCommitCMI(\n    terminateCommit: boolean,\n    includeTotalTime: boolean = false,\n  ): StringKeyMap | Array<string> {\n    const cmiExport: StringKeyMap = this.renderCMIToJSONObject();\n\n    if (terminateCommit || includeTotalTime) {\n      ((cmiExport.cmi as StringKeyMap).core as StringKeyMap).total_time =\n        this.cmi.getCurrentTotalTime();\n    }\n\n    const flattened: StringKeyMap = flatten(cmiExport);\n    switch (this.settings.dataCommitFormat) {\n      case \"flattened\":\n        return flattened;\n      case \"params\":\n        return Object.entries(flattened).map(([item, value]) => `${item}=${value}`);\n      case \"json\":\n      default:\n        return cmiExport;\n    }\n  }\n\n  /**\n   * Render the cmi object to the proper format for LMS commit\n   * @param {boolean} terminateCommit - Whether this is a termination commit\n   * @param {boolean} includeTotalTime - Whether to include total time in the commit data\n   * @return {CommitObject}\n   */\n  renderCommitObject(terminateCommit: boolean, includeTotalTime: boolean = false): CommitObject {\n    const cmiExport = this.renderCommitCMI(terminateCommit, includeTotalTime);\n    const calculateTotalTime = terminateCommit || includeTotalTime;\n    const totalTimeHHMMSS = calculateTotalTime ? this.cmi.getCurrentTotalTime() : \"\";\n    const totalTimeSeconds = getTimeAsSeconds(totalTimeHHMMSS, scorm12_regex.CMITimespan);\n    const lessonStatus = this.cmi.core.lesson_status;\n    let completionStatus = CompletionStatus.UNKNOWN;\n    let successStatus = SuccessStatus.UNKNOWN;\n    if (lessonStatus) {\n      completionStatus =\n        lessonStatus === \"completed\" || lessonStatus === \"passed\"\n          ? CompletionStatus.COMPLETED\n          : CompletionStatus.INCOMPLETE;\n      if (lessonStatus === \"passed\") {\n        successStatus = SuccessStatus.PASSED;\n      } else if (lessonStatus === \"failed\") {\n        successStatus = SuccessStatus.FAILED;\n      }\n    }\n\n    const scoreObject: ScoreObject = this.cmi?.core?.score?.getScoreObject() || {};\n    const commitObject: CommitObject = {\n      successStatus: successStatus,\n      completionStatus: completionStatus,\n      runtimeData: cmiExport as StringKeyMap,\n      totalTimeSeconds: totalTimeSeconds,\n    };\n    if (scoreObject) {\n      commitObject.score = scoreObject;\n    }\n\n    // Populate metadata if enabled\n    if (this.settings.autoPopulateCommitMetadata) {\n      if (this.settings.courseId) {\n        commitObject.courseId = this.settings.courseId;\n      }\n      if (this.settings.scoId) {\n        commitObject.scoId = this.settings.scoId;\n      }\n      if (this.cmi.core.student_id) {\n        commitObject.learnerId = this.cmi.core.student_id;\n      }\n      if (this.cmi.core.student_name) {\n        commitObject.learnerName = this.cmi.core.student_name;\n      }\n    }\n\n    return commitObject;\n  }\n\n  /**\n   * Attempts to store the data to the LMS\n   *\n   * @param {boolean} terminateCommit\n   * @param {CommitTrigger} [trigger] - What initiated the commit\n   * @return {ResultObject}\n   */\n  storeData(terminateCommit: boolean, trigger?: CommitTrigger): ResultObject {\n    if (terminateCommit) {\n      const originalStatus = this.cmi.core.lesson_status;\n\n      // Check browse mode FIRST (before Stage 1)\n      if (this.cmi.core.lesson_mode === \"browse\") {\n        const startingStatus =\n          ((this.startingData?.cmi as StringKeyMap)?.core as StringKeyMap)?.lesson_status || \"\";\n        if (startingStatus === \"\" && originalStatus === \"not attempted\") {\n          this.cmi.core.lesson_status = \"browsed\";\n          // Skip Stage 1 and Stage 2 for browse mode\n          return this.processCommitData(terminateCommit, trigger);\n        }\n      }\n\n      // Stage 1: Apply mastery when status is unset/not-attempted\n      if (\n        !this.cmi.core.lesson_status ||\n        (!this.statusSetByModule && this.cmi.core.lesson_status === \"not attempted\")\n      ) {\n        this.cmi.core.lesson_status = this.settings.autoCompleteLessonStatus\n          ? \"completed\"\n          : \"incomplete\";\n      }\n\n      if (this.cmi.core.lesson_mode === \"normal\") {\n        if (this.cmi.core.credit === \"credit\") {\n          if (\n            this.settings.mastery_override &&\n            this.cmi.student_data.mastery_score !== \"\" &&\n            this.cmi.core.score.raw !== \"\"\n          ) {\n            const rawScore = parseFloat(this.cmi.core.score.raw);\n            const masteryScore = parseFloat(this.cmi.student_data.mastery_score);\n            if (!isNaN(rawScore) && !isNaN(masteryScore)) {\n              this.cmi.core.lesson_status = rawScore >= masteryScore ? \"passed\" : \"failed\";\n            }\n          }\n        }\n      }\n\n      // Stage 2: Override SCO-set status if score_overrides_status is enabled\n      if (\n        this.settings.score_overrides_status &&\n        this.statusSetByModule &&\n        this.cmi.core.lesson_mode === \"normal\" &&\n        this.cmi.core.credit === \"credit\" &&\n        this.cmi.student_data.mastery_score !== \"\" &&\n        this.cmi.core.score.raw !== \"\"\n      ) {\n        const rawScore = parseFloat(this.cmi.core.score.raw);\n        const masteryScore = parseFloat(this.cmi.student_data.mastery_score);\n        if (!isNaN(rawScore) && !isNaN(masteryScore)) {\n          if (rawScore >= masteryScore) {\n            this.cmi.core.lesson_status = \"passed\";\n          } else {\n            this.cmi.core.lesson_status = \"failed\";\n          }\n        }\n      }\n    }\n\n    return this.processCommitData(terminateCommit, trigger);\n  }\n\n  private processCommitData(terminateCommit: boolean, trigger?: CommitTrigger): ResultObject {\n    const commitObject = this.getCommitObject(terminateCommit);\n    if (typeof this.settings.lmsCommitUrl === \"string\") {\n      return this.processHttpRequest(\n        this.settings.lmsCommitUrl,\n        commitObject,\n        terminateCommit,\n        trigger,\n      );\n    } else {\n      return {\n        result: global_constants.SCORM_TRUE,\n        errorCode: 0,\n      };\n    }\n  }\n}\n\nexport default Scorm12API;\n","/**\n * Class for SCORM 2004's cmi.learner_preference object\n */\nimport { BaseCMI } from \"../common/base_cmi\";\nimport { Scorm2004ValidationError } from \"../../exceptions/scorm2004_exceptions\";\nimport { check2004ValidFormat, check2004ValidRange } from \"./validation\";\nimport {\n  scorm2004_constants,\n  scorm2004_errors,\n  scorm2004_regex,\n} from \"../../constants\";\n\nexport class CMILearnerPreference extends BaseCMI {\n  private __children = scorm2004_constants.student_preference_children;\n  private _audio_level = \"1\";\n  private _language = \"\";\n  private _delivery_speed = \"1\";\n  private _audio_captioning = \"0\";\n\n  /**\n   * Constructor for cmi.learner_preference\n   */\n  constructor() {\n    super(\"cmi.learner_preference\");\n  }\n\n  /**\n   * Called when the API has been reset\n   */\n  override reset() {\n    this._initialized = false;\n  }\n\n  /**\n   * Getter for __children\n   * @return {string}\n   * @private\n   */\n  get _children(): string {\n    return this.__children;\n  }\n\n  /**\n   * Setter for __children. Just throws an error.\n   * @param {string} _children\n   * @private\n   */\n  set _children(_children: string) {\n    throw new Scorm2004ValidationError(\n      this._cmi_element + \"._children\",\n      scorm2004_errors.READ_ONLY_ELEMENT as number,\n    );\n  }\n\n  /**\n   * Getter for _audio_level\n   * @return {string}\n   */\n  get audio_level(): string {\n    return this._audio_level;\n  }\n\n  /**\n   * Setter for _audio_level\n   * @param {string} audio_level\n   */\n  set audio_level(audio_level: string) {\n    if (\n      check2004ValidFormat(\n        this._cmi_element + \".audio_level\",\n        audio_level,\n        scorm2004_regex.CMIDecimal,\n      ) &&\n      check2004ValidRange(\n        this._cmi_element + \".audio_level\",\n        audio_level,\n        scorm2004_regex.audio_range,\n      )\n    ) {\n      this._audio_level = audio_level;\n    }\n  }\n\n  /**\n   * Getter for _language\n   * @return {string}\n   */\n  get language(): string {\n    return this._language;\n  }\n\n  /**\n   * Setter for _language\n   * @param {string} language\n   */\n  set language(language: string) {\n    if (check2004ValidFormat(this._cmi_element + \".language\", language, scorm2004_regex.CMILang, true)) {\n      this._language = language;\n    }\n  }\n\n  /**\n   * Getter for _delivery_speed\n   * @return {string}\n   */\n  get delivery_speed(): string {\n    return this._delivery_speed;\n  }\n\n  /**\n   * Setter for _delivery_speed\n   * @param {string} delivery_speed\n   */\n  set delivery_speed(delivery_speed: string) {\n    if (\n      check2004ValidFormat(\n        this._cmi_element + \".delivery_speed\",\n        delivery_speed,\n        scorm2004_regex.CMIDecimal,\n      ) &&\n      check2004ValidRange(\n        this._cmi_element + \".delivery_speed\",\n        delivery_speed,\n        scorm2004_regex.speed_range,\n      )\n    ) {\n      // SCORM 2004 spec requires delivery_speed > 0 (not >= 0)\n      if (parseFloat(delivery_speed) === 0) {\n        throw new Scorm2004ValidationError(\n          this._cmi_element + \".delivery_speed\",\n          scorm2004_errors.VALUE_OUT_OF_RANGE as number,\n        );\n      }\n      this._delivery_speed = delivery_speed;\n    }\n  }\n\n  /**\n   * Getter for _audio_captioning\n   * @return {string}\n   */\n  get audio_captioning(): string {\n    return this._audio_captioning;\n  }\n\n  /**\n   * Setter for _audio_captioning\n   * @param {string} audio_captioning\n   */\n  set audio_captioning(audio_captioning: string) {\n    if (\n      check2004ValidFormat(\n        this._cmi_element + \".audio_captioning\",\n        audio_captioning,\n        scorm2004_regex.CMISInteger,\n      ) &&\n      check2004ValidRange(\n        this._cmi_element + \".audio_captioning\",\n        audio_captioning,\n        scorm2004_regex.text_range,\n      )\n    ) {\n      this._audio_captioning = audio_captioning;\n    }\n  }\n\n  /**\n   * toJSON for cmi.learner_preference\n   *\n   * @return {\n   *    {\n   *      audio_level: string,\n   *      language: string,\n   *      delivery_speed: string,\n   *      audio_captioning: string\n   *    }\n   *  }\n   */\n  toJSON(): {\n    audio_level: string;\n    language: string;\n    delivery_speed: string;\n    audio_captioning: string;\n  } {\n    this.jsonString = true;\n    const result = {\n      audio_level: this.audio_level,\n      language: this.language,\n      delivery_speed: this.delivery_speed,\n      audio_captioning: this.audio_captioning,\n    };\n    this.jsonString = false;\n    return result;\n  }\n}\n","/**\n * Helpers for splitting SCORM 2004 interaction `correct_responses` /\n * `learner_response` pattern strings on the spec's reserved separator\n * delimiters.\n *\n * Per the SCORM 2004 4th Edition RTE (sec 4.1.1.6, Table 4.1.1.6b) the\n * separator delimiters are the *bracketed* tokens \"[,]\", \"[.]\" and \"[:]\":\n *\n *     delimiter ::= \"[\" + reserved_character + \"]\"   // reserved_character ∈ { . , : }\n *\n * and the spec is explicit that the brackets are required: \"The absence of\n * these required characters will cause the delimiter to not be recognized by\n * the system; instead, the set of characters will be treated as part of the\n * underlying characterstring.\" So a bare \".\", \",\" or \":\" is literal data.\n *\n * scorm-again historically split on the *bare* character instead, which both\n * rejected spec-compliant bracketed patterns (issue #1571) and could not\n * represent values that legitimately contain a literal \".\" or \":\". To accept\n * the spec form without breaking legacy plain content, we split on the\n * bracketed tokens throughout a value containing any reserved token. Bare\n * fallback is allowed only for wholly legacy values, except fill-in items,\n * where bare commas are always literal text.\n */\n\nexport function isSpecForm(value: string): boolean {\n  return /\\[[,.:]\\]/.test(value);\n}\n\n/** Remove the square brackets from a reserved token: \"[,]\" -> \",\" */\nexport function stripBrackets(delim: string): string {\n  return delim.replace(/[[\\]]/g, \"\");\n}\n\n/** Escape a string for use inside a RegExp. */\nfunction escapeRegex(s: string): string {\n  return s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\n/**\n * Split `value` on a reserved separator delimiter token such as \"[,]\".\n *\n * - If `value` contains the bracketed token, split on the literal token\n *   (the spec form). Every occurrence is a separator.\n * - Otherwise, if allowed, split on the bare character, treating \"\\<char>\" as an escaped\n *   literal (the legacy/back-compat form); return [value] when disabled.\n *\n * @param value - the characterstring to split\n * @param bracketed - the bracketed delimiter token, e.g. \"[,]\" / \"[.]\" / \"[:]\"\n */\nexport function splitDelimited(value: string, bracketed: string, allowBare = true): string[] {\n  if (!bracketed) {\n    return [value];\n  }\n  if (value.includes(bracketed)) {\n    return value.split(bracketed);\n  }\n  if (!allowBare) {\n    return [value];\n  }\n  const bare = stripBrackets(bracketed);\n  if (!bare) {\n    return [value];\n  }\n  const splitRe = new RegExp(`(?<!\\\\\\\\)${escapeRegex(bare)}`, \"g\");\n  const unescapeRe = new RegExp(`\\\\\\\\${escapeRegex(bare)}`, \"g\");\n  return value.split(splitRe).map((part) => part.replace(unescapeRe, bare));\n}\n\n/**\n * Split `value` on the FIRST occurrence of a reserved separator delimiter only.\n *\n * Used for `performance` patterns (`step_name[.]step_answer`) where the\n * step_answer may itself contain literal dots (decimals like \"3.14\") or colons\n * (ranges). Returns a single element when no delimiter is present, otherwise\n * exactly two elements.\n *\n * @param value - the characterstring to split\n * @param bracketed - the bracketed delimiter token, e.g. \"[.]\"\n */\nexport function splitFirstDelimited(value: string, bracketed: string, allowBare = true): string[] {\n  if (!bracketed) {\n    return [value];\n  }\n  if (value.includes(bracketed)) {\n    const idx = value.indexOf(bracketed);\n    return [value.slice(0, idx), value.slice(idx + bracketed.length)];\n  }\n  if (!allowBare) {\n    return [value];\n  }\n  const bare = stripBrackets(bracketed);\n  if (!bare) {\n    return [value];\n  }\n  const splitRe = new RegExp(`(?<!\\\\\\\\)${escapeRegex(bare)}`);\n  const unescapeRe = new RegExp(`\\\\\\\\${escapeRegex(bare)}`, \"g\");\n  const parts = value.split(splitRe);\n  const first = (parts[0] ?? \"\").replace(unescapeRe, bare);\n  if (parts.length === 1) {\n    return [first];\n  }\n  return [first, parts.slice(1).join(bare).replace(unescapeRe, bare)];\n}\n\n/** Bare separators are supported only in legacy values outside fill-in text. */\nexport function allowsBareDelimiters(value: string, type: string): boolean {\n  return !isSpecForm(value) && type !== \"fill-in\";\n}\n","/**\n * Class representing SCORM 2004's `cmi.interactions` object\n *\n * Per SCORM 2004 RTE Section 4.1.6:\n * - Enhanced interaction tracking vs SCORM 1.2\n * - Supports additional interaction types (long-fill-in, other)\n * - learner_response replaces student_response\n * - timestamp: ISO 8601 format for precise timing\n * - description: Textual description with language support\n * - Stricter validation of response formats by type\n * - Correct response patterns support complex formats\n *\n * @spec RTE 4.2.9 - cmi.interactions\n * @extends CMIArray\n */\nimport { BaseCMI } from \"../common/base_cmi\";\nimport { CMIArray } from \"../common/array\";\nimport { Scorm2004ValidationError } from \"../../exceptions/scorm2004_exceptions\";\nimport { check2004ValidFormat } from \"./validation\";\nimport { allowsBareDelimiters, splitDelimited, splitFirstDelimited } from \"./interaction_delimiters\";\nimport {\n  CorrectResponses,\n  LearnerResponses,\n  ResponseType,\n  scorm2004_constants,\n  scorm2004_errors,\n  scorm2004_regex,\n} from \"../../constants\";\n\n// Whole-value emptiness is distinct from empty items inside a response.\nconst EMPTY_CORRECT_PATTERN_TYPES = new Set([\n  \"choice\",\n  \"fill-in\",\n  \"long-fill-in\",\n  \"other\",\n  \"sequencing\",\n]);\nconst EMPTY_LEARNER_RESPONSE_TYPES = new Set([...EMPTY_CORRECT_PATTERN_TYPES, \"matching\"]);\n\nexport class CMIInteractions extends CMIArray {\n  /**\n   * Constructor for `cmi.interactions` Array\n   *\n   * Per SCORM 2004 RTE Section 4.1.6:\n   * - Read-only array structure (add via index access)\n   * - Each interaction has enhanced metadata and validation\n   */\n  constructor() {\n    super({\n      CMIElement: \"cmi.interactions\",\n      children: scorm2004_constants.interactions_children,\n      errorCode: scorm2004_errors.READ_ONLY_ELEMENT as number,\n      errorClass: Scorm2004ValidationError,\n    });\n  }\n}\n\n/**\n * Class for SCORM 2004's cmi.interaction.n object\n *\n * Per SCORM 2004 RTE Section 4.1.6:\n * - id: Long identifier (up to 4000 chars, supports URN format)\n * - type: Interaction type (true-false, choice, fill-in, long-fill-in, matching, performance, sequencing, likert, numeric, other)\n * - timestamp: ISO 8601 date/time when interaction occurred\n * - weighting: Decimal weight for scoring\n * - learner_response: Response format validated against interaction type\n * - result: correct, incorrect, unanticipated, neutral, or numeric score\n * - latency: ISO 8601 duration format\n * - description: LangString250 with optional language tag\n * - Dependency: id must be set before other elements (except objectives/correct_responses)\n *\n * @spec RTE 4.2.9.1 - cmi.interactions.n.id\n * @spec RTE 4.2.9.2 - cmi.interactions.n.type\n * @spec RTE 4.2.9.3 - cmi.interactions.n.objectives\n * @spec RTE 4.2.9.4 - cmi.interactions.n.timestamp\n * @spec RTE 4.2.9.5 - cmi.interactions.n.correct_responses\n * @spec RTE 4.2.9.6 - cmi.interactions.n.weighting\n * @spec RTE 4.2.9.7 - cmi.interactions.n.learner_response\n * @spec RTE 4.2.9.8 - cmi.interactions.n.result\n * @spec RTE 4.2.9.9 - cmi.interactions.n.latency\n * @spec RTE 4.2.9.10 - cmi.interactions.n.description\n * @extends BaseCMI\n */\n\nexport class CMIInteractionsObject extends BaseCMI {\n  private _id = \"\";\n  private _idIsSet = false;\n  private _type = \"\";\n  private _timestamp = \"\";\n  private _weighting = \"\";\n  private _learner_response = \"\";\n  private _result = \"\";\n  private _latency = \"\";\n  private _description = \"\";\n\n  /**\n   * Constructor for cmi.interaction.n\n   */\n  constructor() {\n    super(\"cmi.interactions.n\");\n    this.objectives = new CMIArray({\n      CMIElement: \"cmi.interactions.n.objectives\",\n      errorCode: scorm2004_errors.READ_ONLY_ELEMENT as number,\n      errorClass: Scorm2004ValidationError,\n      children: scorm2004_constants.objectives_children,\n    });\n    this.correct_responses = new CMIArray({\n      CMIElement: \"cmi.interactions.n.correct_responses\",\n      errorCode: scorm2004_errors.READ_ONLY_ELEMENT as number,\n      errorClass: Scorm2004ValidationError,\n      children: scorm2004_constants.correct_responses_children,\n    });\n  }\n\n  public objectives: CMIArray;\n  public correct_responses: CMIArray;\n\n  /**\n   * Called when the API has been initialized after the CMI has been created\n   */\n  override initialize() {\n    super.initialize();\n    this.objectives?.initialize();\n    this.correct_responses?.initialize();\n  }\n\n  /**\n   * Called when the API has been reset\n   */\n  override reset() {\n    this._initialized = false;\n    this._id = \"\";\n    this._idIsSet = false;\n    this._type = \"\";\n    this._timestamp = \"\";\n    this._weighting = \"\";\n    this._learner_response = \"\";\n    this._result = \"\";\n    this._latency = \"\";\n    this._description = \"\";\n    this.objectives = new CMIArray({\n      CMIElement: \"cmi.interactions.n.objectives\",\n      errorCode: scorm2004_errors.READ_ONLY_ELEMENT as number,\n      errorClass: Scorm2004ValidationError,\n      children: scorm2004_constants.objectives_children,\n    });\n    this.correct_responses = new CMIArray({\n      CMIElement: \"cmi.interactions.n.correct_responses\",\n      errorCode: scorm2004_errors.READ_ONLY_ELEMENT as number,\n      errorClass: Scorm2004ValidationError,\n      children: scorm2004_constants.correct_responses_children,\n    });\n  }\n\n  /**\n   * Getter for _id\n   * @return {string}\n   */\n  get id(): string {\n    return this._id;\n  }\n\n  /**\n   * Setter for _id\n   * Per SCORM 2004 RTE: identifier SHALL NOT be empty or contain only whitespace\n   * Per SCORM 2004 RTE Section 4.1.6: Once set, an interaction ID is immutable (error 351)\n   * @param {string} id\n   */\n  set id(id: string) {\n    // Per spec: identifier cannot be empty or whitespace-only\n    if (id === \"\" || id.trim() === \"\") {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".id\",\n        scorm2004_errors.TYPE_MISMATCH as number,\n      );\n    }\n    // Per SCORM 2004 RTE: Once an interaction ID is set, it cannot be changed\n    if (this._idIsSet && this._id !== id) {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".id\",\n        scorm2004_errors.GENERAL_SET_FAILURE as number,\n      );\n    }\n    if (check2004ValidFormat(this._cmi_element + \".id\", id, scorm2004_regex.CMILongIdentifier)) {\n      this._id = id;\n      this._idIsSet = true;\n    }\n  }\n\n  /**\n   * Getter for _type\n   * @return {string}\n   */\n  get type(): string {\n    return this._type;\n  }\n\n  /**\n   * Setter for _type\n   * @param {string} type\n   */\n  set type(type: string) {\n    if (this.initialized && this._id === \"\") {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".type\",\n        scorm2004_errors.DEPENDENCY_NOT_ESTABLISHED as number,\n      );\n    } else {\n      if (check2004ValidFormat(this._cmi_element + \".type\", type, scorm2004_regex.CMIType)) {\n        this._type = type;\n      }\n    }\n  }\n\n  /**\n   * Getter for _timestamp\n   * @return {string}\n   */\n  get timestamp(): string {\n    return this._timestamp;\n  }\n\n  /**\n   * Setter for _timestamp\n   * @param {string} timestamp\n   */\n  set timestamp(timestamp: string) {\n    if (this.initialized && this._id === \"\") {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".timestamp\",\n        scorm2004_errors.DEPENDENCY_NOT_ESTABLISHED as number,\n      );\n    } else {\n      if (\n        check2004ValidFormat(this._cmi_element + \".timestamp\", timestamp, scorm2004_regex.CMITime)\n      ) {\n        this._timestamp = timestamp;\n      }\n    }\n  }\n\n  /**\n   * Getter for _weighting\n   * @return {string}\n   */\n  get weighting(): string {\n    return this._weighting;\n  }\n\n  /**\n   * Setter for _weighting\n   * @param {string} weighting\n   */\n  set weighting(weighting: string) {\n    if (this.initialized && this._id === \"\") {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".weighting\",\n        scorm2004_errors.DEPENDENCY_NOT_ESTABLISHED as number,\n      );\n    } else {\n      if (\n        check2004ValidFormat(\n          this._cmi_element + \".weighting\",\n          weighting,\n          scorm2004_regex.CMIDecimal,\n        )\n      ) {\n        this._weighting = weighting;\n      }\n    }\n  }\n\n  /**\n   * Getter for _learner_response\n   * @return {string}\n   */\n  get learner_response(): string {\n    return this._learner_response;\n  }\n\n  /**\n   * Setter for _learner_response. Does type validation to make sure response\n   * matches SCORM 2004's spec\n   * @param {string} learner_response\n   */\n  set learner_response(learner_response: string) {\n    if (this.initialized && (this._type === \"\" || this._id === \"\")) {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".learner_response\",\n        scorm2004_errors.DEPENDENCY_NOT_ESTABLISHED as number,\n      );\n    } else {\n      if (learner_response === \"\" && EMPTY_LEARNER_RESPONSE_TYPES.has(this.type)) {\n        this._learner_response = \"\";\n        return;\n      }\n      const allowBare = allowsBareDelimiters(learner_response, this.type);\n      let nodes = [];\n      const response_type = LearnerResponses[this.type];\n\n      if (response_type) {\n        if (response_type?.delimiter) {\n          // Split on the spec's bracketed token (\"[,]\") when present, falling\n          // back to the bare character for legacy plain responses.\n          nodes = splitDelimited(learner_response, response_type.delimiter, allowBare);\n        } else {\n          nodes[0] = learner_response;\n        }\n\n        if (nodes.length > 0 && nodes.length <= response_type.max) {\n          const formatRegex = new RegExp(response_type.format);\n\n          for (let i = 0; i < nodes.length; i++) {\n            if (response_type?.delimiter2) {\n              // Split each node on the spec's bracketed pair token (\"[.]\").\n              // performance step_answers may contain literal dots, so split on\n              // the first delimiter only; matching pairs split on all (so a\n              // malformed 3-member record is rejected below).\n              const node = nodes[i] ?? \"\";\n              const values =\n                this.type === \"performance\"\n                  ? splitFirstDelimited(node, response_type.delimiter2, allowBare)\n                  : splitDelimited(node, response_type.delimiter2, allowBare);\n\n              if (values?.length === 2) {\n                // A performance record must include at least one of\n                // step_name / step_answer; only both-empty is invalid.\n                if (this.type === \"performance\" && values[0] === \"\" && values[1] === \"\") {\n                  throw new Scorm2004ValidationError(\n                    this._cmi_element + \".learner_response\",\n                    scorm2004_errors.TYPE_MISMATCH as number,\n                  );\n                }\n\n                if (!values[0]?.match(formatRegex)) {\n                  throw new Scorm2004ValidationError(\n                    this._cmi_element + \".learner_response\",\n                    scorm2004_errors.TYPE_MISMATCH as number,\n                  );\n                } else {\n                  if (\n                    !response_type.format2 ||\n                    !values[1]?.match(new RegExp(response_type.format2))\n                  ) {\n                    throw new Scorm2004ValidationError(\n                      this._cmi_element + \".learner_response\",\n                      scorm2004_errors.TYPE_MISMATCH as number,\n                    );\n                  }\n                }\n              } else {\n                throw new Scorm2004ValidationError(\n                  this._cmi_element + \".learner_response\",\n                  scorm2004_errors.TYPE_MISMATCH as number,\n                );\n              }\n            } else {\n              if (!nodes[i]?.match(formatRegex)) {\n                throw new Scorm2004ValidationError(\n                  this._cmi_element + \".learner_response\",\n                  scorm2004_errors.TYPE_MISMATCH as number,\n                );\n              } else {\n                if (nodes[i] !== \"\" && response_type.unique) {\n                  for (let j = 0; j < i; j++) {\n                    if (nodes[i] === nodes[j]) {\n                      throw new Scorm2004ValidationError(\n                        this._cmi_element + \".learner_response\",\n                        scorm2004_errors.TYPE_MISMATCH as number,\n                      );\n                    }\n                  }\n                }\n              }\n            }\n          }\n        } else {\n          throw new Scorm2004ValidationError(\n            this._cmi_element + \".learner_response\",\n            scorm2004_errors.GENERAL_SET_FAILURE as number,\n          );\n        }\n\n        this._learner_response = learner_response;\n      } else {\n        throw new Scorm2004ValidationError(\n          this._cmi_element + \".learner_response\",\n          scorm2004_errors.TYPE_MISMATCH as number,\n        );\n      }\n    }\n  }\n\n  /**\n   * Getter for _result\n   * @return {string}\n   */\n  get result(): string {\n    return this._result;\n  }\n\n  /**\n   * Setter for _result\n   * @param {string} result\n   */\n  set result(result: string) {\n    if (check2004ValidFormat(this._cmi_element + \".result\", result, scorm2004_regex.CMIResult)) {\n      this._result = result;\n    }\n  }\n\n  /**\n   * Getter for _latency\n   * @return {string}\n   */\n  get latency(): string {\n    return this._latency;\n  }\n\n  /**\n   * Setter for _latency\n   * @param {string} latency\n   */\n  set latency(latency: string) {\n    if (this.initialized && this._id === \"\") {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".latency\",\n        scorm2004_errors.DEPENDENCY_NOT_ESTABLISHED as number,\n      );\n    } else {\n      if (\n        check2004ValidFormat(this._cmi_element + \".latency\", latency, scorm2004_regex.CMITimespan)\n      ) {\n        this._latency = latency;\n      }\n    }\n  }\n\n  /**\n   * Getter for _description\n   * @return {string}\n   */\n  get description(): string {\n    return this._description;\n  }\n\n  /**\n   * Setter for _description\n   * @param {string} description\n   */\n  set description(description: string) {\n    if (this.initialized && this._id === \"\") {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".description\",\n        scorm2004_errors.DEPENDENCY_NOT_ESTABLISHED as number,\n      );\n    } else {\n      // Note: SCORM 2004 specifies an SPM of 250 chars for description (localized_string_type).\n      // We intentionally do NOT enforce this limit to maximize LMS compatibility (#1642).\n      // The {lang=...} prefix format is still validated.\n      if (\n        check2004ValidFormat(\n          this._cmi_element + \".description\",\n          description,\n          scorm2004_regex.CMILangString,\n          true,\n        )\n      ) {\n        this._description = description;\n      }\n    }\n  }\n\n  // noinspection JSUnusedGlobalSymbols\n  /**\n   * toJSON for cmi.interactions.n\n   *\n   * @return {\n   *    {\n   *      id: string,\n   *      type: string,\n   *      objectives: CMIArray,\n   *      timestamp: string,\n   *      correct_responses: CMIArray,\n   *      weighting: string,\n   *      learner_response: string,\n   *      result: string,\n   *      latency: string,\n   *      description: string\n   *    }\n   *  }\n   */\n  toJSON(): {\n    id: string;\n    type: string;\n    objectives: CMIArray;\n    timestamp: string;\n    correct_responses: CMIArray;\n    weighting: string;\n    learner_response: string;\n    result: string;\n    latency: string;\n    description: string;\n  } {\n    this.jsonString = true;\n    const result = {\n      id: this.id,\n      type: this.type,\n      objectives: this.objectives,\n      timestamp: this.timestamp,\n      weighting: this.weighting,\n      learner_response: this.learner_response,\n      result: this.result,\n      latency: this.latency,\n      description: this.description,\n      correct_responses: this.correct_responses,\n    };\n    this.jsonString = false;\n    return result;\n  }\n}\n\n/**\n * Class representing SCORM 2004's cmi.interactions.n.objectives.n object\n *\n * Per SCORM 2004 RTE Section 4.1.6.1:\n * - Associates interaction with objectives\n * - id: Long identifier matching objective in cmi.objectives\n * - Used to relate interaction performance to learning objectives\n *\n * @extends BaseCMI\n */\nexport class CMIInteractionsObjectivesObject extends BaseCMI {\n  private _id = \"\";\n\n  /**\n   * Constructor for cmi.interactions.n.objectives.n\n   */\n  constructor() {\n    super(\"cmi.interactions.n.objectives.n\");\n  }\n\n  /**\n   * Called when the API has been reset\n   */\n  override reset() {\n    this._initialized = false;\n    this._id = \"\";\n  }\n\n  /**\n   * Getter for _id\n   * @return {string}\n   */\n  get id(): string {\n    return this._id;\n  }\n\n  /**\n   * Setter for _id\n   * Per SCORM 2004 RTE: identifier SHALL NOT be empty or contain only whitespace\n   * @param {string} id\n   */\n  set id(id: string) {\n    // Per spec: identifier cannot be empty or whitespace-only\n    if (id === \"\" || id.trim() === \"\") {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".id\",\n        scorm2004_errors.TYPE_MISMATCH as number,\n      );\n    }\n    if (check2004ValidFormat(this._cmi_element + \".id\", id, scorm2004_regex.CMILongIdentifier)) {\n      this._id = id;\n    }\n  }\n\n  /**\n   * toJSON for cmi.interactions.n.objectives.n\n   * @return {\n   *    {\n   *      id: string\n   *    }\n   *  }\n   */\n  toJSON(): {\n    id: string;\n  } {\n    this.jsonString = true;\n    const result = {\n      id: this.id,\n    };\n    this.jsonString = false;\n    return result;\n  }\n}\n\n/** Validate and strip leading correct-response properties without mutating CMI state. */\nexport function stripCorrectResponsePrefixes(\n  node: string,\n  type?: string,\n  firstItem = true,\n): string {\n  let text = node;\n  const seen = new Set<string>();\n  let prefix: RegExpMatchArray | null;\n  while ((prefix = text.match(/^\\{(lang|case_matters|order_matters)=([^}]*)\\}/))) {\n    const property = prefix[1]!;\n    const value = prefix[2]!;\n    const invalidValue =\n      property === \"lang\"\n        ? !new RegExp(scorm2004_regex.CMILang).test(value)\n        : value !== \"true\" && value !== \"false\";\n    const invalidPosition =\n      type !== undefined &&\n      (seen.has(property) ||\n        (property !== \"lang\" && (!firstItem || seen.has(\"lang\"))) ||\n        (type === \"long-fill-in\" && property === \"order_matters\") ||\n        (type === \"performance\" && property !== \"order_matters\"));\n    if (invalidValue || invalidPosition) {\n      throw new Scorm2004ValidationError(\n        \"cmi.interactions.n.correct_responses.n.pattern\",\n        scorm2004_errors.TYPE_MISMATCH as number,\n      );\n    }\n    seen.add(property);\n    text = text.slice(prefix[0].length);\n  }\n  return text;\n}\n\n/**\n * Helper: validate a `pattern` string against its SCORM definition\n */\nfunction validatePattern(type: string, pattern: string, responseDef: ResponseType) {\n  const allowBare = allowsBareDelimiters(pattern, type);\n  const freeText = [\"fill-in\", \"long-fill-in\", \"other\"].includes(type);\n  // Reject patterns with leading or trailing whitespace\n  if (!freeText && pattern.trim() !== pattern) {\n    throw new Scorm2004ValidationError(\n      \"cmi.interactions.n.correct_responses.n.pattern\",\n      scorm2004_errors.TYPE_MISMATCH as number,\n    );\n  }\n\n  // Reject any nodes with leading/trailing whitespace around tokens\n  const rawNodes = responseDef.delimiter\n    ? splitDelimited(pattern, responseDef.delimiter, allowBare)\n    : [pattern];\n  for (const raw of rawNodes) {\n    if (!freeText && raw.trim() !== raw) {\n      throw new Scorm2004ValidationError(\n        \"cmi.interactions.n.correct_responses.n.pattern\",\n        scorm2004_errors.TYPE_MISMATCH as number,\n      );\n    }\n  }\n\n  // Allow an empty whole pattern for types that permit zero items or empty text\n  if (EMPTY_CORRECT_PATTERN_TYPES.has(type) && pattern === \"\") {\n    return;\n  }\n  // Split into nodes on the primary delimiter (if any). Uses the spec's\n  // bracketed token (\"[,]\" / \"[:]\") when present, falling back to the bare\n  // character for legacy plain patterns.\n  const nodes: string[] = responseDef.delimiter\n    ? splitDelimited(pattern, responseDef.delimiter, allowBare)\n    : [pattern];\n\n  // Enforce within-pattern uniqueness when required. Numeric is exempt:\n  // its nodes are the min/max bounds of a range, and the spec uses identical\n  // bounds (e.g. \"3.14159[:]3.14159\") to express an exact value.\n  if (type !== \"numeric\" && responseDef.unique) {\n    const seen = new Set(nodes);\n    if (seen.size !== nodes.length) {\n      throw new Scorm2004ValidationError(\n        \"cmi.interactions.n.correct_responses.n.pattern\",\n        scorm2004_errors.TYPE_MISMATCH as number,\n      );\n    }\n  }\n\n  // Must have at least 1 node, and no more than max\n  if (nodes.length === 0 || nodes.length > responseDef.max) {\n    throw new Scorm2004ValidationError(\n      \"cmi.interactions.n.correct_responses.n.pattern\",\n      scorm2004_errors.GENERAL_SET_FAILURE as number,\n    );\n  }\n\n  const fmt1 = new RegExp(responseDef.format);\n  const fmt2 = responseDef.format2 ? new RegExp(responseDef.format2) : null;\n\n  const checkSingle = (value: string) => {\n    if (!fmt1.test(value)) {\n      throw new Scorm2004ValidationError(\n        \"cmi.interactions.n.correct_responses.n.pattern\",\n        scorm2004_errors.TYPE_MISMATCH as number,\n      );\n    }\n  };\n\n  const checkPair = (value: string, delimBracketed?: string) => {\n    if (!delimBracketed) {\n      throw new Scorm2004ValidationError(\n        \"cmi.interactions.n.correct_responses.n.pattern\",\n        scorm2004_errors.TYPE_MISMATCH as number,\n      );\n    }\n    const parts = splitDelimited(value, delimBracketed, allowBare);\n    if (parts.length !== 2 || parts[0] === \"\" || parts[1] === \"\") {\n      throw new Scorm2004ValidationError(\n        \"cmi.interactions.n.correct_responses.n.pattern\",\n        scorm2004_errors.TYPE_MISMATCH as number,\n      );\n    }\n    // test both parts\n    if (\n      (parts[0] !== undefined && !fmt1.test(parts[0])) ||\n      (fmt2 && parts[1] !== undefined && !fmt2.test(parts[1]))\n    ) {\n      throw new Scorm2004ValidationError(\n        \"cmi.interactions.n.correct_responses.n.pattern\",\n        scorm2004_errors.TYPE_MISMATCH as number,\n      );\n    }\n  };\n\n  for (const [nodeIndex, node] of nodes.entries()) {\n    switch (type) {\n      case \"numeric\": {\n        // `nodes` are the bounds produced by splitting on the \"[:]\" range\n        // delimiter (1 node for a single value, 2 for a range). A bound may be\n        // empty for an open-ended range (\"[:]10\", \"4[:]\", \"[:]\"), but only in\n        // the spec's bracketed form: a plain \":\" is literal data, so \"5:\" and\n        // \":10\" are invalid single values.\n        if (node === \"\") {\n          const bracketedRange =\n            nodes.length >= 2 && !!responseDef.delimiter && pattern.includes(responseDef.delimiter);\n          if (!bracketedRange) {\n            throw new Scorm2004ValidationError(\n              \"cmi.interactions.n.correct_responses.n.pattern\",\n              scorm2004_errors.TYPE_MISMATCH as number,\n            );\n          }\n          break;\n        }\n        checkSingle(node);\n        break;\n      }\n\n      case \"fill-in\":\n      case \"long-fill-in\": {\n        checkSingle(stripCorrectResponsePrefixes(node, type, nodeIndex === 0));\n        break;\n      }\n\n      case \"performance\": {\n        // Performance record: {order_matters=<boolean>}?<step_name>[.]<step_answer>\n        // - step_name (optional) is a short_identifier_type\n        // - step_answer (optional) is a characterstring (spaces allowed) or a\n        //   numeric range; a record must include at least one of the two.\n        //\n        // step_answer may contain literal dots (\"3.14\") or a \"[:]\" range, so we\n        // split on the FIRST \"[.]\" only.\n        const delimBracketed = responseDef.delimiter2;\n        if (!delimBracketed) {\n          throw new Scorm2004ValidationError(\n            \"cmi.interactions.n.correct_responses.n.pattern\",\n            scorm2004_errors.TYPE_MISMATCH as number,\n          );\n        }\n\n        // Remove the optional leading property delimiter (e.g.\n        // \"{order_matters=false}\") after validating its value and position.\n        const record = stripCorrectResponsePrefixes(node, type, nodeIndex === 0);\n\n        // Split on the FIRST delimiter only -> [step_name, step_answer]\n        const parts = splitFirstDelimited(record, delimBracketed, allowBare);\n\n        // A record must use the \"[.]\" field separator (exactly two parts)\n        if (parts.length !== 2) {\n          throw new Scorm2004ValidationError(\n            \"cmi.interactions.n.correct_responses.n.pattern\",\n            scorm2004_errors.TYPE_MISMATCH as number,\n          );\n        }\n\n        const [part1, part2] = parts;\n\n        // A record must include at least one of step_name / step_answer\n        if (part1 === \"\" && part2 === \"\") {\n          throw new Scorm2004ValidationError(\n            \"cmi.interactions.n.correct_responses.n.pattern\",\n            scorm2004_errors.TYPE_MISMATCH as number,\n          );\n        }\n\n        // Validate step_name against format (empty is allowed)\n        if (part1 === undefined || !fmt1.test(part1)) {\n          throw new Scorm2004ValidationError(\n            \"cmi.interactions.n.correct_responses.n.pattern\",\n            scorm2004_errors.TYPE_MISMATCH as number,\n          );\n        }\n\n        // Validate step_answer against format2 (empty is allowed)\n        if (fmt2 && part2 !== undefined && !fmt2.test(part2)) {\n          throw new Scorm2004ValidationError(\n            \"cmi.interactions.n.correct_responses.n.pattern\",\n            scorm2004_errors.TYPE_MISMATCH as number,\n          );\n        }\n        break;\n      }\n\n      default:\n        if (responseDef.delimiter2) {\n          // matching and other two-part types\n          checkPair(node, responseDef.delimiter2);\n        } else {\n          // simple single-value types (true-false, choice, fill-in, etc.)\n          checkSingle(node);\n        }\n    }\n  }\n}\n\n/**\n * Class representing SCORM 2004's cmi.interactions.n.correct_responses.n object\n *\n * Per SCORM 2004 RTE Section 4.1.6.2 and Appendix D:\n * - Defines correct response patterns for interactions\n * - pattern: Format depends on interaction type (see Appendix D)\n * - Validates pattern against type-specific rules\n * - Supports escaped delimiters in patterns\n * - Multiple correct responses allowed for some types\n * - Type-specific validation ensures data integrity\n *\n * @extends BaseCMI\n */\nexport class CMIInteractionsCorrectResponsesObject extends BaseCMI {\n  private _pattern = \"\";\n  private readonly _interactionType?: string | undefined;\n\n  /**\n   * Constructor for cmi.interactions.n.correct_responses.n\n   * @param interactionType The type of interaction (e.g. \"numeric\", \"choice\", etc.)\n   */\n  constructor(interactionType?: string) {\n    super(\"cmi.interactions.n.correct_responses.n\");\n    this._interactionType = interactionType;\n  }\n\n  override reset() {\n    this._initialized = false;\n    this._pattern = \"\";\n  }\n\n  get pattern(): string {\n    return this._pattern;\n  }\n\n  set pattern(pattern: string) {\n    // Allow an empty whole pattern for types that permit zero items or empty text\n    if (\n      EMPTY_CORRECT_PATTERN_TYPES.has(this._interactionType ?? \"\") &&\n      pattern === \"\"\n    ) {\n      this._pattern = \"\";\n      return;\n    }\n    // 1) Basic SCORM‐pattern format check\n    if (\n      !check2004ValidFormat(this._cmi_element + \".pattern\", pattern, scorm2004_regex.CMIFeedback)\n    ) {\n      return;\n    }\n\n    // 2) If we know the interaction type, run the detailed validator\n    if (this._interactionType) {\n      const responseDef = CorrectResponses[this._interactionType];\n      if (responseDef) {\n        // Skip detailed validation for matching when pattern contains escaped comma or dot\n        if (this._interactionType === \"matching\" && /\\\\[.,]/.test(pattern)) {\n          // accept escaped comma or dot patterns without further validation\n        } else {\n          validatePattern(this._interactionType, pattern, responseDef);\n        }\n      }\n    }\n\n    // 3) Finally, set\n    this._pattern = pattern;\n  }\n\n  toJSON(): { pattern: string } {\n    this.jsonString = true;\n    const result = { pattern: this.pattern };\n    this.jsonString = false;\n    return result;\n  }\n}\n","/**\n * Class for SCORM 2004's cmi *.score object\n */\nimport { CMIScore } from \"../common/score\";\nimport { Scorm2004ValidationError } from \"../../exceptions/scorm2004_exceptions\";\nimport { check2004ValidFormat, check2004ValidRange } from \"./validation\";\nimport {\n  scorm2004_constants,\n  scorm2004_errors,\n  scorm2004_regex,\n} from \"../../constants\";\nimport { ScoreObject } from \"../../types\";\n\nexport class Scorm2004CMIScore extends CMIScore {\n  private _scaled = \"\";\n\n  /**\n   * Constructor for cmi *.score\n   */\n  constructor() {\n    super({\n      CMIElement: \"cmi.score\",\n      score_children: scorm2004_constants.score_children,\n      max: \"\",\n      invalidErrorCode: scorm2004_errors.READ_ONLY_ELEMENT as number,\n      invalidTypeCode: scorm2004_errors.TYPE_MISMATCH as number,\n      invalidRangeCode: scorm2004_errors.VALUE_OUT_OF_RANGE as number,\n      decimalRegex: scorm2004_regex.CMIDecimal,\n      errorClass: Scorm2004ValidationError,\n    });\n  }\n\n  /**\n   * Called when the API has been reset\n   */\n  override reset(): void {\n    this._initialized = false;\n    this._scaled = \"\";\n    this._raw = \"\";\n    this._min = \"\";\n    this._max = \"\";\n  }\n\n  /**\n   * Getter for _scaled\n   * @return {string}\n   */\n  get scaled(): string {\n    return this._scaled;\n  }\n\n  /**\n   * Setter for _scaled\n   * @param {string} scaled\n   */\n  set scaled(scaled: string) {\n    if (\n      check2004ValidFormat(this._cmi_element + \".scaled\", scaled, scorm2004_regex.CMIDecimal) &&\n      check2004ValidRange(this._cmi_element + \".scaled\", scaled, scorm2004_regex.scaled_range)\n    ) {\n      this._scaled = scaled;\n    }\n  }\n\n  override getScoreObject(): ScoreObject {\n    const scoreObject = super.getScoreObject();\n\n    if (!Number.isNaN(Number.parseFloat(this.scaled))) {\n      scoreObject.scaled = Number.parseFloat(this.scaled);\n    }\n\n    return scoreObject;\n  }\n\n  /**\n   * toJSON for cmi *.score\n   *\n   * @return {\n   *    {\n   *      scaled: string,\n   *      raw: string,\n   *      min: string,\n   *      max: string\n   *    }\n   *  }\n   */\n  override toJSON(): {\n    scaled: string;\n    raw: string;\n    min: string;\n    max: string;\n  } {\n    this.jsonString = true;\n    const result = {\n      scaled: this.scaled,\n      raw: this.raw,\n      min: this.min,\n      max: this.max,\n    };\n    this.jsonString = false;\n    return result;\n  }\n}\n","import { CMIArray } from \"../common/array\";\nimport { BaseCMI } from \"../common/base_cmi\";\nimport { Scorm2004ValidationError } from \"../../exceptions/scorm2004_exceptions\";\nimport { check2004ValidFormat } from \"./validation\";\nimport {\n  scorm2004_constants,\n  scorm2004_errors,\n  scorm2004_regex,\n} from \"../../constants\";\n\n/**\n * Class representing SCORM 2004's cmi.comments_from_lms object\n * @spec RTE 4.2.3 - cmi.comments_from_lms\n * @extends CMIArray\n */\nexport class CMICommentsFromLMS extends CMIArray {\n  /**\n   * Constructor for cmi.comments_from_lms Array\n   */\n  constructor() {\n    super({\n      CMIElement: \"cmi.comments_from_lms\",\n      children: scorm2004_constants.comments_children,\n      errorCode: scorm2004_errors.READ_ONLY_ELEMENT as number,\n      errorClass: Scorm2004ValidationError,\n    });\n  }\n}\n\n/**\n * Class representing SCORM 2004's cmi.comments_from_learner object\n * @spec RTE 4.2.2 - cmi.comments_from_learner\n */\n\nexport class CMICommentsFromLearner extends CMIArray {\n  /**\n   * Constructor for cmi.comments_from_learner Array\n   */\n  constructor() {\n    super({\n      CMIElement: \"cmi.comments_from_learner\",\n      children: scorm2004_constants.comments_children,\n      errorCode: scorm2004_errors.READ_ONLY_ELEMENT as number,\n      errorClass: Scorm2004ValidationError,\n    });\n  }\n}\n\n/**\n * Class representing SCORM 2004's cmi.comments_from_learner.n and cmi.comments_from_lms.n object\n */\n\nexport class CMICommentsObject extends BaseCMI {\n  private _comment = \"\";\n  private _location = \"\";\n  private _timestamp = \"\";\n  private readonly _readOnlyAfterInit: boolean;\n\n  /**\n   * Constructor for cmi.comments_from_learner.n and cmi.comments_from_lms.n\n   * @param {boolean} readOnlyAfterInit\n   */\n  constructor(readOnlyAfterInit: boolean = false) {\n    super(\"cmi.comments_from_learner.n\");\n    this._comment = \"\";\n    this._location = \"\";\n    this._timestamp = \"\";\n    this._readOnlyAfterInit = readOnlyAfterInit;\n  }\n\n  /**\n   * Called when the API has been reset\n   */\n  reset(): void {\n    this._initialized = false;\n  }\n\n  /**\n   * Getter for _comment\n   * @return {string}\n   */\n  get comment(): string {\n    return this._comment;\n  }\n\n  /**\n   * Setter for _comment\n   * @param {string} comment\n   */\n  set comment(comment: string) {\n    if (this.initialized && this._readOnlyAfterInit) {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".comment\",\n        scorm2004_errors.READ_ONLY_ELEMENT as number,\n      );\n    } else {\n      if (\n        check2004ValidFormat(\n          this._cmi_element + \".comment\",\n          comment,\n          scorm2004_regex.CMILangString4000,\n          true,\n        )\n      ) {\n        this._comment = comment;\n      }\n    }\n  }\n\n  /**\n   * Getter for _location\n   * @return {string}\n   */\n  get location(): string {\n    return this._location;\n  }\n\n  /**\n   * Setter for _location\n   * @param {string} location\n   */\n  set location(location: string) {\n    if (this.initialized && this._readOnlyAfterInit) {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".location\",\n        scorm2004_errors.READ_ONLY_ELEMENT as number,\n      );\n    } else {\n      if (\n        check2004ValidFormat(\n          this._cmi_element + \".location\",\n          location,\n          scorm2004_regex.CMIString250,\n          true,\n        )\n      ) {\n        this._location = location;\n      }\n    }\n  }\n\n  /**\n   * Getter for _timestamp\n   * @return {string}\n   */\n  get timestamp(): string {\n    return this._timestamp;\n  }\n\n  /**\n   * Setter for _timestamp\n   * @param {string} timestamp\n   */\n  set timestamp(timestamp: string) {\n    if (this.initialized && this._readOnlyAfterInit) {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".timestamp\",\n        scorm2004_errors.READ_ONLY_ELEMENT as number,\n      );\n    } else {\n      if (\n        check2004ValidFormat(this._cmi_element + \".timestamp\", timestamp, scorm2004_regex.CMITime)\n      ) {\n        this._timestamp = timestamp;\n      }\n    }\n  }\n\n  /**\n   * toJSON for cmi.comments_from_learner.n object\n   * @return {\n   *    {\n   *      comment: string,\n   *      location: string,\n   *      timestamp: string\n   *    }\n   *  }\n   */\n  toJSON(): {\n    comment: string;\n    location: string;\n    timestamp: string;\n  } {\n    this.jsonString = true;\n    const result = {\n      comment: this.comment,\n      location: this.location,\n      timestamp: this.timestamp,\n    };\n    this.jsonString = false;\n    return result;\n  }\n}\n","import { CMIArray } from \"../common/array\";\nimport { BaseCMI } from \"../common/base_cmi\";\nimport { Scorm2004ValidationError } from \"../../exceptions/scorm2004_exceptions\";\nimport { Scorm2004CMIScore } from \"./score\";\nimport { check2004ValidFormat, check2004ValidRange } from \"./validation\";\nimport {\n  scorm2004_constants,\n  scorm2004_errors,\n  scorm2004_regex,\n} from \"../../constants\";\n\n/**\n * Class representing SCORM 2004's `cmi.objectives` object\n *\n * Per SCORM 2004 RTE Section 4.1.5:\n * - Enhanced objectives with separate success and completion tracking\n * - Supports global objectives for cross-SCO state sharing\n * - progress_measure: Decimal (0-1) indicating objective completion\n * - description: LangString250 with optional language tag\n * - Objectives can be mapped to sequencing objectives via manifest\n * - Global objectives persist across SCO sessions\n *\n * @spec RTE 4.2.6 - cmi.objectives\n * @extends CMIArray\n */\nexport class CMIObjectives extends CMIArray {\n  /**\n   * Constructor for `cmi.objectives` Array\n   */\n  constructor() {\n    super({\n      CMIElement: \"cmi.objectives\",\n      children: scorm2004_constants.objectives_children,\n      errorCode: scorm2004_errors.READ_ONLY_ELEMENT as number,\n      errorClass: Scorm2004ValidationError,\n    });\n  }\n\n  /**\n   * Find an objective by its ID\n   */\n  public findObjectiveById(id: string): CMIObjectivesObject | undefined {\n    return (this.childArray as CMIObjectivesObject[]).find(\n      (objective) => objective.id === id,\n    );\n  }\n\n  /**\n   * Find objective by its index\n   */\n  public findObjectiveByIndex(index: number): CMIObjectivesObject | undefined {\n    return (this.childArray as CMIObjectivesObject[])[index];\n  }\n\n  /**\n   * Set an objective at the given index\n   */\n  public setObjectiveByIndex(index: number, objective: CMIObjectivesObject) {\n    this.childArray[index] = objective;\n  }\n}\n\n/**\n * Class for SCORM 2004's cmi.objectives.n object\n *\n * Per SCORM 2004 RTE Section 4.1.5:\n * - id: Long identifier (up to 4000 chars, supports URN format)\n * - success_status: Separate from completion (passed, failed, unknown)\n * - completion_status: Completion state (completed, incomplete, not attempted, unknown)\n * - progress_measure: Decimal (0-1) for objective completion percentage\n * - description: LangString250 with optional language tag\n * - score: Scaled score (-1 to 1) and raw/min/max values\n * - Dependency: id must be set before other elements\n * - Global objectives: Persist across SCOs when mapped via manifest\n *\n * @spec RTE 4.2.6.1 - cmi.objectives.n.id\n * @spec RTE 4.2.6.2 - cmi.objectives.n.score\n * @spec RTE 4.2.6.3 - cmi.objectives.n.success_status\n * @spec RTE 4.2.6.4 - cmi.objectives.n.completion_status\n * @spec RTE 4.2.6.5 - cmi.objectives.n.progress_measure\n * @spec RTE 4.2.6.6 - cmi.objectives.n.description\n * @extends BaseCMI\n */\nexport class CMIObjectivesObject extends BaseCMI {\n  private _id = \"\";\n  private _idIsSet = false;\n  private _success_status = \"unknown\";\n  private _completion_status = \"unknown\";\n  private _progress_measure = \"\";\n  private _description = \"\";\n\n  /**\n   * Constructor for cmi.objectives.n\n   */\n  constructor() {\n    super(\"cmi.objectives.n\");\n    this.score = new Scorm2004CMIScore();\n  }\n\n  override reset() {\n    this._initialized = false;\n    this._id = \"\";\n    this._idIsSet = false;\n    this._success_status = \"unknown\";\n    this._completion_status = \"unknown\";\n    this._progress_measure = \"\";\n    this._description = \"\";\n    this.score?.reset();\n  }\n\n  public score: Scorm2004CMIScore;\n\n  /**\n   * Called when the API has been initialized after the CMI has been created\n   */\n  override initialize() {\n    super.initialize();\n    this.score?.initialize();\n  }\n\n  /**\n   * Getter for _id\n   * @return {string}\n   */\n  get id(): string {\n    return this._id;\n  }\n\n  /**\n   * Setter for _id\n   * Per SCORM 2004 RTE: identifier SHALL NOT be empty or contain only whitespace\n   * Per SCORM 2004 RTE Section 4.1.5: Once set, an objective ID is immutable (error 351)\n   * @param {string} id\n   */\n  set id(id: string) {\n    // Per spec: identifier cannot be empty or whitespace-only\n    if (id === \"\" || id.trim() === \"\") {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".id\",\n        scorm2004_errors.TYPE_MISMATCH as number,\n      );\n    }\n    // Per SCORM 2004 RTE: Once an objective ID is set, it cannot be changed\n    if (this._idIsSet && this._id !== id) {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".id\",\n        scorm2004_errors.GENERAL_SET_FAILURE as number,\n      );\n    }\n    if (check2004ValidFormat(this._cmi_element + \".id\", id, scorm2004_regex.CMILongIdentifier)) {\n      this._id = id;\n      this._idIsSet = true;\n    }\n  }\n\n  /**\n   * Getter for _success_status\n   * @return {string}\n   */\n  get success_status(): string {\n    return this._success_status;\n  }\n\n  /**\n   * Setter for _success_status\n   * @param {string} success_status\n   */\n  set success_status(success_status: string) {\n    if (this.initialized && this._id === \"\") {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".success_status\",\n        scorm2004_errors.DEPENDENCY_NOT_ESTABLISHED as number,\n      );\n    } else {\n      if (\n        check2004ValidFormat(\n          this._cmi_element + \".success_status\",\n          success_status,\n          scorm2004_regex.CMISStatus,\n        )\n      ) {\n        this._success_status = success_status;\n      }\n    }\n  }\n\n  /**\n   * Getter for _completion_status\n   * @return {string}\n   */\n  get completion_status(): string {\n    return this._completion_status;\n  }\n\n  /**\n   * Setter for _completion_status\n   * @param {string} completion_status\n   */\n  set completion_status(completion_status: string) {\n    if (this.initialized && this._id === \"\") {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".completion_status\",\n        scorm2004_errors.DEPENDENCY_NOT_ESTABLISHED as number,\n      );\n    } else {\n      if (\n        check2004ValidFormat(\n          this._cmi_element + \".completion_status\",\n          completion_status,\n          scorm2004_regex.CMICStatus,\n        )\n      ) {\n        this._completion_status = completion_status;\n      }\n    }\n  }\n\n  /**\n   * Getter for _progress_measure\n   * @return {string}\n   */\n  get progress_measure(): string {\n    return this._progress_measure;\n  }\n\n  /**\n   * Setter for _progress_measure\n   * @param {string} progress_measure\n   */\n  set progress_measure(progress_measure: string) {\n    if (this.initialized && this._id === \"\") {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".progress_measure\",\n        scorm2004_errors.DEPENDENCY_NOT_ESTABLISHED as number,\n      );\n    } else {\n      if (\n        check2004ValidFormat(\n          this._cmi_element + \".progress_measure\",\n          progress_measure,\n          scorm2004_regex.CMIDecimal,\n        ) &&\n        check2004ValidRange(\n          this._cmi_element + \".progress_measure\",\n          progress_measure,\n          scorm2004_regex.progress_range,\n        )\n      ) {\n        this._progress_measure = progress_measure;\n      }\n    }\n  }\n\n  /**\n   * Getter for _description\n   * @return {string}\n   */\n  get description(): string {\n    return this._description;\n  }\n\n  /**\n   * Setter for _description\n   * @param {string} description\n   */\n  set description(description: string) {\n    if (this.initialized && this._id === \"\") {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".description\",\n        scorm2004_errors.DEPENDENCY_NOT_ESTABLISHED as number,\n      );\n    } else {\n      // Note: SCORM 2004 specifies an SPM of 250 chars for description (localized_string_type).\n      // We intentionally do NOT enforce this limit to maximize LMS compatibility (#1642).\n      // The {lang=...} prefix format is still validated.\n      if (\n        check2004ValidFormat(\n          this._cmi_element + \".description\",\n          description,\n          scorm2004_regex.CMILangString,\n          true,\n        )\n      ) {\n        this._description = description;\n      }\n    }\n  }\n\n  /**\n   * toJSON for cmi.objectives.n\n   *\n   * @return {\n   *    {\n   *      id: string,\n   *      success_status: string,\n   *      completion_status: string,\n   *      progress_measure: string,\n   *      description: string,\n   *      score: Scorm2004CMIScore\n   *    }\n   *  }\n   */\n  toJSON(): {\n    id: string;\n    success_status: string;\n    completion_status: string;\n    progress_measure: string;\n    description: string;\n    score: Scorm2004CMIScore;\n  } {\n    this.jsonString = true;\n    const result = {\n      id: this.id,\n      success_status: this.success_status,\n      completion_status: this.completion_status,\n      progress_measure: this.progress_measure,\n      description: this.description,\n      score: this.score,\n    };\n    this.jsonString = false;\n    return result;\n  }\n\n  /**\n   * Populate this objective from a plain object\n   * @param {any} data\n   */\n  fromJSON(data: any): void {\n    if (!data || typeof data !== \"object\") return;\n    if (typeof data.id === \"string\") this.id = data.id;\n    if (typeof data.success_status === \"string\") this.success_status = data.success_status;\n    if (typeof data.completion_status === \"string\") this.completion_status = data.completion_status;\n    if (typeof data.progress_measure !== \"undefined\") this.progress_measure = String(data.progress_measure);\n    if (typeof data.description === \"string\") this.description = data.description;\n    if (data.score && typeof data.score === \"object\") {\n      if (typeof data.score.scaled !== \"undefined\") this.score.scaled = String(data.score.scaled);\n      if (typeof data.score.raw !== \"undefined\") this.score.raw = String(data.score.raw);\n      if (typeof data.score.min !== \"undefined\") this.score.min = String(data.score.min);\n      if (typeof data.score.max !== \"undefined\") this.score.max = String(data.score.max);\n    }\n  }\n}\n","/**\n * Class representing metadata properties for SCORM 2004's cmi object\n */\nimport { BaseCMI } from \"../common/base_cmi\";\nimport { Scorm2004ValidationError } from \"../../exceptions/scorm2004_exceptions\";\nimport { scorm2004_constants, scorm2004_errors } from \"../../constants\";\n\n/**\n * Class representing metadata properties for SCORM 2004's cmi object\n */\nexport class CMIMetadata extends BaseCMI {\n  private __version = \"1.0\";\n  private __children = scorm2004_constants.cmi_children;\n\n  /**\n   * Constructor for CMIMetadata\n   */\n  constructor() {\n    super(\"cmi\");\n  }\n\n  /**\n   * Getter for __version\n   * @return {string}\n   */\n  get _version(): string {\n    return this.__version;\n  }\n\n  /**\n   * Setter for __version. Just throws an error.\n   * @param {string} _version\n   */\n  set _version(_version: string) {\n    throw new Scorm2004ValidationError(\n      this._cmi_element + \"._version\",\n      scorm2004_errors.READ_ONLY_ELEMENT as number,\n    );\n  }\n\n  /**\n   * Getter for __children\n   * @return {string}\n   */\n  get _children(): string {\n    return this.__children;\n  }\n\n  /**\n   * Setter for __children. Just throws an error.\n   * @param {number} _children\n   */\n  set _children(_children: number) {\n    throw new Scorm2004ValidationError(\n      this._cmi_element + \"._children\",\n      scorm2004_errors.READ_ONLY_ELEMENT as number,\n    );\n  }\n\n  /**\n   * Reset the metadata properties\n   */\n  reset(): void {\n    this._initialized = false;\n    // No need to reset __version and __children as they are constants\n  }\n}\n","/**\n * Class representing learner properties for SCORM 2004's cmi object\n */\nimport { BaseCMI } from \"../common/base_cmi\";\nimport { Scorm2004ValidationError } from \"../../exceptions/scorm2004_exceptions\";\nimport { scorm2004_errors } from \"../../constants\";\n\n/**\n * Class representing learner properties for SCORM 2004's cmi object\n */\nexport class CMILearner extends BaseCMI {\n  private _learner_id = \"\";\n  private _learner_name = \"\";\n\n  /**\n   * Constructor for CMILearner\n   */\n  constructor() {\n    super(\"cmi\");\n  }\n\n  /**\n   * Getter for _learner_id\n   * @return {string}\n   */\n  get learner_id(): string {\n    return this._learner_id;\n  }\n\n  /**\n   * Setter for _learner_id. Can only be called before initialization.\n   * @param {string} learner_id\n   */\n  set learner_id(learner_id: string) {\n    if (this.initialized) {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".learner_id\",\n        scorm2004_errors.READ_ONLY_ELEMENT as number,\n      );\n    } else {\n      // Note: SCORM 2004 3rd Edition specifies SPM of 4000 chars (CMILongIdentifier).\n      // We intentionally do NOT enforce this limit to maximize LMS compatibility.\n      this._learner_id = learner_id;\n    }\n  }\n\n  /**\n   * Getter for _learner_name\n   * @return {string}\n   */\n  get learner_name(): string {\n    return this._learner_name;\n  }\n\n  /**\n   * Setter for _learner_name. Can only be called before initialization.\n   * @param {string} learner_name\n   */\n  set learner_name(learner_name: string) {\n    if (this.initialized) {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".learner_name\",\n        scorm2004_errors.READ_ONLY_ELEMENT as number,\n      );\n    } else {\n      // Note: SCORM 2004 3rd Edition specifies SPM of 250 chars (CMIString250).\n      // We intentionally do NOT enforce this limit to maximize LMS compatibility.\n      this._learner_name = learner_name;\n    }\n  }\n\n  /**\n   * Reset the learner properties\n   */\n  reset(): void {\n    this._initialized = false;\n    // Don't reset learner_id and learner_name as they are read-only after initialization\n  }\n}\n","/**\n * Class representing status properties for SCORM 2004's cmi object\n */\nimport { BaseCMI } from \"../common/base_cmi\";\nimport { check2004ValidFormat, check2004ValidRange } from \"./validation\";\nimport { scorm2004_regex } from \"../../constants\";\n\n/**\n * Class representing status properties for SCORM 2004's cmi object\n */\nexport class CMIStatus extends BaseCMI {\n  private _completion_status = \"unknown\";\n  private _success_status = \"unknown\";\n  private _progress_measure = \"\";\n\n  /**\n   * Constructor for CMIStatus\n   */\n  constructor() {\n    super(\"cmi\");\n  }\n\n  /**\n   * Getter for _completion_status\n   * @return {string}\n   */\n  get completion_status(): string {\n    return this._completion_status;\n  }\n\n  /**\n   * Setter for _completion_status\n   * @param {string} completion_status\n   */\n  set completion_status(completion_status: string) {\n    if (\n      check2004ValidFormat(\n        this._cmi_element + \".completion_status\",\n        completion_status,\n        scorm2004_regex.CMICStatus,\n      )\n    ) {\n      this._completion_status = completion_status;\n    }\n  }\n\n  /**\n   * Getter for _success_status\n   * @return {string}\n   */\n  get success_status(): string {\n    return this._success_status;\n  }\n\n  /**\n   * Setter for _success_status\n   * @param {string} success_status\n   */\n  set success_status(success_status: string) {\n    if (\n      check2004ValidFormat(\n        this._cmi_element + \".success_status\",\n        success_status,\n        scorm2004_regex.CMISStatus,\n      )\n    ) {\n      this._success_status = success_status;\n    }\n  }\n\n  /**\n   * Getter for _progress_measure\n   * @return {string}\n   */\n  get progress_measure(): string {\n    return this._progress_measure;\n  }\n\n  /**\n   * Setter for _progress_measure\n   * @param {string} progress_measure\n   */\n  set progress_measure(progress_measure: string) {\n    if (\n      check2004ValidFormat(\n        this._cmi_element + \".progress_measure\",\n        progress_measure,\n        scorm2004_regex.CMIDecimal,\n      ) &&\n      check2004ValidRange(\n        this._cmi_element + \".progress_measure\",\n        progress_measure,\n        scorm2004_regex.progress_range,\n      )\n    ) {\n      this._progress_measure = progress_measure;\n    }\n  }\n\n  /**\n   * Reset the status properties\n   */\n  reset(): void {\n    this._initialized = false;\n    this._completion_status = \"unknown\";\n    this._success_status = \"unknown\";\n    this._progress_measure = \"\";\n  }\n}\n","/**\n * Class representing session properties for SCORM 2004's cmi object\n */\nimport { BaseCMI } from \"../common/base_cmi\";\nimport { Scorm2004ValidationError } from \"../../exceptions/scorm2004_exceptions\";\nimport { check2004ValidFormat } from \"./validation\";\nimport { scorm2004_errors, scorm2004_regex } from \"../../constants\";\nimport { addTwoDurations, getSecondsAsISODuration } from \"../../utilities\";\n\n/**\n * Class representing session properties for SCORM 2004's cmi object\n */\nexport class CMISession extends BaseCMI {\n  private _entry = \"\";\n  private _exit = \"\";\n  private _session_time = \"PT0H0M0S\";\n  private _total_time = \"PT0S\";\n\n  /**\n   * Constructor for CMISession\n   */\n  constructor() {\n    super(\"cmi\");\n  }\n\n  /**\n   * Getter for _entry\n   * @return {string}\n   */\n  get entry(): string {\n    return this._entry;\n  }\n\n  /**\n   * Setter for _entry. Can only be called before initialization.\n   * @param {string} entry\n   */\n  set entry(entry: string) {\n    if (this.initialized) {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".entry\",\n        scorm2004_errors.READ_ONLY_ELEMENT as number,\n      );\n    } else {\n      this._entry = entry;\n    }\n  }\n\n  /**\n   * Getter for _exit. Should only be called during JSON export.\n   * @return {string}\n   */\n  get exit(): string {\n    if (!this.jsonString) {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".exit\",\n        scorm2004_errors.WRITE_ONLY_ELEMENT as number,\n      );\n    }\n    return this._exit;\n  }\n\n  /**\n   * Internal getter for exit value - for use by the API for sequencing purposes.\n   * This bypasses the write-only restriction since the API needs to know the exit\n   * value to properly handle sequencing and navigation.\n   * @return {string}\n   */\n  getExitValueInternal(): string {\n    return this._exit;\n  }\n\n  /**\n   * Setter for _exit\n   * @param {string} exit\n   */\n  set exit(exit: string) {\n    if (exit === \"logout\") {\n      console.warn(\n        'SCORM 2004: cmi.exit value \"logout\" is deprecated per 4th Edition. ' +\n          'Consider using \"normal\" or \"suspend\" instead.',\n      );\n    }\n    if (check2004ValidFormat(this._cmi_element + \".exit\", exit, scorm2004_regex.CMIExit, true)) {\n      this._exit = exit;\n    }\n  }\n\n  /**\n   * Getter for _session_time. Should only be called during JSON export.\n   * @return {string}\n   */\n  get session_time(): string {\n    if (!this.jsonString) {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".session_time\",\n        scorm2004_errors.WRITE_ONLY_ELEMENT as number,\n      );\n    }\n    return this._session_time;\n  }\n\n  /**\n   * Setter for _session_time\n   * @param {string} session_time\n   */\n  set session_time(session_time: string) {\n    if (\n      check2004ValidFormat(\n        this._cmi_element + \".session_time\",\n        session_time,\n        scorm2004_regex.CMITimespan,\n      )\n    ) {\n      this._session_time = session_time;\n    }\n  }\n\n  /**\n   * Getter for _total_time\n   * @return {string}\n   */\n  get total_time(): string {\n    return this._total_time;\n  }\n\n  /**\n   * Setter for _total_time. Can only be called before initialization.\n   * @param {string} total_time\n   */\n  set total_time(total_time: string) {\n    if (this.initialized) {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".total_time\",\n        scorm2004_errors.READ_ONLY_ELEMENT as number,\n      );\n    } else {\n      this._total_time = total_time;\n    }\n  }\n\n  /**\n   * Adds the current session time to the existing total time.\n   *\n   * @return {string} ISO8601 Duration\n   */\n  getCurrentTotalTime(start_time: number | undefined): string {\n    let sessionTime = this._session_time;\n    if (typeof start_time !== \"undefined\") {\n      const seconds = new Date().getTime() - start_time;\n      sessionTime = getSecondsAsISODuration(seconds / 1000);\n    }\n\n    return addTwoDurations(this._total_time, sessionTime, scorm2004_regex.CMITimespan);\n  }\n\n  /**\n   * Add the completed learner session to the cumulative total.\n   *\n   * @spec SCORM 2004 4th Ed. RTE 4.2.24 / 4.2.28 - session_time is\n   *   accumulated into the LMS-maintained total_time after Terminate.\n   */\n  accumulateSessionTime(start_time: number | undefined): void {\n    this._total_time = this.getCurrentTotalTime(start_time);\n    this._session_time = \"PT0H0M0S\";\n  }\n\n  /**\n   * Reset the session properties\n   *\n   * When resetting for a new SCO delivery, entry is set to \"ab-initio\" per SCORM 2004 spec:\n   * - \"ab-initio\" indicates the learner is beginning a new attempt on the activity\n   * - \"resume\" indicates the learner is resuming a previously suspended attempt\n   *\n   * Since reset() is called for SCO transitions (new attempts), \"ab-initio\" is the correct value.\n   * The LMS can override this if the learner is resuming a suspended session.\n   */\n  reset(): void {\n    this._initialized = false;\n    this._entry = \"ab-initio\";\n    this._exit = \"\";\n    this._session_time = \"PT0H0M0S\";\n    // Don't reset total_time as it's read-only after initialization\n  }\n}\n","/**\n * Class representing content properties for SCORM 2004's cmi object\n */\nimport { BaseCMI } from \"../common/base_cmi\";\nimport { Scorm2004ValidationError } from \"../../exceptions/scorm2004_exceptions\";\nimport { check2004ValidFormat } from \"./validation\";\nimport { scorm2004_errors, scorm2004_regex } from \"../../constants\";\n\n/**\n * Class representing content properties for SCORM 2004's cmi object\n */\nexport class CMIContent extends BaseCMI {\n  private _location = \"\";\n  private _launch_data = \"\";\n  private _suspend_data = \"\";\n\n  /**\n   * Constructor for CMIContent\n   */\n  constructor() {\n    super(\"cmi\");\n  }\n\n  /**\n   * Getter for _location\n   * @return {string}\n   */\n  get location(): string {\n    return this._location;\n  }\n\n  /**\n   * Setter for _location\n   * @param {string} location\n   */\n  set location(location: string) {\n    if (\n      check2004ValidFormat(\n        this._cmi_element + \".location\",\n        location,\n        scorm2004_regex.CMIString1000,\n        true,\n      )\n    ) {\n      this._location = location;\n    }\n  }\n\n  /**\n   * Getter for _launch_data\n   * @return {string}\n   */\n  get launch_data(): string {\n    return this._launch_data;\n  }\n\n  /**\n   * Setter for _launch_data. Can only be called before initialization.\n   * @param {string} launch_data\n   */\n  set launch_data(launch_data: string) {\n    if (this.initialized) {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".launch_data\",\n        scorm2004_errors.READ_ONLY_ELEMENT as number,\n      );\n    } else {\n      // Note: SCORM 2004 3rd Edition specifies SPM of 4000 chars for launch_data.\n      // We intentionally do NOT enforce this limit to maximize LMS compatibility.\n      // Some LMS implementations may provide larger launch_data values.\n      this._launch_data = launch_data;\n    }\n  }\n\n  /**\n   * Getter for _suspend_data\n   * @return {string}\n   */\n  get suspend_data(): string {\n    return this._suspend_data;\n  }\n\n  /**\n   * Setter for _suspend_data\n   * @param {string} suspend_data\n   */\n  set suspend_data(suspend_data: string) {\n    if (\n      check2004ValidFormat(\n        this._cmi_element + \".suspend_data\",\n        suspend_data,\n        scorm2004_regex.CMIString64000,\n        true,\n      )\n    ) {\n      this._suspend_data = suspend_data;\n    }\n  }\n\n  /**\n   * Reset the content properties\n   */\n  reset(): void {\n    this._initialized = false;\n    this._location = \"\";\n    // Don't reset launch_data as it's read-only after initialization\n    this._suspend_data = \"\";\n  }\n}\n","/**\n * Class representing settings properties for SCORM 2004's cmi object\n */\nimport { BaseCMI } from \"../common/base_cmi\";\nimport { Scorm2004ValidationError } from \"../../exceptions/scorm2004_exceptions\";\nimport { scorm2004_errors, scorm2004_regex } from \"../../constants\";\n\n/**\n * Class representing settings properties for SCORM 2004's cmi object\n */\nexport class CMISettings extends BaseCMI {\n  private _credit = \"credit\";\n  private _mode = \"normal\";\n  private _time_limit_action = \"continue,no message\";\n  private _max_time_allowed = \"\";\n\n  /**\n   * Constructor for CMISettings\n   */\n  constructor() {\n    super(\"cmi\");\n  }\n\n  /**\n   * Getter for _credit\n   * @return {string}\n   */\n  get credit(): string {\n    return this._credit;\n  }\n\n  /**\n   * Setter for _credit. Can only be called before initialization.\n   * @param {string} credit\n   */\n  set credit(credit: string) {\n    if (this.initialized) {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".credit\",\n        scorm2004_errors.READ_ONLY_ELEMENT as number,\n      );\n    }\n    if (!/^(credit|no-credit)$/.test(credit)) {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".credit\",\n        scorm2004_errors.TYPE_MISMATCH as number,\n      );\n    }\n    this._credit = credit;\n  }\n\n  /**\n   * Getter for _mode\n   * @return {string}\n   */\n  get mode(): string {\n    return this._mode;\n  }\n\n  /**\n   * Setter for _mode. Can only be called before initialization.\n   * @param {string} mode\n   */\n  set mode(mode: string) {\n    if (this.initialized) {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".mode\",\n        scorm2004_errors.READ_ONLY_ELEMENT as number,\n      );\n    }\n    if (!/^(browse|normal|review)$/.test(mode)) {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".mode\",\n        scorm2004_errors.TYPE_MISMATCH as number,\n      );\n    }\n    this._mode = mode;\n  }\n\n  /**\n   * Getter for _time_limit_action\n   * @return {string}\n   */\n  get time_limit_action(): string {\n    return this._time_limit_action;\n  }\n\n  /**\n   * Setter for _time_limit_action. Can only be called before initialization.\n   * @param {string} time_limit_action\n   */\n  set time_limit_action(time_limit_action: string) {\n    if (this.initialized) {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".time_limit_action\",\n        scorm2004_errors.READ_ONLY_ELEMENT as number,\n      );\n    }\n    if (!/^(exit,message|exit,no message|continue,message|continue,no message)$/.test(time_limit_action)) {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".time_limit_action\",\n        scorm2004_errors.TYPE_MISMATCH as number,\n      );\n    }\n    this._time_limit_action = time_limit_action;\n  }\n\n  /**\n   * Getter for _max_time_allowed\n   * @return {string}\n   */\n  get max_time_allowed(): string {\n    return this._max_time_allowed;\n  }\n\n  /**\n   * Setter for _max_time_allowed. Can only be called before initialization.\n   * @param {string} max_time_allowed\n   */\n  set max_time_allowed(max_time_allowed: string) {\n    if (this.initialized) {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".max_time_allowed\",\n        scorm2004_errors.READ_ONLY_ELEMENT as number,\n      );\n    }\n\n    // Allow empty string (undefined value)\n    if (max_time_allowed === \"\") {\n      this._max_time_allowed = max_time_allowed;\n      return;\n    }\n\n    // Validate format using CMITimespan regex (ISO 8601 duration)\n    const regex = new RegExp(scorm2004_regex.CMITimespan);\n    if (!regex.test(max_time_allowed)) {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".max_time_allowed\",\n        scorm2004_errors.TYPE_MISMATCH as number,\n      );\n    }\n\n    this._max_time_allowed = max_time_allowed;\n  }\n\n  /**\n   * Reset the settings properties\n   */\n  reset(): void {\n    this._initialized = false;\n    // Don't reset these properties as they are read-only after initialization\n  }\n}\n","/**\n * Class representing threshold properties for SCORM 2004's cmi object\n */\nimport { BaseCMI } from \"../common/base_cmi\";\nimport { Scorm2004ValidationError } from \"../../exceptions/scorm2004_exceptions\";\nimport { scorm2004_errors, scorm2004_regex } from \"../../constants\";\n\n/**\n * Class representing threshold properties for SCORM 2004's cmi object\n */\nexport class CMIThresholds extends BaseCMI {\n  private _scaled_passing_score = \"\";\n  private _completion_threshold = \"\";\n\n  /**\n   * Constructor for CMIThresholds\n   */\n  constructor() {\n    super(\"cmi\");\n  }\n\n  /**\n   * Getter for _scaled_passing_score\n   * @return {string}\n   */\n  get scaled_passing_score(): string {\n    return this._scaled_passing_score;\n  }\n\n  /**\n   * Setter for _scaled_passing_score. Can only be called before initialization.\n   * @param {string} scaled_passing_score\n   */\n  set scaled_passing_score(scaled_passing_score: string) {\n    if (this.initialized) {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".scaled_passing_score\",\n        scorm2004_errors.READ_ONLY_ELEMENT ?? 404,\n      );\n    }\n\n    // Allow empty string (undefined value)\n    if (scaled_passing_score === \"\") {\n      this._scaled_passing_score = scaled_passing_score;\n      return;\n    }\n\n    // Validate format using CMIDecimal regex\n    const regex = new RegExp(scorm2004_regex.CMIDecimal);\n    if (!regex.test(scaled_passing_score)) {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".scaled_passing_score\",\n        scorm2004_errors.TYPE_MISMATCH ?? 406,\n      );\n    }\n\n    // Validate range: -1 to 1\n    const num = parseFloat(scaled_passing_score);\n    if (num < -1 || num > 1) {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".scaled_passing_score\",\n        scorm2004_errors.VALUE_OUT_OF_RANGE ?? 407,\n      );\n    }\n\n    this._scaled_passing_score = scaled_passing_score;\n  }\n\n  /**\n   * Getter for _completion_threshold\n   * @return {string}\n   */\n  get completion_threshold(): string {\n    return this._completion_threshold;\n  }\n\n  /**\n   * Setter for _completion_threshold. Can only be called before initialization.\n   * @param {string} completion_threshold\n   */\n  set completion_threshold(completion_threshold: string) {\n    if (this.initialized) {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".completion_threshold\",\n        scorm2004_errors.READ_ONLY_ELEMENT ?? 404,\n      );\n    }\n\n    // Allow empty string (undefined value)\n    if (completion_threshold === \"\") {\n      this._completion_threshold = completion_threshold;\n      return;\n    }\n\n    // Validate format using CMIDecimal regex\n    const regex = new RegExp(scorm2004_regex.CMIDecimal);\n    if (!regex.test(completion_threshold)) {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".completion_threshold\",\n        scorm2004_errors.TYPE_MISMATCH ?? 406,\n      );\n    }\n\n    // Validate range: 0 to 1\n    const num = parseFloat(completion_threshold);\n    if (num < 0 || num > 1) {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".completion_threshold\",\n        scorm2004_errors.VALUE_OUT_OF_RANGE ?? 407,\n      );\n    }\n\n    this._completion_threshold = completion_threshold;\n  }\n\n  /**\n   * Reset the threshold properties\n   */\n  reset(): void {\n    this._initialized = false;\n    // Don't reset these properties as they are read-only after initialization\n  }\n}\n","import { BaseRootCMI } from \"../common/base_cmi\";\nimport { CMILearnerPreference } from \"./learner_preference\";\nimport { CMIInteractions } from \"./interactions\";\nimport { Scorm2004CMIScore } from \"./score\";\nimport { CMICommentsFromLearner, CMICommentsFromLMS } from \"./comments\";\nimport { CMIObjectives } from \"./objectives\";\nimport { CMIMetadata } from \"./metadata\";\nimport { CMILearner } from \"./learner\";\nimport { CMIStatus } from \"./status\";\nimport { CMISession } from \"./session\";\nimport { CMIContent } from \"./content\";\nimport { CMISettings } from \"./settings\";\nimport { CMIThresholds } from \"./thresholds\";\n\n/**\n * Class representing cmi object for SCORM 2004\n *\n * Per SCORM 2004 RTE Section 4.1:\n * - Enhanced data model with additional elements vs SCORM 1.2\n * - Separate completion_status and success_status tracking\n * - Progress measure (0-1 scale) for completion tracking\n * - Scaled scores (-1 to 1) with threshold support\n * - Language support via LangString types\n * - Comments from learner and LMS with timestamps\n * - Enhanced interactions with better type validation\n * - Global objectives support for cross-SCO tracking\n *\n * @extends BaseRootCMI\n */\nexport class CMI extends BaseRootCMI {\n  /**\n   * Constructor for the SCORM 2004 cmi object\n   * @param {boolean} initialized\n   */\n  constructor(initialized: boolean = false) {\n    super(\"cmi\");\n    this.metadata = new CMIMetadata();\n    this.learner = new CMILearner();\n    this.status = new CMIStatus();\n    this.session = new CMISession();\n    this.content = new CMIContent();\n    this.settings = new CMISettings();\n    this.thresholds = new CMIThresholds();\n    this.learner_preference = new CMILearnerPreference();\n    this.score = new Scorm2004CMIScore();\n    this.comments_from_learner = new CMICommentsFromLearner();\n    this.comments_from_lms = new CMICommentsFromLMS();\n    this.interactions = new CMIInteractions();\n    this.objectives = new CMIObjectives();\n    if (initialized) this.initialize();\n  }\n\n  // New component classes\n  private metadata: CMIMetadata;\n  private learner: CMILearner;\n  private status: CMIStatus;\n  private session: CMISession;\n  private content: CMIContent;\n  private settings: CMISettings;\n  private thresholds: CMIThresholds;\n\n  // Original complex objects\n  public learner_preference: CMILearnerPreference;\n  public score: Scorm2004CMIScore;\n  public comments_from_learner: CMICommentsFromLearner;\n  public comments_from_lms: CMICommentsFromLMS;\n  public interactions: CMIInteractions;\n  public objectives: CMIObjectives;\n\n  /**\n   * Called when the API has been initialized after the CMI has been created\n   */\n  override initialize() {\n    super.initialize();\n    // Initialize new component classes\n    this.metadata?.initialize();\n    this.learner?.initialize();\n    this.status?.initialize();\n    this.session?.initialize();\n    this.content?.initialize();\n    this.settings?.initialize();\n    this.thresholds?.initialize();\n\n    // Initialize original complex objects\n    this.learner_preference?.initialize();\n    this.score?.initialize();\n    this.comments_from_learner?.initialize();\n    this.comments_from_lms?.initialize();\n    this.interactions?.initialize();\n    this.objectives?.initialize();\n  }\n\n  /**\n   * Called when API is moving to another SCO\n   *\n   * Resets SCO-specific CMI data while preserving global objectives.\n   *\n   * The objectives.reset(false) call resets individual objective objects\n   * but maintains the array structure. Global objectives stored in\n   * Scorm2004API._globalObjectives are preserved separately and are not\n   * affected by this reset.\n   *\n   * This aligns with SCORM 2004 Sequencing and Navigation (SN) Book:\n   * - Content Delivery Environment Process (DB.2) requires reset between SCOs\n   * - Global objectives (via mapInfo) must persist across SCO transitions\n   * - SCO-specific data (location, entry, session, interactions) must be reset\n   */\n  reset() {\n    this._initialized = false;\n    this._start_time = undefined;\n\n    // Reset new component classes\n    this.metadata?.reset();\n    this.learner?.reset();\n    this.status?.reset();\n    this.session?.reset();\n    this.content?.reset();\n    this.settings?.reset();\n    this.thresholds?.reset();\n\n    // Reset original complex objects\n    // objectives.reset(true) - wipe the array completely so restoreGlobalObjectivesToCMI\n    // can repopulate it from _globalObjectives. The global objectives are persisted in\n    // Scorm2004API._globalObjectives and restored during lmsInitialize().\n    this.objectives?.reset(true);\n    this.interactions?.reset(true);\n    this.score?.reset();\n    this.comments_from_learner?.reset();\n    this.comments_from_lms?.reset();\n    this.learner_preference?.reset();\n  }\n\n  /**\n   * Getter for __version\n   * @return {string}\n   * @private\n   */\n  get _version(): string {\n    return this.metadata._version;\n  }\n\n  /**\n   * Setter for __version. Just throws an error.\n   * @param {string} _version\n   * @private\n   */\n  set _version(_version: string) {\n    this.metadata._version = _version;\n  }\n\n  /**\n   * Getter for __children\n   * @return {string}\n   * @private\n   */\n  get _children(): string {\n    return this.metadata._children;\n  }\n\n  /**\n   * Setter for __children. Just throws an error.\n   * @param {number} _children\n   * @private\n   */\n  set _children(_children: number) {\n    this.metadata._children = _children;\n  }\n\n  /**\n   * Getter for _completion_status\n   * @return {string}\n   * @spec RTE 4.2.8 - cmi.completion_status\n   */\n  get completion_status(): string {\n    return this.status.completion_status;\n  }\n\n  /**\n   * Setter for _completion_status\n   * @param {string} completion_status\n   */\n  set completion_status(completion_status: string) {\n    this.status.completion_status = completion_status;\n  }\n\n  /**\n   * Getter for _completion_threshold\n   * @return {string}\n   * @spec RTE 4.2.9 - cmi.completion_threshold\n   */\n  get completion_threshold(): string {\n    return this.thresholds.completion_threshold;\n  }\n\n  /**\n   * Setter for _completion_threshold. Can only be called before initialization.\n   * @param {string} completion_threshold\n   */\n  set completion_threshold(completion_threshold: string) {\n    this.thresholds.completion_threshold = completion_threshold;\n  }\n\n  /**\n   * Getter for _credit\n   * @return {string}\n   * @spec RTE 4.2.10 - cmi.credit\n   */\n  get credit(): string {\n    return this.settings.credit;\n  }\n\n  /**\n   * Setter for _credit. Can only be called before initialization.\n   * @param {string} credit\n   */\n  set credit(credit: string) {\n    this.settings.credit = credit;\n  }\n\n  /**\n   * Getter for _entry\n   * @return {string}\n   * @spec RTE 4.2.11 - cmi.entry\n   */\n  get entry(): string {\n    return this.session.entry;\n  }\n\n  /**\n   * Setter for _entry. Can only be called before initialization.\n   * @param {string} entry\n   */\n  set entry(entry: string) {\n    this.session.entry = entry;\n  }\n\n  /**\n   * Getter for _exit. Should only be called during JSON export.\n   * @return {string}\n   * @spec RTE 4.2.12 - cmi.exit\n   */\n  get exit(): string {\n    this.session.jsonString = this.jsonString;\n    return this.session.exit;\n  }\n\n  /**\n   * Setter for _exit\n   * @param {string} exit\n   */\n  set exit(exit: string) {\n    this.session.exit = exit;\n  }\n\n  /**\n   * Internal getter for exit value - for use by the API for sequencing purposes.\n   * This bypasses the write-only restriction since the API needs to know the exit\n   * value to properly handle sequencing and navigation.\n   * @return {string}\n   */\n  getExitValueInternal(): string {\n    return this.session.getExitValueInternal();\n  }\n\n  /**\n   * Getter for _launch_data\n   * @return {string}\n   * @spec RTE 4.2.13 - cmi.launch_data\n   */\n  get launch_data(): string {\n    return this.content.launch_data;\n  }\n\n  /**\n   * Setter for _launch_data. Can only be called before initialization.\n   * @param {string} launch_data\n   */\n  set launch_data(launch_data: string) {\n    this.content.launch_data = launch_data;\n  }\n\n  /**\n   * Getter for _learner_id\n   * @return {string}\n   * @spec RTE 4.2.14 - cmi.learner_id\n   */\n  get learner_id(): string {\n    return this.learner.learner_id;\n  }\n\n  /**\n   * Setter for _learner_id. Can only be called before initialization.\n   * @param {string} learner_id\n   */\n  set learner_id(learner_id: string) {\n    this.learner.learner_id = learner_id;\n  }\n\n  /**\n   * Getter for _learner_name\n   * @return {string}\n   * @spec RTE 4.2.15 - cmi.learner_name\n   */\n  get learner_name(): string {\n    return this.learner.learner_name;\n  }\n\n  /**\n   * Setter for _learner_name. Can only be called before initialization.\n   * @param {string} learner_name\n   */\n  set learner_name(learner_name: string) {\n    this.learner.learner_name = learner_name;\n  }\n\n  /**\n   * Getter for _location\n   * @return {string}\n   * @spec RTE 4.2.17 - cmi.location\n   */\n  get location(): string {\n    return this.content.location;\n  }\n\n  /**\n   * Setter for _location\n   * @param {string} location\n   */\n  set location(location: string) {\n    this.content.location = location;\n  }\n\n  /**\n   * Getter for _max_time_allowed\n   * @return {string}\n   * @spec RTE 4.2.18 - cmi.max_time_allowed\n   */\n  get max_time_allowed(): string {\n    return this.settings.max_time_allowed;\n  }\n\n  /**\n   * Setter for _max_time_allowed. Can only be called before initialization.\n   * @param {string} max_time_allowed\n   */\n  set max_time_allowed(max_time_allowed: string) {\n    this.settings.max_time_allowed = max_time_allowed;\n  }\n\n  /**\n   * Getter for _mode\n   * @return {string}\n   * @spec RTE 4.2.19 - cmi.mode\n   */\n  get mode(): string {\n    return this.settings.mode;\n  }\n\n  /**\n   * Setter for _mode. Can only be called before initialization.\n   * @param {string} mode\n   */\n  set mode(mode: string) {\n    this.settings.mode = mode;\n  }\n\n  /**\n   * Getter for _progress_measure\n   * @return {string}\n   * @spec RTE 4.2.21 - cmi.progress_measure\n   */\n  get progress_measure(): string {\n    return this.status.progress_measure;\n  }\n\n  /**\n   * Setter for _progress_measure\n   * @param {string} progress_measure\n   */\n  set progress_measure(progress_measure: string) {\n    this.status.progress_measure = progress_measure;\n  }\n\n  /**\n   * Getter for _scaled_passing_score\n   * @return {string}\n   * @spec RTE 4.2.22 - cmi.scaled_passing_score\n   */\n  get scaled_passing_score(): string {\n    return this.thresholds.scaled_passing_score;\n  }\n\n  /**\n   * Setter for _scaled_passing_score. Can only be called before initialization.\n   * @param {string} scaled_passing_score\n   */\n  set scaled_passing_score(scaled_passing_score: string) {\n    this.thresholds.scaled_passing_score = scaled_passing_score;\n  }\n\n  /**\n   * Getter for _session_time. Should only be called during JSON export.\n   * @return {string}\n   * @spec RTE 4.2.24 - cmi.session_time\n   */\n  get session_time(): string {\n    this.session.jsonString = this.jsonString;\n    return this.session.session_time;\n  }\n\n  /**\n   * Setter for _session_time\n   * @param {string} session_time\n   */\n  set session_time(session_time: string) {\n    this.session.session_time = session_time;\n  }\n\n  /**\n   * Getter for _success_status\n   * @return {string}\n   * @spec RTE 4.2.25 - cmi.success_status\n   */\n  get success_status(): string {\n    return this.status.success_status;\n  }\n\n  /**\n   * Setter for _success_status\n   * @param {string} success_status\n   */\n  set success_status(success_status: string) {\n    this.status.success_status = success_status;\n  }\n\n  /**\n   * Getter for _suspend_data\n   * @return {string}\n   * @spec RTE 4.2.26 - cmi.suspend_data\n   */\n  get suspend_data(): string {\n    return this.content.suspend_data;\n  }\n\n  /**\n   * Setter for _suspend_data\n   * @param {string} suspend_data\n   */\n  set suspend_data(suspend_data: string) {\n    this.content.suspend_data = suspend_data;\n  }\n\n  /**\n   * Getter for _time_limit_action\n   * @return {string}\n   * @spec RTE 4.2.27 - cmi.time_limit_action\n   */\n  get time_limit_action(): string {\n    return this.settings.time_limit_action;\n  }\n\n  /**\n   * Setter for _time_limit_action. Can only be called before initialization.\n   * @param {string} time_limit_action\n   */\n  set time_limit_action(time_limit_action: string) {\n    this.settings.time_limit_action = time_limit_action;\n  }\n\n  /**\n   * Getter for _total_time\n   * @return {string}\n   * @spec RTE 4.2.28 - cmi.total_time\n   */\n  get total_time(): string {\n    return this.session.total_time;\n  }\n\n  /**\n   * Setter for _total_time. Can only be called before initialization.\n   * @param {string} total_time\n   */\n  set total_time(total_time: string) {\n    this.session.total_time = total_time;\n  }\n\n  /**\n   * Adds the current session time to the existing total time.\n   *\n   * @return {string} ISO8601 Duration\n   */\n  getCurrentTotalTime(): string {\n    return this.session.getCurrentTotalTime(this.start_time);\n  }\n\n  /**\n   * Preserve the completed session in total_time before a sequenced SCO reset.\n   *\n   * @spec SCORM 2004 4th Ed. RTE 4.2.24 / 4.2.28\n   */\n  accumulateSessionTime(): void {\n    this.session.accumulateSessionTime(this.start_time);\n    if (this._start_time !== undefined) {\n      this._start_time = new Date().getTime();\n    }\n  }\n\n  /**\n   * toJSON for cmi\n   *\n   * @return {\n   *    {\n   *      comments_from_learner: CMICommentsFromLearner,\n   *      comments_from_lms: CMICommentsFromLMS,\n   *      completion_status: string,\n   *      completion_threshold: string,\n   *      credit: string,\n   *      entry: string,\n   *      exit: string,\n   *      interactions: CMIInteractions,\n   *      launch_data: string,\n   *      learner_id: string,\n   *      learner_name: string,\n   *      learner_preference: CMILearnerPreference,\n   *      location: string,\n   *      max_time_allowed: string,\n   *      mode: string,\n   *      objectives: CMIObjectives,\n   *      progress_measure: string,\n   *      scaled_passing_score: string,\n   *      score: Scorm2004CMIScore,\n   *      session_time: string,\n   *      success_status: string,\n   *      suspend_data: string,\n   *      time_limit_action: string,\n   *      total_time: string\n   *    }\n   *  }\n   */\n  toJSON(): {\n    comments_from_learner: CMICommentsFromLearner;\n    comments_from_lms: CMICommentsFromLMS;\n    completion_status: string;\n    completion_threshold: string;\n    credit: string;\n    entry: string;\n    exit: string;\n    interactions: CMIInteractions;\n    launch_data: string;\n    learner_id: string;\n    learner_name: string;\n    learner_preference: CMILearnerPreference;\n    location: string;\n    max_time_allowed: string;\n    mode: string;\n    objectives: CMIObjectives;\n    progress_measure: string;\n    scaled_passing_score: string;\n    score: Scorm2004CMIScore;\n    session_time: string;\n    success_status: string;\n    suspend_data: string;\n    time_limit_action: string;\n    total_time: string;\n  } {\n    this.jsonString = true;\n\n    // Set jsonString flag on component classes that need it\n    this.session.jsonString = true;\n\n    const result = {\n      comments_from_learner: this.comments_from_learner,\n      comments_from_lms: this.comments_from_lms,\n      completion_status: this.completion_status,\n      completion_threshold: this.completion_threshold,\n      credit: this.credit,\n      entry: this.entry,\n      exit: this.exit,\n      interactions: this.interactions,\n      launch_data: this.launch_data,\n      learner_id: this.learner_id,\n      learner_name: this.learner_name,\n      learner_preference: this.learner_preference,\n      location: this.location,\n      max_time_allowed: this.max_time_allowed,\n      mode: this.mode,\n      objectives: this.objectives,\n      progress_measure: this.progress_measure,\n      scaled_passing_score: this.scaled_passing_score,\n      score: this.score,\n      session_time: this.session_time,\n      success_status: this.success_status,\n      suspend_data: this.suspend_data,\n      time_limit_action: this.time_limit_action,\n      total_time: this.total_time,\n    };\n\n    // Clean up jsonString flags\n    this.jsonString = false;\n    this.session.jsonString = false;\n\n    return result;\n  }\n}\n","import { BaseCMI } from \"../common/base_cmi\";\nimport { CMIArray } from \"../common/array\";\nimport { Scorm2004ValidationError } from \"../../exceptions/scorm2004_exceptions\";\nimport { check2004ValidFormat } from \"./validation\";\nimport { Sequencing } from \"./sequencing/sequencing\";\nimport type { SharedDataMapInfo } from \"./sequencing/activity\";\nimport {\n  NAVBoolean,\n  scorm2004_constants,\n  scorm2004_errors,\n  scorm2004_regex,\n} from \"../../constants\";\n\n/**\n * Class representing SCORM 2004's adl object\n */\nexport class ADL extends BaseCMI {\n  /**\n   * Constructor for adl\n   */\n  constructor() {\n    super(\"adl\");\n    this.nav = new ADLNav();\n    this.data = new ADLData();\n  }\n\n  public nav: ADLNav;\n  public data = new ADLData();\n  private _sequencing: Sequencing | null = null;\n  private _sharedDataStores: Record<string, string> = Object.create(null);\n\n  /**\n   * Called when the API has been initialized after the CMI has been created\n   */\n  override initialize() {\n    super.initialize();\n    this.nav?.initialize();\n    this.data?.initialize();\n  }\n\n  /**\n   * Called when the API needs to be reset\n   */\n  reset() {\n    this._initialized = false;\n    this.nav?.reset();\n    this.data?.reset();\n  }\n\n  /**\n   * Configure the adl.data view for the activity being delivered.\n   *\n   * ADL data stores are keyed by the manifest targetID, while the RTE exposes\n   * only the mappings for the currently delivered activity as adl.data.n.\n   * Rebuilding that view is therefore safe: values live in this ADL-owned\n   * backing map and survive SCO reset/navigation.\n   */\n  configureSharedDataMaps(maps: SharedDataMapInfo[] = []): void {\n    this.captureVisibleSharedData();\n    this.data.configure(maps, this._sharedDataStores);\n  }\n\n  captureSharedDataSnapshot(): Record<string, string> {\n    this.captureVisibleSharedData();\n    return { ...this._sharedDataStores };\n  }\n\n  /** Capture only initialized stores this activity is allowed to write. */\n  captureWritableSharedDataSnapshot(): Record<string, string> {\n    this.captureVisibleSharedData();\n    const writableStores: Record<string, string> = {};\n    for (const child of this.data.childArray) {\n      const dataObject = child as ADLDataObject;\n      if (dataObject.id && dataObject.storeIsSet && dataObject.writeSharedData) {\n        writableStores[dataObject.id] = dataObject.storeValue;\n      }\n    }\n    return writableStores;\n  }\n\n  restoreSharedDataSnapshot(snapshot: Record<string, string> | null | undefined): void {\n    if (!snapshot || typeof snapshot !== \"object\") {\n      return;\n    }\n    for (const targetID of Object.keys(this._sharedDataStores)) {\n      delete this._sharedDataStores[targetID];\n    }\n    for (const [targetID, store] of Object.entries(snapshot)) {\n      if (typeof targetID === \"string\" && typeof store === \"string\") {\n        this._sharedDataStores[targetID] = store;\n      }\n    }\n    this.data.refreshStores(this._sharedDataStores);\n  }\n\n  isConfiguredSharedDataElement(CMIElement: string): boolean {\n    return this.data.isConfiguredElement(CMIElement);\n  }\n\n  private captureVisibleSharedData(): void {\n    for (const child of this.data.childArray) {\n      const dataObject = child as ADLDataObject;\n      // Presence in the backing record is the initialized bit.  In particular,\n      // do not turn a configured-but-never-written bucket into an initialized\n      // empty string while rotating the activity's mapped view.\n      if (dataObject.id && dataObject.storeIsSet) {\n        this._sharedDataStores[dataObject.id] = dataObject.storeValue;\n      }\n    }\n  }\n\n  /**\n   * Getter for sequencing\n   * @return {Sequencing | null}\n   */\n  get sequencing(): Sequencing | null {\n    return this._sequencing;\n  }\n\n  /**\n   * Setter for sequencing\n   * @param {Sequencing | null} sequencing\n   */\n  set sequencing(sequencing: Sequencing | null) {\n    this._sequencing = sequencing;\n    if (sequencing) {\n      sequencing.adlNav = this.nav;\n      this.nav.sequencing = sequencing;\n    }\n  }\n\n  /**\n   * toJSON for adl\n   * @return {\n   *    {\n   *      nav: ADLNav,\n   *      data: ADLData\n   *    }\n   *  }\n   */\n  toJSON(): {\n    nav: ADLNav;\n    data: ADLData;\n  } {\n    this.jsonString = true;\n    const result = {\n      nav: this.nav,\n      data: this.data,\n    };\n    this.jsonString = false;\n    return result;\n  }\n}\n\n/**\n * Class representing SCORM 2004's `adl.nav` object\n * @spec SN 3 - Navigation Data Model\n */\n\nexport class ADLNav extends BaseCMI {\n  private _request = \"_none_\";\n  private _sequencing: Sequencing | null = null;\n\n  /**\n   * Constructor for `adl.nav`\n   */\n  constructor() {\n    super(\"adl.nav\");\n    this.request_valid = new ADLNavRequestValid();\n    this.request_valid.setParentNav(this);\n  }\n\n  public request_valid: ADLNavRequestValid;\n\n  /**\n   * Getter for sequencing\n   * @return {Sequencing | null}\n   */\n  get sequencing(): Sequencing | null {\n    return this._sequencing;\n  }\n\n  /**\n   * Setter for sequencing\n   * @param {Sequencing | null} sequencing\n   */\n  set sequencing(sequencing: Sequencing | null) {\n    this._sequencing = sequencing;\n  }\n\n  /**\n   * Called when the API has been initialized after the CMI has been created\n   */\n  override initialize() {\n    super.initialize();\n    if (typeof this.request_valid?.initialize === \"function\") {\n      this.request_valid.initialize();\n    }\n  }\n\n  /**\n   * Called when the API needs to be reset\n   */\n  reset() {\n    this._initialized = false;\n    this._request = \"_none_\";\n    if (this._sequencing) {\n      this._sequencing.adlNav = null;\n    }\n    this._sequencing = null;\n    this.request_valid?.reset();\n  }\n\n  /**\n   * Getter for _request\n   * @return {string}\n   */\n  get request(): string {\n    return this._request;\n  }\n\n  /**\n   * Setter for _request\n   * @param {string} request\n   */\n  set request(request: string) {\n    if (check2004ValidFormat(this._cmi_element + \".request\", request, scorm2004_regex.NAVEvent)) {\n      this._request = request;\n    }\n  }\n\n  /**\n   * toJSON for adl.nav\n   *\n   * @return {\n   *    {\n   *      request: string\n   *    }\n   *  }\n   */\n  toJSON(): {\n    request: string;\n  } {\n    this.jsonString = true;\n    const result = {\n      request: this.request,\n    };\n    this.jsonString = false;\n    return result;\n  }\n}\n\n/**\n * Class representing SCORM 2004's `adl.data` object\n */\nexport class ADLData extends CMIArray {\n  constructor() {\n    super({\n      CMIElement: \"adl.data\",\n      children: scorm2004_constants.adl_data_children,\n      errorCode: scorm2004_errors.READ_ONLY_ELEMENT as number,\n      errorClass: Scorm2004ValidationError,\n    });\n  }\n\n  override initialize(): void {\n    super.initialize();\n    for (const child of this.childArray) {\n      child.initialize();\n    }\n  }\n\n  override reset(wipe: boolean = false): void {\n    this._initialized = false;\n    if (wipe) {\n      this.childArray = [];\n      return;\n    }\n    for (const child of this.childArray) {\n      (child as ADLDataObject).deinitialize();\n    }\n  }\n\n  configure(maps: SharedDataMapInfo[], stores: Record<string, string>): void {\n    this.childArray = maps.map((map) => {\n      const child = new ADLDataObject();\n      const storeIsSet = Object.prototype.hasOwnProperty.call(stores, map.targetID);\n      child.configure(\n        map.targetID,\n        storeIsSet ? stores[map.targetID]! : \"\",\n        map.readSharedData,\n        map.writeSharedData,\n        storeIsSet,\n        (value) => {\n          stores[map.targetID] = value;\n        },\n      );\n      if (this.initialized) {\n        child.initialize();\n      }\n      return child;\n    });\n  }\n\n  refreshStores(stores: Record<string, string>): void {\n    for (const child of this.childArray) {\n      const dataObject = child as ADLDataObject;\n      const storeIsSet = Object.prototype.hasOwnProperty.call(stores, dataObject.id);\n      dataObject.refreshStore(storeIsSet ? stores[dataObject.id]! : \"\", storeIsSet);\n    }\n  }\n\n  isConfiguredElement(CMIElement: string): boolean {\n    const match = /^adl\\.data\\.(\\d+)\\.store$/.exec(CMIElement);\n    if (!match) return false;\n    const index = Number(match[1]);\n    return Number.isInteger(index) && index >= 0 && index < this.childArray.length;\n  }\n}\n\n/**\n * Class for SCORM 2004's adl.data.n object\n */\nexport class ADLDataObject extends BaseCMI {\n  private _id = \"\";\n  private _store = \"\";\n  private _idIsSet = false;\n  private _storeIsSet = false;\n  private _readSharedData = true;\n  private _writeSharedData = true;\n  private _onStoreChange: ((value: string) => void) | null = null;\n  private readonly _allowStoreWithoutId: boolean;\n\n  constructor(allowStoreWithoutId: boolean = false) {\n    super(\"adl.data.n\");\n    this._allowStoreWithoutId = allowStoreWithoutId;\n  }\n\n  /**\n   * Called when the API has been reset\n   */\n  reset() {\n    this._initialized = false;\n    this._idIsSet = false;\n    this._storeIsSet = false;\n  }\n\n  configure(\n    id: string,\n    store: string | undefined,\n    readSharedData: boolean,\n    writeSharedData: boolean,\n    storeIsSet: boolean,\n    onStoreChange: (value: string) => void,\n  ): void {\n    this._id = id;\n    this._store = store ?? \"\";\n    this._idIsSet = true;\n    this._storeIsSet = storeIsSet;\n    this._readSharedData = readSharedData;\n    this._writeSharedData = writeSharedData;\n    this._onStoreChange = onStoreChange;\n  }\n\n  refreshStore(store: string, storeIsSet: boolean): void {\n    this._store = store;\n    this._storeIsSet = storeIsSet;\n  }\n\n  /** End the SCO session without discarding this LMS-configured bucket. */\n  deinitialize(): void {\n    this._initialized = false;\n  }\n\n  /**\n   * Getter for _id\n   * @return {string}\n   */\n  get id(): string {\n    return this._id;\n  }\n\n  /**\n   * Setter for _id\n   * Per SCORM 2004 4th Ed: id is read-only after initialization (error 404)\n   * @param {string} id\n   */\n  set id(id: string) {\n    // REQ-ADL-015: id is read-only after initialization\n    if (this.initialized) {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".id\",\n        scorm2004_errors.READ_ONLY_ELEMENT as number,\n      );\n    }\n    if (check2004ValidFormat(this._cmi_element + \".id\", id, scorm2004_regex.CMILongIdentifier)) {\n      this._id = id;\n      this._idIsSet = true;\n    }\n  }\n\n  /**\n   * Getter for _store\n   * Per SCORM 2004 4th Ed: returns error 403 if store not initialized\n   * @return {string}\n   */\n  get store(): string {\n    if (this.initialized && !this._readSharedData) {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".store\",\n        scorm2004_errors.WRITE_ONLY_ELEMENT as number,\n      );\n    }\n    // REQ-ADL-020: GetValue on uninitialized store returns error 403\n    if (this.initialized && !this._storeIsSet) {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".store\",\n        scorm2004_errors.VALUE_NOT_INITIALIZED as number,\n      );\n    }\n    return this._store;\n  }\n\n  /**\n   * Setter for _store\n   * Per SCORM 2004 4th Ed: store requires id to be set first (error 408)\n   * Per SCORM 2004 4th Ed SPM: store max length is 64000 characters\n   * @param {string} store\n   */\n  set store(store: string) {\n    if (this.initialized && !this._writeSharedData) {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".store\",\n        scorm2004_errors.READ_ONLY_ELEMENT as number,\n      );\n    }\n    // REQ-ADL-025: Dependency check - id must be set before store\n    if (this.initialized && !this._allowStoreWithoutId && !this._idIsSet) {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".store\",\n        scorm2004_errors.DEPENDENCY_NOT_ESTABLISHED as number,\n      );\n    }\n    // REQ-ADL-017: store SPM is 64000 characters (was incorrectly 4000)\n    if (\n      check2004ValidFormat(\n        this._cmi_element + \".store\",\n        store,\n        scorm2004_regex.CMIString64000,\n        true,\n      )\n    ) {\n      this._store = store;\n      this._storeIsSet = true;\n      this._onStoreChange?.(store);\n    }\n  }\n\n  /** Internal value access used while rotating the mapped view. */\n  get storeValue(): string {\n    return this._store;\n  }\n\n  /** Whether the LMS has initialized this mapped store. */\n  get storeIsSet(): boolean {\n    return this._storeIsSet;\n  }\n\n  /** Whether the current activity may write this shared-data bucket. */\n  get writeSharedData(): boolean {\n    return this._writeSharedData;\n  }\n\n  /**\n   * toJSON for adl.data.n\n   *\n   * @return {\n   *    {\n   *      id: string,\n   *      store: string\n   *    }\n   *  }\n   */\n  toJSON(): {\n    id: string;\n    store: string;\n  } {\n    this.jsonString = true;\n    const result = {\n      id: this._id,\n      store: this._store,\n    };\n    this.jsonString = false;\n    return result;\n  }\n}\n\n/** Validate and store an LMS-provided navigation validity entry. */\nfunction setStaticNavigationValue(\n  values: { [key: string]: NAVBoolean },\n  kind: \"choice\" | \"jump\",\n  key: string,\n  value: string,\n): void {\n  const element = `adl.nav.request_valid.${kind}.${key}`;\n  if (\n    check2004ValidFormat(element, value, scorm2004_regex.NAVBoolean) &&\n    check2004ValidFormat(element, key, scorm2004_regex.NAVTarget)\n  ) {\n    values[key] = value as NAVBoolean;\n  }\n}\n\n/**\n * Helper class for adl.nav.request_valid.choice to support target validation\n */\nclass ADLNavRequestValidChoice {\n  private _parentNav: ADLNav | null = null;\n  private _staticValues: { [key: string]: NAVBoolean } = {};\n\n  getStaticValue(target: string): NAVBoolean | undefined {\n    return this._staticValues[`{target=${target}}`];\n  }\n\n  setStaticValue(key: string, value: string): void {\n    setStaticNavigationValue(this._staticValues, \"choice\", key, value);\n  }\n\n  setParentNav(nav: ADLNav): void {\n    this._parentNav = nav;\n  }\n\n  /**\n   * Validate if a target can be chosen\n   * Called by BaseAPI when accessing adl.nav.request_valid.choice.{target=...}\n   */\n  _isTargetValid(target: string): string {\n    // If sequencing is available, evaluate dynamically\n    if (this._parentNav?.sequencing?.overallSequencingProcess) {\n      const process = this._parentNav.sequencing.overallSequencingProcess;\n      if (process.predictChoiceEnabled) {\n        const result = process.predictChoiceEnabled(target) ? \"true\" : \"false\";\n        return result;\n      }\n    }\n    // Fall back to static value if sequencing not available\n    const value = this.getStaticValue(target);\n    if (value === NAVBoolean.TRUE) {\n      return \"true\";\n    }\n    if (value === NAVBoolean.FALSE) {\n      return \"false\";\n    }\n    return \"unknown\";\n  }\n\n  /**\n   * Get all static values\n   */\n  getAll(): { [key: string]: NAVBoolean } {\n    return { ...this._staticValues };\n  }\n\n  /**\n   * Set static values (used during initialization)\n   */\n  setAll(values: { [key: string]: NAVBoolean }): void {\n    this._staticValues = { ...values };\n  }\n}\n\n/**\n * Helper class for adl.nav.request_valid.jump to support target validation\n */\nclass ADLNavRequestValidJump {\n  private _parentNav: ADLNav | null = null;\n  private _staticValues: { [key: string]: NAVBoolean } = {};\n\n  getStaticValue(target: string): NAVBoolean | undefined {\n    return this._staticValues[`{target=${target}}`];\n  }\n\n  setStaticValue(key: string, value: string): void {\n    setStaticNavigationValue(this._staticValues, \"jump\", key, value);\n  }\n\n  setParentNav(nav: ADLNav): void {\n    this._parentNav = nav;\n  }\n\n  /**\n   * Validate if a target can be jumped to\n   * Called by BaseAPI when accessing adl.nav.request_valid.jump.{target=...}\n   */\n  _isTargetValid(target: string): string {\n    // If sequencing is available, evaluate dynamically\n    const process = this._parentNav?.sequencing?.overallSequencingProcess;\n    if (process?.predictJumpEnabled) {\n      return process.predictJumpEnabled(target) ? \"true\" : \"false\";\n    }\n    if (this._parentNav?.sequencing?.activityTree) {\n      const activity = this._parentNav.sequencing.activityTree.getActivity(target);\n      return activity ? \"true\" : \"false\";\n    }\n    // Fall back to static value if sequencing not available\n    const value = this.getStaticValue(target);\n    if (value === NAVBoolean.TRUE) return \"true\";\n    if (value === NAVBoolean.FALSE) return \"false\";\n    return \"unknown\";\n  }\n\n  /**\n   * Get all static values\n   */\n  getAll(): { [key: string]: NAVBoolean } {\n    return { ...this._staticValues };\n  }\n\n  /**\n   * Set static values (used during initialization)\n   */\n  setAll(values: { [key: string]: NAVBoolean }): void {\n    this._staticValues = { ...values };\n  }\n}\n\n/**\n * Class representing SCORM 2004's adl.nav.request_valid object\n * @spec SN 3.1 - Navigation Request Validity Data Model\n */\n\nexport class ADLNavRequestValid extends BaseCMI {\n  private _continue = \"unknown\";\n  private _previous = \"unknown\";\n  private _choice: ADLNavRequestValidChoice;\n  private _jump: ADLNavRequestValidJump;\n  private _exit = \"unknown\";\n  private _exitAll = \"unknown\";\n  private _abandon = \"unknown\";\n  private _abandonAll = \"unknown\";\n  private _suspendAll = \"unknown\";\n  private _parentNav: ADLNav | null = null;\n\n  /**\n   * Constructor for adl.nav.request_valid\n   */\n  constructor() {\n    super(\"adl.nav.request_valid\");\n    this._choice = new ADLNavRequestValidChoice();\n    this._jump = new ADLNavRequestValidJump();\n  }\n\n  /**\n   * Set parent nav reference for sequencing access\n   * @param {ADLNav} nav - Parent ADLNav instance\n   */\n  setParentNav(nav: ADLNav): void {\n    this._parentNav = nav;\n    this._choice.setParentNav(nav);\n    this._jump.setParentNav(nav);\n  }\n\n  /**\n   * Called when the API has been reset\n   */\n  override reset() {\n    this._initialized = false;\n    this._continue = \"unknown\";\n    this._previous = \"unknown\";\n    this._choice.setAll({});\n    this._jump.setAll({});\n    this._exit = \"unknown\";\n    this._exitAll = \"unknown\";\n    this._abandon = \"unknown\";\n    this._abandonAll = \"unknown\";\n    this._suspendAll = \"unknown\";\n  }\n\n  /**\n   * Getter for _continue\n   * Dynamically evaluates whether continue navigation is valid using sequencing\n   * @return {string}\n   */\n  get continue(): string {\n    // If sequencing is available, evaluate dynamically\n    if (this._parentNav?.sequencing?.overallSequencingProcess) {\n      const process = this._parentNav.sequencing.overallSequencingProcess;\n      if (process.predictContinueEnabled) {\n        return process.predictContinueEnabled() ? \"true\" : \"false\";\n      }\n    }\n    // Fall back to static value if sequencing not available\n    return this._continue;\n  }\n\n  /**\n   * Setter for _continue. Just throws an error.\n   * @param {string} _continue\n   */\n  set continue(_continue: string) {\n    if (this.initialized) {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".continue\",\n        scorm2004_errors.READ_ONLY_ELEMENT as number,\n      );\n    }\n    if (\n      check2004ValidFormat(this._cmi_element + \".continue\", _continue, scorm2004_regex.NAVBoolean)\n    ) {\n      this._continue = _continue;\n    }\n  }\n\n  /**\n   * Getter for _previous\n   * Dynamically evaluates whether previous navigation is valid using sequencing\n   * @return {string}\n   */\n  get previous(): string {\n    // If sequencing is available, evaluate dynamically\n    if (this._parentNav?.sequencing?.overallSequencingProcess) {\n      const process = this._parentNav.sequencing.overallSequencingProcess;\n      if (process.predictPreviousEnabled) {\n        return process.predictPreviousEnabled() ? \"true\" : \"false\";\n      }\n    }\n    // Fall back to static value if sequencing not available\n    return this._previous;\n  }\n\n  /**\n   * Setter for _previous. Just throws an error.\n   * @param {string} _previous\n   */\n  set previous(_previous: string) {\n    if (this.initialized) {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".previous\",\n        scorm2004_errors.READ_ONLY_ELEMENT as number,\n      );\n    }\n    if (\n      check2004ValidFormat(this._cmi_element + \".previous\", _previous, scorm2004_regex.NAVBoolean)\n    ) {\n      this._previous = _previous;\n    }\n  }\n\n  /**\n   * Getter for _choice\n   * @return {ADLNavRequestValidChoice}\n   */\n  get choice(): ADLNavRequestValidChoice {\n    return this._choice;\n  }\n\n  /**\n   * Setter for _choice\n   * @param {{ [key: string]: string }} choice\n   */\n  set choice(choice: { [key: string]: string }) {\n    if (this.initialized) {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".choice\",\n        scorm2004_errors.READ_ONLY_ELEMENT as number,\n      );\n    }\n    if (typeof choice !== \"object\") {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".choice\",\n        scorm2004_errors.TYPE_MISMATCH as number,\n      );\n    }\n    const converted: { [key: string]: NAVBoolean } = {};\n    for (const key in choice) {\n      if ({}.hasOwnProperty.call(choice, key)) {\n        if (\n          check2004ValidFormat(\n            this._cmi_element + \".choice.\" + key,\n            choice[key] || \"\",\n            scorm2004_regex.NAVBoolean,\n          ) &&\n          check2004ValidFormat(this._cmi_element + \".choice.\" + key, key, scorm2004_regex.NAVTarget)\n        ) {\n          // Convert string value to NAVBoolean enum value\n          const value = choice[key];\n          if (value === \"true\") {\n            converted[key] = NAVBoolean.TRUE;\n          } else if (value === \"false\") {\n            converted[key] = NAVBoolean.FALSE;\n          } else if (value === \"unknown\") {\n            converted[key] = NAVBoolean.UNKNOWN;\n          }\n        }\n      }\n    }\n    this._choice.setAll(converted);\n  }\n\n  /**\n   * Getter for _jump\n   * @return {ADLNavRequestValidJump}\n   */\n  get jump(): ADLNavRequestValidJump {\n    return this._jump;\n  }\n\n  /**\n   * Setter for _jump\n   * @param {{ [key: string]: string }} jump\n   */\n  set jump(jump: { [key: string]: string }) {\n    if (this.initialized) {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".jump\",\n        scorm2004_errors.READ_ONLY_ELEMENT as number,\n      );\n    }\n    if (typeof jump !== \"object\") {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".jump\",\n        scorm2004_errors.TYPE_MISMATCH as number,\n      );\n    }\n    const converted: { [key: string]: NAVBoolean } = {};\n    for (const key in jump) {\n      if ({}.hasOwnProperty.call(jump, key)) {\n        if (\n          check2004ValidFormat(\n            this._cmi_element + \".jump.\" + key,\n            jump[key] || \"\",\n            scorm2004_regex.NAVBoolean,\n          ) &&\n          check2004ValidFormat(this._cmi_element + \".jump.\" + key, key, scorm2004_regex.NAVTarget)\n        ) {\n          // Convert string value to NAVBoolean enum value\n          const value = jump[key];\n          if (value === \"true\") {\n            converted[key] = NAVBoolean.TRUE;\n          } else if (value === \"false\") {\n            converted[key] = NAVBoolean.FALSE;\n          } else if (value === \"unknown\") {\n            converted[key] = NAVBoolean.UNKNOWN;\n          }\n        }\n      }\n    }\n    this._jump.setAll(converted);\n  }\n\n  /**\n   * Getter for _exit\n   * @return {string}\n   */\n  get exit(): string {\n    return this._exit;\n  }\n\n  /**\n   * Setter for _exit. Just throws an error.\n   * @param {string} _exit\n   */\n  set exit(_exit: string) {\n    if (this.initialized) {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".exit\",\n        scorm2004_errors.READ_ONLY_ELEMENT as number,\n      );\n    }\n    if (check2004ValidFormat(this._cmi_element + \".exit\", _exit, scorm2004_regex.NAVBoolean)) {\n      this._exit = _exit;\n    }\n  }\n\n  /**\n   * Getter for _exitAll\n   * @return {string}\n   */\n  get exitAll(): string {\n    return this._exitAll;\n  }\n\n  /**\n   * Setter for _exitAll. Just throws an error.\n   * @param {string} _exitAll\n   */\n  set exitAll(_exitAll: string) {\n    if (this.initialized) {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".exitAll\",\n        scorm2004_errors.READ_ONLY_ELEMENT as number,\n      );\n    }\n    if (\n      check2004ValidFormat(this._cmi_element + \".exitAll\", _exitAll, scorm2004_regex.NAVBoolean)\n    ) {\n      this._exitAll = _exitAll;\n    }\n  }\n\n  /**\n   * Getter for _abandon\n   * @return {string}\n   */\n  get abandon(): string {\n    return this._abandon;\n  }\n\n  /**\n   * Setter for _abandon. Just throws an error.\n   * @param {string} _abandon\n   */\n  set abandon(_abandon: string) {\n    if (this.initialized) {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".abandon\",\n        scorm2004_errors.READ_ONLY_ELEMENT as number,\n      );\n    }\n    if (\n      check2004ValidFormat(this._cmi_element + \".abandon\", _abandon, scorm2004_regex.NAVBoolean)\n    ) {\n      this._abandon = _abandon;\n    }\n  }\n\n  /**\n   * Getter for _abandonAll\n   * @return {string}\n   */\n  get abandonAll(): string {\n    return this._abandonAll;\n  }\n\n  /**\n   * Setter for _abandonAll. Just throws an error.\n   * @param {string} _abandonAll\n   */\n  set abandonAll(_abandonAll: string) {\n    if (this.initialized) {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".abandonAll\",\n        scorm2004_errors.READ_ONLY_ELEMENT as number,\n      );\n    }\n    if (\n      check2004ValidFormat(\n        this._cmi_element + \".abandonAll\",\n        _abandonAll,\n        scorm2004_regex.NAVBoolean,\n      )\n    ) {\n      this._abandonAll = _abandonAll;\n    }\n  }\n\n  /**\n   * Getter for _suspendAll\n   * @return {string}\n   */\n  get suspendAll(): string {\n    return this._suspendAll;\n  }\n\n  /**\n   * Setter for _suspendAll. Just throws an error.\n   * @param {string} _suspendAll\n   */\n  set suspendAll(_suspendAll: string) {\n    if (this.initialized) {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".suspendAll\",\n        scorm2004_errors.READ_ONLY_ELEMENT as number,\n      );\n    }\n    if (\n      check2004ValidFormat(\n        this._cmi_element + \".suspendAll\",\n        _suspendAll,\n        scorm2004_regex.NAVBoolean,\n      )\n    ) {\n      this._suspendAll = _suspendAll;\n    }\n  }\n\n  /**\n   * toJSON for adl.nav.request_valid\n   *\n   * @return {\n   *    {\n   *      previous: string,\n   *      continue: string,\n   *      choice: { [key: string]: NAVBoolean },\n   *      jump: { [key: string]: NAVBoolean },\n   *      exit: string,\n   *      exitAll: string,\n   *      abandon: string,\n   *      abandonAll: string,\n   *      suspendAll: string\n   *    }\n   *  }\n   */\n  toJSON(): {\n    previous: string;\n    continue: string;\n    choice: { [key: string]: NAVBoolean };\n    jump: { [key: string]: NAVBoolean };\n    exit: string;\n    exitAll: string;\n    abandon: string;\n    abandonAll: string;\n    suspendAll: string;\n  } {\n    this.jsonString = true;\n    const result = {\n      previous: this.previous,\n      continue: this.continue,\n      choice: this._choice.getAll(),\n      jump: this._jump.getAll(),\n      exit: this.exit,\n      exitAll: this.exitAll,\n      abandon: this.abandon,\n      abandonAll: this.abandonAll,\n      suspendAll: this.suspendAll,\n    };\n    this.jsonString = false;\n    return result;\n  }\n}\n","import { BaseCMI } from \"../../common/base_cmi\";\nimport { Activity } from \"./activity\";\nimport { ActivityTree } from \"./activity_tree\";\nimport { SequencingRules } from \"./sequencing_rules\";\nimport { SequencingControls } from \"./sequencing_controls\";\nimport { RollupRules } from \"./rollup_rules\";\nimport { ADLNav } from \"../adl\";\nimport { Scorm2004ValidationError } from \"../../../exceptions/scorm2004_exceptions\";\nimport { scorm2004_errors } from \"../../../constants/error_codes\";\nimport { AuxiliaryResource, HideLmsUiItem } from \"../../../types/sequencing_types\";\n\n// Type-only import: erased at compile time, so no runtime circular dependency\nimport type { OverallSequencingProcess } from \"./overall_sequencing_process\";\n\n/**\n * Class representing SCORM 2004 sequencing\n */\nexport class Sequencing extends BaseCMI {\n  private _activityTree: ActivityTree;\n  private _sequencingRules: SequencingRules;\n  private _sequencingControls: SequencingControls;\n  private _rollupRules: RollupRules;\n  private _adlNav: ADLNav | null = null;\n  private _hideLmsUi: HideLmsUiItem[] = [];\n  private _auxiliaryResources: AuxiliaryResource[] = [];\n  private _overallSequencingProcess: OverallSequencingProcess | null = null;\n\n  /**\n   * Constructor for Sequencing\n   */\n  constructor() {\n    super(\"sequencing\");\n    this._activityTree = new ActivityTree();\n    this._sequencingRules = new SequencingRules();\n    this._sequencingControls = new SequencingControls();\n    this._rollupRules = new RollupRules();\n  }\n\n  /**\n   * Called when the API has been initialized after the CMI has been created\n   */\n  override initialize() {\n    super.initialize();\n    this._activityTree.initialize();\n    this._sequencingRules.initialize();\n    this._sequencingControls.initialize();\n    this._rollupRules.initialize();\n    \n  }\n\n  /**\n   * Called when the API needs to be reset\n   */\n  reset() {\n    this._initialized = false;\n    this._activityTree.reset();\n    this._sequencingRules.reset();\n    this._sequencingControls.reset();\n    this._rollupRules.reset();\n    this._hideLmsUi = [];\n    this._auxiliaryResources = [];\n  }\n\n  /**\n   * Getter for activityTree\n   * @return {ActivityTree}\n   */\n  get activityTree(): ActivityTree {\n    return this._activityTree;\n  }\n\n  /**\n   * Setter for activityTree\n   * @param {ActivityTree} activityTree\n   */\n  set activityTree(activityTree: ActivityTree) {\n    // noinspection SuspiciousTypeOfGuard\n    if (!(activityTree instanceof ActivityTree)) {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".activityTree\",\n        scorm2004_errors.TYPE_MISMATCH as number,\n      );\n    }\n    this._activityTree = activityTree;\n  }\n\n  /**\n   * Getter for sequencingRules\n   * @return {SequencingRules}\n   */\n  get sequencingRules(): SequencingRules {\n    return this._sequencingRules;\n  }\n\n  /**\n   * Setter for sequencingRules\n   * @param {SequencingRules} sequencingRules\n   */\n  set sequencingRules(sequencingRules: SequencingRules) {\n    // noinspection SuspiciousTypeOfGuard\n    if (!(sequencingRules instanceof SequencingRules)) {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".sequencingRules\",\n        scorm2004_errors.TYPE_MISMATCH as number,\n      );\n    }\n    this._sequencingRules = sequencingRules;\n  }\n\n  /**\n   * Getter for sequencingControls\n   * @return {SequencingControls}\n   */\n  get sequencingControls(): SequencingControls {\n    return this._sequencingControls;\n  }\n\n  /**\n   * Setter for sequencingControls\n   * @param {SequencingControls} sequencingControls\n   */\n  set sequencingControls(sequencingControls: SequencingControls) {\n    // noinspection SuspiciousTypeOfGuard\n    if (!(sequencingControls instanceof SequencingControls)) {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".sequencingControls\",\n        scorm2004_errors.TYPE_MISMATCH as number,\n      );\n    }\n    this._sequencingControls = sequencingControls;\n  }\n\n  get hideLmsUi(): HideLmsUiItem[] {\n    return [...this._hideLmsUi];\n  }\n\n  set hideLmsUi(items: HideLmsUiItem[]) {\n    this._hideLmsUi = [...items];\n  }\n\n  get auxiliaryResources(): AuxiliaryResource[] {\n    return this._auxiliaryResources.map((resource) => ({ ...resource }));\n  }\n\n  set auxiliaryResources(resources: AuxiliaryResource[]) {\n    this._auxiliaryResources = resources.map((resource) => ({ ...resource }));\n  }\n\n  /**\n   * Getter for rollupRules\n   * @return {RollupRules}\n   */\n  get rollupRules(): RollupRules {\n    return this._rollupRules;\n  }\n\n  /**\n   * Setter for rollupRules\n   * @param {RollupRules} rollupRules\n   */\n  set rollupRules(rollupRules: RollupRules) {\n    // noinspection SuspiciousTypeOfGuard\n    if (!(rollupRules instanceof RollupRules)) {\n      throw new Scorm2004ValidationError(\n        this._cmi_element + \".rollupRules\",\n        scorm2004_errors.TYPE_MISMATCH as number,\n      );\n    }\n    this._rollupRules = rollupRules;\n  }\n\n  /**\n   * Getter for adlNav\n   * @return {ADLNav | null}\n   */\n  get adlNav(): ADLNav | null {\n    return this._adlNav;\n  }\n\n  /**\n   * Setter for adlNav\n   * @param {ADLNav | null} adlNav\n   */\n  set adlNav(adlNav: ADLNav | null) {\n    this._adlNav = adlNav;\n\n  }\n\n  /**\n   * Getter for overallSequencingProcess\n   * @return {OverallSequencingProcess | null}\n   */\n  get overallSequencingProcess(): OverallSequencingProcess | null {\n    return this._overallSequencingProcess;\n  }\n\n  /**\n   * Setter for overallSequencingProcess\n   * @param {OverallSequencingProcess | null} process\n   */\n  set overallSequencingProcess(process: OverallSequencingProcess | null) {\n    this._overallSequencingProcess = process;\n  }\n\n\n\n  /**\n   * Process rollup for the entire activity tree\n   */\n  processRollup(): void {\n    // Get the root activity\n    const root = this._activityTree.root;\n    if (!root) {\n      return;\n    }\n\n    // Process rollup from the bottom up\n    this._processRollupRecursive(root);\n  }\n\n\n  /**\n   * Process rollup recursively\n   * @param {Activity} activity - The activity to process rollup for\n   * @private\n   */\n  private _processRollupRecursive(activity: Activity): void {\n    // Process rollup for children first\n    for (const child of activity.children) {\n      this._processRollupRecursive(child);\n    }\n\n    // Process rollup for this activity\n    this._rollupRules.processRollup(activity);\n  }\n\n\n  /**\n   * Get the current activity\n   * @return {Activity | null}\n   */\n  getCurrentActivity(): Activity | null {\n    return this._activityTree.currentActivity;\n  }\n\n  /**\n   * Get the root activity\n   * @return {Activity | null}\n   */\n  getRootActivity(): Activity | null {\n    return this._activityTree.root;\n  }\n\n  /**\n   * toJSON for Sequencing\n   * @return {object}\n   */\n  toJSON(): object {\n    this.jsonString = true;\n    const result = {\n      activityTree: this._activityTree,\n      sequencingRules: this._sequencingRules,\n      sequencingControls: this._sequencingControls,\n      rollupRules: this._rollupRules,\n      adlNav: this._adlNav,\n    };\n    this.jsonString = false;\n    return result;\n  }\n}\n","import { CMIArray } from \"../../cmi/common/array\";\nimport {\n  CMIInteractionsCorrectResponsesObject,\n  CMIInteractionsObject,\n  stripCorrectResponsePrefixes,\n} from \"../../cmi/scorm2004/interactions\";\nimport {\n  allowsBareDelimiters,\n  splitDelimited,\n  splitFirstDelimited,\n} from \"../../cmi/scorm2004/interaction_delimiters\";\nimport { CorrectResponses, ResponseType, scorm2004_errors, scorm2004_regex } from \"../../constants\";\n\n/**\n * Context interface for error handling callbacks\n */\nexport interface ValidationContext {\n  throwSCORMError: (element: string, errorCode: number, message?: string) => void;\n  getLastErrorCode: () => string;\n  /** Optional callback to delegate checkCorrectResponseValue to the API (for test spying) */\n  checkCorrectResponseValue?: (\n    CMIElement: string,\n    interaction_type: string,\n    nodes: Array<any>,\n    value: any,\n  ) => void;\n}\n\n/**\n * Handles validation of SCORM 2004 correct responses for interactions\n *\n * This class is responsible for:\n * - Validating response types against SCORM 2004 specifications\n * - Checking for duplicate choice responses\n * - Validating correct response values\n * - Removing and validating response prefixes\n */\nexport class Scorm2004ResponseValidator {\n  private context: ValidationContext;\n\n  constructor(context: ValidationContext) {\n    this.context = context;\n  }\n\n  /**\n   * Checks for valid response types\n   * @param {string} CMIElement - The CMI element path\n   * @param {ResponseType} response_type - The response type configuration\n   * @param {any} value - The value to validate\n   * @param {string} interaction_type - The type of interaction\n   */\n  checkValidResponseType(\n    CMIElement: string,\n    response_type: ResponseType,\n    value: any,\n    interaction_type: string,\n  ): void {\n    let nodes: any[] = [];\n    if (response_type?.delimiter) {\n      // Split on the spec's bracketed token (\"[,]\" / \"[:]\") when present,\n      // falling back to the bare character for legacy plain values.\n      nodes = splitDelimited(\n        String(value),\n        response_type.delimiter,\n        allowsBareDelimiters(String(value), interaction_type),\n      );\n    } else {\n      nodes[0] = value;\n    }\n\n    if (nodes.length > 0 && nodes.length <= response_type.max) {\n      // Use context callback if available (for API integration), otherwise call directly\n      if (this.context.checkCorrectResponseValue) {\n        this.context.checkCorrectResponseValue(CMIElement, interaction_type, nodes, value);\n      } else {\n        this.checkCorrectResponseValue(CMIElement, interaction_type, nodes, value);\n      }\n    } else if (nodes.length > response_type.max) {\n      this.context.throwSCORMError(\n        CMIElement,\n        scorm2004_errors.GENERAL_SET_FAILURE!,\n        `Data Model Element Pattern Too Long: ${value}`,\n      );\n    }\n  }\n\n  /**\n   * Checks for duplicate 'choice' responses\n   * @param {string} CMIElement - The CMI element path\n   * @param {CMIInteractionsObject} interaction - The interaction object\n   * @param {any} value - The value to check for duplicates\n   */\n  checkDuplicateChoiceResponse(\n    CMIElement: string,\n    interaction: CMIInteractionsObject,\n    value: any,\n  ): void {\n    const interaction_count = interaction.correct_responses._count;\n    if (interaction.type === \"choice\") {\n      for (let i = 0; i < interaction_count && this.context.getLastErrorCode() === \"0\"; i++) {\n        const response = interaction.correct_responses.childArray[i] as\n          CMIInteractionsCorrectResponsesObject | undefined;\n        if (response?.pattern === value) {\n          this.context.throwSCORMError(\n            CMIElement,\n            scorm2004_errors.GENERAL_SET_FAILURE!,\n            `${value}`,\n          );\n        }\n      }\n    }\n  }\n\n  /**\n   * Validate correct response\n   * @param {string} CMIElement - The CMI element path\n   * @param {CMIInteractionsObject} interaction - The interaction object\n   * @param {*} value - The value to validate\n   */\n  validateCorrectResponse(\n    CMIElement: string,\n    interaction: CMIInteractionsObject,\n    value: any,\n  ): void {\n    const parts = CMIElement.split(\".\");\n    const pattern_index = Number(parts[4]);\n\n    if (!interaction) {\n      this.context.throwSCORMError(\n        CMIElement,\n        scorm2004_errors.DEPENDENCY_NOT_ESTABLISHED!,\n        CMIElement,\n      );\n      return;\n    }\n\n    const interaction_count = interaction.correct_responses._count;\n    this.checkDuplicateChoiceResponse(CMIElement, interaction, value);\n\n    const response_type = CorrectResponses[interaction.type];\n    if (\n      response_type &&\n      (typeof response_type.limit === \"undefined\" || interaction_count < response_type.limit)\n    ) {\n      this.checkValidResponseType(CMIElement, response_type, value, interaction.type);\n\n      if (\n        (this.context.getLastErrorCode() === \"0\" &&\n          (!response_type.duplicate ||\n            !this.checkDuplicatedPattern(interaction.correct_responses, pattern_index, value))) ||\n        (this.context.getLastErrorCode() === \"0\" && value === \"\")\n      ) {\n        // do nothing, we want the inverse\n      } else {\n        if (this.context.getLastErrorCode() === \"0\") {\n          this.context.throwSCORMError(\n            CMIElement,\n            scorm2004_errors.GENERAL_SET_FAILURE!,\n            `Data Model Element Pattern Already Exists: ${CMIElement} - ${value}`,\n          );\n        }\n      }\n    } else {\n      this.context.throwSCORMError(\n        CMIElement,\n        scorm2004_errors.GENERAL_SET_FAILURE!,\n        `Data Model Element Collection Limit Reached: ${CMIElement} - ${value}`,\n      );\n    }\n  }\n\n  /**\n   * Check to see if a correct_response value has been duplicated\n   * @param {CMIArray} correct_response - The correct responses array\n   * @param {number} current_index - The current index to skip\n   * @param {*} value - The value to check for duplicates\n   * @return {boolean} True if pattern is duplicated\n   */\n  checkDuplicatedPattern(correct_response: CMIArray, current_index: number, value: any): boolean {\n    let found = false;\n    const count = correct_response._count;\n    for (let i = 0; i < count && !found; i++) {\n      if (i !== current_index) {\n        const item = correct_response.childArray[i] as\n          CMIInteractionsCorrectResponsesObject | undefined;\n        const existingPattern = item?.pattern;\n        if (existingPattern === value) {\n          found = true;\n        }\n      }\n    }\n    return found;\n  }\n\n  /**\n   * Checks for a valid correct_response value\n   * @param {string} CMIElement - The CMI element path\n   * @param {string} interaction_type - The type of interaction\n   * @param {Array} nodes - Array of parsed response nodes\n   * @param {*} value - The original value\n   */\n  checkCorrectResponseValue(\n    CMIElement: string,\n    interaction_type: string,\n    nodes: Array<any>,\n    value: any,\n  ): void {\n    const response = CorrectResponses[interaction_type];\n    if (!response) {\n      this.context.throwSCORMError(\n        CMIElement,\n        scorm2004_errors.TYPE_MISMATCH!,\n        `Incorrect Response Type: ${interaction_type}`,\n      );\n      return;\n    }\n    const allowBare = allowsBareDelimiters(String(value), interaction_type);\n    const formatRegex = new RegExp(response.format);\n    for (let i = 0; i < nodes.length && this.context.getLastErrorCode() === \"0\"; i++) {\n      if (interaction_type.match(\"^(fill-in|long-fill-in|matching|performance|sequencing)$\")) {\n        nodes[i] = this.removeCorrectResponsePrefixes(CMIElement, nodes[i]);\n      }\n\n      if (response?.delimiter2) {\n        // performance step_answers may contain literal dots, so split on the\n        // first \"[.]\" only; matching pairs split on all occurrences so a\n        // malformed 3-member record is rejected.\n        const values =\n          interaction_type === \"performance\"\n            ? splitFirstDelimited(nodes[i], response.delimiter2, allowBare)\n            : splitDelimited(nodes[i], response.delimiter2, allowBare);\n        if (values.length === 2) {\n          // A performance record must include at least one of\n          // step_name / step_answer. Both step fields accept an empty string\n          // individually (one part may be omitted), so reject both-empty here.\n          if (interaction_type === \"performance\" && values[0] === \"\" && values[1] === \"\") {\n            this.context.throwSCORMError(\n              CMIElement,\n              scorm2004_errors.TYPE_MISMATCH!,\n              `${interaction_type}: ${value}`,\n            );\n          } else {\n            const matches = values[0]?.match(formatRegex);\n            if (!matches) {\n              this.context.throwSCORMError(\n                CMIElement,\n                scorm2004_errors.TYPE_MISMATCH!,\n                `${interaction_type}: ${value}`,\n              );\n            } else {\n              if (!response.format2 || !values[1]?.match(new RegExp(response.format2))) {\n                this.context.throwSCORMError(\n                  CMIElement,\n                  scorm2004_errors.TYPE_MISMATCH!,\n                  `${interaction_type}: ${value}`,\n                );\n              }\n            }\n          }\n        } else {\n          this.context.throwSCORMError(\n            CMIElement,\n            scorm2004_errors.TYPE_MISMATCH!,\n            `${interaction_type}: ${value}`,\n          );\n        }\n      } else {\n        // An empty bound of a numeric range (\"[:]10\", \"4[:]\", \"[:]\") is a valid\n        // open-ended range per spec, so it skips the decimal format check. Only\n        // the bracketed \"[:]\" form qualifies; a plain \":\" is literal data.\n        if (\n          interaction_type === \"numeric\" &&\n          nodes.length > 1 &&\n          nodes[i] === \"\" &&\n          !!response.delimiter &&\n          String(value).includes(response.delimiter)\n        ) {\n          continue;\n        }\n        const matches = nodes[i].match(formatRegex);\n        if ((!matches && value !== \"\") || (!matches && interaction_type === \"true-false\")) {\n          this.context.throwSCORMError(\n            CMIElement,\n            scorm2004_errors.TYPE_MISMATCH!,\n            `${interaction_type}: ${value}`,\n          );\n        } else {\n          if (interaction_type === \"numeric\" && nodes.length > 1) {\n            // Only enforce ordering when both bounds are present.\n            if (nodes[0] !== \"\" && nodes[1] !== \"\" && Number(nodes[0]) > Number(nodes[1])) {\n              this.context.throwSCORMError(\n                CMIElement,\n                scorm2004_errors.TYPE_MISMATCH!,\n                `${interaction_type}: ${value}`,\n              );\n            }\n          } else {\n            if (nodes[i] !== \"\" && response.unique) {\n              for (let j = 0; j < i && this.context.getLastErrorCode() === \"0\"; j++) {\n                if (nodes[i] === nodes[j]) {\n                  this.context.throwSCORMError(\n                    CMIElement,\n                    scorm2004_errors.TYPE_MISMATCH!,\n                    `${interaction_type}: ${value}`,\n                  );\n                }\n              }\n            }\n          }\n        }\n      }\n    }\n  }\n\n  /**\n   * Remove prefixes from correct_response\n   * @param {string} CMIElement - The CMI element path\n   * @param {string} node - The node string with potential prefixes\n   * @return {*} The node with prefixes removed\n   */\n  removeCorrectResponsePrefixes(CMIElement: string, node: string): any {\n    try {\n      return stripCorrectResponsePrefixes(node);\n    } catch {\n      this.context.throwSCORMError(CMIElement, scorm2004_errors.TYPE_MISMATCH!, `${node}`);\n      return node;\n    }\n  }\n}\n","import { BaseCMI } from \"../../cmi/common/base_cmi\";\nimport { CMI } from \"../../cmi/scorm2004/cmi\";\nimport { CMIObjectivesObject } from \"../../cmi/scorm2004/objectives\";\nimport {\n  CMIInteractionsCorrectResponsesObject,\n  CMIInteractionsObject,\n  CMIInteractionsObjectivesObject,\n} from \"../../cmi/scorm2004/interactions\";\nimport { CMICommentsObject } from \"../../cmi/scorm2004/comments\";\nimport { ADLDataObject } from \"../../cmi/scorm2004/adl\";\nimport { evaluateCompletionStatusFromThreshold } from \"../../cmi/scorm2004/completion_status_evaluation\";\nimport {\n  CompletionStatus,\n  CorrectResponses,\n  scorm2004_errors,\n  SuccessStatus,\n} from \"../../constants\";\nimport { stringMatches } from \"../../utilities\";\nimport { Scorm2004ResponseValidator } from \"./response_validator\";\n\n/**\n * Context interface for CMI handler operations\n */\nexport interface CMIHandlerContext {\n  cmi: CMI;\n  isInitialized: () => boolean;\n  throwSCORMError: (element: string, errorCode: number, message?: string) => void;\n  getLastErrorCode: () => string;\n}\n\n/**\n * Handles CMI data model operations for SCORM 2004\n *\n * This class is responsible for:\n * - Creating child elements for arrays (objectives, interactions, comments)\n * - Creating correct response objects for interactions\n * - Evaluating completion status based on SCORM 2004 RTE rules\n * - Evaluating success status based on SCORM 2004 RTE rules\n */\nexport class Scorm2004CMIHandler {\n  private context: CMIHandlerContext;\n  private responseValidator: Scorm2004ResponseValidator;\n\n  constructor(context: CMIHandlerContext, responseValidator: Scorm2004ResponseValidator) {\n    this.context = context;\n    this.responseValidator = responseValidator;\n  }\n\n  /**\n   * Gets or builds a new child element to add to the array\n   *\n   * @param {string} CMIElement - The CMI element path\n   * @param {any} value - The value being set\n   * @param {boolean} foundFirstIndex - Whether the first index was found\n   * @return {BaseCMI|null} The child element or null\n   */\n  getChildElement(CMIElement: string, value: any, foundFirstIndex: boolean): BaseCMI | null {\n    if (stringMatches(CMIElement, \"cmi\\\\.objectives\\\\.\\\\d+\")) {\n      return new CMIObjectivesObject();\n    }\n\n    if (foundFirstIndex) {\n      if (stringMatches(CMIElement, \"cmi\\\\.interactions\\\\.\\\\d+\\\\.correct_responses\\\\.\\\\d+\")) {\n        return this.createCorrectResponsesObject(CMIElement, value);\n      } else if (stringMatches(CMIElement, \"cmi\\\\.interactions\\\\.\\\\d+\\\\.objectives\\\\.\\\\d+\")) {\n        return new CMIInteractionsObjectivesObject();\n      }\n    } else if (stringMatches(CMIElement, \"cmi\\\\.interactions\\\\.\\\\d+\")) {\n      return new CMIInteractionsObject();\n    }\n\n    if (stringMatches(CMIElement, \"cmi\\\\.comments_from_learner\\\\.\\\\d+\")) {\n      return new CMICommentsObject();\n    } else if (stringMatches(CMIElement, \"cmi\\\\.comments_from_lms\\\\.\\\\d+\")) {\n      return new CMICommentsObject(true);\n    }\n\n    if (stringMatches(CMIElement, \"adl\\\\.data\\\\.\\\\d+\")) {\n      // Note: SCORM 2004 4th Edition adl.data extension\n      // Per strict spec, adl.data elements should be LMS-created and\n      // SCOs should only access indices < _count. However, we intentionally\n      // allow dynamic creation for backward compatibility with content that\n      // creates adl.data elements on-the-fly.\n      return new ADLDataObject(true);\n    }\n\n    return null;\n  }\n\n  /**\n   * Creates a correct responses object for an interaction\n   *\n   * @param {string} CMIElement - The CMI element path\n   * @param {any} value - The value being set\n   * @return {BaseCMI|null} The correct responses object or null\n   */\n  createCorrectResponsesObject(CMIElement: string, value: any): BaseCMI | null {\n    const parts = CMIElement.split(\".\");\n    const index = Number(parts[2]);\n    const interaction = this.context.cmi.interactions.childArray[index] as\n      CMIInteractionsObject | undefined;\n\n    if (this.context.isInitialized()) {\n      if (typeof interaction === \"undefined\" || !interaction.type) {\n        this.context.throwSCORMError(\n          CMIElement,\n          scorm2004_errors.DEPENDENCY_NOT_ESTABLISHED!,\n          CMIElement,\n        );\n        return null;\n      } else {\n        const interaction_count = interaction.correct_responses._count;\n        const response_type = CorrectResponses[interaction.type];\n\n        // Check if limit is exceeded\n        if (\n          response_type &&\n          typeof response_type.limit !== \"undefined\" &&\n          interaction_count >= response_type.limit\n        ) {\n          this.context.throwSCORMError(\n            CMIElement,\n            scorm2004_errors.GENERAL_SET_FAILURE!,\n            `Data Model Element Collection Limit Reached: ${CMIElement}`,\n          );\n          return null;\n        }\n\n        this.responseValidator.checkDuplicateChoiceResponse(CMIElement, interaction, value);\n        if (response_type) {\n          this.responseValidator.checkValidResponseType(\n            CMIElement,\n            response_type,\n            value,\n            interaction.type,\n          );\n        } else {\n          this.context.throwSCORMError(\n            CMIElement,\n            scorm2004_errors.GENERAL_SET_FAILURE!,\n            `Incorrect Response Type: ${interaction.type}`,\n          );\n          return null;\n        }\n      }\n    }\n\n    if (this.context.getLastErrorCode() === \"0\") {\n      return new CMIInteractionsCorrectResponsesObject(interaction?.type);\n    }\n\n    return null;\n  }\n\n  /**\n   * Evaluates completion_status per SCORM 2004 RTE Table 4.2.4.1a\n   *\n   * Rules:\n   * 1. If completion_threshold is defined AND progress_measure is set:\n   *    - Return \"completed\" if progress_measure >= completion_threshold\n   *    - Return \"incomplete\" if progress_measure < completion_threshold\n   * 2. If completion_threshold is defined but progress_measure is NOT set:\n   *    - Return \"unknown\"\n   * 3. Otherwise:\n   *    - Return the SCO-set value (or \"unknown\" if not set)\n   *\n   * @returns {string} The evaluated completion status\n   */\n  evaluateCompletionStatus(): string {\n    return evaluateCompletionStatusFromThreshold({\n      completionThreshold: this.context.cmi.completion_threshold,\n      progressMeasure: this.context.cmi.progress_measure,\n      storedCompletionStatus: this.context.cmi.completion_status,\n    });\n  }\n\n  /**\n   * Evaluates success_status per SCORM 2004 RTE Table 4.2.21.1a\n   *\n   * Rules:\n   * 1. If scaled_passing_score is defined AND score.scaled is set:\n   *    - Return \"passed\" if score.scaled >= scaled_passing_score\n   *    - Return \"failed\" if score.scaled < scaled_passing_score\n   * 2. If scaled_passing_score is defined but score.scaled is NOT set:\n   *    - Return \"unknown\"\n   * 3. Otherwise:\n   *    - Return the SCO-set value (or \"unknown\" if not set)\n   *\n   * @returns {string} The evaluated success status\n   */\n  evaluateSuccessStatus(): string {\n    const scaledPassingScore = this.context.cmi.scaled_passing_score;\n    const scaledScore = this.context.cmi.score.scaled;\n    const storedStatus = this.context.cmi.success_status;\n\n    // If scaled_passing_score is defined\n    if (\n      scaledPassingScore !== \"\" &&\n      scaledPassingScore !== null &&\n      scaledPassingScore !== undefined\n    ) {\n      const passingScoreValue = parseFloat(String(scaledPassingScore));\n\n      if (!isNaN(passingScoreValue)) {\n        // Check if score.scaled is set\n        if (scaledScore !== \"\" && scaledScore !== null && scaledScore !== undefined) {\n          const scoreValue = parseFloat(String(scaledScore));\n\n          if (!isNaN(scoreValue)) {\n            // Evaluate based on threshold comparison\n            return scoreValue >= passingScoreValue ? SuccessStatus.PASSED : SuccessStatus.FAILED;\n          }\n        }\n\n        // scaled_passing_score is defined but score.scaled is not set\n        return SuccessStatus.UNKNOWN;\n      }\n    }\n\n    // No scaled_passing_score defined - return stored value\n    return storedStatus || SuccessStatus.UNKNOWN;\n  }\n}\n","import { SequencingControls } from \"../cmi/scorm2004/sequencing/sequencing_controls\";\nimport {\n  RuleCondition,\n  SequencingRule,\n  SequencingRules,\n} from \"../cmi/scorm2004/sequencing/sequencing_rules\";\nimport { RollupCondition, RollupRule, RollupRules } from \"../cmi/scorm2004/sequencing/rollup_rules\";\nimport {\n  AuxiliaryResource,\n  AuxiliaryResourceSettings,\n  HIDE_LMS_UI_TOKENS,\n  HideLmsUiItem,\n  RollupConditionSettings,\n  RollupRuleSettings,\n  RollupRulesSettings,\n  RuleConditionSettings,\n  SelectionRandomizationStateSettings,\n  SequencingCollectionSettings,\n  SequencingControlsSettings,\n  SequencingRuleSettings,\n  SequencingRulesSettings,\n} from \"../types/sequencing_types\";\nimport { Activity } from \"../cmi/scorm2004/sequencing/activity\";\n\n/**\n * Builds and configures SCORM 2004 sequencing rules, controls, and collections\n *\n * This class is responsible for:\n * - Applying sequencing controls settings\n * - Creating and configuring sequencing rules\n * - Creating and configuring rollup rules\n * - Sanitizing sequencing collections\n * - Managing HideLmsUi and auxiliary resources\n */\nexport class SequencingConfigurationBuilder {\n  /**\n   * Applies the given sequencing controls settings to the specified target.\n   *\n   * @param {SequencingControls} target - The target object where sequencing control settings will be applied.\n   * @param {SequencingControlsSettings} settings - An object containing the sequencing control settings to be applied to the target.\n   * @return {void} - No return value as the method modifies the target object directly.\n   */\n  applySequencingControlsSettings(\n    target: SequencingControls,\n    settings: SequencingControlsSettings,\n  ): void {\n    if (settings.enabled !== undefined) {\n      target.enabled = settings.enabled;\n    }\n    if (settings.choice !== undefined) {\n      target.choice = settings.choice;\n    }\n    if (settings.choiceExit !== undefined) {\n      target.choiceExit = settings.choiceExit;\n    }\n    if (settings.flow !== undefined) {\n      target.flow = settings.flow;\n    }\n    if (settings.forwardOnly !== undefined) {\n      target.forwardOnly = settings.forwardOnly;\n    }\n    if (settings.useCurrentAttemptObjectiveInfo !== undefined) {\n      target.useCurrentAttemptObjectiveInfo = settings.useCurrentAttemptObjectiveInfo;\n    }\n    if (settings.useCurrentAttemptProgressInfo !== undefined) {\n      target.useCurrentAttemptProgressInfo = settings.useCurrentAttemptProgressInfo;\n    }\n    if (settings.preventActivation !== undefined) {\n      target.preventActivation = settings.preventActivation;\n    }\n    if (settings.constrainChoice !== undefined) {\n      target.constrainChoice = settings.constrainChoice;\n    }\n    if (settings.stopForwardTraversal !== undefined) {\n      target.stopForwardTraversal = settings.stopForwardTraversal;\n    }\n    if (settings.rollupObjectiveSatisfied !== undefined) {\n      target.rollupObjectiveSatisfied = settings.rollupObjectiveSatisfied;\n    }\n    if (settings.rollupProgressCompletion !== undefined) {\n      target.rollupProgressCompletion = settings.rollupProgressCompletion;\n    }\n    if (settings.objectiveMeasureWeight !== undefined) {\n      target.objectiveMeasureWeight = settings.objectiveMeasureWeight;\n    }\n    if (settings.selectionTiming !== undefined) {\n      target.selectionTiming = settings.selectionTiming;\n    }\n    if (settings.selectCount !== undefined) {\n      target.selectCount = settings.selectCount;\n    }\n    if (settings.randomizeChildren !== undefined) {\n      target.randomizeChildren = settings.randomizeChildren;\n    }\n    if (settings.randomizationTiming !== undefined) {\n      target.randomizationTiming = settings.randomizationTiming;\n    }\n    if (settings.selectionCountStatus !== undefined) {\n      target.selectionCountStatus = settings.selectionCountStatus;\n    }\n    if (settings.reorderChildren !== undefined) {\n      target.reorderChildren = settings.reorderChildren;\n    }\n    if (settings.completionSetByContent !== undefined) {\n      target.completionSetByContent = settings.completionSetByContent;\n    }\n    if (settings.objectiveSetByContent !== undefined) {\n      target.objectiveSetByContent = settings.objectiveSetByContent;\n    }\n    if (settings.tracked !== undefined) {\n      target.tracked = settings.tracked;\n    }\n  }\n\n  /**\n   * Applies the sequencing rules settings to the specified target object.\n   *\n   * @param {SequencingRules} target The target object where the sequencing rules will be applied.\n   * @param {SequencingRulesSettings} settings The settings object containing the sequencing rules to be applied. If null or undefined, no rules will be applied.\n   * @return {void} This method does not return a value.\n   */\n  applySequencingRulesSettings(target: SequencingRules, settings: SequencingRulesSettings): void {\n    if (!settings) {\n      return;\n    }\n\n    if (settings.preConditionRules) {\n      for (const ruleSettings of settings.preConditionRules) {\n        const rule = this.createSequencingRule(ruleSettings);\n        target.addPreConditionRule(rule);\n      }\n    }\n\n    if (settings.exitConditionRules) {\n      for (const ruleSettings of settings.exitConditionRules) {\n        const rule = this.createSequencingRule(ruleSettings);\n        target.addExitConditionRule(rule);\n      }\n    }\n\n    if (settings.postConditionRules) {\n      for (const ruleSettings of settings.postConditionRules) {\n        const rule = this.createSequencingRule(ruleSettings);\n        target.addPostConditionRule(rule);\n      }\n    }\n  }\n\n  /**\n   * Create a sequencing rule from settings\n   * @param {SequencingRuleSettings} ruleSettings - The sequencing rule settings\n   * @return {SequencingRule} - The created sequencing rule\n   */\n  createSequencingRule(ruleSettings: SequencingRuleSettings): SequencingRule {\n    // Create rule\n    const rule = new SequencingRule(ruleSettings.action, ruleSettings.conditionCombination);\n\n    // Add conditions\n    for (const conditionSettings of ruleSettings.conditions) {\n      const condition = new RuleCondition(\n        conditionSettings.condition,\n        conditionSettings.operator,\n        new Map(Object.entries(conditionSettings.parameters || {})),\n      );\n      if (conditionSettings.referencedObjective) {\n        condition.referencedObjective = conditionSettings.referencedObjective;\n      }\n      rule.addCondition(condition);\n    }\n\n    return rule;\n  }\n\n  /**\n   * Applies rollup rules settings to the specified target object.\n   * This method processes the provided settings and adds the corresponding\n   * rollup rules to the target.\n   *\n   * @param {RollupRules} target - The target object where rollup rules will be applied.\n   * @param {RollupRulesSettings} settings - The settings containing the rollup rules to be applied.\n   * @return {void} This method does not return a value.\n   */\n  applyRollupRulesSettings(target: RollupRules, settings: RollupRulesSettings): void {\n    if (!settings?.rules) {\n      return;\n    }\n\n    for (const ruleSettings of settings.rules) {\n      const rule = this.createRollupRule(ruleSettings);\n      target.addRule(rule);\n    }\n  }\n\n  /**\n   * Create a rollup rule from settings\n   * @param {RollupRuleSettings} ruleSettings - The rollup rule settings\n   * @return {RollupRule} - The created rollup rule\n   */\n  createRollupRule(ruleSettings: RollupRuleSettings): RollupRule {\n    // Create rule\n    const rule = new RollupRule(\n      ruleSettings.action,\n      ruleSettings.consideration,\n      ruleSettings.minimumCount,\n      ruleSettings.minimumPercent,\n      ruleSettings.conditionCombination,\n    );\n\n    // Add conditions\n    for (const conditionSettings of ruleSettings.conditions) {\n      const condition = new RollupCondition(\n        conditionSettings.condition,\n        new Map(Object.entries(conditionSettings.parameters || {})),\n        conditionSettings.operator,\n      );\n      rule.addCondition(condition);\n    }\n\n    return rule;\n  }\n\n  /**\n   * Sanitizes and processes a collection of sequencing settings. This involves ensuring that\n   * the IDs are trimmed and non-empty, cloning objects deeply to ensure immutability,\n   * and sanitizing each subset of sequencing configurations.\n   *\n   * @param {Record<string, SequencingCollectionSettings>} [collections] -\n   *        A record of sequencing collection settings where keys are collection IDs\n   *        and values are the associated configuration to be sanitized.\n   *\n   * @return {Record<string, SequencingCollectionSettings>}\n   *         A sanitized record of sequencing collection settings, with processed and\n   *         cloned settings for immutability and validity.\n   */\n  sanitizeSequencingCollections(\n    collections?: Record<string, SequencingCollectionSettings> | SequencingCollectionSettings[],\n  ): Record<string, SequencingCollectionSettings> {\n    if (!collections) {\n      return {};\n    }\n\n    const sanitized: Record<string, SequencingCollectionSettings> = {};\n    // @spec SCORM 2004 SN 3.3.2 Sequencing Collection - accept the serialized\n    // collection form ({ id, ...definition }) as well as the keyed host form.\n    const entries: Array<[string, SequencingCollectionSettings]> = Array.isArray(collections)\n      ? collections.map((collection) => [collection.id ?? \"\", collection])\n      : Object.entries(collections);\n\n    for (const [id, collection] of entries) {\n      const trimmedId = id.trim();\n      if (!trimmedId) {\n        continue;\n      }\n\n      const sanitizedCollection: SequencingCollectionSettings = {};\n\n      const cloneObjective = (objective: typeof collection.primaryObjective) => {\n        if (!objective) {\n          return undefined;\n        }\n        const cloned = { ...objective };\n        if (objective.mapInfo) {\n          cloned.mapInfo = objective.mapInfo.map((mapping) => ({ ...mapping }));\n        }\n        return cloned;\n      };\n\n      const primaryObjective = cloneObjective(collection.primaryObjective);\n      if (primaryObjective) {\n        sanitizedCollection.primaryObjective = primaryObjective;\n      }\n      if (collection.objectives) {\n        sanitizedCollection.objectives = collection.objectives\n          .map((objective) => cloneObjective(objective))\n          .filter((objective) => objective !== undefined);\n      }\n\n      if (collection.sequencingControls) {\n        sanitizedCollection.sequencingControls = { ...collection.sequencingControls };\n      }\n      if (collection.sequencingRules) {\n        const ruleClone = (rule: SequencingRuleSettings): SequencingRuleSettings => {\n          const cloned: SequencingRuleSettings = {\n            action: rule.action,\n            conditions: rule.conditions.map((condition) => {\n              const clonedCondition: RuleConditionSettings = {\n                condition: condition.condition,\n              };\n              if (condition.operator !== undefined) {\n                clonedCondition.operator = condition.operator;\n              }\n              if (condition.parameters) {\n                clonedCondition.parameters = { ...condition.parameters };\n              }\n              if (condition.referencedObjective !== undefined) {\n                clonedCondition.referencedObjective = condition.referencedObjective;\n              }\n              return clonedCondition;\n            }),\n          };\n          if (rule.conditionCombination !== undefined) {\n            cloned.conditionCombination = rule.conditionCombination;\n          }\n          return cloned;\n        };\n\n        sanitizedCollection.sequencingRules = {};\n        if (collection.sequencingRules.preConditionRules) {\n          sanitizedCollection.sequencingRules.preConditionRules =\n            collection.sequencingRules.preConditionRules.map(ruleClone);\n        }\n        if (collection.sequencingRules.exitConditionRules) {\n          sanitizedCollection.sequencingRules.exitConditionRules =\n            collection.sequencingRules.exitConditionRules.map(ruleClone);\n        }\n        if (collection.sequencingRules.postConditionRules) {\n          sanitizedCollection.sequencingRules.postConditionRules =\n            collection.sequencingRules.postConditionRules.map(ruleClone);\n        }\n      }\n\n      if (collection.rollupRules) {\n        sanitizedCollection.rollupRules = {\n          rules: collection.rollupRules.rules?.map((rule) => {\n            const clonedRule: RollupRuleSettings = {\n              action: rule.action,\n              conditions: rule.conditions.map((condition) => {\n                const clonedCondition: RollupConditionSettings = {\n                  condition: condition.condition,\n                };\n                if (condition.parameters) {\n                  clonedCondition.parameters = { ...condition.parameters };\n                }\n                if (condition.operator !== undefined) {\n                  clonedCondition.operator = condition.operator;\n                }\n                return clonedCondition;\n              }),\n            };\n            if (rule.conditionCombination !== undefined) {\n              clonedRule.conditionCombination = rule.conditionCombination;\n            }\n            if (rule.consideration !== undefined) {\n              clonedRule.consideration = rule.consideration;\n            }\n            if (rule.minimumCount !== undefined) {\n              clonedRule.minimumCount = rule.minimumCount;\n            }\n            if (rule.minimumPercent !== undefined) {\n              clonedRule.minimumPercent = rule.minimumPercent;\n            }\n            return clonedRule;\n          }),\n        };\n      }\n\n      if (collection.rollupConsiderations) {\n        sanitizedCollection.rollupConsiderations = { ...collection.rollupConsiderations };\n      }\n\n      if (collection.selectionRandomizationState) {\n        sanitizedCollection.selectionRandomizationState = this.cloneSelectionRandomizationState(\n          collection.selectionRandomizationState,\n        );\n      }\n\n      if (collection.hideLmsUi) {\n        sanitizedCollection.hideLmsUi = this.sanitizeHideLmsUi(collection.hideLmsUi);\n      }\n\n      if (collection.auxiliaryResources) {\n        sanitizedCollection.auxiliaryResources = this.sanitizeAuxiliaryResources(\n          collection.auxiliaryResources,\n        );\n      }\n\n      sanitized[trimmedId] = sanitizedCollection;\n    }\n\n    return sanitized;\n  }\n\n  /**\n   * Normalizes the provided collection references into an array of unique, trimmed strings.\n   * Removes duplicates and trims whitespace from each reference.\n   *\n   * @param {string | string[]} [refs] - A single reference string or an array of reference strings to be normalized.\n   *                                      If not provided, defaults to an empty array.\n   * @return {string[]} An array of unique and trimmed strings representing normalized collection references.\n   */\n  normalizeCollectionRefs(refs?: string | string[]): string[] {\n    if (!refs) {\n      return [];\n    }\n\n    const raw = Array.isArray(refs) ? refs : [refs];\n    const seen = new Set<string>();\n    const result: string[] = [];\n\n    for (const ref of raw) {\n      const trimmed = ref.trim();\n      if (!trimmed || seen.has(trimmed)) {\n        continue;\n      }\n      seen.add(trimmed);\n      result.push(trimmed);\n    }\n\n    return result;\n  }\n\n  /**\n   * Applies the sequencing configuration from the given collection to the specified activity.\n   *\n   * @param {Activity} activity - The activity to which the sequencing collection settings will be applied.\n   * @param {SequencingCollectionSettings} collection - The collection of sequencing settings to apply to the activity.\n   * @param {SelectionRandomizationStateSettings[]} selectionStates - The list of selection randomization state objects, which may be modified during this process.\n   * @return {void} This method does not return a value.\n   */\n  applySequencingCollection(\n    activity: Activity,\n    collection: SequencingCollectionSettings,\n    selectionStates: SelectionRandomizationStateSettings[],\n    inlineSequencingRules: boolean = false,\n  ): void {\n    if (!collection) {\n      return;\n    }\n\n    if (collection.sequencingControls) {\n      this.applySequencingControlsSettings(\n        activity.sequencingControls,\n        collection.sequencingControls,\n      );\n    }\n\n    // @spec SCORM 2004 SN 2.1.2: inline top-level Sequencing Information takes\n    // precedence over the same top-level element in a referenced collection.\n    if (collection.sequencingRules && !inlineSequencingRules) {\n      this.applySequencingRulesSettings(activity.sequencingRules, collection.sequencingRules);\n    }\n\n    if (collection.rollupRules) {\n      this.applyRollupRulesSettings(activity.rollupRules, collection.rollupRules);\n    }\n\n    if (collection.rollupConsiderations) {\n      activity.applyRollupConsiderations(collection.rollupConsiderations);\n    }\n\n    if (collection.hideLmsUi) {\n      const merged = this.mergeHideLmsUi(activity.hideLmsUi, collection.hideLmsUi);\n      if (merged.length > 0) {\n        activity.hideLmsUi = merged;\n      }\n    }\n\n    if (collection.auxiliaryResources) {\n      const sanitizedAux = this.sanitizeAuxiliaryResources(collection.auxiliaryResources);\n      if (sanitizedAux.length > 0) {\n        activity.auxiliaryResources = this.mergeAuxiliaryResources(\n          activity.auxiliaryResources,\n          sanitizedAux,\n        );\n      }\n    }\n\n    if (collection.selectionRandomizationState) {\n      selectionStates.push(\n        this.cloneSelectionRandomizationState(collection.selectionRandomizationState),\n      );\n    }\n  }\n\n  /**\n   * Filters and sanitizes a list of items by removing duplicates and ensuring\n   * only valid items are included according to a predefined set of valid tokens.\n   *\n   * @param {HideLmsUiItem[] | undefined} items - The list of items to be sanitized.\n   * Can be undefined, in which case an empty array is returned.\n   * @return {HideLmsUiItem[]} The sanitized list of unique and valid items.\n   */\n  sanitizeHideLmsUi(items: HideLmsUiItem[] | undefined): HideLmsUiItem[] {\n    if (!items) {\n      return [];\n    }\n\n    const valid = new Set(HIDE_LMS_UI_TOKENS);\n    const seen = new Set<HideLmsUiItem>();\n    const sanitized: HideLmsUiItem[] = [];\n\n    for (const item of items) {\n      if (valid.has(item) && !seen.has(item)) {\n        seen.add(item);\n        sanitized.push(item);\n      }\n    }\n\n    return sanitized;\n  }\n\n  /**\n   * Merges the current array of HideLmsUiItem objects with an optional additional array,\n   * and sanitizes the combined result.\n   *\n   * @param {HideLmsUiItem[]} current - The current array of HideLmsUiItem objects.\n   * @param {HideLmsUiItem[]} [additional] - An optional array of additional HideLmsUiItem objects to merge.\n   * @return {HideLmsUiItem[]} The sanitized merged array of HideLmsUiItem objects.\n   */\n  mergeHideLmsUi(current: HideLmsUiItem[], additional?: HideLmsUiItem[]): HideLmsUiItem[] {\n    if (!additional || additional.length === 0) {\n      return current;\n    }\n    return this.sanitizeHideLmsUi([...current, ...additional]);\n  }\n\n  /**\n   * Sanitizes and filters the given auxiliary resources by removing duplicates,\n   * trimming unnecessary whitespace, and ensuring valid data integrity.\n   *\n   * @param {AuxiliaryResourceSettings[]} [resources] - An optional array of auxiliary resource settings\n   *     that include details such as resource ID and purpose.\n   * @return {AuxiliaryResource[]} - A sanitized array of auxiliary resources, each containing\n   *     valid resource IDs and purposes, with duplicates and invalid entries removed.\n   */\n  sanitizeAuxiliaryResources(resources?: AuxiliaryResourceSettings[]): AuxiliaryResource[] {\n    if (!resources) {\n      return [];\n    }\n\n    const seen = new Set<string>();\n    const sanitized: AuxiliaryResource[] = [];\n\n    for (const resource of resources) {\n      if (!resource) continue;\n\n      // Type-safe null/undefined checks before calling trim()\n      if (!resource.resourceId || typeof resource.resourceId !== \"string\") continue;\n      if (!resource.purpose || typeof resource.purpose !== \"string\") continue;\n\n      const resourceId = resource.resourceId.trim();\n      const purpose = resource.purpose.trim();\n\n      if (!resourceId || !purpose) continue;\n\n      const key = `${resourceId}::${purpose}`;\n      if (!seen.has(key)) {\n        seen.add(key);\n        sanitized.push({ resourceId, purpose });\n      }\n    }\n\n    return sanitized;\n  }\n\n  /**\n   * Merges two arrays of auxiliary resources, removing duplicates based on their resource identifiers.\n   *\n   * @param {AuxiliaryResource[] | undefined} existing - The existing array of auxiliary resources. This can be undefined.\n   * @param {AuxiliaryResource[] | undefined} additions - The array of new auxiliary resources to add. This can be undefined.\n   * @return {AuxiliaryResource[]} A new array containing unique auxiliary resources from both input arrays, filtered by their resource identifiers.\n   */\n  mergeAuxiliaryResources(\n    existing: AuxiliaryResource[] | undefined,\n    additions: AuxiliaryResource[] | undefined,\n  ): AuxiliaryResource[] {\n    const merged: AuxiliaryResource[] = [];\n    const seen = new Set<string>();\n\n    for (const resource of [...(existing ?? []), ...(additions ?? [])]) {\n      if (!resource) {\n        continue;\n      }\n      const resourceId = resource.resourceId;\n      if (!resourceId || seen.has(resourceId)) {\n        continue;\n      }\n      seen.add(resourceId);\n      merged.push({ resourceId, purpose: resource.purpose });\n    }\n\n    return merged;\n  }\n\n  /**\n   * Clones the given SelectionRandomizationStateSettings object, creating a new object with identical properties.\n   *\n   * @param {SelectionRandomizationStateSettings} state - The SelectionRandomizationStateSettings object to be cloned.\n   * @return {SelectionRandomizationStateSettings} A new instance of SelectionRandomizationStateSettings with the same properties as the input object.\n   */\n  cloneSelectionRandomizationState(\n    state: SelectionRandomizationStateSettings,\n  ): SelectionRandomizationStateSettings {\n    const clone: SelectionRandomizationStateSettings = {};\n    if (state.childOrder) {\n      clone.childOrder = [...state.childOrder];\n    }\n    if (state.selectedChildIds) {\n      clone.selectedChildIds = [...state.selectedChildIds];\n    }\n    if (state.hiddenFromChoiceChildIds) {\n      clone.hiddenFromChoiceChildIds = [...state.hiddenFromChoiceChildIds];\n    }\n    if (state.selectionCountStatus !== undefined) {\n      clone.selectionCountStatus = state.selectionCountStatus;\n    }\n    if (state.reorderChildren !== undefined) {\n      clone.reorderChildren = state.reorderChildren;\n    }\n    return clone;\n  }\n\n  /**\n   * Applies the selection randomization state to the given activity by updating its sequencing controls\n   * and configuring visibility, availability, and order of its child elements.\n   *\n   * @param {Activity} activity - The activity to which the selection randomization state is applied.\n   * @param {SelectionRandomizationStateSettings} state - The settings object defining the selection\n   * randomization state, including properties for selection count status, child order, reorder controls,\n   * selected child IDs, and hidden child IDs.\n   * @return {void} This method does not return a value.\n   */\n  applySelectionRandomizationState(\n    activity: Activity,\n    state: SelectionRandomizationStateSettings,\n  ): void {\n    const sequencingControls = activity.sequencingControls;\n\n    if (state.selectionCountStatus !== undefined) {\n      sequencingControls.selectionCountStatus = state.selectionCountStatus;\n    }\n\n    if (state.reorderChildren !== undefined) {\n      sequencingControls.reorderChildren = state.reorderChildren;\n    }\n\n    const selectedSet = state.selectedChildIds ? new Set(state.selectedChildIds) : null;\n    const hiddenSet = state.hiddenFromChoiceChildIds\n      ? new Set(state.hiddenFromChoiceChildIds)\n      : null;\n\n    if (state.childOrder && state.childOrder.length > 0) {\n      activity.setChildOrder(state.childOrder);\n    }\n\n    let selectionTouched = false;\n\n    if (selectedSet || hiddenSet) {\n      for (const child of activity.children) {\n        if (selectedSet) {\n          const isSelected = selectedSet.has(child.id);\n          child.isAvailable = isSelected;\n          if (!hiddenSet) {\n            child.isHiddenFromChoice = !isSelected;\n          }\n          selectionTouched = true;\n        }\n\n        if (hiddenSet) {\n          child.isHiddenFromChoice = hiddenSet.has(child.id);\n          selectionTouched = true;\n        }\n      }\n    }\n\n    const shouldSetProcessedChildren =\n      selectionTouched ||\n      !!selectedSet ||\n      state.selectionCountStatus !== undefined ||\n      state.reorderChildren !== undefined ||\n      (state.childOrder && state.childOrder.length > 0);\n\n    if (shouldSetProcessedChildren) {\n      activity.setProcessedChildren(activity.children.filter((child) => child.isAvailable));\n    }\n  }\n}\n","import {\n  Activity,\n  ActivityObjective,\n  ObjectiveMapInfo,\n} from \"../cmi/scorm2004/sequencing/activity\";\nimport {\n  ActivitySettings,\n  ObjectiveSettings,\n  SelectionRandomizationStateSettings,\n  SequencingCollectionSettings,\n} from \"../types/sequencing_types\";\nimport { SequencingConfigurationBuilder } from \"./sequencing_configuration_builder\";\n\n/**\n * Builds and configures SCORM 2004 activity trees from settings\n *\n * This class is responsible for:\n * - Creating activities from settings\n * - Extracting activity IDs from the tree\n * - Creating activity objectives from settings\n * - Managing selection randomization state\n */\nexport class ActivityTreeBuilder {\n  private sequencingCollections: Record<string, SequencingCollectionSettings>;\n  private sequencingConfigBuilder: SequencingConfigurationBuilder;\n\n  constructor(\n    collections?: Record<string, SequencingCollectionSettings>,\n    sequencingConfigBuilder?: SequencingConfigurationBuilder,\n  ) {\n    this.sequencingCollections = collections || {};\n    this.sequencingConfigBuilder = sequencingConfigBuilder || new SequencingConfigurationBuilder();\n  }\n\n  /**\n   * Updates the sequencing collections\n   * @param {Record<string, SequencingCollectionSettings>} collections - The new collections\n   */\n  setSequencingCollections(collections: Record<string, SequencingCollectionSettings>): void {\n    this.sequencingCollections = collections;\n  }\n\n  /**\n   * Create an activity from settings\n   * @param {ActivitySettings} activitySettings - The activity settings\n   * @return {Activity} - The created activity\n   */\n  createActivity(activitySettings: ActivitySettings): Activity {\n    // Create activity\n    const activity = new Activity(activitySettings.id, activitySettings.title);\n\n    const selectionStates: SelectionRandomizationStateSettings[] = [];\n    const collectionRefs = this.sequencingConfigBuilder.normalizeCollectionRefs(\n      activitySettings.sequencingCollectionRefs ?? activitySettings.sequencingIdRef,\n    );\n    const objectiveSettings = new Map<string, ObjectiveSettings>();\n    let primaryObjectiveId: string | null = null;\n\n    const mergeObjectiveSettings = (\n      incoming: ObjectiveSettings | undefined,\n      isPrimary: boolean,\n    ): void => {\n      const objectiveId =\n        incoming?.objectiveID ??\n        (incoming as (ObjectiveSettings & { id?: string }) | undefined)?.id;\n      if (!incoming || !objectiveId) {\n        return;\n      }\n      const existing = objectiveSettings.get(objectiveId);\n      objectiveSettings.set(objectiveId, {\n        ...existing,\n        ...incoming,\n        objectiveID: objectiveId,\n        mapInfo: [...(existing?.mapInfo ?? []), ...(incoming.mapInfo ?? [])],\n      });\n      if (isPrimary) {\n        primaryObjectiveId = objectiveId;\n      }\n    };\n\n    for (const ref of collectionRefs) {\n      const collection = this.sequencingCollections[ref];\n      if (collection) {\n        this.sequencingConfigBuilder.applySequencingCollection(\n          activity,\n          collection,\n          selectionStates,\n          activitySettings.sequencingRules !== undefined,\n        );\n        // @spec SCORM 2004 SN 3.3.2 / 3.10.3 - a referenced sequencing\n        // collection contributes its objective definitions and mapInfo to the activity.\n        mergeObjectiveSettings(collection.primaryObjective, true);\n        for (const objective of collection.objectives ?? []) {\n          mergeObjectiveSettings(objective, objective.isPrimary === true);\n        }\n      }\n    }\n\n    // Set activity properties\n    if (activitySettings.isVisible !== undefined) {\n      activity.isVisible = activitySettings.isVisible;\n    }\n    if (activitySettings.isActive !== undefined) {\n      activity.isActive = activitySettings.isActive;\n    }\n    if (activitySettings.isSuspended !== undefined) {\n      activity.isSuspended = activitySettings.isSuspended;\n    }\n    if (activitySettings.isCompleted !== undefined) {\n      activity.isCompleted = activitySettings.isCompleted;\n    }\n    if (activitySettings.isHiddenFromChoice !== undefined) {\n      activity.isHiddenFromChoice = activitySettings.isHiddenFromChoice;\n    }\n    if (activitySettings.isAvailable !== undefined) {\n      activity.isAvailable = activitySettings.isAvailable;\n    }\n    if (activitySettings.attemptLimit !== undefined) {\n      activity.attemptLimit = activitySettings.attemptLimit;\n    }\n    if (activitySettings.attemptAbsoluteDurationLimit !== undefined) {\n      activity.attemptAbsoluteDurationLimit = activitySettings.attemptAbsoluteDurationLimit;\n    }\n    if (activitySettings.activityAbsoluteDurationLimit !== undefined) {\n      activity.activityAbsoluteDurationLimit = activitySettings.activityAbsoluteDurationLimit;\n    }\n    if (activitySettings.timeLimitAction !== undefined) {\n      activity.timeLimitAction = activitySettings.timeLimitAction;\n    }\n    if (activitySettings.timeLimitDuration !== undefined) {\n      activity.timeLimitDuration = activitySettings.timeLimitDuration;\n    }\n    if (activitySettings.beginTimeLimit !== undefined) {\n      activity.beginTimeLimit = activitySettings.beginTimeLimit;\n    }\n    if (activitySettings.endTimeLimit !== undefined) {\n      activity.endTimeLimit = activitySettings.endTimeLimit;\n    }\n\n    // Inline objective settings are applied last, while collection and inline\n    // mapInfo entries for the same local objective remain additive.\n    mergeObjectiveSettings(activitySettings.primaryObjective, true);\n    for (const objective of activitySettings.objectives ?? []) {\n      mergeObjectiveSettings(objective, objective.isPrimary === true);\n    }\n\n    if (primaryObjectiveId) {\n      const primarySettings = objectiveSettings.get(primaryObjectiveId);\n      if (primarySettings) {\n        const primaryObjective = this.createActivityObjectiveFromSettings(primarySettings, true);\n        activity.primaryObjective = primaryObjective;\n        if (primaryObjective.minNormalizedMeasure !== null) {\n          activity.scaledPassingScore = primaryObjective.minNormalizedMeasure;\n        }\n      }\n    }\n\n    for (const [objectiveId, settings] of objectiveSettings) {\n      if (objectiveId !== primaryObjectiveId) {\n        activity.addObjective(this.createActivityObjectiveFromSettings(settings, false));\n      }\n    }\n\n    if (activitySettings.sequencingControls) {\n      this.sequencingConfigBuilder.applySequencingControlsSettings(\n        activity.sequencingControls,\n        activitySettings.sequencingControls,\n      );\n    }\n    if (activitySettings.deliveryControls) {\n      this.sequencingConfigBuilder.applySequencingControlsSettings(\n        activity.sequencingControls,\n        activitySettings.deliveryControls,\n      );\n    }\n\n    if (activitySettings.sequencingRules) {\n      this.sequencingConfigBuilder.applySequencingRulesSettings(\n        activity.sequencingRules,\n        activitySettings.sequencingRules,\n      );\n    }\n\n    if (activitySettings.rollupRules) {\n      this.sequencingConfigBuilder.applyRollupRulesSettings(\n        activity.rollupRules,\n        activitySettings.rollupRules,\n      );\n    }\n\n    if (activitySettings.rollupConsiderations) {\n      activity.applyRollupConsiderations(activitySettings.rollupConsiderations);\n    }\n\n    if (activitySettings.completionThreshold) {\n      const threshold = activitySettings.completionThreshold;\n\n      if (threshold.completedByMeasure !== undefined) {\n        activity.completedByMeasure = threshold.completedByMeasure;\n      }\n      if (threshold.minProgressMeasure !== undefined) {\n        activity.minProgressMeasure = threshold.minProgressMeasure;\n      }\n      // A schema-default minimum is inert unless this activity derives completion from measure.\n      if (activity.completedByMeasure) {\n        activity.completionThreshold = activity.minProgressMeasure.toString();\n      }\n      if (threshold.progressWeight !== undefined) {\n        activity.progressWeight = threshold.progressWeight;\n      }\n    }\n\n    if (activitySettings.hideLmsUi) {\n      const mergedHide = this.sequencingConfigBuilder.mergeHideLmsUi(\n        activity.hideLmsUi,\n        activitySettings.hideLmsUi,\n      );\n      if (mergedHide.length > 0) {\n        activity.hideLmsUi = mergedHide;\n      }\n    }\n\n    if (activitySettings.auxiliaryResources) {\n      const sanitizedAux = this.sequencingConfigBuilder.sanitizeAuxiliaryResources(\n        activitySettings.auxiliaryResources,\n      );\n      if (sanitizedAux.length > 0) {\n        activity.auxiliaryResources = this.sequencingConfigBuilder.mergeAuxiliaryResources(\n          activity.auxiliaryResources,\n          sanitizedAux,\n        );\n      }\n    }\n\n    if (activitySettings.sharedDataMaps) {\n      activity.sharedDataMaps = activitySettings.sharedDataMaps.map((map) => ({\n        targetID: map.targetID,\n        readSharedData: map.readSharedData ?? true,\n        writeSharedData: map.writeSharedData ?? false,\n      }));\n    }\n\n    // Create child activities\n    if (activitySettings.children) {\n      for (const childSettings of activitySettings.children) {\n        const childActivity = this.createActivity(childSettings);\n        activity.addChild(childActivity);\n      }\n    }\n\n    if (activitySettings.selectionRandomizationState) {\n      selectionStates.push(\n        this.sequencingConfigBuilder.cloneSelectionRandomizationState(\n          activitySettings.selectionRandomizationState,\n        ),\n      );\n    }\n\n    for (const state of selectionStates) {\n      this.sequencingConfigBuilder.applySelectionRandomizationState(activity, state);\n    }\n\n    return activity;\n  }\n\n  /**\n   * Extract all activity IDs from an activity and its children\n   * @param {Activity} activity - The activity to extract IDs from\n   * @return {string[]} - Array of activity IDs\n   */\n  extractActivityIds(activity: Activity): string[] {\n    const ids = [activity.id];\n\n    // Recursively extract IDs from children\n    for (const child of activity.children) {\n      ids.push(...this.extractActivityIds(child));\n    }\n\n    return ids;\n  }\n\n  /**\n   * Create an activity objective from settings\n   * @param {ObjectiveSettings} objectiveSettings - The objective settings\n   * @param {boolean} isPrimary - Whether this is a primary objective\n   * @return {ActivityObjective} - The created objective\n   */\n  createActivityObjectiveFromSettings(\n    objectiveSettings: ObjectiveSettings,\n    isPrimary: boolean,\n  ): ActivityObjective {\n    const mapInfo: ObjectiveMapInfo[] = (objectiveSettings.mapInfo || []).map((info) => ({\n      targetObjectiveID: info.targetObjectiveID,\n      readSatisfiedStatus: info.readSatisfiedStatus ?? true,\n      readNormalizedMeasure: info.readNormalizedMeasure ?? true,\n      writeSatisfiedStatus: info.writeSatisfiedStatus ?? false,\n      writeNormalizedMeasure: info.writeNormalizedMeasure ?? false,\n      readCompletionStatus: info.readCompletionStatus ?? true,\n      writeCompletionStatus: info.writeCompletionStatus ?? false,\n      readProgressMeasure: info.readProgressMeasure ?? true,\n      writeProgressMeasure: info.writeProgressMeasure ?? false,\n      readRawScore: info.readRawScore ?? true,\n      writeRawScore: info.writeRawScore ?? false,\n      readMinScore: info.readMinScore ?? true,\n      writeMinScore: info.writeMinScore ?? false,\n      readMaxScore: info.readMaxScore ?? true,\n      writeMaxScore: info.writeMaxScore ?? false,\n      updateAttemptData: info.updateAttemptData ?? false,\n    }));\n\n    return new ActivityObjective(objectiveSettings.objectiveID, {\n      description: objectiveSettings.description ?? null,\n      satisfiedByMeasure: objectiveSettings.satisfiedByMeasure ?? false,\n      minNormalizedMeasure: objectiveSettings.minNormalizedMeasure ?? null,\n      mapInfo,\n      isPrimary,\n    });\n  }\n}\n","import { CMIObjectivesObject } from \"../cmi/scorm2004/objectives\";\nimport { CMI } from \"../cmi/scorm2004/cmi\";\nimport { OverallSequencingProcess } from \"../cmi/scorm2004/sequencing/overall_sequencing_process\";\nimport { GlobalObjectiveMapEntry, ScoreObject, Settings } from \"../types/api_types\";\nimport { SequencingService } from \"../services/SequencingService\";\nimport { CompletionStatus, SuccessStatus } from \"../constants/enums\";\nimport { Sequencing } from \"../cmi/scorm2004/sequencing/sequencing\";\n\n/**\n * Common set CMI value function type\n */\nexport type CommonSetCMIValueFn = (\n  methodName: string,\n  throwError: boolean,\n  CMIElement: string,\n  value: any,\n) => string;\n\n/**\n * Context interface for global objective operations\n */\nexport interface GlobalObjectiveContext {\n  getSettings: () => Settings;\n  hostDeclaredGlobalObjectiveIds: string[];\n  cmi: CMI;\n  sequencing: Sequencing | null;\n  sequencingService: SequencingService | null;\n  commonSetCMIValue: CommonSetCMIValueFn;\n}\n\n/**\n * Manages global objectives for SCORM 2004\n *\n * This class is responsible for:\n * - Managing the global objectives array that persists across SCO transitions\n * - Restoring global objectives to CMI after initialization\n * - Syncing global objective IDs from sequencing service\n * - Updating global objectives from CMI data\n * - Building objective map entries\n * - Capturing global objective snapshots\n */\nexport class GlobalObjectiveManager {\n  private _globalObjectives: CMIObjectivesObject[] = [];\n  private context: GlobalObjectiveContext;\n  private readonly hostDeclaredGlobalObjectiveIds: Set<string>;\n\n  constructor(context: GlobalObjectiveContext) {\n    this.context = context;\n    // Capture the host extension boundary before sequencing map keys are merged into settings.\n    // @spec SCORM 2004 4th Ed. RTE 4.2.17 / SN 3.10.3 - mapped global\n    // objectives initialize their local activity objective, not an additional RTE row.\n    this.hostDeclaredGlobalObjectiveIds = new Set(context.hostDeclaredGlobalObjectiveIds);\n  }\n\n  /**\n   * Get global objectives array\n   *\n   * Global objectives persist across SCO transitions and are used for cross-activity\n   * objective tracking via mapInfo (SCORM 2004 SN Book SB.2.4).\n   *\n   * @return {CMIObjectivesObject[]} Array of global objective objects\n   */\n  get globalObjectives(): CMIObjectivesObject[] {\n    return this._globalObjectives;\n  }\n\n  /**\n   * Set global objectives array (for deserialization)\n   * @param {CMIObjectivesObject[]} objectives - Array of objectives to set\n   */\n  set globalObjectives(objectives: CMIObjectivesObject[]) {\n    this._globalObjectives = objectives;\n  }\n\n  /**\n   * Update the sequencing service reference\n   * @param {SequencingService | null} service - The sequencing service instance\n   */\n  updateSequencingService(service: SequencingService | null): void {\n    this.context.sequencingService = service;\n  }\n\n  /**\n   * Return whether the host explicitly exposed an objective as a directly writable extension row.\n   *\n   * Manifest map targets are internal sequencing state. A same-named local cmi.objectives row must\n   * still write only through that activity objective's mapInfo.\n   *\n   * @spec SCORM 2004 4th Ed. RTE 4.2.17 / SN 3.10.3 - local run-time objectives\n   *   access global objective state through objective maps\n   */\n  isHostDeclaredGlobalObjectiveId(objectiveId: string): boolean {\n    return this.hostDeclaredGlobalObjectiveIds.has(objectiveId);\n  }\n\n  /**\n   * Syncs global objective IDs from the sequencing service's globalObjectiveMap\n   * to settings.globalObjectiveIds. This ensures that objectives referenced via\n   * mapInfo in the activity tree are recognized as global objectives when\n   * setCMIValue is called.\n   *\n   * Per SCORM 2004 SN Book SB.2.4, global objectives must persist across SCO\n   * transitions and be available for cross-activity objective tracking.\n   */\n  syncGlobalObjectiveIdsFromSequencing(): void {\n    if (!this.context.sequencingService) {\n      return;\n    }\n\n    const overallProcess = this.context.sequencingService.getOverallSequencingProcess();\n    if (!overallProcess) {\n      return;\n    }\n\n    const globalObjectiveMap = overallProcess.getGlobalObjectiveMap();\n    if (!globalObjectiveMap || globalObjectiveMap.size === 0) {\n      return;\n    }\n\n    // Extract global objective IDs from the map\n    const globalIds = Array.from(globalObjectiveMap.keys());\n\n    // Merge with any existing globalObjectiveIds from settings\n    const settings = this.context.getSettings();\n    const existingIds = settings.globalObjectiveIds || [];\n    const mergedIds = Array.from(new Set(existingIds.concat(globalIds)));\n\n    // Update settings with the merged list\n    settings.globalObjectiveIds = mergedIds;\n  }\n\n  /**\n   * Restores global objectives from _globalObjectives to cmi.objectives\n   * This is called after Initialize to ensure global objectives are accessible\n   * to the content via cmi.objectives.n.id, cmi.objectives.n.success_status, etc.\n   *\n   * Per SCORM 2004 SN Book SB.2.4, global objectives must persist across SCO\n   * transitions and be accessible to content via the CMI data model.\n   */\n  restoreGlobalObjectivesToCMI(): void {\n    if (this._globalObjectives.length === 0) {\n      return;\n    }\n\n    const hasCurrentSequencingActivity = Boolean(this.context.sequencing?.getCurrentActivity());\n\n    // Restore each global objective to cmi.objectives\n    for (let i = 0; i < this._globalObjectives.length; i++) {\n      const globalObj = this._globalObjectives[i];\n      if (!globalObj || !globalObj.id) {\n        continue;\n      }\n\n      // A host may explicitly expose a direct global-objective row as an extension. Manifest\n      // mapInfo targets are synchronized through the delivered activity's local objectives and\n      // must not be appended as extra cmi.objectives rows for every SCO.\n      // @spec SCORM 2004 4th Ed. RTE 4.2.17 / SN 3.10.3 - the RTE view is\n      // initialized from the current activity's declared objectives and their read maps.\n      if (hasCurrentSequencingActivity && !this.hostDeclaredGlobalObjectiveIds.has(globalObj.id)) {\n        continue;\n      }\n\n      // Check if this objective already exists in cmi.objectives\n      const existingObjective = this.context.cmi.objectives.findObjectiveById(globalObj.id);\n      if (existingObjective) {\n        // Objective already exists, skip to avoid duplicates\n        continue;\n      }\n\n      // Add the global objective to cmi.objectives\n      const index = this.context.cmi.objectives.childArray.length;\n\n      // Set the objective ID first (this creates the objective in the array)\n      this.context.commonSetCMIValue(\n        \"RestoreGlobalObjective\",\n        true,\n        `cmi.objectives.${index}.id`,\n        globalObj.id,\n      );\n\n      // Restore other properties if they have values\n      if (globalObj.success_status && globalObj.success_status !== \"unknown\") {\n        this.context.commonSetCMIValue(\n          \"RestoreGlobalObjective\",\n          true,\n          `cmi.objectives.${index}.success_status`,\n          globalObj.success_status,\n        );\n      }\n\n      if (globalObj.completion_status && globalObj.completion_status !== \"unknown\") {\n        this.context.commonSetCMIValue(\n          \"RestoreGlobalObjective\",\n          true,\n          `cmi.objectives.${index}.completion_status`,\n          globalObj.completion_status,\n        );\n      }\n\n      if (globalObj.score.scaled !== \"\" && globalObj.score.scaled !== null) {\n        this.context.commonSetCMIValue(\n          \"RestoreGlobalObjective\",\n          true,\n          `cmi.objectives.${index}.score.scaled`,\n          globalObj.score.scaled,\n        );\n      }\n\n      if (globalObj.score.raw !== \"\" && globalObj.score.raw !== null) {\n        this.context.commonSetCMIValue(\n          \"RestoreGlobalObjective\",\n          true,\n          `cmi.objectives.${index}.score.raw`,\n          globalObj.score.raw,\n        );\n      }\n\n      if (globalObj.score.min !== \"\" && globalObj.score.min !== null) {\n        this.context.commonSetCMIValue(\n          \"RestoreGlobalObjective\",\n          true,\n          `cmi.objectives.${index}.score.min`,\n          globalObj.score.min,\n        );\n      }\n\n      if (globalObj.score.max !== \"\" && globalObj.score.max !== null) {\n        this.context.commonSetCMIValue(\n          \"RestoreGlobalObjective\",\n          true,\n          `cmi.objectives.${index}.score.max`,\n          globalObj.score.max,\n        );\n      }\n\n      if (globalObj.progress_measure !== \"\" && globalObj.progress_measure !== null) {\n        this.context.commonSetCMIValue(\n          \"RestoreGlobalObjective\",\n          true,\n          `cmi.objectives.${index}.progress_measure`,\n          globalObj.progress_measure,\n        );\n      }\n\n      if (globalObj.description !== \"\") {\n        this.context.commonSetCMIValue(\n          \"RestoreGlobalObjective\",\n          true,\n          `cmi.objectives.${index}.description`,\n          globalObj.description,\n        );\n      }\n    }\n  }\n\n  /**\n   * Updates the global objective map in the sequencing service from CMI objective data.\n   *\n   * This method synchronizes global objectives between:\n   * - _globalObjectives array (persists across SCO transitions)\n   * - Sequencing service global objective map (used for sequencing decisions)\n   *\n   * When a SCO writes to a global objective via SetValue, this method ensures\n   * the sequencing service is updated so that sequencing rules can evaluate\n   * the objective status correctly.\n   *\n   * According to SCORM 2004 SN Book SB.2.4, global objectives must be synchronized\n   * across all activities that reference them via mapInfo.\n   *\n   * @param {string} objectiveId - The global objective ID\n   * @param {CMIObjectivesObject} objective - The CMI objective object with updated values\n   *\n   * @spec SCORM 2004 4th Ed. SN 3.10.3 - global objectives synchronize CMI objective data\n   * @spec SCORM 2004 4th Ed. ADLSEQ objectives extension - raw/min/max score fields synchronize independently\n   */\n  updateGlobalObjectiveFromCMI(objectiveId: string, objective: CMIObjectivesObject): void {\n    if (!objectiveId || !this.context.sequencingService) {\n      return;\n    }\n\n    const overallProcess = this.context.sequencingService.getOverallSequencingProcess();\n    if (!overallProcess) {\n      return;\n    }\n\n    const map = overallProcess.getGlobalObjectiveMap();\n    if (!map.has(objectiveId)) {\n      const fallbackEntry = this.buildObjectiveMapEntryFromCMI(objective);\n      overallProcess.updateGlobalObjective(objectiveId, fallbackEntry);\n      return;\n    }\n\n    const updatePayload: Record<string, any> = {};\n\n    if (objective.success_status && objective.success_status !== SuccessStatus.UNKNOWN) {\n      updatePayload.satisfiedStatus = objective.success_status === SuccessStatus.PASSED;\n      updatePayload.satisfiedStatusKnown = true;\n    }\n\n    const normalizedMeasure = this.parseObjectiveNumber(objective.score?.scaled);\n    if (normalizedMeasure !== null) {\n      updatePayload.normalizedMeasure = normalizedMeasure;\n      updatePayload.normalizedMeasureKnown = true;\n    }\n\n    // @spec SCORM 2004 4th Ed. ADLSEQ objectives extension - raw score\n    // updates independently of scaled, min, and max score fields.\n    if (objective.score?.raw !== undefined && objective.score.raw !== \"\") {\n      updatePayload.rawScore = objective.score.raw;\n      updatePayload.rawScoreKnown = true;\n    }\n\n    // @spec SCORM 2004 4th Ed. ADLSEQ objectives extension - min score\n    // updates independently of raw, scaled, and max score fields.\n    if (objective.score?.min !== undefined && objective.score.min !== \"\") {\n      updatePayload.minScore = objective.score.min;\n      updatePayload.minScoreKnown = true;\n    }\n\n    // @spec SCORM 2004 4th Ed. ADLSEQ objectives extension - max score\n    // updates independently of raw, scaled, and min score fields.\n    if (objective.score?.max !== undefined && objective.score.max !== \"\") {\n      updatePayload.maxScore = objective.score.max;\n      updatePayload.maxScoreKnown = true;\n    }\n\n    const progressMeasure = this.parseObjectiveNumber(objective.progress_measure);\n    if (progressMeasure !== null) {\n      updatePayload.progressMeasure = progressMeasure;\n      updatePayload.progressMeasureKnown = true;\n    }\n\n    if (objective.completion_status && objective.completion_status !== CompletionStatus.UNKNOWN) {\n      updatePayload.completionStatus = objective.completion_status;\n      updatePayload.completionStatusKnown = true;\n    }\n\n    if (Object.keys(updatePayload).length === 0) {\n      return;\n    }\n\n    overallProcess.updateGlobalObjective(objectiveId, updatePayload);\n  }\n\n  /**\n   * Builds a map entry from the given CMI objectives object to a standardized GlobalObjectiveMapEntry.\n   *\n   * @param {CMIObjectivesObject} objective - The CMI objectives object containing data about a specific learning objective.\n   * @return {GlobalObjectiveMapEntry} An object containing mapped properties and their values based on the provided objective.\n   *\n   * @spec SCORM 2004 4th Ed. SN 3.10.3 - global objective map entries capture objective state\n   * @spec SCORM 2004 4th Ed. ADLSEQ objectives extension - raw/min/max score entries carry per-field known flags\n   */\n  buildObjectiveMapEntryFromCMI(objective: CMIObjectivesObject): GlobalObjectiveMapEntry {\n    const entry: GlobalObjectiveMapEntry = {\n      id: objective.id,\n      satisfiedStatusKnown: false,\n      normalizedMeasureKnown: false,\n      rawScore: \"\",\n      rawScoreKnown: false,\n      minScore: \"\",\n      minScoreKnown: false,\n      maxScore: \"\",\n      maxScoreKnown: false,\n      progressMeasureKnown: false,\n      completionStatusKnown: false,\n      readSatisfiedStatus: true,\n      writeSatisfiedStatus: true,\n      readNormalizedMeasure: true,\n      writeNormalizedMeasure: true,\n      readCompletionStatus: true,\n      writeCompletionStatus: true,\n      readProgressMeasure: true,\n      writeProgressMeasure: true,\n      readRawScore: true,\n      writeRawScore: true,\n      readMinScore: true,\n      writeMinScore: true,\n      readMaxScore: true,\n      writeMaxScore: true,\n    };\n\n    if (objective.success_status && objective.success_status !== SuccessStatus.UNKNOWN) {\n      entry.satisfiedStatus = objective.success_status === SuccessStatus.PASSED;\n      entry.satisfiedStatusKnown = true;\n    }\n\n    const normalizedMeasure = this.parseObjectiveNumber(objective.score?.scaled);\n    if (normalizedMeasure !== null) {\n      entry.normalizedMeasure = normalizedMeasure;\n      entry.normalizedMeasureKnown = true;\n    }\n\n    // @spec SCORM 2004 4th Ed. ADLSEQ objectives extension - raw score\n    // snapshot state carries its own known flag.\n    if (objective.score?.raw !== undefined && objective.score.raw !== \"\") {\n      entry.rawScore = objective.score.raw;\n      entry.rawScoreKnown = true;\n    }\n\n    // @spec SCORM 2004 4th Ed. ADLSEQ objectives extension - min score\n    // snapshot state carries its own known flag.\n    if (objective.score?.min !== undefined && objective.score.min !== \"\") {\n      entry.minScore = objective.score.min;\n      entry.minScoreKnown = true;\n    }\n\n    // @spec SCORM 2004 4th Ed. ADLSEQ objectives extension - max score\n    // snapshot state carries its own known flag.\n    if (objective.score?.max !== undefined && objective.score.max !== \"\") {\n      entry.maxScore = objective.score.max;\n      entry.maxScoreKnown = true;\n    }\n\n    const progressMeasure = this.parseObjectiveNumber(objective.progress_measure);\n    if (progressMeasure !== null) {\n      entry.progressMeasure = progressMeasure;\n      entry.progressMeasureKnown = true;\n    }\n\n    if (objective.completion_status && objective.completion_status !== CompletionStatus.UNKNOWN) {\n      entry.completionStatus = objective.completion_status;\n      entry.completionStatusKnown = true;\n    }\n\n    return entry;\n  }\n\n  /**\n   * Constructs an array of `CMIObjectivesObject` instances from a given snapshot map.\n   *\n   * @param {Record<string, GlobalObjectiveMapEntry>} snapshot - A map where each entry represents objective data\n   *                                         with various properties that may include\n   *                                         satisfied status, progress measure, completion status, etc.\n   * @return {CMIObjectivesObject[]} An array of `CMIObjectivesObject` instances built\n   *                                  from the provided snapshot map. Returns an empty array\n   *                                  if the snapshot is invalid or no valid objectives can be created.\n   *\n   * @spec SCORM 2004 4th Ed. SN 3.10.3 - global objective snapshots restore CMI objective state\n   * @spec SCORM 2004 4th Ed. ADLSEQ objectives extension - raw/min/max score known fields restore independently\n   */\n  buildCMIObjectivesFromMap(\n    snapshot: Record<string, GlobalObjectiveMapEntry>,\n  ): CMIObjectivesObject[] {\n    const objectives: CMIObjectivesObject[] = [];\n    if (!snapshot || typeof snapshot !== \"object\") {\n      return objectives;\n    }\n\n    for (const [objectiveId, entry] of Object.entries(snapshot)) {\n      if (!entry || typeof entry !== \"object\") {\n        continue;\n      }\n      const objective = new CMIObjectivesObject();\n      objective.id = entry.id ?? objectiveId;\n\n      if (entry.satisfiedStatusKnown === true) {\n        objective.success_status = entry.satisfiedStatus\n          ? SuccessStatus.PASSED\n          : SuccessStatus.FAILED;\n      }\n\n      const normalizedMeasure = this.parseObjectiveNumber(entry.normalizedMeasure);\n      if (entry.normalizedMeasureKnown === true && normalizedMeasure !== null) {\n        objective.score.scaled = String(normalizedMeasure);\n      }\n\n      // @spec SCORM 2004 4th Ed. ADLSEQ objectives extension - raw score\n      // restores only when its known flag is true.\n      if (entry.rawScoreKnown === true) {\n        objective.score.raw = String(entry.rawScore ?? \"\");\n      }\n\n      // @spec SCORM 2004 4th Ed. ADLSEQ objectives extension - min score\n      // restores only when its known flag is true.\n      if (entry.minScoreKnown === true) {\n        objective.score.min = String(entry.minScore ?? \"\");\n      }\n\n      // @spec SCORM 2004 4th Ed. ADLSEQ objectives extension - max score\n      // restores only when its known flag is true.\n      if (entry.maxScoreKnown === true) {\n        objective.score.max = String(entry.maxScore ?? \"\");\n      }\n\n      const progressMeasure = this.parseObjectiveNumber(entry.progressMeasure);\n      if (entry.progressMeasureKnown === true && progressMeasure !== null) {\n        objective.progress_measure = String(progressMeasure);\n      }\n\n      if (entry.completionStatusKnown === true && typeof entry.completionStatus === \"string\") {\n        objective.completion_status = entry.completionStatus;\n      }\n\n      objectives.push(objective);\n    }\n\n    return objectives;\n  }\n\n  /**\n   * Constructs a `CMIObjectivesObject` instance from the provided JSON data.\n   *\n   * @param {any} data - The JSON data used to populate the `CMIObjectivesObject`. If the input is invalid or missing, an empty `CMIObjectivesObject` instance is returned.\n   * @return {CMIObjectivesObject} A populated `CMIObjectivesObject` instance based on the input data. Returns a default object if the input does not contain valid fields.\n   */\n  buildCMIObjectiveFromJSON(data: any): CMIObjectivesObject {\n    const objective = new CMIObjectivesObject();\n    if (!data || typeof data !== \"object\") {\n      return objective;\n    }\n\n    if (typeof data.id === \"string\") {\n      objective.id = data.id;\n    }\n\n    if (typeof data.success_status === \"string\") {\n      objective.success_status = data.success_status;\n    }\n\n    if (typeof data.completion_status === \"string\") {\n      objective.completion_status = data.completion_status;\n    }\n\n    if (typeof data.progress_measure === \"string\" && data.progress_measure !== \"\") {\n      objective.progress_measure = data.progress_measure;\n    }\n\n    if (typeof data.description === \"string\") {\n      objective.description = data.description;\n    }\n\n    const score = data.score;\n    if (score && typeof score === \"object\") {\n      if (typeof score.scaled === \"string\" && score.scaled !== \"\") {\n        objective.score.scaled = score.scaled;\n      } else if (typeof score.scaled === \"number\" && Number.isFinite(score.scaled)) {\n        objective.score.scaled = String(score.scaled);\n      }\n\n      if (typeof score.raw === \"string\" && score.raw !== \"\") {\n        objective.score.raw = score.raw;\n      } else if (typeof score.raw === \"number\" && Number.isFinite(score.raw)) {\n        objective.score.raw = String(score.raw);\n      }\n\n      if (typeof score.min === \"string\" && score.min !== \"\") {\n        objective.score.min = score.min;\n      } else if (typeof score.min === \"number\" && Number.isFinite(score.min)) {\n        objective.score.min = String(score.min);\n      }\n\n      if (typeof score.max === \"string\" && score.max !== \"\") {\n        objective.score.max = score.max;\n      } else if (typeof score.max === \"number\" && Number.isFinite(score.max)) {\n        objective.score.max = String(score.max);\n      }\n    }\n\n    return objective;\n  }\n\n  /**\n   * Captures the global objective snapshot by collecting data from the provided overall process\n   * or the internally managed sequencing service if no process is provided.\n   *\n   * @param {OverallSequencingProcess | null} [overallProcess] - An optional parameter representing the overall sequencing process. If not provided, it attempts to use the internal sequencing service.\n   * @return {Record<string, GlobalObjectiveMapEntry>} A record containing the snapshot of the global objectives, with each objective's identifier as the key and its corresponding data as the value.\n   */\n  captureGlobalObjectiveSnapshot(\n    overallProcess?: OverallSequencingProcess | null,\n  ): Record<string, GlobalObjectiveMapEntry> {\n    const snapshot: Record<string, GlobalObjectiveMapEntry> = {};\n\n    const process =\n      overallProcess ?? this.context.sequencingService?.getOverallSequencingProcess() ?? null;\n    if (process) {\n      const processSnapshot = process.getGlobalObjectiveMapSnapshot();\n      for (const [id, data] of Object.entries(processSnapshot)) {\n        snapshot[id] = { ...data };\n      }\n    }\n\n    for (const objective of this._globalObjectives) {\n      if (!objective.id || snapshot[objective.id]) {\n        continue;\n      }\n      snapshot[objective.id] = this.buildObjectiveMapEntryFromCMI(objective);\n    }\n\n    return snapshot;\n  }\n\n  /**\n   * Merge an LMS-provided global-objective snapshot into the manifest-created objective map.\n   * Existing map entries retain their mapInfo permissions while persisted tracking values replace\n   * the corresponding defaults.\n   *\n   * @param {Record<string, GlobalObjectiveMapEntry>} snapshot - Persisted global objective state\n   *\n   * @spec SCORM 2004 4th Ed. SN 3.10.3 - mapped global objective state is available to read maps\n   */\n  restoreGlobalObjectiveSnapshot(snapshot: Record<string, GlobalObjectiveMapEntry>): void {\n    if (!snapshot || typeof snapshot !== \"object\") {\n      return;\n    }\n\n    const process = this.context.sequencingService?.getOverallSequencingProcess() ?? null;\n    if (process) {\n      for (const [objectiveId, objectiveData] of Object.entries(snapshot)) {\n        if (!objectiveId || !objectiveData || typeof objectiveData !== \"object\") {\n          continue;\n        }\n        process.updateGlobalObjective(objectiveId, {\n          ...objectiveData,\n          id: objectiveData.id ?? objectiveId,\n        });\n      }\n\n      // The initial sequencing request evaluates preconditions against activity-local\n      // objective state. Apply restored global values to their read-mapped activity\n      // objectives before Start/Resume All can run.\n      // @spec SCORM 2004 4th Ed. SN 3.10.3 and NB.2.1 - persisted global\n      //   objective values are available to mapped sequencing rules on launch.\n      process.synchronizeGlobalObjectives();\n    }\n\n    this._globalObjectives = this.buildCMIObjectivesFromMap(snapshot);\n  }\n\n  /**\n   * Parses the given value into a finite number if possible, otherwise returns null.\n   *\n   * @param {any} value - The input value to be parsed into a number.\n   * @return {number | null} The parsed finite number if the input is valid, otherwise null.\n   */\n  parseObjectiveNumber(value: any): number | null {\n    if (value === null || value === undefined) {\n      return null;\n    }\n\n    if (typeof value === \"number\" && Number.isFinite(value)) {\n      return value;\n    }\n\n    const parsed = parseFloat(String(value));\n    return Number.isFinite(parsed) ? parsed : null;\n  }\n\n  /**\n   * Synchronize CMI runtime data to the current sequencing activity\n   * When cmi.success_status or cmi.completion_status are set, update the\n   * current activity's primary objective accordingly\n   *\n   * @param {CompletionStatus} completionStatus\n   * @param {SuccessStatus} successStatus\n   * @param {ScoreObject} scoreObject\n   *\n   * @spec SCORM 2004 4th Ed. RTE-to-SN Data Transfer - CMI score data updates the current primary objective\n   * @spec SCORM 2004 4th Ed. ADLSEQ objectives extension - raw/min/max score data is available for write maps\n   */\n  syncCmiToSequencingActivity(\n    completionStatus: CompletionStatus,\n    successStatus: SuccessStatus,\n    scoreObject?: ScoreObject,\n  ): void {\n    if (!this.context.sequencing) {\n      return;\n    }\n\n    const currentActivity = this.context.sequencing.getCurrentActivity();\n    if (!currentActivity || !currentActivity.primaryObjective) {\n      return;\n    }\n\n    const primaryObjective = currentActivity.primaryObjective;\n\n    const satisfiedByMeasure = primaryObjective.satisfiedByMeasure === true;\n\n    // @spec SCORM 2004 4th Ed. SN 4.2.1 Tracking Model - Objective Progress\n    // Status and Objective Measure Status are independent. A direct success\n    // status does not make the normalized measure known, and a measure-controlled\n    // objective ignores direct success status.\n    if (!satisfiedByMeasure && successStatus !== SuccessStatus.UNKNOWN) {\n      primaryObjective.satisfiedStatus = successStatus === SuccessStatus.PASSED;\n      primaryObjective.satisfiedStatusKnown = true;\n      currentActivity.objectiveSatisfiedStatus = successStatus === SuccessStatus.PASSED;\n      currentActivity.objectiveSatisfiedStatusKnown = true;\n    }\n\n    // Update primary objective completion status based on cmi.completion_status\n    if (completionStatus !== CompletionStatus.UNKNOWN) {\n      primaryObjective.completionStatus = completionStatus;\n    }\n\n    // Update normalized measure if score is provided.\n    if (\n      scoreObject?.scaled !== undefined &&\n      scoreObject.scaled !== null &&\n      Number.isFinite(scoreObject.scaled)\n    ) {\n      const normalizedMeasure = scoreObject.scaled;\n      primaryObjective.normalizedMeasure = normalizedMeasure;\n      primaryObjective.measureStatus = true;\n\n      if (satisfiedByMeasure) {\n        // @spec SCORM 2004 4th Ed. SN 3.10 Objective Description - objective\n        // satisfaction is derived from a known measure; when omitted, the\n        // minimum normalized measure defaults to 1.0.\n        const satisfied = normalizedMeasure >= (primaryObjective.minNormalizedMeasure ?? 1.0);\n        primaryObjective.satisfiedStatus = satisfied;\n        primaryObjective.satisfiedStatusKnown = true;\n        currentActivity.objectiveSatisfiedStatus = satisfied;\n        currentActivity.objectiveSatisfiedStatusKnown = true;\n      }\n    }\n\n    // @spec SCORM 2004 4th Ed. ADLSEQ objectives extension - raw score is\n    // available to raw-score write maps independently of scaled score.\n    if (scoreObject?.raw !== undefined && scoreObject.raw !== null) {\n      primaryObjective.rawScore = String(scoreObject.raw);\n    }\n\n    // @spec SCORM 2004 4th Ed. ADLSEQ objectives extension - min score is\n    // available to min-score write maps independently of scaled score.\n    if (scoreObject?.min !== undefined && scoreObject.min !== null) {\n      primaryObjective.minScore = String(scoreObject.min);\n    }\n\n    // @spec SCORM 2004 4th Ed. ADLSEQ objectives extension - max score is\n    // available to max-score write maps independently of scaled score.\n    if (scoreObject?.max !== undefined && scoreObject.max !== null) {\n      primaryObjective.maxScore = String(scoreObject.max);\n    }\n  }\n\n  /**\n   * Find or create a global objective by ID\n   * @param {string} objectiveId - The objective ID\n   * @return {{ index: number; objective: CMIObjectivesObject }} The index and objective\n   */\n  findOrCreateGlobalObjective(objectiveId: string): {\n    index: number;\n    objective: CMIObjectivesObject;\n  } {\n    let index = this._globalObjectives.findIndex((obj) => obj.id === objectiveId);\n\n    if (index === -1) {\n      index = this._globalObjectives.length;\n      const newGlobalObjective = new CMIObjectivesObject();\n      newGlobalObjective.id = objectiveId;\n      this._globalObjectives.push(newGlobalObjective);\n    }\n\n    return { index, objective: this._globalObjectives[index]! };\n  }\n}\n","import { SequencingStateMetadata, Settings } from \"../types/api_types\";\nimport { CMIObjectivesObject } from \"../cmi/scorm2004/objectives\";\nimport { ADL } from \"../cmi/scorm2004/adl\";\nimport { Sequencing } from \"../cmi/scorm2004/sequencing/sequencing\";\nimport { GlobalObjectiveManager } from \"../objectives/global_objective_manager\";\nimport { SequencingService } from \"../services/SequencingService\";\nimport { LogLevelEnum } from \"../constants/enums\";\n\n/**\n * Logging function type\n */\nexport type ApiLogFn = (method: string, message: string, level: number) => void;\n\n/**\n * Context interface for persistence operations\n */\nexport interface PersistenceContext {\n  getSettings: () => Settings;\n  apiLog: ApiLogFn;\n  adl: ADL;\n  sequencing: Sequencing;\n  sequencingService: SequencingService | null;\n  learnerId: string;\n}\n\n/**\n * Handles persistence of SCORM 2004 sequencing state\n *\n * This class is responsible for:\n * - Saving sequencing state to persistent storage\n * - Loading sequencing state from persistent storage\n * - Serializing sequencing state to JSON\n * - Deserializing sequencing state from JSON\n * - Compressing and decompressing state data\n */\nexport class SequencingStatePersistence {\n  private context: PersistenceContext;\n  private globalObjectiveManager: GlobalObjectiveManager;\n  private readonly inFlightLoads = new Map<string, Promise<boolean>>();\n\n  constructor(context: PersistenceContext, globalObjectiveManager: GlobalObjectiveManager) {\n    this.context = context;\n    this.globalObjectiveManager = globalObjectiveManager;\n  }\n\n  /**\n   * Save current sequencing state to persistent storage\n   * @param {Partial<SequencingStateMetadata>} metadata - Optional metadata override\n   * @return {Promise<boolean>} Promise resolving to success status\n   */\n  async saveSequencingState(metadata?: Partial<SequencingStateMetadata>): Promise<boolean> {\n    const settings = this.context.getSettings();\n    if (!settings.sequencingStatePersistence) {\n      this.context.apiLog(\n        \"saveSequencingState\",\n        \"No persistence configuration provided\",\n        LogLevelEnum.WARN,\n      );\n      return false;\n    }\n\n    try {\n      const stateData = this.serializeSequencingState();\n      const fullMetadata: SequencingStateMetadata = {\n        learnerId: this.context.learnerId || \"unknown\",\n        courseId: settings.courseId || \"unknown\",\n        attemptNumber: 1,\n        lastUpdated: new Date().toISOString(),\n        version: settings.sequencingStatePersistence.stateVersion || \"1.0\",\n        ...metadata,\n      };\n\n      const config = settings.sequencingStatePersistence;\n      let dataToSave = stateData;\n\n      // Compress if enabled (using simple base64 encoding for now)\n      if (config.compress !== false) {\n        dataToSave = this.compressStateData(stateData);\n      }\n\n      // Check size limits\n      if (config.maxStateSize && dataToSave.length > config.maxStateSize) {\n        throw new Error(`State size ${dataToSave.length} exceeds limit ${config.maxStateSize}`);\n      }\n\n      const success = await config.persistence.saveState(dataToSave, fullMetadata);\n\n      if (config.debugPersistence) {\n        this.context.apiLog(\n          \"saveSequencingState\",\n          `State save ${success ? \"succeeded\" : \"failed\"}: size=${dataToSave.length}`,\n          success ? LogLevelEnum.INFO : LogLevelEnum.WARN,\n        );\n      }\n\n      return success;\n    } catch (error) {\n      this.context.apiLog(\n        \"saveSequencingState\",\n        `Error saving sequencing state: ${error instanceof Error ? error.message : String(error)}`,\n        LogLevelEnum.ERROR,\n      );\n      return false;\n    }\n  }\n\n  /**\n   * Load sequencing state from persistent storage\n   * @param {Partial<SequencingStateMetadata>} metadata - Optional metadata override\n   * @return {Promise<boolean>} Promise resolving to success status\n   */\n  loadSequencingState(metadata?: Partial<SequencingStateMetadata>): Promise<boolean> {\n    const settings = this.context.getSettings();\n    if (!settings.sequencingStatePersistence) {\n      this.context.apiLog(\n        \"loadSequencingState\",\n        \"No persistence configuration provided\",\n        LogLevelEnum.WARN,\n      );\n      return Promise.resolve(false);\n    }\n    const config = settings.sequencingStatePersistence;\n\n    const fullMetadata: SequencingStateMetadata = {\n      learnerId: this.context.learnerId || \"unknown\",\n      courseId: settings.courseId || \"unknown\",\n      attemptNumber: 1,\n      version: config.stateVersion || \"1.0\",\n      ...metadata,\n    };\n    const loadKey = JSON.stringify({\n      learnerId: fullMetadata.learnerId,\n      courseId: fullMetadata.courseId,\n      attemptNumber: fullMetadata.attemptNumber,\n      version: fullMetadata.version,\n    });\n    const existingLoad = this.inFlightLoads.get(loadKey);\n    if (existingLoad) {\n      // @spec SCORM 2004 4th Ed. SN 4.2 Tracking Model Persistence - one\n      // persisted snapshot must be applied atomically. Equivalent concurrent\n      // loads share the same operation so a late stale load cannot overwrite\n      // runtime tracking changes made after an earlier load completed.\n      return existingLoad;\n    }\n\n    const loadOperation = (async (): Promise<boolean> => {\n      try {\n        const stateData = await config.persistence.loadState(fullMetadata);\n\n        if (!stateData) {\n          if (config.debugPersistence) {\n            this.context.apiLog(\n              \"loadSequencingState\",\n              \"No sequencing state found to load\",\n              LogLevelEnum.INFO,\n            );\n          }\n          return false;\n        }\n\n        // Decompress if needed\n        let dataToLoad = stateData;\n        if (config.compress !== false) {\n          dataToLoad = this.decompressStateData(stateData);\n        }\n\n        const success = this.deserializeSequencingState(dataToLoad);\n\n        if (config.debugPersistence) {\n          this.context.apiLog(\n            \"loadSequencingState\",\n            `State load ${success ? \"succeeded\" : \"failed\"}: size=${stateData.length}`,\n            success ? LogLevelEnum.INFO : LogLevelEnum.WARN,\n          );\n        }\n\n        return success;\n      } catch (error) {\n        this.context.apiLog(\n          \"loadSequencingState\",\n          `Error loading sequencing state: ${error instanceof Error ? error.message : String(error)}`,\n          LogLevelEnum.ERROR,\n        );\n        return false;\n      }\n    })();\n\n    this.inFlightLoads.set(loadKey, loadOperation);\n    void loadOperation.finally(() => {\n      if (this.inFlightLoads.get(loadKey) === loadOperation) {\n        this.inFlightLoads.delete(loadKey);\n      }\n    });\n    return loadOperation;\n  }\n\n  /**\n   * Serialize current sequencing state to JSON string\n   * @return {string} Serialized state\n   */\n  serializeSequencingState(): string {\n    const settings = this.context.getSettings();\n    const state: any = {\n      version: settings.sequencingStatePersistence?.stateVersion || \"1.0\",\n      timestamp: new Date().toISOString(),\n      sequencing: null,\n      currentActivityId: null,\n      globalObjectives: this.globalObjectiveManager.globalObjectives.map((obj) => obj.toJSON()),\n      globalObjectiveMap: {},\n      adlNavState: {\n        request: this.context.adl.nav.request,\n        request_valid: this.context.adl.nav.request_valid,\n      },\n      sharedData:\n        typeof this.context.adl.captureSharedDataSnapshot === \"function\"\n          ? this.context.adl.captureSharedDataSnapshot()\n          : {},\n      contentDelivered: false,\n    };\n\n    // Get sequencing state from overall sequencing process if available\n    if (this.context.sequencingService) {\n      const overallProcess = this.context.sequencingService.getOverallSequencingProcess();\n      if (overallProcess) {\n        // Use the getSequencingState method from overall_sequencing_process\n        const sequencingState = overallProcess.getSequencingState();\n        state.sequencing = sequencingState;\n        if (typeof overallProcess.getSuspensionState === \"function\") {\n          state.suspensionState = overallProcess.getSuspensionState();\n        }\n        state.contentDelivered = overallProcess.hasContentBeenDelivered();\n        state.globalObjectiveMap =\n          this.globalObjectiveManager.captureGlobalObjectiveSnapshot(overallProcess);\n      }\n\n      // Get current activity\n      const currentActivity = this.context.sequencing.getCurrentActivity();\n      if (currentActivity) {\n        state.currentActivityId = currentActivity.id;\n      }\n    }\n\n    if (!state.globalObjectiveMap || Object.keys(state.globalObjectiveMap).length === 0) {\n      state.globalObjectiveMap = this.globalObjectiveManager.captureGlobalObjectiveSnapshot();\n    }\n\n    return JSON.stringify(state);\n  }\n\n  /**\n   * Deserialize sequencing state from JSON string\n   * @param {string} stateData - Serialized state data\n   * @return {boolean} Success status\n   */\n  deserializeSequencingState(stateData: string): boolean {\n    try {\n      const state = JSON.parse(stateData);\n      const settings = this.context.getSettings();\n\n      // Version compatibility check\n      const expectedVersion = settings.sequencingStatePersistence?.stateVersion || \"1.0\";\n      if (state.version !== expectedVersion) {\n        this.context.apiLog(\n          \"deserializeSequencingState\",\n          `State version mismatch: ${state.version} vs expected ${expectedVersion}`,\n          LogLevelEnum.WARN,\n        );\n      }\n\n      // If persistence stored the global objective map separately, ensure it is available to the sequencing state\n      if (state.globalObjectiveMap && state.sequencing && !state.sequencing.globalObjectiveMap) {\n        state.sequencing.globalObjectiveMap = state.globalObjectiveMap;\n      }\n\n      // Restore sequencing state\n      if (this.context.sequencingService) {\n        const overallProcess = this.context.sequencingService.getOverallSequencingProcess();\n        if (overallProcess) {\n          if (state.sequencing) {\n            overallProcess.restoreSequencingState(state.sequencing);\n          }\n\n          // Complete suspension snapshots were added after the original 1.0\n          // persistence envelope. Keep restoring the flattened state for old\n          // snapshots, then apply the richer snapshot when it is present.\n          if (\n            state.suspensionState !== undefined &&\n            typeof overallProcess.restoreSuspensionState === \"function\"\n          ) {\n            overallProcess.restoreSuspensionState(state.suspensionState);\n          }\n\n          // Restore content delivered flag\n          if (state.sequencing && state.contentDelivered) {\n            overallProcess.setContentDelivered(true);\n          }\n        }\n      }\n\n      // Restore global objectives.\n      //\n      // The sequencing global objective map wins wherever the two persisted representations\n      // disagree. It is the store that mapInfo write maps update, so it always reflects the most\n      // recent attempt. The _globalObjectives CMI array is only refreshed when content writes a\n      // global objective id directly through SetValue, so for a package that shares objectives via\n      // mapInfo it lags a generation behind. Applying the array on top would push those stale values\n      // back into the map through updateGlobalObjectiveFromCMI below, silently undoing every write\n      // the previous attempt made. The array still contributes any id the map does not hold.\n      const restoredObjectives = new Map<string, CMIObjectivesObject>();\n\n      if (state.globalObjectiveMap && typeof state.globalObjectiveMap === \"object\") {\n        const objectivesFromMap = this.globalObjectiveManager.buildCMIObjectivesFromMap(\n          state.globalObjectiveMap,\n        );\n        for (const objective of objectivesFromMap) {\n          if (objective.id) {\n            restoredObjectives.set(objective.id, objective);\n          }\n        }\n      }\n\n      if (Array.isArray(state.globalObjectives)) {\n        for (const objData of state.globalObjectives) {\n          const objective = this.globalObjectiveManager.buildCMIObjectiveFromJSON(objData);\n          if (!objective.id) {\n            continue;\n          }\n\n          const fromMap = restoredObjectives.get(objective.id);\n          if (!fromMap) {\n            restoredObjectives.set(objective.id, objective);\n            continue;\n          }\n\n          // The map entry wins on every field it models, but it does not model description: the\n          // global objective map only carries sequencing state. Carry that one field across so\n          // preferring the map does not blank out a description the array still holds.\n          if (!fromMap.description && objective.description) {\n            fromMap.description = objective.description;\n          }\n        }\n      }\n\n      if (restoredObjectives.size > 0) {\n        this.globalObjectiveManager.globalObjectives = Array.from(restoredObjectives.values());\n        this.globalObjectiveManager.globalObjectives.forEach((objective) => {\n          if (objective.id) {\n            this.globalObjectiveManager.updateGlobalObjectiveFromCMI(objective.id, objective);\n          }\n        });\n      }\n\n      // Restore ADL nav state\n      if (\n        state.sharedData &&\n        typeof state.sharedData === \"object\" &&\n        typeof this.context.adl.restoreSharedDataSnapshot === \"function\"\n      ) {\n        this.context.adl.restoreSharedDataSnapshot(state.sharedData);\n      }\n\n      // Restoring the sequencing tree changes the activity whose ADL data view\n      // is exposed. Rebind it before the host can initialize the restored SCO;\n      // configureSharedDataMaps also preserves the initialized-vs-missing bit\n      // from the restored backing snapshot.\n      const restoredActivity = this.context.sequencing.getCurrentActivity();\n      if (restoredActivity && typeof this.context.adl.configureSharedDataMaps === \"function\") {\n        this.context.adl.configureSharedDataMaps(restoredActivity.sharedDataMaps);\n      }\n\n      if (state.adlNavState) {\n        this.context.adl.nav.request = state.adlNavState.request || \"_none_\";\n        const requestValid = this.context.adl.nav.request_valid;\n        const wasInitialized = requestValid.initialized;\n        const savedValidity = state.adlNavState.request_valid || {};\n\n        // Preserve the live object, its choice/jump helpers, and their sequencing links.\n        // Initialize-time auto-loads must also restore read-only validity values.\n        requestValid.reset();\n        try {\n          for (const key of [\n            \"continue\",\n            \"previous\",\n            \"exit\",\n            \"exitAll\",\n            \"abandon\",\n            \"abandonAll\",\n            \"suspendAll\",\n          ] as const) {\n            requestValid[key] = savedValidity[key] ?? \"unknown\";\n          }\n          requestValid.choice = savedValidity.choice ?? {};\n          requestValid.jump = savedValidity.jump ?? {};\n        } finally {\n          if (wasInitialized) requestValid.initialize();\n        }\n      }\n\n      return true;\n    } catch (error) {\n      this.context.apiLog(\n        \"deserializeSequencingState\",\n        `Error deserializing sequencing state: ${error instanceof Error ? error.message : String(error)}`,\n        LogLevelEnum.ERROR,\n      );\n      return false;\n    }\n  }\n\n  /**\n   * Simple compression using base64 encoding\n   * @param {string} data - Data to compress\n   * @return {string} Compressed data\n   */\n  compressStateData(data: string): string {\n    // For now, just use base64 encoding\n    // In a real implementation, you might use a library like lz-string\n    if (typeof btoa !== \"undefined\") {\n      return btoa(encodeURIComponent(data));\n    }\n    return data;\n  }\n\n  /**\n   * Simple decompression from base64\n   * @param {string} data - Data to decompress\n   * @return {string} Decompressed data\n   */\n  decompressStateData(data: string): string {\n    // For now, just use base64 decoding\n    // In a real implementation, you might use a library like lz-string\n    if (typeof atob !== \"undefined\") {\n      try {\n        return decodeURIComponent(atob(data));\n      } catch {\n        return data;\n      }\n    }\n    return data;\n  }\n}\n","import { CMI } from \"../cmi/scorm2004/cmi\";\nimport { CommitObject, ScoreObject, Settings } from \"../types/api_types\";\nimport { flatten, getDurationAsSeconds, StringKeyMap } from \"../utilities\";\nimport { CompletionStatus, SuccessStatus } from \"../constants/enums\";\nimport { scorm2004_regex } from \"../constants/regex\";\nimport { SequencingService } from \"../services/SequencingService\";\nimport { GlobalObjectiveManager } from \"../objectives/global_objective_manager\";\nimport { ADL } from \"../cmi/scorm2004/adl\";\n\n/**\n * Render CMI to JSON function type\n */\nexport type RenderCMIToJSONFn = () => StringKeyMap;\n\n/**\n * Context interface for data serialization operations\n * Uses getSettings() function to always get the current settings object\n * (important for handling reset() which creates a new settings object)\n */\nexport interface DataSerializerContext {\n  getSettings: () => Settings;\n  cmi: CMI;\n  adl?: ADL;\n  sequencingService: SequencingService | null;\n  renderCMIToJSONObject: RenderCMIToJSONFn;\n}\n\n/**\n * Handles data serialization for SCORM 2004 LMS commits\n *\n * This class is responsible for:\n * - Rendering CMI data for LMS commits\n * - Building commit objects with metadata\n * - Determining entry values based on previous exit state\n */\nexport class Scorm2004DataSerializer {\n  private context: DataSerializerContext;\n  private globalObjectiveManager: GlobalObjectiveManager | null;\n\n  constructor(\n    context: DataSerializerContext,\n    globalObjectiveManager?: GlobalObjectiveManager | null,\n  ) {\n    this.context = context;\n    this.globalObjectiveManager = globalObjectiveManager || null;\n  }\n\n  /**\n   * Set the global objective manager (for deferred initialization)\n   * @param {GlobalObjectiveManager} manager - The global objective manager\n   */\n  setGlobalObjectiveManager(manager: GlobalObjectiveManager): void {\n    this.globalObjectiveManager = manager;\n  }\n\n  /**\n   * Update the sequencing service reference\n   * @param {SequencingService | null} service - The sequencing service instance\n   */\n  updateSequencingService(service: SequencingService | null): void {\n    this.context.sequencingService = service;\n  }\n\n  /**\n   * Render the cmi object to the proper format for LMS commit\n   *\n   * @param {boolean} terminateCommit - Whether this is a termination commit\n   * @param {boolean} includeTotalTime - Whether to include total time in the commit data\n   * @return {object|Array} The rendered CMI data\n   */\n  renderCommitCMI(\n    terminateCommit: boolean,\n    includeTotalTime: boolean = false,\n  ): StringKeyMap | Array<any> {\n    const cmiExport = this.renderCMIExport(terminateCommit, includeTotalTime);\n    const sharedData = this.captureSharedData();\n\n    const flattened: StringKeyMap = flatten(cmiExport);\n    switch (this.context.getSettings().dataCommitFormat) {\n      case \"flattened\":\n        return flattened;\n      case \"params\":\n        return Object.entries(flattened).map(([item, value]) => `${item}=${value}`);\n      case \"json\":\n      default:\n        // Compact SCORM 2004 commits are the payload itself (rather than a\n        // runtimeData wrapper), so preserve sharedData at its top level.\n        if (sharedData) {\n          cmiExport.sharedData = sharedData;\n        }\n        return cmiExport;\n    }\n  }\n\n  /** Render the runtime CMI envelope without compact-commit metadata. */\n  private renderCMIExport(terminateCommit: boolean, includeTotalTime: boolean): StringKeyMap {\n    const cmiExport: StringKeyMap = this.context.renderCMIToJSONObject();\n    // The structured commit's runtimeData includes the active CMI model and the currently mapped\n    // SCORM 2004 ADL data buckets. Navigation state belongs to sequencing persistence, not the\n    // per-SCO runtime envelope.\n    if (this.context.adl && this.context.adl.data._count > 0) {\n      cmiExport.adl = {\n        data: JSON.parse(JSON.stringify(this.context.adl.data)),\n      };\n    }\n\n    if (terminateCommit || includeTotalTime) {\n      // Add total_time to the exported cmi object\n      (cmiExport.cmi as StringKeyMap).total_time = this.context.cmi.getCurrentTotalTime();\n    } else {\n      // Remove total_time from export when not terminating\n      delete (cmiExport.cmi as StringKeyMap).total_time;\n    }\n    return cmiExport;\n  }\n\n  private captureSharedData(): Record<string, string> | null {\n    if (\n      !this.context.adl ||\n      typeof this.context.adl.captureWritableSharedDataSnapshot !== \"function\"\n    ) {\n      return null;\n    }\n    const sharedData = this.context.adl.captureWritableSharedDataSnapshot();\n    return Object.keys(sharedData).length > 0 ? sharedData : null;\n  }\n\n  /**\n   * Render the cmi object to the proper format for LMS commit\n   * @param {boolean} terminateCommit - Whether this is a termination commit\n   * @param {boolean} includeTotalTime - Whether to include total time in the commit data\n   * @return {CommitObject} The commit object\n   */\n  renderCommitObject(terminateCommit: boolean, includeTotalTime: boolean = false): CommitObject {\n    const cmiExport = this.renderCommitCMI(terminateCommit, includeTotalTime);\n    // renderCommitCMI adds compact-only metadata at the payload root. Structured commits expose\n    // that metadata beside runtimeData instead, retaining the pre-existing runtimeData format.\n    if (!Array.isArray(cmiExport)) {\n      delete cmiExport.sharedData;\n    }\n    const calculateTotalTime = terminateCommit || includeTotalTime;\n    const totalTimeDuration = calculateTotalTime ? this.context.cmi.getCurrentTotalTime() : \"\";\n    const totalTimeSeconds = getDurationAsSeconds(totalTimeDuration, scorm2004_regex.CMITimespan);\n\n    let completionStatus = CompletionStatus.UNKNOWN;\n    let successStatus = SuccessStatus.UNKNOWN;\n    if (this.context.cmi.completion_status) {\n      if (this.context.cmi.completion_status === \"completed\") {\n        completionStatus = CompletionStatus.COMPLETED;\n      } else if (this.context.cmi.completion_status === \"incomplete\") {\n        completionStatus = CompletionStatus.INCOMPLETE;\n      }\n    }\n    if (this.context.cmi.success_status) {\n      if (this.context.cmi.success_status === \"passed\") {\n        successStatus = SuccessStatus.PASSED;\n      } else if (this.context.cmi.success_status === \"failed\") {\n        successStatus = SuccessStatus.FAILED;\n      }\n    }\n\n    // Structured top-level fields represent the LMS course result. The CMI export remains the\n    // active SCO's runtime data. In a sequenced course the course result is the root activity's\n    // rolled-up tracking state on every commit, not only at the session boundary: a SCO can be\n    // complete/passed while the course root is still incomplete (a pre-test), and a resumed SCO\n    // reports its own passed status while the course root is known-failed. Reporting the SCO's\n    // CMI as the course result on an ordinary commit lets one SCO's status overwrite the course.\n    // @spec SCORM 2004 4th Ed. SN RB.1 (Overall Rollup Process): the tracking status of the\n    // root activity is the course status; a leaf's status contributes only through rollup.\n    const sequencingRoot = this.context.sequencingService?.getSequencingState().rootActivity;\n    if (sequencingRoot) {\n      completionStatus = sequencingRoot.completionStatus ?? CompletionStatus.UNKNOWN;\n      successStatus = sequencingRoot.successStatus ?? SuccessStatus.UNKNOWN;\n    }\n\n    let scoreObject: ScoreObject = this.context.cmi?.score?.getScoreObject() || {};\n    if (sequencingRoot) {\n      const primaryObjective = sequencingRoot.primaryObjective;\n      const hasCourseScore =\n        sequencingRoot.objectiveMeasureStatus ||\n        primaryObjective?.rawScoreKnown === true ||\n        primaryObjective?.minScoreKnown === true ||\n        primaryObjective?.maxScoreKnown === true;\n\n      if (hasCourseScore) {\n        // At a sequencing boundary the active CMI model still belongs to one SCO. Report the\n        // root activity's rolled-up measure as the course score, just as the structured statuses\n        // above report the root rather than whichever SCO happened to terminate last.\n        scoreObject = {};\n        if (sequencingRoot.objectiveMeasureStatus) {\n          scoreObject.scaled = sequencingRoot.objectiveNormalizedMeasure;\n        }\n        if (primaryObjective?.rawScoreKnown) {\n          scoreObject.raw = Number(primaryObjective.rawScore);\n        }\n        if (primaryObjective?.minScoreKnown) {\n          scoreObject.min = Number(primaryObjective.minScore);\n        }\n        if (primaryObjective?.maxScoreKnown) {\n          scoreObject.max = Number(primaryObjective.maxScore);\n        }\n      }\n    }\n    const commitObject: CommitObject = {\n      completionStatus: completionStatus,\n      successStatus: successStatus,\n      totalTimeSeconds: totalTimeSeconds,\n      runtimeData: cmiExport as StringKeyMap,\n    };\n    const sharedData = this.captureSharedData();\n    if (sharedData) {\n      commitObject.sharedData = sharedData;\n    }\n    if (scoreObject) {\n      commitObject.score = scoreObject;\n    }\n\n    // Populate metadata if enabled\n    const metaSettings = this.context.getSettings();\n    if (metaSettings.autoPopulateCommitMetadata) {\n      if (metaSettings.courseId) {\n        commitObject.courseId = metaSettings.courseId;\n      }\n      if (metaSettings.scoId) {\n        commitObject.scoId = metaSettings.scoId;\n      }\n      if (this.context.cmi.learner_id) {\n        commitObject.learnerId = this.context.cmi.learner_id;\n      }\n      if (this.context.cmi.learner_name) {\n        commitObject.learnerName = this.context.cmi.learner_name;\n      }\n      // For SCORM 2004, also populate activityId if available from sequencing\n      const sequencingState = this.context.sequencingService?.getSequencingState();\n      if (sequencingState?.currentActivity?.id) {\n        commitObject.activityId = sequencingState.currentActivity.id;\n      }\n    }\n\n    if (this.globalObjectiveManager) {\n      // Global objective map values are LMS tracking data. Include the synchronized snapshot in\n      // every structured commit so objectivesGlobalToSystem can persist them across course\n      // registrations instead of limiting them to the current in-memory sequencing session.\n      // A normal RTE Commit does not end the activity attempt, so it must not publish current SCO\n      // values into sequencing tracking data. The End Attempt Process performs that transfer.\n      // @spec SCORM 2004 4th Ed. SN TB.2.3 / UP.4 and TR SX-04a / SX-04b\n      // @spec SCORM 2004 4th Ed. SN 3.10.3 - Objective Map Resolution\n      commitObject.globalObjectives = this.globalObjectiveManager.captureGlobalObjectiveSnapshot();\n    }\n\n    return commitObject;\n  }\n\n  /**\n   * Determines the appropriate cmi.entry value based on previous exit state.\n   * Per SCORM 2004 RTE 4.2.11 (cmi.entry) and 4.2.12 (cmi.exit):\n   *\n   * - If previous exit was \"suspend\": \"resume\" (learner suspended, wants to continue)\n   * - If previous exit was \"logout\": \"\" (deprecated, attempt ended)\n   * - If previous exit was \"normal\": \"\" (attempt completed normally)\n   * - If previous exit was \"time-out\":\n   *   - With suspend data: \"resume\" (resuming from interrupted session)\n   *   - Without suspend data: \"\" (session ended)\n   * - If no previous exit or unrecognized: \"ab-initio\" (fresh start)\n   *\n   * @param {string} previousExit - The cmi.exit value from the previous session\n   * @param {boolean} hasSuspendData - Whether suspend_data exists from previous session\n   * @return {string} The appropriate cmi.entry value (\"ab-initio\", \"resume\", or \"\")\n   */\n  determineEntryValue(previousExit: string, hasSuspendData: boolean): string {\n    // Trim whitespace to handle edge cases\n    const trimmedExit = previousExit?.trim();\n\n    // No previous exit or empty exit means first-time entry\n    // Per SCORM 2004 spec Rule 1: ab-initio when this is the first learner session\n    if (\n      previousExit === \"\" ||\n      previousExit === undefined ||\n      previousExit === null ||\n      trimmedExit === \"\"\n    ) {\n      return \"ab-initio\";\n    }\n\n    // Per SCORM 2004 spec Rule 2: resume when previous exit was \"suspend\"\n    if (previousExit === \"suspend\") {\n      return \"resume\";\n    }\n\n    // Per SCORM 2004 spec: logout and normal always mean empty string\n    // (learner previously accessed SCO but didn't suspend)\n    if (previousExit === \"logout\" || previousExit === \"normal\") {\n      return \"\";\n    }\n\n    // Per SCORM 2004 spec: time-out returns \"\" (or possibly \"resume\" if suspend data exists)\n    // The spec allows resume for time-out when there's suspend data from earlier\n    if (previousExit === \"time-out\") {\n      return hasSuspendData ? \"resume\" : \"\";\n    }\n\n    // Unknown/invalid exit values indicate the learner has accessed the SCO before\n    // but conditions for ab-initio or resume aren't met, so return empty string\n    return \"\";\n  }\n}\n","import BaseAPI from \"./BaseAPI\";\nimport {\n  ParsedNavigationRequest,\n  StringKeyMap,\n  parseNavigationRequest,\n  stringMatches,\n} from \"./utilities\";\nimport { BaseCMI } from \"./cmi/common/base_cmi\";\nimport { CMIArray } from \"./cmi/common/array\";\nimport { CMI } from \"./cmi/scorm2004/cmi\";\nimport { CMIObjectivesObject } from \"./cmi/scorm2004/objectives\";\nimport { CMIInteractionsObject } from \"./cmi/scorm2004/interactions\";\nimport { ADL } from \"./cmi/scorm2004/adl\";\nimport { Sequencing } from \"./cmi/scorm2004/sequencing/sequencing\";\nimport {\n  Activity,\n  ActivityObjective,\n  ActivityObjectiveReadState,\n} from \"./cmi/scorm2004/sequencing/activity\";\nimport {\n  GlobalObjective,\n  GlobalObjectiveSynchronizer,\n} from \"./cmi/scorm2004/sequencing/objectives/global_objective_synchronizer\";\nimport {\n  CompletionStatus,\n  global_constants,\n  LogLevelEnum,\n  scorm2004_constants,\n  scorm2004_errors,\n  scorm2004_regex,\n  SuccessStatus,\n} from \"./constants\";\nimport {\n  ActivitySettings,\n  CommitObject,\n  CommitTrigger,\n  GlobalObjectiveMapEntry,\n  ResetOptions,\n  ResultObject,\n  RollupRulesSettings,\n  SequencingCollectionSettings,\n  SequencingControlsSettings,\n  SequencingRulesSettings,\n  SequencingSettings,\n  SequencingStateMetadata,\n  Settings,\n} from \"./types\";\nimport { IHttpService } from \"./interfaces\";\nimport { SequencingConfiguration, SequencingEventListeners, SequencingService } from \"./services\";\nimport type { NavigationPreview } from \"./types/sequencing_types\";\n\n// Import extracted classes\nimport {\n  Scorm2004ResponseValidator,\n  ValidationContext,\n} from \"./handlers/scorm2004/response_validator\";\nimport { Scorm2004CMIHandler, CMIHandlerContext } from \"./handlers/scorm2004/cmi_handler\";\nimport { ActivityTreeBuilder } from \"./configuration/activity_tree_builder\";\nimport { SequencingConfigurationBuilder } from \"./configuration/sequencing_configuration_builder\";\nimport {\n  GlobalObjectiveManager,\n  GlobalObjectiveContext,\n} from \"./objectives/global_objective_manager\";\nimport {\n  SequencingStatePersistence,\n  PersistenceContext,\n} from \"./persistence/sequencing_state_persistence\";\nimport {\n  Scorm2004DataSerializer,\n  DataSerializerContext,\n} from \"./serialization/scorm2004_data_serializer\";\n\n/**\n * Implemented, writable SCORM 2004 elements that have NO spec-defined default\n * value. Per IEEE 1484.11.2 / SCORM 2004 RTE, GetValue of one of these before it\n * has been set must return \"\" with error 403 (VALUE_NOT_INITIALIZED).\n *\n * Excluded by design: elements with a vocabulary/computed default (mode, credit,\n * entry, completion_status, success_status, total_time), the keyword/identity\n * elements (_version, _children, _count, learner_id, learner_name, launch_data),\n * and array `.id` (a missing array entry already yields 403 during traversal).\n *\n * Array indices are normalized to \"N\" for lookup (see {@link normalizeCMIIndices}).\n */\nconst NO_DEFAULT_2004_ELEMENTS: ReadonlySet<string> = new Set<string>([\n  \"cmi.suspend_data\",\n  \"cmi.location\",\n  \"cmi.scaled_passing_score\",\n  \"cmi.max_time_allowed\",\n  \"cmi.completion_threshold\",\n  \"cmi.progress_measure\",\n  \"cmi.score.scaled\",\n  \"cmi.score.raw\",\n  \"cmi.score.min\",\n  \"cmi.score.max\",\n  \"cmi.objectives.N.score.scaled\",\n  \"cmi.objectives.N.score.raw\",\n  \"cmi.objectives.N.score.min\",\n  \"cmi.objectives.N.score.max\",\n  \"cmi.objectives.N.progress_measure\",\n  \"cmi.objectives.N.description\",\n  \"cmi.interactions.N.weighting\",\n  \"cmi.interactions.N.type\",\n  \"cmi.interactions.N.timestamp\",\n  \"cmi.interactions.N.result\",\n  \"cmi.interactions.N.latency\",\n  \"cmi.interactions.N.learner_response\",\n  \"cmi.interactions.N.description\",\n  \"cmi.comments_from_learner.N.timestamp\",\n  \"adl.data.N.store\",\n]);\n\n/** Replace each numeric array-index segment with \"N\" so paths match the table. */\nfunction normalizeCMIIndices(CMIElement: string): string {\n  return CMIElement.replace(/\\.\\d+(?=\\.|$)/g, \".N\");\n}\n\n/**\n * API class for SCORM 2004\n */\nclass Scorm2004API extends BaseAPI {\n  private _version: string = \"1.0\";\n  private readonly _sequencing: Sequencing;\n  private _sequencingService: SequencingService | null = null;\n  private _restoringFromJSON = false;\n  private readonly _runtimeSetCMIElements = new Set<string>();\n  private _extractedScoItemIds: string[] = [];\n  private _sequencingCollections: Record<string, SequencingCollectionSettings> = {};\n\n  // Extracted class instances\n  private _responseValidator: Scorm2004ResponseValidator;\n  private _cmiHandler: Scorm2004CMIHandler;\n  private _activityTreeBuilder: ActivityTreeBuilder;\n  private _sequencingConfigBuilder: SequencingConfigurationBuilder;\n  private _globalObjectiveManager: GlobalObjectiveManager;\n  private _statePersistence: SequencingStatePersistence | null = null;\n  private _dataSerializer: Scorm2004DataSerializer;\n\n  /**\n   * Constructor for SCORM 2004 API\n   * @param {Settings} settings\n   * @param {IHttpService} httpService - Optional HTTP service instance\n   */\n  constructor(settings?: Settings, httpService?: IHttpService) {\n    const settingsCopy = settings ? { ...settings } : undefined;\n    if (settingsCopy) {\n      if (settingsCopy.mastery_override === undefined) {\n        settingsCopy.mastery_override = false;\n      }\n    }\n    super(scorm2004_errors, settingsCopy, httpService);\n\n    this.cmi = new CMI();\n    this.adl = new ADL();\n    this._sequencing = new Sequencing();\n\n    // Connect the sequencing object to the ADL's sequencing property\n    this.adl.sequencing = this._sequencing;\n\n    // Initialize extracted classes\n    this._sequencingConfigBuilder = new SequencingConfigurationBuilder();\n    this._activityTreeBuilder = new ActivityTreeBuilder({}, this._sequencingConfigBuilder);\n\n    // Create validation context - use arrow functions to ensure lazy evaluation\n    // Note: checkCorrectResponseValue calls the validator directly since it's a pass-through\n    const validationContext: ValidationContext = {\n      throwSCORMError: (element: string, errorCode: number, message?: string) =>\n        this.throwSCORMError(element, errorCode, message),\n      getLastErrorCode: () => this.lastErrorCode,\n      checkCorrectResponseValue: (\n        CMIElement: string,\n        interaction_type: string,\n        nodes: Array<any>,\n        value: any,\n      ) =>\n        this._responseValidator.checkCorrectResponseValue(\n          CMIElement,\n          interaction_type,\n          nodes,\n          value,\n        ),\n    };\n    this._responseValidator = new Scorm2004ResponseValidator(validationContext);\n\n    // Create CMI handler context - use arrow functions to ensure spies work correctly\n    const cmiHandlerContext: CMIHandlerContext = {\n      cmi: this.cmi,\n      isInitialized: () => this.isInitialized(),\n      throwSCORMError: (element: string, errorCode: number, message?: string) =>\n        this.throwSCORMError(element, errorCode, message),\n      getLastErrorCode: () => this.lastErrorCode,\n    };\n    this._cmiHandler = new Scorm2004CMIHandler(cmiHandlerContext, this._responseValidator);\n\n    // Initialize global objective manager context - use getter to always get current settings\n    const globalObjectiveContext: GlobalObjectiveContext = {\n      getSettings: () => this.settings,\n      hostDeclaredGlobalObjectiveIds: [...(settingsCopy?.globalObjectiveIds ?? [])],\n      cmi: this.cmi,\n      sequencing: this._sequencing,\n      sequencingService: this._sequencingService,\n      commonSetCMIValue: this._commonSetCMIValue.bind(this),\n    };\n    this._globalObjectiveManager = new GlobalObjectiveManager(globalObjectiveContext);\n\n    // Initialize data serializer - use getter to always get current settings\n    const dataSerializerContext: DataSerializerContext = {\n      getSettings: () => this.settings,\n      cmi: this.cmi,\n      adl: this.adl,\n      sequencingService: this._sequencingService,\n      renderCMIToJSONObject: this.renderCMIToJSONObject.bind(this),\n    };\n    this._dataSerializer = new Scorm2004DataSerializer(\n      dataSerializerContext,\n      this._globalObjectiveManager,\n    );\n\n    // Configure sequencing if settings are provided\n    if (settingsCopy?.sequencing) {\n      this.configureSequencing(settingsCopy.sequencing);\n    }\n\n    // Initialize sequencing service\n    this.initializeSequencingService(settingsCopy);\n\n    // Rename functions to match 2004 Spec and expose to modules\n    this.Initialize = this.lmsInitialize;\n    this.Terminate = this.lmsFinish;\n    this.GetValue = this.lmsGetValue;\n    this.SetValue = this.lmsSetValue;\n    this.Commit = this.lmsCommit;\n    this.GetLastError = this.lmsGetLastError;\n    this.GetErrorString = this.lmsGetErrorString;\n    this.GetDiagnostic = this.lmsGetDiagnostic;\n  }\n\n  public cmi: CMI;\n  public adl: ADL;\n\n  public Initialize: (parameter?: string) => string;\n  public Terminate: (parameter?: string) => string;\n  public GetValue: (CMIElement: string) => string;\n  public SetValue: (CMIElement: string, value: any) => string;\n  public Commit: (parameter?: string) => string;\n  public GetLastError: () => string;\n  public GetErrorString: (CMIErrorCode: string | number) => string;\n  public GetDiagnostic: (CMIErrorCode: string | number) => string;\n\n  /**\n   * Called when the API needs to be reset\n   *\n   * @param {Settings} settings - Optional new settings to merge with existing settings\n   * @param {ResetOptions} options - Behavior for this reset only\n   * @spec SCORM 2004 4th Ed. RTE 4.4 (adl.nav.request_valid) - navigation validity is LMS-determined, not per-SCO run-time data.\n   * @spec SN Book: NB.2.1 (Navigation Request Process) - refresh validity for the current sequencing activity after a SCO reset.\n   */\n  reset(settings?: Settings, options?: ResetOptions) {\n    this.commonReset(settings, options);\n    this._runtimeSetCMIElements.clear();\n\n    this.cmi?.reset();\n    if (options?.resetTotalTime === true) {\n      this.cmi.total_time = \"PT0S\";\n    }\n    this.adl?.reset();\n    this.applyCurrentActivityLaunchData();\n\n    // @spec SCORM 2004 4th Ed. RTE 4.4; SN Book: NB.2.1 - restore the LMS navigation connection and validity only for a delivered activity.\n    if (this._sequencing?.getCurrentActivity()) {\n      this.adl.sequencing = this._sequencing;\n      this._sequencing.overallSequencingProcess?.updateNavigationValidity();\n    }\n  }\n\n  /**\n   * Apply launch-static activity data to CMI while the new SCO is pre-initialize.\n   *\n   * @spec SCORM 2004 4th Ed. RTE 4.2.5, Table 4.2.5a - cmi.completion_threshold\n   * @spec SCORM 2004 4th Ed. RTE 4.2.17, Table 4.2.17a - cmi.objectives\n   */\n  private applyCurrentActivityLaunchData(): void {\n    const currentActivity = this._sequencing?.getCurrentActivity();\n    if (!currentActivity) {\n      return;\n    }\n\n    this.adl.configureSharedDataMaps(currentActivity.sharedDataMaps);\n    this.applyActivityLaunchData(currentActivity);\n  }\n\n  /**\n   * Apply launch-static CMI data when sequencing delivers a new activity before SCO Initialize.\n   *\n   * @spec SCORM 2004 4th Ed. SN DB.2 - Content Delivery Environment Process establishes the delivered activity.\n   * @spec SCORM 2004 4th Ed. RTE 4.2.5, Table 4.2.5a - cmi.completion_threshold is initialized before SCO access.\n   * @spec SCORM 2004 4th Ed. RTE 4.2.17, Table 4.2.17a - cmi.objectives is initialized before SCO access.\n   */\n  private applyDeliveredActivityLaunchData(activity: Activity): void {\n    this.adl.configureSharedDataMaps(activity.sharedDataMaps);\n    // @spec SCORM 2004 4th Ed. RTE 3.1.6 - API Instance State Transition;\n    // launch data is prepared before the SCO opens its communication session.\n    if (!this.isNotInitialized()) {\n      return;\n    }\n\n    this.applyActivityLaunchData(activity);\n  }\n\n  /**\n   * Copy the delivered activity's static launch data into the fresh CMI model.\n   *\n   * @spec SCORM 2004 4th Ed. RTE 4.2.5, Table 4.2.5a - cmi.completion_threshold\n   * @spec SCORM 2004 4th Ed. RTE 4.2.17, Table 4.2.17a - cmi.objectives\n   */\n  private applyActivityLaunchData(currentActivity: Activity): void {\n    if (!this.cmi) {\n      return;\n    }\n\n    const contentActivityData =\n      this._sequencing.overallSequencingProcess?.getContentActivityData(currentActivity);\n    const completionThreshold =\n      contentActivityData?.completionThreshold ??\n      currentActivity.completionThreshold?.toString() ??\n      \"\";\n\n    this.cmi.completion_threshold = completionThreshold;\n    this.seedCurrentActivityObjectives(currentActivity);\n  }\n\n  /**\n   * Seed CMI objective ids after Initialize when automatic sequencing starts during Initialize.\n   *\n   * @spec SCORM 2004 4th Ed. RTE 4.2.17, Table 4.2.17a - cmi.objectives\n   */\n  private applyCurrentActivityObjectiveData(): void {\n    const currentActivity = this._sequencing?.getCurrentActivity();\n    if (!this.cmi || !currentActivity) {\n      return;\n    }\n\n    this.seedCurrentActivityObjectives(currentActivity);\n  }\n\n  /**\n   * Seed CMI objectives from primary and secondary activity objectives.\n   *\n   * @spec SCORM 2004 4th Ed. RTE 4.2.17 - Initialization of Run-Time Objectives from Sequencing Information\n   * @spec SCORM 2004 4th Ed. RTE 4.2.17, Table 4.2.17a - cmi.objectives.n.id and success_status\n   * @spec SCORM 2004 4th Ed. SN 3.10.3 / ADLSEQ objectives extension - objective read maps seed the RTE view\n   */\n  private seedCurrentActivityObjectives(currentActivity: Activity): void {\n    const activityObjectives: ActivityObjective[] = [];\n\n    if (currentActivity.primaryObjective) {\n      activityObjectives.push(currentActivity.primaryObjective);\n    }\n\n    activityObjectives.push(...currentActivity.objectives);\n\n    const seededObjectiveIds = new Set<string>();\n    for (const activityObjective of activityObjectives) {\n      const objectiveId = this.getSeedableObjectiveId(activityObjective);\n      if (!objectiveId || seededObjectiveIds.has(objectiveId)) {\n        continue;\n      }\n      seededObjectiveIds.add(objectiveId);\n\n      const index = this.findOrSeedCMIObjective(objectiveId);\n      if (index === null) {\n        continue;\n      }\n\n      const cmiObjective = this.cmi.objectives.findObjectiveByIndex(index);\n      if (cmiObjective && this.cmi.objectives.initialized && !cmiObjective.initialized) {\n        cmiObjective.initialize();\n      }\n\n      const successStatus = this.getActivityObjectiveSuccessStatus(activityObjective);\n      if (successStatus) {\n        this._commonSetCMIValue(\n          \"SeedActivityObjective\",\n          true,\n          `cmi.objectives.${index}.success_status`,\n          successStatus,\n        );\n      }\n\n      this.seedObjectiveReadMapValues(currentActivity, activityObjective, index);\n    }\n  }\n\n  /**\n   * Seed CMI objective fields from this objective's read-mapped global objectives.\n   *\n   * @spec SCORM 2004 4th Ed. RTE 4.2.17 - Run-Time Objectives are initialized from sequencing information\n   * @spec SCORM 2004 4th Ed. SN 3.10.3 - read mapInfo grants access to mapped global objective state\n   * @spec SCORM 2004 4th Ed. ADLSEQ objectives extension - raw/min/max score read maps seed RTE score fields\n   */\n  private seedObjectiveReadMapValues(\n    currentActivity: Activity,\n    activityObjective: ActivityObjective,\n    objectiveIndex: number,\n  ): void {\n    const globalObjectiveMap = this._sequencing.overallSequencingProcess?.getGlobalObjectiveMap();\n    if (!globalObjectiveMap || activityObjective.mapInfo.length === 0) {\n      return;\n    }\n\n    for (const mapInfo of activityObjective.mapInfo) {\n      const targetObjectiveId = mapInfo.targetObjectiveID || activityObjective.id;\n      const globalObjective = globalObjectiveMap.get(targetObjectiveId) as\n        GlobalObjective | undefined;\n      if (!globalObjective) {\n        continue;\n      }\n\n      const readState = GlobalObjectiveSynchronizer.getGlobalObjectiveReadState(\n        currentActivity,\n        activityObjective,\n        mapInfo,\n        globalObjective,\n        // @spec SCORM 2004 4th Ed. SN 3.10.3: read and write mapInfo flags are\n        // independent; delivery initializes the local objective from the global value.\n        {\n          restrictToFreshWrites: false,\n          allowSatisfiedStatus: true,\n          allowNormalizedMeasure: true,\n        },\n      );\n      this.applyObjectiveReadStateToCMI(objectiveIndex, readState);\n    }\n  }\n\n  /**\n   * Copy mapped global objective state into the seeded CMI objective entry.\n   *\n   * @spec SCORM 2004 4th Ed. RTE 4.2.17, Table 4.2.17a - cmi.objectives launch-time initialization\n   * @spec SCORM 2004 4th Ed. SN 3.10.3 - read maps populate the RTE view without creating local writes\n   * @spec SCORM 2004 4th Ed. ADLSEQ objectives extension - raw/min/max score read maps populate CMI objective scores\n   */\n  private applyObjectiveReadStateToCMI(\n    objectiveIndex: number,\n    readState: ActivityObjectiveReadState,\n  ): void {\n    // @spec SCORM 2004 4th Ed. SN 3.10.3 - unknown global satisfied status\n    // leaves cmi.objectives.n.success_status at its default unknown value.\n    if (readState.satisfiedStatus !== undefined) {\n      this._commonSetCMIValue(\n        \"SeedActivityObjectiveReadMap\",\n        true,\n        `cmi.objectives.${objectiveIndex}.success_status`,\n        readState.satisfiedStatus ? SuccessStatus.PASSED : SuccessStatus.FAILED,\n      );\n    }\n\n    // @spec SCORM 2004 4th Ed. SN 3.10.3 - unknown global normalized measure\n    // leaves cmi.objectives.n.score.scaled uninitialized.\n    if (readState.normalizedMeasure !== undefined) {\n      this._commonSetCMIValue(\n        \"SeedActivityObjectiveReadMap\",\n        true,\n        `cmi.objectives.${objectiveIndex}.score.scaled`,\n        String(readState.normalizedMeasure),\n      );\n    }\n\n    // @spec SCORM 2004 4th Ed. SN 3.10.3 - unknown global completion status\n    // leaves cmi.objectives.n.completion_status at its default unknown value.\n    if (readState.completionStatus !== undefined) {\n      this._commonSetCMIValue(\n        \"SeedActivityObjectiveReadMap\",\n        true,\n        `cmi.objectives.${objectiveIndex}.completion_status`,\n        readState.completionStatus,\n      );\n    }\n\n    // @spec SCORM 2004 4th Ed. SN 3.10.3 - unknown global progress measure\n    // leaves cmi.objectives.n.progress_measure uninitialized.\n    if (readState.progressMeasure !== undefined) {\n      this._commonSetCMIValue(\n        \"SeedActivityObjectiveReadMap\",\n        true,\n        `cmi.objectives.${objectiveIndex}.progress_measure`,\n        String(readState.progressMeasure),\n      );\n    }\n\n    // @spec SCORM 2004 4th Ed. ADLSEQ objectives extension - unknown global\n    // raw score leaves cmi.objectives.n.score.raw uninitialized.\n    if (readState.rawScore !== undefined) {\n      this._commonSetCMIValue(\n        \"SeedActivityObjectiveReadMap\",\n        true,\n        `cmi.objectives.${objectiveIndex}.score.raw`,\n        readState.rawScore,\n      );\n    }\n\n    // @spec SCORM 2004 4th Ed. ADLSEQ objectives extension - unknown global\n    // min score leaves cmi.objectives.n.score.min uninitialized.\n    if (readState.minScore !== undefined) {\n      this._commonSetCMIValue(\n        \"SeedActivityObjectiveReadMap\",\n        true,\n        `cmi.objectives.${objectiveIndex}.score.min`,\n        readState.minScore,\n      );\n    }\n\n    // @spec SCORM 2004 4th Ed. ADLSEQ objectives extension - unknown global\n    // max score leaves cmi.objectives.n.score.max uninitialized.\n    if (readState.maxScore !== undefined) {\n      this._commonSetCMIValue(\n        \"SeedActivityObjectiveReadMap\",\n        true,\n        `cmi.objectives.${objectiveIndex}.score.max`,\n        readState.maxScore,\n      );\n    }\n  }\n\n  /**\n   * Return a manifest-defined objective id that can initialize cmi.objectives.n.id.\n   *\n   * @spec SCORM 2004 4th Ed. RTE 4.2.17, Table 4.2.17a - cmi.objectives.n.id\n   */\n  private getSeedableObjectiveId(activityObjective: ActivityObjective): string | null {\n    const objectiveId: unknown = activityObjective.id;\n    if (typeof objectiveId !== \"string\" || objectiveId.trim() === \"\") {\n      return null;\n    }\n    return objectiveId;\n  }\n\n  /**\n   * Find an existing CMI objective id or create the next CMI objective array entry.\n   *\n   * @spec SCORM 2004 4th Ed. RTE 4.2.17, Table 4.2.17a - cmi.objectives._count\n   * @spec SCORM 2004 4th Ed. RTE 4.2.17, Table 4.2.17a - cmi.objectives.n.id\n   */\n  private findOrSeedCMIObjective(objectiveId: string): number | null {\n    const existingIndex = this.cmi.objectives.childArray.findIndex((objective) => {\n      return (objective as CMIObjectivesObject).id === objectiveId;\n    });\n\n    if (existingIndex >= 0) {\n      return existingIndex;\n    }\n\n    const index = this.cmi.objectives.childArray.length;\n    const result = this._commonSetCMIValue(\n      \"SeedActivityObjective\",\n      true,\n      `cmi.objectives.${index}.id`,\n      objectiveId,\n    );\n\n    return result === global_constants.SCORM_TRUE ? index : null;\n  }\n\n  /**\n   * Translate a known activity objective satisfied status to cmi.objectives.n.success_status.\n   *\n   * @spec SCORM 2004 4th Ed. RTE 4.2.17, Table 4.2.17a - cmi.objectives.n.success_status\n   */\n  private getActivityObjectiveSuccessStatus(\n    activityObjective: ActivityObjective,\n  ): SuccessStatus | null {\n    if (activityObjective.progressStatus || activityObjective.satisfiedStatusKnown) {\n      return activityObjective.satisfiedStatus ? SuccessStatus.PASSED : SuccessStatus.FAILED;\n    }\n\n    return null;\n  }\n\n  /**\n   * Getter for _version\n   * @return {string}\n   */\n  get version(): string {\n    return this._version;\n  }\n\n  /**\n   * Getter for _globalObjectives\n   * @return {CMIObjectivesObject[]} Array of global objective objects\n   */\n  get globalObjectives(): CMIObjectivesObject[] {\n    return this._globalObjectiveManager.globalObjectives;\n  }\n\n  /**\n   * Setter for _globalObjectives (for backward compatibility)\n   * @param {CMIObjectivesObject[]} objectives - Array of global objective objects\n   */\n  set _globalObjectives(objectives: CMIObjectivesObject[]) {\n    this._globalObjectiveManager.globalObjectives = objectives;\n  }\n\n  /**\n   * Getter for _globalObjectives (for backward compatibility with tests using bracket notation)\n   * @return {CMIObjectivesObject[]} Array of global objective objects\n   */\n  get _globalObjectives(): CMIObjectivesObject[] {\n    return this._globalObjectiveManager.globalObjectives;\n  }\n\n  /**\n   * Restore LMS-persisted global objective values before SCO initialization.\n   *\n   * @param {Record<string, GlobalObjectiveMapEntry>} snapshot - Persisted objective map values\n   *\n   * @spec SCORM 2004 4th Ed. SN 3.10.3 - read-mapped objectives use shared global state\n   */\n  restoreGlobalObjectiveSnapshot(snapshot: Record<string, GlobalObjectiveMapEntry>): void {\n    this._globalObjectiveManager.restoreGlobalObjectiveSnapshot(snapshot);\n  }\n\n  /** Restore the LMS-persisted SCORM 2004 shared-data stores. */\n  restoreSharedDataSnapshot(snapshot: Record<string, string>): void {\n    this.adl.restoreSharedDataSnapshot(snapshot);\n  }\n\n  /** Capture all SCORM 2004 shared-data stores, including non-current mappings. */\n  captureSharedDataSnapshot(): Record<string, string> {\n    return this.adl.captureSharedDataSnapshot();\n  }\n\n  /**\n   * Compress state data (delegates to persistence class)\n   * @param {string} data - Data to compress\n   * @return {string} Compressed data\n   */\n  compressStateData(data: string): string {\n    if (this._statePersistence) {\n      return this._statePersistence.compressStateData(data);\n    }\n    // Fallback: simple base64 encoding\n    if (typeof btoa !== \"undefined\") {\n      return btoa(encodeURIComponent(data));\n    }\n    return data;\n  }\n\n  /**\n   * Decompress state data (delegates to persistence class)\n   * @param {string} data - Data to decompress\n   * @return {string} Decompressed data\n   */\n  decompressStateData(data: string): string {\n    if (this._statePersistence) {\n      return this._statePersistence.decompressStateData(data);\n    }\n    // Fallback: simple base64 decoding\n    if (typeof atob !== \"undefined\") {\n      try {\n        return decodeURIComponent(atob(data));\n      } catch {\n        return data;\n      }\n    }\n    return data;\n  }\n\n  /**\n   * Initialize - Begins a communication session with the LMS\n   *\n   * @param {string} parameter - Must be an empty string per SCORM 2004 specification\n   * @return {string} \"true\" or \"false\"\n   */\n  lmsInitialize(parameter: string = \"\"): string {\n    if (parameter !== \"\") {\n      this.throwSCORMError(\"api\", this._error_codes.ARGUMENT_ERROR);\n      return global_constants.SCORM_FALSE;\n    }\n\n    this.restoreOfflineData();\n    this.cmi.initialize();\n    const result = this.initialize(\n      \"Initialize\",\n      \"LMS was already initialized!\",\n      \"LMS is already finished!\",\n    );\n\n    if (result === global_constants.SCORM_TRUE) {\n      this.adl.initialize();\n    }\n\n    if (result === global_constants.SCORM_TRUE && this._sequencingService) {\n      this._sequencingService.initialize();\n      this.applyCurrentActivityObjectiveData();\n    }\n\n    if (result === global_constants.SCORM_TRUE) {\n      this._globalObjectiveManager.restoreGlobalObjectivesToCMI();\n    }\n\n    if (\n      result === global_constants.SCORM_TRUE &&\n      this.settings.sequencingStatePersistence &&\n      this.settings.sequencingStatePersistence.autoLoadOnInitialize !== false\n    ) {\n      // @spec SCORM 2004 4th Ed. SN 4.2 Tracking Model Persistence - an LMS that must\n      // restore tracking before choosing the first delivery can preload it explicitly and\n      // suppress this compatibility auto-load. Initialize remains synchronous per the RTE API.\n      this.loadSequencingState().catch(() => {\n        this.apiLog(\"lmsInitialize\", \"Failed to auto-load sequencing state\", LogLevelEnum.WARN);\n      });\n    }\n\n    return result;\n  }\n\n  /**\n   * Terminate - Ends the communication session and persists data\n   *\n   * @param {string} parameter - Must be an empty string per SCORM 2004 specification\n   * @return {string} \"true\" or \"false\"\n   */\n  lmsFinish(parameter: string = \"\"): string {\n    if (parameter !== \"\") {\n      this.throwSCORMError(\"api\", this._error_codes.ARGUMENT_ERROR);\n      return global_constants.SCORM_FALSE;\n    }\n\n    const pendingNavRequest = this.adl?.nav?.request || \"_none_\";\n    const exitType = this.cmi?.getExitValueInternal() || \"\";\n    const wasAlreadyTerminated = this.isTerminated();\n    const deliveryInProgress = this._sequencingService?.isDeliveryInProgress() ?? false;\n    let normalizedRequest = pendingNavRequest;\n    let normalizedTarget = \"\";\n    const choiceJumpRegex = new RegExp(scorm2004_regex.NAVEvent);\n\n    if (pendingNavRequest !== \"_none_\") {\n      const matches = pendingNavRequest.match(choiceJumpRegex);\n      if (matches) {\n        if (matches.groups?.choice_target) {\n          normalizedTarget = matches.groups?.choice_target;\n          normalizedRequest = \"choice\";\n        } else if (matches.groups?.jump_target) {\n          normalizedTarget = matches.groups?.jump_target;\n          normalizedRequest = \"jump\";\n        }\n      }\n    }\n\n    let requestToProcess: string | null = null;\n    let targetForProcessing: string | undefined;\n    if (normalizedRequest !== \"_none_\") {\n      requestToProcess = normalizedRequest;\n      targetForProcessing = normalizedTarget || undefined;\n    } else if (this._sequencing.getCurrentActivity()) {\n      requestToProcess = \"exit\";\n    }\n\n    // Run termination tracking and objective-map writes before serializing the\n    // termination commit, but defer sequencing/delivery until the commit payload\n    // has been captured. Delivery listeners may synchronously reset CMI for the\n    // next SCO.\n    // @spec SCORM 2004 4th Ed. SN OP.1 and SM.7 - termination and objective map\n    //   writes precede sequencing/delivery and are persisted at the session boundary.\n    const preparedNavigation =\n      !wasAlreadyTerminated && !deliveryInProgress && requestToProcess && this._sequencingService\n        ? this._sequencingService.prepareNavigationRequest(\n            requestToProcess,\n            targetForProcessing,\n            exitType,\n          )\n        : null;\n\n    const result = this.terminate(\"Terminate\", true);\n\n    if (result !== global_constants.SCORM_TRUE && preparedNavigation && this._sequencingService) {\n      this._sequencingService.cancelPreparedNavigation(preparedNavigation);\n    }\n\n    if (\n      result === global_constants.SCORM_TRUE &&\n      !wasAlreadyTerminated &&\n      (this.settings.accumulateSessionTimeOnTerminate === true ||\n        this._sequencingService?.getSequencingState().isInitialized === true)\n    ) {\n      // terminate() has already serialized the completed session. Preserve that\n      // total when opted in, or when active sequencing needs it across delivery\n      // resets of SCO-local CMI data.\n      // @spec SCORM 2004 4th Ed. RTE 4.2.24 / 4.2.28\n      this.cmi.accumulateSessionTime();\n    }\n\n    if (result === global_constants.SCORM_TRUE && !wasAlreadyTerminated && !deliveryInProgress) {\n      let navigationHandled = false;\n      let sequencingAttempted = false;\n      let processedSequencingRequest: string | null = null;\n\n      if (this._sequencingService) {\n        try {\n          if (requestToProcess) {\n            // A prepared request proves that the internal engine was available\n            // and accepted the request for completion. If preparation was not\n            // possible, only invoke the compatibility path when the internal\n            // engine itself is unavailable; an available engine rejecting a\n            // request must not duplicate it through legacy listeners.\n            const sequencingAvailable =\n              this._sequencingService.getSequencingState().isInitialized === true;\n            sequencingAttempted = sequencingAvailable;\n            navigationHandled = preparedNavigation\n              ? this._sequencingService.completeNavigationRequest(preparedNavigation)\n              : this._sequencingService.processNavigationRequest(\n                  requestToProcess,\n                  targetForProcessing,\n                  exitType,\n                );\n            processedSequencingRequest = requestToProcess;\n          }\n        } catch (error) {\n          this.apiLog(\"lmsFinish\", `Sequencing navigation failed: ${error}`, LogLevelEnum.WARN);\n          navigationHandled = false;\n        }\n      }\n\n      if (!navigationHandled && !sequencingAttempted) {\n        if (pendingNavRequest !== \"_none_\") {\n          const navActions: { [key: string]: string } = {\n            continue: \"SequenceNext\",\n            previous: \"SequencePrevious\",\n            choice: \"SequenceChoice\",\n            jump: \"SequenceJump\",\n            exit: \"SequenceExit\",\n            exitAll: \"SequenceExitAll\",\n            abandon: \"SequenceAbandon\",\n            abandonAll: \"SequenceAbandonAll\",\n          };\n\n          const action = navActions[normalizedRequest];\n          if (action) {\n            this.processListeners(action, \"adl.nav.request\", normalizedTarget);\n          }\n        } else if (this.settings.autoProgress) {\n          this.processListeners(\"SequenceNext\", undefined, \"next\");\n        }\n      }\n\n      if (\n        this._sequencingService &&\n        processedSequencingRequest &&\n        [\"exitAll\", \"abandonAll\", \"suspendAll\"].includes(processedSequencingRequest)\n      ) {\n        this._sequencingService.terminate();\n      }\n\n      this.adl.nav.request = \"_none_\";\n    }\n\n    if (result === global_constants.SCORM_TRUE && !wasAlreadyTerminated) {\n      const autoSaveOn = this.settings.sequencingStatePersistence?.autoSaveOn ?? \"commit\";\n      if (this.settings.sequencingStatePersistence && [\"commit\", \"navigate\"].includes(autoSaveOn)) {\n        this.autoSaveSequencingState(\"lmsFinish\");\n      }\n    }\n\n    return result;\n  }\n\n  /**\n   * GetValue - Retrieves a value from the CMI data model\n   *\n   * @param {string} CMIElement - The CMI element path\n   * @return {string} The value of the element, or empty string\n   */\n  lmsGetValue(CMIElement: string): string {\n    // Per SCORM 2004 RTE Section 3.1.3.3: state checks must come before\n    // any data model element processing\n    if (this.isTerminated()) {\n      this.lastErrorCode = String(scorm2004_errors.RETRIEVE_AFTER_TERM);\n      return \"\";\n    }\n    if (!this.isInitialized()) {\n      this.lastErrorCode = String(scorm2004_errors.RETRIEVE_BEFORE_INIT);\n      return \"\";\n    }\n\n    if (CMIElement === \"adl.nav.request\") {\n      this.throwSCORMError(\n        CMIElement,\n        scorm2004_errors.WRITE_ONLY_ELEMENT,\n        \"adl.nav.request is write-only\",\n      );\n      return \"\";\n    }\n\n    const adlNavRequestRegex = \"^adl\\\\.nav\\\\.request_valid\\\\.(choice|jump)\\\\.{target=([^{}\\\\s]+)}$\";\n    if (stringMatches(CMIElement, adlNavRequestRegex)) {\n      const matches = CMIElement.match(adlNavRequestRegex);\n      if (matches) {\n        const request = matches[1];\n        const target = matches[2]?.replace(/{target=/g, \"\").replace(/}/g, \"\") || \"\";\n        if (request === \"choice\" || request === \"jump\") {\n          this.lastErrorCode = \"0\";\n          const overallProcess = this._sequencing?.overallSequencingProcess;\n\n          if (this.settings.scoItemIdValidator) {\n            return String(this.settings.scoItemIdValidator(target));\n          }\n\n          // Choice and jump have live sequencing predictors.\n          if (overallProcess?.predictChoiceEnabled && request === \"choice\") {\n            return overallProcess.predictChoiceEnabled(target) ? \"true\" : \"false\";\n          }\n\n          if (overallProcess?.predictJumpEnabled && request === \"jump\") {\n            return overallProcess.predictJumpEnabled(target) ? \"true\" : \"false\";\n          }\n\n          const staticValue = this.adl.nav.request_valid[request].getStaticValue(target);\n          if (staticValue !== undefined) {\n            return staticValue;\n          }\n\n          if (this._extractedScoItemIds.length > 0) {\n            return String(this._extractedScoItemIds.includes(target));\n          }\n          return String(this.settings?.scoItemIds?.includes(target));\n        }\n      }\n    }\n\n    if (CMIElement === \"cmi.completion_status\") {\n      return this._cmiHandler.evaluateCompletionStatus();\n    }\n\n    if (CMIElement === \"cmi.success_status\") {\n      return this._cmiHandler.evaluateSuccessStatus();\n    }\n\n    return this.getValue(\"GetValue\", true, CMIElement);\n  }\n\n  /**\n   * SetValue - Sets a value in the CMI data model\n   *\n   * @param {string} CMIElement - The CMI element path\n   * @param {any} value - The value to set\n   * @return {string} \"true\" or \"false\"\n   */\n  lmsSetValue(CMIElement: string, value: any): string {\n    const oldValue = this._peekCMIValue(CMIElement);\n\n    const result = this.setValue(\"SetValue\", \"Commit\", true, CMIElement, value);\n\n    if (result === global_constants.SCORM_TRUE) {\n      // @spec SCORM 2004 4th Ed. RTE 3.1.4.4 / 4.2.17 - remember writes\n      // made by the SCO during this attempt, excluding LMS launch seeding.\n      this._runtimeSetCMIElements.add(CMIElement);\n    }\n\n    if (result === global_constants.SCORM_TRUE && this._sequencingService) {\n      try {\n        this._sequencingService.triggerRollupOnCMIChange(CMIElement, oldValue, value);\n      } catch (rollupError) {\n        console.warn(`Sequencing rollup failed for ${CMIElement}: ${rollupError}`);\n      }\n    }\n\n    if (\n      result === global_constants.SCORM_TRUE &&\n      this.settings.sequencingStatePersistence?.autoSaveOn === \"setValue\"\n    ) {\n      const sequencingElements = [\n        \"cmi.completion_status\",\n        \"cmi.success_status\",\n        \"cmi.score.scaled\",\n        \"cmi.objectives\",\n        \"adl.nav.request\",\n      ];\n\n      if (sequencingElements.some((element) => CMIElement.startsWith(element))) {\n        this.saveSequencingState().catch(() => {\n          this.apiLog(\"lmsSetValue\", \"Failed to auto-save sequencing state\", LogLevelEnum.WARN);\n        });\n      }\n    }\n\n    return result;\n  }\n\n  /**\n   * Commit - Requests immediate persistence of data to the LMS\n   *\n   * @param {string} parameter - Must be an empty string per SCORM 2004 specification\n   * @return {string} \"true\" or \"false\"\n   */\n  lmsCommit(parameter: string = \"\"): string {\n    if (parameter !== \"\") {\n      this.throwSCORMError(\"api\", this._error_codes.ARGUMENT_ERROR);\n      return global_constants.SCORM_FALSE;\n    }\n\n    if (this.settings.throttleCommits) {\n      this.scheduleCommit(500, \"Commit\");\n      if (\n        this.settings.sequencingStatePersistence &&\n        (this.settings.sequencingStatePersistence.autoSaveOn ?? \"commit\") === \"commit\"\n      ) {\n        this.autoSaveSequencingState(\"lmsCommit\");\n      }\n      return global_constants.SCORM_TRUE;\n    } else {\n      const result = this.commit(\"Commit\", true);\n\n      if (\n        result === global_constants.SCORM_TRUE &&\n        this.settings.sequencingStatePersistence &&\n        (this.settings.sequencingStatePersistence.autoSaveOn ?? \"commit\") === \"commit\"\n      ) {\n        this.autoSaveSequencingState(\"lmsCommit\");\n      }\n\n      return result;\n    }\n  }\n\n  /**\n   * GetLastError - Returns the error code from the last API call\n   * @return {string} Error code as a string\n   */\n  lmsGetLastError(): string {\n    return this.getLastError(\"GetLastError\");\n  }\n\n  /**\n   * GetErrorString - Returns a short description for an error code\n   * @param {string|number} CMIErrorCode - The error code\n   * @return {string} Short error description\n   */\n  lmsGetErrorString(CMIErrorCode: string | number): string {\n    return this.getErrorString(\"GetErrorString\", CMIErrorCode);\n  }\n\n  /**\n   * GetDiagnostic - Returns detailed diagnostic information for an error\n   * @param {string|number} CMIErrorCode - The error code\n   * @return {string} Detailed diagnostic information\n   */\n  lmsGetDiagnostic(CMIErrorCode: string | number): string {\n    return this.getDiagnostic(\"GetDiagnostic\", CMIErrorCode);\n  }\n\n  /**\n   * Sets a value on the CMI Object\n   * @param {string} CMIElement\n   * @param {any} value\n   * @return {string}\n   */\n  /**\n   * Restore a previously stored CMI data model without republishing it to global objectives.\n   *\n   * loadFromJSON replays stored values through setCMIValue, which is the same entry point content\n   * uses. That makes an LMS-side restore indistinguishable from a fresh SetValue, so restoring an\n   * attempt whose cmi.objectives happens to name a global objective id would push those stored\n   * values back into the sequencing global objective map — overwriting whatever later attempts\n   * wrote and rolling shared objectives back to the moment this attempt was saved. Restored data is\n   * a replay of writes that already happened, so it must not trigger the write path again.\n   *\n   * @spec SCORM 2004 4th Ed. SN 3.10.3 - global objective writes originate from objective mapInfo,\n   *   not from re-loading persisted run-time data\n   */\n  override loadFromJSON(json: StringKeyMap, CMIElement: string = \"\"): void {\n    this._restoringFromJSON = true;\n    try {\n      super.loadFromJSON(json, CMIElement);\n    } finally {\n      this._restoringFromJSON = false;\n    }\n  }\n\n  /**\n   * Offline restore replays queued commits through setCMIValue directly, so it needs the same\n   * global objective guard as loadFromJSON.\n   */\n  protected override restoreOfflineData(): void {\n    this._restoringFromJSON = true;\n    try {\n      super.restoreOfflineData();\n    } finally {\n      this._restoringFromJSON = false;\n    }\n  }\n\n  override setCMIValue(CMIElement: string, value: any): string {\n    if (stringMatches(CMIElement, \"cmi\\\\.objectives\\\\.\\\\d+\")) {\n      const parts = CMIElement.split(\".\");\n      const index = Number(parts[2]);\n      const element_base = `cmi.objectives.${index}`;\n\n      let objective_id;\n      const setting_id = stringMatches(CMIElement, \"cmi\\\\.objectives\\\\.\\\\d+\\\\.id\");\n\n      if (setting_id) {\n        objective_id = value;\n      } else {\n        const objective = this.cmi.objectives.findObjectiveByIndex(index);\n        objective_id = objective ? objective.id : undefined;\n      }\n\n      // Suppress the publish only while replaying stored data into an API that also restores\n      // sequencing state. There the sequencing global objective map has already been loaded and is\n      // the fresher of the two, so republishing would overwrite it. Without sequencing state\n      // persistence there is no fresher map to protect, and this remains the only path that seeds\n      // global objectives from a restored cmi.objectives entry.\n      const suppressGlobalPublish =\n        this._restoringFromJSON && Boolean(this.settings.sequencingStatePersistence);\n      const is_global =\n        !suppressGlobalPublish &&\n        objective_id &&\n        this._globalObjectiveManager.isHostDeclaredGlobalObjectiveId(objective_id);\n\n      if (is_global && this.currentActivityAllowsGlobalObjectiveWrites()) {\n        const { index: global_index } =\n          this._globalObjectiveManager.findOrCreateGlobalObjective(objective_id);\n\n        const global_element = CMIElement.replace(\n          element_base,\n          `_globalObjectives.${global_index}`,\n        );\n        this._commonSetCMIValue(\"SetGlobalObjectiveValue\", true, global_element, value);\n\n        const updatedObjective = this._globalObjectiveManager.globalObjectives[global_index];\n        if (objective_id && updatedObjective) {\n          this._globalObjectiveManager.updateGlobalObjectiveFromCMI(objective_id, updatedObjective);\n        }\n      }\n    }\n    return this._commonSetCMIValue(\"SetValue\", true, CMIElement, value);\n  }\n\n  /**\n   * Return whether the current activity can update shared global objectives.\n   *\n   * @spec SCORM 2004 4th Ed. SN 3.13.1 Tracked - when False, the LMS\n   * \"does not initialize, manage or access any tracking status information\".\n   */\n  private currentActivityAllowsGlobalObjectiveWrites(): boolean {\n    return this._sequencing?.getCurrentActivity()?.sequencingControls.tracked !== false;\n  }\n\n  /**\n   * Gets or builds a new child element to add to the array\n   * @param {string} CMIElement\n   * @param {any} value\n   * @param {boolean} foundFirstIndex\n   * @return {BaseCMI|null}\n   */\n  getChildElement(CMIElement: string, value: any, foundFirstIndex: boolean): BaseCMI | null {\n    return this._cmiHandler.getChildElement(CMIElement, value, foundFirstIndex);\n  }\n\n  /**\n   * Validate correct response\n   * @param {string} CMIElement\n   * @param {*} value\n   */\n  validateCorrectResponse(CMIElement: string, value: any) {\n    const parts = CMIElement.split(\".\");\n    const index = Number(parts[2]);\n    const interaction = this.cmi.interactions.childArray[index] as\n      CMIInteractionsObject | undefined;\n\n    if (!interaction) {\n      this.throwSCORMError(CMIElement, scorm2004_errors.DEPENDENCY_NOT_ESTABLISHED, CMIElement);\n      return;\n    }\n\n    this._responseValidator.validateCorrectResponse(CMIElement, interaction, value);\n  }\n\n  /**\n   * Silently peeks at a CMI value without triggering error logging or\n   * mutating lastErrorCode. Returns null if the element doesn't exist.\n   * Used internally to capture old values before SetValue overwrites them.\n   *\n   * @param {string} CMIElement - dot-delimited CMI path (e.g. \"cmi.interactions.0.id\")\n   * @return {*} the current value, or null if the path doesn't resolve\n   */\n  private _peekCMIValue(CMIElement: string): any {\n    if (!CMIElement || typeof CMIElement !== \"string\") {\n      return null;\n    }\n\n    const segments = CMIElement.split(\".\");\n    let refObject: any = this;\n\n    for (let i = 0; i < segments.length; i++) {\n      const attribute = segments[i] as string;\n\n      if (refObject == null) {\n        return null;\n      }\n\n      try {\n        refObject = refObject[attribute];\n      } catch {\n        // Property getter threw (e.g. write-only elements like session_time)\n        return null;\n      }\n\n      if (refObject instanceof CMIArray) {\n        // Next segment may be a numeric index into childArray, or a\n        // property like _count/_children accessed on the array itself.\n        const nextIndex = i + 1;\n        if (nextIndex >= segments.length) {\n          return refObject;\n        }\n\n        const nextSegment = segments[nextIndex] as string;\n        const index = Number(nextSegment);\n\n        if (!Number.isNaN(index) && Number.isInteger(index) && index >= 0) {\n          if (index >= refObject.childArray.length) {\n            return null;\n          }\n          refObject = refObject.childArray[index];\n          i++; // skip the index segment\n        }\n        // If nextSegment is not a valid numeric index (e.g. _count),\n        // fall through and let the next iteration access it as a\n        // normal property on the CMIArray instance.\n      }\n    }\n\n    return refObject ?? null;\n  }\n\n  /**\n   * Gets a value from the CMI Object\n   * @param {string} CMIElement\n   * @return {*}\n   */\n  override getCMIValue(CMIElement: string): any {\n    return this._commonGetCMIValue(\"GetValue\", true, CMIElement);\n  }\n\n  /**\n   * Raises 403 (VALUE_NOT_INITIALIZED) when an implemented, no-default element is\n   * read before it has ever been set, per IEEE 1484.11.2 / SCORM 2004 RTE.\n   *\n   * Invoked by BaseAPI.getValue after an otherwise-successful resolution, so it\n   * only sees values the data model already returned cleanly. The decision is\n   * deliberately gated to this public boundary (never the getters) to keep\n   * serialization/commit/rollup — which read the getters directly — unaffected.\n   *\n   * A 403 is raised only when all hold:\n   *  - the resolved value is \"\" — any non-empty value is by definition set,\n   *    including values written by internal sequencing/activity-tree paths that\n   *    bypass _commonSetCMIValue (those only ever write non-empty values);\n   *  - the element was never set — _setCMIElements records every successful\n   *    SetValue, loadFromJSON, and global-objective restore (all route through\n   *    _commonSetCMIValue), so an explicit SetValue(x, \"\") still reads back as\n   *    \"\" with code 0; and\n   *  - the element has no spec-defined default ({@link NO_DEFAULT_2004_ELEMENTS}).\n   *\n   * @param {string} CMIElement\n   * @param {*} returnValue - the value getCMIValue resolved\n   * @protected\n   */\n  protected override checkUninitializedGet(CMIElement: string, returnValue: any): void {\n    if (returnValue !== \"\") return;\n    if (this._setCMIElements.has(CMIElement)) return;\n    if (this.adl.isConfiguredSharedDataElement(CMIElement)) return;\n    if (!NO_DEFAULT_2004_ELEMENTS.has(normalizeCMIIndices(CMIElement))) return;\n\n    this.throwSCORMError(\n      CMIElement,\n      this._error_codes.VALUE_NOT_INITIALIZED ?? 403,\n      `The data model element passed to GetValue (${CMIElement}) has not been initialized.`,\n      this.settings.uninitializedGetLogLevel,\n    );\n  }\n\n  /**\n   * Returns the message that corresponds to errorNumber.\n   * @param {(string|number)} errorNumber\n   * @param {boolean} detail\n   * @return {string}\n   */\n  override getLmsErrorMessageDetails(errorNumber: string | number, detail: boolean): string {\n    let basicMessage = \"\";\n    let detailMessage = \"\";\n\n    errorNumber = String(errorNumber);\n    const errorDescription = scorm2004_constants.error_descriptions[errorNumber];\n    if (errorDescription) {\n      basicMessage = errorDescription.basicMessage;\n      detailMessage = errorDescription.detailMessage;\n    }\n\n    return detail ? detailMessage : basicMessage;\n  }\n\n  /**\n   * Replace the whole API with another\n   * @param {Scorm2004API} newAPI\n   */\n  replaceWithAnotherScormAPI(newAPI: Scorm2004API) {\n    this.cmi = newAPI.cmi;\n    this.adl = newAPI.adl;\n  }\n\n  /**\n   * Render the cmi object to the proper format for LMS commit\n   * @param {boolean} terminateCommit\n   * @param {boolean} includeTotalTime\n   * @return {object|Array}\n   */\n  renderCommitCMI(\n    terminateCommit: boolean,\n    includeTotalTime: boolean = false,\n  ): StringKeyMap | Array<any> {\n    return this._dataSerializer.renderCommitCMI(terminateCommit, includeTotalTime);\n  }\n\n  /**\n   * Render the cmi object to the proper format for LMS commit\n   * @param {boolean} terminateCommit\n   * @param {boolean} includeTotalTime\n   * @return {CommitObject}\n   */\n  renderCommitObject(terminateCommit: boolean, includeTotalTime: boolean = false): CommitObject {\n    return this._dataSerializer.renderCommitObject(terminateCommit, includeTotalTime);\n  }\n\n  /**\n   * Attempts to store the data to the LMS\n   * @param {boolean} terminateCommit\n   * @param {CommitTrigger} [trigger] - What initiated the commit\n   * @return {ResultObject}\n   */\n  storeData(terminateCommit: boolean, trigger?: CommitTrigger): ResultObject {\n    if (terminateCommit) {\n      if (this.cmi.mode === \"normal\") {\n        if (this.cmi.credit === \"credit\") {\n          if (this.cmi.completion_threshold && this.cmi.progress_measure) {\n            if (\n              parseFloat(this.cmi.progress_measure) >= parseFloat(this.cmi.completion_threshold)\n            ) {\n              this.cmi.completion_status = \"completed\";\n            } else {\n              this.cmi.completion_status = \"incomplete\";\n            }\n          }\n          if (this.cmi.scaled_passing_score && this.cmi.score.scaled) {\n            if (parseFloat(this.cmi.score.scaled) >= parseFloat(this.cmi.scaled_passing_score)) {\n              this.cmi.success_status = \"passed\";\n            } else {\n              this.cmi.success_status = \"failed\";\n            }\n          }\n        }\n      }\n    }\n\n    let navRequest = false;\n    if (\n      this.adl.nav.request !==\n        ((this.startingData?.adl as StringKeyMap)?.nav as StringKeyMap)?.request &&\n      this.adl.nav.request !== \"_none_\"\n    ) {\n      navRequest = true;\n    }\n\n    const commitObject = this.getCommitObject(terminateCommit);\n    // RTE Commit persists the SCO data model but does not end the activity attempt. Sequencing\n    // tracking and objective maps are updated only by the End Attempt Process prepared before a\n    // successful Terminate; abandon therefore leaves the reported attempt data unrecorded.\n    // @spec SCORM 2004 4th Ed. SN TB.2.3 / UP.4 and TR SX-04a / SX-04b\n    if (typeof this.settings.lmsCommitUrl === \"string\") {\n      const result = this.processHttpRequest(\n        this.settings.lmsCommitUrl,\n        commitObject,\n        terminateCommit,\n        trigger,\n      );\n\n      if (\n        navRequest &&\n        result.navRequest !== undefined &&\n        result.navRequest !== \"\" &&\n        typeof result.navRequest === \"string\"\n      ) {\n        const parsed: ParsedNavigationRequest = parseNavigationRequest(result.navRequest);\n\n        if (!parsed.valid) {\n          this.apiLog(\n            \"storeData\",\n            `Invalid navigation request from LMS: ${parsed.error}`,\n            LogLevelEnum.WARN,\n          );\n        } else {\n          const navEventMap: { [key: string]: string } = {\n            start: \"SequenceStart\",\n            resumeAll: \"SequenceResumeAll\",\n            continue: \"SequenceNext\",\n            previous: \"SequencePrevious\",\n            choice: \"SequenceChoice\",\n            jump: \"SequenceJump\",\n            exit: \"SequenceExit\",\n            exitAll: \"SequenceExitAll\",\n            abandon: \"SequenceAbandon\",\n            abandonAll: \"SequenceAbandonAll\",\n            suspendAll: \"SequenceSuspendAll\",\n          };\n\n          const eventName = navEventMap[parsed.command];\n          if (eventName) {\n            this.processListeners(eventName, \"adl.nav.request\", parsed.targetActivityId);\n          }\n        }\n      } else if (result?.navRequest && !navRequest) {\n        if (\n          typeof result.navRequest === \"object\" &&\n          Object.hasOwnProperty.call(result.navRequest, \"name\") &&\n          result.navRequest.name\n        ) {\n          this.processListeners(result.navRequest.name as string, result.navRequest.data as string);\n        }\n      }\n\n      return result;\n    }\n\n    return {\n      result: global_constants.SCORM_TRUE,\n      errorCode: 0,\n    };\n  }\n\n  /**\n   * Configure sequencing based on provided settings\n   * @param {SequencingSettings} sequencingSettings\n   */\n  private configureSequencing(sequencingSettings: SequencingSettings): void {\n    this._sequencingCollections = this._sequencingConfigBuilder.sanitizeSequencingCollections(\n      sequencingSettings.collections,\n    );\n    this._activityTreeBuilder.setSequencingCollections(this._sequencingCollections);\n\n    if (sequencingSettings.activityTree) {\n      this.configureActivityTree(sequencingSettings.activityTree);\n    }\n\n    if (sequencingSettings.sequencingRules) {\n      this.configureSequencingRules(sequencingSettings.sequencingRules);\n    }\n\n    if (sequencingSettings.sequencingControls) {\n      this.configureSequencingControls(sequencingSettings.sequencingControls);\n    }\n\n    if (sequencingSettings.rollupRules) {\n      this.configureRollupRules(sequencingSettings.rollupRules);\n    }\n\n    if (sequencingSettings.hideLmsUi) {\n      this._sequencing.hideLmsUi = this._sequencingConfigBuilder.sanitizeHideLmsUi(\n        sequencingSettings.hideLmsUi,\n      );\n    } else {\n      this._sequencing.hideLmsUi = [];\n    }\n\n    if (sequencingSettings.auxiliaryResources) {\n      this._sequencing.auxiliaryResources =\n        this._sequencingConfigBuilder.sanitizeAuxiliaryResources(\n          sequencingSettings.auxiliaryResources,\n        );\n    } else {\n      this._sequencing.auxiliaryResources = [];\n    }\n  }\n\n  /**\n   * Configure activity tree based on provided settings\n   * @param {ActivitySettings} activityTreeSettings\n   */\n  private configureActivityTree(activityTreeSettings: ActivitySettings): void {\n    const rootActivity = this._activityTreeBuilder.createActivity(activityTreeSettings);\n    const activityTree = this._sequencing.activityTree;\n    activityTree.root = rootActivity;\n    this._extractedScoItemIds = this._activityTreeBuilder.extractActivityIds(rootActivity);\n  }\n\n  /**\n   * Configure sequencing rules based on provided settings\n   * @param {SequencingRulesSettings} sequencingRulesSettings\n   */\n  private configureSequencingRules(sequencingRulesSettings: SequencingRulesSettings): void {\n    this._sequencingConfigBuilder.applySequencingRulesSettings(\n      this._sequencing.sequencingRules,\n      sequencingRulesSettings,\n    );\n  }\n\n  /**\n   * Configure sequencing controls based on provided settings\n   * @param {SequencingControlsSettings} sequencingControlsSettings\n   */\n  private configureSequencingControls(\n    sequencingControlsSettings: SequencingControlsSettings,\n  ): void {\n    this._sequencingConfigBuilder.applySequencingControlsSettings(\n      this._sequencing.sequencingControls,\n      sequencingControlsSettings,\n    );\n  }\n\n  /**\n   * Configure rollup rules based on provided settings\n   * @param {RollupRulesSettings} rollupRulesSettings\n   */\n  private configureRollupRules(rollupRulesSettings: RollupRulesSettings): void {\n    this._sequencingConfigBuilder.applyRollupRulesSettings(\n      this._sequencing.rollupRules,\n      rollupRulesSettings,\n    );\n  }\n\n  /**\n   * Build the context handed to SequencingStatePersistence.\n   *\n   * `learnerId` is a getter, not a snapshot: the constructor builds this context before the\n   * host has loaded cmi.learner_id, and `this.cmi` can be replaced by reset() or a resume,\n   * so the persistence layer must read the current value each time it saves or loads.\n   *\n   * Because the value is live, a loadSequencingState() issued before the host sets\n   * cmi.learner_id keys its in-flight dedupe on \"unknown\", and a second load issued after the\n   * id is set keys on the real id, so the two are not coalesced. The learner id cannot change\n   * after Initialize(), so the window is limited to hosts that load before initializing.\n   * @spec SCORM 2004 4th Ed. RTE 4.2.11 - cmi.learner_id identifies the learner; persisted\n   * sequencing state must be attributed to that learner, not to a placeholder.\n   * @return {PersistenceContext}\n   */\n  private createPersistenceContext(): PersistenceContext {\n    const api = this;\n    return {\n      getSettings: () => this.settings,\n      apiLog: this.apiLog.bind(this),\n      adl: this.adl,\n      sequencing: this._sequencing,\n      sequencingService: this._sequencingService,\n      get learnerId(): string {\n        return api.cmi.learner_id;\n      },\n    };\n  }\n\n  /**\n   * Initialize the sequencing service\n   * @param {Settings} settings\n   */\n  private initializeSequencingService(settings?: Settings): void {\n    try {\n      const sequencingConfig: SequencingConfiguration = {\n        autoRollupOnCMIChange: settings?.sequencing?.autoRollupOnCMIChange ?? false,\n        autoProgressOnCompletion: settings?.sequencing?.autoProgressOnCompletion ?? false,\n        validateNavigationRequests: settings?.sequencing?.validateNavigationRequests ?? true,\n        enableEventSystem: settings?.sequencing?.enableEventSystem ?? true,\n        logLevel: settings?.sequencing?.logLevel ?? \"info\",\n        ...(settings?.sequencing?.getAttemptElapsedSeconds\n          ? { getAttemptElapsedSeconds: settings.sequencing.getAttemptElapsedSeconds }\n          : {}),\n        wasCMIElementSetByContent: (element) => this._runtimeSetCMIElements.has(element),\n      };\n\n      this._sequencingService = new SequencingService(\n        this._sequencing,\n        this.cmi,\n        this.adl,\n        this.eventService || this,\n        this.loggingService,\n        sequencingConfig,\n      );\n\n      // @spec SCORM 2004 4th Ed. SN DB.2 - delivery establishes the current\n      // activity before the SCO can call Initialize.\n      // @spec SCORM 2004 4th Ed. RTE 4.2.5 / 4.2.17 - launch-static CMI\n      // elements are initialized for the activity's associated SCO.\n      this._sequencingService.setEventListeners(\n        this.buildSequencingEventListeners(settings?.sequencing?.eventListeners),\n      );\n\n      // Update context references after sequencing service is created\n      this._globalObjectiveManager.updateSequencingService(this._sequencingService);\n      this._dataSerializer.updateSequencingService(this._sequencingService);\n\n      // Initialize state persistence\n      if (settings?.sequencingStatePersistence) {\n        this._statePersistence = new SequencingStatePersistence(\n          this.createPersistenceContext(),\n          this._globalObjectiveManager,\n        );\n      }\n\n      this._globalObjectiveManager.syncGlobalObjectiveIdsFromSequencing();\n    } catch (error) {\n      console.warn(\"Failed to initialize sequencing service:\", error);\n      this._sequencingService = null;\n    }\n  }\n\n  /**\n   * Wrap LMS-provided sequencing listeners with API-owned delivery bookkeeping.\n   *\n   * @spec SCORM 2004 4th Ed. SN DB.2 - Content Delivery Environment Process\n   * @spec SCORM 2004 4th Ed. RTE 4.2.5, Table 4.2.5a - cmi.completion_threshold\n   * @spec SCORM 2004 4th Ed. RTE 4.2.17, Table 4.2.17a - cmi.objectives\n   */\n  private buildSequencingEventListeners(\n    listeners?: SequencingEventListeners,\n  ): SequencingEventListeners {\n    return {\n      ...listeners,\n      onActivityDelivery: (activity) => {\n        this.applyDeliveredActivityLaunchData(activity as Activity);\n        listeners?.onActivityDelivery?.(activity);\n      },\n    };\n  }\n\n  /**\n   * Get the sequencing service\n   * @return {SequencingService | null}\n   */\n  public getSequencingService(): SequencingService | null {\n    return this._sequencingService;\n  }\n\n  /**\n   * Preview a host Continue/Previous click without ending the SCO or changing its\n   * tracking data. The result reflects currently reported CMI, not future SCO writes.\n   * This host extension does not change SCORM's adl.nav.request_valid semantics.\n   */\n  public previewNavigationRequest(request: \"continue\" | \"previous\"): NavigationPreview {\n    if (this.isInitialized() && this._sequencingService) {\n      return this._sequencingService.previewNavigationRequest(request);\n    }\n    return {\n      outcome: \"unknown\",\n      targetActivityId: null,\n      endSequencingSession: false,\n      exception: null,\n    };\n  }\n\n  /**\n   * Set sequencing event listeners\n   * @param {SequencingEventListeners} listeners\n   *\n   * @spec SCORM 2004 4th Ed. SN DB.2 - Content Delivery Environment Process\n   * @spec SCORM 2004 4th Ed. RTE 4.2.5 / 4.2.17 - launch-static CMI data\n   */\n  public setSequencingEventListeners(listeners: SequencingEventListeners): void {\n    if (this._sequencingService) {\n      this._sequencingService.setEventListeners(this.buildSequencingEventListeners(listeners));\n    }\n  }\n\n  /**\n   * Update sequencing configuration\n   * @param {SequencingConfiguration} config\n   */\n  public updateSequencingConfiguration(config: SequencingConfiguration): void {\n    if (this._sequencingService) {\n      this._sequencingService.updateConfiguration(config);\n    }\n  }\n\n  /**\n   * Get current sequencing state information\n   * @return {object}\n   */\n  public getSequencingState(): any {\n    if (this._sequencingService) {\n      return this._sequencingService.getSequencingState();\n    }\n    return {\n      isInitialized: false,\n      isActive: false,\n      currentActivity: null,\n      rootActivity: this._sequencing.getRootActivity(),\n      lastSequencingResult: null,\n    };\n  }\n\n  /**\n   * Process a navigation request directly\n   * @param {string} request\n   * @param {string} targetActivityId\n   * @return {boolean}\n   */\n  public processNavigationRequest(request: string, targetActivityId?: string): boolean {\n    if (this._sequencingService) {\n      const result = this._sequencingService.processNavigationRequest(request, targetActivityId);\n      if (result && this.settings.sequencingStatePersistence?.autoSaveOn === \"navigate\") {\n        this.autoSaveSequencingState(\"processNavigationRequest\");\n      }\n      return result;\n    }\n    return false;\n  }\n\n  private autoSaveSequencingState(source: string): void {\n    this.saveSequencingState()\n      .then((saved) => {\n        if (!saved) {\n          this.apiLog(source, \"Failed to auto-save sequencing state\", LogLevelEnum.WARN);\n        }\n      })\n      .catch(() => {\n        this.apiLog(source, \"Failed to auto-save sequencing state\", LogLevelEnum.WARN);\n      });\n  }\n\n  /**\n   * Reset sequencing state explicitly\n   */\n  public resetSequencingState(): void {\n    this._sequencing?.reset();\n    this._sequencingService?.setEventListeners({});\n  }\n\n  /**\n   * Get tracking data for a specific activity\n   * attemptCompletionAmount includes completion measure rollup for clusters.\n   * Only use it when attemptCompletionAmountStatus is true; false means unknown.\n   * @param {string} activityId\n   * @return {object | null}\n   */\n  public getActivityTrackingData(activityId: string): {\n    completionStatus: string;\n    successStatus: string;\n    progressMeasure: number | null;\n    attemptCompletionAmount: number;\n    attemptCompletionAmountStatus: boolean;\n    score: number | null;\n  } | null {\n    if (!this._sequencing?.activityTree) {\n      return null;\n    }\n\n    const activity = this._sequencing.activityTree.getActivity(activityId);\n    if (!activity) {\n      return null;\n    }\n\n    return {\n      completionStatus: activity.completionStatus || \"unknown\",\n      successStatus: activity.successStatus || \"unknown\",\n      progressMeasure: activity.progressMeasure ?? null,\n      attemptCompletionAmount: activity.attemptCompletionAmount,\n      attemptCompletionAmountStatus: activity.attemptCompletionAmountStatus,\n      score: activity.objectiveMeasureStatus ? activity.objectiveNormalizedMeasure : null,\n    };\n  }\n\n  /**\n   * Save current sequencing state to persistent storage\n   * @param {Partial<SequencingStateMetadata>} metadata\n   * @return {Promise<boolean>}\n   */\n  public async saveSequencingState(metadata?: Partial<SequencingStateMetadata>): Promise<boolean> {\n    if (this._statePersistence) {\n      return this._statePersistence.saveSequencingState(metadata);\n    }\n\n    if (!this.settings.sequencingStatePersistence) {\n      this.apiLog(\n        \"saveSequencingState\",\n        \"No persistence configuration provided\",\n        LogLevelEnum.WARN,\n      );\n      return false;\n    }\n\n    // Fallback: create persistence on the fly\n    const persistence = new SequencingStatePersistence(\n      this.createPersistenceContext(),\n      this._globalObjectiveManager,\n    );\n    return persistence.saveSequencingState(metadata);\n  }\n\n  /**\n   * Load sequencing state from persistent storage\n   * @param {Partial<SequencingStateMetadata>} metadata\n   * @return {Promise<boolean>}\n   */\n  public async loadSequencingState(metadata?: Partial<SequencingStateMetadata>): Promise<boolean> {\n    if (this._statePersistence) {\n      return this._statePersistence.loadSequencingState(metadata);\n    }\n\n    if (!this.settings.sequencingStatePersistence) {\n      this.apiLog(\n        \"loadSequencingState\",\n        \"No persistence configuration provided\",\n        LogLevelEnum.WARN,\n      );\n      return false;\n    }\n\n    // Fallback: create persistence on the fly\n    const persistence = new SequencingStatePersistence(\n      this.createPersistenceContext(),\n      this._globalObjectiveManager,\n    );\n    return persistence.loadSequencingState(metadata);\n  }\n\n  /**\n   * Serialize current sequencing state to JSON string\n   * @return {string} Serialized state\n   */\n  public serializeSequencingState(): string {\n    if (this._statePersistence) {\n      return this._statePersistence.serializeSequencingState();\n    }\n\n    // Fallback: create persistence on the fly\n    const persistence = new SequencingStatePersistence(\n      this.createPersistenceContext(),\n      this._globalObjectiveManager,\n    );\n    return persistence.serializeSequencingState();\n  }\n\n  /**\n   * Deserialize sequencing state from JSON string\n   * @param {string} stateData - Serialized state data\n   * @return {boolean} Success status\n   */\n  public deserializeSequencingState(stateData: string): boolean {\n    if (this._statePersistence) {\n      return this._statePersistence.deserializeSequencingState(stateData);\n    }\n\n    // Fallback: create persistence on the fly\n    const persistence = new SequencingStatePersistence(\n      this.createPersistenceContext(),\n      this._globalObjectiveManager,\n    );\n    return persistence.deserializeSequencingState(stateData);\n  }\n\n  /**\n   * Determines the appropriate cmi.entry value based on previous exit state.\n   * @param {string} previousExit\n   * @param {boolean} hasSuspendData\n   * @return {string}\n   */\n  public determineEntryValue(previousExit: string, hasSuspendData: boolean): string {\n    return this._dataSerializer.determineEntryValue(previousExit, hasSuspendData);\n  }\n}\n\nexport default Scorm2004API;\n","import Scorm12API from \"./Scorm12API\";\nimport Scorm2004API from \"./Scorm2004API\";\n\n// Explicitly assign to window for global usage\nif (typeof window !== \"undefined\") {\n  window.Scorm12API = Scorm12API;\n  window.Scorm2004API = Scorm2004API;\n}\n","// src/CrossFrameAPI.ts\nimport {\n  CrossFrameAPIOptions,\n  CrossFrameEvent,\n  CrossFrameEventCallback,\n  MessageData,\n  MessageResponse,\n} from \"./types/CrossFrame\";\nimport { global_errors } from \"./constants/error_codes\";\n\n/**\n * Pending request tracking with timestamp for cache merge protection\n */\ninterface PendingRequest {\n  resolve: (v: unknown) => void;\n  reject: (e: unknown) => void;\n  timer: ReturnType<typeof setTimeout>;\n  /**\n   * Timestamp when the request was sent, used for cache merge protection.\n   * Ensures local modifications made after the request was sent aren't overwritten\n   * by stale server responses that arrive later.\n   */\n  requestTime: number;\n  method: string; // CF-API-02: Track method name for better error reporting\n}\n\n/**\n * Client-side SCORM facade running in your content frame.\n * Returns cached values synchronously, then fires off an async\n * postMessage to the LMS frame to refresh cache and error state.\n */\nexport default class CrossFrameAPI {\n  private _cache = new Map<string, string>();\n  private _cacheTimestamps = new Map<string, number>();\n  private _lastError = \"0\";\n  private _pending = new Map<string, PendingRequest>();\n  private _counter = 0;\n  private readonly _origin: string;\n  private readonly _targetWindow: Window;\n  private readonly _timeout: number;\n  private readonly _heartbeatInterval: number;\n  private readonly _heartbeatTimeout: number;\n\n  private _destroyed = false;\n  private _connected = true;\n  private _lastHeartbeatResponse = Date.now();\n  private _heartbeatTimer: ReturnType<typeof setInterval> | undefined;\n  private _eventListeners = new Map<string, Set<CrossFrameEventCallback>>();\n  private readonly _boundOnMessage: (ev: MessageEvent) => void;\n\n  /**\n   * Type guard to validate MessageResponse structure\n   */\n  private static _isValidMessageResponse(data: unknown): data is MessageResponse {\n    if (typeof data !== \"object\" || data === null) return false;\n\n    const resp = data as Partial<MessageResponse>;\n\n    // messageId is required\n    if (typeof resp.messageId !== \"string\" || resp.messageId.length === 0) return false;\n\n    // error must have correct shape if present\n    if (resp.error !== undefined) {\n      if (typeof resp.error !== \"object\" || resp.error === null) return false;\n      const err = resp.error as Record<string, unknown>;\n      if (typeof err.message !== \"string\") return false;\n      if (err.code !== undefined && typeof err.code !== \"string\") return false;\n    }\n\n    // isHeartbeat must be boolean if present\n    if (resp.isHeartbeat !== undefined && typeof resp.isHeartbeat !== \"boolean\") return false;\n\n    return true;\n  }\n\n  /**\n   * Validates that args is an array and sanitizes it for safe use\n   */\n  private static _validateArgs(args: unknown[]): args is unknown[] {\n    if (!Array.isArray(args)) return false;\n    // Additional validation could check for specific types based on method\n    return true;\n  }\n\n  private _handler: ProxyHandler<CrossFrameAPI> = {\n    get: (target, prop, receiver) => {\n      // If it's an existing property/method, return it\n      if (typeof prop !== \"string\" || prop in target) {\n        const v = Reflect.get(target, prop, receiver);\n        return typeof v === \"function\" ? v.bind(target) : v;\n      }\n\n      // Otherwise treat prop as a SCORM call\n      const methodName = prop;\n      const isGet = methodName.endsWith(\"GetValue\");\n      const isSet = methodName.startsWith(\"LMSSet\") || methodName.endsWith(\"SetValue\");\n      const isInit = methodName === \"Initialize\" || methodName === \"LMSInitialize\";\n      const isFinish = methodName === \"Terminate\" || methodName === \"LMSFinish\";\n      const isCommit = methodName === \"Commit\" || methodName === \"LMSCommit\";\n      const isErrorString = methodName === \"GetErrorString\" || methodName === \"LMSGetErrorString\";\n      const isDiagnostic = methodName === \"GetDiagnostic\" || methodName === \"LMSGetDiagnostic\";\n\n      return (...args: unknown[]): string => {\n        // CF-API-03: Validate args is an array (TypeScript guarantees this, but runtime safety)\n        if (!CrossFrameAPI._validateArgs(args)) {\n          console.error(`CrossFrameAPI: Invalid arguments for ${methodName}`);\n          return \"\";\n        }\n\n        // Synchronous cache update for setter calls\n        if (isSet && args.length >= 2) {\n          const key = args[0] as string;\n          target._cache.set(key, String(args[1]));\n          target._cacheTimestamps.set(key, Date.now());\n          target._lastError = \"0\";\n        }\n\n        // Capture request time for cache merge protection\n        const requestTime = Date.now();\n\n        // Fire off async postMessage to refresh cache and error\n        target\n          ._post(methodName, args)\n          .then((res) => {\n            if (isGet && args.length >= 1) {\n              const key = args[0] as string;\n              // Only update if not locally modified after request was sent\n              const localModTime = target._cacheTimestamps.get(key) ?? 0;\n              if (localModTime < requestTime) {\n                target._cache.set(key, String(res));\n                target._cacheTimestamps.delete(key);\n              }\n              target._lastError = \"0\";\n            }\n            if (isErrorString && args.length >= 1) {\n              const code = String(args[0]);\n              target._cache.set(`error_${code}`, String(res));\n            }\n            if (isDiagnostic && args.length >= 1) {\n              const code = String(args[0]);\n              target._cache.set(`diag_${code}`, String(res));\n            }\n            if (methodName === \"GetLastError\" || methodName === \"LMSGetLastError\") {\n              target._lastError = String(res);\n            }\n          })\n          .catch((err) => target._capture(methodName, err));\n\n        // Return synchronously\n        if (isGet && args.length >= 1) {\n          return target._cache.get(args[0] as string) ?? \"\";\n        }\n        if (isErrorString && args.length >= 1) {\n          const code = String(args[0]);\n          return target._cache.get(`error_${code}`) ?? \"\";\n        }\n        if (isDiagnostic && args.length >= 1) {\n          const code = String(args[0]);\n          return target._cache.get(`diag_${code}`) ?? \"\";\n        }\n        if (isInit || isFinish || isCommit || isSet) {\n          // Immediately return \"true\"\n          const result = \"true\";\n          // Then warm cache with timestamp protection:\n          target\n            ._post(\"getFlattenedCMI\", [])\n            .then((all: unknown) => {\n              if (all && typeof all === \"object\") {\n                const entries = Object.entries(all as Record<string, string>);\n                entries.forEach(([key, val]) => {\n                  // Only update if not locally modified after request was sent\n                  const localModTime = target._cacheTimestamps.get(key) ?? 0;\n                  if (localModTime < requestTime) {\n                    target._cache.set(key, val);\n                    target._cacheTimestamps.delete(key);\n                  }\n                });\n              }\n              // reset error\n              target._lastError = \"0\";\n            })\n            .catch((err) => target._capture(\"getFlattenedCMI\", err));\n          return result;\n        }\n        if (methodName === \"GetLastError\" || methodName === \"LMSGetLastError\") {\n          return target._lastError;\n        }\n        return \"\";\n      };\n    },\n  };\n\n  /**\n   * Creates a new CrossFrameAPI instance.\n   * @param targetOrigin - Origin to send messages to. Default \"*\" sends to any origin.\n   * @param targetWindow - Window to send messages to. Default is window.parent.\n   * @param options - Configuration options\n   */\n  constructor(\n    targetOrigin: string = \"*\",\n    targetWindow: Window = window.parent,\n    options: CrossFrameAPIOptions = {},\n  ) {\n    this._origin = targetOrigin;\n    this._targetWindow = targetWindow;\n    this._timeout = options.timeout ?? 5000;\n    this._heartbeatInterval = options.heartbeatInterval ?? 30000;\n    this._heartbeatTimeout = options.heartbeatTimeout ?? 60000;\n\n    // Warn about wildcard origin security implications\n    if (targetOrigin === \"*\") {\n      console.warn(\n        \"CrossFrameAPI: Using wildcard origin ('*') allows any origin to receive messages. \" +\n          \"This is insecure for production use. \" +\n          \"Specify an explicit origin (e.g., 'https://lms.example.com') to restrict message recipients.\",\n      );\n    }\n\n    this._boundOnMessage = this._onMessage.bind(this);\n    window.addEventListener(\"message\", this._boundOnMessage);\n    this._startHeartbeat();\n\n    return new Proxy(this, this._handler);\n  }\n\n  /**\n   * Destroys this instance, removing event listeners and preventing further message processing.\n   * Once destroyed, the instance cannot be reused.\n   */\n  destroy(): void {\n    if (this._destroyed) return;\n    this._destroyed = true;\n    window.removeEventListener(\"message\", this._boundOnMessage);\n    if (this._heartbeatTimer) {\n      clearInterval(this._heartbeatTimer);\n      this._heartbeatTimer = undefined;\n    }\n    // Reject all pending requests\n    for (const pending of Array.from(this._pending.values())) {\n      clearTimeout(pending.timer);\n      pending.reject(new Error(\"CrossFrameAPI destroyed\"));\n    }\n    this._pending.clear();\n    this._cache.clear();\n    this._cacheTimestamps.clear();\n    this._eventListeners.clear();\n  }\n\n  /**\n   * Subscribes to a CrossFrame event.\n   * @param event - Event type to listen for\n   * @param callback - Function to call when event occurs\n   */\n  on(event: string, callback: CrossFrameEventCallback): void {\n    if (!this._eventListeners.has(event)) {\n      this._eventListeners.set(event, new Set());\n    }\n    this._eventListeners.get(event)?.add(callback);\n  }\n\n  /**\n   * Unsubscribes from a CrossFrame event.\n   * @param event - Event type to stop listening for\n   * @param callback - Function to remove\n   */\n  off(event: string, callback: CrossFrameEventCallback): void {\n    this._eventListeners.get(event)?.delete(callback);\n  }\n\n  /**\n   * Returns whether the connection to the LMS frame is currently active.\n   */\n  get connected(): boolean {\n    return this._connected;\n  }\n\n  /**\n   * Emits an event to all registered listeners.\n   */\n  private _emit(event: CrossFrameEvent): void {\n    this._eventListeners.get(event.type)?.forEach((cb) => cb(event));\n  }\n\n  /**\n   * Starts the heartbeat mechanism for connection detection.\n   */\n  private _startHeartbeat(): void {\n    // CF-API-01: Clear any existing heartbeat timer before starting a new one\n    if (this._heartbeatTimer) {\n      clearInterval(this._heartbeatTimer);\n    }\n\n    this._heartbeatTimer = setInterval(() => {\n      if (this._destroyed) return;\n\n      // Check if we've missed heartbeats\n      const timeSinceLastResponse = Date.now() - this._lastHeartbeatResponse;\n      if (timeSinceLastResponse > this._heartbeatTimeout && this._connected) {\n        this._connected = false;\n        this._emit({ type: \"connectionLost\" });\n      }\n\n      // Send heartbeat ping\n      this._sendHeartbeat();\n    }, this._heartbeatInterval);\n  }\n\n  /**\n   * Sends a heartbeat ping to the LMS frame.\n   */\n  private _sendHeartbeat(): void {\n    const messageId = `hb-${Date.now()}-${this._counter++}`;\n    const msg: MessageData = {\n      messageId,\n      method: \"__heartbeat__\",\n      params: [],\n      isHeartbeat: true,\n    };\n    this._targetWindow.postMessage(msg, this._origin);\n  }\n\n  /**\n   * Send a message to the LMS frame and return a promise for its response.\n   */\n  private _post(method: string, params: unknown[]): Promise<unknown> {\n    if (this._destroyed) {\n      return Promise.reject(new Error(\"CrossFrameAPI destroyed\"));\n    }\n\n    const messageId = `cfapi-${Date.now()}-${this._counter++}`;\n    const requestTime = Date.now();\n\n    // Deep-clean params of non-cloneables (e.g. functions)\n    const safeParams = params.map((p) => {\n      if (typeof p === \"function\") {\n        // DEFENSIVE CODING: Warn about non-serializable function parameters.\n        // This console.warn is intentionally kept in production builds because:\n        // 1. Functions in SCORM API params indicate a programming error by content authors\n        // 2. The warning helps diagnose integration issues during content development\n        // 3. It alerts developers to potential data loss (function becomes undefined)\n        // 4. The frequency should be very low in production (only on misconfigured content)\n        //\n        // Alternative: Could be gated by a debug flag if production console noise is a concern\n        console.warn(\"Dropping function param when posting SCORM call:\", method);\n        return undefined;\n      }\n      return p;\n    });\n\n    return new Promise((resolve, reject) => {\n      const timer = setTimeout(() => {\n        if (this._pending.has(messageId)) {\n          this._pending.delete(messageId);\n          reject(new Error(`Timeout calling ${method}`));\n        }\n      }, this._timeout);\n\n      // CF-API-02: Store method name in pending request for better error reporting\n      this._pending.set(messageId, { resolve, reject, timer, requestTime, method });\n      const msg: MessageData = { messageId, method, params: safeParams };\n      this._targetWindow.postMessage(msg, this._origin);\n    });\n  }\n\n  /**\n   * Handle incoming postMessage responses from the LMS frame.\n   */\n  private _onMessage(ev: MessageEvent): void {\n    if (this._destroyed) return;\n\n    // Validate the message origin and source unless all origins are allowed\n    if (this._origin !== \"*\" && ev.origin !== this._origin) {\n      return;\n    }\n    if (ev.source && ev.source !== this._targetWindow) {\n      return;\n    }\n\n    // CF-API-04: Validate that ev.data has the expected MessageResponse structure\n    if (!CrossFrameAPI._isValidMessageResponse(ev.data)) return;\n\n    const data = ev.data;\n\n    // Handle heartbeat response\n    if (data.isHeartbeat) {\n      this._lastHeartbeatResponse = Date.now();\n      if (!this._connected) {\n        this._connected = true;\n        this._emit({ type: \"connectionRestored\" });\n      }\n      return;\n    }\n\n    // Handle regular response\n    const pending = this._pending.get(data.messageId);\n    if (!pending) return;\n\n    clearTimeout(pending.timer);\n    this._pending.delete(data.messageId);\n\n    if (data.error) {\n      // Check if rate limited and emit event\n      // CF-API-02: Use the actual method name from the pending request\n      if (data.error.message === \"Rate limit exceeded\") {\n        this._emit({ type: \"rateLimited\", method: pending.method });\n      }\n      pending.reject(data.error);\n    } else {\n      pending.resolve(data.result);\n    }\n  }\n\n  /**\n   * Capture and cache SCORM errors.\n   */\n  private _capture(method: string, err: unknown): void {\n    let errorMessage = \"Unknown error\";\n\n    if (err instanceof Error) {\n      errorMessage = err.message;\n    } else if (typeof err === \"object\" && err !== null && \"message\" in err) {\n      errorMessage = String((err as { message: unknown }).message);\n    }\n\n    console.error(`CrossFrameAPI ${method} error:`, err);\n    // Match SCORM error codes (3 digits) from error messages\n    const match = /(?:error code|code)?\\s*(\\d{3})\\b/i.exec(errorMessage);\n    const code = match?.[1] ?? String(global_errors.GENERAL);\n    this._lastError = code;\n    this._cache.set(`error_${code}`, errorMessage);\n  }\n}\n","// src/CrossFrameLMS.ts\nimport { CrossFrameLMSOptions, MessageData, MessageResponse } from \"./types/CrossFrame\";\nimport { IBaseAPI } from \"./interfaces/IBaseAPI\";\n\n/**\n * Server-side SCORM adapter running in your LMS frame (lms.example.com).\n * Listens for postMessage from child (content) frames, invokes real API,\n * and posts back { messageId, result, error }.\n */\nexport default class CrossFrameLMS {\n  private readonly _api: IBaseAPI;\n  private readonly _origin: string;\n  private readonly _rateLimit: number;\n  private _requestTimes: number[] = [];\n  private _destroyed = false;\n  private readonly _boundOnMessage: (ev: MessageEvent) => void;\n\n  /**\n   * Strict allowlist of methods that can be invoked via cross-frame messages.\n   * Only SCORM API methods and internal helpers are permitted.\n   */\n  private static readonly ALLOWED_METHODS = new Set([\n    // SCORM 1.2 methods\n    \"LMSInitialize\",\n    \"LMSFinish\",\n    \"LMSGetValue\",\n    \"LMSSetValue\",\n    \"LMSCommit\",\n    \"LMSGetLastError\",\n    \"LMSGetErrorString\",\n    \"LMSGetDiagnostic\",\n    // SCORM 2004 methods\n    \"Initialize\",\n    \"Terminate\",\n    \"GetValue\",\n    \"SetValue\",\n    \"Commit\",\n    \"GetLastError\",\n    \"GetErrorString\",\n    \"GetDiagnostic\",\n    // Internal method for cache warming\n    \"getFlattenedCMI\",\n  ]);\n\n  /**\n   * Creates a new CrossFrameLMS instance.\n   * @param api - The SCORM API instance to delegate calls to\n   * @param targetOrigin - Origin to accept messages from. Default \"*\" accepts all origins.\n   * @param options - Configuration options\n   */\n  constructor(api: IBaseAPI, targetOrigin: string = \"*\", options: CrossFrameLMSOptions = {}) {\n    this._api = api;\n    this._origin = targetOrigin;\n    this._rateLimit = options.rateLimit ?? 100;\n\n    // Warn about wildcard origin security implications\n    if (targetOrigin === \"*\") {\n      console.warn(\n        \"CrossFrameLMS: Using wildcard origin ('*') allows any origin to send messages. \" +\n          \"This is insecure for production use. \" +\n          \"Specify an explicit origin (e.g., 'https://content.example.com') to restrict message sources.\",\n      );\n    }\n\n    this._boundOnMessage = this._onMessage.bind(this);\n    window.addEventListener(\"message\", this._boundOnMessage);\n  }\n\n  /**\n   * Destroys this instance, removing event listeners and preventing further message processing.\n   * Once destroyed, the instance cannot be reused.\n   */\n  destroy(): void {\n    if (this._destroyed) return;\n    this._destroyed = true;\n    window.removeEventListener(\"message\", this._boundOnMessage);\n    this._requestTimes.length = 0;\n  }\n\n  /**\n   * Checks if the rate limit has been exceeded.\n   * Uses a sliding window of 1 second.\n   * @returns true if rate limit exceeded, false otherwise\n   */\n  private _isRateLimited(): boolean {\n    const now = Date.now();\n    // Remove requests older than 1 second\n    this._requestTimes = this._requestTimes.filter((t) => now - t < 1000);\n    if (this._requestTimes.length >= this._rateLimit) {\n      return true;\n    }\n    this._requestTimes.push(now);\n    return false;\n  }\n\n  /**\n   * Type guard to validate MessageData structure\n   */\n  private static _isValidMessageData(data: unknown): data is MessageData {\n    if (typeof data !== \"object\" || data === null) return false;\n\n    const msg = data as Partial<MessageData>;\n\n    // Required fields\n    if (typeof msg.messageId !== \"string\" || msg.messageId.length === 0) return false;\n    if (typeof msg.method !== \"string\" || msg.method.length === 0) return false;\n\n    // params must be an array if present (required for apply())\n    if (msg.params !== undefined && !Array.isArray(msg.params)) return false;\n\n    // isHeartbeat must be boolean if present\n    if (msg.isHeartbeat !== undefined && typeof msg.isHeartbeat !== \"boolean\") return false;\n\n    return true;\n  }\n\n  /**\n   * Handles incoming postMessage events from child frames.\n   */\n  private _onMessage(ev: MessageEvent): void {\n    // Ignore messages if destroyed\n    if (this._destroyed) return;\n\n    // Validate the message origin unless all origins are allowed\n    if (this._origin !== \"*\" && ev.origin !== this._origin) {\n      return;\n    }\n\n    // CF-LMS-02: Validate that ev.data has the expected MessageData structure\n    if (!CrossFrameLMS._isValidMessageData(ev.data)) return;\n\n    const msg = ev.data;\n    if (!ev.source) return;\n\n    // Validate that ev.source is a Window with postMessage capability\n    // ev.source can be Window, MessagePort, ServiceWorker, or null\n    // We only handle Window sources for iframe communication\n    if (!(\"postMessage\" in ev.source)) return;\n\n    const source = ev.source as Window;\n\n    // Handle heartbeat separately (bypass rate limit and allowlist)\n    if (msg.isHeartbeat) {\n      const resp: MessageResponse = {\n        messageId: msg.messageId,\n        isHeartbeat: true,\n      };\n      source.postMessage(resp, this._origin);\n      return;\n    }\n\n    // Check rate limit\n    if (this._isRateLimited()) {\n      // SCORM ERROR CODE USAGE: Using error code \"101\" for rate limiting\n      //\n      // While not a standard SCORM error code, \"101\" is used here to signal rate limiting\n      // in cross-frame communication. Standard SCORM error codes are:\n      // - SCORM 1.2: 0, 101, 201, 202, 203, 301, 401, 402, 403, 404, 405\n      // - SCORM 2004: 0, 101, 102, 103, 201, 301, 351, 391, 401-408\n      //\n      // Using \"101\" (General Exception) is appropriate here because:\n      // 1. It indicates a general error condition without exposing security details\n      // 2. It's recognized by SCORM content as a non-zero error code\n      // 3. It doesn't conflict with specific SCORM error semantics\n      // 4. The actual error message \"Rate limit exceeded\" provides debug context\n      //\n      // The CrossFrameAPI detects this specific message to emit a \"rateLimited\" event,\n      // allowing content to react appropriately (e.g., back off, show user message).\n      const resp: MessageResponse = {\n        messageId: msg.messageId,\n        error: { message: \"Rate limit exceeded\", code: \"101\" },\n      };\n      source.postMessage(resp, this._origin);\n      return;\n    }\n\n    // Check method allowlist\n    if (!CrossFrameLMS.ALLOWED_METHODS.has(msg.method)) {\n      const resp: MessageResponse = {\n        messageId: msg.messageId,\n        error: { message: `Method not allowed: ${msg.method}`, code: \"101\" },\n      };\n      source.postMessage(resp, this._origin);\n      return;\n    }\n\n    this._process(msg, source);\n  }\n\n  /**\n   * Processes a validated message by invoking the requested API method.\n   */\n  private _process(msg: MessageData, source: Window): void {\n    const sendResponse = (result?: unknown, error?: { message: string; code?: string }) => {\n      const resp: MessageResponse = { messageId: msg.messageId };\n      if (result !== undefined) resp.result = result;\n      if (error !== undefined) resp.error = error;\n      source.postMessage(resp, this._origin);\n    };\n\n    try {\n      const fn = (this._api as unknown as Record<string, unknown>)[msg.method];\n      if (typeof fn !== \"function\") {\n        sendResponse(undefined, { message: `Method ${msg.method} not found` });\n        return;\n      }\n\n      // CF-LMS-01: Validate params is an array before apply()\n      // This should never fail due to _isValidMessageData check, but defense in depth\n      const params = Array.isArray(msg.params) ? msg.params : [];\n\n      const result = fn.apply(this._api, params);\n\n      if (result && typeof (result as Promise<unknown>).then === \"function\") {\n        (result as Promise<unknown>)\n          .then((r) => sendResponse(r))\n          .catch((e: unknown) => {\n            // ERROR CODE PRESERVATION: Extract error code from Error objects\n            // SCORM API errors may include a numeric code property for specific error conditions.\n            // We preserve this code to maintain proper error semantics across the cross-frame boundary.\n            const message = e instanceof Error ? e.message : \"Unknown error\";\n            const code =\n              e && typeof e === \"object\" && \"code\" in e && typeof e.code === \"string\"\n                ? e.code\n                : undefined;\n            const errorObj: { message: string; code?: string } = { message };\n            if (code !== undefined) {\n              errorObj.code = code;\n            }\n            sendResponse(undefined, errorObj);\n          });\n      } else {\n        sendResponse(result);\n      }\n    } catch (e: unknown) {\n      // ERROR CODE PRESERVATION: Extract error code from Error objects\n      // SCORM API errors may include a numeric code property for specific error conditions.\n      // We preserve this code to maintain proper error semantics across the cross-frame boundary.\n      const message = e instanceof Error ? e.message : \"Unknown error\";\n      const code =\n        e && typeof e === \"object\" && \"code\" in e && typeof e.code === \"string\"\n          ? e.code\n          : undefined;\n      const errorObj: { message: string; code?: string } = { message };\n      if (code !== undefined) {\n        errorObj.code = code;\n      }\n      sendResponse(undefined, errorObj);\n    }\n  }\n}\n"],"names":["CORS_SAFELISTED_CONTENT_TYPES","isCorsSafelistedContentType","contentType","essence","split","trim","toLowerCase","includes","isCrossOriginUrl","url","location","origin","URL","href","designations","D","H","M","S","getSecondsAsHHMMSS","totalSeconds","hours","Math","floor","dateObj","Date","minutes","getUTCMinutes","seconds","getSeconds","ms","msStr","countDecimals","toFixed","String","replace","getSecondsAsISODuration","duration","remainder","Object","entries","forEach","designationsKey","current_seconds","value","indexOf","getTimeAsSeconds","memoize","timeString","timeRegex","RegExp","match","test","parts","toString","getDurationAsSeconds","durationRegex","years","months","weeks","days","exec","result","validateISO8601Duration","flatten","data","recurse","cur","prop","Array","isArray","item","i","length","keys","filter","p","prototype","hasOwnProperty","call","isEmpty","num","stringMatches","str","tester","fn","keyFn","options","cache","Map","args","key","JSON","stringify","maxKeyLength","has","get","maxEntries","size","delete","next","set","appendQueryParam","name","fragmentIndex","baseUrl","slice","fragment","separator","endsWith","encodeURIComponent","BaseCMI","jsonString","_cmi_element","_initialized","constructor","cmi_element","this","initialized","initialize","BaseRootCMI","_start_time","start_time","setStartTime","Error","getTime","BaseScormValidationError","CMIElement","errorCode","super","_errorCode","setPrototypeOf","ValidationError","errorMessage","detailedMessage","message","_errorMessage","_detailedMessage","global_constants","scorm12_constants","basicMessage","detailMessage","scorm2004_constants","cmi_children","comments_children","score_children","objectives_children","correct_responses_children","student_preference_children","interactions_children","adl_data_children","error_descriptions","scorm12_errors","Scorm12ValidationError","scorm2004_errors","Scorm2004ValidationError","global_errors","GENERAL","INITIALIZATION_FAILED","INITIALIZED","TERMINATED","TERMINATION_FAILURE","TERMINATION_BEFORE_INIT","MULTIPLE_TERMINATION","RETRIEVE_BEFORE_INIT","RETRIEVE_AFTER_TERM","STORE_BEFORE_INIT","STORE_AFTER_TERM","COMMIT_BEFORE_INIT","COMMIT_AFTER_TERM","ARGUMENT_ERROR","CHILDREN_ERROR","COUNT_ERROR","GENERAL_GET_FAILURE","GENERAL_SET_FAILURE","GENERAL_COMMIT_FAILURE","UNDEFINED_DATA_MODEL","UNIMPLEMENTED_ELEMENT","VALUE_NOT_INITIALIZED","INVALID_SET_VALUE","READ_ONLY_ELEMENT","WRITE_ONLY_ELEMENT","TYPE_MISMATCH","VALUE_OUT_OF_RANGE","DEPENDENCY_NOT_ESTABLISHED","MULTIPLE_TERMINATIONS","CMIArray","_errorClass","__children","childArray","params","children","errorClass","reset","wipe","_children","_count","toJSON","NAVBoolean","SuccessStatus","CompletionStatus","LogLevelEnum","_","DEBUG","INFO","WARN","ERROR","NONE","DefaultSettings","autocommit","autocommitSeconds","throttleCommits","useAsynchronousCommits","sendFullCommit","lmsCommitUrl","dataCommitFormat","commitRequestDataType","terminationCommitContentType","autoProgress","logLevel","uninitializedGetLogLevel","selfReportSessionTime","alwaysSendTotalTime","accumulateSessionTimeOnTerminate","renderCommonCommitFields","autoCompleteLessonStatus","strict_errors","xhrHeaders","xhrWithCredentials","fetchMode","asyncModeBeaconBehavior","includeCommitSequence","responseHandler","async","response","httpResult","json","text","responseText","parse","e","status","xhrResponseHandler","xhr","requestHandler","commitObject","onLogMessage","defaultLogHandler","mastery_override","score_overrides_status","completion_status_on_failed","scoItemIds","scoItemIdValidator","globalObjectiveIds","enableOfflineSupport","courseId","syncOnInitialize","syncOnTerminate","maxSyncAttempts","scoId","autoPopulateCommitMetadata","httpService","globalStudentPreferences","messageLevel","logMessage","console","error","warn","info","debug","log","scorm12_regex","scorm2004_regex","PERFORMANCE_STEP_NAME","PERFORMANCE_CHARACTERSTRING","LearnerResponses","format","max","delimiter","unique","choice","matching","format2","delimiter2","performance","sequencing","likert","numeric","other","CorrectResponses","duplicate","limit","ScheduledCommit","_API","_cancelled","_timeout","_callback","API","when","callback","setTimeout","wrapper","bind","cancel","clearTimeout","isInitialized","commit","HIDE_LMS_UI_TOKENS","deliveryGenerations","WeakMap","getDeliveryGeneration","activity","isTimeLimitExceeded","now","getElapsedSeconds","timeLimitDuration","attemptAbsoluteDurationLimit","limitSeconds","elapsedSeconds","hasHookValue","hookResult","Number","isNaN","attemptExperiencedDuration","attemptDurationSeconds","attemptAbsoluteStartTime","start","nowMs","isOutsideAvailableTimeRange","clock","beginTime","beginTimeLimit","endTime","endTimeLimit","RuleActionType","OBJECTIVE_TRACKING_CONDITIONS","Set","kleeneNot","kleeneAnd","values","hasUnknown","kleeneOr","RuleCondition","_condition","_operator","_parameters","_referencedObjective","static","condition","operator","parameters","setNowProvider","_now","setElapsedSecondsHook","hook","_getElapsedSecondsHook","referencedObjective","objectiveId","resolveReferencedObjective","primaryObjective","id","objectives","find","obj","evaluate","hasReferencedObjective","sequencingControls","tracked","satisfiedStatusKnown","progressStatus","satisfiedStatus","objectiveSatisfiedStatusKnown","objectiveSatisfiedStatus","successStatus","measureStatus","objectiveMeasureStatus","greaterThanValue","normalizedMeasure","objectiveNormalizedMeasure","lessThanValue","completionStatus","attemptCount","hasAttemptLimitExceeded","parseISO8601Duration","fromEntries","SequencingRule","_conditions","_action","_conditionCombination","action","conditionCombination","conditions","addCondition","push","removeCondition","index","splice","map","SequencingRules","_preConditionRules","_exitConditionRules","_postConditionRules","preConditionRules","addPreConditionRule","rule","exitConditionRules","addExitConditionRule","postConditionRules","addPostConditionRule","evaluatePreConditionRules","evaluateExitConditionRules","evaluatePostConditionRules","SequencingRequestType","DeliveryRequestType","SequencingResult","deliveryRequest","targetActivity","exception","endSequencingSession","FlowSubprocessResult","identifiedActivity","deliverable","ChoiceTraversalResult","FlowSubprocessMode","RuleEvaluationEngine","getAttemptElapsedSecondsHook","checkSequencingRules","rules","checkRuleSubprocess","evaluateExitRules","exitAction","sequencingRules","EXIT","EXIT_PARENT","EXIT_ALL","evaluatePostConditionAction","postAction","RETRY","RETRY_ALL","CONTINUE","PREVIOUS","STOP_FORWARD_TRAVERSAL","evaluatePostConditions","sequencingRequest","terminationRequest","stopForwardTraversal","checkLimitConditions","isSuspended","attemptLimit","attemptLimitMs","parseDuration","activityAbsoluteDurationLimit","activityLimitMs","activityExperiencedDuration","matches","totalMs","parseFloat","beginDate","endDate","canDeliverActivity","canDeliver","wasSkipped","preConditionResult","SKIP","DISABLED","DeliveryValidator","activityTree","eventCallback","contentDeliveredGetter","ruleEngineProvider","ruleEngine","setContentDeliveredGetter","getter","validateTreeConsistency","root","consistent","isActivityPartOfTree","activeActivities","getActiveActivities","fireEvent","a","current","parent","validateResources","requiredResources","getRequiredResources","resource","isResourceAvailable","available","checkSystemLimits","adequate","validateConcurrentDelivery","currentActivity","allowed","hasPendingDeliveryRequests","isDeliveryLocked","validateDependencies","prerequisites","getPrerequisites","prerequisite","isPrerequisiteSatisfied","satisfied","objectiveDependencies","getObjectiveDependencies","dependency","isObjectiveDependencySatisfied","getSequencingRuleDependencies","checkActivity","evaluationActivity","emitEvent","isAvailable","disabledRules","failureReason","attemptInProgress","limitDuration","attemptAbsoluteDuration","activityAbsoluteDuration","currentTime","checks","attemptDurationLimit","activityDurationLimit","child","collectActiveActivities","isActive","resources","activityInfo","title","parseDurationToMinutes","document","createElement","canPlayType","navigator","plugins","from","some","plugin","connection","effectiveType","downlink","window","memory","usedJSHeapSize","jsHeapSizeLimit","deviceMemory","hardwareConcurrency","saveData","pendingRequests","pendingScormRequests","navigationLocked","terminationInProgress","scormMaintenanceMode","referencedObjectiveID","choiceExit","siblings","activityIndex","sibling","prerequisiteActivities","prerequisiteId","_activity","getActivity","dependencies","objective","globalObjectiveID","satisfiedByMeasure","readNormalizedMeasure","allRules","objectiveReference","globalObjectives","globalObjective","statusKnown","baseObjectiveId","measureKnown","referencedActivity","conditionType","progressMeasureStatus","rollupRules","isCompleted","eventType","ActivityTreeQueries","isInTree","getAllActivities","isAncestorOf","ancestor","descendant","findCommonAncestor","activity1","activity2","ancestors1","findChildInPath","target","isLastInTree","getNextSibling","getCurrentInParent","isMandatory","mandatory","isAvailableForChoice","isVisible","isHiddenFromChoice","getAncestors","ancestors","getPathToRoot","path","isLeaf","isCluster","getDepth","depth","ChoiceConstraintValidator","treeQueries","validateChoice","valid","pathValidation","validatePathToRoot","checkAvailability","choiceExitValidation","validateChoiceExit","ancestorValidation","validateAncestorConstraints","preventActivation","currentAncestor","ancestorActivity","validation","validateConstraintsAtLevel","targetChild","currentChild","targetIndex","currentIndex","forwardOnly","intermediateChild","constrainChoice","checkForwardOnlyViolation","fromActivity","validateFlowConstraints","validChildren","meetsFlowConstraints","validateConstrainChoiceForFlow","flow","validateTraversalConstraints","canTraverse","canTraverseInto","evaluateConstrainChoiceForTraversal","evaluateForwardOnlyForChoice","ancestorChildren","childInPath","childIndex","currentAtLevel","intermediateActivity","hasTimeBoundaryViolation","hasAttemptLimitViolation","SelectionTiming","RandomizationTiming","SequencingControls","_enabled","_choice","_choiceExit","_flow","_forwardOnly","_useCurrentAttemptObjectiveInfo","_useCurrentAttemptProgressInfo","_preventActivation","_constrainChoice","_stopForwardTraversal","_rollupObjectiveSatisfied","_rollupProgressCompletion","_objectiveMeasureWeight","_selectionTiming","_selectCount","_selectionCountStatus","_randomizeChildren","_randomizationTiming","_reorderChildren","_completionSetByContent","_objectiveSetByContent","_tracked","enabled","useCurrentAttemptObjectiveInfo","useCurrentAttemptProgressInfo","rollupObjectiveSatisfied","rollupProgressCompletion","objectiveMeasureWeight","isChoiceNavigationAllowed","isFlowNavigationAllowed","isForwardNavigationAllowed","isBackwardNavigationAllowed","selectionTiming","selectCount","selectionCountStatus","randomizeChildren","randomizationTiming","reorderChildren","completionSetByContent","objectiveSetByContent","SelectionRandomization","selectChildrenProcess","controls","NEVER","ONCE","selectedChildren","availableIndices","randomIndex","random","randomizeChildrenProcess","randomizedChildren","j","tempI","tempJ","applySelectionAndRandomization","isNewAttempt","processedChildren","getAvailableChildren","childIds","processedIds","setProcessedChildren","shouldApplySelection","shouldApplyRandomization","ON_EACH_NEW_ATTEMPT","isSelectionNeeded","isRandomizationNeeded","FlowTraversalService","activityEvaluationCallback","setActivityEvaluationCallback","getActivityForEvaluation","flowSubprocess","direction","continueFlowActivityTraversal","flowTreeTraversalSubprocess","skipChildren","forwardTraversalBoundary","FORWARD","traverseForward","traverseBackward","isDescendantOfOrSelf","isActivityLastOverall","terminateDescendentAttempts","ensureSelectionAndRandomization","nextSibling","forwardOnlyCluster","previousSibling","getPreviousSibling","getBackwardTraversalEntry","ancestorIterations","parentPreviousSibling","flowActivityTraversalSubprocess","_direction","considerChildren","mode","evaluateFlowActivity","checkSkippedRuleSet","checkActivityProcess","traversalResult","BACKWARD","skippedRules","deliveryCheck","findFirstDeliverableActivity","cluster","findFirstDeliverableActivityResult","boundary","FlowRequestHandler","traversalService","handleStart","flowResult","DELIVER","handleResumeAll","suspendedActivity","handleContinue","handlePrevious","forwardOnlyViolation","ChoiceRequestHandler","constraintValidator","getNow","handleChoice","targetActivityId","pathActivity","HIDE_FROM_CHOICE","deliveryTarget","choiceFlowSubprocess","handleJump","getAvailableChoices","allActivities","availableActivities","choiceFlowTreeTraversal","enhancedChoiceTraversal","isBackwardTraversal","traversalValidation","ExitRequestHandler","handleExit","handleExitAll","handleAbandon","handleAbandonAll","handleSuspendAll","skipExitRules","processDeferredExitAction","RetryRequestHandler","handleRetry","handleRetryAll","SequencingProcess","flowHandler","choiceHandler","exitHandler","retryHandler","_getAttemptElapsedSecondsHook","applyTraversalCallbacks","_sequencingRules","_sequencingControls","_adlNav","getAttemptElapsedSeconds","sequencingRequestProcess","request","START","RESUME_ALL","DO_NOT_DELIVER","CHOICE","JUMP","ABANDON","ABANDON_ALL","SUSPEND_ALL","canActivityBeDelivered","validateNavigationRequest","choiceValidation","jumpTarget","validator","getTreeQueries","getConstraintValidator","getRuleEngine","getTraversalService","ActivityDeliveryService","eventService","loggingService","callbacks","currentDeliveredActivity","currentDeliveredAttemptCount","currentDeliveredGeneration","pendingDelivery","processSequencingResult","onSequencingError","deliverActivity","onSequencingComplete","generation","unloadActivity","onDeliverActivity","processListeners","onUnloadActivity","getCurrentDeliveredActivity","getPendingDelivery","updateCallbacks","AsynchronousHttpService","reportsRequestCompletion","settings","error_codes","processHttpRequest","immediate","apiLog","metadata","onRequestComplete","_performAsyncRequest","processedParams","performBeacon","performFetch","transformResponse","_isSuccessResponse","_prepareRequestBody","body","join","_sendFetch","init","method","headers","keepalive","credentials","fetch","sendBeacon","beaconContentType","_warnIfBeaconContentTypeUnsafe","beaconSuccess","Blob","type","Promise","resolve","ok","parseError","catch","errorDetails","statusText","substring","updateSettings","TARGET_ATTRIBUTE_PREFIX","getErrorCode","errorCodes","code","CMIValueAccessService","context","getUndefinedDataModelErrorCode","setCMIValue","methodName","scorm2004","throwSCORMError","setLastErrorCode","structure","splitCMIElement","refObject","getDataModel","returnValue","foundFirstIndex","invalidErrorMessage","invalidErrorCode","idx","setFinalAttribute","traverseResult","traverseToNextLevel","getCMIValue","attribute","uninitializedErrorMessage","validationResult","validateGetAttribute","arrayResult","handleGetArrayAccess","startsWith","setStaticValue","checkObjectHasProperty","validateCorrectResponse","getLastErrorCode","checkForDuplicateId","handleSetArrayAccess","parseInt","newChild","getChildElement","isFinalAttribute","attrStr","_isTargetValid","collectionPath","element","targetPath","LoggingService","_logLevel","_logHandler","getInstance","_instance","setLogLevel","level","getLogLevel","setLogHandler","handler","shouldLog","getNumericLevel","toUpperCase","getLoggingService","ErrorHandlingService","_lastErrorCode","_lastDiagnostic","_errorCodes","_apiLog","_getLmsErrorMessageDetails","_loggingService","getLmsErrorMessageDetails","lastErrorCode","lastDiagnostic","errorNumber","formattedMessage","clearSCORMError","success","handleValueAccessException","validationError","errorType","stack","jsonError","EventService","listenerMap","listenerCount","parseListenerName","listenerName","listenerSplit","functionName","on","listenerFunctions","listenerFunction","parsedListener","listeners","off","removeIndex","findIndex","clear","newListeners","listener","listenerHasCMIElement","CMIElementsMatch","prefix","SynchronousHttpService","_processListeners","_onRequestComplete","_handleImmediateRequest","_performSyncXHR","requestPayload","XMLHttpRequest","open","setRequestHeader","withCredentials","send","performAsyncRequest","failure","onload","onerror","ontimeout","OfflineStorageService","getLearnerId","boundOnlineStatusChangeHandler","handleOnlineStatusChange","boundCustomNetworkStatusHandler","handleCustomNetworkStatus","addEventListener","storeName","syncQueue","isOnline","onLine","syncInProgress","wasOnline","syncAfterReconnect","event","CustomEvent","online","detail","hasQueuedData","syncOfflineData","then","storeOffline","commitData","queueItem","learnerId","timestamp","syncAttempts","isTerminateCommit","sequence","currentQueue","getFromStorage","saveToStorage","isQuotaError","getOfflineData","getPendingOfflineData","started","matchingCount","allAccepted","remainingQueue","maxAttempts","syncResult","sendDataToLMS","removeFromStorage","configuredCommitUrl","requestUrl","terminateCommitParam","commitMetadata","trigger","reject","_element","processedData","isDeviceOnline","storedData","localStorage","getItem","setItem","DOMException","cause","removeItem","hasPendingOfflineData","queue","destroy","removeEventListener","checkValidFormat","regexPattern","allowEmptyString","formatRegex","checkValidRange","rangePattern","ranges","minBound","maxBound","hasMaximum","check2004ValidFormat","check2004ValidRange","RollupActionType","RollupConditionCombination","RollupConsiderationType","normalizeMinimumPercent","minimumPercent","RollupCondition","evaluateThreeValued","objectiveInfoAvailable","objectiveInfoAvailableInCurrentParentAttempt","progressInfoAvailable","progressInfoAvailableInCurrentParentAttempt","RollupRule","_consideration","_minimumCount","_minimumPercent","consideration","minimumCount","matchingChildren","every","RollupRules","_rules","addRule","removeRule","processRollup","completionRollup","successRollup","_objectiveRollupUsingMeasure","_defaultCompletionRollup","_defaultSuccessRollup","scaledPassingScore","totalWeight","weightedSum","hasValidMeasures","childWeight","ActivityObjective","_id","_description","_satisfiedByMeasure","_minNormalizedMeasure","_mapInfo","_isPrimary","_satisfiedStatus","_satisfiedStatusKnown","_measureStatus","_normalizedMeasure","_rawScore","_rawScoreKnown","_minScore","_minScoreKnown","_maxScore","_maxScoreKnown","_progressMeasure","_progressMeasureStatus","_completionStatus","_progressStatus","_satisfiedStatusDirty","_normalizedMeasureDirty","_completionStatusDirty","_progressMeasureDirty","_rawScoreDirty","_minScoreDirty","_maxScoreDirty","description","minNormalizedMeasure","mapInfo","isPrimary","rawScore","rawScoreKnown","minScore","minScoreKnown","maxScore","maxScoreKnown","progressMeasure","isDirty","property","clearDirty","clearAllDirty","initializeFromCMI","initializeUnknownSatisfiedStatusFromCMI","initializeUnknownCompletionStatusFromCMI","initializeScoreFromCMI","score","applyReadMappedState","state","normalizedMeasureKnown","resetState","updateFromActivity","applyToActivity","setPrimaryObjectiveState","Activity","_title","_parent","_isVisible","_isActive","_isSuspended","_deliveryWasResumed","_isCompleted","_successStatus","_attemptCount","_objectiveInfoAvailableInCurrentParentAttempt","_progressInfoAvailableInCurrentParentAttempt","_attemptCompletionAmount","_attemptAbsoluteDuration","_attemptExperiencedDuration","_activityAbsoluteDuration","_activityExperiencedDuration","_attemptAbsoluteDurationValue","_attemptExperiencedDurationValue","_activityAbsoluteDurationValue","_activityExperiencedDurationValue","_activityStartTimestampUtc","_attemptStartTimestampUtc","_activityEndedDate","_objectiveSatisfiedStatus","_objectiveSatisfiedStatusKnown","_objectiveMeasureStatus","_objectiveNormalizedMeasure","_scaledPassingScore","_objectiveSatisfiedStatusDirty","_objectiveNormalizedMeasureDirty","_objectiveMeasureStatusDirty","_location","_attemptAbsoluteStartTime","_learnerPrefs","_activityAttemptActive","_isHiddenFromChoice","_isAvailable","_hideLmsUi","_auxiliaryResources","_sharedDataMaps","_attemptLimit","_attemptAbsoluteDurationLimit","_activityAbsoluteDurationLimit","_timeLimitAction","_timeLimitDuration","_beginTimeLimit","_endTimeLimit","_launchData","_credit","_maxTimeAllowed","_completionThreshold","_rollupRules","_processedChildren","_isNewAttempt","_primaryObjective","_objectives","_rollupConsiderations","requiredForSatisfied","requiredForNotSatisfied","requiredForCompleted","requiredForIncomplete","measureSatisfactionIfActive","_wasSkipped","_attemptProgressStatus","_wasAutoCompleted","_wasAutoSatisfied","_completedByMeasure","_minProgressMeasure","_progressWeight","_attemptCompletionAmountStatus","clearAllObjectiveDirty","addChild","setChildOrder","order","childMap","reordered","removeChild","deliveryWasResumed","updatePrimaryObjectiveFromActivity","attemptCompletionAmount","incrementAttemptCount","initializeObjectiveProgressForNewAttempt","initializeAttemptProgressForNewAttempt","initializeTrackingForNewAttempt","learnerPrefs","activityAttemptActive","timeLimitAction","attemptAbsoluteDurationValue","attemptExperiencedDurationValue","activityAbsoluteDurationValue","activityExperiencedDurationValue","activityStartTimestampUtc","attemptStartTimestampUtc","activityEndedDate","date","rollupConsiderations","config","applyRollupConsiderations","attemptProgressStatus","wasAutoCompleted","wasAutoSatisfied","completedByMeasure","minProgressMeasure","progressWeight","attemptCompletionAmountStatus","syncPrimaryObjectiveCollection","addObjective","existingIndex","getObjectiveById","additional","getAllObjectives","additionalObjectives","concat","createObjectiveEvaluationView","view","assign","create","copyObjective","isObjectiveDirty","clearObjectiveDirty","objectiveProgressStatus","getObjectiveStateSnapshot","primary","applyObjectiveStateSnapshot","snapshot","applyObjectiveScoreSnapshot","scoreState","resetProcessedChildren","launchData","credit","maxTimeAllowed","completionThreshold","getSuspensionState","sharedDataMaps","c","restoreSuspensionState","objectiveState","objState","o","childState","hideLmsUi","auxiliaryResources","maps","targetID","readSharedData","writeSharedData","sanitized","seen","resourceId","purpose","add","addAuxiliaryResource","captureRollupStatus","attemptCompletionStatus","compareRollupStatus","prior","abs","directive","RollupChildFilter","checkChildForRollupSubprocess","rollupType","rollupAction","included","filterChildrenForRequirement","shouldIncludeChildForRollup","isChildSatisfiedForRollup","isChildObjectiveStatusKnownForRollup","isChildCompletedForRollup","isChildCompletionStatusKnownForRollup","getTrackableChildren","RollupRuleEvaluator","childFilter","evaluateRollupRule","contributingChildren","satisfiedCount","unknownCount","isIncluded","SATISFIED","NOT_SATISFIED","COMPLETED","INCOMPLETE","evaluateRollupConditionsThreeValued","ALL","ANY","AT_LEAST_COUNT","AT_LEAST_PERCENT","evaluateRollupConditionsSubprocess","results","evaluateRulesForAction","actionType","matchingRules","MeasureRollupProcessor","_childFilter","_eventCallback","measureRollupProcess","counted","total","validData","weight","completionMeasureRollupProcess","trackedChildren","totalWeightedMeasure","ObjectiveRollupProcessor","ruleEvaluator","objectiveRollupProcess","measureResult","objectiveRollupUsingMeasure","syncPrimaryObjectiveFromActivity","ruleResult","objectiveRollupUsingRules","defaultResult","objectiveRollupUsingDefault","satisfiedRules","notSatisfiedRules","notSatisfiedChildren","satisfiedChildren","ProgressRollupProcessor","objectiveProcessor","activityProgressRollupProcess","activityProgressRollupUsingMeasure","completedRules","incompleteRules","incompleteChildren","completedChildren","DurationRollupProcessor","durationRollupProcess","earliestChildActivityStartTimestampUtc","earliestChildAttemptStartTimestampUtc","latestChildEndDate","latestAttemptChildEndDate","childrenActivityExperiencedDurationSeconds","childrenAttemptExperiencedDurationSeconds","activityDuration","attemptDuration","startDate","durationMs","activityId","childCount","GlobalObjectiveSynchronizer","processGlobalObjectiveMapping","globalObjectiveCount","collectActivitiesRecursive","act","syncGlobalObjectivesWritePhase","changedActivities","syncGlobalObjectivesReadPhase","processedObjectives","changedActivityCount","canWriteGlobalObjectives","dirtyFieldsToClear","ensureGlobalObjectiveEntry","targetObjectiveID","writeSatisfiedStatus","hasKnownSatisfiedStatus","writeNormalizedMeasure","writeCompletionStatus","completionStatusKnown","writeRawScore","writeMinScore","writeMaxScore","writeProgressMeasure","progressMeasureKnown","updateAttemptData","updateActivityAttemptData","syncTerminatedActivityWritePhase","writeTargets","targetId","isMeasureSatisfactionDeferred","syncGlobalObjectivesReadPhaseInternal","syncGlobalObjectivesDeliveryReadPhase","syncFreshlyWrittenGlobalObjectivesReadPhase","allowActiveWriteMappedRead","beforeStatus","beforeObjectiveSatisfiedStatusKnown","freshlyWroteSatisfiedStatus","freshlyWroteNormalizedMeasure","readState","getGlobalObjectiveReadState","restrictToFreshWrites","allowSatisfiedStatus","allowNormalizedMeasure","applyGlobalObjectiveReadState","globalState","synchronizationTime","toISOString","synchronizeGlobalObjectives","syncObjectiveState","localObjective","getLocalObjectiveState","localState","suppressSatisfiedRead","suppressMeasureRead","readSatisfiedStatus","readCompletionStatus","readProgressMeasure","readRawScore","readMinScore","readMaxScore","createDefaultMapInfo","hasCompletionRollupRules","suspendData","RollupStateValidator","rollupStateLog","validateRollupStateConsistency","rootActivity","inconsistencies","validateActivityRollupState","count","measure","getRollupStateLog","clearRollupStateLog","RollupProcess","childContributionControlsApplyToParent","measureProcessor","progressProcessor","durationProcessor","globalObjectiveSynchronizer","stateValidator","rollupActivity","overallRollupProcess","includeActivity","affectedActivities","onlyDurationRollup","isFirst","afterStatus","rolledUpParents","activityDepth","candidate","sort","left","right","changedActivity","syncTerminatedActivityObjectives","syncActivityObjectivesFromGlobals","syncFreshlyWrittenObjectivesToActiveAncestor","getChildFilter","getRuleEvaluator","getMeasureProcessor","getObjectiveProcessor","getProgressProcessor","getDurationProcessor","getGlobalObjectiveSynchronizer","getStateValidator","ObjectiveEvaluationContext","synchronizer","project","commonAncestor","leaving","projectedGlobals","entry","evaluateCompletionStatusFromThreshold","storedCompletionStatus","thresholdValue","progressValue","VALID_SUCCESS_STATUSES","validateCompletionStatus","validateSuccessStatus","RteDataTransferService","transferRteData","getCMIData","cmiData","transferPrimaryObjective","transferNonPrimaryObjectives","hasProgressMeasure","progress_measure","validatedCompletionStatus","completion_status","hasSuccessStatus","hasNormalizedMeasure","normalizedScore","validatedSuccessStatus","success_status","getObjectiveScoreState","normalized","normalizeScore","cmiObjective","activityObjectiveMatch","activityObjective","isPrimaryObjective","hasExplicitUnknownSuccessStatus","hasCompletionStatus","topLevelCompletionStatus","topLevelPrimaryCompletionWasSet","completion_status_was_set","topLevelSuccessStatus","topLevelPrimarySuccessWasSet","success_status_was_set","topLevelPrimaryScoreWasSet","score_was_set","validatedObjSuccessStatus","validatedObjCompletionStatus","scaled","raw","min","TerminationHandler","sequencingProcess","rollupProcess","globalObjectiveMap","is4thEdition","invalidateCacheCallback","_rteDataTransferService","setInvalidateCacheCallback","processTerminationRequest","hasSequencingRequest","exitType","handleExitTermination","terminateDescendants","endAttempt","exitActionResult","ancestorExitResult","applyAncestorExitActionRules","processedExit","postConditionResult","exitAllResult","toActivity","_currentActivity","handleMultiLevelExit","cleanupSuspendedActivity","activityPath","suspendResult","processSuspendAllRequest","suspendedPath","pathLength","recursionDepth","exitRules","postResult","processExitAtLevel","terminateAll","terminatingActivity","unshift","exitActionRulesSubprocess","cleanedActivities","originalSuspendedActivity","clearSuspendedActivity","contentCommunicatedObjectiveStatus","hasSuspendedChildren","activeAncestor","primaryObjectiveId","DeliveryRequest","DeliveryHandler","adlNav","defaultHideLmsUi","defaultAuxiliaryResources","_deliveryInProgress","contentDelivered","endAttemptCallback","checkActivityCallback","updateNavigationValidityCallback","clearSuspendedActivityCallback","setEndAttemptCallback","terminateDescendentAttemptsProcess","setCheckActivityCallback","setUpdateNavigationValidityCallback","setClearSuspendedActivityCallback","isDeliveryInProgress","hasContentBeenDelivered","resetContentDelivered","setContentDelivered","processDeliveryRequest","getActivityPath","contentDeliveryEnvironmentProcess","isResuming","suspendedPathActivities","newAttemptActivities","isPathActivityResuming","hasKnownReadMappedObjective","initializeForDelivery","setupAttemptTracking","advanceDeliveryGeneration","fireDeliveryEvent","audioCaptioning","audioLevel","deliverySpeed","language","getEffectiveHideLmsUi","HIDE_LMS_UI_ORDER","getEffectiveAuxiliaryResources","merged","lineage","node","reverse","getContentActivityData","pop","NavigationLookAhead","predictContinueEnabled","ensureCacheValid","continueEnabled","predictPreviousEnabled","previousEnabled","predictChoiceEnabled","choiceEnabledMap","predictJumpEnabled","availableChoices","getAllPredictions","invalidateCache","updateCache","currentTreeHash","calculateTreeStateHash","treeStateHash","recalculateCache","predictContinueInternal","predictPreviousInternal","calculateAvailableChoices","calculateAvailableChoicesFromRoot","hasAvailablePreviousActivity","isActivityPotentiallyDeliverableBackward","recursivelyCheckChoiceAvailability","isChoiceEnabled","getActivityTreeStateSignature","signatures","collectActivitySignatures","NavigationRequestType","NavigationRequestResult","NavigationValidityService","navigationLookAhead","getEffectiveHideLmsUiCallback","getEffectiveAuxiliaryResourcesCallback","setGetEffectiveHideLmsUiCallback","setGetEffectiveAuxiliaryResourcesCallback","getNavigationLookAhead","validateRequest","validateStartRequest","validateResumeRequest","validateContinueRequest","validatePreviousRequest","validateChoiceRequest","validateJumpRequest","validateExitRequest","validateExitAllRequest","validateAbandonRequest","validateAbandonAllRequest","validateSuspendAllRequest","forwardOnlyValidation","validateForwardOnlyConstraints","validateChoicePath","isActivityDisabled","activityContains","constrainChoiceValidation","validateConstrainChoice","choiceSetValidation","validateChoiceSet","currentBranch","findChildContaining","targetBranch","requiresNewActivation","validateAncestors","evaluatePreConditionRulesForChoice","container","currentTop","targetTop","traversalStopIndex","between","isActivityMandatory","isActivityCompleted","branchRoot","branchHasActiveAttempt","updateNavigationValidity","continueValid","request_valid","continue","previousValid","previous","choiceMap","jumpMap","choiceRes","jump","GlobalObjectiveService","collectObjectives","objectiveCount","getMap","getSnapshot","serialize","restoreSnapshot","restore","updateObjective","objectiveData","lastUpdated","synchronize","getObjective","hasObjective","getObjectiveIds","getObjectiveCount","serialized","mapData","SequencingStateManager","globalObjectiveService","contentDeliveredSetter","setContentDeliveredAccessors","setter","getState","version","activityStates","serializeActivities","navigationState","getNavigationState","restoreState","deserializeActivities","currentActivityState","setCurrentActivityWithoutActivation","restoreNavigationState","states","serializeActivity","selectionRandomizationState","childOrder","selectedChildIds","hiddenFromChoiceChildIds","restoreActivity","selectionState","selectedSet","hiddenSet","isSelected","requestValid","exit","exitAll","abandon","abandonAll","suspendAll","navState","currentActivityId","suspendedActivityId","hasActivityTree","originalTimestamp","restoreTimestamp","OverallSequencingProcess","terminationHandler","deliveryHandler","navigationValidityService","stateManager","deliveryValidator","enhancedDeliveryValidation","deliveryValidatorOptions","terminationOptions","deliveryOptions","setupCallbacks","evaluationContext","processNavigationRequest","navigationRequest","completeNavigationRequest","prepareNavigationRequest","navResult","sessionEndReason","hadSequencingRequest","termResult","prepared","reason","seqResult","processDelivery","stateCheck","resourceCheck","concurrentCheck","dependencyCheck","deliveryResult","getGlobalObjectiveMap","getGlobalObjectiveMapSnapshot","restoreGlobalObjectiveMapSnapshot","updateGlobalObjective","getSequencingState","restoreSequencingState","invalidateNavigationCache","applyDeliveryControls","terminationRequestProcess","endAttemptProcess","ActivityTree","_root","_suspendedActivity","_activities","_addActivitiesToMap","activitiesToPreserve","getParent","getChildren","useAvailableChildren","getSiblings","getFirstChild","getLastChild","getCommonAncestor","path1","modelPrototypes","clonePreviewState","copy","getPrototypeOf","Reflect","ownKeys","descriptor","getOwnPropertyDescriptor","defineProperty","SequencingService","cmi","adl","activityDeliveryService","overallSequencingProcess","eventListeners","configuration","navigationPreviewConfiguration","isSequencingActive","deliveryNotificationsInProgress","lastCMIValues","lastSequencingResult","autoRollupOnCMIChange","autoProgressOnCompletion","validateNavigationRequests","enableEventSystem","handleActivityDelivery","handleActivityUnload","handleSequencingComplete","handleSequencingError","rollupClock","setupCMIChangeWatchers","createSequencingProcesses","nav","seqOptions","getActivityElapsedSeconds","overallOptions","getCMIDataForTransfer","handleSequencingProcessEvent","shouldAutoStartSequencing","startSequencing","initializeCMITracking","getCurrentActivity","errorMsg","terminate","triggerFinalRollup","endSequencing","previewNavigationRequest","unknown","outcome","tree","pending","process","ended","preview","getExitValueInternal","navRequestType","parseNavigationRequest","rollbackState","operation","handleNavigationDeliveryRequest","cancelPreparedNavigation","sequencingResult","wasInProgress","triggerRollupOnCMIChange","cmiElement","oldValue","newValue","updateActivityFromCMI","setEventListeners","updateConfiguration","getRootActivity","getOverallSequencingProcess","scaledScore","threshold","wasCMIElementSetByContent","field","objectiveIndex","baseCmiObj","normalizedRequest","NOT_VALID","fireDebugEvent","argsLength","listenerError","eventServiceError","scormSequencingEvents","globalListeners","globalError","fireActivityAttemptStart","fireActivityAttemptEnd","fireLimitConditionCheck","fireNavigationValidityUpdate","validity","fireSequencingStateChange","stateKeys","logLevels","configLevel","SerializationService","loadFromFlattenedJSON","isNotInitialized","setStartingData","onInvalidValue","int_pattern","obj_pattern","interactions","others","intMatch","objMatch","b","localeCompare","processItems","items","loadFromJSON","pattern","regex","m","unflatten","setLeaf","currentCMIElement","tempCMIElement","renderCMIToJSONString","k","v","renderCMIToJSONObject","getCommitObject","terminateCommit","renderCommitObject","renderCommitCMI","apiLogLevel","includeTotalTime","check12ValidFormat","check12ValidRange","validationService","validateScore","decimalRegex","scoreRange","invalidTypeCode","invalidRangeCode","validateScorm12Audio","validateScorm12Language","validateScorm12Speed","validateScorm12Text","validateReadOnly","BaseAPI","_error_codes","_settings","_httpService","_eventService","_serializationService","_errorHandlingService","_offlineStorageService","_cmiValueAccessService","_courseId","_pendingCommitCount","_commitSequence","_commitSettleWaiters","_setCMIElements","serializationService","cmiDataService","errorHandlingService","offlineStorageService","TypeError","currentState","asyncCommit","createErrorHandlingService","getOfflineLearnerId","hasPendingData","_checkForDuplicateId","attr","_checkObjectHasProperty","startingData","commonReset","clearScheduledCommit","preserveListeners","restoreOfflineData","restoreValue","runtimeData","callbackName","initializeMessage","terminationMessage","isTerminated","syncSuccess","messageString","padEnd","formatMessage","previousSettings","pendingCommitCount","whenCommitsSettled","waiter","timeoutMs","timeoutId","waiterIndex","_flushCommitSettleWaiters","waiters","checkTerminated","stateCheckPassed","storeData","resultValue","getValue","checkState","checkUninitializedGet","setValue","commitCallback","scheduleCommit","getLastError","getErrorString","CMIErrorCode","getDiagnostic","customDiagnostic","beforeInitError","afterTermError","getCMIArrayProperty","hasDuplicateId","array","idValue","objectivesMatch","interactionObjectivesMatch","interactionIndex","currentObjIndex","interaction","_errorNumber","_detail","_CMIElement","_value","_commonSetCMIValue","_commonGetCMIValue","_returnValue","loadCMIValue","previousErrorCode","getFlattenedCMI","settled","completionDeferred","settle","resolvedTrigger","finalParams","terminateCommitPayloadField","commitSequence","finalUrl","CMIScore","__score_range","__invalid_error_code","__invalid_type_code","__invalid_range_code","__decimal_regex","__error_class","__allow_empty_string","_raw","_min","_max","score_range","getScoreObject","scoreObject","CMICore","_student_id","_student_name","_lesson_location","_lesson_status","_entry","_total_time","_lesson_mode","_exit","_session_time","_suspend_data","student_id","student_name","lesson_location","lesson_status","total_time","lesson_mode","session_time","suspend_data","getCurrentTotalTime","sessionTime","first","second","_status","CMIStudentData","_mastery_score","_max_time_allowed","_time_limit_action","student_data_children","mastery_score","normalizedMasteryScore","max_time_allowed","normalizedValue","fieldName","parseTimeAllowed","time_limit_action","CMIStudentPreference","_audio","_language","_speed","_text","audio","speed","correct_responses","_time","_type","_weighting","_student_response","_result","_latency","time","weighting","student_response","normalizedResult","latency","_pattern","__version","_launch_data","_comments","_comments_from_lms","student_data","core","CMIObjectives","student_preference","CMIInteractions","launch_data","comments","comments_from_lms","_version","NAV","_event","Scorm12API","clearGlobalPreferences","_globalLearnerPrefs","settingsCopy","CMI","LMSInitialize","lmsInitialize","LMSFinish","lmsFinish","LMSGetValue","lmsGetValue","LMSSetValue","lmsSetValue","LMSCommit","lmsCommit","LMSGetLastError","lmsGetLastError","LMSGetErrorString","lmsGetErrorString","LMSGetDiagnostic","lmsGetDiagnostic","statusSetByModule","resetTotalTime","parameter","_updateGlobalPreference","CMIObjectivesObject","CMIInteractionsCorrectResponsesObject","CMIInteractionsObjectivesObject","CMIInteractionsObject","replaceWithAnotherScormAPI","newAPI","cmiExport","flattened","totalTimeHHMMSS","totalTimeSeconds","lessonStatus","learnerName","originalStatus","processCommitData","masteryScore","CMILearnerPreference","_audio_level","_delivery_speed","_audio_captioning","audio_level","delivery_speed","audio_captioning","stripBrackets","delim","escapeRegex","s","splitDelimited","bracketed","allowBare","bare","splitRe","unescapeRe","part","splitFirstDelimited","allowsBareDelimiters","isSpecForm","EMPTY_CORRECT_PATTERN_TYPES","EMPTY_LEARNER_RESPONSE_TYPES","_idIsSet","_timestamp","_learner_response","learner_response","nodes","response_type","stripCorrectResponsePrefixes","firstItem","invalidValue","invalidPosition","_interactionType","interactionType","responseDef","freeText","rawNodes","fmt1","fmt2","checkSingle","checkPair","delimBracketed","nodeIndex","part1","part2","validatePattern","Scorm2004CMIScore","_scaled","CMICommentsFromLMS","CMICommentsFromLearner","CMICommentsObject","_comment","_readOnlyAfterInit","readOnlyAfterInit","comment","findObjectiveById","findObjectiveByIndex","setObjectiveByIndex","_success_status","_completion_status","_progress_measure","fromJSON","CMIMetadata","CMILearner","_learner_id","_learner_name","learner_id","learner_name","CMIStatus","CMISession","addTwoDurations","accumulateSessionTime","CMIContent","CMISettings","_mode","CMIThresholds","_scaled_passing_score","_completion_threshold","scaled_passing_score","completion_threshold","learner","session","content","thresholds","learner_preference","comments_from_learner","ADL","ADLNav","ADLData","_sequencing","_sharedDataStores","configureSharedDataMaps","captureVisibleSharedData","configure","captureSharedDataSnapshot","captureWritableSharedDataSnapshot","writableStores","storeIsSet","storeValue","restoreSharedDataSnapshot","store","refreshStores","isConfiguredSharedDataElement","isConfiguredElement","_request","ADLNavRequestValid","setParentNav","deinitialize","stores","ADLDataObject","dataObject","refreshStore","isInteger","_store","_storeIsSet","_readSharedData","_writeSharedData","_onStoreChange","_allowStoreWithoutId","allowStoreWithoutId","onStoreChange","setStaticNavigationValue","kind","ADLNavRequestValidChoice","_parentNav","_staticValues","getStaticValue","getAll","setAll","ADLNavRequestValidJump","_continue","_previous","_jump","_exitAll","_abandon","_abandonAll","_suspendAll","converted","Sequencing","_activityTree","_overallSequencingProcess","_processRollupRecursive","Scorm2004ResponseValidator","checkValidResponseType","interaction_type","checkCorrectResponseValue","checkDuplicateChoiceResponse","interaction_count","pattern_index","checkDuplicatedPattern","correct_response","current_index","found","existingPattern","removeCorrectResponsePrefixes","Scorm2004CMIHandler","responseValidator","createCorrectResponsesObject","evaluateCompletionStatus","evaluateSuccessStatus","storedStatus","passingScoreValue","scoreValue","SequencingConfigurationBuilder","applySequencingControlsSettings","applySequencingRulesSettings","ruleSettings","createSequencingRule","conditionSettings","applyRollupRulesSettings","createRollupRule","sanitizeSequencingCollections","collections","collection","trimmedId","sanitizedCollection","cloneObjective","cloned","mapping","ruleClone","clonedCondition","clonedRule","cloneSelectionRandomizationState","sanitizeHideLmsUi","sanitizeAuxiliaryResources","normalizeCollectionRefs","refs","ref","trimmed","applySequencingCollection","selectionStates","inlineSequencingRules","mergeHideLmsUi","sanitizedAux","mergeAuxiliaryResources","existing","additions","clone","applySelectionRandomizationState","selectionTouched","ActivityTreeBuilder","sequencingCollections","sequencingConfigBuilder","setSequencingCollections","createActivity","activitySettings","collectionRefs","sequencingCollectionRefs","sequencingIdRef","objectiveSettings","mergeObjectiveSettings","incoming","objectiveID","primarySettings","createActivityObjectiveFromSettings","deliveryControls","mergedHide","childSettings","childActivity","extractActivityIds","ids","GlobalObjectiveManager","_globalObjectives","hostDeclaredGlobalObjectiveIds","updateSequencingService","service","sequencingService","isHostDeclaredGlobalObjectiveId","syncGlobalObjectiveIdsFromSequencing","overallProcess","globalIds","getSettings","mergedIds","restoreGlobalObjectivesToCMI","hasCurrentSequencingActivity","globalObj","commonSetCMIValue","updateGlobalObjectiveFromCMI","fallbackEntry","buildObjectiveMapEntryFromCMI","updatePayload","parseObjectiveNumber","buildCMIObjectivesFromMap","buildCMIObjectiveFromJSON","isFinite","captureGlobalObjectiveSnapshot","processSnapshot","restoreGlobalObjectiveSnapshot","parsed","syncCmiToSequencingActivity","findOrCreateGlobalObjective","newGlobalObjective","SequencingStatePersistence","globalObjectiveManager","inFlightLoads","saveSequencingState","sequencingStatePersistence","stateData","serializeSequencingState","fullMetadata","attemptNumber","stateVersion","dataToSave","compress","compressStateData","maxStateSize","persistence","saveState","debugPersistence","loadSequencingState","loadKey","existingLoad","loadOperation","loadState","dataToLoad","decompressStateData","deserializeSequencingState","finally","adlNavState","sharedData","sequencingState","suspensionState","expectedVersion","restoredObjectives","objectivesFromMap","objData","fromMap","restoredActivity","wasInitialized","savedValidity","btoa","atob","decodeURIComponent","Scorm2004DataSerializer","setGlobalObjectiveManager","manager","renderCMIExport","captureSharedData","totalTimeDuration","sequencingRoot","metaSettings","determineEntryValue","previousExit","hasSuspendData","trimmedExit","NO_DEFAULT_2004_ELEMENTS","Scorm2004API","_sequencingService","_restoringFromJSON","_runtimeSetCMIElements","_extractedScoItemIds","_sequencingCollections","_responseValidator","_cmiHandler","_activityTreeBuilder","_sequencingConfigBuilder","_globalObjectiveManager","_statePersistence","_dataSerializer","globalObjectiveContext","dataSerializerContext","configureSequencing","initializeSequencingService","Initialize","Terminate","GetValue","SetValue","Commit","GetLastError","GetErrorString","GetDiagnostic","applyCurrentActivityLaunchData","applyActivityLaunchData","applyDeliveredActivityLaunchData","contentActivityData","seedCurrentActivityObjectives","applyCurrentActivityObjectiveData","activityObjectives","seededObjectiveIds","getSeedableObjectiveId","findOrSeedCMIObjective","getActivityObjectiveSuccessStatus","seedObjectiveReadMapValues","applyObjectiveReadStateToCMI","autoLoadOnInitialize","pendingNavRequest","wasAlreadyTerminated","deliveryInProgress","normalizedTarget","choiceJumpRegex","groups","choice_target","jump_target","targetForProcessing","requestToProcess","preparedNavigation","navigationHandled","sequencingAttempted","processedSequencingRequest","autoSaveOn","autoSaveSequencingState","adlNavRequestRegex","staticValue","_peekCMIValue","rollupError","element_base","objective_id","currentActivityAllowsGlobalObjectiveWrites","global_index","global_element","updatedObjective","segments","nextIndex","normalizeCMIIndices","errorDescription","navRequest","validCommands","command","dotIndex","eventName","resumeAll","sequencingSettings","configureActivityTree","configureSequencingRules","configureSequencingControls","configureRollupRules","activityTreeSettings","sequencingRulesSettings","sequencingControlsSettings","rollupRulesSettings","createPersistenceContext","api","sequencingConfig","buildSequencingEventListeners","onActivityDelivery","getSequencingService","setSequencingEventListeners","updateSequencingConfiguration","source","saved","resetSequencingState","getActivityTrackingData","CrossFrameAPI","_cache","_cacheTimestamps","_lastError","_pending","_counter","_origin","_targetWindow","_heartbeatInterval","_heartbeatTimeout","_destroyed","_connected","_lastHeartbeatResponse","_heartbeatTimer","_eventListeners","_boundOnMessage","_isValidMessageResponse","messageId","err","isHeartbeat","_validateArgs","_handler","receiver","isGet","isSet","isInit","isFinish","isCommit","isErrorString","isDiagnostic","requestTime","_post","res","localModTime","_capture","all","val","targetOrigin","targetWindow","timeout","heartbeatInterval","heartbeatTimeout","_onMessage","_startHeartbeat","Proxy","clearInterval","timer","connected","_emit","cb","setInterval","_sendHeartbeat","postMessage","safeParams","ev","CrossFrameLMS","_api","_rateLimit","_requestTimes","rateLimit","_isRateLimited","t","_isValidMessageData","msg","ALLOWED_METHODS","_process","sendResponse","resp","apply","r","errorObj"],"mappings":"aAIO,MAeDA,EAAgC,CACpC,aACA,oCACA,uBAGK,SAASC,EAA4BC,GAC1C,MAAMC,IAAYD,GAAe,IAAIE,MAAM,KAAK,IAAM,IAAIC,OAAOC,cACjE,OAAON,EAA8BO,SAASJ,EAChD,CAEO,SAASK,EAAiBC,GAC/B,GAAwB,oBAAbC,WAA6BA,WAAaA,SAASC,OAAQ,OAAO,EAC7E,IACE,OAAO,IAAIC,IAAIH,EAAKC,SAASG,MAAMF,SAAWD,SAASC,MACzD,CAAA,MACE,OAAO,CACT,CACF,CAEA,MAAMG,EAA4B,CAChCC,EAjC6B,MAkC7BC,EAnC8B,KAoC9BC,EArCgC,GAsChCC,EAvCgC,GA6DrBC,EAAsBC,IAEjC,IAAKA,GAAgC,GAAhBA,EACnB,MAAO,WAGT,MAAMC,EAAQC,KAAKC,MAAMH,EAjEK,MAkExBI,EAAU,IAAIC,KAAoB,IAAfL,GACnBM,EAAUF,EAAQG,gBAElBC,EAAUJ,EAAQK,aAClBC,EAAKV,EAAe,EAC1B,IAAIW,EAAQ,GAYZ,OAVIC,EAAcF,GAAM,IAEpBC,EADEC,EAAcF,GAAM,EACdA,EAAGG,QAAQ,GAEJH,EAAPI,GAGVH,EAAQ,IAAMA,EAAM3B,MAAM,KAAK,KAGzBiB,EAAQ,IAAMK,EAAU,IAAME,GAASO,QAAQ,UAAW,OAASJ,GA2BhEK,EAA2BR,IAEtC,IAAKA,GAAsB,GAAXA,EACd,MAAO,OAGT,IAAIS,EAAW,IACXC,EAAYV,EAsChB,OAnC2BW,OAAOC,QAAQ1B,GAGvB2B,QAAQ,EAAEC,EAAiBC,MAC5C,IAAIC,EAAQtB,KAAKC,MAAMe,EAAYK,GACnCL,GAAwBK,EAGpBX,EAAcM,GAAa,IAC7BA,KAA0BA,GAAWL,QAAQ,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