Response API
The Response API provides typed response handlers for different output scenarios. All response types implement the IResponse interface and are produced or normalized through ResponseFactory.
ResponseFactory
ResponseFactory.getResponse() normalizes a plain callback function or an existing IResponse into a unified IResponse:
import { ResponseFactory } from "./HttpProcessor/ResponseApi/ResponseFactory.js";
const response : IResponse = ResponseFactory.getResponse(($data : any) : void => {
// Handle response data
});
Selection logic:
| Input | Result |
|---|---|
Already a BaseResponse | Returned as-is |
| Plain function | Wrapped in CallbackResponse |
| Anything else | New BaseResponse (no-op) |
Response Types
BaseResponse
Base implementation of IResponse. Provides a fluent promise-like API with five lifecycle hooks:
response.Send($data).Then(($result) => { /* sent */ });
response.OnStart($data).Then(($result) => { /* started */ });
response.OnChange($data).Then(($result) => { /* changed */ });
response.OnComplete($data).Then(($result) => { /* completed */ });
response.OnError($message);
Additional methods:
| Method | Description |
|---|---|
Clone($instance) | Copies owner, callbacks, and thread register from another instance. |
AddAbortHandler($handler) | Registers a handler called on Abort(). Implicitly sets KeepAlive(true). |
Abort() | Invokes all registered abort handlers. |
KeepAlive($value?) | Gets or sets whether the connection should be kept alive. |
Dispatch() | Signals the parent process to clear this response. |
FireEvent($name, $args?) | Fires a live content event via LiveContentResolver. |
CallbackResponse
Wraps a plain callback function as an IResponse. When Send() or OnComplete() is called, the callback is invoked asynchronously (via setTimeout). Used by ResponseFactory when a function is passed instead of a response object.
const response : IResponse = ResponseFactory.getResponse(($data : any) : void => {
console.log($data); // called on Send/OnComplete
});
response.Send("hello");
WebResponse
Full HTTP/WebSocket response with multi-format support (BASE64 and JSON). Implements all lifecycle methods (OnStart, OnChange, OnComplete) by setting KeepAlive state and forwarding to Send.
Used for WebSocket and LCP (Live Content Protocol) connections. Decodes incoming ArrayBuffer and base64-encoded payloads in Clone().
// Lifecycle streaming pattern
response.OnStart("initializing").Then(() => { });
response.OnChange(progress).Then(() => { });
response.OnComplete(result).Then(() => { });
RESTResponse
Extends WebResponse for HTTP REST endpoints. Handles status codes, response headers, JSON/XML/form-urlencoded content negotiation, and ETag-based caching.
// Error response with HTTP status
response.SendError("Not authorized", HttpStatusType.FORBIDDEN);
// Access request headers
const headers : ArrayList<string> = response.getRequestHeaders();
Content type negotiation based on Accept header:
| Accept | Content-Type |
|---|---|
*/xml | application/xml; charset=UTF-8 |
*/x-www-form-urlencoded | application/x-www-form-urlencoded; charset=UTF-8 |
| (default) | application/json; charset=UTF-8 |
Options are configured via setOptions() / getOptions() using IRESTResponseOptions (acceptType, etags, force).
StreamResponse
Extends RESTResponse for chunked/streaming responses over HTTP. Accepts an IResponseProtocol with body, status, headers, and normalize fields.
When normalize is true (default), the body is serialized to a JSON string before sending:
response.Send({
body : { chunk: "data" },
status : HttpStatusType.SUCCESS,
headers: { "x-stream-id": "1" }
});
Use for AI/LLM streaming responses or any large data chunked over HTTP.
LiveContentResponse
Extends WebResponse for Server-Sent Events (SSE) and Live Content Protocol (LCP). Enforces the lifecycle state machine — events must arrive in order: onstart → onchange* → oncomplete.
State machine rules:
onstartcan only be sent once, and not afteronchangeoroncomplete.onchangecan be sent multiple times, but not afteroncomplete.oncompletecan only be sent once.- A raw (non-typed) message can only be sent once.
Violations throw a runtime Error to prevent protocol inconsistencies.
InBodyStatusResponse
Extends RESTResponse. Always returns HTTP 200 OK, embedding the actual operation status inside the response body:
{
"code": 200,
"status": "success",
"data": { ... }
}
On error, the body contains:
{
"code": 500,
"status": "error",
"message": "Error description"
}
Use when clients cannot reliably inspect HTTP status codes (e.g., behind proxies or in legacy integrations).
Formatters
BaseResponseFormatter
Base formatter implementing the IResponseFormatter interface. The default format($data) is an identity function — returns data unchanged.
export interface IResponseFormatter {
format($data : any) : any;
}
ToJSONRouteFormatter
Parses a string body into a JSON object. Automatically assigned to PUT and POST endpoints decorated with @Route.
// Input: '{"key":"value"}'
// Output: { key: "value" }
If JSON parsing fails, logs a warning and returns null. Use when route handlers return JSON strings that need to be deserialized before the response is forwarded.
Inheritance Hierarchy
BaseResponse (IResponse)
├── CallbackResponse
└── WebResponse
├── RESTResponse
│ ├── StreamResponse
│ └── InBodyStatusResponse
└── LiveContentResponse
See also: HTTP Processing Pipeline | Localhost Overview | LCP and RPC