alef 0.25.24

Opinionated polyglot binding generator for Rust libraries
Documentation
{{ header }}import { spawn } from 'child_process';
import { resolve } from 'path';
import { createRequire } from 'module';
import { readFileSync } from 'fs';
import { fileURLToPath } from 'url';

let serverProcess;

export async function setup() {
  // Honor a pre-set MOCK_SERVER_URL: when the test runner (e.g. `alef test-apps
  // run`) has already built and started the shared mock-server, it exports
  // MOCK_SERVER_URL into our environment. In that case, reuse it and skip
  // spawning a local binary entirely. Only self-spawn when it is unset.
  if (process.env.MOCK_SERVER_URL) {
    return;
  }

  // Mock server binary must be pre-built (e.g. by CI or `cargo build --manifest-path e2e/rust/Cargo.toml --bin mock-server --release`)
  serverProcess = spawn(
    resolve(__dirname, '../rust/target/release/mock-server'),
    [resolve(__dirname, '../../fixtures')],
    { stdio: ['pipe', 'pipe', 'inherit'] }
  );

  const url = await new Promise<string>((resolve, reject) => {
    let foundUrl = false;

    serverProcess.stdout.on('data', (data) => {
      const dataStr = data.toString();

      const urlMatch = dataStr.match(/MOCK_SERVER_URL=(.*)/);
      if (urlMatch) {
        process.env.MOCK_SERVER_URL = urlMatch[1].trim();
        foundUrl = true;
      }

      const serversMatch = dataStr.match(/MOCK_SERVERS=({.*})/);
      if (serversMatch) {
        try {
          const servers = JSON.parse(serversMatch[1]);
          for (const [fixtureId, fixtureUrl] of Object.entries(servers)) {
            process.env[`MOCK_SERVER_${fixtureId.toUpperCase()}`] = fixtureUrl as string;
          }
        } catch {
          // Ignore JSON parse errors
        }
      }

      if (foundUrl) resolve(process.env.MOCK_SERVER_URL as string);
    });
    setTimeout(() => reject(new Error('Mock server startup timeout')), 30000);
  });
}

export async function teardown() {
  if (serverProcess) {
    serverProcess.stdin.end();
    serverProcess.kill();
  }
}