import { readFile, readdir } from 'node:fs/promises'; import { execFile } from 'node:child_process'; import { promisify } from 'node:util'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; const exec = promisify(execFile); const projectRoot = fileURLToPath(new URL('../', import.meta.url)); export function logAddresses(bytes, encoding) { const text = bytes.toString( encoding || (bytes[0] === 255 && bytes[1] === 254 ? 'utf16le' : 'utf8'), ); return [ ...text .replace(/\x1b\[[0-9;]*m/g, '') .matchAll(/(?:Local:|Network:)\s*(https?:\/\/[^\s]+)/g), ] .map((match) => match[1]) .reverse(); } async function matchesProject(address, root) { try { const url = new URL(address); if ( !['http:', 'https:'].includes(url.protocol) || url.username || url.password ) return false; const source = await readFile(path.join(root, 'src/index.jsx'), 'utf8'); const response = await fetch(new URL('src/index.jsx', url), { signal: AbortSignal.timeout(2500), }); if (!response.ok) return false; const text = await response.text(); const map = text.match( /sourceMappingURL=data:application\/json;base64,([^\s]+)/, ); return ( !!map && JSON.parse( Buffer.from(map[1], 'base64').toString(), ).sourcesContent?.includes(source) ); } catch { return false; } } async function nodePorts() { if (process.platform !== 'win32') return []; const command = '[Console]::OutputEncoding=[Text.Encoding]::UTF8; $OutputEncoding=[Text.Encoding]::UTF8; ' + '$ids = @(Get-CimInstance Win32_Process -Filter "Name=\'node.exe\'" | Select-Object -ExpandProperty ProcessId); ' + 'Get-NetTCPConnection -State Listen -ErrorAction Stop | Where-Object { $_.OwningProcess -in $ids } | Select-Object -ExpandProperty LocalPort -Unique | ConvertTo-Json -Compress'; const { stdout } = await exec( 'powershell.exe', ['-NoProfile', '-Command', command], { timeout: 15000, windowsHide: true }, ); const parsed = JSON.parse(stdout.trim() || '[]'); return [parsed].flat().filter((port) => Number.isInteger(port) && port > 0); } export async function findDevService({ root = projectRoot, getPorts = nodePorts, } = {}) { const candidates = []; const entries = await readdir(root, { withFileTypes: true }); const logs = entries.filter( (entry) => entry.isFile() && /\.log$/i.test(entry.name), ); logs.sort( (a, b) => Number(b.name === 'dev.log') - Number(a.name === 'dev.log'), ); for (const entry of logs.slice(0, 8)) { const bytes = await readFile(path.join(root, entry.name)); candidates.push( ...logAddresses( bytes.subarray(Math.max(0, bytes.length - 262144)), bytes[0] === 255 && bytes[1] === 254 ? 'utf16le' : 'utf8', ), ); } // Only Node listeners are probed; the source map must match this checkout. for (const address of new Set(candidates)) { if (await matchesProject(address, root)) return new URL(address).origin + '/'; } const ports = await getPorts(); for (const address of new Set( ports.map((port) => 'http://127.0.0.1:' + port + '/'), )) { if (await matchesProject(address, root)) return new URL(address).origin + '/'; } return null; }