UXInteract / task_016 /tests /_shared /offline_browser.js
DojiSum's picture
Publish the current 141-task UXInteract release
ef987bb verified
Raw History Blame Contribute Delete
3.34 kB
const fs = require('fs');
const os = require('os');
const path = require('path');
const { spawnSync } = require('child_process');
const { pathToFileURL } = require('url');
function chromiumBinary() {
const candidates = [process.env.CHROMIUM_BIN, '/snap/bin/chromium', '/usr/bin/chromium', '/usr/bin/chromium-browser', '/usr/bin/google-chrome'];
const found = candidates.find(candidate => candidate && fs.existsSync(candidate));
if (!found) throw new Error('offline Chromium binary is unavailable');
return found;
}
function runBrowserCase(entryPath, caseFunction, input = null) {
const snapShared = path.join(os.homedir(), 'snap', 'chromium', 'common');
const stagingRoot = fs.existsSync(snapShared) ? snapShared : os.tmpdir();
const tempDir = fs.mkdtempSync(path.join(stagingRoot, 'harbor-offline-browser-'));
const wrapperPath = path.join(tempDir, 'runner.html');
const candidateDir = path.join(tempDir, 'candidate');
const resolvedEntry = path.resolve(entryPath);
fs.cpSync(path.dirname(resolvedEntry), candidateDir, {
recursive: true,
filter: source => !['tests', 'logs', 'node_modules'].includes(path.basename(source)),
});
const entryUrl = pathToFileURL(path.join(candidateDir, path.basename(resolvedEntry))).href;
const payload = JSON.stringify(input).replace(/</g, '\\u003c');
const source = caseFunction.toString().replace(/<\/script/gi, '<\\/script');
const html = `<!doctype html><meta charset="utf-8"><title>WAITING</title>
<iframe id="candidate" src="${entryUrl}"></iframe>
<script>
const finish = value => {
const json = JSON.stringify(value);
document.title = 'HARBOR_RESULT_' + btoa(unescape(encodeURIComponent(json)));
};
const frame = document.getElementById('candidate');
const timer = setTimeout(() => finish({ok:false,error:'candidate iframe timed out'}), 5000);
frame.addEventListener('load', async () => {
clearTimeout(timer);
try {
const value = await (${source})(frame.contentDocument, frame.contentWindow, ${payload});
finish({ok:true,value});
} catch (error) {
finish({ok:false,error:error && (error.stack || error.message) || String(error)});
}
});
<\/script>`;
fs.writeFileSync(wrapperPath, html, 'utf8');
const result = spawnSync(chromiumBinary(), [
'--headless=new', '--no-sandbox', '--disable-gpu', '--disable-dev-shm-usage',
'--disable-web-security', '--allow-file-access-from-files', '--disable-background-networking',
'--disable-component-update', '--disable-default-apps', '--disable-sync',
'--metrics-recording-only', '--no-first-run', '--host-resolver-rules=MAP * 0.0.0.0',
`--user-data-dir=${path.join(tempDir, 'profile')}`,
'--virtual-time-budget=6500', '--dump-dom', pathToFileURL(wrapperPath).href,
], { encoding: 'utf8', timeout: 15000, env: process.env });
fs.rmSync(tempDir, { recursive: true, force: true });
if (result.error) throw result.error;
const match = result.stdout.match(/<title>HARBOR_RESULT_([^<]+)<\/title>/i);
if (!match) throw new Error(`offline Chromium produced no result (exit ${result.status}); stdout=${result.stdout.slice(-1600)}; stderr=${result.stderr.slice(-1200)}`);
const decoded = JSON.parse(Buffer.from(match[1], 'base64').toString('utf8'));
if (!decoded.ok) throw new Error(decoded.error);
return decoded.value;
}
module.exports = { runBrowserCase };