dompurify 3.4.2 → 3.4.3

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.
package/dist/purify.js CHANGED
@@ -1,1479 +1,1544 @@
1
- /*! @license DOMPurify 3.4.2 | (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.2/LICENSE */
1
+ /*! @license DOMPurify 3.4.3 | (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.3/LICENSE */
2
2
 
3
3
  (function (global, factory) {
4
- typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
5
- typeof define === 'function' && define.amd ? define(factory) :
6
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.DOMPurify = factory());
4
+ typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
5
+ typeof define === 'function' && define.amd ? define(factory) :
6
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.DOMPurify = factory());
7
7
  })(this, (function () { 'use strict';
8
8
 
9
- const {
10
- entries,
11
- setPrototypeOf,
12
- isFrozen,
13
- getPrototypeOf,
14
- getOwnPropertyDescriptor
15
- } = Object;
16
- let {
17
- freeze,
18
- seal,
19
- create
20
- } = Object; // eslint-disable-line import/no-mutable-exports
21
- let {
22
- apply,
23
- construct
24
- } = typeof Reflect !== 'undefined' && Reflect;
25
- if (!freeze) {
26
- freeze = function freeze(x) {
27
- return x;
28
- };
29
- }
30
- if (!seal) {
31
- seal = function seal(x) {
32
- return x;
33
- };
34
- }
35
- if (!apply) {
36
- apply = function apply(func, thisArg) {
37
- for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
38
- args[_key - 2] = arguments[_key];
9
+ function _arrayLikeToArray(r, a) {
10
+ (null == a || a > r.length) && (a = r.length);
11
+ for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
12
+ return n;
13
+ }
14
+ function _arrayWithHoles(r) {
15
+ if (Array.isArray(r)) return r;
16
+ }
17
+ function _iterableToArrayLimit(r, l) {
18
+ var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
19
+ if (null != t) {
20
+ var e,
21
+ n,
22
+ i,
23
+ u,
24
+ a = [],
25
+ f = true,
26
+ o = false;
27
+ try {
28
+ if (i = (t = t.call(r)).next, 0 === l) ; else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0);
29
+ } catch (r) {
30
+ o = true, n = r;
31
+ } finally {
32
+ try {
33
+ if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return;
34
+ } finally {
35
+ if (o) throw n;
39
36
  }
40
- return func.apply(thisArg, args);
41
- };
37
+ }
38
+ return a;
42
39
  }
43
- if (!construct) {
44
- construct = function construct(Func) {
45
- for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
46
- args[_key2 - 1] = arguments[_key2];
47
- }
48
- return new Func(...args);
49
- };
40
+ }
41
+ function _nonIterableRest() {
42
+ throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
43
+ }
44
+ function _slicedToArray(r, e) {
45
+ return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest();
46
+ }
47
+ function _unsupportedIterableToArray(r, a) {
48
+ if (r) {
49
+ if ("string" == typeof r) return _arrayLikeToArray(r, a);
50
+ var t = {}.toString.call(r).slice(8, -1);
51
+ return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;
50
52
  }
51
- const arrayForEach = unapply(Array.prototype.forEach);
52
- const arrayLastIndexOf = unapply(Array.prototype.lastIndexOf);
53
- const arrayPop = unapply(Array.prototype.pop);
54
- const arrayPush = unapply(Array.prototype.push);
55
- const arraySplice = unapply(Array.prototype.splice);
56
- const arrayIsArray = Array.isArray;
57
- const stringToLowerCase = unapply(String.prototype.toLowerCase);
58
- const stringToString = unapply(String.prototype.toString);
59
- const stringMatch = unapply(String.prototype.match);
60
- const stringReplace = unapply(String.prototype.replace);
61
- const stringIndexOf = unapply(String.prototype.indexOf);
62
- const stringTrim = unapply(String.prototype.trim);
63
- const numberToString = unapply(Number.prototype.toString);
64
- const booleanToString = unapply(Boolean.prototype.toString);
65
- const bigintToString = typeof BigInt === 'undefined' ? null : unapply(BigInt.prototype.toString);
66
- const symbolToString = typeof Symbol === 'undefined' ? null : unapply(Symbol.prototype.toString);
67
- const objectHasOwnProperty = unapply(Object.prototype.hasOwnProperty);
68
- const objectToString = unapply(Object.prototype.toString);
69
- const regExpTest = unapply(RegExp.prototype.test);
70
- const typeErrorCreate = unconstruct(TypeError);
71
- /**
72
- * Creates a new function that calls the given function with a specified thisArg and arguments.
73
- *
74
- * @param func - The function to be wrapped and called.
75
- * @returns A new function that calls the given function with a specified thisArg and arguments.
76
- */
77
- function unapply(func) {
78
- return function (thisArg) {
79
- if (thisArg instanceof RegExp) {
80
- thisArg.lastIndex = 0;
81
- }
82
- for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
83
- args[_key3 - 1] = arguments[_key3];
84
- }
85
- return apply(func, thisArg, args);
86
- };
53
+ }
54
+
55
+ const entries = Object.entries,
56
+ setPrototypeOf = Object.setPrototypeOf,
57
+ isFrozen = Object.isFrozen,
58
+ getPrototypeOf = Object.getPrototypeOf,
59
+ getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
60
+ let freeze = Object.freeze,
61
+ seal = Object.seal,
62
+ create = Object.create; // eslint-disable-line import/no-mutable-exports
63
+ let _ref = typeof Reflect !== 'undefined' && Reflect,
64
+ apply = _ref.apply,
65
+ construct = _ref.construct;
66
+ if (!freeze) {
67
+ freeze = function freeze(x) {
68
+ return x;
69
+ };
70
+ }
71
+ if (!seal) {
72
+ seal = function seal(x) {
73
+ return x;
74
+ };
75
+ }
76
+ if (!apply) {
77
+ apply = function apply(func, thisArg) {
78
+ for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
79
+ args[_key - 2] = arguments[_key];
80
+ }
81
+ return func.apply(thisArg, args);
82
+ };
83
+ }
84
+ if (!construct) {
85
+ construct = function construct(Func) {
86
+ for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
87
+ args[_key2 - 1] = arguments[_key2];
88
+ }
89
+ return new Func(...args);
90
+ };
91
+ }
92
+ const arrayForEach = unapply(Array.prototype.forEach);
93
+ const arrayLastIndexOf = unapply(Array.prototype.lastIndexOf);
94
+ const arrayPop = unapply(Array.prototype.pop);
95
+ const arrayPush = unapply(Array.prototype.push);
96
+ const arraySplice = unapply(Array.prototype.splice);
97
+ const arrayIsArray = Array.isArray;
98
+ const stringToLowerCase = unapply(String.prototype.toLowerCase);
99
+ const stringToString = unapply(String.prototype.toString);
100
+ const stringMatch = unapply(String.prototype.match);
101
+ const stringReplace = unapply(String.prototype.replace);
102
+ const stringIndexOf = unapply(String.prototype.indexOf);
103
+ const stringTrim = unapply(String.prototype.trim);
104
+ const numberToString = unapply(Number.prototype.toString);
105
+ const booleanToString = unapply(Boolean.prototype.toString);
106
+ const bigintToString = typeof BigInt === 'undefined' ? null : unapply(BigInt.prototype.toString);
107
+ const symbolToString = typeof Symbol === 'undefined' ? null : unapply(Symbol.prototype.toString);
108
+ const objectHasOwnProperty = unapply(Object.prototype.hasOwnProperty);
109
+ const objectToString = unapply(Object.prototype.toString);
110
+ const regExpTest = unapply(RegExp.prototype.test);
111
+ const typeErrorCreate = unconstruct(TypeError);
112
+ /**
113
+ * Creates a new function that calls the given function with a specified thisArg and arguments.
114
+ *
115
+ * @param func - The function to be wrapped and called.
116
+ * @returns A new function that calls the given function with a specified thisArg and arguments.
117
+ */
118
+ function unapply(func) {
119
+ return function (thisArg) {
120
+ if (thisArg instanceof RegExp) {
121
+ thisArg.lastIndex = 0;
122
+ }
123
+ for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
124
+ args[_key3 - 1] = arguments[_key3];
125
+ }
126
+ return apply(func, thisArg, args);
127
+ };
128
+ }
129
+ /**
130
+ * Creates a new function that constructs an instance of the given constructor function with the provided arguments.
131
+ *
132
+ * @param func - The constructor function to be wrapped and called.
133
+ * @returns A new function that constructs an instance of the given constructor function with the provided arguments.
134
+ */
135
+ function unconstruct(Func) {
136
+ return function () {
137
+ for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
138
+ args[_key4] = arguments[_key4];
139
+ }
140
+ return construct(Func, args);
141
+ };
142
+ }
143
+ /**
144
+ * Add properties to a lookup table
145
+ *
146
+ * @param set - The set to which elements will be added.
147
+ * @param array - The array containing elements to be added to the set.
148
+ * @param transformCaseFunc - An optional function to transform the case of each element before adding to the set.
149
+ * @returns The modified set with added elements.
150
+ */
151
+ function addToSet(set, array) {
152
+ let transformCaseFunc = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : stringToLowerCase;
153
+ if (setPrototypeOf) {
154
+ // Make 'in' and truthy checks like Boolean(set.constructor)
155
+ // independent of any properties defined on Object.prototype.
156
+ // Prevent prototype setters from intercepting set as a this value.
157
+ setPrototypeOf(set, null);
87
158
  }
88
- /**
89
- * Creates a new function that constructs an instance of the given constructor function with the provided arguments.
90
- *
91
- * @param func - The constructor function to be wrapped and called.
92
- * @returns A new function that constructs an instance of the given constructor function with the provided arguments.
93
- */
94
- function unconstruct(Func) {
95
- return function () {
96
- for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
97
- args[_key4] = arguments[_key4];
98
- }
99
- return construct(Func, args);
100
- };
159
+ if (!arrayIsArray(array)) {
160
+ return set;
101
161
  }
102
- /**
103
- * Add properties to a lookup table
104
- *
105
- * @param set - The set to which elements will be added.
106
- * @param array - The array containing elements to be added to the set.
107
- * @param transformCaseFunc - An optional function to transform the case of each element before adding to the set.
108
- * @returns The modified set with added elements.
109
- */
110
- function addToSet(set, array) {
111
- let transformCaseFunc = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : stringToLowerCase;
112
- if (setPrototypeOf) {
113
- // Make 'in' and truthy checks like Boolean(set.constructor)
114
- // independent of any properties defined on Object.prototype.
115
- // Prevent prototype setters from intercepting set as a this value.
116
- setPrototypeOf(set, null);
117
- }
118
- if (!arrayIsArray(array)) {
119
- return set;
120
- }
121
- let l = array.length;
122
- while (l--) {
123
- let element = array[l];
124
- if (typeof element === 'string') {
125
- const lcElement = transformCaseFunc(element);
126
- if (lcElement !== element) {
127
- // Config presets (e.g. tags.js, attrs.js) are immutable.
128
- if (!isFrozen(array)) {
129
- array[l] = lcElement;
130
- }
131
- element = lcElement;
162
+ let l = array.length;
163
+ while (l--) {
164
+ let element = array[l];
165
+ if (typeof element === 'string') {
166
+ const lcElement = transformCaseFunc(element);
167
+ if (lcElement !== element) {
168
+ // Config presets (e.g. tags.js, attrs.js) are immutable.
169
+ if (!isFrozen(array)) {
170
+ array[l] = lcElement;
132
171
  }
172
+ element = lcElement;
133
173
  }
134
- set[element] = true;
135
174
  }
136
- return set;
175
+ set[element] = true;
137
176
  }
138
- /**
139
- * Clean up an array to harden against CSPP
140
- *
141
- * @param array - The array to be cleaned.
142
- * @returns The cleaned version of the array
143
- */
144
- function cleanArray(array) {
145
- for (let index = 0; index < array.length; index++) {
146
- const isPropertyExist = objectHasOwnProperty(array, index);
147
- if (!isPropertyExist) {
148
- array[index] = null;
149
- }
177
+ return set;
178
+ }
179
+ /**
180
+ * Clean up an array to harden against CSPP
181
+ *
182
+ * @param array - The array to be cleaned.
183
+ * @returns The cleaned version of the array
184
+ */
185
+ function cleanArray(array) {
186
+ for (let index = 0; index < array.length; index++) {
187
+ const isPropertyExist = objectHasOwnProperty(array, index);
188
+ if (!isPropertyExist) {
189
+ array[index] = null;
150
190
  }
151
- return array;
152
191
  }
153
- /**
154
- * Shallow clone an object
155
- *
156
- * @param object - The object to be cloned.
157
- * @returns A new object that copies the original.
158
- */
159
- function clone(object) {
160
- const newObject = create(null);
161
- for (const [property, value] of entries(object)) {
162
- const isPropertyExist = objectHasOwnProperty(object, property);
163
- if (isPropertyExist) {
164
- if (arrayIsArray(value)) {
165
- newObject[property] = cleanArray(value);
166
- } else if (value && typeof value === 'object' && value.constructor === Object) {
167
- newObject[property] = clone(value);
168
- } else {
169
- newObject[property] = value;
170
- }
192
+ return array;
193
+ }
194
+ /**
195
+ * Shallow clone an object
196
+ *
197
+ * @param object - The object to be cloned.
198
+ * @returns A new object that copies the original.
199
+ */
200
+ function clone(object) {
201
+ const newObject = create(null);
202
+ for (const _ref2 of entries(object)) {
203
+ var _ref3 = _slicedToArray(_ref2, 2);
204
+ const property = _ref3[0];
205
+ const value = _ref3[1];
206
+ const isPropertyExist = objectHasOwnProperty(object, property);
207
+ if (isPropertyExist) {
208
+ if (arrayIsArray(value)) {
209
+ newObject[property] = cleanArray(value);
210
+ } else if (value && typeof value === 'object' && value.constructor === Object) {
211
+ newObject[property] = clone(value);
212
+ } else {
213
+ newObject[property] = value;
171
214
  }
172
215
  }
173
- return newObject;
174
216
  }
175
- /**
176
- * Convert non-node values into strings without depending on direct property access.
177
- *
178
- * @param value - The value to stringify.
179
- * @returns A string representation of the provided value.
180
- */
181
- function stringifyValue(value) {
182
- switch (typeof value) {
183
- case 'string':
184
- {
185
- return value;
186
- }
187
- case 'number':
188
- {
189
- return numberToString(value);
190
- }
191
- case 'boolean':
192
- {
193
- return booleanToString(value);
194
- }
195
- case 'bigint':
196
- {
197
- return bigintToString ? bigintToString(value) : '0';
198
- }
199
- case 'symbol':
200
- {
201
- return symbolToString ? symbolToString(value) : 'Symbol()';
202
- }
203
- case 'undefined':
204
- {
217
+ return newObject;
218
+ }
219
+ /**
220
+ * Convert non-node values into strings without depending on direct property access.
221
+ *
222
+ * @param value - The value to stringify.
223
+ * @returns A string representation of the provided value.
224
+ */
225
+ function stringifyValue(value) {
226
+ switch (typeof value) {
227
+ case 'string':
228
+ {
229
+ return value;
230
+ }
231
+ case 'number':
232
+ {
233
+ return numberToString(value);
234
+ }
235
+ case 'boolean':
236
+ {
237
+ return booleanToString(value);
238
+ }
239
+ case 'bigint':
240
+ {
241
+ return bigintToString ? bigintToString(value) : '0';
242
+ }
243
+ case 'symbol':
244
+ {
245
+ return symbolToString ? symbolToString(value) : 'Symbol()';
246
+ }
247
+ case 'undefined':
248
+ {
249
+ return objectToString(value);
250
+ }
251
+ case 'function':
252
+ case 'object':
253
+ {
254
+ if (value === null) {
205
255
  return objectToString(value);
206
256
  }
207
- case 'function':
208
- case 'object':
209
- {
210
- if (value === null) {
211
- return objectToString(value);
212
- }
213
- const valueAsRecord = value;
214
- const valueToString = lookupGetter(valueAsRecord, 'toString');
215
- if (typeof valueToString === 'function') {
216
- const stringified = valueToString(valueAsRecord);
217
- return typeof stringified === 'string' ? stringified : objectToString(stringified);
218
- }
219
- return objectToString(value);
220
- }
221
- default:
222
- {
223
- return objectToString(value);
257
+ const valueAsRecord = value;
258
+ const valueToString = lookupGetter(valueAsRecord, 'toString');
259
+ if (typeof valueToString === 'function') {
260
+ const stringified = valueToString(valueAsRecord);
261
+ return typeof stringified === 'string' ? stringified : objectToString(stringified);
224
262
  }
225
- }
263
+ return objectToString(value);
264
+ }
265
+ default:
266
+ {
267
+ return objectToString(value);
268
+ }
226
269
  }
227
- /**
228
- * This method automatically checks if the prop is function or getter and behaves accordingly.
229
- *
230
- * @param object - The object to look up the getter function in its prototype chain.
231
- * @param prop - The property name for which to find the getter function.
232
- * @returns The getter function found in the prototype chain or a fallback function.
233
- */
234
- function lookupGetter(object, prop) {
235
- while (object !== null) {
236
- const desc = getOwnPropertyDescriptor(object, prop);
237
- if (desc) {
238
- if (desc.get) {
239
- return unapply(desc.get);
240
- }
241
- if (typeof desc.value === 'function') {
242
- return unapply(desc.value);
243
- }
270
+ }
271
+ /**
272
+ * This method automatically checks if the prop is function or getter and behaves accordingly.
273
+ *
274
+ * @param object - The object to look up the getter function in its prototype chain.
275
+ * @param prop - The property name for which to find the getter function.
276
+ * @returns The getter function found in the prototype chain or a fallback function.
277
+ */
278
+ function lookupGetter(object, prop) {
279
+ while (object !== null) {
280
+ const desc = getOwnPropertyDescriptor(object, prop);
281
+ if (desc) {
282
+ if (desc.get) {
283
+ return unapply(desc.get);
284
+ }
285
+ if (typeof desc.value === 'function') {
286
+ return unapply(desc.value);
244
287
  }
245
- object = getPrototypeOf(object);
246
- }
247
- function fallbackValue() {
248
- return null;
249
288
  }
250
- return fallbackValue;
289
+ object = getPrototypeOf(object);
251
290
  }
252
- function isRegex(value) {
253
- try {
254
- regExpTest(value, '');
255
- return true;
256
- } catch (_unused) {
257
- return false;
258
- }
291
+ function fallbackValue() {
292
+ return null;
259
293
  }
294
+ return fallbackValue;
295
+ }
296
+ function isRegex(value) {
297
+ try {
298
+ regExpTest(value, '');
299
+ return true;
300
+ } catch (_unused) {
301
+ return false;
302
+ }
303
+ }
260
304
 
261
- 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']);
262
- 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']);
263
- 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']);
264
- // List of SVG elements that are disallowed by default.
265
- // We still need to know them so that we can do namespace
266
- // checks properly in case one wants to add them to
267
- // allow-list.
268
- 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']);
269
- 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']);
270
- // Similarly to SVG, we want to know all MathML elements,
271
- // even those that we disallow by default.
272
- const mathMlDisallowed = freeze(['maction', 'maligngroup', 'malignmark', 'mlongdiv', 'mscarries', 'mscarry', 'msgroup', 'mstack', 'msline', 'msrow', 'semantics', 'annotation', 'annotation-xml', 'mprescripts', 'none']);
273
- const text = freeze(['#text']);
274
-
275
- const html = freeze(['accept', 'action', 'align', 'alt', 'autocapitalize', 'autocomplete', 'autopictureinpicture', 'autoplay', 'background', 'bgcolor', 'border', 'capture', 'cellpadding', 'cellspacing', 'checked', 'cite', 'class', 'clear', 'color', 'cols', 'colspan', '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']);
276
- 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', 'dur', 'edgemode', 'elevation', 'end', 'exponent', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'filterunits', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'fx', 'fy', 'g1', 'g2', 'glyph-name', 'glyphref', 'gradientunits', 'gradienttransform', 'height', 'href', 'id', 'image-rendering', 'in', 'in2', 'intercept', 'k', 'k1', 'k2', 'k3', 'k4', 'kerning', 'keypoints', 'keysplines', 'keytimes', 'lang', 'lengthadjust', 'letter-spacing', 'kernelmatrix', 'kernelunitlength', 'lighting-color', 'local', 'marker-end', 'marker-mid', 'marker-start', 'markerheight', 'markerunits', 'markerwidth', 'maskcontentunits', 'maskunits', 'max', 'mask', 'mask-type', 'media', 'method', 'mode', 'min', 'name', 'numoctaves', 'offset', 'operator', 'opacity', 'order', 'orient', 'orientation', 'origin', 'overflow', 'paint-order', 'path', 'pathlength', 'patterncontentunits', 'patterntransform', 'patternunits', 'points', 'preservealpha', 'preserveaspectratio', 'primitiveunits', 'r', 'rx', 'ry', 'radius', 'refx', 'refy', 'repeatcount', 'repeatdur', 'restart', 'result', 'rotate', 'scale', 'seed', 'shape-rendering', 'slope', 'specularconstant', 'specularexponent', 'spreadmethod', 'startoffset', 'stddeviation', 'stitchtiles', 'stop-color', 'stop-opacity', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke', 'stroke-width', 'style', 'surfacescale', 'systemlanguage', 'tabindex', 'tablevalues', 'targetx', 'targety', 'transform', 'transform-origin', 'text-anchor', 'text-decoration', 'text-rendering', 'textlength', 'type', 'u1', 'u2', 'unicode', 'values', 'viewbox', 'visibility', 'version', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'width', 'word-spacing', 'wrap', 'writing-mode', 'xchannelselector', 'ychannelselector', 'x', 'x1', 'x2', 'xmlns', 'y', 'y1', 'y2', 'z', 'zoomandpan']);
277
- 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']);
278
- const xml = freeze(['xlink:href', 'xml:id', 'xlink:title', 'xml:space', 'xmlns:xlink']);
305
+ const html$1 = freeze(['a', 'abbr', 'acronym', 'address', 'area', 'article', 'aside', 'audio', 'b', 'bdi', 'bdo', 'big', 'blink', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'center', 'cite', 'code', 'col', 'colgroup', 'content', 'data', 'datalist', 'dd', 'decorator', 'del', 'details', 'dfn', 'dialog', 'dir', 'div', 'dl', 'dt', 'element', 'em', 'fieldset', 'figcaption', 'figure', 'font', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'img', 'input', 'ins', 'kbd', 'label', 'legend', 'li', 'main', 'map', 'mark', 'marquee', 'menu', 'menuitem', 'meter', 'nav', 'nobr', 'ol', 'optgroup', 'option', 'output', 'p', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'search', 'section', 'select', 'shadow', 'slot', 'small', 'source', 'spacer', 'span', 'strike', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'time', 'tr', 'track', 'tt', 'u', 'ul', 'var', 'video', 'wbr']);
306
+ const svg$1 = freeze(['svg', 'a', 'altglyph', 'altglyphdef', 'altglyphitem', 'animatecolor', 'animatemotion', 'animatetransform', 'circle', 'clippath', 'defs', 'desc', 'ellipse', 'enterkeyhint', 'exportparts', 'filter', 'font', 'g', 'glyph', 'glyphref', 'hkern', 'image', 'inputmode', 'line', 'lineargradient', 'marker', 'mask', 'metadata', 'mpath', 'part', 'path', 'pattern', 'polygon', 'polyline', 'radialgradient', 'rect', 'stop', 'style', 'switch', 'symbol', 'text', 'textpath', 'title', 'tref', 'tspan', 'view', 'vkern']);
307
+ const svgFilters = freeze(['feBlend', 'feColorMatrix', 'feComponentTransfer', 'feComposite', 'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap', 'feDistantLight', 'feDropShadow', 'feFlood', 'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR', 'feGaussianBlur', 'feImage', 'feMerge', 'feMergeNode', 'feMorphology', 'feOffset', 'fePointLight', 'feSpecularLighting', 'feSpotLight', 'feTile', 'feTurbulence']);
308
+ // List of SVG elements that are disallowed by default.
309
+ // We still need to know them so that we can do namespace
310
+ // checks properly in case one wants to add them to
311
+ // allow-list.
312
+ const svgDisallowed = freeze(['animate', 'color-profile', 'cursor', 'discard', 'font-face', 'font-face-format', 'font-face-name', 'font-face-src', 'font-face-uri', 'foreignobject', 'hatch', 'hatchpath', 'mesh', 'meshgradient', 'meshpatch', 'meshrow', 'missing-glyph', 'script', 'set', 'solidcolor', 'unknown', 'use']);
313
+ const mathMl$1 = freeze(['math', 'menclose', 'merror', 'mfenced', 'mfrac', 'mglyph', 'mi', 'mlabeledtr', 'mmultiscripts', 'mn', 'mo', 'mover', 'mpadded', 'mphantom', 'mroot', 'mrow', 'ms', 'mspace', 'msqrt', 'mstyle', 'msub', 'msup', 'msubsup', 'mtable', 'mtd', 'mtext', 'mtr', 'munder', 'munderover', 'mprescripts']);
314
+ // Similarly to SVG, we want to know all MathML elements,
315
+ // even those that we disallow by default.
316
+ const mathMlDisallowed = freeze(['maction', 'maligngroup', 'malignmark', 'mlongdiv', 'mscarries', 'mscarry', 'msgroup', 'mstack', 'msline', 'msrow', 'semantics', 'annotation', 'annotation-xml', 'mprescripts', 'none']);
317
+ const text = freeze(['#text']);
279
318
 
280
- // eslint-disable-next-line unicorn/better-regex
281
- const MUSTACHE_EXPR = seal(/\{\{[\w\W]*|[\w\W]*\}\}/gm); // Specify template detection regex for SAFE_FOR_TEMPLATES mode
282
- const ERB_EXPR = seal(/<%[\w\W]*|[\w\W]*%>/gm);
283
- const TMPLIT_EXPR = seal(/\$\{[\w\W]*/gm); // eslint-disable-line unicorn/better-regex
284
- const DATA_ATTR = seal(/^data-[\-\w.\u00B7-\uFFFF]+$/); // eslint-disable-line no-useless-escape
285
- const ARIA_ATTR = seal(/^aria-[\-\w]+$/); // eslint-disable-line no-useless-escape
286
- 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
287
- );
288
- const IS_SCRIPT_OR_DATA = seal(/^(?:\w+script|data):/i);
289
- const ATTR_WHITESPACE = seal(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g // eslint-disable-line no-control-regex
290
- );
291
- const DOCTYPE_NAME = seal(/^html$/i);
292
- const CUSTOM_ELEMENT = seal(/^[a-z][.\w]*(-[.\w]+)+$/i);
319
+ const html = freeze(['accept', 'action', 'align', 'alt', 'autocapitalize', 'autocomplete', 'autopictureinpicture', 'autoplay', 'background', 'bgcolor', 'border', 'capture', 'cellpadding', 'cellspacing', 'checked', 'cite', 'class', 'clear', 'color', 'cols', 'colspan', 'controls', 'controlslist', 'coords', 'crossorigin', 'datetime', 'decoding', 'default', 'dir', 'disabled', 'disablepictureinpicture', 'disableremoteplayback', 'download', 'draggable', 'enctype', 'enterkeyhint', 'exportparts', 'face', 'for', 'headers', 'height', 'hidden', 'high', 'href', 'hreflang', 'id', 'inert', 'inputmode', 'integrity', 'ismap', 'kind', 'label', 'lang', 'list', 'loading', 'loop', 'low', 'max', 'maxlength', 'media', 'method', 'min', 'minlength', 'multiple', 'muted', 'name', 'nonce', 'noshade', 'novalidate', 'nowrap', 'open', 'optimum', 'part', 'pattern', 'placeholder', 'playsinline', 'popover', 'popovertarget', 'popovertargetaction', 'poster', 'preload', 'pubdate', 'radiogroup', 'readonly', 'rel', 'required', 'rev', 'reversed', 'role', 'rows', 'rowspan', 'spellcheck', 'scope', 'selected', 'shape', 'size', 'sizes', 'slot', 'span', 'srclang', 'start', 'src', 'srcset', 'step', 'style', 'summary', 'tabindex', 'title', 'translate', 'type', 'usemap', 'valign', 'value', 'width', 'wrap', 'xmlns']);
320
+ const svg = freeze(['accent-height', 'accumulate', 'additive', 'alignment-baseline', 'amplitude', 'ascent', 'attributename', 'attributetype', 'azimuth', 'basefrequency', 'baseline-shift', 'begin', 'bias', 'by', 'class', 'clip', 'clippathunits', 'clip-path', 'clip-rule', 'color', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'cx', 'cy', 'd', 'dx', 'dy', 'diffuseconstant', 'direction', 'display', 'divisor', 'dur', 'edgemode', 'elevation', 'end', 'exponent', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'filterunits', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'fx', 'fy', 'g1', 'g2', 'glyph-name', 'glyphref', 'gradientunits', 'gradienttransform', 'height', 'href', 'id', 'image-rendering', 'in', 'in2', 'intercept', 'k', 'k1', 'k2', 'k3', 'k4', 'kerning', 'keypoints', 'keysplines', 'keytimes', 'lang', 'lengthadjust', 'letter-spacing', 'kernelmatrix', 'kernelunitlength', 'lighting-color', 'local', 'marker-end', 'marker-mid', 'marker-start', 'markerheight', 'markerunits', 'markerwidth', 'maskcontentunits', 'maskunits', 'max', 'mask', 'mask-type', 'media', 'method', 'mode', 'min', 'name', 'numoctaves', 'offset', 'operator', 'opacity', 'order', 'orient', 'orientation', 'origin', 'overflow', 'paint-order', 'path', 'pathlength', 'patterncontentunits', 'patterntransform', 'patternunits', 'points', 'preservealpha', 'preserveaspectratio', 'primitiveunits', 'r', 'rx', 'ry', 'radius', 'refx', 'refy', 'repeatcount', 'repeatdur', 'restart', 'result', 'rotate', 'scale', 'seed', 'shape-rendering', 'slope', 'specularconstant', 'specularexponent', 'spreadmethod', 'startoffset', 'stddeviation', 'stitchtiles', 'stop-color', 'stop-opacity', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke', 'stroke-width', 'style', 'surfacescale', 'systemlanguage', 'tabindex', 'tablevalues', 'targetx', 'targety', 'transform', 'transform-origin', 'text-anchor', 'text-decoration', 'text-rendering', 'textlength', 'type', 'u1', 'u2', 'unicode', 'values', 'viewbox', 'visibility', 'version', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'width', 'word-spacing', 'wrap', 'writing-mode', 'xchannelselector', 'ychannelselector', 'x', 'x1', 'x2', 'xmlns', 'y', 'y1', 'y2', 'z', 'zoomandpan']);
321
+ const mathMl = freeze(['accent', 'accentunder', 'align', 'bevelled', 'close', 'columnalign', 'columnlines', 'columnspacing', 'columnspan', 'denomalign', 'depth', 'dir', 'display', 'displaystyle', 'encoding', 'fence', 'frame', 'height', 'href', 'id', 'largeop', 'length', 'linethickness', 'lquote', 'lspace', 'mathbackground', 'mathcolor', 'mathsize', 'mathvariant', 'maxsize', 'minsize', 'movablelimits', 'notation', 'numalign', 'open', 'rowalign', 'rowlines', 'rowspacing', 'rowspan', 'rspace', 'rquote', 'scriptlevel', 'scriptminsize', 'scriptsizemultiplier', 'selection', 'separator', 'separators', 'stretchy', 'subscriptshift', 'supscriptshift', 'symmetric', 'voffset', 'width', 'xmlns']);
322
+ const xml = freeze(['xlink:href', 'xml:id', 'xlink:title', 'xml:space', 'xmlns:xlink']);
293
323
 
294
- var EXPRESSIONS = /*#__PURE__*/Object.freeze({
295
- __proto__: null,
296
- ARIA_ATTR: ARIA_ATTR,
297
- ATTR_WHITESPACE: ATTR_WHITESPACE,
298
- CUSTOM_ELEMENT: CUSTOM_ELEMENT,
299
- DATA_ATTR: DATA_ATTR,
300
- DOCTYPE_NAME: DOCTYPE_NAME,
301
- ERB_EXPR: ERB_EXPR,
302
- IS_ALLOWED_URI: IS_ALLOWED_URI,
303
- IS_SCRIPT_OR_DATA: IS_SCRIPT_OR_DATA,
304
- MUSTACHE_EXPR: MUSTACHE_EXPR,
305
- TMPLIT_EXPR: TMPLIT_EXPR
306
- });
324
+ const MUSTACHE_EXPR = seal(/{{[\w\W]*|^[\w\W]*}}/g);
325
+ const ERB_EXPR = seal(/<%[\w\W]*|^[\w\W]*%>/g);
326
+ const TMPLIT_EXPR = seal(/\${[\w\W]*/g);
327
+ const DATA_ATTR = seal(/^data-[\-\w.\u00B7-\uFFFF]+$/); // eslint-disable-line no-useless-escape
328
+ const ARIA_ATTR = seal(/^aria-[\-\w]+$/); // eslint-disable-line no-useless-escape
329
+ 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
330
+ );
331
+ const IS_SCRIPT_OR_DATA = seal(/^(?:\w+script|data):/i);
332
+ const ATTR_WHITESPACE = seal(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g // eslint-disable-line no-control-regex
333
+ );
334
+ const DOCTYPE_NAME = seal(/^html$/i);
335
+ const CUSTOM_ELEMENT = seal(/^[a-z][.\w]*(-[.\w]+)+$/i);
307
336
 
308
- /* eslint-disable @typescript-eslint/indent */
309
- // https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType
310
- const NODE_TYPE = {
311
- element: 1,
312
- text: 3,
313
- // Deprecated
314
- progressingInstruction: 7,
315
- comment: 8,
316
- document: 9};
317
- const getGlobal = function getGlobal() {
318
- return typeof window === 'undefined' ? null : window;
337
+ /* eslint-disable @typescript-eslint/indent */
338
+ // https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType
339
+ const NODE_TYPE = {
340
+ element: 1,
341
+ text: 3,
342
+ // Deprecated
343
+ progressingInstruction: 7,
344
+ comment: 8,
345
+ document: 9};
346
+ const getGlobal = function getGlobal() {
347
+ return typeof window === 'undefined' ? null : window;
348
+ };
349
+ /**
350
+ * Creates a no-op policy for internal use only.
351
+ * Don't export this function outside this module!
352
+ * @param trustedTypes The policy factory.
353
+ * @param purifyHostElement The Script element used to load DOMPurify (to determine policy name suffix).
354
+ * @return The policy created (or null, if Trusted Types
355
+ * are not supported or creating the policy failed).
356
+ */
357
+ const _createTrustedTypesPolicy = function _createTrustedTypesPolicy(trustedTypes, purifyHostElement) {
358
+ if (typeof trustedTypes !== 'object' || typeof trustedTypes.createPolicy !== 'function') {
359
+ return null;
360
+ }
361
+ // Allow the callers to control the unique policy name
362
+ // by adding a data-tt-policy-suffix to the script element with the DOMPurify.
363
+ // Policy creation with duplicate names throws in Trusted Types.
364
+ let suffix = null;
365
+ const ATTR_NAME = 'data-tt-policy-suffix';
366
+ if (purifyHostElement && purifyHostElement.hasAttribute(ATTR_NAME)) {
367
+ suffix = purifyHostElement.getAttribute(ATTR_NAME);
368
+ }
369
+ const policyName = 'dompurify' + (suffix ? '#' + suffix : '');
370
+ try {
371
+ return trustedTypes.createPolicy(policyName, {
372
+ createHTML(html) {
373
+ return html;
374
+ },
375
+ createScriptURL(scriptUrl) {
376
+ return scriptUrl;
377
+ }
378
+ });
379
+ } catch (_) {
380
+ // Policy creation failed (most likely another DOMPurify script has
381
+ // already run). Skip creating the policy, as this will only cause errors
382
+ // if TT are enforced.
383
+ console.warn('TrustedTypes policy ' + policyName + ' could not be created.');
384
+ return null;
385
+ }
386
+ };
387
+ const _createHooksMap = function _createHooksMap() {
388
+ return {
389
+ afterSanitizeAttributes: [],
390
+ afterSanitizeElements: [],
391
+ afterSanitizeShadowDOM: [],
392
+ beforeSanitizeAttributes: [],
393
+ beforeSanitizeElements: [],
394
+ beforeSanitizeShadowDOM: [],
395
+ uponSanitizeAttribute: [],
396
+ uponSanitizeElement: [],
397
+ uponSanitizeShadowNode: []
319
398
  };
399
+ };
400
+ function createDOMPurify() {
401
+ let window = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getGlobal();
402
+ const DOMPurify = root => createDOMPurify(root);
403
+ DOMPurify.version = '3.4.3';
404
+ DOMPurify.removed = [];
405
+ if (!window || !window.document || window.document.nodeType !== NODE_TYPE.document || !window.Element) {
406
+ // Not running in a browser, provide a factory function
407
+ // so that you can pass your own Window
408
+ DOMPurify.isSupported = false;
409
+ return DOMPurify;
410
+ }
411
+ let document = window.document;
412
+ const originalDocument = document;
413
+ const currentScript = originalDocument.currentScript;
414
+ const DocumentFragment = window.DocumentFragment,
415
+ HTMLTemplateElement = window.HTMLTemplateElement,
416
+ Node = window.Node,
417
+ Element = window.Element,
418
+ NodeFilter = window.NodeFilter,
419
+ _window$NamedNodeMap = window.NamedNodeMap,
420
+ NamedNodeMap = _window$NamedNodeMap === void 0 ? window.NamedNodeMap || window.MozNamedAttrMap : _window$NamedNodeMap,
421
+ HTMLFormElement = window.HTMLFormElement,
422
+ DOMParser = window.DOMParser,
423
+ trustedTypes = window.trustedTypes;
424
+ const ElementPrototype = Element.prototype;
425
+ const cloneNode = lookupGetter(ElementPrototype, 'cloneNode');
426
+ const remove = lookupGetter(ElementPrototype, 'remove');
427
+ const getNextSibling = lookupGetter(ElementPrototype, 'nextSibling');
428
+ const getChildNodes = lookupGetter(ElementPrototype, 'childNodes');
429
+ const getParentNode = lookupGetter(ElementPrototype, 'parentNode');
430
+ // As per issue #47, the web-components registry is inherited by a
431
+ // new document created via createHTMLDocument. As per the spec
432
+ // (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-registries)
433
+ // a new empty registry is used when creating a template contents owner
434
+ // document, so we use that as our parent document to ensure nothing
435
+ // is inherited.
436
+ if (typeof HTMLTemplateElement === 'function') {
437
+ const template = document.createElement('template');
438
+ if (template.content && template.content.ownerDocument) {
439
+ document = template.content.ownerDocument;
440
+ }
441
+ }
442
+ let trustedTypesPolicy;
443
+ let emptyHTML = '';
444
+ const _document = document,
445
+ implementation = _document.implementation,
446
+ createNodeIterator = _document.createNodeIterator,
447
+ createDocumentFragment = _document.createDocumentFragment,
448
+ getElementsByTagName = _document.getElementsByTagName;
449
+ const importNode = originalDocument.importNode;
450
+ let hooks = _createHooksMap();
320
451
  /**
321
- * Creates a no-op policy for internal use only.
322
- * Don't export this function outside this module!
323
- * @param trustedTypes The policy factory.
324
- * @param purifyHostElement The Script element used to load DOMPurify (to determine policy name suffix).
325
- * @return The policy created (or null, if Trusted Types
326
- * are not supported or creating the policy failed).
452
+ * Expose whether this browser supports running the full DOMPurify.
327
453
  */
328
- const _createTrustedTypesPolicy = function _createTrustedTypesPolicy(trustedTypes, purifyHostElement) {
329
- if (typeof trustedTypes !== 'object' || typeof trustedTypes.createPolicy !== 'function') {
330
- return null;
331
- }
332
- // Allow the callers to control the unique policy name
333
- // by adding a data-tt-policy-suffix to the script element with the DOMPurify.
334
- // Policy creation with duplicate names throws in Trusted Types.
335
- let suffix = null;
336
- const ATTR_NAME = 'data-tt-policy-suffix';
337
- if (purifyHostElement && purifyHostElement.hasAttribute(ATTR_NAME)) {
338
- suffix = purifyHostElement.getAttribute(ATTR_NAME);
339
- }
340
- const policyName = 'dompurify' + (suffix ? '#' + suffix : '');
341
- try {
342
- return trustedTypes.createPolicy(policyName, {
343
- createHTML(html) {
344
- return html;
345
- },
346
- createScriptURL(scriptUrl) {
347
- return scriptUrl;
348
- }
349
- });
350
- } catch (_) {
351
- // Policy creation failed (most likely another DOMPurify script has
352
- // already run). Skip creating the policy, as this will only cause errors
353
- // if TT are enforced.
354
- console.warn('TrustedTypes policy ' + policyName + ' could not be created.');
355
- return null;
454
+ DOMPurify.isSupported = typeof entries === 'function' && typeof getParentNode === 'function' && implementation && implementation.createHTMLDocument !== undefined;
455
+ const MUSTACHE_EXPR$1 = MUSTACHE_EXPR,
456
+ ERB_EXPR$1 = ERB_EXPR,
457
+ TMPLIT_EXPR$1 = TMPLIT_EXPR,
458
+ DATA_ATTR$1 = DATA_ATTR,
459
+ ARIA_ATTR$1 = ARIA_ATTR,
460
+ IS_SCRIPT_OR_DATA$1 = IS_SCRIPT_OR_DATA,
461
+ ATTR_WHITESPACE$1 = ATTR_WHITESPACE,
462
+ CUSTOM_ELEMENT$1 = CUSTOM_ELEMENT;
463
+ let IS_ALLOWED_URI$1 = IS_ALLOWED_URI;
464
+ /**
465
+ * We consider the elements and attributes below to be safe. Ideally
466
+ * don't add any new ones but feel free to remove unwanted ones.
467
+ */
468
+ /* allowed element names */
469
+ let ALLOWED_TAGS = null;
470
+ const DEFAULT_ALLOWED_TAGS = addToSet({}, [...html$1, ...svg$1, ...svgFilters, ...mathMl$1, ...text]);
471
+ /* Allowed attribute names */
472
+ let ALLOWED_ATTR = null;
473
+ const DEFAULT_ALLOWED_ATTR = addToSet({}, [...html, ...svg, ...mathMl, ...xml]);
474
+ /*
475
+ * Configure how DOMPurify should handle custom elements and their attributes as well as customized built-in elements.
476
+ * @property {RegExp|Function|null} tagNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any custom elements)
477
+ * @property {RegExp|Function|null} attributeNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any attributes not on the allow list)
478
+ * @property {boolean} allowCustomizedBuiltInElements allow custom elements derived from built-ins if they pass CUSTOM_ELEMENT_HANDLING.tagNameCheck. Default: `false`.
479
+ */
480
+ let CUSTOM_ELEMENT_HANDLING = Object.seal(create(null, {
481
+ tagNameCheck: {
482
+ writable: true,
483
+ configurable: false,
484
+ enumerable: true,
485
+ value: null
486
+ },
487
+ attributeNameCheck: {
488
+ writable: true,
489
+ configurable: false,
490
+ enumerable: true,
491
+ value: null
492
+ },
493
+ allowCustomizedBuiltInElements: {
494
+ writable: true,
495
+ configurable: false,
496
+ enumerable: true,
497
+ value: false
356
498
  }
499
+ }));
500
+ /* Explicitly forbidden tags (overrides ALLOWED_TAGS/ADD_TAGS) */
501
+ let FORBID_TAGS = null;
502
+ /* Explicitly forbidden attributes (overrides ALLOWED_ATTR/ADD_ATTR) */
503
+ let FORBID_ATTR = null;
504
+ /* Config object to store ADD_TAGS/ADD_ATTR functions (when used as functions) */
505
+ const EXTRA_ELEMENT_HANDLING = Object.seal(create(null, {
506
+ tagCheck: {
507
+ writable: true,
508
+ configurable: false,
509
+ enumerable: true,
510
+ value: null
511
+ },
512
+ attributeCheck: {
513
+ writable: true,
514
+ configurable: false,
515
+ enumerable: true,
516
+ value: null
517
+ }
518
+ }));
519
+ /* Decide if ARIA attributes are okay */
520
+ let ALLOW_ARIA_ATTR = true;
521
+ /* Decide if custom data attributes are okay */
522
+ let ALLOW_DATA_ATTR = true;
523
+ /* Decide if unknown protocols are okay */
524
+ let ALLOW_UNKNOWN_PROTOCOLS = false;
525
+ /* Decide if self-closing tags in attributes are allowed.
526
+ * Usually removed due to a mXSS issue in jQuery 3.0 */
527
+ let ALLOW_SELF_CLOSE_IN_ATTR = true;
528
+ /* Output should be safe for common template engines.
529
+ * This means, DOMPurify removes data attributes, mustaches and ERB
530
+ */
531
+ let SAFE_FOR_TEMPLATES = false;
532
+ /* Output should be safe even for XML used within HTML and alike.
533
+ * This means, DOMPurify removes comments when containing risky content.
534
+ */
535
+ let SAFE_FOR_XML = true;
536
+ /* Decide if document with <html>... should be returned */
537
+ let WHOLE_DOCUMENT = false;
538
+ /* Track whether config is already set on this instance of DOMPurify. */
539
+ let SET_CONFIG = false;
540
+ /* Decide if all elements (e.g. style, script) must be children of
541
+ * document.body. By default, browsers might move them to document.head */
542
+ let FORCE_BODY = false;
543
+ /* Decide if a DOM `HTMLBodyElement` should be returned, instead of a html
544
+ * string (or a TrustedHTML object if Trusted Types are supported).
545
+ * If `WHOLE_DOCUMENT` is enabled a `HTMLHtmlElement` will be returned instead
546
+ */
547
+ let RETURN_DOM = false;
548
+ /* Decide if a DOM `DocumentFragment` should be returned, instead of a html
549
+ * string (or a TrustedHTML object if Trusted Types are supported) */
550
+ let RETURN_DOM_FRAGMENT = false;
551
+ /* Try to return a Trusted Type object instead of a string, return a string in
552
+ * case Trusted Types are not supported */
553
+ let RETURN_TRUSTED_TYPE = false;
554
+ /* Output should be free from DOM clobbering attacks?
555
+ * This sanitizes markups named with colliding, clobberable built-in DOM APIs.
556
+ */
557
+ let SANITIZE_DOM = true;
558
+ /* Achieve full DOM Clobbering protection by isolating the namespace of named
559
+ * properties and JS variables, mitigating attacks that abuse the HTML/DOM spec rules.
560
+ *
561
+ * HTML/DOM spec rules that enable DOM Clobbering:
562
+ * - Named Access on Window (§7.3.3)
563
+ * - DOM Tree Accessors (§3.1.5)
564
+ * - Form Element Parent-Child Relations (§4.10.3)
565
+ * - Iframe srcdoc / Nested WindowProxies (§4.8.5)
566
+ * - HTMLCollection (§4.2.10.2)
567
+ *
568
+ * Namespace isolation is implemented by prefixing `id` and `name` attributes
569
+ * with a constant string, i.e., `user-content-`
570
+ */
571
+ let SANITIZE_NAMED_PROPS = false;
572
+ const SANITIZE_NAMED_PROPS_PREFIX = 'user-content-';
573
+ /* Keep element content when removing element? */
574
+ let KEEP_CONTENT = true;
575
+ /* If a `Node` is passed to sanitize(), then performs sanitization in-place instead
576
+ * of importing it into a new Document and returning a sanitized copy */
577
+ let IN_PLACE = false;
578
+ /* Allow usage of profiles like html, svg and mathMl */
579
+ let USE_PROFILES = {};
580
+ /* Tags to ignore content of when KEEP_CONTENT is true */
581
+ let FORBID_CONTENTS = null;
582
+ const DEFAULT_FORBID_CONTENTS = addToSet({}, ['annotation-xml', 'audio', 'colgroup', 'desc', 'foreignobject', 'head', 'iframe', 'math', 'mi', 'mn', 'mo', 'ms', 'mtext', 'noembed', 'noframes', 'noscript', 'plaintext', 'script', 'style', 'svg', 'template', 'thead', 'title', 'video', 'xmp']);
583
+ /* Tags that are safe for data: URIs */
584
+ let DATA_URI_TAGS = null;
585
+ const DEFAULT_DATA_URI_TAGS = addToSet({}, ['audio', 'video', 'img', 'source', 'image', 'track']);
586
+ /* Attributes safe for values like "javascript:" */
587
+ let URI_SAFE_ATTRIBUTES = null;
588
+ const DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, ['alt', 'class', 'for', 'id', 'label', 'name', 'pattern', 'placeholder', 'role', 'summary', 'title', 'value', 'style', 'xmlns']);
589
+ const MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';
590
+ const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';
591
+ const HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';
592
+ /* Document namespace */
593
+ let NAMESPACE = HTML_NAMESPACE;
594
+ let IS_EMPTY_INPUT = false;
595
+ /* Allowed XHTML+XML namespaces */
596
+ let ALLOWED_NAMESPACES = null;
597
+ const DEFAULT_ALLOWED_NAMESPACES = addToSet({}, [MATHML_NAMESPACE, SVG_NAMESPACE, HTML_NAMESPACE], stringToString);
598
+ let MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, ['mi', 'mo', 'mn', 'ms', 'mtext']);
599
+ let HTML_INTEGRATION_POINTS = addToSet({}, ['annotation-xml']);
600
+ // Certain elements are allowed in both SVG and HTML
601
+ // namespace. We need to specify them explicitly
602
+ // so that they don't get erroneously deleted from
603
+ // HTML namespace.
604
+ const COMMON_SVG_AND_HTML_ELEMENTS = addToSet({}, ['title', 'style', 'font', 'a', 'script']);
605
+ /* Parsing of strict XHTML documents */
606
+ let PARSER_MEDIA_TYPE = null;
607
+ const SUPPORTED_PARSER_MEDIA_TYPES = ['application/xhtml+xml', 'text/html'];
608
+ const DEFAULT_PARSER_MEDIA_TYPE = 'text/html';
609
+ let transformCaseFunc = null;
610
+ /* Keep a reference to config to pass to hooks */
611
+ let CONFIG = null;
612
+ /* Ideally, do not touch anything below this line */
613
+ /* ______________________________________________ */
614
+ const formElement = document.createElement('form');
615
+ const isRegexOrFunction = function isRegexOrFunction(testValue) {
616
+ return testValue instanceof RegExp || testValue instanceof Function;
357
617
  };
358
- const _createHooksMap = function _createHooksMap() {
359
- return {
360
- afterSanitizeAttributes: [],
361
- afterSanitizeElements: [],
362
- afterSanitizeShadowDOM: [],
363
- beforeSanitizeAttributes: [],
364
- beforeSanitizeElements: [],
365
- beforeSanitizeShadowDOM: [],
366
- uponSanitizeAttribute: [],
367
- uponSanitizeElement: [],
368
- uponSanitizeShadowNode: []
369
- };
370
- };
371
- function createDOMPurify() {
372
- let window = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getGlobal();
373
- const DOMPurify = root => createDOMPurify(root);
374
- DOMPurify.version = '3.4.2';
375
- DOMPurify.removed = [];
376
- if (!window || !window.document || window.document.nodeType !== NODE_TYPE.document || !window.Element) {
377
- // Not running in a browser, provide a factory function
378
- // so that you can pass your own Window
379
- DOMPurify.isSupported = false;
380
- return DOMPurify;
381
- }
382
- let {
383
- document
384
- } = window;
385
- const originalDocument = document;
386
- const currentScript = originalDocument.currentScript;
387
- const {
388
- DocumentFragment,
389
- HTMLTemplateElement,
390
- Node,
391
- Element,
392
- NodeFilter,
393
- NamedNodeMap = window.NamedNodeMap || window.MozNamedAttrMap,
394
- HTMLFormElement,
395
- DOMParser,
396
- trustedTypes
397
- } = window;
398
- const ElementPrototype = Element.prototype;
399
- const cloneNode = lookupGetter(ElementPrototype, 'cloneNode');
400
- const remove = lookupGetter(ElementPrototype, 'remove');
401
- const getNextSibling = lookupGetter(ElementPrototype, 'nextSibling');
402
- const getChildNodes = lookupGetter(ElementPrototype, 'childNodes');
403
- const getParentNode = lookupGetter(ElementPrototype, 'parentNode');
404
- // As per issue #47, the web-components registry is inherited by a
405
- // new document created via createHTMLDocument. As per the spec
406
- // (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-registries)
407
- // a new empty registry is used when creating a template contents owner
408
- // document, so we use that as our parent document to ensure nothing
409
- // is inherited.
410
- if (typeof HTMLTemplateElement === 'function') {
411
- const template = document.createElement('template');
412
- if (template.content && template.content.ownerDocument) {
413
- document = template.content.ownerDocument;
414
- }
618
+ /**
619
+ * _parseConfig
620
+ *
621
+ * @param cfg optional config literal
622
+ */
623
+ // eslint-disable-next-line complexity
624
+ const _parseConfig = function _parseConfig() {
625
+ let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
626
+ if (CONFIG && CONFIG === cfg) {
627
+ return;
415
628
  }
416
- let trustedTypesPolicy;
417
- let emptyHTML = '';
418
- const {
419
- implementation,
420
- createNodeIterator,
421
- createDocumentFragment,
422
- getElementsByTagName
423
- } = document;
424
- const {
425
- importNode
426
- } = originalDocument;
427
- let hooks = _createHooksMap();
428
- /**
429
- * Expose whether this browser supports running the full DOMPurify.
430
- */
431
- DOMPurify.isSupported = typeof entries === 'function' && typeof getParentNode === 'function' && implementation && implementation.createHTMLDocument !== undefined;
432
- const {
433
- MUSTACHE_EXPR,
434
- ERB_EXPR,
435
- TMPLIT_EXPR,
436
- DATA_ATTR,
437
- ARIA_ATTR,
438
- IS_SCRIPT_OR_DATA,
439
- ATTR_WHITESPACE,
440
- CUSTOM_ELEMENT
441
- } = EXPRESSIONS;
442
- let {
443
- IS_ALLOWED_URI: IS_ALLOWED_URI$1
444
- } = EXPRESSIONS;
445
- /**
446
- * We consider the elements and attributes below to be safe. Ideally
447
- * don't add any new ones but feel free to remove unwanted ones.
448
- */
449
- /* allowed element names */
450
- let ALLOWED_TAGS = null;
451
- const DEFAULT_ALLOWED_TAGS = addToSet({}, [...html$1, ...svg$1, ...svgFilters, ...mathMl$1, ...text]);
452
- /* Allowed attribute names */
453
- let ALLOWED_ATTR = null;
454
- const DEFAULT_ALLOWED_ATTR = addToSet({}, [...html, ...svg, ...mathMl, ...xml]);
455
- /*
456
- * Configure how DOMPurify should handle custom elements and their attributes as well as customized built-in elements.
457
- * @property {RegExp|Function|null} tagNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any custom elements)
458
- * @property {RegExp|Function|null} attributeNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any attributes not on the allow list)
459
- * @property {boolean} allowCustomizedBuiltInElements allow custom elements derived from built-ins if they pass CUSTOM_ELEMENT_HANDLING.tagNameCheck. Default: `false`.
460
- */
461
- let CUSTOM_ELEMENT_HANDLING = Object.seal(create(null, {
462
- tagNameCheck: {
463
- writable: true,
464
- configurable: false,
465
- enumerable: true,
466
- value: null
467
- },
468
- attributeNameCheck: {
469
- writable: true,
470
- configurable: false,
471
- enumerable: true,
472
- value: null
473
- },
474
- allowCustomizedBuiltInElements: {
475
- writable: true,
476
- configurable: false,
477
- enumerable: true,
478
- value: false
479
- }
480
- }));
481
- /* Explicitly forbidden tags (overrides ALLOWED_TAGS/ADD_TAGS) */
482
- let FORBID_TAGS = null;
483
- /* Explicitly forbidden attributes (overrides ALLOWED_ATTR/ADD_ATTR) */
484
- let FORBID_ATTR = null;
485
- /* Config object to store ADD_TAGS/ADD_ATTR functions (when used as functions) */
486
- const EXTRA_ELEMENT_HANDLING = Object.seal(create(null, {
487
- tagCheck: {
488
- writable: true,
489
- configurable: false,
490
- enumerable: true,
491
- value: null
492
- },
493
- attributeCheck: {
494
- writable: true,
495
- configurable: false,
496
- enumerable: true,
497
- value: null
498
- }
499
- }));
500
- /* Decide if ARIA attributes are okay */
501
- let ALLOW_ARIA_ATTR = true;
502
- /* Decide if custom data attributes are okay */
503
- let ALLOW_DATA_ATTR = true;
504
- /* Decide if unknown protocols are okay */
505
- let ALLOW_UNKNOWN_PROTOCOLS = false;
506
- /* Decide if self-closing tags in attributes are allowed.
507
- * Usually removed due to a mXSS issue in jQuery 3.0 */
508
- let ALLOW_SELF_CLOSE_IN_ATTR = true;
509
- /* Output should be safe for common template engines.
510
- * This means, DOMPurify removes data attributes, mustaches and ERB
511
- */
512
- let SAFE_FOR_TEMPLATES = false;
513
- /* Output should be safe even for XML used within HTML and alike.
514
- * This means, DOMPurify removes comments when containing risky content.
515
- */
516
- let SAFE_FOR_XML = true;
517
- /* Decide if document with <html>... should be returned */
518
- let WHOLE_DOCUMENT = false;
519
- /* Track whether config is already set on this instance of DOMPurify. */
520
- let SET_CONFIG = false;
521
- /* Decide if all elements (e.g. style, script) must be children of
522
- * document.body. By default, browsers might move them to document.head */
523
- let FORCE_BODY = false;
524
- /* Decide if a DOM `HTMLBodyElement` should be returned, instead of a html
525
- * string (or a TrustedHTML object if Trusted Types are supported).
526
- * If `WHOLE_DOCUMENT` is enabled a `HTMLHtmlElement` will be returned instead
527
- */
528
- let RETURN_DOM = false;
529
- /* Decide if a DOM `DocumentFragment` should be returned, instead of a html
530
- * string (or a TrustedHTML object if Trusted Types are supported) */
531
- let RETURN_DOM_FRAGMENT = false;
532
- /* Try to return a Trusted Type object instead of a string, return a string in
533
- * case Trusted Types are not supported */
534
- let RETURN_TRUSTED_TYPE = false;
535
- /* Output should be free from DOM clobbering attacks?
536
- * This sanitizes markups named with colliding, clobberable built-in DOM APIs.
537
- */
538
- let SANITIZE_DOM = true;
539
- /* Achieve full DOM Clobbering protection by isolating the namespace of named
540
- * properties and JS variables, mitigating attacks that abuse the HTML/DOM spec rules.
541
- *
542
- * HTML/DOM spec rules that enable DOM Clobbering:
543
- * - Named Access on Window (§7.3.3)
544
- * - DOM Tree Accessors (§3.1.5)
545
- * - Form Element Parent-Child Relations (§4.10.3)
546
- * - Iframe srcdoc / Nested WindowProxies (§4.8.5)
547
- * - HTMLCollection (§4.2.10.2)
548
- *
549
- * Namespace isolation is implemented by prefixing `id` and `name` attributes
550
- * with a constant string, i.e., `user-content-`
551
- */
552
- let SANITIZE_NAMED_PROPS = false;
553
- const SANITIZE_NAMED_PROPS_PREFIX = 'user-content-';
554
- /* Keep element content when removing element? */
555
- let KEEP_CONTENT = true;
556
- /* If a `Node` is passed to sanitize(), then performs sanitization in-place instead
557
- * of importing it into a new Document and returning a sanitized copy */
558
- let IN_PLACE = false;
559
- /* Allow usage of profiles like html, svg and mathMl */
560
- let USE_PROFILES = {};
561
- /* Tags to ignore content of when KEEP_CONTENT is true */
562
- let FORBID_CONTENTS = null;
563
- const DEFAULT_FORBID_CONTENTS = addToSet({}, ['annotation-xml', 'audio', 'colgroup', 'desc', 'foreignobject', 'head', 'iframe', 'math', 'mi', 'mn', 'mo', 'ms', 'mtext', 'noembed', 'noframes', 'noscript', 'plaintext', 'script', 'style', 'svg', 'template', 'thead', 'title', 'video', 'xmp']);
564
- /* Tags that are safe for data: URIs */
565
- let DATA_URI_TAGS = null;
566
- const DEFAULT_DATA_URI_TAGS = addToSet({}, ['audio', 'video', 'img', 'source', 'image', 'track']);
567
- /* Attributes safe for values like "javascript:" */
568
- let URI_SAFE_ATTRIBUTES = null;
569
- const DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, ['alt', 'class', 'for', 'id', 'label', 'name', 'pattern', 'placeholder', 'role', 'summary', 'title', 'value', 'style', 'xmlns']);
570
- const MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';
571
- const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';
572
- const HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';
573
- /* Document namespace */
574
- let NAMESPACE = HTML_NAMESPACE;
575
- let IS_EMPTY_INPUT = false;
576
- /* Allowed XHTML+XML namespaces */
577
- let ALLOWED_NAMESPACES = null;
578
- const DEFAULT_ALLOWED_NAMESPACES = addToSet({}, [MATHML_NAMESPACE, SVG_NAMESPACE, HTML_NAMESPACE], stringToString);
579
- let MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, ['mi', 'mo', 'mn', 'ms', 'mtext']);
580
- let HTML_INTEGRATION_POINTS = addToSet({}, ['annotation-xml']);
581
- // Certain elements are allowed in both SVG and HTML
582
- // namespace. We need to specify them explicitly
583
- // so that they don't get erroneously deleted from
584
- // HTML namespace.
585
- const COMMON_SVG_AND_HTML_ELEMENTS = addToSet({}, ['title', 'style', 'font', 'a', 'script']);
586
- /* Parsing of strict XHTML documents */
587
- let PARSER_MEDIA_TYPE = null;
588
- const SUPPORTED_PARSER_MEDIA_TYPES = ['application/xhtml+xml', 'text/html'];
589
- const DEFAULT_PARSER_MEDIA_TYPE = 'text/html';
590
- let transformCaseFunc = null;
591
- /* Keep a reference to config to pass to hooks */
592
- let CONFIG = null;
593
- /* Ideally, do not touch anything below this line */
594
- /* ______________________________________________ */
595
- const formElement = document.createElement('form');
596
- const isRegexOrFunction = function isRegexOrFunction(testValue) {
597
- return testValue instanceof RegExp || testValue instanceof Function;
598
- };
599
- /**
600
- * _parseConfig
601
- *
602
- * @param cfg optional config literal
603
- */
604
- // eslint-disable-next-line complexity
605
- const _parseConfig = function _parseConfig() {
606
- let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
607
- if (CONFIG && CONFIG === cfg) {
608
- return;
609
- }
610
- /* Shield configuration object from tampering */
611
- if (!cfg || typeof cfg !== 'object') {
612
- cfg = {};
613
- }
614
- /* Shield configuration object from prototype pollution */
615
- cfg = clone(cfg);
616
- PARSER_MEDIA_TYPE =
617
- // eslint-disable-next-line unicorn/prefer-includes
618
- SUPPORTED_PARSER_MEDIA_TYPES.indexOf(cfg.PARSER_MEDIA_TYPE) === -1 ? DEFAULT_PARSER_MEDIA_TYPE : cfg.PARSER_MEDIA_TYPE;
619
- // HTML tags and attributes are not case-sensitive, converting to lowercase. Keeping XHTML as is.
620
- transformCaseFunc = PARSER_MEDIA_TYPE === 'application/xhtml+xml' ? stringToString : stringToLowerCase;
621
- /* Set configuration parameters */
622
- ALLOWED_TAGS = objectHasOwnProperty(cfg, 'ALLOWED_TAGS') && arrayIsArray(cfg.ALLOWED_TAGS) ? addToSet({}, cfg.ALLOWED_TAGS, transformCaseFunc) : DEFAULT_ALLOWED_TAGS;
623
- ALLOWED_ATTR = objectHasOwnProperty(cfg, 'ALLOWED_ATTR') && arrayIsArray(cfg.ALLOWED_ATTR) ? addToSet({}, cfg.ALLOWED_ATTR, transformCaseFunc) : DEFAULT_ALLOWED_ATTR;
624
- ALLOWED_NAMESPACES = objectHasOwnProperty(cfg, 'ALLOWED_NAMESPACES') && arrayIsArray(cfg.ALLOWED_NAMESPACES) ? addToSet({}, cfg.ALLOWED_NAMESPACES, stringToString) : DEFAULT_ALLOWED_NAMESPACES;
625
- URI_SAFE_ATTRIBUTES = objectHasOwnProperty(cfg, 'ADD_URI_SAFE_ATTR') && arrayIsArray(cfg.ADD_URI_SAFE_ATTR) ? addToSet(clone(DEFAULT_URI_SAFE_ATTRIBUTES), cfg.ADD_URI_SAFE_ATTR, transformCaseFunc) : DEFAULT_URI_SAFE_ATTRIBUTES;
626
- DATA_URI_TAGS = objectHasOwnProperty(cfg, 'ADD_DATA_URI_TAGS') && arrayIsArray(cfg.ADD_DATA_URI_TAGS) ? addToSet(clone(DEFAULT_DATA_URI_TAGS), cfg.ADD_DATA_URI_TAGS, transformCaseFunc) : DEFAULT_DATA_URI_TAGS;
627
- FORBID_CONTENTS = objectHasOwnProperty(cfg, 'FORBID_CONTENTS') && arrayIsArray(cfg.FORBID_CONTENTS) ? addToSet({}, cfg.FORBID_CONTENTS, transformCaseFunc) : DEFAULT_FORBID_CONTENTS;
628
- FORBID_TAGS = objectHasOwnProperty(cfg, 'FORBID_TAGS') && arrayIsArray(cfg.FORBID_TAGS) ? addToSet({}, cfg.FORBID_TAGS, transformCaseFunc) : clone({});
629
- FORBID_ATTR = objectHasOwnProperty(cfg, 'FORBID_ATTR') && arrayIsArray(cfg.FORBID_ATTR) ? addToSet({}, cfg.FORBID_ATTR, transformCaseFunc) : clone({});
630
- USE_PROFILES = objectHasOwnProperty(cfg, 'USE_PROFILES') ? cfg.USE_PROFILES && typeof cfg.USE_PROFILES === 'object' ? clone(cfg.USE_PROFILES) : cfg.USE_PROFILES : false;
631
- ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true
632
- ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true
633
- ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; // Default false
634
- ALLOW_SELF_CLOSE_IN_ATTR = cfg.ALLOW_SELF_CLOSE_IN_ATTR !== false; // Default true
635
- SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false; // Default false
636
- SAFE_FOR_XML = cfg.SAFE_FOR_XML !== false; // Default true
637
- WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false; // Default false
638
- RETURN_DOM = cfg.RETURN_DOM || false; // Default false
639
- RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false; // Default false
640
- RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false; // Default false
641
- FORCE_BODY = cfg.FORCE_BODY || false; // Default false
642
- SANITIZE_DOM = cfg.SANITIZE_DOM !== false; // Default true
643
- SANITIZE_NAMED_PROPS = cfg.SANITIZE_NAMED_PROPS || false; // Default false
644
- KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true
645
- IN_PLACE = cfg.IN_PLACE || false; // Default false
646
- IS_ALLOWED_URI$1 = isRegex(cfg.ALLOWED_URI_REGEXP) ? cfg.ALLOWED_URI_REGEXP : IS_ALLOWED_URI; // Default regexp
647
- NAMESPACE = typeof cfg.NAMESPACE === 'string' ? cfg.NAMESPACE : HTML_NAMESPACE; // Default HTML namespace
648
- MATHML_TEXT_INTEGRATION_POINTS = objectHasOwnProperty(cfg, 'MATHML_TEXT_INTEGRATION_POINTS') && cfg.MATHML_TEXT_INTEGRATION_POINTS && typeof cfg.MATHML_TEXT_INTEGRATION_POINTS === 'object' ? clone(cfg.MATHML_TEXT_INTEGRATION_POINTS) : addToSet({}, ['mi', 'mo', 'mn', 'ms', 'mtext']); // Default built-in map
649
- HTML_INTEGRATION_POINTS = objectHasOwnProperty(cfg, 'HTML_INTEGRATION_POINTS') && cfg.HTML_INTEGRATION_POINTS && typeof cfg.HTML_INTEGRATION_POINTS === 'object' ? clone(cfg.HTML_INTEGRATION_POINTS) : addToSet({}, ['annotation-xml']); // Default built-in map
650
- const customElementHandling = objectHasOwnProperty(cfg, 'CUSTOM_ELEMENT_HANDLING') && cfg.CUSTOM_ELEMENT_HANDLING && typeof cfg.CUSTOM_ELEMENT_HANDLING === 'object' ? clone(cfg.CUSTOM_ELEMENT_HANDLING) : create(null);
651
- CUSTOM_ELEMENT_HANDLING = create(null);
652
- if (objectHasOwnProperty(customElementHandling, 'tagNameCheck') && isRegexOrFunction(customElementHandling.tagNameCheck)) {
653
- CUSTOM_ELEMENT_HANDLING.tagNameCheck = customElementHandling.tagNameCheck; // Default undefined
654
- }
655
- if (objectHasOwnProperty(customElementHandling, 'attributeNameCheck') && isRegexOrFunction(customElementHandling.attributeNameCheck)) {
656
- CUSTOM_ELEMENT_HANDLING.attributeNameCheck = customElementHandling.attributeNameCheck; // Default undefined
657
- }
658
- if (objectHasOwnProperty(customElementHandling, 'allowCustomizedBuiltInElements') && typeof customElementHandling.allowCustomizedBuiltInElements === 'boolean') {
659
- CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = customElementHandling.allowCustomizedBuiltInElements; // Default undefined
660
- }
661
- if (SAFE_FOR_TEMPLATES) {
662
- ALLOW_DATA_ATTR = false;
663
- }
664
- if (RETURN_DOM_FRAGMENT) {
665
- RETURN_DOM = true;
666
- }
667
- /* Parse profile info */
668
- if (USE_PROFILES) {
669
- ALLOWED_TAGS = addToSet({}, text);
670
- ALLOWED_ATTR = create(null);
671
- if (USE_PROFILES.html === true) {
672
- addToSet(ALLOWED_TAGS, html$1);
673
- addToSet(ALLOWED_ATTR, html);
674
- }
675
- if (USE_PROFILES.svg === true) {
676
- addToSet(ALLOWED_TAGS, svg$1);
677
- addToSet(ALLOWED_ATTR, svg);
678
- addToSet(ALLOWED_ATTR, xml);
679
- }
680
- if (USE_PROFILES.svgFilters === true) {
681
- addToSet(ALLOWED_TAGS, svgFilters);
682
- addToSet(ALLOWED_ATTR, svg);
683
- addToSet(ALLOWED_ATTR, xml);
684
- }
685
- if (USE_PROFILES.mathMl === true) {
686
- addToSet(ALLOWED_TAGS, mathMl$1);
687
- addToSet(ALLOWED_ATTR, mathMl);
688
- addToSet(ALLOWED_ATTR, xml);
689
- }
690
- }
691
- /* Always reset function-based ADD_TAGS / ADD_ATTR checks to prevent
692
- * leaking across calls when switching from function to array config */
693
- EXTRA_ELEMENT_HANDLING.tagCheck = null;
694
- EXTRA_ELEMENT_HANDLING.attributeCheck = null;
695
- /* Merge configuration parameters */
696
- if (objectHasOwnProperty(cfg, 'ADD_TAGS')) {
697
- if (typeof cfg.ADD_TAGS === 'function') {
698
- EXTRA_ELEMENT_HANDLING.tagCheck = cfg.ADD_TAGS;
699
- } else if (arrayIsArray(cfg.ADD_TAGS)) {
700
- if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) {
701
- ALLOWED_TAGS = clone(ALLOWED_TAGS);
702
- }
703
- addToSet(ALLOWED_TAGS, cfg.ADD_TAGS, transformCaseFunc);
704
- }
705
- }
706
- if (objectHasOwnProperty(cfg, 'ADD_ATTR')) {
707
- if (typeof cfg.ADD_ATTR === 'function') {
708
- EXTRA_ELEMENT_HANDLING.attributeCheck = cfg.ADD_ATTR;
709
- } else if (arrayIsArray(cfg.ADD_ATTR)) {
710
- if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) {
711
- ALLOWED_ATTR = clone(ALLOWED_ATTR);
712
- }
713
- addToSet(ALLOWED_ATTR, cfg.ADD_ATTR, transformCaseFunc);
714
- }
715
- }
716
- if (objectHasOwnProperty(cfg, 'ADD_URI_SAFE_ATTR') && arrayIsArray(cfg.ADD_URI_SAFE_ATTR)) {
717
- addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR, transformCaseFunc);
629
+ /* Shield configuration object from tampering */
630
+ if (!cfg || typeof cfg !== 'object') {
631
+ cfg = {};
632
+ }
633
+ /* Shield configuration object from prototype pollution */
634
+ cfg = clone(cfg);
635
+ PARSER_MEDIA_TYPE =
636
+ // eslint-disable-next-line unicorn/prefer-includes
637
+ SUPPORTED_PARSER_MEDIA_TYPES.indexOf(cfg.PARSER_MEDIA_TYPE) === -1 ? DEFAULT_PARSER_MEDIA_TYPE : cfg.PARSER_MEDIA_TYPE;
638
+ // HTML tags and attributes are not case-sensitive, converting to lowercase. Keeping XHTML as is.
639
+ transformCaseFunc = PARSER_MEDIA_TYPE === 'application/xhtml+xml' ? stringToString : stringToLowerCase;
640
+ /* Set configuration parameters */
641
+ ALLOWED_TAGS = objectHasOwnProperty(cfg, 'ALLOWED_TAGS') && arrayIsArray(cfg.ALLOWED_TAGS) ? addToSet({}, cfg.ALLOWED_TAGS, transformCaseFunc) : DEFAULT_ALLOWED_TAGS;
642
+ ALLOWED_ATTR = objectHasOwnProperty(cfg, 'ALLOWED_ATTR') && arrayIsArray(cfg.ALLOWED_ATTR) ? addToSet({}, cfg.ALLOWED_ATTR, transformCaseFunc) : DEFAULT_ALLOWED_ATTR;
643
+ ALLOWED_NAMESPACES = objectHasOwnProperty(cfg, 'ALLOWED_NAMESPACES') && arrayIsArray(cfg.ALLOWED_NAMESPACES) ? addToSet({}, cfg.ALLOWED_NAMESPACES, stringToString) : DEFAULT_ALLOWED_NAMESPACES;
644
+ URI_SAFE_ATTRIBUTES = objectHasOwnProperty(cfg, 'ADD_URI_SAFE_ATTR') && arrayIsArray(cfg.ADD_URI_SAFE_ATTR) ? addToSet(clone(DEFAULT_URI_SAFE_ATTRIBUTES), cfg.ADD_URI_SAFE_ATTR, transformCaseFunc) : DEFAULT_URI_SAFE_ATTRIBUTES;
645
+ DATA_URI_TAGS = objectHasOwnProperty(cfg, 'ADD_DATA_URI_TAGS') && arrayIsArray(cfg.ADD_DATA_URI_TAGS) ? addToSet(clone(DEFAULT_DATA_URI_TAGS), cfg.ADD_DATA_URI_TAGS, transformCaseFunc) : DEFAULT_DATA_URI_TAGS;
646
+ FORBID_CONTENTS = objectHasOwnProperty(cfg, 'FORBID_CONTENTS') && arrayIsArray(cfg.FORBID_CONTENTS) ? addToSet({}, cfg.FORBID_CONTENTS, transformCaseFunc) : DEFAULT_FORBID_CONTENTS;
647
+ FORBID_TAGS = objectHasOwnProperty(cfg, 'FORBID_TAGS') && arrayIsArray(cfg.FORBID_TAGS) ? addToSet({}, cfg.FORBID_TAGS, transformCaseFunc) : clone({});
648
+ FORBID_ATTR = objectHasOwnProperty(cfg, 'FORBID_ATTR') && arrayIsArray(cfg.FORBID_ATTR) ? addToSet({}, cfg.FORBID_ATTR, transformCaseFunc) : clone({});
649
+ USE_PROFILES = objectHasOwnProperty(cfg, 'USE_PROFILES') ? cfg.USE_PROFILES && typeof cfg.USE_PROFILES === 'object' ? clone(cfg.USE_PROFILES) : cfg.USE_PROFILES : false;
650
+ ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true
651
+ ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true
652
+ ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; // Default false
653
+ ALLOW_SELF_CLOSE_IN_ATTR = cfg.ALLOW_SELF_CLOSE_IN_ATTR !== false; // Default true
654
+ SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false; // Default false
655
+ SAFE_FOR_XML = cfg.SAFE_FOR_XML !== false; // Default true
656
+ WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false; // Default false
657
+ RETURN_DOM = cfg.RETURN_DOM || false; // Default false
658
+ RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false; // Default false
659
+ RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false; // Default false
660
+ FORCE_BODY = cfg.FORCE_BODY || false; // Default false
661
+ SANITIZE_DOM = cfg.SANITIZE_DOM !== false; // Default true
662
+ SANITIZE_NAMED_PROPS = cfg.SANITIZE_NAMED_PROPS || false; // Default false
663
+ KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true
664
+ IN_PLACE = cfg.IN_PLACE || false; // Default false
665
+ IS_ALLOWED_URI$1 = isRegex(cfg.ALLOWED_URI_REGEXP) ? cfg.ALLOWED_URI_REGEXP : IS_ALLOWED_URI; // Default regexp
666
+ NAMESPACE = typeof cfg.NAMESPACE === 'string' ? cfg.NAMESPACE : HTML_NAMESPACE; // Default HTML namespace
667
+ MATHML_TEXT_INTEGRATION_POINTS = objectHasOwnProperty(cfg, 'MATHML_TEXT_INTEGRATION_POINTS') && cfg.MATHML_TEXT_INTEGRATION_POINTS && typeof cfg.MATHML_TEXT_INTEGRATION_POINTS === 'object' ? clone(cfg.MATHML_TEXT_INTEGRATION_POINTS) : addToSet({}, ['mi', 'mo', 'mn', 'ms', 'mtext']); // Default built-in map
668
+ HTML_INTEGRATION_POINTS = objectHasOwnProperty(cfg, 'HTML_INTEGRATION_POINTS') && cfg.HTML_INTEGRATION_POINTS && typeof cfg.HTML_INTEGRATION_POINTS === 'object' ? clone(cfg.HTML_INTEGRATION_POINTS) : addToSet({}, ['annotation-xml']); // Default built-in map
669
+ const customElementHandling = objectHasOwnProperty(cfg, 'CUSTOM_ELEMENT_HANDLING') && cfg.CUSTOM_ELEMENT_HANDLING && typeof cfg.CUSTOM_ELEMENT_HANDLING === 'object' ? clone(cfg.CUSTOM_ELEMENT_HANDLING) : create(null);
670
+ CUSTOM_ELEMENT_HANDLING = create(null);
671
+ if (objectHasOwnProperty(customElementHandling, 'tagNameCheck') && isRegexOrFunction(customElementHandling.tagNameCheck)) {
672
+ CUSTOM_ELEMENT_HANDLING.tagNameCheck = customElementHandling.tagNameCheck; // Default undefined
673
+ }
674
+ if (objectHasOwnProperty(customElementHandling, 'attributeNameCheck') && isRegexOrFunction(customElementHandling.attributeNameCheck)) {
675
+ CUSTOM_ELEMENT_HANDLING.attributeNameCheck = customElementHandling.attributeNameCheck; // Default undefined
676
+ }
677
+ if (objectHasOwnProperty(customElementHandling, 'allowCustomizedBuiltInElements') && typeof customElementHandling.allowCustomizedBuiltInElements === 'boolean') {
678
+ CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = customElementHandling.allowCustomizedBuiltInElements; // Default undefined
679
+ }
680
+ if (SAFE_FOR_TEMPLATES) {
681
+ ALLOW_DATA_ATTR = false;
682
+ }
683
+ if (RETURN_DOM_FRAGMENT) {
684
+ RETURN_DOM = true;
685
+ }
686
+ /* Parse profile info */
687
+ if (USE_PROFILES) {
688
+ ALLOWED_TAGS = addToSet({}, text);
689
+ ALLOWED_ATTR = create(null);
690
+ if (USE_PROFILES.html === true) {
691
+ addToSet(ALLOWED_TAGS, html$1);
692
+ addToSet(ALLOWED_ATTR, html);
693
+ }
694
+ if (USE_PROFILES.svg === true) {
695
+ addToSet(ALLOWED_TAGS, svg$1);
696
+ addToSet(ALLOWED_ATTR, svg);
697
+ addToSet(ALLOWED_ATTR, xml);
698
+ }
699
+ if (USE_PROFILES.svgFilters === true) {
700
+ addToSet(ALLOWED_TAGS, svgFilters);
701
+ addToSet(ALLOWED_ATTR, svg);
702
+ addToSet(ALLOWED_ATTR, xml);
703
+ }
704
+ if (USE_PROFILES.mathMl === true) {
705
+ addToSet(ALLOWED_TAGS, mathMl$1);
706
+ addToSet(ALLOWED_ATTR, mathMl);
707
+ addToSet(ALLOWED_ATTR, xml);
718
708
  }
719
- if (objectHasOwnProperty(cfg, 'FORBID_CONTENTS') && arrayIsArray(cfg.FORBID_CONTENTS)) {
720
- if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {
721
- FORBID_CONTENTS = clone(FORBID_CONTENTS);
709
+ }
710
+ /* Always reset function-based ADD_TAGS / ADD_ATTR checks to prevent
711
+ * leaking across calls when switching from function to array config */
712
+ EXTRA_ELEMENT_HANDLING.tagCheck = null;
713
+ EXTRA_ELEMENT_HANDLING.attributeCheck = null;
714
+ /* Merge configuration parameters */
715
+ if (objectHasOwnProperty(cfg, 'ADD_TAGS')) {
716
+ if (typeof cfg.ADD_TAGS === 'function') {
717
+ EXTRA_ELEMENT_HANDLING.tagCheck = cfg.ADD_TAGS;
718
+ } else if (arrayIsArray(cfg.ADD_TAGS)) {
719
+ if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) {
720
+ ALLOWED_TAGS = clone(ALLOWED_TAGS);
722
721
  }
723
- addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS, transformCaseFunc);
722
+ addToSet(ALLOWED_TAGS, cfg.ADD_TAGS, transformCaseFunc);
724
723
  }
725
- if (objectHasOwnProperty(cfg, 'ADD_FORBID_CONTENTS') && arrayIsArray(cfg.ADD_FORBID_CONTENTS)) {
726
- if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {
727
- FORBID_CONTENTS = clone(FORBID_CONTENTS);
724
+ }
725
+ if (objectHasOwnProperty(cfg, 'ADD_ATTR')) {
726
+ if (typeof cfg.ADD_ATTR === 'function') {
727
+ EXTRA_ELEMENT_HANDLING.attributeCheck = cfg.ADD_ATTR;
728
+ } else if (arrayIsArray(cfg.ADD_ATTR)) {
729
+ if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) {
730
+ ALLOWED_ATTR = clone(ALLOWED_ATTR);
728
731
  }
729
- addToSet(FORBID_CONTENTS, cfg.ADD_FORBID_CONTENTS, transformCaseFunc);
732
+ addToSet(ALLOWED_ATTR, cfg.ADD_ATTR, transformCaseFunc);
730
733
  }
731
- /* Add #text in case KEEP_CONTENT is set to true */
732
- if (KEEP_CONTENT) {
733
- ALLOWED_TAGS['#text'] = true;
734
- }
735
- /* Add html, head and body to ALLOWED_TAGS in case WHOLE_DOCUMENT is true */
736
- if (WHOLE_DOCUMENT) {
737
- addToSet(ALLOWED_TAGS, ['html', 'head', 'body']);
734
+ }
735
+ if (objectHasOwnProperty(cfg, 'ADD_URI_SAFE_ATTR') && arrayIsArray(cfg.ADD_URI_SAFE_ATTR)) {
736
+ addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR, transformCaseFunc);
737
+ }
738
+ if (objectHasOwnProperty(cfg, 'FORBID_CONTENTS') && arrayIsArray(cfg.FORBID_CONTENTS)) {
739
+ if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {
740
+ FORBID_CONTENTS = clone(FORBID_CONTENTS);
738
741
  }
739
- /* Add tbody to ALLOWED_TAGS in case tables are permitted, see #286, #365 */
740
- if (ALLOWED_TAGS.table) {
741
- addToSet(ALLOWED_TAGS, ['tbody']);
742
- delete FORBID_TAGS.tbody;
742
+ addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS, transformCaseFunc);
743
+ }
744
+ if (objectHasOwnProperty(cfg, 'ADD_FORBID_CONTENTS') && arrayIsArray(cfg.ADD_FORBID_CONTENTS)) {
745
+ if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {
746
+ FORBID_CONTENTS = clone(FORBID_CONTENTS);
743
747
  }
744
- if (cfg.TRUSTED_TYPES_POLICY) {
745
- if (typeof cfg.TRUSTED_TYPES_POLICY.createHTML !== 'function') {
746
- throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');
747
- }
748
- if (typeof cfg.TRUSTED_TYPES_POLICY.createScriptURL !== 'function') {
749
- throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');
750
- }
751
- // Overwrite existing TrustedTypes policy.
752
- trustedTypesPolicy = cfg.TRUSTED_TYPES_POLICY;
753
- // Sign local variables required by `sanitize`.
748
+ addToSet(FORBID_CONTENTS, cfg.ADD_FORBID_CONTENTS, transformCaseFunc);
749
+ }
750
+ /* Add #text in case KEEP_CONTENT is set to true */
751
+ if (KEEP_CONTENT) {
752
+ ALLOWED_TAGS['#text'] = true;
753
+ }
754
+ /* Add html, head and body to ALLOWED_TAGS in case WHOLE_DOCUMENT is true */
755
+ if (WHOLE_DOCUMENT) {
756
+ addToSet(ALLOWED_TAGS, ['html', 'head', 'body']);
757
+ }
758
+ /* Add tbody to ALLOWED_TAGS in case tables are permitted, see #286, #365 */
759
+ if (ALLOWED_TAGS.table) {
760
+ addToSet(ALLOWED_TAGS, ['tbody']);
761
+ delete FORBID_TAGS.tbody;
762
+ }
763
+ if (cfg.TRUSTED_TYPES_POLICY) {
764
+ if (typeof cfg.TRUSTED_TYPES_POLICY.createHTML !== 'function') {
765
+ throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');
766
+ }
767
+ if (typeof cfg.TRUSTED_TYPES_POLICY.createScriptURL !== 'function') {
768
+ throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');
769
+ }
770
+ // Overwrite existing TrustedTypes policy.
771
+ trustedTypesPolicy = cfg.TRUSTED_TYPES_POLICY;
772
+ // Sign local variables required by `sanitize`.
773
+ emptyHTML = trustedTypesPolicy.createHTML('');
774
+ } else {
775
+ // Uninitialized policy, attempt to initialize the internal dompurify policy.
776
+ if (trustedTypesPolicy === undefined) {
777
+ trustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, currentScript);
778
+ }
779
+ // If creating the internal policy succeeded sign internal variables.
780
+ if (trustedTypesPolicy !== null && typeof emptyHTML === 'string') {
754
781
  emptyHTML = trustedTypesPolicy.createHTML('');
755
- } else {
756
- // Uninitialized policy, attempt to initialize the internal dompurify policy.
757
- if (trustedTypesPolicy === undefined) {
758
- trustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, currentScript);
759
- }
760
- // If creating the internal policy succeeded sign internal variables.
761
- if (trustedTypesPolicy !== null && typeof emptyHTML === 'string') {
762
- emptyHTML = trustedTypesPolicy.createHTML('');
763
- }
764
- }
765
- // Prevent further manipulation of configuration.
766
- // Not available in IE8, Safari 5, etc.
767
- if (freeze) {
768
- freeze(cfg);
769
782
  }
770
- CONFIG = cfg;
771
- };
772
- /* Keep track of all possible SVG and MathML tags
773
- * so that we can perform the namespace checks
774
- * correctly. */
775
- const ALL_SVG_TAGS = addToSet({}, [...svg$1, ...svgFilters, ...svgDisallowed]);
776
- const ALL_MATHML_TAGS = addToSet({}, [...mathMl$1, ...mathMlDisallowed]);
777
- /**
778
- * @param element a DOM element whose namespace is being checked
779
- * @returns Return false if the element has a
780
- * namespace that a spec-compliant parser would never
781
- * return. Return true otherwise.
782
- */
783
- const _checkValidNamespace = function _checkValidNamespace(element) {
784
- let parent = getParentNode(element);
785
- // In JSDOM, if we're inside shadow DOM, then parentNode
786
- // can be null. We just simulate parent in this case.
787
- if (!parent || !parent.tagName) {
788
- parent = {
789
- namespaceURI: NAMESPACE,
790
- tagName: 'template'
791
- };
792
- }
793
- const tagName = stringToLowerCase(element.tagName);
794
- const parentTagName = stringToLowerCase(parent.tagName);
795
- if (!ALLOWED_NAMESPACES[element.namespaceURI]) {
783
+ }
784
+ // Prevent further manipulation of configuration.
785
+ // Not available in IE8, Safari 5, etc.
786
+ if (freeze) {
787
+ freeze(cfg);
788
+ }
789
+ CONFIG = cfg;
790
+ };
791
+ /* Keep track of all possible SVG and MathML tags
792
+ * so that we can perform the namespace checks
793
+ * correctly. */
794
+ const ALL_SVG_TAGS = addToSet({}, [...svg$1, ...svgFilters, ...svgDisallowed]);
795
+ const ALL_MATHML_TAGS = addToSet({}, [...mathMl$1, ...mathMlDisallowed]);
796
+ /**
797
+ * @param element a DOM element whose namespace is being checked
798
+ * @returns Return false if the element has a
799
+ * namespace that a spec-compliant parser would never
800
+ * return. Return true otherwise.
801
+ */
802
+ const _checkValidNamespace = function _checkValidNamespace(element) {
803
+ let parent = getParentNode(element);
804
+ // In JSDOM, if we're inside shadow DOM, then parentNode
805
+ // can be null. We just simulate parent in this case.
806
+ if (!parent || !parent.tagName) {
807
+ parent = {
808
+ namespaceURI: NAMESPACE,
809
+ tagName: 'template'
810
+ };
811
+ }
812
+ const tagName = stringToLowerCase(element.tagName);
813
+ const parentTagName = stringToLowerCase(parent.tagName);
814
+ if (!ALLOWED_NAMESPACES[element.namespaceURI]) {
815
+ return false;
816
+ }
817
+ if (element.namespaceURI === SVG_NAMESPACE) {
818
+ // The only way to switch from HTML namespace to SVG
819
+ // is via <svg>. If it happens via any other tag, then
820
+ // it should be killed.
821
+ if (parent.namespaceURI === HTML_NAMESPACE) {
822
+ return tagName === 'svg';
823
+ }
824
+ // The only way to switch from MathML to SVG is via`
825
+ // svg if parent is either <annotation-xml> or MathML
826
+ // text integration points.
827
+ if (parent.namespaceURI === MATHML_NAMESPACE) {
828
+ return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);
829
+ }
830
+ // We only allow elements that are defined in SVG
831
+ // spec. All others are disallowed in SVG namespace.
832
+ return Boolean(ALL_SVG_TAGS[tagName]);
833
+ }
834
+ if (element.namespaceURI === MATHML_NAMESPACE) {
835
+ // The only way to switch from HTML namespace to MathML
836
+ // is via <math>. If it happens via any other tag, then
837
+ // it should be killed.
838
+ if (parent.namespaceURI === HTML_NAMESPACE) {
839
+ return tagName === 'math';
840
+ }
841
+ // The only way to switch from SVG to MathML is via
842
+ // <math> and HTML integration points
843
+ if (parent.namespaceURI === SVG_NAMESPACE) {
844
+ return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName];
845
+ }
846
+ // We only allow elements that are defined in MathML
847
+ // spec. All others are disallowed in MathML namespace.
848
+ return Boolean(ALL_MATHML_TAGS[tagName]);
849
+ }
850
+ if (element.namespaceURI === HTML_NAMESPACE) {
851
+ // The only way to switch from SVG to HTML is via
852
+ // HTML integration points, and from MathML to HTML
853
+ // is via MathML text integration points
854
+ if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) {
796
855
  return false;
797
856
  }
798
- if (element.namespaceURI === SVG_NAMESPACE) {
799
- // The only way to switch from HTML namespace to SVG
800
- // is via <svg>. If it happens via any other tag, then
801
- // it should be killed.
802
- if (parent.namespaceURI === HTML_NAMESPACE) {
803
- return tagName === 'svg';
804
- }
805
- // The only way to switch from MathML to SVG is via`
806
- // svg if parent is either <annotation-xml> or MathML
807
- // text integration points.
808
- if (parent.namespaceURI === MATHML_NAMESPACE) {
809
- return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);
810
- }
811
- // We only allow elements that are defined in SVG
812
- // spec. All others are disallowed in SVG namespace.
813
- return Boolean(ALL_SVG_TAGS[tagName]);
814
- }
815
- if (element.namespaceURI === MATHML_NAMESPACE) {
816
- // The only way to switch from HTML namespace to MathML
817
- // is via <math>. If it happens via any other tag, then
818
- // it should be killed.
819
- if (parent.namespaceURI === HTML_NAMESPACE) {
820
- return tagName === 'math';
821
- }
822
- // The only way to switch from SVG to MathML is via
823
- // <math> and HTML integration points
824
- if (parent.namespaceURI === SVG_NAMESPACE) {
825
- return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName];
826
- }
827
- // We only allow elements that are defined in MathML
828
- // spec. All others are disallowed in MathML namespace.
829
- return Boolean(ALL_MATHML_TAGS[tagName]);
830
- }
831
- if (element.namespaceURI === HTML_NAMESPACE) {
832
- // The only way to switch from SVG to HTML is via
833
- // HTML integration points, and from MathML to HTML
834
- // is via MathML text integration points
835
- if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) {
836
- return false;
837
- }
838
- if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {
839
- return false;
840
- }
841
- // We disallow tags that are specific for MathML
842
- // or SVG and should never appear in HTML namespace
843
- return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]);
844
- }
845
- // For XHTML and XML documents that support custom namespaces
846
- if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && ALLOWED_NAMESPACES[element.namespaceURI]) {
847
- return true;
857
+ if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {
858
+ return false;
848
859
  }
849
- // The code should never reach this place (this means
850
- // that the element somehow got namespace that is not
851
- // HTML, SVG, MathML or allowed via ALLOWED_NAMESPACES).
852
- // Return false just in case.
853
- return false;
854
- };
855
- /**
856
- * _forceRemove
857
- *
858
- * @param node a DOM node
859
- */
860
- const _forceRemove = function _forceRemove(node) {
860
+ // We disallow tags that are specific for MathML
861
+ // or SVG and should never appear in HTML namespace
862
+ return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]);
863
+ }
864
+ // For XHTML and XML documents that support custom namespaces
865
+ if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && ALLOWED_NAMESPACES[element.namespaceURI]) {
866
+ return true;
867
+ }
868
+ // The code should never reach this place (this means
869
+ // that the element somehow got namespace that is not
870
+ // HTML, SVG, MathML or allowed via ALLOWED_NAMESPACES).
871
+ // Return false just in case.
872
+ return false;
873
+ };
874
+ /**
875
+ * _forceRemove
876
+ *
877
+ * @param node a DOM node
878
+ */
879
+ const _forceRemove = function _forceRemove(node) {
880
+ arrayPush(DOMPurify.removed, {
881
+ element: node
882
+ });
883
+ try {
884
+ // eslint-disable-next-line unicorn/prefer-dom-node-remove
885
+ getParentNode(node).removeChild(node);
886
+ } catch (_) {
887
+ remove(node);
888
+ }
889
+ };
890
+ /**
891
+ * _removeAttribute
892
+ *
893
+ * @param name an Attribute name
894
+ * @param element a DOM node
895
+ */
896
+ const _removeAttribute = function _removeAttribute(name, element) {
897
+ try {
861
898
  arrayPush(DOMPurify.removed, {
862
- element: node
899
+ attribute: element.getAttributeNode(name),
900
+ from: element
863
901
  });
864
- try {
865
- // eslint-disable-next-line unicorn/prefer-dom-node-remove
866
- getParentNode(node).removeChild(node);
867
- } catch (_) {
868
- remove(node);
869
- }
870
- };
871
- /**
872
- * _removeAttribute
873
- *
874
- * @param name an Attribute name
875
- * @param element a DOM node
876
- */
877
- const _removeAttribute = function _removeAttribute(name, element) {
878
- try {
879
- arrayPush(DOMPurify.removed, {
880
- attribute: element.getAttributeNode(name),
881
- from: element
882
- });
883
- } catch (_) {
884
- arrayPush(DOMPurify.removed, {
885
- attribute: null,
886
- from: element
887
- });
888
- }
889
- element.removeAttribute(name);
890
- // We void attribute values for unremovable "is" attributes
891
- if (name === 'is') {
892
- if (RETURN_DOM || RETURN_DOM_FRAGMENT) {
893
- try {
894
- _forceRemove(element);
895
- } catch (_) {}
896
- } else {
897
- try {
898
- element.setAttribute(name, '');
899
- } catch (_) {}
900
- }
901
- }
902
- };
903
- /**
904
- * _initDocument
905
- *
906
- * @param dirty - a string of dirty markup
907
- * @return a DOM, filled with the dirty markup
908
- */
909
- const _initDocument = function _initDocument(dirty) {
910
- /* Create a HTML document */
911
- let doc = null;
912
- let leadingWhitespace = null;
913
- if (FORCE_BODY) {
914
- dirty = '<remove></remove>' + dirty;
915
- } else {
916
- /* If FORCE_BODY isn't used, leading whitespace needs to be preserved manually */
917
- const matches = stringMatch(dirty, /^[\r\n\t ]+/);
918
- leadingWhitespace = matches && matches[0];
919
- }
920
- if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && NAMESPACE === HTML_NAMESPACE) {
921
- // Root of XHTML doc must contain xmlns declaration (see https://www.w3.org/TR/xhtml1/normative.html#strict)
922
- dirty = '<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>' + dirty + '</body></html>';
923
- }
924
- const dirtyPayload = trustedTypesPolicy ? trustedTypesPolicy.createHTML(dirty) : dirty;
925
- /*
926
- * Use the DOMParser API by default, fallback later if needs be
927
- * DOMParser not work for svg when has multiple root element.
928
- */
929
- if (NAMESPACE === HTML_NAMESPACE) {
902
+ } catch (_) {
903
+ arrayPush(DOMPurify.removed, {
904
+ attribute: null,
905
+ from: element
906
+ });
907
+ }
908
+ element.removeAttribute(name);
909
+ // We void attribute values for unremovable "is" attributes
910
+ if (name === 'is') {
911
+ if (RETURN_DOM || RETURN_DOM_FRAGMENT) {
930
912
  try {
931
- doc = new DOMParser().parseFromString(dirtyPayload, PARSER_MEDIA_TYPE);
913
+ _forceRemove(element);
932
914
  } catch (_) {}
933
- }
934
- /* Use createHTMLDocument in case DOMParser is not available */
935
- if (!doc || !doc.documentElement) {
936
- doc = implementation.createDocument(NAMESPACE, 'template', null);
915
+ } else {
937
916
  try {
938
- doc.documentElement.innerHTML = IS_EMPTY_INPUT ? emptyHTML : dirtyPayload;
939
- } catch (_) {
940
- // Syntax error if dirtyPayload is invalid xml
941
- }
942
- }
943
- const body = doc.body || doc.documentElement;
944
- if (dirty && leadingWhitespace) {
945
- body.insertBefore(document.createTextNode(leadingWhitespace), body.childNodes[0] || null);
946
- }
947
- /* Work on whole document or just its body */
948
- if (NAMESPACE === HTML_NAMESPACE) {
949
- return getElementsByTagName.call(doc, WHOLE_DOCUMENT ? 'html' : 'body')[0];
917
+ element.setAttribute(name, '');
918
+ } catch (_) {}
950
919
  }
951
- return WHOLE_DOCUMENT ? doc.documentElement : body;
952
- };
953
- /**
954
- * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document.
955
- *
956
- * @param root The root element or node to start traversing on.
957
- * @return The created NodeIterator
958
- */
959
- const _createNodeIterator = function _createNodeIterator(root) {
960
- return createNodeIterator.call(root.ownerDocument || root, root,
961
- // eslint-disable-next-line no-bitwise
962
- NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT | NodeFilter.SHOW_PROCESSING_INSTRUCTION | NodeFilter.SHOW_CDATA_SECTION, null);
963
- };
964
- /**
965
- * _isClobbered
966
- *
967
- * @param element element to check for clobbering attacks
968
- * @return true if clobbered, false if safe
969
- */
970
- const _isClobbered = function _isClobbered(element) {
971
- return element instanceof HTMLFormElement && (typeof element.nodeName !== 'string' || typeof element.textContent !== 'string' || typeof element.removeChild !== 'function' || !(element.attributes instanceof NamedNodeMap) || typeof element.removeAttribute !== 'function' || typeof element.setAttribute !== 'function' || typeof element.namespaceURI !== 'string' || typeof element.insertBefore !== 'function' || typeof element.hasChildNodes !== 'function');
972
- };
973
- /**
974
- * Checks whether the given object is a DOM node.
975
- *
976
- * @param value object to check whether it's a DOM node
977
- * @return true is object is a DOM node
978
- */
979
- const _isNode = function _isNode(value) {
980
- return typeof Node === 'function' && value instanceof Node;
981
- };
982
- function _executeHooks(hooks, currentNode, data) {
983
- arrayForEach(hooks, hook => {
984
- hook.call(DOMPurify, currentNode, data, CONFIG);
985
- });
986
920
  }
987
- /**
988
- * _sanitizeElements
989
- *
990
- * @protect nodeName
991
- * @protect textContent
992
- * @protect removeChild
993
- * @param currentNode to check for permission to exist
994
- * @return true if node was killed, false if left alive
921
+ };
922
+ /**
923
+ * _initDocument
924
+ *
925
+ * @param dirty - a string of dirty markup
926
+ * @return a DOM, filled with the dirty markup
927
+ */
928
+ const _initDocument = function _initDocument(dirty) {
929
+ /* Create a HTML document */
930
+ let doc = null;
931
+ let leadingWhitespace = null;
932
+ if (FORCE_BODY) {
933
+ dirty = '<remove></remove>' + dirty;
934
+ } else {
935
+ /* If FORCE_BODY isn't used, leading whitespace needs to be preserved manually */
936
+ const matches = stringMatch(dirty, /^[\r\n\t ]+/);
937
+ leadingWhitespace = matches && matches[0];
938
+ }
939
+ if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && NAMESPACE === HTML_NAMESPACE) {
940
+ // Root of XHTML doc must contain xmlns declaration (see https://www.w3.org/TR/xhtml1/normative.html#strict)
941
+ dirty = '<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>' + dirty + '</body></html>';
942
+ }
943
+ const dirtyPayload = trustedTypesPolicy ? trustedTypesPolicy.createHTML(dirty) : dirty;
944
+ /*
945
+ * Use the DOMParser API by default, fallback later if needs be
946
+ * DOMParser not work for svg when has multiple root element.
995
947
  */
996
- const _sanitizeElements = function _sanitizeElements(currentNode) {
997
- let content = null;
998
- /* Execute a hook if present */
999
- _executeHooks(hooks.beforeSanitizeElements, currentNode, null);
1000
- /* Check if element is clobbered or can clobber */
1001
- if (_isClobbered(currentNode)) {
1002
- _forceRemove(currentNode);
1003
- return true;
1004
- }
1005
- /* Now let's check the element's type and name */
1006
- const tagName = transformCaseFunc(currentNode.nodeName);
1007
- /* Execute a hook if present */
1008
- _executeHooks(hooks.uponSanitizeElement, currentNode, {
1009
- tagName,
1010
- allowedTags: ALLOWED_TAGS
1011
- });
1012
- /* Detect mXSS attempts abusing namespace confusion */
1013
- if (SAFE_FOR_XML && currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && regExpTest(/<[/\w!]/g, currentNode.innerHTML) && regExpTest(/<[/\w!]/g, currentNode.textContent)) {
1014
- _forceRemove(currentNode);
1015
- return true;
1016
- }
1017
- /* Remove risky CSS construction leading to mXSS */
1018
- if (SAFE_FOR_XML && currentNode.namespaceURI === HTML_NAMESPACE && tagName === 'style' && _isNode(currentNode.firstElementChild)) {
1019
- _forceRemove(currentNode);
1020
- return true;
1021
- }
1022
- /* Remove any occurrence of processing instructions */
1023
- if (currentNode.nodeType === NODE_TYPE.progressingInstruction) {
1024
- _forceRemove(currentNode);
1025
- return true;
1026
- }
1027
- /* Remove any kind of possibly harmful comments */
1028
- if (SAFE_FOR_XML && currentNode.nodeType === NODE_TYPE.comment && regExpTest(/<[/\w]/g, currentNode.data)) {
1029
- _forceRemove(currentNode);
1030
- return true;
948
+ if (NAMESPACE === HTML_NAMESPACE) {
949
+ try {
950
+ doc = new DOMParser().parseFromString(dirtyPayload, PARSER_MEDIA_TYPE);
951
+ } catch (_) {}
952
+ }
953
+ /* Use createHTMLDocument in case DOMParser is not available */
954
+ if (!doc || !doc.documentElement) {
955
+ doc = implementation.createDocument(NAMESPACE, 'template', null);
956
+ try {
957
+ doc.documentElement.innerHTML = IS_EMPTY_INPUT ? emptyHTML : dirtyPayload;
958
+ } catch (_) {
959
+ // Syntax error if dirtyPayload is invalid xml
1031
960
  }
1032
- /* Remove element if anything forbids its presence */
1033
- if (FORBID_TAGS[tagName] || !(EXTRA_ELEMENT_HANDLING.tagCheck instanceof Function && EXTRA_ELEMENT_HANDLING.tagCheck(tagName)) && !ALLOWED_TAGS[tagName]) {
1034
- /* Check if we have a custom element to handle */
1035
- if (!FORBID_TAGS[tagName] && _isBasicCustomElement(tagName)) {
1036
- if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) {
1037
- return false;
1038
- }
1039
- if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)) {
1040
- return false;
1041
- }
961
+ }
962
+ const body = doc.body || doc.documentElement;
963
+ if (dirty && leadingWhitespace) {
964
+ body.insertBefore(document.createTextNode(leadingWhitespace), body.childNodes[0] || null);
965
+ }
966
+ /* Work on whole document or just its body */
967
+ if (NAMESPACE === HTML_NAMESPACE) {
968
+ return getElementsByTagName.call(doc, WHOLE_DOCUMENT ? 'html' : 'body')[0];
969
+ }
970
+ return WHOLE_DOCUMENT ? doc.documentElement : body;
971
+ };
972
+ /**
973
+ * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document.
974
+ *
975
+ * @param root The root element or node to start traversing on.
976
+ * @return The created NodeIterator
977
+ */
978
+ const _createNodeIterator = function _createNodeIterator(root) {
979
+ return createNodeIterator.call(root.ownerDocument || root, root,
980
+ // eslint-disable-next-line no-bitwise
981
+ NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT | NodeFilter.SHOW_PROCESSING_INSTRUCTION | NodeFilter.SHOW_CDATA_SECTION, null);
982
+ };
983
+ /**
984
+ * _isClobbered
985
+ *
986
+ * @param element element to check for clobbering attacks
987
+ * @return true if clobbered, false if safe
988
+ */
989
+ const _isClobbered = function _isClobbered(element) {
990
+ return element instanceof HTMLFormElement && (typeof element.nodeName !== 'string' || typeof element.textContent !== 'string' || typeof element.removeChild !== 'function' || !(element.attributes instanceof NamedNodeMap) || typeof element.removeAttribute !== 'function' || typeof element.setAttribute !== 'function' || typeof element.namespaceURI !== 'string' || typeof element.insertBefore !== 'function' || typeof element.hasChildNodes !== 'function');
991
+ };
992
+ /**
993
+ * Checks whether the given object is a DOM node.
994
+ *
995
+ * @param value object to check whether it's a DOM node
996
+ * @return true is object is a DOM node
997
+ */
998
+ const _isNode = function _isNode(value) {
999
+ return typeof Node === 'function' && value instanceof Node;
1000
+ };
1001
+ function _executeHooks(hooks, currentNode, data) {
1002
+ arrayForEach(hooks, hook => {
1003
+ hook.call(DOMPurify, currentNode, data, CONFIG);
1004
+ });
1005
+ }
1006
+ /**
1007
+ * _sanitizeElements
1008
+ *
1009
+ * @protect nodeName
1010
+ * @protect textContent
1011
+ * @protect removeChild
1012
+ * @param currentNode to check for permission to exist
1013
+ * @return true if node was killed, false if left alive
1014
+ */
1015
+ const _sanitizeElements = function _sanitizeElements(currentNode) {
1016
+ let content = null;
1017
+ /* Execute a hook if present */
1018
+ _executeHooks(hooks.beforeSanitizeElements, currentNode, null);
1019
+ /* Check if element is clobbered or can clobber */
1020
+ if (_isClobbered(currentNode)) {
1021
+ _forceRemove(currentNode);
1022
+ return true;
1023
+ }
1024
+ /* Now let's check the element's type and name */
1025
+ const tagName = transformCaseFunc(currentNode.nodeName);
1026
+ /* Execute a hook if present */
1027
+ _executeHooks(hooks.uponSanitizeElement, currentNode, {
1028
+ tagName,
1029
+ allowedTags: ALLOWED_TAGS
1030
+ });
1031
+ /* Detect mXSS attempts abusing namespace confusion */
1032
+ if (SAFE_FOR_XML && currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && regExpTest(/<[/\w!]/g, currentNode.innerHTML) && regExpTest(/<[/\w!]/g, currentNode.textContent)) {
1033
+ _forceRemove(currentNode);
1034
+ return true;
1035
+ }
1036
+ /* Remove risky CSS construction leading to mXSS */
1037
+ if (SAFE_FOR_XML && currentNode.namespaceURI === HTML_NAMESPACE && tagName === 'style' && _isNode(currentNode.firstElementChild)) {
1038
+ _forceRemove(currentNode);
1039
+ return true;
1040
+ }
1041
+ /* Remove any occurrence of processing instructions */
1042
+ if (currentNode.nodeType === NODE_TYPE.progressingInstruction) {
1043
+ _forceRemove(currentNode);
1044
+ return true;
1045
+ }
1046
+ /* Remove any kind of possibly harmful comments */
1047
+ if (SAFE_FOR_XML && currentNode.nodeType === NODE_TYPE.comment && regExpTest(/<[/\w]/g, currentNode.data)) {
1048
+ _forceRemove(currentNode);
1049
+ return true;
1050
+ }
1051
+ /* Remove element if anything forbids its presence */
1052
+ if (FORBID_TAGS[tagName] || !(EXTRA_ELEMENT_HANDLING.tagCheck instanceof Function && EXTRA_ELEMENT_HANDLING.tagCheck(tagName)) && !ALLOWED_TAGS[tagName]) {
1053
+ /* Check if we have a custom element to handle */
1054
+ if (!FORBID_TAGS[tagName] && _isBasicCustomElement(tagName)) {
1055
+ if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) {
1056
+ return false;
1042
1057
  }
1043
- /* Keep content except for bad-listed elements */
1044
- if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {
1045
- const parentNode = getParentNode(currentNode) || currentNode.parentNode;
1046
- const childNodes = getChildNodes(currentNode) || currentNode.childNodes;
1047
- if (childNodes && parentNode) {
1048
- const childCount = childNodes.length;
1049
- for (let i = childCount - 1; i >= 0; --i) {
1050
- const childClone = cloneNode(childNodes[i], true);
1051
- parentNode.insertBefore(childClone, getNextSibling(currentNode));
1052
- }
1053
- }
1058
+ if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)) {
1059
+ return false;
1054
1060
  }
1055
- _forceRemove(currentNode);
1056
- return true;
1057
- }
1058
- /* Check whether element has a valid namespace */
1059
- if (currentNode instanceof Element && !_checkValidNamespace(currentNode)) {
1060
- _forceRemove(currentNode);
1061
- return true;
1062
1061
  }
1063
- /* Make sure that older browsers don't get fallback-tag mXSS */
1064
- if ((tagName === 'noscript' || tagName === 'noembed' || tagName === 'noframes') && regExpTest(/<\/no(script|embed|frames)/i, currentNode.innerHTML)) {
1065
- _forceRemove(currentNode);
1066
- return true;
1062
+ /* Keep content except for bad-listed elements */
1063
+ if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {
1064
+ const parentNode = getParentNode(currentNode) || currentNode.parentNode;
1065
+ const childNodes = getChildNodes(currentNode) || currentNode.childNodes;
1066
+ if (childNodes && parentNode) {
1067
+ const childCount = childNodes.length;
1068
+ for (let i = childCount - 1; i >= 0; --i) {
1069
+ const childClone = cloneNode(childNodes[i], true);
1070
+ parentNode.insertBefore(childClone, getNextSibling(currentNode));
1071
+ }
1072
+ }
1067
1073
  }
1068
- /* Sanitize element content to be template-safe */
1069
- if (SAFE_FOR_TEMPLATES && currentNode.nodeType === NODE_TYPE.text) {
1070
- /* Get the element's text content */
1071
- content = currentNode.textContent;
1072
- arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {
1073
- content = stringReplace(content, expr, ' ');
1074
+ _forceRemove(currentNode);
1075
+ return true;
1076
+ }
1077
+ /* Check whether element has a valid namespace */
1078
+ if (currentNode instanceof Element && !_checkValidNamespace(currentNode)) {
1079
+ _forceRemove(currentNode);
1080
+ return true;
1081
+ }
1082
+ /* Make sure that older browsers don't get fallback-tag mXSS */
1083
+ if ((tagName === 'noscript' || tagName === 'noembed' || tagName === 'noframes') && regExpTest(/<\/no(script|embed|frames)/i, currentNode.innerHTML)) {
1084
+ _forceRemove(currentNode);
1085
+ return true;
1086
+ }
1087
+ /* Sanitize element content to be template-safe */
1088
+ if (SAFE_FOR_TEMPLATES && currentNode.nodeType === NODE_TYPE.text) {
1089
+ /* Get the element's text content */
1090
+ content = currentNode.textContent;
1091
+ arrayForEach([MUSTACHE_EXPR$1, ERB_EXPR$1, TMPLIT_EXPR$1], expr => {
1092
+ content = stringReplace(content, expr, ' ');
1093
+ });
1094
+ if (currentNode.textContent !== content) {
1095
+ arrayPush(DOMPurify.removed, {
1096
+ element: currentNode.cloneNode()
1074
1097
  });
1075
- if (currentNode.textContent !== content) {
1076
- arrayPush(DOMPurify.removed, {
1077
- element: currentNode.cloneNode()
1078
- });
1079
- currentNode.textContent = content;
1080
- }
1098
+ currentNode.textContent = content;
1081
1099
  }
1082
- /* Execute a hook if present */
1083
- _executeHooks(hooks.afterSanitizeElements, currentNode, null);
1100
+ }
1101
+ /* Execute a hook if present */
1102
+ _executeHooks(hooks.afterSanitizeElements, currentNode, null);
1103
+ return false;
1104
+ };
1105
+ /**
1106
+ * _isValidAttribute
1107
+ *
1108
+ * @param lcTag Lowercase tag name of containing element.
1109
+ * @param lcName Lowercase attribute name.
1110
+ * @param value Attribute value.
1111
+ * @return Returns true if `value` is valid, otherwise false.
1112
+ */
1113
+ // eslint-disable-next-line complexity
1114
+ const _isValidAttribute = function _isValidAttribute(lcTag, lcName, value) {
1115
+ /* FORBID_ATTR must always win, even if ADD_ATTR predicate would allow it */
1116
+ if (FORBID_ATTR[lcName]) {
1084
1117
  return false;
1085
- };
1086
- /**
1087
- * _isValidAttribute
1088
- *
1089
- * @param lcTag Lowercase tag name of containing element.
1090
- * @param lcName Lowercase attribute name.
1091
- * @param value Attribute value.
1092
- * @return Returns true if `value` is valid, otherwise false.
1093
- */
1094
- // eslint-disable-next-line complexity
1095
- const _isValidAttribute = function _isValidAttribute(lcTag, lcName, value) {
1096
- /* FORBID_ATTR must always win, even if ADD_ATTR predicate would allow it */
1097
- if (FORBID_ATTR[lcName]) {
1098
- return false;
1099
- }
1100
- /* Make sure attribute cannot clobber */
1101
- if (SANITIZE_DOM && (lcName === 'id' || lcName === 'name') && (value in document || value in formElement)) {
1118
+ }
1119
+ /* Make sure attribute cannot clobber */
1120
+ if (SANITIZE_DOM && (lcName === 'id' || lcName === 'name') && (value in document || value in formElement)) {
1121
+ return false;
1122
+ }
1123
+ const nameIsPermitted = ALLOWED_ATTR[lcName] || EXTRA_ELEMENT_HANDLING.attributeCheck instanceof Function && EXTRA_ELEMENT_HANDLING.attributeCheck(lcName, lcTag);
1124
+ /* Allow valid data-* attributes: At least one character after "-"
1125
+ (https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes)
1126
+ XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804)
1127
+ We don't need to check the value; it's always URI safe. */
1128
+ if (ALLOW_DATA_ATTR && !FORBID_ATTR[lcName] && regExpTest(DATA_ATTR$1, lcName)) ; else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR$1, lcName)) ; else if (!nameIsPermitted || FORBID_ATTR[lcName]) {
1129
+ if (
1130
+ // First condition does a very basic check if a) it's basically a valid custom element tagname AND
1131
+ // b) if the tagName passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
1132
+ // and c) if the attribute name passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.attributeNameCheck
1133
+ _isBasicCustomElement(lcTag) && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, lcTag) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(lcTag)) && (CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.attributeNameCheck, lcName) || CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.attributeNameCheck(lcName, lcTag)) ||
1134
+ // Alternative, second condition checks if it's an `is`-attribute, AND
1135
+ // the value passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
1136
+ lcName === 'is' && CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, value) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(value))) ; else {
1102
1137
  return false;
1103
1138
  }
1104
- const nameIsPermitted = ALLOWED_ATTR[lcName] || EXTRA_ELEMENT_HANDLING.attributeCheck instanceof Function && EXTRA_ELEMENT_HANDLING.attributeCheck(lcName, lcTag);
1105
- /* Allow valid data-* attributes: At least one character after "-"
1106
- (https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes)
1107
- XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804)
1108
- We don't need to check the value; it's always URI safe. */
1109
- if (ALLOW_DATA_ATTR && !FORBID_ATTR[lcName] && regExpTest(DATA_ATTR, lcName)) ; else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR, lcName)) ; else if (!nameIsPermitted || FORBID_ATTR[lcName]) {
1110
- if (
1111
- // First condition does a very basic check if a) it's basically a valid custom element tagname AND
1112
- // b) if the tagName passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
1113
- // and c) if the attribute name passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.attributeNameCheck
1114
- _isBasicCustomElement(lcTag) && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, lcTag) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(lcTag)) && (CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.attributeNameCheck, lcName) || CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.attributeNameCheck(lcName, lcTag)) ||
1115
- // Alternative, second condition checks if it's an `is`-attribute, AND
1116
- // the value passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
1117
- lcName === 'is' && CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, value) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(value))) ; else {
1118
- return false;
1119
- }
1120
- /* Check value is safe. First, is attr inert? If so, is safe */
1121
- } else if (URI_SAFE_ATTRIBUTES[lcName]) ; else if (regExpTest(IS_ALLOWED_URI$1, stringReplace(value, ATTR_WHITESPACE, ''))) ; else if ((lcName === 'src' || lcName === 'xlink:href' || lcName === 'href') && lcTag !== 'script' && stringIndexOf(value, 'data:') === 0 && DATA_URI_TAGS[lcTag]) ; else if (ALLOW_UNKNOWN_PROTOCOLS && !regExpTest(IS_SCRIPT_OR_DATA, stringReplace(value, ATTR_WHITESPACE, ''))) ; else if (value) {
1122
- return false;
1123
- } else ;
1124
- return true;
1125
- };
1126
- /* Names the HTML spec reserves from valid-custom-element-name; these must
1127
- * never be treated as basic custom elements even when a permissive
1128
- * CUSTOM_ELEMENT_HANDLING.tagNameCheck is configured. */
1129
- 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']);
1130
- /**
1131
- * _isBasicCustomElement
1132
- * checks if at least one dash is included in tagName, and it's not the first char
1133
- * for more sophisticated checking see https://github.com/sindresorhus/validate-element-name
1134
- *
1135
- * @param tagName name of the tag of the node to sanitize
1136
- * @returns Returns true if the tag name meets the basic criteria for a custom element, otherwise false.
1137
- */
1138
- const _isBasicCustomElement = function _isBasicCustomElement(tagName) {
1139
- return !RESERVED_CUSTOM_ELEMENT_NAMES[stringToLowerCase(tagName)] && regExpTest(CUSTOM_ELEMENT, tagName);
1139
+ /* Check value is safe. First, is attr inert? If so, is safe */
1140
+ } else if (URI_SAFE_ATTRIBUTES[lcName]) ; else if (regExpTest(IS_ALLOWED_URI$1, stringReplace(value, ATTR_WHITESPACE$1, ''))) ; else if ((lcName === 'src' || lcName === 'xlink:href' || lcName === 'href') && lcTag !== 'script' && stringIndexOf(value, 'data:') === 0 && DATA_URI_TAGS[lcTag]) ; else if (ALLOW_UNKNOWN_PROTOCOLS && !regExpTest(IS_SCRIPT_OR_DATA$1, stringReplace(value, ATTR_WHITESPACE$1, ''))) ; else if (value) {
1141
+ return false;
1142
+ } else ;
1143
+ return true;
1144
+ };
1145
+ /* Names the HTML spec reserves from valid-custom-element-name; these must
1146
+ * never be treated as basic custom elements even when a permissive
1147
+ * CUSTOM_ELEMENT_HANDLING.tagNameCheck is configured. */
1148
+ 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']);
1149
+ /**
1150
+ * _isBasicCustomElement
1151
+ * checks if at least one dash is included in tagName, and it's not the first char
1152
+ * for more sophisticated checking see https://github.com/sindresorhus/validate-element-name
1153
+ *
1154
+ * @param tagName name of the tag of the node to sanitize
1155
+ * @returns Returns true if the tag name meets the basic criteria for a custom element, otherwise false.
1156
+ */
1157
+ const _isBasicCustomElement = function _isBasicCustomElement(tagName) {
1158
+ return !RESERVED_CUSTOM_ELEMENT_NAMES[stringToLowerCase(tagName)] && regExpTest(CUSTOM_ELEMENT$1, tagName);
1159
+ };
1160
+ /**
1161
+ * _sanitizeAttributes
1162
+ *
1163
+ * @protect attributes
1164
+ * @protect nodeName
1165
+ * @protect removeAttribute
1166
+ * @protect setAttribute
1167
+ *
1168
+ * @param currentNode to sanitize
1169
+ */
1170
+ const _sanitizeAttributes = function _sanitizeAttributes(currentNode) {
1171
+ /* Execute a hook if present */
1172
+ _executeHooks(hooks.beforeSanitizeAttributes, currentNode, null);
1173
+ const attributes = currentNode.attributes;
1174
+ /* Check if we have attributes; if not we might have a text node */
1175
+ if (!attributes || _isClobbered(currentNode)) {
1176
+ return;
1177
+ }
1178
+ const hookEvent = {
1179
+ attrName: '',
1180
+ attrValue: '',
1181
+ keepAttr: true,
1182
+ allowedAttributes: ALLOWED_ATTR,
1183
+ forceKeepAttr: undefined
1140
1184
  };
1141
- /**
1142
- * _sanitizeAttributes
1143
- *
1144
- * @protect attributes
1145
- * @protect nodeName
1146
- * @protect removeAttribute
1147
- * @protect setAttribute
1148
- *
1149
- * @param currentNode to sanitize
1150
- */
1151
- const _sanitizeAttributes = function _sanitizeAttributes(currentNode) {
1185
+ let l = attributes.length;
1186
+ /* Go backwards over all attributes; safely remove bad ones */
1187
+ while (l--) {
1188
+ const attr = attributes[l];
1189
+ const name = attr.name,
1190
+ namespaceURI = attr.namespaceURI,
1191
+ attrValue = attr.value;
1192
+ const lcName = transformCaseFunc(name);
1193
+ const initValue = attrValue;
1194
+ let value = name === 'value' ? initValue : stringTrim(initValue);
1152
1195
  /* Execute a hook if present */
1153
- _executeHooks(hooks.beforeSanitizeAttributes, currentNode, null);
1154
- const {
1155
- attributes
1156
- } = currentNode;
1157
- /* Check if we have attributes; if not we might have a text node */
1158
- if (!attributes || _isClobbered(currentNode)) {
1159
- return;
1196
+ hookEvent.attrName = lcName;
1197
+ hookEvent.attrValue = value;
1198
+ hookEvent.keepAttr = true;
1199
+ hookEvent.forceKeepAttr = undefined; // Allows developers to see this is a property they can set
1200
+ _executeHooks(hooks.uponSanitizeAttribute, currentNode, hookEvent);
1201
+ value = hookEvent.attrValue;
1202
+ /* Full DOM Clobbering protection via namespace isolation,
1203
+ * Prefix id and name attributes with `user-content-`
1204
+ */
1205
+ if (SANITIZE_NAMED_PROPS && (lcName === 'id' || lcName === 'name') && stringIndexOf(value, SANITIZE_NAMED_PROPS_PREFIX) !== 0) {
1206
+ // Remove the attribute with this value
1207
+ _removeAttribute(name, currentNode);
1208
+ // Prefix the value and later re-create the attribute with the sanitized value
1209
+ value = SANITIZE_NAMED_PROPS_PREFIX + value;
1210
+ }
1211
+ // Else: already prefixed, leave the attribute alone — the prefix is
1212
+ // itself the clobbering protection, and re-applying it is incorrect.
1213
+ /* Work around a security issue with comments inside attributes */
1214
+ if (SAFE_FOR_XML && regExpTest(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i, value)) {
1215
+ _removeAttribute(name, currentNode);
1216
+ continue;
1217
+ }
1218
+ /* Make sure we cannot easily use animated hrefs, even if animations are allowed */
1219
+ if (lcName === 'attributename' && stringMatch(value, 'href')) {
1220
+ _removeAttribute(name, currentNode);
1221
+ continue;
1222
+ }
1223
+ /* Did the hooks approve of the attribute? */
1224
+ if (hookEvent.forceKeepAttr) {
1225
+ continue;
1226
+ }
1227
+ /* Did the hooks approve of the attribute? */
1228
+ if (!hookEvent.keepAttr) {
1229
+ _removeAttribute(name, currentNode);
1230
+ continue;
1231
+ }
1232
+ /* Work around a security issue in jQuery 3.0 */
1233
+ if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(/\/>/i, value)) {
1234
+ _removeAttribute(name, currentNode);
1235
+ continue;
1236
+ }
1237
+ /* Sanitize attribute content to be template-safe */
1238
+ if (SAFE_FOR_TEMPLATES) {
1239
+ arrayForEach([MUSTACHE_EXPR$1, ERB_EXPR$1, TMPLIT_EXPR$1], expr => {
1240
+ value = stringReplace(value, expr, ' ');
1241
+ });
1160
1242
  }
1161
- const hookEvent = {
1162
- attrName: '',
1163
- attrValue: '',
1164
- keepAttr: true,
1165
- allowedAttributes: ALLOWED_ATTR,
1166
- forceKeepAttr: undefined
1167
- };
1168
- let l = attributes.length;
1169
- /* Go backwards over all attributes; safely remove bad ones */
1170
- while (l--) {
1171
- const attr = attributes[l];
1172
- const {
1173
- name,
1174
- namespaceURI,
1175
- value: attrValue
1176
- } = attr;
1177
- const lcName = transformCaseFunc(name);
1178
- const initValue = attrValue;
1179
- let value = name === 'value' ? initValue : stringTrim(initValue);
1180
- /* Execute a hook if present */
1181
- hookEvent.attrName = lcName;
1182
- hookEvent.attrValue = value;
1183
- hookEvent.keepAttr = true;
1184
- hookEvent.forceKeepAttr = undefined; // Allows developers to see this is a property they can set
1185
- _executeHooks(hooks.uponSanitizeAttribute, currentNode, hookEvent);
1186
- value = hookEvent.attrValue;
1187
- /* Full DOM Clobbering protection via namespace isolation,
1188
- * Prefix id and name attributes with `user-content-`
1189
- */
1190
- if (SANITIZE_NAMED_PROPS && (lcName === 'id' || lcName === 'name') && stringIndexOf(value, SANITIZE_NAMED_PROPS_PREFIX) !== 0) {
1191
- // Remove the attribute with this value
1192
- _removeAttribute(name, currentNode);
1193
- // Prefix the value and later re-create the attribute with the sanitized value
1194
- value = SANITIZE_NAMED_PROPS_PREFIX + value;
1195
- }
1196
- // Else: already prefixed, leave the attribute alone — the prefix is
1197
- // itself the clobbering protection, and re-applying it is incorrect.
1198
- /* Work around a security issue with comments inside attributes */
1199
- if (SAFE_FOR_XML && regExpTest(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i, value)) {
1200
- _removeAttribute(name, currentNode);
1201
- continue;
1202
- }
1203
- /* Make sure we cannot easily use animated hrefs, even if animations are allowed */
1204
- if (lcName === 'attributename' && stringMatch(value, 'href')) {
1205
- _removeAttribute(name, currentNode);
1206
- continue;
1207
- }
1208
- /* Did the hooks approve of the attribute? */
1209
- if (hookEvent.forceKeepAttr) {
1210
- continue;
1211
- }
1212
- /* Did the hooks approve of the attribute? */
1213
- if (!hookEvent.keepAttr) {
1214
- _removeAttribute(name, currentNode);
1215
- continue;
1216
- }
1217
- /* Work around a security issue in jQuery 3.0 */
1218
- if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(/\/>/i, value)) {
1219
- _removeAttribute(name, currentNode);
1220
- continue;
1221
- }
1222
- /* Sanitize attribute content to be template-safe */
1223
- if (SAFE_FOR_TEMPLATES) {
1224
- arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {
1225
- value = stringReplace(value, expr, ' ');
1226
- });
1227
- }
1228
- /* Is `value` valid for this attribute? */
1229
- const lcTag = transformCaseFunc(currentNode.nodeName);
1230
- if (!_isValidAttribute(lcTag, lcName, value)) {
1231
- _removeAttribute(name, currentNode);
1232
- continue;
1233
- }
1234
- /* Handle attributes that require Trusted Types */
1235
- if (trustedTypesPolicy && typeof trustedTypes === 'object' && typeof trustedTypes.getAttributeType === 'function') {
1236
- if (namespaceURI) ; else {
1237
- switch (trustedTypes.getAttributeType(lcTag, lcName)) {
1238
- case 'TrustedHTML':
1239
- {
1240
- value = trustedTypesPolicy.createHTML(value);
1241
- break;
1242
- }
1243
- case 'TrustedScriptURL':
1244
- {
1245
- value = trustedTypesPolicy.createScriptURL(value);
1246
- break;
1247
- }
1248
- }
1243
+ /* Is `value` valid for this attribute? */
1244
+ const lcTag = transformCaseFunc(currentNode.nodeName);
1245
+ if (!_isValidAttribute(lcTag, lcName, value)) {
1246
+ _removeAttribute(name, currentNode);
1247
+ continue;
1248
+ }
1249
+ /* Handle attributes that require Trusted Types */
1250
+ if (trustedTypesPolicy && typeof trustedTypes === 'object' && typeof trustedTypes.getAttributeType === 'function') {
1251
+ if (namespaceURI) ; else {
1252
+ switch (trustedTypes.getAttributeType(lcTag, lcName)) {
1253
+ case 'TrustedHTML':
1254
+ {
1255
+ value = trustedTypesPolicy.createHTML(value);
1256
+ break;
1257
+ }
1258
+ case 'TrustedScriptURL':
1259
+ {
1260
+ value = trustedTypesPolicy.createScriptURL(value);
1261
+ break;
1262
+ }
1249
1263
  }
1250
1264
  }
1251
- /* Handle invalid data-* attribute set by try-catching it */
1252
- if (value !== initValue) {
1253
- try {
1254
- if (namespaceURI) {
1255
- currentNode.setAttributeNS(namespaceURI, name, value);
1256
- } else {
1257
- /* Fallback to setAttribute() for browser-unrecognized namespaces e.g. "x-schema". */
1258
- currentNode.setAttribute(name, value);
1259
- }
1260
- if (_isClobbered(currentNode)) {
1261
- _forceRemove(currentNode);
1262
- } else {
1263
- arrayPop(DOMPurify.removed);
1264
- }
1265
- } catch (_) {
1266
- _removeAttribute(name, currentNode);
1265
+ }
1266
+ /* Handle invalid data-* attribute set by try-catching it */
1267
+ if (value !== initValue) {
1268
+ try {
1269
+ if (namespaceURI) {
1270
+ currentNode.setAttributeNS(namespaceURI, name, value);
1271
+ } else {
1272
+ /* Fallback to setAttribute() for browser-unrecognized namespaces e.g. "x-schema". */
1273
+ currentNode.setAttribute(name, value);
1274
+ }
1275
+ if (_isClobbered(currentNode)) {
1276
+ _forceRemove(currentNode);
1277
+ } else {
1278
+ arrayPop(DOMPurify.removed);
1267
1279
  }
1280
+ } catch (_) {
1281
+ _removeAttribute(name, currentNode);
1268
1282
  }
1269
1283
  }
1284
+ }
1285
+ /* Execute a hook if present */
1286
+ _executeHooks(hooks.afterSanitizeAttributes, currentNode, null);
1287
+ };
1288
+ /**
1289
+ * _sanitizeShadowDOM
1290
+ *
1291
+ * @param fragment to iterate over recursively
1292
+ */
1293
+ const _sanitizeShadowDOM2 = function _sanitizeShadowDOM(fragment) {
1294
+ let shadowNode = null;
1295
+ const shadowIterator = _createNodeIterator(fragment);
1296
+ /* Execute a hook if present */
1297
+ _executeHooks(hooks.beforeSanitizeShadowDOM, fragment, null);
1298
+ while (shadowNode = shadowIterator.nextNode()) {
1270
1299
  /* Execute a hook if present */
1271
- _executeHooks(hooks.afterSanitizeAttributes, currentNode, null);
1272
- };
1273
- /**
1274
- * _sanitizeShadowDOM
1275
- *
1276
- * @param fragment to iterate over recursively
1277
- */
1278
- const _sanitizeShadowDOM2 = function _sanitizeShadowDOM(fragment) {
1279
- let shadowNode = null;
1280
- const shadowIterator = _createNodeIterator(fragment);
1281
- /* Execute a hook if present */
1282
- _executeHooks(hooks.beforeSanitizeShadowDOM, fragment, null);
1283
- while (shadowNode = shadowIterator.nextNode()) {
1284
- /* Execute a hook if present */
1285
- _executeHooks(hooks.uponSanitizeShadowNode, shadowNode, null);
1286
- /* Sanitize tags and elements */
1287
- _sanitizeElements(shadowNode);
1288
- /* Check attributes next */
1289
- _sanitizeAttributes(shadowNode);
1290
- /* Deep shadow DOM detected */
1291
- if (shadowNode.content instanceof DocumentFragment) {
1292
- _sanitizeShadowDOM2(shadowNode.content);
1293
- }
1300
+ _executeHooks(hooks.uponSanitizeShadowNode, shadowNode, null);
1301
+ /* Sanitize tags and elements */
1302
+ _sanitizeElements(shadowNode);
1303
+ /* Check attributes next */
1304
+ _sanitizeAttributes(shadowNode);
1305
+ /* Deep shadow DOM detected */
1306
+ if (shadowNode.content instanceof DocumentFragment) {
1307
+ _sanitizeShadowDOM2(shadowNode.content);
1294
1308
  }
1295
- /* Execute a hook if present */
1296
- _executeHooks(hooks.afterSanitizeShadowDOM, fragment, null);
1297
- };
1298
- // eslint-disable-next-line complexity
1299
- DOMPurify.sanitize = function (dirty) {
1300
- let cfg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1301
- let body = null;
1302
- let importedNode = null;
1303
- let currentNode = null;
1304
- let returnNode = null;
1305
- /* Make sure we have a string to sanitize.
1306
- DO NOT return early, as this will return the wrong type if
1307
- the user has requested a DOM object rather than a string */
1308
- IS_EMPTY_INPUT = !dirty;
1309
- if (IS_EMPTY_INPUT) {
1310
- dirty = '<!-->';
1309
+ }
1310
+ /* Execute a hook if present */
1311
+ _executeHooks(hooks.afterSanitizeShadowDOM, fragment, null);
1312
+ };
1313
+ /**
1314
+ * _sanitizeAttachedShadowRoots
1315
+ *
1316
+ * Walks `root` and feeds every attached shadow root we encounter into
1317
+ * the existing _sanitizeShadowDOM pipeline. The default node iterator
1318
+ * does not descend into shadow trees, so nodes inside an attached
1319
+ * shadow root would otherwise be skipped entirely.
1320
+ *
1321
+ * Two real input paths put attached shadow roots in front of us:
1322
+ * 1. IN_PLACE on a DOM node that already has shadow roots attached.
1323
+ * 2. DOM-node input where importNode(dirty, true) deep-clones the
1324
+ * shadow root because it was created with `clonable: true`.
1325
+ *
1326
+ * This pass runs once, up front, so the main iteration loop (and the
1327
+ * existing _sanitizeShadowDOM template-content recursion) stay
1328
+ * untouched — string-input paths are not affected.
1329
+ *
1330
+ * @param root the subtree root to walk for attached shadow roots
1331
+ */
1332
+ const _sanitizeAttachedShadowRoots2 = function _sanitizeAttachedShadowRoots(root) {
1333
+ if (root.nodeType === NODE_TYPE.element && root.shadowRoot instanceof DocumentFragment) {
1334
+ const sr = root.shadowRoot;
1335
+ // Recurse first so that nested shadow roots are reached even if
1336
+ // _sanitizeShadowDOM removes hosts at this level.
1337
+ _sanitizeAttachedShadowRoots2(sr);
1338
+ _sanitizeShadowDOM2(sr);
1339
+ }
1340
+ // Snapshot children before recursing. Sanitization of one subtree
1341
+ // (e.g. via an uponSanitizeShadowNode hook) may detach siblings,
1342
+ // and naive nextSibling traversal would silently skip the rest of
1343
+ // the list once a node is detached.
1344
+ const childNodes = root.childNodes;
1345
+ if (!childNodes) {
1346
+ return;
1347
+ }
1348
+ const snapshot = [];
1349
+ arrayForEach(childNodes, child => {
1350
+ arrayPush(snapshot, child);
1351
+ });
1352
+ for (const child of snapshot) {
1353
+ _sanitizeAttachedShadowRoots2(child);
1354
+ }
1355
+ };
1356
+ // eslint-disable-next-line complexity
1357
+ DOMPurify.sanitize = function (dirty) {
1358
+ let cfg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1359
+ let body = null;
1360
+ let importedNode = null;
1361
+ let currentNode = null;
1362
+ let returnNode = null;
1363
+ /* Make sure we have a string to sanitize.
1364
+ DO NOT return early, as this will return the wrong type if
1365
+ the user has requested a DOM object rather than a string */
1366
+ IS_EMPTY_INPUT = !dirty;
1367
+ if (IS_EMPTY_INPUT) {
1368
+ dirty = '<!-->';
1369
+ }
1370
+ /* Stringify, in case dirty is an object */
1371
+ if (typeof dirty !== 'string' && !_isNode(dirty)) {
1372
+ dirty = stringifyValue(dirty);
1373
+ if (typeof dirty !== 'string') {
1374
+ throw typeErrorCreate('dirty is not a string, aborting');
1311
1375
  }
1312
- /* Stringify, in case dirty is an object */
1313
- if (typeof dirty !== 'string' && !_isNode(dirty)) {
1314
- dirty = stringifyValue(dirty);
1315
- if (typeof dirty !== 'string') {
1316
- throw typeErrorCreate('dirty is not a string, aborting');
1376
+ }
1377
+ /* Return dirty HTML if DOMPurify cannot run */
1378
+ if (!DOMPurify.isSupported) {
1379
+ return dirty;
1380
+ }
1381
+ /* Assign config vars */
1382
+ if (!SET_CONFIG) {
1383
+ _parseConfig(cfg);
1384
+ }
1385
+ /* Clean up removed elements */
1386
+ DOMPurify.removed = [];
1387
+ /* Check if dirty is correctly typed for IN_PLACE */
1388
+ if (typeof dirty === 'string') {
1389
+ IN_PLACE = false;
1390
+ }
1391
+ if (IN_PLACE) {
1392
+ /* Do some early pre-sanitization to avoid unsafe root nodes */
1393
+ const nn = dirty.nodeName;
1394
+ if (typeof nn === 'string') {
1395
+ const tagName = transformCaseFunc(nn);
1396
+ if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
1397
+ throw typeErrorCreate('root node is forbidden and cannot be sanitized in-place');
1317
1398
  }
1318
1399
  }
1319
- /* Return dirty HTML if DOMPurify cannot run */
1320
- if (!DOMPurify.isSupported) {
1321
- return dirty;
1322
- }
1323
- /* Assign config vars */
1324
- if (!SET_CONFIG) {
1325
- _parseConfig(cfg);
1326
- }
1327
- /* Clean up removed elements */
1328
- DOMPurify.removed = [];
1329
- /* Check if dirty is correctly typed for IN_PLACE */
1330
- if (typeof dirty === 'string') {
1331
- IN_PLACE = false;
1332
- }
1333
- if (IN_PLACE) {
1334
- /* Do some early pre-sanitization to avoid unsafe root nodes */
1335
- const nn = dirty.nodeName;
1336
- if (typeof nn === 'string') {
1337
- const tagName = transformCaseFunc(nn);
1338
- if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
1339
- throw typeErrorCreate('root node is forbidden and cannot be sanitized in-place');
1340
- }
1341
- }
1342
- } else if (dirty instanceof Node) {
1343
- /* If dirty is a DOM element, append to an empty document to avoid
1344
- elements being stripped by the parser */
1345
- body = _initDocument('<!---->');
1346
- importedNode = body.ownerDocument.importNode(dirty, true);
1347
- if (importedNode.nodeType === NODE_TYPE.element && importedNode.nodeName === 'BODY') {
1348
- /* Node is already a body, use as is */
1349
- body = importedNode;
1350
- } else if (importedNode.nodeName === 'HTML') {
1351
- body = importedNode;
1352
- } else {
1353
- // eslint-disable-next-line unicorn/prefer-dom-node-append
1354
- body.appendChild(importedNode);
1355
- }
1400
+ /* Sanitize attached shadow roots before the main iterator runs.
1401
+ The iterator does not descend into shadow trees. */
1402
+ _sanitizeAttachedShadowRoots2(dirty);
1403
+ } else if (dirty instanceof Node) {
1404
+ /* If dirty is a DOM element, append to an empty document to avoid
1405
+ elements being stripped by the parser */
1406
+ body = _initDocument('<!---->');
1407
+ importedNode = body.ownerDocument.importNode(dirty, true);
1408
+ if (importedNode.nodeType === NODE_TYPE.element && importedNode.nodeName === 'BODY') {
1409
+ /* Node is already a body, use as is */
1410
+ body = importedNode;
1411
+ } else if (importedNode.nodeName === 'HTML') {
1412
+ body = importedNode;
1356
1413
  } else {
1357
- /* Exit directly if we have nothing to do */
1358
- if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT &&
1359
- // eslint-disable-next-line unicorn/prefer-includes
1360
- dirty.indexOf('<') === -1) {
1361
- return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(dirty) : dirty;
1362
- }
1363
- /* Initialize the document to work on */
1364
- body = _initDocument(dirty);
1365
- /* Check we have a DOM node from the data */
1366
- if (!body) {
1367
- return RETURN_DOM ? null : RETURN_TRUSTED_TYPE ? emptyHTML : '';
1368
- }
1369
- }
1370
- /* Remove first element node (ours) if FORCE_BODY is set */
1371
- if (body && FORCE_BODY) {
1372
- _forceRemove(body.firstChild);
1373
- }
1374
- /* Get node iterator */
1375
- const nodeIterator = _createNodeIterator(IN_PLACE ? dirty : body);
1376
- /* Now start iterating over the created document */
1377
- while (currentNode = nodeIterator.nextNode()) {
1378
- /* Sanitize tags and elements */
1379
- _sanitizeElements(currentNode);
1380
- /* Check attributes next */
1381
- _sanitizeAttributes(currentNode);
1382
- /* Shadow DOM detected, sanitize it */
1383
- if (currentNode.content instanceof DocumentFragment) {
1384
- _sanitizeShadowDOM2(currentNode.content);
1385
- }
1386
- }
1387
- /* If we sanitized `dirty` in-place, return it. */
1388
- if (IN_PLACE) {
1389
- return dirty;
1414
+ // eslint-disable-next-line unicorn/prefer-dom-node-append
1415
+ body.appendChild(importedNode);
1416
+ }
1417
+ /* Clonable shadow roots are deep-cloned by importNode(); sanitize
1418
+ them before the main iterator runs, since the iterator does not
1419
+ descend into shadow trees. */
1420
+ _sanitizeAttachedShadowRoots2(importedNode);
1421
+ } else {
1422
+ /* Exit directly if we have nothing to do */
1423
+ if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT &&
1424
+ // eslint-disable-next-line unicorn/prefer-includes
1425
+ dirty.indexOf('<') === -1) {
1426
+ return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(dirty) : dirty;
1390
1427
  }
1391
- /* Return sanitized string or DOM */
1392
- if (RETURN_DOM) {
1393
- if (SAFE_FOR_TEMPLATES) {
1394
- body.normalize();
1395
- let html = body.innerHTML;
1396
- arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {
1397
- html = stringReplace(html, expr, ' ');
1398
- });
1399
- body.innerHTML = html;
1400
- }
1401
- if (RETURN_DOM_FRAGMENT) {
1402
- returnNode = createDocumentFragment.call(body.ownerDocument);
1403
- while (body.firstChild) {
1404
- // eslint-disable-next-line unicorn/prefer-dom-node-append
1405
- returnNode.appendChild(body.firstChild);
1406
- }
1407
- } else {
1408
- returnNode = body;
1409
- }
1410
- if (ALLOWED_ATTR.shadowroot || ALLOWED_ATTR.shadowrootmode) {
1411
- /*
1412
- AdoptNode() is not used because internal state is not reset
1413
- (e.g. the past names map of a HTMLFormElement), this is safe
1414
- in theory but we would rather not risk another attack vector.
1415
- The state that is cloned by importNode() is explicitly defined
1416
- by the specs.
1417
- */
1418
- returnNode = importNode.call(originalDocument, returnNode, true);
1419
- }
1420
- return returnNode;
1428
+ /* Initialize the document to work on */
1429
+ body = _initDocument(dirty);
1430
+ /* Check we have a DOM node from the data */
1431
+ if (!body) {
1432
+ return RETURN_DOM ? null : RETURN_TRUSTED_TYPE ? emptyHTML : '';
1421
1433
  }
1422
- let serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML;
1423
- /* Serialize doctype if allowed */
1424
- if (WHOLE_DOCUMENT && ALLOWED_TAGS['!doctype'] && body.ownerDocument && body.ownerDocument.doctype && body.ownerDocument.doctype.name && regExpTest(DOCTYPE_NAME, body.ownerDocument.doctype.name)) {
1425
- serializedHTML = '<!DOCTYPE ' + body.ownerDocument.doctype.name + '>\n' + serializedHTML;
1434
+ }
1435
+ /* Remove first element node (ours) if FORCE_BODY is set */
1436
+ if (body && FORCE_BODY) {
1437
+ _forceRemove(body.firstChild);
1438
+ }
1439
+ /* Get node iterator */
1440
+ const nodeIterator = _createNodeIterator(IN_PLACE ? dirty : body);
1441
+ /* Now start iterating over the created document */
1442
+ while (currentNode = nodeIterator.nextNode()) {
1443
+ /* Sanitize tags and elements */
1444
+ _sanitizeElements(currentNode);
1445
+ /* Check attributes next */
1446
+ _sanitizeAttributes(currentNode);
1447
+ /* Shadow DOM detected, sanitize it */
1448
+ if (currentNode.content instanceof DocumentFragment) {
1449
+ _sanitizeShadowDOM2(currentNode.content);
1426
1450
  }
1427
- /* Sanitize final string template-safe */
1451
+ }
1452
+ /* If we sanitized `dirty` in-place, return it. */
1453
+ if (IN_PLACE) {
1454
+ return dirty;
1455
+ }
1456
+ /* Return sanitized string or DOM */
1457
+ if (RETURN_DOM) {
1428
1458
  if (SAFE_FOR_TEMPLATES) {
1429
- arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {
1430
- serializedHTML = stringReplace(serializedHTML, expr, ' ');
1459
+ body.normalize();
1460
+ let html = body.innerHTML;
1461
+ arrayForEach([MUSTACHE_EXPR$1, ERB_EXPR$1, TMPLIT_EXPR$1], expr => {
1462
+ html = stringReplace(html, expr, ' ');
1431
1463
  });
1464
+ body.innerHTML = html;
1432
1465
  }
1433
- return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(serializedHTML) : serializedHTML;
1434
- };
1435
- DOMPurify.setConfig = function () {
1436
- let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
1437
- _parseConfig(cfg);
1438
- SET_CONFIG = true;
1439
- };
1440
- DOMPurify.clearConfig = function () {
1441
- CONFIG = null;
1442
- SET_CONFIG = false;
1443
- };
1444
- DOMPurify.isValidAttribute = function (tag, attr, value) {
1445
- /* Initialize shared config vars if necessary. */
1446
- if (!CONFIG) {
1447
- _parseConfig({});
1448
- }
1449
- const lcTag = transformCaseFunc(tag);
1450
- const lcName = transformCaseFunc(attr);
1451
- return _isValidAttribute(lcTag, lcName, value);
1452
- };
1453
- DOMPurify.addHook = function (entryPoint, hookFunction) {
1454
- if (typeof hookFunction !== 'function') {
1455
- return;
1456
- }
1457
- arrayPush(hooks[entryPoint], hookFunction);
1458
- };
1459
- DOMPurify.removeHook = function (entryPoint, hookFunction) {
1460
- if (hookFunction !== undefined) {
1461
- const index = arrayLastIndexOf(hooks[entryPoint], hookFunction);
1462
- return index === -1 ? undefined : arraySplice(hooks[entryPoint], index, 1)[0];
1463
- }
1464
- return arrayPop(hooks[entryPoint]);
1465
- };
1466
- DOMPurify.removeHooks = function (entryPoint) {
1467
- hooks[entryPoint] = [];
1468
- };
1469
- DOMPurify.removeAllHooks = function () {
1470
- hooks = _createHooksMap();
1471
- };
1472
- return DOMPurify;
1473
- }
1474
- var purify = createDOMPurify();
1466
+ if (RETURN_DOM_FRAGMENT) {
1467
+ returnNode = createDocumentFragment.call(body.ownerDocument);
1468
+ while (body.firstChild) {
1469
+ // eslint-disable-next-line unicorn/prefer-dom-node-append
1470
+ returnNode.appendChild(body.firstChild);
1471
+ }
1472
+ } else {
1473
+ returnNode = body;
1474
+ }
1475
+ if (ALLOWED_ATTR.shadowroot || ALLOWED_ATTR.shadowrootmode) {
1476
+ /*
1477
+ AdoptNode() is not used because internal state is not reset
1478
+ (e.g. the past names map of a HTMLFormElement), this is safe
1479
+ in theory but we would rather not risk another attack vector.
1480
+ The state that is cloned by importNode() is explicitly defined
1481
+ by the specs.
1482
+ */
1483
+ returnNode = importNode.call(originalDocument, returnNode, true);
1484
+ }
1485
+ return returnNode;
1486
+ }
1487
+ let serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML;
1488
+ /* Serialize doctype if allowed */
1489
+ if (WHOLE_DOCUMENT && ALLOWED_TAGS['!doctype'] && body.ownerDocument && body.ownerDocument.doctype && body.ownerDocument.doctype.name && regExpTest(DOCTYPE_NAME, body.ownerDocument.doctype.name)) {
1490
+ serializedHTML = '<!DOCTYPE ' + body.ownerDocument.doctype.name + '>\n' + serializedHTML;
1491
+ }
1492
+ /* Sanitize final string template-safe */
1493
+ if (SAFE_FOR_TEMPLATES) {
1494
+ arrayForEach([MUSTACHE_EXPR$1, ERB_EXPR$1, TMPLIT_EXPR$1], expr => {
1495
+ serializedHTML = stringReplace(serializedHTML, expr, ' ');
1496
+ });
1497
+ }
1498
+ return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(serializedHTML) : serializedHTML;
1499
+ };
1500
+ DOMPurify.setConfig = function () {
1501
+ let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
1502
+ _parseConfig(cfg);
1503
+ SET_CONFIG = true;
1504
+ };
1505
+ DOMPurify.clearConfig = function () {
1506
+ CONFIG = null;
1507
+ SET_CONFIG = false;
1508
+ };
1509
+ DOMPurify.isValidAttribute = function (tag, attr, value) {
1510
+ /* Initialize shared config vars if necessary. */
1511
+ if (!CONFIG) {
1512
+ _parseConfig({});
1513
+ }
1514
+ const lcTag = transformCaseFunc(tag);
1515
+ const lcName = transformCaseFunc(attr);
1516
+ return _isValidAttribute(lcTag, lcName, value);
1517
+ };
1518
+ DOMPurify.addHook = function (entryPoint, hookFunction) {
1519
+ if (typeof hookFunction !== 'function') {
1520
+ return;
1521
+ }
1522
+ arrayPush(hooks[entryPoint], hookFunction);
1523
+ };
1524
+ DOMPurify.removeHook = function (entryPoint, hookFunction) {
1525
+ if (hookFunction !== undefined) {
1526
+ const index = arrayLastIndexOf(hooks[entryPoint], hookFunction);
1527
+ return index === -1 ? undefined : arraySplice(hooks[entryPoint], index, 1)[0];
1528
+ }
1529
+ return arrayPop(hooks[entryPoint]);
1530
+ };
1531
+ DOMPurify.removeHooks = function (entryPoint) {
1532
+ hooks[entryPoint] = [];
1533
+ };
1534
+ DOMPurify.removeAllHooks = function () {
1535
+ hooks = _createHooksMap();
1536
+ };
1537
+ return DOMPurify;
1538
+ }
1539
+ var purify = createDOMPurify();
1475
1540
 
1476
- return purify;
1541
+ return purify;
1477
1542
 
1478
1543
  }));
1479
1544
  //# sourceMappingURL=purify.js.map