4 Commits
Author SHA1 Message Date
chrnx 46cfa744a1 Merge pull request 'fix: close the RC.1 API audit gaps (type exports, TLS on Deno/Bun, README)' (#181) from fix/rc1-api-gaps into develop
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 20s
CI / build (push) Successful in 29s
CI / runtimes (edge) (push) Successful in 22s
CI / runtimes (deno) (push) Successful in 32s
Promote → GitHub / push-github (push) Successful in 31s
2026-10-30 14:26:17 +00:00
chrnx ff7001f4be docs: record the RC.1 freeze, the TLS refusal and the new type exports
CI / dco (pull_request) Successful in 6s
CI / runtimes (bun) (pull_request) Successful in 20s
CI / build (pull_request) Successful in 29s
CI / runtimes (edge) (pull_request) Successful in 22s
CI / runtimes (deno) (pull_request) Successful in 32s
The README no longer describes the API as still moving, or the radix
matcher as future work. It also states that native TLS is Node-only.
The CHANGELOG gains a Breaking entry, with migration notes, for the
Deno and Bun TLS refusal, and an Added entry listing the newly
exported types.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-30 08:53:54 -05:00
chrnx 870cdb25e9 fix(adapters): reject createApp({ tls }) on Deno and Bun
Only Node's listen() reads tls. serveDeno and serveBun serve through
the runtime's own listener, so an app created with tls came up as
plain HTTP without warning, for a caller who had asked for HTTPS.

createApp now marks the app with a symbol, following the MARK_EDGE
pattern. Both adapters throw on that mark before they boot or bind.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-30 08:53:52 -05:00
chrnx 0261da6fd6 feat(types): export every type a public signature uses
Public declarations named types the entry points did not export, so a
caller could invoke the API but could not name its parameters or
results. The affected types were ModuleOptions, Ctor, BusLike,
ArgSource, GraphNodeView, GraphRouteView, StandardIssue,
StandardResult, the experimental mesh types, and the adapter option
types: DenoServeOptions, BunServeOptions and EdgeCtx.

Export them all. The changes are additive only, and no beta.2 name
moves. Bun's private BunServeShortOptions becomes the exported
BunServeOptions, and the ambient Bun.serve shape is renamed so the two
cannot collide.

channel() had started returning TappableChannel, which leaked the
internal tap symbol into its public return type. Restore the beta.2
return type, Channel<T>. ws-core still finds the tap through the
symbol, not through the signature.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-30 08:53:49 -05:00
12 changed files with 109 additions and 22 deletions

No files matched your search

+15
View File
@@ -135,8 +135,23 @@ npm treats versions as semver and semver forbids leading zeros.
`return` sees `204` instead; return a value to keep a `200`. A route with its own `@Transformer` `return` sees `204` instead; return a value to keep a `200`. A route with its own `@Transformer`
is not affected. is not affected.
- **`serveDeno()` and `serveBun()` reject an app created with `tls`.** Only Node's `listen()` ever
read `tls`; Deno and Bun serve through their runtime's own listener, so the same app came up as
plain HTTP there, without a word, for someone who had asked for HTTPS. Both adapters now reject
before they boot or bind. Migrate by dropping `tls` from `createApp` and configuring TLS on the
runtime's server, or terminating it at a proxy. An app without `tls` is unaffected.
### Added ### Added
- **Every type a public signature uses can now be imported.** These were already in the
declarations, but nothing exported them, so code could call the API and could not name what it
passed or got back. From the root: `ModuleOptions`, `Ctor`, `BusLike`, `ArgSource`,
`GraphNodeView`, `GraphRouteView`, `StandardIssue`, `StandardResult`, and, for the experimental
mesh, `Link`, `ReconnectOptions`, `ManifestPolicy`, `SocketCtor`, `EventfulSocket`, `RouteEntry`,
`RemoteScopeNode`, `RemoteRoute`, `MeshControlDeps` and `ResponseShape`. From `/deno`:
`DenoServeOptions` and `DenoHttpServer`. From `/bun`: `BunServeOptions` and `BunServer`. From
`/edge`: `EdgeCtx`. All of them are additions, and nothing was renamed.
- **Health probes: `createApp({ health: true })`** (#115). Off by default. `GET`/`HEAD /__live__` - **Health probes: `createApp({ health: true })`** (#115). Off by default. `GET`/`HEAD /__live__`
answers `200 {"status":"ok"}` whenever the process answers. `/__ready__` answers answers `200 {"status":"ok"}` whenever the process answers. `/__ready__` answers
`503 {"status":"booting"}` until `boot()` resolves, then `200 {"status":"ok"}` or `503 {"status":"booting"}` until `boot()` resolves, then `200 {"status":"ok"}` or
+4 -3
View File
@@ -307,13 +307,13 @@ green-tea is **beta**, on the road to a release candidate. Express and Fastify h
**What is not here:** no metrics registry, and **no OpenTelemetry exporter in core** — that is a separate package, because core has one runtime dependency and intends to keep it. A `traceparent` header is carried through untouched for an exporter to interpret; core implements no propagation spec. If your definition of production-ready includes shipping traces on day one, you are writing the exporter, and the stream it needs is the part that now exists. **What is not here:** no metrics registry, and **no OpenTelemetry exporter in core** — that is a separate package, because core has one runtime dependency and intends to keep it. A `traceparent` header is carried through untouched for an exporter to interpret; core implements no propagation spec. If your definition of production-ready includes shipping traces on day one, you are writing the exporter, and the stream it needs is the part that now exists.
**Runtimes differ in what they can offer.** Node ≥ 22, Deno, and Bun run everything. On the edge (Cloudflare Workers) there is no `app.listen()`, no filesystem — so `@Html` file/template modes and `static` serving are unavailable — and mesh does not run there at all (the teapot's secret comparison needs `node:crypto`'s `timingSafeEqual`, which `nodejs_compat` doesn't provide). Workers also require the `nodejs_compat` flag. With `compression`, core never encodes on the edge (Cloudflare does), and on Deno it runs zlib on the main thread, where Deno's own `automaticCompression` is the faster gzip. **Runtimes differ in what they can offer.** Node ≥ 22, Deno, and Bun run everything. On the edge (Cloudflare Workers) there is no `app.listen()`, no filesystem — so `@Html` file/template modes and `static` serving are unavailable — and mesh does not run there at all (the teapot's secret comparison needs `node:crypto`'s `timingSafeEqual`, which `nodejs_compat` doesn't provide). Workers also require the `nodejs_compat` flag. Native TLS (`createApp({ tls })`) is Node's `listen()` only: `serveDeno()` and `serveBun()` reject an app that sets it rather than serve it as plain HTTP, so configure TLS on that runtime's server or at a proxy, as you would on the edge. With `compression`, core never encodes on the edge (Cloudflare does), and on Deno it runs zlib on the main thread, where Deno's own `automaticCompression` is the faster gzip.
**mesh is alpha.** Distributed DI works, but discovery, load-balancing, and failover are not built, and its API and wire protocol may change between releases. It is gated behind an explicit opt-in — `createApp({ mesh, experimental: true })` — and `createApp` throws if you configure `mesh` without it. Don't ship mesh to production yet. **mesh is alpha.** Distributed DI works, but discovery, load-balancing, and failover are not built, and its API and wire protocol may change between releases. It is gated behind an explicit opt-in — `createApp({ mesh, experimental: true })` — and `createApp` throws if you configure `mesh` without it. Don't ship mesh to production yet.
**What a teapot exports: steps and routes, and nothing else.** A `@Provider` marked `export: true` fails the boot with an error that says why — a provider's value *is* the object it builds, a pool or a client or a `db`, and the mesh moves data, not objects. Export a `@Step` instead: it runs on the teapot, per request, and its result is what comes back. That is also what lets a teacup boot without its teapot: a remote step holds nothing between requests, so a teacup whose teapot never answers still starts once the `bootTimeoutMs` grace runs out — it warns and carries on. Be precise about what that means, because it is narrower than it sounds. A teapot that never connected sent no manifest, so nothing of it reached the graph: its routes **404** rather than `503`, since nothing was registered to match, and a local step that `@needs` one of its tokens **still fails the boot**, naming the teapot that did not connect. That failure is deliberate — it is the check that catches a typo in a token name, which no amount of waiting will fix. `503` is what you get from a teapot that connected and *later* died, where the link and its exports do exist. So what the change buys is the teacup that does *not* depend on that teapot starting anyway, rather than refusing over a dependency it never had. Keeping a *needed* token serving while its teapot is legitimately away is a known gap, not an oversight: the intended answer is a per-teapot `expects` list that declares what a teapot would export, which is planned and not built. **What a teapot exports: steps and routes, and nothing else.** A `@Provider` marked `export: true` fails the boot with an error that says why — a provider's value *is* the object it builds, a pool or a client or a `db`, and the mesh moves data, not objects. Export a `@Step` instead: it runs on the teapot, per request, and its result is what comes back. That is also what lets a teacup boot without its teapot: a remote step holds nothing between requests, so a teacup whose teapot never answers still starts once the `bootTimeoutMs` grace runs out — it warns and carries on. Be precise about what that means, because it is narrower than it sounds. A teapot that never connected sent no manifest, so nothing of it reached the graph: its routes **404** rather than `503`, since nothing was registered to match, and a local step that `@needs` one of its tokens **still fails the boot**, naming the teapot that did not connect. That failure is deliberate — it is the check that catches a typo in a token name, which no amount of waiting will fix. `503` is what you get from a teapot that connected and *later* died, where the link and its exports do exist. So what the change buys is the teacup that does *not* depend on that teapot starting anyway, rather than refusing over a dependency it never had. Keeping a *needed* token serving while its teapot is legitimately away is a known gap, not an oversight: the intended answer is a per-teapot `expects` list that declares what a teapot would export, which is planned and not built.
**What is settled, and what is still moving.** Present state, not a roadmap and not the API freeze — this is spare-time work by one person, and a schedule it cannot keep would cost more than it earns. The **graph is the settled part**: `needs`/`provides`, the order derived from them, and the boot-time failure when nothing provides a key have not changed since the beta hardening on 7 July, and `@Provider`, `@Step`, `@Route` and handler shapes still mean what they meant then — the decorator *set* has grown (`@Head`, `@Options`, `@Html`), which only ever adds. **Still moving:** the plugin API, which became `{ name, mount }` and gained `onShutdown`; the runtime entry points, where `serveDeno()` and `serveBun()` became async so they boot before they bind; `createApp`'s options, which gain fields most months; and the pipeline context, which in July became one object mutated in place rather than copied per step — so a step that captured it now sees later steps' writes. **Alpha:** mesh, above. Legacy decorators are a standing *external* risk rather than a green-tea one — see [Why legacy decorators](#why-legacy-decorators). The [matcha](https://github.com/Expressive-Tea/matcha) CLI ships from its own repository on its own version line, so nothing here speaks for it. **What is settled, and what is frozen.** From RC.1 the public surface of the four entry points (`@green-tea/core`, `/deno`, `/bun`, `/edge`) is frozen. Until the stable release it only gains things, and nothing published in `26.9.0-beta.2` is removed. That covers the graph (`needs`/`provides`, the order derived from them, and the boot-time failure when nothing provides a key), the decorators and handler shapes, the plugin API (`{ name, mount }` with `onShutdown`), the runtime entry points (`serveDeno()` and `serveBun()` are async so they boot before they bind), `createApp`'s options, and the pipeline context, which is one object mutated in place, so a step sees what earlier steps wrote. **Outside the freeze:** mesh, marked `@experimental` and described above. Legacy decorators are a standing *external* risk rather than a green-tea one — see [Why legacy decorators](#why-legacy-decorators). The [matcha](https://github.com/Expressive-Tea/matcha) CLI ships from its own repository on its own version line, so nothing here speaks for it.
## Docs & development ## Docs & development
@@ -356,7 +356,8 @@ consumer would have received.
- ✅ **HTML** — `@Html` (string / file / template), a built-in template engine with a bring-your-own `viewEngine` hook, and `static` serving. - ✅ **HTML** — `@Html` (string / file / template), a built-in template engine with a bring-your-own `viewEngine` hook, and `static` serving.
- ✅ **router completeness for beta** — safe constrained params, deterministic precedence, explicit/automatic HEAD and OPTIONS, strict path validation, and ambiguity checks across local and mesh routes. - ✅ **router completeness for beta** — safe constrained params, deterministic precedence, explicit/automatic HEAD and OPTIONS, strict path validation, and ambiguity checks across local and mesh routes.
- ✅ **observability** — a correlated lifecycle event stream (request id, trace id, route pattern, per-step timings) and an injectable `Logger`. Exporters live outside core. - ✅ **observability** — a correlated lifecycle event stream (request id, trace id, route pattern, per-step timings) and an injectable `Logger`. Exporters live outside core.
- **next** — API freeze + first stable release, mesh sub-specs (discovery, load-balancing, failover), official plugins, and a radix-tree matcher for very large route tables. - ✅ **radix-tree matcher** — route lookup by index rather than a walk past every candidate, so a 200-route table costs about what a 10-route one does.
- **next** — first stable release, mesh sub-specs (discovery, load-balancing, failover), and official plugins.
## Versioning ## Versioning
+4 -1
View File
@@ -45,7 +45,7 @@ import { getArgs, getHandlerNeeds, resolveArgs } from '../params';
import { buildOpenApi, type OpenApiInfo } from '../openapi'; import { buildOpenApi, type OpenApiInfo } from '../openapi';
import { connectLink, isPermanentRefusal, type Link } from '../mesh/link'; import { connectLink, isPermanentRefusal, type Link } from '../mesh/link';
import { Rooms } from '../rooms'; import { Rooms } from '../rooms';
import type { TlsOptions, SecurityOptions, CorsOptions } from '../security'; import { TLS_REQUESTED, type TlsOptions, type SecurityOptions, type CorsOptions } from '../security';
import { buildRemote, type RemoteRoute as TeacupRemoteRoute } from '../mesh/teacup'; import { buildRemote, type RemoteRoute as TeacupRemoteRoute } from '../mesh/teacup';
import { import {
buildManifest, buildManifest,
@@ -533,6 +533,9 @@ export function createApp(opts: AppOptions): App {
// `edgeHandler` calls this: on the edge core never encodes, whatever detection concluded. // `edgeHandler` calls this: on the edge core never encodes, whatever detection concluded.
[MARK_EDGE]: edgeMarker(compression), [MARK_EDGE]: edgeMarker(compression),
// `serveDeno` and `serveBun` refuse an app that asked for TLS only Node's listener can give.
[TLS_REQUESTED]: Boolean(opts.tls),
}); });
} }
+12 -5
View File
@@ -1,6 +1,7 @@
import { channel } from './channel'; import { channel } from './channel';
import type { Channel } from './channel'; import type { Channel } from './channel';
import type { App } from './app/types'; import type { App } from './app/types';
import { refuseTls } from './security';
import { import {
WS_MAX_MESSAGE_BYTES, WS_MAX_MESSAGE_BYTES,
DEFAULT_MAX_WS_MESSAGE_BYTES, DEFAULT_MAX_WS_MESSAGE_BYTES,
@@ -32,7 +33,8 @@ interface BunWebSocketHandler {
drain?(ws: BunServerWebSocket): void; drain?(ws: BunServerWebSocket): void;
error?(ws: BunServerWebSocket, error?: unknown): void; error?(ws: BunServerWebSocket, error?: unknown): void;
} }
interface BunServer { /** The part of the server `Bun.serve` returns that {@link BunServeResult} builds on. */
export interface BunServer {
port: number; port: number;
// Returns a promise, verified on Bun 1.3 — the previous `void` here was simply wrong, and it // Returns a promise, verified on Bun 1.3 — the previous `void` here was simply wrong, and it
// hid the fact that this is awaitable at all. // hid the fact that this is awaitable at all.
@@ -53,14 +55,18 @@ export interface BunServeResult extends BunServer {
*/ */
close(options?: { timeoutMs?: number }): Promise<void>; close(options?: { timeoutMs?: number }): Promise<void>;
} }
interface BunServeOptions { interface BunNativeServeOptions {
port?: number; port?: number;
hostname?: string; hostname?: string;
fetch(request: Request, server: BunServer): Response | Promise<Response> | undefined; fetch(request: Request, server: BunServer): Response | Promise<Response> | undefined;
websocket?: BunWebSocketHandler; websocket?: BunWebSocketHandler;
} }
type BunServeShortOptions = { port?: number; hostname?: string }; /** Options for {@link serveBun}; passed through to `Bun.serve`. */
declare const Bun: { serve(options: BunServeOptions): BunServer }; export interface BunServeOptions {
port?: number;
hostname?: string;
}
declare const Bun: { serve(options: BunNativeServeOptions): BunServer };
/** Per-connection state stashed on ws.data between fetch (upgrade) and the open/message/close callbacks. */ /** Per-connection state stashed on ws.data between fetch (upgrade) and the open/message/close callbacks. */
interface BunConnData { interface BunConnData {
@@ -104,7 +110,7 @@ function bunSocket(ws: BunServerWebSocket): WsSocket {
* *
* **Boots before it binds**, which is why it is async — see the `await app.boot()` below. * **Boots before it binds**, which is why it is async — see the `await app.boot()` below.
*/ */
export async function serveBun(app: App, options?: BunServeShortOptions): Promise<BunServeResult> { export async function serveBun(app: App, options?: BunServeOptions): Promise<BunServeResult> {
// The same gate `listen()` runs before it binds a socket, and for the same reason: resolve the // The same gate `listen()` runs before it binds a socket, and for the same reason: resolve the
// graph and run the provider factories here, so a missing key or an unreachable pool is a startup // graph and run the provider factories here, so a missing key or an unreachable pool is a startup
// failure rather than a 500 on every request. // failure rather than a 500 on every request.
@@ -113,6 +119,7 @@ export async function serveBun(app: App, options?: BunServeShortOptions): Promis
// the first request would fix the failure in place and the runtime would answer from it forever, // the first request would fix the failure in place and the runtime would answer from it forever,
// without ever reaching `onError`. This was documented as something the caller should remember to // without ever reaching `onError`. This was documented as something the caller should remember to
// do, which made the correct use of a core helper depend on reading a README. // do, which made the correct use of a core helper depend on reading a README.
refuseTls(app, 'serveBun');
await app.boot(); await app.boot();
const server = Bun.serve({ const server = Bun.serve({
+5 -2
View File
@@ -118,13 +118,15 @@ function newSub<T>(onReturn: () => void): Sub<T> {
* Creates a fan-out {@link Channel}. Values pushed are delivered to every active subscriber. * Creates a fan-out {@link Channel}. Values pushed are delivered to every active subscriber.
* @param opts.buffer Per-subscriber queue cap; drops oldest when exceeded (default: unbounded). * @param opts.buffer Per-subscriber queue cap; drops oldest when exceeded (default: unbounded).
*/ */
export function channel<T>(opts: { buffer?: number } = {}): TappableChannel<T> { export function channel<T>(opts: { buffer?: number } = {}): Channel<T> {
const cap = opts.buffer ?? Infinity; const cap = opts.buffer ?? Infinity;
const subs = new Set<Omit<Sub<T>, 'iterator'>>(); const subs = new Set<Omit<Sub<T>, 'iterator'>>();
let done = false; let done = false;
let closedFlag = false; let closedFlag = false;
return { // Public type stays `Channel<T>` (as in beta.2): the tap is internal plumbing, found by `ws-core`
// through the symbol rather than through this signature.
const ch: TappableChannel<T> = {
get closed() { get closed() {
return closedFlag; return closedFlag;
}, },
@@ -161,4 +163,5 @@ export function channel<T>(opts: { buffer?: number } = {}): TappableChannel<T> {
return () => subs.delete(sink); return () => subs.delete(sink);
}, },
}; };
return ch;
} }
+6 -2
View File
@@ -1,4 +1,5 @@
import type { App } from './app/types'; import type { App } from './app/types';
import { refuseTls } from './security';
import { beginDrain } from './http/health'; import { beginDrain } from './http/health';
import { eventSocket, toWsRequest, upgradeSafely, type EventfulSocket } from './http/ws-adapter'; import { eventSocket, toWsRequest, upgradeSafely, type EventfulSocket } from './http/ws-adapter';
import { closeWithDeadline } from './http/shutdown'; import { closeWithDeadline } from './http/shutdown';
@@ -12,7 +13,8 @@ interface WebSocket extends EventfulSocket {
// Minimal ambient for the Deno globals we use — avoids a @types/deno devDep. // Minimal ambient for the Deno globals we use — avoids a @types/deno devDep.
// Mirrors the real Deno.serve / Deno.upgradeWebSocket signatures we call. // Mirrors the real Deno.serve / Deno.upgradeWebSocket signatures we call.
interface DenoServeOptions { /** Options for {@link serveDeno}; passed through to `Deno.serve`. */
export interface DenoServeOptions {
port?: number; port?: number;
hostname?: string; hostname?: string;
signal?: AbortSignal; signal?: AbortSignal;
@@ -21,7 +23,8 @@ interface DenoServeOptions {
interface DenoServeHandlerInfo { interface DenoServeHandlerInfo {
remoteAddr: { hostname: string; port: number; transport: string }; remoteAddr: { hostname: string; port: number; transport: string };
} }
interface DenoHttpServer { /** The part of the server `Deno.serve` returns that {@link DenoServer} builds on. */
export interface DenoHttpServer {
finished: Promise<void>; finished: Promise<void>;
shutdown(): Promise<void>; shutdown(): Promise<void>;
} }
@@ -65,6 +68,7 @@ export async function serveDeno(app: App, options?: DenoServeOptions): Promise<D
// the first request would fix the failure in place and the runtime would answer from it forever, // the first request would fix the failure in place and the runtime would answer from it forever,
// without ever reaching `onError`. This was documented as something the caller should remember to // without ever reaching `onError`. This was documented as something the caller should remember to
// do, which made the correct use of a core helper depend on reading a README. // do, which made the correct use of a core helper depend on reading a README.
refuseTls(app, 'serveDeno');
await app.boot(); await app.boot();
// Deno's only force-close lever is the abort signal it was served with, so the adapter has to // Deno's only force-close lever is the abort signal it was served with, so the adapter has to
+2 -1
View File
@@ -8,7 +8,8 @@ import { MARK_EDGE } from './http/compression';
interface EdgeWebSocket extends EventfulSocket { interface EdgeWebSocket extends EventfulSocket {
accept(): void; accept(): void;
} }
interface EdgeCtx { /** The Workers execution context {@link edgeHandler} receives as its third argument. */
export interface EdgeCtx {
waitUntil(promise: Promise<unknown>): void; waitUntil(promise: Promise<unknown>): void;
} }
declare const WebSocketPair: { new (): { 0: EdgeWebSocket; 1: EdgeWebSocket } }; declare const WebSocketPair: { new (): { 0: EdgeWebSocket; 1: EdgeWebSocket } };
+11 -6
View File
@@ -22,7 +22,7 @@ export type { App, AppOptions, InspectLine, Explain, ExplainNode, MeshConfig } f
// Graph visualization // Graph visualization
export { toMermaid, toDOT } from './graph-viz'; export { toMermaid, toDOT } from './graph-viz';
export type { GraphView } from './graph-viz'; export type { GraphView, GraphNodeView, GraphRouteView } from './graph-viz';
export { buildOpenApi } from './openapi'; export { buildOpenApi } from './openapi';
export type { OpenApiDoc, OpenApiInfo, OpenApiRoute } from './openapi'; export type { OpenApiDoc, OpenApiInfo, OpenApiRoute } from './openapi';
@@ -48,7 +48,7 @@ export {
Options, Options,
Html, Html,
} from './metadata'; } from './metadata';
export type { Transport, HttpMethod, RouteDecorator, TransformerFn } from './metadata'; export type { Transport, HttpMethod, RouteDecorator, TransformerFn, ModuleOptions, Ctor } from './metadata';
export type { Plugin, PluginApi, ScopeApi, ScopeNode } from './plugin'; export type { Plugin, PluginApi, ScopeApi, ScopeNode } from './plugin';
export type { Hooks } from './app'; export type { Hooks } from './app';
export type { TeardownFn } from './lifecycle'; export type { TeardownFn } from './lifecycle';
@@ -79,7 +79,7 @@ export type { StepFn, CompiledFlow } from './flow';
// Parameter decorators // Parameter decorators
export { needs, ctx, param, query, body, headers, header, cookies, cookie, inbound, abort } from './params'; export { needs, ctx, param, query, body, headers, header, cookies, cookie, inbound, abort } from './params';
export type { Query, RequestHeaders, Headers, Context, ArgSpec, ArgDecorator } from './params'; export type { Query, RequestHeaders, Headers, Context, ArgSpec, ArgSource, ArgDecorator } from './params';
// Cookies // Cookies
export { setCookie, parseCookies } from './cookies'; export { setCookie, parseCookies } from './cookies';
@@ -87,7 +87,7 @@ export type { CookieOptions } from './cookies';
// Observability // Observability
export { createDefaultLogger, logRequests, withConsoleFallback } from './logger'; export { createDefaultLogger, logRequests, withConsoleFallback } from './logger';
export type { Logger, LogLevel, LogFields } from './logger'; export type { Logger, LogLevel, LogFields, BusLike } from './logger';
// Streaming // Streaming
export { channel, isAsyncIterable } from './channel'; export { channel, isAsyncIterable } from './channel';
@@ -103,10 +103,15 @@ export type { CompressionOptions } from './http/compression';
export { UNMATCHED_ROUTE } from './http/core'; export { UNMATCHED_ROUTE } from './http/core';
export type { TlsOptions, CorsOptions, SecurityOptions } from './security'; export type { TlsOptions, CorsOptions, SecurityOptions } from './security';
export type { UploadedFile, MultipartBody } from './multipart'; export type { UploadedFile, MultipartBody } from './multipart';
export type { StandardSchemaV1 } from './standard-schema'; export type { StandardSchemaV1, StandardIssue, StandardResult } from './standard-schema';
// Mesh — experimental (`createApp({ experimental: true })`): outside the API freeze, may change in a minor. // Mesh — experimental (`createApp({ experimental: true })`): outside the API freeze, may change in a minor.
export { connectLink } from './mesh/link'; export { connectLink } from './mesh/link';
export { buildRemote, envelopeFrom } from './mesh/teacup'; export { buildRemote, envelopeFrom } from './mesh/teacup';
export { buildManifest, createMeshControl, MESH_CONTROL_PATH } from './mesh/teapot'; export { buildManifest, createMeshControl, MESH_CONTROL_PATH } from './mesh/teapot';
export type { Manifest, RequestEnvelope, Frame } from './mesh/protocol'; export type { Manifest, RequestEnvelope, Frame, RouteEntry } from './mesh/protocol';
export type { Link, ManifestPolicy, ReconnectOptions } from './mesh/link';
export type { SocketCtor, EventfulSocket } from './http/ws-adapter';
export type { RemoteScopeNode, RemoteRoute } from './mesh/teacup';
export type { MeshControlDeps } from './mesh/teapot';
export type { ResponseShape } from './pipeline';
+2 -1
View File
@@ -129,7 +129,8 @@ export function logRequests(bus: BusLike, logger: Logger): () => void {
} }
/** The slice of {@link Bus} request logging needs — `on` only, matching what a plugin is handed. */ /** The slice of {@link Bus} request logging needs — `on` only, matching what a plugin is handed. */
interface BusLike { /** The part of a {@link Bus} that {@link logRequests} subscribes to. */
export interface BusLike {
on(event: 'request:end' | 'request:failed', listener: (payload: EventPayload) => void): () => void; on(event: 'request:end' | 'request:failed', listener: (payload: EventPayload) => void): () => void;
} }
+1 -1
View File
@@ -16,7 +16,7 @@ export type Headers = RequestHeaders;
/** Per-request bag that accumulates values produced by steps and providers. */ /** Per-request bag that accumulates values produced by steps and providers. */
export type Context = Record<string, unknown>; export type Context = Record<string, unknown>;
type ArgSource = 'ctx' | 'needs' | 'params' | 'query' | 'body' | 'headers' | 'cookies' | 'inbound' | 'abort'; export type ArgSource = 'ctx' | 'needs' | 'params' | 'query' | 'body' | 'headers' | 'cookies' | 'inbound' | 'abort';
/** Describes how a single handler parameter is sourced and (optionally) validated. */ /** Describes how a single handler parameter is sourced and (optionally) validated. */
export interface ArgSpec { export interface ArgSpec {
index: number; index: number;
+17
View File
@@ -10,6 +10,23 @@ export interface TlsOptions {
passphrase?: string; passphrase?: string;
} }
/**
* Set on an app created with `tls`, so the adapters that serve through their runtime's own listener
* (`serveDeno`, `serveBun`) can refuse it. Only Node's `listen()` reads `tls`; anywhere else it would
* serve plain HTTP to someone who asked for HTTPS. Symbol-keyed because it is adapter plumbing.
*/
export const TLS_REQUESTED: unique symbol = Symbol.for('green-tea.tls-requested');
/** Throws when `app` was created with `tls`, which `adapter` cannot honour. */
export function refuseTls(app: object, adapter: string): void {
if ((app as { [TLS_REQUESTED]?: boolean })[TLS_REQUESTED]) {
throw new Error(
`${adapter} does not support createApp({ tls }); it would serve plain HTTP. ` +
`Configure TLS on the runtime's own server or terminate it at a proxy, and drop \`tls\`.`,
);
}
}
/** CORS policy. `origins` may be a literal, list, `'*'`, or a predicate. */ /** CORS policy. `origins` may be a literal, list, `'*'`, or a predicate. */
export interface CorsOptions { export interface CorsOptions {
origins: string | string[] | '*' | ((origin: string) => boolean); origins: string | string[] | '*' | ((origin: string) => boolean);
+30
View File
@@ -0,0 +1,30 @@
import { afterEach, expect, it, vi } from 'vitest';
import { createApp } from '../src';
import { serveDeno } from '../src/deno';
import { serveBun } from '../src/bun';
afterEach(() => {
vi.unstubAllGlobals();
});
// Only Node's `listen()` reads `tls`. Deno and Bun serve through their own listener, so an app
// created with `tls` would come up as plain HTTP there — refused before anything binds.
it.each([
['serveDeno', 'Deno', serveDeno],
['serveBun', 'Bun', serveBun],
] as const)('%s refuses an app created with tls', async (name, global, serve) => {
const listen = vi.fn();
vi.stubGlobal(global, { serve: listen });
const app = createApp({ modules: [], tls: { key: 'k', cert: 'c' } });
await expect(serve(app)).rejects.toThrow(`${name} does not support createApp({ tls })`);
expect(listen).not.toHaveBeenCalled();
});
it('an app without tls is not refused', async () => {
const listen = vi.fn(() => ({ port: 0, stop: vi.fn() }));
vi.stubGlobal('Bun', { serve: listen });
await serveBun(createApp({ modules: [] }));
expect(listen).toHaveBeenCalledOnce();
});