@plinthjs/repl
The Plinth REPL. It is split into a testable engine and a thin interactive wrapper:
Replruns snippets in a persistentnode:vmcontext, returning the value of the last expression and carrying top-level declarations across calls (REPL scope semantics).start()boots anode:replwhose evaluator delegates to a sharedRepl, so the live REPL andRepl.evaluate()follow the same evaluation path.
Bindings (app, registered helpers, variables you set) are exposed to evaluated code as bare identifiers. The package depends only on Node built-ins, @plinthjs/core and @plinthjs/support.
Install
npm install @plinthjs/replUsage
import { Application } from '@plinthjs/core'
import { start } from '@plinthjs/repl'
const app = new Application({ config: { app: { env: 'local' } } })
// Launch an interactive session with `app` in scope.
start({ app, prompt: 'plinth> ' })plinth> app.environment()
'local'
plinth> const total = [1, 2, 3].reduce((a, b) => a + b)
plinth> total * 2
12start() returns the running repl.REPLServer. It throws when called under a test runner (when VITEST is set or NODE_ENV=test), so it never attaches to the process during tests.
The engine
import { Repl } from '@plinthjs/repl'
const repl = new Repl({ context: { greet: (who: string) => `hi ${who}` } })
repl.evaluate('1 + 1') // 2
repl.evaluate('greet("ada")') // 'hi ada'
// Declarations persist across calls.
repl.evaluate('const x = 5')
repl.evaluate('function double(n) { return n * 2 }')
repl.evaluate('double(x)') // 10
// Statement-only snippets return undefined.
repl.evaluate('let y = 1') // undefined
// A returned promise can be awaited by the caller.
await (repl.evaluate('Promise.resolve(7)') as Promise<number>) // 7The vm context is seeded with host standard globals (console, JSON, Promise, fetch, URL, timers, error constructors and so on), so snippets behave as they would in a normal Node REPL.
Bindings
repl
.register('users', usersRepository) // a helper or service
.setVariable('limit', 10) // a plain variable
repl.evaluate('users.take(limit)')
repl.getVariable('limit') // 10
repl.evaluate('const created = 1')
repl.getVariable('created') // 1, top-level declarations land in the scope
repl.context() // the live bindings recordPass an existing engine to start({ repl }) to open a REPL over a scope you have already prepared.
Errors
Errors are never swallowed. A malformed snippet throws a real SyntaxError, and runtime errors are host Error instances, so instanceof checks work on the caller side:
repl.evaluate('null.foo') // throws TypeError
repl.evaluate('missingName') // throws ReferenceError
repl.evaluate('throw "oops"') // throws Error('oops'), with the original value as `cause`