@knime/product-features 1.1.3 → 1.2.0

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