{"version":3,"file":"scorm2004.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/scorm2004/learner_preference.ts","../../src/cmi/scorm2004/interaction_delimiters.ts","../../src/cmi/scorm2004/interactions.ts","../../src/cmi/common/score.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"],"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","/**\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","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","/**\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"],"names":["CORS_SAFELISTED_CONTENT_TYPES","isCorsSafelistedContentType","contentType","essence","split","trim","toLowerCase","includes","isCrossOriginUrl","url","location","origin","URL","href","designations","D","H","M","S","getSecondsAsISODuration","seconds","duration","remainder","Object","entries","forEach","designationsKey","current_seconds","value","Math","floor","num","String","indexOf","parts","length","countDecimals","toFixed","getDurationAsSeconds","memoize","durationRegex","RegExp","match","years","months","weeks","days","hours","minutes","exec","result","toString","validateISO8601Duration","flatten","data","recurse","cur","prop","Array","isArray","item","i","keys","filter","p","prototype","hasOwnProperty","call","isEmpty","stringMatches","str","tester","test","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","Date","getTime","BaseScormValidationError","CMIElement","errorCode","super","_errorCode","setPrototypeOf","ValidationError","errorMessage","detailedMessage","message","_errorMessage","_detailedMessage","global_constants","scorm2004_constants","cmi_children","comments_children","score_children","objectives_children","correct_responses_children","student_preference_children","interactions_children","adl_data_children","error_descriptions","basicMessage","detailMessage","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","replace","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","CMILearnerPreference","_audio_level","_language","_delivery_speed","_audio_captioning","audio_level","delivery_speed","audio_captioning","stripBrackets","delim","escapeRegex","s","splitDelimited","bracketed","allowBare","bare","splitRe","unescapeRe","part","splitFirstDelimited","first","allowsBareDelimiters","isSpecForm","EMPTY_CORRECT_PATTERN_TYPES","EMPTY_LEARNER_RESPONSE_TYPES","CMIInteractions","CMIInteractionsObject","_idIsSet","_type","_timestamp","_weighting","_learner_response","_result","_latency","correct_responses","weighting","learner_response","nodes","response_type","latency","CMIInteractionsObjectivesObject","stripCorrectResponsePrefixes","firstItem","invalidValue","invalidPosition","CMIInteractionsCorrectResponsesObject","_pattern","_interactionType","interactionType","responseDef","freeText","rawNodes","fmt1","fmt2","checkSingle","checkPair","delimBracketed","nodeIndex","part1","part2","validatePattern","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","Scorm2004CMIScore","_scaled","CMICommentsFromLMS","CMICommentsFromLearner","CMICommentsObject","_comment","_readOnlyAfterInit","readOnlyAfterInit","comment","CMIObjectives","findObjectiveById","findObjectiveByIndex","setObjectiveByIndex","CMIObjectivesObject","_success_status","_completion_status","_progress_measure","fromJSON","CMIMetadata","__version","_version","CMILearner","_learner_id","_learner_name","learner_id","learner_name","CMIStatus","CMISession","_entry","_exit","_session_time","_total_time","session_time","total_time","getCurrentTotalTime","sessionTime","second","addTwoDurations","accumulateSessionTime","CMIContent","_launch_data","_suspend_data","launch_data","suspend_data","CMISettings","_mode","_time_limit_action","_max_time_allowed","time_limit_action","max_time_allowed","CMIThresholds","_scaled_passing_score","_completion_threshold","scaled_passing_score","completion_threshold","CMI","learner","session","content","thresholds","learner_preference","comments_from_learner","comments_from_lms","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","cmiExport","renderCMIExport","captureSharedData","flattened","totalTimeDuration","totalTimeSeconds","sequencingRoot","metaSettings","learnerName","determineEntryValue","previousExit","hasSuspendData","trimmedExit","NO_DEFAULT_2004_ELEMENTS","Scorm2004API","_sequencingService","_restoringFromJSON","_runtimeSetCMIElements","_extractedScoItemIds","_sequencingCollections","_responseValidator","_cmiHandler","_activityTreeBuilder","_sequencingConfigBuilder","_globalObjectiveManager","_statePersistence","_dataSerializer","settingsCopy","globalObjectiveContext","dataSerializerContext","configureSequencing","initializeSequencingService","Initialize","lmsInitialize","Terminate","lmsFinish","GetValue","lmsGetValue","SetValue","lmsSetValue","Commit","lmsCommit","GetLastError","lmsGetLastError","GetErrorString","lmsGetErrorString","GetDiagnostic","lmsGetDiagnostic","resetTotalTime","applyCurrentActivityLaunchData","applyActivityLaunchData","applyDeliveredActivityLaunchData","contentActivityData","seedCurrentActivityObjectives","applyCurrentActivityObjectiveData","activityObjectives","seededObjectiveIds","getSeedableObjectiveId","findOrSeedCMIObjective","getActivityObjectiveSuccessStatus","seedObjectiveReadMapValues","applyObjectiveReadStateToCMI","parameter","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","replaceWithAnotherScormAPI","newAPI","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"],"mappings":"oEAIO,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,EAjC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