'use strict';

/**
 * Licensed Materials - Property of IBM
 * IBM Cognos Products: BI Cloud (C) Copyright IBM Corp. 2014, 2018
 * US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
 */
define([], function () {

	var blackListContentTags = ['body', 'embed', 'script', 'object', 'applet', 'meta', 'style', 'link'];

	return {

		/**
   * Cleans the provided html string input to only the supplied array of whiteListedElements
   * @param {String} input Input html to process
   * @param {String | Array} whiteListedElements all whitelisted html tags as an array. ie ['<div>', '<p>'...] or as a string '<div><p>'
   * @param {Boolean} removeComments if true, strips html comments
   */
		cleanseContentElements: function cleanseContentElements(input, whiteListedElements, removeComments) {
			if (!input) {
				return null;
			}

			whiteListedElements = whiteListedElements || [];
			// making sure the allowed arg is a string containing only tags in lowercase (<a><b><c>)
			var allowed = ((whiteListedElements + '').toLowerCase().match(/<[a-z][a-z0-9]*>/g) || []).join('');
			var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi;
			if (removeComments) {
				var commentsAndTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi;
				input = input.replace(commentsAndTags, '');
			}
			return input.replace(tags, function ($0, $1) {
				return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : '';
			});
		},

		isValidHtmlContent: function isValidHtmlContent(widgetContent) {
			return !this.containsTag(widgetContent) && !this.containsBlackListedAttributes(widgetContent) && this.isHtmlSafe(widgetContent);
		},

		containsTag: function containsTag(widgetContent) {
			// Validate by matching whole tag name
			// ie. '<tag attr=...', '<tag>', '<tag/>', '<tag'
			var re = new RegExp('<(' + blackListContentTags.join('|') + ')(\\s|\\/|>|$)', 'i');
			return re.test(widgetContent);
		},

		containsBlackListedAttributes: function containsBlackListedAttributes(widgetContent) {
			// Block any attribute that starts with  'on'
			var re = new RegExp('<\\w+[^>]*\\bon\\w+\\s*=', 'i');
			return re.test(widgetContent);
		},

		isHtmlSafe: function isHtmlSafe(s) {
			var matches = s.match(/<\s*\w+\b[^>]+\s*>/g);
			if (!matches) {
				return true;
			}
			return [true].concat(matches). // return all Html elements with some attributes
			reduce( // reduce matches to true/false if valid or not
			function (prevValue, el) {
				// s is attribute, like class='a b c' or src='url()'
				// return true if attribute starts with javascript
				return prevValue && (el.match(/\w+\s*=\s*"?\s*javascript/gi) ? false : true);
			});
		},

		/**
   * check html strings is valid. If not, we reset it
   */
		sanitizeHtml: function sanitizeHtml(html) {
			if (!html || !this.isValidHtmlContent(html)) {
				return '';
			}
			return html;
		}
	};
});
//# sourceMappingURL=HtmlXSSUtils.js.map