@pie-qti/player-elements 0.1.22 → 0.1.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/dist/ar-SA-BDmOol_3.js +854 -0
  2. package/dist/ar-SA-BDmOol_3.js.map +1 -0
  3. package/dist/{define-Bkc2UFCK.js → define-D7_K0JFy.js} +4057 -2664
  4. package/dist/define-D7_K0JFy.js.map +1 -0
  5. package/dist/dist-BRTWr852.js +5809 -0
  6. package/dist/dist-BRTWr852.js.map +1 -0
  7. package/dist/{dist-CPyrAOfS.js → dist-BaQdJU08.js} +210 -130
  8. package/dist/dist-BaQdJU08.js.map +1 -0
  9. package/dist/{dist-C0bIgnik.js → dist-DwvskOs6.js} +4 -4
  10. package/dist/{dist-C0bIgnik.js.map → dist-DwvskOs6.js.map} +1 -1
  11. package/dist/{dist-_mWRIrTg.js → dist-ffJZTPTU.js} +2440 -2658
  12. package/dist/dist-ffJZTPTU.js.map +1 -0
  13. package/dist/{element-BrpUrZI4.js → element-DSCNeDLu.js} +2 -2
  14. package/dist/{element-BrpUrZI4.js.map → element-DSCNeDLu.js.map} +1 -1
  15. package/dist/{element-class-DWoLXp_r-ms67Krq-.js → element-class-DQy2cIPM-CldZrSRR.js} +3717 -3464
  16. package/dist/element-class-DQy2cIPM-CldZrSRR.js.map +1 -0
  17. package/dist/elements/BaseSvelteMountElement.d.ts +1 -0
  18. package/dist/elements/QtiAssessmentPlayerElement.d.ts +1 -0
  19. package/dist/elements.js +3 -3
  20. package/dist/es-ES-C98YtDtb.js +802 -0
  21. package/dist/es-ES-C98YtDtb.js.map +1 -0
  22. package/dist/fr-FR-CrmmiRPf.js +802 -0
  23. package/dist/fr-FR-CrmmiRPf.js.map +1 -0
  24. package/dist/index.js +2 -2
  25. package/dist/item-toolbar-element-BW9Y_n5x.js +1990 -0
  26. package/dist/item-toolbar-element-BW9Y_n5x.js.map +1 -0
  27. package/dist/{tag-names-DV56RHJk.js → language-tags-DVlRltrl.js} +25 -22
  28. package/dist/language-tags-DVlRltrl.js.map +1 -0
  29. package/dist/nl-NL-BeQBX6yq.js +505 -0
  30. package/dist/nl-NL-BeQBX6yq.js.map +1 -0
  31. package/dist/nl-NL-CAR7pgVz.js +802 -0
  32. package/dist/nl-NL-CAR7pgVz.js.map +1 -0
  33. package/dist/pie-assessment-toolkit-element-CpiB3twr.js +8573 -0
  34. package/dist/pie-assessment-toolkit-element-CpiB3twr.js.map +1 -0
  35. package/dist/pie-tool-calculator-BiWMTJe7.js +2992 -0
  36. package/dist/pie-tool-calculator-BiWMTJe7.js.map +1 -0
  37. package/dist/provider-Y5PhmTAu.js +58 -0
  38. package/dist/provider-Y5PhmTAu.js.map +1 -0
  39. package/dist/register-players.js +1 -1
  40. package/dist/register.js +7285 -9569
  41. package/dist/register.js.map +1 -1
  42. package/dist/{resolveItems-XtUnsftV.js → resolveItems-D8DJkv-4.js} +2 -2
  43. package/dist/{resolveItems-XtUnsftV.js.map → resolveItems-D8DJkv-4.js.map} +1 -1
  44. package/dist/ro-RO-DTZbhL0e.js +802 -0
  45. package/dist/ro-RO-DTZbhL0e.js.map +1 -0
  46. package/dist/root-DSkIM1v3.js +47 -0
  47. package/dist/root-DSkIM1v3.js.map +1 -0
  48. package/dist/th-TH-aqlT_oK3.js +802 -0
  49. package/dist/th-TH-aqlT_oK3.js.map +1 -0
  50. package/dist/tool-tts-inline-B71NTBbb.js +4435 -0
  51. package/dist/tool-tts-inline-B71NTBbb.js.map +1 -0
  52. package/dist/zh-CN-DCqaRRhU.js +802 -0
  53. package/dist/zh-CN-DCqaRRhU.js.map +1 -0
  54. package/package.json +8 -8
  55. package/dist/define-Bkc2UFCK.js.map +0 -1
  56. package/dist/dist-CPyrAOfS.js.map +0 -1
  57. package/dist/dist-DU1nH3y8.js +0 -1247
  58. package/dist/dist-DU1nH3y8.js.map +0 -1
  59. package/dist/dist-_mWRIrTg.js.map +0 -1
  60. package/dist/element-class-DWoLXp_r-ms67Krq-.js.map +0 -1
  61. package/dist/item-toolbar-element-DFppTi_H.js +0 -6015
  62. package/dist/item-toolbar-element-DFppTi_H.js.map +0 -1
  63. package/dist/pie-assessment-toolkit-element-DlSFT_I2.js +0 -28479
  64. package/dist/pie-assessment-toolkit-element-DlSFT_I2.js.map +0 -1
  65. package/dist/pie-tool-calculator-BGp3etqJ.js +0 -2226
  66. package/dist/pie-tool-calculator-BGp3etqJ.js.map +0 -1
  67. package/dist/root-DBWhDxjY.js +0 -98
  68. package/dist/root-DBWhDxjY.js.map +0 -1
  69. package/dist/tag-names-DV56RHJk.js.map +0 -1
  70. package/dist/tool-tts-inline-DVUYjVnD.js +0 -2574
  71. package/dist/tool-tts-inline-DVUYjVnD.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"dist-DU1nH3y8.js","names":["DOMPurify","logger","logger","logger","logger","logger","logger","logger","customEvent","logger"],"sources":["../../../node_modules/.bun/dompurify@3.4.13/node_modules/dompurify/dist/purify.es.mjs","../../../node_modules/.bun/@pie-players+pie-players-shared@0.3.53/node_modules/@pie-players/pie-players-shared/dist/security/sanitize-svg-icon.js","../../../node_modules/.bun/@pie-players+pie-players-shared@0.3.53/node_modules/@pie-players/pie-players-shared/dist/config/profile.js","../../../node_modules/.bun/@pie-players+pie-players-shared@0.3.53/node_modules/@pie-players/pie-players-shared/dist/instrumentation/providers/BaseInstrumentationProvider.js","../../../node_modules/.bun/@pie-players+pie-players-shared@0.3.53/node_modules/@pie-players/pie-players-shared/dist/instrumentation/providers/NewRelicInstrumentationProvider.js","../../../node_modules/.bun/@pie-players+pie-players-shared@0.3.53/node_modules/@pie-players/pie-players-shared/dist/instrumentation/provider-guards.js","../../../node_modules/.bun/@pie-players+pie-players-shared@0.3.53/node_modules/@pie-players/pie-players-shared/dist/loader-config.js","../../../node_modules/.bun/@pie-players+pie-players-shared@0.3.53/node_modules/@pie-players/pie-players-shared/dist/pie/types.js","../../../node_modules/.bun/@pie-players+pie-players-shared@0.3.53/node_modules/@pie-players/pie-players-shared/dist/loaders/element-loader.js","../../../node_modules/.bun/@pie-players+pie-players-shared@0.3.53/node_modules/@pie-players/pie-players-shared/dist/types/index.js","../../../node_modules/.bun/@pie-players+pie-players-shared@0.3.53/node_modules/@pie-players/pie-players-shared/dist/pie/logger.js","../../../node_modules/.bun/@pie-players+pie-players-shared@0.3.53/node_modules/@pie-players/pie-players-shared/dist/pie/math-rendering.js","../../../node_modules/.bun/@pie-players+pie-players-shared@0.3.53/node_modules/@pie-players/pie-players-shared/dist/pie/scoring.js","../../../node_modules/.bun/@pie-players+pie-players-shared@0.3.53/node_modules/@pie-players/pie-players-shared/dist/pie/updates.js","../../../node_modules/.bun/@pie-players+pie-players-shared@0.3.53/node_modules/@pie-players/pie-players-shared/dist/pie/initialization.js","../../../node_modules/.bun/@pie-players+pie-players-shared@0.3.53/node_modules/@pie-players/pie-players-shared/dist/pie/asset-handler.js","../../../node_modules/.bun/@pie-players+pie-players-shared@0.3.53/node_modules/@pie-players/pie-players-shared/dist/pie/authoring.js","../../../node_modules/.bun/@pie-players+pie-players-shared@0.3.53/node_modules/@pie-players/pie-players-shared/dist/pie/instrumentation-event-bridge.js","../../../node_modules/.bun/@pie-players+pie-players-shared@0.3.53/node_modules/@pie-players/pie-players-shared/dist/pie/instrumentation-provider-resolution.js","../../../node_modules/.bun/@pie-players+pie-players-shared@0.3.53/node_modules/@pie-players/pie-players-shared/dist/pie/stages.js","../../../node_modules/.bun/@pie-players+pie-players-shared@0.3.53/node_modules/@pie-players/pie-players-shared/dist/pie/stage-tracker.js","../../../node_modules/.bun/@pie-players+pie-players-shared@0.3.53/node_modules/@pie-players/pie-players-shared/dist/pie/item-session-contract.js","../../../node_modules/.bun/@pie-players+pie-players-shared@0.3.53/node_modules/@pie-players/pie-players-shared/dist/pie/overrides.js","../../../node_modules/.bun/@pie-players+pie-players-shared@0.3.53/node_modules/@pie-players/pie-players-shared/dist/ui/first-focusable.js","../../../node_modules/.bun/@pie-players+pie-players-shared@0.3.53/node_modules/@pie-players/pie-players-shared/dist/ui/focus-trap.js"],"sourcesContent":["/*! @license DOMPurify 3.4.13 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.4.13/LICENSE */\n\nfunction _arrayLikeToArray(r, a) {\n (null == a || a > r.length) && (a = r.length);\n for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];\n return n;\n}\nfunction _arrayWithHoles(r) {\n if (Array.isArray(r)) return r;\n}\nfunction _iterableToArrayLimit(r, l) {\n var t = null == r ? null : \"undefined\" != typeof Symbol && r[Symbol.iterator] || r[\"@@iterator\"];\n if (null != t) {\n var e,\n n,\n i,\n u,\n a = [],\n f = true,\n o = false;\n try {\n if (i = (t = t.call(r)).next, 0 === l) ; else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0);\n } catch (r) {\n o = true, n = r;\n } finally {\n try {\n if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return;\n } finally {\n if (o) throw n;\n }\n }\n return a;\n }\n}\nfunction _nonIterableRest() {\n throw new TypeError(\"Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n}\nfunction _slicedToArray(r, e) {\n return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest();\n}\nfunction _unsupportedIterableToArray(r, a) {\n if (r) {\n if (\"string\" == typeof r) return _arrayLikeToArray(r, a);\n var t = {}.toString.call(r).slice(8, -1);\n return \"Object\" === t && r.constructor && (t = r.constructor.name), \"Map\" === t || \"Set\" === t ? Array.from(r) : \"Arguments\" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;\n }\n}\n\nconst entries = Object.entries,\n setPrototypeOf = Object.setPrototypeOf,\n isFrozen = Object.isFrozen,\n getPrototypeOf = Object.getPrototypeOf,\n getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;\nlet freeze = Object.freeze,\n seal = Object.seal,\n create = Object.create; // eslint-disable-line import/no-mutable-exports\nlet _ref = typeof Reflect !== 'undefined' && Reflect,\n apply = _ref.apply,\n construct = _ref.construct;\nif (!freeze) {\n freeze = function freeze(x) {\n return x;\n };\n}\nif (!seal) {\n seal = function seal(x) {\n return x;\n };\n}\nif (!apply) {\n apply = function apply(func, thisArg) {\n for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {\n args[_key - 2] = arguments[_key];\n }\n return func.apply(thisArg, args);\n };\n}\nif (!construct) {\n construct = function construct(Func) {\n for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {\n args[_key2 - 1] = arguments[_key2];\n }\n return new Func(...args);\n };\n}\nconst arrayForEach = unapply(Array.prototype.forEach);\nconst arrayLastIndexOf = unapply(Array.prototype.lastIndexOf);\nconst arrayPop = unapply(Array.prototype.pop);\nconst arrayPush = unapply(Array.prototype.push);\nconst arraySplice = unapply(Array.prototype.splice);\nconst arrayIsArray = Array.isArray;\nconst stringToLowerCase = unapply(String.prototype.toLowerCase);\nconst stringToString = unapply(String.prototype.toString);\nconst stringMatch = unapply(String.prototype.match);\nconst stringReplace = unapply(String.prototype.replace);\nconst stringIndexOf = unapply(String.prototype.indexOf);\nconst stringTrim = unapply(String.prototype.trim);\nconst numberToString = unapply(Number.prototype.toString);\nconst booleanToString = unapply(Boolean.prototype.toString);\nconst bigintToString = typeof BigInt === 'undefined' ? null : unapply(BigInt.prototype.toString);\nconst symbolToString = typeof Symbol === 'undefined' ? null : unapply(Symbol.prototype.toString);\nconst objectHasOwnProperty = unapply(Object.prototype.hasOwnProperty);\nconst objectToString = unapply(Object.prototype.toString);\nconst regExpTest = unapply(RegExp.prototype.test);\nconst typeErrorCreate = unconstruct(TypeError);\n/**\n * Creates a new function that calls the given function with a specified thisArg and arguments.\n *\n * @param func - The function to be wrapped and called.\n * @returns A new function that calls the given function with a specified thisArg and arguments.\n */\nfunction unapply(func) {\n return function (thisArg) {\n if (thisArg instanceof RegExp) {\n thisArg.lastIndex = 0;\n }\n for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {\n args[_key3 - 1] = arguments[_key3];\n }\n return apply(func, thisArg, args);\n };\n}\n/**\n * Creates a new function that constructs an instance of the given constructor function with the provided arguments.\n *\n * @param func - The constructor function to be wrapped and called.\n * @returns A new function that constructs an instance of the given constructor function with the provided arguments.\n */\nfunction unconstruct(Func) {\n return function () {\n for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {\n args[_key4] = arguments[_key4];\n }\n return construct(Func, args);\n };\n}\n/**\n * Add properties to a lookup table\n *\n * @param set - The set to which elements will be added.\n * @param array - The array containing elements to be added to the set.\n * @param transformCaseFunc - An optional function to transform the case of each element before adding to the set.\n * @returns The modified set with added elements.\n */\nfunction addToSet(set, array) {\n let transformCaseFunc = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : stringToLowerCase;\n if (setPrototypeOf) {\n // Make 'in' and truthy checks like Boolean(set.constructor)\n // independent of any properties defined on Object.prototype.\n // Prevent prototype setters from intercepting set as a this value.\n setPrototypeOf(set, null);\n }\n if (!arrayIsArray(array)) {\n return set;\n }\n let l = array.length;\n while (l--) {\n let element = array[l];\n if (typeof element === 'string') {\n const lcElement = transformCaseFunc(element);\n if (lcElement !== element) {\n // Config presets (e.g. tags.js, attrs.js) are immutable.\n if (!isFrozen(array)) {\n array[l] = lcElement;\n }\n element = lcElement;\n }\n }\n set[element] = true;\n }\n return set;\n}\n/**\n * Clean up an array to harden against CSPP\n *\n * @param array - The array to be cleaned.\n * @returns The cleaned version of the array\n */\nfunction cleanArray(array) {\n for (let index = 0; index < array.length; index++) {\n const isPropertyExist = objectHasOwnProperty(array, index);\n if (!isPropertyExist) {\n array[index] = null;\n }\n }\n return array;\n}\n/**\n * Shallow clone an object\n *\n * @param object - The object to be cloned.\n * @returns A new object that copies the original.\n */\nfunction clone(object) {\n const newObject = create(null);\n for (const _ref2 of entries(object)) {\n var _ref3 = _slicedToArray(_ref2, 2);\n const property = _ref3[0];\n const value = _ref3[1];\n const isPropertyExist = objectHasOwnProperty(object, property);\n if (isPropertyExist) {\n if (arrayIsArray(value)) {\n newObject[property] = cleanArray(value);\n } else if (value && typeof value === 'object' && value.constructor === Object) {\n newObject[property] = clone(value);\n } else {\n newObject[property] = value;\n }\n }\n }\n return newObject;\n}\n/**\n * Convert non-node values into strings without depending on direct property access.\n *\n * @param value - The value to stringify.\n * @returns A string representation of the provided value.\n */\nfunction stringifyValue(value) {\n switch (typeof value) {\n case 'string':\n {\n return value;\n }\n case 'number':\n {\n return numberToString(value);\n }\n case 'boolean':\n {\n return booleanToString(value);\n }\n case 'bigint':\n {\n return bigintToString ? bigintToString(value) : '0';\n }\n case 'symbol':\n {\n return symbolToString ? symbolToString(value) : 'Symbol()';\n }\n case 'undefined':\n {\n return objectToString(value);\n }\n case 'function':\n case 'object':\n {\n if (value === null) {\n return objectToString(value);\n }\n const valueAsRecord = value;\n const valueToString = lookupGetter(valueAsRecord, 'toString');\n if (typeof valueToString === 'function') {\n const stringified = valueToString(valueAsRecord);\n return typeof stringified === 'string' ? stringified : objectToString(stringified);\n }\n return objectToString(value);\n }\n default:\n {\n return objectToString(value);\n }\n }\n}\n/**\n * This method automatically checks if the prop is function or getter and behaves accordingly.\n *\n * @param object - The object to look up the getter function in its prototype chain.\n * @param prop - The property name for which to find the getter function.\n * @returns The getter function found in the prototype chain or a fallback function.\n */\nfunction lookupGetter(object, prop) {\n while (object !== null) {\n const desc = getOwnPropertyDescriptor(object, prop);\n if (desc) {\n if (desc.get) {\n return unapply(desc.get);\n }\n if (typeof desc.value === 'function') {\n return unapply(desc.value);\n }\n }\n object = getPrototypeOf(object);\n }\n function fallbackValue() {\n return null;\n }\n return fallbackValue;\n}\nfunction isRegex(value) {\n try {\n regExpTest(value, '');\n return true;\n } catch (_unused) {\n return false;\n }\n}\n\nconst html$1 = freeze(['a', 'abbr', 'acronym', 'address', 'area', 'article', 'aside', 'audio', 'b', 'bdi', 'bdo', 'big', 'blink', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'center', 'cite', 'code', 'col', 'colgroup', 'content', 'data', 'datalist', 'dd', 'decorator', 'del', 'details', 'dfn', 'dialog', 'dir', 'div', 'dl', 'dt', 'element', 'em', 'fieldset', 'figcaption', 'figure', 'font', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'img', 'input', 'ins', 'kbd', 'label', 'legend', 'li', 'main', 'map', 'mark', 'marquee', 'menu', 'menuitem', 'meter', 'nav', 'nobr', 'ol', 'optgroup', 'option', 'output', 'p', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'search', 'section', 'select', 'shadow', 'slot', 'small', 'source', 'spacer', 'span', 'strike', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'time', 'tr', 'track', 'tt', 'u', 'ul', 'var', 'video', 'wbr']);\nconst svg$1 = freeze(['svg', 'a', 'altglyph', 'altglyphdef', 'altglyphitem', 'animatecolor', 'animatemotion', 'animatetransform', 'circle', 'clippath', 'defs', 'desc', 'ellipse', 'enterkeyhint', 'exportparts', 'filter', 'font', 'g', 'glyph', 'glyphref', 'hkern', 'image', 'inputmode', 'line', 'lineargradient', 'marker', 'mask', 'metadata', 'mpath', 'part', 'path', 'pattern', 'polygon', 'polyline', 'radialgradient', 'rect', 'stop', 'style', 'switch', 'symbol', 'text', 'textpath', 'title', 'tref', 'tspan', 'view', 'vkern']);\nconst svgFilters = freeze(['feBlend', 'feColorMatrix', 'feComponentTransfer', 'feComposite', 'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap', 'feDistantLight', 'feDropShadow', 'feFlood', 'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR', 'feGaussianBlur', 'feImage', 'feMerge', 'feMergeNode', 'feMorphology', 'feOffset', 'fePointLight', 'feSpecularLighting', 'feSpotLight', 'feTile', 'feTurbulence']);\n// List of SVG elements that are disallowed by default.\n// We still need to know them so that we can do namespace\n// checks properly in case one wants to add them to\n// allow-list.\nconst svgDisallowed = freeze(['animate', 'color-profile', 'cursor', 'discard', 'font-face', 'font-face-format', 'font-face-name', 'font-face-src', 'font-face-uri', 'foreignobject', 'hatch', 'hatchpath', 'mesh', 'meshgradient', 'meshpatch', 'meshrow', 'missing-glyph', 'script', 'set', 'solidcolor', 'unknown', 'use']);\nconst mathMl$1 = freeze(['math', 'menclose', 'merror', 'mfenced', 'mfrac', 'mglyph', 'mi', 'mlabeledtr', 'mmultiscripts', 'mn', 'mo', 'mover', 'mpadded', 'mphantom', 'mroot', 'mrow', 'ms', 'mspace', 'msqrt', 'mstyle', 'msub', 'msup', 'msubsup', 'mtable', 'mtd', 'mtext', 'mtr', 'munder', 'munderover', 'mprescripts']);\n// Similarly to SVG, we want to know all MathML elements,\n// even those that we disallow by default.\nconst mathMlDisallowed = freeze(['maction', 'maligngroup', 'malignmark', 'mlongdiv', 'mscarries', 'mscarry', 'msgroup', 'mstack', 'msline', 'msrow', 'semantics', 'annotation', 'annotation-xml', 'mprescripts', 'none']);\nconst text = freeze(['#text']);\n\nconst html = freeze(['accept', 'action', 'align', 'alt', 'autocapitalize', 'autocomplete', 'autopictureinpicture', 'autoplay', 'background', 'bgcolor', 'border', 'capture', 'cellpadding', 'cellspacing', 'checked', 'cite', 'class', 'clear', 'color', 'cols', 'colspan', 'command', 'commandfor', 'controls', 'controlslist', 'coords', 'crossorigin', 'datetime', 'decoding', 'default', 'dir', 'disabled', 'disablepictureinpicture', 'disableremoteplayback', 'download', 'draggable', 'enctype', 'enterkeyhint', 'exportparts', 'face', 'for', 'headers', 'height', 'hidden', 'high', 'href', 'hreflang', 'id', 'inert', 'inputmode', 'integrity', 'ismap', 'kind', 'label', 'lang', 'list', 'loading', 'loop', 'low', 'max', 'maxlength', 'media', 'method', 'min', 'minlength', 'multiple', 'muted', 'name', 'nonce', 'noshade', 'novalidate', 'nowrap', 'open', 'optimum', 'part', 'pattern', 'placeholder', 'playsinline', 'popover', 'popovertarget', 'popovertargetaction', 'poster', 'preload', 'pubdate', 'radiogroup', 'readonly', 'rel', 'required', 'rev', 'reversed', 'role', 'rows', 'rowspan', 'spellcheck', 'scope', 'selected', 'shape', 'size', 'sizes', 'slot', 'span', 'srclang', 'start', 'src', 'srcset', 'step', 'style', 'summary', 'tabindex', 'title', 'translate', 'type', 'usemap', 'valign', 'value', 'width', 'wrap', 'xmlns']);\nconst svg = freeze(['accent-height', 'accumulate', 'additive', 'alignment-baseline', 'amplitude', 'ascent', 'attributename', 'attributetype', 'azimuth', 'basefrequency', 'baseline-shift', 'begin', 'bias', 'by', 'class', 'clip', 'clippathunits', 'clip-path', 'clip-rule', 'color', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'cx', 'cy', 'd', 'dx', 'dy', 'diffuseconstant', 'direction', 'display', 'divisor', 'dominant-baseline', 'dur', 'edgemode', 'elevation', 'end', 'exponent', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'filterunits', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'fx', 'fy', 'g1', 'g2', 'glyph-name', 'glyphref', 'gradientunits', 'gradienttransform', 'height', 'href', 'id', 'image-rendering', 'in', 'in2', 'intercept', 'k', 'k1', 'k2', 'k3', 'k4', 'kerning', 'keypoints', 'keysplines', 'keytimes', 'lang', 'lengthadjust', 'letter-spacing', 'kernelmatrix', 'kernelunitlength', 'lighting-color', 'local', 'marker-end', 'marker-mid', 'marker-start', 'markerheight', 'markerunits', 'markerwidth', 'maskcontentunits', 'maskunits', 'max', 'mask', 'mask-type', 'media', 'method', 'mode', 'min', 'name', 'numoctaves', 'offset', 'operator', 'opacity', 'order', 'orient', 'orientation', 'origin', 'overflow', 'paint-order', 'path', 'pathlength', 'patterncontentunits', 'patterntransform', 'patternunits', 'points', 'preservealpha', 'preserveaspectratio', 'primitiveunits', 'r', 'rx', 'ry', 'radius', 'refx', 'refy', 'repeatcount', 'repeatdur', 'restart', 'result', 'rotate', 'scale', 'seed', 'shape-rendering', 'slope', 'specularconstant', 'specularexponent', 'spreadmethod', 'startoffset', 'stddeviation', 'stitchtiles', 'stop-color', 'stop-opacity', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke', 'stroke-width', 'style', 'surfacescale', 'systemlanguage', 'tabindex', 'tablevalues', 'targetx', 'targety', 'transform', 'transform-origin', 'text-anchor', 'text-decoration', 'text-orientation', 'text-rendering', 'textlength', 'type', 'u1', 'u2', 'unicode', 'values', 'viewbox', 'visibility', 'version', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'width', 'word-spacing', 'wrap', 'writing-mode', 'xchannelselector', 'ychannelselector', 'x', 'x1', 'x2', 'xmlns', 'y', 'y1', 'y2', 'z', 'zoomandpan']);\nconst mathMl = freeze(['accent', 'accentunder', 'align', 'bevelled', 'close', 'columnalign', 'columnlines', 'columnspacing', 'columnspan', 'denomalign', 'depth', 'dir', 'display', 'displaystyle', 'encoding', 'fence', 'frame', 'height', 'href', 'id', 'largeop', 'length', 'linethickness', 'lquote', 'lspace', 'mathbackground', 'mathcolor', 'mathsize', 'mathvariant', 'maxsize', 'minsize', 'movablelimits', 'notation', 'numalign', 'open', 'rowalign', 'rowlines', 'rowspacing', 'rowspan', 'rspace', 'rquote', 'scriptlevel', 'scriptminsize', 'scriptsizemultiplier', 'selection', 'separator', 'separators', 'stretchy', 'subscriptshift', 'supscriptshift', 'symmetric', 'voffset', 'width', 'xmlns']);\nconst xml = freeze(['xlink:href', 'xml:id', 'xlink:title', 'xml:space', 'xmlns:xlink']);\n\nconst MUSTACHE_EXPR = seal(/{{[\\w\\W]*|^[\\w\\W]*}}/g);\nconst ERB_EXPR = seal(/<%[\\w\\W]*|^[\\w\\W]*%>/g);\nconst TMPLIT_EXPR = seal(/\\${[\\w\\W]*/g);\nconst DATA_ATTR = seal(/^data-[\\-\\w.\\u00B7-\\uFFFF]+$/); // eslint-disable-line no-useless-escape\nconst ARIA_ATTR = seal(/^aria-[\\-\\w]+$/); // eslint-disable-line no-useless-escape\nconst IS_ALLOWED_URI = seal(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\\-]+(?:[^a-z+.\\-:]|$))/i // eslint-disable-line no-useless-escape\n);\nconst IS_SCRIPT_OR_DATA = seal(/^(?:\\w+script|data):/i);\nconst ATTR_WHITESPACE = seal(/[\\u0000-\\u0020\\u00A0\\u1680\\u180E\\u2000-\\u2029\\u205F\\u3000]/g // eslint-disable-line no-control-regex\n);\nconst DOCTYPE_NAME = seal(/^html$/i);\nconst CUSTOM_ELEMENT = seal(/^[a-z][.\\w]*(-[.\\w]+)+$/i);\n// Markup-significant character probes used by _sanitizeElements.\n// Shared module-level instances are safe despite the sticky /g flags:\n// unapply() resets lastIndex for RegExp receivers before every call.\nconst ELEMENT_MARKUP_PROBE = seal(/<[/\\w!]/g);\nconst COMMENT_MARKUP_PROBE = seal(/<[/\\w]/g);\nconst FALLBACK_TAG_CLOSE = seal(/<\\/no(script|embed|frames)/i);\nconst SELF_CLOSING_TAG = seal(/\\/>/i);\n\n// https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType\nconst NODE_TYPE = {\n element: 1,\n attribute: 2,\n text: 3,\n cdataSection: 4,\n entityReference: 5,\n // Deprecated\n entityNode: 6,\n // Deprecated\n processingInstruction: 7,\n comment: 8,\n document: 9,\n documentType: 10,\n documentFragment: 11,\n notation: 12 // Deprecated\n};\nconst getGlobal = function getGlobal() {\n return typeof window === 'undefined' ? null : window;\n};\n/**\n * Creates a no-op policy for internal use only.\n * Don't export this function outside this module!\n * @param trustedTypes The policy factory.\n * @param purifyHostElement The Script element used to load DOMPurify (to determine policy name suffix).\n * @return The policy created (or null, if Trusted Types\n * are not supported or creating the policy failed).\n */\nconst _createTrustedTypesPolicy = function _createTrustedTypesPolicy(trustedTypes, purifyHostElement) {\n if (typeof trustedTypes !== 'object' || typeof trustedTypes.createPolicy !== 'function') {\n return null;\n }\n // Allow the callers to control the unique policy name\n // by adding a data-tt-policy-suffix to the script element with the DOMPurify.\n // Policy creation with duplicate names throws in Trusted Types.\n let suffix = null;\n const ATTR_NAME = 'data-tt-policy-suffix';\n if (purifyHostElement && purifyHostElement.hasAttribute(ATTR_NAME)) {\n suffix = purifyHostElement.getAttribute(ATTR_NAME);\n }\n const policyName = 'dompurify' + (suffix ? '#' + suffix : '');\n try {\n return trustedTypes.createPolicy(policyName, {\n createHTML(html) {\n return html;\n },\n createScriptURL(scriptUrl) {\n return scriptUrl;\n }\n });\n } catch (_) {\n // Policy creation failed (most likely another DOMPurify script has\n // already run). Skip creating the policy, as this will only cause errors\n // if TT are enforced.\n console.warn('TrustedTypes policy ' + policyName + ' could not be created.');\n return null;\n }\n};\nconst _createHooksMap = function _createHooksMap() {\n return {\n afterSanitizeAttributes: [],\n afterSanitizeElements: [],\n afterSanitizeShadowDOM: [],\n beforeSanitizeAttributes: [],\n beforeSanitizeElements: [],\n beforeSanitizeShadowDOM: [],\n uponSanitizeAttribute: [],\n uponSanitizeElement: [],\n uponSanitizeShadowNode: []\n };\n};\n/**\n * Resolve a set-valued configuration option: a fresh set built from\n * cfg[key] when it is an own array property (seeded with a clone of\n * options.base when given, case-normalized via options.transform),\n * the fallback set otherwise.\n *\n * @param cfg the cloned, prototype-free configuration object\n * @param key the configuration property to read\n * @param fallback the set to use when the option is absent or not an array\n * @param options transform and optional base set to merge into\n * @returns the resolved set\n */\nconst _resolveSetOption = function _resolveSetOption(cfg, key, fallback, options) {\n return objectHasOwnProperty(cfg, key) && arrayIsArray(cfg[key]) ? addToSet(options.base ? clone(options.base) : {}, cfg[key], options.transform) : fallback;\n};\nfunction createDOMPurify() {\n let window = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getGlobal();\n const DOMPurify = root => createDOMPurify(root);\n DOMPurify.version = '3.4.13';\n DOMPurify.removed = [];\n if (!window || !window.document || window.document.nodeType !== NODE_TYPE.document || !window.Element) {\n // Not running in a browser, provide a factory function\n // so that you can pass your own Window\n DOMPurify.isSupported = false;\n return DOMPurify;\n }\n let document = window.document;\n const originalDocument = document;\n const currentScript = originalDocument.currentScript;\n window.DocumentFragment;\n const HTMLTemplateElement = window.HTMLTemplateElement,\n Node = window.Node,\n Element = window.Element,\n NodeFilter = window.NodeFilter,\n _window$NamedNodeMap = window.NamedNodeMap;\n _window$NamedNodeMap === void 0 ? window.NamedNodeMap || window.MozNamedAttrMap : _window$NamedNodeMap;\n window.HTMLFormElement;\n const DOMParser = window.DOMParser,\n trustedTypes = window.trustedTypes;\n const ElementPrototype = Element.prototype;\n const cloneNode = lookupGetter(ElementPrototype, 'cloneNode');\n const remove = lookupGetter(ElementPrototype, 'remove');\n const getNextSibling = lookupGetter(ElementPrototype, 'nextSibling');\n const getChildNodes = lookupGetter(ElementPrototype, 'childNodes');\n const getParentNode = lookupGetter(ElementPrototype, 'parentNode');\n const getShadowRoot = lookupGetter(ElementPrototype, 'shadowRoot');\n const getAttributes = lookupGetter(ElementPrototype, 'attributes');\n const getNodeType = Node && Node.prototype ? lookupGetter(Node.prototype, 'nodeType') : null;\n const getNodeName = Node && Node.prototype ? lookupGetter(Node.prototype, 'nodeName') : null;\n const getOwnerDocument = Node && Node.prototype ? lookupGetter(Node.prototype, 'ownerDocument') : null;\n // As per issue #47, the web-components registry is inherited by a\n // new document created via createHTMLDocument. As per the spec\n // (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-registries)\n // a new empty registry is used when creating a template contents owner\n // document, so we use that as our parent document to ensure nothing\n // is inherited.\n if (typeof HTMLTemplateElement === 'function') {\n const template = document.createElement('template');\n if (template.content && template.content.ownerDocument) {\n document = template.content.ownerDocument;\n }\n }\n let trustedTypesPolicy;\n let emptyHTML = '';\n // The instance's own internal Trusted Types policy. Unlike a caller-supplied\n // `TRUSTED_TYPES_POLICY`, this is created at most once — Trusted Types throws\n // on duplicate policy names — and is the only policy allowed to persist\n // across configurations and survive `clearConfig()`.\n let defaultTrustedTypesPolicy;\n let defaultTrustedTypesPolicyResolved = false;\n // Tracks whether we are already inside a call to the configured Trusted Types\n // policy (`createHTML` or `createScriptURL`). If a supplied policy callback\n // itself calls `DOMPurify.sanitize` (the cause of #1422), `sanitize` would\n // re-enter the policy and recurse until the stack overflows. We detect that\n // re-entry and throw a clear, actionable error instead. The guard is shared\n // across both callbacks, because either one re-entering `sanitize` triggers\n // the same unbounded recursion.\n let IN_TRUSTED_TYPES_POLICY = 0;\n const _assertNotInTrustedTypesPolicy = function _assertNotInTrustedTypesPolicy() {\n if (IN_TRUSTED_TYPES_POLICY > 0) {\n throw typeErrorCreate('A configured TRUSTED_TYPES_POLICY callback (createHTML or ' + 'createScriptURL) must not call DOMPurify.sanitize, as that causes ' + 'infinite recursion. Do not pass a policy whose callbacks wrap ' + 'DOMPurify as TRUSTED_TYPES_POLICY; see the \"DOMPurify and Trusted ' + 'Types\" section of the README.');\n }\n };\n const _createTrustedHTML = function _createTrustedHTML(html) {\n _assertNotInTrustedTypesPolicy();\n IN_TRUSTED_TYPES_POLICY++;\n try {\n return trustedTypesPolicy.createHTML(html);\n } finally {\n IN_TRUSTED_TYPES_POLICY--;\n }\n };\n const _createTrustedScriptURL = function _createTrustedScriptURL(scriptUrl) {\n _assertNotInTrustedTypesPolicy();\n IN_TRUSTED_TYPES_POLICY++;\n try {\n return trustedTypesPolicy.createScriptURL(scriptUrl);\n } finally {\n IN_TRUSTED_TYPES_POLICY--;\n }\n };\n // Lazily resolve (and cache) the instance's internal default policy.\n // Resolution is attempted at most once: a successful `createPolicy` cannot be\n // repeated (Trusted Types throws on duplicate names), and a failed or\n // unsupported attempt must not be retried on every parse.\n const _getDefaultTrustedTypesPolicy = function _getDefaultTrustedTypesPolicy() {\n if (!defaultTrustedTypesPolicyResolved) {\n defaultTrustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, currentScript);\n defaultTrustedTypesPolicyResolved = true;\n }\n return defaultTrustedTypesPolicy;\n };\n const _document = document,\n implementation = _document.implementation,\n createNodeIterator = _document.createNodeIterator,\n createDocumentFragment = _document.createDocumentFragment,\n getElementsByTagName = _document.getElementsByTagName;\n const importNode = originalDocument.importNode;\n let hooks = _createHooksMap();\n /**\n * Expose whether this browser supports running the full DOMPurify.\n */\n DOMPurify.isSupported = typeof entries === 'function' && typeof getParentNode === 'function' && implementation && implementation.createHTMLDocument !== undefined;\n const MUSTACHE_EXPR$1 = MUSTACHE_EXPR,\n ERB_EXPR$1 = ERB_EXPR,\n TMPLIT_EXPR$1 = TMPLIT_EXPR,\n DATA_ATTR$1 = DATA_ATTR,\n ARIA_ATTR$1 = ARIA_ATTR,\n IS_SCRIPT_OR_DATA$1 = IS_SCRIPT_OR_DATA,\n ATTR_WHITESPACE$1 = ATTR_WHITESPACE,\n CUSTOM_ELEMENT$1 = CUSTOM_ELEMENT;\n let IS_ALLOWED_URI$1 = IS_ALLOWED_URI;\n /**\n * We consider the elements and attributes below to be safe. Ideally\n * don't add any new ones but feel free to remove unwanted ones.\n */\n /* allowed element names */\n let ALLOWED_TAGS = null;\n const DEFAULT_ALLOWED_TAGS = addToSet({}, [...html$1, ...svg$1, ...svgFilters, ...mathMl$1, ...text]);\n /* Allowed attribute names */\n let ALLOWED_ATTR = null;\n const DEFAULT_ALLOWED_ATTR = addToSet({}, [...html, ...svg, ...mathMl, ...xml]);\n /*\n * Configure how DOMPurify should handle custom elements and their attributes as well as customized built-in elements.\n * @property {RegExp|Function|null} tagNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any custom elements)\n * @property {RegExp|Function|null} attributeNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any attributes not on the allow list)\n * @property {boolean} allowCustomizedBuiltInElements allow custom elements derived from built-ins if they pass CUSTOM_ELEMENT_HANDLING.tagNameCheck. Default: `false`.\n */\n let CUSTOM_ELEMENT_HANDLING = Object.seal(create(null, {\n tagNameCheck: {\n writable: true,\n configurable: false,\n enumerable: true,\n value: null\n },\n attributeNameCheck: {\n writable: true,\n configurable: false,\n enumerable: true,\n value: null\n },\n allowCustomizedBuiltInElements: {\n writable: true,\n configurable: false,\n enumerable: true,\n value: false\n }\n }));\n /* Explicitly forbidden tags (overrides ALLOWED_TAGS/ADD_TAGS) */\n let FORBID_TAGS = null;\n /* Explicitly forbidden attributes (overrides ALLOWED_ATTR/ADD_ATTR) */\n let FORBID_ATTR = null;\n /* Config object to store ADD_TAGS/ADD_ATTR functions (when used as functions) */\n const EXTRA_ELEMENT_HANDLING = Object.seal(create(null, {\n tagCheck: {\n writable: true,\n configurable: false,\n enumerable: true,\n value: null\n },\n attributeCheck: {\n writable: true,\n configurable: false,\n enumerable: true,\n value: null\n }\n }));\n /* Decide if ARIA attributes are okay */\n let ALLOW_ARIA_ATTR = true;\n /* Decide if custom data attributes are okay */\n let ALLOW_DATA_ATTR = true;\n /* Decide if unknown protocols are okay */\n let ALLOW_UNKNOWN_PROTOCOLS = false;\n /* Decide if self-closing tags in attributes are allowed.\n * Usually removed due to a mXSS issue in jQuery 3.0 */\n let ALLOW_SELF_CLOSE_IN_ATTR = true;\n /* Output should be safe for common template engines.\n * This means, DOMPurify removes data attributes, mustaches and ERB\n */\n let SAFE_FOR_TEMPLATES = false;\n /* Output should be safe even for XML used within HTML and alike.\n * This means, DOMPurify removes comments when containing risky content.\n */\n let SAFE_FOR_XML = true;\n /* Decide if document with <html>... should be returned */\n let WHOLE_DOCUMENT = false;\n /* Track whether config is already set on this instance of DOMPurify. */\n let SET_CONFIG = false;\n /* Pristine allowlist bindings captured at setConfig() time. On the\n * persistent-config path sanitize() restores the sets from these before\n * the per-walk hook clone-guard, so a hook's in-call widening cannot\n * carry across calls. Null until setConfig() is called; reset by\n * clearConfig(). */\n let SET_CONFIG_ALLOWED_TAGS = null;\n let SET_CONFIG_ALLOWED_ATTR = null;\n /* Decide if all elements (e.g. style, script) must be children of\n * document.body. By default, browsers might move them to document.head */\n let FORCE_BODY = false;\n /* Decide if a DOM `HTMLBodyElement` should be returned, instead of a html\n * string (or a TrustedHTML object if Trusted Types are supported).\n * If `WHOLE_DOCUMENT` is enabled a `HTMLHtmlElement` will be returned instead\n */\n let RETURN_DOM = false;\n /* Decide if a DOM `DocumentFragment` should be returned, instead of a html\n * string (or a TrustedHTML object if Trusted Types are supported) */\n let RETURN_DOM_FRAGMENT = false;\n /* Try to return a Trusted Type object instead of a string, return a string in\n * case Trusted Types are not supported */\n let RETURN_TRUSTED_TYPE = false;\n /* Output should be free from DOM clobbering attacks?\n * This sanitizes markups named with colliding, clobberable built-in DOM APIs.\n */\n let SANITIZE_DOM = true;\n /* Achieve full DOM Clobbering protection by isolating the namespace of named\n * properties and JS variables, mitigating attacks that abuse the HTML/DOM spec rules.\n *\n * HTML/DOM spec rules that enable DOM Clobbering:\n * - Named Access on Window (§7.3.3)\n * - DOM Tree Accessors (§3.1.5)\n * - Form Element Parent-Child Relations (§4.10.3)\n * - Iframe srcdoc / Nested WindowProxies (§4.8.5)\n * - HTMLCollection (§4.2.10.2)\n *\n * Namespace isolation is implemented by prefixing `id` and `name` attributes\n * with a constant string, i.e., `user-content-`\n */\n let SANITIZE_NAMED_PROPS = false;\n const SANITIZE_NAMED_PROPS_PREFIX = 'user-content-';\n /* Keep element content when removing element? */\n let KEEP_CONTENT = true;\n /* If a `Node` is passed to sanitize(), then performs sanitization in-place instead\n * of importing it into a new Document and returning a sanitized copy */\n let IN_PLACE = false;\n /* Allow usage of profiles like html, svg and mathMl */\n let USE_PROFILES = {};\n /* Tags to ignore content of when KEEP_CONTENT is true */\n let FORBID_CONTENTS = null;\n const DEFAULT_FORBID_CONTENTS = addToSet({}, ['annotation-xml', 'audio', 'colgroup', 'desc', 'foreignobject', 'head', 'iframe', 'math', 'mi', 'mn', 'mo', 'ms', 'mtext', 'noembed', 'noframes', 'noscript', 'plaintext', 'script',\n // <selectedcontent> mirrors the selected <option>'s subtree, cloned by\n // the UA (customizable <select>) — including any on* handlers — and the\n // engine re-mirrors synchronously whenever a removal changes which\n // option/selectedcontent is current, even inside DOMPurify's inert\n // DOMParser document. Hoisting its children on removal re-inserts a fresh\n // mirror target ahead of the walk, which the engine refills, looping\n // forever (DoS) and amplifying output. Dropping its content on removal\n // (rather than hoisting) breaks that cascade; the content is a duplicate\n // of the option, which is sanitized on its own. See campaign-3 F1/F6.\n 'selectedcontent', 'style', 'svg', 'template', 'thead', 'title', 'video', 'xmp']);\n /* Tags that are safe for data: URIs */\n let DATA_URI_TAGS = null;\n const DEFAULT_DATA_URI_TAGS = addToSet({}, ['audio', 'video', 'img', 'source', 'image', 'track']);\n /* Attributes safe for values like \"javascript:\" */\n let URI_SAFE_ATTRIBUTES = null;\n const DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, ['alt', 'class', 'for', 'id', 'label', 'name', 'pattern', 'placeholder', 'role', 'summary', 'title', 'value', 'style', 'xmlns']);\n const MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';\n const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';\n const HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';\n /* Document namespace */\n let NAMESPACE = HTML_NAMESPACE;\n let IS_EMPTY_INPUT = false;\n /* Allowed XHTML+XML namespaces */\n let ALLOWED_NAMESPACES = null;\n const DEFAULT_ALLOWED_NAMESPACES = addToSet({}, [MATHML_NAMESPACE, SVG_NAMESPACE, HTML_NAMESPACE], stringToString);\n const DEFAULT_MATHML_TEXT_INTEGRATION_POINTS = freeze(['mi', 'mo', 'mn', 'ms', 'mtext']);\n let MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, DEFAULT_MATHML_TEXT_INTEGRATION_POINTS);\n const DEFAULT_HTML_INTEGRATION_POINTS = freeze(['annotation-xml']);\n let HTML_INTEGRATION_POINTS = addToSet({}, DEFAULT_HTML_INTEGRATION_POINTS);\n // Certain elements are allowed in both SVG and HTML\n // namespace. We need to specify them explicitly\n // so that they don't get erroneously deleted from\n // HTML namespace.\n const COMMON_SVG_AND_HTML_ELEMENTS = addToSet({}, ['title', 'style', 'font', 'a', 'script']);\n /* Parsing of strict XHTML documents */\n let PARSER_MEDIA_TYPE = null;\n const SUPPORTED_PARSER_MEDIA_TYPES = ['application/xhtml+xml', 'text/html'];\n const DEFAULT_PARSER_MEDIA_TYPE = 'text/html';\n let transformCaseFunc = null;\n /* Keep a reference to config to pass to hooks */\n let CONFIG = null;\n /* Ideally, do not touch anything below this line */\n /* ______________________________________________ */\n const formElement = document.createElement('form');\n const isRegexOrFunction = function isRegexOrFunction(testValue) {\n return testValue instanceof RegExp || testValue instanceof Function;\n };\n /**\n * _parseConfig\n *\n * @param cfg optional config literal\n */\n // eslint-disable-next-line complexity\n const _parseConfig = function _parseConfig() {\n let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n if (CONFIG && CONFIG === cfg) {\n return;\n }\n /* Shield configuration object from tampering */\n if (!cfg || typeof cfg !== 'object') {\n cfg = {};\n }\n /* Shield configuration object from prototype pollution */\n cfg = clone(cfg);\n PARSER_MEDIA_TYPE =\n // eslint-disable-next-line unicorn/prefer-includes\n SUPPORTED_PARSER_MEDIA_TYPES.indexOf(cfg.PARSER_MEDIA_TYPE) === -1 ? DEFAULT_PARSER_MEDIA_TYPE : cfg.PARSER_MEDIA_TYPE;\n // HTML tags and attributes are not case-sensitive, converting to lowercase. Keeping XHTML as is.\n transformCaseFunc = PARSER_MEDIA_TYPE === 'application/xhtml+xml' ? stringToString : stringToLowerCase;\n /* Set configuration parameters */\n ALLOWED_TAGS = _resolveSetOption(cfg, 'ALLOWED_TAGS', DEFAULT_ALLOWED_TAGS, {\n transform: transformCaseFunc\n });\n ALLOWED_ATTR = _resolveSetOption(cfg, 'ALLOWED_ATTR', DEFAULT_ALLOWED_ATTR, {\n transform: transformCaseFunc\n });\n ALLOWED_NAMESPACES = _resolveSetOption(cfg, 'ALLOWED_NAMESPACES', DEFAULT_ALLOWED_NAMESPACES, {\n transform: stringToString\n });\n URI_SAFE_ATTRIBUTES = _resolveSetOption(cfg, 'ADD_URI_SAFE_ATTR', DEFAULT_URI_SAFE_ATTRIBUTES, {\n transform: transformCaseFunc,\n base: DEFAULT_URI_SAFE_ATTRIBUTES\n });\n DATA_URI_TAGS = _resolveSetOption(cfg, 'ADD_DATA_URI_TAGS', DEFAULT_DATA_URI_TAGS, {\n transform: transformCaseFunc,\n base: DEFAULT_DATA_URI_TAGS\n });\n FORBID_CONTENTS = _resolveSetOption(cfg, 'FORBID_CONTENTS', DEFAULT_FORBID_CONTENTS, {\n transform: transformCaseFunc\n });\n FORBID_TAGS = _resolveSetOption(cfg, 'FORBID_TAGS', clone({}), {\n transform: transformCaseFunc\n });\n FORBID_ATTR = _resolveSetOption(cfg, 'FORBID_ATTR', clone({}), {\n transform: transformCaseFunc\n });\n USE_PROFILES = objectHasOwnProperty(cfg, 'USE_PROFILES') ? cfg.USE_PROFILES && typeof cfg.USE_PROFILES === 'object' ? clone(cfg.USE_PROFILES) : cfg.USE_PROFILES : false;\n ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true\n ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true\n ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; // Default false\n ALLOW_SELF_CLOSE_IN_ATTR = cfg.ALLOW_SELF_CLOSE_IN_ATTR !== false; // Default true\n SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false; // Default false\n SAFE_FOR_XML = cfg.SAFE_FOR_XML !== false; // Default true\n WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false; // Default false\n RETURN_DOM = cfg.RETURN_DOM || false; // Default false\n RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false; // Default false\n RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false; // Default false\n FORCE_BODY = cfg.FORCE_BODY || false; // Default false\n SANITIZE_DOM = cfg.SANITIZE_DOM !== false; // Default true\n SANITIZE_NAMED_PROPS = cfg.SANITIZE_NAMED_PROPS || false; // Default false\n KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true\n IN_PLACE = cfg.IN_PLACE || false; // Default false\n IS_ALLOWED_URI$1 = isRegex(cfg.ALLOWED_URI_REGEXP) ? cfg.ALLOWED_URI_REGEXP : IS_ALLOWED_URI; // Default regexp\n NAMESPACE = typeof cfg.NAMESPACE === 'string' ? cfg.NAMESPACE : HTML_NAMESPACE; // Default HTML namespace\n MATHML_TEXT_INTEGRATION_POINTS = objectHasOwnProperty(cfg, 'MATHML_TEXT_INTEGRATION_POINTS') && cfg.MATHML_TEXT_INTEGRATION_POINTS && typeof cfg.MATHML_TEXT_INTEGRATION_POINTS === 'object' ? clone(cfg.MATHML_TEXT_INTEGRATION_POINTS) : addToSet({}, DEFAULT_MATHML_TEXT_INTEGRATION_POINTS); // Default built-in map\n HTML_INTEGRATION_POINTS = objectHasOwnProperty(cfg, 'HTML_INTEGRATION_POINTS') && cfg.HTML_INTEGRATION_POINTS && typeof cfg.HTML_INTEGRATION_POINTS === 'object' ? clone(cfg.HTML_INTEGRATION_POINTS) : addToSet({}, DEFAULT_HTML_INTEGRATION_POINTS); // Default built-in map\n const customElementHandling = objectHasOwnProperty(cfg, 'CUSTOM_ELEMENT_HANDLING') && cfg.CUSTOM_ELEMENT_HANDLING && typeof cfg.CUSTOM_ELEMENT_HANDLING === 'object' ? clone(cfg.CUSTOM_ELEMENT_HANDLING) : create(null);\n CUSTOM_ELEMENT_HANDLING = create(null);\n if (objectHasOwnProperty(customElementHandling, 'tagNameCheck') && isRegexOrFunction(customElementHandling.tagNameCheck)) {\n CUSTOM_ELEMENT_HANDLING.tagNameCheck = customElementHandling.tagNameCheck; // Default undefined\n }\n if (objectHasOwnProperty(customElementHandling, 'attributeNameCheck') && isRegexOrFunction(customElementHandling.attributeNameCheck)) {\n CUSTOM_ELEMENT_HANDLING.attributeNameCheck = customElementHandling.attributeNameCheck; // Default undefined\n }\n if (objectHasOwnProperty(customElementHandling, 'allowCustomizedBuiltInElements') && typeof customElementHandling.allowCustomizedBuiltInElements === 'boolean') {\n CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = customElementHandling.allowCustomizedBuiltInElements; // Default undefined\n }\n seal(CUSTOM_ELEMENT_HANDLING);\n if (SAFE_FOR_TEMPLATES) {\n ALLOW_DATA_ATTR = false;\n }\n if (RETURN_DOM_FRAGMENT) {\n RETURN_DOM = true;\n }\n /* Parse profile info */\n if (USE_PROFILES) {\n ALLOWED_TAGS = addToSet({}, text);\n ALLOWED_ATTR = create(null);\n if (USE_PROFILES.html === true) {\n addToSet(ALLOWED_TAGS, html$1);\n addToSet(ALLOWED_ATTR, html);\n }\n if (USE_PROFILES.svg === true) {\n addToSet(ALLOWED_TAGS, svg$1);\n addToSet(ALLOWED_ATTR, svg);\n addToSet(ALLOWED_ATTR, xml);\n }\n if (USE_PROFILES.svgFilters === true) {\n addToSet(ALLOWED_TAGS, svgFilters);\n addToSet(ALLOWED_ATTR, svg);\n addToSet(ALLOWED_ATTR, xml);\n }\n if (USE_PROFILES.mathMl === true) {\n addToSet(ALLOWED_TAGS, mathMl$1);\n addToSet(ALLOWED_ATTR, mathMl);\n addToSet(ALLOWED_ATTR, xml);\n }\n }\n /* Always reset function-based ADD_TAGS / ADD_ATTR checks to prevent\n * leaking across calls when switching from function to array config */\n EXTRA_ELEMENT_HANDLING.tagCheck = null;\n EXTRA_ELEMENT_HANDLING.attributeCheck = null;\n /* Merge configuration parameters */\n if (objectHasOwnProperty(cfg, 'ADD_TAGS')) {\n if (typeof cfg.ADD_TAGS === 'function') {\n EXTRA_ELEMENT_HANDLING.tagCheck = cfg.ADD_TAGS;\n } else if (arrayIsArray(cfg.ADD_TAGS)) {\n if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) {\n ALLOWED_TAGS = clone(ALLOWED_TAGS);\n }\n addToSet(ALLOWED_TAGS, cfg.ADD_TAGS, transformCaseFunc);\n }\n }\n if (objectHasOwnProperty(cfg, 'ADD_ATTR')) {\n if (typeof cfg.ADD_ATTR === 'function') {\n EXTRA_ELEMENT_HANDLING.attributeCheck = cfg.ADD_ATTR;\n } else if (arrayIsArray(cfg.ADD_ATTR)) {\n if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) {\n ALLOWED_ATTR = clone(ALLOWED_ATTR);\n }\n addToSet(ALLOWED_ATTR, cfg.ADD_ATTR, transformCaseFunc);\n }\n }\n if (objectHasOwnProperty(cfg, 'ADD_URI_SAFE_ATTR') && arrayIsArray(cfg.ADD_URI_SAFE_ATTR)) {\n addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR, transformCaseFunc);\n }\n if (objectHasOwnProperty(cfg, 'FORBID_CONTENTS') && arrayIsArray(cfg.FORBID_CONTENTS)) {\n if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {\n FORBID_CONTENTS = clone(FORBID_CONTENTS);\n }\n addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS, transformCaseFunc);\n }\n if (objectHasOwnProperty(cfg, 'ADD_FORBID_CONTENTS') && arrayIsArray(cfg.ADD_FORBID_CONTENTS)) {\n if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {\n FORBID_CONTENTS = clone(FORBID_CONTENTS);\n }\n addToSet(FORBID_CONTENTS, cfg.ADD_FORBID_CONTENTS, transformCaseFunc);\n }\n /* Add #text in case KEEP_CONTENT is set to true */\n if (KEEP_CONTENT) {\n ALLOWED_TAGS['#text'] = true;\n }\n /* Add html, head and body to ALLOWED_TAGS in case WHOLE_DOCUMENT is true */\n if (WHOLE_DOCUMENT) {\n addToSet(ALLOWED_TAGS, ['html', 'head', 'body']);\n }\n /* Add tbody to ALLOWED_TAGS in case tables are permitted, see #286, #365 */\n if (ALLOWED_TAGS.table) {\n addToSet(ALLOWED_TAGS, ['tbody']);\n delete FORBID_TAGS.tbody;\n }\n // Re-derive the active Trusted Types policy from this configuration on\n // every parse. The active policy must never be sticky closure state that\n // outlives the config that set it: a caller-supplied policy left in place\n // after `clearConfig()` — or after a later call that supplied none, or\n // `TRUSTED_TYPES_POLICY: null` — could sign a subsequent \"default\"\n // `RETURN_TRUSTED_TYPE` result with a foreign, possibly unsafe policy.\n // See GHSA-vxr8-fq34-vvx9.\n if (cfg.TRUSTED_TYPES_POLICY) {\n if (typeof cfg.TRUSTED_TYPES_POLICY.createHTML !== 'function') {\n throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a \"createHTML\" hook.');\n }\n if (typeof cfg.TRUSTED_TYPES_POLICY.createScriptURL !== 'function') {\n throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a \"createScriptURL\" hook.');\n }\n // A caller-supplied policy applies to this configuration only.\n const previousTrustedTypesPolicy = trustedTypesPolicy;\n trustedTypesPolicy = cfg.TRUSTED_TYPES_POLICY;\n // Sign local variables required by `sanitize`. If the supplied policy's\n // `createHTML` is circular (i.e. it calls `DOMPurify.sanitize`), this\n // throws via the re-entrancy guard. Restore the previous policy first so\n // the instance is not left in a poisoned state. See #1422.\n try {\n emptyHTML = _createTrustedHTML('');\n } catch (error) {\n trustedTypesPolicy = previousTrustedTypesPolicy;\n throw error;\n }\n } else if (cfg.TRUSTED_TYPES_POLICY === null) {\n // Explicit opt-out for this call: perform no Trusted Types signing and\n // create nothing (so a strict `trusted-types` CSP that disallows a\n // `dompurify` policy can still call `sanitize` from inside its own\n // policy — see #1422). Resetting to `undefined` rather than a sticky\n // `null` also drops any previously retained caller policy, so it cannot\n // resurface on a later call, while still allowing the next config-less\n // call to restore the internal default policy. See GHSA-vxr8-fq34-vvx9.\n trustedTypesPolicy = undefined;\n emptyHTML = '';\n } else {\n // No policy supplied: keep the currently active policy if one is set — a\n // previously supplied policy is intentionally sticky across config-less\n // calls — otherwise fall back to the instance's own internal policy,\n // created at most once. (A policy supplied for a *single* call still\n // lingers by design; what must not linger is a policy whose configuration\n // has been torn down via `clearConfig()`, which restores the default.)\n if (trustedTypesPolicy === undefined) {\n trustedTypesPolicy = _getDefaultTrustedTypesPolicy();\n }\n // Sign internal variables only when a policy is active. A falsy policy\n // (Trusted Types unsupported, creation failed, or an explicit opt-out)\n // leaves `emptyHTML` as a plain string, so we never call `.createHTML` on\n // a non-policy and throw. See #1422.\n if (trustedTypesPolicy && typeof emptyHTML === 'string') {\n emptyHTML = _createTrustedHTML('');\n }\n }\n // Prevent further manipulation of configuration.\n // Not available in IE8, Safari 5, etc.\n if (freeze) {\n freeze(cfg);\n }\n CONFIG = cfg;\n };\n /* Keep track of all possible SVG and MathML tags\n * so that we can perform the namespace checks\n * correctly. */\n const ALL_SVG_TAGS = addToSet({}, [...svg$1, ...svgFilters, ...svgDisallowed]);\n const ALL_MATHML_TAGS = addToSet({}, [...mathMl$1, ...mathMlDisallowed]);\n /**\n * Namespace rules for an element in the SVG namespace.\n *\n * @param tagName the element's lowercase tag name\n * @param parent the (possibly simulated) parent node\n * @param parentTagName the parent's lowercase tag name\n * @returns true if a spec-compliant parser could produce this element\n */\n const _checkSvgNamespace = function _checkSvgNamespace(tagName, parent, parentTagName) {\n // The only way to switch from HTML namespace to SVG\n // is via <svg>. If it happens via any other tag, then\n // it should be killed.\n if (parent.namespaceURI === HTML_NAMESPACE) {\n return tagName === 'svg';\n }\n // The only way to switch from MathML to SVG is via <svg>\n // if the parent is either <annotation-xml> or a MathML\n // text integration point.\n if (parent.namespaceURI === MATHML_NAMESPACE) {\n return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);\n }\n // We only allow elements that are defined in SVG\n // spec. All others are disallowed in SVG namespace.\n return Boolean(ALL_SVG_TAGS[tagName]);\n };\n /**\n * Namespace rules for an element in the MathML namespace.\n *\n * @param tagName the element's lowercase tag name\n * @param parent the (possibly simulated) parent node\n * @param parentTagName the parent's lowercase tag name\n * @returns true if a spec-compliant parser could produce this element\n */\n const _checkMathMlNamespace = function _checkMathMlNamespace(tagName, parent, parentTagName) {\n // The only way to switch from HTML namespace to MathML\n // is via <math>. If it happens via any other tag, then\n // it should be killed.\n if (parent.namespaceURI === HTML_NAMESPACE) {\n return tagName === 'math';\n }\n // The only way to switch from SVG to MathML is via\n // <math> and HTML integration points\n if (parent.namespaceURI === SVG_NAMESPACE) {\n return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName];\n }\n // We only allow elements that are defined in MathML\n // spec. All others are disallowed in MathML namespace.\n return Boolean(ALL_MATHML_TAGS[tagName]);\n };\n /**\n * Namespace rules for an element in the HTML namespace.\n *\n * @param tagName the element's lowercase tag name\n * @param parent the (possibly simulated) parent node\n * @param parentTagName the parent's lowercase tag name\n * @returns true if a spec-compliant parser could produce this element\n */\n const _checkHtmlNamespace = function _checkHtmlNamespace(tagName, parent, parentTagName) {\n // The only way to switch from SVG to HTML is via\n // HTML integration points, and from MathML to HTML\n // is via MathML text integration points\n if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) {\n return false;\n }\n if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {\n return false;\n }\n // We disallow tags that are specific for MathML\n // or SVG and should never appear in HTML namespace\n return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]);\n };\n /**\n * @param element a DOM element whose namespace is being checked\n * @returns Return false if the element has a\n * namespace that a spec-compliant parser would never\n * return. Return true otherwise.\n */\n const _checkValidNamespace = function _checkValidNamespace(element) {\n let parent = getParentNode(element);\n // In JSDOM, if we're inside shadow DOM, then parentNode\n // can be null. We just simulate parent in this case.\n if (!parent || !parent.tagName) {\n parent = {\n namespaceURI: NAMESPACE,\n tagName: 'template'\n };\n }\n const tagName = stringToLowerCase(element.tagName);\n const parentTagName = stringToLowerCase(parent.tagName);\n if (!ALLOWED_NAMESPACES[element.namespaceURI]) {\n return false;\n }\n if (element.namespaceURI === SVG_NAMESPACE) {\n return _checkSvgNamespace(tagName, parent, parentTagName);\n }\n if (element.namespaceURI === MATHML_NAMESPACE) {\n return _checkMathMlNamespace(tagName, parent, parentTagName);\n }\n if (element.namespaceURI === HTML_NAMESPACE) {\n return _checkHtmlNamespace(tagName, parent, parentTagName);\n }\n // For XHTML and XML documents that support custom namespaces\n if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && ALLOWED_NAMESPACES[element.namespaceURI]) {\n return true;\n }\n // The code should never reach this place (this means\n // that the element somehow got namespace that is not\n // HTML, SVG, MathML or allowed via ALLOWED_NAMESPACES).\n // Return false just in case.\n return false;\n };\n /**\n * _forceRemove\n *\n * @param node a DOM node\n */\n const _forceRemove = function _forceRemove(node) {\n arrayPush(DOMPurify.removed, {\n element: node\n });\n try {\n // eslint-disable-next-line unicorn/prefer-dom-node-remove\n getParentNode(node).removeChild(node);\n } catch (_) {\n /* The normal detach failed — this is reached for a parentless node\n (getParentNode() is null, so .removeChild throws). Element.prototype\n .remove() is itself a spec no-op on a parentless node, so a recorded\n \"removal\" would otherwise hand the caller back an intact,\n payload-bearing node (e.g. a detached IN_PLACE root the mXSS canary or\n the style-with-element-child rule decided to kill). Fail closed by\n throwing — exactly as a clobbered root does at the IN_PLACE entry —\n rather than trying to \"neutralize\" the node via its own methods.\n Neutralizing would mean calling getAttributeNames()/removeAttribute()\n on the node, both of which a <form> root can clobber via a named child\n (and _isClobbered does not even probe getAttributeNames), so the\n neutralize step could itself be silently defeated, leaving the payload\n intact. A throw touches only the cached, clobber-safe remove() and\n getParentNode(). Generalizes GHSA-r47g-fvhr-h676 (clobbered-form root)\n to every root-kill reason. REPORT-3.\n This lives inside the catch, so it never fires for a normally-removed\n in-tree node: those have a parent, removeChild() succeeds, and the\n catch is not entered. Only a kept (parentless) root reaches here. */\n remove(node);\n if (!getParentNode(node)) {\n throw typeErrorCreate('a node selected for removal could not be detached from its tree ' + 'and cannot be safely returned; refusing to sanitize in place');\n }\n }\n };\n /**\n * _neutralizeRoot\n *\n * Fail-closed teardown of an in-place root after the sanitize walk aborts\n * (campaign-3 F2). An internal throw mid-walk — e.g. a page-registered\n * custom element's reaction detaches a node so `_forceRemove`'s deliberate\n * parentless guard throws, or any other re-entrant engine mutation — would\n * otherwise leave the caller's *live* tree half-sanitized, with everything\n * after the abort point still carrying its handlers. There is no safe way\n * to resume the walk (the tree mutated under us), so we strip the root bare:\n * remove every child and every attribute, then let the caller's catch see\n * the original error. Clobber-safe (cached `remove`/`childNodes`/`attributes`\n * getters; the root was already clobber-pre-flighted at the IN_PLACE entry).\n *\n * @param root the in-place root to empty\n */\n const _neutralizeRoot = function _neutralizeRoot(root) {\n /* Strip every disallowed attribute (on* handlers included) off the whole\n subtree BEFORE detaching anything. Detaching first would hand back\n handler-bearing originals (e.g. an already-loading `<img onerror>`)\n whose queued resource event still fires in page scope after we throw.\n Clobber-safe reads; a doomed clobbered node's own attributes are\n irrelevant while its non-clobbered descendants are reached and scrubbed. */\n _neutralizeSubtree(root);\n const childNodes = getChildNodes(root);\n if (childNodes) {\n const snapshot = [];\n arrayForEach(childNodes, child => {\n arrayPush(snapshot, child);\n });\n arrayForEach(snapshot, child => {\n try {\n remove(child);\n } catch (_) {\n /* Best-effort teardown; a still-attached child is handled below */\n }\n });\n }\n const attributes = getAttributes(root);\n if (attributes) {\n for (let i = attributes.length - 1; i >= 0; --i) {\n const attribute = attributes[i];\n const name = attribute && attribute.name;\n if (typeof name === 'string') {\n try {\n root.removeAttribute(name);\n } catch (_) {\n /* Clobbered removeAttribute — ignore (fail-closed best effort) */\n }\n }\n }\n }\n };\n /**\n * _removeAttribute\n *\n * @param name an Attribute name\n * @param element a DOM node\n */\n const _removeAttribute = function _removeAttribute(name, element) {\n try {\n arrayPush(DOMPurify.removed, {\n attribute: element.getAttributeNode(name),\n from: element\n });\n } catch (_) {\n arrayPush(DOMPurify.removed, {\n attribute: null,\n from: element\n });\n }\n element.removeAttribute(name);\n // We void attribute values for unremovable \"is\" attributes\n if (name === 'is') {\n if (RETURN_DOM || RETURN_DOM_FRAGMENT) {\n try {\n _forceRemove(element);\n } catch (_) {}\n } else {\n try {\n element.setAttribute(name, '');\n } catch (_) {}\n }\n }\n };\n /**\n * _stripDisallowedAttributes\n *\n * Removes every attribute the active configuration does not allow from a\n * single element, using the same allowlist as the main attribute pass (so\n * `on*` handlers go, but no `/^on/` blocklist is introduced). Used only to\n * neutralise nodes that are being discarded from an in-place tree.\n *\n * @param element the element to strip\n */\n const _stripDisallowedAttributes = function _stripDisallowedAttributes(element) {\n const attributes = getAttributes(element);\n if (!attributes) {\n return;\n }\n for (let i = attributes.length - 1; i >= 0; --i) {\n const attribute = attributes[i];\n const name = attribute && attribute.name;\n if (typeof name !== 'string' || ALLOWED_ATTR[transformCaseFunc(name)]) {\n continue;\n }\n try {\n element.removeAttribute(name);\n } catch (_) {\n /* Clobbered removeAttribute on a doomed node — ignore */\n }\n }\n };\n /**\n * _neutralizeSubtree\n *\n * Completes the audit-5 F1 fix across every removal path. The KEEP_CONTENT\n * move-hoist neutralises only disallowed-tag removals; clobber, mXSS-canary,\n * namespace, comment, processing-instruction and KEEP_CONTENT:false removals\n * all drop their subtree wholesale via `_forceRemove`. On the IN_PLACE path\n * those dropped nodes are detached from the caller's LIVE tree but a\n * handler-bearing original among them (an `<img onerror>`/`<video>` that was\n * loading) keeps its queued resource event, which fires in page scope after\n * sanitize returns. This walks a removed subtree and strips every attribute\n * the active configuration does not allow — so `on*` handlers are cancelled\n * through the SAME allowlist that governs kept nodes, not a separate `/^on/`\n * blocklist. Run synchronously before sanitize returns, i.e. before any\n * queued event can fire. Hook-free by design: these nodes leave the output,\n * so firing attribute hooks for them would be surprising. Clobber-safe reads;\n * a doomed clobbered node may shadow `removeAttribute` (its own attributes are\n * irrelevant — it is discarded — while its non-clobbered descendants, e.g.\n * the `<img>`, are reached and scrubbed).\n *\n * @param root the root of a removed subtree to neutralise\n */\n const _neutralizeSubtree = function _neutralizeSubtree(root) {\n const stack = [root];\n while (stack.length > 0) {\n const node = stack.pop();\n const nodeType = getNodeType ? getNodeType(node) : node.nodeType;\n if (nodeType === NODE_TYPE.element) {\n _stripDisallowedAttributes(node);\n }\n const childNodes = getChildNodes(node);\n if (childNodes) {\n for (let i = childNodes.length - 1; i >= 0; --i) {\n stack.push(childNodes[i]);\n }\n }\n }\n };\n /**\n * _neutralizePatchLinkage\n *\n * IN_PLACE entry pre-pass (declarative-partial-updates / streaming\n * hardening, https://github.com/WICG/declarative-partial-updates).\n *\n * The main walk strips patch linkage (`for`/`patchsrc`) and removes range\n * markers (PIs / markup comments) node-by-node, in document order, AS it\n * reaches each node. On a live in-place root that leaves a window: from the\n * moment the root is connected until the walk arrives at a given node, that\n * node's linkage is live. A patch applied on connection/stream can fire as\n * a microtask during the walk and inject or teleport an unsanitized DOM\n * range into a region the iterator has already passed and will not revisit,\n * so the post-return \"tree is sanitized\" contract is violated. Sweep the\n * whole tree once up front and sever every linkage before the walk begins,\n * closing that window.\n *\n * This CANNOT undo a patch that already fired before sanitize ran — that is\n * the irreducible \"do not IN_PLACE a live-connected attacker tree\" caveat —\n * but it closes everything from sanitize-start onward. Gated on SAFE_FOR_XML\n * to group with the rest of the declarative-partial-updates handling and\n * stay overridable, consistent with the codebase.\n *\n * Clobber-safe traversal (cached childNodes getter); per-node try/catch so a\n * clobbered root cannot defeat the sweep of its non-clobbered descendants.\n *\n * NOTE (pending real-Chrome confirmation, see test/declarative-patch-probe\n * .html Q1): this mirrors the existing policy of keeping `for` on\n * <label>/<output>. If the shipping feature can drive a patch through a\n * surviving `for`-on-label/output + `id` pair, this pre-pass and the\n * attribute check at _isBasicCustomElement's caller must additionally drop\n * that pair on the IN_PLACE path. Left as-is until the taxonomy is verified.\n *\n * @param root the in-place root to sweep\n */\n const _neutralizePatchLinkage = function _neutralizePatchLinkage(root) {\n if (!SAFE_FOR_XML) {\n return;\n }\n const stack = [root];\n while (stack.length > 0) {\n const node = stack.pop();\n const nodeType = getNodeType ? getNodeType(node) : node.nodeType;\n /* Remove range markers (the target side of a patch linkage): every\n processing instruction, and any markup-bearing comment. */\n if (nodeType === NODE_TYPE.processingInstruction || nodeType === NODE_TYPE.comment && regExpTest(COMMENT_MARKUP_PROBE, node.data)) {\n try {\n remove(node);\n } catch (_) {\n /* Best-effort */\n }\n continue;\n }\n /* Strip patch-source attributes (the source side) off elements. */\n if (nodeType === NODE_TYPE.element) {\n const element = node;\n const lcTag = transformCaseFunc(getNodeName ? getNodeName(node) : node.nodeName);\n try {\n if (element.hasAttribute && element.hasAttribute('patchsrc')) {\n element.removeAttribute('patchsrc');\n }\n if (element.hasAttribute && element.hasAttribute('for') && lcTag !== 'label' && lcTag !== 'output') {\n element.removeAttribute('for');\n }\n } catch (_) {\n /* Clobbered removeAttribute/hasAttribute on a doomed node — ignore */\n }\n }\n const childNodes = getChildNodes(node);\n if (childNodes) {\n for (let i = childNodes.length - 1; i >= 0; --i) {\n stack.push(childNodes[i]);\n }\n }\n }\n };\n /**\n * _initDocument\n *\n * @param dirty - a string of dirty markup\n * @return a DOM, filled with the dirty markup\n */\n const _initDocument = function _initDocument(dirty) {\n /* Create a HTML document */\n let doc = null;\n let leadingWhitespace = null;\n if (FORCE_BODY) {\n dirty = '<remove></remove>' + dirty;\n } else {\n /* If FORCE_BODY isn't used, leading whitespace needs to be preserved manually */\n const matches = stringMatch(dirty, /^[\\r\\n\\t ]+/);\n leadingWhitespace = matches && matches[0];\n }\n if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && NAMESPACE === HTML_NAMESPACE) {\n // Root of XHTML doc must contain xmlns declaration (see https://www.w3.org/TR/xhtml1/normative.html#strict)\n dirty = '<html xmlns=\"http://www.w3.org/1999/xhtml\"><head></head><body>' + dirty + '</body></html>';\n }\n const dirtyPayload = trustedTypesPolicy ? _createTrustedHTML(dirty) : dirty;\n /*\n * Use the DOMParser API by default, fallback later if needs be\n * DOMParser not work for svg when has multiple root element.\n */\n if (NAMESPACE === HTML_NAMESPACE) {\n try {\n doc = new DOMParser().parseFromString(dirtyPayload, PARSER_MEDIA_TYPE);\n } catch (_) {}\n }\n /* Use createHTMLDocument in case DOMParser is not available */\n if (!doc || !doc.documentElement) {\n doc = implementation.createDocument(NAMESPACE, 'template', null);\n try {\n doc.documentElement.innerHTML = IS_EMPTY_INPUT ? emptyHTML : dirtyPayload;\n } catch (_) {\n // Syntax error if dirtyPayload is invalid xml\n }\n }\n const body = doc.body || doc.documentElement;\n if (dirty && leadingWhitespace) {\n body.insertBefore(document.createTextNode(leadingWhitespace), body.childNodes[0] || null);\n }\n /* Work on whole document or just its body */\n if (NAMESPACE === HTML_NAMESPACE) {\n return getElementsByTagName.call(doc, WHOLE_DOCUMENT ? 'html' : 'body')[0];\n }\n return WHOLE_DOCUMENT ? doc.documentElement : body;\n };\n /**\n * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document.\n *\n * @param root The root element or node to start traversing on.\n * @return The created NodeIterator\n */\n const _createNodeIterator = function _createNodeIterator(root) {\n /* Read ownerDocument through the cached Node.prototype getter, never the\n direct property. HTMLFormElement has [LegacyOverrideBuiltIns], so a\n clobbering child (<input name=\"ownerDocument\"> or a form-associated\n external input) shadows the prototype getter and makes a direct read\n return that <input>. createNodeIterator.call(<input>, ...) then throws\n \"Illegal invocation\", and on the IN_PLACE path that throw lands before\n the walk's fail-closed barrier - leaving the caller's live tree, with\n any already-armed handler in it, un-neutralized. The cached getter\n returns the real Document regardless of the clobber. */\n const doc = getOwnerDocument ? getOwnerDocument(root) : root.ownerDocument;\n return createNodeIterator.call(doc || root, root,\n // eslint-disable-next-line no-bitwise\n NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT | NodeFilter.SHOW_PROCESSING_INSTRUCTION | NodeFilter.SHOW_CDATA_SECTION, null);\n };\n /**\n * Replace template expression syntax (mustache, ERB, template\n * literal) with a space; shared by all SAFE_FOR_TEMPLATES scrub\n * sites. Order matters: mustache, then ERB, then template literal.\n *\n * @param value the string to scrub\n * @returns the scrubbed string\n */\n const _stripTemplateExpressions = function _stripTemplateExpressions(value) {\n value = stringReplace(value, MUSTACHE_EXPR$1, ' ');\n value = stringReplace(value, ERB_EXPR$1, ' ');\n value = stringReplace(value, TMPLIT_EXPR$1, ' ');\n return value;\n };\n /**\n * Strip template-engine expressions ({{...}}, ${...}, <%...%>) from the\n * character data of an element subtree. Used as the final safety net for\n * SAFE_FOR_TEMPLATES on every DOM-returning code path so that expressions\n * which only form after text-node normalization (e.g. fragments split across\n * stripped elements) cannot survive into a template-evaluating framework.\n *\n * Walks text/comment/CDATA/processing-instruction nodes and mutates `.data`\n * in place rather than round-tripping through innerHTML. This preserves\n * descendant node references (important for IN_PLACE callers), avoids a\n * serialize/reparse cycle, and reads literal character data — which means\n * `<%...%>` in text content matches the ERB regex against its real bytes\n * instead of the HTML-entity-escaped form innerHTML would produce.\n *\n * Attribute values are not visited here; SAFE_FOR_TEMPLATES handling for\n * attributes is performed during the per-node `_sanitizeAttributes` pass.\n *\n * @param node The root element whose character data should be scrubbed.\n */\n const _scrubTemplateExpressions2 = function _scrubTemplateExpressions(node) {\n var _node$querySelectorAl;\n node.normalize();\n /* Clobber-safe ownerDocument read, same reasoning as _createNodeIterator:\n under SAFE_FOR_TEMPLATES this runs on the live IN_PLACE root, which may\n carry a form-named-getter override of ownerDocument. */\n const doc = getOwnerDocument ? getOwnerDocument(node) : node.ownerDocument;\n const walker = createNodeIterator.call(doc || node, node,\n // eslint-disable-next-line no-bitwise\n NodeFilter.SHOW_TEXT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_CDATA_SECTION | NodeFilter.SHOW_PROCESSING_INSTRUCTION, null);\n let currentNode = walker.nextNode();\n while (currentNode) {\n currentNode.data = _stripTemplateExpressions(currentNode.data);\n currentNode = walker.nextNode();\n }\n // NodeIterator does not descend into <template>.content per the DOM spec,\n // so we must explicitly recurse into each template's content fragment,\n // mirroring the approach used by _sanitizeShadowDOM.\n const templates = (_node$querySelectorAl = node.querySelectorAll) === null || _node$querySelectorAl === void 0 ? void 0 : _node$querySelectorAl.call(node, 'template');\n if (templates) {\n arrayForEach(templates, tmpl => {\n if (_isDocumentFragment(tmpl.content)) {\n _scrubTemplateExpressions2(tmpl.content);\n }\n });\n }\n };\n /**\n * _isClobbered\n *\n * Detect DOM-clobbering on HTMLFormElement nodes. Form is the only HTML\n * interface with [LegacyOverrideBuiltIns]; a descendant element with a\n * `name` attribute matching a prototype property shadows that property\n * on direct reads. We use this check at the IN_PLACE entry-point and\n * during attribute sanitization to refuse clobbered forms.\n *\n * @param element element to check for clobbering attacks\n * @return true if clobbered, false if safe\n */\n const _isClobbered = function _isClobbered(element) {\n // Realm-independent tag-name probe. If we can't determine the tag\n // name at all, we can't reason about clobbering — return false\n // (the caller's other defences still apply).\n const realTagName = getNodeName ? getNodeName(element) : null;\n if (typeof realTagName !== 'string') {\n return false;\n }\n if (transformCaseFunc(realTagName) !== 'form') {\n return false;\n }\n return typeof element.nodeName !== 'string' || typeof element.textContent !== 'string' || typeof element.removeChild !== 'function' ||\n // Realm-safe NamedNodeMap detection: equality against the cached\n // prototype getter. Clobbered .attributes (e.g. <input name=\"attributes\">)\n // makes the direct read diverge from the cached read; a clean form\n // (same-realm OR foreign-realm) has both reads pointing at the same\n // canonical NamedNodeMap.\n element.attributes !== getAttributes(element) || typeof element.removeAttribute !== 'function' || typeof element.setAttribute !== 'function' || typeof element.namespaceURI !== 'string' || typeof element.insertBefore !== 'function' || typeof element.hasChildNodes !== 'function' ||\n // NodeType clobbering probe. Cached Node.prototype.nodeType getter\n // returns the integer 1 for any Element regardless of realm; direct\n // read on a clobbered form (e.g. <input name=\"nodeType\">) returns\n // the named child element. Cheap addition — nodeType is read from\n // an internal slot, no serialization cost — and removes a residual\n // clobbering surface used by several mXSS / PI / comment branches\n // in _sanitizeElements that compare currentNode.nodeType directly.\n element.nodeType !== getNodeType(element) ||\n // HTMLFormElement has [LegacyOverrideBuiltIns]: a descendant named\n // \"childNodes\" shadows the prototype getter. Direct reads of\n // form.childNodes from a clobbered form return the named child\n // instead of the real NodeList, so any walk that reads it directly\n // skips the form's real children. Compare the direct read to the\n // cached Node.prototype getter — when the form's named-property\n // getter intercepts the read, the two values differ and we flag\n // the form. This catches every clobbering child type (input,\n // select, etc.) regardless of whether the named child happens to\n // carry a numeric .length, which a typeof-based probe would miss\n // (e.g. HTMLSelectElement.length is a defined unsigned-long).\n element.childNodes !== getChildNodes(element);\n };\n /**\n * Checks whether the given value is a DocumentFragment from any realm.\n *\n * The realm-independent replacement reads `nodeType` through the cached\n * Node.prototype getter and compares to the DOCUMENT_FRAGMENT_NODE\n * constant (11). nodeType is a numeric value resolved from the node's\n * internal slot, identical across realms for the same kind of node.\n *\n * @param value object to check\n * @return true if value is a DocumentFragment-shaped node from any realm\n */\n const _isDocumentFragment = function _isDocumentFragment(value) {\n if (!getNodeType || typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return getNodeType(value) === NODE_TYPE.documentFragment;\n } catch (_) {\n return false;\n }\n };\n /**\n * Checks whether the given object is a DOM node, including nodes that\n * originate from a different window/realm (e.g. an iframe's\n * contentDocument). The previous `value instanceof Node` check was\n * realm-bound: nodes from a different window failed it, causing\n * sanitize() to silently stringify them and reset IN_PLACE to false,\n * returning the original node unsanitized. See GHSA-4w3q-35jp-p934.\n *\n * @param value object to check whether it's a DOM node\n * @return true if value is a DOM node from any realm\n */\n const _isNode = function _isNode(value) {\n if (!getNodeType || typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof getNodeType(value) === 'number';\n } catch (_) {\n return false;\n }\n };\n function _executeHooks(hooks, currentNode, data) {\n if (hooks.length === 0) {\n return;\n }\n arrayForEach(hooks, hook => {\n hook.call(DOMPurify, currentNode, data, CONFIG);\n });\n }\n /**\n * Structural-threat checks that condemn a node regardless of the\n * allowlists: mXSS via namespace confusion, risky CSS construction,\n * processing instructions, markup-bearing comments. Pure predicate;\n * the caller removes. Check order is load-bearing.\n *\n * @param currentNode the node to inspect\n * @param tagName the node's transformCaseFunc'd tag name\n * @return true if the node must be removed\n */\n const _isUnsafeNode = function _isUnsafeNode(currentNode, tagName) {\n /* Detect mXSS attempts abusing namespace confusion */\n if (SAFE_FOR_XML && currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && regExpTest(ELEMENT_MARKUP_PROBE, currentNode.textContent) && regExpTest(ELEMENT_MARKUP_PROBE, currentNode.innerHTML)) {\n return true;\n }\n /* Remove risky CSS construction leading to mXSS */\n if (SAFE_FOR_XML && currentNode.namespaceURI === HTML_NAMESPACE && tagName === 'style' && _isNode(currentNode.firstElementChild)) {\n return true;\n }\n /* Remove any occurrence of processing instructions */\n if (currentNode.nodeType === NODE_TYPE.processingInstruction) {\n return true;\n }\n /* Remove any kind of possibly harmful comments */\n if (SAFE_FOR_XML && currentNode.nodeType === NODE_TYPE.comment && regExpTest(COMMENT_MARKUP_PROBE, currentNode.data)) {\n return true;\n }\n return false;\n };\n /**\n * Handle a node whose tag is forbidden or not allowlisted: keep\n * allowed custom elements (false return exits _sanitizeElements\n * early - the namespace and fallback-tag removal checks are\n * intentionally skipped for kept custom elements), else hoist\n * content per KEEP_CONTENT and remove.\n *\n * A kept custom element is the ONLY case in which this function\n * returns false, so the caller uses that return value to run the\n * afterSanitizeElements hook on the kept element and keep the\n * element-hook lifecycle consistent with normal allowlisted\n * elements (GHSA-c2j3-45gr-mqc4).\n *\n * @param currentNode the disallowed node\n * @param tagName the node's transformCaseFunc'd tag name\n * @return true if the node was removed, false if kept\n */\n const _sanitizeDisallowedNode = function _sanitizeDisallowedNode(currentNode, tagName, root) {\n /* Check if we have a custom element to handle */\n if (!FORBID_TAGS[tagName] && _isBasicCustomElement(tagName)) {\n if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) {\n return false;\n }\n if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)) {\n return false;\n }\n }\n /* Keep content except for bad-listed elements.\n Use the cached prototype getters exclusively — the previous code\n had `|| currentNode.parentNode` / `|| currentNode.childNodes`\n fallbacks, but the cached getters always return the canonical\n value (or null for a real parent-less node), so the fallback\n path was dead in safe cases and a clobbering surface in unsafe\n ones. Falsy cached results stay falsy; the `if (childNodes &&\n parentNode)` check already gates correctly. */\n if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {\n const parentNode = getParentNode(currentNode);\n const childNodes = getChildNodes(currentNode);\n if (childNodes && parentNode) {\n const childCount = childNodes.length;\n /* Hoist by moving each child up one level rather than deep-cloning\n it. Moving transfers every descendant exactly once, so a chain of\n nested disallowed elements costs O(n) instead of the O(n^2) that\n re-cloning the shrinking subtree at each level produced; it also\n empties the removed original, so `DOMPurify.removed` no longer\n pins whole subtrees. Moving preserves the in-place guarantee too:\n an original carrying already-queued resource events (`<img\n onerror>`, `<video>`/`<audio>` error, lazy/`onload`, …) is\n relocated and sanitised rather than left detached but still armed.\n The sole case that must clone is removing the walk root itself.\n The result is serialised from the root's subtree, so a restrictive\n ALLOWED_TAGS that strips the root (`body` on the string path) must\n leave the content inside it, which only cloning does. In IN_PLACE\n the root is pre-validated as an allowed tag and so is never removed\n here, so that path always takes the move branch.\n `childNodes` is live; a tail-to-head walk keeps `childNodes[i]`\n valid whether we move (drops the trailing entry) or clone (leaves\n the list intact). */\n for (let i = childCount - 1; i >= 0; --i) {\n const hoisted = currentNode === root ? cloneNode(childNodes[i], true) : childNodes[i];\n parentNode.insertBefore(hoisted, getNextSibling(currentNode));\n }\n }\n }\n _forceRemove(currentNode);\n return true;\n };\n /**\n * Fork a hook-mutable allowlist off its shared binding the first time a\n * (possibly lazily-installed) uponSanitize* hook is about to see it, so the\n * hook cannot widen the per-instance default or the setConfig binding by\n * reference and leak past the call. Returns the set unchanged once it is\n * already call-local, so repeated calls across elements are idempotent.\n *\n * @param hookList the uponSanitize* hook array for this event\n * @param set the current ALLOWED_TAGS / ALLOWED_ATTR binding\n * @param defaultSet the per-instance DEFAULT_ALLOWED_* constant\n * @param setConfigSet the captured setConfig() binding, or null\n * @return a call-local clone if a hook is present and set is still shared,\n * else set unchanged\n */\n const _forkSharedAllowlist = function _forkSharedAllowlist(hookList, set, defaultSet, setConfigSet) {\n if (hookList.length === 0) {\n return set;\n }\n return set === defaultSet || set === setConfigSet ? clone(set) : set;\n };\n /**\n * _sanitizeElements\n *\n * @protect nodeName\n * @protect textContent\n * @protect removeChild\n * @param currentNode to check for permission to exist\n * @return true if node was killed, false if left alive\n */\n // eslint-disable-next-line complexity\n const _sanitizeElements = function _sanitizeElements(currentNode, root) {\n /* Execute a hook if present */\n _executeHooks(hooks.beforeSanitizeElements, currentNode, null);\n /* A hook may have detached the node - treat it as removed (see the\n detached-node comment after the uponSanitizeElement hook below). On\n the IN_PLACE path, neutralize the detached subtree first so a queued\n resource handler on it cannot fire in page scope after we return. */\n if (currentNode !== root && getParentNode(currentNode) === null) {\n if (IN_PLACE) {\n _neutralizeSubtree(currentNode);\n }\n return true;\n }\n /* Check if element is clobbered or can clobber */\n if (_isClobbered(currentNode)) {\n _forceRemove(currentNode);\n return true;\n }\n /* Now let's check the element's type and name */\n const tagName = transformCaseFunc(getNodeName ? getNodeName(currentNode) : currentNode.nodeName);\n /* Close the pre-walk clone-guard's timing gap: an uponSanitizeElement\n hook may have been installed after that guard sampled the hook arrays\n (e.g. lazily from beforeSanitizeElements), leaving ALLOWED_TAGS still\n aliasing a shared binding that a widening hook would mutate by\n reference. Fork it before exposing it to the hook. */\n ALLOWED_TAGS = _forkSharedAllowlist(hooks.uponSanitizeElement, ALLOWED_TAGS, DEFAULT_ALLOWED_TAGS, SET_CONFIG_ALLOWED_TAGS);\n /* Execute a hook if present */\n _executeHooks(hooks.uponSanitizeElement, currentNode, {\n tagName,\n allowedTags: ALLOWED_TAGS\n });\n /* A hook may have detached the node from the tree — a long-standing\n user pattern (issue #469; draw.io-style foreignObject filtering).\n Per the cached, unclobberable parentNode getter the node is\n genuinely out of the tree, so it can reach neither the serialized\n output nor an IN_PLACE live tree; treat it as removed and stop\n processing it. Without this guard, the unsafe-node / namespace\n checks below would call _forceRemove on a parentless node and hit\n the REPORT-3 fail-closed throw — which exists for nodes DOMPurify\n wants gone but *cannot* detach (clobbered / parentless roots), the\n opposite of a node that is already safely gone. The walk root is\n exempt: a detached IN_PLACE root is legitimate input and must still\n be fully sanitized, and a kill-decision on it must keep hitting the\n REPORT-3 throw. Nodes detached by hooks stay the hook's\n responsibility for placement: they are not recorded in\n DOMPurify.removed, so the post-walk IN_PLACE pass (which iterates\n DOMPurify.removed) does not reach them. But a hook-detached subtree\n can still hold a queued resource-event handler - e.g. an <img onload>\n that began loading when the caller built the live tree - which fires\n in page scope after sanitize returns even though the handler never\n reached the returned tree. That is the audit-5 F1 hazard, and the\n documented node.remove() hook pattern walks straight into it. So on\n the IN_PLACE path we neutralize the detached subtree inline here,\n stripping its non-allow-listed attributes before returning, exactly\n as the post-walk pass does for _forceRemove'd subtrees. */\n if (currentNode !== root && getParentNode(currentNode) === null) {\n if (IN_PLACE) {\n _neutralizeSubtree(currentNode);\n }\n return true;\n }\n /* Remove mXSS vectors, processing instructions and risky comments */\n if (_isUnsafeNode(currentNode, tagName)) {\n _forceRemove(currentNode);\n return true;\n }\n /* Remove element if anything forbids its presence */\n if (FORBID_TAGS[tagName] || !(EXTRA_ELEMENT_HANDLING.tagCheck instanceof Function && EXTRA_ELEMENT_HANDLING.tagCheck(tagName)) && !ALLOWED_TAGS[tagName]) {\n const removed = _sanitizeDisallowedNode(currentNode, tagName, root);\n /* A false return means the node is a custom element kept via\n CUSTOM_ELEMENT_HANDLING - the only keep path through\n _sanitizeDisallowedNode. Run afterSanitizeElements on it so the\n element-hook lifecycle matches normal allowlisted elements: a\n security policy applied in this hook (e.g. stripping an attribute\n from every surviving element) must not silently skip kept custom\n elements (GHSA-c2j3-45gr-mqc4). This mirrors the normal-element\n tail below - the hook runs, then the walker's subsequent\n _sanitizeAttributes pass sanitizes the element's attributes. The\n deliberately skipped namespace and fallback-tag removal checks stay\n skipped; they are removal decisions, not the hook contract. */\n if (removed === false) {\n _executeHooks(hooks.afterSanitizeElements, currentNode, null);\n }\n return removed;\n }\n /* Check whether element has a valid namespace.\n Realm-safe check (GHSA-hpcv-96wg-7vj8): use the cached Node.prototype\n nodeType getter rather than `instanceof Element`, which is realm-\n bound and short-circuits to false for any node minted in a different\n realm — letting a foreign-realm element with a forbidden namespace\n slip past the namespace check entirely. */\n const nt = getNodeType ? getNodeType(currentNode) : currentNode.nodeType;\n if (nt === NODE_TYPE.element && !_checkValidNamespace(currentNode)) {\n _forceRemove(currentNode);\n return true;\n }\n /* Make sure that older browsers don't get fallback-tag mXSS */\n if ((tagName === 'noscript' || tagName === 'noembed' || tagName === 'noframes') && regExpTest(FALLBACK_TAG_CLOSE, currentNode.innerHTML)) {\n _forceRemove(currentNode);\n return true;\n }\n /* Sanitize element content to be template-safe */\n if (SAFE_FOR_TEMPLATES && currentNode.nodeType === NODE_TYPE.text) {\n /* Get the element's text content */\n const content = _stripTemplateExpressions(currentNode.textContent);\n if (currentNode.textContent !== content) {\n arrayPush(DOMPurify.removed, {\n element: currentNode.cloneNode()\n });\n currentNode.textContent = content;\n }\n }\n /* Execute a hook if present */\n _executeHooks(hooks.afterSanitizeElements, currentNode, null);\n return false;\n };\n /**\n * _isValidAttribute\n *\n * @param lcTag Lowercase tag name of containing element.\n * @param lcName Lowercase attribute name.\n * @param value Attribute value.\n * @return Returns true if `value` is valid, otherwise false.\n */\n // eslint-disable-next-line complexity\n const _isValidAttribute = function _isValidAttribute(lcTag, lcName, value) {\n /* FORBID_ATTR must always win, even if ADD_ATTR predicate would allow it */\n if (FORBID_ATTR[lcName]) {\n return false;\n }\n /* Reject declarative-partial-updates patch-linkage attributes\n (https://github.com/WICG/declarative-partial-updates).\n Empirical note (Chrome 150, verified — see\n test/declarative-patch-probe-v3.html): expansion is NOT applied after\n sanitization. For the string path it fires during sanitize()'s own\n parse, so the walk sees and sanitizes the fully materialized expanded\n tree — teleports into MathML/SVG integration points included; a\n weaponized `<template for>`->`<img onerror>` comes back with the handler\n stripped. For the IN_PLACE path it fires on connection, before the walk.\n Either way DOMPurify is NOT blind to the patch.\n This removal is therefore defense-in-depth rather than the sole barrier:\n it prevents live linkage from surviving into the OUTPUT and re-expanding\n in the caller's context, and keeps behaviour deterministic if a future\n engine defers expansion. `for` is legitimate only on <label>/<output>;\n anywhere else (notably <template for>) it links the element to a patch\n target and teleports or removes an arbitrary DOM range by id/marker name.\n `patchsrc` fetches remote markup and is treated as a script-loading\n mechanism (CSP). Gated on SAFE_FOR_XML so the removal groups with the\n other structural-threat checks and stays overridable, consistent with\n the rest of the codebase. PI range markers are already removed by\n _isUnsafeNode. */\n if (SAFE_FOR_XML && lcName === 'patchsrc') {\n return false;\n }\n if (SAFE_FOR_XML && lcName === 'for' && lcTag !== 'label' && lcTag !== 'output') {\n return false;\n }\n /* Make sure attribute cannot clobber */\n if (SANITIZE_DOM && (lcName === 'id' || lcName === 'name') && (value in document || value in formElement)) {\n return false;\n }\n const nameIsPermitted = ALLOWED_ATTR[lcName] || EXTRA_ELEMENT_HANDLING.attributeCheck instanceof Function && EXTRA_ELEMENT_HANDLING.attributeCheck(lcName, lcTag);\n /* Allow valid data-* attributes: At least one character after \"-\"\n (https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes)\n XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804)\n We don't need to check the value; it's always URI safe. */\n if (ALLOW_DATA_ATTR && regExpTest(DATA_ATTR$1, lcName)) ; else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR$1, lcName)) ; else if (!nameIsPermitted) {\n if (\n // First condition does a very basic check if a) it's basically a valid custom element tagname AND\n // b) if the tagName passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck\n // and c) if the attribute name passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.attributeNameCheck\n _isBasicCustomElement(lcTag) && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, lcTag) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(lcTag)) && (CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.attributeNameCheck, lcName) || CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.attributeNameCheck(lcName, lcTag)) ||\n // Alternative, second condition checks if it's an `is`-attribute, AND\n // the value passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck\n lcName === 'is' && CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, value) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(value))) ; else {\n return false;\n }\n /* Check value is safe. First, is attr inert? If so, is safe */\n } else if (URI_SAFE_ATTRIBUTES[lcName]) ; else if (regExpTest(IS_ALLOWED_URI$1, stringReplace(value, ATTR_WHITESPACE$1, ''))) ; else if ((lcName === 'src' || lcName === 'xlink:href' || lcName === 'href') && lcTag !== 'script' && stringIndexOf(value, 'data:') === 0 && DATA_URI_TAGS[lcTag]) ; else if (ALLOW_UNKNOWN_PROTOCOLS && !regExpTest(IS_SCRIPT_OR_DATA$1, stringReplace(value, ATTR_WHITESPACE$1, ''))) ; else if (value) {\n return false;\n } else ;\n return true;\n };\n /* Names the HTML spec reserves from valid-custom-element-name; these must\n * never be treated as basic custom elements even when a permissive\n * CUSTOM_ELEMENT_HANDLING.tagNameCheck is configured. */\n const RESERVED_CUSTOM_ELEMENT_NAMES = addToSet({}, ['annotation-xml', 'color-profile', 'font-face', 'font-face-format', 'font-face-name', 'font-face-src', 'font-face-uri', 'missing-glyph']);\n /**\n * _isBasicCustomElement\n * checks if at least one dash is included in tagName, and it's not the first char\n * for more sophisticated checking see https://github.com/sindresorhus/validate-element-name\n *\n * @param tagName name of the tag of the node to sanitize\n * @returns Returns true if the tag name meets the basic criteria for a custom element, otherwise false.\n */\n const _isBasicCustomElement = function _isBasicCustomElement(tagName) {\n return !RESERVED_CUSTOM_ELEMENT_NAMES[stringToLowerCase(tagName)] && regExpTest(CUSTOM_ELEMENT$1, tagName);\n };\n /**\n * Wrap an attribute value in the matching Trusted Types object when\n * the active policy requires it. Namespaced attributes pass through\n * unchanged (no TT support yet, see\n * https://bugs.chromium.org/p/chromium/issues/detail?id=1305293).\n *\n * @param lcTag lowercase tag name of the containing element\n * @param lcName lowercase attribute name\n * @param namespaceURI the attribute's namespace, if any\n * @param value the attribute value to wrap\n * @return the value, wrapped when Trusted Types demand it\n */\n const _applyTrustedTypesToAttribute = function _applyTrustedTypesToAttribute(lcTag, lcName, namespaceURI, value) {\n if (trustedTypesPolicy && typeof trustedTypes === 'object' && typeof trustedTypes.getAttributeType === 'function' && !namespaceURI) {\n switch (trustedTypes.getAttributeType(lcTag, lcName)) {\n case 'TrustedHTML':\n {\n return _createTrustedHTML(value);\n }\n case 'TrustedScriptURL':\n {\n return _createTrustedScriptURL(value);\n }\n }\n }\n return value;\n };\n /**\n * Write a modified attribute value back onto the element. On\n * success, re-probe for clobbering introduced by the new value and\n * remove the element when found; otherwise pop the removal entry\n * recorded by the earlier _removeAttribute (long-standing pairing\n * with the SANITIZE_NAMED_PROPS path - do not \"fix\" casually). On\n * failure, remove the attribute instead.\n *\n * @param currentNode the element carrying the attribute\n * @param name the attribute name as present on the element\n * @param namespaceURI the attribute's namespace, if any\n * @param value the new attribute value\n */\n const _setAttributeValue = function _setAttributeValue(currentNode, name, namespaceURI, value) {\n try {\n if (namespaceURI) {\n currentNode.setAttributeNS(namespaceURI, name, value);\n } else {\n /* Fallback to setAttribute() for browser-unrecognized namespaces e.g. \"x-schema\". */\n currentNode.setAttribute(name, value);\n }\n if (_isClobbered(currentNode)) {\n _forceRemove(currentNode);\n } else {\n arrayPop(DOMPurify.removed);\n }\n } catch (_) {\n _removeAttribute(name, currentNode);\n }\n };\n /**\n * _sanitizeAttributes\n *\n * @protect attributes\n * @protect nodeName\n * @protect removeAttribute\n * @protect setAttribute\n *\n * @param currentNode to sanitize\n */\n const _sanitizeAttributes = function _sanitizeAttributes(currentNode) {\n /* Execute a hook if present */\n _executeHooks(hooks.beforeSanitizeAttributes, currentNode, null);\n const attributes = currentNode.attributes;\n /* Check if we have attributes; if not we might have a text node */\n if (!attributes || _isClobbered(currentNode)) {\n return;\n }\n /* Same lazy-install guard as uponSanitizeElement (see there): fork the\n attribute allowlist off its shared binding before a hook can see it. */\n ALLOWED_ATTR = _forkSharedAllowlist(hooks.uponSanitizeAttribute, ALLOWED_ATTR, DEFAULT_ALLOWED_ATTR, SET_CONFIG_ALLOWED_ATTR);\n const hookEvent = {\n attrName: '',\n attrValue: '',\n keepAttr: true,\n allowedAttributes: ALLOWED_ATTR,\n forceKeepAttr: undefined\n };\n let l = attributes.length;\n const lcTag = transformCaseFunc(currentNode.nodeName);\n /* Go backwards over all attributes; safely remove bad ones */\n while (l--) {\n const attr = attributes[l];\n const name = attr.name,\n namespaceURI = attr.namespaceURI,\n attrValue = attr.value;\n const lcName = transformCaseFunc(name);\n const initValue = attrValue;\n let value = name === 'value' ? initValue : stringTrim(initValue);\n /* Execute a hook if present */\n hookEvent.attrName = lcName;\n hookEvent.attrValue = value;\n hookEvent.keepAttr = true;\n hookEvent.forceKeepAttr = undefined; // Allows developers to see this is a property they can set\n _executeHooks(hooks.uponSanitizeAttribute, currentNode, hookEvent);\n value = hookEvent.attrValue;\n /* Full DOM Clobbering protection via namespace isolation,\n * Prefix id and name attributes with `user-content-`\n */\n if (SANITIZE_NAMED_PROPS && (lcName === 'id' || lcName === 'name') && stringIndexOf(value, SANITIZE_NAMED_PROPS_PREFIX) !== 0) {\n // Remove the attribute with this value\n _removeAttribute(name, currentNode);\n // Prefix the value and later re-create the attribute with the sanitized value\n value = SANITIZE_NAMED_PROPS_PREFIX + value;\n }\n // Else: already prefixed, leave the attribute alone — the prefix is\n // itself the clobbering protection, and re-applying it is incorrect.\n /* Work around a security issue with comments inside attributes */\n if (SAFE_FOR_XML && regExpTest(/((--!?|])>)|<\\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i, value)) {\n _removeAttribute(name, currentNode);\n continue;\n }\n /* Make sure we cannot easily use animated hrefs, even if animations are allowed */\n if (lcName === 'attributename' && stringMatch(value, 'href')) {\n _removeAttribute(name, currentNode);\n continue;\n }\n /* Did the hooks force-keep the attribute? */\n if (hookEvent.forceKeepAttr) {\n continue;\n }\n /* Did the hooks approve of the attribute? */\n if (!hookEvent.keepAttr) {\n _removeAttribute(name, currentNode);\n continue;\n }\n /* Work around a security issue in jQuery 3.0 */\n if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(SELF_CLOSING_TAG, value)) {\n _removeAttribute(name, currentNode);\n continue;\n }\n /* Sanitize attribute content to be template-safe */\n if (SAFE_FOR_TEMPLATES) {\n value = _stripTemplateExpressions(value);\n }\n /* Is `value` valid for this attribute? */\n if (!_isValidAttribute(lcTag, lcName, value)) {\n _removeAttribute(name, currentNode);\n continue;\n }\n /* Handle attributes that require Trusted Types */\n value = _applyTrustedTypesToAttribute(lcTag, lcName, namespaceURI, value);\n /* Handle invalid data-* attribute set by try-catching it */\n if (value !== initValue) {\n _setAttributeValue(currentNode, name, namespaceURI, value);\n }\n }\n /* Execute a hook if present */\n _executeHooks(hooks.afterSanitizeAttributes, currentNode, null);\n };\n /**\n * _sanitizeShadowDOM\n *\n * @param fragment to iterate over recursively\n */\n const _sanitizeShadowDOM2 = function _sanitizeShadowDOM(fragment) {\n let shadowNode = null;\n const shadowIterator = _createNodeIterator(fragment);\n /* Execute a hook if present */\n _executeHooks(hooks.beforeSanitizeShadowDOM, fragment, null);\n while (shadowNode = shadowIterator.nextNode()) {\n /* Execute a hook if present */\n _executeHooks(hooks.uponSanitizeShadowNode, shadowNode, null);\n /* Sanitize tags and elements */\n _sanitizeElements(shadowNode, fragment);\n /* Check attributes next */\n _sanitizeAttributes(shadowNode);\n /* Deep shadow DOM detected.\n Realm-safe check (GHSA-hpcv-96wg-7vj8): use nodeType against the\n DOCUMENT_FRAGMENT_NODE constant rather than instanceof, so we\n recurse into <template>.content from foreign realms too. */\n if (_isDocumentFragment(shadowNode.content)) {\n _sanitizeShadowDOM2(shadowNode.content);\n }\n /* An element iterated here may itself host an attached\n shadow root. The default NodeIterator does not enter shadow\n trees, so a shadow root nested inside template.content was\n previously reached by no walk at all (the pre-pass at\n _sanitizeAttachedShadowRoots descends via childNodes, which\n doesn't enter template.content; the template-content recursion\n above iterates the content but never inspected shadowRoot).\n Walk it explicitly. The nodeType guard avoids reading\n shadowRoot off text / comment / CDATA / PI nodes that the\n iterator also surfaces. */\n const shadowNodeType = getNodeType ? getNodeType(shadowNode) : shadowNode.nodeType;\n if (shadowNodeType === NODE_TYPE.element) {\n const innerSr = getShadowRoot(shadowNode);\n if (_isDocumentFragment(innerSr)) {\n _sanitizeAttachedShadowRoots(innerSr);\n _sanitizeShadowDOM2(innerSr);\n }\n }\n }\n /* Execute a hook if present */\n _executeHooks(hooks.afterSanitizeShadowDOM, fragment, null);\n };\n /**\n * _sanitizeAttachedShadowRoots\n *\n * Walks `root` and feeds every attached shadow root we encounter into\n * the existing _sanitizeShadowDOM pipeline. The default node iterator\n * does not descend into shadow trees, so nodes inside an attached\n * shadow root would otherwise be skipped entirely.\n *\n * Two real input paths put attached shadow roots in front of us:\n * 1. IN_PLACE on a DOM node that already has shadow roots attached.\n * 2. DOM-node input where importNode(dirty, true) deep-clones the\n * shadow root because it was created with `clonable: true`.\n *\n * This pass runs once, up front, so the main iteration loop (and the\n * existing _sanitizeShadowDOM template-content recursion) stay\n * untouched — string-input paths are not affected.\n *\n * @param root the subtree root to walk for attached shadow roots\n */\n const _sanitizeAttachedShadowRoots = function _sanitizeAttachedShadowRoots(root) {\n /* Iterative (explicit stack) rather than per-child recursion. DOM APIs\n impose no depth cap, so an attacker-shaped tree (JSON/CRDT/editor data\n built straight into the DOM — the IN_PLACE surface) deeper than the JS\n call-stack budget would otherwise overflow native recursion here and\n throw at the IN_PLACE entry pre-pass, before a single node is\n sanitized, leaving the caller's live tree untouched (fail-open). See\n campaign-3 F4. A heap stack keeps depth off the call stack.\n Each work item is either a node to descend into, or a deferred\n `_sanitizeShadowDOM` for an already-walked shadow root. The deferred\n form preserves the original post-order discipline: a shadow root's\n nested shadow roots are discovered before the outer shadow is\n sanitized (which may remove hosts). Pushes are in reverse of the\n desired processing order (LIFO): template content, then children, then\n the shadow-sanitize, then the shadow walk — so the order matches the\n previous recursion exactly. */\n const stack = [{\n node: root,\n shadow: null\n }];\n while (stack.length > 0) {\n const item = stack.pop();\n /* Deferred shadow-DOM sanitisation: runs after its subtree was walked. */\n if (item.shadow) {\n _sanitizeShadowDOM2(item.shadow);\n continue;\n }\n const node = item.node;\n const nodeType = getNodeType ? getNodeType(node) : node.nodeType;\n const isElement = nodeType === NODE_TYPE.element;\n /* (pushed last → processed first) Children, snapshotted in reverse so\n the first child is processed first. Snapshotting matters because a\n hook may detach siblings mid-walk. */\n const childNodes = getChildNodes(node);\n if (childNodes) {\n for (let i = childNodes.length - 1; i >= 0; --i) {\n stack.push({\n node: childNodes[i],\n shadow: null\n });\n }\n }\n /* (pushed before children → processed after them, matching the old\n \"template content last\" order) When the node is a <template>,\n descend into its content. */\n if (isElement) {\n const rootName = getNodeName ? getNodeName(node) : null;\n if (typeof rootName === 'string' && transformCaseFunc(rootName) === 'template') {\n const content = node.content;\n if (_isDocumentFragment(content)) {\n stack.push({\n node: content,\n shadow: null\n });\n }\n }\n }\n /* Shadow root (processed first): walk its subtree, then sanitise it.\n Realm-safe check (GHSA-hpcv-96wg-7vj8): nodeType-based detection\n rather than `instanceof DocumentFragment`, which is realm-bound and\n silently skipped foreign-realm shadow roots (e.g.\n iframe.contentDocument attachShadow). */\n if (isElement) {\n const sr = getShadowRoot(node);\n if (_isDocumentFragment(sr)) {\n /* Push the deferred sanitise first so it pops after the shadow\n walk we push next, i.e. nested shadow roots are discovered\n before this one is sanitised. */\n stack.push({\n node: null,\n shadow: sr\n }, {\n node: sr,\n shadow: null\n });\n }\n }\n }\n };\n // eslint-disable-next-line complexity\n DOMPurify.sanitize = function (dirty) {\n let cfg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n let body = null;\n let importedNode = null;\n let currentNode = null;\n let returnNode = null;\n /* Make sure we have a string to sanitize.\n DO NOT return early, as this will return the wrong type if\n the user has requested a DOM object rather than a string */\n IS_EMPTY_INPUT = !dirty;\n if (IS_EMPTY_INPUT) {\n dirty = '<!-->';\n }\n /* Stringify, in case dirty is an object */\n if (typeof dirty !== 'string' && !_isNode(dirty)) {\n dirty = stringifyValue(dirty);\n if (typeof dirty !== 'string') {\n throw typeErrorCreate('dirty is not a string, aborting');\n }\n }\n /* Return dirty HTML if DOMPurify cannot run */\n if (!DOMPurify.isSupported) {\n return dirty;\n }\n /* Assign config vars */\n if (SET_CONFIG) {\n /* Persistent setConfig() path: _parseConfig is skipped, so the sets are\n * not re-derived per call. Restore them from the pristine bindings\n * captured at setConfig() time so a previous call's hook clone (mutated\n * below) does not carry over. */\n ALLOWED_TAGS = SET_CONFIG_ALLOWED_TAGS;\n ALLOWED_ATTR = SET_CONFIG_ALLOWED_ATTR;\n } else {\n _parseConfig(cfg);\n }\n /* Clone the hook-mutable allowlists before the walk whenever an\n * uponSanitize* hook is registered. The hook event exposes ALLOWED_TAGS\n * and ALLOWED_ATTR by reference (as allowedTags / allowedAttributes), so\n * a hook that widens them would otherwise mutate the shared set\n * permanently: across later calls and across every element. Cloning per\n * walk keeps documented in-call widening working while scoping it to the\n * call. A single guard for both config paths - the per-call path rebinds\n * the sets in _parseConfig each call, the persistent path restores them\n * from the captured bindings just above - so the two cannot diverge. */\n if (hooks.uponSanitizeElement.length > 0 || hooks.uponSanitizeAttribute.length > 0) {\n ALLOWED_TAGS = clone(ALLOWED_TAGS);\n }\n if (hooks.uponSanitizeAttribute.length > 0) {\n ALLOWED_ATTR = clone(ALLOWED_ATTR);\n }\n /* Clean up removed elements */\n DOMPurify.removed = [];\n /* Resolve IN_PLACE for this call without mutating persistent config.\n Writing the IN_PLACE closure variable here leaks under setConfig(),\n where _parseConfig is skipped on later calls: a single string call would\n disable in-place mode for every subsequent node call, returning a\n sanitized copy while leaving the caller's node — which in-place callers\n keep using and whose return value they ignore — unsanitized. REPORT-2. */\n const inPlace = IN_PLACE && typeof dirty !== 'string' && _isNode(dirty);\n if (inPlace) {\n /* Declarative-partial-updates / streaming pre-pass: sever every patch\n linkage across the live tree BEFORE the walk, so no patch can fire\n mid-walk and inject into an already-processed region. Runs first, so\n it also covers the forbidden/clobbered roots that throw below. */\n _neutralizePatchLinkage(dirty);\n /* Do some early pre-sanitization to avoid unsafe root nodes.\n Read nodeName through the cached prototype getter — a clobbering\n child named \"nodeName\" on the form root would otherwise shadow\n the property and let this check skip the root-allowlist\n validation entirely. */\n const nn = getNodeName ? getNodeName(dirty) : dirty.nodeName;\n if (typeof nn === 'string') {\n const tagName = transformCaseFunc(nn);\n if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {\n /* Fail closed on a live root: neutralize handlers/children before\n throwing, exactly as the mid-walk abort path does. */\n _neutralizeRoot(dirty);\n throw typeErrorCreate('root node is forbidden and cannot be sanitized in-place');\n }\n }\n /* Pre-flight the root through _isClobbered. The iterator-driven\n removal path can not detach a parent-less root: _forceRemove\n falls through to Element.prototype.remove(), which per spec\n is a no-op on a node with no parent. A clobbered root would\n then survive the main loop with its attributes uninspected,\n because _sanitizeAttributes early-returns on _isClobbered. The\n result would be an attacker-controlled form, complete with any\n event-handler attributes the caller passed in, handed back to\n the application unsanitized. Refuse to sanitize such a root\n the same way we refuse a forbidden tag. GHSA-r47g-fvhr-h676. */\n if (_isClobbered(dirty)) {\n /* Fail closed on a live clobbered root before throwing.\n _neutralizeRoot's reads are clobber-safe (cached getters); the\n form's non-clobbered descendants, e.g. an armed <img>, are scrubbed. */\n _neutralizeRoot(dirty);\n throw typeErrorCreate('root node is clobbered and cannot be sanitized in-place');\n }\n /* Sanitize attached shadow roots before the main iterator runs.\n The iterator does not descend into shadow trees. Same fail-closed\n barrier as the main walk (campaign-3 F2): a custom-element reaction\n inside a shadow root could abort this pre-pass before the walk runs,\n which would otherwise leave the entire live tree unsanitized. */\n try {\n _sanitizeAttachedShadowRoots(dirty);\n } catch (error) {\n _neutralizeRoot(dirty);\n throw error;\n }\n } else if (_isNode(dirty)) {\n /* If dirty is a DOM element, append to an empty document to avoid\n elements being stripped by the parser */\n body = _initDocument('<!---->');\n importedNode = body.ownerDocument.importNode(dirty, true);\n if (importedNode.nodeType === NODE_TYPE.element && importedNode.nodeName === 'BODY') {\n /* Node is already a body, use as is */\n body = importedNode;\n } else if (importedNode.nodeName === 'HTML') {\n body = importedNode;\n } else {\n // eslint-disable-next-line unicorn/prefer-dom-node-append\n body.appendChild(importedNode);\n }\n /* Clonable shadow roots are deep-cloned by importNode(); sanitize\n them before the main iterator runs, since the iterator does not\n descend into shadow trees. The walk routes every read through a\n cached prototype getter so clobbering descendants on a form root\n cannot hide a shadow host from this pass. */\n _sanitizeAttachedShadowRoots(importedNode);\n } else {\n /* Exit directly if we have nothing to do */\n if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT &&\n // eslint-disable-next-line unicorn/prefer-includes\n dirty.indexOf('<') === -1) {\n return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? _createTrustedHTML(dirty) : dirty;\n }\n /* Initialize the document to work on */\n body = _initDocument(dirty);\n /* Check we have a DOM node from the data */\n if (!body) {\n return RETURN_DOM ? null : RETURN_TRUSTED_TYPE ? emptyHTML : '';\n }\n }\n /* Remove first element node (ours) if FORCE_BODY is set */\n if (body && FORCE_BODY) {\n _forceRemove(body.firstChild);\n }\n /* Get node iterator */\n const walkRoot = inPlace ? dirty : body;\n /* Now start iterating over the created document.\n The walk runs inside an exception barrier (campaign-3 F2): a re-entrant\n engine/custom-element mutation can detach a node mid-walk so\n `_forceRemove`'s parentless guard throws, aborting the loop. Without the\n barrier the caller's in-place tree would be left half-sanitized with the\n unvisited tail still armed. _createNodeIterator itself is inside the\n barrier too: constructing the iterator dereferences the root's document,\n and any failure there (e.g. an exotic/clobbered root) must still fail\n closed rather than skip the neutralize. On any throw we fail closed -\n strip the in-place root bare - then rethrow so the existing throw\n contract is preserved. (String/DOM-copy paths never return the partial\n body, so the propagating throw is already fail-closed there.) */\n try {\n const nodeIterator = _createNodeIterator(walkRoot);\n while (currentNode = nodeIterator.nextNode()) {\n /* Sanitize tags and elements */\n _sanitizeElements(currentNode, walkRoot);\n /* Check attributes next */\n _sanitizeAttributes(currentNode);\n /* Shadow DOM detected, sanitize it.\n Realm-safe check (GHSA-hpcv-96wg-7vj8): nodeType-based detection\n instead of instanceof, so foreign-realm <template>.content is\n walked correctly. */\n if (_isDocumentFragment(currentNode.content)) {\n _sanitizeShadowDOM2(currentNode.content);\n }\n }\n } catch (error) {\n if (inPlace) {\n _neutralizeRoot(dirty);\n /* Nodes _forceRemove'd earlier in the aborted walk are already\n detached from the root, so _neutralizeRoot's subtree pass does not\n reach them. Defuse them too, mirroring the success-path loop below. */\n arrayForEach(DOMPurify.removed, entry => {\n if (entry.element) {\n _neutralizeSubtree(entry.element);\n }\n });\n }\n throw error;\n }\n /* If we sanitized `dirty` in-place, return it. */\n if (inPlace) {\n /* Fail-closed completion of the audit-5 F1 fix: every node removed from\n the caller's live tree is detached but may still hold a queued\n resource-event handler that fires in page scope after we return. The\n move-hoist covers only disallowed-tag KEEP_CONTENT removals; strip the\n non-allow-listed attributes off every other removed subtree (clobber,\n mXSS, namespace, comments, KEEP_CONTENT:false, …) so those handlers are\n cancelled before any event can fire. Runs synchronously, pre-return. */\n arrayForEach(DOMPurify.removed, entry => {\n if (entry.element) {\n _neutralizeSubtree(entry.element);\n }\n });\n if (SAFE_FOR_TEMPLATES) {\n _scrubTemplateExpressions2(dirty);\n }\n return dirty;\n }\n /* Return sanitized string or DOM */\n if (RETURN_DOM) {\n if (SAFE_FOR_TEMPLATES) {\n _scrubTemplateExpressions2(body);\n }\n if (RETURN_DOM_FRAGMENT) {\n returnNode = createDocumentFragment.call(body.ownerDocument);\n while (body.firstChild) {\n // eslint-disable-next-line unicorn/prefer-dom-node-append\n returnNode.appendChild(body.firstChild);\n }\n } else {\n returnNode = body;\n }\n if (ALLOWED_ATTR.shadowroot || ALLOWED_ATTR.shadowrootmode) {\n /*\n AdoptNode() is not used because internal state is not reset\n (e.g. the past names map of a HTMLFormElement), this is safe\n in theory but we would rather not risk another attack vector.\n The state that is cloned by importNode() is explicitly defined\n by the specs.\n */\n returnNode = importNode.call(originalDocument, returnNode, true);\n }\n return returnNode;\n }\n let serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML;\n /* Serialize doctype if allowed */\n if (WHOLE_DOCUMENT && ALLOWED_TAGS['!doctype'] && body.ownerDocument && body.ownerDocument.doctype && body.ownerDocument.doctype.name && regExpTest(DOCTYPE_NAME, body.ownerDocument.doctype.name)) {\n serializedHTML = '<!DOCTYPE ' + body.ownerDocument.doctype.name + '>\\n' + serializedHTML;\n }\n /* Sanitize final string template-safe */\n if (SAFE_FOR_TEMPLATES) {\n serializedHTML = _stripTemplateExpressions(serializedHTML);\n }\n return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? _createTrustedHTML(serializedHTML) : serializedHTML;\n };\n DOMPurify.setConfig = function () {\n let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n _parseConfig(cfg);\n SET_CONFIG = true;\n SET_CONFIG_ALLOWED_TAGS = ALLOWED_TAGS;\n SET_CONFIG_ALLOWED_ATTR = ALLOWED_ATTR;\n };\n DOMPurify.clearConfig = function () {\n CONFIG = null;\n SET_CONFIG = false;\n SET_CONFIG_ALLOWED_TAGS = null;\n SET_CONFIG_ALLOWED_ATTR = null;\n // Drop any caller-supplied Trusted Types policy so it cannot poison later\n // `RETURN_TRUSTED_TYPE` output. The internal default policy (cached, and\n // never recreated — Trusted Types throws on duplicate names) is restored by\n // the next `_parseConfig`. See GHSA-vxr8-fq34-vvx9.\n trustedTypesPolicy = defaultTrustedTypesPolicy;\n emptyHTML = '';\n };\n DOMPurify.isValidAttribute = function (tag, attr, value) {\n /* Initialize shared config vars if necessary. */\n if (!CONFIG) {\n _parseConfig({});\n }\n const lcTag = transformCaseFunc(tag);\n const lcName = transformCaseFunc(attr);\n return _isValidAttribute(lcTag, lcName, value);\n };\n DOMPurify.addHook = function (entryPoint, hookFunction) {\n if (typeof hookFunction !== 'function') {\n return;\n }\n /* Reject unknown entry points. Without this, a non-hook key (e.g.\n * '__proto__') indexes off the prototype chain rather than a real\n * hook array, and arrayPush then writes to Object.prototype. Guard\n * with an own-property check against the known hook names. */\n if (!objectHasOwnProperty(hooks, entryPoint)) {\n return;\n }\n arrayPush(hooks[entryPoint], hookFunction);\n };\n DOMPurify.removeHook = function (entryPoint, hookFunction) {\n if (!objectHasOwnProperty(hooks, entryPoint)) {\n return undefined;\n }\n if (hookFunction !== undefined) {\n const index = arrayLastIndexOf(hooks[entryPoint], hookFunction);\n return index === -1 ? undefined : arraySplice(hooks[entryPoint], index, 1)[0];\n }\n return arrayPop(hooks[entryPoint]);\n };\n DOMPurify.removeHooks = function (entryPoint) {\n if (!objectHasOwnProperty(hooks, entryPoint)) {\n return;\n }\n hooks[entryPoint] = [];\n };\n DOMPurify.removeAllHooks = function () {\n hooks = _createHooksMap();\n };\n return DOMPurify;\n}\nvar purify = createDOMPurify();\n\nexport { purify as default };\n//# sourceMappingURL=purify.es.mjs.map\n","/**\n * Sanitize an SVG string intended to be rendered as an icon.\n *\n * Used by toolbars and tool-button components when their icon prop is an\n * inline SVG supplied by a tool configuration. Runs DOMPurify with the\n * SVG profile, forbids `<script>` / `<foreignObject>` and strips\n * event-handler attributes.\n *\n * Returns an empty string when `window` / `document` are unavailable (SSR)\n * or the input is not a string.\n */\nimport DOMPurify from \"dompurify\";\nlet svgPurifierInstance = null;\nfunction resolveSvgPurifier() {\n if (svgPurifierInstance)\n return svgPurifierInstance;\n if (typeof window === \"undefined\" || !window.document)\n return null;\n const factory = DOMPurify;\n svgPurifierInstance =\n typeof factory === \"function\"\n ? factory(window)\n : DOMPurify;\n return svgPurifierInstance;\n}\nconst FORBIDDEN_TAGS = [\n \"script\",\n \"foreignobject\",\n \"iframe\",\n \"object\",\n \"embed\",\n \"base\",\n \"form\",\n];\nconst FORBIDDEN_ATTRS = [\n \"onerror\",\n \"onload\",\n \"onclick\",\n \"onmouseover\",\n \"onmouseout\",\n \"onmouseenter\",\n \"onmouseleave\",\n \"onfocus\",\n \"onblur\",\n \"onkeydown\",\n \"onkeyup\",\n \"onkeypress\",\n \"formaction\",\n \"xlink:href\",\n];\nconst stringCache = new Map();\nconst STRING_CACHE_MAX = 64;\nexport function sanitizeSvgIcon(icon) {\n if (typeof icon !== \"string\" || icon.length === 0)\n return \"\";\n const trimmed = icon.trimStart();\n if (!trimmed.toLowerCase().startsWith(\"<svg\"))\n return \"\";\n const cached = stringCache.get(icon);\n if (cached !== undefined)\n return cached;\n const purifier = resolveSvgPurifier();\n if (!purifier)\n return \"\";\n const result = purifier.sanitize(icon, {\n USE_PROFILES: { svg: true, svgFilters: true },\n FORBID_TAGS: FORBIDDEN_TAGS,\n FORBID_ATTR: FORBIDDEN_ATTRS,\n ALLOW_UNKNOWN_PROTOCOLS: false,\n RETURN_TRUSTED_TYPE: false,\n });\n const str = typeof result === \"string\" ? result : String(result ?? \"\");\n if (stringCache.size >= STRING_CACHE_MAX) {\n // Naive LRU: clear oldest half when the cache fills up. Tool icons are\n // a small fixed set per assessment so this is rarely hit.\n const keys = [...stringCache.keys()];\n for (let i = 0; i < keys.length / 2; i += 1) {\n stringCache.delete(keys[i]);\n }\n }\n stringCache.set(icon, str);\n return str;\n}\n/** Reset sanitizer state. Intended for tests. */\nexport function resetSvgSanitizerForTesting() {\n svgPurifierInstance = null;\n stringCache.clear();\n}\n//# sourceMappingURL=sanitize-svg-icon.js.map","/**\n * Minimal, frontend-safe defaults for PIE build service URLs.\n *\n * In PIEOneer, these come from `$env/dynamic/public`. In `pie-players` we avoid\n * SvelteKit env dependencies so this can be consumed by any bundler.\n */\n// Default public bundle host. Keep this aligned with the IIFE loader default.\n// (We prefer the proxy endpoint, which is stable/cached for browser usage.)\nconst DEFAULT_BUILDER_ORIGIN_URL = \"https://proxy.pie-api.com\";\nconst DEFAULT_BUILDER_BUNDLE_URL = `${DEFAULT_BUILDER_ORIGIN_URL}/bundles/`;\nfunction readPublicEnv(key) {\n try {\n // Vite/SvelteKit-like\n const v = import.meta?.env?.[key];\n if (typeof v === \"string\" && v.length > 0)\n return v;\n }\n catch { }\n return undefined;\n}\nexport const BUILDER_ORIGIN_URL = (typeof window !== \"undefined\" && window.PIE_BUILDER_ORIGIN_URL) ||\n readPublicEnv(\"PUBLIC_BUILDER_ORIGIN_URL\") ||\n DEFAULT_BUILDER_ORIGIN_URL;\nexport const BUILDER_BUNDLE_URL = (typeof window !== \"undefined\" && window.PIE_BUILDER_BUNDLE_URL) ||\n readPublicEnv(\"PUBLIC_BUILDER_BUNDLE_URL\") ||\n DEFAULT_BUILDER_BUNDLE_URL;\n//# sourceMappingURL=profile.js.map","/**\n * Base Instrumentation Provider\n *\n * Abstract base class that implements common instrumentation logic for all providers.\n * Provides a template method pattern for tracking errors and events with consistent\n * filtering, transformation, and sampling behavior.\n *\n * Concrete providers only need to implement the actual tracking methods specific\n * to their instrumentation backend (New Relic, DataDog, etc.)\n */\n/**\n * Abstract base class for instrumentation providers\n *\n * Implements the template method pattern:\n * 1. Checks if provider is ready\n * 2. Applies filters (errorFilter, eventFilter)\n * 3. Applies sampling (sampleRate)\n * 4. Transforms attributes (attributeTransformer)\n * 5. Delegates to concrete provider implementation (doTrackError, doTrackEvent, etc.)\n */\nexport class BaseInstrumentationProvider {\n initialized = false;\n config;\n // ============================================================================\n // Public API methods (template methods)\n // ============================================================================\n /**\n * Track an error with the instrumentation provider\n *\n * Template method that:\n * 1. Checks if provider is ready\n * 2. Applies error filter if configured\n * 3. Transforms attributes if configured\n * 4. Delegates to concrete provider implementation (doTrackError)\n *\n * @param error The error to track\n * @param attributes Contextual attributes\n */\n trackError(error, attributes) {\n // Guard: check if provider is ready\n if (!this.guardedOperation(\"trackError\", error, attributes)) {\n return;\n }\n // Apply error filter\n if (!this.applyErrorFilter(error, attributes)) {\n return;\n }\n // Transform attributes\n const finalAttributes = this.transformAttributes(attributes);\n // Delegate to concrete provider\n try {\n this.doTrackError(error, finalAttributes);\n if (this.config?.debug) {\n console.log(`[${this.providerName}] Tracked error:`, error, finalAttributes);\n }\n }\n catch (err) {\n console.error(`[${this.providerName}] Error tracking error:`, err);\n }\n }\n /**\n * Track a custom event with the instrumentation provider\n *\n * Template method that:\n * 1. Checks if provider is ready\n * 2. Applies event filter if configured\n * 3. Applies sampling if configured\n * 4. Transforms attributes if configured\n * 5. Adds timestamp if not present\n * 6. Delegates to concrete provider implementation (doTrackEvent)\n *\n * @param eventName Name of the event\n * @param attributes Event attributes\n */\n trackEvent(eventName, attributes) {\n // Guard: check if provider is ready\n if (!this.guardedOperation(\"trackEvent\", eventName, attributes)) {\n return;\n }\n // Apply event filter\n if (!this.applyEventFilter(eventName, attributes)) {\n return;\n }\n // Apply sampling\n if (!this.applySampling(eventName)) {\n return;\n }\n // Transform attributes\n let finalAttributes = this.transformAttributes(attributes);\n // Add timestamp if not present\n if (!finalAttributes.timestamp) {\n finalAttributes = {\n ...finalAttributes,\n timestamp: new Date().toISOString(),\n };\n }\n // Delegate to concrete provider\n try {\n this.doTrackEvent(eventName, finalAttributes);\n if (this.config?.debug) {\n console.log(`[${this.providerName}] Tracked event:`, eventName, finalAttributes);\n }\n }\n catch (err) {\n console.error(`[${this.providerName}] Error tracking event:`, err);\n }\n }\n /**\n * Track a performance metric\n *\n * Default implementation tracks metrics as events with a `metric:` prefix.\n * Concrete providers can override this method if their backend has a\n * dedicated metric API.\n *\n * @param metricName Name of the metric\n * @param value Numeric value\n * @param attributes Optional metric attributes\n */\n trackMetric(metricName, value, attributes) {\n // Default implementation: track as event\n this.trackEvent(`metric:${metricName}`, {\n ...attributes,\n metricValue: value,\n metricName,\n });\n }\n /**\n * Set user context for session tracking\n *\n * Template method that checks if provider is ready then delegates\n * to concrete provider implementation.\n *\n * @param userId User identifier\n * @param attributes Optional user attributes\n */\n setUserContext(userId, attributes) {\n // Guard: check if provider is ready\n if (!this.guardedOperation(\"setUserContext\", userId, attributes)) {\n return;\n }\n // Delegate to concrete provider\n try {\n this.doSetUserContext(userId, attributes);\n if (this.config?.debug) {\n console.log(`[${this.providerName}] Set user context:`, userId, attributes);\n }\n }\n catch (err) {\n console.error(`[${this.providerName}] Error setting user context:`, err);\n }\n }\n /**\n * Set global custom attributes\n *\n * Template method that checks if provider is ready then delegates\n * to concrete provider implementation.\n *\n * @param attributes Attributes to set globally\n */\n setGlobalAttributes(attributes) {\n // Guard: check if provider is ready\n if (!this.guardedOperation(\"setGlobalAttributes\", attributes)) {\n return;\n }\n // Delegate to concrete provider\n try {\n this.doSetGlobalAttributes(attributes);\n if (this.config?.debug) {\n console.log(`[${this.providerName}] Set global attributes:`, attributes);\n }\n }\n catch (err) {\n console.error(`[${this.providerName}] Error setting global attributes:`, err);\n }\n }\n // ============================================================================\n // Protected utility methods (shared logic)\n // ============================================================================\n /**\n * Guard operation - check if provider is ready\n *\n * Returns false if provider is not ready, logging a warning in debug mode.\n *\n * @param operation Name of the operation for logging\n * @param args Arguments for logging\n * @returns true if provider is ready, false otherwise\n */\n guardedOperation(operation, ...args) {\n if (!this.isReady()) {\n if (this.config?.debug) {\n console.warn(`[${this.providerName}] Attempted to ${operation} but provider not ready:`, ...args);\n }\n return false;\n }\n return true;\n }\n /**\n * Apply error filter if configured\n *\n * Returns false if error should be filtered out, logging in debug mode.\n *\n * @param error The error\n * @param attributes Error attributes\n * @returns true if error should be tracked, false if filtered out\n */\n applyErrorFilter(error, attributes) {\n if (this.config?.errorFilter &&\n !this.config.errorFilter(error, attributes)) {\n if (this.config?.debug) {\n console.log(`[${this.providerName}] Error filtered out:`, error, attributes);\n }\n return false;\n }\n return true;\n }\n /**\n * Apply event filter if configured\n *\n * Returns false if event should be filtered out, logging in debug mode.\n *\n * @param eventName Event name\n * @param attributes Event attributes\n * @returns true if event should be tracked, false if filtered out\n */\n applyEventFilter(eventName, attributes) {\n if (this.config?.eventFilter &&\n !this.config.eventFilter(eventName, attributes)) {\n if (this.config?.debug) {\n console.log(`[${this.providerName}] Event filtered out:`, eventName, attributes);\n }\n return false;\n }\n return true;\n }\n /**\n * Apply sampling if configured\n *\n * Returns false if event should be sampled out, logging in debug mode.\n *\n * @param eventName Event name for logging\n * @returns true if event should be tracked, false if sampled out\n */\n applySampling(eventName) {\n if (this.config?.sampleRate !== undefined && this.config.sampleRate < 1.0) {\n if (Math.random() > this.config.sampleRate) {\n if (this.config?.debug) {\n console.log(`[${this.providerName}] Event sampled out:`, eventName);\n }\n return false;\n }\n }\n return true;\n }\n /**\n * Transform attributes if transformer is configured\n *\n * @param attributes Original attributes\n * @returns Transformed attributes or original if no transformer\n */\n transformAttributes(attributes) {\n if (this.config?.attributeTransformer) {\n return this.config.attributeTransformer(attributes);\n }\n return attributes;\n }\n}\n//# sourceMappingURL=BaseInstrumentationProvider.js.map","/**\n * New Relic Instrumentation Provider\n *\n * Default provider for existing New Relic Browser Agent instrumentation.\n *\n * This provider wraps the global `window.newrelic` object provided by\n * the New Relic Browser Agent.\n *\n * @example\n * ```typescript\n * const provider = new NewRelicInstrumentationProvider();\n * await provider.initialize();\n *\n * if (provider.isReady()) {\n * provider.trackError(new Error('Something went wrong'), {\n * component: 'my-component',\n * errorType: 'ValidationError'\n * });\n * }\n * ```\n */\nimport { BaseInstrumentationProvider } from \"./BaseInstrumentationProvider.js\";\nexport class NewRelicInstrumentationProvider extends BaseInstrumentationProvider {\n providerId = \"newrelic\";\n providerName = \"New Relic\";\n /**\n * Initialize the New Relic provider\n *\n * Checks if the New Relic Browser Agent is available via `window.newrelic`.\n * If not available, initialization succeeds but `isReady()` will return false.\n *\n * @param config Optional configuration\n */\n async initialize(config) {\n this.config = config;\n // Check if New Relic is available\n if (typeof window !== \"undefined\" && window.newrelic) {\n this.initialized = true;\n if (this.config?.debug) {\n console.log(\"[NewRelicProvider] Initialized successfully\");\n }\n }\n else {\n if (this.config?.debug) {\n console.warn(\"[NewRelicProvider] New Relic not available (window.newrelic not found)\");\n }\n // Don't throw - allow graceful degradation\n this.initialized = false;\n }\n }\n /**\n * Check if provider is ready\n *\n * @returns true if New Relic is available and initialized\n */\n isReady() {\n return (this.initialized &&\n typeof window !== \"undefined\" &&\n !!window.newrelic);\n }\n /**\n * Cleanup provider resources\n *\n * Marks provider as uninitialized. The global `window.newrelic` object\n * is not modified.\n */\n destroy() {\n this.initialized = false;\n if (this.config?.debug) {\n console.log(\"[NewRelicProvider] Destroyed\");\n }\n }\n /**\n * Track an error with New Relic\n *\n * Calls `newrelic.noticeError(error, attributes)`\n *\n * @param error The error to track\n * @param attributes Transformed attributes (already filtered and transformed by base class)\n */\n doTrackError(error, attributes) {\n const newrelic = window.newrelic;\n newrelic.noticeError(error, attributes);\n }\n /**\n * Track a custom event/page action with New Relic\n *\n * Calls `newrelic.addPageAction(eventName, attributes)`\n *\n * @param eventName Name of the event\n * @param attributes Transformed attributes (already filtered and transformed by base class)\n */\n doTrackEvent(eventName, attributes) {\n const newrelic = window.newrelic;\n newrelic.addPageAction(eventName, attributes);\n }\n /**\n * Set user context for session tracking\n *\n * Calls `newrelic.setUserId()` and `newrelic.setCustomAttribute()` for user attributes.\n *\n * @param userId User identifier\n * @param attributes Optional user attributes\n */\n doSetUserContext(userId, attributes) {\n const newrelic = window.newrelic;\n // Set user ID if method exists\n if (newrelic.setUserId) {\n newrelic.setUserId(userId);\n }\n // Set custom attributes for user\n if (attributes && newrelic.setCustomAttribute) {\n for (const [key, value] of Object.entries(attributes)) {\n newrelic.setCustomAttribute(key, value);\n }\n }\n }\n /**\n * Set global custom attributes\n *\n * Calls `newrelic.setCustomAttribute()` for each attribute.\n *\n * @param attributes Attributes to set globally\n */\n doSetGlobalAttributes(attributes) {\n const newrelic = window.newrelic;\n if (newrelic.setCustomAttribute) {\n for (const [key, value] of Object.entries(attributes)) {\n newrelic.setCustomAttribute(key, value);\n }\n }\n }\n}\n//# sourceMappingURL=NewRelicInstrumentationProvider.js.map","export function isInstrumentationProvider(value) {\n if (!value || typeof value !== \"object\")\n return false;\n const candidate = value;\n return (typeof candidate.providerId === \"string\" &&\n typeof candidate.providerName === \"string\" &&\n typeof candidate.initialize === \"function\" &&\n typeof candidate.trackError === \"function\" &&\n typeof candidate.trackEvent === \"function\" &&\n typeof candidate.destroy === \"function\" &&\n typeof candidate.isReady === \"function\");\n}\n//# sourceMappingURL=provider-guards.js.map","/**\n * Shared loader configuration for PIE custom elements.\n *\n * Mirrors the `LoaderConfig` used by PIEOneer's custom element tags.\n */\nexport const DEFAULT_IIFE_BUNDLE_RETRY_CONFIG = {\n retryDelayMs: 3000,\n timeoutMs: 120000,\n};\nexport const DEFAULT_LOADER_CONFIG = {\n trackPageActions: false,\n instrumentationProvider: undefined,\n maxResourceRetries: 3,\n resourceRetryDelay: 500,\n iifeBundleRetry: DEFAULT_IIFE_BUNDLE_RETRY_CONFIG,\n};\n//# sourceMappingURL=loader-config.js.map","/**\n * PIE Types Module\n *\n * Pure type definitions, interfaces, and enums used across PIE utilities.\n * This module has NO runtime dependencies on other PIE modules.\n */\n/**\n * PIE bundle types\n */\nexport var BundleType;\n(function (BundleType) {\n BundleType[\"player\"] = \"player.js\";\n BundleType[\"clientPlayer\"] = \"client-player.js\";\n BundleType[\"editor\"] = \"editor.js\";\n})(BundleType || (BundleType = {}));\n/**\n * Internal PIE registry entry status\n */\nexport var Status;\n(function (Status) {\n Status[\"loading\"] = \"loading\";\n Status[\"loaded\"] = \"loaded\";\n})(Status || (Status = {}));\n/**\n * Default options for updatePieElement\n */\nexport const defaultPieElementOptions = {\n invokeControllerForModel: true,\n env: { mode: \"gather\", role: \"student\", partialScoring: false },\n eventListeners: {},\n};\n/**\n * Type guard: Check if object has window.pie\n */\nexport function isPieAvailable(obj) {\n return obj && typeof obj.pie === \"object\";\n}\n/**\n * Type guard: Check if object is a CustomElementConstructor\n */\nexport function isCustomElementConstructor(obj) {\n return (typeof obj === \"function\" &&\n \"prototype\" in obj &&\n obj.prototype instanceof HTMLElement);\n}\n/**\n * Type guard: Check if window has PIE_REGISTRY\n */\nexport function isPieRegistryAvailable(obj) {\n return obj && typeof obj.PIE_REGISTRY === \"object\";\n}\n//# sourceMappingURL=types.js.map","/**\n * ElementLoader primitive — the one place where \"these tags are registered\n * with customElements\" is decided.\n *\n * Owns the truthful promise contract end-to-end:\n *\n * ensureRegistered(elements, options) resolves iff every requested tag\n * is in `customElements` at the moment of resolution. On partial\n * success it rejects with an `ElementLoaderError` carrying the set of\n * unregistered tags and a per-tag `RegistrationFailureReason` map.\n *\n * The primitive delegates the actual fetch/register work to a backend\n * adapter (IIFE or ESM) but always verifies the outcome via\n * `customElements.whenDefined`. An adapter cannot silently under-register\n * — the primitive will catch it and surface a timeout reason.\n *\n * See packages/players-shared/tests/element-loader-contract.test.ts for\n * the executable specification of every failure mode this primitive is\n * required to catch.\n */\nimport { DEFAULT_IIFE_BUNDLE_RETRY_CONFIG } from \"../loader-config.js\";\nimport { AdapterFailure, } from \"./element-loader-types.js\";\nimport { createEsmBackend } from \"./esm-adapter.js\";\nimport { createIifeBackend } from \"./iife-adapter.js\";\nexport { AdapterFailure } from \"./element-loader-types.js\";\n/**\n * Aggregate error thrown by `ensureRegistered` when one or more requested\n * tags were not registered by the time verification timed out.\n */\nexport class ElementLoaderError extends Error {\n name = \"ElementLoaderError\";\n unregisteredTags;\n reasons;\n constructor(message, unregisteredTags, reasons) {\n super(message);\n this.unregisteredTags = unregisteredTags;\n this.reasons = reasons;\n }\n}\n/**\n * Thrown by `assertRegistered` when any requested tag is missing from\n * `customElements`. Carries enough detail for the host to diagnose what\n * pre-registration step was skipped.\n */\nexport class ElementAssertionError extends Error {\n name = \"ElementAssertionError\";\n expectedTags;\n missingTags;\n currentlyRegisteredTags;\n constructor(expected, missing, currentlyRegistered) {\n super(buildAssertionMessage(expected, missing, currentlyRegistered));\n this.expectedTags = expected;\n this.missingTags = missing;\n this.currentlyRegisteredTags = currentlyRegistered;\n }\n}\nfunction buildAssertionMessage(expected, missing, registered) {\n const expectedStr = expected.join(\", \");\n const missingStr = missing.join(\", \");\n const registeredStr = registered.length\n ? registered.join(\", \")\n : \"(none enumerable)\";\n return (`ElementLoader.assertRegistered: expected [${expectedStr}], ` +\n `missing [${missingStr}]. customElements contains: [${registeredStr}].`);\n}\nconst DEFAULT_WHEN_DEFINED_TIMEOUT_MS = 5000;\nconst DEFAULT_LOAD_TIMEOUT_MS = DEFAULT_IIFE_BUNDLE_RETRY_CONFIG.timeoutMs;\n// Module-scoped in-flight cache. Key: backend signature + sorted elements.\n// Keeps concurrent identical requests collapsed to one backend call.\nconst inFlightRequests = new Map();\nconst resolvedEsmBackends = new Map();\nconst resolvedBackendOverrides = new Map();\n/**\n * Resolve iff every tag in `elements` is registered with `customElements`.\n * Reject with `ElementLoaderError` otherwise.\n *\n * The primitive is the sole authority on registration state:\n * - Empty element map resolves immediately (no backend call).\n * - Already-registered tags resolve immediately (no backend call).\n * - Concurrent identical requests share one backend call.\n * - After the adapter's `load` settles, a post-load verification pass\n * (bounded `customElements.whenDefined`) checks every tag. Any missing\n * tag becomes a rejection.\n */\nexport async function ensureRegistered(elements, options) {\n if (!elements || Object.keys(elements).length === 0)\n return;\n const tags = Object.keys(elements);\n const timeoutMs = options.whenDefinedTimeoutMs ?? DEFAULT_WHEN_DEFINED_TIMEOUT_MS;\n const loadTimeoutMs = options.loadTimeoutMs ?? DEFAULT_LOAD_TIMEOUT_MS;\n // Fast path: everything already registered. Skip backend and dedup\n // bookkeeping entirely.\n if (allAlreadyRegistered(tags))\n return;\n const dedupKey = buildDedupKey(options.backend, elements);\n const existing = inFlightRequests.get(dedupKey);\n if (existing)\n return existing;\n const backend = resolveBackend(options.backend);\n const doc = resolveDoc(options.doc);\n const promise = runEnsureRegistered(elements, tags, backend, { doc, whenDefinedTimeoutMs: timeoutMs }, timeoutMs, loadTimeoutMs);\n inFlightRequests.set(dedupKey, promise);\n try {\n await promise;\n }\n finally {\n if (inFlightRequests.get(dedupKey) === promise) {\n inFlightRequests.delete(dedupKey);\n }\n }\n}\nasync function runEnsureRegistered(elements, tags, backend, context, timeoutMs, loadTimeoutMs) {\n let adapterError;\n try {\n await raceWithLoadTimeout(backend.load(elements, context), tags, loadTimeoutMs);\n }\n catch (err) {\n adapterError = err instanceof Error ? err : new Error(String(err));\n }\n const verification = await Promise.all(tags.map(async (tag) => {\n if (isRegistered(tag))\n return { tag, ok: true };\n try {\n await whenDefinedWithTimeout(tag, timeoutMs);\n return { tag, ok: true };\n }\n catch {\n return { tag, ok: false };\n }\n }));\n const unregistered = new Set();\n const reasons = new Map();\n for (const v of verification) {\n if (v.ok)\n continue;\n unregistered.add(v.tag);\n const adapterReason = extractAdapterReason(adapterError, v.tag);\n reasons.set(v.tag, adapterReason ?? { kind: \"timeout\", tag: v.tag, timeoutMs });\n }\n if (unregistered.size > 0) {\n throw new ElementLoaderError(`Element registration failed; missing tags: ${[...unregistered].join(\", \")}`, unregistered, reasons);\n }\n}\n/**\n * Race the backend's `load()` against a cumulative deadline.\n *\n * On timeout, synthesize an `AdapterFailure` whose `reasons` map carries\n * a `kind: \"timeout\"` entry per requested tag. The verification pass in\n * `runEnsureRegistered` will then produce a normal `ElementLoaderError`\n * with structured per-tag reasons — same surface shape as any other\n * adapter rejection.\n */\nasync function raceWithLoadTimeout(loadPromise, tags, loadTimeoutMs) {\n let timer;\n try {\n await Promise.race([\n loadPromise,\n new Promise((_, reject) => {\n timer = setTimeout(() => {\n const reasons = new Map();\n for (const tag of tags) {\n reasons.set(tag, {\n kind: \"timeout\",\n tag,\n timeoutMs: loadTimeoutMs,\n });\n }\n reject(new AdapterFailure(reasons));\n }, loadTimeoutMs);\n }),\n ]);\n }\n finally {\n if (timer)\n clearTimeout(timer);\n }\n}\n/**\n * Synchronously assert that every tag is already in `customElements`.\n * Throws `ElementAssertionError` with diagnostic detail otherwise.\n *\n * Used by hosts that opt into the \"preloaded\" strategy — they pre-register\n * elements out-of-band and want a loud failure if anything is missing.\n */\nexport function assertRegistered(tags) {\n if (!tags || tags.length === 0)\n return;\n const missing = tags.filter((tag) => !isRegistered(tag));\n if (missing.length === 0)\n return;\n throw new ElementAssertionError(tags, missing, snapshotRegisteredTags());\n}\n// ─── Internals ───────────────────────────────────────────────────────────────\nfunction resolveBackend(backend) {\n if (isDirectBackend(backend))\n return backend;\n if (\"kind\" in backend) {\n if (backend.kind === \"iife\")\n return createIifeBackend(backend);\n if (backend.kind === \"esm\") {\n const backendKey = backendKeyOf(backend);\n const override = resolvedBackendOverrides.get(backendKey);\n if (override)\n return override;\n const existing = resolvedEsmBackends.get(backendKey);\n if (existing)\n return existing;\n const created = createEsmBackend(backend);\n resolvedEsmBackends.set(backendKey, created);\n return created;\n }\n }\n throw new Error(\"ElementLoader: invalid backend option\");\n}\nfunction isDirectBackend(backend) {\n return (typeof backend.load === \"function\" &&\n !(\"kind\" in backend));\n}\nfunction resolveDoc(doc) {\n if (doc)\n return doc;\n if (typeof document !== \"undefined\")\n return document;\n throw new Error(\"ElementLoader: no Document available; pass options.doc explicitly\");\n}\nfunction buildDedupKey(backend, elements) {\n const backendKey = backendKeyOf(backend);\n const entries = Object.entries(elements).sort(([a], [b]) => a.localeCompare(b));\n return `${backendKey}|${JSON.stringify(entries)}`;\n}\nconst backendIds = new WeakMap();\nlet nextBackendId = 0;\nconst functionIds = new WeakMap();\nlet nextFunctionId = 0;\nconst opaqueObjectIds = new WeakMap();\nlet nextOpaqueObjectId = 0;\nfunction backendKeyOf(backend) {\n if (isDirectBackend(backend)) {\n let id = backendIds.get(backend);\n if (!id) {\n id = `b${++nextBackendId}`;\n backendIds.set(backend, id);\n }\n return `backend#${id}`;\n }\n if (\"kind\" in backend) {\n if (backend.kind === \"iife\") {\n return `iife#${fingerprintValue({\n kind: \"iife\",\n bundleHost: backend.bundleHost,\n bundleType: backend.bundleType ?? \"\",\n needsControllers: backend.needsControllers ?? true,\n bundleInfo: backend.bundleInfo ?? null,\n debugEnabled: backend.debugEnabled ?? null,\n bundleRetry: backend.bundleRetry ?? null,\n onBundleRetryStatus: backend.onBundleRetryStatus ?? null,\n trackPageActions: backend.trackPageActions ?? false,\n instrumentationProvider: backend.instrumentationProvider ?? null,\n })}`;\n }\n if (backend.kind === \"esm\") {\n return `esm#${fingerprintValue({\n kind: \"esm\",\n cdnBaseUrl: backend.cdnBaseUrl,\n cdnProvider: backend.cdnProvider ?? null,\n moduleResolution: backend.moduleResolution ?? \"url\",\n view: backend.view ?? \"delivery\",\n viewConfig: backend.viewConfig ?? null,\n loadControllers: backend.loadControllers ?? true,\n debugEnabled: backend.debugEnabled ?? null,\n trackPageActions: backend.trackPageActions ?? false,\n instrumentationProvider: backend.instrumentationProvider ?? null,\n })}`;\n }\n }\n return \"unknown\";\n}\nfunction fingerprintValue(value) {\n return JSON.stringify(normalizeForFingerprint(value, new Map()));\n}\nfunction normalizeForFingerprint(value, seen) {\n if (value === null || value === undefined)\n return value;\n const primitiveType = typeof value;\n if (primitiveType === \"string\" ||\n primitiveType === \"number\" ||\n primitiveType === \"boolean\") {\n return value;\n }\n if (primitiveType === \"function\") {\n return { __functionRef: getFunctionRefId(value) };\n }\n if (primitiveType !== \"object\") {\n return String(value);\n }\n const objectValue = value;\n const existing = seen.get(objectValue);\n if (existing)\n return { __cycleRef: existing };\n const cycleRefId = `cycle#${seen.size + 1}`;\n seen.set(objectValue, cycleRefId);\n if (Array.isArray(value)) {\n return value.map((entry) => normalizeForFingerprint(entry, seen));\n }\n if (!isPlainObject(value)) {\n return { __objectRef: getOpaqueObjectRefId(objectValue) };\n }\n const normalized = {};\n for (const key of Object.keys(value).sort()) {\n normalized[key] = normalizeForFingerprint(value[key], seen);\n }\n return normalized;\n}\nfunction isPlainObject(value) {\n if (!value || typeof value !== \"object\")\n return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\nfunction getFunctionRefId(fn) {\n let id = functionIds.get(fn);\n if (!id) {\n id = `fn#${++nextFunctionId}`;\n functionIds.set(fn, id);\n }\n return id;\n}\nfunction getOpaqueObjectRefId(value) {\n let id = opaqueObjectIds.get(value);\n if (!id) {\n id = `obj#${++nextOpaqueObjectId}`;\n opaqueObjectIds.set(value, id);\n }\n return id;\n}\nfunction allAlreadyRegistered(tags) {\n return tags.every((tag) => isRegistered(tag));\n}\nfunction isRegistered(tag) {\n if (typeof customElements === \"undefined\")\n return false;\n return customElements.get(tag) !== undefined;\n}\nasync function whenDefinedWithTimeout(tag, timeoutMs) {\n if (typeof customElements === \"undefined\") {\n throw new Error(`no customElements to await ${tag}`);\n }\n let timer;\n try {\n return await Promise.race([\n customElements.whenDefined(tag).then(() => undefined),\n new Promise((_, reject) => {\n timer = setTimeout(() => reject(new Error(`Timeout waiting for ${tag}`)), timeoutMs);\n }),\n ]);\n }\n finally {\n if (timer)\n clearTimeout(timer);\n }\n}\nfunction snapshotRegisteredTags() {\n if (typeof customElements === \"undefined\")\n return [];\n // Standard `CustomElementRegistry` does not expose iteration. Tests install\n // a scripted registry with a `__pieSnapshot` extension to make diagnostic\n // messages assertable. Production falls through to an empty list —\n // still strictly better than today's \"missing tags: X\" error which leaks\n // no registry state at all.\n const reg = customElements;\n if (typeof reg.__pieSnapshot === \"function\") {\n try {\n return reg.__pieSnapshot();\n }\n catch {\n return [];\n }\n }\n return [];\n}\nfunction extractAdapterReason(err, tag) {\n if (!err)\n return undefined;\n if (err instanceof AdapterFailure)\n return err.reasons.get(tag);\n return { kind: \"backend-rejected\", tag, cause: err.message };\n}\n// ─── Test-only helpers ───────────────────────────────────────────────────────\n/**\n * Internal helpers for test harnesses. Not part of the public runtime API;\n * production code should never reach for these.\n *\n * @internal\n */\nexport const __testing = {\n resetDedupState() {\n inFlightRequests.clear();\n resolvedEsmBackends.clear();\n resolvedBackendOverrides.clear();\n },\n inFlightCount() {\n return inFlightRequests.size;\n },\n dedupKeyFor(elements, backend) {\n return buildDedupKey(backend, elements);\n },\n replaceResolvedBackendForTesting(backend, resolvedBackend) {\n resolvedBackendOverrides.set(backendKeyOf(backend), resolvedBackend);\n },\n restoreResolvedBackendsForTesting() {\n resolvedEsmBackends.clear();\n resolvedBackendOverrides.clear();\n },\n};\n//# sourceMappingURL=element-loader.js.map","export var SessionEventType;\n(function (SessionEventType) {\n SessionEventType[\"SAVE\"] = \"save\";\n SessionEventType[\"MODEL\"] = \"model\";\n SessionEventType[\"SCORE\"] = \"score\";\n SessionEventType[\"MANUAL_SCORE\"] = \"manual-score\";\n})(SessionEventType || (SessionEventType = {}));\nexport var ScoreType;\n(function (ScoreType) {\n ScoreType[\"AUTO\"] = \"auto\";\n ScoreType[\"MANUAL\"] = \"manual\";\n})(ScoreType || (ScoreType = {}));\nexport var ModeType;\n(function (ModeType) {\n ModeType[\"GATHER\"] = \"gather\";\n ModeType[\"VIEW\"] = \"view\";\n ModeType[\"EVALUATE\"] = \"evaluate\";\n})(ModeType || (ModeType = {}));\nexport var SanctionedVersionChangeStatus;\n(function (SanctionedVersionChangeStatus) {\n SanctionedVersionChangeStatus[\"PENDING\"] = \"pending\";\n SanctionedVersionChangeStatus[\"IN_PROGRESS\"] = \"in_progress\";\n SanctionedVersionChangeStatus[\"COMPLETED\"] = \"completed\";\n SanctionedVersionChangeStatus[\"FAILED\"] = \"failed\";\n})(SanctionedVersionChangeStatus || (SanctionedVersionChangeStatus = {}));\n/**\n * During the loading of elements from PIE bundles, we do a trick where we make\n * editor components available as web components by appending this to the element name.\n */\nexport const editorPostFix = \"-pie-editor--\";\nexport class ModelUpdatedEvent extends CustomEvent {\n update;\n reset;\n static TYPE = \"model.updated\";\n constructor(update, reset = false) {\n super(ModelUpdatedEvent.TYPE, { bubbles: true, detail: { update, reset } });\n this.update = update;\n this.reset = reset;\n }\n}\nexport class DeleteImageEvent extends CustomEvent {\n src;\n done;\n static TYPE = \"delete.image\";\n constructor(src, done) {\n super(DeleteImageEvent.TYPE, { bubbles: true, detail: { src, done } });\n this.src = src;\n this.done = done;\n }\n}\nexport class InsertImageEvent extends CustomEvent {\n handler;\n static TYPE = \"insert.image\";\n constructor(handler) {\n super(InsertImageEvent.TYPE, { bubbles: true, detail: handler });\n this.handler = handler;\n }\n}\nexport class DeleteSoundEvent extends CustomEvent {\n src;\n done;\n static TYPE = \"delete.sound\";\n constructor(src, done) {\n super(DeleteSoundEvent.TYPE, { bubbles: true, detail: { src, done } });\n this.src = src;\n this.done = done;\n }\n}\nexport class InsertSoundEvent extends CustomEvent {\n handler;\n static TYPE = \"insert.sound\";\n constructor(handler) {\n super(InsertSoundEvent.TYPE, { bubbles: true, detail: handler });\n this.handler = handler;\n }\n}\nexport const isPassageEntity = (passage) => typeof passage === \"object\" && passage !== null;\nexport function isPrerelease(version) {\n return (typeof version === \"object\" &&\n version !== null &&\n typeof version.major === \"number\" &&\n typeof version.minor === \"number\" &&\n typeof version.patch === \"number\" &&\n !!version.prerelease && // Check if prerelease exists\n typeof version.prerelease.tag === \"string\" &&\n typeof version.prerelease.version === \"number\");\n}\nexport function formatVersion(semVer) {\n if (!semVer)\n return \"\";\n const base = [semVer.major, semVer.minor, semVer.patch].join(\".\");\n if (isPrerelease(semVer) && semVer.prerelease) {\n const prerelease = [semVer.prerelease.tag, semVer.prerelease.version].join(\".\");\n return `${base}-${prerelease}`;\n }\n return base;\n}\nexport class SessionChangedEvent extends CustomEvent {\n component;\n complete;\n static TYPE = \"session-changed\";\n constructor(component, complete) {\n super(SessionChangedEvent.TYPE, {\n bubbles: true,\n composed: true,\n detail: { complete, component },\n });\n this.component = component;\n this.complete = complete;\n }\n}\n// CMS Types (copied from @pie-api-aws/datastore to avoid importing server-only package)\nexport var StandardType;\n(function (StandardType) {\n StandardType[StandardType[\"ROOT\"] = 0] = \"ROOT\";\n StandardType[StandardType[\"SUBJECT\"] = 1] = \"SUBJECT\";\n StandardType[StandardType[\"LEVEL\"] = 2] = \"LEVEL\";\n StandardType[StandardType[\"STANDARD\"] = 3] = \"STANDARD\";\n})(StandardType || (StandardType = {}));\n//# sourceMappingURL=index.js.map","/**\n * PIE Logger Utility\n *\n * Simple, efficient logging for PIE players with debug mode support.\n * Uses browser console methods (debug, info, warn, error) which can be\n * filtered natively in browser dev tools.\n *\n * Usage:\n * ```typescript\n * const logger = createPieLogger('pie-item-player', debug);\n * logger.debug('Detailed debug info', data); // Only shown if debug=true\n * logger.info('Important production info'); // Always shown\n * logger.warn('Warning message'); // Always shown\n * logger.error('Error occurred', error); // Always shown\n * ```\n */\n/**\n * Create a PIE logger instance\n *\n * @param namespace - Component name for log prefixing (e.g., 'pie-item-player')\n * @param debugEnabledFn - Function that returns whether debug logs should be shown (checked dynamically on each call)\n * @returns Logger instance with debug, info, warn, error methods\n */\nexport function createPieLogger(namespace, debugEnabledFn) {\n const prefix = `[${namespace}]`;\n return {\n // Only debug method checks debugEnabledFn - it's checked dynamically on every call\n debug: (message, ...args) => {\n if (debugEnabledFn()) {\n console.debug(prefix, message, ...args);\n }\n },\n // info, warn, error always log (not gated by debug flag)\n info: (message, ...args) => console.info(prefix, message, ...args),\n warn: (message, ...args) => console.warn(prefix, message, ...args),\n error: (message, ...args) => console.error(prefix, message, ...args),\n };\n}\n/**\n * Check if debug mode is enabled globally\n */\nexport function isGlobalDebugEnabled() {\n return typeof window !== \"undefined\" && window.PIE_DEBUG === true;\n}\n//# sourceMappingURL=logger.js.map","/**\n * Math rendering bootstrap for PIE players\n *\n * PIE elements expect @pie-lib/math-rendering to be available on window.\n * This module ensures required globals are populated from the upstream\n * @pie-lib/math-rendering-module package, and also supports overriding with\n * a custom renderer object when needed.\n */\n/// <reference path=\"../shims.d.ts\" />\nimport { createPieLogger, isGlobalDebugEnabled } from \"./logger.js\";\nconst GLOBAL_KEY = \"@pie-lib/math-rendering\";\nconst GLOBAL_DLL_KEY = \"_dll_pie_lib__math_rendering\";\nlet initPromise = null;\nconst logger = createPieLogger(\"math-rendering\", () => isGlobalDebugEnabled());\nconst getWindowRenderer = () => {\n if (typeof window === \"undefined\") {\n return null;\n }\n const renderer = window[GLOBAL_KEY];\n return renderer || null;\n};\nconst setWindowRenderer = (renderer) => {\n if (typeof window === \"undefined\")\n return;\n window[GLOBAL_KEY] = renderer;\n window[GLOBAL_DLL_KEY] = renderer;\n};\n/**\n * Initialize math rendering with optional custom renderer\n *\n * If no custom renderer is provided, defaults to MathJax.\n * For custom renderers, use setMathRenderer() before calling this function.\n *\n * Sets TWO window globals that PIE elements expect:\n * - window[\"@pie-lib/math-rendering\"] (standard key)\n * - window[\"_dll_pie_lib__math_rendering\"] (SystemJS/DLL key for IIFE bundles)\n *\n * @param customRenderer - Optional custom renderer to use instead of default MathJax\n *\n * @example\n * ```typescript\n * // Default MathJax\n * await initializeMathRendering();\n *\n * // Custom renderer instance implementing MathRenderingAPI\n * const customRenderer = await createCustomRenderer();\n * await initializeMathRendering(customRenderer);\n *\n * // Or use setMathRenderer first\n * setMathRenderer(katexRenderer);\n * await initializeMathRendering();\n * ```\n */\nexport async function initializeMathRendering(customRenderer) {\n // Only run in browser\n if (typeof window === \"undefined\") {\n return;\n }\n // Explicit override always wins.\n if (customRenderer) {\n setWindowRenderer(customRenderer);\n return;\n }\n // Already initialized - skip.\n if (getWindowRenderer()) {\n return;\n }\n if (initPromise) {\n await initPromise;\n return;\n }\n initPromise = (async () => {\n try {\n const { _dll_pie_lib__math_rendering } = await import(\"@pie-lib/math-rendering-module/module\");\n setWindowRenderer(_dll_pie_lib__math_rendering);\n logger.debug(\"Math rendering module initialized (both globals set)\");\n }\n catch (error) {\n logger.error(\"Failed to initialize math rendering:\", error);\n throw error;\n }\n })();\n try {\n await initPromise;\n }\n finally {\n initPromise = null;\n }\n}\n/**\n * Set custom math renderer programmatically\n *\n * Call this BEFORE initializeMathRendering() or any loader.load() calls\n * to override the default MathJax renderer.\n *\n * @param renderer - The renderer to use\n *\n * @example\n * ```typescript\n * import { setMathRenderer } from '@pie-players/pie-players-shared/pie';\n *\n * const renderer = await createCustomRenderer();\n * setMathRenderer(renderer);\n *\n * // Now load PIE elements - they'll use your custom renderer\n * await loader.load(config, document, needsControllers);\n * ```\n */\nexport function setMathRenderer(renderer) {\n setWindowRenderer(renderer);\n}\n/**\n * Render math in the given element\n *\n * Convenience wrapper that calls the active renderer's renderMath() function.\n * Typically called after PIE elements are rendered.\n *\n * @param element - The element to render math within\n */\nexport function renderMath(element) {\n const renderer = getWindowRenderer();\n if (renderer && typeof renderer.renderMath === \"function\") {\n renderer.renderMath(element);\n }\n}\n//# sourceMappingURL=math-rendering.js.map","/**\n * PIE Scoring Module\n *\n * Scoring and outcome calculation for PIE elements.\n */\nimport { createPieLogger, isGlobalDebugEnabled } from \"./logger.js\";\nimport { pieRegistry } from \"./registry.js\";\nimport { BundleType } from \"./types.js\";\nimport { findOrAddSession } from \"./utils.js\";\n// Create module-level logger (respects global debug flag - pass function for dynamic checking)\nconst logger = createPieLogger(\"pie-scoring\", () => isGlobalDebugEnabled());\n/**\n * Find the controller for a PIE element\n */\nexport const findPieController = (elementName) => {\n const registry = pieRegistry();\n logger.debug(`[findPieController] Looking for controller for: ${elementName}`);\n logger.debug(`[findPieController] Registry has entries for:`, Object.keys(registry));\n const entry = registry[elementName];\n if (!entry) {\n logger.error(`[findPieController] ❌ No registry entry found for element: ${elementName}`);\n logger.error(`[findPieController] Available element names:`, Object.keys(registry));\n logger.error(`[findPieController] Full registry:`, registry);\n return undefined;\n }\n logger.debug(`[findPieController] Found registry entry for ${elementName}:`, {\n package: entry.package,\n tagName: entry.tagName,\n hasController: !!entry.controller,\n controllerKeys: entry.controller ? Object.keys(entry.controller) : [],\n bundleType: entry.bundleType,\n });\n const controller = entry.controller;\n if (!controller) {\n // Check if missing controller is expected based on bundle type\n if (entry.bundleType === BundleType.clientPlayer) {\n // client-player.js MUST have controllers\n logger.error(`[findPieController] ❌ CRITICAL: Registry entry exists for ${elementName} but controller is missing!`);\n logger.error(`[findPieController] Bundle type: ${entry.bundleType} (controllers required)`);\n logger.error(`[findPieController] Entry:`, entry);\n throw new Error(`No controller found for ${elementName}. client-player.js bundles MUST include controllers. Check bundle loading and registration.`);\n }\n else {\n // player.js doesn't have controllers - this is expected\n logger.debug(`[findPieController] ℹ️ No controller for ${elementName} - using server-processed models (player.js bundle)`);\n }\n }\n else {\n logger.debug(`[findPieController] ✅ Controller found for ${elementName} with functions:`, Object.keys(controller));\n }\n return controller;\n};\nconst escapeAttributeSelectorValue = (value) => value\n .replace(/\\\\/g, \"\\\\\\\\\")\n .replace(/\"/g, '\\\\\"')\n .replace(/\\n/g, \"\\\\a \")\n .replace(/\\r/g, \"\\\\d \");\nconst findRenderedPieElement = (root, modelId) => {\n const escapedId = escapeAttributeSelectorValue(modelId);\n return (root.querySelector(`[id=\"${escapedId}\"]`) ||\n root.querySelector(`[pie-id=\"${escapedId}\"]`));\n};\nconst invokeOutcome = async (controller, model, session, env, argumentShape) => {\n if (argumentShape === \"model-session-env\") {\n const outcome = controller.outcome;\n return outcome.call(controller, model, session, env);\n }\n const outcome = controller.outcome;\n return outcome.call(controller, session, env);\n};\n/**\n * Score a PIE item by calling outcome on all PIE elements\n */\nexport async function scorePieItem(config, sessionData, options = {}) {\n const root = options.container ?? document;\n const models = options.models ?? config.models ?? [];\n const outcomeArguments = options.outcomeArguments ?? \"session-env\";\n const scoringEnv = {\n ...options.env,\n mode: \"evaluate\",\n partialScoring: options.env?.partialScoring,\n };\n const r = await Promise.all(models.map(async (model) => {\n const pieEl = findRenderedPieElement(root, model.id);\n logger.debug(\"found pieEl %O for model id %s\", pieEl, model.id);\n const session = findOrAddSession(sessionData, model.id, model.element);\n if (pieEl) {\n const controller = findPieController(pieEl.localName);\n if (controller?.outcome) {\n return {\n ...session,\n ...(await invokeOutcome(controller, model, session, scoringEnv, outcomeArguments)),\n };\n }\n else {\n logger.debug(\"ignore %s (no controller)\", pieEl.localName);\n }\n }\n else {\n logger.debug(\"ignore %s (no element found for %s)\", model.id);\n }\n return undefined;\n }));\n logger.debug(\"scorePieItem result\", r);\n return {\n results: options.includeMissingResults\n ? r\n : r.filter(Boolean),\n };\n}\n//# sourceMappingURL=scoring.js.map","/**\n * PIE Updates Module\n *\n * Functions for updating PIE elements with new models, sessions, and env.\n */\nimport { mergeObjectsIgnoringNullUndefined } from \"../object/index.js\";\nimport { wrapModelRichContent } from \"../security/wrap-model-rich-content.js\";\nimport { createPieLogger, isGlobalDebugEnabled } from \"./logger.js\";\nimport { findPieController } from \"./scoring.js\";\nimport { defaultPieElementOptions } from \"./types.js\";\nimport { findOrAddSession } from \"./utils.js\";\n// Create module-level logger (respects global debug flag - pass function for dynamic checking)\nconst logger = createPieLogger(\"pie-updates\", () => isGlobalDebugEnabled());\nconst describeControllerShape = (controller) => {\n if (!controller)\n return \"missing\";\n if (typeof controller === \"function\")\n return \"function\";\n if (typeof controller !== \"object\")\n return typeof controller;\n const keys = Object.keys(controller);\n const defaultValue = controller.default;\n const defaultKeys = defaultValue && typeof defaultValue === \"object\"\n ? Object.keys(defaultValue)\n : [];\n return defaultKeys.length > 0\n ? `object(keys=[${keys.join(\",\")}],defaultKeys=[${defaultKeys.join(\",\")}])`\n : `object(keys=[${keys.join(\",\")}])`;\n};\nconst resolveControllerModelFunction = (controller) => {\n if (!controller)\n return null;\n if (typeof controller === \"function\") {\n return controller;\n }\n if (typeof controller !== \"object\")\n return null;\n const direct = controller.model;\n if (typeof direct === \"function\") {\n return (model, sessionData, env, updateSession) => direct.call(controller, model, sessionData, env, updateSession);\n }\n const fromDefault = controller.default;\n if (fromDefault && typeof fromDefault === \"object\") {\n const nested = fromDefault.model;\n if (typeof nested === \"function\") {\n return (model, sessionData, env, updateSession) => nested.call(fromDefault, model, sessionData, env, updateSession);\n }\n }\n return null;\n};\nconst emitControllerError = (pieElement, detail) => {\n pieElement.dispatchEvent(new CustomEvent(\"pie-controller-error\", {\n detail,\n bubbles: true,\n composed: true,\n }));\n};\n/**\n * Helper function to apply controller to element\n * Extracted to eliminate duplication and ensure consistent controller invocation\n */\nconst applyControllerToElement = async (element, model, elementSession, controller, env, logPrefix, onElementSessionUpdate) => {\n logger.debug(`${logPrefix} Using controller, env:`, env);\n logger.debug(`${logPrefix} Model before filter:`, {\n id: model.id,\n element: model.element,\n hasCorrectResponse: \"correctResponse\" in model,\n });\n // Create updateSession callback for controller to save derived state (e.g.\n // shuffle order). Mutate the in-flight element session so this render uses it,\n // AND propagate the write to the authoritative session via the host callback\n // so subsequent renders reuse it instead of regenerating it. The write-back is\n // keyed by the canonical model id/element (the entry findOrAddSession resolved),\n // which also tolerates controllers that pass an undefined id/element.\n const updateSession = (id, _elementName, properties) => {\n logger.debug(`${logPrefix} updateSession called for ${id} with:`, properties);\n Object.assign(elementSession, properties);\n onElementSessionUpdate?.(model.id, model.element, properties);\n return Promise.resolve();\n };\n try {\n const modelFunction = resolveControllerModelFunction(controller);\n if (!modelFunction) {\n throw new Error(`Controller contract mismatch: expected a model() function but received ${describeControllerShape(controller)}`);\n }\n const controllerResult = await modelFunction(model, elementSession, env, updateSession);\n // Merge controller result with id and element (like server-side PieControllerExecutor does)\n const controllerResultObject = controllerResult && typeof controllerResult === \"object\"\n ? controllerResult\n : {};\n const filteredModel = {\n id: model.id,\n element: model.element,\n ...controllerResultObject,\n };\n const wrappedModel = wrapModelRichContent(filteredModel);\n logger.debug(`${logPrefix} ✅ Controller filtered model:`, {\n id: wrappedModel.id,\n element: wrappedModel.element,\n hasCorrectResponse: \"correctResponse\" in wrappedModel,\n mode: env.mode,\n role: env.role,\n });\n element.model = wrappedModel;\n element.session = elementSession;\n }\n catch (err) {\n logger.error(`${logPrefix} ❌ Controller error:`, err);\n throw err; // Re-throw - controller errors are fatal\n }\n};\nconst resolveAndValidateUpdateOptions = (opts) => {\n const { config, session, env, eventListeners, invokeControllerForModel, onElementSessionUpdate, } = mergeObjectsIgnoringNullUndefined(defaultPieElementOptions, opts);\n if (!env) {\n throw new Error(\"env is required\");\n }\n if (!session) {\n throw new Error(\"session is required\");\n }\n if (!config) {\n throw new Error(\"config is required\");\n }\n return {\n config,\n session,\n env,\n eventListeners,\n invokeControllerForModel,\n onElementSessionUpdate,\n };\n};\nconst updateSinglePieElement = async (pieElement, controllerLookupTag, options, logContext) => {\n const { config, session, env, eventListeners, invokeControllerForModel, onElementSessionUpdate, } = options;\n const model = config.models?.find((m) => m.id === pieElement.id);\n if (!model) {\n logger.error(`${logContext} Model not found for`, controllerLookupTag);\n throw new Error(`model not found for ${controllerLookupTag}`);\n }\n const elementSession = findOrAddSession(session, model.id, model.element);\n // Always attach event listeners (don't skip them for no-controller case)\n if (eventListeners) {\n Object.entries(eventListeners).forEach(([evt, fn]) => {\n pieElement.addEventListener(evt, fn);\n });\n }\n if (env && invokeControllerForModel) {\n const controller = findPieController(controllerLookupTag);\n if (!controller) {\n logger.debug(`${logContext} ℹ️ No controller for ${controllerLookupTag}, using server-processed model`);\n pieElement.model = wrapModelRichContent(model);\n pieElement.session = elementSession;\n return;\n }\n logger.debug(`${logContext} Invoking controller for ${controllerLookupTag}#${pieElement.id}`, {\n mode: env.mode,\n role: env.role,\n hasCorrectResponse: \"correctResponse\" in model,\n });\n // Await the controller so any updateSession write-back completes before the\n // caller computes/emits the session signature; otherwise a late, async\n // shuffle write lands after the cycle that read the session and the order\n // never round-trips (PIE-631).\n try {\n await applyControllerToElement(pieElement, model, elementSession, controller, env, `${logContext}(${controllerLookupTag}#${pieElement.id})`, onElementSessionUpdate);\n }\n catch (err) {\n const errorMessage = err instanceof Error ? err.message : String(err);\n const isContractError = errorMessage.includes(\"Controller contract mismatch\");\n logger.error(`${logContext} Controller failed for ${controllerLookupTag}#${pieElement.id}:`, err);\n emitControllerError(pieElement, {\n code: isContractError\n ? \"PIE_CONTROLLER_CONTRACT_ERROR\"\n : \"PIE_CONTROLLER_RUNTIME_ERROR\",\n message: `${controllerLookupTag} controller failed while applying model for ${pieElement.id}. ${errorMessage}`,\n elementName: controllerLookupTag,\n elementId: pieElement.id,\n controllerShape: describeControllerShape(controller),\n cause: errorMessage,\n });\n // Fall back to raw model on controller error\n pieElement.model = wrapModelRichContent(model);\n pieElement.session = elementSession;\n }\n }\n else {\n logger.debug(`${logContext} Direct model assignment for ${controllerLookupTag}#${pieElement.id} (no controller invocation requested)`);\n pieElement.model = wrapModelRichContent(model);\n pieElement.session = elementSession;\n }\n};\n/**\n * Update a PIE element by ref (direct Element reference)\n */\nexport const updatePieElementWithRef = (el, opts) => {\n const options = resolveAndValidateUpdateOptions(opts);\n const pieElement = el;\n const elName = pieElement.tagName.toLowerCase();\n return updateSinglePieElement(pieElement, elName, options, \"[updatePieElementWithRef]\");\n};\n/**\n * Update a PIE element by name (finds all matching elements in DOM)\n */\nexport const updatePieElement = (elName, opts) => {\n const options = resolveAndValidateUpdateOptions(opts);\n const { container } = mergeObjectsIgnoringNullUndefined(defaultPieElementOptions, opts);\n // Use container for scoped query or fallback to document for global query\n const searchRoot = container || document;\n const pieElements = searchRoot.querySelectorAll(elName);\n if (!pieElements || pieElements.length === 0) {\n logger.debug(`no elements found for ${elName}`);\n return Promise.resolve();\n }\n return Promise.all(Array.from(pieElements, (el) => updateSinglePieElement(el, elName, options, \"[updatePieElement]\"))).then(() => undefined);\n};\n/**\n * Update all PIE elements in a config\n */\nexport const updatePieElements = (config, session, env, container, onElementSessionUpdate) => {\n logger.debug(\"[updatePieElements] Updating all elements with env:\", env);\n return Promise.all(Object.entries(config.elements).map(([elName, _pkg]) => updatePieElement(elName, {\n config,\n session,\n env,\n container,\n onElementSessionUpdate,\n }))).then(() => undefined);\n};\n//# sourceMappingURL=updates.js.map","/**\n * PIE Initialization Module\n *\n * Bundle loading and element initialization logic.\n * This is the core of the PIE player system.\n */\nimport { BUILDER_BUNDLE_URL } from \"../config/profile.js\";\nimport { mergeObjectsIgnoringNullUndefined } from \"../object/index.js\";\nimport { wrapModelRichContent } from \"../security/wrap-model-rich-content.js\";\nimport { editorPostFix } from \"../types/index.js\";\nimport { createPieLogger, isGlobalDebugEnabled } from \"./logger.js\";\nimport { initializeMathRendering } from \"./math-rendering.js\";\nimport { pieRegistry } from \"./registry.js\";\nimport { findPieController } from \"./scoring.js\";\nimport { defineCustomElementSafely } from \"./custom-element-define.js\";\nimport { validateCustomElementTag } from \"./tag-names.js\";\nimport { BundleType, isCustomElementConstructor, isPieAvailable, Status, } from \"./types.js\";\nimport { updatePieElement } from \"./updates.js\";\nimport { findOrAddSession, getPackageWithoutVersion, getPieElementBundlesUrl, } from \"./utils.js\";\n// Create module-level logger (respects global debug flag - pass function for dynamic checking)\nconst logger = createPieLogger(\"pie-initialization\", () => isGlobalDebugEnabled());\n// Default options for loading PIE elements\nconst defaultOptions = {\n buildServiceBase: BUILDER_BUNDLE_URL,\n bundleType: BundleType.player, // Default to player.js (no controllers, server-processed models)\n env: { mode: \"gather\", role: \"student\" },\n};\n/**\n * Helper function to initialize a PIE element\n */\nconst initializePieElement = (element, options) => {\n const { config, session, env, eventListeners } = options;\n if (element.__pieInitialized) {\n return;\n }\n const tagName = element.tagName.toLowerCase();\n logger.debug(`[initializePieElement] Initializing ${tagName}#${element.id}`);\n // Find model for this element\n let model = config?.models?.find((m) => m.id === element.id);\n if (!model) {\n // Only warn if this element is from a client-player.js bundle (where models are expected)\n // player.js bundles use server-processed models, so missing models are expected there\n const registry = pieRegistry();\n const registryEntry = registry[tagName];\n if (registryEntry && registryEntry.bundleType === BundleType.clientPlayer) {\n logger.warn(`[initializePieElement] Model not found for PIE element ${tagName}#${element.id} (client-player.js bundle)`);\n }\n return;\n }\n // Set session (with element property for updateSession callback)\n const elementSession = findOrAddSession(session, model.id, model.element);\n element.session = elementSession;\n element.__pieInitialized = true;\n logger.debug(`[initializePieElement] Session set for ${tagName}#${element.id}:`, elementSession);\n // Set model - use controller if available (client-player.js), or use server-processed model (player.js)\n const controller = findPieController(tagName);\n if (!env) {\n logger.error(`[initializePieElement] ❌ FATAL: No env provided for ${tagName}`);\n throw new Error(`No env provided for ${tagName}. PIE elements require an env object with mode and role.`);\n }\n if (!controller) {\n // No controller available - using server-processed model (player.js bundle)\n logger.debug(`[initializePieElement] ℹ️ No controller for ${tagName}, using server-processed model`);\n logger.debug(`[initializePieElement] Model already processed by server:`, {\n id: model.id,\n element: model.element,\n hasCorrectResponse: \"correctResponse\" in model,\n mode: env.mode,\n role: env.role,\n });\n // Set model directly - server already processed it\n element.model = wrapModelRichContent(model);\n }\n else {\n // Controller available - run client-side processing (client-player.js bundle)\n // Note: updatePieElementWithRef handles controller invocation\n logger.debug(`[initializePieElement] Controller found for ${tagName}, will invoke model() function`);\n }\n // Add event listeners\n if (eventListeners) {\n Object.entries(eventListeners).forEach(([evt, fn]) => {\n element.addEventListener(evt, fn);\n });\n }\n};\nconst getEditorElementTagName = (elementTagName, pkg) => validateCustomElementTag(elementTagName + editorPostFix, `editor element tag for ${pkg}`);\nconst updateRegisteredElement = (elementTagName, config, session, options, omitEnv = false) => {\n updatePieElement(elementTagName, {\n config,\n session,\n ...(omitEnv ? {} : { env: options.env }),\n container: options.container,\n ...(options.eventListeners?.[elementTagName] && {\n eventListeners: options.eventListeners[elementTagName],\n }),\n });\n};\n/**\n * Shared element registration logic\n * Extracted from initializePiesFromLoadedBundle and loadPieModule to eliminate ~200 lines of duplication\n * Also fixes MutationObserver memory leak by storing latest config/session in window context\n *\n * `elementModule` may be `null`. In that case we cannot register *new*\n * tags (no element constructor source), but we can still update tags\n * that another loader (e.g. the section-player's IIFE adapter) has\n * already registered with `customElements`. This is the common case\n * when `pie-item-player` mounts inside `pie-section-player`: the\n * section player has already pre-warmed the bundle through the deep\n * `ElementLoader` primitive, so the `window.pie.default` bundle-global\n * path is not required for those tags.\n */\nconst registerPieElementsFromBundle = (elementModule, config, session, registry, options) => {\n const promises = [];\n const isNodeWithinContainer = (node, container) => {\n if (!container || container === document)\n return true;\n return node instanceof Node && container.contains(node);\n };\n if (elementModule) {\n logger.debug(\"[registerPieElementsFromBundle] Available packages in bundle:\", Object.keys(elementModule));\n }\n else {\n logger.debug(\"[registerPieElementsFromBundle] No bundle module supplied; will only update tags already registered with customElements.\");\n }\n logger.debug(\"[registerPieElementsFromBundle] config.elements:\", config.elements);\n // Store latest config/session in window so MutationObserver can access current values\n if (typeof window !== \"undefined\") {\n window._pieCurrentContext = {\n config,\n session,\n env: options.env,\n container: options.container,\n };\n }\n Object.entries(config.elements).forEach(([elName, pkg]) => {\n const elementTagName = validateCustomElementTag(elName, `element tag in config.elements for ${String(pkg)}`);\n logger.debug(`[registerPieElementsFromBundle] Processing element: ${elementTagName} -> ${pkg}`);\n // Fast path — the tag is already registered with customElements\n // (typically by the host's pre-warm pipeline). We can update its\n // session/model bindings without needing the bundle module at all.\n // This branch is also the one that runs when `elementModule` is\n // `null` because `window.pie` was missing.\n if (customElements.get(elementTagName)) {\n updateRegisteredElement(elementTagName, config, session, options);\n if (options.bundleType === BundleType.editor) {\n const editorElName = getEditorElementTagName(elementTagName, String(pkg));\n updateRegisteredElement(editorElName, config, session, options, true);\n }\n return;\n }\n // From here on we are in the \"register a new tag\" branch, which\n // requires a bundle module to read the element constructor from.\n if (!elementModule) {\n // A missing bundle module + an unregistered tag is *not*\n // always an error: in the section-player composition the\n // host's own `ElementLoader` may register this tag\n // out-of-band moments later, in which case `updatePieElement`\n // will pick it up on the next reactive pass via the\n // MutationObserver / `whenDefined` paths. Log at warn so the\n // transient miss is still visible during diagnostics without\n // printing a red stack trace for a routine timing condition.\n logger.warn(`[registerPieElementsFromBundle] Skipping \"${elementTagName}\" — no bundle module available and the tag is not yet registered. Will bind on next update if the host's loader registers it.`);\n return;\n }\n const pkgStripped = getPackageWithoutVersion(pkg);\n logger.debug(`[registerPieElementsFromBundle] Package without version: \"${pkgStripped}\"`);\n const elementData = elementModule[pkgStripped];\n logger.debug(`[registerPieElementsFromBundle] elementData result:`, elementData ? \"FOUND\" : \"UNDEFINED\");\n if (!elementData) {\n logger.error(`[registerPieElementsFromBundle] ❌ Package \"${pkgStripped}\" not found in bundle!`);\n logger.error(`[registerPieElementsFromBundle] Lookup key: \"${pkgStripped}\"`);\n logger.error(`[registerPieElementsFromBundle] Available packages:`, Object.keys(elementModule));\n throw new Error(`pie ${pkgStripped} not found in ${Object.keys(elementModule)}`);\n }\n logger.debug(`[registerPieElementsFromBundle] elementData for ${pkgStripped}:`, {\n hasController: !!elementData.controller,\n hasElement: !!elementData.Element,\n hasConfig: !!elementData.config,\n controllerKeys: elementData.controller\n ? Object.keys(elementData.controller)\n : [],\n bundleType: options.bundleType,\n });\n // Validate controller presence based on bundle type\n if (!elementData.controller) {\n if (options.bundleType === BundleType.clientPlayer) {\n logger.error(`[registerPieElementsFromBundle] ❌ CRITICAL: No controller found for ${pkgStripped}!`);\n logger.error(`[registerPieElementsFromBundle] Bundle type: ${options.bundleType} (controllers required)`);\n throw new Error(`No controller found for ${pkgStripped}. client-player.js bundles MUST include controllers!`);\n }\n else {\n logger.debug(`[registerPieElementsFromBundle] ℹ️ No controller found for ${pkgStripped} - using server-processed models (player.js bundle)`);\n }\n }\n {\n // Register the element in our registry\n logger.debug(`[registerPieElementsFromBundle] Registering ${elName} in registry${elementData.controller\n ? \" with controller\"\n : \" (no controller - server-processed models)\"}`);\n registry[elementTagName] = {\n package: pkg,\n status: Status.loading,\n tagName: elementTagName,\n controller: elementData.controller || null,\n config: elementData.config,\n bundleType: options.bundleType,\n };\n if (isCustomElementConstructor(elementData.Element)) {\n defineCustomElementSafely(elementTagName, elementData.Element, `element tag in config.elements for ${String(pkg)}`);\n // Initialize existing elements\n const searchRoot = options.container || document;\n const elements = searchRoot.querySelectorAll(elementTagName);\n logger.debug(`[registerPieElementsFromBundle] Found ${elements.length} elements for tag '${elementTagName}'`);\n elements.forEach((el) => {\n initializePieElement(el, {\n config,\n session,\n env: options.env,\n eventListeners: options.eventListeners?.[elementTagName],\n });\n });\n // Update registry status\n registry[elementTagName] = {\n ...registry[elementTagName],\n status: Status.loaded,\n };\n promises.push(customElements.whenDefined(elementTagName).then(() => {\n logger.debug(\"[registerPieElementsFromBundle] defined custom PIE element: %s\", elementTagName);\n }));\n // Setup MutationObserver that uses current context (only once)\n if (!window._pieElementObserver) {\n window._pieElementObserver = new MutationObserver((mutations) => {\n // Use current context from window instead of stale closure\n const context = window._pieCurrentContext;\n if (!context) {\n logger.warn(\"[MutationObserver] No current context available\");\n return;\n }\n mutations.forEach((mutation) => {\n if (mutation.type === \"childList\") {\n mutation.addedNodes.forEach((node) => {\n if (node.nodeType === Node.ELEMENT_NODE) {\n if (!isNodeWithinContainer(node, context.container)) {\n return;\n }\n const tagName = node.tagName.toLowerCase();\n if (registry[tagName]) {\n initializePieElement(node, {\n config: context.config,\n session: context.session,\n env: context.env,\n eventListeners: options.eventListeners?.[tagName],\n });\n }\n // Check children of added nodes\n node\n .querySelectorAll(\"*\")\n .forEach((childNode) => {\n if (!isNodeWithinContainer(childNode, context.container)) {\n return;\n }\n const childTagName = childNode.tagName.toLowerCase();\n if (registry[childTagName]) {\n initializePieElement(childNode, {\n config: context.config,\n session: context.session,\n env: context.env,\n eventListeners: options.eventListeners?.[childTagName],\n });\n }\n });\n }\n });\n }\n });\n });\n window._pieElementObserver.observe(document.body, {\n childList: true,\n subtree: true,\n });\n }\n // Handle editor elements if needed\n if (options.bundleType === BundleType.editor) {\n if (isCustomElementConstructor(elementData.Configure)) {\n const editorElName = getEditorElementTagName(elementTagName, String(pkg));\n defineCustomElementSafely(editorElName, elementData.Configure, `editor element tag for ${String(pkg)}`);\n promises.push(customElements.whenDefined(editorElName).then(() => {\n logger.debug(`[registerPieElementsFromBundle] defined custom PIE editor element: ${editorElName}`);\n }));\n }\n else {\n logger.error(`[registerPieElementsFromBundle] pie.Configure for ${pkgStripped} is not a valid custom element constructor.`, elementData.configure);\n }\n }\n }\n else {\n logger.error(`[registerPieElementsFromBundle] pie.Element for ${pkgStripped} is not a valid custom element constructor.`);\n }\n }\n });\n return promises;\n};\n/**\n * Initialize PIE elements from a bundle that may already be loaded.\n *\n * `window.pie` is the IIFE bundle-loading global populated by\n * `loadPieModule` / `loadBundleFromString`. When the host loaded the\n * bundle through the deep `ElementLoader` primitive instead — as\n * `pie-section-player` does — the global is irrelevant: the loader\n * registers tags directly with `customElements`, so this function only\n * needs to bind models/sessions to whatever is already registered.\n *\n * Behavior:\n * - `window.pie` available → register any new tags from the bundle and\n * update bindings for already-registered tags.\n * - `window.pie` missing → fall back to the update-only path. Tags that\n * are already registered get their model/session updated; tags that\n * are not yet registered are logged at `warn` and left alone — the\n * host's loader is expected to register them imminently, after which\n * the existing `MutationObserver` / `updatePieElements` flow binds\n * them on the next reactive pass.\n *\n * The original blanket `window.pie not found; was the bundle inlined\n * correctly?` error has been removed: in the section-player + item-player\n * composition it produced a confusing red stack trace for a routine\n * timing condition that the host already handles. Genuine failures\n * (bundle not loaded by *anyone*) still surface — every unregistered tag\n * gets its own warning, and `updatePieElements` later reports any tag\n * that never resolves.\n */\nexport const initializePiesFromLoadedBundle = (config, session, opts = {}) => {\n const registry = pieRegistry();\n const options = mergeObjectsIgnoringNullUndefined(defaultOptions, opts);\n if (isPieAvailable(window)) {\n logger.debug(\"[initializePiesFromLoadedBundle] window.pie available\");\n const elementModule = window.pie.default;\n registerPieElementsFromBundle(elementModule, config, session, registry, options);\n return;\n }\n logger.debug(\"[initializePiesFromLoadedBundle] window.pie not present; using update-only path. Already-registered tags will be bound now; missing tags are expected to be registered by the host's loader and will bind on the next update pass.\");\n registerPieElementsFromBundle(null, config, session, registry, options);\n};\n/**\n * Load a PIE bundle from a URL and initialize elements\n */\nexport const loadPieModule = async (config, session, opts = {}) => {\n if (!session) {\n throw new Error(\"session is required\");\n }\n // Initialize math-rendering module (required by PIE elements)\n await initializeMathRendering();\n const registry = pieRegistry();\n const options = mergeObjectsIgnoringNullUndefined(defaultOptions, opts);\n const url = opts.bundleUrl || getPieElementBundlesUrl(config, options);\n const script = document.createElement(\"script\");\n script.src = url;\n script.defer = true;\n script.onerror = () => {\n throw new Error(`failed to load script: ${url}`);\n };\n const loadPromise = new Promise((loadResolve) => {\n script.addEventListener(\"load\", () => {\n logger.debug(\"[loadPieModule] Script loaded from:\", url);\n if (isPieAvailable(window)) {\n logger.debug(\"[loadPieModule] window.pie available\");\n const elementModule = window.pie.default;\n // Use shared registration logic (returns array of promises)\n const registrationPromises = registerPieElementsFromBundle(elementModule, config, session, registry, options);\n // Wait for all element definitions to complete\n Promise.all(registrationPromises).then(() => loadResolve());\n }\n else {\n logger.error(\"[loadPieModule] pie var not found; is %s a proper PIE IIFE module?\", url);\n loadResolve();\n }\n });\n });\n document.head.appendChild(script);\n await loadPromise;\n return { session };\n};\n/**\n * Load a PIE bundle from a JavaScript string into window.pie (IIFE bundles only)\n * This only registers elements and controllers - does NOT initialize them.\n * For initialization, use initializePiesFromLoadedBundle after loading.\n */\nexport const loadBundleFromString = async (bundleJs) => {\n await initializeMathRendering();\n await withBlobBundleUrl(bundleJs, { stripSourceMapComment: true }, async (bundleUrl) => {\n // Create a script tag to execute the bundle\n const script = document.createElement(\"script\");\n script.src = bundleUrl;\n script.type = \"text/javascript\"; // IIFE bundles are standard JS\n // Wait for script to load\n await new Promise((resolve, reject) => {\n script.onload = () => resolve();\n script.onerror = () => reject(new Error(\"Failed to load bundle\"));\n document.head.appendChild(script);\n });\n logger.debug(\"[loadBundleFromString] Bundle loaded into window.pie\");\n });\n};\n/**\n * Load a PIE bundle from a JavaScript string and initialize elements\n * Convenience wrapper around loadBundleFromString + loadPieModule\n */\nexport const loadPieModuleFromString = async (bundleJs, config, session, opts = {}) => {\n await withBlobBundleUrl(bundleJs, {}, async (bundleUrl) => {\n // Use existing loadPieModule with the blob URL\n await loadPieModule(config, session, { ...opts, bundleUrl });\n });\n};\nconst withBlobBundleUrl = async (bundleJs, options, run) => {\n const source = options.stripSourceMapComment\n ? bundleJs.replace(/\\/\\/# sourceMappingURL=.*$/m, \"\")\n : bundleJs;\n const blob = new Blob([source], { type: \"application/javascript\" });\n const bundleUrl = URL.createObjectURL(blob);\n try {\n return await run(bundleUrl);\n }\n finally {\n URL.revokeObjectURL(bundleUrl);\n }\n};\n//# sourceMappingURL=initialization.js.map","/**\n * Asset Handler Utilities\n *\n * Handles image and sound upload events for authoring mode.\n * Provides default DataURL-based implementation and event management.\n */\nimport { DeleteImageEvent, DeleteSoundEvent, InsertImageEvent, InsertSoundEvent, } from \"../types/index.js\";\nimport { createPieLogger, isGlobalDebugEnabled } from \"./logger.js\";\nconst logger = createPieLogger(\"asset-handler\", () => isGlobalDebugEnabled());\n/**\n * DataURL-based asset handler (default implementation)\n *\n * Converts uploaded files to base64 data URLs.\n * Suitable for demos and local development.\n */\nexport class DataURLAssetHandler {\n onComplete;\n cancelled = false;\n fileReader = null;\n constructor(onComplete) {\n this.onComplete = onComplete;\n }\n cancel() {\n this.cancelled = true;\n if (this.fileReader) {\n this.fileReader.abort();\n }\n logger.debug(\"[DataURLAssetHandler] Upload cancelled\");\n }\n done(err, src) {\n if (this.cancelled) {\n return;\n }\n if (err) {\n logger.error(\"[DataURLAssetHandler] Error during upload:\", err);\n // Optionally notify user of error\n return;\n }\n if (src) {\n logger.debug(\"[DataURLAssetHandler] Upload complete, src:\", src.substring(0, 50) + \"...\");\n this.onComplete(src);\n }\n }\n fileChosen(file) {\n if (this.cancelled) {\n return;\n }\n logger.debug(\"[DataURLAssetHandler] File chosen:\", file.name, file.type, file.size);\n this.fileReader = new FileReader();\n this.fileReader.onload = (e) => {\n const dataUrl = e.target?.result;\n logger.debug(\"[DataURLAssetHandler] File converted to data URL\");\n this.done(undefined, dataUrl);\n };\n this.fileReader.onerror = () => {\n logger.error(\"[DataURLAssetHandler] FileReader error\");\n this.done(new Error(\"Failed to read file\"));\n };\n this.fileReader.onprogress = (e) => {\n if (e.lengthComputable) {\n const percent = (e.loaded / e.total) * 100;\n this.progress(percent, e.loaded, e.total);\n }\n };\n this.fileReader.readAsDataURL(file);\n }\n progress(percent, bytes, total) {\n logger.debug(`[DataURLAssetHandler] Progress: ${percent.toFixed(1)}% (${bytes}/${total} bytes)`);\n // Could dispatch custom event here for progress UI\n }\n}\nfunction toError(value, fallback) {\n if (value instanceof Error) {\n return value;\n }\n return new Error(String(value ?? fallback));\n}\nfunction createOnceCompletion(handler, dataURLHandler) {\n let settled = false;\n const originalDone = handler.done;\n const originalCancel = handler.cancel;\n const done = (err, src) => {\n if (settled) {\n return;\n }\n settled = true;\n if (err) {\n try {\n originalCancel?.();\n }\n catch (cancelError) {\n logger.error(\"[asset-handler] cancel callback failed:\", cancelError);\n }\n dataURLHandler.cancel();\n }\n try {\n originalDone?.(err, src);\n }\n catch (doneError) {\n logger.error(\"[asset-handler] done callback failed:\", doneError);\n }\n };\n const cancel = () => {\n if (settled) {\n return;\n }\n settled = true;\n try {\n originalCancel?.();\n }\n catch (cancelError) {\n logger.error(\"[asset-handler] cancel callback failed:\", cancelError);\n }\n dataURLHandler.cancel();\n };\n handler.done = done;\n handler.cancel = cancel;\n return {\n done,\n cancel,\n isSettled: () => settled,\n };\n}\nfunction pickFileWithDialogLifecycle(accept, onCancel) {\n return new Promise((resolve) => {\n const input = document.createElement(\"input\");\n input.type = \"file\";\n input.accept = accept;\n let resolved = false;\n let changeHandled = false;\n let dialogOpened = false;\n const cleanup = () => {\n input.onchange = null;\n window.removeEventListener(\"focus\", onFocus);\n input.removeEventListener(\"cancel\", onCancelEvent);\n };\n const finalize = (file) => {\n if (resolved) {\n return;\n }\n resolved = true;\n cleanup();\n resolve(file);\n };\n const onFocus = () => {\n if (!dialogOpened || changeHandled) {\n return;\n }\n dialogOpened = false;\n window.setTimeout(() => {\n if (changeHandled || resolved) {\n return;\n }\n const file = input.files?.[0] ?? null;\n if (!file) {\n onCancel();\n }\n finalize(file);\n }, 300);\n };\n const onCancelEvent = () => {\n onCancel();\n finalize(null);\n };\n input.onchange = () => {\n changeHandled = true;\n dialogOpened = false;\n finalize(input.files?.[0] ?? null);\n };\n input.addEventListener(\"cancel\", onCancelEvent);\n window.addEventListener(\"focus\", onFocus);\n dialogOpened = true;\n input.click();\n });\n}\nfunction getPastedFile(handler) {\n if (!handler.isPasted || typeof handler.getChosenFile !== \"function\") {\n return null;\n }\n try {\n return handler.getChosenFile() ?? null;\n }\n catch (error) {\n logger.error(\"[asset-handler] Failed to read pasted file\", error);\n return null;\n }\n}\n/**\n * Asset Event Manager\n *\n * Manages asset-related event listeners for configure elements.\n * Handles InsertImageEvent, DeleteImageEvent, InsertSoundEvent, DeleteSoundEvent.\n */\nexport class AssetEventManager {\n element;\n onInsertImage;\n onDeleteImage;\n onInsertSound;\n onDeleteSound;\n listeners = [];\n constructor(element, onInsertImage, onDeleteImage, onInsertSound, onDeleteSound) {\n this.element = element;\n this.onInsertImage = onInsertImage;\n this.onDeleteImage = onDeleteImage;\n this.onInsertSound = onInsertSound;\n this.onDeleteSound = onDeleteSound;\n }\n /**\n * Attach event listeners\n */\n attach() {\n logger.debug(\"[AssetEventManager] Attaching event listeners\");\n // Insert Image Event\n if (this.onInsertImage) {\n const insertImageHandler = (e) => {\n const event = e;\n logger.debug(\"[AssetEventManager] InsertImageEvent received\");\n this.onInsertImage(event.detail);\n };\n this.element.addEventListener(InsertImageEvent.TYPE, insertImageHandler);\n this.listeners.push({\n type: InsertImageEvent.TYPE,\n handler: insertImageHandler,\n });\n }\n // Delete Image Event\n if (this.onDeleteImage) {\n const deleteImageHandler = (e) => {\n const event = e;\n logger.debug(\"[AssetEventManager] DeleteImageEvent received, src:\", event.detail.src);\n this.onDeleteImage(event.detail.src, event.detail.done);\n };\n this.element.addEventListener(DeleteImageEvent.TYPE, deleteImageHandler);\n this.listeners.push({\n type: DeleteImageEvent.TYPE,\n handler: deleteImageHandler,\n });\n }\n // Insert Sound Event\n if (this.onInsertSound) {\n const insertSoundHandler = (e) => {\n const event = e;\n logger.debug(\"[AssetEventManager] InsertSoundEvent received\");\n this.onInsertSound(event.detail);\n };\n this.element.addEventListener(InsertSoundEvent.TYPE, insertSoundHandler);\n this.listeners.push({\n type: InsertSoundEvent.TYPE,\n handler: insertSoundHandler,\n });\n }\n // Delete Sound Event\n if (this.onDeleteSound) {\n const deleteSoundHandler = (e) => {\n const event = e;\n logger.debug(\"[AssetEventManager] DeleteSoundEvent received, src:\", event.detail.src);\n this.onDeleteSound(event.detail.src, event.detail.done);\n };\n this.element.addEventListener(DeleteSoundEvent.TYPE, deleteSoundHandler);\n this.listeners.push({\n type: DeleteSoundEvent.TYPE,\n handler: deleteSoundHandler,\n });\n }\n logger.debug(\"[AssetEventManager] Attached\", this.listeners.length, \"event listeners\");\n }\n /**\n * Detach event listeners (cleanup)\n */\n detach() {\n logger.debug(\"[AssetEventManager] Detaching event listeners\");\n this.listeners.forEach(({ type, handler }) => {\n this.element.removeEventListener(type, handler);\n });\n this.listeners = [];\n logger.debug(\"[AssetEventManager] All event listeners detached\");\n }\n}\n/**\n * Create default image insert handler using DataURL conversion\n */\nexport function createDefaultImageInsertHandler(onComplete) {\n return (handler) => {\n logger.debug(\"[createDefaultImageInsertHandler] Creating DataURL handler\");\n let completion = null;\n const dataURLHandler = new DataURLAssetHandler((src) => {\n onComplete(src);\n completion?.done(undefined, src);\n });\n completion = createOnceCompletion(handler, dataURLHandler);\n const finishCancelled = () => {\n completion?.done(new Error(\"Image selection cancelled\"));\n };\n const handleChosenFile = (file) => {\n if (!file) {\n finishCancelled();\n return;\n }\n try {\n handler.fileChosen(file);\n }\n catch (error) {\n logger.error(\"[createDefaultImageInsertHandler] fileChosen failed\", error);\n completion?.done(toError(error, \"Image fileChosen failed\"));\n return;\n }\n try {\n dataURLHandler.fileChosen(file);\n }\n catch (error) {\n completion?.done(toError(error, \"Image upload failed\"));\n }\n };\n const pastedFile = getPastedFile(handler);\n if (pastedFile) {\n handleChosenFile(pastedFile);\n return;\n }\n if (handler.isPasted) {\n completion?.done(new Error(\"Pasted image is unavailable\"));\n return;\n }\n void pickFileWithDialogLifecycle(\"image/*\", finishCancelled)\n .then((file) => {\n if (completion?.isSettled()) {\n return;\n }\n handleChosenFile(file);\n })\n .catch((error) => {\n completion?.done(toError(error, \"Image selection failed\"));\n });\n };\n}\n/**\n * Create default sound insert handler using DataURL conversion\n */\nexport function createDefaultSoundInsertHandler(onComplete) {\n return (handler) => {\n logger.debug(\"[createDefaultSoundInsertHandler] Creating DataURL handler\");\n let completion = null;\n const dataURLHandler = new DataURLAssetHandler((src) => {\n onComplete(src);\n completion?.done(undefined, src);\n });\n const handlerLike = handler;\n completion = createOnceCompletion(handlerLike, dataURLHandler);\n const finishCancelled = () => {\n completion?.done(new Error(\"Sound selection cancelled\"));\n };\n const handleChosenFile = (file) => {\n if (!file) {\n finishCancelled();\n return;\n }\n // Some handlers expose fileChosen as function, while others store file directly.\n const maybeFileChosen = handlerLike.fileChosen;\n if (typeof maybeFileChosen === \"function\") {\n try {\n maybeFileChosen(file);\n }\n catch (error) {\n logger.error(\"[createDefaultSoundInsertHandler] fileChosen failed\", error);\n completion?.done(toError(error, \"Sound fileChosen failed\"));\n return;\n }\n }\n try {\n dataURLHandler.fileChosen(file);\n }\n catch (error) {\n completion?.done(toError(error, \"Sound upload failed\"));\n }\n };\n const pastedFile = getPastedFile(handlerLike);\n if (pastedFile) {\n handleChosenFile(pastedFile);\n return;\n }\n if (handlerLike.isPasted) {\n completion?.done(new Error(\"Pasted sound is unavailable\"));\n return;\n }\n void pickFileWithDialogLifecycle(\"audio/*\", finishCancelled)\n .then((file) => {\n if (completion?.isSettled()) {\n return;\n }\n handleChosenFile(file);\n })\n .catch((error) => {\n completion?.done(toError(error, \"Sound selection failed\"));\n });\n };\n}\n/**\n * Create default image delete handler (no-op for DataURL)\n */\nexport function createDefaultImageDeleteHandler() {\n return (src, done) => {\n logger.debug(\"[createDefaultImageDeleteHandler] Delete requested for:\", src.substring(0, 50));\n // For DataURL, no server-side deletion needed\n done(); // Success\n };\n}\n/**\n * Create default sound delete handler (no-op for DataURL)\n */\nexport function createDefaultSoundDeleteHandler() {\n return (src, done) => {\n logger.debug(\"[createDefaultSoundDeleteHandler] Delete requested for:\", src.substring(0, 50));\n // For DataURL, no server-side deletion needed\n done(); // Success\n };\n}\n//# sourceMappingURL=asset-handler.js.map","import { AssetEventManager } from \"./asset-handler.js\";\nimport { createPieLogger, isGlobalDebugEnabled } from \"./logger.js\";\nimport { findPieController } from \"./scoring.js\";\nimport { parsePackageName } from \"./utils.js\";\nconst logger = createPieLogger(\"authoring\", () => isGlobalDebugEnabled());\nfunction isRecord(value) {\n return !!value && typeof value === \"object\" && !Array.isArray(value);\n}\nfunction packageNameWithoutVersion(packageSpec) {\n try {\n return parsePackageName(packageSpec).name;\n }\n catch {\n return packageSpec;\n }\n}\nfunction packageBaseName(packageName) {\n const lastSegment = packageName.split(\"/\").pop();\n return lastSegment || packageName;\n}\nfunction lookupOwn(source, keys) {\n if (!isRecord(source))\n return undefined;\n for (const key of keys) {\n if (Object.hasOwn(source, key)) {\n return source[key];\n }\n }\n return undefined;\n}\nfunction mergeConfiguration(deliveryConfig, authoringConfig) {\n if (authoringConfig === undefined) {\n return deliveryConfig ?? {};\n }\n if (isRecord(deliveryConfig) && isRecord(authoringConfig)) {\n return {\n ...deliveryConfig,\n ...authoringConfig,\n };\n }\n return authoringConfig;\n}\nexport function resolveConfigureConfiguration(configuration, elementTag, packageSpec) {\n const versionlessPackageName = packageNameWithoutVersion(packageSpec);\n const basePackageName = packageBaseName(versionlessPackageName);\n const deliveryConfig = lookupOwn(configuration, [\n packageSpec,\n versionlessPackageName,\n elementTag,\n ]);\n const authoringConfig = lookupOwn(configuration?.authoring, [\n elementTag,\n packageSpec,\n versionlessPackageName,\n basePackageName,\n ]);\n return mergeConfiguration(deliveryConfig, authoringConfig);\n}\nfunction findModelForConfigureElement(models, configureElement) {\n const modelId = configureElement.id;\n if (!modelId)\n return undefined;\n return models.find((model) => model.id === modelId);\n}\nfunction queryConfigureElements(container, configureTag) {\n return Array.from(container.querySelectorAll(configureTag));\n}\nexport function initializeAuthoringConfigures(config, configuration = {}, options) {\n const container = options.container ?? document;\n const initializedModels = [];\n logger.debug(\"[initializeAuthoringConfigures] Starting initialization\");\n logger.debug(\"[initializeAuthoringConfigures] Config:\", config);\n logger.debug(\"[initializeAuthoringConfigures] Configuration:\", configuration);\n logger.debug(\"[initializeAuthoringConfigures] Env:\", options.env);\n if (!config?.elements || !config?.models) {\n logger.warn(\"[initializeAuthoringConfigures] Invalid config - missing elements or models\");\n return initializedModels;\n }\n for (const [elementTag, packageSpec] of Object.entries(config.elements)) {\n const configureTag = `${elementTag}-config`;\n const elements = queryConfigureElements(container, configureTag);\n logger.debug(`[initializeAuthoringConfigures] Found ${elements.length} ${configureTag} elements`);\n for (const element of elements) {\n const model = findModelForConfigureElement(config.models, element);\n if (!model) {\n logger.warn(`[initializeAuthoringConfigures] No model found for ${configureTag}#${element.id || \"(missing-id)\"}`);\n continue;\n }\n const configureElement = element;\n const elementConfiguration = resolveConfigureConfiguration(configuration, elementTag, String(packageSpec));\n configureElement.model = model;\n configureElement.configuration = elementConfiguration;\n initializedModels.push({\n id: model.id,\n element: model.element,\n configureTag,\n configuration: elementConfiguration,\n });\n logger.debug(`[initializeAuthoringConfigures] Model and configuration set for ${configureTag}#${model.id}`, elementConfiguration);\n }\n }\n logger.debug(\"[initializeAuthoringConfigures] Initialization complete\");\n return initializedModels;\n}\nfunction resolveValidationController(configureElement) {\n return findPieController(configureElement.localName);\n}\nfunction hasValidationErrors(validation) {\n if (!validation || typeof validation !== \"object\")\n return false;\n const validationRecord = validation;\n if (validationRecord.hasErrors === true)\n return true;\n const errors = validationRecord.errors;\n return Array.isArray(errors) && errors.length > 0;\n}\nexport async function validateAuthoringModels(config, configuration = {}, options = {}) {\n const container = options.container ?? document;\n const validatedModels = [];\n if (!config?.elements || !config?.models) {\n return { hasErrors: false, validatedModels };\n }\n for (const [elementTag, packageSpec] of Object.entries(config.elements)) {\n const configureTag = `${elementTag}-config`;\n const elements = queryConfigureElements(container, configureTag);\n for (const element of elements) {\n const model = findModelForConfigureElement(config.models, element);\n if (!model)\n continue;\n const controller = resolveValidationController(element);\n const elementConfiguration = resolveConfigureConfiguration(configuration, elementTag, String(packageSpec));\n const validation = typeof controller?.validate === \"function\"\n ? await controller.validate(model, elementConfiguration)\n : undefined;\n validatedModels.push({\n ...model,\n ...(isRecord(validation) ? validation : {}),\n id: model.id,\n element: model.element,\n validation,\n });\n }\n }\n return {\n hasErrors: validatedModels.some((model) => hasValidationErrors(model.validation)),\n validatedModels,\n };\n}\nfunction toError(value) {\n return value instanceof Error\n ? value\n : new Error(String(value ?? \"Unknown authoring error\"));\n}\nexport function createAuthoringAssetEventManager(rootElement, handlers, onHandlerError) {\n return new AssetEventManager(rootElement, handlers.onInsertImage\n ? (handler) => {\n try {\n handlers.onInsertImage?.(handler);\n }\n catch (error) {\n const err = toError(error);\n onHandlerError(\"onInsertImage\", err);\n handler.done(err);\n }\n }\n : undefined, handlers.onDeleteImage\n ? (src, done) => {\n try {\n handlers.onDeleteImage?.(src, done);\n }\n catch (error) {\n const err = toError(error);\n onHandlerError(\"onDeleteImage\", err);\n done(err);\n }\n }\n : undefined, handlers.onInsertSound\n ? (handler) => {\n try {\n handlers.onInsertSound?.(handler);\n }\n catch (error) {\n const err = toError(error);\n onHandlerError(\"onInsertSound\", err);\n handler.done(err);\n }\n }\n : undefined, handlers.onDeleteSound\n ? (src, done) => {\n try {\n handlers.onDeleteSound?.(src, done);\n }\n catch (error) {\n const err = toError(error);\n onHandlerError(\"onDeleteSound\", err);\n done(err);\n }\n }\n : undefined);\n}\n//# sourceMappingURL=authoring.js.map","import { isInstrumentationProvider } from \"../instrumentation/provider-guards.js\";\nimport { createPieLogger, isGlobalDebugEnabled } from \"./logger.js\";\nconst logger = createPieLogger(\"instrumentation-event-bridge\", () => isGlobalDebugEnabled());\nfunction normalizeEventDetail(detail) {\n if (detail && typeof detail === \"object\") {\n return detail;\n }\n if (typeof detail === \"undefined\") {\n return {};\n }\n return { value: detail };\n}\nfunction warnInvalidProvider(component) {\n logger.warn(`[InstrumentationEventBridge:${component}] Ignoring invalid instrumentation provider; expected InstrumentationProvider contract`);\n}\nfunction trackBridgeError(args) {\n try {\n args.provider.trackError(args.error instanceof Error\n ? args.error\n : new Error(String(args.error ?? \"Unknown instrumentation bridge error\")), {\n component: args.component,\n errorType: \"InstrumentationBridgeError\",\n sourceEventName: args.sourceEventName,\n });\n }\n catch {\n // Avoid recursive failures while reporting instrumentation bridge errors.\n }\n}\nexport function attachInstrumentationEventBridge(args) {\n if (!args.host || !args.eventMap.length)\n return () => { };\n if (!args.instrumentationProvider)\n return () => { };\n if (!isInstrumentationProvider(args.instrumentationProvider)) {\n if (args.debug) {\n warnInvalidProvider(args.component);\n }\n return () => { };\n }\n const provider = args.instrumentationProvider;\n const removeListeners = [];\n const dedupeWindowMs = Math.max(0, args.dedupeWindowMs ?? 0);\n const recentEventMap = new Map();\n const computeDedupeKey = (mapping, detail) => {\n const summary = [\n detail.assessmentId,\n detail.sectionId,\n detail.attemptId,\n detail.itemId,\n detail.canonicalItemId,\n detail.sourceRuntimeId,\n ]\n .map((value) => String(value ?? \"\"))\n .join(\"|\");\n return `${mapping.instrumentationEventName}|${summary}`;\n };\n for (const mapping of args.eventMap) {\n const handler = (event) => {\n try {\n if (!provider.isReady())\n return;\n if (args.shouldTrackEvent && !args.shouldTrackEvent(event))\n return;\n const customEvent = event;\n const detail = normalizeEventDetail(customEvent.detail);\n const timestamp = new Date().toISOString();\n const mergedAttributes = {\n ...detail,\n ...args.staticAttributes,\n component: args.component,\n sourceEventName: mapping.sourceEventName,\n timestamp,\n };\n if (dedupeWindowMs > 0) {\n const now = Date.now();\n const dedupeKey = computeDedupeKey(mapping, mergedAttributes);\n const previousTimestamp = recentEventMap.get(dedupeKey);\n if (typeof previousTimestamp === \"number\" &&\n now - previousTimestamp < dedupeWindowMs) {\n return;\n }\n recentEventMap.set(dedupeKey, now);\n }\n provider.trackEvent(mapping.instrumentationEventName, {\n ...mergedAttributes,\n });\n }\n catch (error) {\n trackBridgeError({\n provider,\n component: args.component,\n error,\n sourceEventName: mapping.sourceEventName,\n });\n }\n };\n args.host.addEventListener(mapping.sourceEventName, handler);\n removeListeners.push(() => {\n args.host?.removeEventListener(mapping.sourceEventName, handler);\n });\n }\n return () => {\n for (const removeListener of removeListeners) {\n removeListener();\n }\n };\n}\n//# sourceMappingURL=instrumentation-event-bridge.js.map","import { isInstrumentationProvider } from \"../instrumentation/provider-guards.js\";\nimport { NewRelicInstrumentationProvider } from \"../instrumentation/providers/NewRelicInstrumentationProvider.js\";\nimport { createPieLogger, isGlobalDebugEnabled } from \"./logger.js\";\nfunction asRecord(value) {\n return value && typeof value === \"object\" ? value : {};\n}\nfunction resolveLoaderConfig(playerLike) {\n const player = asRecord(playerLike);\n const loaderConfig = asRecord(player.loaderConfig);\n return Object.keys(loaderConfig).length > 0 ? loaderConfig : null;\n}\nfunction resolveProviderFromLoaderConfig(loaderConfig) {\n if (!loaderConfig || !(\"instrumentationProvider\" in loaderConfig)) {\n return { kind: \"unset\" };\n }\n const provider = loaderConfig.instrumentationProvider;\n if (provider === null)\n return { kind: \"null\" };\n if (typeof provider === \"undefined\")\n return { kind: \"unset\" };\n return { kind: \"value\", value: provider };\n}\nfunction resolveTrackPageActionsFromLoaderConfig(loaderConfig) {\n if (!loaderConfig || !(\"trackPageActions\" in loaderConfig))\n return undefined;\n const trackPageActions = loaderConfig.trackPageActions;\n return typeof trackPageActions === \"boolean\" ? trackPageActions : undefined;\n}\nfunction selectProviderCandidate(runtimeCandidate, topLevelCandidate) {\n if (runtimeCandidate.kind === \"value\" || runtimeCandidate.kind === \"null\") {\n return runtimeCandidate;\n }\n return topLevelCandidate;\n}\nlet defaultProvider;\nconst logger = createPieLogger(\"instrumentation-provider-resolution\", () => isGlobalDebugEnabled());\nfunction getDefaultInstrumentationProvider() {\n if (!defaultProvider) {\n defaultProvider = new NewRelicInstrumentationProvider();\n // New Relic provider sets readiness based on window.newrelic.\n void defaultProvider.initialize();\n }\n return defaultProvider;\n}\nexport function resolveInstrumentationProvider(args) {\n const runtimeLoaderConfig = resolveLoaderConfig(args.runtimePlayer);\n const topLevelLoaderConfig = resolveLoaderConfig(args.player);\n const runtimeTrackPageActions = resolveTrackPageActionsFromLoaderConfig(runtimeLoaderConfig);\n const topLevelTrackPageActions = resolveTrackPageActionsFromLoaderConfig(topLevelLoaderConfig);\n const trackPageActions = runtimeTrackPageActions ?? topLevelTrackPageActions ?? false;\n const candidateProvider = selectProviderCandidate(resolveProviderFromLoaderConfig(runtimeLoaderConfig), resolveProviderFromLoaderConfig(topLevelLoaderConfig));\n if (candidateProvider.kind === \"null\")\n return undefined;\n if (candidateProvider.kind === \"unset\") {\n return trackPageActions ? getDefaultInstrumentationProvider() : undefined;\n }\n if (isInstrumentationProvider(candidateProvider.value)) {\n return candidateProvider.value;\n }\n if (args.debug) {\n const prefix = args.component ? `[${args.component}] ` : \"\";\n logger.warn(`${prefix}Ignoring invalid instrumentation provider; expected InstrumentationProvider contract`);\n }\n return undefined;\n}\n//# sourceMappingURL=instrumentation-provider-resolution.js.map","/**\n * Canonical stage vocabulary (M6 of the Coherent Options Surface track).\n *\n * One monotonic stage list is the unified replacement for the previous\n * drift of `toolkit-ready`, `section-ready`, `section-controller-ready`,\n * `interaction-ready`, `readiness-change`, and `ready` — all of which\n * have been removed. Hosts ask the same question — \"is this CE at\n * stage ≥ X?\" — across every `<pie-section-player-*>` and\n * `<pie-assessment-toolkit>` element.\n *\n * The four-stage canonical list (`composed`, `engine-ready`, `interactive`,\n * `disposed`) was finalized after the M5/M6 cumulative review confirmed\n * zero internal or external consumers for the original `attached`,\n * `runtime-bound`, and `ui-rendered` stages. The retro keeps the same\n * shape for both the toolkit CE and the layout CEs — every CE iterates\n * through the same list so subscribers don't need to special-case shape.\n *\n * Locked decisions (see `m6_ready_vocab_canonical_followup.plan.md`):\n * - **A1** Stage machine model with one canonical event family.\n * - **B1** \"All items loaded\" is reclassified as `pie-loading-complete`,\n * not a stage. (The previous `ready` DOM event alias was removed in\n * the broad architecture review compat sweep.)\n * - **C1** `readiness.mode = \"strict\"` only delays the `interactive`\n * transition; every earlier stage fires identically across modes.\n * - **D1** One DOM event family `pie-stage-change` with the stage in the\n * payload, mirroring the M3 `framework-error` idiom.\n *\n * Failure semantics deliberately stay in the M3 framework-error contract —\n * `status: \"failed\"` records the position; the framework error records the\n * cause.\n */\nexport const STAGES = Object.freeze([\n \"composed\",\n \"engine-ready\",\n \"interactive\",\n \"disposed\",\n]);\n/**\n * Stages that apply to a given CE shape. Post-retro the toolkit and the\n * layout CEs share the same canonical list; `applicableStages` is kept as\n * an indirection so the tracker, telemetry, and tests don't have to be\n * rewritten when a future stage diverges between shapes.\n */\nexport function applicableStages(_sourceCe) {\n return STAGES;\n}\n/**\n * Strict ordering index used by the tracker to detect monotonic\n * violations. `disposed` is last; `composed` is first.\n */\nexport function stageOrdinal(stage) {\n const idx = STAGES.indexOf(stage);\n if (idx === -1) {\n throw new Error(`Unknown stage \\`${stage}\\``);\n }\n return idx;\n}\n//# sourceMappingURL=stages.js.map","import { STAGES, applicableStages, stageOrdinal, } from \"./stages.js\";\nlet unexpectedTransitionWarned = false;\nfunction defaultUnexpectedTransitionLogger(info) {\n if (unexpectedTransitionWarned)\n return;\n unexpectedTransitionWarned = true;\n if (typeof console !== \"undefined\" && console.warn) {\n console.warn(`[pie-stage-tracker] Unexpected ${info.reason} stage transition ` +\n `from \\`${info.from ?? \"<none>\"}\\` to \\`${info.to}\\`. ` +\n `Stage transitions are expected to be monotonic within a cohort; ` +\n `call \\`reset()\\` when \\`(sectionId, attemptId)\\` changes.`);\n }\n}\nexport function createStageTracker(opts) {\n const applicable = applicableStages(opts.sourceCeShape);\n const applicableSet = new Set(applicable);\n const now = opts.now ?? (() => new Date().toISOString());\n const onUnexpected = opts.onUnexpectedTransition ?? defaultUnexpectedTransitionLogger;\n let current = null;\n let sectionId = opts.sectionId;\n let attemptId = opts.attemptId;\n const emitted = new Set();\n function emitDetail(stage, status) {\n opts.emit({\n stage,\n status,\n runtimeId: opts.runtimeId,\n sectionId,\n attemptId,\n timestamp: now(),\n sourceCe: opts.sourceCe,\n });\n }\n function fillSkippedBefore(stage) {\n const targetIdx = stageOrdinal(stage);\n const startIdx = current === null ? 0 : stageOrdinal(current) + 1;\n for (let idx = startIdx; idx < targetIdx; idx += 1) {\n const skipCandidate = STAGES[idx];\n if (applicableSet.has(skipCandidate))\n continue;\n if (emitted.has(skipCandidate))\n continue;\n emitted.add(skipCandidate);\n emitDetail(skipCandidate, \"skipped\");\n }\n }\n function enter(stage, status = \"entered\") {\n const nextOrdinal = stageOrdinal(stage);\n const currentOrdinal = current === null ? -1 : stageOrdinal(current);\n if (status === \"entered\") {\n if (emitted.has(stage)) {\n onUnexpected({ from: current, to: stage, reason: \"duplicate\" });\n return;\n }\n if (nextOrdinal < currentOrdinal) {\n onUnexpected({ from: current, to: stage, reason: \"backward\" });\n return;\n }\n if (!applicableSet.has(stage)) {\n // A non-applicable stage entered with `entered` is a programming\n // error: the tracker auto-skips it when a later stage enters.\n // Treat it as a `skipped` emission and continue.\n if (emitted.has(stage))\n return;\n emitted.add(stage);\n emitDetail(stage, \"skipped\");\n return;\n }\n fillSkippedBefore(stage);\n emitted.add(stage);\n current = stage;\n emitDetail(stage, \"entered\");\n return;\n }\n // `status === \"failed\"` records position; do not gate on monotonic\n // ordering — failure can happen during any transition. Mark the stage\n // as emitted so a subsequent `entered` for the same stage warns as a\n // duplicate; downstream recovery should call `reset()` first.\n if (status === \"failed\") {\n fillSkippedBefore(stage);\n emitted.add(stage);\n current = stage;\n emitDetail(stage, \"failed\");\n return;\n }\n // `status === \"skipped\"` is reserved for the auto-fill path; explicit\n // callers shouldn't pass it. Accept it idempotently for robustness.\n if (emitted.has(stage))\n return;\n emitted.add(stage);\n emitDetail(stage, \"skipped\");\n }\n function reset(next) {\n current = null;\n emitted.clear();\n if (next) {\n sectionId = next.sectionId;\n attemptId = next.attemptId;\n }\n }\n function getCurrent() {\n return current;\n }\n return { enter, reset, getCurrent };\n}\n//# sourceMappingURL=stage-tracker.js.map","const DEFAULT_SESSION_ID = \"\";\nconst METADATA_ONLY_SESSION_KEYS = new Set([\n \"complete\",\n \"component\",\n \"timestamp\",\n \"sourceRuntimeId\",\n]);\nconst ELEMENT_IDENTITY_SESSION_KEYS = new Set([\n \"id\",\n \"element\",\n ...METADATA_ONLY_SESSION_KEYS,\n]);\nfunction areSessionContainersEqual(left, right) {\n if (!left && !right)\n return true;\n if (!left || !right)\n return false;\n if ((left.id || \"\") !== (right.id || \"\"))\n return false;\n try {\n return JSON.stringify(left.data || []) === JSON.stringify(right.data || []);\n }\n catch {\n return false;\n }\n}\nexport function normalizeItemSessionContainer(input, fallbackSessionId = DEFAULT_SESSION_ID) {\n if (input && typeof input === \"object\") {\n const candidate = input;\n if (Array.isArray(candidate.data)) {\n return {\n id: typeof candidate.id === \"string\" ? candidate.id : fallbackSessionId,\n data: candidate.data,\n };\n }\n if (Array.isArray(input)) {\n return { id: fallbackSessionId, data: input };\n }\n return { id: fallbackSessionId, data: [input] };\n }\n if (Array.isArray(input)) {\n return { id: fallbackSessionId, data: input };\n }\n return { id: fallbackSessionId, data: [] };\n}\nexport function hasResponseValue(value) {\n if (value == null)\n return false;\n if (Array.isArray(value))\n return value.some((entry) => hasResponseValue(entry));\n if (typeof value !== \"object\")\n return false;\n for (const [key, nested] of Object.entries(value)) {\n if (key === \"value\" &&\n nested !== undefined &&\n nested !== null &&\n !(typeof nested === \"string\" && nested.trim() === \"\") &&\n !(Array.isArray(nested) && nested.length === 0)) {\n return true;\n }\n if (hasResponseValue(nested))\n return true;\n }\n return false;\n}\nexport function hasResponseField(value) {\n if (value == null)\n return false;\n if (Array.isArray(value))\n return value.some((entry) => hasResponseField(entry));\n if (typeof value !== \"object\")\n return false;\n for (const [key, nested] of Object.entries(value)) {\n if (key === \"value\") {\n return true;\n }\n if (hasResponseField(nested))\n return true;\n }\n return false;\n}\nfunction isPlainObject(value) {\n return Boolean(value) && typeof value === \"object\" && !Array.isArray(value);\n}\nfunction getMetadataComponent(sessionDetail, candidate) {\n if (typeof sessionDetail.component === \"string\")\n return sessionDetail.component;\n if (typeof candidate?.component === \"string\")\n return candidate.component;\n return undefined;\n}\nfunction getMetadataComplete(sessionDetail, candidate) {\n if (typeof sessionDetail.complete === \"boolean\")\n return sessionDetail.complete;\n if (typeof candidate?.complete === \"boolean\")\n return candidate.complete;\n return undefined;\n}\nfunction isElementIdentityOnlyPayload(candidate) {\n const candidateKeys = Object.keys(candidate);\n const hasIdentityKey = \"id\" in candidate || \"element\" in candidate;\n return (hasIdentityKey &&\n !hasResponseField(candidate) &&\n candidateKeys.every((key) => ELEMENT_IDENTITY_SESSION_KEYS.has(key)));\n}\nfunction mergeSessionEntry(existing, incoming) {\n const merged = { ...existing };\n for (const [key, value] of Object.entries(incoming)) {\n const previous = merged[key];\n merged[key] =\n isPlainObject(previous) && isPlainObject(value)\n ? mergeSessionEntry(previous, value)\n : value;\n }\n return merged;\n}\nexport function mergeElementIntoSession(itemId, previousItemSession, entryId, entry) {\n const previous = normalizeItemSessionContainer(previousItemSession, itemId);\n const nextData = [...previous.data];\n const existingIndex = nextData.findIndex((candidate) => {\n if (!candidate || typeof candidate !== \"object\")\n return false;\n return candidate.id === entryId;\n });\n if (existingIndex >= 0) {\n const existing = nextData[existingIndex];\n nextData[existingIndex] =\n existing && typeof existing === \"object\"\n ? mergeSessionEntry(existing, entry)\n : entry;\n }\n else {\n nextData.push(entry);\n }\n return {\n id: previous.id || itemId,\n data: nextData,\n };\n}\nexport function normalizeItemSessionChange(args) {\n const sessionDetail = (args.sessionDetail || {});\n const actualSession = sessionDetail &&\n typeof sessionDetail === \"object\" &&\n \"session\" in sessionDetail\n ? sessionDetail.session\n : args.sessionDetail;\n const safeItemId = typeof args.itemId === \"string\" && args.itemId\n ? args.itemId\n : typeof actualSession?.id ===\n \"string\"\n ? String(actualSession.id)\n : \"\";\n if (!actualSession || typeof actualSession !== \"object\") {\n return {\n itemId: safeItemId,\n session: null,\n intent: \"metadata-only\",\n component: getMetadataComponent(sessionDetail),\n complete: getMetadataComplete(sessionDetail),\n };\n }\n const candidate = actualSession;\n if (Array.isArray(candidate.data)) {\n const normalizedCandidate = normalizeItemSessionContainer(candidate, safeItemId);\n const previousNormalized = args.previousItemSession !== undefined\n ? normalizeItemSessionContainer(args.previousItemSession, safeItemId)\n : null;\n const sessionDetailKeys = Object.keys(sessionDetail);\n const metadataWithSessionOnly = sessionDetailKeys.length > 0 &&\n sessionDetailKeys.every((key) => key === \"session\" ||\n key === \"complete\" ||\n key === \"component\" ||\n key === \"timestamp\" ||\n key === \"sourceRuntimeId\");\n if (metadataWithSessionOnly &&\n previousNormalized &&\n areSessionContainersEqual(normalizedCandidate, previousNormalized)) {\n return {\n itemId: safeItemId,\n session: null,\n intent: \"metadata-only\",\n component: getMetadataComponent(sessionDetail),\n complete: getMetadataComplete(sessionDetail),\n };\n }\n return {\n itemId: safeItemId,\n session: normalizedCandidate,\n intent: \"replace-item-session\",\n component: getMetadataComponent(sessionDetail),\n complete: getMetadataComplete(sessionDetail),\n };\n }\n const candidateKeys = Object.keys(candidate);\n const isMetadataOnlyPayload = candidateKeys.length > 0 &&\n candidateKeys.every((key) => key === \"complete\" ||\n key === \"component\" ||\n key === \"timestamp\" ||\n key === \"sourceRuntimeId\");\n if (isMetadataOnlyPayload) {\n return {\n itemId: safeItemId,\n session: null,\n intent: \"metadata-only\",\n component: getMetadataComponent(sessionDetail, candidate),\n complete: getMetadataComplete(sessionDetail, candidate),\n };\n }\n if (isElementIdentityOnlyPayload(candidate)) {\n return {\n itemId: safeItemId,\n session: null,\n intent: \"metadata-only\",\n component: getMetadataComponent(sessionDetail, candidate),\n complete: getMetadataComplete(sessionDetail, candidate),\n };\n }\n const component = getMetadataComponent(sessionDetail, candidate) ?? \"response\";\n const elementEntryId = typeof candidate.id === \"string\" && candidate.id ? candidate.id : component;\n const merged = mergeElementIntoSession(safeItemId, args.previousItemSession, elementEntryId, { id: elementEntryId, ...candidate });\n return {\n itemId: safeItemId,\n session: merged,\n intent: \"merge-element-session\",\n component,\n complete: getMetadataComplete(sessionDetail, candidate),\n };\n}\n//# sourceMappingURL=item-session-contract.js.map","/**\n * PIE element override helpers.\n *\n * Used to:\n * - parse overrides from URL params\n * - apply overrides to a PIE config (server-side or client-side)\n * - build URLs/params for sharing override state\n */\nimport { cloneDeep } from \"../object/index.js\";\nimport { createPieLogger, isGlobalDebugEnabled } from \"./logger.js\";\nimport { parsePackageName } from \"./utils.js\";\nconst logger = createPieLogger(\"pie-overrides\", () => isGlobalDebugEnabled());\n/**\n * Apply element overrides to a PIE config\n * @param config The original PIE config\n * @param elementOverrides Map of element packages to override versions\n * @returns Updated config with overridden elements\n */\nexport function applyElementOverrides(config, elementOverrides) {\n if (!config ||\n !elementOverrides ||\n Object.keys(elementOverrides).length === 0) {\n return config;\n }\n // Create a deep copy of the config to avoid mutating the original\n const updatedConfig = cloneDeep(config);\n // Check if there are elements to override\n if (!updatedConfig.elements) {\n return updatedConfig;\n }\n // Process each override\n for (const [packageName, version] of Object.entries(elementOverrides)) {\n let matched = false;\n // Find the element key that uses this package\n for (const [elementKey, elementPackageValue] of Object.entries(updatedConfig.elements)) {\n const elementPackageStr = String(elementPackageValue);\n let basePackageName = \"\";\n try {\n basePackageName = parsePackageName(elementPackageStr).name;\n }\n catch {\n logger.debug(`Couldn't parse element package value: ${elementPackageStr}`);\n continue;\n }\n if (basePackageName === packageName) {\n matched = true;\n // Create a new element key with the specified version\n const versionNumber = String(version).replace(/[^0-9.-]/g, \"\");\n const parts = String(elementKey).split(\"--version-\");\n const baseElementName = parts[0];\n const newElementKey = `${baseElementName}--version-${versionNumber.replace(/\\./g, \"-\")}`;\n // Update the elements map\n updatedConfig.elements[newElementKey] = `${packageName}@${version}`;\n // If the key changed, update markup to reference the new key\n if (newElementKey !== elementKey) {\n if (updatedConfig.markup) {\n updatedConfig.markup = String(updatedConfig.markup).replace(new RegExp(elementKey, \"g\"), newElementKey);\n }\n // Remove the old element if we created a new one with a different key\n delete updatedConfig.elements[elementKey];\n }\n }\n }\n if (!matched) {\n logger.debug(`No matching element found for package ${packageName}`);\n }\n }\n return updatedConfig;\n}\n/**\n * Apply element version overrides without renaming custom element tags.\n *\n * Unlike `applyElementOverrides`, this helper keeps `config.markup` and\n * `config.elements` keys intact and only updates each matching element package\n * value to the requested version. This is intended for unified `pie-item-player`\n * flows where stable tag names are required.\n */\nexport function applyElementVersionOverridesPreserveTags(config, elementOverrides) {\n if (!config ||\n !elementOverrides ||\n Object.keys(elementOverrides).length === 0) {\n return config;\n }\n const updatedConfig = cloneDeep(config);\n if (!updatedConfig.elements || typeof updatedConfig.elements !== \"object\") {\n return updatedConfig;\n }\n for (const [elementKey, elementPackageValue] of Object.entries(updatedConfig.elements)) {\n const elementPackageStr = String(elementPackageValue);\n try {\n const parsed = parsePackageName(elementPackageStr);\n const nextVersion = elementOverrides[parsed.name];\n if (!nextVersion)\n continue;\n const packageBase = parsed.path\n ? `${parsed.name}/${parsed.path}`\n : parsed.name;\n updatedConfig.elements[elementKey] =\n `${packageBase}@${String(nextVersion).trim()}`;\n }\n catch {\n logger.debug(`Couldn't parse element package value: ${elementPackageStr}`);\n }\n }\n return updatedConfig;\n}\n/**\n * Parse element overrides from URL search params.\n * @returns Map of element package names to versions\n */\nexport function parseElementOverridesFromUrl(searchParams) {\n const overrides = {};\n // Look for parameters with the pattern pie-overrides[packageName]=version\n for (const [key, value] of searchParams.entries()) {\n if (key.startsWith(\"pie-overrides[\") && key.endsWith(\"]\")) {\n // Extract the package name from between the brackets\n const packageName = key.substring(14, key.length - 1);\n // Ensure the package name format is correct (including @)\n const normalizedPackageName = packageName.startsWith(\"@\")\n ? packageName\n : `@${packageName}`;\n overrides[normalizedPackageName] = value;\n }\n }\n return overrides;\n}\n/**\n * Parse element overrides from current window URL (client-only).\n */\nexport function parseElementOverridesFromCurrentUrl() {\n if (typeof window === \"undefined\") {\n return {};\n }\n const url = new URL(window.location.href);\n return parseElementOverridesFromUrl(url.searchParams);\n}\n/**\n * Generate a URL parameter string for an element override\n */\nexport function formatElementOverrideParam(packageName, version) {\n // Normalize the package name for the parameter key (strip leading @)\n const normalizedPackageName = packageName.startsWith(\"@\")\n ? packageName.substring(1)\n : packageName;\n return `pie-overrides[${normalizedPackageName}]=${encodeURIComponent(version)}`;\n}\n/**\n * Creates a URL that preserves existing overrides and adds or updates a new one.\n */\nexport function addOrUpdateOverrideInUrl(url, packageName, version) {\n const params = new URLSearchParams(url.search);\n // Remove @ if present for consistency in URL\n const normalizedPackageName = packageName.startsWith(\"@\")\n ? packageName.substring(1)\n : packageName;\n // Set the new override\n params.set(`pie-overrides[${normalizedPackageName}]`, version);\n // Create the new URL\n const newUrl = new URL(url.pathname, url.origin);\n newUrl.search = params.toString();\n return newUrl.toString();\n}\n/**\n * Extract package information from a package string.\n * Intended for UI display.\n */\nexport function extractPackageInfo(packageStr) {\n try {\n const parsed = parsePackageName(String(packageStr));\n return {\n name: parsed.name,\n version: parsed.version || \"unknown\",\n displayName: parsed.name.split(\"/\").pop() || parsed.name,\n };\n }\n catch {\n const s = String(packageStr);\n return {\n name: s,\n version: \"unknown\",\n displayName: s.split(\"/\").pop() || s,\n };\n }\n}\n//# sourceMappingURL=overrides.js.map","/**\n * Selector for elements that are commonly keyboard-focusable in assessment UI.\n * Kept in sync with `focus-trap.ts` for consistent tab-order surfaces.\n */\nexport const FOCUSABLE_SELECTOR = [\n \"a[href]\",\n \"button:not([disabled])\",\n \"input:not([disabled]):not([type='hidden'])\",\n \"select:not([disabled])\",\n \"textarea:not([disabled])\",\n \"[contenteditable]:not([contenteditable='false'])\",\n \"[tabindex]:not([tabindex='-1'])\",\n].join(\",\");\n/**\n * Whether `el` is a reasonable programmatic focus target (matches selector,\n * not disabled, not inside `inert`, and has a layout box).\n */\nexport function isProgrammaticFocusTarget(el) {\n if (!el.matches(FOCUSABLE_SELECTOR))\n return false;\n if (el.hasAttribute(\"disabled\"))\n return false;\n if (el.closest(\"[inert]\"))\n return false;\n return el.offsetParent !== null || el.getClientRects().length > 0;\n}\n//# sourceMappingURL=first-focusable.js.map","import { FOCUSABLE_SELECTOR, isProgrammaticFocusTarget, } from \"./first-focusable.js\";\nfunction getFocusableElements(container) {\n return Array.from(container.querySelectorAll(FOCUSABLE_SELECTOR)).filter((el) => isProgrammaticFocusTarget(el));\n}\nfunction focusInitialTarget(container, initialFocus) {\n try {\n if (initialFocus && container.contains(initialFocus)) {\n initialFocus.focus();\n return;\n }\n const focusable = getFocusableElements(container);\n if (focusable.length > 0) {\n focusable[0].focus();\n return;\n }\n container.focus?.();\n }\n catch {\n // ignore\n }\n}\n/**\n * Focus trap helper for floating dialogs/panels.\n *\n * Keeps tab navigation contained, supports Escape callback,\n * and restores prior focus when the trap is removed.\n */\nexport function createFocusTrap(container, options = {}) {\n const prev = typeof document !== \"undefined\"\n ? document.activeElement\n : null;\n const wrap = options.wrap ?? true;\n const onKeydown = (event) => {\n if (event.key === \"Escape\") {\n options.onEscape?.();\n return;\n }\n if (event.key !== \"Tab\")\n return;\n const focusable = getFocusableElements(container);\n if (!focusable.length) {\n if (!wrap)\n return;\n event.preventDefault();\n container.focus?.();\n return;\n }\n const current = document.activeElement;\n const currentIndex = focusable.indexOf(current || focusable[0]);\n if (event.shiftKey) {\n if (currentIndex <= 0) {\n if (wrap) {\n event.preventDefault();\n focusable[focusable.length - 1].focus();\n }\n else {\n options.onTabExit?.(\"backward\", event);\n }\n }\n return;\n }\n if (currentIndex === focusable.length - 1) {\n if (wrap) {\n event.preventDefault();\n focusable[0].focus();\n }\n else {\n options.onTabExit?.(\"forward\", event);\n }\n }\n };\n queueMicrotask(() => focusInitialTarget(container, options.initialFocus));\n container.addEventListener(\"keydown\", onKeydown);\n return () => {\n container.removeEventListener(\"keydown\", onKeydown);\n try {\n prev?.focus?.();\n }\n catch {\n // ignore\n }\n };\n}\n//# sourceMappingURL=focus-trap.js.map"],"x_google_ignoreList":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24],"mappings":";AAEA,SAAS,EAAkB,GAAG,GAAG;CAC/B,CAAS,KAAR,QAAa,IAAI,EAAE,YAAY,IAAI,EAAE;CACtC,KAAK,IAAI,IAAI,GAAG,IAAI,MAAM,CAAC,GAAG,IAAI,GAAG,KAAK,EAAE,KAAK,EAAE;CACnD,OAAO;AACT;AACA,SAAS,EAAgB,GAAG;CAC1B,IAAI,MAAM,QAAQ,CAAC,GAAG,OAAO;AAC/B;AACA,SAAS,EAAsB,GAAG,GAAG;CACnC,IAAI,IAAY,KAAR,OAAY,OAAsB,OAAO,SAAtB,OAAgC,EAAE,OAAO,aAAa,EAAE;CACnF,IAAY,KAAR,MAAW;EACb,IAAI,GACF,GACA,GACA,GACA,IAAI,CAAC,GACL,IAAI,IACJ,IAAI;EACN,IAAI;GACF,IAAI,KAAK,IAAI,EAAE,KAAK,CAAC,EAAA,CAAG,MAAY,MAAN,GAAgB,OAAO,EAAE,KAAK,IAAI,EAAE,KAAK,CAAC,EAAA,CAAG,UAAU,EAAE,KAAK,EAAE,KAAK,GAAG,EAAE,WAAW,IAAI,IAAI,CAAC;EAC9H,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