"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getSanitizedInitialMessages = getSanitizedInitialMessages;
exports.getSanitizedI18nConfig = getSanitizedI18nConfig;
exports.getSanitizedCustomCss = getSanitizedCustomCss;
exports.createPage = createPage;
const sanitize_html_1 = __importDefault(require("sanitize-html"));
function sanitizeUserInput(input) {
    let sanitized = (0, sanitize_html_1.default)(input, {
        allowedTags: [],
        allowedAttributes: {},
    });
    sanitized = sanitized.replace(/javascript:/gi, '');
    sanitized = sanitized.replace(/data:/gi, '');
    sanitized = sanitized.replace(/vbscript:/gi, '');
    return sanitized;
}
function getSanitizedInitialMessages(initialMessages) {
    const sanitizedString = sanitizeUserInput(initialMessages);
    return sanitizedString
        .split('\n')
        .map((line) => line.trim())
        .filter((line) => line !== '');
}
function getSanitizedI18nConfig(config) {
    const sanitized = {};
    for (const [key, value] of Object.entries(config)) {
        sanitized[key] = sanitizeUserInput(value);
    }
    return sanitized;
}
function getSanitizedCustomCss(customCss) {
    return customCss.replace(/<\/style/gi, '');
}
function createPage({ instanceId, webhookUrl, showWelcomeScreen, loadPreviousSession, i18n: { en }, initialMessages, authentication, allowFileUploads, allowedFilesMimeTypes, customCss, enableStreaming, }) {
    const validAuthenticationOptions = [
        'none',
        'basicAuth',
        'n8nUserAuth',
    ];
    const validLoadPreviousSessionOptions = [
        'manually',
        'memory',
        'notSupported',
    ];
    const sanitizedAuthentication = validAuthenticationOptions.includes(authentication)
        ? authentication
        : 'none';
    const sanitizedShowWelcomeScreen = !!showWelcomeScreen;
    const sanitizedAllowFileUploads = !!allowFileUploads;
    const sanitizedAllowedFilesMimeTypes = sanitizeUserInput(allowedFilesMimeTypes?.toString() ?? '');
    const sanitizedCustomCss = getSanitizedCustomCss(customCss?.toString() ?? '');
    const sanitizedLoadPreviousSession = validLoadPreviousSessionOptions.includes(loadPreviousSession)
        ? loadPreviousSession
        : 'notSupported';
    const sanitizedInitialMessages = getSanitizedInitialMessages(initialMessages);
    const sanitizedI18nConfig = getSanitizedI18nConfig(en || {});
    return `<!doctype html>
	<html lang="en">
		<head>
			<meta charset="utf-8">
			<meta name="viewport" content="width=device-width, initial-scale=1">
			<title>Chat</title>
			<link href="https://cdn.jsdelivr.net/npm/normalize.css@8.0.1/normalize.min.css" rel="stylesheet" />
			<link href="https://cdn.jsdelivr.net/npm/@n8n/chat/dist/style.css" rel="stylesheet" />
			<style>
				html,
				body,
				#n8n-chat {
					width: 100%;
					height: 100%;
				}
			</style>
			<style>${sanitizedCustomCss}</style>
		</head>
		<body>
			<script type="module">
				import { createChat } from 'https://cdn.jsdelivr.net/npm/@n8n/chat/dist/chat.bundle.es.js';

				(async function () {
					const authentication = '${sanitizedAuthentication}';
					let metadata;
					if (authentication === 'n8nUserAuth') {
						try {
							const response = await fetch('/rest/login', {
									method: 'GET',
									headers: { 'browser-id': localStorage.getItem('n8n-browserId') }
							});

							if (response.status !== 200) {
								throw new Error('Not logged in');
							}

							const responseData = await response.json();
							metadata = {
								user: {
									id: responseData.data.id,
									firstName: responseData.data.firstName,
									lastName: responseData.data.lastName,
									email: responseData.data.email,
								},
							};
						} catch (error) {
							window.location.href = '/signin?redirect=' + window.location.href;
							return;
						}
					}

					createChat({
						mode: 'fullscreen',
						webhookUrl: '${webhookUrl}',
						showWelcomeScreen: ${sanitizedShowWelcomeScreen},
						loadPreviousSession: ${sanitizedLoadPreviousSession !== 'notSupported'},
						metadata: metadata,
						webhookConfig: {
							headers: {
								'X-Instance-Id': '${instanceId}',
							}
						},
						allowFileUploads: ${sanitizedAllowFileUploads},
						allowedFilesMimeTypes: ${JSON.stringify(sanitizedAllowedFilesMimeTypes)},
						i18n: {
							${Object.keys(sanitizedI18nConfig).length ? `en: ${JSON.stringify(sanitizedI18nConfig)},` : ''}
						},
						${sanitizedInitialMessages.length ? `initialMessages: ${JSON.stringify(sanitizedInitialMessages)},` : ''}
						enableStreaming: ${!!enableStreaming},
					});
				})();
			</script>
		</body>
	</html>`;
}
//# sourceMappingURL=templates.js.map