|
| 1 | +// Copyright (c) Meta Platforms, Inc. and affiliates. |
| 2 | +// One-off evidence capture helpers. Not for merge. |
| 3 | +import {createServer} from 'node:http'; |
| 4 | +import {readFile} from 'node:fs/promises'; |
| 5 | +import path from 'node:path'; |
| 6 | + |
| 7 | +const TYPES = {'.html': 'text/html', '.js': 'text/javascript', '.css': 'text/css', '.json': 'application/json', '.svg': 'image/svg+xml', '.woff2': 'font/woff2', '.png': 'image/png'}; |
| 8 | + |
| 9 | +export function serve(root) { |
| 10 | + const base = path.resolve(root); |
| 11 | + return new Promise(resolve => { |
| 12 | + const server = createServer(async (req, res) => { |
| 13 | + const url = new URL(req.url, 'http://x'); |
| 14 | + const file = path.resolve(base, '.' + decodeURIComponent(url.pathname === '/' ? '/index.html' : url.pathname)); |
| 15 | + if (file !== base && !file.startsWith(base + path.sep)) { |
| 16 | + res.writeHead(404); |
| 17 | + res.end(); |
| 18 | + return; |
| 19 | + } |
| 20 | + try { |
| 21 | + const body = await readFile(file); |
| 22 | + res.writeHead(200, {'content-type': TYPES[path.extname(file)] ?? 'application/octet-stream'}); |
| 23 | + res.end(body); |
| 24 | + } catch { |
| 25 | + res.writeHead(404); |
| 26 | + res.end(); |
| 27 | + } |
| 28 | + }); |
| 29 | + server.listen(0, '127.0.0.1', () => resolve(server)); |
| 30 | + }); |
| 31 | +} |
| 32 | + |
| 33 | +export async function settle(page) { |
| 34 | + await page.evaluate(async () => { |
| 35 | + await document.fonts.ready; |
| 36 | + await new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r))); |
| 37 | + }); |
| 38 | +} |
| 39 | + |
| 40 | +// A clip around the side nav and any open menu, with a margin. |
| 41 | +export async function navClip(page) { |
| 42 | + return page.evaluate(() => { |
| 43 | + const boxes = [...document.querySelectorAll('nav, [role="navigation"], .astryx-side-nav, [role="menu"]')] |
| 44 | + .map(e => e.getBoundingClientRect()) |
| 45 | + .filter(r => r.width > 0 && r.height > 0); |
| 46 | + const left = Math.max(0, Math.min(...boxes.map(r => r.left)) - 24); |
| 47 | + const top = Math.max(0, Math.min(...boxes.map(r => r.top)) - 24); |
| 48 | + const right = Math.min(innerWidth, Math.max(...boxes.map(r => r.right)) + 24); |
| 49 | + const bottom = Math.min(innerHeight, Math.max(...boxes.map(r => r.bottom)) + 24); |
| 50 | + return {x: left, y: top, width: right - left, height: bottom - top}; |
| 51 | + }); |
| 52 | +} |
0 commit comments