@ukic/canary-web-components 3.0.0-canary.44 → 3.0.0-canary.45

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