← Back to Documentation Index

Kimera.js API Documentation

This document provides comprehensive documentation of all APIs available in Kimera.js.

Command Line Interface

kimera

Launch the interactive REPL (Read-Eval-Print Loop).

kimera

Behavior:

Example:

$ kimera
Kimera 0.2.0
Exit using Ctrl+C or Ctrl+D

> const x = 10
undefined
> x * 2
20
> console.log("Hello!")
Hello!
undefined
> const add = (a, b) => a + b
undefined
> add(5, 3)
8

kimera run [file]

Execute a JavaScript or TypeScript file.

kimera run <file> [flags]

Arguments:

Flags:

Examples:

# Run a JavaScript file (no permissions)
kimera run script.js

# Run a TypeScript file with type annotations
kimera run app.ts

# Run with permission flags
kimera run script.js --fs              # Filesystem only
kimera run script.js --net             # Network only
kimera run script.js --env             # Environment variables only
kimera run script.js --fs --net --env  # All permissions

Error Handling:

The command returns proper exit codes:

Error messages are formatted with context:

$ kimera run missing.js
Error: failed to run file: failed to read file "missing.js": open missing.js: no such file or directory

kimera version

Display the version of Kimera.js.

kimera version

Output:

Kimera 0.2.0

kimera help / kimera --help

Display help information about available commands.

kimera --help

Output:

Kimera is a modern JavaScript/TypeScript runtime that provides a REPL
and file execution capabilities.

Usage:
  kimera [flags]
  kimera [command]

Available Commands:
  help        Help about any command
  run         Run a JavaScript or TypeScript file
  version     Print the version information

Flags:
  -h, --help   help for kimera

Use "kimera [command] --help" for more information about a command.

JavaScript/TypeScript APIs

Console API

console.log(...args)

Prints messages to standard output.

Parameters:

Example:

console.log("Hello");
console.log("Multiple", "arguments");
console.log("Value:", 42);
console.log(`Template: ${1 + 1}`);

Kimera File System API

The Kimera object provides file system operations.

Kimera.readFile(filePath)

Reads the entire contents of a file as a string.

Parameters:

Returns:

Throws:

Example:

// Read a text file
const content = Kimera.readFile("./data.txt");
console.log(content);

// Read with error handling
try {
  const data = Kimera.readFile("./config.json");
  console.log(data);
} catch (error) {
  console.log("Failed to read file");
}

Kimera.writeFile(filePath, content)

Writes content to a file, creating it if it doesn't exist or overwriting if it does.

Parameters:

Returns:

Throws:

Example:

// Write simple text
Kimera.writeFile("output.txt", "Hello World!");

// Write multi-line content
const data = "Line 1\nLine 2\nLine 3";
Kimera.writeFile("multiline.txt", data);

// Overwrite existing file
Kimera.writeFile("existing.txt", "New content");

// Write with error handling
try {
  Kimera.writeFile("/protected/file.txt", "data");
} catch (error) {
  console.log("Permission denied");
}

Note: File system operations require the --fs flag:

kimera run script.js --fs

Kimera Environment Variables API

The Kimera object provides environment variable operations.

Kimera.getEnv(varName)

Reads the value of an environment variable.

Parameters:

Returns:

Throws:

Example:

// Read an environment variable
const path = Kimera.getEnv("PATH");
console.log("PATH:", path);

// Check if a variable exists
const myVar = Kimera.getEnv("MY_VAR");
if (myVar) {
  console.log("MY_VAR is set to:", myVar);
} else {
  console.log("MY_VAR is not set");
}

// With error handling
try {
  const home = Kimera.getEnv("HOME");
  console.log("Home directory:", home);
} catch (error) {
  console.log("Environment access denied");
}

Kimera.setEnv(varName, value)

Sets the value of an environment variable in the current process.

Parameters:

Returns:

Throws:

Example:

// Set an environment variable
Kimera.setEnv("MY_VAR", "my_value");

// Verify it was set
const value = Kimera.getEnv("MY_VAR");
console.log(value); // "my_value"

// Set with error handling
try {
  Kimera.setEnv("CONFIG_PATH", "/etc/config");
  console.log("Environment variable set successfully");
} catch (error) {
  console.log("Failed to set environment variable");
}

Note: Environment variable operations require the --env flag:

kimera run script.js --env

Kimera HTTP Server API

The Kimera object provides HTTP server functionality for building web servers and APIs.

Kimera.createServer(handler)

Creates an HTTP server with the specified request handler function.

Parameters:

Request Object:

Response Object (returned by handler):

Returns:

Example:

// Create a simple HTTP server
const server = Kimera.createServer((request) => {
  console.log(`${request.method} ${request.path}`);
  
  return {
    status: 200,
    headers: {
      "Content-Type": "text/plain",
    },
    body: "Hello, World!",
  };
});

// Start listening on port 8080
server.listen(8080);

server.listen(port)

Starts the HTTP server listening on the specified port.

Parameters:

Returns:

Example:

const server = Kimera.createServer((request) => {
  return {
    status: 200,
    headers: { "Content-Type": "text/html" },
    body: "<h1>Welcome</h1>",
  };
});

server.listen(3000);
console.log("Server running on port 3000"); // This won't execute until server stops

server.close()

Stops the HTTP server and releases the port.

Returns:

Example:

const server = Kimera.createServer((request) => {
  if (request.path === "/shutdown") {
    server.close(); // Stop the server
    return {
      status: 200,
      body: "Server shutting down",
    };
  }
  return { status: 200, body: "OK" };
});

server.listen(8080);

HTTP Server Examples:

Route Handling:

const server = Kimera.createServer((request) => {
  // Route based on path
  if (request.path === "/") {
    return {
      status: 200,
      headers: { "Content-Type": "text/html" },
      body: "<h1>Home Page</h1>",
    };
  }
  
  if (request.path === "/api") {
    return {
      status: 200,
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ message: "API endpoint" }),
    };
  }
  
  // 404 for unknown routes
  return {
    status: 404,
    headers: { "Content-Type": "text/plain" },
    body: "Not Found",
  };
});

server.listen(8080);

HTTP Method Handling:

const server = Kimera.createServer((request) => {
  if (request.path === "/data") {
    if (request.method === "GET") {
      return {
        status: 200,
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ items: [1, 2, 3] }),
      };
    }
    
    if (request.method === "POST") {
      return {
        status: 201,
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ 
          message: "Created",
          received: request.body 
        }),
      };
    }
    
    return {
      status: 405,
      body: "Method Not Allowed",
    };
  }
  
  return { status: 404, body: "Not Found" };
});

server.listen(8080);

Note: HTTP server operations require the --net flag:

kimera run server.js --net

Global Functions

close()

Exits the Kimera runtime immediately.

Example:

console.log("Before exit");
close();
console.log("This won't print");

Global Objects

Kimera provides the following global objects:

Language Support

JavaScript

Kimera.js supports modern JavaScript (ES6+) including:

TypeScript

Full TypeScript support with automatic transpilation:

// Type annotations
const greet = (name: string): string => {
  return `Hello, ${name}!`;
};

// Interfaces
interface User {
  name: string;
  age: number;
}

const user: User = {
  name: "Alice",
  age: 30,
};

// Generics
function identity<T>(arg: T): T {
  return arg;
}

Note: TypeScript is transpiled to JavaScript using esbuild, so type checking happens at transpilation time, not runtime.

Error Handling

All file operations and runtime errors can be caught using try-catch:

try {
  const content = Kimera.readFile("missing.txt");
} catch (error) {
  console.log("Error occurred:", error);
}

try {
  Kimera.writeFile("/root/protected.txt", "data");
} catch (error) {
  console.log("Permission denied");
}

Best Practices

  1. Always handle file errors: Use try-catch blocks when reading or writing files

    try {
      const data = Kimera.readFile(filename);
    } catch (error) {
      console.log("File operation failed");
    }
    
  2. Use async/await for cleaner code: Kimera supports modern async patterns

    const main = async () => {
      // Your async code here
    };
    
    main();
    
  3. Leverage TypeScript for type safety: Use .ts files for better development experience

    interface Config {
      port: number;
      host: string;
    }
    

Architecture & Implementation Details

Error Handling

Kimera uses Go's idiomatic error handling patterns:

Example error flow:

Error: failed to run file: failed to read file "script.js": open script.js: no such file or directory
       [cmd layer]          [core layer]           [os layer]

Resource Management

TypeScript Transpilation

Limitations

Current limitations of Kimera.js:

Examples

Reading and Processing a File

// Read a file and count lines
const content = Kimera.readFile("data.txt");
const lines = content.split("\n");
console.log(`File has ${lines.length} lines`);

Run with:

kimera run script.js --fs

Creating a Log File

const logMessage = (message) => {
  const timestamp = new Date().toISOString();
  const logEntry = `[${timestamp}] ${message}\n`;

  try {
    // Append to log (read existing, append, write back)
    let existingLog = "";
    try {
      existingLog = Kimera.readFile("app.log");
    } catch (e) {
      // File doesn't exist yet, that's okay
    }
    Kimera.writeFile("app.log", existingLog + logEntry);
  } catch (error) {
    console.log("Failed to write log");
  }
};

logMessage("Application started");
logMessage("Processing data");

Run with:

kimera run script.js --fs

TypeScript with File Operations

interface FileData {
  content: string;
  lines: number;
}

const analyzeFile = (path: string): FileData => {
  const content: string = Kimera.readFile(path);
  const lines: number = content.split("\n").length;

  return { content, lines };
};

const result = analyzeFile("data.txt");
console.log(`Lines: ${result.lines}`);

Run with:

kimera run script.ts --fs

Building an HTTP API Server

// Create a REST API server
const server = Kimera.createServer((request) => {
  console.log(`${request.method} ${request.path}`);
  
  // CORS headers for API
  const headers = {
    "Content-Type": "application/json",
    "Access-Control-Allow-Origin": "*",
  };
  
  // Route: GET /users
  if (request.path === "/users" && request.method === "GET") {
    return {
      status: 200,
      headers,
      body: JSON.stringify([
        { id: 1, name: "Alice" },
        { id: 2, name: "Bob" },
      ]),
    };
  }
  
  // Route: POST /users
  if (request.path === "/users" && request.method === "POST") {
    const newUser = JSON.parse(request.body);
    return {
      status: 201,
      headers,
      body: JSON.stringify({ 
        id: 3, 
        ...newUser,
        created: true 
      }),
    };
  }
  
  // Route: GET /health
  if (request.path === "/health") {
    return {
      status: 200,
      headers,
      body: JSON.stringify({ status: "healthy", uptime: Date.now() }),
    };
  }
  
  // 404 for unknown routes
  return {
    status: 404,
    headers,
    body: JSON.stringify({ error: "Not Found" }),
  };
});

console.log("API server starting on port 3000...");
server.listen(3000);

Run with:

kimera run api.js --net

Test with:

curl http://localhost:3000/users
curl -X POST -d '{"name":"Charlie"}' http://localhost:3000/users
curl http://localhost:3000/health