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