jinzd-ai-cli 0.4.307 → 0.4.308

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