// Run one lab's MATLAB layer through the numbl CLI, outside the browser. // // node scripts/runlab.mjs '' [--show key,key] // // It composes main.m exactly as the app does (driver, newline, script), copies // the shared library into a scratch directory, runs it, and prints out.json. // NUMBL_DIR points at a numbl checkout (default ~/src/numbl). import { execFileSync } from 'node:child_process' import { mkdtempSync, mkdirSync, readFileSync, writeFileSync, readdirSync, copyFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join, dirname, resolve } from 'node:path' import { fileURLToPath } from 'node:url' const here = dirname(fileURLToPath(import.meta.url)) const root = resolve(here, '..') const numbl = process.env.NUMBL_DIR ?? join(process.env.HOME, 'src', 'numbl') const cli = join(numbl, 'dist-cli', 'cli.js') export function runLab(driverPath, scriptPath, params, opts = {}) { const dir = mkdtempSync(join(tmpdir(), 'lapl-')) const lib = join(root, 'src', 'matlab') for (const f of readdirSync(lib)) if (f.endsWith('.m')) copyFileSync(join(lib, f), join(dir, f)) const driver = readFileSync(driverPath, 'utf8') const script = readFileSync(scriptPath, 'utf8') writeFileSync(join(dir, 'main.m'), `${driver}\n${script}`) writeFileSync(join(dir, 'params.json'), JSON.stringify(params)) const t0 = Date.now() const stdout = execFileSync('node', [cli, 'run', 'main.m'], { cwd: dir, encoding: 'utf8' }) const ms = Date.now() - t0 const out = JSON.parse(readFileSync(join(dir, 'out.json'), 'utf8')) if (opts.verbose && stdout.trim()) process.stdout.write(stdout) return { out, stdout, ms, dir } } if (process.argv[1] === fileURLToPath(import.meta.url)) { const [driverPath, scriptPath, paramsJson] = process.argv.slice(2) if (!driverPath || !scriptPath) { console.error('usage: node scripts/runlab.mjs \'\'') process.exit(2) } const { out, stdout, ms } = runLab(driverPath, scriptPath, JSON.parse(paramsJson ?? '{}')) if (stdout.trim()) process.stdout.write(stdout) const show = process.argv.includes('--full') console.log(`[${ms} ms]`) console.log(JSON.stringify(out, null, show ? 1 : 0).slice(0, show ? 1e9 : 4000)) } mkdirSync(join(root, 'tmp'), { recursive: true })