ScriptContext
This file defines the ScriptContext
class, which provides a unified context for script execution in the @sodacore/core
library. It exposes helpers for logging, session management, and interactive prompts, and provides access to the underlying socket, command, and context data.
Features
- Logging: Access to a
LogScriptHelper
for sending log messages. - Session Management: Access to a
SessionScriptHelper
for managing session data. - Prompts: Access to a
PromptScriptHelper
for interactive user prompts. - Socket Access: Retrieve the underlying Bun socket.
- Command & Context Access: Retrieve the current command and its context.
- Message Sending: Send custom commands and context data over the socket.
Usage
typescript
const scriptContext = new ScriptContext(socket, 'myCommand', { foo: 'bar' });
scriptContext.log.info('Script started');
scriptContext.session.set('user', 'alice');
const answer = await scriptContext.prompts.text({ message: 'Enter your name:' });
const socketInstance = scriptContext.getSocket();
const command = scriptContext.getCommand();
const contextValue = scriptContext.getContext('foo');
scriptContext.send('custom:command', { data: 123 });
API
Constructor
typescript
constructor(
private socket: Socket<IScriptSocketData>,
private command: string,
private context?: Record<string, any>,
)
- socket: The Bun socket instance for communication.
- command: The command being executed.
- context: Optional context data for the script.
Properties
- log: Instance of
LogScriptHelper
for logging. - session: Instance of
SessionScriptHelper
for session data management. - prompts: Instance of
PromptScriptHelper
for interactive prompts.
Methods
getSocket(): Socket<IScriptSocketData>
Returns the underlying socket instance.
getCommand(): string
Returns the current command string.
getContext<T = Record<string, any>>(key?: string): T
Returns the context object, or a specific value by key if provided.
send(command: string, context: Record<string, any> = {}): void
Sends a command and context data over the socket as a JSON string.
Notes
- Designed for use in script helpers or CLI tools that require unified access to logging, session, and prompt utilities.
- The
send
method is used internally by helpers and can also be used directly for custom communication.