npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@fluojs/runtime

v3.1.2

Published

Application bootstrap and runtime orchestration — module graph compilation, DI wiring, and diagnostics export for Fluo.

Downloads

1,172

Readme

@fluojs/runtime

The assembly layer that compiles a module graph and wires DI and HTTP into a runnable application shell.

Preparing for the coordinated Node 24 release? Follow the consumer migration guide before upgrading packages.

Table of Contents

Installation

npm install @fluojs/runtime

The published package intentionally declares no package-wide engines.node: its root, ./web, and runtime-neutral internal seams contain no eager Node builtin imports and are shared by Node, Bun, Deno, Cloudflare Workers, and other Web-standard hosts. Node listener, filesystem, logger, compression, and process-signal responsibilities live in @fluojs/platform-nodejs, which declares the verified Node engine range.

Node Static Asset Source

@fluojs/http owns portable static middleware and representation-selection contracts. @fluojs/platform-nodejs exports createNodeFileSystemAssetSource(...), its Node filesystem StaticAssetSource implementation: it validates the root directory during configuration, keeps lexical and realpath resolution inside that root (including symlink checks), and can select .br or .gz siblings. For each selected regular-file representation, it opens the verified file, eagerly copies the entire file into an immutable byte snapshot, and closes its FileHandle before response writing. Its returned source() replays only that snapshot and never reopens or lazily streams the pathname; application owners therefore bound memory by the selected whole-file size, and size plus the strong ETag describe those exact bytes. Raw Node, Express, and Fastify adapters share this portable middleware/source seam and preserve the selected representation boundary rather than applying adapter-specific re-encoding. This Node-only helper is intentionally absent from @fluojs/runtime/web; Web and edge deployments must provide an application-owned source.

When to Use

Use this package when you need to:

  • Bootstrap a fluo application: Convert your modules into a running HTTP server or microservice.
  • Orchestrate DI and Lifecycle: Manage module-graph compilation, provider wiring, and application hooks (onModuleInit, onApplicationBootstrap).
  • Create Standalone Contexts: Run CLI tasks, scripts, or workers that need DI but not an HTTP server.
  • Diagnostic Inspection: Produce machine-readable platform snapshots, compiled route catalogs, and diagnostic issues for CLI export while leaving graph viewing and Mermaid presentation to Studio.

Quick Start

Minimal HTTP Application

The FluoFactory is the primary entrypoint for creating applications.

import { Module } from '@fluojs/core';
import { Controller, Get } from '@fluojs/http';
import { FluoFactory } from '@fluojs/runtime';
import { NodeHttpApplicationAdapter } from '@fluojs/platform-nodejs';

@Controller('/')
class AppController {
  @Get()
  index() {
    return { hello: 'world' };
  }
}

@Module({
  controllers: [AppController],
})
class AppModule { }

// Create and start the application
const app = await FluoFactory.create(AppModule, {
  adapter: NodeHttpApplicationAdapter.create({ port: 3000 }),
});

await app.listen();

The @Get() above uses the empty relative path, so the controller serves GET /. With @Controller('cats') it would serve /cats, not bypass the prefix. An empty @Module() can also bootstrap and close without inventing providers.

Common Patterns

Canonical HTTP Factory

Use FluoFactory.create(AppModule, { adapter }) → app.listen() → app.close() as the only HTTP creation path. logger registers the exact supplied object as APPLICATION_LOGGER; omission selects the portable console logger. Factory composes configured CORS → global prefix/exclusions → default security headers → caller middleware; module middleware follows route matching. CORS/prefix default off, security headers default on, and securityHeaders: false opts out.

Readiness/listen/startup-log/host-registration failures clean acquired resources through close('bootstrap-failed') and preserve the initiating error. Create a new app to start again. Optional shutdownRegistration is supplied by the host and runs only after listen. Omission or close before listen installs no signals. Node callers can supply createNodeShutdownSignalRegistration() from @fluojs/platform-nodejs.

Signal unregistration is attempted once and never skips runtime teardown on failure. Concurrent and later closes share its failure, aggregating with other teardown failures. Once runtime resources close, state is closed even if signal unregistration failed. app.get(PublicToken<T>) infers Promise<T> and checks admission around asynchronous resolution. Use app.dispatch() for ordinary requests; direct container and dispatcher access remains a low-level integration surface without that same gate.

See the HTTP Factory migration and lifecycle contract.

Health endpoint middleware

HealthModule.forRoot() accepts class-based endpointMiddleware for its generated health and readiness routes. Middleware resolves through DI, runs in declaration order, and applies to both normalized endpoints under an optional custom path; omitting it preserves the default behavior.

HealthModule.forRoot({
  endpointMiddleware: [HealthProbeAuthMiddleware],
  path: '/internal/',
});

This configuration applies HealthProbeAuthMiddleware to /internal/health and /internal/ready, not to unrelated application routes.

Streaming multipart consumption

Use parseMultipartStream(...) from @fluojs/runtime/web for a standalone raw Request or request-like body when large uploaded files must not be materialized as Uint8Array values. The existing parseMultipart(...) API remains the explicit buffered mode. Select exactly one mode for a request: buffered and streaming parsing of the same body reject with MultipartBodyConsumedError.

import {
  parseMultipartStream,
  type MultipartFilePart,
} from '@fluojs/runtime/web';

for await (const part of parseMultipartStream(request, {
  maxFieldSize: 1 * 1024 * 1024,
  maxFields: 20,
  maxFiles: 4,
  maxFileSize: 20 * 1024 * 1024,
  maxHeaderSize: 8 * 1024,
  maxTotalSize: 25 * 1024 * 1024,
})) {
  if (part.kind === 'field') {
    continue; // part.name and part.value
  }

  const file: MultipartFilePart = part;
  await store(file.stream); // finish or cancel before reading the next part
}

For Node.js, Express, Fastify, and Web application dispatch, opt in at application bootstrap with multipart.strategy: 'stream'. The route receives the same AsyncIterable<MultipartPart> through RequestContext.request.body; adapter dispatch creates the iterator but does not pull or buffer it before the route consumes it.

import { FluoFactory } from '@fluojs/runtime';
import { createConsoleApplicationLogger, NodeHttpApplicationAdapter } from '@fluojs/platform-nodejs';
const app = await FluoFactory.create(AppModule, {
  adapter: NodeHttpApplicationAdapter.create({
    multipart: {
      strategy: 'stream',
      maxTotalSize: 25 * 1024 * 1024,
    },
  }),
  logger: createConsoleApplicationLogger(),
});

@Controller('/uploads')
class UploadController {
  @Post('/')
  async upload(_input: undefined, context: RequestContext) {
    for await (const part of context.request.body as AsyncIterable<MultipartPart>) {
      // Consume each file stream before advancing to the next part.
    }
  }
}

Streaming mode applies bounded field and header defaults. Buffered parseMultipart(...) preserves its prior acceptance behavior for fields and headers unless maxFieldSize, maxFields, or maxHeaderSize is explicitly configured.

MultipartFilePart.stream is a Web ReadableStream<Uint8Array> with parser-driven backpressure: a file body is yielded before the complete request arrives, and the next request chunk is read only when the active file stream needs it. File-stream cancellation, request abort, parser failures, and every size/count/header limit cancel the active source and release the parser. The parser accepts native Fetch Request values plus native async-iterable Node/Express/Fastify request streams (directly or as MultipartRequestLike wrappers); it never exposes adapter-native multipart objects or temporary-file APIs.

Optional Early Hints capability

The runtime preserves the adapter-owned optional context.response.earlyHints capability without making it part of the required response method surface. Node.js, Express, and Fastify responses provide the writer; Web-standard response factories omit it so Bun, Deno, Workers, and custom Fetch hosts are detectable as unsupported before use. Early writes remain independent from final status, headers, body, and commit ownership. See the @fluojs/http Early Hints contract.

Conditional request bootstrap

Runtime bootstrap accepts the conditionalRequest option from @fluojs/http. Its resolver returns explicit representation existence plus optional validators; it runs after middleware and guards, before interceptors and controller invocation. See the @fluojs/http Conditional Requests contract for the resolver shape, RFC 9110 precedence, and HEAD rules.

Access log observers

Pass createAccessLogObserver(...) through the bootstrap observers option to route portable request lifecycle records to application-owned structured logging. The observer preserves the dispatcher lifecycle for native adapters by selecting the complete fallback path; see the @fluojs/http Access logging contract for trusted client identity and header allowlist requirements.

HTTP binder composition

Scope and inputs: BootstrapApplicationOptions and CreateApplicationOptions accept binder?: (defaultBinder: Binder) => Binder. Import bootstrap APIs from @fluojs/runtime and the Binder contract and StandardSchemaBinder from @fluojs/http. Omission preserves the existing default HTTP binding pipeline. CreateApplicationContextOptions excludes binder: pure DI contexts do not create an HTTP dispatcher.

The synchronous factory runs once per HTTP application bootstrap, when runtime assembles the dispatcher, not once per request. It receives the default binder already configured with global converters. Delegate ordinary DTOs to that binder rather than constructing an unrelated default and losing those settings. The returned binder is reused by the application's dispatcher.

This bootstrap fragment assumes an existing AppModule with registered controllers; see the complete schema route example.

import { StandardSchemaBinder } from '@fluojs/http';
import { NodeHttpApplicationAdapter } from '@fluojs/platform-nodejs';
import { FluoFactory } from '@fluojs/runtime';
import { AppModule } from './app.js';

const app = await FluoFactory.create(AppModule, {
  adapter: NodeHttpApplicationAdapter.create({ host: '127.0.0.1', port: 3000 }),
  binder: (defaultBinder) => new StandardSchemaBinder(defaultBinder),
});
await app.listen();

FluoFactory.create(AppModule, options) accepts the same factory. Existing converters can be supplied alongside binder; they continue to run through the fallback for ordinary DTOs. Schema tokens instead use their schema's conversion/default rules. Do not pass a binder instance or an async factory where this callback is expected.

Failures and ownership: a result without a callable bind method rejects bootstrap with TypeError; factory exceptions propagate through existing bootstrap-failure cleanup. Runtime wires the binder but does not add a binder disposal hook. Application-owned external resources still need their normal lifecycle registration. The host owns shutdown and calls app.close(); the fragment above does not register process signals. This option changes neither native body parsing nor HEAD behavior. HTTP owns projection, validation errors, and request order; see its input policy contract.

Evidence: src/types.ts, src/bootstrap.ts, and ../testing/src/input-materialization.e2e.test.ts are the option, composition, and application-boundary regression locations.

Application Context (No HTTP)

For background workers or scripts, use createApplicationContext to skip HTTP setup.

import { FluoFactory } from '@fluojs/runtime';

const context = await FluoFactory.createApplicationContext(AppModule);

// Resolve a service directly from the container
const userService = await context.get(UserService);
await userService.doWork();

await context.close();

Migrating PlatformShell Lifecycle Overlap

RuntimePlatformShell.start() and stop() are strictly exclusive. While either transition is active, every overlapping start() or stop() call returns an immediately rejected promise with PlatformLifecycleConflictError, code PLATFORM_LIFECYCLE_CONFLICT, and activeOperation / requestedOperation on both the error and its structured meta. isPlatformLifecycleConflictError(...) validates those fields and the versioned runtime owner contract across compatible duplicate copies. The shell never shares, queues, or coalesces overlapping work. Sequential calls made after settlement remain idempotent, and failed transitions release the exclusive gate so callers can retry explicitly.

In @fluojs/runtime 2.x, overlapping start() calls could start the same components more than once, and stop() called during an in-flight startup could return before startup settled and leave resources running. When upgrading, give one application boundary ownership of each lifecycle transition. If another path can overlap, catch PlatformLifecycleConflictError, wait for the boundary-owned transition to settle, and retry explicitly only if the desired state is still required. Do not recreate a hidden queue around callback reentry; component lifecycle callbacks receive the same immediate conflict after synchronous code or arbitrary await boundaries.

Migrating NestJS Lifecycle Hooks

The public runtime lifecycle contract has four hooks: startup runs onModuleInit() and then onApplicationBootstrap(), while shutdown runs onModuleDestroy() and then onApplicationShutdown(signal?) in reverse lifecycle-instance order. Each eligible singleton multi: true contribution is a distinct lifecycle instance: startup follows contribution order and shutdown reverses it. NestJS beforeApplicationShutdown is unsupported and is not probed or invoked by fluo.

Move shutdown preparation into the documented phase that owns it. Use onModuleDestroy() for module-resource teardown that must finish before the application-wide signal phase, or onApplicationShutdown(signal?) for signal-aware application cleanup. @fluojs/runtime provides no beforeApplicationShutdown compatibility shim, alias, fallback, or additional runtime hook.

NestJS app.enableShutdownHooks() is not an implicit default. On Node, opt into SIGINT/SIGTERM with FluoFactory.create(AppModule, { adapter, shutdownRegistration: createNodeShutdownSignalRegistration() }). Fetch hosts do not install Node signals; the host calls app.close(signal?).

Lifecycle hooks are not the listener-close or connection-drain phase. During app.close(signal?), fluo runs the shutdown hooks before adapter.close(signal?); migrated cleanup that requires a closed listener or completed adapter drain belongs at the adapter or host shutdown boundary after close, not in a same-named lifecycle hook.

Studio Devtools Bridge

@fluojs/runtime can publish live Studio snapshots and request traces without reading process.env directly. fluo dev --studio remains the default Node path: the CLI starts the sidecar, creates tokenized Studio config, and injects it before the app imports runtime. Runtime reads those injected fields once, validates the HTTP(S) endpoint, and keeps a frozen private snapshot, so later mutation of the legacy process-global cannot change instrumentation inputs.

Package integrations can instead import StudioDevtoolsRuntime and its transport contracts from @fluojs/runtime/devtools, then pass a host-owned bridge through studioDevtools to FluoFactory.create(...), or FluoFactory.createApplicationContext(...). An explicit bridge takes precedence over CLI injection and needs no process-global mutation:

import { FluoFactory } from '@fluojs/runtime';
import { StudioDevtoolsRuntime } from '@fluojs/runtime/devtools';

const studioDevtools = new StudioDevtoolsRuntime({
  appId: 'my-bun-app',
  runtime: 'bun',
  transport: { publish: (event) => hostStudioTransport.send(event) },
});

const app = await FluoFactory.create(AppModule, { studioDevtools });

This package publishes a transport-neutral seam, not Bun, Deno, or Cloudflare Workers sidecar implementations. A non-Node host is live-Studio supported only when its owner supplies a bridge and executable host integration evidence; otherwise use the inspect/static artifact path. Live route descriptors include the exact graphNodeId of their route node; Runtime retains the existing node-ID format while Studio consumes this explicit correlation instead of reproducing it. Request traces intentionally omit bodies, cookies, and full headers, and runtime strips query strings/fragments from the trace url before publishing events so local tokens are not copied into Studio event history. Failed-request events use only the fixed Request failed message and never include raw exception text, names, stacks, causes, or stringified values.

Global Exception Filters

Handle cross-cutting errors by registering filters during bootstrap.

import { FluoFactory, type ExceptionFilterHandler } from '@fluojs/runtime';

class GlobalErrorFilter implements ExceptionFilterHandler {
  async catch(error, { response }) {
    console.error('Caught error:', error);
    response.setStatus(500);
    void response.send({ error: 'Internal Server Error' });
    return true; // Mark as handled
  }
}

const app = await FluoFactory.create(AppModule, {
  adapter: NodeHttpApplicationAdapter.create({ port: 3000 }),
  filters: [new GlobalErrorFilter()],
});

Content negotiation

FluoFactory.create(...) accepts contentNegotiation and forward it unchanged to the HTTP dispatcher. Configure formatters once at the application boundary and use @Produces(...) on routes to select their allowed representations:

import { Controller, Get, Produces } from '@fluojs/http';
import { FluoFactory } from '@fluojs/runtime';

@Controller('/reports')
class ReportController {
  @Produces('application/json', 'text/plain')
  @Get('/')
  getReport() {
    return { ok: true };
  }
}

const app = await FluoFactory.create(AppModule, {
  contentNegotiation: {
    defaultMediaType: 'application/json',
    formatters: [
      { mediaType: 'application/json', format: JSON.stringify },
      { mediaType: 'text/plain', format: (value) => `plain:${JSON.stringify(value)}` },
    ],
  },
});

Runtime does not parse Accept or own response policy. @fluojs/http applies the documented quality, wildcard, suffix, default, malformed-input, and 406 semantics and emits canonical Vary: Accept for every successful formatter selection. Standalone application contexts do not create an HTTP dispatcher, so they do not use this option. See the HTTP package contract.

Optional HTML Error Representations

FluoFactory.create(...) accepts CreateApplicationOptions.errorRepresentation, inherited from BootstrapApplicationOptions.errorRepresentation, and passes it unchanged to the HTTP dispatcher. Register an application-owned provider when negotiated browser requests should receive complete HTML error or not-found documents while JSON remains canonical:

function escapeHtml(value: string): string {
  return value
    .replaceAll('&', '&amp;')
    .replaceAll('<', '&lt;')
    .replaceAll('>', '&gt;')
    .replaceAll('"', '&quot;')
    .replaceAll("'", '&#39;');
}

const app = await FluoFactory.create(AppModule, {
  adapter: NodeHttpApplicationAdapter.create({ port: 3000 }),
  errorRepresentation: {
    html: {
      render({ json }) {
        return `<!doctype html><main>${json.error.status}: ${escapeHtml(json.error.message)}</main>`;
      },
    },
  },
});

Runtime only wires this option. @fluojs/http owns error classification, Accept negotiation, request scope, response status and headers, HEAD, abort, commit, and canonical JSON fallback. The returned string or bytes are trusted application HTML: runtime does not escape or sanitize request-derived or error-derived values, so the provider must do so before interpolation. Standalone application contexts do not use the option because they do not create an HTTP dispatcher. See the HTTP package contract.

Framework-Managed and Handler-Owned Responses

The normal request path is framework-managed: a handler returns a value, interceptors may transform it, and the runtime response writer commits it. This is the path where @fluojs/serialization can apply SerializerInterceptor to a returned DTO.

Advanced handlers can instead take response ownership by calling RequestContext.response.send(...), redirect(...), or a manual streaming helper. Once that response is committed, SerializerInterceptor, when present, bypasses serialization and returns the value it received from next.handle() unchanged. This does not freeze the chain result: other interceptors may still transform it. Independently, the dispatcher sees the committed response and skips a second success-response write, so it does not write the final interceptor-chain result. Direct response code must therefore produce the final safe payload before committing; a serializer cannot reshape it afterward.

Module Composition

fluo uses a strict module graph. Modules must explicitly export providers to make them available to importing modules.

@Module({
  providers: [DatabaseService],
  exports: [DatabaseService], // Make it available outside
})
class DatabaseModule {}

@Module({
  imports: [DatabaseModule],
providers: [UsersService], // UsersService can inject DatabaseService
})
class UsersModule {}

Behavioral Contracts

  • Framework-owned runtime injection tokens use stable same-realm identities, so compatible duplicate copies can register and consume the same application-owned container, adapter, platform-shell, cleanup, compiled-module, provider-set, and bootstrap-readiness contracts. This does not globalize application state or change service constructor-token identity.
  • Runtime lifecycle remains a four-hook contract. Startup completes the provider-ordered onModuleInit() phase before onApplicationBootstrap(); shutdown reverses lifecycle-instance order for onModuleDestroy() and then onApplicationShutdown(signal?). Every eligible singleton multi: true contribution participates as its own instance in contribution order. NestJS beforeApplicationShutdown is unsupported and has no compatibility shim.
  • Request body parsing enforces maxBodySize while bytes are still streaming for both Web-standard and Node-backed requests. Oversized Web bodies settle as HTTP 413 without waiting for stream cancellation, and cancellation failures do not mask that response, including on the default cloned-body path where the original request remains unread.
  • preferNativeJsonBodyReader remains accepted by @fluojs/runtime/web as a deprecated adapter compatibility option, but it no longer changes parsing. Web JSON bodies always use the bounded streaming reader so native whole-body reads cannot bypass maxBodySize.
  • On @fluojs/platform-nodejs, Node request body parsing normalizes the primary content-type media type before JSON and multipart detection, so mixed-case JSON and multipart headers preserve the documented parser behavior.
  • Node-backed and Web-standard request wrappers snapshot cheap request metadata before body parsing, then materialize body/rawBody once at the dispatch boundary so userland continues to observe synchronous parsed values.
  • Node-backed cookies/query values and Web-standard headers are snapshotted when the request wrapper is created, then lazily normalized and memoized per request; later upstream object mutations do not change the FrameworkRequest view.
  • Node-backed request context IDs prefer x-request-id and fall back to x-correlation-id when x-request-id is absent, so error responses and request-aware integrations keep the upstream correlation identifier.
  • ApplicationContext.get() and Application.get() memoize only direct root singleton class/factory provider lookups known at bootstrap, while preserving alias, request, transient, post-close, multi-provider, and container.override() resolution semantics.
  • multi: true provider tokens are not context-cache memoized: each get() call delegates to DI so the container can assemble a fresh contribution array while still reusing each contribution according to its own provider scope.
  • When duplicateProviderPolicy is warn or ignore, context-cache eligibility and lifecycle hook execution are based on the effective winning provider selected by bootstrap; stale losing providers do not seed cache entries or lifecycle hooks.
  • Module graph compilation validates runtime and @Module(...) provider declarations through DI's canonical normalization before cache-key generation or visibility traversal. Malformed inject values, dependency wrappers/tokens, and scopes therefore fail with InvalidProviderError instead of leaking traversal-specific errors.
  • If application or context bootstrap fails after runtime resources or lifecycle instances have been created, fluo resets readiness, runs registered runtime cleanup callbacks, invokes shutdown hooks for instances resolved so far with bootstrap-failed, disposes the container, logs cleanup failures, and rethrows the original bootstrap error.
  • Application.listen() and microservice listen() are serialized with shutdown: overlapping startup calls share the same in-flight startup, shutdown waits for in-flight startup to settle, and a startup that races with shutdown cannot transition the shell back to ready after close begins. The public Application.state contract remains bootstrapped or ready while teardown is pending and changes to closed only after teardown completes successfully. Independently, starting application or context close synchronously closes a terminal operation gate: Application.get(), ApplicationContext.get(), connectMicroservice(), startAllMicroservices(), and application listen() reject while teardown is pending and stay rejected after a failed close attempt. Provider lookups admitted immediately before close recheck that gate after asynchronous resolution and cannot return a stale value after shutdown starts. A later close() skips completed runtime teardown phases and re-enters incomplete adapter or lifecycle-hook stages according to their own retry contracts. Container-managed onDestroy() hooks are terminal best-effort cleanup: every materialized hook is attempted on the first container disposal, failed hooks are retried by a later explicit application or context close(), and hooks that completed successfully are never run again. Once microservice close starts, a terminal ingress gate rejects new send() and emit() calls before runtime or transport handoff, including while listen() is still pending and after a failed close attempt.
  • Application.dispatch() uses that same synchronous terminal admission gate. A direct dispatch started after Application.close() begins rejects before entering the HTTP dispatcher, including while teardown is pending, after a failed close, and after successful close. A dispatch admitted before the gate closes remains dispatcher-owned and is not retroactively cancelled by close.
  • @fluojs/platform-nodejs owns each pending raw Node listen operation and its EADDRINUSE retry timer. Calling adapter close() while startup is retrying cancels the retry, waits for the pending listen to settle, and prevents the listener from binding after shutdown reports completion.
  • Factory post-listen shutdownRegistration failure closes the created application with bootstrap-failed and rejects with the original registration failure independently of cleanup errors. The Node host callback rolls back partially installed handlers.
  • Shutdown signal unregistration failures do not skip application close: app.close() always continues through adapter shutdown, lifecycle hooks, runtime cleanup callbacks, and container disposal; if close otherwise succeeds it rejects with the unregistration error, and if close also fails it rejects with an aggregate containing both failures.
  • Connected microservices are owned children of their parent Application: startAllMicroservices() starts them sequentially and rolls back already-started children with bootstrap-failed if a later child fails, while Application.close(signal) closes connected children before parent lifecycle hooks, adapter shutdown, and container disposal.
  • FluoFactory.createMicroservice() preserves the original bootstrap/runtime-resolution error when cleanup fails and logs cleanup failures separately.
  • Bootstrap resolves independent singleton lifecycle providers concurrently, then runs lifecycle hooks in deterministic provider order.
  • Multipart parsing rejects payloads when the cumulative body size exceeds the configured multipart.maxTotalSize; runtime adapters default that limit to maxBodySize unless you override it.
  • @fluojs/runtime/web multipart parsing uses Web-standard TextEncoder and Uint8Array primitives without requiring the Node.js Buffer global. Uploaded file buffer values are Uint8Array; Node-only consumers can convert them explicitly with Buffer.from(file.buffer) at their application boundary.
  • @fluojs/runtime/web exposes two mutually exclusive multipart consumption modes: parseMultipart(...) buffers fields and files, while parseMultipartStream(...) yields discriminated field/file parts and never materializes complete file payloads. Streaming mode enforces per-field, per-file, total-size, field-count, file-count, and header limits while bytes are read; abort, cancellation, and parser failures cancel the active source. A body selected by either mode rejects a second buffered or streaming selection with MultipartBodyConsumedError.
  • NodeHttpApplicationAdapter.create(...) accepts maxBodySize only as a non-negative integer byte count and fail fast during adapter creation/bootstrap when the value is invalid.
  • Response stream backpressure helpers settle waitForDrain() on drain, close, or error so streaming writers do not hang on dead connections.
  • HTTP application bootstrap passes an optional application-owned errorRepresentation.html provider to the dispatcher without taking representation ownership. Canonical JSON remains the default; HTTP keeps classification, negotiation, status/header, HEAD, abort, commit, and fallback semantics.
  • HTTP response writing is single-owner: framework-managed handler results may be transformed by interceptors before the runtime commits them. Once a handler or response helper commits RequestContext.response, the dispatcher skips a second success-response write. SerializerInterceptor bypasses serialization and returns the value it received from next.handle() unchanged, while other interceptors may still transform the chain result.
  • Runtime health modules report /ready as starting with HTTP 503 until bootstrap marks them ready, and they return to starting as soon as application/context shutdown begins, including failed shutdown attempts.
  • Runtime health module readiness checks receive the current RequestContext, allowing public integrations to resolve runtime-exposed status providers without importing internal runtime tokens.
  • Signal-driven shutdown helpers preserve bounded drain semantics, log timeout/failure conditions, and set process.exitCode when shutdown does not finish cleanly, but they leave final process termination ownership to the surrounding host runtime.
  • Platform snapshot and diagnostic issue production stay in runtime; graph viewing, filtering presentation, and Mermaid rendering are Studio-owned contracts consumed by CLI and automation callers.
  • Compiled route inspection is a one-way projection from HandlerDescriptor values. Effective method, path, version, params, module, controller, and handler fields are copied into frozen entries; ordinary routes use kind: 'http', while runtime-aware integrations can publish a more specific marker such as react-page. Route inspection never participates in matching, conflict detection, or dispatch and does not retain request body, cookie, header, query-value, or other request-private data.
  • Legacy route-inspection markers written by compatible same-realm integration copies remain discoverable by runtime inspection copies. The marker stays an immutable projection detail and does not change route matching, conflict detection, dispatch, or request-private data ownership.
  • Runtime-connected Studio instrumentation accepts either an explicit host-owned studioDevtools bridge or the default CLI-injected Node config, never direct process.env reads. The documented @fluojs/runtime/devtools subpath exposes transport-neutral bridge contracts so package integrations do not need private imports or process-global mutation. Explicit bridges take precedence; CLI config is captured once into a validated, frozen private snapshot and remains the no-op fallback when neither bridge nor valid config is present.
  • Studio request traces omit request/response bodies, cookies, and full headers; the trace url is sanitized to path-only form before publish so query tokens and fragments are not retained in local Studio event history.
  • Platform component snapshots are runtime-owned contract payloads: each component reports readiness, health, dependency ids, telemetry tags, diagnostic issues, and resource ownership through ownership.ownsResources / ownership.externallyManaged. Runtime preserves those ownership flags in shell snapshots so adapters and package integrations can distinguish resources fluo must stop from externally managed resources the host owns.
  • Runtime retains distinct lifecycle diagnostics from validation, start, rollback, and stop. Failures produced by repeatable ready(), health(), and snapshot() probes are bounded to the latest failure for each component and probe phase, so long-running polling cannot grow PlatformShellSnapshot.diagnostics without bound while the latest cause remains visible.
  • RuntimePlatformShell.start() and stop() enforce one strictly exclusive lifecycle transition. Every overlapping operation, including a same-operation call or callback reentry after arbitrary awaits, receives an immediate PlatformLifecycleConflictError rejection instead of shared or queued work. The active transition is published before component work begins, failed transitions release it by identity, and explicit retry after settlement preserves sequential idempotency, dependency ordering, private startup rollback, and cleanup retry behavior.
  • Module graph compile-result caching is opt-in through moduleGraphCache: true; its process-local cache retains at most 100 least-recently-used successful snapshots, keys entries by root module identity, runtime providers, validation tokens, module replacement pairs, core metadata versions, and the compile algorithm version, and returns isolated graph copies so caller mutations cannot poison later bootstraps. Hosts that need application-owned lifetime control can pass new ModuleGraphCompileCache(maxEntries) instead and call dispose() during application teardown.
  • moduleReplacements is a low-level testing seam on bootstrapModule(...) / BootstrapModuleOptions. It compiles replacement module metadata while preserving the original logical module identity, rejects replacement cycles through the normal module graph validation path, and does not mutate source module metadata.
  • raceWithAbort(fn, signal) always removes its abort listener once fn settles, including when fn throws synchronously before returning a promise. The synchronous throw is converted into a settled rejection so the cleanup-dependent finally flow still runs and the listener is not leaked across repeated failed operations.

Public API Overview

  • FluoFactory: Class-based runtime bootstrap facade with explicit static access.
  • Application: Extends ApplicationContext with listen(), dispatch(), and state.
  • ApplicationContext: Provides get<T>(token), close(), and access to container, modules, and bootstrap diagnostics.
  • LifecycleHooks: Convenience union covering OnModuleInit, OnApplicationBootstrap, OnModuleDestroy, and OnApplicationShutdown.
  • MicroserviceRuntime: Transport contract resolved by FluoFactory.createMicroservice(...). Implementations expose listen(), optional send()/emit(), and an optional close(signal?). The optional markShutdownStarted() hook is invoked synchronously when the owning shell begins shutdown so implementations can close their own ingress gate before any awaited cleanup, keeping new send()/emit()/listen() attempts rejected even while a racing listen() is still settling.
  • HealthModule.forRoot(options): Runtime-owned /health and /ready module facade whose readiness marker follows bootstrap and shutdown lifecycle transitions. It returns a RuntimeHealthModule so first-party runtime-aware packages can register ReadinessCheck functions without importing internal runtime seams.
  • RuntimeHealthModule: Module class contract returned by HealthModule.forRoot(...), including addReadinessCheck(...), markReady(), and markStarting().
  • ReadinessCheck: Function type used by runtime health modules. Checks receive the /ready request context and return a boolean or promise.
  • defineModule(cls, metadata): Programmatic module definition helper.
  • CreateApplicationOptions: Accepts logger, middleware policies, optional host shutdownRegistration, and HTTP dispatcher options. BootstrapApplicationOptions remains an existing integration type, not another creation function.
  • @fluojs/runtime/devtools: Package-integration subpath for StudioDevtoolsRuntime, its transport contracts, and live Studio event contracts. Pass the created bridge as studioDevtools during application or context bootstrap.
  • bootstrapModule(...): Lower-level module graph bootstrap helper. Its BootstrapModuleOptions include moduleGraphCache for opt-in compile-result caching and moduleReplacements / ModuleReplacementMap for testing-only module replacement compilation that keeps authored module identities stable.
  • ModuleGraphCompileCache: Bounded caller-owned module graph compile cache. Pass an instance as moduleGraphCache and call dispose() when its application or host lifetime ends.
  • createBootstrapTimingDiagnostics(...), createRuntimeDiagnosticsGraph(...): Runtime-owned diagnostics snapshot helpers for CLI/support tooling. They produce machine-readable data; Studio owns viewer parsing, graph presentation, and Mermaid rendering.
  • createRuntimeRouteInspection(...), createRuntimeRouteCatalog(...), and createRuntimeInspectionSnapshot(...): Runtime-owned immutable projections that add effective compiled route diagnostics to platform snapshots without changing HTTP route behavior.
  • RuntimeRouteInspection and RuntimeInspectionSnapshot: Serializable read-only route and inspect artifact contracts. RuntimeRouteInspection.params contains parameter names only, never request values.
  • PlatformShell, PlatformComponent, PlatformShellSnapshot, PlatformSnapshot, PlatformDiagnosticIssue, and related platform report types: Public lifecycle diagnostics and resource-ownership contracts used by runtime-aware packages. RuntimePlatformShell preserves component-provided ownership and emits validation/readiness/health diagnostics without requiring consumers to import internal runtime tokens.
  • PlatformLifecycleOperation, PlatformLifecycleConflictError: Root-exported lifecycle conflict contracts. The error uses code PLATFORM_LIFECYCLE_CONFLICT and exposes matching activeOperation / requestedOperation fields and structured metadata.
  • createRequestAbortContext(...), trackActiveRequestTransaction(...), untrackActiveRequestTransaction(...): Request abort and active transaction helpers used by runtime-aware integrations.
  • UploadedFile: Runtime-neutral multipart file descriptor whose in-memory buffer payload is a Web-standard Uint8Array.
  • MultipartFieldPart, MultipartFilePart, MultipartPart, and MultipartBodyConsumedError: Typed streaming multipart contracts. MultipartFilePart.stream is single-consumer and must settle before iteration requests the following part.

Runtime-Specific Entry Points

Use @fluojs/platform-nodejs for Node-host responsibilities and @fluojs/runtime/web for portable Web-standard helpers. Runtime's published internal* subpaths remain runtime-neutral package-integration seams for first-party adapters and runtime-aware packages.

Migration is direct and intentionally has no compatibility shim:

| Removed import | Replacement | | :--- | :--- | | @fluojs/runtime/node | @fluojs/platform-nodejs | | @fluojs/runtime/internal-node | @fluojs/platform-nodejs/internal |

Use the supported Node adapter, logger, filesystem, and shutdown registration exports at the replacement entrypoint. Duplicate Nodejs aliases and platform bootstrap/run exports are removed.

| Subpath | Purpose | | :--- | :--- | | @fluojs/platform-nodejs | Supported Node.js entrypoint for logger factories, the concrete Node adapter, and shutdown signal registration. | | @fluojs/runtime/web | Shared Web-standard request/response utilities for Bun, Deno, and Cloudflare Workers, including createWebRequestResponseFactory, dispatchWebRequest, createWebFrameworkRequest, buffered parseMultipart, and streaming parseMultipartStream. | | @fluojs/runtime/internal | Internal package-integration seam for runtime wiring tokens, runtime-owned metadata and route-inspection helpers, plus defineModule(...) and createRuntimeRouteInspection(...) for first-party runtime-neutral integrations that must align with compiled runtime descriptors. | | @fluojs/platform-nodejs/internal | Node-only internal seam for adapter/runtime plumbing; prefer @fluojs/platform-nodejs in application code. | | @fluojs/runtime/internal/http-adapter | Internal HTTP adapter seam for platform packages. | | @fluojs/runtime/internal/request-response-factory | Internal request/response factory seam for platform packages. |

Node-Specific Package (@fluojs/platform-nodejs)

Logger factories, createNodeFileSystemAssetSource({ root, precompressed }) for eager immutable Node/Express/Fastify static asset snapshots, and other supported Node-only helpers are not on the portable runtime root. Import them from the Node platform package:

import {
  createConsoleApplicationLogger,
  createJsonApplicationLogger,
  createNodeFileSystemAssetSource,
  NodeHttpApplicationAdapter,
  type NodeFileSystemAssetPrecompression,
  type NodeFileSystemAssetSourceOptions,
} from '@fluojs/platform-nodejs';
const adapter = NodeHttpApplicationAdapter.create({
  port: 3000,
  maxBodySize: 1_048_576,
});

For the public Node runtime surface, maxBodySize, retryDelayMs, retryLimit, and shutdownTimeoutMs are number-only non-negative integers. Values such as '1mb', fractional retry counts, or negative shutdown timeouts are rejected immediately during adapter creation instead of being coerced later. Node request context IDs prefer x-request-id; when it is absent, x-correlation-id is used as the request ID fallback for runtime error responses and request-aware integrations.

  • createConsoleApplicationLogger(): Colorized console logger using process.stdout/process.stderr. The default remains the pretty format. Pass { mode: 'minimal' } for concise [fluo] LEVEL [context] message lines, { mode: 'silent' } to suppress runtime logger output, { level: 'warn' } or another threshold to filter lower-severity messages, and { color: false } when you need deterministic non-colored output.
  • createJsonApplicationLogger(): Structured JSON logger using process.stdout/process.stderr.
  • createNodeFileSystemAssetSource(options): Node-only filesystem implementation of the @fluojs/http StaticAssetSource contract. NodeFileSystemAssetSourceOptions names its { root, precompressed } boundary and NodeFileSystemAssetPrecompression selects .br / .gz siblings. Each accepted representation is securely opened, eagerly copied into an immutable in-memory byte snapshot, and its FileHandle is closed before middleware response writing. The returned source() only replays that snapshot; it never reopens the pathname. Application owners therefore bound memory by the selected asset size, while size and the strong ETag describe those exact snapshot bytes.
  • NodeHttpApplicationAdapter.create(): Raw Node http/https adapter factory for adapter-first runtime setup. The helper normalizes the primary Node request content-type before JSON/multipart detection and accepts maxBodySize, retryDelayMs, retryLimit, and shutdownTimeoutMs only as non-negative integers.
  • createNodeShutdownSignalRegistration(...), defaultNodeShutdownSignals(), registerShutdownSignals(...): Node-owned signal APIs. Supply the registration callback to Factory; lower-level host integrations can register directly.

Runtime app logging is separate from CLI lifecycle reporting. Configure ApplicationLogger when you want to change logs emitted by the application/runtime itself:

import { createConsoleApplicationLogger, createJsonApplicationLogger } from '@fluojs/platform-nodejs';

const minimalLogger = createConsoleApplicationLogger({ mode: 'minimal', level: 'warn' });
const jsonLogger = createJsonApplicationLogger();

Use CLI reporter flags such as fluo dev --verbose when you need raw child-process output from the development command instead.

Node Compression Failure Migration

Breaking change: When response compression fails before a Node response commits, FrameworkResponse.send() rejects. Adapter integrations must await that promise and handle the rejection; they must not swallow it or assume that an uncompressed success response was sent.

For dispatcher-managed requests, the runtime recovers by writing its JSON 500 envelope. The adapter removes a Content-Type it assigned for the failed body so the envelope uses application/json; an explicit Content-Type set by application code remains unchanged. Consumers that relied on a fulfilled send() or a stale adapter-assigned text/plain or application/octet-stream header must handle the rejection or fallback explicitly and set any required application-owned header themselves.

Lower-level Node compression internals stay behind the @fluojs/platform-nodejs/internal seam rather than the public @fluojs/platform-nodejs contract.

Runtime Cleanup Callbacks

Providers that receive the internal RUNTIME_CLEANUP_REGISTRATION token may register cleanup callbacks that return void or Promise<void>. Runtime close and bootstrap-failure cleanup run the callbacks in registration order and await each one before entering later cleanup phases. Failures do not prevent later callbacks from running: close() aggregates cleanup failures and leaves that incomplete phase eligible for an explicit retry, while bootstrap preserves its original failure and reports cleanup failures through ApplicationLogger.

Related Packages

Example Sources

Bounded Body Parsing

The HTTP-owned BodyParser policy is available as bodyParser on CreateWebRequestResponseFactoryOptions and DispatchWebRequestOptions from @fluojs/runtime/web, and as the final optional argument of createWebFrameworkRequest(request, signal, multipart, maxBodySize, rawBody, bodyParser). A supplied dispatch factory owns its parsing configuration and takes precedence.

import { createWebRequestResponseFactory } from '@fluojs/runtime/web';

const factory = createWebRequestResponseFactory({
  bodyParser: 'text',
  maxBodySize: 1_048_576,
  rawBody: true,
});

The default remains MIME-based parsing with a 1 MiB limit. The factory creates a cheap metadata snapshot and materializes the body once at dispatch, before HTTP middleware/guards. Text/custom policies retain bounded UTF-8 decoding and exact raw bytes without header changes; they use the creation-time Content-Length. Default behavior is unchanged. Web helpers read a clone by default, leaving the original readable; Next deliberately sets consumeOriginalBody: true, avoiding any Request reconstruction or clone workaround. Host-parsed bodies supplied by other factories/adapters are not routed through this Web parser.

For callback/default delegation, empty/absent bodies, abort cooperation, authentication order, and adapter capabilities, see the HTTP parser contract. Evidence: src/web-body-parser.test.ts, src/web-body-limit.test.ts, and the Next production example.

Compatible framework service copies

compileModuleGraph() accepts a caller-owned ModuleGraphCompileCache from a compatible same-realm runtime copy only after validating its complete versioned owner capability. Cache snapshots remain cloned, LRU and size remain owned by that cache, and disposal is observed through its original methods.

Module exports remain authoritative when a designated service class comes from a compatible package copy; this behavior does not make unexported providers visible.