@vaadin/bundles 24.9.21 → 24.9.23

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.
@@ -10,7 +10,7 @@ __webpack_require__.r(__webpack_exports__);
10
10
  /* harmony export */ __webpack_require__.d(__webpack_exports__, {
11
11
  /* harmony export */ "default": () => (/* binding */ purify_default)
12
12
  /* harmony export */ });
13
- /*! @license DOMPurify 3.4.16 | (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.16/LICENSE */
13
+ /*! @license DOMPurify 3.4.18 | (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.18/LICENSE */
14
14
  function _OverloadYield(e, d) {
15
15
  this.v = e, this.k = d;
16
16
  }
@@ -105,6 +105,7 @@ AsyncGenerator.prototype["function" == typeof Symbol && Symbol.asyncIterator ||
105
105
  return this._invoke("return", e);
106
106
  };
107
107
  const entries = Object.entries;
108
+ const objectKeys = Object.keys;
108
109
  const setPrototypeOf = Object.setPrototypeOf;
109
110
  const isFrozen = Object.isFrozen;
110
111
  const getPrototypeOf = Object.getPrototypeOf;
@@ -130,13 +131,15 @@ if (!construct) construct = function construct(Func) {
130
131
  return new Func(...args);
131
132
  };
132
133
  const arrayForEach = unapply(Array.prototype.forEach);
133
- Array.prototype.indexOf;
134
134
  const arrayLastIndexOf = unapply(Array.prototype.lastIndexOf);
135
135
  const arrayPop = unapply(Array.prototype.pop);
136
136
  const arrayPush = unapply(Array.prototype.push);
137
- Array.prototype.slice;
137
+ const arraySlice = unapply(Array.prototype.slice);
138
138
  const arraySplice = unapply(Array.prototype.splice);
139
139
  const arrayIsArray = Array.isArray;
140
+ const setCreate = unconstruct(Set);
141
+ const setAdd = unapply(Set.prototype.add);
142
+ const setHas = unapply(Set.prototype.has);
140
143
  const stringToLowerCase = unapply(String.prototype.toLowerCase);
141
144
  const stringToString = unapply(String.prototype.toString);
142
145
  const stringMatch = unapply(String.prototype.match);
@@ -149,7 +152,11 @@ const bigintToString = typeof BigInt === "undefined" ? null : unapply(BigInt.pro
149
152
  const symbolToString = typeof Symbol === "undefined" ? null : unapply(Symbol.prototype.toString);
150
153
  const objectHasOwnProperty = unapply(Object.prototype.hasOwnProperty);
151
154
  const objectToString = unapply(Object.prototype.toString);
152
- const regExpTest = unapply(RegExp.prototype.test);
155
+ const regExpTestRaw = RegExp.prototype.test;
156
+ const regExpTest = function regExpTest(regExp, value) {
157
+ if (regExp instanceof RegExp) regExp.lastIndex = 0;
158
+ return apply(regExpTestRaw, regExp, [value]);
159
+ };
153
160
  const typeErrorCreate = unconstruct(TypeError);
154
161
  /**
155
162
  * Creates a new function that calls the given function with a specified thisArg and arguments.
@@ -159,7 +166,6 @@ const typeErrorCreate = unconstruct(TypeError);
159
166
  */
160
167
  function unapply(func) {
161
168
  return function(thisArg) {
162
- if (thisArg instanceof RegExp) thisArg.lastIndex = 0;
163
169
  for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) args[_key3 - 1] = arguments[_key3];
164
170
  return apply(func, thisArg, args);
165
171
  };
@@ -233,6 +239,19 @@ function clone(object) {
233
239
  return newObject;
234
240
  }
235
241
  /**
242
+ * Copy a flat lookup table
243
+ *
244
+ * @param set - The set to copy.
245
+ * @returns A new prototype-free set with the same entries.
246
+ */
247
+ function cloneSet(set) {
248
+ const newSet = create(null);
249
+ const keys = objectKeys(set);
250
+ let l = keys.length;
251
+ while (l--) newSet[keys[l]] = set[keys[l]];
252
+ return newSet;
253
+ }
254
+ /**
236
255
  * Convert non-node values into strings without depending on direct property access.
237
256
  *
238
257
  * @param value - The value to stringify.
@@ -281,7 +300,27 @@ function lookupGetter(object, prop) {
281
300
  }
282
301
  return fallbackValue;
283
302
  }
303
+ /**
304
+ * Like lookupGetter, but for accessor properties only, and returns null
305
+ * instead of a null-returning fallback when no getter exists on the chain.
306
+ * Lets a caller fall back to a direct property read in environments that
307
+ * lack the getter, where a fallback returning null would be indistinguishable
308
+ * from a legitimate null value (e.g. namespaceURI of a no-namespace element).
309
+ *
310
+ * @param object - The object (usually a prototype) to start the lookup at.
311
+ * @param prop - The accessor property name.
312
+ * @returns The unapplied getter, or null if none was found.
313
+ */
314
+ function lookupAccessor(object, prop) {
315
+ while (object !== null) {
316
+ const desc = getOwnPropertyDescriptor(object, prop);
317
+ if (desc) return desc.get ? unapply(desc.get) : null;
318
+ object = getPrototypeOf(object);
319
+ }
320
+ return null;
321
+ }
284
322
  function isRegex(value) {
323
+ if (!value) return false;
285
324
  try {
286
325
  regExpTest(value, "");
287
326
  return true;
@@ -424,8 +463,6 @@ const svg$1 = freeze([
424
463
  "defs",
425
464
  "desc",
426
465
  "ellipse",
427
- "enterkeyhint",
428
- "exportparts",
429
466
  "filter",
430
467
  "font",
431
468
  "g",
@@ -433,14 +470,12 @@ const svg$1 = freeze([
433
470
  "glyphref",
434
471
  "hkern",
435
472
  "image",
436
- "inputmode",
437
473
  "line",
438
474
  "lineargradient",
439
475
  "marker",
440
476
  "mask",
441
477
  "metadata",
442
478
  "mpath",
443
- "part",
444
479
  "path",
445
480
  "pattern",
446
481
  "polygon",
@@ -940,6 +975,7 @@ const xml = freeze([
940
975
  const MUSTACHE_EXPR = seal(/{{[\w\W]*|^[\w\W]*}}/g);
941
976
  const ERB_EXPR = seal(/<%[\w\W]*|^[\w\W]*%>/g);
942
977
  const TMPLIT_EXPR = seal(/\${[\w\W]*/g);
978
+ const TMPL_MARKER_SERIALIZED = seal(/{{|}}|\${|<%|%>|&lt;%|%&gt;/);
943
979
  const DATA_ATTR = seal(/^data-[\-\w.\u00B7-\uFFFF]+$/);
944
980
  const ARIA_ATTR = seal(/^aria-[\-\w]+$/);
945
981
  const IS_ALLOWED_URI = seal(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i);
@@ -951,21 +987,17 @@ const ELEMENT_MARKUP_PROBE = seal(/<[/\w!]/g);
951
987
  const COMMENT_MARKUP_PROBE = seal(/<[/\w]/g);
952
988
  const FALLBACK_TAG_CLOSE = seal(/<\/no(script|embed|frames)/i);
953
989
  const SELF_CLOSING_TAG = seal(/\/>/i);
990
+ const ATTR_VALUE_BREAKOUT = seal(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i);
991
+ const LEADING_WHITESPACE = seal(/^[\r\n\t ]+/);
954
992
  const NODE_TYPE = {
955
993
  element: 1,
956
- attribute: 2,
957
994
  text: 3,
958
- cdataSection: 4,
959
- entityReference: 5,
960
- entityNode: 6,
961
995
  processingInstruction: 7,
962
996
  comment: 8,
963
997
  document: 9,
964
- documentType: 10,
965
- documentFragment: 11,
966
- notation: 12
998
+ documentFragment: 11
967
999
  };
968
- const LITERAL_TEXT_ELEMENT_NAMES = [
1000
+ const LITERAL_TEXT_ELEMENTS = freeze(addToSet({}, [
969
1001
  "style",
970
1002
  "script",
971
1003
  "xmp",
@@ -974,15 +1006,7 @@ const LITERAL_TEXT_ELEMENT_NAMES = [
974
1006
  "noframes",
975
1007
  "plaintext",
976
1008
  "noscript"
977
- ];
978
- const LITERAL_TEXT_ELEMENTS = freeze(addToSet({}, LITERAL_TEXT_ELEMENT_NAMES));
979
- const LITERAL_TEXT_CLOSE = function() {
980
- const map = {};
981
- arrayForEach(LITERAL_TEXT_ELEMENT_NAMES, (name) => {
982
- map[name] = seal(new RegExp("</" + name + "(?=[\\t\\n\\f\\r />])", "i"));
983
- });
984
- return freeze(map);
985
- }();
1009
+ ]));
986
1010
  const getGlobal = function getGlobal() {
987
1011
  return typeof window === "undefined" ? null : window;
988
1012
  };
@@ -1028,39 +1052,33 @@ const _createHooksMap = function _createHooksMap() {
1028
1052
  };
1029
1053
  };
1030
1054
  /**
1031
- * Resolve a set-valued configuration option: a fresh set built from
1032
- * cfg[key] when it is an own array property (seeded with a clone of
1033
- * options.base when given, case-normalized via options.transform),
1034
- * the fallback set otherwise.
1055
+ * Resolve a set-valued configuration option.
1035
1056
  *
1036
1057
  * @param cfg the cloned, prototype-free configuration object
1037
1058
  * @param key the configuration property to read
1038
1059
  * @param fallback the set to use when the option is absent or not an array
1039
- * @param options transform and optional base set to merge into
1040
- * @returns the resolved set
1060
+ * @param options case transform, and an optional base set to extend a copy of
1061
+ * @returns a fresh set built from cfg[key], or the fallback
1041
1062
  */
1042
1063
  const _resolveSetOption = function _resolveSetOption(cfg, key, fallback, options) {
1043
- return objectHasOwnProperty(cfg, key) && arrayIsArray(cfg[key]) ? addToSet(options.base ? clone(options.base) : {}, cfg[key], options.transform) : fallback;
1064
+ return objectHasOwnProperty(cfg, key) && arrayIsArray(cfg[key]) ? addToSet(options.base ? cloneSet(options.base) : {}, cfg[key], options.transform) : fallback;
1044
1065
  };
1045
1066
  /**
1046
- * Resolve an object-valued configuration option: a prototype-free clone
1047
- * of cfg[key] when it is an own, truthy object property, else a fresh
1048
- * fallback built by makeFallback (fresh on every parse, so a previous
1049
- * parse can never leak state into the next one).
1067
+ * Resolve an object-valued configuration option.
1050
1068
  *
1051
1069
  * @param cfg the cloned, prototype-free configuration object
1052
1070
  * @param key the configuration property to read
1053
- * @param makeFallback builds the fallback value when the option is absent
1054
- * @returns the resolved object
1071
+ * @param fallback the read-only value to use when the option is absent
1072
+ * @returns a prototype-free clone of cfg[key], or the fallback
1055
1073
  */
1056
- const _resolveObjectOption = function _resolveObjectOption(cfg, key, makeFallback) {
1074
+ const _resolveObjectOption = function _resolveObjectOption(cfg, key, fallback) {
1057
1075
  const value = objectHasOwnProperty(cfg, key) ? cfg[key] : void 0;
1058
- return value && typeof value === "object" ? clone(value) : makeFallback();
1076
+ return value && typeof value === "object" ? clone(value) : fallback;
1059
1077
  };
1060
1078
  function createDOMPurify() {
1061
1079
  let window = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : getGlobal();
1062
1080
  const DOMPurify = (root) => createDOMPurify(root);
1063
- DOMPurify.version = "3.4.16";
1081
+ DOMPurify.version = "3.4.18";
1064
1082
  DOMPurify.removed = [];
1065
1083
  if (!window || !window.document || window.document.nodeType !== NODE_TYPE.document || !window.Element) {
1066
1084
  DOMPurify.isSupported = false;
@@ -1069,11 +1087,7 @@ function createDOMPurify() {
1069
1087
  let document = window.document;
1070
1088
  const originalDocument = document;
1071
1089
  const currentScript = originalDocument.currentScript;
1072
- window.DocumentFragment;
1073
- const HTMLTemplateElement = window.HTMLTemplateElement, Node = window.Node, Element = window.Element, NodeFilter = window.NodeFilter;
1074
- window.NamedNodeMap === void 0 && (window.NamedNodeMap || window.MozNamedAttrMap);
1075
- window.HTMLFormElement;
1076
- const DOMParser = window.DOMParser, trustedTypes = window.trustedTypes;
1090
+ const HTMLTemplateElement = window.HTMLTemplateElement, Node = window.Node, Element = window.Element, NodeFilter = window.NodeFilter, DOMParser = window.DOMParser, trustedTypes = window.trustedTypes;
1077
1091
  const ElementPrototype = Element.prototype;
1078
1092
  const cloneNode = lookupGetter(ElementPrototype, "cloneNode");
1079
1093
  const remove = lookupGetter(ElementPrototype, "remove");
@@ -1092,6 +1106,10 @@ function createDOMPurify() {
1092
1106
  const _readNodeName = function _readNodeName(node) {
1093
1107
  return getNodeName ? getNodeName(node) : node.nodeName;
1094
1108
  };
1109
+ const getNamespaceURI = lookupAccessor(ElementPrototype, "namespaceURI");
1110
+ const _readNamespaceURI = function _readNamespaceURI(element) {
1111
+ return getNamespaceURI ? getNamespaceURI(element) : element.namespaceURI;
1112
+ };
1095
1113
  if (typeof HTMLTemplateElement === "function") {
1096
1114
  const template = document.createElement("template");
1097
1115
  if (template.content && template.content.ownerDocument) document = template.content.ownerDocument;
@@ -1113,6 +1131,9 @@ function createDOMPurify() {
1113
1131
  IN_TRUSTED_TYPES_POLICY--;
1114
1132
  }
1115
1133
  };
1134
+ const _signOutput = function _signOutput(html) {
1135
+ return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? _createTrustedHTML(html) : html;
1136
+ };
1116
1137
  const _createTrustedScriptURL = function _createTrustedScriptURL(scriptUrl) {
1117
1138
  _assertNotInTrustedTypesPolicy();
1118
1139
  IN_TRUSTED_TYPES_POLICY++;
@@ -1157,26 +1178,7 @@ function createDOMPurify() {
1157
1178
  ...mathMl,
1158
1179
  ...xml
1159
1180
  ]);
1160
- let CUSTOM_ELEMENT_HANDLING = Object.seal(create(null, {
1161
- tagNameCheck: {
1162
- writable: true,
1163
- configurable: false,
1164
- enumerable: true,
1165
- value: null
1166
- },
1167
- attributeNameCheck: {
1168
- writable: true,
1169
- configurable: false,
1170
- enumerable: true,
1171
- value: null
1172
- },
1173
- allowCustomizedBuiltInElements: {
1174
- writable: true,
1175
- configurable: false,
1176
- enumerable: true,
1177
- value: false
1178
- }
1179
- }));
1181
+ let CUSTOM_ELEMENT_HANDLING = null;
1180
1182
  let FORBID_TAGS = null;
1181
1183
  let FORBID_ATTR = null;
1182
1184
  const EXTRA_ELEMENT_HANDLING = Object.seal(create(null, {
@@ -1212,7 +1214,8 @@ function createDOMPurify() {
1212
1214
  const SANITIZE_NAMED_PROPS_PREFIX = "user-content-";
1213
1215
  let KEEP_CONTENT = true;
1214
1216
  let IN_PLACE = false;
1215
- let USE_PROFILES = {};
1217
+ let IN_PLACE_VISITED = null;
1218
+ let USE_PROFILES = false;
1216
1219
  let FORBID_CONTENTS = null;
1217
1220
  const DEFAULT_FORBID_CONTENTS = addToSet({}, [
1218
1221
  "annotation-xml",
@@ -1279,16 +1282,17 @@ function createDOMPurify() {
1279
1282
  SVG_NAMESPACE,
1280
1283
  HTML_NAMESPACE
1281
1284
  ], stringToString);
1282
- const DEFAULT_MATHML_TEXT_INTEGRATION_POINTS = freeze([
1285
+ const DEFAULT_MATHML_TEXT_INTEGRATION_POINTS = freeze(addToSet({}, [
1283
1286
  "mi",
1284
1287
  "mo",
1285
1288
  "mn",
1286
1289
  "ms",
1287
1290
  "mtext"
1288
- ]);
1289
- let MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, DEFAULT_MATHML_TEXT_INTEGRATION_POINTS);
1290
- const DEFAULT_HTML_INTEGRATION_POINTS = freeze(["annotation-xml"]);
1291
- let HTML_INTEGRATION_POINTS = addToSet({}, DEFAULT_HTML_INTEGRATION_POINTS);
1291
+ ]));
1292
+ let MATHML_TEXT_INTEGRATION_POINTS = null;
1293
+ const DEFAULT_HTML_INTEGRATION_POINTS = freeze(addToSet({}, ["annotation-xml"]));
1294
+ let HTML_INTEGRATION_POINTS = null;
1295
+ const DEFAULT_CUSTOM_ELEMENT_HANDLING = freeze(create(null));
1292
1296
  const COMMON_SVG_AND_HTML_ELEMENTS = addToSet({}, [
1293
1297
  "title",
1294
1298
  "style",
@@ -1312,7 +1316,6 @@ function createDOMPurify() {
1312
1316
  */
1313
1317
  const _parseConfig = function _parseConfig() {
1314
1318
  let cfg = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
1315
- if (CONFIG && CONFIG === cfg) return;
1316
1319
  if (!cfg || typeof cfg !== "object") cfg = {};
1317
1320
  cfg = clone(cfg);
1318
1321
  PARSER_MEDIA_TYPE = SUPPORTED_PARSER_MEDIA_TYPES.indexOf(cfg.PARSER_MEDIA_TYPE) === -1 ? DEFAULT_PARSER_MEDIA_TYPE : cfg.PARSER_MEDIA_TYPE;
@@ -1329,8 +1332,8 @@ function createDOMPurify() {
1329
1332
  base: DEFAULT_DATA_URI_TAGS
1330
1333
  });
1331
1334
  FORBID_CONTENTS = _resolveSetOption(cfg, "FORBID_CONTENTS", DEFAULT_FORBID_CONTENTS, { transform: transformCaseFunc });
1332
- FORBID_TAGS = _resolveSetOption(cfg, "FORBID_TAGS", clone({}), { transform: transformCaseFunc });
1333
- FORBID_ATTR = _resolveSetOption(cfg, "FORBID_ATTR", clone({}), { transform: transformCaseFunc });
1335
+ FORBID_TAGS = _resolveSetOption(cfg, "FORBID_TAGS", create(null), { transform: transformCaseFunc });
1336
+ FORBID_ATTR = _resolveSetOption(cfg, "FORBID_ATTR", create(null), { transform: transformCaseFunc });
1334
1337
  USE_PROFILES = objectHasOwnProperty(cfg, "USE_PROFILES") ? cfg.USE_PROFILES && typeof cfg.USE_PROFILES === "object" ? clone(cfg.USE_PROFILES) : cfg.USE_PROFILES : false;
1335
1338
  ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false;
1336
1339
  ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false;
@@ -1349,9 +1352,9 @@ function createDOMPurify() {
1349
1352
  IN_PLACE = cfg.IN_PLACE || false;
1350
1353
  IS_ALLOWED_URI$1 = isRegex(cfg.ALLOWED_URI_REGEXP) ? cfg.ALLOWED_URI_REGEXP : IS_ALLOWED_URI;
1351
1354
  NAMESPACE = typeof cfg.NAMESPACE === "string" ? cfg.NAMESPACE : HTML_NAMESPACE;
1352
- MATHML_TEXT_INTEGRATION_POINTS = _resolveObjectOption(cfg, "MATHML_TEXT_INTEGRATION_POINTS", () => addToSet({}, DEFAULT_MATHML_TEXT_INTEGRATION_POINTS));
1353
- HTML_INTEGRATION_POINTS = _resolveObjectOption(cfg, "HTML_INTEGRATION_POINTS", () => addToSet({}, DEFAULT_HTML_INTEGRATION_POINTS));
1354
- const customElementHandling = _resolveObjectOption(cfg, "CUSTOM_ELEMENT_HANDLING", () => create(null));
1355
+ MATHML_TEXT_INTEGRATION_POINTS = _resolveObjectOption(cfg, "MATHML_TEXT_INTEGRATION_POINTS", DEFAULT_MATHML_TEXT_INTEGRATION_POINTS);
1356
+ HTML_INTEGRATION_POINTS = _resolveObjectOption(cfg, "HTML_INTEGRATION_POINTS", DEFAULT_HTML_INTEGRATION_POINTS);
1357
+ const customElementHandling = _resolveObjectOption(cfg, "CUSTOM_ELEMENT_HANDLING", DEFAULT_CUSTOM_ELEMENT_HANDLING);
1355
1358
  CUSTOM_ELEMENT_HANDLING = create(null);
1356
1359
  if (objectHasOwnProperty(customElementHandling, "tagNameCheck") && isRegexOrFunction(customElementHandling.tagNameCheck)) CUSTOM_ELEMENT_HANDLING.tagNameCheck = customElementHandling.tagNameCheck;
1357
1360
  if (objectHasOwnProperty(customElementHandling, "attributeNameCheck") && isRegexOrFunction(customElementHandling.attributeNameCheck)) CUSTOM_ELEMENT_HANDLING.attributeNameCheck = customElementHandling.attributeNameCheck;
@@ -1360,6 +1363,7 @@ function createDOMPurify() {
1360
1363
  if (SAFE_FOR_TEMPLATES) ALLOW_DATA_ATTR = false;
1361
1364
  if (RETURN_DOM_FRAGMENT) RETURN_DOM = true;
1362
1365
  if (USE_PROFILES) {
1366
+ if ((objectHasOwnProperty(cfg, "ALLOWED_TAGS") || objectHasOwnProperty(cfg, "ALLOWED_ATTR")) && typeof console !== "undefined" && typeof console.warn === "function") console.warn("DOMPurify: USE_PROFILES overrides ALLOWED_TAGS and ALLOWED_ATTR. Do not use these options together.");
1363
1367
  ALLOWED_TAGS = addToSet({}, text);
1364
1368
  ALLOWED_ATTR = create(null);
1365
1369
  if (USE_PROFILES.html === true) {
@@ -1387,19 +1391,19 @@ function createDOMPurify() {
1387
1391
  if (objectHasOwnProperty(cfg, "ADD_TAGS")) {
1388
1392
  if (typeof cfg.ADD_TAGS === "function") EXTRA_ELEMENT_HANDLING.tagCheck = cfg.ADD_TAGS;
1389
1393
  else if (arrayIsArray(cfg.ADD_TAGS)) {
1390
- if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) ALLOWED_TAGS = clone(ALLOWED_TAGS);
1394
+ if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) ALLOWED_TAGS = cloneSet(ALLOWED_TAGS);
1391
1395
  addToSet(ALLOWED_TAGS, cfg.ADD_TAGS, transformCaseFunc);
1392
1396
  }
1393
1397
  }
1394
1398
  if (objectHasOwnProperty(cfg, "ADD_ATTR")) {
1395
1399
  if (typeof cfg.ADD_ATTR === "function") EXTRA_ELEMENT_HANDLING.attributeCheck = cfg.ADD_ATTR;
1396
1400
  else if (arrayIsArray(cfg.ADD_ATTR)) {
1397
- if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) ALLOWED_ATTR = clone(ALLOWED_ATTR);
1401
+ if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) ALLOWED_ATTR = cloneSet(ALLOWED_ATTR);
1398
1402
  addToSet(ALLOWED_ATTR, cfg.ADD_ATTR, transformCaseFunc);
1399
1403
  }
1400
1404
  }
1401
1405
  if (objectHasOwnProperty(cfg, "ADD_FORBID_CONTENTS") && arrayIsArray(cfg.ADD_FORBID_CONTENTS)) {
1402
- if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) FORBID_CONTENTS = clone(FORBID_CONTENTS);
1406
+ if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) FORBID_CONTENTS = cloneSet(FORBID_CONTENTS);
1403
1407
  addToSet(FORBID_CONTENTS, cfg.ADD_FORBID_CONTENTS, transformCaseFunc);
1404
1408
  }
1405
1409
  if (KEEP_CONTENT) ALLOWED_TAGS["#text"] = true;
@@ -1409,7 +1413,7 @@ function createDOMPurify() {
1409
1413
  "body"
1410
1414
  ]);
1411
1415
  if (ALLOWED_TAGS.table) {
1412
- addToSet(ALLOWED_TAGS, ["tbody"]);
1416
+ ALLOWED_TAGS.tbody = true;
1413
1417
  delete FORBID_TAGS.tbody;
1414
1418
  }
1415
1419
  if (cfg.TRUSTED_TYPES_POLICY) {
@@ -1430,8 +1434,7 @@ function createDOMPurify() {
1430
1434
  if (trustedTypesPolicy === void 0) trustedTypesPolicy = _getDefaultTrustedTypesPolicy();
1431
1435
  if (trustedTypesPolicy && typeof emptyHTML === "string") emptyHTML = _createTrustedHTML("");
1432
1436
  }
1433
- if (freeze) freeze(cfg);
1434
- CONFIG = cfg;
1437
+ CONFIG = freeze(cfg);
1435
1438
  };
1436
1439
  const ALL_SVG_TAGS = addToSet({}, [
1437
1440
  ...svg$1,
@@ -1443,39 +1446,39 @@ function createDOMPurify() {
1443
1446
  * Namespace rules for an element in the SVG namespace.
1444
1447
  *
1445
1448
  * @param tagName the element's lowercase tag name
1446
- * @param parent the (possibly simulated) parent node
1449
+ * @param parentNamespace the (possibly simulated) parent's namespace
1447
1450
  * @param parentTagName the parent's lowercase tag name
1448
1451
  * @returns true if a spec-compliant parser could produce this element
1449
1452
  */
1450
- const _checkSvgNamespace = function _checkSvgNamespace(tagName, parent, parentTagName) {
1451
- if (parent.namespaceURI === HTML_NAMESPACE) return tagName === "svg";
1452
- if (parent.namespaceURI === MATHML_NAMESPACE) return tagName === "svg" && (parentTagName === "annotation-xml" || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);
1453
+ const _checkSvgNamespace = function _checkSvgNamespace(tagName, parentNamespace, parentTagName) {
1454
+ if (parentNamespace === HTML_NAMESPACE) return tagName === "svg";
1455
+ if (parentNamespace === MATHML_NAMESPACE) return tagName === "svg" && (parentTagName === "annotation-xml" || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);
1453
1456
  return Boolean(ALL_SVG_TAGS[tagName]);
1454
1457
  };
1455
1458
  /**
1456
1459
  * Namespace rules for an element in the MathML namespace.
1457
1460
  *
1458
1461
  * @param tagName the element's lowercase tag name
1459
- * @param parent the (possibly simulated) parent node
1462
+ * @param parentNamespace the (possibly simulated) parent's namespace
1460
1463
  * @param parentTagName the parent's lowercase tag name
1461
1464
  * @returns true if a spec-compliant parser could produce this element
1462
1465
  */
1463
- const _checkMathMlNamespace = function _checkMathMlNamespace(tagName, parent, parentTagName) {
1464
- if (parent.namespaceURI === HTML_NAMESPACE) return tagName === "math";
1465
- if (parent.namespaceURI === SVG_NAMESPACE) return tagName === "math" && HTML_INTEGRATION_POINTS[parentTagName];
1466
+ const _checkMathMlNamespace = function _checkMathMlNamespace(tagName, parentNamespace, parentTagName) {
1467
+ if (parentNamespace === HTML_NAMESPACE) return tagName === "math";
1468
+ if (parentNamespace === SVG_NAMESPACE) return tagName === "math" && HTML_INTEGRATION_POINTS[parentTagName];
1466
1469
  return Boolean(ALL_MATHML_TAGS[tagName]);
1467
1470
  };
1468
1471
  /**
1469
1472
  * Namespace rules for an element in the HTML namespace.
1470
1473
  *
1471
1474
  * @param tagName the element's lowercase tag name
1472
- * @param parent the (possibly simulated) parent node
1475
+ * @param parentNamespace the (possibly simulated) parent's namespace
1473
1476
  * @param parentTagName the parent's lowercase tag name
1474
1477
  * @returns true if a spec-compliant parser could produce this element
1475
1478
  */
1476
- const _checkHtmlNamespace = function _checkHtmlNamespace(tagName, parent, parentTagName) {
1477
- if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) return false;
1478
- if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) return false;
1479
+ const _checkHtmlNamespace = function _checkHtmlNamespace(tagName, parentNamespace, parentTagName) {
1480
+ if (parentNamespace === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) return false;
1481
+ if (parentNamespace === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) return false;
1479
1482
  return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]);
1480
1483
  };
1481
1484
  /**
@@ -1485,19 +1488,20 @@ function createDOMPurify() {
1485
1488
  * return. Return true otherwise.
1486
1489
  */
1487
1490
  const _checkValidNamespace = function _checkValidNamespace(element) {
1488
- let parent = getParentNode(element);
1489
- if (!parent || !parent.tagName) parent = {
1490
- namespaceURI: NAMESPACE,
1491
- tagName: "template"
1492
- };
1493
- const tagName = stringToLowerCase(element.tagName);
1494
- const parentTagName = stringToLowerCase(parent.tagName);
1495
- if (!ALLOWED_NAMESPACES[element.namespaceURI]) return false;
1496
- if (element.namespaceURI === SVG_NAMESPACE) return _checkSvgNamespace(tagName, parent, parentTagName);
1497
- if (element.namespaceURI === MATHML_NAMESPACE) return _checkMathMlNamespace(tagName, parent, parentTagName);
1498
- if (element.namespaceURI === HTML_NAMESPACE) return _checkHtmlNamespace(tagName, parent, parentTagName);
1499
- if (PARSER_MEDIA_TYPE === "application/xhtml+xml" && ALLOWED_NAMESPACES[element.namespaceURI]) return true;
1500
- return false;
1491
+ const elementNamespace = _readNamespaceURI(element);
1492
+ const tagName = stringToLowerCase(_readNodeName(element));
1493
+ const parentNode = getParentNode(element);
1494
+ let parentNamespace = NAMESPACE;
1495
+ let parentTagName = "template";
1496
+ if (parentNode && _readNodeType(parentNode) === NODE_TYPE.element) {
1497
+ parentNamespace = _readNamespaceURI(parentNode);
1498
+ parentTagName = stringToLowerCase(_readNodeName(parentNode));
1499
+ }
1500
+ if (!ALLOWED_NAMESPACES[elementNamespace]) return false;
1501
+ if (elementNamespace === SVG_NAMESPACE) return _checkSvgNamespace(tagName, parentNamespace, parentTagName);
1502
+ if (elementNamespace === MATHML_NAMESPACE) return _checkMathMlNamespace(tagName, parentNamespace, parentTagName);
1503
+ if (elementNamespace === HTML_NAMESPACE) return _checkHtmlNamespace(tagName, parentNamespace, parentTagName);
1504
+ return PARSER_MEDIA_TYPE === "application/xhtml+xml";
1501
1505
  };
1502
1506
  /**
1503
1507
  * _forceRemove
@@ -1514,17 +1518,10 @@ function createDOMPurify() {
1514
1518
  }
1515
1519
  };
1516
1520
  /**
1517
- * _stripAttributeNode
1518
- *
1519
- * Remove a single Attr node case/namespace-exactly on an attribute-teardown
1520
- * path. Name-based removeAttribute() ASCII-lowercases its lookup key for an
1521
- * HTML element in an HTML document and so silently misses a case-preserved
1522
- * handler (e.g. `ONERROR` off an XML/XHTML import) - the same defect
1523
- * _removeAttribute() was fixed for, which a name-based call would reintroduce
1524
- * on these IN_PLACE teardown paths. Unlike _removeAttribute this does not
1525
- * record into DOMPurify.removed: the neutralize passes intentionally do not
1526
- * book-keep. A clobbered/detached node falls back to best-effort name-based
1527
- * removal.
1521
+ * Removes an Attr node as that exact node, without book-keeping. Name-based
1522
+ * removal lowercases the name in HTML documents and would miss a
1523
+ * case-preserved one such as `ONERROR`, so it is only the fallback for
1524
+ * clobbered or detached nodes.
1528
1525
  *
1529
1526
  * @param element the element to strip the attribute from
1530
1527
  * @param attribute the Attr node to remove
@@ -1540,55 +1537,26 @@ function createDOMPurify() {
1540
1537
  }
1541
1538
  };
1542
1539
  /**
1543
- * _neutralizeRoot
1544
- *
1545
- * Fail-closed teardown of an in-place root after the sanitize walk aborts
1546
- * (campaign-3 F2). An internal throw mid-walk — e.g. a page-registered
1547
- * custom element's reaction detaches a node so `_forceRemove`'s deliberate
1548
- * parentless guard throws, or any other re-entrant engine mutation — would
1549
- * otherwise leave the caller's *live* tree half-sanitized, with everything
1550
- * after the abort point still carrying its handlers. There is no safe way
1551
- * to resume the walk (the tree mutated under us), so we strip the root bare:
1552
- * remove every child and every attribute, then let the caller's catch see
1553
- * the original error. Clobber-safe (cached `remove`/`childNodes`/`attributes`
1554
- * getters; the root was already clobber-pre-flighted at the IN_PLACE entry).
1540
+ * Fail-closed teardown of an in-place root: strip every disallowed attribute
1541
+ * in the subtree first, so nothing armed is left behind, then remove all
1542
+ * children and the root's own attributes.
1555
1543
  *
1556
1544
  * @param root the in-place root to empty
1557
1545
  */
1558
1546
  const _neutralizeRoot = function _neutralizeRoot(root) {
1559
1547
  _neutralizeSubtree(root);
1560
1548
  const childNodes = getChildNodes(root);
1561
- if (childNodes) {
1562
- const snapshot = [];
1563
- arrayForEach(childNodes, (child) => {
1564
- arrayPush(snapshot, child);
1565
- });
1566
- arrayForEach(snapshot, (child) => {
1567
- try {
1568
- remove(child);
1569
- } catch (_) {}
1570
- });
1571
- }
1572
- const attributes = getAttributes(root);
1573
- if (attributes) for (let i = attributes.length - 1; i >= 0; --i) {
1574
- const attribute = attributes[i];
1575
- const name = attribute && attribute.name;
1576
- if (typeof name === "string") _stripAttributeNode(root, attribute, name);
1577
- }
1549
+ if (childNodes) arrayForEach(arraySlice(childNodes), (child) => {
1550
+ try {
1551
+ remove(child);
1552
+ } catch (_) {}
1553
+ });
1554
+ if (_readNodeType(root) === NODE_TYPE.element) _stripAttributes(root, false);
1578
1555
  };
1579
1556
  /**
1580
- * _removeAttribute
1581
- *
1582
- * Name-based getAttributeNode()/removeAttribute() ASCII-lowercase their
1583
- * lookup key for HTML elements in an HTML document, so they silently miss an
1584
- * attribute whose stored qualified name still contains uppercase ASCII
1585
- * letters. That happens when the node came from a case-preserving source
1586
- * (an XML/XHTML document imported via importNode(), or createAttributeNS()),
1587
- * where e.g. `ONERROR` survives the walk: the policy check lowercases to
1588
- * `onerror` and rejects it, but `removeAttribute('ONERROR')` looks up
1589
- * `onerror` and finds nothing. Remove the exact Attr node instead, which is
1590
- * case- and namespace-exact, and fall back to name-based removal only when
1591
- * the caller could not supply the node.
1557
+ * Removes an attribute, preferably as its exact Attr node: name-based
1558
+ * removal lowercases the name in HTML documents and misses case-preserved
1559
+ * names, e.g. from imported XHTML.
1592
1560
  *
1593
1561
  * @param name an Attribute name
1594
1562
  * @param element a DOM node
@@ -1604,14 +1572,10 @@ function createDOMPurify() {
1604
1572
  attribute: attr || null,
1605
1573
  from: element
1606
1574
  });
1607
- try {
1608
- if (attr) removeAttributeNode(element, attr);
1609
- else element.removeAttribute(name);
1610
- } catch (_) {
1611
- try {
1612
- element.removeAttribute(name);
1613
- } catch (_) {}
1614
- }
1575
+ if (attr) _stripAttributeNode(element, attr, name);
1576
+ else try {
1577
+ element.removeAttribute(name);
1578
+ } catch (_) {}
1615
1579
  if (name === "is") {
1616
1580
  if (RETURN_DOM || RETURN_DOM_FRAGMENT) try {
1617
1581
  _forceRemove(element);
@@ -1622,97 +1586,172 @@ function createDOMPurify() {
1622
1586
  }
1623
1587
  };
1624
1588
  /**
1625
- * _stripDisallowedAttributes
1626
- *
1627
- * Removes every attribute the active configuration does not allow from a
1628
- * single element, using the same allowlist as the main attribute pass (so
1629
- * `on*` handlers go, but no `/^on/` blocklist is introduced). Used only to
1630
- * neutralise nodes that are being discarded from an in-place tree.
1589
+ * Removes an element's attributes without book-keeping. Used to neutralize
1590
+ * nodes discarded from an in-place tree.
1631
1591
  *
1632
1592
  * @param element the element to strip
1593
+ * @param keepAllowed whether attributes on the allowlist stay
1633
1594
  */
1634
- const _stripDisallowedAttributes = function _stripDisallowedAttributes(element) {
1595
+ const _stripAttributes = function _stripAttributes(element, keepAllowed) {
1635
1596
  const attributes = getAttributes(element);
1636
1597
  if (!attributes) return;
1637
1598
  for (let i = attributes.length - 1; i >= 0; --i) {
1638
1599
  const attribute = attributes[i];
1639
1600
  const name = attribute && attribute.name;
1640
- if (typeof name !== "string" || ALLOWED_ATTR[transformCaseFunc(name)]) continue;
1641
- _stripAttributeNode(element, attribute, name);
1601
+ if (typeof name === "string" && !(keepAllowed && ALLOWED_ATTR[transformCaseFunc(name)])) _stripAttributeNode(element, attribute, name);
1642
1602
  }
1643
1603
  };
1644
1604
  /**
1645
- * _neutralizeSubtree
1646
- *
1647
- * Completes the audit-5 F1 fix across every removal path. The KEEP_CONTENT
1648
- * move-hoist neutralises only disallowed-tag removals; clobber, mXSS-canary,
1649
- * namespace, comment, processing-instruction and KEEP_CONTENT:false removals
1650
- * all drop their subtree wholesale via `_forceRemove`. On the IN_PLACE path
1651
- * those dropped nodes are detached from the caller's LIVE tree but a
1652
- * handler-bearing original among them (an `<img onerror>`/`<video>` that was
1653
- * loading) keeps its queued resource event, which fires in page scope after
1654
- * sanitize returns. This walks a removed subtree and strips every attribute
1655
- * the active configuration does not allow — so `on*` handlers are cancelled
1656
- * through the SAME allowlist that governs kept nodes, not a separate `/^on/`
1657
- * blocklist. Run synchronously before sanitize returns, i.e. before any
1658
- * queued event can fire. Hook-free by design: these nodes leave the output,
1659
- * so firing attribute hooks for them would be surprising. Clobber-safe reads;
1660
- * a doomed clobbered node may shadow `removeAttribute` (its own attributes are
1661
- * irrelevant — it is discarded — while its non-clobbered descendants, e.g.
1662
- * the `<img>`, are reached and scrubbed).
1605
+ * Iterative depth-first walk, so deep trees cannot overflow the call stack,
1606
+ * reading through the cached getters, so clobbering cannot hide children.
1607
+ * When `visit` returns false, the node's children are skipped. With
1608
+ * `intoShadow`, open shadow roots are walked after their host's children.
1663
1609
  *
1664
- * @param root the root of a removed subtree to neutralise
1610
+ * @param root where to start
1611
+ * @param visit called for every node
1612
+ * @param intoShadow whether to enter open shadow roots
1665
1613
  */
1666
- const _neutralizeSubtree = function _neutralizeSubtree(root) {
1614
+ const _walkTree = function _walkTree(root, visit) {
1615
+ let intoShadow = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : false;
1667
1616
  const stack = [root];
1668
1617
  while (stack.length > 0) {
1669
1618
  const node = stack.pop();
1670
- if (_readNodeType(node) === NODE_TYPE.element) _stripDisallowedAttributes(node);
1619
+ if (visit(node) === false) continue;
1620
+ if (intoShadow && _readNodeType(node) === NODE_TYPE.element) {
1621
+ const shadowRoot = getShadowRoot(node);
1622
+ if (_isDocumentFragment(shadowRoot)) stack.push(shadowRoot);
1623
+ }
1671
1624
  const childNodes = getChildNodes(node);
1672
1625
  if (childNodes) for (let i = childNodes.length - 1; i >= 0; --i) stack.push(childNodes[i]);
1673
1626
  }
1674
1627
  };
1675
1628
  /**
1676
- * _neutralizePatchLinkage
1629
+ * Strips disallowed attributes from every element of a discarded subtree,
1630
+ * so a handler that is already queued (a loading image) cannot fire.
1677
1631
  *
1678
- * IN_PLACE entry pre-pass (declarative-partial-updates / streaming
1679
- * hardening, https://github.com/WICG/declarative-partial-updates).
1632
+ * @param root the root of a removed subtree
1633
+ */
1634
+ const _neutralizeSubtree = function _neutralizeSubtree(root) {
1635
+ _walkTree(root, (node) => {
1636
+ if (_readNodeType(node) === NODE_TYPE.element) _stripAttributes(node, true);
1637
+ });
1638
+ };
1639
+ /**
1640
+ * All nodes under `root`, root first, including open shadow roots. Template
1641
+ * content is not entered, it is inert.
1680
1642
  *
1681
- * The main walk strips patch linkage (`for`/`patchsrc`) and removes range
1682
- * markers (PIs / markup comments) node-by-node, in document order, AS it
1683
- * reaches each node. On a live in-place root that leaves a window: from the
1684
- * moment the root is connected until the walk arrives at a given node, that
1685
- * node's linkage is live. A patch applied on connection/stream can fire as
1686
- * a microtask during the walk and inject or teleport an unsanitized DOM
1687
- * range into a region the iterator has already passed and will not revisit,
1688
- * so the post-return "tree is sanitized" contract is violated. Sweep the
1689
- * whole tree once up front and sever every linkage before the walk begins,
1690
- * closing that window.
1643
+ * @param root the in-place root
1644
+ * @return the nodes
1645
+ */
1646
+ const _collectLiveNodes = function _collectLiveNodes(root) {
1647
+ const nodes = [];
1648
+ _walkTree(root, (node) => {
1649
+ nodes.push(node);
1650
+ }, true);
1651
+ return nodes;
1652
+ };
1653
+ /**
1654
+ * Strips disallowed attributes from every element that was under the
1655
+ * in-place root when the call started and no longer is, whatever removed
1656
+ * or moved it.
1691
1657
  *
1692
- * This CANNOT undo a patch that already fired before sanitize ran — that is
1693
- * the irreducible "do not IN_PLACE a live-connected attacker tree" caveat —
1694
- * but it closes everything from sanitize-start onward. Gated on SAFE_FOR_XML
1695
- * to group with the rest of the declarative-partial-updates handling and
1696
- * stay overridable, consistent with the codebase.
1658
+ * @param root the in-place root
1659
+ * @param before the root's nodes, collected before the walk
1660
+ */
1661
+ const _neutralizeEscapedElements = function _neutralizeEscapedElements(root, before) {
1662
+ const reachable = setCreate();
1663
+ arrayForEach(_collectLiveNodes(root), (node) => {
1664
+ if (_readNodeType(node) === NODE_TYPE.element) setAdd(reachable, node);
1665
+ });
1666
+ arrayForEach(before, (node) => {
1667
+ if (_readNodeType(node) === NODE_TYPE.element && !setHas(reachable, node)) _stripAttributes(node, true);
1668
+ });
1669
+ };
1670
+ /**
1671
+ * Neutralizes everything that left the in-place tree during the call: what
1672
+ * DOMPurify removed, and what hooks or custom elements removed or moved out.
1673
+ *
1674
+ * @param root the in-place root
1675
+ * @param before the root's nodes, collected before the walk
1676
+ * @return true if the root itself was removed
1677
+ */
1678
+ const _neutralizeDiscarded = function _neutralizeDiscarded(root, before) {
1679
+ let rootRemoved = false;
1680
+ arrayForEach(DOMPurify.removed, (entry) => {
1681
+ if (entry.element) {
1682
+ rootRemoved = rootRemoved || entry.element === root;
1683
+ _neutralizeSubtree(entry.element);
1684
+ }
1685
+ });
1686
+ _neutralizeEscapedElements(root, before);
1687
+ return rootRemoved;
1688
+ };
1689
+ const MAX_UNVISITED_ROUNDS = 8;
1690
+ /**
1691
+ * The walk only moves forward, so a node moved to a position it already
1692
+ * passed is never visited. Give every original node that is still in the
1693
+ * tree but unvisited the normal treatment, hooks included. Nodes created
1694
+ * during the call are left alone. Fails closed if the tree keeps changing.
1697
1695
  *
1698
- * Clobber-safe traversal (cached childNodes getter); per-node try/catch so a
1699
- * clobbered root cannot defeat the sweep of its non-clobbered descendants.
1696
+ * @param root the in-place root
1697
+ * @param before the root's nodes, collected before the walk
1698
+ */
1699
+ const _sanitizeUnvisitedNodes = function _sanitizeUnvisitedNodes(root, before) {
1700
+ const visited = IN_PLACE_VISITED;
1701
+ let original = null;
1702
+ const getOriginal = () => {
1703
+ if (!original) {
1704
+ original = setCreate();
1705
+ arrayForEach(before, (beforeNode) => {
1706
+ setAdd(original, beforeNode);
1707
+ });
1708
+ }
1709
+ return original;
1710
+ };
1711
+ for (let round = 0;; round++) {
1712
+ const live = _collectLiveNodes(root);
1713
+ const containers = [root];
1714
+ let pending = false;
1715
+ arrayForEach(live, (node) => {
1716
+ if (_readNodeType(node) === NODE_TYPE.documentFragment) arrayPush(containers, node);
1717
+ else if (!pending && !setHas(visited, node)) pending = setHas(getOriginal(), node);
1718
+ });
1719
+ if (!pending) return;
1720
+ if (round >= MAX_UNVISITED_ROUNDS) throw typeErrorCreate("the tree kept changing during in-place sanitization; refusing to return it");
1721
+ arrayForEach(containers, (container, index) => {
1722
+ _sanitizeUnvisitedIn(container, index > 0, root, getOriginal());
1723
+ });
1724
+ }
1725
+ };
1726
+ /**
1727
+ * One _sanitizeUnvisitedNodes pass over the root or an open shadow root.
1700
1728
  *
1701
- * NOTE (pending real-Chrome confirmation, see test/declarative-patch-probe
1702
- * .html Q1): this mirrors the existing policy of keeping `for` on
1703
- * <label>/<output>. If the shipping feature can drive a patch through a
1704
- * surviving `for`-on-label/output + `id` pair, this pre-pass and the
1705
- * attribute check at _isBasicCustomElement's caller must additionally drop
1706
- * that pair on the IN_PLACE path. Left as-is until the taxonomy is verified.
1729
+ * @param container the root or an open shadow root
1730
+ * @param inShadow whether container is a shadow root
1731
+ * @param root the in-place root
1732
+ * @param original the root's nodes collected before the walk, as a set
1733
+ */
1734
+ const _sanitizeUnvisitedIn = function _sanitizeUnvisitedIn(container, inShadow, root, original) {
1735
+ const iterator = _createNodeIterator(container);
1736
+ let node;
1737
+ while (node = iterator.nextNode()) {
1738
+ if (!setHas(original, node) || setHas(IN_PLACE_VISITED, node)) continue;
1739
+ if (inShadow) _executeHooks(hooks.uponSanitizeShadowNode, node, null);
1740
+ _sanitizeNode(node, root);
1741
+ }
1742
+ };
1743
+ /**
1744
+ * Records that _sanitizeElements processed `node`. No-op outside IN_PLACE.
1707
1745
  *
1708
- * @param root the in-place root to sweep
1746
+ * @param node the node being processed
1709
1747
  */
1748
+ const _markVisited = function _markVisited(node) {
1749
+ if (IN_PLACE_VISITED) setAdd(IN_PLACE_VISITED, node);
1750
+ };
1710
1751
  /**
1711
- * Central policy for declarative-partial-updates patch-linkage attributes,
1712
- * shared by the _neutralizePatchLinkage pre-pass and _isValidAttribute so
1713
- * the two sites cannot drift: `patchsrc` always links, `for` links
1714
- * everywhere except on <label>/<output>, and the whole policy is gated on
1715
- * SAFE_FOR_XML (see the rationale block in _isValidAttribute).
1752
+ * Patch-linkage attributes (declarative partial updates): `patchsrc`
1753
+ * always, `for` everywhere except on <label> and <output>. Gated on
1754
+ * SAFE_FOR_XML. Shared by the IN_PLACE pre-pass and _isValidAttribute.
1716
1755
  *
1717
1756
  * @param lcName the transformCaseFunc'd attribute name
1718
1757
  * @param lcTag the transformCaseFunc'd tag name of the carrying element
@@ -1723,17 +1762,26 @@ function createDOMPurify() {
1723
1762
  if (lcName === "patchsrc") return true;
1724
1763
  return lcName === "for" && lcTag !== "label" && lcTag !== "output";
1725
1764
  };
1765
+ /**
1766
+ * IN_PLACE pre-pass: sever all patch linkage before the walk, so no patch
1767
+ * can fire mid-walk into a part of the tree the walker already passed.
1768
+ * Removes range markers (processing instructions, comments with markup)
1769
+ * and strips linkage attributes. It cannot undo a patch that already fired.
1770
+ *
1771
+ * TODO: if the shipped feature can patch through `for` on <label>/<output>,
1772
+ * drop that pair here too.
1773
+ *
1774
+ * @param root the in-place root to sweep
1775
+ */
1726
1776
  const _neutralizePatchLinkage = function _neutralizePatchLinkage(root) {
1727
1777
  if (!SAFE_FOR_XML) return;
1728
- const stack = [root];
1729
- while (stack.length > 0) {
1730
- const node = stack.pop();
1778
+ _walkTree(root, (node) => {
1731
1779
  const nodeType = _readNodeType(node);
1732
1780
  if (nodeType === NODE_TYPE.processingInstruction || nodeType === NODE_TYPE.comment && regExpTest(COMMENT_MARKUP_PROBE, node.data)) {
1733
1781
  try {
1734
1782
  remove(node);
1735
1783
  } catch (_) {}
1736
- continue;
1784
+ return false;
1737
1785
  }
1738
1786
  if (nodeType === NODE_TYPE.element) {
1739
1787
  const element = node;
@@ -1743,9 +1791,8 @@ function createDOMPurify() {
1743
1791
  if (element.hasAttribute && element.hasAttribute("for") && _isPatchLinkageAttribute("for", lcTag)) element.removeAttribute("for");
1744
1792
  } catch (_) {}
1745
1793
  }
1746
- const childNodes = getChildNodes(node);
1747
- if (childNodes) for (let i = childNodes.length - 1; i >= 0; --i) stack.push(childNodes[i]);
1748
- }
1794
+ return true;
1795
+ });
1749
1796
  };
1750
1797
  /**
1751
1798
  * _initDocument
@@ -1758,7 +1805,7 @@ function createDOMPurify() {
1758
1805
  let leadingWhitespace = null;
1759
1806
  if (FORCE_BODY) dirty = "<remove></remove>" + dirty;
1760
1807
  else {
1761
- const matches = stringMatch(dirty, /^[\r\n\t ]+/);
1808
+ const matches = stringMatch(dirty, LEADING_WHITESPACE);
1762
1809
  leadingWhitespace = matches && matches[0];
1763
1810
  }
1764
1811
  if (PARSER_MEDIA_TYPE === "application/xhtml+xml" && NAMESPACE === HTML_NAMESPACE) dirty = "<html xmlns=\"http://www.w3.org/1999/xhtml\"><head></head><body>" + dirty + "</body></html>";
@@ -1778,14 +1825,18 @@ function createDOMPurify() {
1778
1825
  return WHOLE_DOCUMENT ? doc.documentElement : body;
1779
1826
  };
1780
1827
  /**
1781
- * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document.
1828
+ * Creates a NodeIterator over `root`. ownerDocument is read through the
1829
+ * cached getter: a form child named "ownerDocument" shadows the direct
1830
+ * read and would make createNodeIterator throw.
1782
1831
  *
1783
- * @param root The root element or node to start traversing on.
1832
+ * @param root The node to start traversing on.
1833
+ * @param characterDataOnly whether to skip elements
1784
1834
  * @return The created NodeIterator
1785
1835
  */
1786
1836
  const _createNodeIterator = function _createNodeIterator(root) {
1837
+ let characterDataOnly = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : false;
1787
1838
  const doc = getOwnerDocument ? getOwnerDocument(root) : root.ownerDocument;
1788
- return createNodeIterator.call(doc || root, root, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT | NodeFilter.SHOW_PROCESSING_INSTRUCTION | NodeFilter.SHOW_CDATA_SECTION, null);
1839
+ return createNodeIterator.call(doc || root, root, (characterDataOnly ? 0 : NodeFilter.SHOW_ELEMENT) | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT | NodeFilter.SHOW_PROCESSING_INSTRUCTION | NodeFilter.SHOW_CDATA_SECTION, null);
1789
1840
  };
1790
1841
  /**
1791
1842
  * Replace template expression syntax (mustache, ERB, template
@@ -1802,47 +1853,42 @@ function createDOMPurify() {
1802
1853
  return value;
1803
1854
  };
1804
1855
  /**
1805
- * Strip template-engine expressions ({{...}}, ${...}, <%...%>) from the
1806
- * character data of an element subtree. Used as the final safety net for
1807
- * SAFE_FOR_TEMPLATES on every DOM-returning code path so that expressions
1808
- * which only form after text-node normalization (e.g. fragments split across
1809
- * stripped elements) cannot survive into a template-evaluating framework.
1810
- *
1811
- * Walks text/comment/CDATA/processing-instruction nodes and mutates `.data`
1812
- * in place rather than round-tripping through innerHTML. This preserves
1813
- * descendant node references (important for IN_PLACE callers), avoids a
1814
- * serialize/reparse cycle, and reads literal character data — which means
1815
- * `<%...%>` in text content matches the ERB regex against its real bytes
1816
- * instead of the HTML-entity-escaped form innerHTML would produce.
1817
- *
1818
- * Attribute values are not visited here; SAFE_FOR_TEMPLATES handling for
1819
- * attributes is performed during the per-node `_sanitizeAttributes` pass.
1856
+ * Strips template expressions from the character data under `node`,
1857
+ * template contents included. Runs after the walk, since an expression can
1858
+ * also form when a removed element leaves two text nodes adjacent. Works on
1859
+ * the nodes rather than on markup, which keeps node references intact and
1860
+ * sees `<%` unescaped. Attribute values are handled in _sanitizeAttributes.
1820
1861
  *
1821
1862
  * @param node The root element whose character data should be scrubbed.
1822
1863
  */
1823
1864
  const _scrubTemplateExpressions2 = function _scrubTemplateExpressions(node) {
1824
1865
  var _node$querySelectorAl;
1866
+ _scrubOwnCharacterData(node);
1867
+ const templates = (_node$querySelectorAl = node.querySelectorAll) === null || _node$querySelectorAl === void 0 ? void 0 : _node$querySelectorAl.call(node, "template");
1868
+ if (templates) arrayForEach(templates, (tmpl) => {
1869
+ if (_isDocumentFragment(tmpl.content)) _scrubTemplateExpressions2(tmpl.content);
1870
+ });
1871
+ };
1872
+ /**
1873
+ * Normalizes `node` and strips template expressions from its own character
1874
+ * data. Template contents and shadow roots are not entered, their own
1875
+ * _sanitizeShadowDOM call scrubs them.
1876
+ *
1877
+ * @param node The root whose own character data should be scrubbed.
1878
+ */
1879
+ const _scrubOwnCharacterData = function _scrubOwnCharacterData(node) {
1825
1880
  node.normalize();
1826
- const doc = getOwnerDocument ? getOwnerDocument(node) : node.ownerDocument;
1827
- const walker = createNodeIterator.call(doc || node, node, NodeFilter.SHOW_TEXT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_CDATA_SECTION | NodeFilter.SHOW_PROCESSING_INSTRUCTION, null);
1881
+ const walker = _createNodeIterator(node, true);
1828
1882
  let currentNode = walker.nextNode();
1829
1883
  while (currentNode) {
1830
1884
  currentNode.data = _stripTemplateExpressions(currentNode.data);
1831
1885
  currentNode = walker.nextNode();
1832
1886
  }
1833
- const templates = (_node$querySelectorAl = node.querySelectorAll) === null || _node$querySelectorAl === void 0 ? void 0 : _node$querySelectorAl.call(node, "template");
1834
- if (templates) arrayForEach(templates, (tmpl) => {
1835
- if (_isDocumentFragment(tmpl.content)) _scrubTemplateExpressions2(tmpl.content);
1836
- });
1837
1887
  };
1838
1888
  /**
1839
- * _isClobbered
1840
- *
1841
- * Detect DOM-clobbering on HTMLFormElement nodes. Form is the only HTML
1842
- * interface with [LegacyOverrideBuiltIns]; a descendant element with a
1843
- * `name` attribute matching a prototype property shadows that property
1844
- * on direct reads. We use this check at the IN_PLACE entry-point and
1845
- * during attribute sanitization to refuse clobbered forms.
1889
+ * Detects DOM clobbering on a form, the only element whose named children
1890
+ * shadow its own properties. Each probe compares a direct read with what
1891
+ * the property has to be.
1846
1892
  *
1847
1893
  * @param element element to check for clobbering attacks
1848
1894
  * @return true if clobbered, false if safe
@@ -1854,42 +1900,26 @@ function createDOMPurify() {
1854
1900
  return typeof element.nodeName !== "string" || typeof element.textContent !== "string" || typeof element.removeChild !== "function" || element.attributes !== getAttributes(element) || typeof element.removeAttribute !== "function" || typeof element.removeAttributeNode !== "function" || typeof element.getAttributeNode !== "function" || typeof element.setAttribute !== "function" || typeof element.namespaceURI !== "string" || typeof element.insertBefore !== "function" || typeof element.hasChildNodes !== "function" || element.nodeType !== getNodeType(element) || element.childNodes !== getChildNodes(element);
1855
1901
  };
1856
1902
  /**
1857
- * Checks whether the given value is a DocumentFragment from any realm.
1858
- *
1859
- * The realm-independent replacement reads `nodeType` through the cached
1860
- * Node.prototype getter and compares to the DOCUMENT_FRAGMENT_NODE
1861
- * constant (11). nodeType is a numeric value resolved from the node's
1862
- * internal slot, identical across realms for the same kind of node.
1903
+ * Reads nodeType through the cached getter, so the result holds for nodes
1904
+ * from any realm (GHSA-4w3q-35jp-p934) and cannot be clobbered.
1863
1905
  *
1864
- * @param value object to check
1865
- * @return true if value is a DocumentFragment-shaped node from any realm
1906
+ * @param value anything
1907
+ * @return the node type, or null if value is not a DOM node
1866
1908
  */
1867
- const _isDocumentFragment = function _isDocumentFragment(value) {
1868
- if (!getNodeType || typeof value !== "object" || value === null) return false;
1909
+ const _nodeTypeOf = function _nodeTypeOf(value) {
1910
+ if (!getNodeType || typeof value !== "object" || value === null) return null;
1869
1911
  try {
1870
- return getNodeType(value) === NODE_TYPE.documentFragment;
1912
+ const nodeType = getNodeType(value);
1913
+ return typeof nodeType === "number" ? nodeType : null;
1871
1914
  } catch (_) {
1872
- return false;
1915
+ return null;
1873
1916
  }
1874
1917
  };
1875
- /**
1876
- * Checks whether the given object is a DOM node, including nodes that
1877
- * originate from a different window/realm (e.g. an iframe's
1878
- * contentDocument). The previous `value instanceof Node` check was
1879
- * realm-bound: nodes from a different window failed it, causing
1880
- * sanitize() to silently stringify them and reset IN_PLACE to false,
1881
- * returning the original node unsanitized. See GHSA-4w3q-35jp-p934.
1882
- *
1883
- * @param value object to check whether it's a DOM node
1884
- * @return true if value is a DOM node from any realm
1885
- */
1918
+ const _isDocumentFragment = function _isDocumentFragment(value) {
1919
+ return _nodeTypeOf(value) === NODE_TYPE.documentFragment;
1920
+ };
1886
1921
  const _isNode = function _isNode(value) {
1887
- if (!getNodeType || typeof value !== "object" || value === null) return false;
1888
- try {
1889
- return typeof getNodeType(value) === "number";
1890
- } catch (_) {
1891
- return false;
1892
- }
1922
+ return _nodeTypeOf(value) !== null;
1893
1923
  };
1894
1924
  function _executeHooks(hooks, currentNode, data) {
1895
1925
  if (hooks.length === 0) return;
@@ -1905,13 +1935,14 @@ function createDOMPurify() {
1905
1935
  *
1906
1936
  * @param currentNode the node to inspect
1907
1937
  * @param tagName the node's transformCaseFunc'd tag name
1938
+ * @param nodeType the node's type, read through the cached getter
1908
1939
  * @return true if the node must be removed
1909
1940
  */
1910
- const _isUnsafeNode = function _isUnsafeNode(currentNode, tagName) {
1911
- if (SAFE_FOR_XML && currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && regExpTest(ELEMENT_MARKUP_PROBE, currentNode.textContent) && regExpTest(ELEMENT_MARKUP_PROBE, currentNode.innerHTML)) return true;
1912
- 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))) return true;
1913
- if (currentNode.nodeType === NODE_TYPE.processingInstruction) return true;
1914
- if (SAFE_FOR_XML && currentNode.nodeType === NODE_TYPE.comment && regExpTest(COMMENT_MARKUP_PROBE, currentNode.data)) return true;
1941
+ const _isUnsafeNode = function _isUnsafeNode(currentNode, tagName, nodeType) {
1942
+ if (SAFE_FOR_XML && nodeType === NODE_TYPE.element && currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && regExpTest(ELEMENT_MARKUP_PROBE, currentNode.textContent) && regExpTest(ELEMENT_MARKUP_PROBE, currentNode.innerHTML)) return true;
1943
+ if (SAFE_FOR_XML && LITERAL_TEXT_ELEMENTS[tagName] && nodeType === NODE_TYPE.element && _readNamespaceURI(currentNode) === HTML_NAMESPACE && (_isNode(currentNode.firstElementChild) || typeof currentNode.textContent === "string" && regExpTest(ELEMENT_MARKUP_PROBE, currentNode.textContent))) return true;
1944
+ if (nodeType === NODE_TYPE.processingInstruction) return true;
1945
+ if (SAFE_FOR_XML && nodeType === NODE_TYPE.comment && regExpTest(COMMENT_MARKUP_PROBE, currentNode.data)) return true;
1915
1946
  return false;
1916
1947
  };
1917
1948
  /**
@@ -1935,17 +1966,9 @@ function createDOMPurify() {
1935
1966
  return false;
1936
1967
  };
1937
1968
  /**
1938
- * Handle a node whose tag is forbidden or not allowlisted: keep
1939
- * allowed custom elements (false return exits _sanitizeElements
1940
- * early - the namespace and fallback-tag removal checks are
1941
- * intentionally skipped for kept custom elements), else hoist
1942
- * content per KEEP_CONTENT and remove.
1943
- *
1944
- * A kept custom element is the ONLY case in which this function
1945
- * returns false, so the caller uses that return value to run the
1946
- * afterSanitizeElements hook on the kept element and keep the
1947
- * element-hook lifecycle consistent with normal allowlisted
1948
- * elements (GHSA-c2j3-45gr-mqc4).
1969
+ * Handles a node whose tag is forbidden or not allowlisted: hoists its
1970
+ * content per KEEP_CONTENT and removes it. The one exception is a custom
1971
+ * element allowed via CUSTOM_ELEMENT_HANDLING, which is kept.
1949
1972
  *
1950
1973
  * @param currentNode the disallowed node
1951
1974
  * @param tagName the node's transformCaseFunc'd tag name
@@ -1953,7 +1976,7 @@ function createDOMPurify() {
1953
1976
  */
1954
1977
  const _sanitizeDisallowedNode = function _sanitizeDisallowedNode(currentNode, tagName, root) {
1955
1978
  if (!FORBID_TAGS[tagName] && _isBasicCustomElement(tagName) && _matchesNameCheck(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) return false;
1956
- if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {
1979
+ if (KEEP_CONTENT && !FORBID_CONTENTS[tagName] && !FORBID_CONTENTS[stringToLowerCase(tagName)]) {
1957
1980
  const parentNode = getParentNode(currentNode);
1958
1981
  const childNodes = getChildNodes(currentNode);
1959
1982
  if (childNodes && parentNode) {
@@ -1968,11 +1991,9 @@ function createDOMPurify() {
1968
1991
  return true;
1969
1992
  };
1970
1993
  /**
1971
- * Fork a hook-mutable allowlist off its shared binding the first time a
1972
- * (possibly lazily-installed) uponSanitize* hook is about to see it, so the
1973
- * hook cannot widen the per-instance default or the setConfig binding by
1974
- * reference and leak past the call. Returns the set unchanged once it is
1975
- * already call-local, so repeated calls across elements are idempotent.
1994
+ * Forks an allowlist off its shared binding (the instance default or the
1995
+ * setConfig() capture) before a hook sees it, so a hook's widening stays
1996
+ * within the call. A set that is already call-local is returned as is.
1976
1997
  *
1977
1998
  * @param hookList the uponSanitize* hook array for this event
1978
1999
  * @param set the current ALLOWED_TAGS / ALLOWED_ATTR binding
@@ -1983,38 +2004,16 @@ function createDOMPurify() {
1983
2004
  */
1984
2005
  const _forkSharedAllowlist = function _forkSharedAllowlist(hookList, set, defaultSet, setConfigSet) {
1985
2006
  if (hookList.length === 0) return set;
1986
- return set === defaultSet || set === setConfigSet ? clone(set) : set;
2007
+ return set === defaultSet || set === setConfigSet ? cloneSet(set) : set;
1987
2008
  };
1988
2009
  /**
1989
- * Shared guard for a node that a hook has detached from the walk tree,
1990
- * used after each element-hook site in _sanitizeElements. Detaching is a
1991
- * long-standing user pattern (issue #469; draw.io-style foreignObject
1992
- * filtering). Per the cached, unclobberable parentNode getter the node is
1993
- * genuinely out of the tree, so it can reach neither the serialized
1994
- * output nor an IN_PLACE live tree; treat it as removed and stop
1995
- * processing it. Without this guard, the unsafe-node / namespace checks
1996
- * would call _forceRemove on a parentless node and hit the REPORT-3
1997
- * fail-closed throw — which exists for nodes DOMPurify wants gone but
1998
- * *cannot* detach (clobbered / parentless roots), the opposite of a node
1999
- * that is already safely gone. The walk root is exempt: a detached
2000
- * IN_PLACE root is legitimate input and must still be fully sanitized,
2001
- * and a kill-decision on it must keep hitting the REPORT-3 throw.
2002
- *
2003
- * Nodes detached by hooks stay the hook's responsibility for placement:
2004
- * they are not recorded in DOMPurify.removed, so the post-walk IN_PLACE
2005
- * pass (which iterates DOMPurify.removed) does not reach them. But a
2006
- * hook-detached subtree can still hold a queued resource-event handler -
2007
- * e.g. an <img onload> that began loading when the caller built the live
2008
- * tree - which fires in page scope after sanitize returns even though the
2009
- * handler never reached the returned tree. That is the audit-5 F1 hazard,
2010
- * and the documented node.remove() hook pattern walks straight into it.
2011
- * So on the IN_PLACE path we neutralize the detached subtree inline,
2012
- * stripping its non-allow-listed attributes before returning, exactly as
2013
- * the post-walk pass does for _forceRemove'd subtrees.
2010
+ * A hook may have detached the node it was called for. If so, treat it as
2011
+ * removed and stop processing it; the walk root is exempt. On the IN_PLACE
2012
+ * path the detached subtree is neutralized right away.
2014
2013
  *
2015
2014
  * @param currentNode the node a hook may have detached
2016
2015
  * @param root the current walk root
2017
- * @return true if the node is detached and now handled, false otherwise
2016
+ * @return true if the node was detached
2018
2017
  */
2019
2018
  const _handleHookDetachedNode = function _handleHookDetachedNode(currentNode, root) {
2020
2019
  if (currentNode === root || getParentNode(currentNode) !== null) return false;
@@ -2031,6 +2030,7 @@ function createDOMPurify() {
2031
2030
  * @return true if node was killed, false if left alive
2032
2031
  */
2033
2032
  const _sanitizeElements = function _sanitizeElements(currentNode, root) {
2033
+ _markVisited(currentNode);
2034
2034
  _executeHooks(hooks.beforeSanitizeElements, currentNode, null);
2035
2035
  if (_handleHookDetachedNode(currentNode, root)) return true;
2036
2036
  if (_isClobbered(currentNode)) {
@@ -2038,13 +2038,14 @@ function createDOMPurify() {
2038
2038
  return true;
2039
2039
  }
2040
2040
  const tagName = transformCaseFunc(_readNodeName(currentNode));
2041
+ const nodeType = _readNodeType(currentNode);
2041
2042
  ALLOWED_TAGS = _forkSharedAllowlist(hooks.uponSanitizeElement, ALLOWED_TAGS, DEFAULT_ALLOWED_TAGS, SET_CONFIG_ALLOWED_TAGS);
2042
2043
  _executeHooks(hooks.uponSanitizeElement, currentNode, {
2043
2044
  tagName,
2044
2045
  allowedTags: ALLOWED_TAGS
2045
2046
  });
2046
2047
  if (_handleHookDetachedNode(currentNode, root)) return true;
2047
- if (_isUnsafeNode(currentNode, tagName)) {
2048
+ if (_isUnsafeNode(currentNode, tagName, nodeType)) {
2048
2049
  _forceRemove(currentNode);
2049
2050
  return true;
2050
2051
  }
@@ -2056,7 +2057,7 @@ function createDOMPurify() {
2056
2057
  }
2057
2058
  return removed;
2058
2059
  }
2059
- if (_readNodeType(currentNode) === NODE_TYPE.element && !_checkValidNamespace(currentNode)) {
2060
+ if (nodeType === NODE_TYPE.element && !_checkValidNamespace(currentNode)) {
2060
2061
  _forceRemove(currentNode);
2061
2062
  return true;
2062
2063
  }
@@ -2064,9 +2065,10 @@ function createDOMPurify() {
2064
2065
  _forceRemove(currentNode);
2065
2066
  return true;
2066
2067
  }
2067
- if (SAFE_FOR_TEMPLATES && currentNode.nodeType === NODE_TYPE.text) {
2068
- const content = _stripTemplateExpressions(currentNode.textContent);
2069
- if (currentNode.textContent !== content) {
2068
+ if (SAFE_FOR_TEMPLATES && nodeType === NODE_TYPE.text) {
2069
+ const text = currentNode.textContent;
2070
+ const content = _stripTemplateExpressions(text);
2071
+ if (text !== content) {
2070
2072
  arrayPush(DOMPurify.removed, { element: currentNode.cloneNode() });
2071
2073
  currentNode.textContent = content;
2072
2074
  }
@@ -2091,9 +2093,10 @@ function createDOMPurify() {
2091
2093
  if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR$1, lcName)) return true;
2092
2094
  if (!nameIsPermitted) return _isBasicCustomElement(lcTag) && _matchesNameCheck(CUSTOM_ELEMENT_HANDLING.tagNameCheck, lcTag) && _matchesNameCheck(CUSTOM_ELEMENT_HANDLING.attributeNameCheck, lcName, lcTag) || lcName === "is" && CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements && _matchesNameCheck(CUSTOM_ELEMENT_HANDLING.tagNameCheck, value);
2093
2095
  if (URI_SAFE_ATTRIBUTES[lcName]) return true;
2094
- if (regExpTest(IS_ALLOWED_URI$1, stringReplace(value, ATTR_WHITESPACE$1, ""))) return true;
2096
+ const compactValue = stringReplace(value, ATTR_WHITESPACE$1, "");
2097
+ if (regExpTest(IS_ALLOWED_URI$1, compactValue)) return true;
2095
2098
  if ((lcName === "src" || lcName === "xlink:href" || lcName === "href") && lcTag !== "script" && stringIndexOf(value, "data:") === 0 && DATA_URI_TAGS[lcTag]) return true;
2096
- if (ALLOW_UNKNOWN_PROTOCOLS && !regExpTest(IS_SCRIPT_OR_DATA$1, stringReplace(value, ATTR_WHITESPACE$1, ""))) return true;
2099
+ if (ALLOW_UNKNOWN_PROTOCOLS && !regExpTest(IS_SCRIPT_OR_DATA$1, compactValue)) return true;
2097
2100
  return !value;
2098
2101
  };
2099
2102
  const RESERVED_CUSTOM_ELEMENT_NAMES = addToSet({}, [
@@ -2137,21 +2140,8 @@ function createDOMPurify() {
2137
2140
  return value;
2138
2141
  };
2139
2142
  /**
2140
- * Write a modified attribute value back onto the element. On
2141
- * success, re-probe for clobbering introduced by the new value and
2142
- * remove the element when found; otherwise, when this writeback is the
2143
- * recreate half of the SANITIZE_NAMED_PROPS remove-and-recreate, pop the
2144
- * removal entry that path recorded so it does not show as removed. On
2145
- * failure, remove the attribute instead.
2146
- *
2147
- * Returns true only on a clean write (the value was set and the new value
2148
- * introduced no clobbering). The caller uses that, together with its own
2149
- * knowledge of whether this attribute pushed a DOMPurify.removed record, to
2150
- * decide whether to pop that record. The pop must happen ONLY for the
2151
- * named-prop remove-and-recreate; popping on any other value change (trim,
2152
- * template scrubbing, Trusted Types) would consume an unrelated _forceRemove
2153
- * subtree-cleanup record and let that detached subtree keep a live event
2154
- * handler through the IN_PLACE neutralization pass (SO-001).
2143
+ * Writes a changed attribute value back. If the new value clobbers, the
2144
+ * element is removed; if the write fails, the attribute is.
2155
2145
  *
2156
2146
  * @param currentNode the element carrying the attribute
2157
2147
  * @param name the attribute name as present on the element
@@ -2174,6 +2164,19 @@ function createDOMPurify() {
2174
2164
  }
2175
2165
  };
2176
2166
  /**
2167
+ * Value checks that apply before a hook can force-keep an attribute. Also
2168
+ * used by isValidAttribute(), so it never approves a value that sanitize()
2169
+ * would strip.
2170
+ *
2171
+ * @param name the attribute name as found on the node (case preserved)
2172
+ * @param value the attribute value
2173
+ * @returns true if the attribute must be removed because of its value
2174
+ */
2175
+ const _isUnsafeAttributeValue = function _isUnsafeAttributeValue(name, value) {
2176
+ if (SAFE_FOR_XML && regExpTest(ATTR_VALUE_BREAKOUT, value)) return true;
2177
+ return stringToLowerCase(name) === "attributename" && stringIndexOf(value, "href") !== -1;
2178
+ };
2179
+ /**
2177
2180
  * _sanitizeAttributes
2178
2181
  *
2179
2182
  * @protect attributes
@@ -2198,7 +2201,7 @@ function createDOMPurify() {
2198
2201
  forceKeepAttr: void 0
2199
2202
  };
2200
2203
  let l = attributes.length;
2201
- const lcTag = transformCaseFunc(currentNode.nodeName);
2204
+ const lcTag = transformCaseFunc(_readNodeName(currentNode));
2202
2205
  while (l--) {
2203
2206
  const attr = attributes[l];
2204
2207
  const name = attr.name, namespaceURI = attr.namespaceURI, attrValue = attr.value;
@@ -2217,11 +2220,7 @@ function createDOMPurify() {
2217
2220
  value = SANITIZE_NAMED_PROPS_PREFIX + value;
2218
2221
  recreatedNamedProp = true;
2219
2222
  }
2220
- if (SAFE_FOR_XML && regExpTest(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i, value)) {
2221
- _removeAttribute(name, currentNode, attr);
2222
- continue;
2223
- }
2224
- if (lcName === "attributename" && stringMatch(value, "href")) {
2223
+ if (_isUnsafeAttributeValue(name, value)) {
2225
2224
  _removeAttribute(name, currentNode, attr);
2226
2225
  continue;
2227
2226
  }
@@ -2248,6 +2247,18 @@ function createDOMPurify() {
2248
2247
  _handleHookDetachedNode(currentNode, root);
2249
2248
  };
2250
2249
  /**
2250
+ * Sanitizes one node: the node itself, its attributes and, for a
2251
+ * template, its content.
2252
+ *
2253
+ * @param node the node to sanitize
2254
+ * @param root the current walk root
2255
+ */
2256
+ const _sanitizeNode = function _sanitizeNode(node, root) {
2257
+ _sanitizeElements(node, root);
2258
+ _sanitizeAttributes(node, root);
2259
+ if (_isDocumentFragment(node.content)) _sanitizeShadowDOM2(node.content);
2260
+ };
2261
+ /**
2251
2262
  * _sanitizeShadowDOM
2252
2263
  *
2253
2264
  * @param fragment to iterate over recursively
@@ -2258,9 +2269,7 @@ function createDOMPurify() {
2258
2269
  _executeHooks(hooks.beforeSanitizeShadowDOM, fragment, null);
2259
2270
  while (shadowNode = shadowIterator.nextNode()) {
2260
2271
  _executeHooks(hooks.uponSanitizeShadowNode, shadowNode, null);
2261
- _sanitizeElements(shadowNode, fragment);
2262
- _sanitizeAttributes(shadowNode, fragment);
2263
- if (_isDocumentFragment(shadowNode.content)) _sanitizeShadowDOM2(shadowNode.content);
2272
+ _sanitizeNode(shadowNode, fragment);
2264
2273
  if (_readNodeType(shadowNode) === NODE_TYPE.element) {
2265
2274
  const innerSr = getShadowRoot(shadowNode);
2266
2275
  if (_isDocumentFragment(innerSr)) {
@@ -2269,24 +2278,13 @@ function createDOMPurify() {
2269
2278
  }
2270
2279
  }
2271
2280
  }
2281
+ if (SAFE_FOR_TEMPLATES) _scrubOwnCharacterData(fragment);
2272
2282
  _executeHooks(hooks.afterSanitizeShadowDOM, fragment, null);
2273
2283
  };
2274
2284
  /**
2275
- * _sanitizeAttachedShadowRoots
2276
- *
2277
- * Walks `root` and feeds every attached shadow root we encounter into
2278
- * the existing _sanitizeShadowDOM pipeline. The default node iterator
2279
- * does not descend into shadow trees, so nodes inside an attached
2280
- * shadow root would otherwise be skipped entirely.
2281
- *
2282
- * Two real input paths put attached shadow roots in front of us:
2283
- * 1. IN_PLACE on a DOM node that already has shadow roots attached.
2284
- * 2. DOM-node input where importNode(dirty, true) deep-clones the
2285
- * shadow root because it was created with `clonable: true`.
2286
- *
2287
- * This pass runs once, up front, so the main iteration loop (and the
2288
- * existing _sanitizeShadowDOM template-content recursion) stay
2289
- * untouched — string-input paths are not affected.
2285
+ * Sanitizes every attached shadow root under `root`, since the node
2286
+ * iterator does not enter shadow trees. Needed for IN_PLACE input and for
2287
+ * DOM input whose clonable shadow roots were copied by importNode().
2290
2288
  *
2291
2289
  * @param root the subtree root to walk for attached shadow roots
2292
2290
  */
@@ -2347,10 +2345,10 @@ function createDOMPurify() {
2347
2345
  ALLOWED_TAGS = SET_CONFIG_ALLOWED_TAGS;
2348
2346
  ALLOWED_ATTR = SET_CONFIG_ALLOWED_ATTR;
2349
2347
  } else _parseConfig(cfg);
2350
- if (hooks.uponSanitizeElement.length > 0 || hooks.uponSanitizeAttribute.length > 0) ALLOWED_TAGS = clone(ALLOWED_TAGS);
2351
- if (hooks.uponSanitizeAttribute.length > 0) ALLOWED_ATTR = clone(ALLOWED_ATTR);
2352
2348
  DOMPurify.removed = [];
2353
2349
  const inPlace = IN_PLACE && typeof dirty !== "string" && _isNode(dirty);
2350
+ let inPlaceNodes = [];
2351
+ const outerVisited = IN_PLACE_VISITED;
2354
2352
  if (inPlace) {
2355
2353
  _neutralizePatchLinkage(dirty);
2356
2354
  const nn = _readNodeName(dirty);
@@ -2365,12 +2363,8 @@ function createDOMPurify() {
2365
2363
  _neutralizeRoot(dirty);
2366
2364
  throw typeErrorCreate("root node is clobbered and cannot be sanitized in-place");
2367
2365
  }
2368
- try {
2369
- _sanitizeAttachedShadowRoots(dirty);
2370
- } catch (error) {
2371
- _neutralizeRoot(dirty);
2372
- throw error;
2373
- }
2366
+ inPlaceNodes = _collectLiveNodes(dirty);
2367
+ IN_PLACE_VISITED = setCreate();
2374
2368
  } else if (_isNode(dirty)) {
2375
2369
  body = _initDocument("<!---->");
2376
2370
  importedNode = body.ownerDocument.importNode(dirty, true);
@@ -2379,37 +2373,28 @@ function createDOMPurify() {
2379
2373
  else body.appendChild(importedNode);
2380
2374
  _sanitizeAttachedShadowRoots(body);
2381
2375
  } else {
2382
- if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT && dirty.indexOf("<") === -1) return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? _createTrustedHTML(dirty) : dirty;
2376
+ if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT && dirty.indexOf("<") === -1) return _signOutput(dirty);
2383
2377
  body = _initDocument(dirty);
2384
2378
  if (!body) return RETURN_DOM ? null : RETURN_TRUSTED_TYPE ? emptyHTML : "";
2385
2379
  }
2386
2380
  if (body && FORCE_BODY) _forceRemove(body.firstChild);
2387
2381
  const walkRoot = inPlace ? dirty : body;
2388
2382
  try {
2383
+ if (inPlace) _sanitizeAttachedShadowRoots(dirty);
2389
2384
  const nodeIterator = _createNodeIterator(walkRoot);
2390
- while (currentNode = nodeIterator.nextNode()) {
2391
- _sanitizeElements(currentNode, walkRoot);
2392
- _sanitizeAttributes(currentNode, walkRoot);
2393
- if (_isDocumentFragment(currentNode.content)) _sanitizeShadowDOM2(currentNode.content);
2394
- }
2385
+ while (currentNode = nodeIterator.nextNode()) _sanitizeNode(currentNode, walkRoot);
2386
+ if (inPlace) _sanitizeUnvisitedNodes(dirty, inPlaceNodes);
2395
2387
  } catch (error) {
2396
2388
  if (inPlace) {
2397
2389
  _neutralizeRoot(dirty);
2398
- arrayForEach(DOMPurify.removed, (entry) => {
2399
- if (entry.element) _neutralizeSubtree(entry.element);
2400
- });
2390
+ _neutralizeDiscarded(dirty, inPlaceNodes);
2401
2391
  }
2402
2392
  throw error;
2393
+ } finally {
2394
+ IN_PLACE_VISITED = outerVisited;
2403
2395
  }
2404
2396
  if (inPlace) {
2405
- let rootWasRemoved = false;
2406
- arrayForEach(DOMPurify.removed, (entry) => {
2407
- if (entry.element) {
2408
- if (entry.element === dirty) rootWasRemoved = true;
2409
- _neutralizeSubtree(entry.element);
2410
- }
2411
- });
2412
- if (rootWasRemoved) throw typeErrorCreate("a node selected for removal could not be safely returned; refusing to sanitize in place");
2397
+ if (_neutralizeDiscarded(dirty, inPlaceNodes)) throw typeErrorCreate("a node selected for removal could not be safely returned; refusing to sanitize in place");
2413
2398
  if (SAFE_FOR_TEMPLATES) _scrubTemplateExpressions2(dirty);
2414
2399
  return dirty;
2415
2400
  }
@@ -2422,10 +2407,14 @@ function createDOMPurify() {
2422
2407
  if (ALLOWED_ATTR.shadowroot || ALLOWED_ATTR.shadowrootmode) returnNode = importNode.call(originalDocument, returnNode, true);
2423
2408
  return returnNode;
2424
2409
  }
2425
- let serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML;
2410
+ const serialize = () => WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML;
2411
+ let serializedHTML = serialize();
2412
+ if (SAFE_FOR_TEMPLATES && regExpTest(TMPL_MARKER_SERIALIZED, serializedHTML)) {
2413
+ _scrubOwnCharacterData(body);
2414
+ serializedHTML = serialize();
2415
+ }
2426
2416
  if (WHOLE_DOCUMENT && ALLOWED_TAGS["!doctype"] && body.ownerDocument && body.ownerDocument.doctype && body.ownerDocument.doctype.name && regExpTest(DOCTYPE_NAME, body.ownerDocument.doctype.name)) serializedHTML = "<!DOCTYPE " + body.ownerDocument.doctype.name + ">\n" + serializedHTML;
2427
- if (SAFE_FOR_TEMPLATES) serializedHTML = _stripTemplateExpressions(serializedHTML);
2428
- return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? _createTrustedHTML(serializedHTML) : serializedHTML;
2417
+ return _signOutput(serializedHTML);
2429
2418
  };
2430
2419
  DOMPurify.setConfig = function() {
2431
2420
  let cfg = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
@@ -2446,6 +2435,7 @@ function createDOMPurify() {
2446
2435
  if (!CONFIG) _parseConfig({});
2447
2436
  const lcTag = transformCaseFunc(tag);
2448
2437
  const lcName = transformCaseFunc(attr);
2438
+ if (typeof value === "string" && (_isUnsafeAttributeValue(attr, value) || !ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(SELF_CLOSING_TAG, value))) return false;
2449
2439
  return _isValidAttribute(lcTag, lcName, value);
2450
2440
  };
2451
2441
  DOMPurify.addHook = function(entryPoint, hookFunction) {