> ## Documentation Index
> Fetch the complete documentation index at: https://docs.mirage.strukto.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# QuickJS

> Run JavaScript scripts and pipe transforms in both Mirage SDKs.

QuickJS runs `node` and `js` in both SDKs. It supports
ES2023 for small scripts and pipe transforms, with access to workspace files
under the same permissions as shell commands. Node.js's most used APIs are
laid over the engine: `fs`, `path`, `process`, `Buffer`, `require`, the
timers and Node's `console`. It has no npm packages and no network access.

Both SDKs run the same engine, the WASI build of
[quickjs-ng](https://github.com/quickjs-ng/quickjs), so a script answers
the same in either.

## Installation

Download `qjs-wasi.wasm` from a
[quickjs-ng release](https://github.com/quickjs-ng/quickjs/releases) and
point the runtime's `home`, or `MIRAGE_QUICKJS_HOME`, at its directory.

> [tab] Python
>
> ```bash theme={null}
> pip install 'mirage-ai[quickjs]'
> ```

> [tab] TypeScript
>
> No package to add: each run executes in a worker. In a browser, `home`
> is the URL of the folder holding `qjs-wasi.wasm`, and the page needs the
> same [worker setup](https://docs.mirage.strukto.ai/typescript/runtime/pyodide.md#worker-and-browser-setup)
> as Pyodide.
>
> QuickJS does not run on Cloudflare Workers: with no worker to stop it,
> a script that never calls the host would hold the isolate, as the
> [Cloudflare quickstart](https://docs.mirage.strukto.ai/typescript/cloudflare-quickstart.md#run-a-workspace)
> describes.

## Usage

Declare an `in_process` machine that runs QuickJS to run `node` on it once its engine is found:

> [tab] Python
>
> ```python theme={null}
> from mirage import RAMVFS, MountMode, Workspace
> from mirage.runtime.js import QuickJsRuntime
>
> ws = Workspace(
>     {"/data": RAMVFS()},
>     mode=MountMode.EXEC,
>     machines={"js": QuickJsRuntime(config={"home": "/path/to/quickjs"})},
> )
> await ws.shell("node -e 'console.log(1 + 1)'")
> ```

> [tab] TypeScript
>
> ```typescript theme={null}
> import { MountMode, RAMVFS, Workspace } from '@struktoai/mirage-node'
>
> const ws = new Workspace(
>   { '/data': new RAMVFS() },
>   {
>     mode: MountMode.EXEC,
>     machines: { js: { provider: 'in_process', runtime: 'quickjs', home: '/path/to/quickjs' } },
>   },
> )
> await ws.shell("node -e 'console.log(1 + 1)'")
> ```

> [tab] YAML
>
> ```yaml theme={null}
> mode: exec
> machines:
>   js:
>     provider: in_process
>     runtime: quickjs
>     home: /path/to/quickjs
> mounts:
>   /data:
>     vfs: ram
> ```

## Memory

A run holds no more than its workspace's
[`max_memory`](https://docs.mirage.strukto.ai/home/limits#memory) has left,
96 MB by default. A program that needs more gets `InternalError: out of
memory`.

## JavaScript compatibility

`std` and `os` are globals, as `qjs --std` gives them. Examples assume a
writable `/data` mount. Mount modes and permissions still apply.

### `std.open()`

`std.open(path, mode, errorObj)` returns `null` on failure and sets
`errorObj.errno`. A read-only mount refuses modes that write. The modes are
`r`, `w`, `a` and `x`, with the `b` and `+` modifiers; for example, `rb`
combines `r` and `b`.

> [accordion] Example: append to a workspace file
>
> ```javascript theme={null}
> const error = {};
> const file = std.open("/data/log.txt", "a", error);
> if (file === null) {
>   throw new Error("Open failed: " + error.errno);
> }
> try {
>   file.puts("Job completed.\n");
> } finally {
>   file.close();
> }
> ```

> [accordion] Limitations
>
> | API or behavior | Limitation |
> | - | - |
> | `x` | Exclusive-creation modifier: use `wx` or `ax`; `x` alone is not a valid mode. |
> | Write modes | A read-only mount refuses modes that write. |

### File objects

`readAsString()`, `read()`, `getline()`, `seek()`, `tell()`, `tello()`,
`eof()`, `puts()`, `write()`, `printf()`, `flush()` and `close()`.

> [accordion] Example: write, seek and read a file
>
> ```javascript theme={null}
> const file = std.open("/data/example.txt", "w+");
> if (file === null) {
>   throw new Error("Could not open example.txt");
> }
> try {
>   file.puts("hello\n");
>   file.seek(0, std.SEEK_SET);
>   print(file.readAsString());
> } finally {
>   file.close();
> }
> ```

> [accordion] Limitations
>
> | API or behavior | Limitation |
> | - | - |
> | `file.puts()`, `file.write()`, `file.flush()` | Reach the mount at `close`, or when the run ends; a write the mount refuses fails the `close`. |

### `std`

`getenv()`, `setenv()`, `getenviron()`, `exit()`, `loadFile()`,
`writeFile()`, `printf()`, `fdopen()`, `strerror()` and `Error`. Environment
variables come from the Mirage session. `std.loadFile()` returns `null` when
reading fails.

> [accordion] Example: read a session environment variable
>
> ```javascript theme={null}
> const jobId = std.getenv("JOB_ID");
> std.printf("Job: %s\n", jobId === undefined ? "unknown" : jobId);
> ```

> [accordion] Limitations
>
> | API or behavior | Limitation |
> | - | - |
> | `std.popen()` | ✗ |
> | `std.tmpfile()` | ✗ |

### Standard streams

`std.in` receives the command's piped input as it arrives, and `std.in`,
`std.out` and `std.err` are descriptors 0 to 2.

> [accordion] Example: forward piped input
>
> ```javascript theme={null}
> const input = std.in.readAsString();
> std.out.puts(input);
> std.err.puts("Input forwarded.\n");
> ```

> [accordion] Limitations
>
> | API or behavior | Limitation |
> | - | - |
> | `std.out.printf()`, `std.err.printf()` | C format; return the UTF-8 bytes written. Unlike `printf` on an opened FILE. |

### `os`

`readdir()`, `stat()`, `mkdir()`, `remove()`, `utimes()`, `rename()`,
`getcwd()`, `chdir()`, `open()`, `read()`, `write()`, `seek()`, `close()`,
`sleep()`, `setTimeout()` and `platform`.

> [accordion] Example: list a workspace directory
>
> ```javascript theme={null}
> const [names, errno] = os.readdir("/data");
> if (errno !== 0) {
>   throw new Error("Read directory failed: " + errno);
> }
> console.log(names);
> ```

> [accordion] Limitations
>
> | API or behavior | Limitation |
> | - | - |
> | `os.lstat()` | ✗ |
> | `os.symlink()` | ✗ |
> | `os.readlink()` | ✗ |
> | `os.realpath()` | ✗ |
> | `os.exec()` | ✗ |
> | `os.readdir()`, `os.stat()` | Return `[value, errno]`. `mode` from `os.stat()` has only the file type bits. |
> | `os.remove()` | `os.remove` also removes an empty directory. |
> | `os.rename()` | `-75` (`EXDEV`) across mounts. |
> | `os.getcwd()`, `os.chdir()` | The shell's working directory; a change lasts for the run. |
> | `os.platform` | `wasi`. |

### `Date`

`Date.now()` and `new Date()` start at the workspace's
[system time](https://docs.mirage.strukto.ai/home/configuration/workspace.md#system-time) when it sets one, and files
the program writes are stamped from the same clock. `performance.now()` and
`os.now()` measure elapsed time.

| API | Support |
| - | - |
| `Date.now()` | ✓ |
| `new Date()` | ✓ |
| `performance.now()`, `os.now()` | ✓ |

> [accordion] Example: print the current time
>
> ```javascript theme={null}
> print(new Date().toISOString());
> ```

> [accordion] Limitations
>
> | API or behavior | Limitation |
> | - | - |
> | Local times | UTC. `TZ` does not change them. |

### `console` and printing

`console.log()`, `console.info()` and `console.debug()` write to stdout, and
`console.error()` and `console.warn()` to stderr. They format values as
Node's `util.inspect()` does and take `util.format()` placeholders such as
`%s`, `%d` and `%j`. `print()` writes the engine's own way.

> [accordion] Example: print a result
>
> ```javascript theme={null}
> console.log("Total:", 2 + 3, { items: [1, 2] });
> console.error("%d skipped", 1);
> print("done");
> ```

> [accordion] Limitations
>
> | API or behavior | Limitation |
> | - | - |
> | `console.table()`, `console.time()`, `console.count()` | ✗ |
> | Arrays of more than six items | One line, where Node groups them in columns |

### Node.js APIs

`require()` returns these modules, with or without the `node:` prefix, and
loads files by path: JavaScript as CommonJS, and JSON parsed. `process`,
`Buffer`, `TextEncoder`, `TextDecoder`, `global`, the timers and a script's
`__filename` and `__dirname` are globals.

> [accordion] Example: filter a JSON file
>
> ```javascript theme={null}
> const fs = require("fs");
> const path = require("path");
>
> const file = path.join("/data", "issues.json");
> const open = JSON.parse(fs.readFileSync(file)).filter((i) => i.open);
> fs.writeFileSync("/data/open.json", JSON.stringify(open));
> console.log(open.length, "open");
> ```

> [accordion] Example: read piped input by line
>
> ```javascript theme={null}
> const rl = require("readline").createInterface({ input: process.stdin });
> rl.on("line", (line) => console.log(line.toUpperCase()));
> ```

> [accordion] Support
>
> | Module or global | Support |
> | - | - |
> | `fs` | `readFileSync`, `writeFileSync`, `appendFileSync`, `copyFileSync`, `existsSync`, `accessSync`, `statSync`, `lstatSync`, `readdirSync` (with `withFileTypes`), `realpathSync`, `mkdirSync` (with `recursive`), `rmSync`, `rmdirSync`, `unlinkSync`, `renameSync`, each also as a callback, and `fs.constants`; errors carry Node's `code`, `syscall`, `path` and Linux `errno` |
> | `fs/promises`, `fs.promises` | The same calls, as promises |
> | `path` | POSIX: `join`, `resolve`, `normalize`, `dirname`, `basename`, `extname`, `relative`, `isAbsolute`, `parse`, `format`, `sep`, `delimiter` |
> | `process` | `argv`, `env`, `cwd()`, `chdir()`, `exit()`, `nextTick()`, `stdout.write()`, `stderr.write()`, and `stdin` as events (`data`, `end`, `readable`), `read()` and `for await`, each chunk as it arrives |
> | `readline` | `createInterface({ input: process.stdin })`, as `line` and `close` events (`on`, `once`, `off`) or `for await` |
> | `buffer`, `Buffer` | `from`, `alloc`, `concat`, `isBuffer`, `byteLength`, `toString` in `utf8`, `base64`, `base64url`, `hex`, `latin1` and `ascii` |
> | `util` | `format`, `inspect`, `promisify` |
> | Timers | `setTimeout`, `setInterval`, `setImmediate` and their `clear` calls |

> [accordion] Limitations
>
> | API or behavior | Limitation |
> | - | - |
> | npm packages | ✗ |
> | Other modules, such as `http`, `child_process` and `os` | ✗ |
> | `import` of `node:` modules in an ES module | ✗; `require()` works in both modes |
> | Streams, such as `fs.createReadStream()` | ✗ |
> | `process.exitCode` at the end of a run | Read by `process.exit()` only |
> | `process.nextTick()` | Runs in turn with promise jobs, not ahead of them |
> | Waiting on stdin | Holds the engine until input arrives, so timers wait while a read does |
> | Modules an ES module imports | Run before Node's globals are set, so they reach them in functions, not at their top level |
> | Symbolic links | `lstatSync` follows them, as `statSync` does, so `unlinkSync` refuses a link to a directory; `rmSync` removes a link, never what it points at |

### Runtime globals

`scriptArgs`, the invocation name and arguments, and `atob()`, `btoa()` and
`queueMicrotask()`.

> [accordion] Example: read arguments and encode text
>
> ```javascript theme={null}
> print(scriptArgs.slice(1));
> const encoded = btoa("hello");
> print(encoded);
> print(atob(encoded));
> ```

### Unavailable host APIs

Unavailable in this runtime.

> [accordion] Limitations
>
> | API or behavior | Limitation |
> | - | - |
> | `fetch()` | ✗ |

## Notes

* `-e <code>` runs the argument, a file runs a mounted script, and with
  neither, piped input is the program. A `.mjs` file runs as an ES module;
  `.js` and `-e` run as classic scripts, and `-m` forces module mode.
* `console.log` and `print` add a newline; `std.out.puts` and `std.err.puts`
  write raw.
* An error in async code fails the run.
* QuickJS cannot reach host files or the network. `command_limits` bound its
  time and output. Run untrusted or heavy code on a
  [machine](https://docs.mirage.strukto.ai/home/setup/machine/overview.md).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.