Files
core/src/container.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

44 lines
1.6 KiB
TypeScript

/** Lifetime of a binding: `app` values are memoized for the process, `request` values are recomputed per resolve. */
export type Scope = 'app' | 'request';
/** Produces a bound value from the current context; may be async. */
export type Factory = (ctx: Record<string, unknown>) => unknown | Promise<unknown>;
interface Binding {
scope: Scope;
factory: Factory;
cached?: unknown;
resolved?: boolean;
}
/** Minimal token-keyed dependency container with app-scoped memoization and async, mesh-ready resolution. */
export class Container {
private readonly bindings = new Map<string, Binding>();
/** Bind `token` to `factory` under `scope`, replacing any existing binding. */
register(token: string, scope: Scope, factory: Factory): void {
this.bindings.set(token, { scope, factory });
}
/** Whether `token` currently has a binding. */
has(token: string): boolean {
return this.bindings.has(token);
}
/** Resolve `token`'s value; app-scoped results are cached, request-scoped ones re-run the factory. Throws on unknown tokens. */
// ponytail: app-scope memoizes; request-scope always re-runs. resolve is async
// so a future remote transport (mesh) slots in without changing callers.
async resolve(token: string, ctx: Record<string, unknown> = {}): Promise<unknown> {
const binding = this.bindings.get(token);
if (!binding) throw new Error(`unknown token: ${token}`);
if (binding.scope === 'app' && binding.resolved) return binding.cached;
const value = await binding.factory(ctx);
if (binding.scope === 'app') {
binding.cached = value;
binding.resolved = true;
}
return value;
}
}