import http from "node:http"; //#region src/global.d.ts type otherstring = string & {}; //#endregion //#region src/common/logger.d.ts type LogLevel = 'CORE' | 'INFO' | 'WARN' | 'ERROR' | 'SUCC' | 'DEBUG' | 'VERBOSE' | otherstring; interface LogEntry { timestamp: string; level: LogLevel; [key: string]: unknown; } type LoggerOption = 'one-line' | 'json-line' | FluxionLoggerFn; type FluxionLoggerFn = (entry: LogEntry) => void; interface MessageObject { [key: string]: unknown; message?: string; } interface FluxionLogger { /** * [WARN] We assert that `fields` is an object or undefined. */ write(level: LogLevel, messageOrObject: string | MessageObject): void; info(messageOrObject: string | MessageObject): void; warn(messageOrObject: string | MessageObject): void; error(messageOrObject: string | MessageObject): void; succ(messageOrObject: string | MessageObject): void; debug(messageOrObject: string | MessageObject): void; verbose(messageOrObject: string | MessageObject): void; } //#endregion //#region src/common/consts.d.ts declare enum HttpCode { Ok = 200, Created = 201, Accepted = 202, NoContent = 204, PartialContent = 206, MovedPermanently = 301, Found = 302, NotModified = 304, TemporaryRedirect = 307, PermanentRedirect = 308, BadRequest = 400, Unauthorized = 401, Forbidden = 403, NotFound = 404, MethodNotAllowed = 405, NotAcceptable = 406, RequestTimeout = 408, Conflict = 409, Gone = 410, PayloadTooLarge = 413, UnsupportedMediaType = 415, UnprocessableEntity = 422, TooManyRequests = 429, InternalServerError = 500, NotImplemented = 501, BadGateway = 502, ServiceUnavailable = 503, GatewayTimeout = 504 } declare const enum FluxionModuleType { Api = 0, StaticResource = 1 } //#endregion //#region src/types.d.ts interface FluxionRequest { /** * HTTP request method (GET, POST, PUT, DELETE, etc.) */ method: string; /** * Client IP address (supports X-Forwarded-For and X-Real-IP headers) */ ip: string; /** * Parsed request URL */ url: URL; /** * Parsed query parameters from URL search string */ query: Record; /** * Parsed request body (JSON, form data, etc.) */ body: Record; /** * Raw HTTP request headers */ headers: http.IncomingHttpHeaders; /** * Parsed cookies from the Cookie header */ cookie: Record; meta: Record; } interface FluxionOptions { /** * The directory where dynamic files (e.g. uploaded files) will be stored. It will be created if it doesn't exist. * It is recommended to use an empty directory that is not used for any other purpose, to avoid potential conflicts or security issues. */ dir: string; host: string; port: number; /** * Default to 5000ms. */ handlerTimeoutMs?: number; /** * Timeout for graceful shutdown. When shutting down, the server will wait this long for * active connections to close before force-exiting. * Default to 3000ms. */ shutdownTimeoutMs?: number; /** * Timeout for each middleware execution. * Default to 3000ms. */ middlewareTimeoutMs?: number; /** * Default to 3 minutes 3*60*1000ms. */ staticResourceTimeoutMs?: number; /** * Inject Path that will be used like `path.join(moduleDir,modulepath)` * - default is `process.cwd()` */ moduleDir?: string; /** * Maximum request body bytes accepted by dynamic handlers. * Requests larger than this limit will return 413. */ maxRequestBytes?: number; /** * Logger output mode or custom logger sink. * Defaults to `one-line`. * * Also accepts a logger function that will replace the default one. * * ! **ATTENTION** Fluxion calls the logging function synchronously and fails silently; make sure to handle exceptions yourself. */ logger?: LoggerOption; /** * Glob patterns for files that should be registered as API handlers. * Files matching these patterns will be loaded as handlers and registered as APIs. * Defaults to TypeScript files (*.ts). * @example ['*.api.ts', 'handlers/*.js'] - register specific patterns as APIs */ apiInclude?: string[]; /** * Glob patterns for files that should be registered as static resources. * Files(after matching `apiInclude`) matching these patterns will be served as static files. * Defaults to all files if not provided. * @example ['*.html', '*.css', '*.js'] - serve specific patterns as static files */ staticInclude?: string[]; /** * Glob patterns for files that should be excluded from registration. * Files matching these patterns will not be registered (neither as API nor static resource). * Defaults to common exclusions like node_modules, .git, dist, etc. */ exclude?: string[]; /** * HTTPS server configuration. If provided, the server will use HTTPS instead of HTTP. * Both `key` and `cert` are required for HTTPS. `ca` is optional for certificate chains. */ https?: { /** * Path to the private key file (PEM format) or the key content as a string/buffer. */ key: string | Buffer; /** * Path to the certificate file (PEM format) or the certificate content as a string/buffer. */ cert: string | Buffer; /** * Optional: Path to CA certificate file(s) or the CA content as a string/buffer/array. * Used for intermediate certificates. */ ca?: string | Buffer | Array; }; /** * Content-Security-Policy header value. * Defaults to "default-src 'self'". * Set to `false` to disable the CSP header entirely. * @example "default-src 'self'; script-src 'self' 'unsafe-inline'; img-src 'self' https:" */ csp?: string | false; /** * Meta API endpoints to enable. Each endpoint corresponds to a /_fluxion/ route. * Available endpoints: 'healthz', 'version', 'stats', 'config' * Defaults to ['healthz', 'version', 'stats'] * * Endpoint descriptions: * - healthz: Basic health check (no authentication required) * - version: Version information (no authentication required) * - stats: Memory, CPU, and runtime statistics (no authentication required) * - config: Current configuration (requires secret authentication) */ metaApis?: ('healthz' | 'version' | 'stats' | 'config')[]; /** * Secret for protecting sensitive meta API endpoints. * * **Authentication:** Only 'config' endpoint requires secret authentication via `?secret=` parameter. * Basic monitoring endpoints ('healthz', 'version', 'stats') are publicly accessible. * * **Priority:** Explicit `metaSecret` option > `FLUXION_META_SECRET` environment variable. * * **Validation:** Must be at least 20 characters, include both letters and digits, and contain no whitespace. * * **Defaults:** Reads from `FLUXION_META_SECRET` environment variable if not explicitly set. * * **Disabled:** When set to `undefined` or doesn't meet validation rules, 'routes' and 'config' endpoints are disabled. */ metaSecret?: string; } interface NormalizedFluxionOptions { /** * It's absolute path to the directory where dynamic files will be stored. */ dir: string; host: string; port: number; handlerTimeoutMs: number; middlewareTimeoutMs: number; staticResourceTimeoutMs: number; shutdownTimeoutMs: number; moduleDir: string; maxRequestBytes: number; logger: LoggerOption; apiInclude: string[]; staticInclude: string[]; exclude: string[]; metaApis: ('healthz' | 'version' | 'stats' | 'config')[]; metaSecret?: string; https?: { key: string | Buffer; cert: string | Buffer; ca?: string | Buffer | Array; }; /** * Content-Security-Policy header value. */ csp: string | false; normalizedFlag: symbol; } interface FluxionModuleContext { logger: FluxionLogger; } type FluxionHandler = (request: FluxionRequest, cx: FluxionModuleContext, rawRequest: InstanceType, rawResponse: InstanceType & { req: InstanceType; }) => Promise | unknown; type FluxionMiddleware = (request: FluxionRequest, cx: FluxionModuleContext, rawRequest: InstanceType, rawResponse: InstanceType) => Promise | unknown; type FluxionDisposer = () => Promise | void; /** * Supported HTTP methods for FluxionModule */ type HTTPMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'HEAD' | 'OPTIONS' | 'TRACE' | 'CONNECT' | otherstring; interface FluxionModule { /** * Main handler for an api */ handler: FluxionHandler; /** * This is meant to clear resources used by handler while it's down. */ disposer?: FluxionDisposer; /** * How many ms to wait until the request times out */ handlerTimeoutMs?: number; /** * Allowed HTTP methods for this module. * If specified, only these methods will be accepted. * @example ['GET', 'POST'] */ methods?: HTTPMethod[]; /** * These functions will execute sequentially and be awaited. * * **Side Effect Accepted :** You can modify the arguments, and next middleware will use the modified version. */ middlewares?: FluxionMiddleware[]; } type NormalizedModule = FluxionModule & { absolutePath: string; /** * mtime from `fs.stat` */ mtimeMs: number; type: FluxionModuleType; }; //#endregion //#region src/fluxion.d.ts declare function fluxion(options: FluxionOptions | NormalizedFluxionOptions): Promise; //#endregion //#region src/http/exceptions.d.ts /** * Base class for all HTTP exceptions */ declare abstract class HttpException extends Error implements NodeJS.ErrnoException { errno?: number | undefined; code?: string | undefined; constructor(message: string, statusCode: HttpCode, code: string); } /** * 400 Bad Request - Malformed or invalid request */ declare class BadRequestException extends HttpException { constructor(message?: string); } /** * 401 Unauthorized - Authentication required or failed */ declare class UnauthorizedException extends HttpException { constructor(message?: string); } /** * 403 Forbidden - Valid request but refused authorization */ declare class ForbiddenException extends HttpException { constructor(message?: string); } /** * 404 Not Found - Resource does not exist */ declare class NotFoundException extends HttpException { constructor(message?: string); } /** * 405 Method Not Allowed - HTTP method not supported for resource */ declare class MethodNotAllowedException extends HttpException { constructor(message?: string); } /** * 406 Not Acceptable - Cannot generate acceptable response */ declare class NotAcceptableException extends HttpException { constructor(message?: string); } /** * 408 Request Timeout - Client did not produce request within time */ declare class RequestTimeoutException extends HttpException { constructor(message?: string); } /** * 409 Conflict - Request conflicts with current state */ declare class ConflictException extends HttpException { constructor(message?: string); } /** * 410 Gone - Resource no longer available */ declare class GoneException extends HttpException { constructor(message?: string); } /** * 413 Payload Too Large - Request entity larger than limits */ declare class PayloadTooLargeException extends HttpException { constructor(message?: string); } /** * 415 Unsupported Media Type - Requested format not supported */ declare class UnsupportedMediaTypeException extends HttpException { constructor(message?: string); } /** * 422 Unprocessable Entity - Syntactically correct but semantically erroneous */ declare class UnprocessableEntityException extends HttpException { constructor(message?: string); } /** * 429 Too Many Requests - Rate limit exceeded */ declare class TooManyRequestsException extends HttpException { constructor(message?: string); } /** * 500 Internal Server Error - Unexpected server condition */ declare class InternalServerErrorException extends HttpException { constructor(message?: string); } /** * 501 Not Implemented - Server does not support functionality */ declare class NotImplementedException extends HttpException { constructor(message?: string); } /** * 502 Bad Gateway - Invalid response from upstream server */ declare class BadGatewayException extends HttpException { constructor(message?: string); } /** * 503 Service Unavailable - Server temporarily unavailable */ declare class ServiceUnavailableException extends HttpException { constructor(message?: string); } /** * 504 Gateway Timeout - Upstream server timeout */ declare class GatewayTimeoutException extends HttpException { constructor(message?: string); } //#endregion //#region src/defines/options.d.ts /** * Normalize options and create necessary resources like the dynamic directory and logger. */ declare function defineFluxionOptions(o: FluxionOptions): NormalizedFluxionOptions; //#endregion //#region src/defines/index.d.ts /** * Use handler function and optional disposer function to define a Fluxion module. * @param handler Main function that handles request and response instances * @param disposer Deal with resource cleanup when the server is about to close */ declare function defineFluxionModule(handler: FluxionHandler, disposer?: FluxionDisposer): NormalizedModule; /** * Provides type safety for defining Fluxion modules. */ declare function defineFluxionModule(fluxionModule: FluxionModule): NormalizedModule; declare function defineFluxionMiddleware(middleware: FluxionMiddleware): FluxionMiddleware; declare function defineFluxionLogger(loggerFn: FluxionLoggerFn): FluxionLoggerFn; //#endregion export { BadGatewayException, BadRequestException, ConflictException, type FluxionDisposer, type FluxionHandler, type FluxionModule, type FluxionModuleContext, type FluxionOptions, type FluxionRequest, ForbiddenException, GatewayTimeoutException, GoneException, HttpCode, HttpException, InternalServerErrorException, MethodNotAllowedException, NotAcceptableException, NotFoundException, NotImplementedException, PayloadTooLargeException, RequestTimeoutException, ServiceUnavailableException, TooManyRequestsException, UnauthorizedException, UnprocessableEntityException, UnsupportedMediaTypeException, defineFluxionLogger, defineFluxionMiddleware, defineFluxionModule, defineFluxionOptions, fluxion }; //# sourceMappingURL=index.d.mts.map