Download Game! Currently 71 players and visitors. Last logged in:WhlxchGlauriCordobaDefault

Blitzer's Blog >> 72550

Back to blogs index
Posted: 16 Sep 2026 15:42 [ permalink ]
That makes things significantly cleaner. By sticking to trusted nodes, we can
drop the heavy C++ native bindings of isolated-vm and rely entirely on Node's
native vm module. This ensures the harness remains lightweight, highly
portable, and perfectly suited for containerized distributed environments.
Since the execution layer is settled, let's build the Single-File Packager and
CLI.
This component acts as a compiler: it reads the spec.json, grabs the
Javascript implementation, verifies the syntax using the V8 engine, and
outputs a highly portable, self-contained artifact that can be dropped into
any Node.js, browser, or QuickJS environment.
1. The Packager (harness/packager.js)
The packager bundles the specification and the code into a single Immediately
Invoked Function Expression (IIFE). Crucially, we use vm.Script during the
packaging phase as a syntax verification tool to ensure we never deploy broken
code to the registry.
const fs = require('fs').promises;
const path = require('path');
const vm = require('vm');

async function compileRoutine(routineName) {
    const routineDir = path.join(__dirname, '../routines', routineName);
    const specPath = path.join(routineDir, 'spec.json');
    
    // 1. Read and validate spec
    const specRaw = await fs.readFile(specPath, 'utf8');
    const spec = JSON.parse(specRaw);
    
    // 2. Read Javascript Implementation
    const jsEntry = spec.implementations.javascript.entry;
    const code = await fs.readFile(path.join(routineDir, jsEntry), 'utf8');

    // 3. Syntax Verification (Pre-flight check)
    try {
        // We don't run it, we just compile it to catch early syntax errors
        new vm.Script(`(${code})`);
    } catch (err) {
        throw new Error(`Syntax Error in ${routineName} (${jsEntry}):
${err.message}`);
    }

    // 4. Build the Portable Artifact
    // We inject the spec and the runner into a clean, evaluatable string
    const bundled = `(function() {
    const spec = ${JSON.stringify(spec, null, 2)};
    const implementation = ${code};
    
    return {
        spec: spec,
        // The runner automatically applies defaults from the spec
        run: async function(params = {}) {
            const executionParams = {};
            for (const [key, config] of Object.entries(spec.parameters)) {
                if (config.required && params[key] === undefined) {
                    throw new Error("Missing required parameter: " + key);
                }
                executionParams[key] = params[key] !== undefined ? params[key]
: config.default;
            }
            return await implementation(executionParams);
        }
    };
})()`;

    return bundled;
}

module.exports = { compileRoutine };

2. The CLI Developer Tool (harness/cli.js)
This CLI allows you to rapidly build, test, and compile routines locally
before they ever hit the registry API.
#!/usr/bin/env node
const { compileRoutine } = require('./packager');
const { runSecurely } = require('./runner'); // Using the native vm lockdown
we established
const fs = require('fs').promises;
const path = require('path');

const [,, command, routineName, ...args] = process.argv;

async function main() {
    if (!command || !routineName) {
        console.log('Usage: node cli.js <test|compile> <routine_name>
[params_json]');
        process.exit(1);
    }

    try {
        if (command === 'compile') {
            console.log(`Compiling [${routineName}]...`);
            const artifact = await compileRoutine(routineName);
            
            const outPath = path.join(__dirname, `../routines/${routineName}/di
st.js`);
            await fs.writeFile(outPath, artifact);
            
console.log(` Success! Artifact written to ${outPath}`);
            console.log(`Size: ${(Buffer.byteLength(artifact) /
1024).toFixed(2)} KB`);
        } 
        
        else if (command === 'test') {
            console.log(`Running [${routineName}] in local sandbox...`);
            // Parse inline JSON args if provided, otherwise empty object
            const params = args[0] ? JSON.parse(args[0]) : {};
            
            // Read code directly for local testing
            const dir = path.join(__dirname, '../routines', routineName);
            const spec = JSON.parse(await fs.readFile(path.join(dir,
'spec.json'), 'utf8'));
            const code = await fs.readFile(path.join(dir, spec.implementations.
javascript.entry), 'utf8');
            
            const start = performance.now();
            const result = await runSecurely(code, params);
            const end = performance.now();
            
            console.log('
--- Result ---');
            console.log(JSON.stringify(result, null, 2));
            console.log(`
Execution time: ${(end - start).toFixed(2)}ms`);
        }
    } catch (err) {
        console.error(` Error: ${err.message}`);
        process.exit(1);
    }
}

main();

3. Consuming the Artifact
Because the packager generates a pure anonymous function closure, consuming it
in any Javascript environment is frictionless.
If this artifact is retrieved via a GET /routines/calculate_tax/download
endpoint, the receiving node executes it like this:
/ On the consumer node (Browser, QuickJS, or another Node instance)
const rawArtifact = await fetch('http://registry/api/routines/calculate_tax/art
ifact').then(r => r.text());

/ eval() securely instantiates the object. 
/ It does not execute the routine, it just parses the closure.
const routine = eval(rawArtifact);

/ The consumer can inspect the spec...
console.log(routine.spec.description);

/ ...or run the routine with full validation logic bundled inside
const result = await routine.run({ subtotal: 100 });