routed 0.3.3
routed: ^0.3.3 copied to clipboard
A modular HTTP engine and routing framework for Dart with middleware, configuration, sessions, and observability built in.
0.3.4 #
- bump jose + artisanal dependencies
0.3.3 #
Configuration #
ConfigLoaderOptionsgains aresolveEnvTemplatesflag. Whenfalse,{{ env.* }}Liquid expressions are preserved as raw placeholders through template rendering, enablingconfig:cacheto generate Dart files with deferred environment resolution.ConfigLoader.load()now returns aConfigSnapshotcontaining both the resolved config map and the raw YAML sources.- New
buildEnvTemplateContext()public function builds the Liquid template context fromPlatform.environmentat runtime. CoreServiceProvider.withCachedConfig()named constructor accepts aConfigSnapshotfor zero-I/O startup from a pre-built config cache.
Engine DX #
Engine()andEngine.create()accept an optionalconfigItemsparameter that auto-prepends aCoreServiceProvider(configItems: ...)to the providers list, eliminating the need to manually constructCoreServiceProviderfor simple inline configuration.- New
withConfigItems(Map<String, dynamic>)EngineOpt function allows late config overrides that run after providers register but before boot.
CLI and Scaffolding #
config:cachecommand generates a Dart file with aresolveRoutedConfig()function for zero-I/O startup. Supports--output,--json-output,--pretty,--docs, and--docs-outputoptions.config:clearcommand removes cached config files.config:publishsimplified -- generates config stubs directly frombuildConfigDefaults()/collectConfigDocs()instead of resolving package roots. Added--onlyoption for selective stub generation.provider:listnow accepts an optional positional ID filter and displays config source information.createcommand supports Inertia scaffolding via--inertia,--inertia-framework,--inertia-package-manager, and--inertia-outputflags. Entry key defaults toindex.htmlfor Vite 7 compatibility.- Generated apps now include a CLI entrypoint with a built-in
servecommand. - CLI command discovery can build engines without initialization via
createEngine(initialize: false). - Provider and artisanal command registries are merged into generated CLI
runners for
dart run <app>:cli.
Error Responses #
- All error responses are now content-negotiated based on the
Acceptheader,X-Requested-With(XHR detection), and requestContent-Type. API clients receive JSON, browsers receive styled HTML error pages, and other clients receive plain text. - New
ctx.errorResponse()method onEngineContextproduces a content-negotiated error response with status code, message, and optional custom JSON body override. - New convenience getters:
ctx.wantsJson,ctx.acceptsHtml, andctx.accepts(mimeType)for inspecting client content preferences. - Built-in error handler (
_handleGlobalError) and 404 handler now useerrorResponse()instead of hardcoded JSON. - All built-in middleware error paths updated:
recoveryMiddleware,rateLimitMiddleware,basicAuthMiddleware,timeoutMiddleware, and JWT_writeUnauthorized. - Breaking: Clients that previously received JSON error bodies without
sending an
Accept: application/jsonheader will now receive plain text instead. Add theAcceptheader to restore JSON responses.
Auth #
- Added
userInfoRequesttoOAuthProviderfor non-standard userinfo flows. - Introduced
CallbackProviderfor custom auth callbacks (ex: Telegram). - Added WebAuthn provider types and configuration classes.
- Split auth manager internals into focused modules for options and token storage.
- Provider booting now defers until required dependency types are available and warns when dependencies remain unresolved.
AuthManager.updateSession()replaces the authenticated identity in-place for both session and JWT strategies (reissues JWT cookie for JWT strategy).SessionAuth.updateSession()provides a static convenience API that delegates to the manager when wired byAuthServiceProvider.AuthServiceProviderregistersJwtVerifieras a container instance and wiresSessionAuth.setSessionUpdaterfor theupdateSessionfacade.
Container #
- Added
waitFor<T>(),waitForType(), andmakeWhenAvailable<T>()with optional timeout for awaiting lazily-registered dependencies.
Sessions #
sessionMiddleware()resolvesSessionConfigfrom the request container at runtime when no explicitstore/nameis provided.- Fixed post-response write guard to use
ctx.isClosedinstead ofctx.response.isClosed.
Views #
- Added a view extension registry so providers can register view engine extensions; Liquid applies registered extensions during rendering.
Logging #
RoutedLogger.createForChannel()creates a logger with a channel override key merged into the context.LoggingServiceProviderreads channel-specific log levels fromlogging.channels.*config keys and respects theLOG_CHANNELenvironment variable for default channel selection.
0.3.2 #
OAuth Improvements #
- Added
userInfoRequestcallback toOAuthProviderfor providers that require custom userinfo fetching (e.g., POST instead of GET). Matches NextAuth's pattern for handling non-standard OAuth endpoints like Dropbox.
Performance Optimizations #
- Added
EngineFeatures.enableRequestContainerFastPathfor high-throughput scenarios that skips per-request container creation and uses a read-only root container. - Added
EngineFeatures.enableTrieRoutingfor optional trie-based route matching. - Added path interning with LRU cache (
pathInternCacheSizeconfig option) to reduce string allocations during routing. - Middleware chains are now cached per-route and invalidated when global middleware changes.
- Lazy initialization of error lists and other context state to reduce allocations.
- Added
EngineFeatures.enableSecureRequestIdsoption (defaults to fast non-secure IDs).
EngineContext Convenience Helpers #
- Added
ctx.clientIP,ctx.remoteAddr,ctx.path,ctx.host,ctx.urishortcuts. - Added
ctx.body(),ctx.bodyBytes,ctx.contentLengthfor request body access. - Added
ctx.statusCodegetter andctx.write()for response manipulation.
Engine API Changes #
Engine.create()now loads all built-in providers by default (Engine.builtins).- Added
Engine.defaultProvidersfor minimal core + routing setup. - Explicit provider composition via
providersparameter replacesincludeDefaultProviders. CoreServiceProvidernow acceptsconfigItemsfor in-memory configuration.CoreServiceProvider.withLoader()factory for file-based configuration loading.
Logging Improvements #
- Request logger now outputs clean structured logs with
msg="Request completed"and separate key=value pairs for method, path, status, duration_ms, request_id. SingleFileLogDrivernow usesPlainTextLogFormatterby default to avoid ANSI escape codes in file output.
0.3.1 #
- Removed the
cryptodependency and replaced secure cookie encryption with a pointycastle-backed AES-GCM implementation plus internal hash/HMAC helpers. - Scaffold templates now live on disk and are embedded via build_runner, keeping template sources out of inline Dart strings.
- Web and fullstack scaffolds default to Tailwind; fullstack now renders Liquid layout + view files instead of inline HTML.
- Config loading now preserves
app.rootwhenconfigDirectorypoints at the project root.
0.3.0 #
0.2.0 #
-
Introduced a full auth stack with
AuthManager, built-in credentials/email/OAuth providers, session + JWT strategies, and first-class auth routes. -
Added auth callbacks/events for sign-in, sign-out, session, and JWT lifecycles, along with event hooks that align with routed observability signals.
-
Added RBAC helpers and policy-based authorization with Haigate integration for ability checks and middleware wiring.
-
Providers are now registry-driven with config-backed schemas, enabling dynamic auth provider configuration without hardcoding provider defaults.
-
Auth sessions now support refresh windows via
sessionUpdateAgeand JWT update age refreshes for long-lived client sessions. -
Updated CLI scaffolding/templates to align with the new auth config defaults and testing helpers.
-
Expanded auth docs and examples, including policy and JWT demo flows.
-
Introduced a full localization stack: translation contracts, registry-driven locale resolvers (query, cookie, session, header, and custom IDs), global middleware, helpers (
trans,transChoice,currentLocale), and manifest defaults so apps can ship multilingual responses out of the box. -
The configuration provider now leans on the shared
config_utilshelpers with deep merge/dot lookups, dynamic defaults for storage/session/cache, and doc snapshots that powerprovider:list --configoutput inrouted. -
Refactored the logging provider to use the new config snapshots, tightening context propagation and keeping structured logger defaults in sync with the rest of the engine.
-
Route lifecycle events now cover 404s and WebSocket handlers, publishing consistent metadata through
SignalHubfor observability hooks. -
Added Windows shutdown signal support so graceful server drains and CLI commands behave the same across platforms.
0.1.0 #
-
Driver registries now throw descriptive
ProviderConfigExceptions when the same driver ID is registered twice, and the CLI surfaces duplicate registrations throughprovider:list --configwith actionable guidance. -
Session authentication now exposes
SessionAuthhelpers (login/logout/current), declarative guard middleware, and remember-me token rotation with documented configuration options and examples. -
Added Haigate authorization gates with a shared registry, per-route middleware helpers, provider integration, and configuration-driven abilities mirroring Laravel-style gates.
-
Reorganized exports: core APIs remain under
package:routed/routed.dart, while service providers and driver registries moved topackage:routed/providers.dartandpackage:routed/drivers.dartrespectively. Added focused barrels for bindings (package:routed/bindings.dart), middleware (package:routed/middleware.dart), renderers (package:routed/renderers.dart), and validation (package:routed/validation.dart). -
Added a first-class signal hub (
SignalHub) that wraps routing lifecycle events (started,finished,routeMatched,routingError,afterRouting) withconnect/disconnectsemantics and re-publishes handler errors asUnhandledSignalErrorevents for observability. Accessible viaAppZone.signalsandcontainer.make<SignalHub>(). -
Signals now support Django-style receiver parity:
connectreturns disposable subscriptions, accepts optionalkey/senderarguments to deduplicate handlers and scope dispatch, andUnhandledSignalErrorexposes the failing handler's key and sender metadata. -
JWT verification and OAuth2 introspection support configurable
clockSkewtolerances via both code and manifest configuration, allowing short-lived clock drift without sacrificing validation rigor. -
HTTP and HTTPS servers emit structured startup and fatal-error logs through
LoggingContextwhile keeping the existing console output for local development. -
WebSocket routes resolve
MiddlewareRefentries and propagate route metadata to the logging context so middleware and telemetry behave the same across HTTP and WebSocket endpoints. -
Unified driver registration across storage, cache, and session providers so built-in drivers register through the same public APIs that applications use.
-
Added a storage driver registry and disk builders, enabling custom storage drivers without editing the service provider.
-
Driver registries now accept documentation callbacks so storage/cache/session drivers can advertise their custom configuration keys in provider docs.
-
routed provider:driverscaffolds starter files for storage and cache drivers, including documentation hooks that surface inprovider:list --config. -
Added
logging.include_stack_tracesto control whether unhandled errors log stack traces; defaults tofalsefor quieter production logs while keeping browser responses unchanged. -
ctx.ssenow disables output buffering, primes the response with a:okcomment, flushes every frame immediately, and watches the shutdown controller so draining servers close SSE connections promptly. -
The HTTP accept loop processes each request concurrently, so long-lived SSE streams no longer block unrelated requests.
-
Response.flush()now flushes the very first bytes even before streaming begins—SSE clients advance to the OPEN state instantly. -
Added
EngineContext.upgrade, a safe alternative to socket hijacking for bespoke protocols that need direct access to the underlyingSocket. -
Replaced SSE integration tests with lightweight context tests that cover event encoding, heartbeats, and error paths.
-
Documented Server-Sent Events usage and added a runnable counter example, linking both into the docs navigation.
0.1.0 #
- Introduced a contextual logging API (
ctx.logger/LoggingContext) and exposed configuration hooks viaRoutedLogger. - Added configurable error handling hooks (
beforeError,onError,afterError) plus default observers for request failures. - Unified middleware and handler signatures to return
Response, ensuring predictable flow control across the pipeline. - Refreshed binding and validation utilities with overridable rule factories and per-field message overrides.
- Tightened engine lifecycle management with request-scoped containers, request tracking, and safer size limiting.
- Updated dependencies (
contextual,liquify,decimal,lints,server_testing), removed the unused TOML renderer, and bumped the SDK minimum to 3.9.0.
0.0.1-alpha #
- Initial version.