@mmlogic/components 0.5.1 → 0.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/dist/cjs/cell-renderer-CmaO0CZT.js +862 -0
  2. package/dist/cjs/loader.cjs.js +1 -1
  3. package/dist/cjs/mosterdcomponents.cjs.js +1 -1
  4. package/dist/cjs/mrd-boolean-field_23.cjs.entry.js +2490 -817
  5. package/dist/cjs/mrd-merge-view.cjs.entry.js +273 -0
  6. package/dist/collection/collection-manifest.json +1 -0
  7. package/dist/collection/components/fields/mrd-textarea-field/mrd-textarea-field.js +9 -5
  8. package/dist/collection/components/merge/mrd-merge-view/merge-diff.js +99 -0
  9. package/dist/collection/components/merge/mrd-merge-view/merge-parts.js +44 -0
  10. package/dist/collection/components/merge/mrd-merge-view/mrd-merge-view.css +244 -0
  11. package/dist/collection/components/merge/mrd-merge-view/mrd-merge-view.js +397 -0
  12. package/dist/collection/dev/api.js +24 -0
  13. package/dist/collection/dev/app.js +84 -4
  14. package/dist/collection/utils/cell-renderer.js +6 -1
  15. package/dist/collection/utils/i18n.js +104 -0
  16. package/dist/components/cell-renderer.js +1 -0
  17. package/dist/components/format.js +1 -1
  18. package/dist/components/i18n.js +1 -1
  19. package/dist/components/mrd-layout-section.js +1 -1
  20. package/dist/components/mrd-merge-view.d.ts +11 -0
  21. package/dist/components/mrd-merge-view.js +1 -0
  22. package/dist/components/mrd-table2.js +1 -1
  23. package/dist/components/mrd-textarea-field2.js +2 -1
  24. package/dist/esm/cell-renderer-D63AUZxa.js +854 -0
  25. package/dist/esm/loader.js +1 -1
  26. package/dist/esm/mosterdcomponents.js +1 -1
  27. package/dist/esm/mrd-boolean-field_23.entry.js +2420 -747
  28. package/dist/esm/mrd-merge-view.entry.js +271 -0
  29. package/dist/mosterdcomponents/mosterdcomponents.esm.js +1 -1
  30. package/dist/mosterdcomponents/p-2e16a7d0.entry.js +1 -0
  31. package/dist/mosterdcomponents/p-CnqDM0Gb.js +1 -0
  32. package/dist/mosterdcomponents/p-b5f38707.entry.js +3 -0
  33. package/dist/types/components/fields/mrd-textarea-field/mrd-textarea-field.d.ts +1 -0
  34. package/dist/types/components/merge/mrd-merge-view/merge-diff.d.ts +43 -0
  35. package/dist/types/components/merge/mrd-merge-view/merge-parts.d.ts +37 -0
  36. package/dist/types/components/merge/mrd-merge-view/mrd-merge-view.d.ts +68 -0
  37. package/dist/types/components.d.ts +151 -0
  38. package/package.json +2 -1
  39. package/dist/mosterdcomponents/p-cdecc698.entry.js +0 -1
@@ -1,4 +1,5 @@
1
1
  import { r as registerInstance, c as createEvent, h, H as Host, g as getElement, w as writeTask } from './index-DiSe6vjv.js';
2
+ import { t, p as parseLocalizedNumber, f as formatDate, C as CellRenderer, a as formatNumber, b as formatPercentage, c as formatCurrency } from './cell-renderer-D63AUZxa.js';
2
3
  import { b as ClientLayoutItemFieldDataType, e as ClientLayoutNavigateBehaviour, a as ClientLayoutItemType, c as ClientLayoutItemRelationDisplayType, d as ClientLayoutItemRelationEditBehavior, r as resolveArchetype, A as ARCHETYPE_DOCUMENT } from './client-layout-DCOAAH92.js';
3
4
 
4
5
  const mrdBooleanFieldCss = () => `.sc-mrd-boolean-field-h{display:block}.mrd-boolean-field.sc-mrd-boolean-field{display:flex;align-items:center;width:100%}.mrd-boolean-field__toggle-label.sc-mrd-boolean-field{display:flex;align-items:center;gap:var(--mrd-space-3);cursor:pointer;user-select:none}.mrd-boolean-field__checkbox.sc-mrd-boolean-field{position:absolute;opacity:0;width:0;height:0;pointer-events:none}.mrd-boolean-field__checkbox.sc-mrd-boolean-field:checked+.mrd-boolean-field__toggle.sc-mrd-boolean-field{background-color:var(--mrd-color-primary)}.mrd-boolean-field__checkbox.sc-mrd-boolean-field:checked+.mrd-boolean-field__toggle.sc-mrd-boolean-field::after{transform:translateX(20px)}.mrd-boolean-field__checkbox.sc-mrd-boolean-field:focus+.mrd-boolean-field__toggle.sc-mrd-boolean-field{box-shadow:var(--mrd-shadow-focus)}.mrd-boolean-field__checkbox.sc-mrd-boolean-field:disabled+.mrd-boolean-field__toggle.sc-mrd-boolean-field{opacity:0.5;cursor:not-allowed}.mrd-boolean-field__toggle.sc-mrd-boolean-field{position:relative;display:inline-block;width:44px;height:24px;background-color:var(--mrd-color-neutral-300);border-radius:var(--mrd-border-radius-full);transition:background-color var(--mrd-transition);flex-shrink:0}.mrd-boolean-field__toggle.sc-mrd-boolean-field::after{content:"";position:absolute;top:2px;left:2px;width:20px;height:20px;background-color:var(--mrd-color-white);border-radius:50%;transition:transform var(--mrd-transition);box-shadow:var(--mrd-shadow-sm)}.mrd-boolean-field__text.sc-mrd-boolean-field{font-family:var(--mrd-font-family);font-size:var(--mrd-font-size-base);color:var(--mrd-color-neutral-800)}.mrd-boolean-field__text--required.sc-mrd-boolean-field::after{content:" *";color:var(--mrd-color-danger)}`;
@@ -32,644 +33,6 @@ const MrdBooleanField = class {
32
33
  };
33
34
  MrdBooleanField.style = mrdBooleanFieldCss();
34
35
 
35
- function formatNumber(value, locale, options) {
36
- if (value === null || value === undefined || isNaN(value))
37
- return '';
38
- return new Intl.NumberFormat(locale, options).format(value);
39
- }
40
- function formatCurrency(amount, currency, locale) {
41
- if (amount === null || amount === undefined || isNaN(amount))
42
- return '';
43
- return new Intl.NumberFormat(locale, {
44
- style: 'currency',
45
- currency,
46
- minimumFractionDigits: 2,
47
- maximumFractionDigits: 2,
48
- }).format(amount);
49
- }
50
- function formatPercentage(value, locale, decimalPrecision = 2) {
51
- if (value === null || value === undefined || isNaN(value))
52
- return '';
53
- return new Intl.NumberFormat(locale, {
54
- style: 'percent',
55
- minimumFractionDigits: decimalPrecision,
56
- maximumFractionDigits: decimalPrecision,
57
- }).format(value);
58
- }
59
- function formatDate(value, locale) {
60
- if (!value)
61
- return '';
62
- const date = typeof value === 'string' ? new Date(value) : value;
63
- if (isNaN(date.getTime()))
64
- return '';
65
- return new Intl.DateTimeFormat(locale, { year: 'numeric', month: '2-digit', day: '2-digit' }).format(date);
66
- }
67
- function formatDateTime(value, locale) {
68
- if (!value)
69
- return '';
70
- const date = typeof value === 'string' ? new Date(value) : value;
71
- if (isNaN(date.getTime()))
72
- return '';
73
- return new Intl.DateTimeFormat(locale, {
74
- year: 'numeric',
75
- month: '2-digit',
76
- day: '2-digit',
77
- hour: '2-digit',
78
- minute: '2-digit',
79
- }).format(date);
80
- }
81
- function formatTime(value, locale) {
82
- if (!value)
83
- return '';
84
- // value is HH:MM or HH:MM:SS
85
- const [hours, minutes] = value.split(':').map(Number);
86
- const date = new Date();
87
- date.setHours(hours, minutes, 0, 0);
88
- return new Intl.DateTimeFormat(locale, { hour: '2-digit', minute: '2-digit' }).format(date);
89
- }
90
- function parseLocalizedNumber(str, locale) {
91
- var _a, _b, _c, _d;
92
- if (!str || !str.trim())
93
- return null;
94
- // Detect decimal and thousands separators from the locale
95
- const parts = new Intl.NumberFormat(locale).formatToParts(1234567.89);
96
- const groupSep = (_b = (_a = parts.find((p) => p.type === 'group')) === null || _a === void 0 ? void 0 : _a.value) !== null && _b !== void 0 ? _b : ',';
97
- const decimalSep = (_d = (_c = parts.find((p) => p.type === 'decimal')) === null || _c === void 0 ? void 0 : _c.value) !== null && _d !== void 0 ? _d : '.';
98
- // Remove group separators, replace decimal separator with '.'
99
- const normalized = str
100
- .replace(new RegExp(`\\${groupSep}`, 'g'), '')
101
- .replace(new RegExp(`\\${decimalSep}`), '.')
102
- .replace('%', '')
103
- .trim();
104
- const parsed = parseFloat(normalized);
105
- return isNaN(parsed) ? null : parsed;
106
- }
107
-
108
- const translations = {
109
- nl: {
110
- required: 'Dit veld is verplicht',
111
- select_placeholder: 'Selecteer een optie',
112
- search_placeholder: 'Zoeken...',
113
- upload_file: 'Bestand uploaden',
114
- choose_file: 'Bestand kiezen',
115
- clear: 'Wissen',
116
- today: 'Vandaag',
117
- invalid_email: 'Voer een geldig e-mailadres in',
118
- invalid_url: 'Voer een geldige URL in',
119
- invalid_number: 'Voer een geldig getal in',
120
- drop_file_here: 'Sleep bestand hierheen of',
121
- browse: 'bladeren',
122
- file_too_large: 'Bestand is te groot',
123
- invalid_image: 'Selecteer een afbeeldingsbestand',
124
- search_results: 'Zoekresultaten',
125
- no_results: 'Geen resultaten gevonden',
126
- load_failed_retry: 'Laden mislukt — opnieuw proberen',
127
- loading: 'Laden...',
128
- submit: 'Opslaan',
129
- cancel: 'Annuleren',
130
- remove: 'Verwijderen',
131
- add: 'Toevoegen',
132
- yes: 'Ja',
133
- no: 'Nee',
134
- // mrd-table footer
135
- table_of: 'van',
136
- download: 'Downloaden',
137
- // mrd-table toolbar
138
- table_filter: 'Filteren',
139
- table_filter_hide: 'Filter verbergen',
140
- table_filter_active: 'actief',
141
- table_filter_clear_all: 'Alle filters wissen',
142
- table_new_record: 'Nieuw record',
143
- table_export_excel: 'Exporteer naar Excel',
144
- doc_view_switch: 'Weergave wisselen',
145
- doc_view_tree: 'Boomweergave',
146
- doc_view_list: 'Lijstweergave',
147
- // mrd-table filter popup
148
- filter_sorting: 'Sortering',
149
- filter_ascending: 'Oplopend',
150
- filter_descending: 'Aflopend',
151
- filter_section: 'Filter',
152
- filter_apply: 'Toepassen',
153
- filter_clear: 'Wissen',
154
- filter_contains: 'Bevat',
155
- filter_starts_with: 'Begint met',
156
- filter_equals: 'Gelijk aan',
157
- filter_has_value: 'Heeft waarde',
158
- filter_is_empty: 'Is leeg',
159
- filter_is_not_empty: 'Is niet leeg',
160
- filter_exact: 'Exact',
161
- filter_range: 'Bereik',
162
- filter_from: 'Van',
163
- filter_to: 'Tot',
164
- filter_all: 'Alle',
165
- filter_select_all: 'Alles',
166
- filter_select_none: 'Geen',
167
- filter_search_value: 'Zoekwaarde...',
168
- filter_no_support: 'Geen filtering beschikbaar voor dit veldtype.',
169
- // mrd-table textblock
170
- textblock_show_more: 'Meer tonen',
171
- close: 'Sluiten',
172
- // history badge
173
- history_until: 'tot',
174
- history_badge_tooltip: 'Vorige waarden',
175
- hyperlink_name: 'Linktekst (optioneel)',
176
- // mrd-document-list
177
- new_folder: 'Nieuwe folder',
178
- folder_name_placeholder: 'Foldernaam',
179
- folder_no_slash: "Een foldernaam mag geen '/' bevatten",
180
- folder_duplicate: 'Er bestaat al een folder met deze naam',
181
- doc_empty_drop: 'Nog geen documenten — sleep bestanden hierheen',
182
- },
183
- en: {
184
- required: 'This field is required',
185
- select_placeholder: 'Select an option',
186
- search_placeholder: 'Search...',
187
- upload_file: 'Upload file',
188
- choose_file: 'Choose file',
189
- clear: 'Clear',
190
- today: 'Today',
191
- invalid_email: 'Please enter a valid email address',
192
- invalid_url: 'Please enter a valid URL',
193
- invalid_number: 'Please enter a valid number',
194
- drop_file_here: 'Drop file here or',
195
- browse: 'browse',
196
- file_too_large: 'File is too large',
197
- invalid_image: 'Please select an image file',
198
- search_results: 'Search results',
199
- no_results: 'No results found',
200
- load_failed_retry: 'Failed to load — retry',
201
- loading: 'Loading...',
202
- submit: 'Save',
203
- cancel: 'Cancel',
204
- remove: 'Remove',
205
- add: 'Add',
206
- yes: 'Yes',
207
- no: 'No',
208
- // mrd-table footer
209
- table_of: 'of',
210
- download: 'Download',
211
- // mrd-table toolbar
212
- table_filter: 'Filter',
213
- table_filter_hide: 'Hide filter',
214
- table_filter_active: 'active',
215
- table_filter_clear_all: 'Clear all filters',
216
- table_new_record: 'New record',
217
- table_export_excel: 'Export to Excel',
218
- doc_view_switch: 'Switch view',
219
- doc_view_tree: 'Tree view',
220
- doc_view_list: 'List view',
221
- // mrd-table filter popup
222
- filter_sorting: 'Sorting',
223
- filter_ascending: 'Ascending',
224
- filter_descending: 'Descending',
225
- filter_section: 'Filter',
226
- filter_apply: 'Apply',
227
- filter_clear: 'Clear',
228
- filter_contains: 'Contains',
229
- filter_starts_with: 'Starts with',
230
- filter_equals: 'Equals',
231
- filter_has_value: 'Has value',
232
- filter_is_empty: 'Is empty',
233
- filter_is_not_empty: 'Is not empty',
234
- filter_exact: 'Exact',
235
- filter_range: 'Range',
236
- filter_from: 'From',
237
- filter_to: 'To',
238
- filter_all: 'All',
239
- filter_select_all: 'All',
240
- filter_select_none: 'None',
241
- filter_search_value: 'Search value...',
242
- filter_no_support: 'Filtering is not available for this field type.',
243
- // mrd-table textblock
244
- textblock_show_more: 'Show more',
245
- close: 'Close',
246
- // history badge
247
- history_until: 'until',
248
- history_badge_tooltip: 'Previous values',
249
- hyperlink_name: 'Link text (optional)',
250
- // mrd-document-list
251
- new_folder: 'New folder',
252
- folder_name_placeholder: 'Folder name',
253
- folder_no_slash: "A folder name cannot contain '/'",
254
- folder_duplicate: 'A folder with this name already exists',
255
- doc_empty_drop: 'No documents yet — drop files here',
256
- },
257
- ar: {
258
- required: 'هذا الحقل مطلوب',
259
- select_placeholder: 'اختر خياراً',
260
- search_placeholder: 'بحث...',
261
- upload_file: 'رفع ملف',
262
- choose_file: 'اختر ملفاً',
263
- clear: 'مسح',
264
- today: 'اليوم',
265
- invalid_email: 'يرجى إدخال عنوان بريد إلكتروني صحيح',
266
- invalid_url: 'يرجى إدخال رابط صحيح',
267
- invalid_number: 'يرجى إدخال رقم صحيح',
268
- drop_file_here: 'اسحب الملف هنا أو',
269
- browse: 'تصفح',
270
- file_too_large: 'الملف كبير جداً',
271
- invalid_image: 'يرجى اختيار ملف صورة',
272
- search_results: 'نتائج البحث',
273
- no_results: 'لم يتم العثور على نتائج',
274
- load_failed_retry: 'فشل التحميل — إعادة المحاولة',
275
- loading: 'جار التحميل...',
276
- submit: 'حفظ',
277
- cancel: 'إلغاء',
278
- remove: 'إزالة',
279
- add: 'إضافة',
280
- yes: 'نعم',
281
- no: 'لا',
282
- // mrd-table footer
283
- table_of: 'من أصل',
284
- download: 'تنزيل',
285
- // mrd-table toolbar
286
- table_filter: 'تصفية',
287
- table_filter_hide: 'إخفاء التصفية',
288
- table_filter_active: 'نشط',
289
- table_filter_clear_all: 'مسح جميع الفلاتر',
290
- table_new_record: 'سجل جديد',
291
- table_export_excel: 'تصدير إلى Excel',
292
- doc_view_switch: 'تبديل العرض',
293
- doc_view_tree: 'عرض شجري',
294
- doc_view_list: 'عرض القائمة',
295
- // mrd-table filter popup
296
- filter_sorting: 'الترتيب',
297
- filter_ascending: 'تصاعدي',
298
- filter_descending: 'تنازلي',
299
- filter_section: 'تصفية',
300
- filter_apply: 'تطبيق',
301
- filter_clear: 'مسح',
302
- filter_contains: 'يحتوي على',
303
- filter_starts_with: 'يبدأ بـ',
304
- filter_equals: 'يساوي',
305
- filter_has_value: 'له قيمة',
306
- filter_is_empty: 'فارغ',
307
- filter_is_not_empty: 'ليس فارغاً',
308
- filter_exact: 'دقيق',
309
- filter_range: 'نطاق',
310
- filter_from: 'من',
311
- filter_to: 'إلى',
312
- filter_all: 'الكل',
313
- filter_select_all: 'الكل',
314
- filter_select_none: 'لا شيء',
315
- filter_search_value: 'قيمة البحث...',
316
- filter_no_support: 'التصفية غير متاحة لهذا النوع من الحقول.',
317
- // mrd-table textblock
318
- textblock_show_more: 'عرض المزيد',
319
- close: 'إغلاق',
320
- // history badge
321
- history_until: 'حتى',
322
- history_badge_tooltip: 'القيم السابقة',
323
- hyperlink_name: 'نص الرابط (اختياري)',
324
- },
325
- fr: {
326
- required: 'Ce champ est obligatoire',
327
- select_placeholder: 'Sélectionner une option',
328
- search_placeholder: 'Rechercher...',
329
- upload_file: 'Télécharger un fichier',
330
- choose_file: 'Choisir un fichier',
331
- clear: 'Effacer',
332
- today: "Aujourd'hui",
333
- invalid_email: 'Veuillez saisir une adresse e-mail valide',
334
- invalid_url: 'Veuillez saisir une URL valide',
335
- invalid_number: 'Veuillez saisir un nombre valide',
336
- drop_file_here: 'Déposez le fichier ici ou',
337
- browse: 'parcourir',
338
- file_too_large: 'Le fichier est trop volumineux',
339
- invalid_image: 'Veuillez sélectionner un fichier image',
340
- search_results: 'Résultats de recherche',
341
- no_results: 'Aucun résultat trouvé',
342
- load_failed_retry: 'Échec du chargement — réessayer',
343
- loading: 'Chargement...',
344
- submit: 'Enregistrer',
345
- cancel: 'Annuler',
346
- remove: 'Supprimer',
347
- add: 'Ajouter',
348
- yes: 'Oui',
349
- no: 'Non',
350
- // mrd-table footer
351
- table_of: 'sur',
352
- download: 'Télécharger',
353
- // mrd-table toolbar
354
- table_filter: 'Filtrer',
355
- table_filter_hide: 'Masquer le filtre',
356
- table_filter_active: 'actif',
357
- table_filter_clear_all: 'Effacer tous les filtres',
358
- table_new_record: 'Nouvel enregistrement',
359
- table_export_excel: 'Exporter vers Excel',
360
- doc_view_switch: 'Changer de vue',
361
- doc_view_tree: 'Vue arborescente',
362
- doc_view_list: 'Vue liste',
363
- // mrd-table filter popup
364
- filter_sorting: 'Tri',
365
- filter_ascending: 'Croissant',
366
- filter_descending: 'Décroissant',
367
- filter_section: 'Filtre',
368
- filter_apply: 'Appliquer',
369
- filter_clear: 'Effacer',
370
- filter_contains: 'Contient',
371
- filter_starts_with: 'Commence par',
372
- filter_equals: 'Égal à',
373
- filter_has_value: 'A une valeur',
374
- filter_is_empty: 'Est vide',
375
- filter_is_not_empty: "N'est pas vide",
376
- filter_exact: 'Exact',
377
- filter_range: 'Plage',
378
- filter_from: 'De',
379
- filter_to: 'À',
380
- filter_all: 'Tous',
381
- filter_select_all: 'Tous',
382
- filter_select_none: 'Aucun',
383
- filter_search_value: 'Valeur de recherche...',
384
- filter_no_support: "Le filtrage n'est pas disponible pour ce type de champ.",
385
- // mrd-table textblock
386
- textblock_show_more: 'Voir plus',
387
- close: 'Fermer',
388
- // history badge
389
- history_until: "jusqu'au",
390
- history_badge_tooltip: 'Valeurs précédentes',
391
- hyperlink_name: 'Texte du lien (optionnel)',
392
- },
393
- de: {
394
- required: 'Dieses Feld ist erforderlich',
395
- select_placeholder: 'Option auswählen',
396
- search_placeholder: 'Suchen...',
397
- upload_file: 'Datei hochladen',
398
- choose_file: 'Datei auswählen',
399
- clear: 'Löschen',
400
- today: 'Heute',
401
- invalid_email: 'Bitte geben Sie eine gültige E-Mail-Adresse ein',
402
- invalid_url: 'Bitte geben Sie eine gültige URL ein',
403
- invalid_number: 'Bitte geben Sie eine gültige Zahl ein',
404
- drop_file_here: 'Datei hier ablegen oder',
405
- browse: 'durchsuchen',
406
- file_too_large: 'Datei ist zu groß',
407
- invalid_image: 'Bitte eine Bilddatei auswählen',
408
- search_results: 'Suchergebnisse',
409
- no_results: 'Keine Ergebnisse gefunden',
410
- load_failed_retry: 'Laden fehlgeschlagen — erneut versuchen',
411
- loading: 'Laden...',
412
- submit: 'Speichern',
413
- cancel: 'Abbrechen',
414
- remove: 'Entfernen',
415
- add: 'Hinzufügen',
416
- yes: 'Ja',
417
- no: 'Nein',
418
- // mrd-table footer
419
- table_of: 'von',
420
- download: 'Herunterladen',
421
- // mrd-table toolbar
422
- table_filter: 'Filtern',
423
- table_filter_hide: 'Filter ausblenden',
424
- table_filter_active: 'aktiv',
425
- table_filter_clear_all: 'Alle Filter löschen',
426
- table_new_record: 'Neuer Eintrag',
427
- table_export_excel: 'Als Excel exportieren',
428
- doc_view_switch: 'Ansicht wechseln',
429
- doc_view_tree: 'Baumansicht',
430
- doc_view_list: 'Listenansicht',
431
- // mrd-table filter popup
432
- filter_sorting: 'Sortierung',
433
- filter_ascending: 'Aufsteigend',
434
- filter_descending: 'Absteigend',
435
- filter_section: 'Filter',
436
- filter_apply: 'Anwenden',
437
- filter_clear: 'Löschen',
438
- filter_contains: 'Enthält',
439
- filter_starts_with: 'Beginnt mit',
440
- filter_equals: 'Gleich',
441
- filter_has_value: 'Hat Wert',
442
- filter_is_empty: 'Ist leer',
443
- filter_is_not_empty: 'Ist nicht leer',
444
- filter_exact: 'Genau',
445
- filter_range: 'Bereich',
446
- filter_from: 'Von',
447
- filter_to: 'Bis',
448
- filter_all: 'Alle',
449
- filter_select_all: 'Alle',
450
- filter_select_none: 'Keine',
451
- filter_search_value: 'Suchwert...',
452
- filter_no_support: 'Filterung ist für diesen Feldtyp nicht verfügbar.',
453
- // mrd-table textblock
454
- textblock_show_more: 'Mehr anzeigen',
455
- close: 'Schließen',
456
- // history badge
457
- history_until: 'bis',
458
- history_badge_tooltip: 'Vorherige Werte',
459
- hyperlink_name: 'Linktext (optional)',
460
- },
461
- es: {
462
- required: 'Este campo es obligatorio',
463
- select_placeholder: 'Seleccionar una opción',
464
- search_placeholder: 'Buscar...',
465
- upload_file: 'Subir archivo',
466
- choose_file: 'Elegir archivo',
467
- clear: 'Borrar',
468
- today: 'Hoy',
469
- invalid_email: 'Por favor, introduzca una dirección de correo electrónico válida',
470
- invalid_url: 'Por favor, introduzca una URL válida',
471
- invalid_number: 'Por favor, introduzca un número válido',
472
- drop_file_here: 'Suelte el archivo aquí o',
473
- browse: 'explorar',
474
- file_too_large: 'El archivo es demasiado grande',
475
- invalid_image: 'Seleccione un archivo de imagen',
476
- search_results: 'Resultados de búsqueda',
477
- no_results: 'No se encontraron resultados',
478
- load_failed_retry: 'Error al cargar — reintentar',
479
- loading: 'Cargando...',
480
- submit: 'Guardar',
481
- cancel: 'Cancelar',
482
- remove: 'Eliminar',
483
- add: 'Añadir',
484
- yes: 'Sí',
485
- no: 'No',
486
- // mrd-table footer
487
- table_of: 'de',
488
- download: 'Descargar',
489
- // mrd-table toolbar
490
- table_filter: 'Filtrar',
491
- table_filter_hide: 'Ocultar filtro',
492
- table_filter_active: 'activo',
493
- table_filter_clear_all: 'Borrar todos los filtros',
494
- table_new_record: 'Nuevo registro',
495
- table_export_excel: 'Exportar a Excel',
496
- doc_view_switch: 'Cambiar vista',
497
- doc_view_tree: 'Vista de árbol',
498
- doc_view_list: 'Vista de lista',
499
- // mrd-table filter popup
500
- filter_sorting: 'Ordenación',
501
- filter_ascending: 'Ascendente',
502
- filter_descending: 'Descendente',
503
- filter_section: 'Filtro',
504
- filter_apply: 'Aplicar',
505
- filter_clear: 'Borrar',
506
- filter_contains: 'Contiene',
507
- filter_starts_with: 'Empieza por',
508
- filter_equals: 'Igual a',
509
- filter_has_value: 'Tiene valor',
510
- filter_is_empty: 'Está vacío',
511
- filter_is_not_empty: 'No está vacío',
512
- filter_exact: 'Exacto',
513
- filter_range: 'Rango',
514
- filter_from: 'Desde',
515
- filter_to: 'Hasta',
516
- filter_all: 'Todos',
517
- filter_select_all: 'Todos',
518
- filter_select_none: 'Ninguno',
519
- filter_search_value: 'Valor de búsqueda...',
520
- filter_no_support: 'El filtrado no está disponible para este tipo de campo.',
521
- // mrd-table textblock
522
- textblock_show_more: 'Mostrar más',
523
- close: 'Cerrar',
524
- // history badge
525
- history_until: 'hasta',
526
- history_badge_tooltip: 'Valores anteriores',
527
- hyperlink_name: 'Texto del enlace (opcional)',
528
- },
529
- it: {
530
- required: 'Questo campo è obbligatorio',
531
- select_placeholder: "Seleziona un'opzione",
532
- search_placeholder: 'Cerca...',
533
- upload_file: 'Carica file',
534
- choose_file: 'Scegli file',
535
- clear: 'Cancella',
536
- today: 'Oggi',
537
- invalid_email: 'Inserisci un indirizzo email valido',
538
- invalid_url: 'Inserisci un URL valido',
539
- invalid_number: 'Inserisci un numero valido',
540
- drop_file_here: 'Trascina il file qui o',
541
- browse: 'sfoglia',
542
- file_too_large: 'Il file è troppo grande',
543
- invalid_image: 'Seleziona un file immagine',
544
- search_results: 'Risultati della ricerca',
545
- no_results: 'Nessun risultato trovato',
546
- load_failed_retry: 'Caricamento non riuscito — riprova',
547
- loading: 'Caricamento...',
548
- submit: 'Salva',
549
- cancel: 'Annulla',
550
- remove: 'Rimuovi',
551
- add: 'Aggiungi',
552
- yes: 'Sì',
553
- no: 'No',
554
- // mrd-table footer
555
- table_of: 'di',
556
- download: 'Scarica',
557
- // mrd-table toolbar
558
- table_filter: 'Filtra',
559
- table_filter_hide: 'Nascondi filtro',
560
- table_filter_active: 'attivo',
561
- table_filter_clear_all: 'Cancella tutti i filtri',
562
- table_new_record: 'Nuovo record',
563
- table_export_excel: 'Esporta in Excel',
564
- doc_view_switch: 'Cambia vista',
565
- doc_view_tree: 'Vista ad albero',
566
- doc_view_list: 'Vista elenco',
567
- // mrd-table filter popup
568
- filter_sorting: 'Ordinamento',
569
- filter_ascending: 'Crescente',
570
- filter_descending: 'Decrescente',
571
- filter_section: 'Filtro',
572
- filter_apply: 'Applica',
573
- filter_clear: 'Cancella',
574
- filter_contains: 'Contiene',
575
- filter_starts_with: 'Inizia con',
576
- filter_equals: 'Uguale a',
577
- filter_has_value: 'Ha valore',
578
- filter_is_empty: 'È vuoto',
579
- filter_is_not_empty: 'Non è vuoto',
580
- filter_exact: 'Esatto',
581
- filter_range: 'Intervallo',
582
- filter_from: 'Da',
583
- filter_to: 'A',
584
- filter_all: 'Tutti',
585
- filter_select_all: 'Tutti',
586
- filter_select_none: 'Nessuno',
587
- filter_search_value: 'Valore di ricerca...',
588
- filter_no_support: 'Il filtro non è disponibile per questo tipo di campo.',
589
- // mrd-table textblock
590
- textblock_show_more: 'Mostra altro',
591
- close: 'Chiudi',
592
- // history badge
593
- history_until: 'fino a',
594
- history_badge_tooltip: 'Valori precedenti',
595
- hyperlink_name: 'Testo del collegamento (opzionale)',
596
- },
597
- uk: {
598
- required: "Це поле обов'язкове",
599
- select_placeholder: 'Виберіть варіант',
600
- search_placeholder: 'Пошук...',
601
- upload_file: 'Завантажити файл',
602
- choose_file: 'Вибрати файл',
603
- clear: 'Очистити',
604
- today: 'Сьогодні',
605
- invalid_email: 'Будь ласка, введіть дійсну адресу електронної пошти',
606
- invalid_url: 'Будь ласка, введіть дійсну URL-адресу',
607
- invalid_number: 'Будь ласка, введіть дійсне число',
608
- drop_file_here: 'Перетягніть файл сюди або',
609
- browse: 'огляд',
610
- file_too_large: 'Файл занадто великий',
611
- invalid_image: 'Будь ласка, виберіть файл зображення',
612
- search_results: 'Результати пошуку',
613
- no_results: 'Результатів не знайдено',
614
- load_failed_retry: 'Не вдалося завантажити — повторити',
615
- loading: 'Завантаження...',
616
- submit: 'Зберегти',
617
- cancel: 'Скасувати',
618
- remove: 'Видалити',
619
- add: 'Додати',
620
- yes: 'Так',
621
- no: 'Ні',
622
- // mrd-table footer
623
- table_of: 'з',
624
- download: 'Завантажити',
625
- // mrd-table toolbar
626
- table_filter: 'Фільтрувати',
627
- table_filter_hide: 'Сховати фільтр',
628
- table_filter_active: 'активний',
629
- table_filter_clear_all: 'Очистити всі фільтри',
630
- table_new_record: 'Новий запис',
631
- table_export_excel: 'Експортувати до Excel',
632
- doc_view_switch: 'Змінити вигляд',
633
- doc_view_tree: 'Деревоподібний вигляд',
634
- doc_view_list: 'Список',
635
- // mrd-table filter popup
636
- filter_sorting: 'Сортування',
637
- filter_ascending: 'За зростанням',
638
- filter_descending: 'За спаданням',
639
- filter_section: 'Фільтр',
640
- filter_apply: 'Застосувати',
641
- filter_clear: 'Очистити',
642
- filter_contains: 'Містить',
643
- filter_starts_with: 'Починається з',
644
- filter_equals: 'Дорівнює',
645
- filter_has_value: 'Має значення',
646
- filter_is_empty: 'Порожнє',
647
- filter_is_not_empty: 'Не порожнє',
648
- filter_exact: 'Точно',
649
- filter_range: 'Діапазон',
650
- filter_from: 'Від',
651
- filter_to: 'До',
652
- filter_all: 'Всі',
653
- filter_select_all: 'Всі',
654
- filter_select_none: 'Жодного',
655
- filter_search_value: 'Значення для пошуку...',
656
- filter_no_support: 'Фільтрування недоступне для цього типу поля.',
657
- // mrd-table textblock
658
- textblock_show_more: 'Показати більше',
659
- close: 'Закрити',
660
- // history badge
661
- history_until: 'до',
662
- history_badge_tooltip: 'Попередні значення',
663
- hyperlink_name: "Текст посилання (необов'язково)",
664
- },
665
- };
666
- function t(key, locale) {
667
- var _a, _b, _c;
668
- const lang = (locale !== null && locale !== void 0 ? locale : 'en').split('-')[0].toLowerCase();
669
- const dict = (_a = translations[lang]) !== null && _a !== void 0 ? _a : translations['en'];
670
- return (_c = (_b = dict[key]) !== null && _b !== void 0 ? _b : translations['en'][key]) !== null && _c !== void 0 ? _c : key;
671
- }
672
-
673
36
  function validateRequired(value) {
674
37
  if (value === null || value === undefined)
675
38
  return false;
@@ -2914,110 +2277,6 @@ function buildContainerHref(item, selfHref, parentId) {
2914
2277
  return `/${base}/${tenant}/${item.fromClass}/${parentId}`;
2915
2278
  }
2916
2279
 
2917
- class CellRenderer {
2918
- static render(column, row, locale) {
2919
- var _a, _b, _c, _d;
2920
- if (column.type === ClientLayoutItemType.RELATION) {
2921
- const name = (_a = column.name) !== null && _a !== void 0 ? _a : '';
2922
- const link = (_b = row === null || row === void 0 ? void 0 : row._links) === null || _b === void 0 ? void 0 : _b[name];
2923
- if (!link)
2924
- return '';
2925
- if (Array.isArray(link))
2926
- return link.map((l) => { var _a; return (_a = l.name) !== null && _a !== void 0 ? _a : ''; }).filter(Boolean).join(', ');
2927
- return (_c = link.name) !== null && _c !== void 0 ? _c : '';
2928
- }
2929
- if (column.type !== ClientLayoutItemType.FIELD)
2930
- return '';
2931
- const name = (_d = column.name) !== null && _d !== void 0 ? _d : '';
2932
- const dataType = column.dataType;
2933
- const listItems = column.listItems;
2934
- const raw = row === null || row === void 0 ? void 0 : row[name];
2935
- if (raw == null || raw === '')
2936
- return '';
2937
- const values = Array.isArray(raw) ? raw : [raw];
2938
- return values
2939
- .map(v => CellRenderer.renderValue(dataType !== null && dataType !== void 0 ? dataType : 'TEXT', v, listItems !== null && listItems !== void 0 ? listItems : [], locale))
2940
- .filter(s => s !== '')
2941
- .join(', ');
2942
- }
2943
- static renderValue(dataType, value, listItems, locale) {
2944
- var _a, _b;
2945
- switch (dataType) {
2946
- case 'INTEGER':
2947
- return formatNumber(Number(value), locale, { maximumFractionDigits: 0 });
2948
- case 'DECIMAL':
2949
- return formatNumber(Number(value), locale);
2950
- case 'PERCENTAGE':
2951
- return formatPercentage(Number(value), locale);
2952
- case 'CURRENCY': {
2953
- const { amount, currency } = typeof value === 'object' && value !== null
2954
- ? value
2955
- : { amount: value, currency: '' };
2956
- return currency
2957
- ? formatCurrency(Number(amount), currency, locale)
2958
- : formatNumber(Number(amount), locale);
2959
- }
2960
- case 'DATE':
2961
- return formatDate(value, locale);
2962
- case 'DATETIME':
2963
- return formatDateTime(value, locale);
2964
- case 'TIME':
2965
- return formatTime(value, locale);
2966
- case 'BOOLEAN':
2967
- return value ? '✓' : '';
2968
- case 'FILE':
2969
- case 'IMAGE':
2970
- return typeof value === 'object' && value !== null ? ((_a = value.fileName) !== null && _a !== void 0 ? _a : '') : '';
2971
- case 'LIST': {
2972
- const item = listItems.find(li => li.key === String(value));
2973
- return (_b = item === null || item === void 0 ? void 0 : item.label) !== null && _b !== void 0 ? _b : String(value);
2974
- }
2975
- case 'TEXTBLOCK': {
2976
- const stripped = String(value).replace(/<[^>]*>/g, '');
2977
- const txt = document.createElement('textarea');
2978
- txt.innerHTML = stripped;
2979
- return txt.value.trim();
2980
- }
2981
- case 'LONGTEXT':
2982
- return String(value).replace(/[\r\n]+/g, ' ').trim();
2983
- case 'JSON': {
2984
- const str = typeof value === 'object' ? JSON.stringify(value) : String(value);
2985
- return str.replace(/[\r\n]+/g, ' ').trim();
2986
- }
2987
- case 'SECRET':
2988
- return value ? '••••••••' : '';
2989
- default:
2990
- return String(value);
2991
- }
2992
- }
2993
- /**
2994
- * Returns syntax-highlighted JSON as an HTML string with inline styles.
2995
- * compact=true → single line (no indentation); compact=false → pretty-printed.
2996
- */
2997
- static formatJson(value, compact = false) {
2998
- try {
2999
- const parsed = typeof value === 'string' ? JSON.parse(value) : value;
3000
- const json = compact ? JSON.stringify(parsed) : JSON.stringify(parsed, null, 2);
3001
- return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, match => {
3002
- let style = 'color:#2aa198';
3003
- if (/^"/.test(match)) {
3004
- style = /:$/.test(match) ? 'color:#881391' : 'color:#268bd2';
3005
- }
3006
- else if (/true|false/.test(match)) {
3007
- style = 'color:#b58900';
3008
- }
3009
- else if (/null/.test(match)) {
3010
- style = 'color:#dc322f';
3011
- }
3012
- return `<span style="${style}">${match}</span>`;
3013
- });
3014
- }
3015
- catch (_a) {
3016
- return String(value);
3017
- }
3018
- }
3019
- }
3020
-
3021
2280
  /** FILE and IMAGE cells share the same download button. */
3022
2281
  function downloadLink(ctx, href, fileName, label) {
3023
2282
  return (h("button", { class: "mrd-layout-section__download-link", onClick: () => href && ctx.on.download({ href, fileName }) }, h("svg", { class: "mrd-layout-section__file-icon", viewBox: "0 0 24 24", "aria-hidden": "true" }, h("path", { fill: "currentColor", d: "M14 2H6c-1.1 0-2 .9-2 2v16c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V8l-6-6zm-1 7V3.5L18.5 9H13zm-3 8l-3-3 1.41-1.41L10 14.17l4.59-4.58L16 11l-6 6z" })), label));
@@ -5275,6 +4534,2417 @@ const MrdTextField = class {
5275
4534
  };
5276
4535
  MrdTextField.style = mrdTextFieldCss();
5277
4536
 
4537
+ /*! @license DOMPurify 3.4.12 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.4.12/LICENSE */
4538
+
4539
+ function _arrayLikeToArray(r, a) {
4540
+ (null == a || a > r.length) && (a = r.length);
4541
+ for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
4542
+ return n;
4543
+ }
4544
+ function _arrayWithHoles(r) {
4545
+ if (Array.isArray(r)) return r;
4546
+ }
4547
+ function _iterableToArrayLimit(r, l) {
4548
+ var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
4549
+ if (null != t) {
4550
+ var e,
4551
+ n,
4552
+ i,
4553
+ u,
4554
+ a = [],
4555
+ f = true,
4556
+ o = false;
4557
+ try {
4558
+ if (i = (t = t.call(r)).next, 0 === l) ; else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = true);
4559
+ } catch (r) {
4560
+ o = true, n = r;
4561
+ } finally {
4562
+ try {
4563
+ if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return;
4564
+ } finally {
4565
+ if (o) throw n;
4566
+ }
4567
+ }
4568
+ return a;
4569
+ }
4570
+ }
4571
+ function _nonIterableRest() {
4572
+ throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
4573
+ }
4574
+ function _slicedToArray(r, e) {
4575
+ return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest();
4576
+ }
4577
+ function _unsupportedIterableToArray(r, a) {
4578
+ if (r) {
4579
+ if ("string" == typeof r) return _arrayLikeToArray(r, a);
4580
+ var t = {}.toString.call(r).slice(8, -1);
4581
+ return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;
4582
+ }
4583
+ }
4584
+
4585
+ const entries = Object.entries,
4586
+ setPrototypeOf = Object.setPrototypeOf,
4587
+ isFrozen = Object.isFrozen,
4588
+ getPrototypeOf = Object.getPrototypeOf,
4589
+ getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
4590
+ let freeze = Object.freeze,
4591
+ seal = Object.seal,
4592
+ create = Object.create; // eslint-disable-line import/no-mutable-exports
4593
+ let _ref = typeof Reflect !== 'undefined' && Reflect,
4594
+ apply = _ref.apply,
4595
+ construct = _ref.construct;
4596
+ if (!freeze) {
4597
+ freeze = function freeze(x) {
4598
+ return x;
4599
+ };
4600
+ }
4601
+ if (!seal) {
4602
+ seal = function seal(x) {
4603
+ return x;
4604
+ };
4605
+ }
4606
+ if (!apply) {
4607
+ apply = function apply(func, thisArg) {
4608
+ for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
4609
+ args[_key - 2] = arguments[_key];
4610
+ }
4611
+ return func.apply(thisArg, args);
4612
+ };
4613
+ }
4614
+ if (!construct) {
4615
+ construct = function construct(Func) {
4616
+ for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
4617
+ args[_key2 - 1] = arguments[_key2];
4618
+ }
4619
+ return new Func(...args);
4620
+ };
4621
+ }
4622
+ const arrayForEach = unapply(Array.prototype.forEach);
4623
+ const arrayLastIndexOf = unapply(Array.prototype.lastIndexOf);
4624
+ const arrayPop = unapply(Array.prototype.pop);
4625
+ const arrayPush = unapply(Array.prototype.push);
4626
+ const arraySplice = unapply(Array.prototype.splice);
4627
+ const arrayIsArray = Array.isArray;
4628
+ const stringToLowerCase = unapply(String.prototype.toLowerCase);
4629
+ const stringToString = unapply(String.prototype.toString);
4630
+ const stringMatch = unapply(String.prototype.match);
4631
+ const stringReplace = unapply(String.prototype.replace);
4632
+ const stringIndexOf = unapply(String.prototype.indexOf);
4633
+ const stringTrim = unapply(String.prototype.trim);
4634
+ const numberToString = unapply(Number.prototype.toString);
4635
+ const booleanToString = unapply(Boolean.prototype.toString);
4636
+ const bigintToString = typeof BigInt === 'undefined' ? null : unapply(BigInt.prototype.toString);
4637
+ const symbolToString = typeof Symbol === 'undefined' ? null : unapply(Symbol.prototype.toString);
4638
+ const objectHasOwnProperty = unapply(Object.prototype.hasOwnProperty);
4639
+ const objectToString = unapply(Object.prototype.toString);
4640
+ const regExpTest = unapply(RegExp.prototype.test);
4641
+ const typeErrorCreate = unconstruct(TypeError);
4642
+ /**
4643
+ * Creates a new function that calls the given function with a specified thisArg and arguments.
4644
+ *
4645
+ * @param func - The function to be wrapped and called.
4646
+ * @returns A new function that calls the given function with a specified thisArg and arguments.
4647
+ */
4648
+ function unapply(func) {
4649
+ return function (thisArg) {
4650
+ if (thisArg instanceof RegExp) {
4651
+ thisArg.lastIndex = 0;
4652
+ }
4653
+ for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
4654
+ args[_key3 - 1] = arguments[_key3];
4655
+ }
4656
+ return apply(func, thisArg, args);
4657
+ };
4658
+ }
4659
+ /**
4660
+ * Creates a new function that constructs an instance of the given constructor function with the provided arguments.
4661
+ *
4662
+ * @param func - The constructor function to be wrapped and called.
4663
+ * @returns A new function that constructs an instance of the given constructor function with the provided arguments.
4664
+ */
4665
+ function unconstruct(Func) {
4666
+ return function () {
4667
+ for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
4668
+ args[_key4] = arguments[_key4];
4669
+ }
4670
+ return construct(Func, args);
4671
+ };
4672
+ }
4673
+ /**
4674
+ * Add properties to a lookup table
4675
+ *
4676
+ * @param set - The set to which elements will be added.
4677
+ * @param array - The array containing elements to be added to the set.
4678
+ * @param transformCaseFunc - An optional function to transform the case of each element before adding to the set.
4679
+ * @returns The modified set with added elements.
4680
+ */
4681
+ function addToSet(set, array) {
4682
+ let transformCaseFunc = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : stringToLowerCase;
4683
+ if (setPrototypeOf) {
4684
+ // Make 'in' and truthy checks like Boolean(set.constructor)
4685
+ // independent of any properties defined on Object.prototype.
4686
+ // Prevent prototype setters from intercepting set as a this value.
4687
+ setPrototypeOf(set, null);
4688
+ }
4689
+ if (!arrayIsArray(array)) {
4690
+ return set;
4691
+ }
4692
+ let l = array.length;
4693
+ while (l--) {
4694
+ let element = array[l];
4695
+ if (typeof element === 'string') {
4696
+ const lcElement = transformCaseFunc(element);
4697
+ if (lcElement !== element) {
4698
+ // Config presets (e.g. tags.js, attrs.js) are immutable.
4699
+ if (!isFrozen(array)) {
4700
+ array[l] = lcElement;
4701
+ }
4702
+ element = lcElement;
4703
+ }
4704
+ }
4705
+ set[element] = true;
4706
+ }
4707
+ return set;
4708
+ }
4709
+ /**
4710
+ * Clean up an array to harden against CSPP
4711
+ *
4712
+ * @param array - The array to be cleaned.
4713
+ * @returns The cleaned version of the array
4714
+ */
4715
+ function cleanArray(array) {
4716
+ for (let index = 0; index < array.length; index++) {
4717
+ const isPropertyExist = objectHasOwnProperty(array, index);
4718
+ if (!isPropertyExist) {
4719
+ array[index] = null;
4720
+ }
4721
+ }
4722
+ return array;
4723
+ }
4724
+ /**
4725
+ * Shallow clone an object
4726
+ *
4727
+ * @param object - The object to be cloned.
4728
+ * @returns A new object that copies the original.
4729
+ */
4730
+ function clone(object) {
4731
+ const newObject = create(null);
4732
+ for (const _ref2 of entries(object)) {
4733
+ var _ref3 = _slicedToArray(_ref2, 2);
4734
+ const property = _ref3[0];
4735
+ const value = _ref3[1];
4736
+ const isPropertyExist = objectHasOwnProperty(object, property);
4737
+ if (isPropertyExist) {
4738
+ if (arrayIsArray(value)) {
4739
+ newObject[property] = cleanArray(value);
4740
+ } else if (value && typeof value === 'object' && value.constructor === Object) {
4741
+ newObject[property] = clone(value);
4742
+ } else {
4743
+ newObject[property] = value;
4744
+ }
4745
+ }
4746
+ }
4747
+ return newObject;
4748
+ }
4749
+ /**
4750
+ * Convert non-node values into strings without depending on direct property access.
4751
+ *
4752
+ * @param value - The value to stringify.
4753
+ * @returns A string representation of the provided value.
4754
+ */
4755
+ function stringifyValue(value) {
4756
+ switch (typeof value) {
4757
+ case 'string':
4758
+ {
4759
+ return value;
4760
+ }
4761
+ case 'number':
4762
+ {
4763
+ return numberToString(value);
4764
+ }
4765
+ case 'boolean':
4766
+ {
4767
+ return booleanToString(value);
4768
+ }
4769
+ case 'bigint':
4770
+ {
4771
+ return bigintToString ? bigintToString(value) : '0';
4772
+ }
4773
+ case 'symbol':
4774
+ {
4775
+ return symbolToString ? symbolToString(value) : 'Symbol()';
4776
+ }
4777
+ case 'undefined':
4778
+ {
4779
+ return objectToString(value);
4780
+ }
4781
+ case 'function':
4782
+ case 'object':
4783
+ {
4784
+ if (value === null) {
4785
+ return objectToString(value);
4786
+ }
4787
+ const valueAsRecord = value;
4788
+ const valueToString = lookupGetter(valueAsRecord, 'toString');
4789
+ if (typeof valueToString === 'function') {
4790
+ const stringified = valueToString(valueAsRecord);
4791
+ return typeof stringified === 'string' ? stringified : objectToString(stringified);
4792
+ }
4793
+ return objectToString(value);
4794
+ }
4795
+ default:
4796
+ {
4797
+ return objectToString(value);
4798
+ }
4799
+ }
4800
+ }
4801
+ /**
4802
+ * This method automatically checks if the prop is function or getter and behaves accordingly.
4803
+ *
4804
+ * @param object - The object to look up the getter function in its prototype chain.
4805
+ * @param prop - The property name for which to find the getter function.
4806
+ * @returns The getter function found in the prototype chain or a fallback function.
4807
+ */
4808
+ function lookupGetter(object, prop) {
4809
+ while (object !== null) {
4810
+ const desc = getOwnPropertyDescriptor(object, prop);
4811
+ if (desc) {
4812
+ if (desc.get) {
4813
+ return unapply(desc.get);
4814
+ }
4815
+ if (typeof desc.value === 'function') {
4816
+ return unapply(desc.value);
4817
+ }
4818
+ }
4819
+ object = getPrototypeOf(object);
4820
+ }
4821
+ function fallbackValue() {
4822
+ return null;
4823
+ }
4824
+ return fallbackValue;
4825
+ }
4826
+ function isRegex(value) {
4827
+ try {
4828
+ regExpTest(value, '');
4829
+ return true;
4830
+ } catch (_unused) {
4831
+ return false;
4832
+ }
4833
+ }
4834
+
4835
+ 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']);
4836
+ 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']);
4837
+ 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']);
4838
+ // List of SVG elements that are disallowed by default.
4839
+ // We still need to know them so that we can do namespace
4840
+ // checks properly in case one wants to add them to
4841
+ // allow-list.
4842
+ 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']);
4843
+ 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']);
4844
+ // Similarly to SVG, we want to know all MathML elements,
4845
+ // even those that we disallow by default.
4846
+ const mathMlDisallowed = freeze(['maction', 'maligngroup', 'malignmark', 'mlongdiv', 'mscarries', 'mscarry', 'msgroup', 'mstack', 'msline', 'msrow', 'semantics', 'annotation', 'annotation-xml', 'mprescripts', 'none']);
4847
+ const text = freeze(['#text']);
4848
+
4849
+ const html = freeze(['accept', 'action', 'align', 'alt', 'autocapitalize', 'autocomplete', 'autopictureinpicture', 'autoplay', 'background', 'bgcolor', 'border', 'capture', 'cellpadding', 'cellspacing', 'checked', 'cite', 'class', 'clear', 'color', 'cols', 'colspan', 'command', 'commandfor', 'controls', 'controlslist', 'coords', 'crossorigin', 'datetime', 'decoding', 'default', 'dir', 'disabled', 'disablepictureinpicture', 'disableremoteplayback', 'download', 'draggable', 'enctype', 'enterkeyhint', 'exportparts', 'face', 'for', 'headers', 'height', 'hidden', 'high', 'href', 'hreflang', 'id', 'inert', 'inputmode', 'integrity', 'ismap', 'kind', 'label', 'lang', 'list', 'loading', 'loop', 'low', 'max', 'maxlength', 'media', 'method', 'min', 'minlength', 'multiple', 'muted', 'name', 'nonce', 'noshade', 'novalidate', 'nowrap', 'open', 'optimum', 'part', 'pattern', 'placeholder', 'playsinline', 'popover', 'popovertarget', 'popovertargetaction', 'poster', 'preload', 'pubdate', 'radiogroup', 'readonly', 'rel', 'required', 'rev', 'reversed', 'role', 'rows', 'rowspan', 'spellcheck', 'scope', 'selected', 'shape', 'size', 'sizes', 'slot', 'span', 'srclang', 'start', 'src', 'srcset', 'step', 'style', 'summary', 'tabindex', 'title', 'translate', 'type', 'usemap', 'valign', 'value', 'width', 'wrap', 'xmlns']);
4850
+ const svg = freeze(['accent-height', 'accumulate', 'additive', 'alignment-baseline', 'amplitude', 'ascent', 'attributename', 'attributetype', 'azimuth', 'basefrequency', 'baseline-shift', 'begin', 'bias', 'by', 'class', 'clip', 'clippathunits', 'clip-path', 'clip-rule', 'color', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'cx', 'cy', 'd', 'dx', 'dy', 'diffuseconstant', 'direction', 'display', 'divisor', 'dominant-baseline', 'dur', 'edgemode', 'elevation', 'end', 'exponent', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'filterunits', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'fx', 'fy', 'g1', 'g2', 'glyph-name', 'glyphref', 'gradientunits', 'gradienttransform', 'height', 'href', 'id', 'image-rendering', 'in', 'in2', 'intercept', 'k', 'k1', 'k2', 'k3', 'k4', 'kerning', 'keypoints', 'keysplines', 'keytimes', 'lang', 'lengthadjust', 'letter-spacing', 'kernelmatrix', 'kernelunitlength', 'lighting-color', 'local', 'marker-end', 'marker-mid', 'marker-start', 'markerheight', 'markerunits', 'markerwidth', 'maskcontentunits', 'maskunits', 'max', 'mask', 'mask-type', 'media', 'method', 'mode', 'min', 'name', 'numoctaves', 'offset', 'operator', 'opacity', 'order', 'orient', 'orientation', 'origin', 'overflow', 'paint-order', 'path', 'pathlength', 'patterncontentunits', 'patterntransform', 'patternunits', 'points', 'preservealpha', 'preserveaspectratio', 'primitiveunits', 'r', 'rx', 'ry', 'radius', 'refx', 'refy', 'repeatcount', 'repeatdur', 'restart', 'result', 'rotate', 'scale', 'seed', 'shape-rendering', 'slope', 'specularconstant', 'specularexponent', 'spreadmethod', 'startoffset', 'stddeviation', 'stitchtiles', 'stop-color', 'stop-opacity', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke', 'stroke-width', 'style', 'surfacescale', 'systemlanguage', 'tabindex', 'tablevalues', 'targetx', 'targety', 'transform', 'transform-origin', 'text-anchor', 'text-decoration', 'text-orientation', 'text-rendering', 'textlength', 'type', 'u1', 'u2', 'unicode', 'values', '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']);
4851
+ const mathMl = freeze(['accent', 'accentunder', 'align', 'bevelled', 'close', 'columnalign', 'columnlines', 'columnspacing', 'columnspan', 'denomalign', 'depth', 'dir', 'display', 'displaystyle', 'encoding', 'fence', 'frame', 'height', 'href', 'id', 'largeop', 'length', 'linethickness', 'lquote', 'lspace', 'mathbackground', 'mathcolor', 'mathsize', 'mathvariant', 'maxsize', 'minsize', 'movablelimits', 'notation', 'numalign', 'open', 'rowalign', 'rowlines', 'rowspacing', 'rowspan', 'rspace', 'rquote', 'scriptlevel', 'scriptminsize', 'scriptsizemultiplier', 'selection', 'separator', 'separators', 'stretchy', 'subscriptshift', 'supscriptshift', 'symmetric', 'voffset', 'width', 'xmlns']);
4852
+ const xml = freeze(['xlink:href', 'xml:id', 'xlink:title', 'xml:space', 'xmlns:xlink']);
4853
+
4854
+ const MUSTACHE_EXPR = seal(/{{[\w\W]*|^[\w\W]*}}/g);
4855
+ const ERB_EXPR = seal(/<%[\w\W]*|^[\w\W]*%>/g);
4856
+ const TMPLIT_EXPR = seal(/\${[\w\W]*/g);
4857
+ const DATA_ATTR = seal(/^data-[\-\w.\u00B7-\uFFFF]+$/); // eslint-disable-line no-useless-escape
4858
+ const ARIA_ATTR = seal(/^aria-[\-\w]+$/); // eslint-disable-line no-useless-escape
4859
+ 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
4860
+ );
4861
+ const IS_SCRIPT_OR_DATA = seal(/^(?:\w+script|data):/i);
4862
+ const ATTR_WHITESPACE = seal(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g // eslint-disable-line no-control-regex
4863
+ );
4864
+ const DOCTYPE_NAME = seal(/^html$/i);
4865
+ const CUSTOM_ELEMENT = seal(/^[a-z][.\w]*(-[.\w]+)+$/i);
4866
+ // Markup-significant character probes used by _sanitizeElements.
4867
+ // Shared module-level instances are safe despite the sticky /g flags:
4868
+ // unapply() resets lastIndex for RegExp receivers before every call.
4869
+ const ELEMENT_MARKUP_PROBE = seal(/<[/\w!]/g);
4870
+ const COMMENT_MARKUP_PROBE = seal(/<[/\w]/g);
4871
+ const FALLBACK_TAG_CLOSE = seal(/<\/no(script|embed|frames)/i);
4872
+ const SELF_CLOSING_TAG = seal(/\/>/i);
4873
+
4874
+ // https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType
4875
+ const NODE_TYPE = {
4876
+ element: 1,
4877
+ text: 3,
4878
+ // Deprecated
4879
+ processingInstruction: 7,
4880
+ comment: 8,
4881
+ document: 9,
4882
+ documentFragment: 11};
4883
+ const getGlobal = function getGlobal() {
4884
+ return typeof window === 'undefined' ? null : window;
4885
+ };
4886
+ /**
4887
+ * Creates a no-op policy for internal use only.
4888
+ * Don't export this function outside this module!
4889
+ * @param trustedTypes The policy factory.
4890
+ * @param purifyHostElement The Script element used to load DOMPurify (to determine policy name suffix).
4891
+ * @return The policy created (or null, if Trusted Types
4892
+ * are not supported or creating the policy failed).
4893
+ */
4894
+ const _createTrustedTypesPolicy = function _createTrustedTypesPolicy(trustedTypes, purifyHostElement) {
4895
+ if (typeof trustedTypes !== 'object' || typeof trustedTypes.createPolicy !== 'function') {
4896
+ return null;
4897
+ }
4898
+ // Allow the callers to control the unique policy name
4899
+ // by adding a data-tt-policy-suffix to the script element with the DOMPurify.
4900
+ // Policy creation with duplicate names throws in Trusted Types.
4901
+ let suffix = null;
4902
+ const ATTR_NAME = 'data-tt-policy-suffix';
4903
+ if (purifyHostElement && purifyHostElement.hasAttribute(ATTR_NAME)) {
4904
+ suffix = purifyHostElement.getAttribute(ATTR_NAME);
4905
+ }
4906
+ const policyName = 'dompurify' + (suffix ? '#' + suffix : '');
4907
+ try {
4908
+ return trustedTypes.createPolicy(policyName, {
4909
+ createHTML(html) {
4910
+ return html;
4911
+ },
4912
+ createScriptURL(scriptUrl) {
4913
+ return scriptUrl;
4914
+ }
4915
+ });
4916
+ } catch (_) {
4917
+ // Policy creation failed (most likely another DOMPurify script has
4918
+ // already run). Skip creating the policy, as this will only cause errors
4919
+ // if TT are enforced.
4920
+ console.warn('TrustedTypes policy ' + policyName + ' could not be created.');
4921
+ return null;
4922
+ }
4923
+ };
4924
+ const _createHooksMap = function _createHooksMap() {
4925
+ return {
4926
+ afterSanitizeAttributes: [],
4927
+ afterSanitizeElements: [],
4928
+ afterSanitizeShadowDOM: [],
4929
+ beforeSanitizeAttributes: [],
4930
+ beforeSanitizeElements: [],
4931
+ beforeSanitizeShadowDOM: [],
4932
+ uponSanitizeAttribute: [],
4933
+ uponSanitizeElement: [],
4934
+ uponSanitizeShadowNode: []
4935
+ };
4936
+ };
4937
+ /**
4938
+ * Resolve a set-valued configuration option: a fresh set built from
4939
+ * cfg[key] when it is an own array property (seeded with a clone of
4940
+ * options.base when given, case-normalized via options.transform),
4941
+ * the fallback set otherwise.
4942
+ *
4943
+ * @param cfg the cloned, prototype-free configuration object
4944
+ * @param key the configuration property to read
4945
+ * @param fallback the set to use when the option is absent or not an array
4946
+ * @param options transform and optional base set to merge into
4947
+ * @returns the resolved set
4948
+ */
4949
+ const _resolveSetOption = function _resolveSetOption(cfg, key, fallback, options) {
4950
+ return objectHasOwnProperty(cfg, key) && arrayIsArray(cfg[key]) ? addToSet(options.base ? clone(options.base) : {}, cfg[key], options.transform) : fallback;
4951
+ };
4952
+ function createDOMPurify() {
4953
+ let window = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getGlobal();
4954
+ const DOMPurify = root => createDOMPurify(root);
4955
+ DOMPurify.version = '3.4.12';
4956
+ DOMPurify.removed = [];
4957
+ if (!window || !window.document || window.document.nodeType !== NODE_TYPE.document || !window.Element) {
4958
+ // Not running in a browser, provide a factory function
4959
+ // so that you can pass your own Window
4960
+ DOMPurify.isSupported = false;
4961
+ return DOMPurify;
4962
+ }
4963
+ let document = window.document;
4964
+ const originalDocument = document;
4965
+ const currentScript = originalDocument.currentScript;
4966
+ const HTMLTemplateElement = window.HTMLTemplateElement,
4967
+ Node = window.Node,
4968
+ Element = window.Element,
4969
+ NodeFilter = window.NodeFilter;
4970
+ const DOMParser = window.DOMParser,
4971
+ trustedTypes = window.trustedTypes;
4972
+ const ElementPrototype = Element.prototype;
4973
+ const cloneNode = lookupGetter(ElementPrototype, 'cloneNode');
4974
+ const remove = lookupGetter(ElementPrototype, 'remove');
4975
+ const getNextSibling = lookupGetter(ElementPrototype, 'nextSibling');
4976
+ const getChildNodes = lookupGetter(ElementPrototype, 'childNodes');
4977
+ const getParentNode = lookupGetter(ElementPrototype, 'parentNode');
4978
+ const getShadowRoot = lookupGetter(ElementPrototype, 'shadowRoot');
4979
+ const getAttributes = lookupGetter(ElementPrototype, 'attributes');
4980
+ const getNodeType = Node && Node.prototype ? lookupGetter(Node.prototype, 'nodeType') : null;
4981
+ const getNodeName = Node && Node.prototype ? lookupGetter(Node.prototype, 'nodeName') : null;
4982
+ // As per issue #47, the web-components registry is inherited by a
4983
+ // new document created via createHTMLDocument. As per the spec
4984
+ // (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-registries)
4985
+ // a new empty registry is used when creating a template contents owner
4986
+ // document, so we use that as our parent document to ensure nothing
4987
+ // is inherited.
4988
+ if (typeof HTMLTemplateElement === 'function') {
4989
+ const template = document.createElement('template');
4990
+ if (template.content && template.content.ownerDocument) {
4991
+ document = template.content.ownerDocument;
4992
+ }
4993
+ }
4994
+ let trustedTypesPolicy;
4995
+ let emptyHTML = '';
4996
+ // The instance's own internal Trusted Types policy. Unlike a caller-supplied
4997
+ // `TRUSTED_TYPES_POLICY`, this is created at most once — Trusted Types throws
4998
+ // on duplicate policy names — and is the only policy allowed to persist
4999
+ // across configurations and survive `clearConfig()`.
5000
+ let defaultTrustedTypesPolicy;
5001
+ let defaultTrustedTypesPolicyResolved = false;
5002
+ // Tracks whether we are already inside a call to the configured Trusted Types
5003
+ // policy (`createHTML` or `createScriptURL`). If a supplied policy callback
5004
+ // itself calls `DOMPurify.sanitize` (the cause of #1422), `sanitize` would
5005
+ // re-enter the policy and recurse until the stack overflows. We detect that
5006
+ // re-entry and throw a clear, actionable error instead. The guard is shared
5007
+ // across both callbacks, because either one re-entering `sanitize` triggers
5008
+ // the same unbounded recursion.
5009
+ let IN_TRUSTED_TYPES_POLICY = 0;
5010
+ const _assertNotInTrustedTypesPolicy = function _assertNotInTrustedTypesPolicy() {
5011
+ if (IN_TRUSTED_TYPES_POLICY > 0) {
5012
+ throw typeErrorCreate('A configured TRUSTED_TYPES_POLICY callback (createHTML or ' + 'createScriptURL) must not call DOMPurify.sanitize, as that causes ' + 'infinite recursion. Do not pass a policy whose callbacks wrap ' + 'DOMPurify as TRUSTED_TYPES_POLICY; see the "DOMPurify and Trusted ' + 'Types" section of the README.');
5013
+ }
5014
+ };
5015
+ const _createTrustedHTML = function _createTrustedHTML(html) {
5016
+ _assertNotInTrustedTypesPolicy();
5017
+ IN_TRUSTED_TYPES_POLICY++;
5018
+ try {
5019
+ return trustedTypesPolicy.createHTML(html);
5020
+ } finally {
5021
+ IN_TRUSTED_TYPES_POLICY--;
5022
+ }
5023
+ };
5024
+ const _createTrustedScriptURL = function _createTrustedScriptURL(scriptUrl) {
5025
+ _assertNotInTrustedTypesPolicy();
5026
+ IN_TRUSTED_TYPES_POLICY++;
5027
+ try {
5028
+ return trustedTypesPolicy.createScriptURL(scriptUrl);
5029
+ } finally {
5030
+ IN_TRUSTED_TYPES_POLICY--;
5031
+ }
5032
+ };
5033
+ // Lazily resolve (and cache) the instance's internal default policy.
5034
+ // Resolution is attempted at most once: a successful `createPolicy` cannot be
5035
+ // repeated (Trusted Types throws on duplicate names), and a failed or
5036
+ // unsupported attempt must not be retried on every parse.
5037
+ const _getDefaultTrustedTypesPolicy = function _getDefaultTrustedTypesPolicy() {
5038
+ if (!defaultTrustedTypesPolicyResolved) {
5039
+ defaultTrustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, currentScript);
5040
+ defaultTrustedTypesPolicyResolved = true;
5041
+ }
5042
+ return defaultTrustedTypesPolicy;
5043
+ };
5044
+ const _document = document,
5045
+ implementation = _document.implementation,
5046
+ createNodeIterator = _document.createNodeIterator,
5047
+ createDocumentFragment = _document.createDocumentFragment,
5048
+ getElementsByTagName = _document.getElementsByTagName;
5049
+ const importNode = originalDocument.importNode;
5050
+ let hooks = _createHooksMap();
5051
+ /**
5052
+ * Expose whether this browser supports running the full DOMPurify.
5053
+ */
5054
+ DOMPurify.isSupported = typeof entries === 'function' && typeof getParentNode === 'function' && implementation && implementation.createHTMLDocument !== undefined;
5055
+ const MUSTACHE_EXPR$1 = MUSTACHE_EXPR,
5056
+ ERB_EXPR$1 = ERB_EXPR,
5057
+ TMPLIT_EXPR$1 = TMPLIT_EXPR,
5058
+ DATA_ATTR$1 = DATA_ATTR,
5059
+ ARIA_ATTR$1 = ARIA_ATTR,
5060
+ IS_SCRIPT_OR_DATA$1 = IS_SCRIPT_OR_DATA,
5061
+ ATTR_WHITESPACE$1 = ATTR_WHITESPACE,
5062
+ CUSTOM_ELEMENT$1 = CUSTOM_ELEMENT;
5063
+ let IS_ALLOWED_URI$1 = IS_ALLOWED_URI;
5064
+ /**
5065
+ * We consider the elements and attributes below to be safe. Ideally
5066
+ * don't add any new ones but feel free to remove unwanted ones.
5067
+ */
5068
+ /* allowed element names */
5069
+ let ALLOWED_TAGS = null;
5070
+ const DEFAULT_ALLOWED_TAGS = addToSet({}, [...html$1, ...svg$1, ...svgFilters, ...mathMl$1, ...text]);
5071
+ /* Allowed attribute names */
5072
+ let ALLOWED_ATTR = null;
5073
+ const DEFAULT_ALLOWED_ATTR = addToSet({}, [...html, ...svg, ...mathMl, ...xml]);
5074
+ /*
5075
+ * Configure how DOMPurify should handle custom elements and their attributes as well as customized built-in elements.
5076
+ * @property {RegExp|Function|null} tagNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any custom elements)
5077
+ * @property {RegExp|Function|null} attributeNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any attributes not on the allow list)
5078
+ * @property {boolean} allowCustomizedBuiltInElements allow custom elements derived from built-ins if they pass CUSTOM_ELEMENT_HANDLING.tagNameCheck. Default: `false`.
5079
+ */
5080
+ let CUSTOM_ELEMENT_HANDLING = Object.seal(create(null, {
5081
+ tagNameCheck: {
5082
+ writable: true,
5083
+ configurable: false,
5084
+ enumerable: true,
5085
+ value: null
5086
+ },
5087
+ attributeNameCheck: {
5088
+ writable: true,
5089
+ configurable: false,
5090
+ enumerable: true,
5091
+ value: null
5092
+ },
5093
+ allowCustomizedBuiltInElements: {
5094
+ writable: true,
5095
+ configurable: false,
5096
+ enumerable: true,
5097
+ value: false
5098
+ }
5099
+ }));
5100
+ /* Explicitly forbidden tags (overrides ALLOWED_TAGS/ADD_TAGS) */
5101
+ let FORBID_TAGS = null;
5102
+ /* Explicitly forbidden attributes (overrides ALLOWED_ATTR/ADD_ATTR) */
5103
+ let FORBID_ATTR = null;
5104
+ /* Config object to store ADD_TAGS/ADD_ATTR functions (when used as functions) */
5105
+ const EXTRA_ELEMENT_HANDLING = Object.seal(create(null, {
5106
+ tagCheck: {
5107
+ writable: true,
5108
+ configurable: false,
5109
+ enumerable: true,
5110
+ value: null
5111
+ },
5112
+ attributeCheck: {
5113
+ writable: true,
5114
+ configurable: false,
5115
+ enumerable: true,
5116
+ value: null
5117
+ }
5118
+ }));
5119
+ /* Decide if ARIA attributes are okay */
5120
+ let ALLOW_ARIA_ATTR = true;
5121
+ /* Decide if custom data attributes are okay */
5122
+ let ALLOW_DATA_ATTR = true;
5123
+ /* Decide if unknown protocols are okay */
5124
+ let ALLOW_UNKNOWN_PROTOCOLS = false;
5125
+ /* Decide if self-closing tags in attributes are allowed.
5126
+ * Usually removed due to a mXSS issue in jQuery 3.0 */
5127
+ let ALLOW_SELF_CLOSE_IN_ATTR = true;
5128
+ /* Output should be safe for common template engines.
5129
+ * This means, DOMPurify removes data attributes, mustaches and ERB
5130
+ */
5131
+ let SAFE_FOR_TEMPLATES = false;
5132
+ /* Output should be safe even for XML used within HTML and alike.
5133
+ * This means, DOMPurify removes comments when containing risky content.
5134
+ */
5135
+ let SAFE_FOR_XML = true;
5136
+ /* Decide if document with <html>... should be returned */
5137
+ let WHOLE_DOCUMENT = false;
5138
+ /* Track whether config is already set on this instance of DOMPurify. */
5139
+ let SET_CONFIG = false;
5140
+ /* Pristine allowlist bindings captured at setConfig() time. On the
5141
+ * persistent-config path sanitize() restores the sets from these before
5142
+ * the per-walk hook clone-guard, so a hook's in-call widening cannot
5143
+ * carry across calls. Null until setConfig() is called; reset by
5144
+ * clearConfig(). */
5145
+ let SET_CONFIG_ALLOWED_TAGS = null;
5146
+ let SET_CONFIG_ALLOWED_ATTR = null;
5147
+ /* Decide if all elements (e.g. style, script) must be children of
5148
+ * document.body. By default, browsers might move them to document.head */
5149
+ let FORCE_BODY = false;
5150
+ /* Decide if a DOM `HTMLBodyElement` should be returned, instead of a html
5151
+ * string (or a TrustedHTML object if Trusted Types are supported).
5152
+ * If `WHOLE_DOCUMENT` is enabled a `HTMLHtmlElement` will be returned instead
5153
+ */
5154
+ let RETURN_DOM = false;
5155
+ /* Decide if a DOM `DocumentFragment` should be returned, instead of a html
5156
+ * string (or a TrustedHTML object if Trusted Types are supported) */
5157
+ let RETURN_DOM_FRAGMENT = false;
5158
+ /* Try to return a Trusted Type object instead of a string, return a string in
5159
+ * case Trusted Types are not supported */
5160
+ let RETURN_TRUSTED_TYPE = false;
5161
+ /* Output should be free from DOM clobbering attacks?
5162
+ * This sanitizes markups named with colliding, clobberable built-in DOM APIs.
5163
+ */
5164
+ let SANITIZE_DOM = true;
5165
+ /* Achieve full DOM Clobbering protection by isolating the namespace of named
5166
+ * properties and JS variables, mitigating attacks that abuse the HTML/DOM spec rules.
5167
+ *
5168
+ * HTML/DOM spec rules that enable DOM Clobbering:
5169
+ * - Named Access on Window (§7.3.3)
5170
+ * - DOM Tree Accessors (§3.1.5)
5171
+ * - Form Element Parent-Child Relations (§4.10.3)
5172
+ * - Iframe srcdoc / Nested WindowProxies (§4.8.5)
5173
+ * - HTMLCollection (§4.2.10.2)
5174
+ *
5175
+ * Namespace isolation is implemented by prefixing `id` and `name` attributes
5176
+ * with a constant string, i.e., `user-content-`
5177
+ */
5178
+ let SANITIZE_NAMED_PROPS = false;
5179
+ const SANITIZE_NAMED_PROPS_PREFIX = 'user-content-';
5180
+ /* Keep element content when removing element? */
5181
+ let KEEP_CONTENT = true;
5182
+ /* If a `Node` is passed to sanitize(), then performs sanitization in-place instead
5183
+ * of importing it into a new Document and returning a sanitized copy */
5184
+ let IN_PLACE = false;
5185
+ /* Allow usage of profiles like html, svg and mathMl */
5186
+ let USE_PROFILES = {};
5187
+ /* Tags to ignore content of when KEEP_CONTENT is true */
5188
+ let FORBID_CONTENTS = null;
5189
+ const DEFAULT_FORBID_CONTENTS = addToSet({}, ['annotation-xml', 'audio', 'colgroup', 'desc', 'foreignobject', 'head', 'iframe', 'math', 'mi', 'mn', 'mo', 'ms', 'mtext', 'noembed', 'noframes', 'noscript', 'plaintext', 'script',
5190
+ // <selectedcontent> mirrors the selected <option>'s subtree, cloned by
5191
+ // the UA (customizable <select>) — including any on* handlers — and the
5192
+ // engine re-mirrors synchronously whenever a removal changes which
5193
+ // option/selectedcontent is current, even inside DOMPurify's inert
5194
+ // DOMParser document. Hoisting its children on removal re-inserts a fresh
5195
+ // mirror target ahead of the walk, which the engine refills, looping
5196
+ // forever (DoS) and amplifying output. Dropping its content on removal
5197
+ // (rather than hoisting) breaks that cascade; the content is a duplicate
5198
+ // of the option, which is sanitized on its own. See campaign-3 F1/F6.
5199
+ 'selectedcontent', 'style', 'svg', 'template', 'thead', 'title', 'video', 'xmp']);
5200
+ /* Tags that are safe for data: URIs */
5201
+ let DATA_URI_TAGS = null;
5202
+ const DEFAULT_DATA_URI_TAGS = addToSet({}, ['audio', 'video', 'img', 'source', 'image', 'track']);
5203
+ /* Attributes safe for values like "javascript:" */
5204
+ let URI_SAFE_ATTRIBUTES = null;
5205
+ const DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, ['alt', 'class', 'for', 'id', 'label', 'name', 'pattern', 'placeholder', 'role', 'summary', 'title', 'value', 'style', 'xmlns']);
5206
+ const MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';
5207
+ const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';
5208
+ const HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';
5209
+ /* Document namespace */
5210
+ let NAMESPACE = HTML_NAMESPACE;
5211
+ let IS_EMPTY_INPUT = false;
5212
+ /* Allowed XHTML+XML namespaces */
5213
+ let ALLOWED_NAMESPACES = null;
5214
+ const DEFAULT_ALLOWED_NAMESPACES = addToSet({}, [MATHML_NAMESPACE, SVG_NAMESPACE, HTML_NAMESPACE], stringToString);
5215
+ const DEFAULT_MATHML_TEXT_INTEGRATION_POINTS = freeze(['mi', 'mo', 'mn', 'ms', 'mtext']);
5216
+ let MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, DEFAULT_MATHML_TEXT_INTEGRATION_POINTS);
5217
+ const DEFAULT_HTML_INTEGRATION_POINTS = freeze(['annotation-xml']);
5218
+ let HTML_INTEGRATION_POINTS = addToSet({}, DEFAULT_HTML_INTEGRATION_POINTS);
5219
+ // Certain elements are allowed in both SVG and HTML
5220
+ // namespace. We need to specify them explicitly
5221
+ // so that they don't get erroneously deleted from
5222
+ // HTML namespace.
5223
+ const COMMON_SVG_AND_HTML_ELEMENTS = addToSet({}, ['title', 'style', 'font', 'a', 'script']);
5224
+ /* Parsing of strict XHTML documents */
5225
+ let PARSER_MEDIA_TYPE = null;
5226
+ const SUPPORTED_PARSER_MEDIA_TYPES = ['application/xhtml+xml', 'text/html'];
5227
+ const DEFAULT_PARSER_MEDIA_TYPE = 'text/html';
5228
+ let transformCaseFunc = null;
5229
+ /* Keep a reference to config to pass to hooks */
5230
+ let CONFIG = null;
5231
+ /* Ideally, do not touch anything below this line */
5232
+ /* ______________________________________________ */
5233
+ const formElement = document.createElement('form');
5234
+ const isRegexOrFunction = function isRegexOrFunction(testValue) {
5235
+ return testValue instanceof RegExp || testValue instanceof Function;
5236
+ };
5237
+ /**
5238
+ * _parseConfig
5239
+ *
5240
+ * @param cfg optional config literal
5241
+ */
5242
+ // eslint-disable-next-line complexity
5243
+ const _parseConfig = function _parseConfig() {
5244
+ let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
5245
+ if (CONFIG && CONFIG === cfg) {
5246
+ return;
5247
+ }
5248
+ /* Shield configuration object from tampering */
5249
+ if (!cfg || typeof cfg !== 'object') {
5250
+ cfg = {};
5251
+ }
5252
+ /* Shield configuration object from prototype pollution */
5253
+ cfg = clone(cfg);
5254
+ PARSER_MEDIA_TYPE =
5255
+ // eslint-disable-next-line unicorn/prefer-includes
5256
+ SUPPORTED_PARSER_MEDIA_TYPES.indexOf(cfg.PARSER_MEDIA_TYPE) === -1 ? DEFAULT_PARSER_MEDIA_TYPE : cfg.PARSER_MEDIA_TYPE;
5257
+ // HTML tags and attributes are not case-sensitive, converting to lowercase. Keeping XHTML as is.
5258
+ transformCaseFunc = PARSER_MEDIA_TYPE === 'application/xhtml+xml' ? stringToString : stringToLowerCase;
5259
+ /* Set configuration parameters */
5260
+ ALLOWED_TAGS = _resolveSetOption(cfg, 'ALLOWED_TAGS', DEFAULT_ALLOWED_TAGS, {
5261
+ transform: transformCaseFunc
5262
+ });
5263
+ ALLOWED_ATTR = _resolveSetOption(cfg, 'ALLOWED_ATTR', DEFAULT_ALLOWED_ATTR, {
5264
+ transform: transformCaseFunc
5265
+ });
5266
+ ALLOWED_NAMESPACES = _resolveSetOption(cfg, 'ALLOWED_NAMESPACES', DEFAULT_ALLOWED_NAMESPACES, {
5267
+ transform: stringToString
5268
+ });
5269
+ URI_SAFE_ATTRIBUTES = _resolveSetOption(cfg, 'ADD_URI_SAFE_ATTR', DEFAULT_URI_SAFE_ATTRIBUTES, {
5270
+ transform: transformCaseFunc,
5271
+ base: DEFAULT_URI_SAFE_ATTRIBUTES
5272
+ });
5273
+ DATA_URI_TAGS = _resolveSetOption(cfg, 'ADD_DATA_URI_TAGS', DEFAULT_DATA_URI_TAGS, {
5274
+ transform: transformCaseFunc,
5275
+ base: DEFAULT_DATA_URI_TAGS
5276
+ });
5277
+ FORBID_CONTENTS = _resolveSetOption(cfg, 'FORBID_CONTENTS', DEFAULT_FORBID_CONTENTS, {
5278
+ transform: transformCaseFunc
5279
+ });
5280
+ FORBID_TAGS = _resolveSetOption(cfg, 'FORBID_TAGS', clone({}), {
5281
+ transform: transformCaseFunc
5282
+ });
5283
+ FORBID_ATTR = _resolveSetOption(cfg, 'FORBID_ATTR', clone({}), {
5284
+ transform: transformCaseFunc
5285
+ });
5286
+ USE_PROFILES = objectHasOwnProperty(cfg, 'USE_PROFILES') ? cfg.USE_PROFILES && typeof cfg.USE_PROFILES === 'object' ? clone(cfg.USE_PROFILES) : cfg.USE_PROFILES : false;
5287
+ ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true
5288
+ ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true
5289
+ ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; // Default false
5290
+ ALLOW_SELF_CLOSE_IN_ATTR = cfg.ALLOW_SELF_CLOSE_IN_ATTR !== false; // Default true
5291
+ SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false; // Default false
5292
+ SAFE_FOR_XML = cfg.SAFE_FOR_XML !== false; // Default true
5293
+ WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false; // Default false
5294
+ RETURN_DOM = cfg.RETURN_DOM || false; // Default false
5295
+ RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false; // Default false
5296
+ RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false; // Default false
5297
+ FORCE_BODY = cfg.FORCE_BODY || false; // Default false
5298
+ SANITIZE_DOM = cfg.SANITIZE_DOM !== false; // Default true
5299
+ SANITIZE_NAMED_PROPS = cfg.SANITIZE_NAMED_PROPS || false; // Default false
5300
+ KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true
5301
+ IN_PLACE = cfg.IN_PLACE || false; // Default false
5302
+ IS_ALLOWED_URI$1 = isRegex(cfg.ALLOWED_URI_REGEXP) ? cfg.ALLOWED_URI_REGEXP : IS_ALLOWED_URI; // Default regexp
5303
+ NAMESPACE = typeof cfg.NAMESPACE === 'string' ? cfg.NAMESPACE : HTML_NAMESPACE; // Default HTML namespace
5304
+ MATHML_TEXT_INTEGRATION_POINTS = objectHasOwnProperty(cfg, 'MATHML_TEXT_INTEGRATION_POINTS') && cfg.MATHML_TEXT_INTEGRATION_POINTS && typeof cfg.MATHML_TEXT_INTEGRATION_POINTS === 'object' ? clone(cfg.MATHML_TEXT_INTEGRATION_POINTS) : addToSet({}, DEFAULT_MATHML_TEXT_INTEGRATION_POINTS); // Default built-in map
5305
+ HTML_INTEGRATION_POINTS = objectHasOwnProperty(cfg, 'HTML_INTEGRATION_POINTS') && cfg.HTML_INTEGRATION_POINTS && typeof cfg.HTML_INTEGRATION_POINTS === 'object' ? clone(cfg.HTML_INTEGRATION_POINTS) : addToSet({}, DEFAULT_HTML_INTEGRATION_POINTS); // Default built-in map
5306
+ const customElementHandling = objectHasOwnProperty(cfg, 'CUSTOM_ELEMENT_HANDLING') && cfg.CUSTOM_ELEMENT_HANDLING && typeof cfg.CUSTOM_ELEMENT_HANDLING === 'object' ? clone(cfg.CUSTOM_ELEMENT_HANDLING) : create(null);
5307
+ CUSTOM_ELEMENT_HANDLING = create(null);
5308
+ if (objectHasOwnProperty(customElementHandling, 'tagNameCheck') && isRegexOrFunction(customElementHandling.tagNameCheck)) {
5309
+ CUSTOM_ELEMENT_HANDLING.tagNameCheck = customElementHandling.tagNameCheck; // Default undefined
5310
+ }
5311
+ if (objectHasOwnProperty(customElementHandling, 'attributeNameCheck') && isRegexOrFunction(customElementHandling.attributeNameCheck)) {
5312
+ CUSTOM_ELEMENT_HANDLING.attributeNameCheck = customElementHandling.attributeNameCheck; // Default undefined
5313
+ }
5314
+ if (objectHasOwnProperty(customElementHandling, 'allowCustomizedBuiltInElements') && typeof customElementHandling.allowCustomizedBuiltInElements === 'boolean') {
5315
+ CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = customElementHandling.allowCustomizedBuiltInElements; // Default undefined
5316
+ }
5317
+ seal(CUSTOM_ELEMENT_HANDLING);
5318
+ if (SAFE_FOR_TEMPLATES) {
5319
+ ALLOW_DATA_ATTR = false;
5320
+ }
5321
+ if (RETURN_DOM_FRAGMENT) {
5322
+ RETURN_DOM = true;
5323
+ }
5324
+ /* Parse profile info */
5325
+ if (USE_PROFILES) {
5326
+ ALLOWED_TAGS = addToSet({}, text);
5327
+ ALLOWED_ATTR = create(null);
5328
+ if (USE_PROFILES.html === true) {
5329
+ addToSet(ALLOWED_TAGS, html$1);
5330
+ addToSet(ALLOWED_ATTR, html);
5331
+ }
5332
+ if (USE_PROFILES.svg === true) {
5333
+ addToSet(ALLOWED_TAGS, svg$1);
5334
+ addToSet(ALLOWED_ATTR, svg);
5335
+ addToSet(ALLOWED_ATTR, xml);
5336
+ }
5337
+ if (USE_PROFILES.svgFilters === true) {
5338
+ addToSet(ALLOWED_TAGS, svgFilters);
5339
+ addToSet(ALLOWED_ATTR, svg);
5340
+ addToSet(ALLOWED_ATTR, xml);
5341
+ }
5342
+ if (USE_PROFILES.mathMl === true) {
5343
+ addToSet(ALLOWED_TAGS, mathMl$1);
5344
+ addToSet(ALLOWED_ATTR, mathMl);
5345
+ addToSet(ALLOWED_ATTR, xml);
5346
+ }
5347
+ }
5348
+ /* Always reset function-based ADD_TAGS / ADD_ATTR checks to prevent
5349
+ * leaking across calls when switching from function to array config */
5350
+ EXTRA_ELEMENT_HANDLING.tagCheck = null;
5351
+ EXTRA_ELEMENT_HANDLING.attributeCheck = null;
5352
+ /* Merge configuration parameters */
5353
+ if (objectHasOwnProperty(cfg, 'ADD_TAGS')) {
5354
+ if (typeof cfg.ADD_TAGS === 'function') {
5355
+ EXTRA_ELEMENT_HANDLING.tagCheck = cfg.ADD_TAGS;
5356
+ } else if (arrayIsArray(cfg.ADD_TAGS)) {
5357
+ if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) {
5358
+ ALLOWED_TAGS = clone(ALLOWED_TAGS);
5359
+ }
5360
+ addToSet(ALLOWED_TAGS, cfg.ADD_TAGS, transformCaseFunc);
5361
+ }
5362
+ }
5363
+ if (objectHasOwnProperty(cfg, 'ADD_ATTR')) {
5364
+ if (typeof cfg.ADD_ATTR === 'function') {
5365
+ EXTRA_ELEMENT_HANDLING.attributeCheck = cfg.ADD_ATTR;
5366
+ } else if (arrayIsArray(cfg.ADD_ATTR)) {
5367
+ if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) {
5368
+ ALLOWED_ATTR = clone(ALLOWED_ATTR);
5369
+ }
5370
+ addToSet(ALLOWED_ATTR, cfg.ADD_ATTR, transformCaseFunc);
5371
+ }
5372
+ }
5373
+ if (objectHasOwnProperty(cfg, 'ADD_URI_SAFE_ATTR') && arrayIsArray(cfg.ADD_URI_SAFE_ATTR)) {
5374
+ addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR, transformCaseFunc);
5375
+ }
5376
+ if (objectHasOwnProperty(cfg, 'FORBID_CONTENTS') && arrayIsArray(cfg.FORBID_CONTENTS)) {
5377
+ if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {
5378
+ FORBID_CONTENTS = clone(FORBID_CONTENTS);
5379
+ }
5380
+ addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS, transformCaseFunc);
5381
+ }
5382
+ if (objectHasOwnProperty(cfg, 'ADD_FORBID_CONTENTS') && arrayIsArray(cfg.ADD_FORBID_CONTENTS)) {
5383
+ if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {
5384
+ FORBID_CONTENTS = clone(FORBID_CONTENTS);
5385
+ }
5386
+ addToSet(FORBID_CONTENTS, cfg.ADD_FORBID_CONTENTS, transformCaseFunc);
5387
+ }
5388
+ /* Add #text in case KEEP_CONTENT is set to true */
5389
+ if (KEEP_CONTENT) {
5390
+ ALLOWED_TAGS['#text'] = true;
5391
+ }
5392
+ /* Add html, head and body to ALLOWED_TAGS in case WHOLE_DOCUMENT is true */
5393
+ if (WHOLE_DOCUMENT) {
5394
+ addToSet(ALLOWED_TAGS, ['html', 'head', 'body']);
5395
+ }
5396
+ /* Add tbody to ALLOWED_TAGS in case tables are permitted, see #286, #365 */
5397
+ if (ALLOWED_TAGS.table) {
5398
+ addToSet(ALLOWED_TAGS, ['tbody']);
5399
+ delete FORBID_TAGS.tbody;
5400
+ }
5401
+ // Re-derive the active Trusted Types policy from this configuration on
5402
+ // every parse. The active policy must never be sticky closure state that
5403
+ // outlives the config that set it: a caller-supplied policy left in place
5404
+ // after `clearConfig()` — or after a later call that supplied none, or
5405
+ // `TRUSTED_TYPES_POLICY: null` — could sign a subsequent "default"
5406
+ // `RETURN_TRUSTED_TYPE` result with a foreign, possibly unsafe policy.
5407
+ // See GHSA-vxr8-fq34-vvx9.
5408
+ if (cfg.TRUSTED_TYPES_POLICY) {
5409
+ if (typeof cfg.TRUSTED_TYPES_POLICY.createHTML !== 'function') {
5410
+ throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');
5411
+ }
5412
+ if (typeof cfg.TRUSTED_TYPES_POLICY.createScriptURL !== 'function') {
5413
+ throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');
5414
+ }
5415
+ // A caller-supplied policy applies to this configuration only.
5416
+ const previousTrustedTypesPolicy = trustedTypesPolicy;
5417
+ trustedTypesPolicy = cfg.TRUSTED_TYPES_POLICY;
5418
+ // Sign local variables required by `sanitize`. If the supplied policy's
5419
+ // `createHTML` is circular (i.e. it calls `DOMPurify.sanitize`), this
5420
+ // throws via the re-entrancy guard. Restore the previous policy first so
5421
+ // the instance is not left in a poisoned state. See #1422.
5422
+ try {
5423
+ emptyHTML = _createTrustedHTML('');
5424
+ } catch (error) {
5425
+ trustedTypesPolicy = previousTrustedTypesPolicy;
5426
+ throw error;
5427
+ }
5428
+ } else if (cfg.TRUSTED_TYPES_POLICY === null) {
5429
+ // Explicit opt-out for this call: perform no Trusted Types signing and
5430
+ // create nothing (so a strict `trusted-types` CSP that disallows a
5431
+ // `dompurify` policy can still call `sanitize` from inside its own
5432
+ // policy — see #1422). Resetting to `undefined` rather than a sticky
5433
+ // `null` also drops any previously retained caller policy, so it cannot
5434
+ // resurface on a later call, while still allowing the next config-less
5435
+ // call to restore the internal default policy. See GHSA-vxr8-fq34-vvx9.
5436
+ trustedTypesPolicy = undefined;
5437
+ emptyHTML = '';
5438
+ } else {
5439
+ // No policy supplied: keep the currently active policy if one is set — a
5440
+ // previously supplied policy is intentionally sticky across config-less
5441
+ // calls — otherwise fall back to the instance's own internal policy,
5442
+ // created at most once. (A policy supplied for a *single* call still
5443
+ // lingers by design; what must not linger is a policy whose configuration
5444
+ // has been torn down via `clearConfig()`, which restores the default.)
5445
+ if (trustedTypesPolicy === undefined) {
5446
+ trustedTypesPolicy = _getDefaultTrustedTypesPolicy();
5447
+ }
5448
+ // Sign internal variables only when a policy is active. A falsy policy
5449
+ // (Trusted Types unsupported, creation failed, or an explicit opt-out)
5450
+ // leaves `emptyHTML` as a plain string, so we never call `.createHTML` on
5451
+ // a non-policy and throw. See #1422.
5452
+ if (trustedTypesPolicy && typeof emptyHTML === 'string') {
5453
+ emptyHTML = _createTrustedHTML('');
5454
+ }
5455
+ }
5456
+ // Prevent further manipulation of configuration.
5457
+ // Not available in IE8, Safari 5, etc.
5458
+ if (freeze) {
5459
+ freeze(cfg);
5460
+ }
5461
+ CONFIG = cfg;
5462
+ };
5463
+ /* Keep track of all possible SVG and MathML tags
5464
+ * so that we can perform the namespace checks
5465
+ * correctly. */
5466
+ const ALL_SVG_TAGS = addToSet({}, [...svg$1, ...svgFilters, ...svgDisallowed]);
5467
+ const ALL_MATHML_TAGS = addToSet({}, [...mathMl$1, ...mathMlDisallowed]);
5468
+ /**
5469
+ * Namespace rules for an element in the SVG namespace.
5470
+ *
5471
+ * @param tagName the element's lowercase tag name
5472
+ * @param parent the (possibly simulated) parent node
5473
+ * @param parentTagName the parent's lowercase tag name
5474
+ * @returns true if a spec-compliant parser could produce this element
5475
+ */
5476
+ const _checkSvgNamespace = function _checkSvgNamespace(tagName, parent, parentTagName) {
5477
+ // The only way to switch from HTML namespace to SVG
5478
+ // is via <svg>. If it happens via any other tag, then
5479
+ // it should be killed.
5480
+ if (parent.namespaceURI === HTML_NAMESPACE) {
5481
+ return tagName === 'svg';
5482
+ }
5483
+ // The only way to switch from MathML to SVG is via <svg>
5484
+ // if the parent is either <annotation-xml> or a MathML
5485
+ // text integration point.
5486
+ if (parent.namespaceURI === MATHML_NAMESPACE) {
5487
+ return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);
5488
+ }
5489
+ // We only allow elements that are defined in SVG
5490
+ // spec. All others are disallowed in SVG namespace.
5491
+ return Boolean(ALL_SVG_TAGS[tagName]);
5492
+ };
5493
+ /**
5494
+ * Namespace rules for an element in the MathML namespace.
5495
+ *
5496
+ * @param tagName the element's lowercase tag name
5497
+ * @param parent the (possibly simulated) parent node
5498
+ * @param parentTagName the parent's lowercase tag name
5499
+ * @returns true if a spec-compliant parser could produce this element
5500
+ */
5501
+ const _checkMathMlNamespace = function _checkMathMlNamespace(tagName, parent, parentTagName) {
5502
+ // The only way to switch from HTML namespace to MathML
5503
+ // is via <math>. If it happens via any other tag, then
5504
+ // it should be killed.
5505
+ if (parent.namespaceURI === HTML_NAMESPACE) {
5506
+ return tagName === 'math';
5507
+ }
5508
+ // The only way to switch from SVG to MathML is via
5509
+ // <math> and HTML integration points
5510
+ if (parent.namespaceURI === SVG_NAMESPACE) {
5511
+ return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName];
5512
+ }
5513
+ // We only allow elements that are defined in MathML
5514
+ // spec. All others are disallowed in MathML namespace.
5515
+ return Boolean(ALL_MATHML_TAGS[tagName]);
5516
+ };
5517
+ /**
5518
+ * Namespace rules for an element in the HTML namespace.
5519
+ *
5520
+ * @param tagName the element's lowercase tag name
5521
+ * @param parent the (possibly simulated) parent node
5522
+ * @param parentTagName the parent's lowercase tag name
5523
+ * @returns true if a spec-compliant parser could produce this element
5524
+ */
5525
+ const _checkHtmlNamespace = function _checkHtmlNamespace(tagName, parent, parentTagName) {
5526
+ // The only way to switch from SVG to HTML is via
5527
+ // HTML integration points, and from MathML to HTML
5528
+ // is via MathML text integration points
5529
+ if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) {
5530
+ return false;
5531
+ }
5532
+ if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {
5533
+ return false;
5534
+ }
5535
+ // We disallow tags that are specific for MathML
5536
+ // or SVG and should never appear in HTML namespace
5537
+ return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]);
5538
+ };
5539
+ /**
5540
+ * @param element a DOM element whose namespace is being checked
5541
+ * @returns Return false if the element has a
5542
+ * namespace that a spec-compliant parser would never
5543
+ * return. Return true otherwise.
5544
+ */
5545
+ const _checkValidNamespace = function _checkValidNamespace(element) {
5546
+ let parent = getParentNode(element);
5547
+ // In JSDOM, if we're inside shadow DOM, then parentNode
5548
+ // can be null. We just simulate parent in this case.
5549
+ if (!parent || !parent.tagName) {
5550
+ parent = {
5551
+ namespaceURI: NAMESPACE,
5552
+ tagName: 'template'
5553
+ };
5554
+ }
5555
+ const tagName = stringToLowerCase(element.tagName);
5556
+ const parentTagName = stringToLowerCase(parent.tagName);
5557
+ if (!ALLOWED_NAMESPACES[element.namespaceURI]) {
5558
+ return false;
5559
+ }
5560
+ if (element.namespaceURI === SVG_NAMESPACE) {
5561
+ return _checkSvgNamespace(tagName, parent, parentTagName);
5562
+ }
5563
+ if (element.namespaceURI === MATHML_NAMESPACE) {
5564
+ return _checkMathMlNamespace(tagName, parent, parentTagName);
5565
+ }
5566
+ if (element.namespaceURI === HTML_NAMESPACE) {
5567
+ return _checkHtmlNamespace(tagName, parent, parentTagName);
5568
+ }
5569
+ // For XHTML and XML documents that support custom namespaces
5570
+ if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && ALLOWED_NAMESPACES[element.namespaceURI]) {
5571
+ return true;
5572
+ }
5573
+ // The code should never reach this place (this means
5574
+ // that the element somehow got namespace that is not
5575
+ // HTML, SVG, MathML or allowed via ALLOWED_NAMESPACES).
5576
+ // Return false just in case.
5577
+ return false;
5578
+ };
5579
+ /**
5580
+ * _forceRemove
5581
+ *
5582
+ * @param node a DOM node
5583
+ */
5584
+ const _forceRemove = function _forceRemove(node) {
5585
+ arrayPush(DOMPurify.removed, {
5586
+ element: node
5587
+ });
5588
+ try {
5589
+ // eslint-disable-next-line unicorn/prefer-dom-node-remove
5590
+ getParentNode(node).removeChild(node);
5591
+ } catch (_) {
5592
+ /* The normal detach failed — this is reached for a parentless node
5593
+ (getParentNode() is null, so .removeChild throws). Element.prototype
5594
+ .remove() is itself a spec no-op on a parentless node, so a recorded
5595
+ "removal" would otherwise hand the caller back an intact,
5596
+ payload-bearing node (e.g. a detached IN_PLACE root the mXSS canary or
5597
+ the style-with-element-child rule decided to kill). Fail closed by
5598
+ throwing — exactly as a clobbered root does at the IN_PLACE entry —
5599
+ rather than trying to "neutralize" the node via its own methods.
5600
+ Neutralizing would mean calling getAttributeNames()/removeAttribute()
5601
+ on the node, both of which a <form> root can clobber via a named child
5602
+ (and _isClobbered does not even probe getAttributeNames), so the
5603
+ neutralize step could itself be silently defeated, leaving the payload
5604
+ intact. A throw touches only the cached, clobber-safe remove() and
5605
+ getParentNode(). Generalizes GHSA-r47g-fvhr-h676 (clobbered-form root)
5606
+ to every root-kill reason. REPORT-3.
5607
+ This lives inside the catch, so it never fires for a normally-removed
5608
+ in-tree node: those have a parent, removeChild() succeeds, and the
5609
+ catch is not entered. Only a kept (parentless) root reaches here. */
5610
+ remove(node);
5611
+ if (!getParentNode(node)) {
5612
+ throw typeErrorCreate('a node selected for removal could not be detached from its tree ' + 'and cannot be safely returned; refusing to sanitize in place');
5613
+ }
5614
+ }
5615
+ };
5616
+ /**
5617
+ * _neutralizeRoot
5618
+ *
5619
+ * Fail-closed teardown of an in-place root after the sanitize walk aborts
5620
+ * (campaign-3 F2). An internal throw mid-walk — e.g. a page-registered
5621
+ * custom element's reaction detaches a node so `_forceRemove`'s deliberate
5622
+ * parentless guard throws, or any other re-entrant engine mutation — would
5623
+ * otherwise leave the caller's *live* tree half-sanitized, with everything
5624
+ * after the abort point still carrying its handlers. There is no safe way
5625
+ * to resume the walk (the tree mutated under us), so we strip the root bare:
5626
+ * remove every child and every attribute, then let the caller's catch see
5627
+ * the original error. Clobber-safe (cached `remove`/`childNodes`/`attributes`
5628
+ * getters; the root was already clobber-pre-flighted at the IN_PLACE entry).
5629
+ *
5630
+ * @param root the in-place root to empty
5631
+ */
5632
+ const _neutralizeRoot = function _neutralizeRoot(root) {
5633
+ /* Strip every disallowed attribute (on* handlers included) off the whole
5634
+ subtree BEFORE detaching anything. Detaching first would hand back
5635
+ handler-bearing originals (e.g. an already-loading `<img onerror>`)
5636
+ whose queued resource event still fires in page scope after we throw.
5637
+ Clobber-safe reads; a doomed clobbered node's own attributes are
5638
+ irrelevant while its non-clobbered descendants are reached and scrubbed. */
5639
+ _neutralizeSubtree(root);
5640
+ const childNodes = getChildNodes(root);
5641
+ if (childNodes) {
5642
+ const snapshot = [];
5643
+ arrayForEach(childNodes, child => {
5644
+ arrayPush(snapshot, child);
5645
+ });
5646
+ arrayForEach(snapshot, child => {
5647
+ try {
5648
+ remove(child);
5649
+ } catch (_) {
5650
+ /* Best-effort teardown; a still-attached child is handled below */
5651
+ }
5652
+ });
5653
+ }
5654
+ const attributes = getAttributes(root);
5655
+ if (attributes) {
5656
+ for (let i = attributes.length - 1; i >= 0; --i) {
5657
+ const attribute = attributes[i];
5658
+ const name = attribute && attribute.name;
5659
+ if (typeof name === 'string') {
5660
+ try {
5661
+ root.removeAttribute(name);
5662
+ } catch (_) {
5663
+ /* Clobbered removeAttribute — ignore (fail-closed best effort) */
5664
+ }
5665
+ }
5666
+ }
5667
+ }
5668
+ };
5669
+ /**
5670
+ * _removeAttribute
5671
+ *
5672
+ * @param name an Attribute name
5673
+ * @param element a DOM node
5674
+ */
5675
+ const _removeAttribute = function _removeAttribute(name, element) {
5676
+ try {
5677
+ arrayPush(DOMPurify.removed, {
5678
+ attribute: element.getAttributeNode(name),
5679
+ from: element
5680
+ });
5681
+ } catch (_) {
5682
+ arrayPush(DOMPurify.removed, {
5683
+ attribute: null,
5684
+ from: element
5685
+ });
5686
+ }
5687
+ element.removeAttribute(name);
5688
+ // We void attribute values for unremovable "is" attributes
5689
+ if (name === 'is') {
5690
+ if (RETURN_DOM || RETURN_DOM_FRAGMENT) {
5691
+ try {
5692
+ _forceRemove(element);
5693
+ } catch (_) {}
5694
+ } else {
5695
+ try {
5696
+ element.setAttribute(name, '');
5697
+ } catch (_) {}
5698
+ }
5699
+ }
5700
+ };
5701
+ /**
5702
+ * _stripDisallowedAttributes
5703
+ *
5704
+ * Removes every attribute the active configuration does not allow from a
5705
+ * single element, using the same allowlist as the main attribute pass (so
5706
+ * `on*` handlers go, but no `/^on/` blocklist is introduced). Used only to
5707
+ * neutralise nodes that are being discarded from an in-place tree.
5708
+ *
5709
+ * @param element the element to strip
5710
+ */
5711
+ const _stripDisallowedAttributes = function _stripDisallowedAttributes(element) {
5712
+ const attributes = getAttributes(element);
5713
+ if (!attributes) {
5714
+ return;
5715
+ }
5716
+ for (let i = attributes.length - 1; i >= 0; --i) {
5717
+ const attribute = attributes[i];
5718
+ const name = attribute && attribute.name;
5719
+ if (typeof name !== 'string' || ALLOWED_ATTR[transformCaseFunc(name)]) {
5720
+ continue;
5721
+ }
5722
+ try {
5723
+ element.removeAttribute(name);
5724
+ } catch (_) {
5725
+ /* Clobbered removeAttribute on a doomed node — ignore */
5726
+ }
5727
+ }
5728
+ };
5729
+ /**
5730
+ * _neutralizeSubtree
5731
+ *
5732
+ * Completes the audit-5 F1 fix across every removal path. The KEEP_CONTENT
5733
+ * move-hoist neutralises only disallowed-tag removals; clobber, mXSS-canary,
5734
+ * namespace, comment, processing-instruction and KEEP_CONTENT:false removals
5735
+ * all drop their subtree wholesale via `_forceRemove`. On the IN_PLACE path
5736
+ * those dropped nodes are detached from the caller's LIVE tree but a
5737
+ * handler-bearing original among them (an `<img onerror>`/`<video>` that was
5738
+ * loading) keeps its queued resource event, which fires in page scope after
5739
+ * sanitize returns. This walks a removed subtree and strips every attribute
5740
+ * the active configuration does not allow — so `on*` handlers are cancelled
5741
+ * through the SAME allowlist that governs kept nodes, not a separate `/^on/`
5742
+ * blocklist. Run synchronously before sanitize returns, i.e. before any
5743
+ * queued event can fire. Hook-free by design: these nodes leave the output,
5744
+ * so firing attribute hooks for them would be surprising. Clobber-safe reads;
5745
+ * a doomed clobbered node may shadow `removeAttribute` (its own attributes are
5746
+ * irrelevant — it is discarded — while its non-clobbered descendants, e.g.
5747
+ * the `<img>`, are reached and scrubbed).
5748
+ *
5749
+ * @param root the root of a removed subtree to neutralise
5750
+ */
5751
+ const _neutralizeSubtree = function _neutralizeSubtree(root) {
5752
+ const stack = [root];
5753
+ while (stack.length > 0) {
5754
+ const node = stack.pop();
5755
+ const nodeType = getNodeType ? getNodeType(node) : node.nodeType;
5756
+ if (nodeType === NODE_TYPE.element) {
5757
+ _stripDisallowedAttributes(node);
5758
+ }
5759
+ const childNodes = getChildNodes(node);
5760
+ if (childNodes) {
5761
+ for (let i = childNodes.length - 1; i >= 0; --i) {
5762
+ stack.push(childNodes[i]);
5763
+ }
5764
+ }
5765
+ }
5766
+ };
5767
+ /**
5768
+ * _neutralizePatchLinkage
5769
+ *
5770
+ * IN_PLACE entry pre-pass (declarative-partial-updates / streaming
5771
+ * hardening, https://github.com/WICG/declarative-partial-updates).
5772
+ *
5773
+ * The main walk strips patch linkage (`for`/`patchsrc`) and removes range
5774
+ * markers (PIs / markup comments) node-by-node, in document order, AS it
5775
+ * reaches each node. On a live in-place root that leaves a window: from the
5776
+ * moment the root is connected until the walk arrives at a given node, that
5777
+ * node's linkage is live. A patch applied on connection/stream can fire as
5778
+ * a microtask during the walk and inject or teleport an unsanitized DOM
5779
+ * range into a region the iterator has already passed and will not revisit,
5780
+ * so the post-return "tree is sanitized" contract is violated. Sweep the
5781
+ * whole tree once up front and sever every linkage before the walk begins,
5782
+ * closing that window.
5783
+ *
5784
+ * This CANNOT undo a patch that already fired before sanitize ran — that is
5785
+ * the irreducible "do not IN_PLACE a live-connected attacker tree" caveat —
5786
+ * but it closes everything from sanitize-start onward. Gated on SAFE_FOR_XML
5787
+ * to group with the rest of the declarative-partial-updates handling and
5788
+ * stay overridable, consistent with the codebase.
5789
+ *
5790
+ * Clobber-safe traversal (cached childNodes getter); per-node try/catch so a
5791
+ * clobbered root cannot defeat the sweep of its non-clobbered descendants.
5792
+ *
5793
+ * NOTE (pending real-Chrome confirmation, see test/declarative-patch-probe
5794
+ * .html Q1): this mirrors the existing policy of keeping `for` on
5795
+ * <label>/<output>. If the shipping feature can drive a patch through a
5796
+ * surviving `for`-on-label/output + `id` pair, this pre-pass and the
5797
+ * attribute check at _isBasicCustomElement's caller must additionally drop
5798
+ * that pair on the IN_PLACE path. Left as-is until the taxonomy is verified.
5799
+ *
5800
+ * @param root the in-place root to sweep
5801
+ */
5802
+ const _neutralizePatchLinkage = function _neutralizePatchLinkage(root) {
5803
+ if (!SAFE_FOR_XML) {
5804
+ return;
5805
+ }
5806
+ const stack = [root];
5807
+ while (stack.length > 0) {
5808
+ const node = stack.pop();
5809
+ const nodeType = getNodeType ? getNodeType(node) : node.nodeType;
5810
+ /* Remove range markers (the target side of a patch linkage): every
5811
+ processing instruction, and any markup-bearing comment. */
5812
+ if (nodeType === NODE_TYPE.processingInstruction || nodeType === NODE_TYPE.comment && regExpTest(COMMENT_MARKUP_PROBE, node.data)) {
5813
+ try {
5814
+ remove(node);
5815
+ } catch (_) {
5816
+ /* Best-effort */
5817
+ }
5818
+ continue;
5819
+ }
5820
+ /* Strip patch-source attributes (the source side) off elements. */
5821
+ if (nodeType === NODE_TYPE.element) {
5822
+ const element = node;
5823
+ const lcTag = transformCaseFunc(getNodeName ? getNodeName(node) : node.nodeName);
5824
+ try {
5825
+ if (element.hasAttribute && element.hasAttribute('patchsrc')) {
5826
+ element.removeAttribute('patchsrc');
5827
+ }
5828
+ if (element.hasAttribute && element.hasAttribute('for') && lcTag !== 'label' && lcTag !== 'output') {
5829
+ element.removeAttribute('for');
5830
+ }
5831
+ } catch (_) {
5832
+ /* Clobbered removeAttribute/hasAttribute on a doomed node — ignore */
5833
+ }
5834
+ }
5835
+ const childNodes = getChildNodes(node);
5836
+ if (childNodes) {
5837
+ for (let i = childNodes.length - 1; i >= 0; --i) {
5838
+ stack.push(childNodes[i]);
5839
+ }
5840
+ }
5841
+ }
5842
+ };
5843
+ /**
5844
+ * _initDocument
5845
+ *
5846
+ * @param dirty - a string of dirty markup
5847
+ * @return a DOM, filled with the dirty markup
5848
+ */
5849
+ const _initDocument = function _initDocument(dirty) {
5850
+ /* Create a HTML document */
5851
+ let doc = null;
5852
+ let leadingWhitespace = null;
5853
+ if (FORCE_BODY) {
5854
+ dirty = '<remove></remove>' + dirty;
5855
+ } else {
5856
+ /* If FORCE_BODY isn't used, leading whitespace needs to be preserved manually */
5857
+ const matches = stringMatch(dirty, /^[\r\n\t ]+/);
5858
+ leadingWhitespace = matches && matches[0];
5859
+ }
5860
+ if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && NAMESPACE === HTML_NAMESPACE) {
5861
+ // Root of XHTML doc must contain xmlns declaration (see https://www.w3.org/TR/xhtml1/normative.html#strict)
5862
+ dirty = '<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>' + dirty + '</body></html>';
5863
+ }
5864
+ const dirtyPayload = trustedTypesPolicy ? _createTrustedHTML(dirty) : dirty;
5865
+ /*
5866
+ * Use the DOMParser API by default, fallback later if needs be
5867
+ * DOMParser not work for svg when has multiple root element.
5868
+ */
5869
+ if (NAMESPACE === HTML_NAMESPACE) {
5870
+ try {
5871
+ doc = new DOMParser().parseFromString(dirtyPayload, PARSER_MEDIA_TYPE);
5872
+ } catch (_) {}
5873
+ }
5874
+ /* Use createHTMLDocument in case DOMParser is not available */
5875
+ if (!doc || !doc.documentElement) {
5876
+ doc = implementation.createDocument(NAMESPACE, 'template', null);
5877
+ try {
5878
+ doc.documentElement.innerHTML = IS_EMPTY_INPUT ? emptyHTML : dirtyPayload;
5879
+ } catch (_) {
5880
+ // Syntax error if dirtyPayload is invalid xml
5881
+ }
5882
+ }
5883
+ const body = doc.body || doc.documentElement;
5884
+ if (dirty && leadingWhitespace) {
5885
+ body.insertBefore(document.createTextNode(leadingWhitespace), body.childNodes[0] || null);
5886
+ }
5887
+ /* Work on whole document or just its body */
5888
+ if (NAMESPACE === HTML_NAMESPACE) {
5889
+ return getElementsByTagName.call(doc, WHOLE_DOCUMENT ? 'html' : 'body')[0];
5890
+ }
5891
+ return WHOLE_DOCUMENT ? doc.documentElement : body;
5892
+ };
5893
+ /**
5894
+ * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document.
5895
+ *
5896
+ * @param root The root element or node to start traversing on.
5897
+ * @return The created NodeIterator
5898
+ */
5899
+ const _createNodeIterator = function _createNodeIterator(root) {
5900
+ return createNodeIterator.call(root.ownerDocument || root, root,
5901
+ // eslint-disable-next-line no-bitwise
5902
+ NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT | NodeFilter.SHOW_PROCESSING_INSTRUCTION | NodeFilter.SHOW_CDATA_SECTION, null);
5903
+ };
5904
+ /**
5905
+ * Replace template expression syntax (mustache, ERB, template
5906
+ * literal) with a space; shared by all SAFE_FOR_TEMPLATES scrub
5907
+ * sites. Order matters: mustache, then ERB, then template literal.
5908
+ *
5909
+ * @param value the string to scrub
5910
+ * @returns the scrubbed string
5911
+ */
5912
+ const _stripTemplateExpressions = function _stripTemplateExpressions(value) {
5913
+ value = stringReplace(value, MUSTACHE_EXPR$1, ' ');
5914
+ value = stringReplace(value, ERB_EXPR$1, ' ');
5915
+ value = stringReplace(value, TMPLIT_EXPR$1, ' ');
5916
+ return value;
5917
+ };
5918
+ /**
5919
+ * Strip template-engine expressions ({{...}}, ${...}, <%...%>) from the
5920
+ * character data of an element subtree. Used as the final safety net for
5921
+ * SAFE_FOR_TEMPLATES on every DOM-returning code path so that expressions
5922
+ * which only form after text-node normalization (e.g. fragments split across
5923
+ * stripped elements) cannot survive into a template-evaluating framework.
5924
+ *
5925
+ * Walks text/comment/CDATA/processing-instruction nodes and mutates `.data`
5926
+ * in place rather than round-tripping through innerHTML. This preserves
5927
+ * descendant node references (important for IN_PLACE callers), avoids a
5928
+ * serialize/reparse cycle, and reads literal character data — which means
5929
+ * `<%...%>` in text content matches the ERB regex against its real bytes
5930
+ * instead of the HTML-entity-escaped form innerHTML would produce.
5931
+ *
5932
+ * Attribute values are not visited here; SAFE_FOR_TEMPLATES handling for
5933
+ * attributes is performed during the per-node `_sanitizeAttributes` pass.
5934
+ *
5935
+ * @param node The root element whose character data should be scrubbed.
5936
+ */
5937
+ const _scrubTemplateExpressions2 = function _scrubTemplateExpressions(node) {
5938
+ var _node$querySelectorAl;
5939
+ node.normalize();
5940
+ const walker = createNodeIterator.call(node.ownerDocument || node, node,
5941
+ // eslint-disable-next-line no-bitwise
5942
+ NodeFilter.SHOW_TEXT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_CDATA_SECTION | NodeFilter.SHOW_PROCESSING_INSTRUCTION, null);
5943
+ let currentNode = walker.nextNode();
5944
+ while (currentNode) {
5945
+ currentNode.data = _stripTemplateExpressions(currentNode.data);
5946
+ currentNode = walker.nextNode();
5947
+ }
5948
+ // NodeIterator does not descend into <template>.content per the DOM spec,
5949
+ // so we must explicitly recurse into each template's content fragment,
5950
+ // mirroring the approach used by _sanitizeShadowDOM.
5951
+ const templates = (_node$querySelectorAl = node.querySelectorAll) === null || _node$querySelectorAl === void 0 ? void 0 : _node$querySelectorAl.call(node, 'template');
5952
+ if (templates) {
5953
+ arrayForEach(templates, tmpl => {
5954
+ if (_isDocumentFragment(tmpl.content)) {
5955
+ _scrubTemplateExpressions2(tmpl.content);
5956
+ }
5957
+ });
5958
+ }
5959
+ };
5960
+ /**
5961
+ * _isClobbered
5962
+ *
5963
+ * Detect DOM-clobbering on HTMLFormElement nodes. Form is the only HTML
5964
+ * interface with [LegacyOverrideBuiltIns]; a descendant element with a
5965
+ * `name` attribute matching a prototype property shadows that property
5966
+ * on direct reads. We use this check at the IN_PLACE entry-point and
5967
+ * during attribute sanitization to refuse clobbered forms.
5968
+ *
5969
+ * @param element element to check for clobbering attacks
5970
+ * @return true if clobbered, false if safe
5971
+ */
5972
+ const _isClobbered = function _isClobbered(element) {
5973
+ // Realm-independent tag-name probe. If we can't determine the tag
5974
+ // name at all, we can't reason about clobbering — return false
5975
+ // (the caller's other defences still apply).
5976
+ const realTagName = getNodeName ? getNodeName(element) : null;
5977
+ if (typeof realTagName !== 'string') {
5978
+ return false;
5979
+ }
5980
+ if (transformCaseFunc(realTagName) !== 'form') {
5981
+ return false;
5982
+ }
5983
+ return typeof element.nodeName !== 'string' || typeof element.textContent !== 'string' || typeof element.removeChild !== 'function' ||
5984
+ // Realm-safe NamedNodeMap detection: equality against the cached
5985
+ // prototype getter. Clobbered .attributes (e.g. <input name="attributes">)
5986
+ // makes the direct read diverge from the cached read; a clean form
5987
+ // (same-realm OR foreign-realm) has both reads pointing at the same
5988
+ // canonical NamedNodeMap.
5989
+ element.attributes !== getAttributes(element) || typeof element.removeAttribute !== 'function' || typeof element.setAttribute !== 'function' || typeof element.namespaceURI !== 'string' || typeof element.insertBefore !== 'function' || typeof element.hasChildNodes !== 'function' ||
5990
+ // NodeType clobbering probe. Cached Node.prototype.nodeType getter
5991
+ // returns the integer 1 for any Element regardless of realm; direct
5992
+ // read on a clobbered form (e.g. <input name="nodeType">) returns
5993
+ // the named child element. Cheap addition — nodeType is read from
5994
+ // an internal slot, no serialization cost — and removes a residual
5995
+ // clobbering surface used by several mXSS / PI / comment branches
5996
+ // in _sanitizeElements that compare currentNode.nodeType directly.
5997
+ element.nodeType !== getNodeType(element) ||
5998
+ // HTMLFormElement has [LegacyOverrideBuiltIns]: a descendant named
5999
+ // "childNodes" shadows the prototype getter. Direct reads of
6000
+ // form.childNodes from a clobbered form return the named child
6001
+ // instead of the real NodeList, so any walk that reads it directly
6002
+ // skips the form's real children. Compare the direct read to the
6003
+ // cached Node.prototype getter — when the form's named-property
6004
+ // getter intercepts the read, the two values differ and we flag
6005
+ // the form. This catches every clobbering child type (input,
6006
+ // select, etc.) regardless of whether the named child happens to
6007
+ // carry a numeric .length, which a typeof-based probe would miss
6008
+ // (e.g. HTMLSelectElement.length is a defined unsigned-long).
6009
+ element.childNodes !== getChildNodes(element);
6010
+ };
6011
+ /**
6012
+ * Checks whether the given value is a DocumentFragment from any realm.
6013
+ *
6014
+ * The realm-independent replacement reads `nodeType` through the cached
6015
+ * Node.prototype getter and compares to the DOCUMENT_FRAGMENT_NODE
6016
+ * constant (11). nodeType is a numeric value resolved from the node's
6017
+ * internal slot, identical across realms for the same kind of node.
6018
+ *
6019
+ * @param value object to check
6020
+ * @return true if value is a DocumentFragment-shaped node from any realm
6021
+ */
6022
+ const _isDocumentFragment = function _isDocumentFragment(value) {
6023
+ if (!getNodeType || typeof value !== 'object' || value === null) {
6024
+ return false;
6025
+ }
6026
+ try {
6027
+ return getNodeType(value) === NODE_TYPE.documentFragment;
6028
+ } catch (_) {
6029
+ return false;
6030
+ }
6031
+ };
6032
+ /**
6033
+ * Checks whether the given object is a DOM node, including nodes that
6034
+ * originate from a different window/realm (e.g. an iframe's
6035
+ * contentDocument). The previous `value instanceof Node` check was
6036
+ * realm-bound: nodes from a different window failed it, causing
6037
+ * sanitize() to silently stringify them and reset IN_PLACE to false,
6038
+ * returning the original node unsanitized. See GHSA-4w3q-35jp-p934.
6039
+ *
6040
+ * @param value object to check whether it's a DOM node
6041
+ * @return true if value is a DOM node from any realm
6042
+ */
6043
+ const _isNode = function _isNode(value) {
6044
+ if (!getNodeType || typeof value !== 'object' || value === null) {
6045
+ return false;
6046
+ }
6047
+ try {
6048
+ return typeof getNodeType(value) === 'number';
6049
+ } catch (_) {
6050
+ return false;
6051
+ }
6052
+ };
6053
+ function _executeHooks(hooks, currentNode, data) {
6054
+ if (hooks.length === 0) {
6055
+ return;
6056
+ }
6057
+ arrayForEach(hooks, hook => {
6058
+ hook.call(DOMPurify, currentNode, data, CONFIG);
6059
+ });
6060
+ }
6061
+ /**
6062
+ * Structural-threat checks that condemn a node regardless of the
6063
+ * allowlists: mXSS via namespace confusion, risky CSS construction,
6064
+ * processing instructions, markup-bearing comments. Pure predicate;
6065
+ * the caller removes. Check order is load-bearing.
6066
+ *
6067
+ * @param currentNode the node to inspect
6068
+ * @param tagName the node's transformCaseFunc'd tag name
6069
+ * @return true if the node must be removed
6070
+ */
6071
+ const _isUnsafeNode = function _isUnsafeNode(currentNode, tagName) {
6072
+ /* Detect mXSS attempts abusing namespace confusion */
6073
+ if (SAFE_FOR_XML && currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && regExpTest(ELEMENT_MARKUP_PROBE, currentNode.textContent) && regExpTest(ELEMENT_MARKUP_PROBE, currentNode.innerHTML)) {
6074
+ return true;
6075
+ }
6076
+ /* Remove risky CSS construction leading to mXSS */
6077
+ if (SAFE_FOR_XML && currentNode.namespaceURI === HTML_NAMESPACE && tagName === 'style' && _isNode(currentNode.firstElementChild)) {
6078
+ return true;
6079
+ }
6080
+ /* Remove any occurrence of processing instructions */
6081
+ if (currentNode.nodeType === NODE_TYPE.processingInstruction) {
6082
+ return true;
6083
+ }
6084
+ /* Remove any kind of possibly harmful comments */
6085
+ if (SAFE_FOR_XML && currentNode.nodeType === NODE_TYPE.comment && regExpTest(COMMENT_MARKUP_PROBE, currentNode.data)) {
6086
+ return true;
6087
+ }
6088
+ return false;
6089
+ };
6090
+ /**
6091
+ * Handle a node whose tag is forbidden or not allowlisted: keep
6092
+ * allowed custom elements (false return exits _sanitizeElements
6093
+ * early - the namespace and fallback-tag removal checks are
6094
+ * intentionally skipped for kept custom elements), else hoist
6095
+ * content per KEEP_CONTENT and remove.
6096
+ *
6097
+ * A kept custom element is the ONLY case in which this function
6098
+ * returns false, so the caller uses that return value to run the
6099
+ * afterSanitizeElements hook on the kept element and keep the
6100
+ * element-hook lifecycle consistent with normal allowlisted
6101
+ * elements (GHSA-c2j3-45gr-mqc4).
6102
+ *
6103
+ * @param currentNode the disallowed node
6104
+ * @param tagName the node's transformCaseFunc'd tag name
6105
+ * @return true if the node was removed, false if kept
6106
+ */
6107
+ const _sanitizeDisallowedNode = function _sanitizeDisallowedNode(currentNode, tagName) {
6108
+ /* Check if we have a custom element to handle */
6109
+ if (!FORBID_TAGS[tagName] && _isBasicCustomElement(tagName)) {
6110
+ if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) {
6111
+ return false;
6112
+ }
6113
+ if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)) {
6114
+ return false;
6115
+ }
6116
+ }
6117
+ /* Keep content except for bad-listed elements.
6118
+ Use the cached prototype getters exclusively — the previous code
6119
+ had `|| currentNode.parentNode` / `|| currentNode.childNodes`
6120
+ fallbacks, but the cached getters always return the canonical
6121
+ value (or null for a real parent-less node), so the fallback
6122
+ path was dead in safe cases and a clobbering surface in unsafe
6123
+ ones. Falsy cached results stay falsy; the `if (childNodes &&
6124
+ parentNode)` check already gates correctly. */
6125
+ if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {
6126
+ const parentNode = getParentNode(currentNode);
6127
+ const childNodes = getChildNodes(currentNode);
6128
+ if (childNodes && parentNode) {
6129
+ const childCount = childNodes.length;
6130
+ /* In-place: hoist the *original* children so the iterator visits
6131
+ and sanitises them through the same allowlist pass as every other
6132
+ node. The caller built the tree in the live document, so the
6133
+ originals carry already-queued resource events (`<img onerror>`,
6134
+ `<video>`/`<audio>` error, lazy/`onload`, …); cloning would leave
6135
+ those originals detached but still armed, firing in page scope
6136
+ while the returned tree looked clean. Moving is safe in-place: the
6137
+ root is pre-validated as an allowed tag and so is never the node
6138
+ being removed, which keeps `parentNode` inside the iterator root
6139
+ and the relocated child inside the serialised tree.
6140
+ Otherwise (string / DOM-copy paths): clone. The iterator is rooted
6141
+ at — and the result serialised from — `body`, so a restrictive
6142
+ ALLOWED_TAGS that removes `body` itself must leave its content in
6143
+ place, which only cloning does; and those paths parse into an
6144
+ inert document, so their discarded originals never had a queued
6145
+ event to neutralise.
6146
+ `childNodes` is live; a tail-to-head walk keeps `childNodes[i]`
6147
+ valid whether we move (drops the trailing entry) or clone (leaves
6148
+ the list intact). */
6149
+ for (let i = childCount - 1; i >= 0; --i) {
6150
+ const hoisted = IN_PLACE ? childNodes[i] : cloneNode(childNodes[i], true);
6151
+ parentNode.insertBefore(hoisted, getNextSibling(currentNode));
6152
+ }
6153
+ }
6154
+ }
6155
+ _forceRemove(currentNode);
6156
+ return true;
6157
+ };
6158
+ /**
6159
+ * _sanitizeElements
6160
+ *
6161
+ * @protect nodeName
6162
+ * @protect textContent
6163
+ * @protect removeChild
6164
+ * @param currentNode to check for permission to exist
6165
+ * @return true if node was killed, false if left alive
6166
+ */
6167
+ // eslint-disable-next-line complexity
6168
+ const _sanitizeElements = function _sanitizeElements(currentNode, root) {
6169
+ /* Execute a hook if present */
6170
+ _executeHooks(hooks.beforeSanitizeElements, currentNode, null);
6171
+ /* A hook may have detached the node — treat it as removed (see the
6172
+ detached-node comment after the uponSanitizeElement hook below). */
6173
+ if (currentNode !== root && getParentNode(currentNode) === null) {
6174
+ return true;
6175
+ }
6176
+ /* Check if element is clobbered or can clobber */
6177
+ if (_isClobbered(currentNode)) {
6178
+ _forceRemove(currentNode);
6179
+ return true;
6180
+ }
6181
+ /* Now let's check the element's type and name */
6182
+ const tagName = transformCaseFunc(getNodeName ? getNodeName(currentNode) : currentNode.nodeName);
6183
+ /* Execute a hook if present */
6184
+ _executeHooks(hooks.uponSanitizeElement, currentNode, {
6185
+ tagName,
6186
+ allowedTags: ALLOWED_TAGS
6187
+ });
6188
+ /* A hook may have detached the node from the tree — a long-standing
6189
+ user pattern (issue #469; draw.io-style foreignObject filtering).
6190
+ Per the cached, unclobberable parentNode getter the node is
6191
+ genuinely out of the tree, so it can reach neither the serialized
6192
+ output nor an IN_PLACE live tree; treat it as removed and stop
6193
+ processing it. Without this guard, the unsafe-node / namespace
6194
+ checks below would call _forceRemove on a parentless node and hit
6195
+ the REPORT-3 fail-closed throw — which exists for nodes DOMPurify
6196
+ wants gone but *cannot* detach (clobbered / parentless roots), the
6197
+ opposite of a node that is already safely gone. The walk root is
6198
+ exempt: a detached IN_PLACE root is legitimate input and must still
6199
+ be fully sanitized, and a kill-decision on it must keep hitting the
6200
+ REPORT-3 throw. Nodes detached by hooks are the hook's
6201
+ responsibility: they are not recorded in DOMPurify.removed and are
6202
+ not neutralized by the post-walk IN_PLACE pass. */
6203
+ if (currentNode !== root && getParentNode(currentNode) === null) {
6204
+ return true;
6205
+ }
6206
+ /* Remove mXSS vectors, processing instructions and risky comments */
6207
+ if (_isUnsafeNode(currentNode, tagName)) {
6208
+ _forceRemove(currentNode);
6209
+ return true;
6210
+ }
6211
+ /* Remove element if anything forbids its presence */
6212
+ if (FORBID_TAGS[tagName] || !(EXTRA_ELEMENT_HANDLING.tagCheck instanceof Function && EXTRA_ELEMENT_HANDLING.tagCheck(tagName)) && !ALLOWED_TAGS[tagName]) {
6213
+ const removed = _sanitizeDisallowedNode(currentNode, tagName);
6214
+ /* A false return means the node is a custom element kept via
6215
+ CUSTOM_ELEMENT_HANDLING - the only keep path through
6216
+ _sanitizeDisallowedNode. Run afterSanitizeElements on it so the
6217
+ element-hook lifecycle matches normal allowlisted elements: a
6218
+ security policy applied in this hook (e.g. stripping an attribute
6219
+ from every surviving element) must not silently skip kept custom
6220
+ elements (GHSA-c2j3-45gr-mqc4). This mirrors the normal-element
6221
+ tail below - the hook runs, then the walker's subsequent
6222
+ _sanitizeAttributes pass sanitizes the element's attributes. The
6223
+ deliberately skipped namespace and fallback-tag removal checks stay
6224
+ skipped; they are removal decisions, not the hook contract. */
6225
+ if (removed === false) {
6226
+ _executeHooks(hooks.afterSanitizeElements, currentNode, null);
6227
+ }
6228
+ return removed;
6229
+ }
6230
+ /* Check whether element has a valid namespace.
6231
+ Realm-safe check (GHSA-hpcv-96wg-7vj8): use the cached Node.prototype
6232
+ nodeType getter rather than `instanceof Element`, which is realm-
6233
+ bound and short-circuits to false for any node minted in a different
6234
+ realm — letting a foreign-realm element with a forbidden namespace
6235
+ slip past the namespace check entirely. */
6236
+ const nt = getNodeType ? getNodeType(currentNode) : currentNode.nodeType;
6237
+ if (nt === NODE_TYPE.element && !_checkValidNamespace(currentNode)) {
6238
+ _forceRemove(currentNode);
6239
+ return true;
6240
+ }
6241
+ /* Make sure that older browsers don't get fallback-tag mXSS */
6242
+ if ((tagName === 'noscript' || tagName === 'noembed' || tagName === 'noframes') && regExpTest(FALLBACK_TAG_CLOSE, currentNode.innerHTML)) {
6243
+ _forceRemove(currentNode);
6244
+ return true;
6245
+ }
6246
+ /* Sanitize element content to be template-safe */
6247
+ if (SAFE_FOR_TEMPLATES && currentNode.nodeType === NODE_TYPE.text) {
6248
+ /* Get the element's text content */
6249
+ const content = _stripTemplateExpressions(currentNode.textContent);
6250
+ if (currentNode.textContent !== content) {
6251
+ arrayPush(DOMPurify.removed, {
6252
+ element: currentNode.cloneNode()
6253
+ });
6254
+ currentNode.textContent = content;
6255
+ }
6256
+ }
6257
+ /* Execute a hook if present */
6258
+ _executeHooks(hooks.afterSanitizeElements, currentNode, null);
6259
+ return false;
6260
+ };
6261
+ /**
6262
+ * _isValidAttribute
6263
+ *
6264
+ * @param lcTag Lowercase tag name of containing element.
6265
+ * @param lcName Lowercase attribute name.
6266
+ * @param value Attribute value.
6267
+ * @return Returns true if `value` is valid, otherwise false.
6268
+ */
6269
+ // eslint-disable-next-line complexity
6270
+ const _isValidAttribute = function _isValidAttribute(lcTag, lcName, value) {
6271
+ /* FORBID_ATTR must always win, even if ADD_ATTR predicate would allow it */
6272
+ if (FORBID_ATTR[lcName]) {
6273
+ return false;
6274
+ }
6275
+ /* Reject declarative-partial-updates patch-linkage attributes
6276
+ (https://github.com/WICG/declarative-partial-updates).
6277
+ Empirical note (Chrome 150, verified — see
6278
+ test/declarative-patch-probe-v3.html): expansion is NOT applied after
6279
+ sanitization. For the string path it fires during sanitize()'s own
6280
+ parse, so the walk sees and sanitizes the fully materialized expanded
6281
+ tree — teleports into MathML/SVG integration points included; a
6282
+ weaponized `<template for>`->`<img onerror>` comes back with the handler
6283
+ stripped. For the IN_PLACE path it fires on connection, before the walk.
6284
+ Either way DOMPurify is NOT blind to the patch.
6285
+ This removal is therefore defense-in-depth rather than the sole barrier:
6286
+ it prevents live linkage from surviving into the OUTPUT and re-expanding
6287
+ in the caller's context, and keeps behaviour deterministic if a future
6288
+ engine defers expansion. `for` is legitimate only on <label>/<output>;
6289
+ anywhere else (notably <template for>) it links the element to a patch
6290
+ target and teleports or removes an arbitrary DOM range by id/marker name.
6291
+ `patchsrc` fetches remote markup and is treated as a script-loading
6292
+ mechanism (CSP). Gated on SAFE_FOR_XML so the removal groups with the
6293
+ other structural-threat checks and stays overridable, consistent with
6294
+ the rest of the codebase. PI range markers are already removed by
6295
+ _isUnsafeNode. */
6296
+ if (SAFE_FOR_XML && lcName === 'patchsrc') {
6297
+ return false;
6298
+ }
6299
+ if (SAFE_FOR_XML && lcName === 'for' && lcTag !== 'label' && lcTag !== 'output') {
6300
+ return false;
6301
+ }
6302
+ /* Make sure attribute cannot clobber */
6303
+ if (SANITIZE_DOM && (lcName === 'id' || lcName === 'name') && (value in document || value in formElement)) {
6304
+ return false;
6305
+ }
6306
+ const nameIsPermitted = ALLOWED_ATTR[lcName] || EXTRA_ELEMENT_HANDLING.attributeCheck instanceof Function && EXTRA_ELEMENT_HANDLING.attributeCheck(lcName, lcTag);
6307
+ /* Allow valid data-* attributes: At least one character after "-"
6308
+ (https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes)
6309
+ XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804)
6310
+ We don't need to check the value; it's always URI safe. */
6311
+ if (ALLOW_DATA_ATTR && regExpTest(DATA_ATTR$1, lcName)) ; else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR$1, lcName)) ; else if (!nameIsPermitted) {
6312
+ if (
6313
+ // First condition does a very basic check if a) it's basically a valid custom element tagname AND
6314
+ // b) if the tagName passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
6315
+ // and c) if the attribute name passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.attributeNameCheck
6316
+ _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)) ||
6317
+ // Alternative, second condition checks if it's an `is`-attribute, AND
6318
+ // the value passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
6319
+ 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 {
6320
+ return false;
6321
+ }
6322
+ /* Check value is safe. First, is attr inert? If so, is safe */
6323
+ } else if (URI_SAFE_ATTRIBUTES[lcName]) ; else if (regExpTest(IS_ALLOWED_URI$1, stringReplace(value, ATTR_WHITESPACE$1, ''))) ; else if ((lcName === 'src' || lcName === 'xlink:href' || lcName === 'href') && lcTag !== 'script' && stringIndexOf(value, 'data:') === 0 && DATA_URI_TAGS[lcTag]) ; else if (ALLOW_UNKNOWN_PROTOCOLS && !regExpTest(IS_SCRIPT_OR_DATA$1, stringReplace(value, ATTR_WHITESPACE$1, ''))) ; else if (value) {
6324
+ return false;
6325
+ } else ;
6326
+ return true;
6327
+ };
6328
+ /* Names the HTML spec reserves from valid-custom-element-name; these must
6329
+ * never be treated as basic custom elements even when a permissive
6330
+ * CUSTOM_ELEMENT_HANDLING.tagNameCheck is configured. */
6331
+ const RESERVED_CUSTOM_ELEMENT_NAMES = addToSet({}, ['annotation-xml', 'color-profile', 'font-face', 'font-face-format', 'font-face-name', 'font-face-src', 'font-face-uri', 'missing-glyph']);
6332
+ /**
6333
+ * _isBasicCustomElement
6334
+ * checks if at least one dash is included in tagName, and it's not the first char
6335
+ * for more sophisticated checking see https://github.com/sindresorhus/validate-element-name
6336
+ *
6337
+ * @param tagName name of the tag of the node to sanitize
6338
+ * @returns Returns true if the tag name meets the basic criteria for a custom element, otherwise false.
6339
+ */
6340
+ const _isBasicCustomElement = function _isBasicCustomElement(tagName) {
6341
+ return !RESERVED_CUSTOM_ELEMENT_NAMES[stringToLowerCase(tagName)] && regExpTest(CUSTOM_ELEMENT$1, tagName);
6342
+ };
6343
+ /**
6344
+ * Wrap an attribute value in the matching Trusted Types object when
6345
+ * the active policy requires it. Namespaced attributes pass through
6346
+ * unchanged (no TT support yet, see
6347
+ * https://bugs.chromium.org/p/chromium/issues/detail?id=1305293).
6348
+ *
6349
+ * @param lcTag lowercase tag name of the containing element
6350
+ * @param lcName lowercase attribute name
6351
+ * @param namespaceURI the attribute's namespace, if any
6352
+ * @param value the attribute value to wrap
6353
+ * @return the value, wrapped when Trusted Types demand it
6354
+ */
6355
+ const _applyTrustedTypesToAttribute = function _applyTrustedTypesToAttribute(lcTag, lcName, namespaceURI, value) {
6356
+ if (trustedTypesPolicy && typeof trustedTypes === 'object' && typeof trustedTypes.getAttributeType === 'function' && !namespaceURI) {
6357
+ switch (trustedTypes.getAttributeType(lcTag, lcName)) {
6358
+ case 'TrustedHTML':
6359
+ {
6360
+ return _createTrustedHTML(value);
6361
+ }
6362
+ case 'TrustedScriptURL':
6363
+ {
6364
+ return _createTrustedScriptURL(value);
6365
+ }
6366
+ }
6367
+ }
6368
+ return value;
6369
+ };
6370
+ /**
6371
+ * Write a modified attribute value back onto the element. On
6372
+ * success, re-probe for clobbering introduced by the new value and
6373
+ * remove the element when found; otherwise pop the removal entry
6374
+ * recorded by the earlier _removeAttribute (long-standing pairing
6375
+ * with the SANITIZE_NAMED_PROPS path - do not "fix" casually). On
6376
+ * failure, remove the attribute instead.
6377
+ *
6378
+ * @param currentNode the element carrying the attribute
6379
+ * @param name the attribute name as present on the element
6380
+ * @param namespaceURI the attribute's namespace, if any
6381
+ * @param value the new attribute value
6382
+ */
6383
+ const _setAttributeValue = function _setAttributeValue(currentNode, name, namespaceURI, value) {
6384
+ try {
6385
+ if (namespaceURI) {
6386
+ currentNode.setAttributeNS(namespaceURI, name, value);
6387
+ } else {
6388
+ /* Fallback to setAttribute() for browser-unrecognized namespaces e.g. "x-schema". */
6389
+ currentNode.setAttribute(name, value);
6390
+ }
6391
+ if (_isClobbered(currentNode)) {
6392
+ _forceRemove(currentNode);
6393
+ } else {
6394
+ arrayPop(DOMPurify.removed);
6395
+ }
6396
+ } catch (_) {
6397
+ _removeAttribute(name, currentNode);
6398
+ }
6399
+ };
6400
+ /**
6401
+ * _sanitizeAttributes
6402
+ *
6403
+ * @protect attributes
6404
+ * @protect nodeName
6405
+ * @protect removeAttribute
6406
+ * @protect setAttribute
6407
+ *
6408
+ * @param currentNode to sanitize
6409
+ */
6410
+ const _sanitizeAttributes = function _sanitizeAttributes(currentNode) {
6411
+ /* Execute a hook if present */
6412
+ _executeHooks(hooks.beforeSanitizeAttributes, currentNode, null);
6413
+ const attributes = currentNode.attributes;
6414
+ /* Check if we have attributes; if not we might have a text node */
6415
+ if (!attributes || _isClobbered(currentNode)) {
6416
+ return;
6417
+ }
6418
+ const hookEvent = {
6419
+ attrName: '',
6420
+ attrValue: '',
6421
+ keepAttr: true,
6422
+ allowedAttributes: ALLOWED_ATTR,
6423
+ forceKeepAttr: undefined
6424
+ };
6425
+ let l = attributes.length;
6426
+ const lcTag = transformCaseFunc(currentNode.nodeName);
6427
+ /* Go backwards over all attributes; safely remove bad ones */
6428
+ while (l--) {
6429
+ const attr = attributes[l];
6430
+ const name = attr.name,
6431
+ namespaceURI = attr.namespaceURI,
6432
+ attrValue = attr.value;
6433
+ const lcName = transformCaseFunc(name);
6434
+ const initValue = attrValue;
6435
+ let value = name === 'value' ? initValue : stringTrim(initValue);
6436
+ /* Execute a hook if present */
6437
+ hookEvent.attrName = lcName;
6438
+ hookEvent.attrValue = value;
6439
+ hookEvent.keepAttr = true;
6440
+ hookEvent.forceKeepAttr = undefined; // Allows developers to see this is a property they can set
6441
+ _executeHooks(hooks.uponSanitizeAttribute, currentNode, hookEvent);
6442
+ value = hookEvent.attrValue;
6443
+ /* Full DOM Clobbering protection via namespace isolation,
6444
+ * Prefix id and name attributes with `user-content-`
6445
+ */
6446
+ if (SANITIZE_NAMED_PROPS && (lcName === 'id' || lcName === 'name') && stringIndexOf(value, SANITIZE_NAMED_PROPS_PREFIX) !== 0) {
6447
+ // Remove the attribute with this value
6448
+ _removeAttribute(name, currentNode);
6449
+ // Prefix the value and later re-create the attribute with the sanitized value
6450
+ value = SANITIZE_NAMED_PROPS_PREFIX + value;
6451
+ }
6452
+ // Else: already prefixed, leave the attribute alone — the prefix is
6453
+ // itself the clobbering protection, and re-applying it is incorrect.
6454
+ /* Work around a security issue with comments inside attributes */
6455
+ if (SAFE_FOR_XML && regExpTest(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i, value)) {
6456
+ _removeAttribute(name, currentNode);
6457
+ continue;
6458
+ }
6459
+ /* Make sure we cannot easily use animated hrefs, even if animations are allowed */
6460
+ if (lcName === 'attributename' && stringMatch(value, 'href')) {
6461
+ _removeAttribute(name, currentNode);
6462
+ continue;
6463
+ }
6464
+ /* Did the hooks force-keep the attribute? */
6465
+ if (hookEvent.forceKeepAttr) {
6466
+ continue;
6467
+ }
6468
+ /* Did the hooks approve of the attribute? */
6469
+ if (!hookEvent.keepAttr) {
6470
+ _removeAttribute(name, currentNode);
6471
+ continue;
6472
+ }
6473
+ /* Work around a security issue in jQuery 3.0 */
6474
+ if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(SELF_CLOSING_TAG, value)) {
6475
+ _removeAttribute(name, currentNode);
6476
+ continue;
6477
+ }
6478
+ /* Sanitize attribute content to be template-safe */
6479
+ if (SAFE_FOR_TEMPLATES) {
6480
+ value = _stripTemplateExpressions(value);
6481
+ }
6482
+ /* Is `value` valid for this attribute? */
6483
+ if (!_isValidAttribute(lcTag, lcName, value)) {
6484
+ _removeAttribute(name, currentNode);
6485
+ continue;
6486
+ }
6487
+ /* Handle attributes that require Trusted Types */
6488
+ value = _applyTrustedTypesToAttribute(lcTag, lcName, namespaceURI, value);
6489
+ /* Handle invalid data-* attribute set by try-catching it */
6490
+ if (value !== initValue) {
6491
+ _setAttributeValue(currentNode, name, namespaceURI, value);
6492
+ }
6493
+ }
6494
+ /* Execute a hook if present */
6495
+ _executeHooks(hooks.afterSanitizeAttributes, currentNode, null);
6496
+ };
6497
+ /**
6498
+ * _sanitizeShadowDOM
6499
+ *
6500
+ * @param fragment to iterate over recursively
6501
+ */
6502
+ const _sanitizeShadowDOM2 = function _sanitizeShadowDOM(fragment) {
6503
+ let shadowNode = null;
6504
+ const shadowIterator = _createNodeIterator(fragment);
6505
+ /* Execute a hook if present */
6506
+ _executeHooks(hooks.beforeSanitizeShadowDOM, fragment, null);
6507
+ while (shadowNode = shadowIterator.nextNode()) {
6508
+ /* Execute a hook if present */
6509
+ _executeHooks(hooks.uponSanitizeShadowNode, shadowNode, null);
6510
+ /* Sanitize tags and elements */
6511
+ _sanitizeElements(shadowNode, fragment);
6512
+ /* Check attributes next */
6513
+ _sanitizeAttributes(shadowNode);
6514
+ /* Deep shadow DOM detected.
6515
+ Realm-safe check (GHSA-hpcv-96wg-7vj8): use nodeType against the
6516
+ DOCUMENT_FRAGMENT_NODE constant rather than instanceof, so we
6517
+ recurse into <template>.content from foreign realms too. */
6518
+ if (_isDocumentFragment(shadowNode.content)) {
6519
+ _sanitizeShadowDOM2(shadowNode.content);
6520
+ }
6521
+ /* An element iterated here may itself host an attached
6522
+ shadow root. The default NodeIterator does not enter shadow
6523
+ trees, so a shadow root nested inside template.content was
6524
+ previously reached by no walk at all (the pre-pass at
6525
+ _sanitizeAttachedShadowRoots descends via childNodes, which
6526
+ doesn't enter template.content; the template-content recursion
6527
+ above iterates the content but never inspected shadowRoot).
6528
+ Walk it explicitly. The nodeType guard avoids reading
6529
+ shadowRoot off text / comment / CDATA / PI nodes that the
6530
+ iterator also surfaces. */
6531
+ const shadowNodeType = getNodeType ? getNodeType(shadowNode) : shadowNode.nodeType;
6532
+ if (shadowNodeType === NODE_TYPE.element) {
6533
+ const innerSr = getShadowRoot(shadowNode);
6534
+ if (_isDocumentFragment(innerSr)) {
6535
+ _sanitizeAttachedShadowRoots(innerSr);
6536
+ _sanitizeShadowDOM2(innerSr);
6537
+ }
6538
+ }
6539
+ }
6540
+ /* Execute a hook if present */
6541
+ _executeHooks(hooks.afterSanitizeShadowDOM, fragment, null);
6542
+ };
6543
+ /**
6544
+ * _sanitizeAttachedShadowRoots
6545
+ *
6546
+ * Walks `root` and feeds every attached shadow root we encounter into
6547
+ * the existing _sanitizeShadowDOM pipeline. The default node iterator
6548
+ * does not descend into shadow trees, so nodes inside an attached
6549
+ * shadow root would otherwise be skipped entirely.
6550
+ *
6551
+ * Two real input paths put attached shadow roots in front of us:
6552
+ * 1. IN_PLACE on a DOM node that already has shadow roots attached.
6553
+ * 2. DOM-node input where importNode(dirty, true) deep-clones the
6554
+ * shadow root because it was created with `clonable: true`.
6555
+ *
6556
+ * This pass runs once, up front, so the main iteration loop (and the
6557
+ * existing _sanitizeShadowDOM template-content recursion) stay
6558
+ * untouched — string-input paths are not affected.
6559
+ *
6560
+ * @param root the subtree root to walk for attached shadow roots
6561
+ */
6562
+ const _sanitizeAttachedShadowRoots = function _sanitizeAttachedShadowRoots(root) {
6563
+ /* Iterative (explicit stack) rather than per-child recursion. DOM APIs
6564
+ impose no depth cap, so an attacker-shaped tree (JSON/CRDT/editor data
6565
+ built straight into the DOM — the IN_PLACE surface) deeper than the JS
6566
+ call-stack budget would otherwise overflow native recursion here and
6567
+ throw at the IN_PLACE entry pre-pass, before a single node is
6568
+ sanitized, leaving the caller's live tree untouched (fail-open). See
6569
+ campaign-3 F4. A heap stack keeps depth off the call stack.
6570
+ Each work item is either a node to descend into, or a deferred
6571
+ `_sanitizeShadowDOM` for an already-walked shadow root. The deferred
6572
+ form preserves the original post-order discipline: a shadow root's
6573
+ nested shadow roots are discovered before the outer shadow is
6574
+ sanitized (which may remove hosts). Pushes are in reverse of the
6575
+ desired processing order (LIFO): template content, then children, then
6576
+ the shadow-sanitize, then the shadow walk — so the order matches the
6577
+ previous recursion exactly. */
6578
+ const stack = [{
6579
+ node: root,
6580
+ shadow: null
6581
+ }];
6582
+ while (stack.length > 0) {
6583
+ const item = stack.pop();
6584
+ /* Deferred shadow-DOM sanitisation: runs after its subtree was walked. */
6585
+ if (item.shadow) {
6586
+ _sanitizeShadowDOM2(item.shadow);
6587
+ continue;
6588
+ }
6589
+ const node = item.node;
6590
+ const nodeType = getNodeType ? getNodeType(node) : node.nodeType;
6591
+ const isElement = nodeType === NODE_TYPE.element;
6592
+ /* (pushed last → processed first) Children, snapshotted in reverse so
6593
+ the first child is processed first. Snapshotting matters because a
6594
+ hook may detach siblings mid-walk. */
6595
+ const childNodes = getChildNodes(node);
6596
+ if (childNodes) {
6597
+ for (let i = childNodes.length - 1; i >= 0; --i) {
6598
+ stack.push({
6599
+ node: childNodes[i],
6600
+ shadow: null
6601
+ });
6602
+ }
6603
+ }
6604
+ /* (pushed before children → processed after them, matching the old
6605
+ "template content last" order) When the node is a <template>,
6606
+ descend into its content. */
6607
+ if (isElement) {
6608
+ const rootName = getNodeName ? getNodeName(node) : null;
6609
+ if (typeof rootName === 'string' && transformCaseFunc(rootName) === 'template') {
6610
+ const content = node.content;
6611
+ if (_isDocumentFragment(content)) {
6612
+ stack.push({
6613
+ node: content,
6614
+ shadow: null
6615
+ });
6616
+ }
6617
+ }
6618
+ }
6619
+ /* Shadow root (processed first): walk its subtree, then sanitise it.
6620
+ Realm-safe check (GHSA-hpcv-96wg-7vj8): nodeType-based detection
6621
+ rather than `instanceof DocumentFragment`, which is realm-bound and
6622
+ silently skipped foreign-realm shadow roots (e.g.
6623
+ iframe.contentDocument attachShadow). */
6624
+ if (isElement) {
6625
+ const sr = getShadowRoot(node);
6626
+ if (_isDocumentFragment(sr)) {
6627
+ /* Push the deferred sanitise first so it pops after the shadow
6628
+ walk we push next, i.e. nested shadow roots are discovered
6629
+ before this one is sanitised. */
6630
+ stack.push({
6631
+ node: null,
6632
+ shadow: sr
6633
+ }, {
6634
+ node: sr,
6635
+ shadow: null
6636
+ });
6637
+ }
6638
+ }
6639
+ }
6640
+ };
6641
+ // eslint-disable-next-line complexity
6642
+ DOMPurify.sanitize = function (dirty) {
6643
+ let cfg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
6644
+ let body = null;
6645
+ let importedNode = null;
6646
+ let currentNode = null;
6647
+ let returnNode = null;
6648
+ /* Make sure we have a string to sanitize.
6649
+ DO NOT return early, as this will return the wrong type if
6650
+ the user has requested a DOM object rather than a string */
6651
+ IS_EMPTY_INPUT = !dirty;
6652
+ if (IS_EMPTY_INPUT) {
6653
+ dirty = '<!-->';
6654
+ }
6655
+ /* Stringify, in case dirty is an object */
6656
+ if (typeof dirty !== 'string' && !_isNode(dirty)) {
6657
+ dirty = stringifyValue(dirty);
6658
+ if (typeof dirty !== 'string') {
6659
+ throw typeErrorCreate('dirty is not a string, aborting');
6660
+ }
6661
+ }
6662
+ /* Return dirty HTML if DOMPurify cannot run */
6663
+ if (!DOMPurify.isSupported) {
6664
+ return dirty;
6665
+ }
6666
+ /* Assign config vars */
6667
+ if (SET_CONFIG) {
6668
+ /* Persistent setConfig() path: _parseConfig is skipped, so the sets are
6669
+ * not re-derived per call. Restore them from the pristine bindings
6670
+ * captured at setConfig() time so a previous call's hook clone (mutated
6671
+ * below) does not carry over. */
6672
+ ALLOWED_TAGS = SET_CONFIG_ALLOWED_TAGS;
6673
+ ALLOWED_ATTR = SET_CONFIG_ALLOWED_ATTR;
6674
+ } else {
6675
+ _parseConfig(cfg);
6676
+ }
6677
+ /* Clone the hook-mutable allowlists before the walk whenever an
6678
+ * uponSanitize* hook is registered. The hook event exposes ALLOWED_TAGS
6679
+ * and ALLOWED_ATTR by reference (as allowedTags / allowedAttributes), so
6680
+ * a hook that widens them would otherwise mutate the shared set
6681
+ * permanently: across later calls and across every element. Cloning per
6682
+ * walk keeps documented in-call widening working while scoping it to the
6683
+ * call. A single guard for both config paths - the per-call path rebinds
6684
+ * the sets in _parseConfig each call, the persistent path restores them
6685
+ * from the captured bindings just above - so the two cannot diverge. */
6686
+ if (hooks.uponSanitizeElement.length > 0 || hooks.uponSanitizeAttribute.length > 0) {
6687
+ ALLOWED_TAGS = clone(ALLOWED_TAGS);
6688
+ }
6689
+ if (hooks.uponSanitizeAttribute.length > 0) {
6690
+ ALLOWED_ATTR = clone(ALLOWED_ATTR);
6691
+ }
6692
+ /* Clean up removed elements */
6693
+ DOMPurify.removed = [];
6694
+ /* Resolve IN_PLACE for this call without mutating persistent config.
6695
+ Writing the IN_PLACE closure variable here leaks under setConfig(),
6696
+ where _parseConfig is skipped on later calls: a single string call would
6697
+ disable in-place mode for every subsequent node call, returning a
6698
+ sanitized copy while leaving the caller's node — which in-place callers
6699
+ keep using and whose return value they ignore — unsanitized. REPORT-2. */
6700
+ const inPlace = IN_PLACE && typeof dirty !== 'string' && _isNode(dirty);
6701
+ if (inPlace) {
6702
+ /* Declarative-partial-updates / streaming pre-pass: sever every patch
6703
+ linkage across the live tree BEFORE the walk, so no patch can fire
6704
+ mid-walk and inject into an already-processed region. Runs first, so
6705
+ it also covers the forbidden/clobbered roots that throw below. */
6706
+ _neutralizePatchLinkage(dirty);
6707
+ /* Do some early pre-sanitization to avoid unsafe root nodes.
6708
+ Read nodeName through the cached prototype getter — a clobbering
6709
+ child named "nodeName" on the form root would otherwise shadow
6710
+ the property and let this check skip the root-allowlist
6711
+ validation entirely. */
6712
+ const nn = getNodeName ? getNodeName(dirty) : dirty.nodeName;
6713
+ if (typeof nn === 'string') {
6714
+ const tagName = transformCaseFunc(nn);
6715
+ if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
6716
+ /* Fail closed on a live root: neutralize handlers/children before
6717
+ throwing, exactly as the mid-walk abort path does. */
6718
+ _neutralizeRoot(dirty);
6719
+ throw typeErrorCreate('root node is forbidden and cannot be sanitized in-place');
6720
+ }
6721
+ }
6722
+ /* Pre-flight the root through _isClobbered. The iterator-driven
6723
+ removal path can not detach a parent-less root: _forceRemove
6724
+ falls through to Element.prototype.remove(), which per spec
6725
+ is a no-op on a node with no parent. A clobbered root would
6726
+ then survive the main loop with its attributes uninspected,
6727
+ because _sanitizeAttributes early-returns on _isClobbered. The
6728
+ result would be an attacker-controlled form, complete with any
6729
+ event-handler attributes the caller passed in, handed back to
6730
+ the application unsanitized. Refuse to sanitize such a root
6731
+ the same way we refuse a forbidden tag. GHSA-r47g-fvhr-h676. */
6732
+ if (_isClobbered(dirty)) {
6733
+ /* Fail closed on a live clobbered root before throwing.
6734
+ _neutralizeRoot's reads are clobber-safe (cached getters); the
6735
+ form's non-clobbered descendants, e.g. an armed <img>, are scrubbed. */
6736
+ _neutralizeRoot(dirty);
6737
+ throw typeErrorCreate('root node is clobbered and cannot be sanitized in-place');
6738
+ }
6739
+ /* Sanitize attached shadow roots before the main iterator runs.
6740
+ The iterator does not descend into shadow trees. Same fail-closed
6741
+ barrier as the main walk (campaign-3 F2): a custom-element reaction
6742
+ inside a shadow root could abort this pre-pass before the walk runs,
6743
+ which would otherwise leave the entire live tree unsanitized. */
6744
+ try {
6745
+ _sanitizeAttachedShadowRoots(dirty);
6746
+ } catch (error) {
6747
+ _neutralizeRoot(dirty);
6748
+ throw error;
6749
+ }
6750
+ } else if (_isNode(dirty)) {
6751
+ /* If dirty is a DOM element, append to an empty document to avoid
6752
+ elements being stripped by the parser */
6753
+ body = _initDocument('<!---->');
6754
+ importedNode = body.ownerDocument.importNode(dirty, true);
6755
+ if (importedNode.nodeType === NODE_TYPE.element && importedNode.nodeName === 'BODY') {
6756
+ /* Node is already a body, use as is */
6757
+ body = importedNode;
6758
+ } else if (importedNode.nodeName === 'HTML') {
6759
+ body = importedNode;
6760
+ } else {
6761
+ // eslint-disable-next-line unicorn/prefer-dom-node-append
6762
+ body.appendChild(importedNode);
6763
+ }
6764
+ /* Clonable shadow roots are deep-cloned by importNode(); sanitize
6765
+ them before the main iterator runs, since the iterator does not
6766
+ descend into shadow trees. The walk routes every read through a
6767
+ cached prototype getter so clobbering descendants on a form root
6768
+ cannot hide a shadow host from this pass. */
6769
+ _sanitizeAttachedShadowRoots(importedNode);
6770
+ } else {
6771
+ /* Exit directly if we have nothing to do */
6772
+ if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT &&
6773
+ // eslint-disable-next-line unicorn/prefer-includes
6774
+ dirty.indexOf('<') === -1) {
6775
+ return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? _createTrustedHTML(dirty) : dirty;
6776
+ }
6777
+ /* Initialize the document to work on */
6778
+ body = _initDocument(dirty);
6779
+ /* Check we have a DOM node from the data */
6780
+ if (!body) {
6781
+ return RETURN_DOM ? null : RETURN_TRUSTED_TYPE ? emptyHTML : '';
6782
+ }
6783
+ }
6784
+ /* Remove first element node (ours) if FORCE_BODY is set */
6785
+ if (body && FORCE_BODY) {
6786
+ _forceRemove(body.firstChild);
6787
+ }
6788
+ /* Get node iterator */
6789
+ const walkRoot = inPlace ? dirty : body;
6790
+ const nodeIterator = _createNodeIterator(walkRoot);
6791
+ /* Now start iterating over the created document.
6792
+ The walk runs inside an exception barrier (campaign-3 F2): a re-entrant
6793
+ engine/custom-element mutation can detach a node mid-walk so
6794
+ `_forceRemove`'s parentless guard throws, aborting the loop. Without the
6795
+ barrier the caller's in-place tree would be left half-sanitized with the
6796
+ unvisited tail still armed. On any throw we fail closed — strip the
6797
+ in-place root bare — then rethrow so the existing throw contract is
6798
+ preserved. (String/DOM-copy paths never return the partial body, so the
6799
+ propagating throw is already fail-closed there.) */
6800
+ try {
6801
+ while (currentNode = nodeIterator.nextNode()) {
6802
+ /* Sanitize tags and elements */
6803
+ _sanitizeElements(currentNode, walkRoot);
6804
+ /* Check attributes next */
6805
+ _sanitizeAttributes(currentNode);
6806
+ /* Shadow DOM detected, sanitize it.
6807
+ Realm-safe check (GHSA-hpcv-96wg-7vj8): nodeType-based detection
6808
+ instead of instanceof, so foreign-realm <template>.content is
6809
+ walked correctly. */
6810
+ if (_isDocumentFragment(currentNode.content)) {
6811
+ _sanitizeShadowDOM2(currentNode.content);
6812
+ }
6813
+ }
6814
+ } catch (error) {
6815
+ if (inPlace) {
6816
+ _neutralizeRoot(dirty);
6817
+ /* Nodes _forceRemove'd earlier in the aborted walk are already
6818
+ detached from the root, so _neutralizeRoot's subtree pass does not
6819
+ reach them. Defuse them too, mirroring the success-path loop below. */
6820
+ arrayForEach(DOMPurify.removed, entry => {
6821
+ if (entry.element) {
6822
+ _neutralizeSubtree(entry.element);
6823
+ }
6824
+ });
6825
+ }
6826
+ throw error;
6827
+ }
6828
+ /* If we sanitized `dirty` in-place, return it. */
6829
+ if (inPlace) {
6830
+ /* Fail-closed completion of the audit-5 F1 fix: every node removed from
6831
+ the caller's live tree is detached but may still hold a queued
6832
+ resource-event handler that fires in page scope after we return. The
6833
+ move-hoist covers only disallowed-tag KEEP_CONTENT removals; strip the
6834
+ non-allow-listed attributes off every other removed subtree (clobber,
6835
+ mXSS, namespace, comments, KEEP_CONTENT:false, …) so those handlers are
6836
+ cancelled before any event can fire. Runs synchronously, pre-return. */
6837
+ arrayForEach(DOMPurify.removed, entry => {
6838
+ if (entry.element) {
6839
+ _neutralizeSubtree(entry.element);
6840
+ }
6841
+ });
6842
+ if (SAFE_FOR_TEMPLATES) {
6843
+ _scrubTemplateExpressions2(dirty);
6844
+ }
6845
+ return dirty;
6846
+ }
6847
+ /* Return sanitized string or DOM */
6848
+ if (RETURN_DOM) {
6849
+ if (SAFE_FOR_TEMPLATES) {
6850
+ _scrubTemplateExpressions2(body);
6851
+ }
6852
+ if (RETURN_DOM_FRAGMENT) {
6853
+ returnNode = createDocumentFragment.call(body.ownerDocument);
6854
+ while (body.firstChild) {
6855
+ // eslint-disable-next-line unicorn/prefer-dom-node-append
6856
+ returnNode.appendChild(body.firstChild);
6857
+ }
6858
+ } else {
6859
+ returnNode = body;
6860
+ }
6861
+ if (ALLOWED_ATTR.shadowroot || ALLOWED_ATTR.shadowrootmode) {
6862
+ /*
6863
+ AdoptNode() is not used because internal state is not reset
6864
+ (e.g. the past names map of a HTMLFormElement), this is safe
6865
+ in theory but we would rather not risk another attack vector.
6866
+ The state that is cloned by importNode() is explicitly defined
6867
+ by the specs.
6868
+ */
6869
+ returnNode = importNode.call(originalDocument, returnNode, true);
6870
+ }
6871
+ return returnNode;
6872
+ }
6873
+ let serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML;
6874
+ /* Serialize doctype if allowed */
6875
+ if (WHOLE_DOCUMENT && ALLOWED_TAGS['!doctype'] && body.ownerDocument && body.ownerDocument.doctype && body.ownerDocument.doctype.name && regExpTest(DOCTYPE_NAME, body.ownerDocument.doctype.name)) {
6876
+ serializedHTML = '<!DOCTYPE ' + body.ownerDocument.doctype.name + '>\n' + serializedHTML;
6877
+ }
6878
+ /* Sanitize final string template-safe */
6879
+ if (SAFE_FOR_TEMPLATES) {
6880
+ serializedHTML = _stripTemplateExpressions(serializedHTML);
6881
+ }
6882
+ return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? _createTrustedHTML(serializedHTML) : serializedHTML;
6883
+ };
6884
+ DOMPurify.setConfig = function () {
6885
+ let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
6886
+ _parseConfig(cfg);
6887
+ SET_CONFIG = true;
6888
+ SET_CONFIG_ALLOWED_TAGS = ALLOWED_TAGS;
6889
+ SET_CONFIG_ALLOWED_ATTR = ALLOWED_ATTR;
6890
+ };
6891
+ DOMPurify.clearConfig = function () {
6892
+ CONFIG = null;
6893
+ SET_CONFIG = false;
6894
+ SET_CONFIG_ALLOWED_TAGS = null;
6895
+ SET_CONFIG_ALLOWED_ATTR = null;
6896
+ // Drop any caller-supplied Trusted Types policy so it cannot poison later
6897
+ // `RETURN_TRUSTED_TYPE` output. The internal default policy (cached, and
6898
+ // never recreated — Trusted Types throws on duplicate names) is restored by
6899
+ // the next `_parseConfig`. See GHSA-vxr8-fq34-vvx9.
6900
+ trustedTypesPolicy = defaultTrustedTypesPolicy;
6901
+ emptyHTML = '';
6902
+ };
6903
+ DOMPurify.isValidAttribute = function (tag, attr, value) {
6904
+ /* Initialize shared config vars if necessary. */
6905
+ if (!CONFIG) {
6906
+ _parseConfig({});
6907
+ }
6908
+ const lcTag = transformCaseFunc(tag);
6909
+ const lcName = transformCaseFunc(attr);
6910
+ return _isValidAttribute(lcTag, lcName, value);
6911
+ };
6912
+ DOMPurify.addHook = function (entryPoint, hookFunction) {
6913
+ if (typeof hookFunction !== 'function') {
6914
+ return;
6915
+ }
6916
+ /* Reject unknown entry points. Without this, a non-hook key (e.g.
6917
+ * '__proto__') indexes off the prototype chain rather than a real
6918
+ * hook array, and arrayPush then writes to Object.prototype. Guard
6919
+ * with an own-property check against the known hook names. */
6920
+ if (!objectHasOwnProperty(hooks, entryPoint)) {
6921
+ return;
6922
+ }
6923
+ arrayPush(hooks[entryPoint], hookFunction);
6924
+ };
6925
+ DOMPurify.removeHook = function (entryPoint, hookFunction) {
6926
+ if (!objectHasOwnProperty(hooks, entryPoint)) {
6927
+ return undefined;
6928
+ }
6929
+ if (hookFunction !== undefined) {
6930
+ const index = arrayLastIndexOf(hooks[entryPoint], hookFunction);
6931
+ return index === -1 ? undefined : arraySplice(hooks[entryPoint], index, 1)[0];
6932
+ }
6933
+ return arrayPop(hooks[entryPoint]);
6934
+ };
6935
+ DOMPurify.removeHooks = function (entryPoint) {
6936
+ if (!objectHasOwnProperty(hooks, entryPoint)) {
6937
+ return;
6938
+ }
6939
+ hooks[entryPoint] = [];
6940
+ };
6941
+ DOMPurify.removeAllHooks = function () {
6942
+ hooks = _createHooksMap();
6943
+ };
6944
+ return DOMPurify;
6945
+ }
6946
+ var purify = createDOMPurify();
6947
+
5278
6948
  const mrdTextareaFieldCss = () => `.sc-mrd-textarea-field-h{display:block}.mrd-textarea-field.sc-mrd-textarea-field{display:flex;flex-direction:column;gap:var(--mrd-space-1);width:100%}.mrd-textarea-field__label.sc-mrd-textarea-field{display:block;font-family:var(--mrd-font-family);font-size:var(--mrd-label-font-size);font-weight:var(--mrd-label-font-weight);color:var(--mrd-label-color)}.mrd-textarea-field__label--required.sc-mrd-textarea-field::after{content:" *";color:var(--mrd-color-danger)}.mrd-textarea-field__error.sc-mrd-textarea-field{font-family:var(--mrd-font-family);font-size:var(--mrd-error-font-size);color:var(--mrd-error-color)}.mrd-textarea-field__container.sc-mrd-textarea-field{border:var(--mrd-border-width) solid var(--mrd-border-color);border-radius:var(--mrd-border-radius);overflow:hidden;background-color:var(--mrd-input-bg);transition:border-color var(--mrd-transition), box-shadow var(--mrd-transition)}.mrd-textarea-field__container.sc-mrd-textarea-field:focus-within{border-color:var(--mrd-border-color-focus);box-shadow:var(--mrd-shadow-focus)}.mrd-textarea-field__container--error.sc-mrd-textarea-field{border-color:var(--mrd-border-color-error)}.mrd-textarea-field__container--error.sc-mrd-textarea-field:focus-within{box-shadow:var(--mrd-shadow-focus-error)}.mrd-textarea-field__editor.sc-mrd-textarea-field{min-height:150px;font-family:var(--mrd-font-family);font-size:var(--mrd-font-size-base)}.mrd-textarea-field__editor.sc-mrd-textarea-field .ql-toolbar.sc-mrd-textarea-field{border:none;border-bottom:var(--mrd-border-width) solid var(--mrd-border-color);font-family:var(--mrd-font-family)}.mrd-textarea-field__editor.sc-mrd-textarea-field .ql-container.sc-mrd-textarea-field{border:none;font-family:var(--mrd-font-family);font-size:var(--mrd-font-size-base)}.mrd-textarea-field__editor.sc-mrd-textarea-field .ql-editor.sc-mrd-textarea-field{min-height:120px;padding:var(--mrd-input-padding-y) var(--mrd-input-padding-x)}.mrd-textarea-field__editor.sc-mrd-textarea-field .ql-editor.ql-blank.sc-mrd-textarea-field::before{color:var(--mrd-input-placeholder-color);font-style:normal}`;
5279
6949
 
5280
6950
  const MrdTextareaField = class {
@@ -5320,14 +6990,12 @@ const MrdTextareaField = class {
5320
6990
  quill.clipboard.dangerouslyPasteHTML(this.value);
5321
6991
  }
5322
6992
  quill.on('text-change', () => {
5323
- var _a, _b;
5324
- const html = (_b = (_a = this.editorEl.querySelector('.ql-editor')) === null || _a === void 0 ? void 0 : _a.innerHTML) !== null && _b !== void 0 ? _b : '';
6993
+ const html = this.getSanitizedHtml();
5325
6994
  this.mrdChange.emit({ name: this.name, value: html });
5326
6995
  });
5327
6996
  quill.on('selection-change', (range) => {
5328
- var _a, _b;
5329
6997
  if (!range) {
5330
- const html = (_b = (_a = this.editorEl.querySelector('.ql-editor')) === null || _a === void 0 ? void 0 : _a.innerHTML) !== null && _b !== void 0 ? _b : '';
6998
+ const html = this.getSanitizedHtml();
5331
6999
  this.error = requiredError(html, this.required, this.locale);
5332
7000
  this.mrdBlur.emit({ name: this.name, value: html });
5333
7001
  }
@@ -5338,8 +7006,13 @@ const MrdTextareaField = class {
5338
7006
  console.error('Failed to load Quill editor:', err);
5339
7007
  }
5340
7008
  }
7009
+ getSanitizedHtml() {
7010
+ var _a, _b;
7011
+ const html = (_b = (_a = this.editorEl.querySelector('.ql-editor')) === null || _a === void 0 ? void 0 : _a.innerHTML) !== null && _b !== void 0 ? _b : '';
7012
+ return purify.sanitize(html);
7013
+ }
5341
7014
  render() {
5342
- return (h(Host, { key: 'de39890fc23146b880e69be7a8f04c91786ae9c9' }, h("div", { key: '0ccc855f3ee44553559a9ea8a70690466789f76d', class: "mrd-textarea-field" }, h(FieldLabel, { key: '2a16dcbeedbba8b5d8d1e8e8c0f021f14813f609', base: "mrd-textarea-field", label: this.label, required: this.required }), h("div", { key: '979ecb0ed163e3f753d75635452eea49d76edf29', class: controlClass('mrd-textarea-field', !!this.error, 'container') }, h("div", { key: '8ea96a080086b68df55017a1464f6bce502f9a58', class: "mrd-textarea-field__editor" })), h(FieldError, { key: 'd6ac1a12f7be3594ed8cdb6d94b304c46dc8285b', base: "mrd-textarea-field", error: this.error }))));
7015
+ return (h(Host, { key: '708c1f8f14d2de4b5a274155d190fc19a304d7f0' }, h("div", { key: 'cf5c7a571e74cad08e0e320e91db4e22a3b2e080', class: "mrd-textarea-field" }, h(FieldLabel, { key: '4ced05f3914440f89dc5605901fc311e8ad54360', base: "mrd-textarea-field", label: this.label, required: this.required }), h("div", { key: '81147829bc575d05f3521bf3704edfdfe0d9b2cf', class: controlClass('mrd-textarea-field', !!this.error, 'container') }, h("div", { key: 'a9f42d86cab460d5e0cf6de87e0c0a0a1ca7d77a', class: "mrd-textarea-field__editor" })), h(FieldError, { key: '9f4b5271d0901e474ef6c0f1170b3ef718a844a9', base: "mrd-textarea-field", error: this.error }))));
5343
7016
  }
5344
7017
  get el() { return getElement(this); }
5345
7018
  };