api-server / test-long.js
XWX-AI's picture
chore: increase HTML size limit from 8MB to 10MB for backend consistency
b89c431
const http = require('http');
const fs = require('fs');
const BACKEND_PORT = process.env.PORT || 7861;
const CSS = `@media print { @page { size: A4; margin: 15mm 10mm; } body { -webkit-print-color-adjust: exact; } }
body { font-family: -apple-system, sans-serif; font-size: 14px; line-height: 1.6; max-width: 746px; margin: 0 auto; padding: 20px; }
h1,h2,h3 { font-weight: 600; margin: 16px 0 8px; }
pre { background: #f6f8fa; padding: 16px; border-radius: 6px; overflow-x: auto; border: 1px solid #e1e4e8; }
code { font-family: monospace; font-size: 13px; }
p { margin: 8px 0; } table { border-collapse: collapse; width: 100%; margin: 12px 0; }
th,td { border: 1px solid #dfe2e5; padding: 8px 12px; } th { background: #f1f3f4; }
.chat-container { display: flex; flex-direction: column; gap: 16px; }
.message-row { display: flex; gap: 10px; } .message-bubble { max-width: 85%; padding: 12px 16px; border-radius: 12px; }
.ai-bubble { background: #fff; border: 1px solid #eee; } .user-bubble { background: #e8f0fe; }
.avatar { width: 32px; height: 32px; border-radius: 50%; display: flex; align-items: center; justify-content: center; }`;
function E(s) { return s.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;'); }
function shikiWrap(token, color) {
return `<span style="color:${color}">${E(token)}</span>`;
}
function generateShikiCode(lines) {
return lines.map(line => {
const parts = [];
const tokens = line.split(/(\s+|[^a-zA-Z0-9_\s]+)/g);
for (const tok of tokens) {
if (!tok) continue;
if (/^\s+$/.test(tok)) { parts.push(tok); continue; }
let color = '#c9d1d9';
if (/^(const|let|var|function|return|if|else|for|async|await|import|from|export|class|extends|new|try|catch|throw|typeof|this|switch|case|break|continue|while|do|of|in|static|get|set|super|interface|type|void|null|undefined|true|false)$/.test(tok)) color = '#ff7b72';
else if (/^(console|log|error|fetch|Promise|Math|Date|JSON|Map|Set|Array|Object|String|Number|Error|setTimeout|clearTimeout|AbortController|AbortSignal|require|module|exports|process)$/.test(tok)) color = '#d2a8ff';
else if (/^\d+$/.test(tok)) color = '#79c0ff';
else if (/^[{}()\[\];,\.:=+\-*/<>!&|?%@~^'"`]+$/.test(tok)) color = '#c9d1d9';
else if (/^[A-Z]/.test(tok) && tok.length > 1) color = '#ffa657';
parts.push(shikiWrap(tok, color));
}
return parts.join('');
}).join('\n');
}
const CODE_LINES = [
'async function fetchData(url, options = {}) {',
' const controller = new AbortController();',
' const timeout = setTimeout(() => controller.abort(), 30000);',
' try {',
' const response = await fetch(url, {',
' ...options,',
' signal: controller.signal,',
" headers: { 'Content-Type': 'application/json' },",
' });',
' if (!response.ok) {',
' throw new Error(`HTTP ${response.status}: ${response.statusText}`);',
' }',
' const data = await response.json();',
" console.log('Data received:', data);",
' return data;',
' } catch (error) {',
" console.error('Fetch failed:', error.message);",
' throw error;',
' } finally {',
' clearTimeout(timeout);',
' }',
'}',
];
const TEXT = '<p>This is a typical AI response explaining a concept with some details and examples that users commonly see in chat conversations.</p>';
function buildHtml(targetSizeMB) {
const shikiCode = generateShikiCode(CODE_LINES);
const codeBlock = `<pre data-language="javascript"><code class="language-javascript">${shikiCode}</code></pre>`;
const codeBlockSize = Buffer.byteLength(codeBlock, 'utf8');
const textBlockSize = Buffer.byteLength(TEXT, 'utf8');
const overhead = 2048;
const targetBytes = targetSizeMB * 1024 * 1024 - overhead;
let html = `<!DOCTYPE html><html><head><meta charset="UTF-8"><style>${CSS}</style></head><body><div class="chat-container">`;
const codeIterations = Math.ceil((targetBytes * 0.5) / codeBlockSize);
const textIterations = Math.ceil((targetBytes * 0.5) / textBlockSize);
let i = 0, j = 0;
while (i < codeIterations || j < textIterations) {
if (i < codeIterations) {
html += `<div class="message-row"><div class="avatar">&#129302;</div><div class="message-bubble ai-bubble">${codeBlock}</div></div>`;
i++;
}
if (j < textIterations) {
html += `<div class="message-row"><div class="avatar">&#128100;</div><div class="message-bubble user-bubble">${TEXT}</div></div>`;
j++;
}
}
html += '</div></body></html>';
return html;
}
async function sendPdfRequest(html) {
const payload = JSON.stringify({
html, codeTheme: 'github', showWatermark: false,
imageCount: 0, totalImageSizeMB: 0,
platform: 'Benchmark', language: 'en-US', extensionVersion: '2.0.2',
exportCount: 0, exportPdf: 0, exportMd: 0, exportTxt: 0,
exportDocx: 0, exportJson: 0, exportClipboard: 0, exportNotion: 0,
});
return new Promise((resolve, reject) => {
const startTime = Date.now();
const req = http.request({
hostname: 'localhost', port: BACKEND_PORT, path: '/api/generate_pdf',
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(payload) },
timeout: 1800000, // 30 min
}, (res) => {
const chunks = [];
res.on('data', (chunk) => chunks.push(chunk));
res.on('end', () => {
const elapsed = ((Date.now() - startTime) / 1000).toFixed(1);
if (res.statusCode === 200) {
resolve({ ok: true, elapsed, pdfSizeMB: (Buffer.concat(chunks).length / 1024 / 1024).toFixed(2) });
} else {
resolve({ ok: false, elapsed, status: res.statusCode, error: Buffer.concat(chunks).toString() });
}
});
});
req.on('error', reject);
req.on('timeout', () => { req.destroy(); reject(new Error('HTTP timeout')); });
req.write(payload);
req.end();
});
}
async function main() {
const size = parseFloat(process.argv[2] || '4.92');
const html = buildHtml(size);
const actualSizeMB = (Buffer.byteLength(html, 'utf8') / 1024 / 1024).toFixed(2);
console.log(`Testing ${size} MB target, actual ${actualSizeMB} MB HTML...`);
console.log(`Start: ${new Date().toISOString()}`);
try {
const result = await sendPdfRequest(html);
console.log(`End: ${new Date().toISOString()}`);
if (result.ok) {
console.log(`SUCCESS in ${result.elapsed}s, PDF: ${result.pdfSizeMB} MB`);
} else {
console.log(`FAIL: HTTP ${result.status}, ${result.elapsed}s`);
console.log(result.error);
}
} catch (err) {
console.error(`ERROR: ${err.message}`);
}
}
main();