Skip to content

ream ​

@c9up/ream: the framework core: the application and its lifecycle, the container, the environment, the HTTP server with its router, request, response, sessions and body parser, events, the scheduler, the console, and the test client. Guide: Application.

Installation ​

bash
pnpm add @c9up/ream

The native binaries (HTTP server, scheduler, event bus) come in one npm package per platform, which @c9up/ream lists as an optional dependency at its exact version:

PlatformPackage
Linux x64 (glibc)@c9up/ream-linux-x64-gnu
Linux arm64 (glibc)@c9up/ream-linux-arm64-gnu
macOS x64@c9up/ream-darwin-x64
macOS arm64@c9up/ream-darwin-arm64
Windows x64@c9up/ream-win32-x64-msvc

The package manager installs only the one that matches the machine, so an install downloads one platform's binaries and needs no Rust toolchain. Do not omit optional dependencies (--no-optional, --omit=optional): the binaries would be missing. Linux binaries target glibc; musl (Alpine) is not supported. A missing binary throws E_REAM_NAPI_NOT_FOUND: its help names the package to install, and its cause is the load error.

ream new creates a project with it. Optional peer dependencies: @c9up/inker (template rendering and the session template tags), @c9up/quasar (the redis session store and the redis scheduler lock), @c9up/comet (the JSON-RPC router).

Entry points ​

ImportContents
@c9up/reamThe application, container, env, HTTP layer, router, sessions, events, scheduler, console, errors, and most of what the subpaths below export.
@c9up/ream/typesContainerBindings, ContainerBinding, Authenticators, AuthenticatorName: the interfaces packages augment.
@c9up/ream/exceptionsException, createError, the HTTP exceptions and ExceptionHandler.
@c9up/ream/envloadEnvFiles, envFileNames.
@c9up/ream/bootstrapcreateHyperServerFactory: the native HTTP server factory.
@c9up/ream/hotSide-effect module loaded by ream dev: swaps changed modules in the running process.
@c9up/ream/dev/hmrThe browser reload endpoint and script used in development.
@c9up/ream/services/appThe application instance (default export) and its setters.
@c9up/ream/services/configThe config store (default export).
@c9up/ream/services/routerThe router (default export) and its setters.
@c9up/ream/services/serverThe server (default export) and its setters.
@c9up/ream/services/loggerThe app logger (default export) and its setters.
@c9up/ream/services/encryptionThe APP_KEY signer (default export) and its setters.
@c9up/ream/services/urlBuilderurlFor, signedUrlFor.
@c9up/ream/services/consoleThe console application (default export) and its setters.
@c9up/ream/services/dumperThe dumper (default export) and dd.
@c9up/ream/services/replThe REPL (default export).
@c9up/ream/dumperDumper and its config types.
@c9up/ream/replRepl and its types.
@c9up/ream/bodyparser, @c9up/ream/bodyparser_middlewareThe body parser middleware (default export) and BodyParserConfig.
@c9up/ream/bodyparser/configdefineConfig for config/bodyparser.ts.
@c9up/ream/session, @c9up/ream/session_middlewareThe session middleware (default export).
@c9up/ream/session/configdefineConfig for config/session.ts.
@c9up/ream/eventsThe event emitter, BaseEvent, EventsBuffer, EventsProvider, defineConfig.
@c9up/ream/events/providerEventsProvider (default export).
@c9up/ream/events/configdefineConfig, checkEventsConfig for config/events.ts.
@c9up/ream/events/services/mainThe emitter (default export), getEmitter, setEmitter.
@c9up/ream/events/testingFakeBus: an in-memory event bus for tests.
@c9up/ream/events/helixEvent assertions for tests: collect, fake, assertEmitted, waitForEvent, …
@c9up/ream/scheduler/providerScheduleProvider (default export).
@c9up/ream/scheduler/configdefineConfig for config/scheduler.ts and locks.
@c9up/ream/rpc/providerRpcProvider (default export).
@c9up/ream/rpc/routerRpcRouter: JSON-RPC methods.
@c9up/ream/graphql/providerGraphQLProvider (default export).
@c9up/ream/openapi/providerOpenApiProvider (default export).
@c9up/ream/storage/providerStaticProvider (default export): static files.
@c9up/ream/healthHealth checks: HealthChecks, BaseCheck, Result and the built-in checks.
@c9up/ream/http-clientHttpClient for outbound requests, and fakeHttp for tests.
@c9up/ream/consoleThe console kernel, BaseCommand, decorators, prompts, loaders.
@c9up/ream/commandsThe command loader of the commands ream ships (migrate, schedule:*).
@c9up/ream/stubsThe stub template engine and stubsRoot.
@c9up/ream/helpersString, type-check, fs, base64, timing and type helpers.
@c9up/ream/helpers/string, /helpers/is, /helpers/base64, /helpers/types, /helpers/fsEach helper group on its own.
@c9up/ream/testingTestClient, createTestClient, ApiResponse, TestWebSocket.
@c9up/ream/testing/utilscreateTestUtils: boots the app for a test suite.
@c9up/ream/tsconfig.app.json, /tsconfig.package.json, /tsconfig.client.json, /swcrc.app.jsonBase compiler configs to extend.

Commands ​

Commands an app gets from ream, run through ream <name>:

CommandDescription
listLists the commands (the default command).
helpShows a command's help.
make:controller, make:service, make:entity, make:validator, make:moduleGenerate a class under app/<module>/; make:module writes entity, controller and validator.
make:provider, make:command, make:middleware, make:event, make:listenerGenerate a provider, a command, a middleware, an event or a listener.
ejectCopies a make: stub into stubs/ to edit it.
migrateRuns pending migrations for every registered migration source.
migrate:rollbackRolls back the last batch for every source.
migrate:statusShows applied and pending migrations for every source.
schedule:listLists every scheduled task, its next run and its stats.
schedule:runRuns a scheduled task once, now, bypassing its lock.

Every make: command takes --force (-f), --dry-run and --json. The Ignitor registers the migrate and schedule:* commands of the @c9up/ream/commands loader by itself; an application command of the same name replaces one.

Exports ​

@c9up/ream ​

Application and configuration ​

ExportKindDescription
IgnitorclassBoots and wires the framework: rc file, providers, HTTP server, console.
ConsoleKernelclassBoots the app in console mode and dispatches a command.
defineConfigfunctiondefineConfig(config: ReamrcConfig): ReamrcConfig: types reamrc.ts.
ReamrcConfig, IgnitorConfig, TestsConfig, TestSuiteConfig, MobileConfig, HyperServerLikeinterfaceThe rc file, the Ignitor options, the tests and mobile blocks, the native server shape.
ApplicationclassThe application: container, config, paths, environment, lifecycle hooks.
ApplicationOptions, ApplicationHook, ApplicationImporter, ApplicationMode, ApplicationState, AppEnvironmenttypeIts options and states. AppEnvironment is 'web' | 'console' | 'test' | 'repl' | 'unknown'; ApplicationMode is 'run' | 'warmup'.
directories, DirectoriesNodeconst / interfaceThe conventional directory layout.
ProviderclassBase provider with register, boot, start, ready, shutdown.
ProviderContract, AppContext, ConfigReaderinterfaceThe provider contract and what a provider receives.
ConfigStoreclassThe config built from config/*.ts: get, set, has, all, defaults.
configProviderconstconfigProvider.create(resolver): a config value resolved from the application.
defineModuleConfigfunctiondefineModuleConfig<T>(config: T): T: types a module's config.
envfunctionenv(key: string): reads an environment variable in a config file.
EnvclassLoads .env* files and validates process.env against a schema.
SchemaNode, RequiredNode, SchemaFnOptions, StringOptions, OptionalConditiontypeEnv.schema node types.
SecretclassA value that prints as [redacted]; .release() reads it.
loadEnvFilesfunctionloadEnvFiles(appRoot: URL, options?: { skipEnvLocal?: boolean }): Promise<void>.
MigrationRegistryclassWhere data packages register their migration runners.
MigrationRunnerContract, MigrationState, MigrationStatusNode, RegisteredMigrationSourcetypeIts contracts.
installGracefulShutdownfunctioninstallGracefulShutdown(options: ShutdownOptions): ShutdownHandle: drains on SIGTERM / SIGINT.
ShutdownOptions, ShutdownHandleinterface
startHotReload, HotReloadOptionsfunction / interfaceWatches TypeScript files and re-registers handlers on change.
VERSIONconstThe package version.

Container ​

ExportKindDescription
ContainerclassThe IoC container. Resolution is async.
ContainerResolverclassA per-request resolver with its own scoped values.
ContextualBindingsBuilder, ConditionalBindingsBuilderclassReturned by container.when() and container.if().
Binding, BindingCondition, ContainerEmitter, ContainerOptions, ServiceFactory, ServiceScope, ServiceTokentypeContainer types. ServiceToken is a class, a string or a symbol.
ContainerBindings, ContainerBindinginterface / typeThe known string tokens; packages augment it.
Authenticators, AuthenticatorNameinterface / typeThe guard names; the auth package augments it.
ServicefunctionService(options?: { scope?: ServiceScope }): class decorator that registers a service.
injectfunctioninject(): ClassDecorator & MethodDecorator: records constructor or method dependencies.
InjectfunctionInject(token: ServiceToken): ParameterDecorator: injects a token into one parameter.
getServiceMetadata, getServiceRegistry, clearServiceRegistryfunctionRead or reset what @Service recorded.

HTTP ​

ExportKindDescription
HttpContextclassThe request context: request, response, params, session, auth, logger, …
RequestclassThe incoming request.
ResponseclassThe response builder.
RedirectBuilderclassReturned by response.redirect(): toPath, toRoute, back, toIntended, withQs, status.
RequestValidatorclassValidates a request with a validator object.
RequestAwareValidator, RequestValidationOptions, ValidatableContext, ValidationHookContexttypeIts contracts.
RawRequest, RouteInfo, AuthState, AuthorizerinterfaceParts of the context.
SseStream, SseStreamOptionsclass / interfaceThe stream response.sse() opens. Its end() ends the HTTP response: the client reads the end of the body once what was sent before is delivered.
ServerWebSocketclassThe server side of one WebSocket connection.
WebSocketHubclassThe sockets of one server.
WebSocketContexttypeHttpContext & { socket: ServerWebSocket }.
isWebSocketContextfunctionisWebSocketContext(ctx: HttpContext): ctx is WebSocketContext.
WebSocketBackend, WebSocketClose, WebSocketEvent, WebSocketMessage, WebSocketStatetypeWebSocket types.
ServerclassThe HTTP server: global middleware, error handler, trusted proxies, gRPC.
createHttpKernel, HttpKernelConfigfunction / interfaceBuilds the request handler on its own (serverless, tests).
GrpcCall, GrpcHandler, GrpcReply, GrpcLimits, NativeGrpcCall, NativeGrpcHandlertypegRPC on the HTTP port.
ErrorHandlerClass, LazyImport, MiddlewareClass, MiddlewareEntry, MiddlewareFunctiontypeMiddleware and error handler shapes.
resolveMiddlewareEntryfunctionresolveMiddlewareEntry(entry: MiddlewareEntry): MiddlewareFunction.
composeMiddlewarefunctioncomposeMiddleware(middleware: MiddlewareFunction[]): MiddlewareFunction.
MiddlewareRegistry, NamedMiddlewareSourceclass / interfaceNamed middleware. new MiddlewareRegistry(source?): get(name) answers a name given to register(), else the source's (the application's registry reads its router's named() collection); names() lists both.
Macroable, MacroFn, GetterFnclass / typemacro() and getter(), on HttpContext, Request, Response, Router and the route builders.
BodyParserMiddleware, BodyParserConfigclass / interfaceParses JSON, form, raw and multipart bodies.
MultipartFile, FileValidationOptions, MimeTypeclass / typeAn uploaded file: validate(), errors, move(), stream().
StaticMiddleware, StaticConfig, DotFilesPolicy, defineStaticConfigclass / type / functionServes files from public/.
StaticProvider, StaticProviderOptionsclass / interfaceRegisters the static middleware.
ApiResource, PaginationMetaclass / interfaceTransforms entities into API responses.

Router ​

ExportKindDescription
RouterclassRoutes, groups, resources, named routes, URL building.
RouteBuilderclassOne route, returned by router.get() and the other verbs.
GroupBuilderclassA group, returned by router.group().
RouteResourceclassResourceful routes, returned by router.resource().
OnRouteBuilderclassrouter.on(path).render(view) / .redirect(name).
UrlBuilderclassBuilds a URL for a named route, piece by piece.
matchersconstmatchers.number(), .uuid(), .slug(): parameter matchers.
RouteDefinition, RouteHandler, RouteHandlerFunction, ControllerAction, MatchResult, ParamMatcher, SignedUrlOptions, WebSocketRouteHandler, WebSocketRouteHandlerFunctiontypeRoute types.
InferRouteParamstypeThe params object a pattern such as /users/:id declares.

Sessions ​

ExportKindDescription
SessionclassThe request session: values, flash messages, regeneration, tagging.
SessionMiddlewareclassLoads and commits the session.
SessionCookieDriver, SessionFileDriver, SessionMemoryDriver, SessionRedisDriver, SessionDatabaseDriverclassThe stores.
SessionConfig, SessionDriver, SessionDriverWithTagging, TaggedSession, SessionDatabaseDriverOptions, SessionDbConnection, SessionFileDriverOptions, RedisSessionOptions, SessionRedisClient, SessionRedisClientSourcetypeConfig and store contracts.
sessionStoreSupportsTaggingfunction(driver: SessionDriver): driver is SessionDriverWithTagging.
ReadOnlyValuesStore, ValuePathclass / typeThe flash messages store.

Errors ​

ExportKindDescription
ExceptionclassBase exception (@c9up/flare's, the one every package extends) with status, code, help, and optional handle() / report().
createErrorfunctioncreateError<T extends unknown[]>(message: string, code: string, status?: number): ErrorClass<T>; the class takes the %s values as an array: new E_X([value]).
ErrorClass, ExceptionClass, HttpError, StatusPageRenderertype
ExceptionHandlerclassRenders and reports errors; extend it in the app.
RuntimeException, InvalidArgumentsExceptionerrorE_RUNTIME_EXCEPTION, E_INVALID_ARGUMENTS_EXCEPTION.
errorsnamespaceThe package's errors, one class per code, see Errors: error instanceof errors.E_ROUTE_NOT_FOUND.
createPipelineError, validatePipelineConfig, PIPELINE_STAGES, PipelineStageNamefunction / const / typePipeline stage errors.
errorDocsUrl, DOCS_BASE_URLfunction / consterrorDocsUrl(code): the code's row in the error index.
ErrorBoundary, ErrorEvent, ErrorEmitter, ErrorSeverityclass / typeThe root error boundary.
renderError, parseStack, prettyPrintError, RenderOptions, StackFramefunction / typeError rendering for the terminal.
didYouMean, findClosestMatches, levenshteinfunctionSuggestions for a mistyped name.

Security ​

ExportKindDescription
CookieSignerclassSigns (sign / unsign) and encrypts (encrypt / decrypt, AES-256-GCM) values with APP_KEY (the encryption binding).
SignedUrl, SignedUrlConfigclass / interfaceSigned URLs (the signedUrl binding).
hmacSign, hmacVerify, constantTimeEq, randomBytesBase64, randomHexfunctionCrypto primitives, native when available.
hasNativeCrypto, setNapifunctionWhether the native crypto is loaded; replace it.

Events ​

ExportKindDescription
EmitterclassThe event emitter (the emitter binding).
BaseEventclassBase of class-based events: static dispatch(...args), emit().
EventsBuffer, BufferedEvent, BufferedEventName, EventFinderclass / typeWhat emitter.fake() returns, with its assertions.
ListenerClass, EmitterResolver, UnsubscribeFunction, AsyncUnsubscribeFunctiontype
defineEventsConfig, EventsConfigfunction / interfaceconfig/events.ts.

Scheduler ​

ExportKindDescription
SchedulerclassCron scheduler on a native ticker: register, unregister, start, stop, listTasks, nextRun, runTaskNow, getStats.
SchedulefunctionSchedule(cronExpr: string): MethodDecorator: runs a method on a cron schedule.
getScheduleMetadata, SCHEDULE_METADATA_KEY, ScheduleMetadatafunction / const / typeWhat @Schedule recorded.
ScheduleProvider, ScheduleProviderOptionsclass / interfaceRegisters the scheduler.
defineSchedulerConfig, SchedulerConfig, SchedulerOptionsfunction / interfaceconfig/scheduler.ts and the Scheduler options.
locks, MemoryLockBackend, RedisLockBackend, LockBackend, LockBackendFactory, LockRedisClient, LockRedisResolverconst / class / typeThe lock that keeps one instance of a task running.
StatsTracker, TaskInfo, TaskStats, RunTaskOutcome, ScheduleInvocation, ErrorReporterclass / typeTask listing and statistics.
ScheduleEvent, ScheduleEventSink, ScheduleTaskStartedEvent, ScheduleTaskCompletedEvent, ScheduleTaskFailedEvent, ScheduleTaskSkippedEventtypeTask lifecycle events.

APIs ​

ExportKindDescription
GraphQLEngine, GraphQLConfig, ResolverOptions, SelectionFieldclass / typeA GraphQL engine. GraphQLConfig: schemaPath, path, playground, debug, and the limits maxQueryBytes (100 000), maxDepth (12), maxComplexity (1000), maxErrors (100), maxFieldRepeats (10), maxMutationRepeats (1). ResolverOptions: guard/guards, role/roles, permissions, middleware (named middleware run before each call), maxRepeats. engine.resolveType(abstractType, fn) names the object type of an interface or union value.
GraphQLProvider, GraphQLProviderOptionsclass / interfaceMounts it.
OpenApiGenerator, OpenApiConfigclass / interfaceBuilds an OpenAPI document from the routes.
OpenApiMiddleware, OpenApiMiddlewareConfigclass / interfaceServes it.
OpenApiProvider, OpenApiProviderOptions, OpenApiDocsConfigclass / interfaceRegisters both.
HealthCheck, HealthCheckOptions, HealthChecker, HealthCheckResult, HealthStatusclass / typeA /health endpoint for liveness and readiness probes.

Console ​

ExportKindDescription
BaseCommandclassBase of a command.
args, flagsconstDecorators: @args.string(), @flags.boolean(), …
KernelclassThe console kernel.
HelpCommand, ListCommandclassThe built-in commands.
IndexGeneratorclassWrites the commands manifest.
FsLoader, ListLoaderclassCommand loaders.
ParserclassThe argv parser.
Prompt, PromptTrapclassPrompts, and scripted answers for tests.
ConsoleExceptionHandlerclassRenders a command's error.
Logger, UiclassTerminal output, from @c9up/lumen.
ArgumentMetaData, FlagMetaData, CommandClass, CommandInstance, CommandOptionsinterfaceCommand metadata.

Codemods and stubs ​

ExportKindDescription
createCodemodsfunctionThe API a package's configure() hook uses to edit the project.
Codemods, EnvValidationNode, EnvVarsOptions, GeneratedStub, MiddlewarePosition, PreloadEnvironmenttypeIts types.
compileStub, renderStub, escapeHtmlfunctionThe stub template engine.
StubState, StubValue, StubFunction, StubBlock, TemplateOptionstypeIts types.

Services and types ​

ExportKindDescription
setApp, setRouter, setServerfunctionSeat the instances behind the services/* modules.
AsyncOrSync, Constructor, Dict, ExtractFunctions, OneOrMore, Opaque, Prettify, UnwrapOpaquetypeType helpers.

Ignitor ​

ts
new Ignitor(appRoot?: URL | IgnitorConfig, config?: IgnitorConfig)
MemberSignatureDescription
useRcFileuseRcFile(reamrc: ReamrcConfig): IgnitorLoads reamrc.ts.
taptap(callback: (app: Application) => void): IgnitorReaches the application before start.
setEnvironment / getEnvironmentsetEnvironment(env: AppEnvironment): Ignitor
routesroutes(callback: (router: Router) => void): IgnitorDeclares routes inline.
useuse(mw: MiddlewareFunction): IgnitorAdds a global middleware inline.
namednamed(name: string, mw: MiddlewareFunction): IgnitorRegisters a named middleware inline.
providerprovider(factory: (app: Application) => ProviderContract): IgnitorRegisters a provider inline.
configureconfigure(key: string, value: unknown): IgnitorSets a config value.
onErroronError(listener: (event: ErrorEvent) => void): IgnitorListens for error events.
httpServerhttpServer(): IgnitorHTTP server mode.
consoleconsole(): ConsoleKernelConsole mode.
testModetestMode(): IgnitorTest mode.
warmUpwarmUp(): Promise<Ignitor>Assembles the application without running it.
startstart(): Promise<Ignitor>Boots and, in HTTP mode, listens.
stopstop(): Promise<void>Graceful shutdown; every step runs even when one throws.
port / hostport(): Promise<number> / host(): string | undefinedThe bound address.
consoleAppconsoleApp(): Promise<Console>The programmatic console.
getApp, getRouter, getServer, getRcFile, getAppRoot, getImporterAccessors.
getKernelgetKernel(): (request) => Promise<response>The request handler, for serverless use and tests.
isStarted, isDevMode, getPhaseState.

Application ​

ts
new Application(options: ApplicationOptions)
MemberSignatureDescription
containercontainer: Container
configconfig: ConfigStore
appRootappRoot: URL | undefinedThe project root.
makePath / makeURLmakePath(...paths: string[]): stringA path (or URL) inside the project root.
relativePathrelativePath(absolutePath: string): string
configPath, startPath, tmpPath, publicPath, providersPath, commandsPath, contractsPath, migrationsPath, seedersPath, factoriesPath, languageFilesPath, viewsPath, httpControllersPath, modelsPath, servicesPath, exceptionsPath, mailersPath, mailsPath, middlewarePath, policiesPath, validatorsPath, eventsPath, listenersPath, transformersPath, generatedClientPath, generatedServerPath(...paths: string[]): stringA path inside each conventional directory.
directoriesdirectories: DirectoriesNodeThe layout, reamrc.ts overrides included.
rcFilercFile: ReamrcContentsThe parsed rc file.
getEnvironment / setEnvironmentgetEnvironment(): AppEnvironmentweb, console, test, repl or unknown.
getMode / setModegetMode(): ApplicationModerun or warmup; set only before boot.
getStategetState(): ApplicationStateWhere the application is in its lifecycle.
nodeEnvironmentnodeEnvironment: stringThe normalised NODE_ENV, or 'unknown'.
inProduction, inDev, inTest, managedByPm2boolean
isBooted, isReady, isTerminating, isTerminatedboolean
appName, versionstring | undefinedFrom the app's package.json.
usingInkerbooleanWhether @c9up/inker is installed.
booting / bootedbooting(callback: () => void | Promise<void>): voidHooks around provider boot.
starting / readystarting(handler: ApplicationHook): ApplicationHooks before the server starts, and once it is ready.
terminating / onShutdownterminating(callback: () => void | Promise<void>): voidHooks when shutdown begins.
registerregister(provider: ProviderContract): voidRegisters a provider instance.
bootboot(): Promise<void>Boots every provider.
terminate / shutdownterminate(): Promise<void>Graceful shutdown; providers shut down in reverse order.
providers, providerCountThe registered providers.
importimport(moduleIdentifier: string): Promise<unknown>Imports a module through the app's importer.
importDefaultimportDefault<T>(moduleIdentifier: string): Promise<T>Its default export.
listen, listenOnce, listenIf, listenOnceIflisten(signal: Signals, callback: () => void): voidProcess signals.
notifynotify(message: unknown, callback?): voidTells the process supervisor a state was reached.
toJSONtoJSON(){ appName, version, environment, nodeEnvironment, state, isReady, isTerminating }.

Provider ​

ts
class Provider {
  constructor(app: AppContext)
  register(): void           // bind into the container (synchronous)
  boot(): Promise<void>      // set the framework up
  start(): Promise<void>     // before the HTTP server starts
  ready(): Promise<void>     // once the server is listening
  shutdown(): Promise<void>  // in reverse order
}

Container ​

ts
new Container(options?: ContainerOptions)
MemberSignatureDescription
singletonsingleton(token: ServiceToken, factory: ServiceFactory): voidBuilt once, then cached.
bindbind(token: ServiceToken, factory: ServiceFactory): voidBuilt on every resolution.
bindValuebindValue<T>(token: ServiceToken, value: T): voidAn existing value.
aliasalias(alias: ServiceToken, target: ServiceToken): void
make / resolvemake<T>(token: ServiceToken, runtimeValues?: unknown[]): Promise<T>Resolves or constructs.
callcall(instance, method, runtimeValues?): Promise<unknown>Calls a method with its dependencies injected.
whenwhen(parent).asksFor(token).provide(factory)A contextual binding for one class.
contextualBindingcontextualBinding(parent, binding: ServiceToken, factory: ServiceFactory): voidSame, in one call.
if / conditionalBindingif(condition: BindingCondition): ConditionalBindingsBuilderA binding for the resolutions where condition holds.
resolvingresolving(token: ServiceToken, callback: (value) => void | Promise<void>): voidRuns each time token is constructed.
swapswap(token: ServiceToken, factory: ServiceFactory): voidReplaces a binding, for tests.
overrideoverride<T>(token: ServiceToken, value: T): voidReplaces a binding with a value, for tests.
restore / restoreAllrestore(token?: ServiceToken): voidUndoes swaps. A token holds one swap: restore(token) removes it outright.
swappedswapped(token: ServiceToken): ServiceFactory | undefinedThe factory swapped in for token, without running it; undefined when it is not swapped. Put it back later with swap(token, previous).
createResolvercreateResolver(): ContainerResolverA resolver with its own scoped values.
runWithScopedValuesrunWithScopedValues<T>(values: ReadonlyMap<ServiceToken, unknown>, fn: () => Promise<T>): Promise<T>
has / hasBinding / hasAllBindingshas(token: ServiceToken): booleanResolvable / explicitly bound / all of them.
bindingsreadonly { token, scope, target? }[]Every token, sorted.
useEmitteruseEmitter(emitter: ContainerEmitter): ContainerEmits container_binding:resolved after each resolution.
sizenumber

HttpContext ​

MemberSignatureDescription
requestRequest
responseResponse
paramsMatchedParamsRoute parameters.
routeRouteInfoThe matched route.
routeKeystringMETHOD-pattern of the matched route.
subdomainsRecord<string, string>What the route's domain captured from the host.
idstringThe request id.
authAuthStateSet by an auth middleware.
bouncerAuthorizer | undefinedSet by an authorization middleware.
sessionSession | undefinedSet by SessionMiddleware.
eventsEmitter | undefinedWhen EventsProvider is registered.
loggerContextLoggerThe request's logger.
localestringFrom Accept-Language.
storeMap<string, unknown>Per-request values for middleware.
containerResolverContainerResolver | undefinedPer-request resolver.
inspectinspect(): stringA one-line summary.
HttpContext.getstatic get(): HttpContext | nullThe ambient context, or null outside a request.
HttpContext.getOrFailstatic getOrFail(): HttpContextThrows E_HTTP_CONTEXT_NOT_FOUND outside a request.
HttpContext.runstatic run<T>(ctx: HttpContext, fn: () => T): T
HttpContext.runOutsideContextstatic runOutsideContext<T>(fn: () => T): T
HttpContext.useAsyncLocalStoragestatic useAsyncLocalStorage(enabled: boolean): voidTurns ambient tracking on or off.
HttpContext.macro / getterstatic macro(name: string, fn: MacroFn): voidExtends every context.

Request ​

MemberSignatureDescription
methodmethod(): stringThe method the route was matched with: with http.allowMethodSpoofing on, a POST takes the _method of its query string (?_method=DELETE). A _method in the body is never read.
intendedintended(): stringThe real method.
urlurl(includeQs?: boolean): stringThe pathname, with the query string on request.
completeUrlcompleteUrl(includeQueryString?: boolean): stringprotocol://host/path.
pathpath(): string
parsedUrlparsedUrl(): { pathname, search, query }
ip / ipsip(): string / ips(): string[]Client address, through trusted proxies.
protocol / secureprotocol(): string / secure(): boolean
host, hostname, authority, subdomainshost(): string | null
headerheader(key: string, defaultValue?: string): string | undefined
headersheaders(): Readonly<Dict>
idid(): string | undefinedx-request-id.
param / paramsparam(key: string, defaultValue?: string): string | undefinedRoute parameters.
qsqs(): Dict<unknown>The parsed query string.
bodybody(): unknownThe parsed body.
allall(): Dict<unknown>Query string merged with body.
inputinput<T>(key: string, defaultValue?: T): TOne input value, dot notation accepted.
only / exceptonly(keys: string[]): Dict<unknown>
originaloriginal(): Dict<unknown>The input as received.
raw / rawBufferraw(): string / rawBuffer(): BufferThe raw body.
hasBodyhasBody(): boolean
updateBody, updateQs, updateRawBodyupdateBody(body: Dict<unknown>): voidReplace the input, for a middleware.
validateUsingvalidateUsing<T>(validator: RequestAwareValidator<T>, options?): Promise<T>Throws E_VALIDATION_ERROR on failure.
tryValidateUsingtryValidateUsing<T>(validator, options?): Promise<[unknown, null] | [null, T]>
validatedvalidated(): unknownWhat the route's .validate() produced.
filefile(key: string, options?: FileValidationOptions): MultipartFile | nullOne upload.
filesfiles(key: string, options?: FileValidationOptions): MultipartFile[]Every upload under a key.
allFilesallFiles(): Record<string, unknown>
cookiecookie(name: string, defaultValue?: string): string | nullA signed cookie.
plainCookieplainCookie<T>(name: string, defaultValue?: T, options?: { encoded?: boolean }): T | null
encryptedCookieencryptedCookie(name: string, defaultValue?: string): string | null
cookies / cookiesListcookies(): Dict
hasValidSignaturehasValidSignature(purpose?: string): booleanVerifies a signed URL over the exact path the router matched and its query.
isis(types: string[]): string | nullMatches the content type.
accepts, language, charset, encodingaccepts<T extends string>(types: T[]): T | nullContent negotiation.
types, languages, charsets, encodingstypes(): string[]Everything the client accepts, best first.
fresh / stalefresh(): booleanWhether the client's cached copy is still fresh.
ajax, pjax, prefetchajax(): boolean
matchesRoutematchesRoute(identifier: string | string[]): booleanBy route name, pattern or controller reference.
upgradesToWebSocketupgradesToWebSocket(): boolean
getPreviousUrlgetPreviousUrl(allowedHosts?: string[], fallback?: string): stringThe Referer, when it is an allowed host.
csrfToken, csrfProtectedSet by the CSRF middleware.
serialize / toJSON / serializeSafeserialize(): Record<string, unknown>A JSON view; serializeSafe is fit for logs.

Response ​

MemberSignatureDescription
status / safeStatusstatus(code: number): ResponsesafeStatus sets it only if still 200.
header, append, safeHeader, removeHeaderheader(key: string, value: string): Response
varyvary(field: string | string[]): Response
typetype(type: string, charset?: string): Response
locationlocation(url: string): Response
sendsend(data: unknown): voidThe content type is detected when unset.
jsonjson(data: unknown): void
jsonpjsonp(body: unknown, callbackName?: string): voidSends X-Content-Type-Options: nosniff.
sendBuffersendBuffer(buffer: Buffer): void
streamstream(body: ReadableStream, errorCallback?): Promise<void>
downloaddownload(filePath: string, generateEtag?: boolean, errorCallback?): void
attachmentattachment(filePath: string, name?: string, disposition?: string, generateEtag?: boolean): voidWith Content-Disposition.
ssesse(options?: SseStreamOptions): Promise<SseStream>Opens a server-sent events stream.
redirectredirect(): RedirectBuilder / redirect(path: string, forwardQueryString?: boolean, statusCode?: number): void
cookiecookie(name: string, value: string, options?: CookieOptions): ResponseSigned.
plainCookieplainCookie(name: string, value: unknown, options?): ResponseUnsigned.
encryptedCookieencryptedCookie(name: string, value: string, options?): ResponseAES-256-GCM.
clearCookieclearCookie(name: string, options?): Response
setEtagsetEtag(body: string | Buffer, weak?: boolean): Response
freshfresh(): boolean
abortabort(body: unknown, status?: number): neverThrows E_HTTP_REQUEST_ABORTED (400 by default), built by E_HTTP_EXCEPTION.invoke(): its code is E_HTTP_EXCEPTION.
abortIf / abortUnlessabortIf(condition: unknown, body: unknown, status?: number)
setRequestIdsetRequestId(): ResponseEchoes x-request-id.
onFinishonFinish(callback: (err: Error | null) => void): void
noContent, continue, switchingProtocols(): void204, 100, 101.
ok, created, accepted, nonAuthoritativeInformation, resetContent, partialContent(body?: unknown): void200 to 206.
multipleChoices, movedPermanently, movedTemporarily, seeOther, notModified, useProxy, temporaryRedirect(body?: unknown): void300 to 307.
badRequest, unauthorized, paymentRequired, forbidden, notFound, methodNotAllowed, notAcceptable, proxyAuthenticationRequired, requestTimeout, conflict, gone, lengthRequired, preconditionFailed, requestEntityTooLarge, requestUriTooLong, unsupportedMediaType, requestedRangeNotSatisfiable, expectationFailed, unprocessableEntity, tooManyRequests(body?: unknown): void400 to 429.
internalServerError, notImplemented, badGateway, serviceUnavailable, gatewayTimeout, httpVersionNotSupported(body?: unknown): void500 to 505.
getStatus, getHeaders, getHeader, getBodyRead what was set.
finished, headersSent, isPending, hasContent, hasStream, hasLazyBodyboolean
noncestring | undefinedThe CSP nonce of the request.

Router ​

MemberSignatureDescription
get, post, put, patch, delete, head, optionsget(path: string, handler: RouteHandler): RouteBuilder
anyany(path: string, handler: RouteHandler): RouteBuilderEvery method.
routeroute(pattern: string, methods: string | string[], handler: RouteHandler): RouteBuilder
wsws(path: string, handler: WebSocketRouteHandler): RouteBuilderA WebSocket route.
resource / shallowResourceresource(path: string, controller): RouteResource
groupgroup(callback: () => void): GroupBuilderAlso group(config, callback).
onon(path: string): OnRouteBuilder
wherewhere(param: string, matcher: string | ParamMatcher): RouterA matcher for every route.
matchers{ number(), uuid(), slug() }
useuse(middleware: LazyImport<MiddlewareClassConstructor>[]): RouterRouter middleware: runs on matched routes.
namednamed<Name extends string>(collection: Record<Name, MiddlewareEntry>): Record<Name, (args?) => MiddlewareFunction>Named middleware: one factory per name of the collection. Routes and groups also reach them by name, .middleware('auth'); RPC methods and GraphQL resolvers too.
getNamedMiddleware / getNamedMiddlewareNamesgetNamedMiddleware(name: string): MiddlewareFunction | undefinedWhat named() declared, by name, run with no arguments; and the list of names.
controllerscontrollers(map: Record<string, LazyControllerImport>): RouterControllers referenced by string.
urlFor / makeUrlurlFor(name: string, params?: Record<string, string>): string
makeSignedUrlmakeSignedUrl(name: string, params?, options?: SignedUrlOptions): string
builder / urlBuilder / builderForDomainbuilder(): UrlBuilder
namedManifestnamedManifest(): Record<string, string>Name to pattern, for clients.
namedRoutesnamedRoutes(): Record<string, { path; methods }>
generateTypesgenerateTypes(): stringTypeScript types of the named routes.
find / findOrFail / hasfind(identifier: string): RouteDefinition | nullBy name or pattern.
matchmatch(method: string, path: string, host?: string, options?): MatchResult | undefined
getRoutesgetRoutes(): RouteDefinition[]
parsePatternparsePattern(pattern: string): { name; optional }[]
commit / commitedcommit(): voidFreezes the table and builds the index.
toJSON, usingDomains, routeCount, clear

RouteBuilder ​

MemberSignatureDescription
asas(name: string): RouteBuilderNames the route.
prefixprefix(prefix: string): RouteBuilder
middlewaremiddleware(...names: string[]): RouteBuilderNamed middleware, by the names router.named() declared, run with no arguments (pass arguments with .use(middleware.auth(args))). A name nothing declares stops the application when the kernel is built: E_MIDDLEWARE_NOT_FOUND.
useuse(...mw: MiddlewareFunction[]): RouteBuilderInline middleware.
guardguard(...guards: string[]): RouteBuilderAuthentication by one of the guards; each call adds a level.
role / permissionrole(...roles: string[]): RouteBuilderrole needs one of its roles; each call adds a requirement. permission needs every one.
wherewhere(param: string, matcher: string | ParamMatcher): RouteBuilder
validatevalidate(validator: string): RouteBuilderValidates the body with a named validator.
domaindomain(d: string): RouteBuilder
versionversion(v: string): RouteBuilder
deprecatesdeprecates(version: string, options?: { sunset?: string }): RouteBuilder
getName, getPattern, setPattern, getHandler, getMiddleware, getDefinition, markAsDeleted, isDeleted, toJSON

GroupBuilder ​

prefix(p), as(namePrefix), middleware(...names), use(...mw), guard(...guards), role(...roles), permission(...permissions), domain(d), where(param, matcher), each returning the group; routes lists its routes. permission adds the group's permissions to each route's own. guard and role each add a level of their own: the request must be authenticated by a guard the group AND every route level name, and the user needs one of the group's roles AND one of each route-level list. group({ guards, roles, permissions }, callback) does the same.

RouteResource ​

only(actions), except(actions), apiOnly(), where(key, matcher), params(resources), use(actions, middleware) (alias middleware), as(name, normalizeName?), tap(callback) / tap(actions, callback), each returning the resource; routes lists the generated RouteBuilders.

Server ​

MemberSignatureDescription
useuse(middleware: MiddlewareEntry[]): ServerGlobal middleware.
errorHandlererrorHandler(handler: LazyImport<ErrorHandlerClass>): Server
trustedProxiestrustedProxies(cidrs: string[]): Server
grpcgrpc(handler: GrpcHandler, limits?: GrpcLimits): ServerServes gRPC on the HTTP port.
supportsWebSocketssupportsWebSockets(): boolean
getRouter, getErrorHandler, getServerMiddleware, getTrustedProxies, getGrpcHandler, getGrpcLimits

Session ​

MemberSignatureDescription
getget<T>(key: string, defaultValue?: T): T
putput(key: string, value: unknown): void
has, all, forget, pull, clear
increment / decrementincrement(key: string, amount?: number): void
flashflash(key: string | Record<string, unknown>, value?: unknown): voidFor the next request only.
flashAll, flashOnly, flashExceptflashOnly(keys: string[]): voidFlash the request input.
flashErrorsflashErrors(errors: Record<string, string | string[]>): void
flashValidationErrorsflashValidationErrors(error, withInput?: boolean): voidFlashes the input without the password fields, _csrf and _method.
reflash, reflashOnly, reflashExceptKeep the previous flash data.
flashMessagesReadOnlyValuesStoreWhat the previous request flashed.
oldold<T>(key: string, defaultValue?: T): TOne previous flash value.
regenerateregenerate(): voidRotates the id, keeping the data.
sessionId, fresh, isEmpty, readonly, revocable
setIntendedUrl, getIntendedUrl, pullIntendedUrl, clearIntendedUrlWhere the user was heading.
supportsTaggingsupportsTagging(): boolean
tag / untagtag(userId: string | number): Promise<void>Links the session to a user. A session created or regenerated in the request is tagged when it is saved.

Env ​

MemberSignatureDescription
Env.createstatic create(appRoot: URL, schema): Promise<Env<…>>Loads .env*, validates, and returns a typed reader. Throws E_INVALID_ENV_VARIABLES.
Env.schemastring, number, boolean, enum, secretEach with .optional() and .optionalWhen(condition). string takes { format: 'host' | 'url' | 'email' | 'uuid' }.
Env.rulesstatic rules(schema): { validate(values) }A reusable validator.
Env.defineIdentifier / defineIdentifierIfMissing / removeIdentifierstatic defineIdentifier(name: string, resolver): voidInterpolation identifiers such as file:.
getget(key, fallback?)Typed by the schema.
setset(key, value): void

Exception ​

ts
class Exception extends Error {
  constructor(message: string, options?: { status?: number; code?: string })
  static status: number
  static code: string
  static help?: string
  status: number
  code: string
  help?: string
  handle?(error: Exception, ctx: HttpContext): void | Promise<void>
  report?(error: Exception, ctx: HttpContext): void | Promise<void>
}

ExceptionHandler ​

ts
new ExceptionHandler(debug: boolean)

handle(error, ctx), report(error, ctx), and the renderers it picks by content negotiation: renderError, renderErrorAsJSON, renderErrorAsJSONAPI, renderErrorAsHTML, renderValidationError, renderValidationErrorAsJSON, renderValidationErrorAsJSONAPI, renderValidationErrorAsHTML.

Emitter ​

MemberSignatureDescription
onon(event: string | EventClass, listener): UnsubscribeFunction
onceonce(event, listener): void
listenIflistenIf(condition: boolean | (() => boolean), event, listener): UnsubscribeFunction
listenlisten(event, listeners: (ListenerClass | LazyListenerImport)[]): voidSeveral listener classes.
emitemit(event: string, data: unknown): Promise<void>
emitSerialemitSerial(event: string, data: unknown): Promise<void>Listeners one at a time.
dispatchEventdispatchEvent<T extends object>(event: T): Promise<void>A class-based event.
onAny / offAnyonAny(pattern?: string, listener): Promise<AsyncUnsubscribeFunction>Wildcard subscription.
taptap(observer: (event: string, data: unknown) => void): UnsubscribeFunctionWatches every emission.
off, clearListener, clearListeners, clearAllListeners
listenerCount, hasListeners, eventsListeners
onErroronError(listener: (event: string, error: unknown) => void): voidListener failures.
fake / restorefake(events?: BufferedEventName[]): EventsBufferCaptures events instead of delivering them.
request / onRequestrequest<T>(name: string, data: unknown, timeoutMs?: number): Promise<T>Request and reply over the bus.
setCorrelationId, getCorrelationId, clearCorrelationIdCorrelation id of the current async context.

BaseCommand ​

MemberSignatureDescription
commandNamestatic commandName: string
descriptionstatic description: string
aliasesstatic aliases: readonly string[]
helpstatic help?: string | string[]
optionsstatic options: CommandOptionsstartApp, staysAlive, allowUnknownFlags, …
defineArgument / defineFlagstatic defineArgument(name: string, options?): voidWithout a decorator.
runrun(...args): unknownThe command body.
prepare, interact, completedLifecycle hooks around run().
terminateterminate(): Promise<void>Ends a staysAlive command.
logger, ui, colors, promptOutput and prompts.
appApplicationWith startApp: true.
kernel, parsed, isMain
exitCodenumber | undefinedA non-zero exit without throwing.
result, errorFilled after the run.
execexec(): Promise<unknown>Hydrates, then runs.
assertSucceeded, assertFailed, assertExitCode, assertNotExitCode, assertLog, assertLogMatches, assertTableRowsAssertions for tests.

@c9up/ream/types ​

ExportKindDescription
ContainerBindingsinterfaceThe string tokens the container resolves, with their types. A package adds its own by augmenting it.
ContainerBindingtypekeyof ContainerBindings.
AuthenticatorsinterfaceThe guards of the application, augmented by the auth config.
AuthenticatorNametypekeyof Authenticators.

@c9up/ream/exceptions ​

Exception, createError, ErrorClass, RuntimeException, InvalidArgumentsException, E_ROUTE_NOT_FOUND, E_UNAUTHORIZED_ACCESS, E_AUTHORIZATION_FAILURE, E_WARDEN_MFA_REQUIRED, E_VALIDATION_ERROR, E_HTTP_EXCEPTION, E_HTTP_REQUEST_ABORTED, HttpError, StatusPageRenderer, ExceptionClass, ExceptionHandler: the same as in @c9up/ream.

@c9up/ream/env ​

ExportKindDescription
loadEnvFilesfunctionloadEnvFiles(appRoot: URL, options?: { skipEnvLocal?: boolean }): Promise<void>: loads the .env* files into process.env; an existing key is never overwritten.
envFileNamesfunctionenvFileNames(options?: { skipEnvLocal?: boolean }): string[]: the files read, most specific first.

@c9up/ream/bootstrap ​

ExportKindDescription
createHyperServerFactoryfunctioncreateHyperServerFactory(): (port: number, host?: string) => HyperServerLike: the native server for this platform. There is no JavaScript server to fall back to: it throws E_REAM_NAPI_NOT_FOUND when the binary is missing, E_REAM_NAPI_LOAD_FAILED when it is there but does not load (cause is the load error), and E_REAM_NAPI_UNSUPPORTED_PLATFORM on a platform with no binary.

@c9up/ream/hot and @c9up/ream/dev/hmr ​

@c9up/ream/hot exports nothing: ream dev loads it with --import before bin/server.ts. It watches the import graph and swaps a changed module in the running process.

Export (dev/hmr)KindDescription
HMR_PATHconst"/__ream/hmr".
hmrEndpointfunctionThe middleware that answers the browser's reload stream.
hmrClientScriptfunctionhmrClientScript(nonce?: string): string: the script injected into HTML pages in development.
hmrTokenfunctionhmrToken(): string: changes on a restart and on a hot swap.
hotReloadCountfunctionhotReloadCount(): number.
hotReloadHappenedfunctionhotReloadHappened(): void: called when a module was swapped.

@c9up/ream/services/* ​

Each module's default export is the live instance of the running application, through a proxy that throws when it is used before the application seats it.

ImportDefault exportOther exports
services/appApplicationsetApp, clearApp, getApp
services/configConfigStore
services/routerRoutersetRouter, clearRouter, getRouter
services/serverServersetServer, clearServer, getServer
services/loggerthe app loggersetLogger, clearLogger, getLogger
services/encryptionCookieSignersetEncryption, clearEncryption, getEncryption
services/consoleConsolesetConsole, clearConsole
services/dumperDumperdd(value: unknown): never
services/replRepl
services/urlBuilderurlFor(name, params?), signedUrlFor(name, params?, options?)
events/services/mainEmittersetEmitter, getEmitter

@c9up/ream/dumper ​

ExportKindDescription
DumperclassdumpToAnsi(value, options?), dumpToHtml(value, options?), getHeadElements(cspNonce?), dd(value), configureAnsiOutput(config), configureHtmlOutput(config).
ConsoleDumpConfig, HTMLDumpConfig, DumpSourceinterfaceRendering options; where a dump was written.
errorsnamespaceE_DUMP_DIE_EXCEPTION.

dd() stops a request with an HTML dump, or a command with a printed one.

@c9up/ream/repl ​

ExportKindDescription
Replclassstart(context?), addMethod(name, handler, options?), ready(callback), useCompiler(compiler), notify(message), getMethods(), describeMethods(), server.
ReplConstructorOptions, MethodCallback, MethodOptions, Compilertype

@c9up/ream/bodyparser, @c9up/ream/bodyparser_middleware, @c9up/ream/bodyparser/config ​

The middleware class is the default export; BodyParserConfig is its config type; bodyparser/config exports defineConfig(config: BodyParserConfig): BodyParserConfig. Options under Configuration.

@c9up/ream/session, @c9up/ream/session_middleware, @c9up/ream/session/config ​

The session middleware class is the default export. session/config exports defineConfig(config: SessionConfigInput): SessionConfigInput, which validates the config, and SessionConfigInput (SessionConfig plus secret, required by the cookie store).

@c9up/ream/events and its subpaths ​

ImportExports
eventsEmitter, BaseEvent, EventsBuffer, EventsProvider, defineConfig, EventsConfig, ListenerClass, BufferedEvent, BufferedEventName, EventFinder, UnsubscribeFunction, AsyncUnsubscribeFunction, ContainerResolver (the resolver shape listeners are built with), EventBus, EventsAppContext.
events/providerEventsProvider (default): builds the bus and binds emitter.
events/configdefineConfig, checkEventsConfig(config: unknown): EventsConfig, EventsConfig.
events/testingFakeBus: captures emits and requests (CapturedEmit, CapturedRequest, FakeBusPredicate, FakeBusPredicateArg, FakeBusRequestHandler).
events/helixcollect(bus, pattern), fake(bus, pattern), assertEmitted(events, name, payload?), assertNotEmitted(events, name), waitForEvent(events, name, options?), waitForChain(events, correlationId, names, options?), and CollectedEvent, CollectResult, WaitForEventOptions, WaitForChainOptions.

@c9up/ream/scheduler/provider, @c9up/ream/scheduler/config ​

ScheduleProvider (default export) registers the Scheduler and the @Schedule methods; ScheduleProviderOptions takes a scheduler to inject. scheduler/config exports defineConfig(config: SchedulerConfig): SchedulerConfig, SchedulerConfig, LockBackend, LockBackendFactory, and locks:

ts
locks.memory(): LockBackendFactory
locks.redis(options: { connection: string | LockRedisResolver; prefix?: string }): LockBackendFactory

@c9up/ream/rpc/provider, @c9up/ream/rpc/router ​

RpcProvider (default export) mounts the JSON-RPC endpoint. RpcProviderOptions: path (default /rpc), guards, contentTypes, router; RpcConfig: webSocket?: boolean | RpcWebSocketOptions serves the methods over a WebSocket on the same path.

RpcRouter memberSignatureDescription
methodmethod(name: string, handler: RpcHandler): RpcMethodBuilderNames starting with rpc. are reserved.
namespacenamespace<T>(prefix: string, controller, methods: readonly ControllerMethodName<T>[]): voidRegisters controller methods as <prefix>.<method>.
groupgroup(config: { guard?; guards?; middleware? }, callback: (rpc: RpcRouter) => void): void
handlehandle(ctx: HttpContext): Promise<void>Answers one JSON-RPC request or batch.
webSocketwebSocket(options?: RpcWebSocketOptions): (ctx: WebSocketContext) => voidmaxInFlight, maxQueued.
useContaineruseContainer(container): voidResolves namespace controllers.
getMethods / getMethodgetMethods(): string[]

RpcMethodBuilder: guard, role, permission, validate, middleware. Also exported: RpcHandler, RpcMethodDefinition, RpcRouterOptions, RpcWebSocketOptions, ControllerMethodName.

@c9up/ream/graphql/provider, @c9up/ream/openapi/provider, @c9up/ream/storage/provider ​

ProviderOptions
GraphQLProvider (default)GraphQLProviderOptions: engine to inject.
OpenApiProvider (default)OpenApiDocsConfig: enabled (default: on except in production), guards, middleware (names or functions), specPath (default /api-docs), docsPath (Swagger UI, default /docs), title (default 'API'), version (default '1.0.0'). OpenApiProviderOptions: generator to inject.
StaticProvider (default)StaticProviderOptions: middleware to inject.

@c9up/ream/health ​

ExportKindDescription
HealthChecksclassregister(checks), append(checks), run(): Promise<HealthCheckReport>: runs every check concurrently.
BaseCheckclassThe base of a check.
DiskSpaceCheck, MemoryHeapCheck, MemoryRSSCheckclassBuilt-in checks.
ResultclassBuilds a check result.
HealthCheckContract, HealthCheckReport, HealthCheckResult, HealthCheckTracingDatatypeA report's isHealthy is false as soon as one check reports error.
tracingChannelsnamespaceDiagnostics channels around each check.

@c9up/ream/http-client ​

ExportKindDescription
HttpClientclassget, post, put, patch, delete, request(input, options?), close(). Refuses non-public addresses.
HttpResponseclassstatus, headers, url, body, ok, header(name), text(), json().
HttpClientOptions, HttpRequestOptions, OutgoingRequestinterface
fakeHttpfunctionfakeHttp(options?: HttpClientOptions): FakeHttpClient.
FakeHttpClientclasson(method, match, response), onAny(match, response), requests, reset().
FakeMatcher, FakeResponse, RecordedRequesttype
isPublicAddressfunctionisPublicAddress(address: string): boolean.

A failed request throws one of errors.E_HTTP_CLIENT_INVALID_URL, E_HTTP_CLIENT_PRIVATE_ADDRESS, E_HTTP_CLIENT_UNREACHABLE, E_HTTP_CLIENT_TIMED_OUT, E_HTTP_CLIENT_TOO_LARGE or E_HTTP_CLIENT_REDIRECT_REFUSED (errors of @c9up/ream); each carries url, the URL asked for without its query string.

HttpClientOptions: timeout (ms, default 10000, redirects included), maxResponseBytes (default 5 MiB), maxRedirects (default 3), crossHostRedirects (default false), userAgent (default @c9up/ream), headers, allowHosts (hosts exempt from the public-address rule). HttpRequestOptions: method, headers, body, json, signal, timeout, maxResponseBytes.

@c9up/ream/console ​

Everything under Console above, plus: Console, ConsoleOptions, ExceptionHandler (the console one), TaskContext, Tasks, Table, Box, Action, Colors, StyleName, TaskOutcome (from @c9up/lumen), ArgumentOptions, FlagOptions, CommandsManifest, CommandExecutor, CommandLoader, ErrorRenderer, GlobalFlagListener, HandleResult, KernelOptions, KernelState, serializeCommand, ParseOptions, parseArgv, PromptOptions, BooleanPromptOptions, MultiplePromptOptions, SelectPromptOptions, PromptChoice, commandExec (tracing channel), ExecutedCommand, ParsedInput, isCommandClass, renderErrorWithSuggestions, sortAlphabetically, validateCommand, validateCommandMetaData.

@c9up/ream/commands ​

A command loader: getMetaData(): Promise<SerializedCommand[]> and getCommand(metadata): Promise<CommandClass | null>, over migrate, migrate:rollback, migrate:status, schedule:list and schedule:run.

@c9up/ream/stubs ​

ExportKindDescription
stubsRootconst<package>/stubs: the make: stubs.
compilefunctioncompile(input: string, options?: TemplateOptions): (state: StubState) => string.
renderfunctionrender(input: string, state?: StubState, options?: TemplateOptions): string.
escapeHtmlfunctionescapeHtml(value: unknown): string.
StubValue, StubFunction, StubState, StubBlock, TemplateOptionstype

@c9up/ream/helpers ​

ExportKindDescription
stringconstString helpers (below), plus bytes, milliseconds and seconds.
isconstType checks (below).
base64constencode, decode, urlEncode, urlDecode; a decode returns null on bad input.
SecretclassA value that prints as [redacted].
safeEqualfunctionsafeEqual(a: string | Buffer, b: string | Buffer): boolean: constant-time comparison.
safeTimingfunctionsafeTiming<T>(minimumMs: number, callback: (timing: { returnEarly(): void }) => Promise<T>): Promise<T>: never returns before minimumMs.
composefunctioncompose(superclass, ...mixins): applies mixins to a base class.
defineStaticPropertyfunctiondefineStaticProperty<T>(target, propertyName, { initialValue, strategy: 'inherit' | 'define' | ((value: T) => T) }): gives a subclass its own copy of an inherited static.
milliseconds, secondsconstparse(duration: string | number): number and format(value: number, long?: boolean): string.
MessageBuilderclassBuilds and verifies a message envelope with a purpose and an expiry.
VerificationTokenclassAbstract base of single-use tokens (<identifier>.<secret>, only the SHA-256 of the secret stored); subclass it to add persistence.
fsReadAll, fsImportAll, ReadAllFilesOptions, ImportAllFilesOptionsfunction / typeRead or import every file of a directory.
isString, isNumber, … hasPropertyfunctionThe is functions, also exported one by one.
the type helperstypeAs in helpers/types.

@c9up/ream/helpers/string (also the default export): camelCase, snakeCase, pascalCase, dashCase, dotCase, noCase, titleCase, capitalCase, sentenceCase, sentence, toSentence, wordWrap, justify, truncate, excerpt, condenseWhitespace, slug, plural, pluralize, singular, isPlural, isSingular, ordinal, ordinalize, humanize, htmlEscape, escapeHTML, encodeSymbols, interpolate, isEmpty, uuid, random, generateRandom, prettyHrTime, toUnixSlash.

@c9up/ream/helpers/is (also the default export): isString, isNumber, isBoolean, isFunction, isObject, isPlainObject, isArray, isPromise, isNull, isUndefined, isNullOrUndefined, isBuffer, isDate, isRegExp, isError, isEmpty, isNonEmptyString, isNonEmptyArray, isInteger, isPositive, hasProperty.

@c9up/ream/helpers/types: InferRouteParams, OneOrMore, Opaque, UnwrapOpaque, AsyncOrSync, Constructor, AbstractConstructor, ExtractFunctions, Prettify, ExtractUndefined, ExtractDefined, LazyImport, UnWrapLazyImport, UnwrapPromise, MakeOptional, MakeRequired, MakeNullable, DeepPartial, DeepRequired, DeepReadonly, EmptyObject, ExtractKeysOfType, AllOf, NoneOf, TypeGuard, Brand.

@c9up/ream/helpers/base64: base64. @c9up/ream/helpers/fs: fsReadAll, fsImportAll, ReadAllPathType, ReadAllFilesOptions, ImportAllFilesOptions.

@c9up/ream/testing ​

ExportKindDescription
TestClientclassAn HTTP client over the app booted on a random port.
createTestClientfunctioncreateTestClient(bootFn, options?: { auth?: AuthStrategy }): Promise<TestClient>: creates and boots one.
RequestBuilderclassOne request: awaitable, with chained assertions.
ApiResponseclassThe response, with assertions.
TestWebSocket, TestWebSocketOptions, TestWebSocketCloseclass / typeclient.ws(path).
AuthStrategy, AuthSubjectinterfaceHow withAuth() / asUser() authenticate.
RouteManifest, RouteEntry, resolveNamedRoutetype / functionNamed routes for visit().
HttpMethod, HttpSender, QueryParams, TestResponsetype
parseHttpResponsefunctionparseHttpResponse(raw: string | Buffer): TestResponse.
partialMatchfunctionpartialMatch(actual: unknown, expected: unknown): boolean.
TestClient memberSignatureDescription
constructornew TestClient(bootFn: (port: number) => Promise<{ port; close }>, options?: { auth?: AuthStrategy; routes?: RouteManifest })
boot / closeboot(): Promise<void>Idempotent.
booted, port
get, post, put, patch, delete, head, optionsget(path: string): RequestBuilder
request / fluentrequest(path: string, method?: HttpMethod): RequestBuilder
visitvisit(name: string, params?: Record<string, string>): RequestBuilderGETs a named route.
withHeaderwithHeader(name: string, value: string): TestClientA default header.
wsws(path: string, options?: TestWebSocketOptions): Promise<TestWebSocket>

RequestBuilder: body and headers (json, form, body, field, fields, file, header, headers, cookie, cookies, qs, type, accept, bearerToken, basicAuth, unsafeJson, unsafeForm, unsafeQs, serialize), behaviour (timeout, redirects), auth (withAuth, asUser, loginAs, withCsrf / withCsrfToken), debugging (dump, dumpBody, dumpHeaders, dumpCookies), send(), and the assertions below. RequestBuilder.addSerializer(name, fn) and addParser(contentType, fn) register body codecs.

ApiResponse: status(), statusType(), headers(), header(name), text(), body(), json<T>(), method(), type(), charset(), cookies(), cookie(name), redirects(), links(), files(), hasBody(), hasError(), hasFatalError(), error(), the dump*() methods, assertAgainstApiSpec(), and the assertions below.

Assertions, on both: assertStatus, assertHeader, assertHeaderMissing, assertCookie, assertCookieMissing, assertBody, assertBodyContains, assertBodyNotContains, assertTextIncludes, assertRedirectsTo, and one per status: assertOk, assertCreated, assertAccepted, assertNoContent, assertMovedPermanently, assertFound, assertBadRequest, assertUnauthorized, assertPaymentRequired, assertForbidden, assertNotFound, assertMethodNotAllowed, assertNotAcceptable, assertRequestTimeout, assertConflict, assertGone, assertLengthRequired, assertPreconditionFailed, assertPayloadTooLarge, assertURITooLong, assertUnsupportedMediaType, assertRangeNotSatisfiable, assertImATeapot, assertUnprocessableEntity, assertLocked, assertTooManyRequests, assertInternalServerError. RequestBuilder also has expectStatus, expectHeader, expectCookie, expectJson.

@c9up/ream/testing/utils ​

ExportKindDescription
createTestUtilsfunctioncreateTestUtils(boot: BootServer): TestUtils.
TestUtilsclasshttpServer(): HttpServerUtils, client(): TestClient | undefined.
HttpServerUtilsclassstart(): Promise<() => Promise<void>>: starts the server and returns its close function.
BootServertype(port: number) => Promise<{ port: number; close: () => Promise<void> | void }>.

Configuration ​

reamrc.ts ​

defineConfig(config: ReamrcConfig) from @c9up/ream:

OptionTypeDefaultDescription
providers(() => Promise<{ default: Provider }> | { file; environment?: string[] })[]Providers, optionally limited to environments.
preloads(() => Promise<unknown> | { file; environment?: string[] })[]Modules imported at boot (start/routes.ts, start/kernel.ts).
commands(() => Promise<unknown>)[]Command loaders.
commandsAliasesRecord<string, string>Shorthands: { resource: 'make:controller --resource' }.
directoriesPartial<DirectoriesNode>the conventional layoutOverrides, merged over the defaults.
modules{ path?: string; autoload?: string[] }./app/modules, ['routes', 'events']What to load from each module directory; a trailing / names a directory.
testsTestsConfigsuites (name, files, timeout, retries, configure), timeout, forceExit, bootstrap. Read by ream test.
assets{ devServer?: { command; args? }; build?: { command; args? } }The asset command ream dev and ream build run beside the app.
metaFiles{ pattern: string; reloadServer: boolean }[]Non-module files of the app; reloadServer restarts the dev server when one changes.
mobileMobileConfigThe phone app ream android:* builds: name, id, entry, version (default 1.0.0), build, icon, css, android (permissions, abis, signing), updates (url, publicKey, directory).

Ignitor options ​

new Ignitor(appRoot, config?: IgnitorConfig):

OptionTypeDefaultDescription
portnumberPORT, then 3000
hoststringHOST, then 0.0.0.0 in production and localhost otherwise
serverFactory(port: number, host: string) => HyperServerLikeThe HTTP server; createHyperServerFactory() gives the native one.
importer(filePath: string) => Promise<unknown>How the app's modules are imported.
watchDirsstring[]Directories watched for hot reload.
gracefulShutdownbooleantrueDrains the server on SIGTERM / SIGINT (web mode).
allowedHostsstring[] | true—Development only: hosts the /__ream/ pages answer besides IP addresses, localhost, .localhost names and the bind host (a leading . adds the subdomains). true allows any host.

config/app.ts: http ​

Read by the native server. Timeouts are in milliseconds; 0 disables a bound.

OptionDefaultDescription
http.headersTimeout60000Time to receive the request headers.
http.requestTimeout300000Time to receive the whole request.
http.keepAliveTimeout5000Idle time of a kept-alive connection.
http.maxConnections10000Open connections; 0 for no cap.
http.webSocket.maxFrameSize1 MiBBytes, or a size such as '1mb'.
http.webSocket.maxMessageSize1 MiB
http.webSocket.maxBufferedBytes4 MiBOutgoing backlog per connection.
http.webSocket.idleTimeout600000 never closes.
http.webSocket.allowedOriginssame originBrowser origins allowed to connect, or ['*'].

config/bodyparser.ts ​

defineConfig from @c9up/ream/bodyparser/config. The native server enforces each limit while reading the body.

OptionDefaultDescription
allowedMethods['POST', 'PUT', 'PATCH', 'DELETE']Methods whose body is parsed.
json.limit'1mb'A size string or a number of bytes.
json.typesapplication/json, application/json-patch+json, application/vnd.api+json, application/csp-report
json.stricttrueOnly objects and arrays.
json.convertEmptyStringsToNull, json.trimWhitespacestrue
form.limit'1mb'
form.typesapplication/x-www-form-urlencoded
form.convertEmptyStringsToNull, form.trimWhitespacestrue
form.queryString{}Query-string parser options.
raw.limit'1mb'
raw.typestext/*
multipart.limit'20mb'
multipart.maxFiles, multipart.maxFields1000
multipart.typesmultipart/form-data
multipart.convertEmptyStringsToNull, multipart.trimWhitespacestrue

config/session.ts ​

defineConfig from @c9up/ream/session/config:

OptionDefaultDescription
storenone: requiredA key of stores, or a driver name (cookie, memory, file, redis, database).
storesNamed stores: { driver, ...options }.
secretSigns the session cookie; required by the cookie store.
cookieName'ream_session'
age7200 secondsA number of seconds or a duration such as '2h'.
clearWithBrowserfalseA cookie without expiry.
rollingfalseRe-sends the cookie on every response.
cookie{ path: '/', httpOnly: true, sameSite: 'lax' }, secure in productionhttpOnly: false is refused.
locationfile store: the directory.
dbConnection, tableName, gcProbabilitytableName: 'sessions'database store.
connection, client, prefixprefix: 'ream:session:'redis store.

config/events.ts ​

defineConfig from @c9up/ream/events/config: store: 'memory' (the default and only store). Any other option is refused.

config/scheduler.ts ​

defineConfig from @c9up/ream/scheduler/config:

OptionDefaultDescription
locknone: every instance runs every tasklocks.memory() or locks.redis({ connection }).
defaultLockTtlMs60000How long a lease lasts.

Static files ​

defineStaticConfig(config?: Partial<StaticConfig>):

OptionDefaultDescription
rootThe directory served.
enabledtrue
prefixServe only under this URL prefix.
index'index.html'false disables.
extensionsFallback extensions tried when the path has none.
dotFiles'ignore''ignore', 'deny' (403) or 'allow'.
etag, lastModified, cacheControl, acceptRangestrue
maxAge0Cache-Control: max-age, in milliseconds.
immutablefalseNeeds maxAge.
headers(filePath, stat) => Record<string, string>: extra headers per file.

Container bindings ​

TokenResolves to
appApplication
appRootstring: the absolute project root
configConfigStore
routerRouter
serverServer
middlewareMiddlewareRegistry
HttpContextthe HttpContext class
encryptionCookieSigner
signedUrlSignedUrl
emitterEmitter
migrationsMigrationRegistry
consoleConsole
consoleKernelKernel

Other packages add theirs (logger, auth, db, …) by augmenting ContainerBindings from @c9up/ream/types.

Errors ​

Each code links to its row in the error index.

Container ​

CodeRaised when
E_CONTAINER_NOT_FOUNDNo binding found for the requested token. Includes "did you mean?" suggestions for typos. Register it with container.singleton() or decorate the class with @inject().
E_CIRCULAR_DEPENDENCYCircular dependency (or circular alias) detected during resolution. Use explicit factories or decouple via events.
E_CONTAINER_MISSING_METADATAA class declares constructor parameters but the container finds no dependency metadata for them. Enable decorator metadata, annotate the parameters with @inject(), or declare static containerInjections.
E_CONTAINER_RESERVED_TOKENThe token name reads as an Object.prototype key (constructor, __proto__…). Pick another name.
E_CONTAINER_MISSING_ASKS_FORcontainer.when(...).provide() was called before asksFor(): the contextual binding does not say which dependency it replaces.
E_CONTAINER_METHOD_NOT_CALLABLEcontainer.call() named a member of the instance that is not a method.
E_CONTAINER_INVALID_DECORATOR_TARGET@Service() or @inject() was put on something that is not a class (or, for @inject(), one of its methods).

Router ​

CodeRaised when
E_ROUTE_NOT_FOUND (404)No route matches the requested method and path. The message is Cannot GET:/path.
E_DUPLICATE_ROUTETwo routes declare the same method and path.
E_DUPLICATE_ROUTE_NAMETwo routes carry the same name.
E_MISSING_ROUTE_NAMEA named group prefixes a route that has no name of its own. Name every route of a named group.
E_INVALID_ROUTE_DOMAINA route domain has a parameter without a name, or the same parameter twice.
E_EMPTY_GATE_REQUIREMENT.guard(), .role() or .permission() was called with nothing, or a route group, an RPC group, config/rpc.ts, config/openapi.ts or a GraphQL resolver was given an empty guards, roles or permissions list. An empty requirement would protect nothing. Raised where the route, method or resolver is declared; for a controller action whose @Role(), @Permission() or @Guard() names nothing, on each request to it.
E_UNREGISTERED_CONTROLLERA route names a controller by string that is not registered.
E_NO_VIEW_ENGINErouter.on(path).render() was used and no template engine is installed.
E_VALIDATOR_NOT_FOUNDA route names a validator that is not registered.
E_INVALID_CONTROLLER_REFERENCEA route handler string is not of the form 'Controller.method'.
E_INVALID_RESOURCE_NAMErouter.resource() was given an empty name.
E_CONTROLLER_METHOD_NOT_FOUNDThe controller a route names has no such method. Answered with 500.
E_CANNOT_LOOKUP_ROUTE (500)urlFor(), findOrFail() or the test client's visit() named a route that does not exist.
E_MISSING_ROUTE_PARAMSA URL was built for a route without one of its required parameters.

WebSocket ​

CodeRaised when
E_WEBSOCKET_UPGRADE_REQUIRED (426)A plain request reached a WebSocket route.
E_WEBSOCKET_UNSUPPORTED (501)A WebSocket route was reached on a server that cannot hold WebSockets.
E_WEBSOCKET_BAD_HANDSHAKE (400)The handshake is not an HTTP/1.1 GET, lacks Connection: upgrade, or its Sec-WebSocket-Key is not 16 bytes. Answered by the server, before routing.
E_WEBSOCKET_VERSION (426)A WebSocket version other than 13. Answered with Sec-WebSocket-Version: 13, before routing.
E_WEBSOCKET_ORIGIN (403)A browser origin that http.webSocket.allowedOrigins does not allow (same origin by default). Answered before routing.
E_WEBSOCKET_PROTOCOL (500)socket.acceptProtocol() named a subprotocol the client did not offer.
E_WEBSOCKET_NOT_REGISTERED (500)A response was 101 without a registered socket.
E_WEBSOCKET_NOT_UPGRADE (500)A 101 answered a request that was not a WebSocket handshake.
E_WEBSOCKET_REGISTERThe native server refused a fresh socket id.
E_WEBSOCKET_CONTEXTA WebSocket route's handler ran without its socket (called outside the kernel).
E_WEBSOCKET_CLOSE_CODEsocket.close() with a code a close frame may not carry (RFC 6455 §7.4).
E_WEBSOCKET_CLOSE_REASONA close reason over 123 bytes.
E_INVALID_WEBSOCKET_CONFIGA native WebSocket limit of 0 bytes.
E_TEST_CLIENT_WEBSOCKET_REFUSEDThe test client's WebSocket handshake was refused (its status and body are the application's answer) or failed.

Middleware pipeline ​

CodeRaised when
E_PIPELINE_UNKNOWN_MIDDLEWAREA route references a named middleware that is not registered. Register it with middleware.register().
E_MIDDLEWARE_NOT_FOUNDA route, an RPC method or a GraphQL resolver names a middleware nothing declared. Declare it with router.named() (or middleware.register()). An HTTP route's names are checked when the kernel is built, at boot.
E_MIDDLEWARE_ENTRYA middleware entry with no declared parameters was read as a lazy import, and it did not resolve to a module with a default export.
E_PIPELINE_DOUBLE_NEXTA middleware called next() more than once. Each middleware should call next() at most once.
E_PIPELINE_ERRORA handler threw an error that carries no framework code. The error keeps the stage position in its context.
E_VALIDATOR_UNUSABLEA route validator exposes none of validateResultAsync(), validateResult() or validate().

HTTP ​

CodeRaised when
E_UNKNOWN (500)The code the exception handler reports for a thrown value that carries none.
E_RUNTIME_EXCEPTION (500)RuntimeException: a failure of the program, not of the request.
E_INVALID_ARGUMENTS_EXCEPTION (500)InvalidArgumentsException: a function was called with arguments it cannot use.
E_HTTP_EXCEPTION (varies)A generic HTTP error carrying the response body. E_HTTP_EXCEPTION.invoke(body, status, code?) builds one: the message is a string body, or the message of an object body.
E_HTTP_REQUEST_ABORTED (400)The class response.abort() (or abortIf / abortUnless) throws; the body given is sent with the status given, 400 by default. It extends E_HTTP_EXCEPTION and carries its code.
E_UNAUTHORIZED_ACCESS (401)A route's .auth() guard refused the request, or .role() / .permission() found no authenticated user. The same code, status, message (Unauthorized access), identifier, getResponseMessage and handle as @c9up/warden's: it renders itself as 401 { "error": { "code", "message" } }.
E_AUTHORIZATION_FAILURE (403)A route's .role() or .permission() refused an authenticated user. The same code, status, message (Access denied), identifier, getResponseMessage and handle as @c9up/warden's: it renders itself by content negotiation, { "errors": [{ "message" }] } for JSON, a JSON:API error object, the message as text for HTML, a denied form submission with a session redirected back with the message flashed. The roles and permissions asked for are not sent.
E_WARDEN_MFA_REQUIRED (403)The route gate reached a controller action carrying @RequireMfa() with a credential that did not complete the MFA step-up (ctx.auth.user.mfa is not true). The same code, status, message and body as @c9up/warden's middleware: 403 { error: { code, message } }.
E_VALIDATION_ERROR (422)The request data failed validation. The message is Validation failure, messages carries one entry per field and rule; a browser form is redirected back with the errors flashed.
E_REQUEST_ENTITY_TOO_LARGE (413)The request body is over the body parser's limit. Reading the raw body of such a request raises it too.
E_HANDLER_FAILURE (500)The exception handler itself threw while rendering an error.
E_HTTP_CONTEXT_NOT_FOUNDHttpContext.getOrFail() was called outside a request, or with ambient-context tracking turned off. Pass ctx explicitly.
E_RESPONSE_TOO_LARGEA response body is over the configured ceiling. Bodies are held whole in memory, so a large file should be streamed or served from storage.
E_BODYPARSER_CONFIGThe body parser config uses an option that is no longer supported.
E_BODYPARSER_INVALID_SIZEA body size limit is neither a number of bytes nor a size such as '1mb'.
E_ENCODING_UNSUPPORTED (415)A JSON, form or text body arrives with a Content-Encoding other than identity. The body parser does not inflate bodies, gzip and deflate included.
E_BODYPARSER_INVALID_JSON (400 / 422)A JSON body is malformed (400), or under json.strict is neither an object nor an array (422).
E_HTTP_REQUEST_TIMEOUT (408)The native server did not receive the request body in time.
E_REQUEST_ABORTED (400)The client closed the connection while the body was being read.
E_INVALID_MULTIPART_REQUEST (400)A multipart/form-data body is malformed, or its boundary parameter is missing.
E_PATH_TRAVERSAL (400)The native server found .. in the path, raw or percent-encoded.
E_PARAMETER_POLLUTION (400)The native server found a query-string key twice.
E_TOO_MANY_REQUESTS (429)The native server's rate limit refused the request; the body carries retryAfter, with Retry-After and X-RateLimit-* headers.
E_STREAM_UNKNOWN (500)A server-sent event stream id is unknown to the server.
E_RESPONSE_INVALID_HEADERA header name or value carries CR, LF or NUL, which would split the response.
E_RESPONSE_INVALID_COOKIEA cookie a browser would reject or misread: a name outside the cookie token grammar, a path or domain outside the attribute grammar, sameSite: true, SameSite=None or partitioned without secure, an invalid expires date, or an http.cookie block with an unknown key or a value of the wrong type.
E_RESPONSE_NO_CONTEXTresponse.redirect() on a response built outside a request.
E_RESPONSE_SSE_UNSUPPORTEDresponse.sse() on a server that has no stream backend.
E_REDIRECT_NO_ROUTERredirect().toRoute() with no route URL resolver wired.
E_STREAM_REGISTERThe server refused a fresh server-sent event stream id.
E_MULTIPART_UNSAFE_FILE_NAMEfile.move() was given, or derived from the client's file name, a name that is not a plain file name.
E_MULTIPART_FILE_EXISTSfile.move() found a file at the destination and overwrite is off.
E_TEST_CLIENT_NO_ROUTE_MANIFESTThe test client's visit() needs routes: router.namedManifest() in the client options.
E_TEST_CLIENT_TIMEOUTA test client request, or a test WebSocket message, did not arrive within its timeout.
E_TEST_CLIENT_MISSING_CSRF_TOKENwithCsrf() was called with no token and no CSRF cookie set.
E_TEST_CLIENT_NO_AUTH_STRATEGYwithAuth() or asUser() was used without an auth strategy in the client options.
E_TEST_CLIENT_NO_SESSION_SEEDERloginAs() with a session guard, and no sessionSeeder in the client options.
E_TEST_CLIENT_UNKNOWN_SERIALIZERserialize() named a serializer that is not registered.
E_TEST_CLIENT_ASSERTION_FAILEDAn assertion of the test client's response failed.

Sessions ​

CodeRaised when
E_SESSION_NOT_READY (500)session.<method>() needs a session store, and this session was built without one.
E_SESSION_STORE_NOT_CONFIGURED (500)The session config names no store. Set store, or store: 'memory' for sessions kept in this process only.
E_SESSION_STORE_NOT_CONDITIONAL (500)The store has no update(), so it cannot write a session back only while it still exists; a request running across a logout could sign the user in again.
E_SESSION_TAGGING_NOT_SUPPORTED (500)A session tagging method was called on a store that does not support it. Use the memory, redis or database store.
E_SESSION_COOKIE_NOT_HTTP_ONLY (500)The session cookie is configured with httpOnly: false. Remove it: a script able to read the cookie turns any XSS into an account takeover.
E_SESSION_TEMPLATE_ENGINE_UNUSABLEThe template engine is installed but the session tags cannot be registered on it.
E_SESSION_MISSING_SECRETThe cookie session store has no secret.
E_SESSION_MISSING_LOCATIONThe file session store has no location.
E_SESSION_INVALID_CONNECTIONThe database session store's connection lacks query() and execute().
E_SESSION_UNKNOWN_DRIVERThe session config names a driver that does not exist.
E_SESSION_INVALID_GC_PROBABILITYgcProbability is not a percentage between 0 and 100.
E_SESSION_INVALID_TABLE_NAMEThe session table name is not a plain identifier.
E_SESSION_FILE_LOCKEDAnother request kept the session file locked longer than the store waits.
E_SESSION_QUASAR_MISSINGA Redis session store names a quasar connection and @c9up/quasar is not installed.
E_SESSION_INCOMPLETE_CONNECTIONThe quasar connection lacks the commands a session store sends.

Application, env and Ignitor ​

CodeRaised when
E_INVALID_ENV_VARIABLESEnv.create() found environment variables that fail their schema. The message is Validation failed for one or more environment variables; help lists each one on a - line, and failures holds them.
E_MISSING_ENCRYPTER_KEYEncryption, a signed cookie or a signed URL was used and APP_KEY is not set. help names what needed it.
E_INSECURE_ENCRYPTER_KEYAPP_KEY is shorter than 16 characters, or is a key known from scaffolding or documentation.
E_CRYPTO_FAILEDA native crypto call (hmacSign(), randomHex()…) failed in the engine.
E_REAMRC_UNKNOWN_OPTIONreamrc.ts tests holds an option that does not exist.
E_MISSING_PROVIDER_FILEA reamrc.ts providers entry has no file.
E_INVALID_PROVIDERA reamrc.ts providers entry has a file that is not a function. A provider module with no default export, or whose default export is not a class, raises E_RUNTIME_EXCEPTION.
E_MISSING_PRELOAD_FILEA reamrc.ts preloads entry has no file.
E_INVALID_PRELOAD_FILEA reamrc.ts preloads entry has a file that is not a function.
E_IGNITOR_ALREADY_STARTEDwarmUp() was called while the application was already past that phase.
E_IGNITOR_WARMUP_ONLYAn application assembled with warmUp() was started. Build a fresh Ignitor to run one.
E_IGNITOR_INVALID_PORTPORT is not an integer between 0 and 65535.
E_IGNITOR_INVALID_HTTP_CONFIGAn http.<key> limit is not a whole number in range.
E_IGNITOR_NO_SERVER_FACTORYhttpServer() was called with no serverFactory in the config.
E_IGNITOR_GRPC_UNSUPPORTEDA gRPC handler is registered, but this server cannot serve gRPC.
E_SERVER_GRPC_ALREADY_SETA second gRPC handler was registered on the server.
E_SERVER_GRPC_INVALID_LIMITA gRPC message size limit is not a whole number of bytes, or -1 for no limit.
E_SERVER_INVALID_PORTThe native server was given a port above 65535.
E_SERVER_INVALID_HOSTThe native server's bind address is not an IPv4 or IPv6 address, nor localhost.
E_SERVER_INVALID_TRUSTED_PROXYA trustedProxies() entry is not an address, a CIDR range, a netmask range, a named range or *. The server refuses to start.
E_SERVER_INVALID_BODY_LIMITA body limit handed to the native server is not a byte count or a part count of zero or more.
E_SERVER_BIND_FAILEDThe native server could not bind its address: the port is taken, or the address is not on this machine.
E_SERVER_NO_HANDLERThe native server was started before a request handler was registered.
E_SERVER_NOT_STARTEDThe native server's port was read before the server started.
E_SERVER_LOCK_POISONEDA lock of the native server was left poisoned by a panic. This is a bug in Ream.
E_REAM_STUB_SYNTAXA stub template has a syntax error.
E_ENV_FILE_NOT_FOUNDA .env value file:<path> names a file that does not exist. The message names the variable and the path.
E_ENV_CIRCULAR_REFERENCE.env values reference each other in a loop (A=$B, B=$A).
E_IDENTIFIER_ALREADY_DEFINED (500)Env.defineIdentifier() was given a name already registered (file is built in). Use defineIdentifierIfMissing() or remove the identifier first.
E_APP_MISSING_IMPORTERapp.import() / app.importDefault(id) was called on an application built without an importer.
E_DUMP_DIE_EXCEPTION (500)dd() stopped the request (answered with an HTML dump) or the command (printed the dump). Never reported.
E_APP_ALREADY_BOOTEDapp.setMode() or app.setEnvironment() was called after the application booted.
E_APP_ROOT_NOT_SETapp.makePath() (or another path helper) on an application with no root.
E_APP_MISSING_DEFAULT_EXPORTA lazily imported module (app.importDefault(), a lazy listener, a route's lazy controller) has no default export.
E_APP_SHUTDOWN_FAILEDSeveral terminating or shutdown hooks failed; errors holds each failure.
E_SERVICE_NOT_BOOTEDA @c9up/ream/services/* accessor, urlFor() or signedUrlFor() was used before the application booted it.
E_ENV_PATH_NO_FILEENV_PATH names a directory that holds none of the .env files.
E_MIGRATION_SOURCE_CONFLICTTwo providers registered a migration source under the same name.
E_INVALID_DURATIONA duration (a session age, a cookie maxAge, a signed URL expiry…) is neither a number nor a string such as '30m'.
E_BASE64_MALFORMEDbase64.decode() or base64.urlDecode() in strict mode met a malformed value.
E_HEALTH_INVALID_THRESHOLDA memory health check threshold is not a byte size, or not a percentage between 0 and 100.
E_REAM_STUB_NOT_FOUNDNo stub at the given path.
E_REAM_STUB_UNSAFE_PATHA stub path, or the destination a stub declares, is absolute or leaves its root, or a generator's destination is a symbolic link leading outside the project or to nothing.
E_REAM_STUB_NO_DESTINATIONA stub declares no destination (no to: front-matter line), or an empty one.
E_REAM_STUB_FORBIDDEN_KEYA stub template reads or sets a key it may not reach (constructor, __proto__…). A TypeError.
E_REAM_STUB_EVALUATIONA stub template failed while rendering: an unknown name, a property of nothing, a call to what is not a function, {{#each}} over what is not a list. A TypeError or a ReferenceError.
E_CODEMODS_FILE_NOT_FOUNDA codemod needs reamrc.ts, start/kernel.ts or start/env.ts and the file does not exist.
E_CODEMODS_UNRECOGNIZED_SOURCEA codemod could not find what it edits in the file (providers: [, defineConfig({ ... }), router.use([, Env.create(...)…). Make the change by hand.
E_CODEMODS_UNSAFE_PATHA codemod was asked to write outside the project: an absolute path, .., a symlink that resolves outside, or an unsafe module path.
E_CODEMODS_INVALID_OPTIONA codemod option is out of range: a middleware position or tier, a preload environment.
E_CODEMODS_INVALID_ENV_VARIABLEAn environment variable name is not an identifier, or its value holds a line break.
E_CODEMODS_INVALID_ENV_VALIDATIONdefineEnvValidations() was given a comment over one line, or a rule that is not one complete expression.
E_CODEMODS_MIDDLEWARE_CONFLICTA middleware is already registered in the other tier of start/kernel.ts.
E_REAM_INTERNALAn invariant inside @c9up/ream broke; a bug to report.
E_REAM_NAPI_UNSUPPORTED_PLATFORMNo prebuilt native binary (HTTP server, scheduler, event bus, GraphQL) exists for this platform.
E_REAM_NAPI_LOAD_FAILEDA native binary exists but cannot be loaded. The message names the binary and the fix (rebuild a local build, reinstall a platform package); cause is the load error, with the paths on the host.
E_REAM_NAPI_NOT_FOUNDA native binary is found neither at the package root nor in the platform package @c9up/ream-<platform>; help names the package to install, cause is the loader's error.

Console ​

CodeRaised when
E_CONSOLE_COMMAND_NOT_FOUNDNo command has this name.
E_CONSOLE_MISSING_ARGUMENTA required argument was not given.
E_CONSOLE_MISSING_ARGUMENT_VALUEAn argument was given with no value.
E_CONSOLE_UNEXPECTED_ARGUMENTMore arguments than the command declares.
E_CONSOLE_UNKNOWN_FLAGA flag the command does not declare.
E_CONSOLE_MISSING_FLAGA required flag was not given.
E_CONSOLE_MISSING_FLAG_VALUEA flag that takes a value was given without one.
E_CONSOLE_INVALID_FLAG_VALUEA flag value of the wrong type.
E_CONSOLE_INVALID_FLAG_GROUPShort flags were grouped (-abc) with one that cannot be grouped.
E_CONSOLE_NOT_INTERACTIVEA command asked a question while stdin is not interactive. Pass the value as a flag.
E_CONSOLE_PROMPT_CANCELLEDThe user cancelled a prompt.
E_CONSOLE_EMPTY_CHOICESA choice prompt was asked with no options.
E_CONSOLE_INVALID_TRAP_VALUEA scripted answer (a prompt trap in a test) was rejected by the prompt's own validation.
E_CONSOLE_TRAP_OUT_OF_RANGEA prompt trap chose an option that was not offered.
E_CONSOLE_DUPLICATE_COMMANDTwo commands claim the same name.
E_CONSOLE_INVALID_COMMANDAn entry of reamrc.ts commands is neither a command loader nor a default-exported command class.
E_CONSOLE_INVALID_COMMAND_METADATAA command loader exported metadata that does not describe a command.
E_CONSOLE_INVALID_ARGUMENTA command declares its arguments in an order that cannot be parsed: an argument after a spread one, or a required one after an optional one.
E_CONSOLE_INVALID_ALIASA command alias expands to nothing.
E_CONSOLE_LATE_GLOBAL_FLAGA global flag was declared after the kernel started.
E_CONSOLE_LATE_LOADERA command loader was added after the kernel started.
E_CONSOLE_KERNEL_RUNNINGA command is already running through this kernel.
E_CONSOLE_KERNEL_COMPLETEDThe kernel has finished; it cannot run another command line.
E_CONSOLE_NOT_BOOTEDA console application method was called before the commands were loaded.
E_CONSOLE_NO_APPA command needs the application and the kernel has none. Dispatch through the Ignitor's console kernel.
E_CONSOLE_APP_NOT_STARTEDA command used the application without declaring startApp: true in its options.
E_CONSOLE_ASSERTION_FAILEDAn assertion on a command run in a test failed (assertSucceeded(), assertLog(), assertTableRows()…).

Scheduler ​

CodeRaised when
E_SCHEDULE_INVALID_CRONA scheduled task's cron expression could not be registered.
E_SCHEDULE_INVALID_TARGET@Schedule was put on a static method.
E_SCHEDULE_SYMBOL_METHOD@Schedule was put on a symbol-keyed method.
E_SCHEDULE_ANONYMOUS_CLASSAn anonymous class declares @Schedule; its task names would collide.
E_SCHEDULE_METHOD_NOT_FOUNDA scheduled method is not callable on the instance the container resolved.
E_SCHEDULE_INVALID_CALLBACKScheduler.register() was given something other than a function.
E_SCHEDULE_INVALID_TASK_NAMEScheduler.register() was given an empty task name.
E_SCHEDULE_INVALID_LOCK_BACKENDlockBackend does not implement acquire(name, ttlMs) and release(name).
E_SCHEDULE_INVALID_LOCK_TTLdefaultLockTtlMs is not a finite positive number.
E_SCHEDULE_INVALID_EVENT_SINKeventSink does not implement emit(event).
E_SCHEDULE_INVALID_ERROR_REPORTERerrorReporter is not a function.
E_SCHEDULE_TASK_UNKNOWNrunTaskNow() named a task that is not registered.
E_SCHEDULE_TASK_TIMEOUTA task did not complete within its timeoutMs; it keeps running in the background.
E_SCHEDULE_PROVIDER_ALREADY_REGISTEREDThe scheduler provider was registered twice on the same container.
E_SCHEDULER_NATIVE_ERRORA call into the native scheduler failed.
E_NATIVE_CALLBACK_FAILEDA JavaScript callback the native binding could not hold: napi refused to wrap it. napi's own status is in the message.
E_NATIVE_PANICA Rust panic in a native binding, caught before it could stop the process. This is a bug in Ream. The scheduler reports it as E_SCHEDULER_NATIVE_ERROR.
E_SCHEDULER_INVALID_CRONThe native scheduler refused a cron expression.
E_SCHEDULER_CRON_NO_FIREThe native scheduler refused a cron expression that never fires.
E_SCHEDULER_DUPLICATE_TASKThe native scheduler already has a task of that name.
E_SCHEDULE_QUASAR_MISSINGThe scheduler lock names a quasar connection and @c9up/quasar is not installed.
E_SCHEDULE_INCOMPLETE_CONNECTIONThe quasar connection lacks the commands a scheduler lock sends.

Events ​

CodeRaised when
E_EVENTS_UNSUPPORTED_STOREconfig/events.ts names a store other than 'memory', the only one this build has.
E_EVENTS_UNSUPPORTED_OPTIONconfig/events.ts holds an option nothing reads (retries included), or is not an object.
E_EVENTS_MISSING_LISTENER_METHODA listener class has no method of the name the listener was registered with.
E_EVENTS_INVALID_ARGUMENTonAny() without a listener, or waitForChain() with no event names.
E_EVENTS_ASSERTION_FAILEDAn event assertion failed (assertEmitted(), assertNotEmitted(), on the helpers or the FakeBus).
E_EVENTS_TIMEOUTAn awaited event, event chain or fake request reply did not arrive within its timeout.
E_EVENTS_DUPLICATE_REQUEST_HANDLERFakeBus.onRequest() was given a second handler for the same name.
E_EVENTS_NO_REQUEST_HANDLERemitter.request() or FakeBus.request() named a request no handler answers.
E_EVENTS_HANDLER_FAILEDA request handler panicked, or refused the request with an error of its own.
E_EVENTS_BUS_FAILEDThe native event bus failed: its task panicked or was cancelled, or an event could not be serialized.

RPC and GraphQL ​

CodeRaised when
E_RPC_INVALID_METHOD_NAMEAn RPC method name is empty or not a string.
E_RPC_RESERVED_METHOD_NAMEAn RPC method takes a reserved name (rpc.*).
E_RPC_UNKNOWN_CONTROLLER_METHODAn RPC route names a controller method that does not exist.
E_RPC_PROVIDER_ALREADY_REGISTEREDThe RPC provider was registered twice on the same container.
E_GRAPHQL_PROVIDER_ALREADY_REGISTEREDThe GraphQL provider was registered twice on the same container.
E_GRAPHQL_SCHEMA_NOT_FOUNDThe GraphQL schemaPath names a file that does not exist.
E_GRAPHQL_INVALID_SCHEMAThe GraphQL schema does not parse, declares a type twice, or names a type it does not declare. Every query is then refused with GraphQL schema could not be read, and the reason is logged.
E_GRAPHQL_INVALID_RESULTA GraphQL resolver returned a value its field's declared type cannot hold: an object under a String, something that is not a list under [Task], a value of an interface or union whose object type is not known. The field fails; the client reads Internal server error outside debug.
E_GRAPHQL_SERIALIZE_FAILEDThe native GraphQL parser could not serialize its result.

HTTP client ​

CodeRaised when
E_HTTP_CLIENT_INVALID_URLThe URL cannot be parsed, is not http or https, or carries credentials (send them in a header).
E_HTTP_CLIENT_PRIVATE_ADDRESSThe host is, or resolves to, an address that is not public.
E_HTTP_CLIENT_UNREACHABLEThe host could not be reached.
E_HTTP_CLIENT_TIMED_OUTThe request did not complete within its timeout.
E_HTTP_CLIENT_TOO_LARGEThe response body is over the size limit.
E_HTTP_CLIENT_REDIRECT_REFUSEDA redirect was refused: too many of them, from https to http, or to another host.

Each one is a class of errors, a flare Exception: read error.code, or test error instanceof errors.E_ROUTE_NOT_FOUND. An error that says how to fix it carries the advice in help.

Migration ​

  • @c9up/ream/events/configure is gone. ream configure takes a package name, so it never reached that hook. Every new app already lists @c9up/ream/events/provider, and config/events.ts is optional: without it the bus uses the in-memory store. Add the provider to reamrc.ts by hand if your app predates that.

  • ReamError, isReamError and the module errors (AtlasError, ContainerError, EventsError, ForgeError, PipelineError, RouterError, RuneError, WardenError) are gone. Replace isReamError(error, 'E_X') and instanceof ReamError with error instanceof errors.E_X or a test on error.code. The advice that was in hint is in help; the data that was in context is on named fields (E_CIRCULAR_DEPENDENCY.chain, E_RESPONSE_TOO_LARGE.bytes and ceiling, E_SCHEDULE_INVALID_CRON.task and cronExpr…). error.docsUrl is errorDocsUrl(error.code).

  • The error classes are no longer exported one by one from @c9up/ream: import { E_ROUTE_NOT_FOUND } from '@c9up/ream' becomes import { errors } from '@c9up/ream' and errors.E_ROUTE_NOT_FOUND. @c9up/ream/exceptions still exports the HTTP exceptions by name.

  • Renamed classes: ShutdownError is errors.E_APP_SHUTDOWN_FAILED (an Exception with errors, no longer an AggregateError); EnvValidationException and EnvVarError are errors.E_INVALID_ENV_VARIABLES (failures lists each variable); HttpClientError is one class per code, errors.E_HTTP_CLIENT_*, and reason is gone: read error.code; WebSocketRefused is errors.E_TEST_CLIENT_WEBSOCKET_REFUSED; ExpectationError is errors.E_TEST_CLIENT_ASSERTION_FAILED; StubSyntaxError, StubTypeError and StubReferenceError are errors.E_REAM_STUB_SYNTAX, E_REAM_STUB_FORBIDDEN_KEY and E_REAM_STUB_EVALUATION, and no longer extend TypeError or ReferenceError.

  • Exception, createError, RuntimeException and InvalidArgumentsException are @c9up/flare's. A createError class takes its placeholder values as an array: new E_X('a', 'b') becomes new E_X(['a', 'b']). InvalidArgumentsException has the code E_INVALID_ARGUMENTS_EXCEPTION (was E_INVALID_ARGUMENTS) and no longer extends RuntimeException.

  • Outside debug mode, the exception handler shows the message of a 5xx error only when it is flagged expose: true; being an Exception is no longer enough.

  • The route guards raise the codes @c9up/warden raises: E_UNAUTHORIZED is now E_UNAUTHORIZED_ACCESS (401, Unauthorized access) and E_FORBIDDEN is now E_AUTHORIZATION_FAILURE (403, Access denied, without the required list). Both render themselves (handle), exactly as warden's errors of the same code do, so a refusal answers the same bytes whether a route guard or warden raised it: 401 { "error": { "code", "message" } } for E_UNAUTHORIZED_ACCESS; for E_AUTHORIZATION_FAILURE, { "errors": [{ "message" }] } for JSON, a JSON:API error object, the message as text for HTML, and a denied form submission with a session redirected back with the message flashed. Both carry an identifier (errors.<CODE>) through which ctx.i18n translates the message. E_ROW_NOT_FOUND is removed from errors: nothing in ream raised it; @c9up/atlas raises its own.

  • E_UNKNOWN_ROUTE is now E_CANNOT_LOOKUP_ROUTE (500, Cannot lookup route "<name>"). The test client lists the manifest's names in help; urlFor() no longer lists the registered names.

  • E_ROUTE_NOT_FOUND is a createError class: new errors.E_ROUTE_NOT_FOUND([method, url]), message Cannot GET:/path.

  • E_HTTP_EXCEPTION carries body and is built with E_HTTP_EXCEPTION.invoke(body, status, code?). E_HTTP_REQUEST_ABORTED extends it, and the error response.abort() throws has the code E_HTTP_EXCEPTION: test error instanceof errors.E_HTTP_REQUEST_ABORTED rather than its code.

  • E_MISSING_APP_KEY is now E_MISSING_ENCRYPTER_KEY and E_INSECURE_APP_KEY is now E_INSECURE_ENCRYPTER_KEY. Their message is fixed; what needed the key is in help.

  • E_BAD_MULTIPART is now E_INVALID_MULTIPART_REQUEST.

  • The exception handler runs where an error is thrown, inside the middleware chain: the next() of the outer middleware returns normally, so their code after await next() runs (the session is saved, a flashed message survives). A try { await next() } catch around an inner layer no longer sees its errors.

  • E_INVALID_ENV_VARIABLES has the message Validation failed for one or more environment variables; the failures are in help, one - line each. E_IDENTIFIER_ALREADY_DEFINED is a createError class (new E_IDENTIFIER_ALREADY_DEFINED([name])) with status 500, and has no identifier field.

  • A compressed JSON, form or text body (Content-Encoding other than identity) is refused with E_ENCODING_UNSUPPORTED (415) instead of being parsed as text.

  • The native scheduler's codes carry the namespace: INVALID_CRON is E_SCHEDULER_INVALID_CRON, CRON_NO_FIRE is E_SCHEDULER_CRON_NO_FIRE, DUPLICATE_TASK is E_SCHEDULER_DUPLICATE_TASK; the native loader's <PREFIX>_NAPI_NOT_FOUND, <PREFIX>_NAPI_LOAD_FAILED and <PREFIX>_UNSUPPORTED_PLATFORM are E_REAM_NAPI_NOT_FOUND, E_REAM_NAPI_LOAD_FAILED and E_REAM_NAPI_UNSUPPORTED_PLATFORM.

  • createHyperServerFactory() no longer returns undefined. A missing native binary throws E_REAM_NAPI_NOT_FOUND, a binary that does not load throws E_REAM_NAPI_LOAD_FAILED with the load error as cause, and an unsupported platform throws E_REAM_NAPI_UNSUPPORTED_PLATFORM. Before, each of these returned undefined: a web app then stopped on E_IGNITOR_NO_SERVER_FACTORY without the reason, and a test app ran with no server. Remove any if (serverFactory === undefined) check: the error now says what is missing.

  • Role gates only restrict. RouteDefinition.roles (and RpcMethodDefinition.roles) is now a string[][]: a list of requirements, and the user needs one role of EACH. Before, a group's roles, a route's roles and the controller's @Role() were one flat list and any role of it passed: a route .role('editor') inside a group .role('admin') let an editor through, and @Role('a', 'b') let a user with a only through when warden's middleware was not installed. Now:

    • .role('a', 'b') still needs a or b, but .role('a').role('b') needs both;
    • a group's .role() (chained or group({ roles })) and each nested group's add a requirement on top of the route's own;
    • each role of @Role('a', 'b') is required, on ream's route gate as on warden's middleware.

    A route that relied on the old reading needs every role it really accepts in ONE call: .role('admin', 'editor'). Code that reads route.roles gets arrays of roles, and MiddlewareRegistry.buildChain() takes roles: [['admin']]. Permissions do not change: every one is required, the group's and the route's together.

  • Guard levels only restrict too. RouteDefinition.guards and RpcMethodDefinition.guards are now string[][], and the request must be authenticated by a guard EVERY level names. Before, a group's guards, a route's guards and @Guard() were one list, and any of them could authenticate: a route .guard('web') inside a group .guard('jwt') accepted a session-only request. Now .guard('jwt', 'web') still accepts either guard, but .guard('jwt').guard('web'), a group .guard('jwt') around a route .guard('web'), or any levels with no guard in common accept no request (401). ctx.auth.authenticateUsing() is called once, with the guards every level names. A nested rpc.group() now keeps the enclosing group's guards and middleware; before, it replaced them. OpenAPI lists the guards every level names as the security alternatives. MiddlewareRegistry.buildChain() takes guards: [['jwt']].

  • GraphQL checks every selection against the schema, at every depth, before any resolver runs. Before, only root fields were checked: below them a client could select any property of what a resolver returned, and { tasks } with no sub-selection answered the objects whole. Now:

    • a field its type does not declare is refused (Cannot query field "passwordHash" on type "User".), and so is a fragment on a type the value cannot be;
    • a field of object type needs a sub-selection: replace { tasks } with { tasks { id title } };
    • only own properties that the type declares are copied. A getter on a class prototype is no longer read: return the value as a property of the object;
    • an object under Int, Float, String, Boolean, ID or an enum fails the field (E_GRAPHQL_INVALID_RESULT) unless its toJSON() gives a string, a number or a boolean. Declare a scalar for a free-form value, or an object type with its fields;
    • a single value under a list type, or a list under an object type, fails the field;
    • the schema must declare every type it names (scalar DateTime, type User). Otherwise every query answers GraphQL schema could not be read;
    • a field of an interface or union type needs the object type of each value: return objects with __typename, or register engine.resolveType('SearchResult', (value) => 'User');
    • __typename is answered on every object, interface and union type, and at the root.
  • GraphQL stops validating after 100 errors (maxErrors) and ends the list with Too many validation errors, error limit reached. Validation aborted. A message is reported once.

  • GraphQL bounds how many times one request may select the same root field: 10 times (maxFieldRepeats), and once for a mutation (maxMutationRepeats). A request that repeats a mutation under aliases is now refused. To batch a mutation, raise maxMutationRepeats or set maxRepeats on its resolver.

  • The route gate enforces @RequireMfa(). Before, it read @Guard, @Role and @Permission off a controller action and ignored @RequireMfa: without Warden's auth middleware, the action ran without the step-up. Now an action carrying it answers 401 to an anonymous request and 403 E_WARDEN_MFA_REQUIRED unless ctx.auth.user.mfa is true, on every stack. If your own auth middleware fills ctx.auth, put the credential's mfa claim on ctx.auth.user. MiddlewareRegistry.buildChain() takes mfa: true.

  • ctx.route.controller and ctx.route.action are set on the first request to a lazily imported controller too. Before, they were empty on that request, so a middleware reading the action's decorators through them (Warden's) let it through once per route after each start. A lazily imported module with no default export now answers E_APP_MISSING_DEFAULT_EXPORT.

  • .guard(), .role() and .permission() refuse an empty call. Before, .guard(), .role(...roles) with an empty list and group({ guards: [], roles: [] }) added no requirement and the route stayed public. They now throw E_EMPTY_GATE_REQUIREMENT when the route is declared; so do an RPC method's .guard() / .role() / .permission(), rpc.group({ guards: [] }), guards: [] in config/rpc.ts, and guards: [], roles: [] or permissions: [] on a GraphQL resolver. A controller action whose @Role(), @Permission() or @Guard() names nothing answers every request with E_EMPTY_GATE_REQUIREMENT (500). Name at least one (.guard('jwt')), or remove the call or the key for no requirement. A list read from configuration must not be empty.

  • Cookie names are no longer percent-decoded on read nor percent-encoded on write. A cookie sent as %73ession is read as %73ession, not as session. response.cookie(), plainCookie(), encryptedCookie() and clearCookie() now throw E_RESPONSE_INVALID_COOKIE for a name with a space, a ;, a =, a control or a non-ASCII character; before, such a name was written encoded. Rename the cookie to visible ASCII (my_pref instead of my pref).

  • With http.allowMethodSpoofing on, request.method() no longer reads _method from the body. It answers the method the route was matched with: the _method of the query string on a POST, or the request-line method. A body _method never selected a route; it only changed what request.method() told the CSRF check, the body parser and your middleware. Put _method in the form's action URL (action="/posts/1?_method=DELETE").

  • SignedUrl.verify() and request.hasValidSignature() check the signature over the exact path?query received, without parsing it as a URL. A URL whose path a URL parser would normalise (\, . or .. segments, %2e%2e, a leading //), whose query was reordered or re-encoded, or an absolute URL (https://host/path?…) no longer verifies. Pass verify() the request target as received (req.url, request.url(true)), and send the URL make() returned unchanged.

  • Upload type detection reads the first 64 KiB of each file, and the files of one request share one bound on ZIP work (4096 entries, 4 MiB scanned). A ZIP-based file past that bound, or whose distinguishing part starts after 64 KiB, now reports typeSource: 'claimed' and the client's extension instead of a detected type. If extnames validation then refuses such an upload, send fewer ZIP-based files per request.

  • response.cookie(), encryptedCookie(), plainCookie() and clearCookie() now merge the cookie defaults under the options of each call: maxAge: '2h', path: '/', httpOnly: true, secure: true, sameSite: 'lax', overridable in config/app.ts → http.cookie. A cookie written without options was name=value; HttpOnly and lasted the browser session; it now lasts two hours and is sent over HTTPS only. Pass maxAge: undefined for a browser-session cookie, secure: false (or http.cookie.secure: false) for a cookie a plain-HTTP host must receive. An unknown key or a wrong type in http.cookie stops the boot with E_RESPONSE_INVALID_COOKIE.

  • A cookie path or domain outside the cookie grammar (a ;, a control character, a non-ASCII character, a domain that is not a host name) now throws E_RESPONSE_INVALID_COOKIE; a CR or LF there threw E_RESPONSE_INVALID_HEADER before.

  • redirect().toIntended() and redirect().back() judge a relative URL by how a browser parses it: /<TAB>/host, /<LF>/host and /\host now fall back instead of leaving the site.

  • A request handler that throws or rejects ends its request with E_EVENTS_HANDLER_FAILED (message Request handler for '<name>' failed: <message>). Before, a synchronous throw ended the process and a rejection left the requester waiting for E_EVENTS_TIMEOUT; with FakeBus, request() rejected with the handler's own error. Catch errors.E_EVENTS_HANDLER_FAILED where you awaited the handler's error or the timeout. A FakeBus request handler receives a third argument, fail(message).

  • OpenApiProvider is off in production: set enabled: true in config/openapi.ts to serve the docs there, with guards or middleware to protect them. /api-docs and /docs are now routes, not a server middleware: your server middleware runs before them, and an application route on the same path and method now stops the boot with E_DUPLICATE_ROUTE (move the docs with specPath / docsPath).

  • session.flashValidationErrors() no longer flashes password, password_confirmation, passwordConfirmation, _csrf and _method back: a form redisplayed after a validation failure gets those fields empty.

  • HealthCheck (the root-export class) reports a check that throws as Health check failed instead of the thrown message, and a timeout as Health check timed out after <ms>ms without the check's name (it is in name). The thrown error goes to the new onError option, stderr by default: pass onError to send it to your logger.

  • A codemod or a make:* generator no longer writes through a symbolic link to a path that does not exist: addEnvVars, writeFile, makeUsingStub and the reamrc.ts / start/kernel.ts / start/env.ts codemods throw E_CODEMODS_UNSAFE_PATH, a generator skips it (E_REAM_STUB_UNSAFE_PATH with --force). writeFile now refuses an existing link out of the project even without force. Replace such a link with a regular file. A .env that addEnvVars creates has mode 0600.

  • A resolver's bound values (the request's HttpContext, anything bound with ctx.containerResolver.bindValue()) are no longer visible to async work that outlives the resolution: a timer or an unawaited promise started while a service was being built for a request now gets E_CONTAINER_NOT_FOUND from make(HttpContext) instead of that request's context. Hand such work the data it needs when it is scheduled.

  • In development, the /__ream/ pages (profiler, toolbar assets, reload stream) answer 403 to a Host that is not an IP address, localhost, a .localhost name or the bind host, and to a cross-site request. Opening them through another name (a tunnel, a .test domain) needs allowedHosts: ['that.name'] on the Ignitor.

  • route.middleware('auth') and group.middleware('auth') now find a middleware declared with router.named({ auth }). Before, only names given to middleware.register() or Ignitor.named() resolved, and the route answered 500 E_MIDDLEWARE_NOT_FOUND on every request. A name nothing declares now stops the application at boot (when the HTTP kernel is built) with E_MIDDLEWARE_NOT_FOUND, naming the route: fix the name, or declare it in router.named(). RPC methods and GraphQL resolvers find router.named() names too.

  • The middlewares of router.use() now run before the route's named middlewares, as the documented order says. Before, a named middleware ran first, so a named auth that reads the session or the user found by @c9up/warden/silent-auth refused every request. A named middleware that relied on running before the router stack must move into it. MiddlewareRegistry.buildChain() takes the router stack as routerMiddleware, not mixed into the inline list.

See also ​