Skip to content
Projets

À propos

Exécutez en toute sécurité dans les navigateurs des plugins utilisateur, des règles, des formules et du JavaScript généré par IA.

IA et apprentissage automatique

Comment ces chiffres sont mesurés

Progression mesurée des étoiles

in 24h
0
in 7 days
+1
in 15 days
0
in 1 month
-1

Variations nettes sur des périodes qui se chevauchent, pas des totaux quotidiens. Les mesures absentes restent vides. Les étoiles indiquent l’intérêt, pas la qualité.

README.md

Original

sablejs

Fast, safe, debuggable execution for user-authored and AI-generated JavaScript.

Ubuntu CI npm beta License Release

Quick Start · Recipes · Examples · Security · Documentation

sablejs compiles untrusted JavaScript ahead of time into a plain CommonJS module — built for plugins, pricing and workflow rules, formulas, and AI-generated scripts.

  • Fast — Runs directly on the host JS engine; no embedded VM.
  • Safe — Copied data, locked prototypes, and revocable capabilities.
  • Debuggable — Standard Source Map v3 and inspectable compiler IR.
JS (ES5–ES2025) ─(sablejs: auto ES5.1 transform + AOT)─▶ Plain CJS ─▶ Node · Browser · Worker

Inspired by Figma's WebAssembly plugin sandbox and its QuickJS runtime.

Quick start

Install the v2 beta (latest remains on v1 while v2 is in beta; coming from v1? See the Migration Guide):

npm install sablejs@beta

Try it in one file

Guest programs are scripts in ES5.1–ES2025 syntax (no import/export) that return their final expression value — modern syntax is lowered to ES5.1 automatically:

const { compile, worker } = require("sablejs");

// 1. Compile untrusted source ahead of time (defaults to sandbox mode + O1 optimization)
const { code } = compile("const total = input.price * 1.2; ({ total });");

// 2. Load the compiled artifact and create a single-run instance
const program = worker.loadCompiledArtifact(code);
const instance = program.createInstance({
  globals: { input: { price: 100 } },
});

try {
  console.log(instance.run()); // { total: 120 }
} finally {
  instance.dispose(); // always dispose to release resources and revoke capabilities
}

Precompile for production

In production, keep compilation at build time (or in a server-side cache). Your deployed app only needs the generated artifact and sablejs/runtime:

// build.cjs — build time
const fs = require("node:fs");
const { compile } = require("sablejs");

const { code } = compile("const total = input.price * 1.2; ({ total });");
fs.writeFileSync("program.cjs", code);
// run.cjs — runtime (no compiler needed)
const program = require("./program.cjs");
const instance = program.createInstance({
  globals: { input: { price: 100 } },
});

try {
  console.log(instance.run()); // { total: 120 }
} finally {
  instance.dispose();
}

[!TIP] Three-piece mental model: compile() produces a standalone .cjs artifact → your app caches or bundles that artifact → each execution creates a fresh single-run instance, calls instance.run(), and cleans up with instance.dispose().

Common recipes

1. Pass host functions (capabilities)

In default sandbox mode, globals data is recursively deep-copied so guest mutations never touch host objects. Any host function anywhere in globals becomes a capability automatically — arguments and return values are copied, host error stacks are stripped, and the wrapper is revoked on dispose():

const instance = program.createInstance({
  globals: {
    input: { price: 100 },
    save: async function (record) {
      const res = await fetch("/api/records", {
        method: "POST",
        body: JSON.stringify(record),
      });
      return { saved: res.ok };
    },
  },
});

Need a custom wrapper name or a bound this receiver? Wrap explicitly with capability():

const { capability } = require("sablejs");

const save = capability(api.save, {
  name: "save",
  thisValue: api,
});

Explicit capability() tokens also work unchanged in security: "trusted" (where they unwrap back to the raw host function).

2. Export and call guest functions

End your guest script with a function expression to return a callable function to the host:

// Guest source: "function price(input) { return { total: input.price * 1.2 }; } price;"
const instance = program.createInstance({ globals: {} });

try {
  const price = instance.run(); // synchronous — returns a callable
  console.log(price({ price: 100 })); // { total: 120 }
} finally {
  instance.dispose();
}

Host-initiated calls automatically copy arguments and this in sandbox mode, while calls between guest functions keep standard JavaScript reference semantics.

3. Enforce timeouts with a Worker

The language boundary restricts what code can reach, not how long it runs. To stop infinite loops and bound execution time, run programs in a dedicated Worker using sablejs/worker:

// sandbox.worker.js
const program = require("./program.cjs");
require("sablejs/worker").handleSandboxMessages(program);
// host.js (browser Worker, or Node worker_threads with a small adapter)
const { createSandboxClient } = require("sablejs/worker");

const sandbox = createSandboxClient(new Worker("/sandbox.worker.js"), {
  timeoutMs: 1000,
});

await sandbox.run({ price: 100 }); // { total: 120 }

createSandboxClient terminates the Worker on timeout and exposes sandbox.evaluate(artifactCode, input) for dynamically compiled artifacts. Never pass raw uncompiled user source to evaluate(). See Worker isolation for Node adapters, Worker-side capabilities, and size limits.

4. Modern JavaScript & TypeScript

compile() lowers ES2015–ES2025 syntax (let/const, arrow functions, classes/#private, destructuring, spread, for..of, templates, ?., ??, &&=/||=/??=) to ES5.1 automatically via a built-in zero-dependency pass (transform: "auto", zero overhead for pure ES5.1 inputs).

Need strict ES5.1 enforcement, TypeScript/JSX stripping, async/generator support, or standalone ES5.1 output?

const { compile, transformToES5 } = require("sablejs");

// Strict ES5.1 only (rejects ES2015+ syntax)
compile(es5Source, { transform: false });

// Custom hook for TS/JSX/async (returning `{ code, map }` automatically chains Source Map v3)
compile(tsSource, {
  transform: (code, { sourceFile }) => myTsOrBabelTransform(code, sourceFile),
  sourceMap: true,
});

// Standalone ES5.1 lowering helper
const { code } = transformToES5("const double = (x = 1) => x * 2; double(5);");

All public entry points (sablejs, sablejs/runtime, sablejs/worker) ship TypeScript declarations in types/:

import { compile } from "sablejs";
import type { CompileOptions, CompileResult } from "sablejs";

const options: CompileOptions = {
  optimization: "O1",
  security: "sandbox",
  sourceMap: { mode: "external", sourceFile: "rules/input.js" },
};
const result: CompileResult = compile(source, options);

5. Source maps & IR debugging

Opt into Source Map v3 generation with sourceMap or inspect compiler stages with dumpDir / dumpIR:

const result = compile(source, {
  sourceMap: {
    mode: "external", // or "inline" (embeds base64 data URL)
    sourceFile: "rules/input.js",
    generatedFile: "rules.cjs",
    sourceMapURL: "rules.cjs.map",
    sourcesContent: false,
  },
});
Option Purpose
sourceMap: true | "external" | "inline" | { ... } Statement-level Source Map v3 (static eval/Function bodies map to #eval-N / #dynamic-N). Zero overhead when omitted. See Source maps.
dumpDir: "/path" Writes transformed.es5.js (when lowered), hir.txt, cfg.txt, mir.txt, code.js, and code.js.map (when mapping is enabled). Pass custom fs for non-Node hosts.
includeHIR / includeCFG / includeMIR / dumpIR Attaches IR/CFG graph objects directly onto result.

Sandbox at a glance

Surface Default sandbox behavior
ES5.1 built-ins Protected Object, Array, Math, Date, RegExp, JSON, etc. Readable and callable; prototype mutation blocked.
Modern host built-ins Map, Set, Promise, typed arrays, Symbol, BigInt, Reflect, Proxy, Intl exposed when the host has them (intrinsics remain read-only).
Injected globals Primitives, plain objects, arrays, Date, RegExp, buffers/Uint8Array, Map, Set deep-copied; host functions wrapped as revocable capabilities.
Host & dynamic code window, document, process, fs, ambient class instances, and runtime eval/Function blocked. Static literal eval/Function inputs are compiled ahead of time.

Need raw object identity and zero-copy interop for fully trusted code? Pass security: "trusted". Read the threat model and boundary policies in Security.

Compatibility & status

Surface Contract
Guest language ES5.1–ES2025 scripts (auto-lowered to ES5.1; use esbuild/Babel/SWC for modules, TS/JSX, or async/generators)
Output CommonJS module (bundle with esbuild/Vite/Rollup for browsers)
Optimization O1 default (O0 baseline; O2 and Os remain experimental until CFG/SSA hardening gates complete)
Tested hosts Node 24, Deno 2, Bun, Chromium, Firefox, WebKit
Conformance Release-gated pinned ES5.1 Test262 suite (es5id corpus)

Performance note: Historical reference runs on Linux x64 (2026-08-24) recorded an O2 sandbox score of 2,202 on V8 Benchmark Suite 7 vs 1,181 in QuickJS-WASM 0.32.0 (87.5 KB gzipped browser bundle including runtime). Treat O2 numbers as historical reference baselines rather than the current O1 default; see Performance for methodology, artifact sizes, and reproduction commands.

Documentation

Browse the full Docs Index or jump directly to a guide:

Guide What you will learn
Examples 10 runnable demos across Node, Browser, Worker, Deno, Bun, precompile, caching, and error handling
Migrating from v1 to v2 Upgrading from v1 opcodes/CLI to v2 AOT compilation and capabilities
Choosing an execution model Comparing sablejs vs QuickJS-WASM, cross-origin iframes, and eval
Worker isolation Wall-clock timeouts, Worker-side capabilities, browser Worker bundling, size budgets
Security model Threat model, trust boundaries, feature policies, and audit record
Source maps Node --enable-source-maps, browser DevTools, virtual eval sources, compiler design
Compatibility Built-in ES2015+ → ES5.1 transform, custom hooks, host built-ins, and Test262 policy
Architecture · Performance · Roadmap Compiler layers, IR verification, benchmarks, release workflow, and roadmap

Development

git clone https://github.com/ErosZy/sablejs.git
cd sablejs
npm ci
npm test                      # unit + security adversarial suite
npm run check:format          # Prettier code formatting check
npm run check:types           # TypeScript CJS/ESM checks
npm run check:examples        # verifies all examples match documented output
npm run build && npm run check:compliance

npm run build produces dist/runtime.js and dist/compiler.js. See Architecture for Test262, differential fuzzing, benchmark suites, and the release workflow. Report vulnerabilities via SECURITY.md.

License

Apache-2.0 — third-party dependency notices live in THIRD_PARTY_NOTICES.

Explorer des projets similaires

Chargement…