10 Commits
Author SHA1 Message Date
chrnx b0b0b1388d docs: add README, MIT license, and DCO-based contributing guide
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-06-26 02:00:21 -05:00
chrnx ccaacb9a02 fix: stream errors -> 500, guard non-object body picks, test @query e2e 2026-06-26 01:51:02 -05:00
chrnx 7114bf685e feat: handlers declare deps via arg decorators, graph-validated at boot 2026-06-26 01:44:57 -05:00
chrnx 5bb825e293 feat: parse query string and json body into the request 2026-06-26 01:42:01 -05:00
chrnx 751db324d6 feat: handler argument decorators (needs/ctx/param/query/body/headers) 2026-06-26 01:40:04 -05:00
chrnx 97faff4c06 fix: guard handler errors, dedupe runner names, export flow core, test optional provider 2026-06-26 01:11:26 -05:00
chrnx 04c8b3a743 feat: end-to-end example demonstrating the four core ideas 2026-06-26 01:04:24 -05:00
chrnx 221a230270 fix: spread provider returns in boot snapshot; dedupe path-join; guard step runner 2026-06-26 01:01:06 -05:00
chrnx 62eb6587ea feat: boot orchestrator, app, inspect, fail-fast providers
Wires all modules together into createApp(): topo-ordered providers run
at boot (fail-fast for required), pipeline runs per request, inspect()
returns the ordered chain, plugins observe via Bus without mutating state.
2026-06-26 00:55:02 -05:00
chrnx 3803d4fe95 feat: node http transport with :param route matching 2026-06-26 00:49:29 -05:00
15 changed files with 845 additions and 1 deletions

No files matched your search

+56
View File
@@ -0,0 +1,56 @@
# Contributing to green-tea
Thanks for your interest. green-tea is open source, but not anyone can push directly — contributions land through reviewed pull/merge requests with a **DCO sign-off**.
## Developer Certificate of Origin (DCO)
We use the [Developer Certificate of Origin](./DCO) instead of a CLA. It's a lightweight, per-commit affirmation that you have the right to submit your work under the project's license. No copyright assignment, no paperwork.
**Every commit must be signed off.** Add the `-s` flag:
```bash
git commit -s -m "feat: add the thing"
```
This appends a trailer to your commit message:
```
Signed-off-by: Your Name <your.email@example.com>
```
The name and email must match your real `git config user.name` / `user.email`. Commits without a valid `Signed-off-by` line are rejected.
To sign off a range you forgot to sign:
```bash
git rebase --signoff <base>
```
## Branch model (GitFlow)
- `main` — production-ready, protected. No direct pushes.
- `develop` — active development, protected. Feature branches merge here.
- `feature/<name>` — branch from `develop`.
- `hotfix/<name>` — branch from `main`.
- `release/<version>` — release stabilization.
`main` and `develop` are protected: they require a reviewed MR and signed-off commits. (Branch protection is configured on the git server, not in this repo.)
## Commits
Follow [Conventional Commits](https://www.conventionalcommits.org/): `feat:`, `fix:`, `chore:`, `docs:`, `test:`, `refactor:`. Focus the message on the *why*. Do not add AI co-authoring attribution.
## Before you open an MR
```bash
npm test # all tests must pass
npm run typecheck # must be clean — this includes the compile-time-guarantee type test
```
- Write tests for new behavior (TDD welcome). We use Vitest.
- Keep runtime dependencies at zero beyond `reflect-metadata`.
- New public API needs a doc note in `README.md`.
## Reporting issues
Open an issue with a minimal reproduction: green-tea version, Node version, and the smallest module/route that shows the problem.
+37
View File
@@ -0,0 +1,37 @@
Developer Certificate of Origin
Version 1.1
Copyright (C) 2004, 2006 The Linux Foundation and its contributors.
1 Letterman Drive
Suite D4700
San Francisco, CA, 94129
Everyone is permitted to copy and distribute verbatim copies of this
license document, but changing it is not allowed.
Developer's Certificate of Origin 1.1
By making a contribution to this project, I certify that:
(a) The contribution was created in whole or in part by me and I
have the right to submit it under the open source license
indicated in the file; or
(b) The contribution is based upon previous work that, to the best
of my knowledge, is covered under an appropriate open source
license and I have the right under that license to submit that
work with modifications, whether created in whole or in part
by me, under the same open source license (unless I am
permitted to submit under a different license), as indicated
in the file; or
(c) The contribution was provided directly to me by some other
person who certified (a), (b) or (c) and I have not modified
it.
(d) I understand and agree that this project and the contribution
are public and that a record of the contribution (including all
personal information I submit with it, including my sign-off) is
maintained indefinitely and may be redistributed consistent with
this project or the open source license(s) involved.
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 green-tea contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+101
View File
@@ -0,0 +1,101 @@
# 🍵 green-tea
> A declarative, type-safe HTTP framework for Node. The request pipeline is an explicit **dependency graph**, not a mutable middleware chain.
`@green-tea/core` — **alpha**. Zero runtime dependencies beyond `reflect-metadata`.
## Why
Express/Fastify middleware is positional, untyped, and globally mutable: order depends on the line you wrote `app.use()` on, `req.user` may or may not exist, and a plugin can quietly delete your body parser. green-tea replaces that model:
- **Declarative, not positional.** You declare what each step *needs* and *produces*. The graph order is computed at boot via topological sort — there is no "put this before that".
- **The type is the contract.** What a handler reads from the context *is* its dependency declaration. The typed `flow` core makes a handler that reads `ctx.user` **fail to compile** if no step produces `user`.
- **Structural plugin isolation.** Plugins get only `bus.on(...)` (observe) and `scope.add(...)` (extend their own scope). There is no API to reorder or delete another scope's steps.
- **Response = return value.** No `Response.json()`. Return data; a `@Transformer` serializes it in a leave phase. Cut a request by `throw`ing a typed signal.
- **Fail-fast boot.** A required provider that can't initialize (e.g. the DB) stops the server from serving — no 500s because a resource wasn't ready.
## Quick look
```typescript
import {
createApp, Provider, Step, Route, Get, Module,
Transformer, JsonTransformer, Unauthorized, needs, param,
} from '@green-tea/core';
@Provider({ provides: 'db' })
class Database {
provide() {
const users = { u1: { id: 'u1', name: 'Diego' } };
return { db: { find: (token: string) => users[token] ?? null } };
}
}
@Step({ provides: 'user', needs: ['db', 'req'] })
class Authenticate {
run(ctx) {
const user = ctx.db.find(ctx.req.headers['x-token']);
if (!user) throw new Unauthorized('invalid token'); // cut the request
return { user }; // continue
}
}
@Route('/users')
class UserController {
@Get('/:id')
@Transformer(JsonTransformer)
getUser(@needs('user') user, @param('id') id) { // the signature IS the contract
return { requested: id, you: user };
}
}
@Module({ mountpoint: '/api', providers: [Database], steps: [Authenticate], controllers: [UserController] })
class ApiModule {}
const app = createApp({ modules: [ApiModule] });
console.log(app.inspect('/api/users/:id')); // auditable: ordered chain with origins
app.listen(3000);
```
```bash
curl -H 'x-token: u1' http://localhost:3000/api/users/9
# {"requested":"9","you":{"id":"u1","name":"Diego"}}
```
## Argument decorators
The handler signature declares exactly what it wants — in any order, nothing more.
| Decorator | Injects | Forms |
|---|---|---|
| `@needs('user')` | a graph-produced value (boot-validated) | `('key')` |
| `@ctx()` | the whole accumulated context | `()` |
| `@param(...)` | route params | `()` · `('id')` · `(['a','b'])` |
| `@query(...)` | parsed query string | `()` · `('q')` · `(['a','b'])` |
| `@body(...)` | parsed JSON body | `()` · `('field')` · `(['a','b'])` |
| `@headers(...)` | request headers | `()` · `('authorization')` · `(['a','b'])` |
`@needs` keys are validated at boot: if nothing provides the key, `createApp` throws with a clear error instead of serving `undefined`.
## Two layers
1. **Typed functional core (`flow`)** — `flow().step(...).step(...).handle(...)`; step outputs accumulate into the context type (`Acc & Out`). This is where the compile-time guarantee lives.
2. **Declarative decorator layer** — `@Provider/@Step/@Module/@Route/@Get/@Transformer` + argument decorators. Emits runtime metadata, builds and topologically sorts the graph, validates at boot.
## Development
```bash
npm install
npm test # vitest
npm run typecheck # tsc --noEmit (includes the compile-time-guarantee type test)
npm run build # emit dist/
```
## Roadmap
- **streams** — native WebSocket/SSE + reactive streams (steps that open an observed channel).
- **mesh** — `teapot`/`teacup`: distributed scopes over a persistent channel with auto-registration. Model: a BEAM/OTP-style cluster, *not* microservices. The core's `resolve()` is already async + transport-agnostic to allow this without a rewrite.
- official plugins (cors, body parsers, auth) — structurally unable to sabotage the global pipeline.
## License
[MIT](./LICENSE) © green-tea contributors. Contributions require a [DCO sign-off](./CONTRIBUTING.md).
+11
View File
@@ -0,0 +1,11 @@
````markdown
# green-tea example
```bash
npx ts-node example/server.ts # or: npm run build && node dist/example/server.js
curl -H 'x-token: u1' http://localhost:3000/api/users/9
```
Demonstrates: typed context contract, graph-derived order, `app.inspect()`,
and a logger plugin that observes the bus without touching the chain.
````
+43
View File
@@ -0,0 +1,43 @@
import { createApp, Provider, Step, Route, Get, Module, Transformer, JsonTransformer, Unauthorized, Plugin, needs, param } from '../src/index';
interface User { id: string; name: string }
@Provider({ provides: 'db' })
class Database {
provide() {
const users: Record<string, User> = { u1: { id: 'u1', name: 'Diego' } };
return { db: { find: (token: string) => users[token] ?? null } };
}
}
@Step({ provides: 'user', needs: ['db', 'req'] })
class Authenticate {
run(ctx: { db: { find: (t: string) => User | null }; req: { headers: Record<string, string> } }) {
const user = ctx.db.find(ctx.req.headers['x-token']);
if (!user) throw new Unauthorized('invalid token');
return { user };
}
}
@Route('/users')
class UserController {
@Get('/:id')
@Transformer(JsonTransformer)
getUser(@needs('user') user: User, @param('id') id: string) {
return { requested: id, you: user };
}
}
@Module({ mountpoint: '/api', providers: [Database], steps: [Authenticate], controllers: [UserController] })
class ApiModule {}
const logger: Plugin = (api) => {
api.bus.on('request:step:enter', (p) => console.log(`-> ${p.name}`));
};
export const app = createApp({ modules: [ApiModule], plugins: [logger] });
if (require.main === module) {
console.log('chain for /api/users/:id ->', app.inspect('/api/users/:id'));
app.listen(3000).then(() => console.log('green-tea on http://localhost:3000'));
}
+181
View File
@@ -0,0 +1,181 @@
import http from 'http';
import { Bus } from './bus';
import { Container } from './container';
import { topoSort, GraphNode } from './graph';
import { runPipeline, PipelineStep } from './pipeline';
import { createHttpServer, RouteDef } from './http';
import { JsonTransformer } from './transformers';
import { mountPlugin, Plugin, ScopeApi, ScopeNode } from './plugin';
import {
Ctor, getModuleMeta, getProviderMeta, getStepMeta, getRoutes, getTransformer, joinPath,
} from './metadata';
import { getArgs, getHandlerNeeds, resolveArgs } from './params';
export interface InspectLine { name: string; kind: 'provider' | 'step' | 'handler'; origin: string }
export interface App {
listen(port: number): Promise<http.Server>;
inspect(routePath: string): InspectLine[];
bus: Bus;
}
interface RoutePlan {
pattern: string;
origin: string;
providers: GraphNode[];
steps: GraphNode[];
handlerName: string;
needs: string[];
run: (ctx: any) => unknown;
transformer: typeof JsonTransformer;
}
export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[] }): App {
const bus = new Bus();
const container = new Container();
const extraSteps: ScopeNode[] = [];
const scope: ScopeApi = { add: (n) => extraSteps.push(n) };
// collect declarations from modules
const providerNodes: GraphNode[] = [];
const stepNodes: GraphNode[] = [];
const runners = new Map<string, (ctx: any) => any>(); // node name -> runtime fn
const setRunner = (name: string, fn: (ctx: any) => any) => {
if (runners.has(name)) throw new Error(`duplicate provider/step name '${name}' — names must be unique across modules and plugins`);
runners.set(name, fn);
};
const providerMeta = new Map<string, { optional: boolean }>();
const routePlans: RoutePlan[] = [];
for (const mod of opts.modules) {
const m = getModuleMeta(mod);
if (!m) throw new Error(`${mod.name} is not a @Module`);
const origin = `module:${mod.name}`;
for (const P of m.providers ?? []) {
const meta = getProviderMeta(P)!;
providerNodes.push({ name: meta.provides, needs: meta.needs, provides: [meta.provides], origin });
providerMeta.set(meta.provides, { optional: meta.optional });
const inst: any = new P();
setRunner(meta.provides, (ctx) => inst.provide(ctx));
}
for (const S of m.steps ?? []) {
const meta = getStepMeta(S)!;
stepNodes.push({ name: meta.provides, needs: meta.needs, provides: [meta.provides], origin });
const inst: any = new S();
setRunner(meta.provides, (ctx) => inst.run(ctx));
}
for (const C of m.controllers ?? []) {
for (const route of getRoutes(C)) {
const inst: any = new C();
const argSpecs = getArgs(C, route.handlerName);
routePlans.push({
pattern: joinPath(m.mountpoint, route.path),
origin,
providers: [],
steps: [],
handlerName: route.handlerName,
needs: getHandlerNeeds(argSpecs),
run: (c: any) => inst[route.handlerName](...resolveArgs(argSpecs, c)),
transformer: getTransformer(C, route.handlerName) ?? JsonTransformer,
});
}
}
}
// plugin-added steps join the graph as their own scope
for (const plugin of opts.plugins ?? []) mountPlugin(plugin, bus, scope);
for (const n of extraSteps) {
const node = { name: n.name, needs: n.needs, provides: n.provides, origin: 'plugin' };
if (n.kind === 'provider') providerNodes.push(node); else stepNodes.push(node);
setRunner(n.name, n.run);
}
// For each route, resolve which providers/steps feed it via topo order.
// MVP: every route depends on every declared step + provider in the app graph.
const seedKeys = ['req', 'params'];
const ordered = topoSort([...providerNodes, ...stepNodes], seedKeys);
const orderedProviders = ordered.filter((n) => providerNodes.includes(n));
const orderedSteps = ordered.filter((n) => stepNodes.includes(n));
for (const plan of routePlans) { plan.providers = orderedProviders; plan.steps = orderedSteps; }
const producedKeys = new Set<string>([
...providerNodes.flatMap((n) => n.provides),
...stepNodes.flatMap((n) => n.provides),
]);
const allowed = new Set<string>([...producedKeys, 'req', 'params', 'query', 'body', 'headers']);
for (const plan of routePlans) {
for (const need of plan.needs) {
if (!allowed.has(need)) {
throw new Error(`handler '${plan.handlerName}' needs '${need}' but nothing provides it`);
}
}
}
const inspect = (routePath: string): InspectLine[] => {
const plan = routePlans.find((p) => p.pattern === routePath);
if (!plan) throw new Error(`no route: ${routePath}`);
return [
...plan.providers.map((p) => ({ name: p.name, kind: 'provider' as const, origin: p.origin })),
...plan.steps.map((s) => ({ name: s.name, kind: 'step' as const, origin: s.origin })),
{ name: plan.handlerName, kind: 'handler' as const, origin: plan.origin },
];
};
const listen = async (port: number): Promise<http.Server> => {
// run app-scoped providers in order (fail-fast for required)
for (const node of orderedProviders) {
bus.emit('boot:provider:start', { name: node.name, scope: node.origin });
try {
const value = await runners.get(node.name)!(await snapshot(container, node.needs));
container.register(node.name, 'app', () => value);
await container.resolve(node.name); // warm the cache
bus.emit('boot:provider:ok', { name: node.name });
} catch (error) {
bus.emit('boot:provider:fail', { name: node.name, error });
if (!providerMeta.get(node.name)?.optional) {
throw new Error(`provider '${node.name}' failed: ${(error as Error).message}`);
}
// optional: warn, leave it unregistered; routes needing it fail at request time
// ponytail: full partial-degradation is out of scope (spec §10); warn is enough here
console.warn(`[green-tea] optional provider '${node.name}' failed: ${(error as Error).message}`);
}
}
const routeDefs: RouteDef[] = routePlans.map((plan) => ({
method: 'GET',
pattern: plan.pattern,
handler: async (req) => {
// build app-scoped seed by spreading each provider's resolved value into context
// providers follow the same merge convention as steps: return { token: value }
const provided: Record<string, unknown> = {};
for (const p of plan.providers) {
if (container.has(p.name)) {
const resolved = (await container.resolve(p.name)) as Record<string, unknown>;
Object.assign(provided, resolved);
}
}
const steps: PipelineStep[] = plan.steps.map((s) => {
const fn = runners.get(s.name);
if (!fn) throw new Error(`no runner registered for step '${s.name}'`);
return { name: s.name, origin: s.origin, run: fn };
});
return runPipeline({
steps, handler: plan.run, transformer: plan.transformer, bus,
seed: { ...provided, req, params: req.params, query: req.query, body: req.body, headers: req.headers },
});
},
}));
const server = createHttpServer(routeDefs);
await new Promise<void>((resolve) => server.listen(port, resolve));
return server;
};
return { listen, inspect, bus };
}
async function snapshot(c: Container, needs: string[]): Promise<Record<string, unknown>> {
const out: Record<string, unknown> = {};
for (const key of needs) if (c.has(key)) Object.assign(out, (await c.resolve(key)) as Record<string, unknown>);
return out;
}
+90
View File
@@ -0,0 +1,90 @@
import http from 'http';
import { errorToResponse } from './transformers';
import type { ResponseShape } from './pipeline';
export type RouteHandler = (req: {
method: string; url: string;
headers: Record<string, string | string[] | undefined>;
params: Record<string, string>;
query: Record<string, string>;
body: unknown;
}) => Promise<ResponseShape>;
export interface RouteDef { method: string; pattern: string; handler: RouteHandler }
export interface MatchedRoute { params: Record<string, string>; handler: RouteHandler }
export function matchRoute(routes: RouteDef[], method: string, path: string): MatchedRoute | undefined {
const segs = path.split('/').filter(Boolean);
for (const r of routes) {
if (r.method !== method) continue;
const pat = r.pattern.split('/').filter(Boolean);
if (pat.length !== segs.length) continue;
const params: Record<string, string> = {};
let ok = true;
for (let i = 0; i < pat.length; i++) {
if (pat[i].startsWith(':')) params[pat[i].slice(1)] = decodeURIComponent(segs[i]);
else if (pat[i] !== segs[i]) { ok = false; break; }
}
if (ok) return { params, handler: r.handler };
}
return undefined;
}
export function parseQuery(url: string): Record<string, string> {
const qs = url.split('?')[1] ?? '';
const out: Record<string, string> = {};
for (const [k, v] of new URLSearchParams(qs)) out[k] = v;
return out;
}
async function readBody(req: http.IncomingMessage): Promise<string | undefined> {
const chunks: Buffer[] = [];
for await (const chunk of req) chunks.push(chunk as Buffer);
if (chunks.length === 0) return undefined;
const raw = Buffer.concat(chunks).toString('utf8');
return raw === '' ? undefined : raw;
}
export function createHttpServer(routes: RouteDef[]): http.Server {
return http.createServer(async (req, res) => {
const url = req.url ?? '/';
const path = url.split('?')[0];
const matched = matchRoute(routes, req.method ?? 'GET', path);
if (!matched) {
res.writeHead(404, { 'content-type': 'application/json' });
res.end(JSON.stringify({ error: 'Not Found' }));
return;
}
let raw: string | undefined;
try {
raw = await readBody(req);
} catch {
// stream/network failure — not the client's JSON fault
res.writeHead(500, { 'content-type': 'application/json' });
res.end(JSON.stringify({ error: 'Internal Server Error' }));
return;
}
let body: unknown = raw;
const ct = String(req.headers['content-type'] ?? '');
if (raw !== undefined && ct.includes('application/json')) {
try {
body = JSON.parse(raw);
} catch {
res.writeHead(400, { 'content-type': 'application/json' });
res.end(JSON.stringify({ error: 'Invalid JSON body' }));
return;
}
}
let result: ResponseShape;
try {
result = await matched.handler({
method: req.method ?? 'GET', url, headers: req.headers,
params: matched.params, query: parseQuery(url), body,
});
} catch (error) {
result = errorToResponse(error);
}
res.writeHead(result.status, result.headers);
res.end(result.body);
});
}
+12
View File
@@ -1,2 +1,14 @@
import 'reflect-metadata';
export const VERSION = '0.0.0';
export { createApp } from './app';
export type { App, InspectLine } from './app';
export { Provider, Step, Route, Get, Module, Transformer } from './metadata';
export type { Plugin } from './plugin';
export { JsonTransformer } from './transformers';
export { HttpError, Unauthorized, NotFound, Redirect, NotModified } from './signals';
export { Bus } from './bus';
export { flow, Flow } from './flow';
export type { StepFn, CompiledFlow } from './flow';
export { needs, ctx, param, query, body, headers } from './params';
export type { Query, Headers, Context, ArgSpec } from './params';
+1 -1
View File
@@ -74,6 +74,6 @@ export function getRoutes(cls: Ctor): RouteMeta[] {
return routes.map((r) => ({ ...r, path: joinPath(prefix, r.path) }));
}
function joinPath(a: string, b: string): string {
export function joinPath(a: string, b: string): string {
return `${a.replace(/\/$/, '')}/${b.replace(/^\//, '')}`.replace(/\/+/g, '/');
}
+78
View File
@@ -0,0 +1,78 @@
import 'reflect-metadata';
import type { Ctor } from './metadata';
export type Query = Record<string, string>;
export type Headers = Record<string, string | string[] | undefined>;
export type Context = Record<string, unknown>;
type ArgSource = 'ctx' | 'needs' | 'params' | 'query' | 'body' | 'headers';
export interface ArgSpec { index: number; source: ArgSource; key?: string; keys?: string[] }
const ARGS = Symbol('gt:args');
function record(target: object, methodKey: string | symbol | undefined, spec: ArgSpec): void {
if (methodKey === undefined) return; // constructor params not supported
const ctor = target.constructor as Ctor;
const map: Record<string, ArgSpec[]> = Reflect.getMetadata(ARGS, ctor) ?? {};
const list = map[String(methodKey)] ?? [];
list.push(spec);
map[String(methodKey)] = list;
Reflect.defineMetadata(ARGS, map, ctor);
}
function envelope(source: ArgSource) {
return (arg?: string | string[]): ParameterDecorator =>
(target, methodKey, index) => {
const spec: ArgSpec = Array.isArray(arg)
? { index, source, keys: arg }
: typeof arg === 'string'
? { index, source, key: arg }
: { index, source };
record(target, methodKey, spec);
};
}
export const param = envelope('params');
export const query = envelope('query');
export const body = envelope('body');
export const headers = envelope('headers');
export function needs(key: string): ParameterDecorator {
return (target, methodKey, index) => record(target, methodKey, { index, source: 'needs', key });
}
export function ctx(): ParameterDecorator {
return (target, methodKey, index) => record(target, methodKey, { index, source: 'ctx' });
}
export function getArgs(cls: Ctor, methodName: string): ArgSpec[] {
const map: Record<string, ArgSpec[]> = Reflect.getMetadata(ARGS, cls) ?? {};
return [...(map[methodName] ?? [])].sort((a, b) => a.index - b.index);
}
export function getHandlerNeeds(specs: ArgSpec[]): string[] {
return specs.filter((s) => s.source === 'needs' && s.key).map((s) => s.key as string);
}
export function resolveArgs(specs: ArgSpec[], context: Context): unknown[] {
if (specs.length === 0) return [];
const max = Math.max(...specs.map((s) => s.index));
const args: unknown[] = new Array(max + 1).fill(undefined);
for (const s of specs) args[s.index] = resolveOne(s, context);
return args;
}
function resolveOne(s: ArgSpec, context: Context): unknown {
if (s.source === 'ctx') return context;
if (s.source === 'needs') return context[s.key as string];
const bag = context[s.source];
if (typeof bag !== 'object' || bag === null) return bag; // can't pick from a non-object; return as-is
const record = bag as Record<string, unknown>;
if (s.keys) {
const out: Record<string, unknown> = {};
for (const k of s.keys) out[k] = record[k];
return out;
}
if (s.key !== undefined) return record[s.key];
return record;
}
+109
View File
@@ -0,0 +1,109 @@
import 'reflect-metadata';
import { expect, test, vi } from 'vitest';
import { Provider, Step, Route, Get, Module, Transformer } from '../src/metadata';
import { JsonTransformer } from '../src/transformers';
import { Unauthorized } from '../src/signals';
import { createApp } from '../src/app';
import { needs, param, query } from '../src/params';
@Provider({ provides: 'db' })
class Db { provide() { return { db: { find: (t: string) => (t === 'good' ? { id: 'u1' } : null) } }; } }
@Step({ provides: 'user', needs: ['db', 'req'] })
class Auth {
run(ctx: any) {
const user = ctx.db.find(ctx.req.headers['x-token']);
if (!user) throw new Unauthorized('bad token');
return { user };
}
}
@Route('/users')
class UserCtl {
@Get('/:id')
@Transformer(JsonTransformer)
getUser(@needs('user') user: any, @param('id') id: string) { return { id, user }; }
}
@Module({ mountpoint: '/api', providers: [Db], steps: [Auth], controllers: [UserCtl] })
class ApiModule {}
test('inspect lists the ordered chain with origins', () => {
const app = createApp({ modules: [ApiModule] });
const lines = app.inspect('/api/users/:id');
expect(lines.map((l) => `${l.kind}:${l.name}`)).toEqual(['provider:db', 'step:user', 'handler:getUser']);
});
test('a logger plugin observes step:enter without mutating the chain', async () => {
const seen: string[] = [];
const logger = (api: any) => api.bus.on('request:step:enter', (p: any) => seen.push(p.name));
const app = createApp({ modules: [ApiModule], plugins: [logger] });
const server = await app.listen(0);
const port = (server.address() as any).port;
const ok = await fetch(`http://127.0.0.1:${port}/api/users/7`, { headers: { 'x-token': 'good' } });
expect(ok.status).toBe(200);
expect(await ok.json()).toEqual({ id: '7', user: { id: 'u1' } });
expect(seen).toContain('user');
const bad = await fetch(`http://127.0.0.1:${port}/api/users/7`, { headers: { 'x-token': 'nope' } });
expect(bad.status).toBe(401);
server.close();
});
test('required provider failure aborts boot', () => {
@Provider({ provides: 'broken' })
class Broken { provide() { throw new Error('cannot connect'); } }
@Module({ mountpoint: '/x', providers: [Broken], steps: [], controllers: [] })
class BrokenModule {}
const app = createApp({ modules: [BrokenModule] });
return expect(app.listen(0)).rejects.toThrow(/provider 'broken' failed/);
});
test('optional provider failure warns but does not abort boot', async () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
@Provider({ provides: 'cache', optional: true })
class FlakyCache { provide() { throw new Error('cache down'); } }
@Route('/ping')
class PingCtl { @Get('/') ping() { return { ok: true }; } }
@Module({ mountpoint: '/sys', providers: [FlakyCache], steps: [], controllers: [PingCtl] })
class SysModule {}
const app = createApp({ modules: [SysModule] });
const server = await app.listen(0); // must NOT throw
expect(warn).toHaveBeenCalledWith(expect.stringContaining("optional provider 'cache' failed"));
server.close();
warn.mockRestore();
});
test('handler receives @query value through a live request', async () => {
@Route('/search')
class SearchCtl {
@Get('/')
run(@query('q') q: string) { return { q }; }
}
@Module({ mountpoint: '/s', providers: [], steps: [], controllers: [SearchCtl] })
class SearchModule {}
const app = createApp({ modules: [SearchModule] });
const server = await app.listen(0);
const port = (server.address() as any).port;
const res = await fetch(`http://127.0.0.1:${port}/s/search/?q=hello`);
expect(await res.json()).toEqual({ q: 'hello' });
server.close();
});
test('boot fails when a handler needs something nothing provides', () => {
@Route('/things')
class ThingCtl {
@Get('/')
list(@needs('missing') _m: any) { return []; }
}
@Module({ mountpoint: '/t', providers: [], steps: [], controllers: [ThingCtl] })
class ThingModule {}
expect(() => createApp({ modules: [ThingModule] }))
.toThrow(/handler 'list' needs 'missing'/);
});
+16
View File
@@ -0,0 +1,16 @@
import { expect, test } from 'vitest';
import { app } from '../example/server';
test('example: inspect shows graph-ordered chain', () => {
expect(app.inspect('/api/users/:id').map((l) => `${l.kind}:${l.name}`))
.toEqual(['provider:db', 'step:user', 'handler:getUser']);
});
test('example: authenticated request returns the user', async () => {
const server = await app.listen(0);
const port = (server.address() as any).port;
const res = await fetch(`http://127.0.0.1:${port}/api/users/9`, { headers: { 'x-token': 'u1' } });
expect(res.status).toBe(200);
expect(await res.json()).toEqual({ requested: '9', you: { id: 'u1', name: 'Diego' } });
server.close();
});
+42
View File
@@ -0,0 +1,42 @@
import { expect, test } from 'vitest';
import { matchRoute, parseQuery, createHttpServer } from '../src/http';
const handler = async () => ({ status: 200, headers: {}, body: 'ok' });
test('matches a static + :param route and extracts params', () => {
const routes = [{ method: 'GET', pattern: '/api/users/:id', handler }];
const m = matchRoute(routes, 'GET', '/api/users/42');
expect(m?.params).toEqual({ id: '42' });
});
test('returns undefined when nothing matches', () => {
const routes = [{ method: 'GET', pattern: '/api/users/:id', handler }];
expect(matchRoute(routes, 'GET', '/api/orders/1')).toBeUndefined();
expect(matchRoute(routes, 'POST', '/api/users/1')).toBeUndefined();
});
test('parseQuery extracts query params from a url', () => {
expect(parseQuery('/api/users/9?q=hi&date=2026')).toEqual({ q: 'hi', date: '2026' });
expect(parseQuery('/api/users/9')).toEqual({});
});
test('server parses json body and rejects malformed json with 400', async () => {
const server = createHttpServer([{
method: 'POST', pattern: '/echo',
handler: async (req) => ({ status: 200, headers: { 'content-type': 'application/json' }, body: JSON.stringify({ got: req.body, q: req.query }) }),
}]);
await new Promise<void>((r) => server.listen(0, r));
const port = (server.address() as any).port;
const ok = await fetch(`http://127.0.0.1:${port}/echo?x=1`, {
method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ a: 1 }),
});
expect(await ok.json()).toEqual({ got: { a: 1 }, q: { x: '1' } });
const bad = await fetch(`http://127.0.0.1:${port}/echo`, {
method: 'POST', headers: { 'content-type': 'application/json' }, body: '{not json',
});
expect(bad.status).toBe(400);
server.close();
});
+47
View File
@@ -0,0 +1,47 @@
import 'reflect-metadata';
import { expect, test } from 'vitest';
import { needs, ctx, param, query, getArgs, getHandlerNeeds, resolveArgs } from '../src/params';
class Ctl {
handler(
@needs('user') _user: unknown,
@param('id') _id: unknown,
@query() _q: unknown,
@query(['a', 'b']) _sub: unknown,
@ctx() _c: unknown,
) { return null; }
}
test('getArgs returns specs sorted by parameter index', () => {
const specs = getArgs(Ctl, 'handler');
expect(specs.map((s) => [s.index, s.source, s.key ?? s.keys])).toEqual([
[0, 'needs', 'user'],
[1, 'params', 'id'],
[2, 'query', undefined],
[3, 'query', ['a', 'b']],
[4, 'ctx', undefined],
]);
});
test('getHandlerNeeds extracts only @needs keys', () => {
expect(getHandlerNeeds(getArgs(Ctl, 'handler'))).toEqual(['user']);
});
test('resolveArgs builds positional args from context', () => {
const context = {
user: { id: 'u1' },
params: { id: '7' },
query: { a: '1', b: '2', c: '3' },
};
const args = resolveArgs(getArgs(Ctl, 'handler'), context);
expect(args[0]).toEqual({ id: 'u1' });
expect(args[1]).toBe('7');
expect(args[2]).toEqual({ a: '1', b: '2', c: '3' });
expect(args[3]).toEqual({ a: '1', b: '2' });
expect(args[4]).toBe(context);
});
test('a handler with no arg decorators resolves to no args', () => {
class Bare { ping() { return 1; } }
expect(resolveArgs(getArgs(Bare, 'ping'), {})).toEqual([]);
});