@bigbinary/neeto-message-templates-frontend 0.2.0 → 0.3.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.
package/dist/index.js CHANGED
@@ -1,17 +1,17 @@
1
1
  import React, { useContext, useState, useRef, useEffect } from 'react';
2
- import { isNotEmpty, noop as noop$1, findBy, capitalize as capitalize$1, nullSafe } from '@bigbinary/neeto-commons-frontend/pure';
2
+ import { isNotEmpty, noop as noop$1, renameKeys, findBy, capitalize as capitalize$1, nullSafe } from '@bigbinary/neeto-commons-frontend/pure';
3
3
  import { buildFiltersFromURL, Bar } from '@bigbinary/neeto-filters-frontend';
4
4
  import Container from '@bigbinary/neeto-molecules/Container';
5
5
  import NeetoHeader from '@bigbinary/neeto-molecules/Header';
6
6
  import SubHeader from '@bigbinary/neeto-molecules/SubHeader';
7
7
  import { Dropdown, Typography, Button, Pane, Table, NoData, Alert, Select, Textarea } from '@bigbinary/neetoui';
8
8
  import { isEmpty, prop, equals, includes, pick, omit, assoc, mergeAll, pluck } from 'ramda';
9
- import { QueryClient, QueryCache, QueryClientProvider, useQuery } from 'react-query';
10
- import { ReactQueryDevtools } from 'react-query/devtools';
11
9
  import { MenuHorizontal } from '@bigbinary/neeto-icons';
10
+ import { DEFAULT_PAGE_INDEX } from '@bigbinary/neeto-commons-frontend/constants';
12
11
  import { useMutationWithInvalidation, withImmutableActions } from '@bigbinary/neeto-commons-frontend/react-utils';
12
+ import { useQuery } from 'react-query';
13
13
  import axios from 'axios';
14
- import { create as create$1 } from 'zustand';
14
+ import { create } from 'zustand';
15
15
  import { FormikEditor } from '@bigbinary/neeto-editor';
16
16
  import { Input, Form as Form$1, Select as Select$1, Button as Button$1 } from '@bigbinary/neetoui/formik';
17
17
  import { isPhoneNumberValid } from '@bigbinary/neeto-molecules/PhoneNumber';
@@ -19,1599 +19,6 @@ import * as yup from 'yup';
19
19
  import { useFormikContext } from 'formik';
20
20
  import TableWrapper from '@bigbinary/neeto-molecules/TableWrapper';
21
21
 
22
- /*! @license DOMPurify 3.0.2 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.0.2/LICENSE */
23
-
24
- const {
25
- entries,
26
- setPrototypeOf,
27
- isFrozen,
28
- getPrototypeOf,
29
- getOwnPropertyDescriptor
30
- } = Object;
31
- let {
32
- freeze,
33
- seal,
34
- create
35
- } = Object; // eslint-disable-line import/no-mutable-exports
36
-
37
- let {
38
- apply,
39
- construct
40
- } = typeof Reflect !== 'undefined' && Reflect;
41
-
42
- if (!apply) {
43
- apply = function apply(fun, thisValue, args) {
44
- return fun.apply(thisValue, args);
45
- };
46
- }
47
-
48
- if (!freeze) {
49
- freeze = function freeze(x) {
50
- return x;
51
- };
52
- }
53
-
54
- if (!seal) {
55
- seal = function seal(x) {
56
- return x;
57
- };
58
- }
59
-
60
- if (!construct) {
61
- construct = function construct(Func, args) {
62
- return new Func(...args);
63
- };
64
- }
65
-
66
- const arrayForEach = unapply(Array.prototype.forEach);
67
- const arrayPop = unapply(Array.prototype.pop);
68
- const arrayPush = unapply(Array.prototype.push);
69
- const stringToLowerCase = unapply(String.prototype.toLowerCase);
70
- const stringToString = unapply(String.prototype.toString);
71
- const stringMatch = unapply(String.prototype.match);
72
- const stringReplace = unapply(String.prototype.replace);
73
- const stringIndexOf = unapply(String.prototype.indexOf);
74
- const stringTrim = unapply(String.prototype.trim);
75
- const regExpTest = unapply(RegExp.prototype.test);
76
- const typeErrorCreate = unconstruct(TypeError);
77
- function unapply(func) {
78
- return function (thisArg) {
79
- for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
80
- args[_key - 1] = arguments[_key];
81
- }
82
-
83
- return apply(func, thisArg, args);
84
- };
85
- }
86
- function unconstruct(func) {
87
- return function () {
88
- for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
89
- args[_key2] = arguments[_key2];
90
- }
91
-
92
- return construct(func, args);
93
- };
94
- }
95
- /* Add properties to a lookup table */
96
-
97
- function addToSet(set, array, transformCaseFunc) {
98
- transformCaseFunc = transformCaseFunc ? transformCaseFunc : stringToLowerCase;
99
-
100
- if (setPrototypeOf) {
101
- // Make 'in' and truthy checks like Boolean(set.constructor)
102
- // independent of any properties defined on Object.prototype.
103
- // Prevent prototype setters from intercepting set as a this value.
104
- setPrototypeOf(set, null);
105
- }
106
-
107
- let l = array.length;
108
-
109
- while (l--) {
110
- let element = array[l];
111
-
112
- if (typeof element === 'string') {
113
- const lcElement = transformCaseFunc(element);
114
-
115
- if (lcElement !== element) {
116
- // Config presets (e.g. tags.js, attrs.js) are immutable.
117
- if (!isFrozen(array)) {
118
- array[l] = lcElement;
119
- }
120
-
121
- element = lcElement;
122
- }
123
- }
124
-
125
- set[element] = true;
126
- }
127
-
128
- return set;
129
- }
130
- /* Shallow clone an object */
131
-
132
- function clone(object) {
133
- const newObject = create(null);
134
-
135
- for (const [property, value] of entries(object)) {
136
- newObject[property] = value;
137
- }
138
-
139
- return newObject;
140
- }
141
- /* This method automatically checks if the prop is function
142
- * or getter and behaves accordingly. */
143
-
144
- function lookupGetter(object, prop) {
145
- while (object !== null) {
146
- const desc = getOwnPropertyDescriptor(object, prop);
147
-
148
- if (desc) {
149
- if (desc.get) {
150
- return unapply(desc.get);
151
- }
152
-
153
- if (typeof desc.value === 'function') {
154
- return unapply(desc.value);
155
- }
156
- }
157
-
158
- object = getPrototypeOf(object);
159
- }
160
-
161
- function fallbackValue(element) {
162
- console.warn('fallback value for', element);
163
- return null;
164
- }
165
-
166
- return fallbackValue;
167
- }
168
-
169
- 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', 'section', 'select', 'shadow', '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']); // SVG
170
-
171
- const svg$1 = freeze(['svg', 'a', 'altglyph', 'altglyphdef', 'altglyphitem', 'animatecolor', 'animatemotion', 'animatetransform', 'circle', 'clippath', 'defs', 'desc', 'ellipse', 'filter', 'font', 'g', 'glyph', 'glyphref', 'hkern', 'image', 'line', 'lineargradient', 'marker', 'mask', 'metadata', 'mpath', 'path', 'pattern', 'polygon', 'polyline', 'radialgradient', 'rect', 'stop', 'style', 'switch', 'symbol', 'text', 'textpath', 'title', 'tref', 'tspan', 'view', 'vkern']);
172
- const svgFilters = freeze(['feBlend', 'feColorMatrix', 'feComponentTransfer', 'feComposite', 'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap', 'feDistantLight', 'feFlood', 'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR', 'feGaussianBlur', 'feImage', 'feMerge', 'feMergeNode', 'feMorphology', 'feOffset', 'fePointLight', 'feSpecularLighting', 'feSpotLight', 'feTile', 'feTurbulence']); // List of SVG elements that are disallowed by default.
173
- // We still need to know them so that we can do namespace
174
- // checks properly in case one wants to add them to
175
- // allow-list.
176
-
177
- const svgDisallowed = freeze(['animate', 'color-profile', 'cursor', 'discard', 'fedropshadow', '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']);
178
- 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']); // Similarly to SVG, we want to know all MathML elements,
179
- // even those that we disallow by default.
180
-
181
- const mathMlDisallowed = freeze(['maction', 'maligngroup', 'malignmark', 'mlongdiv', 'mscarries', 'mscarry', 'msgroup', 'mstack', 'msline', 'msrow', 'semantics', 'annotation', 'annotation-xml', 'mprescripts', 'none']);
182
- const text = freeze(['#text']);
183
-
184
- 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', 'face', 'for', 'headers', 'height', 'hidden', 'high', 'href', 'hreflang', 'id', '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', 'pattern', 'placeholder', 'playsinline', 'poster', 'preload', 'pubdate', 'radiogroup', 'readonly', 'rel', 'required', 'rev', 'reversed', 'role', 'rows', 'rowspan', 'spellcheck', 'scope', 'selected', 'shape', 'size', 'sizes', 'span', 'srclang', 'start', 'src', 'srcset', 'step', 'style', 'summary', 'tabindex', 'title', 'translate', 'type', 'usemap', 'valign', 'value', 'width', 'xmlns', 'slot']);
185
- const svg = freeze(['accent-height', 'accumulate', 'additive', 'alignment-baseline', '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', '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', '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', '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', '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', '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']);
186
- 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']);
187
- const xml = freeze(['xlink:href', 'xml:id', 'xlink:title', 'xml:space', 'xmlns:xlink']);
188
-
189
- const MUSTACHE_EXPR = seal(/\{\{[\w\W]*|[\w\W]*\}\}/gm); // Specify template detection regex for SAFE_FOR_TEMPLATES mode
190
-
191
- const ERB_EXPR = seal(/<%[\w\W]*|[\w\W]*%>/gm);
192
- const TMPLIT_EXPR = seal(/\${[\w\W]*}/gm);
193
- const DATA_ATTR = seal(/^data-[\-\w.\u00B7-\uFFFF]/); // eslint-disable-line no-useless-escape
194
-
195
- const ARIA_ATTR = seal(/^aria-[\-\w]+$/); // eslint-disable-line no-useless-escape
196
-
197
- const IS_ALLOWED_URI = seal(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i // eslint-disable-line no-useless-escape
198
- );
199
- const IS_SCRIPT_OR_DATA = seal(/^(?:\w+script|data):/i);
200
- const ATTR_WHITESPACE = seal(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g // eslint-disable-line no-control-regex
201
- );
202
- const DOCTYPE_NAME = seal(/^html$/i);
203
-
204
- var EXPRESSIONS = /*#__PURE__*/Object.freeze({
205
- __proto__: null,
206
- MUSTACHE_EXPR: MUSTACHE_EXPR,
207
- ERB_EXPR: ERB_EXPR,
208
- TMPLIT_EXPR: TMPLIT_EXPR,
209
- DATA_ATTR: DATA_ATTR,
210
- ARIA_ATTR: ARIA_ATTR,
211
- IS_ALLOWED_URI: IS_ALLOWED_URI,
212
- IS_SCRIPT_OR_DATA: IS_SCRIPT_OR_DATA,
213
- ATTR_WHITESPACE: ATTR_WHITESPACE,
214
- DOCTYPE_NAME: DOCTYPE_NAME
215
- });
216
-
217
- const getGlobal = () => typeof window === 'undefined' ? null : window;
218
- /**
219
- * Creates a no-op policy for internal use only.
220
- * Don't export this function outside this module!
221
- * @param {?TrustedTypePolicyFactory} trustedTypes The policy factory.
222
- * @param {Document} document The document object (to determine policy name suffix)
223
- * @return {?TrustedTypePolicy} The policy created (or null, if Trusted Types
224
- * are not supported).
225
- */
226
-
227
-
228
- const _createTrustedTypesPolicy = function _createTrustedTypesPolicy(trustedTypes, document) {
229
- if (typeof trustedTypes !== 'object' || typeof trustedTypes.createPolicy !== 'function') {
230
- return null;
231
- } // Allow the callers to control the unique policy name
232
- // by adding a data-tt-policy-suffix to the script element with the DOMPurify.
233
- // Policy creation with duplicate names throws in Trusted Types.
234
-
235
-
236
- let suffix = null;
237
- const ATTR_NAME = 'data-tt-policy-suffix';
238
-
239
- if (document.currentScript && document.currentScript.hasAttribute(ATTR_NAME)) {
240
- suffix = document.currentScript.getAttribute(ATTR_NAME);
241
- }
242
-
243
- const policyName = 'dompurify' + (suffix ? '#' + suffix : '');
244
-
245
- try {
246
- return trustedTypes.createPolicy(policyName, {
247
- createHTML(html) {
248
- return html;
249
- },
250
-
251
- createScriptURL(scriptUrl) {
252
- return scriptUrl;
253
- }
254
-
255
- });
256
- } catch (_) {
257
- // Policy creation failed (most likely another DOMPurify script has
258
- // already run). Skip creating the policy, as this will only cause errors
259
- // if TT are enforced.
260
- console.warn('TrustedTypes policy ' + policyName + ' could not be created.');
261
- return null;
262
- }
263
- };
264
-
265
- function createDOMPurify() {
266
- let window = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getGlobal();
267
-
268
- const DOMPurify = root => createDOMPurify(root);
269
- /**
270
- * Version label, exposed for easier checks
271
- * if DOMPurify is up to date or not
272
- */
273
-
274
-
275
- DOMPurify.version = '3.0.2';
276
- /**
277
- * Array of elements that DOMPurify removed during sanitation.
278
- * Empty if nothing was removed.
279
- */
280
-
281
- DOMPurify.removed = [];
282
-
283
- if (!window || !window.document || window.document.nodeType !== 9) {
284
- // Not running in a browser, provide a factory function
285
- // so that you can pass your own Window
286
- DOMPurify.isSupported = false;
287
- return DOMPurify;
288
- }
289
-
290
- const originalDocument = window.document;
291
- let {
292
- document
293
- } = window;
294
- const {
295
- DocumentFragment,
296
- HTMLTemplateElement,
297
- Node,
298
- Element,
299
- NodeFilter,
300
- NamedNodeMap = window.NamedNodeMap || window.MozNamedAttrMap,
301
- HTMLFormElement,
302
- DOMParser,
303
- trustedTypes
304
- } = window;
305
- const ElementPrototype = Element.prototype;
306
- const cloneNode = lookupGetter(ElementPrototype, 'cloneNode');
307
- const getNextSibling = lookupGetter(ElementPrototype, 'nextSibling');
308
- const getChildNodes = lookupGetter(ElementPrototype, 'childNodes');
309
- const getParentNode = lookupGetter(ElementPrototype, 'parentNode'); // As per issue #47, the web-components registry is inherited by a
310
- // new document created via createHTMLDocument. As per the spec
311
- // (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-registries)
312
- // a new empty registry is used when creating a template contents owner
313
- // document, so we use that as our parent document to ensure nothing
314
- // is inherited.
315
-
316
- if (typeof HTMLTemplateElement === 'function') {
317
- const template = document.createElement('template');
318
-
319
- if (template.content && template.content.ownerDocument) {
320
- document = template.content.ownerDocument;
321
- }
322
- }
323
-
324
- const trustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, originalDocument);
325
-
326
- const emptyHTML = trustedTypesPolicy ? trustedTypesPolicy.createHTML('') : '';
327
- const {
328
- implementation,
329
- createNodeIterator,
330
- createDocumentFragment,
331
- getElementsByTagName
332
- } = document;
333
- const {
334
- importNode
335
- } = originalDocument;
336
- let hooks = {};
337
- /**
338
- * Expose whether this browser supports running the full DOMPurify.
339
- */
340
-
341
- DOMPurify.isSupported = typeof entries === 'function' && typeof getParentNode === 'function' && implementation && typeof implementation.createHTMLDocument !== 'undefined';
342
- const {
343
- MUSTACHE_EXPR,
344
- ERB_EXPR,
345
- TMPLIT_EXPR,
346
- DATA_ATTR,
347
- ARIA_ATTR,
348
- IS_SCRIPT_OR_DATA,
349
- ATTR_WHITESPACE
350
- } = EXPRESSIONS;
351
- let {
352
- IS_ALLOWED_URI: IS_ALLOWED_URI$1
353
- } = EXPRESSIONS;
354
- /**
355
- * We consider the elements and attributes below to be safe. Ideally
356
- * don't add any new ones but feel free to remove unwanted ones.
357
- */
358
-
359
- /* allowed element names */
360
-
361
- let ALLOWED_TAGS = null;
362
- const DEFAULT_ALLOWED_TAGS = addToSet({}, [...html$1, ...svg$1, ...svgFilters, ...mathMl$1, ...text]);
363
- /* Allowed attribute names */
364
-
365
- let ALLOWED_ATTR = null;
366
- const DEFAULT_ALLOWED_ATTR = addToSet({}, [...html, ...svg, ...mathMl, ...xml]);
367
- /*
368
- * Configure how DOMPUrify should handle custom elements and their attributes as well as customized built-in elements.
369
- * @property {RegExp|Function|null} tagNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any custom elements)
370
- * @property {RegExp|Function|null} attributeNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any attributes not on the allow list)
371
- * @property {boolean} allowCustomizedBuiltInElements allow custom elements derived from built-ins if they pass CUSTOM_ELEMENT_HANDLING.tagNameCheck. Default: `false`.
372
- */
373
-
374
- let CUSTOM_ELEMENT_HANDLING = Object.seal(Object.create(null, {
375
- tagNameCheck: {
376
- writable: true,
377
- configurable: false,
378
- enumerable: true,
379
- value: null
380
- },
381
- attributeNameCheck: {
382
- writable: true,
383
- configurable: false,
384
- enumerable: true,
385
- value: null
386
- },
387
- allowCustomizedBuiltInElements: {
388
- writable: true,
389
- configurable: false,
390
- enumerable: true,
391
- value: false
392
- }
393
- }));
394
- /* Explicitly forbidden tags (overrides ALLOWED_TAGS/ADD_TAGS) */
395
-
396
- let FORBID_TAGS = null;
397
- /* Explicitly forbidden attributes (overrides ALLOWED_ATTR/ADD_ATTR) */
398
-
399
- let FORBID_ATTR = null;
400
- /* Decide if ARIA attributes are okay */
401
-
402
- let ALLOW_ARIA_ATTR = true;
403
- /* Decide if custom data attributes are okay */
404
-
405
- let ALLOW_DATA_ATTR = true;
406
- /* Decide if unknown protocols are okay */
407
-
408
- let ALLOW_UNKNOWN_PROTOCOLS = false;
409
- /* Decide if self-closing tags in attributes are allowed.
410
- * Usually removed due to a mXSS issue in jQuery 3.0 */
411
-
412
- let ALLOW_SELF_CLOSE_IN_ATTR = true;
413
- /* Output should be safe for common template engines.
414
- * This means, DOMPurify removes data attributes, mustaches and ERB
415
- */
416
-
417
- let SAFE_FOR_TEMPLATES = false;
418
- /* Decide if document with <html>... should be returned */
419
-
420
- let WHOLE_DOCUMENT = false;
421
- /* Track whether config is already set on this instance of DOMPurify. */
422
-
423
- let SET_CONFIG = false;
424
- /* Decide if all elements (e.g. style, script) must be children of
425
- * document.body. By default, browsers might move them to document.head */
426
-
427
- let FORCE_BODY = false;
428
- /* Decide if a DOM `HTMLBodyElement` should be returned, instead of a html
429
- * string (or a TrustedHTML object if Trusted Types are supported).
430
- * If `WHOLE_DOCUMENT` is enabled a `HTMLHtmlElement` will be returned instead
431
- */
432
-
433
- let RETURN_DOM = false;
434
- /* Decide if a DOM `DocumentFragment` should be returned, instead of a html
435
- * string (or a TrustedHTML object if Trusted Types are supported) */
436
-
437
- let RETURN_DOM_FRAGMENT = false;
438
- /* Try to return a Trusted Type object instead of a string, return a string in
439
- * case Trusted Types are not supported */
440
-
441
- let RETURN_TRUSTED_TYPE = false;
442
- /* Output should be free from DOM clobbering attacks?
443
- * This sanitizes markups named with colliding, clobberable built-in DOM APIs.
444
- */
445
-
446
- let SANITIZE_DOM = true;
447
- /* Achieve full DOM Clobbering protection by isolating the namespace of named
448
- * properties and JS variables, mitigating attacks that abuse the HTML/DOM spec rules.
449
- *
450
- * HTML/DOM spec rules that enable DOM Clobbering:
451
- * - Named Access on Window (§7.3.3)
452
- * - DOM Tree Accessors (§3.1.5)
453
- * - Form Element Parent-Child Relations (§4.10.3)
454
- * - Iframe srcdoc / Nested WindowProxies (§4.8.5)
455
- * - HTMLCollection (§4.2.10.2)
456
- *
457
- * Namespace isolation is implemented by prefixing `id` and `name` attributes
458
- * with a constant string, i.e., `user-content-`
459
- */
460
-
461
- let SANITIZE_NAMED_PROPS = false;
462
- const SANITIZE_NAMED_PROPS_PREFIX = 'user-content-';
463
- /* Keep element content when removing element? */
464
-
465
- let KEEP_CONTENT = true;
466
- /* If a `Node` is passed to sanitize(), then performs sanitization in-place instead
467
- * of importing it into a new Document and returning a sanitized copy */
468
-
469
- let IN_PLACE = false;
470
- /* Allow usage of profiles like html, svg and mathMl */
471
-
472
- let USE_PROFILES = {};
473
- /* Tags to ignore content of when KEEP_CONTENT is true */
474
-
475
- let FORBID_CONTENTS = null;
476
- 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']);
477
- /* Tags that are safe for data: URIs */
478
-
479
- let DATA_URI_TAGS = null;
480
- const DEFAULT_DATA_URI_TAGS = addToSet({}, ['audio', 'video', 'img', 'source', 'image', 'track']);
481
- /* Attributes safe for values like "javascript:" */
482
-
483
- let URI_SAFE_ATTRIBUTES = null;
484
- const DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, ['alt', 'class', 'for', 'id', 'label', 'name', 'pattern', 'placeholder', 'role', 'summary', 'title', 'value', 'style', 'xmlns']);
485
- const MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';
486
- const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';
487
- const HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';
488
- /* Document namespace */
489
-
490
- let NAMESPACE = HTML_NAMESPACE;
491
- let IS_EMPTY_INPUT = false;
492
- /* Allowed XHTML+XML namespaces */
493
-
494
- let ALLOWED_NAMESPACES = null;
495
- const DEFAULT_ALLOWED_NAMESPACES = addToSet({}, [MATHML_NAMESPACE, SVG_NAMESPACE, HTML_NAMESPACE], stringToString);
496
- /* Parsing of strict XHTML documents */
497
-
498
- let PARSER_MEDIA_TYPE;
499
- const SUPPORTED_PARSER_MEDIA_TYPES = ['application/xhtml+xml', 'text/html'];
500
- const DEFAULT_PARSER_MEDIA_TYPE = 'text/html';
501
- let transformCaseFunc;
502
- /* Keep a reference to config to pass to hooks */
503
-
504
- let CONFIG = null;
505
- /* Ideally, do not touch anything below this line */
506
-
507
- /* ______________________________________________ */
508
-
509
- const formElement = document.createElement('form');
510
-
511
- const isRegexOrFunction = function isRegexOrFunction(testValue) {
512
- return testValue instanceof RegExp || testValue instanceof Function;
513
- };
514
- /**
515
- * _parseConfig
516
- *
517
- * @param {Object} cfg optional config literal
518
- */
519
- // eslint-disable-next-line complexity
520
-
521
-
522
- const _parseConfig = function _parseConfig(cfg) {
523
- if (CONFIG && CONFIG === cfg) {
524
- return;
525
- }
526
- /* Shield configuration object from tampering */
527
-
528
-
529
- if (!cfg || typeof cfg !== 'object') {
530
- cfg = {};
531
- }
532
- /* Shield configuration object from prototype pollution */
533
-
534
-
535
- cfg = clone(cfg);
536
- PARSER_MEDIA_TYPE = // eslint-disable-next-line unicorn/prefer-includes
537
- SUPPORTED_PARSER_MEDIA_TYPES.indexOf(cfg.PARSER_MEDIA_TYPE) === -1 ? PARSER_MEDIA_TYPE = DEFAULT_PARSER_MEDIA_TYPE : PARSER_MEDIA_TYPE = cfg.PARSER_MEDIA_TYPE; // HTML tags and attributes are not case-sensitive, converting to lowercase. Keeping XHTML as is.
538
-
539
- transformCaseFunc = PARSER_MEDIA_TYPE === 'application/xhtml+xml' ? stringToString : stringToLowerCase;
540
- /* Set configuration parameters */
541
-
542
- ALLOWED_TAGS = 'ALLOWED_TAGS' in cfg ? addToSet({}, cfg.ALLOWED_TAGS, transformCaseFunc) : DEFAULT_ALLOWED_TAGS;
543
- ALLOWED_ATTR = 'ALLOWED_ATTR' in cfg ? addToSet({}, cfg.ALLOWED_ATTR, transformCaseFunc) : DEFAULT_ALLOWED_ATTR;
544
- ALLOWED_NAMESPACES = 'ALLOWED_NAMESPACES' in cfg ? addToSet({}, cfg.ALLOWED_NAMESPACES, stringToString) : DEFAULT_ALLOWED_NAMESPACES;
545
- URI_SAFE_ATTRIBUTES = 'ADD_URI_SAFE_ATTR' in cfg ? addToSet(clone(DEFAULT_URI_SAFE_ATTRIBUTES), // eslint-disable-line indent
546
- cfg.ADD_URI_SAFE_ATTR, // eslint-disable-line indent
547
- transformCaseFunc // eslint-disable-line indent
548
- ) // eslint-disable-line indent
549
- : DEFAULT_URI_SAFE_ATTRIBUTES;
550
- DATA_URI_TAGS = 'ADD_DATA_URI_TAGS' in cfg ? addToSet(clone(DEFAULT_DATA_URI_TAGS), // eslint-disable-line indent
551
- cfg.ADD_DATA_URI_TAGS, // eslint-disable-line indent
552
- transformCaseFunc // eslint-disable-line indent
553
- ) // eslint-disable-line indent
554
- : DEFAULT_DATA_URI_TAGS;
555
- FORBID_CONTENTS = 'FORBID_CONTENTS' in cfg ? addToSet({}, cfg.FORBID_CONTENTS, transformCaseFunc) : DEFAULT_FORBID_CONTENTS;
556
- FORBID_TAGS = 'FORBID_TAGS' in cfg ? addToSet({}, cfg.FORBID_TAGS, transformCaseFunc) : {};
557
- FORBID_ATTR = 'FORBID_ATTR' in cfg ? addToSet({}, cfg.FORBID_ATTR, transformCaseFunc) : {};
558
- USE_PROFILES = 'USE_PROFILES' in cfg ? cfg.USE_PROFILES : false;
559
- ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true
560
-
561
- ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true
562
-
563
- ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; // Default false
564
-
565
- ALLOW_SELF_CLOSE_IN_ATTR = cfg.ALLOW_SELF_CLOSE_IN_ATTR !== false; // Default true
566
-
567
- SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false; // Default false
568
-
569
- WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false; // Default false
570
-
571
- RETURN_DOM = cfg.RETURN_DOM || false; // Default false
572
-
573
- RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false; // Default false
574
-
575
- RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false; // Default false
576
-
577
- FORCE_BODY = cfg.FORCE_BODY || false; // Default false
578
-
579
- SANITIZE_DOM = cfg.SANITIZE_DOM !== false; // Default true
580
-
581
- SANITIZE_NAMED_PROPS = cfg.SANITIZE_NAMED_PROPS || false; // Default false
582
-
583
- KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true
584
-
585
- IN_PLACE = cfg.IN_PLACE || false; // Default false
586
-
587
- IS_ALLOWED_URI$1 = cfg.ALLOWED_URI_REGEXP || IS_ALLOWED_URI;
588
- NAMESPACE = cfg.NAMESPACE || HTML_NAMESPACE;
589
- CUSTOM_ELEMENT_HANDLING = cfg.CUSTOM_ELEMENT_HANDLING || {};
590
-
591
- if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck)) {
592
- CUSTOM_ELEMENT_HANDLING.tagNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck;
593
- }
594
-
595
- if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)) {
596
- CUSTOM_ELEMENT_HANDLING.attributeNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck;
597
- }
598
-
599
- if (cfg.CUSTOM_ELEMENT_HANDLING && typeof cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements === 'boolean') {
600
- CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements;
601
- }
602
-
603
- if (SAFE_FOR_TEMPLATES) {
604
- ALLOW_DATA_ATTR = false;
605
- }
606
-
607
- if (RETURN_DOM_FRAGMENT) {
608
- RETURN_DOM = true;
609
- }
610
- /* Parse profile info */
611
-
612
-
613
- if (USE_PROFILES) {
614
- ALLOWED_TAGS = addToSet({}, [...text]);
615
- ALLOWED_ATTR = [];
616
-
617
- if (USE_PROFILES.html === true) {
618
- addToSet(ALLOWED_TAGS, html$1);
619
- addToSet(ALLOWED_ATTR, html);
620
- }
621
-
622
- if (USE_PROFILES.svg === true) {
623
- addToSet(ALLOWED_TAGS, svg$1);
624
- addToSet(ALLOWED_ATTR, svg);
625
- addToSet(ALLOWED_ATTR, xml);
626
- }
627
-
628
- if (USE_PROFILES.svgFilters === true) {
629
- addToSet(ALLOWED_TAGS, svgFilters);
630
- addToSet(ALLOWED_ATTR, svg);
631
- addToSet(ALLOWED_ATTR, xml);
632
- }
633
-
634
- if (USE_PROFILES.mathMl === true) {
635
- addToSet(ALLOWED_TAGS, mathMl$1);
636
- addToSet(ALLOWED_ATTR, mathMl);
637
- addToSet(ALLOWED_ATTR, xml);
638
- }
639
- }
640
- /* Merge configuration parameters */
641
-
642
-
643
- if (cfg.ADD_TAGS) {
644
- if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) {
645
- ALLOWED_TAGS = clone(ALLOWED_TAGS);
646
- }
647
-
648
- addToSet(ALLOWED_TAGS, cfg.ADD_TAGS, transformCaseFunc);
649
- }
650
-
651
- if (cfg.ADD_ATTR) {
652
- if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) {
653
- ALLOWED_ATTR = clone(ALLOWED_ATTR);
654
- }
655
-
656
- addToSet(ALLOWED_ATTR, cfg.ADD_ATTR, transformCaseFunc);
657
- }
658
-
659
- if (cfg.ADD_URI_SAFE_ATTR) {
660
- addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR, transformCaseFunc);
661
- }
662
-
663
- if (cfg.FORBID_CONTENTS) {
664
- if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {
665
- FORBID_CONTENTS = clone(FORBID_CONTENTS);
666
- }
667
-
668
- addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS, transformCaseFunc);
669
- }
670
- /* Add #text in case KEEP_CONTENT is set to true */
671
-
672
-
673
- if (KEEP_CONTENT) {
674
- ALLOWED_TAGS['#text'] = true;
675
- }
676
- /* Add html, head and body to ALLOWED_TAGS in case WHOLE_DOCUMENT is true */
677
-
678
-
679
- if (WHOLE_DOCUMENT) {
680
- addToSet(ALLOWED_TAGS, ['html', 'head', 'body']);
681
- }
682
- /* Add tbody to ALLOWED_TAGS in case tables are permitted, see #286, #365 */
683
-
684
-
685
- if (ALLOWED_TAGS.table) {
686
- addToSet(ALLOWED_TAGS, ['tbody']);
687
- delete FORBID_TAGS.tbody;
688
- } // Prevent further manipulation of configuration.
689
- // Not available in IE8, Safari 5, etc.
690
-
691
-
692
- if (freeze) {
693
- freeze(cfg);
694
- }
695
-
696
- CONFIG = cfg;
697
- };
698
-
699
- const MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, ['mi', 'mo', 'mn', 'ms', 'mtext']);
700
- const HTML_INTEGRATION_POINTS = addToSet({}, ['foreignobject', 'desc', 'title', 'annotation-xml']); // Certain elements are allowed in both SVG and HTML
701
- // namespace. We need to specify them explicitly
702
- // so that they don't get erroneously deleted from
703
- // HTML namespace.
704
-
705
- const COMMON_SVG_AND_HTML_ELEMENTS = addToSet({}, ['title', 'style', 'font', 'a', 'script']);
706
- /* Keep track of all possible SVG and MathML tags
707
- * so that we can perform the namespace checks
708
- * correctly. */
709
-
710
- const ALL_SVG_TAGS = addToSet({}, svg$1);
711
- addToSet(ALL_SVG_TAGS, svgFilters);
712
- addToSet(ALL_SVG_TAGS, svgDisallowed);
713
- const ALL_MATHML_TAGS = addToSet({}, mathMl$1);
714
- addToSet(ALL_MATHML_TAGS, mathMlDisallowed);
715
- /**
716
- *
717
- *
718
- * @param {Element} element a DOM element whose namespace is being checked
719
- * @returns {boolean} Return false if the element has a
720
- * namespace that a spec-compliant parser would never
721
- * return. Return true otherwise.
722
- */
723
-
724
- const _checkValidNamespace = function _checkValidNamespace(element) {
725
- let parent = getParentNode(element); // In JSDOM, if we're inside shadow DOM, then parentNode
726
- // can be null. We just simulate parent in this case.
727
-
728
- if (!parent || !parent.tagName) {
729
- parent = {
730
- namespaceURI: NAMESPACE,
731
- tagName: 'template'
732
- };
733
- }
734
-
735
- const tagName = stringToLowerCase(element.tagName);
736
- const parentTagName = stringToLowerCase(parent.tagName);
737
-
738
- if (!ALLOWED_NAMESPACES[element.namespaceURI]) {
739
- return false;
740
- }
741
-
742
- if (element.namespaceURI === SVG_NAMESPACE) {
743
- // The only way to switch from HTML namespace to SVG
744
- // is via <svg>. If it happens via any other tag, then
745
- // it should be killed.
746
- if (parent.namespaceURI === HTML_NAMESPACE) {
747
- return tagName === 'svg';
748
- } // The only way to switch from MathML to SVG is via`
749
- // svg if parent is either <annotation-xml> or MathML
750
- // text integration points.
751
-
752
-
753
- if (parent.namespaceURI === MATHML_NAMESPACE) {
754
- return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);
755
- } // We only allow elements that are defined in SVG
756
- // spec. All others are disallowed in SVG namespace.
757
-
758
-
759
- return Boolean(ALL_SVG_TAGS[tagName]);
760
- }
761
-
762
- if (element.namespaceURI === MATHML_NAMESPACE) {
763
- // The only way to switch from HTML namespace to MathML
764
- // is via <math>. If it happens via any other tag, then
765
- // it should be killed.
766
- if (parent.namespaceURI === HTML_NAMESPACE) {
767
- return tagName === 'math';
768
- } // The only way to switch from SVG to MathML is via
769
- // <math> and HTML integration points
770
-
771
-
772
- if (parent.namespaceURI === SVG_NAMESPACE) {
773
- return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName];
774
- } // We only allow elements that are defined in MathML
775
- // spec. All others are disallowed in MathML namespace.
776
-
777
-
778
- return Boolean(ALL_MATHML_TAGS[tagName]);
779
- }
780
-
781
- if (element.namespaceURI === HTML_NAMESPACE) {
782
- // The only way to switch from SVG to HTML is via
783
- // HTML integration points, and from MathML to HTML
784
- // is via MathML text integration points
785
- if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) {
786
- return false;
787
- }
788
-
789
- if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {
790
- return false;
791
- } // We disallow tags that are specific for MathML
792
- // or SVG and should never appear in HTML namespace
793
-
794
-
795
- return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]);
796
- } // For XHTML and XML documents that support custom namespaces
797
-
798
-
799
- if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && ALLOWED_NAMESPACES[element.namespaceURI]) {
800
- return true;
801
- } // The code should never reach this place (this means
802
- // that the element somehow got namespace that is not
803
- // HTML, SVG, MathML or allowed via ALLOWED_NAMESPACES).
804
- // Return false just in case.
805
-
806
-
807
- return false;
808
- };
809
- /**
810
- * _forceRemove
811
- *
812
- * @param {Node} node a DOM node
813
- */
814
-
815
-
816
- const _forceRemove = function _forceRemove(node) {
817
- arrayPush(DOMPurify.removed, {
818
- element: node
819
- });
820
-
821
- try {
822
- // eslint-disable-next-line unicorn/prefer-dom-node-remove
823
- node.parentNode.removeChild(node);
824
- } catch (_) {
825
- node.remove();
826
- }
827
- };
828
- /**
829
- * _removeAttribute
830
- *
831
- * @param {String} name an Attribute name
832
- * @param {Node} node a DOM node
833
- */
834
-
835
-
836
- const _removeAttribute = function _removeAttribute(name, node) {
837
- try {
838
- arrayPush(DOMPurify.removed, {
839
- attribute: node.getAttributeNode(name),
840
- from: node
841
- });
842
- } catch (_) {
843
- arrayPush(DOMPurify.removed, {
844
- attribute: null,
845
- from: node
846
- });
847
- }
848
-
849
- node.removeAttribute(name); // We void attribute values for unremovable "is"" attributes
850
-
851
- if (name === 'is' && !ALLOWED_ATTR[name]) {
852
- if (RETURN_DOM || RETURN_DOM_FRAGMENT) {
853
- try {
854
- _forceRemove(node);
855
- } catch (_) {}
856
- } else {
857
- try {
858
- node.setAttribute(name, '');
859
- } catch (_) {}
860
- }
861
- }
862
- };
863
- /**
864
- * _initDocument
865
- *
866
- * @param {String} dirty a string of dirty markup
867
- * @return {Document} a DOM, filled with the dirty markup
868
- */
869
-
870
-
871
- const _initDocument = function _initDocument(dirty) {
872
- /* Create a HTML document */
873
- let doc;
874
- let leadingWhitespace;
875
-
876
- if (FORCE_BODY) {
877
- dirty = '<remove></remove>' + dirty;
878
- } else {
879
- /* If FORCE_BODY isn't used, leading whitespace needs to be preserved manually */
880
- const matches = stringMatch(dirty, /^[\r\n\t ]+/);
881
- leadingWhitespace = matches && matches[0];
882
- }
883
-
884
- if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && NAMESPACE === HTML_NAMESPACE) {
885
- // Root of XHTML doc must contain xmlns declaration (see https://www.w3.org/TR/xhtml1/normative.html#strict)
886
- dirty = '<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>' + dirty + '</body></html>';
887
- }
888
-
889
- const dirtyPayload = trustedTypesPolicy ? trustedTypesPolicy.createHTML(dirty) : dirty;
890
- /*
891
- * Use the DOMParser API by default, fallback later if needs be
892
- * DOMParser not work for svg when has multiple root element.
893
- */
894
-
895
- if (NAMESPACE === HTML_NAMESPACE) {
896
- try {
897
- doc = new DOMParser().parseFromString(dirtyPayload, PARSER_MEDIA_TYPE);
898
- } catch (_) {}
899
- }
900
- /* Use createHTMLDocument in case DOMParser is not available */
901
-
902
-
903
- if (!doc || !doc.documentElement) {
904
- doc = implementation.createDocument(NAMESPACE, 'template', null);
905
-
906
- try {
907
- doc.documentElement.innerHTML = IS_EMPTY_INPUT ? emptyHTML : dirtyPayload;
908
- } catch (_) {// Syntax error if dirtyPayload is invalid xml
909
- }
910
- }
911
-
912
- const body = doc.body || doc.documentElement;
913
-
914
- if (dirty && leadingWhitespace) {
915
- body.insertBefore(document.createTextNode(leadingWhitespace), body.childNodes[0] || null);
916
- }
917
- /* Work on whole document or just its body */
918
-
919
-
920
- if (NAMESPACE === HTML_NAMESPACE) {
921
- return getElementsByTagName.call(doc, WHOLE_DOCUMENT ? 'html' : 'body')[0];
922
- }
923
-
924
- return WHOLE_DOCUMENT ? doc.documentElement : body;
925
- };
926
- /**
927
- * _createIterator
928
- *
929
- * @param {Document} root document/fragment to create iterator for
930
- * @return {Iterator} iterator instance
931
- */
932
-
933
-
934
- const _createIterator = function _createIterator(root) {
935
- return createNodeIterator.call(root.ownerDocument || root, root, // eslint-disable-next-line no-bitwise
936
- NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT, null, false);
937
- };
938
- /**
939
- * _isClobbered
940
- *
941
- * @param {Node} elm element to check for clobbering attacks
942
- * @return {Boolean} true if clobbered, false if safe
943
- */
944
-
945
-
946
- const _isClobbered = function _isClobbered(elm) {
947
- return elm instanceof HTMLFormElement && (typeof elm.nodeName !== 'string' || typeof elm.textContent !== 'string' || typeof elm.removeChild !== 'function' || !(elm.attributes instanceof NamedNodeMap) || typeof elm.removeAttribute !== 'function' || typeof elm.setAttribute !== 'function' || typeof elm.namespaceURI !== 'string' || typeof elm.insertBefore !== 'function' || typeof elm.hasChildNodes !== 'function');
948
- };
949
- /**
950
- * _isNode
951
- *
952
- * @param {Node} obj object to check whether it's a DOM node
953
- * @return {Boolean} true is object is a DOM node
954
- */
955
-
956
-
957
- const _isNode = function _isNode(object) {
958
- return typeof Node === 'object' ? object instanceof Node : object && typeof object === 'object' && typeof object.nodeType === 'number' && typeof object.nodeName === 'string';
959
- };
960
- /**
961
- * _executeHook
962
- * Execute user configurable hooks
963
- *
964
- * @param {String} entryPoint Name of the hook's entry point
965
- * @param {Node} currentNode node to work on with the hook
966
- * @param {Object} data additional hook parameters
967
- */
968
-
969
-
970
- const _executeHook = function _executeHook(entryPoint, currentNode, data) {
971
- if (!hooks[entryPoint]) {
972
- return;
973
- }
974
-
975
- arrayForEach(hooks[entryPoint], hook => {
976
- hook.call(DOMPurify, currentNode, data, CONFIG);
977
- });
978
- };
979
- /**
980
- * _sanitizeElements
981
- *
982
- * @protect nodeName
983
- * @protect textContent
984
- * @protect removeChild
985
- *
986
- * @param {Node} currentNode to check for permission to exist
987
- * @return {Boolean} true if node was killed, false if left alive
988
- */
989
-
990
-
991
- const _sanitizeElements = function _sanitizeElements(currentNode) {
992
- let content;
993
- /* Execute a hook if present */
994
-
995
- _executeHook('beforeSanitizeElements', currentNode, null);
996
- /* Check if element is clobbered or can clobber */
997
-
998
-
999
- if (_isClobbered(currentNode)) {
1000
- _forceRemove(currentNode);
1001
-
1002
- return true;
1003
- }
1004
- /* Now let's check the element's type and name */
1005
-
1006
-
1007
- const tagName = transformCaseFunc(currentNode.nodeName);
1008
- /* Execute a hook if present */
1009
-
1010
- _executeHook('uponSanitizeElement', currentNode, {
1011
- tagName,
1012
- allowedTags: ALLOWED_TAGS
1013
- });
1014
- /* Detect mXSS attempts abusing namespace confusion */
1015
-
1016
-
1017
- if (currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && (!_isNode(currentNode.content) || !_isNode(currentNode.content.firstElementChild)) && regExpTest(/<[/\w]/g, currentNode.innerHTML) && regExpTest(/<[/\w]/g, currentNode.textContent)) {
1018
- _forceRemove(currentNode);
1019
-
1020
- return true;
1021
- }
1022
- /* Remove element if anything forbids its presence */
1023
-
1024
-
1025
- if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
1026
- /* Check if we have a custom element to handle */
1027
- if (!FORBID_TAGS[tagName] && _basicCustomElementTest(tagName)) {
1028
- if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) return false;
1029
- if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)) return false;
1030
- }
1031
- /* Keep content except for bad-listed elements */
1032
-
1033
-
1034
- if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {
1035
- const parentNode = getParentNode(currentNode) || currentNode.parentNode;
1036
- const childNodes = getChildNodes(currentNode) || currentNode.childNodes;
1037
-
1038
- if (childNodes && parentNode) {
1039
- const childCount = childNodes.length;
1040
-
1041
- for (let i = childCount - 1; i >= 0; --i) {
1042
- parentNode.insertBefore(cloneNode(childNodes[i], true), getNextSibling(currentNode));
1043
- }
1044
- }
1045
- }
1046
-
1047
- _forceRemove(currentNode);
1048
-
1049
- return true;
1050
- }
1051
- /* Check whether element has a valid namespace */
1052
-
1053
-
1054
- if (currentNode instanceof Element && !_checkValidNamespace(currentNode)) {
1055
- _forceRemove(currentNode);
1056
-
1057
- return true;
1058
- }
1059
- /* Make sure that older browsers don't get noscript mXSS */
1060
-
1061
-
1062
- if ((tagName === 'noscript' || tagName === 'noembed') && regExpTest(/<\/no(script|embed)/i, currentNode.innerHTML)) {
1063
- _forceRemove(currentNode);
1064
-
1065
- return true;
1066
- }
1067
- /* Sanitize element content to be template-safe */
1068
-
1069
-
1070
- if (SAFE_FOR_TEMPLATES && currentNode.nodeType === 3) {
1071
- /* Get the element's text content */
1072
- content = currentNode.textContent;
1073
- content = stringReplace(content, MUSTACHE_EXPR, ' ');
1074
- content = stringReplace(content, ERB_EXPR, ' ');
1075
- content = stringReplace(content, TMPLIT_EXPR, ' ');
1076
-
1077
- if (currentNode.textContent !== content) {
1078
- arrayPush(DOMPurify.removed, {
1079
- element: currentNode.cloneNode()
1080
- });
1081
- currentNode.textContent = content;
1082
- }
1083
- }
1084
- /* Execute a hook if present */
1085
-
1086
-
1087
- _executeHook('afterSanitizeElements', currentNode, null);
1088
-
1089
- return false;
1090
- };
1091
- /**
1092
- * _isValidAttribute
1093
- *
1094
- * @param {string} lcTag Lowercase tag name of containing element.
1095
- * @param {string} lcName Lowercase attribute name.
1096
- * @param {string} value Attribute value.
1097
- * @return {Boolean} Returns true if `value` is valid, otherwise false.
1098
- */
1099
- // eslint-disable-next-line complexity
1100
-
1101
-
1102
- const _isValidAttribute = function _isValidAttribute(lcTag, lcName, value) {
1103
- /* Make sure attribute cannot clobber */
1104
- if (SANITIZE_DOM && (lcName === 'id' || lcName === 'name') && (value in document || value in formElement)) {
1105
- return false;
1106
- }
1107
- /* Allow valid data-* attributes: At least one character after "-"
1108
- (https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes)
1109
- XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804)
1110
- We don't need to check the value; it's always URI safe. */
1111
-
1112
-
1113
- if (ALLOW_DATA_ATTR && !FORBID_ATTR[lcName] && regExpTest(DATA_ATTR, lcName)) ; else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR, lcName)) ; else if (!ALLOWED_ATTR[lcName] || FORBID_ATTR[lcName]) {
1114
- if ( // First condition does a very basic check if a) it's basically a valid custom element tagname AND
1115
- // b) if the tagName passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
1116
- // and c) if the attribute name passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.attributeNameCheck
1117
- _basicCustomElementTest(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)) || // Alternative, second condition checks if it's an `is`-attribute, AND
1118
- // the value passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
1119
- 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 {
1120
- return false;
1121
- }
1122
- /* Check value is safe. First, is attr inert? If so, is safe */
1123
-
1124
- } else if (URI_SAFE_ATTRIBUTES[lcName]) ; else if (regExpTest(IS_ALLOWED_URI$1, stringReplace(value, ATTR_WHITESPACE, ''))) ; 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, stringReplace(value, ATTR_WHITESPACE, ''))) ; else if (!value) ; else {
1125
- return false;
1126
- }
1127
-
1128
- return true;
1129
- };
1130
- /**
1131
- * _basicCustomElementCheck
1132
- * checks if at least one dash is included in tagName, and it's not the first char
1133
- * for more sophisticated checking see https://github.com/sindresorhus/validate-element-name
1134
- * @param {string} tagName name of the tag of the node to sanitize
1135
- */
1136
-
1137
-
1138
- const _basicCustomElementTest = function _basicCustomElementTest(tagName) {
1139
- return tagName.indexOf('-') > 0;
1140
- };
1141
- /**
1142
- * _sanitizeAttributes
1143
- *
1144
- * @protect attributes
1145
- * @protect nodeName
1146
- * @protect removeAttribute
1147
- * @protect setAttribute
1148
- *
1149
- * @param {Node} currentNode to sanitize
1150
- */
1151
-
1152
-
1153
- const _sanitizeAttributes = function _sanitizeAttributes(currentNode) {
1154
- let attr;
1155
- let value;
1156
- let lcName;
1157
- let l;
1158
- /* Execute a hook if present */
1159
-
1160
- _executeHook('beforeSanitizeAttributes', currentNode, null);
1161
-
1162
- const {
1163
- attributes
1164
- } = currentNode;
1165
- /* Check if we have attributes; if not we might have a text node */
1166
-
1167
- if (!attributes) {
1168
- return;
1169
- }
1170
-
1171
- const hookEvent = {
1172
- attrName: '',
1173
- attrValue: '',
1174
- keepAttr: true,
1175
- allowedAttributes: ALLOWED_ATTR
1176
- };
1177
- l = attributes.length;
1178
- /* Go backwards over all attributes; safely remove bad ones */
1179
-
1180
- while (l--) {
1181
- attr = attributes[l];
1182
- const {
1183
- name,
1184
- namespaceURI
1185
- } = attr;
1186
- value = name === 'value' ? attr.value : stringTrim(attr.value);
1187
- lcName = transformCaseFunc(name);
1188
- /* Execute a hook if present */
1189
-
1190
- hookEvent.attrName = lcName;
1191
- hookEvent.attrValue = value;
1192
- hookEvent.keepAttr = true;
1193
- hookEvent.forceKeepAttr = undefined; // Allows developers to see this is a property they can set
1194
-
1195
- _executeHook('uponSanitizeAttribute', currentNode, hookEvent);
1196
-
1197
- value = hookEvent.attrValue;
1198
- /* Did the hooks approve of the attribute? */
1199
-
1200
- if (hookEvent.forceKeepAttr) {
1201
- continue;
1202
- }
1203
- /* Remove attribute */
1204
-
1205
-
1206
- _removeAttribute(name, currentNode);
1207
- /* Did the hooks approve of the attribute? */
1208
-
1209
-
1210
- if (!hookEvent.keepAttr) {
1211
- continue;
1212
- }
1213
- /* Work around a security issue in jQuery 3.0 */
1214
-
1215
-
1216
- if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(/\/>/i, value)) {
1217
- _removeAttribute(name, currentNode);
1218
-
1219
- continue;
1220
- }
1221
- /* Sanitize attribute content to be template-safe */
1222
-
1223
-
1224
- if (SAFE_FOR_TEMPLATES) {
1225
- value = stringReplace(value, MUSTACHE_EXPR, ' ');
1226
- value = stringReplace(value, ERB_EXPR, ' ');
1227
- value = stringReplace(value, TMPLIT_EXPR, ' ');
1228
- }
1229
- /* Is `value` valid for this attribute? */
1230
-
1231
-
1232
- const lcTag = transformCaseFunc(currentNode.nodeName);
1233
-
1234
- if (!_isValidAttribute(lcTag, lcName, value)) {
1235
- continue;
1236
- }
1237
- /* Full DOM Clobbering protection via namespace isolation,
1238
- * Prefix id and name attributes with `user-content-`
1239
- */
1240
-
1241
-
1242
- if (SANITIZE_NAMED_PROPS && (lcName === 'id' || lcName === 'name')) {
1243
- // Remove the attribute with this value
1244
- _removeAttribute(name, currentNode); // Prefix the value and later re-create the attribute with the sanitized value
1245
-
1246
-
1247
- value = SANITIZE_NAMED_PROPS_PREFIX + value;
1248
- }
1249
- /* Handle attributes that require Trusted Types */
1250
-
1251
-
1252
- if (trustedTypesPolicy && typeof trustedTypes === 'object' && typeof trustedTypes.getAttributeType === 'function') {
1253
- if (namespaceURI) ; else {
1254
- switch (trustedTypes.getAttributeType(lcTag, lcName)) {
1255
- case 'TrustedHTML':
1256
- value = trustedTypesPolicy.createHTML(value);
1257
- break;
1258
-
1259
- case 'TrustedScriptURL':
1260
- value = trustedTypesPolicy.createScriptURL(value);
1261
- break;
1262
- }
1263
- }
1264
- }
1265
- /* Handle invalid data-* attribute set by try-catching it */
1266
-
1267
-
1268
- try {
1269
- if (namespaceURI) {
1270
- currentNode.setAttributeNS(namespaceURI, name, value);
1271
- } else {
1272
- /* Fallback to setAttribute() for browser-unrecognized namespaces e.g. "x-schema". */
1273
- currentNode.setAttribute(name, value);
1274
- }
1275
-
1276
- arrayPop(DOMPurify.removed);
1277
- } catch (_) {}
1278
- }
1279
- /* Execute a hook if present */
1280
-
1281
-
1282
- _executeHook('afterSanitizeAttributes', currentNode, null);
1283
- };
1284
- /**
1285
- * _sanitizeShadowDOM
1286
- *
1287
- * @param {DocumentFragment} fragment to iterate over recursively
1288
- */
1289
-
1290
-
1291
- const _sanitizeShadowDOM = function _sanitizeShadowDOM(fragment) {
1292
- let shadowNode;
1293
-
1294
- const shadowIterator = _createIterator(fragment);
1295
- /* Execute a hook if present */
1296
-
1297
-
1298
- _executeHook('beforeSanitizeShadowDOM', fragment, null);
1299
-
1300
- while (shadowNode = shadowIterator.nextNode()) {
1301
- /* Execute a hook if present */
1302
- _executeHook('uponSanitizeShadowNode', shadowNode, null);
1303
- /* Sanitize tags and elements */
1304
-
1305
-
1306
- if (_sanitizeElements(shadowNode)) {
1307
- continue;
1308
- }
1309
- /* Deep shadow DOM detected */
1310
-
1311
-
1312
- if (shadowNode.content instanceof DocumentFragment) {
1313
- _sanitizeShadowDOM(shadowNode.content);
1314
- }
1315
- /* Check attributes, sanitize if necessary */
1316
-
1317
-
1318
- _sanitizeAttributes(shadowNode);
1319
- }
1320
- /* Execute a hook if present */
1321
-
1322
-
1323
- _executeHook('afterSanitizeShadowDOM', fragment, null);
1324
- };
1325
- /**
1326
- * Sanitize
1327
- * Public method providing core sanitation functionality
1328
- *
1329
- * @param {String|Node} dirty string or DOM node
1330
- * @param {Object} configuration object
1331
- */
1332
- // eslint-disable-next-line complexity
1333
-
1334
-
1335
- DOMPurify.sanitize = function (dirty) {
1336
- let cfg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1337
- let body;
1338
- let importedNode;
1339
- let currentNode;
1340
- let returnNode;
1341
- /* Make sure we have a string to sanitize.
1342
- DO NOT return early, as this will return the wrong type if
1343
- the user has requested a DOM object rather than a string */
1344
-
1345
- IS_EMPTY_INPUT = !dirty;
1346
-
1347
- if (IS_EMPTY_INPUT) {
1348
- dirty = '<!-->';
1349
- }
1350
- /* Stringify, in case dirty is an object */
1351
-
1352
-
1353
- if (typeof dirty !== 'string' && !_isNode(dirty)) {
1354
- // eslint-disable-next-line no-negated-condition
1355
- if (typeof dirty.toString !== 'function') {
1356
- throw typeErrorCreate('toString is not a function');
1357
- } else {
1358
- dirty = dirty.toString();
1359
-
1360
- if (typeof dirty !== 'string') {
1361
- throw typeErrorCreate('dirty is not a string, aborting');
1362
- }
1363
- }
1364
- }
1365
- /* Return dirty HTML if DOMPurify cannot run */
1366
-
1367
-
1368
- if (!DOMPurify.isSupported) {
1369
- return dirty;
1370
- }
1371
- /* Assign config vars */
1372
-
1373
-
1374
- if (!SET_CONFIG) {
1375
- _parseConfig(cfg);
1376
- }
1377
- /* Clean up removed elements */
1378
-
1379
-
1380
- DOMPurify.removed = [];
1381
- /* Check if dirty is correctly typed for IN_PLACE */
1382
-
1383
- if (typeof dirty === 'string') {
1384
- IN_PLACE = false;
1385
- }
1386
-
1387
- if (IN_PLACE) {
1388
- /* Do some early pre-sanitization to avoid unsafe root nodes */
1389
- if (dirty.nodeName) {
1390
- const tagName = transformCaseFunc(dirty.nodeName);
1391
-
1392
- if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
1393
- throw typeErrorCreate('root node is forbidden and cannot be sanitized in-place');
1394
- }
1395
- }
1396
- } else if (dirty instanceof Node) {
1397
- /* If dirty is a DOM element, append to an empty document to avoid
1398
- elements being stripped by the parser */
1399
- body = _initDocument('<!---->');
1400
- importedNode = body.ownerDocument.importNode(dirty, true);
1401
-
1402
- if (importedNode.nodeType === 1 && importedNode.nodeName === 'BODY') {
1403
- /* Node is already a body, use as is */
1404
- body = importedNode;
1405
- } else if (importedNode.nodeName === 'HTML') {
1406
- body = importedNode;
1407
- } else {
1408
- // eslint-disable-next-line unicorn/prefer-dom-node-append
1409
- body.appendChild(importedNode);
1410
- }
1411
- } else {
1412
- /* Exit directly if we have nothing to do */
1413
- if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT && // eslint-disable-next-line unicorn/prefer-includes
1414
- dirty.indexOf('<') === -1) {
1415
- return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(dirty) : dirty;
1416
- }
1417
- /* Initialize the document to work on */
1418
-
1419
-
1420
- body = _initDocument(dirty);
1421
- /* Check we have a DOM node from the data */
1422
-
1423
- if (!body) {
1424
- return RETURN_DOM ? null : RETURN_TRUSTED_TYPE ? emptyHTML : '';
1425
- }
1426
- }
1427
- /* Remove first element node (ours) if FORCE_BODY is set */
1428
-
1429
-
1430
- if (body && FORCE_BODY) {
1431
- _forceRemove(body.firstChild);
1432
- }
1433
- /* Get node iterator */
1434
-
1435
-
1436
- const nodeIterator = _createIterator(IN_PLACE ? dirty : body);
1437
- /* Now start iterating over the created document */
1438
-
1439
-
1440
- while (currentNode = nodeIterator.nextNode()) {
1441
- /* Sanitize tags and elements */
1442
- if (_sanitizeElements(currentNode)) {
1443
- continue;
1444
- }
1445
- /* Shadow DOM detected, sanitize it */
1446
-
1447
-
1448
- if (currentNode.content instanceof DocumentFragment) {
1449
- _sanitizeShadowDOM(currentNode.content);
1450
- }
1451
- /* Check attributes, sanitize if necessary */
1452
-
1453
-
1454
- _sanitizeAttributes(currentNode);
1455
- }
1456
- /* If we sanitized `dirty` in-place, return it. */
1457
-
1458
-
1459
- if (IN_PLACE) {
1460
- return dirty;
1461
- }
1462
- /* Return sanitized string or DOM */
1463
-
1464
-
1465
- if (RETURN_DOM) {
1466
- if (RETURN_DOM_FRAGMENT) {
1467
- returnNode = createDocumentFragment.call(body.ownerDocument);
1468
-
1469
- while (body.firstChild) {
1470
- // eslint-disable-next-line unicorn/prefer-dom-node-append
1471
- returnNode.appendChild(body.firstChild);
1472
- }
1473
- } else {
1474
- returnNode = body;
1475
- }
1476
-
1477
- if (ALLOWED_ATTR.shadowroot || ALLOWED_ATTR.shadowrootmod) {
1478
- /*
1479
- AdoptNode() is not used because internal state is not reset
1480
- (e.g. the past names map of a HTMLFormElement), this is safe
1481
- in theory but we would rather not risk another attack vector.
1482
- The state that is cloned by importNode() is explicitly defined
1483
- by the specs.
1484
- */
1485
- returnNode = importNode.call(originalDocument, returnNode, true);
1486
- }
1487
-
1488
- return returnNode;
1489
- }
1490
-
1491
- let serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML;
1492
- /* Serialize doctype if allowed */
1493
-
1494
- if (WHOLE_DOCUMENT && ALLOWED_TAGS['!doctype'] && body.ownerDocument && body.ownerDocument.doctype && body.ownerDocument.doctype.name && regExpTest(DOCTYPE_NAME, body.ownerDocument.doctype.name)) {
1495
- serializedHTML = '<!DOCTYPE ' + body.ownerDocument.doctype.name + '>\n' + serializedHTML;
1496
- }
1497
- /* Sanitize final string template-safe */
1498
-
1499
-
1500
- if (SAFE_FOR_TEMPLATES) {
1501
- serializedHTML = stringReplace(serializedHTML, MUSTACHE_EXPR, ' ');
1502
- serializedHTML = stringReplace(serializedHTML, ERB_EXPR, ' ');
1503
- serializedHTML = stringReplace(serializedHTML, TMPLIT_EXPR, ' ');
1504
- }
1505
-
1506
- return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(serializedHTML) : serializedHTML;
1507
- };
1508
- /**
1509
- * Public method to set the configuration once
1510
- * setConfig
1511
- *
1512
- * @param {Object} cfg configuration object
1513
- */
1514
-
1515
-
1516
- DOMPurify.setConfig = function (cfg) {
1517
- _parseConfig(cfg);
1518
-
1519
- SET_CONFIG = true;
1520
- };
1521
- /**
1522
- * Public method to remove the configuration
1523
- * clearConfig
1524
- *
1525
- */
1526
-
1527
-
1528
- DOMPurify.clearConfig = function () {
1529
- CONFIG = null;
1530
- SET_CONFIG = false;
1531
- };
1532
- /**
1533
- * Public method to check if an attribute value is valid.
1534
- * Uses last set config, if any. Otherwise, uses config defaults.
1535
- * isValidAttribute
1536
- *
1537
- * @param {string} tag Tag name of containing element.
1538
- * @param {string} attr Attribute name.
1539
- * @param {string} value Attribute value.
1540
- * @return {Boolean} Returns true if `value` is valid. Otherwise, returns false.
1541
- */
1542
-
1543
-
1544
- DOMPurify.isValidAttribute = function (tag, attr, value) {
1545
- /* Initialize shared config vars if necessary. */
1546
- if (!CONFIG) {
1547
- _parseConfig({});
1548
- }
1549
-
1550
- const lcTag = transformCaseFunc(tag);
1551
- const lcName = transformCaseFunc(attr);
1552
- return _isValidAttribute(lcTag, lcName, value);
1553
- };
1554
- /**
1555
- * AddHook
1556
- * Public method to add DOMPurify hooks
1557
- *
1558
- * @param {String} entryPoint entry point for the hook to add
1559
- * @param {Function} hookFunction function to execute
1560
- */
1561
-
1562
-
1563
- DOMPurify.addHook = function (entryPoint, hookFunction) {
1564
- if (typeof hookFunction !== 'function') {
1565
- return;
1566
- }
1567
-
1568
- hooks[entryPoint] = hooks[entryPoint] || [];
1569
- arrayPush(hooks[entryPoint], hookFunction);
1570
- };
1571
- /**
1572
- * RemoveHook
1573
- * Public method to remove a DOMPurify hook at a given entryPoint
1574
- * (pops it from the stack of hooks if more are present)
1575
- *
1576
- * @param {String} entryPoint entry point for the hook to remove
1577
- * @return {Function} removed(popped) hook
1578
- */
1579
-
1580
-
1581
- DOMPurify.removeHook = function (entryPoint) {
1582
- if (hooks[entryPoint]) {
1583
- return arrayPop(hooks[entryPoint]);
1584
- }
1585
- };
1586
- /**
1587
- * RemoveHooks
1588
- * Public method to remove all DOMPurify hooks at a given entryPoint
1589
- *
1590
- * @param {String} entryPoint entry point for the hooks to remove
1591
- */
1592
-
1593
-
1594
- DOMPurify.removeHooks = function (entryPoint) {
1595
- if (hooks[entryPoint]) {
1596
- hooks[entryPoint] = [];
1597
- }
1598
- };
1599
- /**
1600
- * RemoveAllHooks
1601
- * Public method to remove all DOMPurify hooks
1602
- *
1603
- */
1604
-
1605
-
1606
- DOMPurify.removeAllHooks = function () {
1607
- hooks = {};
1608
- };
1609
-
1610
- return DOMPurify;
1611
- }
1612
-
1613
- var purify = createDOMPurify();
1614
-
1615
22
  function _typeof$1(obj) {
1616
23
  "@babel/helpers - typeof";
1617
24
 
@@ -5310,45 +3717,6 @@ instance.use(Browser).use(initReactI18next).init({
5310
3717
  order: ["navigator"]
5311
3718
  }
5312
3719
  });
5313
- instance.services.formatter.addCached("boldList", function (lng, options) {
5314
- var formatter = new Intl.ListFormat(lng, options);
5315
- var sanitizer = function sanitizer(value) {
5316
- return purify.sanitize(value, {
5317
- USE_PROFILES: {
5318
- html: true
5319
- }
5320
- });
5321
- };
5322
- return function (value) {
5323
- var boldEmails = value.map(function (email) {
5324
- return "<strong>".concat(email, "</strong>");
5325
- });
5326
- var sanitizedEmails = sanitizer(boldEmails).split(",");
5327
- return formatter.format(sanitizedEmails);
5328
- };
5329
- });
5330
-
5331
- var queryClient = new QueryClient({
5332
- queryCache: new QueryCache(),
5333
- defaultOptions: {
5334
- queries: {
5335
- refetchOnWindowFocus: false,
5336
- keepPreviousData: true
5337
- }
5338
- }
5339
- });
5340
-
5341
- var withReactQuery = function withReactQuery(Component) {
5342
- var QueryWrapper = function QueryWrapper(props) {
5343
- return /*#__PURE__*/React.createElement(QueryClientProvider, {
5344
- client: queryClient
5345
- }, /*#__PURE__*/React.createElement(Component, props), /*#__PURE__*/React.createElement(ReactQueryDevtools, {
5346
- initialIsOpen: false,
5347
- position: "bottom-right"
5348
- }));
5349
- };
5350
- return QueryWrapper;
5351
- };
5352
3720
 
5353
3721
  var MESSAGE_TEMPLATES = {
5354
3722
  email: {
@@ -5382,7 +3750,6 @@ var MESSAGE_TEMPLATE_INITIAL_STATE = {
5382
3750
  template: {}
5383
3751
  };
5384
3752
  var DEFAULT_PAGE_SIZE = 10;
5385
- var DEFAULT_PAGE_INDEX = 1;
5386
3753
  var DEFAULT_PAGE_PROPERTIES = {
5387
3754
  size: DEFAULT_PAGE_SIZE,
5388
3755
  index: DEFAULT_PAGE_INDEX
@@ -5429,14 +3796,14 @@ var messageTemplatesApi = {
5429
3796
  };
5430
3797
 
5431
3798
  var QUERY_KEYS = {
5432
- MESSAGE_TEMPLATE: "message-templates"
3799
+ NEETO_MESSAGE_TEMPLATES: "neeto-message-templates"
5433
3800
  };
5434
3801
 
5435
3802
  var ownerIdValue = function ownerIdValue(ownerId) {
5436
3803
  return isEmpty(ownerId) ? undefined : ownerId;
5437
3804
  };
5438
3805
  var useFetchTemplates = function useFetchTemplates(params) {
5439
- return useQuery([QUERY_KEYS.MESSAGE_TEMPLATE, params], function () {
3806
+ return useQuery([QUERY_KEYS.NEETO_MESSAGE_TEMPLATES, params], function () {
5440
3807
  return messageTemplatesApi.fetchAll(params);
5441
3808
  });
5442
3809
  };
@@ -5447,7 +3814,7 @@ var useCreateTemplate = function useCreateTemplate(ownerId, options) {
5447
3814
  ownerId: ownerIdValue(ownerId)
5448
3815
  });
5449
3816
  }, {
5450
- keysToInvalidate: [QUERY_KEYS.MESSAGE_TEMPLATE],
3817
+ keysToInvalidate: [QUERY_KEYS.NEETO_MESSAGE_TEMPLATES],
5451
3818
  onSuccess: options === null || options === void 0 ? void 0 : options.onSuccess
5452
3819
  });
5453
3820
  };
@@ -5461,7 +3828,7 @@ var useUpdateTemplate = function useUpdateTemplate(ownerId) {
5461
3828
  ownerId: ownerIdValue(ownerId)
5462
3829
  });
5463
3830
  }, {
5464
- keysToInvalidate: [QUERY_KEYS.MESSAGE_TEMPLATE]
3831
+ keysToInvalidate: [QUERY_KEYS.NEETO_MESSAGE_TEMPLATES]
5465
3832
  });
5466
3833
  };
5467
3834
  var useDeleteTemplate = function useDeleteTemplate(ownerId) {
@@ -5471,12 +3838,12 @@ var useDeleteTemplate = function useDeleteTemplate(ownerId) {
5471
3838
  ownerId: ownerIdValue(ownerId)
5472
3839
  });
5473
3840
  }, {
5474
- keysToInvalidate: [QUERY_KEYS.MESSAGE_TEMPLATE]
3841
+ keysToInvalidate: [QUERY_KEYS.NEETO_MESSAGE_TEMPLATES]
5475
3842
  });
5476
3843
  };
5477
3844
 
5478
3845
  /** @type {import("neetocommons/react-utils").ZustandStoreHook} */
5479
- var useTemplateStore = create$1(withImmutableActions(function (set) {
3846
+ var useTemplateStore = create(withImmutableActions(function (set) {
5480
3847
  return {
5481
3848
  templateType: "",
5482
3849
  setTemplateState: set
@@ -6470,7 +4837,6 @@ var MessageTemplates = function MessageTemplates(_ref) {
6470
4837
  }
6471
4838
  }));
6472
4839
  };
6473
- var index$1 = withReactQuery(MessageTemplates);
6474
4840
 
6475
4841
  var formatEditorContent = function formatEditorContent(value) {
6476
4842
  return value === null || value === void 0 ? void 0 : value.replaceAll(/<\/?(?!img)\w*\b[^>]*>/gi, "").trim();
@@ -6499,18 +4865,19 @@ var WHATSAPP_MESSAGE_FORM_VALIDATIONS_SCHEMA = yup.object().shape({
6499
4865
  function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
6500
4866
  function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
6501
4867
  var EmailAndSms = function EmailAndSms(_ref) {
6502
- var isEmailTemplate = _ref.isEmailTemplate,
6503
- onClose = _ref.onClose,
4868
+ var onClose = _ref.onClose,
6504
4869
  templates = _ref.templates,
6505
- handleSubmit = _ref.handleSubmit,
6506
4870
  setInitialFocusField = _ref.setInitialFocusField,
6507
4871
  templateVariables = _ref.templateVariables,
6508
4872
  customFields = _ref.customFields,
6509
4873
  customFieldsInitialValues = _ref.customFieldsInitialValues,
6510
- customFieldsValidationSchema = _ref.customFieldsValidationSchema;
4874
+ customFieldsValidationSchema = _ref.customFieldsValidationSchema,
4875
+ type = _ref.type,
4876
+ handleSubmit = _ref.handleSubmit;
6511
4877
  var editorRef = useRef(null);
6512
4878
  var _useTranslation = useTranslation(),
6513
4879
  t = _useTranslation.t;
4880
+ var isEmailTemplate = type === "email";
6514
4881
  var _ref2 = isEmailTemplate ? [SEND_MESSAGE_INITIAL_VALUES, EMAIL_MESSAGE_FORM_SCHEMA] : [pick(["body"], SEND_MESSAGE_INITIAL_VALUES), SMS_MESSAGE_FORM_VALIDATION_SCHEMA],
6515
4882
  _ref3 = _slicedToArray(_ref2, 2),
6516
4883
  INITIAL_VALUES = _ref3[0],
@@ -6529,8 +4896,7 @@ var EmailAndSms = function EmailAndSms(_ref) {
6529
4896
  onSubmit: handleSubmit
6530
4897
  }
6531
4898
  }, function (_ref4) {
6532
- var dirty = _ref4.dirty,
6533
- isSubmitting = _ref4.isSubmitting,
4899
+ var isSubmitting = _ref4.isSubmitting,
6534
4900
  setValues = _ref4.setValues,
6535
4901
  values = _ref4.values;
6536
4902
  var handleTemplateChange = function handleTemplateChange(value) {
@@ -6547,15 +4913,11 @@ var EmailAndSms = function EmailAndSms(_ref) {
6547
4913
  isSearchable: true,
6548
4914
  innerRef: setInitialFocusField,
6549
4915
  label: t("template.title"),
4916
+ options: renameKeys({
4917
+ name: "label",
4918
+ id: "value"
4919
+ }, templates),
6550
4920
  placeholder: t("sendMessage.selectTemplate"),
6551
- options: templates.map(function (_ref5) {
6552
- var name = _ref5.name,
6553
- id = _ref5.id;
6554
- return {
6555
- label: name,
6556
- value: id
6557
- };
6558
- }),
6559
4921
  onChange: handleTemplateChange
6560
4922
  }), customFields, isEmailTemplate && /*#__PURE__*/React.createElement(Input, {
6561
4923
  required: true,
@@ -6574,7 +4936,7 @@ var EmailAndSms = function EmailAndSms(_ref) {
6574
4936
  }), /*#__PURE__*/React.createElement(Pane.Footer, {
6575
4937
  className: "absolute bottom-0 left-0 flex gap-x-2"
6576
4938
  }, /*#__PURE__*/React.createElement(Button, {
6577
- disabled: !dirty || isSubmitting,
4939
+ disabled: isSubmitting,
6578
4940
  label: t("template.send"),
6579
4941
  loading: isSubmitting,
6580
4942
  type: "submit"
@@ -6635,8 +4997,7 @@ var Whatsapp = function Whatsapp(_ref) {
6635
4997
  onSubmit: handleSubmit
6636
4998
  }
6637
4999
  }, function (_ref3) {
6638
- var dirty = _ref3.dirty,
6639
- isSubmitting = _ref3.isSubmitting,
5000
+ var isSubmitting = _ref3.isSubmitting,
6640
5001
  values = _ref3.values,
6641
5002
  setValues = _ref3.setValues;
6642
5003
  var handleTemplateChange = function handleTemplateChange(value) {
@@ -6658,14 +5019,10 @@ var Whatsapp = function Whatsapp(_ref) {
6658
5019
  defaultValue: initialFormValues.selectedTemplate,
6659
5020
  label: t("template.title"),
6660
5021
  name: "selectedTemplate",
6661
- options: templates.map(function (_ref4) {
6662
- var name = _ref4.name,
6663
- id = _ref4.id;
6664
- return {
6665
- label: name,
6666
- value: id
6667
- };
6668
- }),
5022
+ options: renameKeys({
5023
+ name: "label",
5024
+ id: "value"
5025
+ }, templates),
6669
5026
  onChange: handleTemplateChange
6670
5027
  }), /*#__PURE__*/React.createElement(Textarea, {
6671
5028
  disabled: true,
@@ -6693,7 +5050,7 @@ var Whatsapp = function Whatsapp(_ref) {
6693
5050
  })), /*#__PURE__*/React.createElement(Pane.Footer, {
6694
5051
  className: "absolute bottom-0 left-0 flex gap-x-2"
6695
5052
  }, /*#__PURE__*/React.createElement(Button$1, {
6696
- disabled: !dirty || isSubmitting,
5053
+ disabled: isSubmitting,
6697
5054
  label: t("template.send"),
6698
5055
  loading: isSubmitting,
6699
5056
  type: "submit"
@@ -6732,6 +5089,7 @@ var SendMessagePane = function SendMessagePane(_ref) {
6732
5089
  return initialFocusField.current = fieldRef;
6733
5090
  };
6734
5091
  var value = MESSAGE_TEMPLATES[type].value;
5092
+ var isWhatsappTemplate = type === "whatsapp";
6735
5093
  var templateParams = {
6736
5094
  status: "active",
6737
5095
  templateType: value,
@@ -6742,8 +5100,6 @@ var SendMessagePane = function SendMessagePane(_ref) {
6742
5100
  _useFetchTemplates$da2 = _useFetchTemplates$da === void 0 ? {} : _useFetchTemplates$da,
6743
5101
  _useFetchTemplates$da3 = _useFetchTemplates$da2.templates,
6744
5102
  templates = _useFetchTemplates$da3 === void 0 ? [] : _useFetchTemplates$da3;
6745
- var isEmailTemplate = type === "email";
6746
- var isWhatsappTemplate = type === "whatsapp";
6747
5103
  return /*#__PURE__*/React.createElement(Pane, {
6748
5104
  initialFocusRef: initialFocusField,
6749
5105
  isOpen: isOpen,
@@ -6753,21 +5109,20 @@ var SendMessagePane = function SendMessagePane(_ref) {
6753
5109
  weight: "semibold"
6754
5110
  }, t("common.send"), " ", type)), /*#__PURE__*/React.createElement(Pane.Body, null, isWhatsappTemplate ? /*#__PURE__*/React.createElement(Whatsapp, {
6755
5111
  handleSubmit: handleSubmit,
6756
- templates: templates,
6757
- onClose: onClose
5112
+ onClose: onClose,
5113
+ templates: templates
6758
5114
  }) : /*#__PURE__*/React.createElement(EmailAndSms, {
6759
5115
  customFields: customFields,
6760
5116
  customFieldsInitialValues: customFieldsInitialValues,
6761
5117
  customFieldsValidationSchema: customFieldsValidationSchema,
6762
5118
  handleSubmit: handleSubmit,
6763
- isEmailTemplate: isEmailTemplate,
5119
+ onClose: onClose,
6764
5120
  setInitialFocusField: setInitialFocusField,
6765
5121
  templateVariables: templateVariables,
6766
5122
  templates: templates,
6767
- onClose: onClose
5123
+ type: type
6768
5124
  })));
6769
5125
  };
6770
- var index = withReactQuery(SendMessagePane);
6771
5126
 
6772
- export { index$1 as MessageTemplates, index as SendMessagePane };
5127
+ export { MessageTemplates, SendMessagePane };
6773
5128
  //# sourceMappingURL=index.js.map