Files
core/src/encoders.ts
T
chrnx d6c5cee0ee feat: beta-hardening — routing, degradation, mesh gate, uploads, @header
Restructure first: split the two oversized files by cohesion (http.ts 449
→ http/{router,request,stream,ws,server,types}; app.ts 556 → app/{types,
introspect,index}), rename cryptic locals, JSDoc the public API, and
extract helpers so no function exceeds the complexity gate (createApp
187 → <15, listen 113 → 6). Public import paths are unchanged (barrels).

On that structure, five features that close the biggest gaps vs
Express/Fastify/Nest for a comparable beta:

- routing: `:name*` catch-all, specificity precedence (static ▸ param ▸
  catch-all, not registration order), and 405 + Allow when a path exists
  under a different method (was 404)
- visible degradation: optional providers that fail boot are summarized on
  listen() and queryable via app.degraded(), instead of a silent warn
- mesh is alpha — gated behind `experimental: true`; createApp throws if
  `mesh` is configured without it
- multipart moves to the optional `busboy` peer dependency (clear 501 when
  absent), keeping the core at one runtime dependency
- `@header('name')` as a singular alias of `@headers`

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-07 12:00:15 -05:00

28 lines
1.2 KiB
TypeScript

/**
* Serializes stream items into wire frames for a streaming transport (SSE, NDJSON).
* `headers` is written once before the first frame; `ping` (if present) is sent periodically to keep the connection alive.
*/
export interface StreamEncoder {
headers: Record<string, string>;
encode(item: unknown): string | Buffer;
encodeError(err: unknown): string | Buffer | null;
ping?(): string;
}
const messageOf = (error: unknown): string => (error instanceof Error ? error.message : String(error));
/** Server-Sent Events encoder: one JSON payload per `data:` event, with comment-line pings. */
export const sseEncoder: StreamEncoder = {
headers: { 'content-type': 'text/event-stream', 'cache-control': 'no-cache', connection: 'keep-alive' },
encode: (item) => `data: ${JSON.stringify(item)}\n\n`,
encodeError: (err) => `event: error\ndata: ${JSON.stringify({ error: messageOf(err) })}\n\n`,
ping: () => ': ping\n\n',
};
/** Newline-delimited JSON encoder: one JSON object per line. */
export const ndjsonEncoder: StreamEncoder = {
headers: { 'content-type': 'application/x-ndjson' },
encode: (item) => `${JSON.stringify(item)}\n`,
encodeError: (err) => `${JSON.stringify({ error: messageOf(err) })}\n`,
};