@ts0/core
v0.3.0-beta.0
Published
Zero-dependency, deterministic, fuel- and memory-metered ts0 (TypeScript-subset) engine.
Maintainers
Readme
@ts0/core
Beta. Until v1 a release can break the previous one, with no migration path.
Zero-dependency, deterministic, fuel- and memory-metered ts0 (TypeScript-subset) compiler and synchronous sandboxed runtime.
Features
- Zero
eval, zeroFunction, zero ambient globals, zero external dependencies. - Inline TypeScript type erasure with identical semantics in Node, Edge workers, and strict-CSP browsers.
- Unified fuel, memory, and stack ledger (
maxSourceLength,maxFuel,maxMemory) with values bounded by construction. - Capability-based host
importswith staticprogram.imports/program.exportsinspection and $O(\Delta)$WeakMapstructural sharing across calls.
Usage
Install with pnpm add @ts0/[email protected].
import { compile, type Arg, type Limits } from "@ts0/core"
const limits: Limits = { maxFuel: 20_000, maxMemory: 16_384 }
const program = compile(
`
export function sumPositive(xs: readonly number[]): number {
let total = 0
for (const x of xs) {
if (x > 0) {
total = total + x
}
}
return total
}
`,
{ limits }
)
const result: Arg = program.call("sumPositive", [[3, -1, 7]])
// => 10
export { result }API
compile(source, options?)->Program- Unknown fields in
optionsoroptions.limitsraiseINVALID_LIMITand suggest a supported spelling. - A string in
options.importsnames an element type usable only as a JSX tag. Withjsx: true, a tag bound to that import constructs a{ type, props, children }descriptor in the VM. String entries requirejsx: true. Function imports remain callable. - Set
options.implicitImportsto a module-to-names map such as{ "@ui": ["Text"] }to make selectedoptions.importsbindings available without an import declaration. Guest bindings take precedence. Referenced bindings appear inProgram.imports. Program.exports: sorted exported function namesProgram.importsis a static dependency list of referenced host functions and element types. It is sorted and deduplicated by{ module, name }, using the imported name for aliases.Program.call(exportName, args?): accepts top-levelArg(Data | undefined) values (nested arrays forbidundefined;undefined-valued record fields are omitted across the boundary) and returns deeply frozenArgProgram.callWithMetrics(exportName, args?)returns the same value in aCallResultwith frozenCallMetricscontainingfuelUsed,maxFuel,peakMemory, andmaxMemory. Memory is measured in engine units, and the peak includes argument and result conversion.currentCallSpan()returns the frozen, 1-basedSourceSpanof the guest call site during a synchronous host import. Outside that import it returnsundefined.program.jsxElementSpan(value)returns the frozen, 1-basedSourceSpanof the opening tag name for an element-type record from that program. Copies, deserialized records, intrinsic tags, fragments and records from other programs returnundefined.Ts0Error: structured compile/runtime/boundary error withcode: Ts0ErrorCode, derivedcategory: Ts0ErrorCategory, and optional 1-based{ line, column }pointspan- Import result conversion errors use the guest call-site span. Exported guest result conversion errors include
phase: "guest-result". Exceptions from inside the host callback propagate unchanged.
Guest arguments and import replies are already-decoded data. Cap untrusted payload bytes at the transport before decoding, and cap record members and array entries before constructing containers when the decoder supports it. Apply these caps to remote replies before reading and decoding the full response. Native reflection materializes all own keys, including symbols and non-enumerable keys, before the engine can reject a wide record. The engine's memory ledger measures its own units.
The argument list and fresh arrays crossing into the guest each cost one fuel unit per 16 entries, rounded up. Eligible frozen engine results reused by reference still bypass traversal.
Array sorting and reversing use the immutable toSorted() and toReversed() methods. Unknown JSX component diagnostics can suggest names from explicit and implicit imports.
String casing follows the host's Unicode tables. Pin the exact host runtime
when toUpperCase() or toLowerCase() informs a decision that must agree
across deployments.
JSX descriptors retain child array structure, booleans and numbers. Between JSX tags, undefined becomes null, including inside nested child arrays.
import { compile } from "@ts0/core"
const program = compile(
'import { Card } from "ui"; export const View = () => <Card title="Hi" />',
{ jsx: true, imports: { ui: { Card: "card" } } }
)
const value = program.call("View")
const span =
value !== null && typeof value === "object"
? program.jsxElementSpan(value)
: undefined
export { value, span }Decoding a named export
Bind the name once and decode each result in trusted host code. The guest's return annotation guides authoring and is erased at compile time.
import type { Arg, Program } from "@ts0/core"
function bindExport<T>(
program: Program,
name: string,
decode: (value: Arg) => T
) {
if (!program.exports.includes(name)) {
throw new Error(`Missing guest export "${name}".`)
}
return (...args: readonly Arg[]): T => decode(program.call(name, args))
}
export { bindExport }Boundary identity explains when an input reference survives a call. Use the guest reference when authoring guest code. The meter reports successful calls in engine units. The memory charge depends on guest execution and boundary values, with a one-unit conversion charge for reusable engine-produced arguments and import replies. Host callback time and host heap are outside the meter.
Async calls
Use compileAsync from @ts0/core/async for exported async guest functions. Call program.call(name, args, { signal }) or program.callWithMetrics(name, args, { signal }) in memory. Both return promises. Guest errors reject with Ts0Error, handler failures reject with the original thrown value, and cancellation rejects with the signal's reason.
In an async guest function, every host call is awaited as a statement or as a whole initializer, assignment or return value. Effect grants are functions. Effects can return plain data or ordinary native promises from the current realm. Inputs and replies cross by value. The in-memory effect context contains the zero-based occurrence index and signal. Each call shares one fuel, memory, stack and effect budget across all awaits. No journal is needed for an in-memory call.
This example uses a native dialog with a method="dialog" form and a confirmation button with value="delete".
import { compileAsync } from "@ts0/core/async"
function confirmThenDelete(
dialog: HTMLDialogElement,
deleteRow: (id: string) => Promise<void>
) {
const program = compileAsync(
`import { confirm, erase } from "host"
export async function remove(id: string) {
const approved = await confirm()
if (!approved) { return false }
await erase(id)
return true
}`,
{
effects: {
host: {
confirm: () =>
new Promise<boolean>((resolve) => {
dialog.returnValue = ""
dialog.addEventListener(
"close",
() => {
resolve(dialog.returnValue === "delete")
},
{ once: true }
)
dialog.showModal()
}),
erase: (_context, id) => {
if (typeof id !== "string") {
throw new Error("Expected a row ID.")
}
return deleteRow(id)
},
},
},
}
)
return (id: string, signal?: AbortSignal) =>
program.call("remove", [id], { signal })
}
export { confirmThenDelete }Durable runs
Import createRun and runDurable from @ts0/core/durable to run a program compiled by compileAsync with a journal. Persist createRun(program, exportName, args, { runId, scope }) before dispatch. Activate with runDurable(program, { journal, runId, scope, append, signal }). The runner reads the export and canonical arguments from the manifest. Supply an async append that fences by run ID and expected position.
Durable effect contexts also carry runId, a stable key, and the opaque pending value. Narrow the context with "runId" in ctx to use these fields. After saving a wait request, return ctx.pending. A later activation replays committed replies, then calls the pending effect with the same key.
The runner requires authoritative, correctly keyed history. Equivalent resume behavior also depends on a compatible host runtime and equivalent live replies or recovered destination outcomes. Pin the runtime and include its identity, build and policy in scope. Route outstanding runs to the deployment that created them. Resuming with a different scope raises JOURNAL_SCOPE before effects are dispatched. The approval example includes Node, V8, ICU and Unicode versions in its scope. Durable approval runtime scope
A committed terminal receipt closes the run. terminal: false covers an effect throw or rejection, an activation abort, and failed or refused journal storage, including an unknown commit outcome. Reload authoritative history before retrying or reconciling. Effects may run again if their reply was never committed. Deduplicate writes at their destination using the effect key. The host owns the journal, current authorization, exclusive ownership, and decisions about when to wake, abandon, or retry.
The runner accepts up to 8 MiB of UTF-8 journal text. It charges the compact encoding against a separate 8 MiB run budget and reserves room for a terminal failure. Use compact JSON in storage. The direct ESM entries share the same execution guard. The approval example shows a file-backed adapter and restart tests.
import type { compile } from "@ts0/core"
async function verifyDurable(compileSync: typeof compile) {
const view = compileSync("export function view() { return 7 }")
const { compileAsync } = await import("@ts0/core/async")
const { createRun, runDurable } = await import("@ts0/core/durable")
const task = compileAsync(
'import { read } from "tools"; export async function run() { return await read() }',
{
effects: {
tools: {
read: () => {
try {
view.call("view")
} catch (error) {
if (error instanceof Error && "code" in error) {
return String(error.code)
}
}
return "unguarded"
},
},
},
}
)
const identity = { runId: "example-run", scope: "example:policy-v1" }
if ((await task.call("run")) !== "REENTRY_FORBIDDEN") {
throw new Error("The in-memory call must use the shared execution guard.")
}
const journal = createRun(task, "run", [], identity)
const records = JSON.parse(journal) as unknown[]
const result = await runDurable(task, {
...identity,
journal,
async append({ expectedPosition, record }) {
if (expectedPosition !== records.length - 1) {
return false
}
records.push(record)
return true
},
})
if (result.status !== "done" || result.value !== "REENTRY_FORBIDDEN") {
throw new Error("The packed entries must share the active execution guard.")
}
}
export { verifyDurable }