@gobing-ai/ts-runtime
Runtime abstraction layer — platform detection, file system, process execution, configuration,
context management, path utilities, and a shared plugin/capability core. Works on Node.js, Bun,
and Cloudflare Workers through a factory pattern that auto-detects the runtime.
ts-runtime decouples application code from platform specifics. Instead of importing node:fs or node:child_process directly, consumers use interfaces (FileSystem, ProcessExecutor) resolved by loadRuntimeFactory() at startup. The factory auto-detects the platform and wires the correct implementations — createNodeFileSystem (real node:fs) for Node/Bun, createCfFileSystem (stub) for Workers. Node filesystem modules are loaded lazily, so importing the package remains safe for Worker bundles.
Overview
Key abstractions:
| Concept |
Interface |
Bun/Node impl |
Cloudflare impl |
| Runtime factory |
RuntimeFactory → loadRuntimeFactory() |
nodeBunFactory |
cloudflareWorkersFactory |
| File system |
FileSystem |
createNodeFileSystem() (sync node:fs) |
createCfFileSystem() (stub) |
| Process execution |
ProcessExecutor (interface) |
NodeProcessExecutor — run() via execa, runStreaming() via Bun.spawn |
throws |
| Process registry |
ProcessRegistry (optional) |
InMemoryProcessRegistry / createInMemoryProcessRegistry() — list + subscribe all spawns |
n/a (no process exec) |
| SQL database |
createDbAdapter(config) → DbAdapter |
Bun SQLite via @gobing-ai/ts-db (optional peer) |
throws D1NotConfiguredError (D1 round pending) |
| Configuration |
Config (Zod schema) |
YAML + env vars |
CONFIG_YAML blob + env vars |
| Context |
RuntimeContext |
service locator |
service locator |
| Path utilities |
SEP, basenamePath, dirnamePath, joinPath, resolvePath, relativePath, … |
runtime-portable (zero node:*) |
runtime-portable (zero node:*) |
| Schema validation |
loadStructuredConfig |
JSON-Schema + YAML |
JSON-Schema + YAML |
Extension core (./extension) |
CapabilityRegistry, loadExtensionModules |
trust-gated module loading |
— |
Bun SQLite boundary (./bun-sqlite) |
Database re-export |
bun:sqlite |
unavailable |
| Tracing |
SpanContext |
{ traceId, spanId } |
{ traceId, spanId } |
Architecture
classDiagram
class RuntimeFactory {
<<interface>>
+string runtimeName
+createFileSystem() FileSystem
+createProcessExecutor() ProcessExecutor
+loadConfig() Promise~Config~
+createDbAdapter(config) Promise~DbAdapter~
}
class nodeBunFactory {
+createFileSystem() createNodeFileSystem()
+createProcessExecutor() ProcessExecutor
+loadConfig() Promise~Config~
+createDbAdapter() Promise~DbAdapter~
}
class cloudflareWorkersFactory {
+createFileSystem() createCfFileSystem()
+createProcessExecutor() never
+loadConfig() Promise~Config~
+createDbAdapter() never
}
class FileSystem {
<<interface>>
+exists(path) boolean~|~Promise~boolean~
+readFile(path) string~|~Promise~string~
+writeFile(path, content) void~|~Promise~void~
+ensureDir(path) void~|~Promise~void~
+readDir(path) string[]~|~Promise~string[]~
+deleteFile(path) void~|~Promise~void~
+stat(path) FileStat~|~null~|~Promise~FileStat|~
+resolve(...segments) string
+getProjectRoot() string
+readFileStream(path) AsyncIterable<string>▀optional (ADR-021)
+realPath(path) string▀optional (ADR-022)
}
class createNodeFileSystem {
+readFile(path) string
+writeFile(path, content) void
+exists(path) boolean
+ensureDir(path) void
+stat(path) FileStat | null
+getProjectRoot() string
+readFileStream(path) AsyncIterable<string>
+realPath(path) string
}
class createCfFileSystem {
+readFile(path) never
+writeFile(path, content) never
+exists(path) false
+ensureDir(path) void
+stat(path) null
+getProjectRoot() '/bundle'
}
class ProcessExecutor {
<<interface>>
+run(options) Promise~ProcessResult~
+runStreaming(options) PipeProcess
}
class NodeProcessExecutor {
+run(options) Promise~ProcessResult~
+runStreaming(options) PipeProcess
}
class ProcessRegistry {
<<interface>>
+listExecutions(filter?) ProcessExecution[]
+getExecution(id) ProcessExecution?
+subscribe(listener) unsub
+begin(input) string
+update(id, patch) void
+complete(id, update?) void
+clear() void
}
class InMemoryProcessRegistry {
+listExecutions(filter?) ProcessExecution[]
+begin(input) string
+complete(id, update?) void
}
class PipeProcess {
<<interface>>
+pid number?
+stdout ReadableStream?
+stderr ReadableStream?
+exited Promise~number?~
+writeStdin(input) void
+endStdin() void
+kill(signal?) void
}
class RuntimeContext {
+RuntimeScope scope
+RuntimeName runtimeName
+RuntimeCapabilities capabilities
+register(key, service) void
+get(key) T | undefined
+require(key) T
+has(key) boolean
+dispose() Promise~void~
}
class Config {
+AppConfig app
+DatabaseConfig database
+LoggingConfig logging
}
class SpanContext {
<<interface>>
+string traceId
+string spanId
+Record~string,string~ baggage?
+Record~string,string|number|boolean~ attributes?
}
RuntimeFactory <|.. nodeBunFactory : implements
RuntimeFactory <|.. cloudflareWorkersFactory : implements
FileSystem <|.. createNodeFileSystem : implements
FileSystem <|.. createCfFileSystem : implements
ProcessExecutor --> PipeProcess : creates
ProcessExecutor <|.. NodeProcessExecutor : implements
ProcessRegistry <|.. InMemoryProcessRegistry : implements
NodeProcessExecutor ..> ProcessRegistry : optional registry
nodeBunFactory --> createNodeFileSystem : creates
nodeBunFactory --> NodeProcessExecutor : creates
cloudflareWorkersFactory --> createCfFileSystem : creates
RuntimeContext --> FileSystem : "fileSystem"
RuntimeContext --> Config : "config"
RuntimeContext --> ProcessExecutor : "processExecutor"
How It Works
1. Runtime selection
loadRuntimeFactory() auto-detects the platform and returns a factory that creates the correct
FileSystem, ProcessExecutor, and Config. Use createRuntimeContextFromFactory() to wire
everything automatically:
import { createRuntimeContextFromFactory } from '@gobing-ai/ts-runtime';
const ctx = await createRuntimeContextFromFactory();
// ctx.runtimeName → 'node-bun' (auto-detected)
// ctx.capabilities → { hasFilesystem: true, hasProcessExecution: true }
// ctx.require('fileSystem') → canonical FileSystem (createNodeFileSystem)
// ctx.require('config') → Config from config.yaml
For manual control or synchronous code, createRuntimeContext() is still available
(deprecated — kept for backward compatibility):
import { createRuntimeContext } from '@gobing-ai/ts-runtime';
const ctx = createRuntimeContext({
runtimeName: 'node-bun',
capabilities: { hasFilesystem: true, hasProcessExecution: true, hasPersistentStorage: true },
});
2. Service registration
Services are registered into RuntimeContext and accessed by key:
ctx.register('db', drizzleAdapter);
ctx.register('cache', redisClient);
const db = ctx.require('db'); // throws if missing
const cache = ctx.get('cache'); // undefined if missing
3. Configuration
Config is loaded from YAML with environment variable interpolation and Zod validation:
# config.yaml
app:
name: my-app
env: ${APP_ENV}
port: ${PORT}
database:
url: ${DATABASE_URL}
logging:
level: debug
import { buildConfigFromYaml } from '@gobing-ai/ts-runtime';
const yaml = await fs.readFile('config.yaml');
const config = buildConfigFromYaml(yaml, {
overrides: { app: { port: 8080 } },
});
// config.app.port === 8080 (overridden)
// config.logging.level === 'debug' (from YAML)
4. Structured config + JSON-schema validation
loadStructuredConfig reads a .json/.yaml file and — if it declares a top-level $schema — validates
it against that schema before returning. This powers schema-checked rule and workflow files in
ts-rule-engine and ts-dual-workflow-engine.
import { loadStructuredConfig } from '@gobing-ai/ts-runtime';
const config = await loadStructuredConfig('rules.yaml'); // validates against its $schema, throws on violation
const raw = await loadStructuredConfig('rules.yaml', { validateSchema: false }); // skip validation
A StructuredConfigSchemaError (with a violations array of { path, message }) is thrown on any
schema violation.
$schema reference styles
There are three ways a config file can name its schema. Prefer the bundled package specifier — it is
the most secure and performant default:
| Style |
Example |
Resolution |
Notes |
| Package specifier (recommended) |
$schema: "@gobing-ai/ts-rule-engine/schemas/rule-file.schema.json" |
Resolved through node_modules via the module resolver, then read from disk |
No network, no path guessing; survives hoisting/pnpm/monorepo layouts. Schemas ship in each package's schemas/ (declared in files). Quote the value — YAML treats a leading @ as reserved. |
| Relative path |
$schema: ./schemas/rule-file.schema.json |
Resolved against the config file's directory |
Fine for repo-local schemas; brittle if the config moves. |
| Remote URL |
$schema: https://json-schema.org/.../rule-file.schema.json |
Fetched over HTTP(S) — off by default |
SSRF/DoS surface for third-party configs. Opt in with both { allowRemote: true } and a fetch implementation — there is no built-in fetch; the caller owns timeout/credentials. |
// Bundled package schema (default path — no extra options needed):
// $schema: "@gobing-ai/ts-rule-engine/schemas/rule-file.schema.json"
await loadStructuredConfig('rules.yaml');
// Remote schema is refused unless BOTH flags are present:
await loadStructuredConfig('rules.yaml', { allowRemote: true, fetch: myFetch }); // caller-supplied fetch
// { allowRemote: true } alone -> refused (no built-in fetch)
// { fetch: myFetch } alone -> refused (no explicit opt-in)
Security: remote schema fetching is disabled by default. Resolving a bundled schema from
node_modules keeps validation entirely local — no outbound request, no dependency on a schema host's
availability, and no chance for a malicious config to point validation at an internal URL.
5. Path utilities
Runtime-portable path math that avoids node:path so the same logic works on Cloudflare Workers
(ADR-008). All functions use POSIX-style separators; Windows drive paths are normalized and treated
as absolute.
import {
SEP, basenamePath, dirnamePath, isAbsolutePath,
joinPath, normalizeSeparators, relativePath, resolvePath,
getProcessCwd,
} from '@gobing-ai/ts-runtime';
normalizeSeparators('C:\\Users\\x\\file'); // 'C:/Users/x/file'
SEP; // '/' on POSIX, '\\' on Windows
isAbsolutePath('/abs'); // true
dirnamePath('/a/b/c.ts'); // '/a/b'
basenamePath('/a/b/c.ts'); // 'c.ts'
basenamePath('/a/b/c.ts', '.ts'); // 'c'
joinPath('/a', 'b', 'c'); // '/a/b/c'
resolvePath('/a/b', '../c'); // '/a/c'
relativePath('/a/x', '/a/y'); // '../y'
getProcessCwd(); // process.cwd() or '/' on Workers
6. Extension core (@gobing-ai/ts-runtime/extension)
The ./extension subpath exposes a generic, domain-agnostic extension/capability core used by both
ts-rule-engine and ts-dual-workflow-engine (ADR-010). It shares the mechanism — a typed registry
with origin metadata, a trust-gated extension loader, and a path guard — without knowing anything
about evaluators, resolvers, actions, or guards. Each engine owns its domain-specific kinds,
schemas, error types, and override semantics.
Capability registry