@wix/entity-advanced-permissions 1.1421.0 → 1.1422.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2760 @@
1
+ "use strict";
2
+ ((typeof self !== 'undefined' ? self : this)["webpackJsonp__wix_entity_advanced_permissions"] = (typeof self !== 'undefined' ? self : this)["webpackJsonp__wix_entity_advanced_permissions"] || []).push([[500],{
3
+
4
+ /***/ 7500
5
+ /*!********************************************************************************************!*\
6
+ !*** ../../../node_modules/@wix/wix-ui-icons-common/dist/esm/core/sanitize.js + 1 modules ***!
7
+ \********************************************************************************************/
8
+ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
9
+
10
+ // ESM COMPAT FLAG
11
+ __webpack_require__.r(__webpack_exports__);
12
+
13
+ // EXPORTS
14
+ __webpack_require__.d(__webpack_exports__, {
15
+ sanitizeSvgContent: () => (/* binding */ sanitizeSvgContent)
16
+ });
17
+
18
+ ;// ../../../node_modules/@wix/wix-ui-icons-common/node_modules/dompurify/dist/purify.es.mjs
19
+ /*! @license DOMPurify 3.4.15 | (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.15/LICENSE */
20
+
21
+ function _arrayLikeToArray(r, a) {
22
+ (null == a || a > r.length) && (a = r.length);
23
+ for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
24
+ return n;
25
+ }
26
+ function _arrayWithHoles(r) {
27
+ if (Array.isArray(r)) return r;
28
+ }
29
+ function _iterableToArrayLimit(r, l) {
30
+ var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
31
+ if (null != t) {
32
+ var e,
33
+ n,
34
+ i,
35
+ u,
36
+ a = [],
37
+ f = true,
38
+ o = false;
39
+ try {
40
+ 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);
41
+ } catch (r) {
42
+ o = true, n = r;
43
+ } finally {
44
+ try {
45
+ if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return;
46
+ } finally {
47
+ if (o) throw n;
48
+ }
49
+ }
50
+ return a;
51
+ }
52
+ }
53
+ function _nonIterableRest() {
54
+ throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
55
+ }
56
+ function _slicedToArray(r, e) {
57
+ return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest();
58
+ }
59
+ function _unsupportedIterableToArray(r, a) {
60
+ if (r) {
61
+ if ("string" == typeof r) return _arrayLikeToArray(r, a);
62
+ var t = {}.toString.call(r).slice(8, -1);
63
+ 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;
64
+ }
65
+ }
66
+
67
+ const entries = Object.entries,
68
+ setPrototypeOf = Object.setPrototypeOf,
69
+ isFrozen = Object.isFrozen,
70
+ getPrototypeOf = Object.getPrototypeOf,
71
+ getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
72
+ let freeze = Object.freeze,
73
+ seal = Object.seal,
74
+ create = Object.create; // eslint-disable-line import/no-mutable-exports
75
+ let _ref = typeof Reflect !== 'undefined' && Reflect,
76
+ apply = _ref.apply,
77
+ construct = _ref.construct;
78
+ if (!freeze) {
79
+ freeze = function freeze(x) {
80
+ return x;
81
+ };
82
+ }
83
+ if (!seal) {
84
+ seal = function seal(x) {
85
+ return x;
86
+ };
87
+ }
88
+ if (!apply) {
89
+ apply = function apply(func, thisArg) {
90
+ for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
91
+ args[_key - 2] = arguments[_key];
92
+ }
93
+ return func.apply(thisArg, args);
94
+ };
95
+ }
96
+ if (!construct) {
97
+ construct = function construct(Func) {
98
+ for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
99
+ args[_key2 - 1] = arguments[_key2];
100
+ }
101
+ return new Func(...args);
102
+ };
103
+ }
104
+ const arrayForEach = unapply(Array.prototype.forEach);
105
+ const arrayLastIndexOf = unapply(Array.prototype.lastIndexOf);
106
+ const arrayPop = unapply(Array.prototype.pop);
107
+ const arrayPush = unapply(Array.prototype.push);
108
+ const arraySplice = unapply(Array.prototype.splice);
109
+ const arrayIsArray = Array.isArray;
110
+ const stringToLowerCase = unapply(String.prototype.toLowerCase);
111
+ const stringToString = unapply(String.prototype.toString);
112
+ const stringMatch = unapply(String.prototype.match);
113
+ const stringReplace = unapply(String.prototype.replace);
114
+ const stringIndexOf = unapply(String.prototype.indexOf);
115
+ const stringTrim = unapply(String.prototype.trim);
116
+ const numberToString = unapply(Number.prototype.toString);
117
+ const booleanToString = unapply(Boolean.prototype.toString);
118
+ const bigintToString = typeof BigInt === 'undefined' ? null : unapply(BigInt.prototype.toString);
119
+ const symbolToString = typeof Symbol === 'undefined' ? null : unapply(Symbol.prototype.toString);
120
+ const objectHasOwnProperty = unapply(Object.prototype.hasOwnProperty);
121
+ const objectToString = unapply(Object.prototype.toString);
122
+ const regExpTest = unapply(RegExp.prototype.test);
123
+ const typeErrorCreate = unconstruct(TypeError);
124
+ /**
125
+ * Creates a new function that calls the given function with a specified thisArg and arguments.
126
+ *
127
+ * @param func - The function to be wrapped and called.
128
+ * @returns A new function that calls the given function with a specified thisArg and arguments.
129
+ */
130
+ function unapply(func) {
131
+ return function (thisArg) {
132
+ if (thisArg instanceof RegExp) {
133
+ thisArg.lastIndex = 0;
134
+ }
135
+ for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
136
+ args[_key3 - 1] = arguments[_key3];
137
+ }
138
+ return apply(func, thisArg, args);
139
+ };
140
+ }
141
+ /**
142
+ * Creates a new function that constructs an instance of the given constructor function with the provided arguments.
143
+ *
144
+ * @param func - The constructor function to be wrapped and called.
145
+ * @returns A new function that constructs an instance of the given constructor function with the provided arguments.
146
+ */
147
+ function unconstruct(Func) {
148
+ return function () {
149
+ for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
150
+ args[_key4] = arguments[_key4];
151
+ }
152
+ return construct(Func, args);
153
+ };
154
+ }
155
+ /**
156
+ * Add properties to a lookup table
157
+ *
158
+ * @param set - The set to which elements will be added.
159
+ * @param array - The array containing elements to be added to the set.
160
+ * @param transformCaseFunc - An optional function to transform the case of each element before adding to the set.
161
+ * @returns The modified set with added elements.
162
+ */
163
+ function addToSet(set, array) {
164
+ let transformCaseFunc = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : stringToLowerCase;
165
+ if (setPrototypeOf) {
166
+ // Make 'in' and truthy checks like Boolean(set.constructor)
167
+ // independent of any properties defined on Object.prototype.
168
+ // Prevent prototype setters from intercepting set as a this value.
169
+ setPrototypeOf(set, null);
170
+ }
171
+ if (!arrayIsArray(array)) {
172
+ return set;
173
+ }
174
+ let l = array.length;
175
+ while (l--) {
176
+ let element = array[l];
177
+ if (typeof element === 'string') {
178
+ const lcElement = transformCaseFunc(element);
179
+ if (lcElement !== element) {
180
+ // Config presets (e.g. tags.js, attrs.js) are immutable.
181
+ if (!isFrozen(array)) {
182
+ array[l] = lcElement;
183
+ }
184
+ element = lcElement;
185
+ }
186
+ }
187
+ set[element] = true;
188
+ }
189
+ return set;
190
+ }
191
+ /**
192
+ * Clean up an array to harden against CSPP
193
+ *
194
+ * @param array - The array to be cleaned.
195
+ * @returns The cleaned version of the array
196
+ */
197
+ function cleanArray(array) {
198
+ for (let index = 0; index < array.length; index++) {
199
+ const isPropertyExist = objectHasOwnProperty(array, index);
200
+ if (!isPropertyExist) {
201
+ array[index] = null;
202
+ }
203
+ }
204
+ return array;
205
+ }
206
+ /**
207
+ * Shallow clone an object
208
+ *
209
+ * @param object - The object to be cloned.
210
+ * @returns A new object that copies the original.
211
+ */
212
+ function clone(object) {
213
+ const newObject = create(null);
214
+ for (const _ref2 of entries(object)) {
215
+ var _ref3 = _slicedToArray(_ref2, 2);
216
+ const property = _ref3[0];
217
+ const value = _ref3[1];
218
+ const isPropertyExist = objectHasOwnProperty(object, property);
219
+ if (isPropertyExist) {
220
+ if (arrayIsArray(value)) {
221
+ newObject[property] = cleanArray(value);
222
+ } else if (value && typeof value === 'object' && value.constructor === Object) {
223
+ newObject[property] = clone(value);
224
+ } else {
225
+ newObject[property] = value;
226
+ }
227
+ }
228
+ }
229
+ return newObject;
230
+ }
231
+ /**
232
+ * Convert non-node values into strings without depending on direct property access.
233
+ *
234
+ * @param value - The value to stringify.
235
+ * @returns A string representation of the provided value.
236
+ */
237
+ function stringifyValue(value) {
238
+ switch (typeof value) {
239
+ case 'string':
240
+ {
241
+ return value;
242
+ }
243
+ case 'number':
244
+ {
245
+ return numberToString(value);
246
+ }
247
+ case 'boolean':
248
+ {
249
+ return booleanToString(value);
250
+ }
251
+ case 'bigint':
252
+ {
253
+ return bigintToString ? bigintToString(value) : '0';
254
+ }
255
+ case 'symbol':
256
+ {
257
+ return symbolToString ? symbolToString(value) : 'Symbol()';
258
+ }
259
+ case 'undefined':
260
+ {
261
+ return objectToString(value);
262
+ }
263
+ case 'function':
264
+ case 'object':
265
+ {
266
+ if (value === null) {
267
+ return objectToString(value);
268
+ }
269
+ const valueAsRecord = value;
270
+ const valueToString = lookupGetter(valueAsRecord, 'toString');
271
+ if (typeof valueToString === 'function') {
272
+ const stringified = valueToString(valueAsRecord);
273
+ return typeof stringified === 'string' ? stringified : objectToString(stringified);
274
+ }
275
+ return objectToString(value);
276
+ }
277
+ default:
278
+ {
279
+ return objectToString(value);
280
+ }
281
+ }
282
+ }
283
+ /**
284
+ * This method automatically checks if the prop is function or getter and behaves accordingly.
285
+ *
286
+ * @param object - The object to look up the getter function in its prototype chain.
287
+ * @param prop - The property name for which to find the getter function.
288
+ * @returns The getter function found in the prototype chain or a fallback function.
289
+ */
290
+ function lookupGetter(object, prop) {
291
+ while (object !== null) {
292
+ const desc = getOwnPropertyDescriptor(object, prop);
293
+ if (desc) {
294
+ if (desc.get) {
295
+ return unapply(desc.get);
296
+ }
297
+ if (typeof desc.value === 'function') {
298
+ return unapply(desc.value);
299
+ }
300
+ }
301
+ object = getPrototypeOf(object);
302
+ }
303
+ function fallbackValue() {
304
+ return null;
305
+ }
306
+ return fallbackValue;
307
+ }
308
+ function isRegex(value) {
309
+ try {
310
+ regExpTest(value, '');
311
+ return true;
312
+ } catch (_unused) {
313
+ return false;
314
+ }
315
+ }
316
+
317
+ 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']);
318
+ 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']);
319
+ 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']);
320
+ // List of SVG elements that are disallowed by default.
321
+ // We still need to know them so that we can do namespace
322
+ // checks properly in case one wants to add them to
323
+ // allow-list.
324
+ 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']);
325
+ 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']);
326
+ // Similarly to SVG, we want to know all MathML elements,
327
+ // even those that we disallow by default.
328
+ const mathMlDisallowed = freeze(['maction', 'maligngroup', 'malignmark', 'mlongdiv', 'mscarries', 'mscarry', 'msgroup', 'mstack', 'msline', 'msrow', 'semantics', 'annotation', 'annotation-xml', 'mprescripts', 'none']);
329
+ const purify_es_text = freeze(['#text']);
330
+
331
+ 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']);
332
+ 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', 'pointer-events', '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', 'vector-effect', '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']);
333
+ 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']);
334
+ const xml = freeze(['xlink:href', 'xml:id', 'xlink:title', 'xml:space', 'xmlns:xlink']);
335
+
336
+ const MUSTACHE_EXPR = seal(/{{[\w\W]*|^[\w\W]*}}/g);
337
+ const ERB_EXPR = seal(/<%[\w\W]*|^[\w\W]*%>/g);
338
+ const TMPLIT_EXPR = seal(/\${[\w\W]*/g);
339
+ const DATA_ATTR = seal(/^data-[\-\w.\u00B7-\uFFFF]+$/); // eslint-disable-line no-useless-escape
340
+ const ARIA_ATTR = seal(/^aria-[\-\w]+$/); // eslint-disable-line no-useless-escape
341
+ 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-escape
342
+ );
343
+ const IS_SCRIPT_OR_DATA = seal(/^(?:\w+script|data):/i);
344
+ const ATTR_WHITESPACE = seal(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g // eslint-disable-line no-control-regex
345
+ );
346
+ const DOCTYPE_NAME = seal(/^html$/i);
347
+ const CUSTOM_ELEMENT = seal(/^[a-z][.\w]*(-[.\w]+)+$/i);
348
+ // Markup-significant character probes used by _sanitizeElements.
349
+ // Shared module-level instances are safe despite the sticky /g flags:
350
+ // unapply() resets lastIndex for RegExp receivers before every call.
351
+ const ELEMENT_MARKUP_PROBE = seal(/<[/\w!]/g);
352
+ const COMMENT_MARKUP_PROBE = seal(/<[/\w]/g);
353
+ const FALLBACK_TAG_CLOSE = seal(/<\/no(script|embed|frames)/i);
354
+ const SELF_CLOSING_TAG = seal(/\/>/i);
355
+
356
+ // https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType
357
+ const NODE_TYPE = {
358
+ element: 1,
359
+ attribute: 2,
360
+ text: 3,
361
+ cdataSection: 4,
362
+ entityReference: 5,
363
+ // Deprecated
364
+ entityNode: 6,
365
+ // Deprecated
366
+ processingInstruction: 7,
367
+ comment: 8,
368
+ document: 9,
369
+ documentType: 10,
370
+ documentFragment: 11,
371
+ notation: 12 // Deprecated
372
+ };
373
+ /* HTML-namespace elements whose child text nodes are serialized *literally*
374
+ (unescaped) by the HTML fragment-serialization algorithm. Two reparse-mXSS
375
+ shapes ride on that literal serialization:
376
+ (a) an element child - a tree the HTML parser can never build, but the DOM
377
+ API and an XML/XHTML parse can - after which a `</tag>`-bearing text
378
+ sibling breaks the element open on reparse; and
379
+ (b) text-only content that already carries the element's OWN end tag, e.g.
380
+ `<style>...</style><img onerror=x>` built as a node, which the literal
381
+ serializer emits verbatim for the HTML parser to re-open.
382
+ Shape (a) is handled by the firstElementChild branch in _isUnsafeNode; shape
383
+ (b) by the LITERAL_TEXT_CLOSE probe. Both read textContent (the raw-serialized
384
+ form for these elements) rather than innerHTML, because an XML/XHTML working
385
+ document serializes innerHTML with `<` escaped, which silently blinds the
386
+ innerHTML-based probes (rule 1's second probe and FALLBACK_TAG_CLOSE) there.
387
+ `script` is never allow-listed, but is kept here so the guard matches the
388
+ serializer's own literal-text list exactly. */
389
+ const LITERAL_TEXT_ELEMENT_NAMES = ['style', 'script', 'xmp', 'iframe', 'noembed', 'noframes', 'plaintext', 'noscript'];
390
+ const LITERAL_TEXT_ELEMENTS = freeze(addToSet({}, LITERAL_TEXT_ELEMENT_NAMES));
391
+ /* Per-element end-tag matcher. On an HTML reparse the ONLY token that
392
+ terminates a literal-text element's raw content is its own end tag; a foreign
393
+ literal-text close (e.g. `</xmp>` sitting inside `<style>`) does not break
394
+ out, so matching is per-element, not a shared alternation. The lookahead
395
+ requires an HTML tag-name terminator (whitespace, `/` or `>`) so a longer
396
+ name such as `</styles` is not mistaken for `</style`. */
397
+ const LITERAL_TEXT_CLOSE = function () {
398
+ const map = {};
399
+ arrayForEach(LITERAL_TEXT_ELEMENT_NAMES, name => {
400
+ map[name] = seal(new RegExp('</' + name + '(?=[\\t\\n\\f\\r />])', 'i'));
401
+ });
402
+ return freeze(map);
403
+ }();
404
+ const getGlobal = function getGlobal() {
405
+ return typeof window === 'undefined' ? null : window;
406
+ };
407
+ /**
408
+ * Creates a no-op policy for internal use only.
409
+ * Don't export this function outside this module!
410
+ * @param trustedTypes The policy factory.
411
+ * @param purifyHostElement The Script element used to load DOMPurify (to determine policy name suffix).
412
+ * @return The policy created (or null, if Trusted Types
413
+ * are not supported or creating the policy failed).
414
+ */
415
+ const _createTrustedTypesPolicy = function _createTrustedTypesPolicy(trustedTypes, purifyHostElement) {
416
+ if (typeof trustedTypes !== 'object' || typeof trustedTypes.createPolicy !== 'function') {
417
+ return null;
418
+ }
419
+ // Allow the callers to control the unique policy name
420
+ // by adding a data-tt-policy-suffix to the script element with the DOMPurify.
421
+ // Policy creation with duplicate names throws in Trusted Types.
422
+ let suffix = null;
423
+ const ATTR_NAME = 'data-tt-policy-suffix';
424
+ if (purifyHostElement && purifyHostElement.hasAttribute(ATTR_NAME)) {
425
+ suffix = purifyHostElement.getAttribute(ATTR_NAME);
426
+ }
427
+ const policyName = 'dompurify' + (suffix ? '#' + suffix : '');
428
+ try {
429
+ return trustedTypes.createPolicy(policyName, {
430
+ createHTML(html) {
431
+ return html;
432
+ },
433
+ createScriptURL(scriptUrl) {
434
+ return scriptUrl;
435
+ }
436
+ });
437
+ } catch (_) {
438
+ // Policy creation failed (most likely another DOMPurify script has
439
+ // already run). Skip creating the policy, as this will only cause errors
440
+ // if TT are enforced.
441
+ console.warn('TrustedTypes policy ' + policyName + ' could not be created.');
442
+ return null;
443
+ }
444
+ };
445
+ const _createHooksMap = function _createHooksMap() {
446
+ return {
447
+ afterSanitizeAttributes: [],
448
+ afterSanitizeElements: [],
449
+ afterSanitizeShadowDOM: [],
450
+ beforeSanitizeAttributes: [],
451
+ beforeSanitizeElements: [],
452
+ beforeSanitizeShadowDOM: [],
453
+ uponSanitizeAttribute: [],
454
+ uponSanitizeElement: [],
455
+ uponSanitizeShadowNode: []
456
+ };
457
+ };
458
+ /**
459
+ * Resolve a set-valued configuration option: a fresh set built from
460
+ * cfg[key] when it is an own array property (seeded with a clone of
461
+ * options.base when given, case-normalized via options.transform),
462
+ * the fallback set otherwise.
463
+ *
464
+ * @param cfg the cloned, prototype-free configuration object
465
+ * @param key the configuration property to read
466
+ * @param fallback the set to use when the option is absent or not an array
467
+ * @param options transform and optional base set to merge into
468
+ * @returns the resolved set
469
+ */
470
+ const _resolveSetOption = function _resolveSetOption(cfg, key, fallback, options) {
471
+ return objectHasOwnProperty(cfg, key) && arrayIsArray(cfg[key]) ? addToSet(options.base ? clone(options.base) : {}, cfg[key], options.transform) : fallback;
472
+ };
473
+ /**
474
+ * Resolve an object-valued configuration option: a prototype-free clone
475
+ * of cfg[key] when it is an own, truthy object property, else a fresh
476
+ * fallback built by makeFallback (fresh on every parse, so a previous
477
+ * parse can never leak state into the next one).
478
+ *
479
+ * @param cfg the cloned, prototype-free configuration object
480
+ * @param key the configuration property to read
481
+ * @param makeFallback builds the fallback value when the option is absent
482
+ * @returns the resolved object
483
+ */
484
+ const _resolveObjectOption = function _resolveObjectOption(cfg, key, makeFallback) {
485
+ const value = objectHasOwnProperty(cfg, key) ? cfg[key] : undefined;
486
+ return value && typeof value === 'object' ? clone(value) : makeFallback();
487
+ };
488
+ function createDOMPurify() {
489
+ let window = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getGlobal();
490
+ const DOMPurify = root => createDOMPurify(root);
491
+ DOMPurify.version = '3.4.15';
492
+ DOMPurify.removed = [];
493
+ if (!window || !window.document || window.document.nodeType !== NODE_TYPE.document || !window.Element) {
494
+ // Not running in a browser, provide a factory function
495
+ // so that you can pass your own Window
496
+ DOMPurify.isSupported = false;
497
+ return DOMPurify;
498
+ }
499
+ let document = window.document;
500
+ const originalDocument = document;
501
+ const currentScript = originalDocument.currentScript;
502
+ window.DocumentFragment;
503
+ const HTMLTemplateElement = window.HTMLTemplateElement,
504
+ Node = window.Node,
505
+ Element = window.Element,
506
+ NodeFilter = window.NodeFilter,
507
+ _window$NamedNodeMap = window.NamedNodeMap;
508
+ _window$NamedNodeMap === void 0 ? window.NamedNodeMap || window.MozNamedAttrMap : _window$NamedNodeMap;
509
+ window.HTMLFormElement;
510
+ const DOMParser = window.DOMParser,
511
+ trustedTypes = window.trustedTypes;
512
+ const ElementPrototype = Element.prototype;
513
+ const cloneNode = lookupGetter(ElementPrototype, 'cloneNode');
514
+ const remove = lookupGetter(ElementPrototype, 'remove');
515
+ // Clobber-safe Attr-node removal. On an HTMLFormElement a descendant named
516
+ // "removeAttributeNode" shadows the prototype method via
517
+ // [LegacyOverrideBuiltIns], so element.removeAttributeNode(attr) throws.
518
+ // Calling the cached Element.prototype method with the element as the
519
+ // receiver removes the exact live Attr node regardless of the shadowing.
520
+ const removeAttributeNode = lookupGetter(ElementPrototype, 'removeAttributeNode');
521
+ const getNextSibling = lookupGetter(ElementPrototype, 'nextSibling');
522
+ const getChildNodes = lookupGetter(ElementPrototype, 'childNodes');
523
+ const getParentNode = lookupGetter(ElementPrototype, 'parentNode');
524
+ const getShadowRoot = lookupGetter(ElementPrototype, 'shadowRoot');
525
+ const getAttributes = lookupGetter(ElementPrototype, 'attributes');
526
+ const getNodeType = Node && Node.prototype ? lookupGetter(Node.prototype, 'nodeType') : null;
527
+ const getNodeName = Node && Node.prototype ? lookupGetter(Node.prototype, 'nodeName') : null;
528
+ const getOwnerDocument = Node && Node.prototype ? lookupGetter(Node.prototype, 'ownerDocument') : null;
529
+ /* Clobber-safe nodeType / nodeName reads through the cached Node.prototype
530
+ getters, with a direct-property fallback for environments that lack
531
+ Node.prototype. Sites that need a different fallback (e.g. _isClobbered
532
+ returns early on a null name) intentionally keep their own reads. */
533
+ const _readNodeType = function _readNodeType(node) {
534
+ return getNodeType ? getNodeType(node) : node.nodeType;
535
+ };
536
+ const _readNodeName = function _readNodeName(node) {
537
+ return getNodeName ? getNodeName(node) : node.nodeName;
538
+ };
539
+ // As per issue #47, the web-components registry is inherited by a
540
+ // new document created via createHTMLDocument. As per the spec
541
+ // (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-registries)
542
+ // a new empty registry is used when creating a template contents owner
543
+ // document, so we use that as our parent document to ensure nothing
544
+ // is inherited.
545
+ if (typeof HTMLTemplateElement === 'function') {
546
+ const template = document.createElement('template');
547
+ if (template.content && template.content.ownerDocument) {
548
+ document = template.content.ownerDocument;
549
+ }
550
+ }
551
+ let trustedTypesPolicy;
552
+ let emptyHTML = '';
553
+ // The instance's own internal Trusted Types policy. Unlike a caller-supplied
554
+ // `TRUSTED_TYPES_POLICY`, this is created at most once — Trusted Types throws
555
+ // on duplicate policy names — and is the only policy allowed to persist
556
+ // across configurations and survive `clearConfig()`.
557
+ let defaultTrustedTypesPolicy;
558
+ let defaultTrustedTypesPolicyResolved = false;
559
+ // Tracks whether we are already inside a call to the configured Trusted Types
560
+ // policy (`createHTML` or `createScriptURL`). If a supplied policy callback
561
+ // itself calls `DOMPurify.sanitize` (the cause of #1422), `sanitize` would
562
+ // re-enter the policy and recurse until the stack overflows. We detect that
563
+ // re-entry and throw a clear, actionable error instead. The guard is shared
564
+ // across both callbacks, because either one re-entering `sanitize` triggers
565
+ // the same unbounded recursion.
566
+ let IN_TRUSTED_TYPES_POLICY = 0;
567
+ const _assertNotInTrustedTypesPolicy = function _assertNotInTrustedTypesPolicy() {
568
+ if (IN_TRUSTED_TYPES_POLICY > 0) {
569
+ 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.');
570
+ }
571
+ };
572
+ const _createTrustedHTML = function _createTrustedHTML(html) {
573
+ _assertNotInTrustedTypesPolicy();
574
+ IN_TRUSTED_TYPES_POLICY++;
575
+ try {
576
+ return trustedTypesPolicy.createHTML(html);
577
+ } finally {
578
+ IN_TRUSTED_TYPES_POLICY--;
579
+ }
580
+ };
581
+ const _createTrustedScriptURL = function _createTrustedScriptURL(scriptUrl) {
582
+ _assertNotInTrustedTypesPolicy();
583
+ IN_TRUSTED_TYPES_POLICY++;
584
+ try {
585
+ return trustedTypesPolicy.createScriptURL(scriptUrl);
586
+ } finally {
587
+ IN_TRUSTED_TYPES_POLICY--;
588
+ }
589
+ };
590
+ // Lazily resolve (and cache) the instance's internal default policy.
591
+ // Resolution is attempted at most once: a successful `createPolicy` cannot be
592
+ // repeated (Trusted Types throws on duplicate names), and a failed or
593
+ // unsupported attempt must not be retried on every parse.
594
+ const _getDefaultTrustedTypesPolicy = function _getDefaultTrustedTypesPolicy() {
595
+ if (!defaultTrustedTypesPolicyResolved) {
596
+ defaultTrustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, currentScript);
597
+ defaultTrustedTypesPolicyResolved = true;
598
+ }
599
+ return defaultTrustedTypesPolicy;
600
+ };
601
+ const _document = document,
602
+ implementation = _document.implementation,
603
+ createNodeIterator = _document.createNodeIterator,
604
+ createDocumentFragment = _document.createDocumentFragment,
605
+ getElementsByTagName = _document.getElementsByTagName;
606
+ const importNode = originalDocument.importNode;
607
+ let hooks = _createHooksMap();
608
+ /**
609
+ * Expose whether this browser supports running the full DOMPurify.
610
+ */
611
+ DOMPurify.isSupported = typeof entries === 'function' && typeof getParentNode === 'function' && implementation && implementation.createHTMLDocument !== undefined;
612
+ const MUSTACHE_EXPR$1 = MUSTACHE_EXPR,
613
+ ERB_EXPR$1 = ERB_EXPR,
614
+ TMPLIT_EXPR$1 = TMPLIT_EXPR,
615
+ DATA_ATTR$1 = DATA_ATTR,
616
+ ARIA_ATTR$1 = ARIA_ATTR,
617
+ IS_SCRIPT_OR_DATA$1 = IS_SCRIPT_OR_DATA,
618
+ ATTR_WHITESPACE$1 = ATTR_WHITESPACE,
619
+ CUSTOM_ELEMENT$1 = CUSTOM_ELEMENT;
620
+ let IS_ALLOWED_URI$1 = IS_ALLOWED_URI;
621
+ /**
622
+ * We consider the elements and attributes below to be safe. Ideally
623
+ * don't add any new ones but feel free to remove unwanted ones.
624
+ */
625
+ /* allowed element names */
626
+ let ALLOWED_TAGS = null;
627
+ const DEFAULT_ALLOWED_TAGS = addToSet({}, [...html$1, ...svg$1, ...svgFilters, ...mathMl$1, ...purify_es_text]);
628
+ /* Allowed attribute names */
629
+ let ALLOWED_ATTR = null;
630
+ const DEFAULT_ALLOWED_ATTR = addToSet({}, [...html, ...svg, ...mathMl, ...xml]);
631
+ /*
632
+ * Configure how DOMPurify should handle custom elements and their attributes as well as customized built-in elements.
633
+ * @property {RegExp|Function|null} tagNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any custom elements)
634
+ * @property {RegExp|Function|null} attributeNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any attributes not on the allow list)
635
+ * @property {boolean} allowCustomizedBuiltInElements allow custom elements derived from built-ins if they pass CUSTOM_ELEMENT_HANDLING.tagNameCheck. Default: `false`.
636
+ */
637
+ let CUSTOM_ELEMENT_HANDLING = Object.seal(create(null, {
638
+ tagNameCheck: {
639
+ writable: true,
640
+ configurable: false,
641
+ enumerable: true,
642
+ value: null
643
+ },
644
+ attributeNameCheck: {
645
+ writable: true,
646
+ configurable: false,
647
+ enumerable: true,
648
+ value: null
649
+ },
650
+ allowCustomizedBuiltInElements: {
651
+ writable: true,
652
+ configurable: false,
653
+ enumerable: true,
654
+ value: false
655
+ }
656
+ }));
657
+ /* Explicitly forbidden tags (overrides ALLOWED_TAGS/ADD_TAGS) */
658
+ let FORBID_TAGS = null;
659
+ /* Explicitly forbidden attributes (overrides ALLOWED_ATTR/ADD_ATTR) */
660
+ let FORBID_ATTR = null;
661
+ /* Config object to store ADD_TAGS/ADD_ATTR functions (when used as functions) */
662
+ const EXTRA_ELEMENT_HANDLING = Object.seal(create(null, {
663
+ tagCheck: {
664
+ writable: true,
665
+ configurable: false,
666
+ enumerable: true,
667
+ value: null
668
+ },
669
+ attributeCheck: {
670
+ writable: true,
671
+ configurable: false,
672
+ enumerable: true,
673
+ value: null
674
+ }
675
+ }));
676
+ /* Decide if ARIA attributes are okay */
677
+ let ALLOW_ARIA_ATTR = true;
678
+ /* Decide if custom data attributes are okay */
679
+ let ALLOW_DATA_ATTR = true;
680
+ /* Decide if unknown protocols are okay */
681
+ let ALLOW_UNKNOWN_PROTOCOLS = false;
682
+ /* Decide if self-closing tags in attributes are allowed.
683
+ * Usually removed due to a mXSS issue in jQuery 3.0 */
684
+ let ALLOW_SELF_CLOSE_IN_ATTR = true;
685
+ /* Output should be safe for common template engines.
686
+ * This means, DOMPurify removes data attributes, mustaches and ERB
687
+ */
688
+ let SAFE_FOR_TEMPLATES = false;
689
+ /* Output should be safe even for XML used within HTML and alike.
690
+ * This means, DOMPurify removes comments when containing risky content.
691
+ */
692
+ let SAFE_FOR_XML = true;
693
+ /* Decide if document with <html>... should be returned */
694
+ let WHOLE_DOCUMENT = false;
695
+ /* Track whether config is already set on this instance of DOMPurify. */
696
+ let SET_CONFIG = false;
697
+ /* Pristine allowlist bindings captured at setConfig() time. On the
698
+ * persistent-config path sanitize() restores the sets from these before
699
+ * the per-walk hook clone-guard, so a hook's in-call widening cannot
700
+ * carry across calls. Null until setConfig() is called; reset by
701
+ * clearConfig(). */
702
+ let SET_CONFIG_ALLOWED_TAGS = null;
703
+ let SET_CONFIG_ALLOWED_ATTR = null;
704
+ /* Decide if all elements (e.g. style, script) must be children of
705
+ * document.body. By default, browsers might move them to document.head */
706
+ let FORCE_BODY = false;
707
+ /* Decide if a DOM `HTMLBodyElement` should be returned, instead of a html
708
+ * string (or a TrustedHTML object if Trusted Types are supported).
709
+ * If `WHOLE_DOCUMENT` is enabled a `HTMLHtmlElement` will be returned instead
710
+ */
711
+ let RETURN_DOM = false;
712
+ /* Decide if a DOM `DocumentFragment` should be returned, instead of a html
713
+ * string (or a TrustedHTML object if Trusted Types are supported) */
714
+ let RETURN_DOM_FRAGMENT = false;
715
+ /* Try to return a Trusted Type object instead of a string, return a string in
716
+ * case Trusted Types are not supported */
717
+ let RETURN_TRUSTED_TYPE = false;
718
+ /* Output should be free from DOM clobbering attacks?
719
+ * This sanitizes markups named with colliding, clobberable built-in DOM APIs.
720
+ */
721
+ let SANITIZE_DOM = true;
722
+ /* Achieve full DOM Clobbering protection by isolating the namespace of named
723
+ * properties and JS variables, mitigating attacks that abuse the HTML/DOM spec rules.
724
+ *
725
+ * HTML/DOM spec rules that enable DOM Clobbering:
726
+ * - Named Access on Window (§7.3.3)
727
+ * - DOM Tree Accessors (§3.1.5)
728
+ * - Form Element Parent-Child Relations (§4.10.3)
729
+ * - Iframe srcdoc / Nested WindowProxies (§4.8.5)
730
+ * - HTMLCollection (§4.2.10.2)
731
+ *
732
+ * Namespace isolation is implemented by prefixing `id` and `name` attributes
733
+ * with a constant string, i.e., `user-content-`
734
+ */
735
+ let SANITIZE_NAMED_PROPS = false;
736
+ const SANITIZE_NAMED_PROPS_PREFIX = 'user-content-';
737
+ /* Keep element content when removing element? */
738
+ let KEEP_CONTENT = true;
739
+ /* If a `Node` is passed to sanitize(), then performs sanitization in-place instead
740
+ * of importing it into a new Document and returning a sanitized copy */
741
+ let IN_PLACE = false;
742
+ /* Allow usage of profiles like html, svg and mathMl */
743
+ let USE_PROFILES = {};
744
+ /* Tags to ignore content of when KEEP_CONTENT is true */
745
+ let FORBID_CONTENTS = null;
746
+ const DEFAULT_FORBID_CONTENTS = addToSet({}, ['annotation-xml', 'audio', 'colgroup', 'desc', 'foreignobject', 'head', 'iframe', 'math', 'mi', 'mn', 'mo', 'ms', 'mtext', 'noembed', 'noframes', 'noscript', 'plaintext', 'script',
747
+ // <selectedcontent> mirrors the selected <option>'s subtree, cloned by
748
+ // the UA (customizable <select>) — including any on* handlers — and the
749
+ // engine re-mirrors synchronously whenever a removal changes which
750
+ // option/selectedcontent is current, even inside DOMPurify's inert
751
+ // DOMParser document. Hoisting its children on removal re-inserts a fresh
752
+ // mirror target ahead of the walk, which the engine refills, looping
753
+ // forever (DoS) and amplifying output. Dropping its content on removal
754
+ // (rather than hoisting) breaks that cascade; the content is a duplicate
755
+ // of the option, which is sanitized on its own. See campaign-3 F1/F6.
756
+ 'selectedcontent', 'style', 'svg', 'template', 'thead', 'title', 'video', 'xmp']);
757
+ /* Tags that are safe for data: URIs */
758
+ let DATA_URI_TAGS = null;
759
+ const DEFAULT_DATA_URI_TAGS = addToSet({}, ['audio', 'video', 'img', 'source', 'image', 'track']);
760
+ /* Attributes safe for values like "javascript:" */
761
+ let URI_SAFE_ATTRIBUTES = null;
762
+ const DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, ['alt', 'class', 'for', 'id', 'label', 'name', 'pattern', 'placeholder', 'role', 'summary', 'title', 'value', 'style', 'xmlns']);
763
+ const MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';
764
+ const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';
765
+ const HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';
766
+ /* Document namespace */
767
+ let NAMESPACE = HTML_NAMESPACE;
768
+ let IS_EMPTY_INPUT = false;
769
+ /* Allowed XHTML+XML namespaces */
770
+ let ALLOWED_NAMESPACES = null;
771
+ const DEFAULT_ALLOWED_NAMESPACES = addToSet({}, [MATHML_NAMESPACE, SVG_NAMESPACE, HTML_NAMESPACE], stringToString);
772
+ const DEFAULT_MATHML_TEXT_INTEGRATION_POINTS = freeze(['mi', 'mo', 'mn', 'ms', 'mtext']);
773
+ let MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, DEFAULT_MATHML_TEXT_INTEGRATION_POINTS);
774
+ const DEFAULT_HTML_INTEGRATION_POINTS = freeze(['annotation-xml']);
775
+ let HTML_INTEGRATION_POINTS = addToSet({}, DEFAULT_HTML_INTEGRATION_POINTS);
776
+ // Certain elements are allowed in both SVG and HTML
777
+ // namespace. We need to specify them explicitly
778
+ // so that they don't get erroneously deleted from
779
+ // HTML namespace.
780
+ const COMMON_SVG_AND_HTML_ELEMENTS = addToSet({}, ['title', 'style', 'font', 'a', 'script']);
781
+ /* Parsing of strict XHTML documents */
782
+ let PARSER_MEDIA_TYPE = null;
783
+ const SUPPORTED_PARSER_MEDIA_TYPES = ['application/xhtml+xml', 'text/html'];
784
+ const DEFAULT_PARSER_MEDIA_TYPE = 'text/html';
785
+ let transformCaseFunc = null;
786
+ /* Keep a reference to config to pass to hooks */
787
+ let CONFIG = null;
788
+ /* Ideally, do not touch anything below this line */
789
+ /* ______________________________________________ */
790
+ const formElement = document.createElement('form');
791
+ const isRegexOrFunction = function isRegexOrFunction(testValue) {
792
+ return testValue instanceof RegExp || testValue instanceof Function;
793
+ };
794
+ /**
795
+ * _parseConfig
796
+ *
797
+ * @param cfg optional config literal
798
+ */
799
+ // eslint-disable-next-line complexity
800
+ const _parseConfig = function _parseConfig() {
801
+ let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
802
+ if (CONFIG && CONFIG === cfg) {
803
+ return;
804
+ }
805
+ /* Shield configuration object from tampering */
806
+ if (!cfg || typeof cfg !== 'object') {
807
+ cfg = {};
808
+ }
809
+ /* Shield configuration object from prototype pollution */
810
+ cfg = clone(cfg);
811
+ PARSER_MEDIA_TYPE =
812
+ // eslint-disable-next-line unicorn/prefer-includes
813
+ SUPPORTED_PARSER_MEDIA_TYPES.indexOf(cfg.PARSER_MEDIA_TYPE) === -1 ? DEFAULT_PARSER_MEDIA_TYPE : cfg.PARSER_MEDIA_TYPE;
814
+ // HTML tags and attributes are not case-sensitive, converting to lowercase. Keeping XHTML as is.
815
+ transformCaseFunc = PARSER_MEDIA_TYPE === 'application/xhtml+xml' ? stringToString : stringToLowerCase;
816
+ /* Set configuration parameters */
817
+ ALLOWED_TAGS = _resolveSetOption(cfg, 'ALLOWED_TAGS', DEFAULT_ALLOWED_TAGS, {
818
+ transform: transformCaseFunc
819
+ });
820
+ ALLOWED_ATTR = _resolveSetOption(cfg, 'ALLOWED_ATTR', DEFAULT_ALLOWED_ATTR, {
821
+ transform: transformCaseFunc
822
+ });
823
+ ALLOWED_NAMESPACES = _resolveSetOption(cfg, 'ALLOWED_NAMESPACES', DEFAULT_ALLOWED_NAMESPACES, {
824
+ transform: stringToString
825
+ });
826
+ URI_SAFE_ATTRIBUTES = _resolveSetOption(cfg, 'ADD_URI_SAFE_ATTR', DEFAULT_URI_SAFE_ATTRIBUTES, {
827
+ transform: transformCaseFunc,
828
+ base: DEFAULT_URI_SAFE_ATTRIBUTES
829
+ });
830
+ DATA_URI_TAGS = _resolveSetOption(cfg, 'ADD_DATA_URI_TAGS', DEFAULT_DATA_URI_TAGS, {
831
+ transform: transformCaseFunc,
832
+ base: DEFAULT_DATA_URI_TAGS
833
+ });
834
+ FORBID_CONTENTS = _resolveSetOption(cfg, 'FORBID_CONTENTS', DEFAULT_FORBID_CONTENTS, {
835
+ transform: transformCaseFunc
836
+ });
837
+ FORBID_TAGS = _resolveSetOption(cfg, 'FORBID_TAGS', clone({}), {
838
+ transform: transformCaseFunc
839
+ });
840
+ FORBID_ATTR = _resolveSetOption(cfg, 'FORBID_ATTR', clone({}), {
841
+ transform: transformCaseFunc
842
+ });
843
+ USE_PROFILES = objectHasOwnProperty(cfg, 'USE_PROFILES') ? cfg.USE_PROFILES && typeof cfg.USE_PROFILES === 'object' ? clone(cfg.USE_PROFILES) : cfg.USE_PROFILES : false;
844
+ ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true
845
+ ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true
846
+ ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; // Default false
847
+ ALLOW_SELF_CLOSE_IN_ATTR = cfg.ALLOW_SELF_CLOSE_IN_ATTR !== false; // Default true
848
+ SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false; // Default false
849
+ SAFE_FOR_XML = cfg.SAFE_FOR_XML !== false; // Default true
850
+ WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false; // Default false
851
+ RETURN_DOM = cfg.RETURN_DOM || false; // Default false
852
+ RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false; // Default false
853
+ RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false; // Default false
854
+ FORCE_BODY = cfg.FORCE_BODY || false; // Default false
855
+ SANITIZE_DOM = cfg.SANITIZE_DOM !== false; // Default true
856
+ SANITIZE_NAMED_PROPS = cfg.SANITIZE_NAMED_PROPS || false; // Default false
857
+ KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true
858
+ IN_PLACE = cfg.IN_PLACE || false; // Default false
859
+ IS_ALLOWED_URI$1 = isRegex(cfg.ALLOWED_URI_REGEXP) ? cfg.ALLOWED_URI_REGEXP : IS_ALLOWED_URI; // Default regexp
860
+ NAMESPACE = typeof cfg.NAMESPACE === 'string' ? cfg.NAMESPACE : HTML_NAMESPACE; // Default HTML namespace
861
+ MATHML_TEXT_INTEGRATION_POINTS = _resolveObjectOption(cfg, 'MATHML_TEXT_INTEGRATION_POINTS', () => addToSet({}, DEFAULT_MATHML_TEXT_INTEGRATION_POINTS) // Default built-in map
862
+ );
863
+ HTML_INTEGRATION_POINTS = _resolveObjectOption(cfg, 'HTML_INTEGRATION_POINTS', () => addToSet({}, DEFAULT_HTML_INTEGRATION_POINTS) // Default built-in map
864
+ );
865
+ const customElementHandling = _resolveObjectOption(cfg, 'CUSTOM_ELEMENT_HANDLING', () => create(null));
866
+ CUSTOM_ELEMENT_HANDLING = create(null);
867
+ if (objectHasOwnProperty(customElementHandling, 'tagNameCheck') && isRegexOrFunction(customElementHandling.tagNameCheck)) {
868
+ CUSTOM_ELEMENT_HANDLING.tagNameCheck = customElementHandling.tagNameCheck; // Default undefined
869
+ }
870
+ if (objectHasOwnProperty(customElementHandling, 'attributeNameCheck') && isRegexOrFunction(customElementHandling.attributeNameCheck)) {
871
+ CUSTOM_ELEMENT_HANDLING.attributeNameCheck = customElementHandling.attributeNameCheck; // Default undefined
872
+ }
873
+ if (objectHasOwnProperty(customElementHandling, 'allowCustomizedBuiltInElements') && typeof customElementHandling.allowCustomizedBuiltInElements === 'boolean') {
874
+ CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = customElementHandling.allowCustomizedBuiltInElements; // Default undefined
875
+ }
876
+ seal(CUSTOM_ELEMENT_HANDLING);
877
+ if (SAFE_FOR_TEMPLATES) {
878
+ ALLOW_DATA_ATTR = false;
879
+ }
880
+ if (RETURN_DOM_FRAGMENT) {
881
+ RETURN_DOM = true;
882
+ }
883
+ /* Parse profile info */
884
+ if (USE_PROFILES) {
885
+ ALLOWED_TAGS = addToSet({}, purify_es_text);
886
+ ALLOWED_ATTR = create(null);
887
+ if (USE_PROFILES.html === true) {
888
+ addToSet(ALLOWED_TAGS, html$1);
889
+ addToSet(ALLOWED_ATTR, html);
890
+ }
891
+ if (USE_PROFILES.svg === true) {
892
+ addToSet(ALLOWED_TAGS, svg$1);
893
+ addToSet(ALLOWED_ATTR, svg);
894
+ addToSet(ALLOWED_ATTR, xml);
895
+ }
896
+ if (USE_PROFILES.svgFilters === true) {
897
+ addToSet(ALLOWED_TAGS, svgFilters);
898
+ addToSet(ALLOWED_ATTR, svg);
899
+ addToSet(ALLOWED_ATTR, xml);
900
+ }
901
+ if (USE_PROFILES.mathMl === true) {
902
+ addToSet(ALLOWED_TAGS, mathMl$1);
903
+ addToSet(ALLOWED_ATTR, mathMl);
904
+ addToSet(ALLOWED_ATTR, xml);
905
+ }
906
+ }
907
+ /* Always reset function-based ADD_TAGS / ADD_ATTR checks to prevent
908
+ * leaking across calls when switching from function to array config */
909
+ EXTRA_ELEMENT_HANDLING.tagCheck = null;
910
+ EXTRA_ELEMENT_HANDLING.attributeCheck = null;
911
+ /* Merge configuration parameters */
912
+ if (objectHasOwnProperty(cfg, 'ADD_TAGS')) {
913
+ if (typeof cfg.ADD_TAGS === 'function') {
914
+ EXTRA_ELEMENT_HANDLING.tagCheck = cfg.ADD_TAGS;
915
+ } else if (arrayIsArray(cfg.ADD_TAGS)) {
916
+ if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) {
917
+ ALLOWED_TAGS = clone(ALLOWED_TAGS);
918
+ }
919
+ addToSet(ALLOWED_TAGS, cfg.ADD_TAGS, transformCaseFunc);
920
+ }
921
+ }
922
+ if (objectHasOwnProperty(cfg, 'ADD_ATTR')) {
923
+ if (typeof cfg.ADD_ATTR === 'function') {
924
+ EXTRA_ELEMENT_HANDLING.attributeCheck = cfg.ADD_ATTR;
925
+ } else if (arrayIsArray(cfg.ADD_ATTR)) {
926
+ if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) {
927
+ ALLOWED_ATTR = clone(ALLOWED_ATTR);
928
+ }
929
+ addToSet(ALLOWED_ATTR, cfg.ADD_ATTR, transformCaseFunc);
930
+ }
931
+ }
932
+ if (objectHasOwnProperty(cfg, 'ADD_FORBID_CONTENTS') && arrayIsArray(cfg.ADD_FORBID_CONTENTS)) {
933
+ if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {
934
+ FORBID_CONTENTS = clone(FORBID_CONTENTS);
935
+ }
936
+ addToSet(FORBID_CONTENTS, cfg.ADD_FORBID_CONTENTS, transformCaseFunc);
937
+ }
938
+ /* Add #text in case KEEP_CONTENT is set to true */
939
+ if (KEEP_CONTENT) {
940
+ ALLOWED_TAGS['#text'] = true;
941
+ }
942
+ /* Add html, head and body to ALLOWED_TAGS in case WHOLE_DOCUMENT is true */
943
+ if (WHOLE_DOCUMENT) {
944
+ addToSet(ALLOWED_TAGS, ['html', 'head', 'body']);
945
+ }
946
+ /* Add tbody to ALLOWED_TAGS in case tables are permitted, see #286, #365 */
947
+ if (ALLOWED_TAGS.table) {
948
+ addToSet(ALLOWED_TAGS, ['tbody']);
949
+ delete FORBID_TAGS.tbody;
950
+ }
951
+ // Re-derive the active Trusted Types policy from this configuration on
952
+ // every parse. The active policy must never be sticky closure state that
953
+ // outlives the config that set it: a caller-supplied policy left in place
954
+ // after `clearConfig()` — or after a later call that supplied none, or
955
+ // `TRUSTED_TYPES_POLICY: null` — could sign a subsequent "default"
956
+ // `RETURN_TRUSTED_TYPE` result with a foreign, possibly unsafe policy.
957
+ // See GHSA-vxr8-fq34-vvx9.
958
+ if (cfg.TRUSTED_TYPES_POLICY) {
959
+ if (typeof cfg.TRUSTED_TYPES_POLICY.createHTML !== 'function') {
960
+ throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');
961
+ }
962
+ if (typeof cfg.TRUSTED_TYPES_POLICY.createScriptURL !== 'function') {
963
+ throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');
964
+ }
965
+ // A caller-supplied policy applies to this configuration only.
966
+ const previousTrustedTypesPolicy = trustedTypesPolicy;
967
+ trustedTypesPolicy = cfg.TRUSTED_TYPES_POLICY;
968
+ // Sign local variables required by `sanitize`. If the supplied policy's
969
+ // `createHTML` is circular (i.e. it calls `DOMPurify.sanitize`), this
970
+ // throws via the re-entrancy guard. Restore the previous policy first so
971
+ // the instance is not left in a poisoned state. See #1422.
972
+ try {
973
+ emptyHTML = _createTrustedHTML('');
974
+ } catch (error) {
975
+ trustedTypesPolicy = previousTrustedTypesPolicy;
976
+ throw error;
977
+ }
978
+ } else if (cfg.TRUSTED_TYPES_POLICY === null) {
979
+ // Explicit opt-out for this call: perform no Trusted Types signing and
980
+ // create nothing (so a strict `trusted-types` CSP that disallows a
981
+ // `dompurify` policy can still call `sanitize` from inside its own
982
+ // policy — see #1422). Resetting to `undefined` rather than a sticky
983
+ // `null` also drops any previously retained caller policy, so it cannot
984
+ // resurface on a later call, while still allowing the next config-less
985
+ // call to restore the internal default policy. See GHSA-vxr8-fq34-vvx9.
986
+ trustedTypesPolicy = undefined;
987
+ emptyHTML = '';
988
+ } else {
989
+ // No policy supplied: keep the currently active policy if one is set — a
990
+ // previously supplied policy is intentionally sticky across config-less
991
+ // calls — otherwise fall back to the instance's own internal policy,
992
+ // created at most once. (A policy supplied for a *single* call still
993
+ // lingers by design; what must not linger is a policy whose configuration
994
+ // has been torn down via `clearConfig()`, which restores the default.)
995
+ if (trustedTypesPolicy === undefined) {
996
+ trustedTypesPolicy = _getDefaultTrustedTypesPolicy();
997
+ }
998
+ // Sign internal variables only when a policy is active. A falsy policy
999
+ // (Trusted Types unsupported, creation failed, or an explicit opt-out)
1000
+ // leaves `emptyHTML` as a plain string, so we never call `.createHTML` on
1001
+ // a non-policy and throw. See #1422.
1002
+ if (trustedTypesPolicy && typeof emptyHTML === 'string') {
1003
+ emptyHTML = _createTrustedHTML('');
1004
+ }
1005
+ }
1006
+ // Prevent further manipulation of configuration.
1007
+ // Not available in IE8, Safari 5, etc.
1008
+ if (freeze) {
1009
+ freeze(cfg);
1010
+ }
1011
+ CONFIG = cfg;
1012
+ };
1013
+ /* Keep track of all possible SVG and MathML tags
1014
+ * so that we can perform the namespace checks
1015
+ * correctly. */
1016
+ const ALL_SVG_TAGS = addToSet({}, [...svg$1, ...svgFilters, ...svgDisallowed]);
1017
+ const ALL_MATHML_TAGS = addToSet({}, [...mathMl$1, ...mathMlDisallowed]);
1018
+ /**
1019
+ * Namespace rules for an element in the SVG namespace.
1020
+ *
1021
+ * @param tagName the element's lowercase tag name
1022
+ * @param parent the (possibly simulated) parent node
1023
+ * @param parentTagName the parent's lowercase tag name
1024
+ * @returns true if a spec-compliant parser could produce this element
1025
+ */
1026
+ const _checkSvgNamespace = function _checkSvgNamespace(tagName, parent, parentTagName) {
1027
+ // The only way to switch from HTML namespace to SVG
1028
+ // is via <svg>. If it happens via any other tag, then
1029
+ // it should be killed.
1030
+ if (parent.namespaceURI === HTML_NAMESPACE) {
1031
+ return tagName === 'svg';
1032
+ }
1033
+ // The only way to switch from MathML to SVG is via <svg>
1034
+ // if the parent is either <annotation-xml> or a MathML
1035
+ // text integration point.
1036
+ if (parent.namespaceURI === MATHML_NAMESPACE) {
1037
+ return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);
1038
+ }
1039
+ // We only allow elements that are defined in SVG
1040
+ // spec. All others are disallowed in SVG namespace.
1041
+ return Boolean(ALL_SVG_TAGS[tagName]);
1042
+ };
1043
+ /**
1044
+ * Namespace rules for an element in the MathML namespace.
1045
+ *
1046
+ * @param tagName the element's lowercase tag name
1047
+ * @param parent the (possibly simulated) parent node
1048
+ * @param parentTagName the parent's lowercase tag name
1049
+ * @returns true if a spec-compliant parser could produce this element
1050
+ */
1051
+ const _checkMathMlNamespace = function _checkMathMlNamespace(tagName, parent, parentTagName) {
1052
+ // The only way to switch from HTML namespace to MathML
1053
+ // is via <math>. If it happens via any other tag, then
1054
+ // it should be killed.
1055
+ if (parent.namespaceURI === HTML_NAMESPACE) {
1056
+ return tagName === 'math';
1057
+ }
1058
+ // The only way to switch from SVG to MathML is via
1059
+ // <math> and HTML integration points
1060
+ if (parent.namespaceURI === SVG_NAMESPACE) {
1061
+ return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName];
1062
+ }
1063
+ // We only allow elements that are defined in MathML
1064
+ // spec. All others are disallowed in MathML namespace.
1065
+ return Boolean(ALL_MATHML_TAGS[tagName]);
1066
+ };
1067
+ /**
1068
+ * Namespace rules for an element in the HTML namespace.
1069
+ *
1070
+ * @param tagName the element's lowercase tag name
1071
+ * @param parent the (possibly simulated) parent node
1072
+ * @param parentTagName the parent's lowercase tag name
1073
+ * @returns true if a spec-compliant parser could produce this element
1074
+ */
1075
+ const _checkHtmlNamespace = function _checkHtmlNamespace(tagName, parent, parentTagName) {
1076
+ // The only way to switch from SVG to HTML is via
1077
+ // HTML integration points, and from MathML to HTML
1078
+ // is via MathML text integration points
1079
+ if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) {
1080
+ return false;
1081
+ }
1082
+ if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {
1083
+ return false;
1084
+ }
1085
+ // We disallow tags that are specific for MathML
1086
+ // or SVG and should never appear in HTML namespace
1087
+ return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]);
1088
+ };
1089
+ /**
1090
+ * @param element a DOM element whose namespace is being checked
1091
+ * @returns Return false if the element has a
1092
+ * namespace that a spec-compliant parser would never
1093
+ * return. Return true otherwise.
1094
+ */
1095
+ const _checkValidNamespace = function _checkValidNamespace(element) {
1096
+ let parent = getParentNode(element);
1097
+ // In JSDOM, if we're inside shadow DOM, then parentNode
1098
+ // can be null. We just simulate parent in this case.
1099
+ if (!parent || !parent.tagName) {
1100
+ parent = {
1101
+ namespaceURI: NAMESPACE,
1102
+ tagName: 'template'
1103
+ };
1104
+ }
1105
+ const tagName = stringToLowerCase(element.tagName);
1106
+ const parentTagName = stringToLowerCase(parent.tagName);
1107
+ if (!ALLOWED_NAMESPACES[element.namespaceURI]) {
1108
+ return false;
1109
+ }
1110
+ if (element.namespaceURI === SVG_NAMESPACE) {
1111
+ return _checkSvgNamespace(tagName, parent, parentTagName);
1112
+ }
1113
+ if (element.namespaceURI === MATHML_NAMESPACE) {
1114
+ return _checkMathMlNamespace(tagName, parent, parentTagName);
1115
+ }
1116
+ if (element.namespaceURI === HTML_NAMESPACE) {
1117
+ return _checkHtmlNamespace(tagName, parent, parentTagName);
1118
+ }
1119
+ // For XHTML and XML documents that support custom namespaces
1120
+ if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && ALLOWED_NAMESPACES[element.namespaceURI]) {
1121
+ return true;
1122
+ }
1123
+ // The code should never reach this place (this means
1124
+ // that the element somehow got namespace that is not
1125
+ // HTML, SVG, MathML or allowed via ALLOWED_NAMESPACES).
1126
+ // Return false just in case.
1127
+ return false;
1128
+ };
1129
+ /**
1130
+ * _forceRemove
1131
+ *
1132
+ * @param node a DOM node
1133
+ */
1134
+ const _forceRemove = function _forceRemove(node) {
1135
+ arrayPush(DOMPurify.removed, {
1136
+ element: node
1137
+ });
1138
+ try {
1139
+ // eslint-disable-next-line unicorn/prefer-dom-node-remove
1140
+ getParentNode(node).removeChild(node);
1141
+ } catch (_) {
1142
+ /* The normal detach failed — this is reached for a parentless node
1143
+ (getParentNode() is null, so .removeChild throws). Element.prototype
1144
+ .remove() is itself a spec no-op on a parentless node, so a recorded
1145
+ "removal" would otherwise hand the caller back an intact,
1146
+ payload-bearing node (e.g. a detached IN_PLACE root the mXSS canary or
1147
+ the style-with-element-child rule decided to kill). Fail closed by
1148
+ throwing — exactly as a clobbered root does at the IN_PLACE entry —
1149
+ rather than trying to "neutralize" the node via its own methods.
1150
+ Neutralizing would mean calling getAttributeNames()/removeAttribute()
1151
+ on the node, both of which a <form> root can clobber via a named child
1152
+ (and _isClobbered does not even probe getAttributeNames), so the
1153
+ neutralize step could itself be silently defeated, leaving the payload
1154
+ intact. A throw touches only the cached, clobber-safe remove() and
1155
+ getParentNode(). Generalizes GHSA-r47g-fvhr-h676 (clobbered-form root)
1156
+ to every root-kill reason. REPORT-3.
1157
+ This lives inside the catch, so it never fires for a normally-removed
1158
+ in-tree node: those have a parent, removeChild() succeeds, and the
1159
+ catch is not entered. Only a kept (parentless) root reaches here. */
1160
+ remove(node);
1161
+ if (!getParentNode(node)) {
1162
+ throw typeErrorCreate('a node selected for removal could not be detached from its tree ' + 'and cannot be safely returned; refusing to sanitize in place');
1163
+ }
1164
+ }
1165
+ };
1166
+ /**
1167
+ * _stripAttributeNode
1168
+ *
1169
+ * Remove a single Attr node case/namespace-exactly on an attribute-teardown
1170
+ * path. Name-based removeAttribute() ASCII-lowercases its lookup key for an
1171
+ * HTML element in an HTML document and so silently misses a case-preserved
1172
+ * handler (e.g. `ONERROR` off an XML/XHTML import) - the same defect
1173
+ * _removeAttribute() was fixed for, which a name-based call would reintroduce
1174
+ * on these IN_PLACE teardown paths. Unlike _removeAttribute this does not
1175
+ * record into DOMPurify.removed: the neutralize passes intentionally do not
1176
+ * book-keep. A clobbered/detached node falls back to best-effort name-based
1177
+ * removal.
1178
+ *
1179
+ * @param element the element to strip the attribute from
1180
+ * @param attribute the Attr node to remove
1181
+ * @param name the attribute's name, for the fallback path
1182
+ */
1183
+ const _stripAttributeNode = function _stripAttributeNode(element, attribute, name) {
1184
+ try {
1185
+ removeAttributeNode(element, attribute);
1186
+ } catch (_) {
1187
+ try {
1188
+ element.removeAttribute(name);
1189
+ } catch (_) {}
1190
+ }
1191
+ };
1192
+ /**
1193
+ * _neutralizeRoot
1194
+ *
1195
+ * Fail-closed teardown of an in-place root after the sanitize walk aborts
1196
+ * (campaign-3 F2). An internal throw mid-walk — e.g. a page-registered
1197
+ * custom element's reaction detaches a node so `_forceRemove`'s deliberate
1198
+ * parentless guard throws, or any other re-entrant engine mutation — would
1199
+ * otherwise leave the caller's *live* tree half-sanitized, with everything
1200
+ * after the abort point still carrying its handlers. There is no safe way
1201
+ * to resume the walk (the tree mutated under us), so we strip the root bare:
1202
+ * remove every child and every attribute, then let the caller's catch see
1203
+ * the original error. Clobber-safe (cached `remove`/`childNodes`/`attributes`
1204
+ * getters; the root was already clobber-pre-flighted at the IN_PLACE entry).
1205
+ *
1206
+ * @param root the in-place root to empty
1207
+ */
1208
+ const _neutralizeRoot = function _neutralizeRoot(root) {
1209
+ /* Strip every disallowed attribute (on* handlers included) off the whole
1210
+ subtree BEFORE detaching anything. Detaching first would hand back
1211
+ handler-bearing originals (e.g. an already-loading `<img onerror>`)
1212
+ whose queued resource event still fires in page scope after we throw.
1213
+ Clobber-safe reads; a doomed clobbered node's own attributes are
1214
+ irrelevant while its non-clobbered descendants are reached and scrubbed. */
1215
+ _neutralizeSubtree(root);
1216
+ const childNodes = getChildNodes(root);
1217
+ if (childNodes) {
1218
+ const snapshot = [];
1219
+ arrayForEach(childNodes, child => {
1220
+ arrayPush(snapshot, child);
1221
+ });
1222
+ arrayForEach(snapshot, child => {
1223
+ try {
1224
+ remove(child);
1225
+ } catch (_) {
1226
+ /* Best-effort teardown; a still-attached child is handled below */
1227
+ }
1228
+ });
1229
+ }
1230
+ const attributes = getAttributes(root);
1231
+ if (attributes) {
1232
+ for (let i = attributes.length - 1; i >= 0; --i) {
1233
+ const attribute = attributes[i];
1234
+ const name = attribute && attribute.name;
1235
+ if (typeof name === 'string') {
1236
+ _stripAttributeNode(root, attribute, name);
1237
+ }
1238
+ }
1239
+ }
1240
+ };
1241
+ /**
1242
+ * _removeAttribute
1243
+ *
1244
+ * Name-based getAttributeNode()/removeAttribute() ASCII-lowercase their
1245
+ * lookup key for HTML elements in an HTML document, so they silently miss an
1246
+ * attribute whose stored qualified name still contains uppercase ASCII
1247
+ * letters. That happens when the node came from a case-preserving source
1248
+ * (an XML/XHTML document imported via importNode(), or createAttributeNS()),
1249
+ * where e.g. `ONERROR` survives the walk: the policy check lowercases to
1250
+ * `onerror` and rejects it, but `removeAttribute('ONERROR')` looks up
1251
+ * `onerror` and finds nothing. Remove the exact Attr node instead, which is
1252
+ * case- and namespace-exact, and fall back to name-based removal only when
1253
+ * the caller could not supply the node.
1254
+ *
1255
+ * @param name an Attribute name
1256
+ * @param element a DOM node
1257
+ * @param attr the exact Attr node to remove, when the caller has it
1258
+ */
1259
+ const _removeAttribute = function _removeAttribute(name, element, attr) {
1260
+ if (!attr) {
1261
+ try {
1262
+ attr = element.getAttributeNode(name);
1263
+ } catch (_) {
1264
+ attr = null;
1265
+ }
1266
+ }
1267
+ arrayPush(DOMPurify.removed, {
1268
+ attribute: attr || null,
1269
+ from: element
1270
+ });
1271
+ try {
1272
+ if (attr) {
1273
+ removeAttributeNode(element, attr);
1274
+ } else {
1275
+ element.removeAttribute(name);
1276
+ }
1277
+ } catch (_) {
1278
+ /* Clobbered or already-detached node - best-effort fall back to a
1279
+ name-based removal so the "is" handling below still runs. Note this
1280
+ fallback ASCII-lowercases its lookup key in an HTML document and so
1281
+ cannot reach a case-preserved attribute name; the cached
1282
+ removeAttributeNode() above is what removes those, and a clobbered
1283
+ form is already removed wholesale by _isClobbered() before reaching
1284
+ here. */
1285
+ try {
1286
+ element.removeAttribute(name);
1287
+ } catch (_) {}
1288
+ }
1289
+ // We void attribute values for unremovable "is" attributes
1290
+ if (name === 'is') {
1291
+ if (RETURN_DOM || RETURN_DOM_FRAGMENT) {
1292
+ try {
1293
+ _forceRemove(element);
1294
+ } catch (_) {}
1295
+ } else {
1296
+ try {
1297
+ element.setAttribute(name, '');
1298
+ } catch (_) {}
1299
+ }
1300
+ }
1301
+ };
1302
+ /**
1303
+ * _stripDisallowedAttributes
1304
+ *
1305
+ * Removes every attribute the active configuration does not allow from a
1306
+ * single element, using the same allowlist as the main attribute pass (so
1307
+ * `on*` handlers go, but no `/^on/` blocklist is introduced). Used only to
1308
+ * neutralise nodes that are being discarded from an in-place tree.
1309
+ *
1310
+ * @param element the element to strip
1311
+ */
1312
+ const _stripDisallowedAttributes = function _stripDisallowedAttributes(element) {
1313
+ const attributes = getAttributes(element);
1314
+ if (!attributes) {
1315
+ return;
1316
+ }
1317
+ for (let i = attributes.length - 1; i >= 0; --i) {
1318
+ const attribute = attributes[i];
1319
+ const name = attribute && attribute.name;
1320
+ if (typeof name !== 'string' || ALLOWED_ATTR[transformCaseFunc(name)]) {
1321
+ continue;
1322
+ }
1323
+ _stripAttributeNode(element, attribute, name);
1324
+ }
1325
+ };
1326
+ /**
1327
+ * _neutralizeSubtree
1328
+ *
1329
+ * Completes the audit-5 F1 fix across every removal path. The KEEP_CONTENT
1330
+ * move-hoist neutralises only disallowed-tag removals; clobber, mXSS-canary,
1331
+ * namespace, comment, processing-instruction and KEEP_CONTENT:false removals
1332
+ * all drop their subtree wholesale via `_forceRemove`. On the IN_PLACE path
1333
+ * those dropped nodes are detached from the caller's LIVE tree but a
1334
+ * handler-bearing original among them (an `<img onerror>`/`<video>` that was
1335
+ * loading) keeps its queued resource event, which fires in page scope after
1336
+ * sanitize returns. This walks a removed subtree and strips every attribute
1337
+ * the active configuration does not allow — so `on*` handlers are cancelled
1338
+ * through the SAME allowlist that governs kept nodes, not a separate `/^on/`
1339
+ * blocklist. Run synchronously before sanitize returns, i.e. before any
1340
+ * queued event can fire. Hook-free by design: these nodes leave the output,
1341
+ * so firing attribute hooks for them would be surprising. Clobber-safe reads;
1342
+ * a doomed clobbered node may shadow `removeAttribute` (its own attributes are
1343
+ * irrelevant — it is discarded — while its non-clobbered descendants, e.g.
1344
+ * the `<img>`, are reached and scrubbed).
1345
+ *
1346
+ * @param root the root of a removed subtree to neutralise
1347
+ */
1348
+ const _neutralizeSubtree = function _neutralizeSubtree(root) {
1349
+ const stack = [root];
1350
+ while (stack.length > 0) {
1351
+ const node = stack.pop();
1352
+ const nodeType = _readNodeType(node);
1353
+ if (nodeType === NODE_TYPE.element) {
1354
+ _stripDisallowedAttributes(node);
1355
+ }
1356
+ const childNodes = getChildNodes(node);
1357
+ if (childNodes) {
1358
+ for (let i = childNodes.length - 1; i >= 0; --i) {
1359
+ stack.push(childNodes[i]);
1360
+ }
1361
+ }
1362
+ }
1363
+ };
1364
+ /**
1365
+ * _neutralizePatchLinkage
1366
+ *
1367
+ * IN_PLACE entry pre-pass (declarative-partial-updates / streaming
1368
+ * hardening, https://github.com/WICG/declarative-partial-updates).
1369
+ *
1370
+ * The main walk strips patch linkage (`for`/`patchsrc`) and removes range
1371
+ * markers (PIs / markup comments) node-by-node, in document order, AS it
1372
+ * reaches each node. On a live in-place root that leaves a window: from the
1373
+ * moment the root is connected until the walk arrives at a given node, that
1374
+ * node's linkage is live. A patch applied on connection/stream can fire as
1375
+ * a microtask during the walk and inject or teleport an unsanitized DOM
1376
+ * range into a region the iterator has already passed and will not revisit,
1377
+ * so the post-return "tree is sanitized" contract is violated. Sweep the
1378
+ * whole tree once up front and sever every linkage before the walk begins,
1379
+ * closing that window.
1380
+ *
1381
+ * This CANNOT undo a patch that already fired before sanitize ran — that is
1382
+ * the irreducible "do not IN_PLACE a live-connected attacker tree" caveat —
1383
+ * but it closes everything from sanitize-start onward. Gated on SAFE_FOR_XML
1384
+ * to group with the rest of the declarative-partial-updates handling and
1385
+ * stay overridable, consistent with the codebase.
1386
+ *
1387
+ * Clobber-safe traversal (cached childNodes getter); per-node try/catch so a
1388
+ * clobbered root cannot defeat the sweep of its non-clobbered descendants.
1389
+ *
1390
+ * NOTE (pending real-Chrome confirmation, see test/declarative-patch-probe
1391
+ * .html Q1): this mirrors the existing policy of keeping `for` on
1392
+ * <label>/<output>. If the shipping feature can drive a patch through a
1393
+ * surviving `for`-on-label/output + `id` pair, this pre-pass and the
1394
+ * attribute check at _isBasicCustomElement's caller must additionally drop
1395
+ * that pair on the IN_PLACE path. Left as-is until the taxonomy is verified.
1396
+ *
1397
+ * @param root the in-place root to sweep
1398
+ */
1399
+ /**
1400
+ * Central policy for declarative-partial-updates patch-linkage attributes,
1401
+ * shared by the _neutralizePatchLinkage pre-pass and _isValidAttribute so
1402
+ * the two sites cannot drift: `patchsrc` always links, `for` links
1403
+ * everywhere except on <label>/<output>, and the whole policy is gated on
1404
+ * SAFE_FOR_XML (see the rationale block in _isValidAttribute).
1405
+ *
1406
+ * @param lcName the transformCaseFunc'd attribute name
1407
+ * @param lcTag the transformCaseFunc'd tag name of the carrying element
1408
+ * @return true if the attribute is patch linkage and must be dropped
1409
+ */
1410
+ const _isPatchLinkageAttribute = function _isPatchLinkageAttribute(lcName, lcTag) {
1411
+ if (!SAFE_FOR_XML) {
1412
+ return false;
1413
+ }
1414
+ if (lcName === 'patchsrc') {
1415
+ return true;
1416
+ }
1417
+ return lcName === 'for' && lcTag !== 'label' && lcTag !== 'output';
1418
+ };
1419
+ const _neutralizePatchLinkage = function _neutralizePatchLinkage(root) {
1420
+ if (!SAFE_FOR_XML) {
1421
+ return;
1422
+ }
1423
+ const stack = [root];
1424
+ while (stack.length > 0) {
1425
+ const node = stack.pop();
1426
+ const nodeType = _readNodeType(node);
1427
+ /* Remove range markers (the target side of a patch linkage): every
1428
+ processing instruction, and any markup-bearing comment. */
1429
+ if (nodeType === NODE_TYPE.processingInstruction || nodeType === NODE_TYPE.comment && regExpTest(COMMENT_MARKUP_PROBE, node.data)) {
1430
+ try {
1431
+ remove(node);
1432
+ } catch (_) {
1433
+ /* Best-effort */
1434
+ }
1435
+ continue;
1436
+ }
1437
+ /* Strip patch-source attributes (the source side) off elements. */
1438
+ if (nodeType === NODE_TYPE.element) {
1439
+ const element = node;
1440
+ const lcTag = transformCaseFunc(_readNodeName(node));
1441
+ try {
1442
+ if (element.hasAttribute && element.hasAttribute('patchsrc')) {
1443
+ element.removeAttribute('patchsrc');
1444
+ }
1445
+ if (element.hasAttribute && element.hasAttribute('for') && _isPatchLinkageAttribute('for', lcTag)) {
1446
+ element.removeAttribute('for');
1447
+ }
1448
+ } catch (_) {
1449
+ /* Clobbered removeAttribute/hasAttribute on a doomed node — ignore */
1450
+ }
1451
+ }
1452
+ const childNodes = getChildNodes(node);
1453
+ if (childNodes) {
1454
+ for (let i = childNodes.length - 1; i >= 0; --i) {
1455
+ stack.push(childNodes[i]);
1456
+ }
1457
+ }
1458
+ }
1459
+ };
1460
+ /**
1461
+ * _initDocument
1462
+ *
1463
+ * @param dirty - a string of dirty markup
1464
+ * @return a DOM, filled with the dirty markup
1465
+ */
1466
+ const _initDocument = function _initDocument(dirty) {
1467
+ /* Create a HTML document */
1468
+ let doc = null;
1469
+ let leadingWhitespace = null;
1470
+ if (FORCE_BODY) {
1471
+ dirty = '<remove></remove>' + dirty;
1472
+ } else {
1473
+ /* If FORCE_BODY isn't used, leading whitespace needs to be preserved manually */
1474
+ const matches = stringMatch(dirty, /^[\r\n\t ]+/);
1475
+ leadingWhitespace = matches && matches[0];
1476
+ }
1477
+ if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && NAMESPACE === HTML_NAMESPACE) {
1478
+ // Root of XHTML doc must contain xmlns declaration (see https://www.w3.org/TR/xhtml1/normative.html#strict)
1479
+ dirty = '<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>' + dirty + '</body></html>';
1480
+ }
1481
+ const dirtyPayload = trustedTypesPolicy ? _createTrustedHTML(dirty) : dirty;
1482
+ /*
1483
+ * Use the DOMParser API by default, fallback later if needs be
1484
+ * DOMParser not work for svg when has multiple root element.
1485
+ */
1486
+ if (NAMESPACE === HTML_NAMESPACE) {
1487
+ try {
1488
+ doc = new DOMParser().parseFromString(dirtyPayload, PARSER_MEDIA_TYPE);
1489
+ } catch (_) {}
1490
+ }
1491
+ /* Use createHTMLDocument in case DOMParser is not available */
1492
+ if (!doc || !doc.documentElement) {
1493
+ doc = implementation.createDocument(NAMESPACE, 'template', null);
1494
+ try {
1495
+ doc.documentElement.innerHTML = IS_EMPTY_INPUT ? emptyHTML : dirtyPayload;
1496
+ } catch (_) {
1497
+ // Syntax error if dirtyPayload is invalid xml
1498
+ }
1499
+ }
1500
+ const body = doc.body || doc.documentElement;
1501
+ if (dirty && leadingWhitespace) {
1502
+ body.insertBefore(document.createTextNode(leadingWhitespace), body.childNodes[0] || null);
1503
+ }
1504
+ /* Work on whole document or just its body */
1505
+ if (NAMESPACE === HTML_NAMESPACE) {
1506
+ return getElementsByTagName.call(doc, WHOLE_DOCUMENT ? 'html' : 'body')[0];
1507
+ }
1508
+ return WHOLE_DOCUMENT ? doc.documentElement : body;
1509
+ };
1510
+ /**
1511
+ * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document.
1512
+ *
1513
+ * @param root The root element or node to start traversing on.
1514
+ * @return The created NodeIterator
1515
+ */
1516
+ const _createNodeIterator = function _createNodeIterator(root) {
1517
+ /* Read ownerDocument through the cached Node.prototype getter, never the
1518
+ direct property. HTMLFormElement has [LegacyOverrideBuiltIns], so a
1519
+ clobbering child (<input name="ownerDocument"> or a form-associated
1520
+ external input) shadows the prototype getter and makes a direct read
1521
+ return that <input>. createNodeIterator.call(<input>, ...) then throws
1522
+ "Illegal invocation", and on the IN_PLACE path that throw lands before
1523
+ the walk's fail-closed barrier - leaving the caller's live tree, with
1524
+ any already-armed handler in it, un-neutralized. The cached getter
1525
+ returns the real Document regardless of the clobber. */
1526
+ const doc = getOwnerDocument ? getOwnerDocument(root) : root.ownerDocument;
1527
+ return createNodeIterator.call(doc || root, root,
1528
+ // eslint-disable-next-line no-bitwise
1529
+ NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT | NodeFilter.SHOW_PROCESSING_INSTRUCTION | NodeFilter.SHOW_CDATA_SECTION, null);
1530
+ };
1531
+ /**
1532
+ * Replace template expression syntax (mustache, ERB, template
1533
+ * literal) with a space; shared by all SAFE_FOR_TEMPLATES scrub
1534
+ * sites. Order matters: mustache, then ERB, then template literal.
1535
+ *
1536
+ * @param value the string to scrub
1537
+ * @returns the scrubbed string
1538
+ */
1539
+ const _stripTemplateExpressions = function _stripTemplateExpressions(value) {
1540
+ value = stringReplace(value, MUSTACHE_EXPR$1, ' ');
1541
+ value = stringReplace(value, ERB_EXPR$1, ' ');
1542
+ value = stringReplace(value, TMPLIT_EXPR$1, ' ');
1543
+ return value;
1544
+ };
1545
+ /**
1546
+ * Strip template-engine expressions ({{...}}, ${...}, <%...%>) from the
1547
+ * character data of an element subtree. Used as the final safety net for
1548
+ * SAFE_FOR_TEMPLATES on every DOM-returning code path so that expressions
1549
+ * which only form after text-node normalization (e.g. fragments split across
1550
+ * stripped elements) cannot survive into a template-evaluating framework.
1551
+ *
1552
+ * Walks text/comment/CDATA/processing-instruction nodes and mutates `.data`
1553
+ * in place rather than round-tripping through innerHTML. This preserves
1554
+ * descendant node references (important for IN_PLACE callers), avoids a
1555
+ * serialize/reparse cycle, and reads literal character data — which means
1556
+ * `<%...%>` in text content matches the ERB regex against its real bytes
1557
+ * instead of the HTML-entity-escaped form innerHTML would produce.
1558
+ *
1559
+ * Attribute values are not visited here; SAFE_FOR_TEMPLATES handling for
1560
+ * attributes is performed during the per-node `_sanitizeAttributes` pass.
1561
+ *
1562
+ * @param node The root element whose character data should be scrubbed.
1563
+ */
1564
+ const _scrubTemplateExpressions2 = function _scrubTemplateExpressions(node) {
1565
+ var _node$querySelectorAl;
1566
+ node.normalize();
1567
+ /* Clobber-safe ownerDocument read, same reasoning as _createNodeIterator:
1568
+ under SAFE_FOR_TEMPLATES this runs on the live IN_PLACE root, which may
1569
+ carry a form-named-getter override of ownerDocument. */
1570
+ const doc = getOwnerDocument ? getOwnerDocument(node) : node.ownerDocument;
1571
+ const walker = createNodeIterator.call(doc || node, node,
1572
+ // eslint-disable-next-line no-bitwise
1573
+ NodeFilter.SHOW_TEXT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_CDATA_SECTION | NodeFilter.SHOW_PROCESSING_INSTRUCTION, null);
1574
+ let currentNode = walker.nextNode();
1575
+ while (currentNode) {
1576
+ currentNode.data = _stripTemplateExpressions(currentNode.data);
1577
+ currentNode = walker.nextNode();
1578
+ }
1579
+ // NodeIterator does not descend into <template>.content per the DOM spec,
1580
+ // so we must explicitly recurse into each template's content fragment,
1581
+ // mirroring the approach used by _sanitizeShadowDOM.
1582
+ const templates = (_node$querySelectorAl = node.querySelectorAll) === null || _node$querySelectorAl === void 0 ? void 0 : _node$querySelectorAl.call(node, 'template');
1583
+ if (templates) {
1584
+ arrayForEach(templates, tmpl => {
1585
+ if (_isDocumentFragment(tmpl.content)) {
1586
+ _scrubTemplateExpressions2(tmpl.content);
1587
+ }
1588
+ });
1589
+ }
1590
+ };
1591
+ /**
1592
+ * _isClobbered
1593
+ *
1594
+ * Detect DOM-clobbering on HTMLFormElement nodes. Form is the only HTML
1595
+ * interface with [LegacyOverrideBuiltIns]; a descendant element with a
1596
+ * `name` attribute matching a prototype property shadows that property
1597
+ * on direct reads. We use this check at the IN_PLACE entry-point and
1598
+ * during attribute sanitization to refuse clobbered forms.
1599
+ *
1600
+ * @param element element to check for clobbering attacks
1601
+ * @return true if clobbered, false if safe
1602
+ */
1603
+ const _isClobbered = function _isClobbered(element) {
1604
+ // Realm-independent tag-name probe. If we can't determine the tag
1605
+ // name at all, we can't reason about clobbering — return false
1606
+ // (the caller's other defences still apply).
1607
+ const realTagName = getNodeName ? getNodeName(element) : null;
1608
+ if (typeof realTagName !== 'string') {
1609
+ return false;
1610
+ }
1611
+ if (transformCaseFunc(realTagName) !== 'form') {
1612
+ return false;
1613
+ }
1614
+ return typeof element.nodeName !== 'string' || typeof element.textContent !== 'string' || typeof element.removeChild !== 'function' ||
1615
+ // Realm-safe NamedNodeMap detection: equality against the cached
1616
+ // prototype getter. Clobbered .attributes (e.g. <input name="attributes">)
1617
+ // makes the direct read diverge from the cached read; a clean form
1618
+ // (same-realm OR foreign-realm) has both reads pointing at the same
1619
+ // canonical NamedNodeMap.
1620
+ element.attributes !== getAttributes(element) || typeof element.removeAttribute !== 'function' ||
1621
+ // A form descendant named "removeAttributeNode" or "getAttributeNode"
1622
+ // shadows these Attr-node methods via [LegacyOverrideBuiltIns].
1623
+ // _removeAttribute() / _stripAttributeNode() reach for
1624
+ // element.removeAttributeNode(attr) first; when it is shadowed the call
1625
+ // throws and the name-based fallback element.removeAttribute(name)
1626
+ // ASCII-lowercases its lookup key in an HTML document, silently missing
1627
+ // a case-preserved event-handler attribute (e.g. an ONANIMATIONSTART
1628
+ // that reached the sanitizer through an XML/XHTML parse). Flag the form
1629
+ // so it is removed wholesale, exactly as for the other shadowed methods.
1630
+ typeof element.removeAttributeNode !== 'function' || typeof element.getAttributeNode !== 'function' || typeof element.setAttribute !== 'function' || typeof element.namespaceURI !== 'string' || typeof element.insertBefore !== 'function' || typeof element.hasChildNodes !== 'function' ||
1631
+ // NodeType clobbering probe. Cached Node.prototype.nodeType getter
1632
+ // returns the integer 1 for any Element regardless of realm; direct
1633
+ // read on a clobbered form (e.g. <input name="nodeType">) returns
1634
+ // the named child element. Cheap addition — nodeType is read from
1635
+ // an internal slot, no serialization cost — and removes a residual
1636
+ // clobbering surface used by several mXSS / PI / comment branches
1637
+ // in _sanitizeElements that compare currentNode.nodeType directly.
1638
+ element.nodeType !== getNodeType(element) ||
1639
+ // HTMLFormElement has [LegacyOverrideBuiltIns]: a descendant named
1640
+ // "childNodes" shadows the prototype getter. Direct reads of
1641
+ // form.childNodes from a clobbered form return the named child
1642
+ // instead of the real NodeList, so any walk that reads it directly
1643
+ // skips the form's real children. Compare the direct read to the
1644
+ // cached Node.prototype getter — when the form's named-property
1645
+ // getter intercepts the read, the two values differ and we flag
1646
+ // the form. This catches every clobbering child type (input,
1647
+ // select, etc.) regardless of whether the named child happens to
1648
+ // carry a numeric .length, which a typeof-based probe would miss
1649
+ // (e.g. HTMLSelectElement.length is a defined unsigned-long).
1650
+ element.childNodes !== getChildNodes(element);
1651
+ };
1652
+ /**
1653
+ * Checks whether the given value is a DocumentFragment from any realm.
1654
+ *
1655
+ * The realm-independent replacement reads `nodeType` through the cached
1656
+ * Node.prototype getter and compares to the DOCUMENT_FRAGMENT_NODE
1657
+ * constant (11). nodeType is a numeric value resolved from the node's
1658
+ * internal slot, identical across realms for the same kind of node.
1659
+ *
1660
+ * @param value object to check
1661
+ * @return true if value is a DocumentFragment-shaped node from any realm
1662
+ */
1663
+ const _isDocumentFragment = function _isDocumentFragment(value) {
1664
+ if (!getNodeType || typeof value !== 'object' || value === null) {
1665
+ return false;
1666
+ }
1667
+ try {
1668
+ return getNodeType(value) === NODE_TYPE.documentFragment;
1669
+ } catch (_) {
1670
+ return false;
1671
+ }
1672
+ };
1673
+ /**
1674
+ * Checks whether the given object is a DOM node, including nodes that
1675
+ * originate from a different window/realm (e.g. an iframe's
1676
+ * contentDocument). The previous `value instanceof Node` check was
1677
+ * realm-bound: nodes from a different window failed it, causing
1678
+ * sanitize() to silently stringify them and reset IN_PLACE to false,
1679
+ * returning the original node unsanitized. See GHSA-4w3q-35jp-p934.
1680
+ *
1681
+ * @param value object to check whether it's a DOM node
1682
+ * @return true if value is a DOM node from any realm
1683
+ */
1684
+ const _isNode = function _isNode(value) {
1685
+ if (!getNodeType || typeof value !== 'object' || value === null) {
1686
+ return false;
1687
+ }
1688
+ try {
1689
+ return typeof getNodeType(value) === 'number';
1690
+ } catch (_) {
1691
+ return false;
1692
+ }
1693
+ };
1694
+ function _executeHooks(hooks, currentNode, data) {
1695
+ if (hooks.length === 0) {
1696
+ return;
1697
+ }
1698
+ arrayForEach(hooks, hook => {
1699
+ hook.call(DOMPurify, currentNode, data, CONFIG);
1700
+ });
1701
+ }
1702
+ /**
1703
+ * Structural-threat checks that condemn a node regardless of the
1704
+ * allowlists: mXSS via namespace confusion, risky CSS construction,
1705
+ * processing instructions, markup-bearing comments. Pure predicate;
1706
+ * the caller removes. Check order is load-bearing.
1707
+ *
1708
+ * @param currentNode the node to inspect
1709
+ * @param tagName the node's transformCaseFunc'd tag name
1710
+ * @return true if the node must be removed
1711
+ */
1712
+ const _isUnsafeNode = function _isUnsafeNode(currentNode, tagName) {
1713
+ /* Detect mXSS attempts abusing namespace confusion */
1714
+ if (SAFE_FOR_XML && currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && regExpTest(ELEMENT_MARKUP_PROBE, currentNode.textContent) && regExpTest(ELEMENT_MARKUP_PROBE, currentNode.innerHTML)) {
1715
+ return true;
1716
+ }
1717
+ /* Remove rawtext/literal-text elements whose literal serialization
1718
+ re-opens markup on an HTML reparse - shapes (a) and (b) documented at
1719
+ LITERAL_TEXT_ELEMENTS. Both are invisible to rule 1 above (which
1720
+ self-disables once there is an element child, and whose second probe
1721
+ reads the innerHTML an XML/XHTML document serializes escaped), which
1722
+ is why both probes here read textContent instead. Previously only
1723
+ `style`-with-element-child was covered; every element in
1724
+ LITERAL_TEXT_ELEMENTS shares this literal serialization and is
1725
+ equally affected. */
1726
+ if (SAFE_FOR_XML && currentNode.namespaceURI === HTML_NAMESPACE && LITERAL_TEXT_ELEMENTS[tagName] && (_isNode(currentNode.firstElementChild) || typeof currentNode.textContent === 'string' && regExpTest(LITERAL_TEXT_CLOSE[tagName], currentNode.textContent))) {
1727
+ return true;
1728
+ }
1729
+ /* Remove any occurrence of processing instructions */
1730
+ if (currentNode.nodeType === NODE_TYPE.processingInstruction) {
1731
+ return true;
1732
+ }
1733
+ /* Remove any kind of possibly harmful comments */
1734
+ if (SAFE_FOR_XML && currentNode.nodeType === NODE_TYPE.comment && regExpTest(COMMENT_MARKUP_PROBE, currentNode.data)) {
1735
+ return true;
1736
+ }
1737
+ return false;
1738
+ };
1739
+ /**
1740
+ * Evaluate a CUSTOM_ELEMENT_HANDLING check (a RegExp or a predicate
1741
+ * function, per the validation in _parseConfig) against a name.
1742
+ * Additional arguments are forwarded to predicate functions - the
1743
+ * attributeNameCheck predicate receives the tag name as its second
1744
+ * argument. A null/absent check never matches.
1745
+ *
1746
+ * @param check the configured tagNameCheck / attributeNameCheck value
1747
+ * @param name the name to test
1748
+ * @param args extra arguments forwarded to a predicate function
1749
+ * @return true if the check matches the name
1750
+ */
1751
+ const _matchesNameCheck = function _matchesNameCheck(check, name) {
1752
+ if (check instanceof RegExp) {
1753
+ return regExpTest(check, name);
1754
+ }
1755
+ if (check instanceof Function) {
1756
+ for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
1757
+ args[_key - 2] = arguments[_key];
1758
+ }
1759
+ return Boolean(check(name, ...args));
1760
+ }
1761
+ return false;
1762
+ };
1763
+ /**
1764
+ * Handle a node whose tag is forbidden or not allowlisted: keep
1765
+ * allowed custom elements (false return exits _sanitizeElements
1766
+ * early - the namespace and fallback-tag removal checks are
1767
+ * intentionally skipped for kept custom elements), else hoist
1768
+ * content per KEEP_CONTENT and remove.
1769
+ *
1770
+ * A kept custom element is the ONLY case in which this function
1771
+ * returns false, so the caller uses that return value to run the
1772
+ * afterSanitizeElements hook on the kept element and keep the
1773
+ * element-hook lifecycle consistent with normal allowlisted
1774
+ * elements (GHSA-c2j3-45gr-mqc4).
1775
+ *
1776
+ * @param currentNode the disallowed node
1777
+ * @param tagName the node's transformCaseFunc'd tag name
1778
+ * @return true if the node was removed, false if kept
1779
+ */
1780
+ const _sanitizeDisallowedNode = function _sanitizeDisallowedNode(currentNode, tagName, root) {
1781
+ /* Check if we have a custom element to handle */
1782
+ if (!FORBID_TAGS[tagName] && _isBasicCustomElement(tagName) && _matchesNameCheck(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) {
1783
+ return false;
1784
+ }
1785
+ /* Keep content except for bad-listed elements.
1786
+ Use the cached prototype getters exclusively — the previous code
1787
+ had `|| currentNode.parentNode` / `|| currentNode.childNodes`
1788
+ fallbacks, but the cached getters always return the canonical
1789
+ value (or null for a real parent-less node), so the fallback
1790
+ path was dead in safe cases and a clobbering surface in unsafe
1791
+ ones. Falsy cached results stay falsy; the `if (childNodes &&
1792
+ parentNode)` check already gates correctly. */
1793
+ if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {
1794
+ const parentNode = getParentNode(currentNode);
1795
+ const childNodes = getChildNodes(currentNode);
1796
+ if (childNodes && parentNode) {
1797
+ const childCount = childNodes.length;
1798
+ /* Hoist by moving each child up one level rather than deep-cloning
1799
+ it. Moving transfers every descendant exactly once, so a chain of
1800
+ nested disallowed elements costs O(n) instead of the O(n^2) that
1801
+ re-cloning the shrinking subtree at each level produced; it also
1802
+ empties the removed original, so `DOMPurify.removed` no longer
1803
+ pins whole subtrees. Moving preserves the in-place guarantee too:
1804
+ an original carrying already-queued resource events (`<img
1805
+ onerror>`, `<video>`/`<audio>` error, lazy/`onload`, …) is
1806
+ relocated and sanitised rather than left detached but still armed.
1807
+ The sole case that must clone is removing the walk root itself.
1808
+ The result is serialised from the root's subtree, so a restrictive
1809
+ ALLOWED_TAGS that strips the root (`body` on the string path) must
1810
+ leave the content inside it, which only cloning does. In IN_PLACE
1811
+ the root is pre-validated as an allowed tag and so is never removed
1812
+ here, so that path always takes the move branch.
1813
+ `childNodes` is live; a tail-to-head walk keeps `childNodes[i]`
1814
+ valid whether we move (drops the trailing entry) or clone (leaves
1815
+ the list intact). */
1816
+ for (let i = childCount - 1; i >= 0; --i) {
1817
+ const hoisted = currentNode === root ? cloneNode(childNodes[i], true) : childNodes[i];
1818
+ parentNode.insertBefore(hoisted, getNextSibling(currentNode));
1819
+ }
1820
+ }
1821
+ }
1822
+ _forceRemove(currentNode);
1823
+ return true;
1824
+ };
1825
+ /**
1826
+ * Fork a hook-mutable allowlist off its shared binding the first time a
1827
+ * (possibly lazily-installed) uponSanitize* hook is about to see it, so the
1828
+ * hook cannot widen the per-instance default or the setConfig binding by
1829
+ * reference and leak past the call. Returns the set unchanged once it is
1830
+ * already call-local, so repeated calls across elements are idempotent.
1831
+ *
1832
+ * @param hookList the uponSanitize* hook array for this event
1833
+ * @param set the current ALLOWED_TAGS / ALLOWED_ATTR binding
1834
+ * @param defaultSet the per-instance DEFAULT_ALLOWED_* constant
1835
+ * @param setConfigSet the captured setConfig() binding, or null
1836
+ * @return a call-local clone if a hook is present and set is still shared,
1837
+ * else set unchanged
1838
+ */
1839
+ const _forkSharedAllowlist = function _forkSharedAllowlist(hookList, set, defaultSet, setConfigSet) {
1840
+ if (hookList.length === 0) {
1841
+ return set;
1842
+ }
1843
+ return set === defaultSet || set === setConfigSet ? clone(set) : set;
1844
+ };
1845
+ /**
1846
+ * Shared guard for a node that a hook has detached from the walk tree,
1847
+ * used after each element-hook site in _sanitizeElements. Detaching is a
1848
+ * long-standing user pattern (issue #469; draw.io-style foreignObject
1849
+ * filtering). Per the cached, unclobberable parentNode getter the node is
1850
+ * genuinely out of the tree, so it can reach neither the serialized
1851
+ * output nor an IN_PLACE live tree; treat it as removed and stop
1852
+ * processing it. Without this guard, the unsafe-node / namespace checks
1853
+ * would call _forceRemove on a parentless node and hit the REPORT-3
1854
+ * fail-closed throw — which exists for nodes DOMPurify wants gone but
1855
+ * *cannot* detach (clobbered / parentless roots), the opposite of a node
1856
+ * that is already safely gone. The walk root is exempt: a detached
1857
+ * IN_PLACE root is legitimate input and must still be fully sanitized,
1858
+ * and a kill-decision on it must keep hitting the REPORT-3 throw.
1859
+ *
1860
+ * Nodes detached by hooks stay the hook's responsibility for placement:
1861
+ * they are not recorded in DOMPurify.removed, so the post-walk IN_PLACE
1862
+ * pass (which iterates DOMPurify.removed) does not reach them. But a
1863
+ * hook-detached subtree can still hold a queued resource-event handler -
1864
+ * e.g. an <img onload> that began loading when the caller built the live
1865
+ * tree - which fires in page scope after sanitize returns even though the
1866
+ * handler never reached the returned tree. That is the audit-5 F1 hazard,
1867
+ * and the documented node.remove() hook pattern walks straight into it.
1868
+ * So on the IN_PLACE path we neutralize the detached subtree inline,
1869
+ * stripping its non-allow-listed attributes before returning, exactly as
1870
+ * the post-walk pass does for _forceRemove'd subtrees.
1871
+ *
1872
+ * @param currentNode the node a hook may have detached
1873
+ * @param root the current walk root
1874
+ * @return true if the node is detached and now handled, false otherwise
1875
+ */
1876
+ const _handleHookDetachedNode = function _handleHookDetachedNode(currentNode, root) {
1877
+ if (currentNode === root || getParentNode(currentNode) !== null) {
1878
+ return false;
1879
+ }
1880
+ if (IN_PLACE) {
1881
+ _neutralizeSubtree(currentNode);
1882
+ }
1883
+ return true;
1884
+ };
1885
+ /**
1886
+ * _sanitizeElements
1887
+ *
1888
+ * @protect nodeName
1889
+ * @protect textContent
1890
+ * @protect removeChild
1891
+ * @param currentNode to check for permission to exist
1892
+ * @return true if node was killed, false if left alive
1893
+ */
1894
+ const _sanitizeElements = function _sanitizeElements(currentNode, root) {
1895
+ /* Execute a hook if present */
1896
+ _executeHooks(hooks.beforeSanitizeElements, currentNode, null);
1897
+ /* A hook may have detached the node - treat it as removed (see
1898
+ _handleHookDetachedNode for the full rationale). */
1899
+ if (_handleHookDetachedNode(currentNode, root)) {
1900
+ return true;
1901
+ }
1902
+ /* Check if element is clobbered or can clobber */
1903
+ if (_isClobbered(currentNode)) {
1904
+ _forceRemove(currentNode);
1905
+ return true;
1906
+ }
1907
+ /* Now let's check the element's type and name */
1908
+ const tagName = transformCaseFunc(_readNodeName(currentNode));
1909
+ /* Close the pre-walk clone-guard's timing gap: an uponSanitizeElement
1910
+ hook may have been installed after that guard sampled the hook arrays
1911
+ (e.g. lazily from beforeSanitizeElements), leaving ALLOWED_TAGS still
1912
+ aliasing a shared binding that a widening hook would mutate by
1913
+ reference. Fork it before exposing it to the hook. */
1914
+ ALLOWED_TAGS = _forkSharedAllowlist(hooks.uponSanitizeElement, ALLOWED_TAGS, DEFAULT_ALLOWED_TAGS, SET_CONFIG_ALLOWED_TAGS);
1915
+ /* Execute a hook if present */
1916
+ _executeHooks(hooks.uponSanitizeElement, currentNode, {
1917
+ tagName,
1918
+ allowedTags: ALLOWED_TAGS
1919
+ });
1920
+ /* The uponSanitizeElement hook may have detached the node, exactly as
1921
+ above (see _handleHookDetachedNode for the full rationale). */
1922
+ if (_handleHookDetachedNode(currentNode, root)) {
1923
+ return true;
1924
+ }
1925
+ /* Remove mXSS vectors, processing instructions and risky comments */
1926
+ if (_isUnsafeNode(currentNode, tagName)) {
1927
+ _forceRemove(currentNode);
1928
+ return true;
1929
+ }
1930
+ /* Remove element if anything forbids its presence */
1931
+ if (FORBID_TAGS[tagName] || !(EXTRA_ELEMENT_HANDLING.tagCheck instanceof Function && EXTRA_ELEMENT_HANDLING.tagCheck(tagName)) && !ALLOWED_TAGS[tagName]) {
1932
+ const removed = _sanitizeDisallowedNode(currentNode, tagName, root);
1933
+ /* A false return means the node is a custom element kept via
1934
+ CUSTOM_ELEMENT_HANDLING - the only keep path through
1935
+ _sanitizeDisallowedNode. Run afterSanitizeElements on it so the
1936
+ element-hook lifecycle matches normal allowlisted elements: a
1937
+ security policy applied in this hook (e.g. stripping an attribute
1938
+ from every surviving element) must not silently skip kept custom
1939
+ elements (GHSA-c2j3-45gr-mqc4). This mirrors the normal-element
1940
+ tail below - the hook runs, then the walker's subsequent
1941
+ _sanitizeAttributes pass sanitizes the element's attributes. The
1942
+ deliberately skipped namespace and fallback-tag removal checks stay
1943
+ skipped; they are removal decisions, not the hook contract. */
1944
+ if (removed === false) {
1945
+ _executeHooks(hooks.afterSanitizeElements, currentNode, null);
1946
+ }
1947
+ return removed;
1948
+ }
1949
+ /* Check whether element has a valid namespace.
1950
+ Realm-safe check (GHSA-hpcv-96wg-7vj8): use the cached Node.prototype
1951
+ nodeType getter rather than `instanceof Element`, which is realm-
1952
+ bound and short-circuits to false for any node minted in a different
1953
+ realm — letting a foreign-realm element with a forbidden namespace
1954
+ slip past the namespace check entirely. */
1955
+ const nt = _readNodeType(currentNode);
1956
+ if (nt === NODE_TYPE.element && !_checkValidNamespace(currentNode)) {
1957
+ _forceRemove(currentNode);
1958
+ return true;
1959
+ }
1960
+ /* Make sure that older browsers don't get fallback-tag mXSS */
1961
+ if ((tagName === 'noscript' || tagName === 'noembed' || tagName === 'noframes') && regExpTest(FALLBACK_TAG_CLOSE, currentNode.innerHTML)) {
1962
+ _forceRemove(currentNode);
1963
+ return true;
1964
+ }
1965
+ /* Sanitize element content to be template-safe */
1966
+ if (SAFE_FOR_TEMPLATES && currentNode.nodeType === NODE_TYPE.text) {
1967
+ /* Get the element's text content */
1968
+ const content = _stripTemplateExpressions(currentNode.textContent);
1969
+ if (currentNode.textContent !== content) {
1970
+ arrayPush(DOMPurify.removed, {
1971
+ element: currentNode.cloneNode()
1972
+ });
1973
+ currentNode.textContent = content;
1974
+ }
1975
+ }
1976
+ /* Execute a hook if present */
1977
+ _executeHooks(hooks.afterSanitizeElements, currentNode, null);
1978
+ return false;
1979
+ };
1980
+ /**
1981
+ * _isValidAttribute
1982
+ *
1983
+ * @param lcTag Lowercase tag name of containing element.
1984
+ * @param lcName Lowercase attribute name.
1985
+ * @param value Attribute value.
1986
+ * @return Returns true if `value` is valid, otherwise false.
1987
+ */
1988
+ // eslint-disable-next-line complexity
1989
+ const _isValidAttribute = function _isValidAttribute(lcTag, lcName, value) {
1990
+ /* FORBID_ATTR must always win, even if ADD_ATTR predicate would allow it */
1991
+ if (FORBID_ATTR[lcName]) {
1992
+ return false;
1993
+ }
1994
+ /* Reject declarative-partial-updates patch-linkage attributes
1995
+ (https://github.com/WICG/declarative-partial-updates).
1996
+ Empirical note (Chrome 150, verified — see
1997
+ test/declarative-patch-probe-v3.html): expansion is NOT applied after
1998
+ sanitization. For the string path it fires during sanitize()'s own
1999
+ parse, so the walk sees and sanitizes the fully materialized expanded
2000
+ tree — teleports into MathML/SVG integration points included; a
2001
+ weaponized `<template for>`->`<img onerror>` comes back with the handler
2002
+ stripped. For the IN_PLACE path it fires on connection, before the walk.
2003
+ Either way DOMPurify is NOT blind to the patch.
2004
+ This removal is therefore defense-in-depth rather than the sole barrier:
2005
+ it prevents live linkage from surviving into the OUTPUT and re-expanding
2006
+ in the caller's context, and keeps behaviour deterministic if a future
2007
+ engine defers expansion. `for` is legitimate only on <label>/<output>;
2008
+ anywhere else (notably <template for>) it links the element to a patch
2009
+ target and teleports or removes an arbitrary DOM range by id/marker name.
2010
+ `patchsrc` fetches remote markup and is treated as a script-loading
2011
+ mechanism (CSP). Gated on SAFE_FOR_XML so the removal groups with the
2012
+ other structural-threat checks and stays overridable, consistent with
2013
+ the rest of the codebase. PI range markers are already removed by
2014
+ _isUnsafeNode. */
2015
+ if (_isPatchLinkageAttribute(lcName, lcTag)) {
2016
+ return false;
2017
+ }
2018
+ /* Make sure attribute cannot clobber */
2019
+ if (SANITIZE_DOM && (lcName === 'id' || lcName === 'name') && (value in document || value in formElement)) {
2020
+ return false;
2021
+ }
2022
+ const nameIsPermitted = ALLOWED_ATTR[lcName] || EXTRA_ELEMENT_HANDLING.attributeCheck instanceof Function && EXTRA_ELEMENT_HANDLING.attributeCheck(lcName, lcTag);
2023
+ /* Allow valid data-* attributes: At least one character after "-"
2024
+ (https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes)
2025
+ XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804)
2026
+ We don't need to check the value; it's always URI safe. */
2027
+ if (ALLOW_DATA_ATTR && regExpTest(DATA_ATTR$1, lcName)) {
2028
+ return true;
2029
+ }
2030
+ /* Allow valid aria-* attributes, the value is always URI safe */
2031
+ if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR$1, lcName)) {
2032
+ return true;
2033
+ }
2034
+ /* A name outside the allowlist is acceptable on custom-element terms
2035
+ only. The value checks below are intentionally skipped in that case:
2036
+ if the user supplied a tagNameCheck we also allow derived custom
2037
+ elements using the same test, and attributes passing the configured
2038
+ attributeNameCheck are allowed as custom elements define these at
2039
+ their own discretion. */
2040
+ if (!nameIsPermitted) {
2041
+ return (
2042
+ // Condition a) covers a basically valid custom element tag name whose
2043
+ // tag passes the configured tagNameCheck and whose attribute name
2044
+ // passes the configured attributeNameCheck ...
2045
+ _isBasicCustomElement(lcTag) && _matchesNameCheck(CUSTOM_ELEMENT_HANDLING.tagNameCheck, lcTag) && _matchesNameCheck(CUSTOM_ELEMENT_HANDLING.attributeNameCheck, lcName, lcTag) ||
2046
+ // Condition b) covers an `is` attribute whose value passes the
2047
+ // configured tagNameCheck while customized built-in elements are
2048
+ // allowed.
2049
+ lcName === 'is' && CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements && _matchesNameCheck(CUSTOM_ELEMENT_HANDLING.tagNameCheck, value)
2050
+ );
2051
+ }
2052
+ /* Check value is safe. First, is attr inert? If so, is safe */
2053
+ if (URI_SAFE_ATTRIBUTES[lcName]) {
2054
+ return true;
2055
+ }
2056
+ /* Check no script, data or unknown possibly unsafe URI
2057
+ unless we know URI values are safe for that attribute */
2058
+ if (regExpTest(IS_ALLOWED_URI$1, stringReplace(value, ATTR_WHITESPACE$1, ''))) {
2059
+ return true;
2060
+ }
2061
+ /* Keep image data URIs alive if src/xlink:href is allowed */
2062
+ /* Further prevent gadget XSS for dynamically built script tags */
2063
+ if ((lcName === 'src' || lcName === 'xlink:href' || lcName === 'href') && lcTag !== 'script' && stringIndexOf(value, 'data:') === 0 && DATA_URI_TAGS[lcTag]) {
2064
+ return true;
2065
+ }
2066
+ /* Allow unknown protocols: This provides support for links that
2067
+ are handled by protocol handlers which may be unknown ahead of
2068
+ time, e.g. fb:, spotify: */
2069
+ if (ALLOW_UNKNOWN_PROTOCOLS && !regExpTest(IS_SCRIPT_OR_DATA$1, stringReplace(value, ATTR_WHITESPACE$1, ''))) {
2070
+ return true;
2071
+ }
2072
+ /* Only an empty (binary) value remains safe at this point;
2073
+ anything else is presumed unsafe, do not add it back */
2074
+ return !value;
2075
+ };
2076
+ /* Names the HTML spec reserves from valid-custom-element-name; these must
2077
+ * never be treated as basic custom elements even when a permissive
2078
+ * CUSTOM_ELEMENT_HANDLING.tagNameCheck is configured. */
2079
+ 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']);
2080
+ /**
2081
+ * _isBasicCustomElement
2082
+ * checks if at least one dash is included in tagName, and it's not the first char
2083
+ * for more sophisticated checking see https://github.com/sindresorhus/validate-element-name
2084
+ *
2085
+ * @param tagName name of the tag of the node to sanitize
2086
+ * @returns Returns true if the tag name meets the basic criteria for a custom element, otherwise false.
2087
+ */
2088
+ const _isBasicCustomElement = function _isBasicCustomElement(tagName) {
2089
+ return !RESERVED_CUSTOM_ELEMENT_NAMES[stringToLowerCase(tagName)] && regExpTest(CUSTOM_ELEMENT$1, tagName);
2090
+ };
2091
+ /**
2092
+ * Wrap an attribute value in the matching Trusted Types object when
2093
+ * the active policy requires it. Namespaced attributes pass through
2094
+ * unchanged (no TT support yet, see
2095
+ * https://bugs.chromium.org/p/chromium/issues/detail?id=1305293).
2096
+ *
2097
+ * @param lcTag lowercase tag name of the containing element
2098
+ * @param lcName lowercase attribute name
2099
+ * @param namespaceURI the attribute's namespace, if any
2100
+ * @param value the attribute value to wrap
2101
+ * @return the value, wrapped when Trusted Types demand it
2102
+ */
2103
+ const _applyTrustedTypesToAttribute = function _applyTrustedTypesToAttribute(lcTag, lcName, namespaceURI, value) {
2104
+ if (trustedTypesPolicy && typeof trustedTypes === 'object' && typeof trustedTypes.getAttributeType === 'function' && !namespaceURI) {
2105
+ switch (trustedTypes.getAttributeType(lcTag, lcName)) {
2106
+ case 'TrustedHTML':
2107
+ {
2108
+ return _createTrustedHTML(value);
2109
+ }
2110
+ case 'TrustedScriptURL':
2111
+ {
2112
+ return _createTrustedScriptURL(value);
2113
+ }
2114
+ }
2115
+ }
2116
+ return value;
2117
+ };
2118
+ /**
2119
+ * Write a modified attribute value back onto the element. On
2120
+ * success, re-probe for clobbering introduced by the new value and
2121
+ * remove the element when found; otherwise, when this writeback is the
2122
+ * recreate half of the SANITIZE_NAMED_PROPS remove-and-recreate, pop the
2123
+ * removal entry that path recorded so it does not show as removed. On
2124
+ * failure, remove the attribute instead.
2125
+ *
2126
+ * Returns true only on a clean write (the value was set and the new value
2127
+ * introduced no clobbering). The caller uses that, together with its own
2128
+ * knowledge of whether this attribute pushed a DOMPurify.removed record, to
2129
+ * decide whether to pop that record. The pop must happen ONLY for the
2130
+ * named-prop remove-and-recreate; popping on any other value change (trim,
2131
+ * template scrubbing, Trusted Types) would consume an unrelated _forceRemove
2132
+ * subtree-cleanup record and let that detached subtree keep a live event
2133
+ * handler through the IN_PLACE neutralization pass (SO-001).
2134
+ *
2135
+ * @param currentNode the element carrying the attribute
2136
+ * @param name the attribute name as present on the element
2137
+ * @param namespaceURI the attribute's namespace, if any
2138
+ * @param value the new attribute value
2139
+ * @return true if the value was written without introducing clobbering
2140
+ */
2141
+ const _setAttributeValue = function _setAttributeValue(currentNode, name, namespaceURI, value) {
2142
+ try {
2143
+ if (namespaceURI) {
2144
+ currentNode.setAttributeNS(namespaceURI, name, value);
2145
+ } else {
2146
+ /* Fallback to setAttribute() for browser-unrecognized namespaces e.g. "x-schema". */
2147
+ currentNode.setAttribute(name, value);
2148
+ }
2149
+ if (_isClobbered(currentNode)) {
2150
+ _forceRemove(currentNode);
2151
+ return false;
2152
+ }
2153
+ return true;
2154
+ } catch (_) {
2155
+ _removeAttribute(name, currentNode);
2156
+ return false;
2157
+ }
2158
+ };
2159
+ /**
2160
+ * _sanitizeAttributes
2161
+ *
2162
+ * @protect attributes
2163
+ * @protect nodeName
2164
+ * @protect removeAttribute
2165
+ * @protect setAttribute
2166
+ *
2167
+ * @param currentNode to sanitize
2168
+ */
2169
+ // eslint-disable-next-line complexity
2170
+ const _sanitizeAttributes = function _sanitizeAttributes(currentNode) {
2171
+ /* Execute a hook if present */
2172
+ _executeHooks(hooks.beforeSanitizeAttributes, currentNode, null);
2173
+ const attributes = currentNode.attributes;
2174
+ /* Check if we have attributes; if not we might have a text node */
2175
+ if (!attributes || _isClobbered(currentNode)) {
2176
+ return;
2177
+ }
2178
+ /* Same lazy-install guard as uponSanitizeElement (see there): fork the
2179
+ attribute allowlist off its shared binding before a hook can see it. */
2180
+ ALLOWED_ATTR = _forkSharedAllowlist(hooks.uponSanitizeAttribute, ALLOWED_ATTR, DEFAULT_ALLOWED_ATTR, SET_CONFIG_ALLOWED_ATTR);
2181
+ const hookEvent = {
2182
+ attrName: '',
2183
+ attrValue: '',
2184
+ keepAttr: true,
2185
+ allowedAttributes: ALLOWED_ATTR,
2186
+ forceKeepAttr: undefined
2187
+ };
2188
+ let l = attributes.length;
2189
+ const lcTag = transformCaseFunc(currentNode.nodeName);
2190
+ /* Go backwards over all attributes; safely remove bad ones */
2191
+ while (l--) {
2192
+ const attr = attributes[l];
2193
+ const name = attr.name,
2194
+ namespaceURI = attr.namespaceURI,
2195
+ attrValue = attr.value;
2196
+ const lcName = transformCaseFunc(name);
2197
+ const initValue = attrValue;
2198
+ let value = name === 'value' ? initValue : stringTrim(initValue);
2199
+ /* Tracks whether this specific attribute pushed a DOMPurify.removed
2200
+ record that a later _setAttributeValue() writeback is expected to pop
2201
+ back off (the SANITIZE_NAMED_PROPS remove-and-recreate below is the
2202
+ only path that does). A value that merely changed via trim, template
2203
+ scrubbing, or Trusted Types pushes no such record, so its writeback
2204
+ must NOT pop — otherwise it consumes an unrelated _forceRemove subtree
2205
+ record and that detached subtree escapes the IN_PLACE handler-
2206
+ neutralization pass (SO-001). */
2207
+ let recreatedNamedProp = false;
2208
+ /* Execute a hook if present */
2209
+ hookEvent.attrName = lcName;
2210
+ hookEvent.attrValue = value;
2211
+ hookEvent.keepAttr = true;
2212
+ hookEvent.forceKeepAttr = undefined; // Allows developers to see this is a property they can set
2213
+ _executeHooks(hooks.uponSanitizeAttribute, currentNode, hookEvent);
2214
+ value = hookEvent.attrValue;
2215
+ /* Full DOM Clobbering protection via namespace isolation,
2216
+ * Prefix id and name attributes with `user-content-`
2217
+ */
2218
+ if (SANITIZE_NAMED_PROPS && (lcName === 'id' || lcName === 'name') && stringIndexOf(value, SANITIZE_NAMED_PROPS_PREFIX) !== 0) {
2219
+ // Remove the attribute with this value
2220
+ _removeAttribute(name, currentNode, attr);
2221
+ // Prefix the value and later re-create the attribute with the sanitized value
2222
+ value = SANITIZE_NAMED_PROPS_PREFIX + value;
2223
+ // This attribute owns the record just pushed; its recreate writeback
2224
+ // is the one allowed to pop it back off.
2225
+ recreatedNamedProp = true;
2226
+ }
2227
+ // Else: already prefixed, leave the attribute alone — the prefix is
2228
+ // itself the clobbering protection, and re-applying it is incorrect.
2229
+ /* Work around a security issue with comments inside attributes */
2230
+ if (SAFE_FOR_XML && regExpTest(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i, value)) {
2231
+ _removeAttribute(name, currentNode, attr);
2232
+ continue;
2233
+ }
2234
+ /* Make sure we cannot easily use animated hrefs, even if animations are allowed */
2235
+ if (lcName === 'attributename' && stringMatch(value, 'href')) {
2236
+ _removeAttribute(name, currentNode, attr);
2237
+ continue;
2238
+ }
2239
+ /* Did the hooks force-keep the attribute? */
2240
+ if (hookEvent.forceKeepAttr) {
2241
+ continue;
2242
+ }
2243
+ /* Did the hooks approve of the attribute? */
2244
+ if (!hookEvent.keepAttr) {
2245
+ _removeAttribute(name, currentNode, attr);
2246
+ continue;
2247
+ }
2248
+ /* Work around a security issue in jQuery 3.0 */
2249
+ if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(SELF_CLOSING_TAG, value)) {
2250
+ _removeAttribute(name, currentNode, attr);
2251
+ continue;
2252
+ }
2253
+ /* Sanitize attribute content to be template-safe */
2254
+ if (SAFE_FOR_TEMPLATES) {
2255
+ value = _stripTemplateExpressions(value);
2256
+ }
2257
+ /* Is `value` valid for this attribute? */
2258
+ if (!_isValidAttribute(lcTag, lcName, value)) {
2259
+ _removeAttribute(name, currentNode, attr);
2260
+ continue;
2261
+ }
2262
+ /* Handle attributes that require Trusted Types */
2263
+ value = _applyTrustedTypesToAttribute(lcTag, lcName, namespaceURI, value);
2264
+ /* Handle invalid data-* attribute set by try-catching it */
2265
+ if (value !== initValue) {
2266
+ const cleanWrite = _setAttributeValue(currentNode, name, namespaceURI, value);
2267
+ /* Only the named-prop remove-and-recreate owns a DOMPurify.removed
2268
+ record to pop; a plain trim/template/Trusted-Types writeback owns
2269
+ none, so popping here would drop an unrelated subtree's cleanup
2270
+ record (SO-001). */
2271
+ if (cleanWrite && recreatedNamedProp) {
2272
+ arrayPop(DOMPurify.removed);
2273
+ }
2274
+ }
2275
+ }
2276
+ /* Execute a hook if present */
2277
+ _executeHooks(hooks.afterSanitizeAttributes, currentNode, null);
2278
+ };
2279
+ /**
2280
+ * _sanitizeShadowDOM
2281
+ *
2282
+ * @param fragment to iterate over recursively
2283
+ */
2284
+ const _sanitizeShadowDOM2 = function _sanitizeShadowDOM(fragment) {
2285
+ let shadowNode = null;
2286
+ const shadowIterator = _createNodeIterator(fragment);
2287
+ /* Execute a hook if present */
2288
+ _executeHooks(hooks.beforeSanitizeShadowDOM, fragment, null);
2289
+ while (shadowNode = shadowIterator.nextNode()) {
2290
+ /* Execute a hook if present */
2291
+ _executeHooks(hooks.uponSanitizeShadowNode, shadowNode, null);
2292
+ /* Sanitize tags and elements */
2293
+ _sanitizeElements(shadowNode, fragment);
2294
+ /* Check attributes next */
2295
+ _sanitizeAttributes(shadowNode);
2296
+ /* Deep shadow DOM detected.
2297
+ Realm-safe check (GHSA-hpcv-96wg-7vj8): use nodeType against the
2298
+ DOCUMENT_FRAGMENT_NODE constant rather than instanceof, so we
2299
+ recurse into <template>.content from foreign realms too. */
2300
+ if (_isDocumentFragment(shadowNode.content)) {
2301
+ _sanitizeShadowDOM2(shadowNode.content);
2302
+ }
2303
+ /* An element iterated here may itself host an attached
2304
+ shadow root. The default NodeIterator does not enter shadow
2305
+ trees, so a shadow root nested inside template.content was
2306
+ previously reached by no walk at all (the pre-pass at
2307
+ _sanitizeAttachedShadowRoots descends via childNodes, which
2308
+ doesn't enter template.content; the template-content recursion
2309
+ above iterates the content but never inspected shadowRoot).
2310
+ Walk it explicitly. The nodeType guard avoids reading
2311
+ shadowRoot off text / comment / CDATA / PI nodes that the
2312
+ iterator also surfaces. */
2313
+ if (_readNodeType(shadowNode) === NODE_TYPE.element) {
2314
+ const innerSr = getShadowRoot(shadowNode);
2315
+ if (_isDocumentFragment(innerSr)) {
2316
+ _sanitizeAttachedShadowRoots(innerSr);
2317
+ _sanitizeShadowDOM2(innerSr);
2318
+ }
2319
+ }
2320
+ }
2321
+ /* Execute a hook if present */
2322
+ _executeHooks(hooks.afterSanitizeShadowDOM, fragment, null);
2323
+ };
2324
+ /**
2325
+ * _sanitizeAttachedShadowRoots
2326
+ *
2327
+ * Walks `root` and feeds every attached shadow root we encounter into
2328
+ * the existing _sanitizeShadowDOM pipeline. The default node iterator
2329
+ * does not descend into shadow trees, so nodes inside an attached
2330
+ * shadow root would otherwise be skipped entirely.
2331
+ *
2332
+ * Two real input paths put attached shadow roots in front of us:
2333
+ * 1. IN_PLACE on a DOM node that already has shadow roots attached.
2334
+ * 2. DOM-node input where importNode(dirty, true) deep-clones the
2335
+ * shadow root because it was created with `clonable: true`.
2336
+ *
2337
+ * This pass runs once, up front, so the main iteration loop (and the
2338
+ * existing _sanitizeShadowDOM template-content recursion) stay
2339
+ * untouched — string-input paths are not affected.
2340
+ *
2341
+ * @param root the subtree root to walk for attached shadow roots
2342
+ */
2343
+ const _sanitizeAttachedShadowRoots = function _sanitizeAttachedShadowRoots(root) {
2344
+ /* Iterative (explicit stack) rather than per-child recursion. DOM APIs
2345
+ impose no depth cap, so an attacker-shaped tree (JSON/CRDT/editor data
2346
+ built straight into the DOM — the IN_PLACE surface) deeper than the JS
2347
+ call-stack budget would otherwise overflow native recursion here and
2348
+ throw at the IN_PLACE entry pre-pass, before a single node is
2349
+ sanitized, leaving the caller's live tree untouched (fail-open). See
2350
+ campaign-3 F4. A heap stack keeps depth off the call stack.
2351
+ Each work item is either a node to descend into, or a deferred
2352
+ `_sanitizeShadowDOM` for an already-walked shadow root. The deferred
2353
+ form preserves the original post-order discipline: a shadow root's
2354
+ nested shadow roots are discovered before the outer shadow is
2355
+ sanitized (which may remove hosts). Pushes are in reverse of the
2356
+ desired processing order (LIFO): template content, then children, then
2357
+ the shadow-sanitize, then the shadow walk — so the order matches the
2358
+ previous recursion exactly. */
2359
+ const stack = [{
2360
+ node: root,
2361
+ shadow: null
2362
+ }];
2363
+ while (stack.length > 0) {
2364
+ const item = stack.pop();
2365
+ /* Deferred shadow-DOM sanitisation: runs after its subtree was walked. */
2366
+ if (item.shadow) {
2367
+ _sanitizeShadowDOM2(item.shadow);
2368
+ continue;
2369
+ }
2370
+ const node = item.node;
2371
+ const nodeType = _readNodeType(node);
2372
+ const isElement = nodeType === NODE_TYPE.element;
2373
+ /* (pushed last → processed first) Children, snapshotted in reverse so
2374
+ the first child is processed first. Snapshotting matters because a
2375
+ hook may detach siblings mid-walk. */
2376
+ const childNodes = getChildNodes(node);
2377
+ if (childNodes) {
2378
+ for (let i = childNodes.length - 1; i >= 0; --i) {
2379
+ stack.push({
2380
+ node: childNodes[i],
2381
+ shadow: null
2382
+ });
2383
+ }
2384
+ }
2385
+ /* (pushed before children → processed after them, matching the old
2386
+ "template content last" order) When the node is a <template>,
2387
+ descend into its content. */
2388
+ if (isElement) {
2389
+ const rootName = getNodeName ? getNodeName(node) : null;
2390
+ if (typeof rootName === 'string' && transformCaseFunc(rootName) === 'template') {
2391
+ const content = node.content;
2392
+ if (_isDocumentFragment(content)) {
2393
+ stack.push({
2394
+ node: content,
2395
+ shadow: null
2396
+ });
2397
+ }
2398
+ }
2399
+ }
2400
+ /* Shadow root (processed first): walk its subtree, then sanitise it.
2401
+ Realm-safe check (GHSA-hpcv-96wg-7vj8): nodeType-based detection
2402
+ rather than `instanceof DocumentFragment`, which is realm-bound and
2403
+ silently skipped foreign-realm shadow roots (e.g.
2404
+ iframe.contentDocument attachShadow). */
2405
+ if (isElement) {
2406
+ const sr = getShadowRoot(node);
2407
+ if (_isDocumentFragment(sr)) {
2408
+ /* Push the deferred sanitise first so it pops after the shadow
2409
+ walk we push next, i.e. nested shadow roots are discovered
2410
+ before this one is sanitised. */
2411
+ stack.push({
2412
+ node: null,
2413
+ shadow: sr
2414
+ }, {
2415
+ node: sr,
2416
+ shadow: null
2417
+ });
2418
+ }
2419
+ }
2420
+ }
2421
+ };
2422
+ // eslint-disable-next-line complexity
2423
+ DOMPurify.sanitize = function (dirty) {
2424
+ let cfg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
2425
+ let body = null;
2426
+ let importedNode = null;
2427
+ let currentNode = null;
2428
+ let returnNode = null;
2429
+ /* Make sure we have a string to sanitize.
2430
+ DO NOT return early, as this will return the wrong type if
2431
+ the user has requested a DOM object rather than a string */
2432
+ IS_EMPTY_INPUT = !dirty;
2433
+ if (IS_EMPTY_INPUT) {
2434
+ dirty = '<!-->';
2435
+ }
2436
+ /* Stringify, in case dirty is an object */
2437
+ if (typeof dirty !== 'string' && !_isNode(dirty)) {
2438
+ dirty = stringifyValue(dirty);
2439
+ if (typeof dirty !== 'string') {
2440
+ throw typeErrorCreate('dirty is not a string, aborting');
2441
+ }
2442
+ }
2443
+ /* Return dirty HTML if DOMPurify cannot run */
2444
+ if (!DOMPurify.isSupported) {
2445
+ return dirty;
2446
+ }
2447
+ /* Assign config vars */
2448
+ if (SET_CONFIG) {
2449
+ /* Persistent setConfig() path: _parseConfig is skipped, so the sets are
2450
+ * not re-derived per call. Restore them from the pristine bindings
2451
+ * captured at setConfig() time so a previous call's hook clone (mutated
2452
+ * below) does not carry over. */
2453
+ ALLOWED_TAGS = SET_CONFIG_ALLOWED_TAGS;
2454
+ ALLOWED_ATTR = SET_CONFIG_ALLOWED_ATTR;
2455
+ } else {
2456
+ _parseConfig(cfg);
2457
+ }
2458
+ /* Clone the hook-mutable allowlists before the walk whenever an
2459
+ * uponSanitize* hook is registered. The hook event exposes ALLOWED_TAGS
2460
+ * and ALLOWED_ATTR by reference (as allowedTags / allowedAttributes), so
2461
+ * a hook that widens them would otherwise mutate the shared set
2462
+ * permanently: across later calls and across every element. Cloning per
2463
+ * walk keeps documented in-call widening working while scoping it to the
2464
+ * call. A single guard for both config paths - the per-call path rebinds
2465
+ * the sets in _parseConfig each call, the persistent path restores them
2466
+ * from the captured bindings just above - so the two cannot diverge. */
2467
+ if (hooks.uponSanitizeElement.length > 0 || hooks.uponSanitizeAttribute.length > 0) {
2468
+ ALLOWED_TAGS = clone(ALLOWED_TAGS);
2469
+ }
2470
+ if (hooks.uponSanitizeAttribute.length > 0) {
2471
+ ALLOWED_ATTR = clone(ALLOWED_ATTR);
2472
+ }
2473
+ /* Clean up removed elements */
2474
+ DOMPurify.removed = [];
2475
+ /* Resolve IN_PLACE for this call without mutating persistent config.
2476
+ Writing the IN_PLACE closure variable here leaks under setConfig(),
2477
+ where _parseConfig is skipped on later calls: a single string call would
2478
+ disable in-place mode for every subsequent node call, returning a
2479
+ sanitized copy while leaving the caller's node — which in-place callers
2480
+ keep using and whose return value they ignore — unsanitized. REPORT-2. */
2481
+ const inPlace = IN_PLACE && typeof dirty !== 'string' && _isNode(dirty);
2482
+ if (inPlace) {
2483
+ /* Declarative-partial-updates / streaming pre-pass: sever every patch
2484
+ linkage across the live tree BEFORE the walk, so no patch can fire
2485
+ mid-walk and inject into an already-processed region. Runs first, so
2486
+ it also covers the forbidden/clobbered roots that throw below. */
2487
+ _neutralizePatchLinkage(dirty);
2488
+ /* Do some early pre-sanitization to avoid unsafe root nodes.
2489
+ Read nodeName through the cached prototype getter — a clobbering
2490
+ child named "nodeName" on the form root would otherwise shadow
2491
+ the property and let this check skip the root-allowlist
2492
+ validation entirely. */
2493
+ const nn = _readNodeName(dirty);
2494
+ if (typeof nn === 'string') {
2495
+ const tagName = transformCaseFunc(nn);
2496
+ if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
2497
+ /* Fail closed on a live root: neutralize handlers/children before
2498
+ throwing, exactly as the mid-walk abort path does. */
2499
+ _neutralizeRoot(dirty);
2500
+ throw typeErrorCreate('root node is forbidden and cannot be sanitized in-place');
2501
+ }
2502
+ }
2503
+ /* Pre-flight the root through _isClobbered. The iterator-driven
2504
+ removal path can not detach a parent-less root: _forceRemove
2505
+ falls through to Element.prototype.remove(), which per spec
2506
+ is a no-op on a node with no parent. A clobbered root would
2507
+ then survive the main loop with its attributes uninspected,
2508
+ because _sanitizeAttributes early-returns on _isClobbered. The
2509
+ result would be an attacker-controlled form, complete with any
2510
+ event-handler attributes the caller passed in, handed back to
2511
+ the application unsanitized. Refuse to sanitize such a root
2512
+ the same way we refuse a forbidden tag. GHSA-r47g-fvhr-h676. */
2513
+ if (_isClobbered(dirty)) {
2514
+ /* Fail closed on a live clobbered root before throwing.
2515
+ _neutralizeRoot's reads are clobber-safe (cached getters); the
2516
+ form's non-clobbered descendants, e.g. an armed <img>, are scrubbed. */
2517
+ _neutralizeRoot(dirty);
2518
+ throw typeErrorCreate('root node is clobbered and cannot be sanitized in-place');
2519
+ }
2520
+ /* Sanitize attached shadow roots before the main iterator runs.
2521
+ The iterator does not descend into shadow trees. Same fail-closed
2522
+ barrier as the main walk (campaign-3 F2): a custom-element reaction
2523
+ inside a shadow root could abort this pre-pass before the walk runs,
2524
+ which would otherwise leave the entire live tree unsanitized. */
2525
+ try {
2526
+ _sanitizeAttachedShadowRoots(dirty);
2527
+ } catch (error) {
2528
+ _neutralizeRoot(dirty);
2529
+ throw error;
2530
+ }
2531
+ } else if (_isNode(dirty)) {
2532
+ /* If dirty is a DOM element, append to an empty document to avoid
2533
+ elements being stripped by the parser */
2534
+ body = _initDocument('<!---->');
2535
+ importedNode = body.ownerDocument.importNode(dirty, true);
2536
+ if (importedNode.nodeType === NODE_TYPE.element && importedNode.nodeName === 'BODY') {
2537
+ /* Node is already a body, use as is */
2538
+ body = importedNode;
2539
+ } else if (importedNode.nodeName === 'HTML') {
2540
+ body = importedNode;
2541
+ } else {
2542
+ // eslint-disable-next-line unicorn/prefer-dom-node-append
2543
+ body.appendChild(importedNode);
2544
+ }
2545
+ /* Clonable shadow roots are deep-cloned by importNode(); sanitize
2546
+ them before the main iterator runs, since the iterator does not
2547
+ descend into shadow trees. The walk routes every read through a
2548
+ cached prototype getter so clobbering descendants on a form root
2549
+ cannot hide a shadow host from this pass.
2550
+ Traverse from `body`, not `importedNode`: when importedNode is a
2551
+ DocumentFragment, the appendChild() above moves its children into
2552
+ `body` and leaves the fragment empty, so walking importedNode would
2553
+ scan nothing and miss every attached shadow host now under `body`
2554
+ (SO-003). In the BODY/HTML branches `body === importedNode`, so this
2555
+ is equivalent there; in the element branch `body` contains the
2556
+ appended element and its descendants. `body` covers all three. */
2557
+ _sanitizeAttachedShadowRoots(body);
2558
+ } else {
2559
+ /* Exit directly if we have nothing to do */
2560
+ if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT &&
2561
+ // eslint-disable-next-line unicorn/prefer-includes
2562
+ dirty.indexOf('<') === -1) {
2563
+ return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? _createTrustedHTML(dirty) : dirty;
2564
+ }
2565
+ /* Initialize the document to work on */
2566
+ body = _initDocument(dirty);
2567
+ /* Check we have a DOM node from the data */
2568
+ if (!body) {
2569
+ return RETURN_DOM ? null : RETURN_TRUSTED_TYPE ? emptyHTML : '';
2570
+ }
2571
+ }
2572
+ /* Remove first element node (ours) if FORCE_BODY is set */
2573
+ if (body && FORCE_BODY) {
2574
+ _forceRemove(body.firstChild);
2575
+ }
2576
+ /* Get node iterator */
2577
+ const walkRoot = inPlace ? dirty : body;
2578
+ /* Now start iterating over the created document.
2579
+ The walk runs inside an exception barrier (campaign-3 F2): a re-entrant
2580
+ engine/custom-element mutation can detach a node mid-walk so
2581
+ `_forceRemove`'s parentless guard throws, aborting the loop. Without the
2582
+ barrier the caller's in-place tree would be left half-sanitized with the
2583
+ unvisited tail still armed. _createNodeIterator itself is inside the
2584
+ barrier too: constructing the iterator dereferences the root's document,
2585
+ and any failure there (e.g. an exotic/clobbered root) must still fail
2586
+ closed rather than skip the neutralize. On any throw we fail closed -
2587
+ strip the in-place root bare - then rethrow so the existing throw
2588
+ contract is preserved. (String/DOM-copy paths never return the partial
2589
+ body, so the propagating throw is already fail-closed there.) */
2590
+ try {
2591
+ const nodeIterator = _createNodeIterator(walkRoot);
2592
+ while (currentNode = nodeIterator.nextNode()) {
2593
+ /* Sanitize tags and elements */
2594
+ _sanitizeElements(currentNode, walkRoot);
2595
+ /* Check attributes next */
2596
+ _sanitizeAttributes(currentNode);
2597
+ /* Shadow DOM detected, sanitize it.
2598
+ Realm-safe check (GHSA-hpcv-96wg-7vj8): nodeType-based detection
2599
+ instead of instanceof, so foreign-realm <template>.content is
2600
+ walked correctly. */
2601
+ if (_isDocumentFragment(currentNode.content)) {
2602
+ _sanitizeShadowDOM2(currentNode.content);
2603
+ }
2604
+ }
2605
+ } catch (error) {
2606
+ if (inPlace) {
2607
+ _neutralizeRoot(dirty);
2608
+ /* Nodes _forceRemove'd earlier in the aborted walk are already
2609
+ detached from the root, so _neutralizeRoot's subtree pass does not
2610
+ reach them. Defuse them too, mirroring the success-path loop below. */
2611
+ arrayForEach(DOMPurify.removed, entry => {
2612
+ if (entry.element) {
2613
+ _neutralizeSubtree(entry.element);
2614
+ }
2615
+ });
2616
+ }
2617
+ throw error;
2618
+ }
2619
+ /* If we sanitized `dirty` in-place, return it. */
2620
+ if (inPlace) {
2621
+ /* Fail-closed completion of the audit-5 F1 fix: every node removed from
2622
+ the caller's live tree is detached but may still hold a queued
2623
+ resource-event handler that fires in page scope after we return. The
2624
+ move-hoist covers only disallowed-tag KEEP_CONTENT removals; strip the
2625
+ non-allow-listed attributes off every other removed subtree (clobber,
2626
+ mXSS, namespace, comments, KEEP_CONTENT:false, …) so those handlers are
2627
+ cancelled before any event can fire. Runs synchronously, pre-return. */
2628
+ arrayForEach(DOMPurify.removed, entry => {
2629
+ if (entry.element) {
2630
+ _neutralizeSubtree(entry.element);
2631
+ }
2632
+ });
2633
+ if (SAFE_FOR_TEMPLATES) {
2634
+ _scrubTemplateExpressions2(dirty);
2635
+ }
2636
+ return dirty;
2637
+ }
2638
+ /* Return sanitized string or DOM */
2639
+ if (RETURN_DOM) {
2640
+ if (SAFE_FOR_TEMPLATES) {
2641
+ _scrubTemplateExpressions2(body);
2642
+ }
2643
+ if (RETURN_DOM_FRAGMENT) {
2644
+ returnNode = createDocumentFragment.call(body.ownerDocument);
2645
+ while (body.firstChild) {
2646
+ // eslint-disable-next-line unicorn/prefer-dom-node-append
2647
+ returnNode.appendChild(body.firstChild);
2648
+ }
2649
+ } else {
2650
+ returnNode = body;
2651
+ }
2652
+ if (ALLOWED_ATTR.shadowroot || ALLOWED_ATTR.shadowrootmode) {
2653
+ /*
2654
+ AdoptNode() is not used because internal state is not reset
2655
+ (e.g. the past names map of a HTMLFormElement), this is safe
2656
+ in theory but we would rather not risk another attack vector.
2657
+ The state that is cloned by importNode() is explicitly defined
2658
+ by the specs.
2659
+ */
2660
+ returnNode = importNode.call(originalDocument, returnNode, true);
2661
+ }
2662
+ return returnNode;
2663
+ }
2664
+ let serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML;
2665
+ /* Serialize doctype if allowed */
2666
+ if (WHOLE_DOCUMENT && ALLOWED_TAGS['!doctype'] && body.ownerDocument && body.ownerDocument.doctype && body.ownerDocument.doctype.name && regExpTest(DOCTYPE_NAME, body.ownerDocument.doctype.name)) {
2667
+ serializedHTML = '<!DOCTYPE ' + body.ownerDocument.doctype.name + '>\n' + serializedHTML;
2668
+ }
2669
+ /* Sanitize final string template-safe */
2670
+ if (SAFE_FOR_TEMPLATES) {
2671
+ serializedHTML = _stripTemplateExpressions(serializedHTML);
2672
+ }
2673
+ return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? _createTrustedHTML(serializedHTML) : serializedHTML;
2674
+ };
2675
+ DOMPurify.setConfig = function () {
2676
+ let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
2677
+ _parseConfig(cfg);
2678
+ SET_CONFIG = true;
2679
+ SET_CONFIG_ALLOWED_TAGS = ALLOWED_TAGS;
2680
+ SET_CONFIG_ALLOWED_ATTR = ALLOWED_ATTR;
2681
+ };
2682
+ DOMPurify.clearConfig = function () {
2683
+ CONFIG = null;
2684
+ SET_CONFIG = false;
2685
+ SET_CONFIG_ALLOWED_TAGS = null;
2686
+ SET_CONFIG_ALLOWED_ATTR = null;
2687
+ // Drop any caller-supplied Trusted Types policy so it cannot poison later
2688
+ // `RETURN_TRUSTED_TYPE` output. The internal default policy (cached, and
2689
+ // never recreated — Trusted Types throws on duplicate names) is restored by
2690
+ // the next `_parseConfig`. See GHSA-vxr8-fq34-vvx9.
2691
+ trustedTypesPolicy = defaultTrustedTypesPolicy;
2692
+ emptyHTML = '';
2693
+ };
2694
+ DOMPurify.isValidAttribute = function (tag, attr, value) {
2695
+ /* Initialize shared config vars if necessary. */
2696
+ if (!CONFIG) {
2697
+ _parseConfig({});
2698
+ }
2699
+ const lcTag = transformCaseFunc(tag);
2700
+ const lcName = transformCaseFunc(attr);
2701
+ return _isValidAttribute(lcTag, lcName, value);
2702
+ };
2703
+ DOMPurify.addHook = function (entryPoint, hookFunction) {
2704
+ if (typeof hookFunction !== 'function') {
2705
+ return;
2706
+ }
2707
+ /* Reject unknown entry points. Without this, a non-hook key (e.g.
2708
+ * '__proto__') indexes off the prototype chain rather than a real
2709
+ * hook array, and arrayPush then writes to Object.prototype. Guard
2710
+ * with an own-property check against the known hook names. */
2711
+ if (!objectHasOwnProperty(hooks, entryPoint)) {
2712
+ return;
2713
+ }
2714
+ arrayPush(hooks[entryPoint], hookFunction);
2715
+ };
2716
+ DOMPurify.removeHook = function (entryPoint, hookFunction) {
2717
+ if (!objectHasOwnProperty(hooks, entryPoint)) {
2718
+ return undefined;
2719
+ }
2720
+ if (hookFunction !== undefined) {
2721
+ const index = arrayLastIndexOf(hooks[entryPoint], hookFunction);
2722
+ return index === -1 ? undefined : arraySplice(hooks[entryPoint], index, 1)[0];
2723
+ }
2724
+ return arrayPop(hooks[entryPoint]);
2725
+ };
2726
+ DOMPurify.removeHooks = function (entryPoint) {
2727
+ if (!objectHasOwnProperty(hooks, entryPoint)) {
2728
+ return;
2729
+ }
2730
+ hooks[entryPoint] = [];
2731
+ };
2732
+ DOMPurify.removeAllHooks = function () {
2733
+ hooks = _createHooksMap();
2734
+ };
2735
+ return DOMPurify;
2736
+ }
2737
+ var purify = createDOMPurify();
2738
+
2739
+
2740
+ //# sourceMappingURL=purify.es.mjs.map
2741
+
2742
+ ;// ../../../node_modules/@wix/wix-ui-icons-common/dist/esm/core/sanitize.js
2743
+
2744
+ const SVG_NAMESPACE = "http://www.w3.org/2000/svg";
2745
+ function sanitizeSvgContent(content) {
2746
+ if (typeof content !== "string" || !purify.isSupported) {
2747
+ return "";
2748
+ }
2749
+ return purify.sanitize(content, {
2750
+ USE_PROFILES: { svg: true, svgFilters: true },
2751
+ NAMESPACE: SVG_NAMESPACE
2752
+ });
2753
+ }
2754
+
2755
+
2756
+
2757
+ /***/ }
2758
+
2759
+ }]);
2760
+ //# sourceMappingURL=500.chunk.js.map