Brunobkr/llama.cpp_AlgMor24_github
ΩFFFΣLLIa • llama.cpp • AlgMor24 ██████╗ ███████╗███████╗███████╗██╗ ██╗ ██╗ █████╗ ██╔═══██╗██╔════╝██╔════╝██╔════╝██║ ██║ ██║██╔══██╗ ██║ ██║█████╗ █████╗ █████╗ ██║ ██║ ██║███████║ ██║ ██║██╔══╝ ██╔══╝ ██╔══╝ ██║ ██║ ██║██╔══██║ ╚██████╔╝██║ ██║ ███████╗███████╗███████╗██║██║ ██║ ╚═════╝ ╚═╝ ╚═╝ ╚══════╝╚══════╝╚══════╝╚═╝╚═╝ ╚═╝ High-Performance LLM / VLM Inference & Autonomous Agentic Ecosystem… See the full description on the dataset page: https://huggingface.co/datasets/Brunobkr/llama.cpp_AlgMor24_github.
03.1k
1/*! @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 */2 3(function (global, factory) {4 typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :5 typeof define === 'function' && define.amd ? define(factory) :6 (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.DOMPurify = factory());7})(this, (function () { 'use strict';8 9 function _arrayLikeToArray(r, a) {10 (null == a || a > r.length) && (a = r.length);11 for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];12 return n;13 }14 function _arrayWithHoles(r) {15 if (Array.isArray(r)) return r;16 }17 function _iterableToArrayLimit(r, l) {18 var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];19 if (null != t) {20 var e,21 n,22 i,23 u,24 a = [],25 f = true,26 o = false;27 try {28 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);29 } catch (r) {30 o = true, n = r;31 } finally {32 try {33 if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return;34 } finally {35 if (o) throw n;36 }37 }38 return a;39 }40 }41 function _nonIterableRest() {42 throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");43 }44 function _slicedToArray(r, e) {45 return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest();46 }47 function _unsupportedIterableToArray(r, a) {48 if (r) {49 if ("string" == typeof r) return _arrayLikeToArray(r, a);50 var t = {}.toString.call(r).slice(8, -1);51 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;52 }53 }54 55 const entries = Object.entries,56 setPrototypeOf = Object.setPrototypeOf,57 isFrozen = Object.isFrozen,58 getPrototypeOf = Object.getPrototypeOf,59 getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;60 let freeze = Object.freeze,61 seal = Object.seal,62 create = Object.create; // eslint-disable-line import/no-mutable-exports63 let _ref = typeof Reflect !== 'undefined' && Reflect,64 apply = _ref.apply,65 construct = _ref.construct;66 if (!freeze) {67 freeze = function freeze(x) {68 return x;69 };70 }71 if (!seal) {72 seal = function seal(x) {73 return x;74 };75 }76 if (!apply) {77 apply = function apply(func, thisArg) {78 for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {79 args[_key - 2] = arguments[_key];80 }81 return func.apply(thisArg, args);82 };83 }84 if (!construct) {85 construct = function construct(Func) {86 for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {87 args[_key2 - 1] = arguments[_key2];88 }89 return new Func(...args);90 };91 }92 const arrayForEach = unapply(Array.prototype.forEach);93 const arrayLastIndexOf = unapply(Array.prototype.lastIndexOf);94 const arrayPop = unapply(Array.prototype.pop);95 const arrayPush = unapply(Array.prototype.push);96 const arraySplice = unapply(Array.prototype.splice);97 const arrayIsArray = Array.isArray;98 const stringToLowerCase = unapply(String.prototype.toLowerCase);99 const stringToString = unapply(String.prototype.toString);100 const stringMatch = unapply(String.prototype.match);101 const stringReplace = unapply(String.prototype.replace);102 const stringIndexOf = unapply(String.prototype.indexOf);103 const stringTrim = unapply(String.prototype.trim);104 const numberToString = unapply(Number.prototype.toString);105 const booleanToString = unapply(Boolean.prototype.toString);106 const bigintToString = typeof BigInt === 'undefined' ? null : unapply(BigInt.prototype.toString);107 const symbolToString = typeof Symbol === 'undefined' ? null : unapply(Symbol.prototype.toString);108 const objectHasOwnProperty = unapply(Object.prototype.hasOwnProperty);109 const objectToString = unapply(Object.prototype.toString);110 const regExpTest = unapply(RegExp.prototype.test);111 const typeErrorCreate = unconstruct(TypeError);112 /**113 * Creates a new function that calls the given function with a specified thisArg and arguments.114 *115 * @param func - The function to be wrapped and called.116 * @returns A new function that calls the given function with a specified thisArg and arguments.117 */118 function unapply(func) {119 return function (thisArg) {120 if (thisArg instanceof RegExp) {121 thisArg.lastIndex = 0;122 }123 for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {124 args[_key3 - 1] = arguments[_key3];125 }126 return apply(func, thisArg, args);127 };128 }129 /**130 * Creates a new function that constructs an instance of the given constructor function with the provided arguments.131 *132 * @param func - The constructor function to be wrapped and called.133 * @returns A new function that constructs an instance of the given constructor function with the provided arguments.134 */135 function unconstruct(Func) {136 return function () {137 for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {138 args[_key4] = arguments[_key4];139 }140 return construct(Func, args);141 };142 }143 /**144 * Add properties to a lookup table145 *146 * @param set - The set to which elements will be added.147 * @param array - The array containing elements to be added to the set.148 * @param transformCaseFunc - An optional function to transform the case of each element before adding to the set.149 * @returns The modified set with added elements.150 */151 function addToSet(set, array) {152 let transformCaseFunc = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : stringToLowerCase;153 if (setPrototypeOf) {154 // Make 'in' and truthy checks like Boolean(set.constructor)155 // independent of any properties defined on Object.prototype.156 // Prevent prototype setters from intercepting set as a this value.157 setPrototypeOf(set, null);158 }159 if (!arrayIsArray(array)) {160 return set;161 }162 let l = array.length;163 while (l--) {164 let element = array[l];165 if (typeof element === 'string') {166 const lcElement = transformCaseFunc(element);167 if (lcElement !== element) {168 // Config presets (e.g. tags.js, attrs.js) are immutable.169 if (!isFrozen(array)) {170 array[l] = lcElement;171 }172 element = lcElement;173 }174 }175 set[element] = true;176 }177 return set;178 }179 /**180 * Clean up an array to harden against CSPP181 *182 * @param array - The array to be cleaned.183 * @returns The cleaned version of the array184 */185 function cleanArray(array) {186 for (let index = 0; index < array.length; index++) {187 const isPropertyExist = objectHasOwnProperty(array, index);188 if (!isPropertyExist) {189 array[index] = null;190 }191 }192 return array;193 }194 /**195 * Shallow clone an object196 *197 * @param object - The object to be cloned.198 * @returns A new object that copies the original.199 */200 function clone(object) {201 const newObject = create(null);202 for (const _ref2 of entries(object)) {203 var _ref3 = _slicedToArray(_ref2, 2);204 const property = _ref3[0];205 const value = _ref3[1];206 const isPropertyExist = objectHasOwnProperty(object, property);207 if (isPropertyExist) {208 if (arrayIsArray(value)) {209 newObject[property] = cleanArray(value);210 } else if (value && typeof value === 'object' && value.constructor === Object) {211 newObject[property] = clone(value);212 } else {213 newObject[property] = value;214 }215 }216 }217 return newObject;218 }219 /**220 * Convert non-node values into strings without depending on direct property access.221 *222 * @param value - The value to stringify.223 * @returns A string representation of the provided value.224 */225 function stringifyValue(value) {226 switch (typeof value) {227 case 'string':228 {229 return value;230 }231 case 'number':232 {233 return numberToString(value);234 }235 case 'boolean':236 {237 return booleanToString(value);238 }239 case 'bigint':240 {241 return bigintToString ? bigintToString(value) : '0';242 }243 case 'symbol':244 {245 return symbolToString ? symbolToString(value) : 'Symbol()';246 }247 case 'undefined':248 {249 return objectToString(value);250 }251 case 'function':252 case 'object':253 {254 if (value === null) {255 return objectToString(value);256 }257 const valueAsRecord = value;258 const valueToString = lookupGetter(valueAsRecord, 'toString');259 if (typeof valueToString === 'function') {260 const stringified = valueToString(valueAsRecord);261 return typeof stringified === 'string' ? stringified : objectToString(stringified);262 }263 return objectToString(value);264 }265 default:266 {267 return objectToString(value);268 }269 }270 }271 /**272 * This method automatically checks if the prop is function or getter and behaves accordingly.273 *274 * @param object - The object to look up the getter function in its prototype chain.275 * @param prop - The property name for which to find the getter function.276 * @returns The getter function found in the prototype chain or a fallback function.277 */278 function lookupGetter(object, prop) {279 while (object !== null) {280 const desc = getOwnPropertyDescriptor(object, prop);281 if (desc) {282 if (desc.get) {283 return unapply(desc.get);284 }285 if (typeof desc.value === 'function') {286 return unapply(desc.value);287 }288 }289 object = getPrototypeOf(object);290 }291 function fallbackValue() {292 return null;293 }294 return fallbackValue;295 }296 function isRegex(value) {297 try {298 regExpTest(value, '');299 return true;300 } catch (_unused) {301 return false;302 }303 }304 305 const 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']);306 const 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']);307 const 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']);308 // List of SVG elements that are disallowed by default.309 // We still need to know them so that we can do namespace310 // checks properly in case one wants to add them to311 // allow-list.312 const 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']);313 const 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']);314 // Similarly to SVG, we want to know all MathML elements,315 // even those that we disallow by default.316 const mathMlDisallowed = freeze(['maction', 'maligngroup', 'malignmark', 'mlongdiv', 'mscarries', 'mscarry', 'msgroup', 'mstack', 'msline', 'msrow', 'semantics', 'annotation', 'annotation-xml', 'mprescripts', 'none']);317 const text = freeze(['#text']);318 319 const 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']);320 const 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']);321 const 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']);322 const xml = freeze(['xlink:href', 'xml:id', 'xlink:title', 'xml:space', 'xmlns:xlink']);323 324 const MUSTACHE_EXPR = seal(/{{[\w\W]*|^[\w\W]*}}/g);325 const ERB_EXPR = seal(/<%[\w\W]*|^[\w\W]*%>/g);326 const TMPLIT_EXPR = seal(/\${[\w\W]*/g);327 const DATA_ATTR = seal(/^data-[\-\w.\u00B7-\uFFFF]+$/); // eslint-disable-line no-useless-escape328 const ARIA_ATTR = seal(/^aria-[\-\w]+$/); // eslint-disable-line no-useless-escape329 const 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-escape330 );331 const IS_SCRIPT_OR_DATA = seal(/^(?:\w+script|data):/i);332 const ATTR_WHITESPACE = seal(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g // eslint-disable-line no-control-regex333 );334 const DOCTYPE_NAME = seal(/^html$/i);335 const CUSTOM_ELEMENT = seal(/^[a-z][.\w]*(-[.\w]+)+$/i);336 // Markup-significant character probes used by _sanitizeElements.337 // Shared module-level instances are safe despite the sticky /g flags:338 // unapply() resets lastIndex for RegExp receivers before every call.339 const ELEMENT_MARKUP_PROBE = seal(/<[/\w!]/g);340 const COMMENT_MARKUP_PROBE = seal(/<[/\w]/g);341 const FALLBACK_TAG_CLOSE = seal(/<\/no(script|embed|frames)/i);342 const SELF_CLOSING_TAG = seal(/\/>/i);343 344 // https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType345 const NODE_TYPE = {346 element: 1,347 attribute: 2,348 text: 3,349 cdataSection: 4,350 entityReference: 5,351 // Deprecated352 entityNode: 6,353 // Deprecated354 processingInstruction: 7,355 comment: 8,356 document: 9,357 documentType: 10,358 documentFragment: 11,359 notation: 12 // Deprecated360 };361 const getGlobal = function getGlobal() {362 return typeof window === 'undefined' ? null : window;363 };364 /**365 * Creates a no-op policy for internal use only.366 * Don't export this function outside this module!367 * @param trustedTypes The policy factory.368 * @param purifyHostElement The Script element used to load DOMPurify (to determine policy name suffix).369 * @return The policy created (or null, if Trusted Types370 * are not supported or creating the policy failed).371 */372 const _createTrustedTypesPolicy = function _createTrustedTypesPolicy(trustedTypes, purifyHostElement) {373 if (typeof trustedTypes !== 'object' || typeof trustedTypes.createPolicy !== 'function') {374 return null;375 }376 // Allow the callers to control the unique policy name377 // by adding a data-tt-policy-suffix to the script element with the DOMPurify.378 // Policy creation with duplicate names throws in Trusted Types.379 let suffix = null;380 const ATTR_NAME = 'data-tt-policy-suffix';381 if (purifyHostElement && purifyHostElement.hasAttribute(ATTR_NAME)) {382 suffix = purifyHostElement.getAttribute(ATTR_NAME);383 }384 const policyName = 'dompurify' + (suffix ? '#' + suffix : '');385 try {386 return trustedTypes.createPolicy(policyName, {387 createHTML(html) {388 return html;389 },390 createScriptURL(scriptUrl) {391 return scriptUrl;392 }393 });394 } catch (_) {395 // Policy creation failed (most likely another DOMPurify script has396 // already run). Skip creating the policy, as this will only cause errors397 // if TT are enforced.398 console.warn('TrustedTypes policy ' + policyName + ' could not be created.');399 return null;400 }401 };402 const _createHooksMap = function _createHooksMap() {403 return {404 afterSanitizeAttributes: [],405 afterSanitizeElements: [],406 afterSanitizeShadowDOM: [],407 beforeSanitizeAttributes: [],408 beforeSanitizeElements: [],409 beforeSanitizeShadowDOM: [],410 uponSanitizeAttribute: [],411 uponSanitizeElement: [],412 uponSanitizeShadowNode: []413 };414 };415 /**416 * Resolve a set-valued configuration option: a fresh set built from417 * cfg[key] when it is an own array property (seeded with a clone of418 * options.base when given, case-normalized via options.transform),419 * the fallback set otherwise.420 *421 * @param cfg the cloned, prototype-free configuration object422 * @param key the configuration property to read423 * @param fallback the set to use when the option is absent or not an array424 * @param options transform and optional base set to merge into425 * @returns the resolved set426 */427 const _resolveSetOption = function _resolveSetOption(cfg, key, fallback, options) {428 return objectHasOwnProperty(cfg, key) && arrayIsArray(cfg[key]) ? addToSet(options.base ? clone(options.base) : {}, cfg[key], options.transform) : fallback;429 };430 function createDOMPurify() {431 let window = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getGlobal();432 const DOMPurify = root => createDOMPurify(root);433 DOMPurify.version = '3.4.13';434 DOMPurify.removed = [];435 if (!window || !window.document || window.document.nodeType !== NODE_TYPE.document || !window.Element) {436 // Not running in a browser, provide a factory function437 // so that you can pass your own Window438 DOMPurify.isSupported = false;439 return DOMPurify;440 }441 let document = window.document;442 const originalDocument = document;443 const currentScript = originalDocument.currentScript;444 window.DocumentFragment;445 const HTMLTemplateElement = window.HTMLTemplateElement,446 Node = window.Node,447 Element = window.Element,448 NodeFilter = window.NodeFilter,449 _window$NamedNodeMap = window.NamedNodeMap;450 _window$NamedNodeMap === void 0 ? window.NamedNodeMap || window.MozNamedAttrMap : _window$NamedNodeMap;451 window.HTMLFormElement;452 const DOMParser = window.DOMParser,453 trustedTypes = window.trustedTypes;454 const ElementPrototype = Element.prototype;455 const cloneNode = lookupGetter(ElementPrototype, 'cloneNode');456 const remove = lookupGetter(ElementPrototype, 'remove');457 const getNextSibling = lookupGetter(ElementPrototype, 'nextSibling');458 const getChildNodes = lookupGetter(ElementPrototype, 'childNodes');459 const getParentNode = lookupGetter(ElementPrototype, 'parentNode');460 const getShadowRoot = lookupGetter(ElementPrototype, 'shadowRoot');461 const getAttributes = lookupGetter(ElementPrototype, 'attributes');462 const getNodeType = Node && Node.prototype ? lookupGetter(Node.prototype, 'nodeType') : null;463 const getNodeName = Node && Node.prototype ? lookupGetter(Node.prototype, 'nodeName') : null;464 const getOwnerDocument = Node && Node.prototype ? lookupGetter(Node.prototype, 'ownerDocument') : null;465 // As per issue #47, the web-components registry is inherited by a466 // new document created via createHTMLDocument. As per the spec467 // (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-registries)468 // a new empty registry is used when creating a template contents owner469 // document, so we use that as our parent document to ensure nothing470 // is inherited.471 if (typeof HTMLTemplateElement === 'function') {472 const template = document.createElement('template');473 if (template.content && template.content.ownerDocument) {474 document = template.content.ownerDocument;475 }476 }477 let trustedTypesPolicy;478 let emptyHTML = '';479 // The instance's own internal Trusted Types policy. Unlike a caller-supplied480 // `TRUSTED_TYPES_POLICY`, this is created at most once — Trusted Types throws481 // on duplicate policy names — and is the only policy allowed to persist482 // across configurations and survive `clearConfig()`.483 let defaultTrustedTypesPolicy;484 let defaultTrustedTypesPolicyResolved = false;485 // Tracks whether we are already inside a call to the configured Trusted Types486 // policy (`createHTML` or `createScriptURL`). If a supplied policy callback487 // itself calls `DOMPurify.sanitize` (the cause of #1422), `sanitize` would488 // re-enter the policy and recurse until the stack overflows. We detect that489 // re-entry and throw a clear, actionable error instead. The guard is shared490 // across both callbacks, because either one re-entering `sanitize` triggers491 // the same unbounded recursion.492 let IN_TRUSTED_TYPES_POLICY = 0;493 const _assertNotInTrustedTypesPolicy = function _assertNotInTrustedTypesPolicy() {494 if (IN_TRUSTED_TYPES_POLICY > 0) {495 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.');496 }497 };498 const _createTrustedHTML = function _createTrustedHTML(html) {499 _assertNotInTrustedTypesPolicy();500 IN_TRUSTED_TYPES_POLICY++;501 try {502 return trustedTypesPolicy.createHTML(html);503 } finally {504 IN_TRUSTED_TYPES_POLICY--;505 }506 };507 const _createTrustedScriptURL = function _createTrustedScriptURL(scriptUrl) {508 _assertNotInTrustedTypesPolicy();509 IN_TRUSTED_TYPES_POLICY++;510 try {511 return trustedTypesPolicy.createScriptURL(scriptUrl);512 } finally {513 IN_TRUSTED_TYPES_POLICY--;514 }515 };516 // Lazily resolve (and cache) the instance's internal default policy.517 // Resolution is attempted at most once: a successful `createPolicy` cannot be518 // repeated (Trusted Types throws on duplicate names), and a failed or519 // unsupported attempt must not be retried on every parse.520 const _getDefaultTrustedTypesPolicy = function _getDefaultTrustedTypesPolicy() {521 if (!defaultTrustedTypesPolicyResolved) {522 defaultTrustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, currentScript);523 defaultTrustedTypesPolicyResolved = true;524 }525 return defaultTrustedTypesPolicy;526 };527 const _document = document,528 implementation = _document.implementation,529 createNodeIterator = _document.createNodeIterator,530 createDocumentFragment = _document.createDocumentFragment,531 getElementsByTagName = _document.getElementsByTagName;532 const importNode = originalDocument.importNode;533 let hooks = _createHooksMap();534 /**535 * Expose whether this browser supports running the full DOMPurify.536 */537 DOMPurify.isSupported = typeof entries === 'function' && typeof getParentNode === 'function' && implementation && implementation.createHTMLDocument !== undefined;538 const MUSTACHE_EXPR$1 = MUSTACHE_EXPR,539 ERB_EXPR$1 = ERB_EXPR,540 TMPLIT_EXPR$1 = TMPLIT_EXPR,541 DATA_ATTR$1 = DATA_ATTR,542 ARIA_ATTR$1 = ARIA_ATTR,543 IS_SCRIPT_OR_DATA$1 = IS_SCRIPT_OR_DATA,544 ATTR_WHITESPACE$1 = ATTR_WHITESPACE,545 CUSTOM_ELEMENT$1 = CUSTOM_ELEMENT;546 let IS_ALLOWED_URI$1 = IS_ALLOWED_URI;547 /**548 * We consider the elements and attributes below to be safe. Ideally549 * don't add any new ones but feel free to remove unwanted ones.550 */551 /* allowed element names */552 let ALLOWED_TAGS = null;553 const DEFAULT_ALLOWED_TAGS = addToSet({}, [...html$1, ...svg$1, ...svgFilters, ...mathMl$1, ...text]);554 /* Allowed attribute names */555 let ALLOWED_ATTR = null;556 const DEFAULT_ALLOWED_ATTR = addToSet({}, [...html, ...svg, ...mathMl, ...xml]);557 /*558 * Configure how DOMPurify should handle custom elements and their attributes as well as customized built-in elements.559 * @property {RegExp|Function|null} tagNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any custom elements)560 * @property {RegExp|Function|null} attributeNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any attributes not on the allow list)561 * @property {boolean} allowCustomizedBuiltInElements allow custom elements derived from built-ins if they pass CUSTOM_ELEMENT_HANDLING.tagNameCheck. Default: `false`.562 */563 let CUSTOM_ELEMENT_HANDLING = Object.seal(create(null, {564 tagNameCheck: {565 writable: true,566 configurable: false,567 enumerable: true,568 value: null569 },570 attributeNameCheck: {571 writable: true,572 configurable: false,573 enumerable: true,574 value: null575 },576 allowCustomizedBuiltInElements: {577 writable: true,578 configurable: false,579 enumerable: true,580 value: false581 }582 }));583 /* Explicitly forbidden tags (overrides ALLOWED_TAGS/ADD_TAGS) */584 let FORBID_TAGS = null;585 /* Explicitly forbidden attributes (overrides ALLOWED_ATTR/ADD_ATTR) */586 let FORBID_ATTR = null;587 /* Config object to store ADD_TAGS/ADD_ATTR functions (when used as functions) */588 const EXTRA_ELEMENT_HANDLING = Object.seal(create(null, {589 tagCheck: {590 writable: true,591 configurable: false,592 enumerable: true,593 value: null594 },595 attributeCheck: {596 writable: true,597 configurable: false,598 enumerable: true,599 value: null600 }601 }));602 /* Decide if ARIA attributes are okay */603 let ALLOW_ARIA_ATTR = true;604 /* Decide if custom data attributes are okay */605 let ALLOW_DATA_ATTR = true;606 /* Decide if unknown protocols are okay */607 let ALLOW_UNKNOWN_PROTOCOLS = false;608 /* Decide if self-closing tags in attributes are allowed.609 * Usually removed due to a mXSS issue in jQuery 3.0 */610 let ALLOW_SELF_CLOSE_IN_ATTR = true;611 /* Output should be safe for common template engines.612 * This means, DOMPurify removes data attributes, mustaches and ERB613 */614 let SAFE_FOR_TEMPLATES = false;615 /* Output should be safe even for XML used within HTML and alike.616 * This means, DOMPurify removes comments when containing risky content.617 */618 let SAFE_FOR_XML = true;619 /* Decide if document with <html>... should be returned */620 let WHOLE_DOCUMENT = false;621 /* Track whether config is already set on this instance of DOMPurify. */622 let SET_CONFIG = false;623 /* Pristine allowlist bindings captured at setConfig() time. On the624 * persistent-config path sanitize() restores the sets from these before625 * the per-walk hook clone-guard, so a hook's in-call widening cannot626 * carry across calls. Null until setConfig() is called; reset by627 * clearConfig(). */628 let SET_CONFIG_ALLOWED_TAGS = null;629 let SET_CONFIG_ALLOWED_ATTR = null;630 /* Decide if all elements (e.g. style, script) must be children of631 * document.body. By default, browsers might move them to document.head */632 let FORCE_BODY = false;633 /* Decide if a DOM `HTMLBodyElement` should be returned, instead of a html634 * string (or a TrustedHTML object if Trusted Types are supported).635 * If `WHOLE_DOCUMENT` is enabled a `HTMLHtmlElement` will be returned instead636 */637 let RETURN_DOM = false;638 /* Decide if a DOM `DocumentFragment` should be returned, instead of a html639 * string (or a TrustedHTML object if Trusted Types are supported) */640 let RETURN_DOM_FRAGMENT = false;641 /* Try to return a Trusted Type object instead of a string, return a string in642 * case Trusted Types are not supported */643 let RETURN_TRUSTED_TYPE = false;644 /* Output should be free from DOM clobbering attacks?645 * This sanitizes markups named with colliding, clobberable built-in DOM APIs.646 */647 let SANITIZE_DOM = true;648 /* Achieve full DOM Clobbering protection by isolating the namespace of named649 * properties and JS variables, mitigating attacks that abuse the HTML/DOM spec rules.650 *651 * HTML/DOM spec rules that enable DOM Clobbering:652 * - Named Access on Window (§7.3.3)653 * - DOM Tree Accessors (§3.1.5)654 * - Form Element Parent-Child Relations (§4.10.3)655 * - Iframe srcdoc / Nested WindowProxies (§4.8.5)656 * - HTMLCollection (§4.2.10.2)657 *658 * Namespace isolation is implemented by prefixing `id` and `name` attributes659 * with a constant string, i.e., `user-content-`660 */661 let SANITIZE_NAMED_PROPS = false;662 const SANITIZE_NAMED_PROPS_PREFIX = 'user-content-';663 /* Keep element content when removing element? */664 let KEEP_CONTENT = true;665 /* If a `Node` is passed to sanitize(), then performs sanitization in-place instead666 * of importing it into a new Document and returning a sanitized copy */667 let IN_PLACE = false;668 /* Allow usage of profiles like html, svg and mathMl */669 let USE_PROFILES = {};670 /* Tags to ignore content of when KEEP_CONTENT is true */671 let FORBID_CONTENTS = null;672 const DEFAULT_FORBID_CONTENTS = addToSet({}, ['annotation-xml', 'audio', 'colgroup', 'desc', 'foreignobject', 'head', 'iframe', 'math', 'mi', 'mn', 'mo', 'ms', 'mtext', 'noembed', 'noframes', 'noscript', 'plaintext', 'script',673 // <selectedcontent> mirrors the selected <option>'s subtree, cloned by674 // the UA (customizable <select>) — including any on* handlers — and the675 // engine re-mirrors synchronously whenever a removal changes which676 // option/selectedcontent is current, even inside DOMPurify's inert677 // DOMParser document. Hoisting its children on removal re-inserts a fresh678 // mirror target ahead of the walk, which the engine refills, looping679 // forever (DoS) and amplifying output. Dropping its content on removal680 // (rather than hoisting) breaks that cascade; the content is a duplicate681 // of the option, which is sanitized on its own. See campaign-3 F1/F6.682 'selectedcontent', 'style', 'svg', 'template', 'thead', 'title', 'video', 'xmp']);683 /* Tags that are safe for data: URIs */684 let DATA_URI_TAGS = null;685 const DEFAULT_DATA_URI_TAGS = addToSet({}, ['audio', 'video', 'img', 'source', 'image', 'track']);686 /* Attributes safe for values like "javascript:" */687 let URI_SAFE_ATTRIBUTES = null;688 const DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, ['alt', 'class', 'for', 'id', 'label', 'name', 'pattern', 'placeholder', 'role', 'summary', 'title', 'value', 'style', 'xmlns']);689 const MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';690 const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';691 const HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';692 /* Document namespace */693 let NAMESPACE = HTML_NAMESPACE;694 let IS_EMPTY_INPUT = false;695 /* Allowed XHTML+XML namespaces */696 let ALLOWED_NAMESPACES = null;697 const DEFAULT_ALLOWED_NAMESPACES = addToSet({}, [MATHML_NAMESPACE, SVG_NAMESPACE, HTML_NAMESPACE], stringToString);698 const DEFAULT_MATHML_TEXT_INTEGRATION_POINTS = freeze(['mi', 'mo', 'mn', 'ms', 'mtext']);699 let MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, DEFAULT_MATHML_TEXT_INTEGRATION_POINTS);700 const DEFAULT_HTML_INTEGRATION_POINTS = freeze(['annotation-xml']);701 let HTML_INTEGRATION_POINTS = addToSet({}, DEFAULT_HTML_INTEGRATION_POINTS);702 // Certain elements are allowed in both SVG and HTML703 // namespace. We need to specify them explicitly704 // so that they don't get erroneously deleted from705 // HTML namespace.706 const COMMON_SVG_AND_HTML_ELEMENTS = addToSet({}, ['title', 'style', 'font', 'a', 'script']);707 /* Parsing of strict XHTML documents */708 let PARSER_MEDIA_TYPE = null;709 const SUPPORTED_PARSER_MEDIA_TYPES = ['application/xhtml+xml', 'text/html'];710 const DEFAULT_PARSER_MEDIA_TYPE = 'text/html';711 let transformCaseFunc = null;712 /* Keep a reference to config to pass to hooks */713 let CONFIG = null;714 /* Ideally, do not touch anything below this line */715 /* ______________________________________________ */716 const formElement = document.createElement('form');717 const isRegexOrFunction = function isRegexOrFunction(testValue) {718 return testValue instanceof RegExp || testValue instanceof Function;719 };720 /**721 * _parseConfig722 *723 * @param cfg optional config literal724 */725 // eslint-disable-next-line complexity726 const _parseConfig = function _parseConfig() {727 let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};728 if (CONFIG && CONFIG === cfg) {729 return;730 }731 /* Shield configuration object from tampering */732 if (!cfg || typeof cfg !== 'object') {733 cfg = {};734 }735 /* Shield configuration object from prototype pollution */736 cfg = clone(cfg);737 PARSER_MEDIA_TYPE =738 // eslint-disable-next-line unicorn/prefer-includes739 SUPPORTED_PARSER_MEDIA_TYPES.indexOf(cfg.PARSER_MEDIA_TYPE) === -1 ? DEFAULT_PARSER_MEDIA_TYPE : cfg.PARSER_MEDIA_TYPE;740 // HTML tags and attributes are not case-sensitive, converting to lowercase. Keeping XHTML as is.741 transformCaseFunc = PARSER_MEDIA_TYPE === 'application/xhtml+xml' ? stringToString : stringToLowerCase;742 /* Set configuration parameters */743 ALLOWED_TAGS = _resolveSetOption(cfg, 'ALLOWED_TAGS', DEFAULT_ALLOWED_TAGS, {744 transform: transformCaseFunc745 });746 ALLOWED_ATTR = _resolveSetOption(cfg, 'ALLOWED_ATTR', DEFAULT_ALLOWED_ATTR, {747 transform: transformCaseFunc748 });749 ALLOWED_NAMESPACES = _resolveSetOption(cfg, 'ALLOWED_NAMESPACES', DEFAULT_ALLOWED_NAMESPACES, {750 transform: stringToString751 });752 URI_SAFE_ATTRIBUTES = _resolveSetOption(cfg, 'ADD_URI_SAFE_ATTR', DEFAULT_URI_SAFE_ATTRIBUTES, {753 transform: transformCaseFunc,754 base: DEFAULT_URI_SAFE_ATTRIBUTES755 });756 DATA_URI_TAGS = _resolveSetOption(cfg, 'ADD_DATA_URI_TAGS', DEFAULT_DATA_URI_TAGS, {757 transform: transformCaseFunc,758 base: DEFAULT_DATA_URI_TAGS759 });760 FORBID_CONTENTS = _resolveSetOption(cfg, 'FORBID_CONTENTS', DEFAULT_FORBID_CONTENTS, {761 transform: transformCaseFunc762 });763 FORBID_TAGS = _resolveSetOption(cfg, 'FORBID_TAGS', clone({}), {764 transform: transformCaseFunc765 });766 FORBID_ATTR = _resolveSetOption(cfg, 'FORBID_ATTR', clone({}), {767 transform: transformCaseFunc768 });769 USE_PROFILES = objectHasOwnProperty(cfg, 'USE_PROFILES') ? cfg.USE_PROFILES && typeof cfg.USE_PROFILES === 'object' ? clone(cfg.USE_PROFILES) : cfg.USE_PROFILES : false;770 ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true771 ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true772 ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; // Default false773 ALLOW_SELF_CLOSE_IN_ATTR = cfg.ALLOW_SELF_CLOSE_IN_ATTR !== false; // Default true774 SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false; // Default false775 SAFE_FOR_XML = cfg.SAFE_FOR_XML !== false; // Default true776 WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false; // Default false777 RETURN_DOM = cfg.RETURN_DOM || false; // Default false778 RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false; // Default false779 RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false; // Default false780 FORCE_BODY = cfg.FORCE_BODY || false; // Default false781 SANITIZE_DOM = cfg.SANITIZE_DOM !== false; // Default true782 SANITIZE_NAMED_PROPS = cfg.SANITIZE_NAMED_PROPS || false; // Default false783 KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true784 IN_PLACE = cfg.IN_PLACE || false; // Default false785 IS_ALLOWED_URI$1 = isRegex(cfg.ALLOWED_URI_REGEXP) ? cfg.ALLOWED_URI_REGEXP : IS_ALLOWED_URI; // Default regexp786 NAMESPACE = typeof cfg.NAMESPACE === 'string' ? cfg.NAMESPACE : HTML_NAMESPACE; // Default HTML namespace787 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 map788 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 map789 const customElementHandling = objectHasOwnProperty(cfg, 'CUSTOM_ELEMENT_HANDLING') && cfg.CUSTOM_ELEMENT_HANDLING && typeof cfg.CUSTOM_ELEMENT_HANDLING === 'object' ? clone(cfg.CUSTOM_ELEMENT_HANDLING) : create(null);790 CUSTOM_ELEMENT_HANDLING = create(null);791 if (objectHasOwnProperty(customElementHandling, 'tagNameCheck') && isRegexOrFunction(customElementHandling.tagNameCheck)) {792 CUSTOM_ELEMENT_HANDLING.tagNameCheck = customElementHandling.tagNameCheck; // Default undefined793 }794 if (objectHasOwnProperty(customElementHandling, 'attributeNameCheck') && isRegexOrFunction(customElementHandling.attributeNameCheck)) {795 CUSTOM_ELEMENT_HANDLING.attributeNameCheck = customElementHandling.attributeNameCheck; // Default undefined796 }797 if (objectHasOwnProperty(customElementHandling, 'allowCustomizedBuiltInElements') && typeof customElementHandling.allowCustomizedBuiltInElements === 'boolean') {798 CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = customElementHandling.allowCustomizedBuiltInElements; // Default undefined799 }800 seal(CUSTOM_ELEMENT_HANDLING);801 if (SAFE_FOR_TEMPLATES) {802 ALLOW_DATA_ATTR = false;803 }804 if (RETURN_DOM_FRAGMENT) {805 RETURN_DOM = true;806 }807 /* Parse profile info */808 if (USE_PROFILES) {809 ALLOWED_TAGS = addToSet({}, text);810 ALLOWED_ATTR = create(null);811 if (USE_PROFILES.html === true) {812 addToSet(ALLOWED_TAGS, html$1);813 addToSet(ALLOWED_ATTR, html);814 }815 if (USE_PROFILES.svg === true) {816 addToSet(ALLOWED_TAGS, svg$1);817 addToSet(ALLOWED_ATTR, svg);818 addToSet(ALLOWED_ATTR, xml);819 }820 if (USE_PROFILES.svgFilters === true) {821 addToSet(ALLOWED_TAGS, svgFilters);822 addToSet(ALLOWED_ATTR, svg);823 addToSet(ALLOWED_ATTR, xml);824 }825 if (USE_PROFILES.mathMl === true) {826 addToSet(ALLOWED_TAGS, mathMl$1);827 addToSet(ALLOWED_ATTR, mathMl);828 addToSet(ALLOWED_ATTR, xml);829 }830 }831 /* Always reset function-based ADD_TAGS / ADD_ATTR checks to prevent832 * leaking across calls when switching from function to array config */833 EXTRA_ELEMENT_HANDLING.tagCheck = null;834 EXTRA_ELEMENT_HANDLING.attributeCheck = null;835 /* Merge configuration parameters */836 if (objectHasOwnProperty(cfg, 'ADD_TAGS')) {837 if (typeof cfg.ADD_TAGS === 'function') {838 EXTRA_ELEMENT_HANDLING.tagCheck = cfg.ADD_TAGS;839 } else if (arrayIsArray(cfg.ADD_TAGS)) {840 if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) {841 ALLOWED_TAGS = clone(ALLOWED_TAGS);842 }843 addToSet(ALLOWED_TAGS, cfg.ADD_TAGS, transformCaseFunc);844 }845 }846 if (objectHasOwnProperty(cfg, 'ADD_ATTR')) {847 if (typeof cfg.ADD_ATTR === 'function') {848 EXTRA_ELEMENT_HANDLING.attributeCheck = cfg.ADD_ATTR;849 } else if (arrayIsArray(cfg.ADD_ATTR)) {850 if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) {851 ALLOWED_ATTR = clone(ALLOWED_ATTR);852 }853 addToSet(ALLOWED_ATTR, cfg.ADD_ATTR, transformCaseFunc);854 }855 }856 if (objectHasOwnProperty(cfg, 'ADD_URI_SAFE_ATTR') && arrayIsArray(cfg.ADD_URI_SAFE_ATTR)) {857 addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR, transformCaseFunc);858 }859 if (objectHasOwnProperty(cfg, 'FORBID_CONTENTS') && arrayIsArray(cfg.FORBID_CONTENTS)) {860 if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {861 FORBID_CONTENTS = clone(FORBID_CONTENTS);862 }863 addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS, transformCaseFunc);864 }865 if (objectHasOwnProperty(cfg, 'ADD_FORBID_CONTENTS') && arrayIsArray(cfg.ADD_FORBID_CONTENTS)) {866 if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {867 FORBID_CONTENTS = clone(FORBID_CONTENTS);868 }869 addToSet(FORBID_CONTENTS, cfg.ADD_FORBID_CONTENTS, transformCaseFunc);870 }871 /* Add #text in case KEEP_CONTENT is set to true */872 if (KEEP_CONTENT) {873 ALLOWED_TAGS['#text'] = true;874 }875 /* Add html, head and body to ALLOWED_TAGS in case WHOLE_DOCUMENT is true */876 if (WHOLE_DOCUMENT) {877 addToSet(ALLOWED_TAGS, ['html', 'head', 'body']);878 }879 /* Add tbody to ALLOWED_TAGS in case tables are permitted, see #286, #365 */880 if (ALLOWED_TAGS.table) {881 addToSet(ALLOWED_TAGS, ['tbody']);882 delete FORBID_TAGS.tbody;883 }884 // Re-derive the active Trusted Types policy from this configuration on885 // every parse. The active policy must never be sticky closure state that886 // outlives the config that set it: a caller-supplied policy left in place887 // after `clearConfig()` — or after a later call that supplied none, or888 // `TRUSTED_TYPES_POLICY: null` — could sign a subsequent "default"889 // `RETURN_TRUSTED_TYPE` result with a foreign, possibly unsafe policy.890 // See GHSA-vxr8-fq34-vvx9.891 if (cfg.TRUSTED_TYPES_POLICY) {892 if (typeof cfg.TRUSTED_TYPES_POLICY.createHTML !== 'function') {893 throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');894 }895 if (typeof cfg.TRUSTED_TYPES_POLICY.createScriptURL !== 'function') {896 throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');897 }898 // A caller-supplied policy applies to this configuration only.899 const previousTrustedTypesPolicy = trustedTypesPolicy;900 trustedTypesPolicy = cfg.TRUSTED_TYPES_POLICY;901 // Sign local variables required by `sanitize`. If the supplied policy's902 // `createHTML` is circular (i.e. it calls `DOMPurify.sanitize`), this903 // throws via the re-entrancy guard. Restore the previous policy first so904 // the instance is not left in a poisoned state. See #1422.905 try {906 emptyHTML = _createTrustedHTML('');907 } catch (error) {908 trustedTypesPolicy = previousTrustedTypesPolicy;909 throw error;910 }911 } else if (cfg.TRUSTED_TYPES_POLICY === null) {912 // Explicit opt-out for this call: perform no Trusted Types signing and913 // create nothing (so a strict `trusted-types` CSP that disallows a914 // `dompurify` policy can still call `sanitize` from inside its own915 // policy — see #1422). Resetting to `undefined` rather than a sticky916 // `null` also drops any previously retained caller policy, so it cannot917 // resurface on a later call, while still allowing the next config-less918 // call to restore the internal default policy. See GHSA-vxr8-fq34-vvx9.919 trustedTypesPolicy = undefined;920 emptyHTML = '';921 } else {922 // No policy supplied: keep the currently active policy if one is set — a923 // previously supplied policy is intentionally sticky across config-less924 // calls — otherwise fall back to the instance's own internal policy,925 // created at most once. (A policy supplied for a *single* call still926 // lingers by design; what must not linger is a policy whose configuration927 // has been torn down via `clearConfig()`, which restores the default.)928 if (trustedTypesPolicy === undefined) {929 trustedTypesPolicy = _getDefaultTrustedTypesPolicy();930 }931 // Sign internal variables only when a policy is active. A falsy policy932 // (Trusted Types unsupported, creation failed, or an explicit opt-out)933 // leaves `emptyHTML` as a plain string, so we never call `.createHTML` on934 // a non-policy and throw. See #1422.935 if (trustedTypesPolicy && typeof emptyHTML === 'string') {936 emptyHTML = _createTrustedHTML('');937 }938 }939 // Prevent further manipulation of configuration.940 // Not available in IE8, Safari 5, etc.941 if (freeze) {942 freeze(cfg);943 }944 CONFIG = cfg;945 };946 /* Keep track of all possible SVG and MathML tags947 * so that we can perform the namespace checks948 * correctly. */949 const ALL_SVG_TAGS = addToSet({}, [...svg$1, ...svgFilters, ...svgDisallowed]);950 const ALL_MATHML_TAGS = addToSet({}, [...mathMl$1, ...mathMlDisallowed]);951 /**952 * Namespace rules for an element in the SVG namespace.953 *954 * @param tagName the element's lowercase tag name955 * @param parent the (possibly simulated) parent node956 * @param parentTagName the parent's lowercase tag name957 * @returns true if a spec-compliant parser could produce this element958 */959 const _checkSvgNamespace = function _checkSvgNamespace(tagName, parent, parentTagName) {960 // The only way to switch from HTML namespace to SVG961 // is via <svg>. If it happens via any other tag, then962 // it should be killed.963 if (parent.namespaceURI === HTML_NAMESPACE) {964 return tagName === 'svg';965 }966 // The only way to switch from MathML to SVG is via <svg>967 // if the parent is either <annotation-xml> or a MathML968 // text integration point.969 if (parent.namespaceURI === MATHML_NAMESPACE) {970 return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);971 }972 // We only allow elements that are defined in SVG973 // spec. All others are disallowed in SVG namespace.974 return Boolean(ALL_SVG_TAGS[tagName]);975 };976 /**977 * Namespace rules for an element in the MathML namespace.978 *979 * @param tagName the element's lowercase tag name980 * @param parent the (possibly simulated) parent node981 * @param parentTagName the parent's lowercase tag name982 * @returns true if a spec-compliant parser could produce this element983 */984 const _checkMathMlNamespace = function _checkMathMlNamespace(tagName, parent, parentTagName) {985 // The only way to switch from HTML namespace to MathML986 // is via <math>. If it happens via any other tag, then987 // it should be killed.988 if (parent.namespaceURI === HTML_NAMESPACE) {989 return tagName === 'math';990 }991 // The only way to switch from SVG to MathML is via992 // <math> and HTML integration points993 if (parent.namespaceURI === SVG_NAMESPACE) {994 return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName];995 }996 // We only allow elements that are defined in MathML997 // spec. All others are disallowed in MathML namespace.998 return Boolean(ALL_MATHML_TAGS[tagName]);999 };1000 /**1001 * Namespace rules for an element in the HTML namespace.1002 *1003 * @param tagName the element's lowercase tag name1004 * @param parent the (possibly simulated) parent node1005 * @param parentTagName the parent's lowercase tag name1006 * @returns true if a spec-compliant parser could produce this element1007 */1008 const _checkHtmlNamespace = function _checkHtmlNamespace(tagName, parent, parentTagName) {1009 // The only way to switch from SVG to HTML is via1010 // HTML integration points, and from MathML to HTML1011 // is via MathML text integration points1012 if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) {1013 return false;1014 }1015 if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {1016 return false;1017 }1018 // We disallow tags that are specific for MathML1019 // or SVG and should never appear in HTML namespace1020 return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]);1021 };1022 /**1023 * @param element a DOM element whose namespace is being checked1024 * @returns Return false if the element has a1025 * namespace that a spec-compliant parser would never1026 * return. Return true otherwise.1027 */1028 const _checkValidNamespace = function _checkValidNamespace(element) {1029 let parent = getParentNode(element);1030 // In JSDOM, if we're inside shadow DOM, then parentNode1031 // can be null. We just simulate parent in this case.1032 if (!parent || !parent.tagName) {1033 parent = {1034 namespaceURI: NAMESPACE,1035 tagName: 'template'1036 };1037 }1038 const tagName = stringToLowerCase(element.tagName);1039 const parentTagName = stringToLowerCase(parent.tagName);1040 if (!ALLOWED_NAMESPACES[element.namespaceURI]) {1041 return false;1042 }1043 if (element.namespaceURI === SVG_NAMESPACE) {1044 return _checkSvgNamespace(tagName, parent, parentTagName);1045 }1046 if (element.namespaceURI === MATHML_NAMESPACE) {1047 return _checkMathMlNamespace(tagName, parent, parentTagName);1048 }1049 if (element.namespaceURI === HTML_NAMESPACE) {1050 return _checkHtmlNamespace(tagName, parent, parentTagName);1051 }1052 // For XHTML and XML documents that support custom namespaces1053 if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && ALLOWED_NAMESPACES[element.namespaceURI]) {1054 return true;1055 }1056 // The code should never reach this place (this means1057 // that the element somehow got namespace that is not1058 // HTML, SVG, MathML or allowed via ALLOWED_NAMESPACES).1059 // Return false just in case.1060 return false;1061 };1062 /**1063 * _forceRemove1064 *1065 * @param node a DOM node1066 */1067 const _forceRemove = function _forceRemove(node) {1068 arrayPush(DOMPurify.removed, {1069 element: node1070 });1071 try {1072 // eslint-disable-next-line unicorn/prefer-dom-node-remove1073 getParentNode(node).removeChild(node);1074 } catch (_) {1075 /* The normal detach failed — this is reached for a parentless node1076 (getParentNode() is null, so .removeChild throws). Element.prototype1077 .remove() is itself a spec no-op on a parentless node, so a recorded1078 "removal" would otherwise hand the caller back an intact,1079 payload-bearing node (e.g. a detached IN_PLACE root the mXSS canary or1080 the style-with-element-child rule decided to kill). Fail closed by1081 throwing — exactly as a clobbered root does at the IN_PLACE entry —1082 rather than trying to "neutralize" the node via its own methods.1083 Neutralizing would mean calling getAttributeNames()/removeAttribute()1084 on the node, both of which a <form> root can clobber via a named child1085 (and _isClobbered does not even probe getAttributeNames), so the1086 neutralize step could itself be silently defeated, leaving the payload1087 intact. A throw touches only the cached, clobber-safe remove() and1088 getParentNode(). Generalizes GHSA-r47g-fvhr-h676 (clobbered-form root)1089 to every root-kill reason. REPORT-3.1090 This lives inside the catch, so it never fires for a normally-removed1091 in-tree node: those have a parent, removeChild() succeeds, and the1092 catch is not entered. Only a kept (parentless) root reaches here. */1093 remove(node);1094 if (!getParentNode(node)) {1095 throw typeErrorCreate('a node selected for removal could not be detached from its tree ' + 'and cannot be safely returned; refusing to sanitize in place');1096 }1097 }1098 };1099 /**1100 * _neutralizeRoot1101 *1102 * Fail-closed teardown of an in-place root after the sanitize walk aborts1103 * (campaign-3 F2). An internal throw mid-walk — e.g. a page-registered1104 * custom element's reaction detaches a node so `_forceRemove`'s deliberate1105 * parentless guard throws, or any other re-entrant engine mutation — would1106 * otherwise leave the caller's *live* tree half-sanitized, with everything1107 * after the abort point still carrying its handlers. There is no safe way1108 * to resume the walk (the tree mutated under us), so we strip the root bare:1109 * remove every child and every attribute, then let the caller's catch see1110 * the original error. Clobber-safe (cached `remove`/`childNodes`/`attributes`1111 * getters; the root was already clobber-pre-flighted at the IN_PLACE entry).1112 *1113 * @param root the in-place root to empty1114 */1115 const _neutralizeRoot = function _neutralizeRoot(root) {1116 /* Strip every disallowed attribute (on* handlers included) off the whole1117 subtree BEFORE detaching anything. Detaching first would hand back1118 handler-bearing originals (e.g. an already-loading `<img onerror>`)1119 whose queued resource event still fires in page scope after we throw.1120 Clobber-safe reads; a doomed clobbered node's own attributes are1121 irrelevant while its non-clobbered descendants are reached and scrubbed. */1122 _neutralizeSubtree(root);1123 const childNodes = getChildNodes(root);1124 if (childNodes) {1125 const snapshot = [];1126 arrayForEach(childNodes, child => {1127 arrayPush(snapshot, child);1128 });1129 arrayForEach(snapshot, child => {1130 try {1131 remove(child);1132 } catch (_) {1133 /* Best-effort teardown; a still-attached child is handled below */1134 }1135 });1136 }1137 const attributes = getAttributes(root);1138 if (attributes) {1139 for (let i = attributes.length - 1; i >= 0; --i) {1140 const attribute = attributes[i];1141 const name = attribute && attribute.name;1142 if (typeof name === 'string') {1143 try {1144 root.removeAttribute(name);1145 } catch (_) {1146 /* Clobbered removeAttribute — ignore (fail-closed best effort) */1147 }1148 }1149 }1150 }1151 };1152 /**1153 * _removeAttribute1154 *1155 * @param name an Attribute name1156 * @param element a DOM node1157 */1158 const _removeAttribute = function _removeAttribute(name, element) {1159 try {1160 arrayPush(DOMPurify.removed, {1161 attribute: element.getAttributeNode(name),1162 from: element1163 });1164 } catch (_) {1165 arrayPush(DOMPurify.removed, {1166 attribute: null,1167 from: element1168 });1169 }1170 element.removeAttribute(name);1171 // We void attribute values for unremovable "is" attributes1172 if (name === 'is') {1173 if (RETURN_DOM || RETURN_DOM_FRAGMENT) {1174 try {1175 _forceRemove(element);1176 } catch (_) {}1177 } else {1178 try {1179 element.setAttribute(name, '');1180 } catch (_) {}1181 }1182 }1183 };1184 /**1185 * _stripDisallowedAttributes1186 *1187 * Removes every attribute the active configuration does not allow from a1188 * single element, using the same allowlist as the main attribute pass (so1189 * `on*` handlers go, but no `/^on/` blocklist is introduced). Used only to1190 * neutralise nodes that are being discarded from an in-place tree.1191 *1192 * @param element the element to strip1193 */1194 const _stripDisallowedAttributes = function _stripDisallowedAttributes(element) {1195 const attributes = getAttributes(element);1196 if (!attributes) {1197 return;1198 }1199 for (let i = attributes.length - 1; i >= 0; --i) {1200 const attribute = attributes[i];