@nextrush/core 3.0.6 → 4.0.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/middleware.ts","../src/application.ts"],"names":[],"mappings":";;;;AA4DO,SAAS,OAAA,CAAQ,YAA0B,OAAA,EAA8C;AAE9F,EAAA,IAAI,CAAC,KAAA,CAAM,OAAA,CAAQ,UAAU,CAAA,EAAG;AAC9B,IAAA,MAAM,IAAI,UAAU,mCAAmC,CAAA;AAAA,EACzD;AAEA,EAAA,KAAA,MAAW,MAAM,UAAA,EAAY;AAC3B,IAAA,IAAI,OAAO,OAAO,UAAA,EAAY;AAC5B,MAAA,MAAM,IAAI,UAAU,+BAA+B,CAAA;AAAA,IACrD;AAAA,EACF;AAEA,EAAA,MAAM,kBAAA,GAAqB,OAAA,EAAS,kBAAA,IAAsB,OAAA,CAAQ,IAAI,QAAA,KAAa,YAAA;AAGnF,EAAA,MAAM,KAAA,GAAQ,CAAC,GAAG,UAAU,CAAA;AAC5B,EAAA,MAAM,MAAM,KAAA,CAAM,MAAA;AAGlB,EAAA,IAAI,QAAQ,CAAA,EAAG;AACb,IAAA,OAAO,SAAS,kBAAA,CAAmB,IAAA,EAAe,IAAA,EAA4B;AAC5E,MAAA,OAAO,IAAA,GAAO,IAAA,EAAK,GAAI,OAAA,CAAQ,OAAA,EAAQ;AAAA,IACzC,CAAA;AAAA,EACF;AAOA,EAAA,OAAO,SAAS,kBAAA,CAAmB,GAAA,EAAc,IAAA,EAA4B;AAE3E,IAAA,IAAI,KAAA,GAAQ,EAAA;AAEZ,IAAA,SAAS,SAAS,CAAA,EAA0B;AAC1C,MAAA,IAAI,KAAK,KAAA,EAAO;AACd,QAAA,OAAO,OAAA,CAAQ,MAAA,CAAO,IAAI,KAAA,CAAM,8BAA8B,CAAC,CAAA;AAAA,MACjE;AAEA,MAAA,KAAA,GAAQ,C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CAAA,KAAO,EAAE,MAAA,YAAkB,KAAA,GAAQ,EAAE,MAAA,GAAS,IAAI,MAAM,MAAA,CAAO,CAAA,CAAE,MAAM,CAAC,CAAE,CAAA;AAAA,EACpF;AACF;AAcO,SAAS,UAAU,OAAA,EAA2C;AACnE,EAAA,OAAO,IAAI,YAAY,OAAO,CAAA;AAChC","file":"index.js","sourcesContent":["/**\n * @nextrush/core - Middleware Composition\n *\n * Koa-style middleware composition with async/await support.\n * This is the heart of the middleware pipeline.\n *\n * @packageDocumentation\n */\n\nimport type { Context, Middleware, Next } from '@nextrush/types';\n\n/**\n * Composed middleware handler - can be called with just context\n */\nexport type ComposedMiddleware = (ctx: Context, next?: Next) => Promise<void>;\n\n/**\n * Options for middleware composition\n */\nexport interface ComposeOptions {\n /**\n * Warn when a middleware sends a response AND calls next().\n * Enabled by default in non-production environments.\n * @default process.env.NODE_ENV !== 'production'\n */\n warnDoubleResponse?: boolean;\n}\n\n/**\n * Compose multiple middleware functions into a single middleware.\n *\n * Executes middleware in order, each middleware can call `await next()`\n * to pass control to the next middleware and wait for it to complete.\n *\n * @param middleware - Array of middleware functions to compose\n * @param options - Composition options\n * @returns Single composed middleware function\n *\n * @example\n * ```typescript\n * const composed = compose([\n * async (ctx, next) => {\n * console.log('1 - before');\n * await next();\n * console.log('1 - after');\n * },\n * async (ctx, next) => {\n * console.log('2 - before');\n * await next();\n * console.log('2 - after');\n * },\n * ]);\n *\n * // Output:\n * // 1 - before\n * // 2 - before\n * // 2 - after\n * // 1 - after\n * ```\n */\nexport function compose(middleware: Middleware[], options?: ComposeOptions): ComposedMiddleware {\n // Validate middleware array\n if (!Array.isArray(middleware)) {\n throw new TypeError('Middleware stack must be an array');\n }\n\n for (const fn of middleware) {\n if (typeof fn !== 'function') {\n throw new TypeError('Middleware must be a function');\n }\n }\n\n const warnDoubleResponse = options?.warnDoubleResponse ?? process.env.NODE_ENV !== 'production';\n\n // Snapshot middleware array at compose time\n const stack = [...middleware];\n const len = stack.length;\n\n // FAST PATH: No middleware — just call next()\n if (len === 0) {\n return function composedMiddleware(_ctx: Context, next?: Next): Promise<void> {\n return next ? next() : Promise.resolve();\n };\n }\n\n /**\n * Composed middleware function\n * Uses index-based dispatch to avoid per-request closure chains\n * while preserving double-next detection per call.\n */\n return function composedMiddleware(ctx: Context, next?: Next): Promise<void> {\n // Per-request index tracker — only state needed\n let index = -1;\n\n function dispatch(i: number): Promise<void> {\n if (i <= index) {\n return Promise.reject(new Error('next() called multiple times'));\n }\n\n index = i;\n\n let fn: Middleware | Next | undefined;\n if (i < len) {\n fn = stack[i];\n } else if (i === len) {\n fn = next;\n }\n\n if (!fn) {\n return Promise.resolve();\n }\n\n // Capture responded state before middleware runs (dev-mode warning)\n const respondedBefore = warnDoubleResponse ? ctx.responded : false;\n let nextCalled = false;\n\n const nextFn = () => {\n nextCalled = true;\n return dispatch(i + 1);\n };\n\n // Wire up ctx.next() if the context supports it\n if (ctx.setNext) {\n ctx.setNext(nextFn);\n }\n\n try {\n const result = Promise.resolve(fn(ctx, nextFn));\n\n if (warnDoubleResponse) {\n return result.then(() => {\n if (!respondedBefore && ctx.responded && nextCalled) {\n console.warn(\n `[nextrush] Middleware at index ${String(i)} sent a response and called next(). ` +\n 'Downstream middleware may attempt to write to an already-finished response. ' +\n 'Either send a response OR call next(), not both.'\n );\n }\n });\n }\n\n return result;\n } catch (err: unknown) {\n return Promise.reject(err instanceof Error ? err : new Error(String(err)));\n }\n }\n\n return dispatch(0);\n };\n}\n\n/**\n * Check if a function is a valid middleware\n */\nexport function isMiddleware(fn: unknown): fn is Middleware {\n return typeof fn === 'function';\n}\n\n/**\n * Flatten nested middleware arrays with type validation.\n * Uses bounded depth (10 levels) to prevent V8 deoptimization on deeply nested arrays.\n */\nexport function flattenMiddleware(arr: (Middleware | Middleware[])[]): Middleware[] {\n const flattened = arr.flat(10);\n for (const fn of flattened) {\n if (typeof fn !== 'function') {\n throw new TypeError(`Invalid middleware: expected function, got ${typeof fn}`);\n }\n }\n return flattened;\n}\n","/**\n * @nextrush/core - Application Class\n *\n * The Application class is the main entry point for NextRush.\n * It manages middleware registration and plugin installation.\n *\n * @packageDocumentation\n */\n\nimport type { Context, Middleware, Plugin, PluginWithHooks } from '@nextrush/types';\nimport { compose } from './middleware';\n\n/** @internal Symbol keys for route() state — avoids polluting user's ctx.state namespace */\nconst ORIGINAL_PATH = Symbol.for('nextrush.originalPath');\nconst ROUTE_PREFIX = Symbol.for('nextrush.routePrefix');\n\n/**\n * Error handler function type\n */\nexport type ErrorHandler = (error: Error, ctx: Context) => void | Promise<void>;\n\n/**\n * Logger interface for pluggable logging\n */\nexport interface Logger {\n error(...args: unknown[]): void;\n warn(...args: unknown[]): void;\n info(...args: unknown[]): void;\n debug(...args: unknown[]): void;\n}\n\n/** No-op logger — default when no logger is configured */\nconst NOOP_LOGGER: Logger = {\n error(..._args) {\n void _args;\n },\n warn(..._args) {\n void _args;\n },\n info(..._args) {\n void _args;\n },\n debug(..._args) {\n void _args;\n },\n};\n\n/**\n * Application options\n */\nexport interface ApplicationOptions {\n /**\n * Environment mode\n * @default 'development'\n */\n env?: 'development' | 'production' | 'test';\n\n /**\n * Whether to use proxy headers (X-Forwarded-For, etc.)\n * @default false\n */\n proxy?: boolean;\n\n /**\n * Custom logger. Defaults to no-op (silent).\n *\n * @remarks\n * Pass `console` for quick development logging:\n * ```ts\n * const app = createApp({ logger: console });\n * ```\n *\n * For production, provide a structured logger (e.g. pino, winston)\n * that implements the {@link Logger} interface.\n *\n * Adapters and internal hooks use `app.logger` — configuring it here\n * ensures consistent logging across the framework.\n */\n logger?: Logger;\n}\n\n/**\n * Listener callback type\n */\nexport type ListenCallback = () => void;\n\n/**\n * Routable interface - any object with routes() method\n * This allows mounting Router instances without circular dependency\n */\nexport interface Routable {\n routes(): Middleware;\n}\n\n/**\n * The Application class\n *\n * @example\n * ```typescript\n * const app = createApp();\n *\n * app.use(async (ctx) => {\n * ctx.json({ message: 'Hello World' });\n * });\n *\n * // Mount with an adapter\n * listen(app, { port: 3000 });\n * ```\n */\nexport class Application {\n /**\n * Middleware stack\n */\n private readonly middlewareStack: Middleware[] = [];\n\n /**\n * Installed plugins\n */\n private readonly plugins = new Map<string, Plugin>();\n\n /**\n * Custom error handler\n */\n private _errorHandler: ErrorHandler | null = null;\n\n /**\n * Pluggable logger\n */\n readonly logger: Logger;\n\n /**\n * Application options\n */\n readonly options: ApplicationOptions;\n\n /**\n * Whether the app is running\n */\n private _isRunning = false;\n\n constructor(options: ApplicationOptions = {}) {\n this.options = {\n env: options.env ?? 'development',\n proxy: options.proxy ?? false,\n };\n this.logger = options.logger ?? NOOP_LOGGER;\n }\n\n /**\n * Check if running in production\n */\n get isProduction(): boolean {\n return this.options.env === 'production';\n }\n\n /**\n * Check if app is running\n */\n get isRunning(): boolean {\n return this._isRunning;\n }\n\n /**\n * Get middleware count\n */\n get middlewareCount(): number {\n return this.middlewareStack.length;\n }\n\n /**\n * Throws if the app is already running.\n * Prevents configuration mutations after start().\n */\n private assertNotRunning(method: string): void {\n if (this._isRunning) {\n throw new Error(`Cannot call ${method}() after the application has started`);\n }\n }\n\n // ===========================================================================\n // Middleware Registration\n // ===========================================================================\n\n /**\n * Register middleware function(s)\n *\n * @param middleware - Middleware function or array of middleware\n * @returns this for chaining\n *\n * @example\n * ```typescript\n * // Single middleware\n * app.use(async (ctx) => {\n * console.log(ctx.method, ctx.path);\n * await ctx.next();\n * });\n *\n * // Multiple middleware\n * app.use(cors(), helmet(), json());\n * ```\n */\n use(...middleware: Middleware[]): this {\n this.assertNotRunning('use');\n for (const mw of middleware) {\n if (typeof mw !== 'function') {\n throw new TypeError('Middleware must be a function');\n }\n this.middlewareStack.push(mw);\n }\n return this;\n }\n\n // ===========================================================================\n // Router Mounting (Hono-style)\n // ===========================================================================\n\n /**\n * Mount a router at a path prefix\n *\n * This is the Hono-style API for mounting routers directly on the app.\n * The router's routes will only match requests that start with the given prefix.\n *\n * @param path - Path prefix for the router (e.g., '/api/users')\n * @param router - Router instance to mount\n * @returns this for chaining\n *\n * @example\n * ```typescript\n * // Create modular routers\n * const users = createRouter();\n * users.get('/', listUsers);\n * users.get('/:id', getUser);\n * users.post('/', createUser);\n *\n * const posts = createRouter();\n * posts.get('/', listPosts);\n * posts.get('/:id', getPost);\n *\n * // Mount directly on app - clean like Hono!\n * const app = createApp();\n * app.route('/api/users', users);\n * app.route('/api/posts', posts);\n *\n * listen(app, 3000);\n * ```\n */\n route(path: string, router: Routable): this {\n this.assertNotRunning('route');\n // Root mount optimization: skip all prefix processing\n if (path === '/' || path === '') {\n this.middlewareStack.push(router.routes());\n return this;\n }\n\n const routerMiddleware = router.routes();\n // Normalize prefix: ensure leading '/', strip trailing '/'\n let normalizedPrefix = path.endsWith('/') ? path.slice(0, -1) : path;\n if (!normalizedPrefix.startsWith('/')) {\n normalizedPrefix = '/' + normalizedPrefix;\n }\n const prefixLen = normalizedPrefix.length;\n\n // NOTE (DX-3): We cast `ctx` to `{ path: string }` inside this middleware\n // to temporarily strip the `readonly` modifier on `path`. This is intentional:\n // route mounting must adjust ctx.path for the sub-router and restore it\n // afterwards. The Context interface keeps `path` readonly to prevent\n // accidental mutation by user code, but internal mounting is the exception.\n const mountedMiddleware: Middleware = async (ctx, next) => {\n const currentPath = ctx.path;\n\n // Fast prefix check\n if (!currentPath.startsWith(normalizedPrefix)) {\n return next();\n }\n\n // Check prefix boundary (avoid /api/usersxxx matching /api/users)\n const hasCharAfterPrefix = prefixLen < currentPath.length;\n if (hasCharAfterPrefix && currentPath.charCodeAt(prefixLen) !== 47) {\n // 47 = '/'\n return next();\n }\n\n // Direct path manipulation (no Proxy - fast!)\n const adjustedPath = currentPath.slice(prefixLen) || '/';\n (ctx as { path: string }).path = adjustedPath;\n\n // Store original for recovery (Symbol keys avoid ctx.state pollution)\n (ctx.state as Record<symbol, unknown>)[ORIGINAL_PATH] = currentPath;\n (ctx.state as Record<symbol, unknown>)[ROUTE_PREFIX] = normalizedPrefix;\n\n try {\n await routerMiddleware(ctx, async () => {\n // Restore original path before calling downstream middleware\n // so downstream sees the full unmounted path\n (ctx as { path: string }).path = currentPath;\n await next();\n // Re-apply stripped path for router's return path\n (ctx as { path: string }).path = adjustedPath;\n });\n } finally {\n // Restore original path and clean up Symbol state\n (ctx as { path: string }).path = currentPath;\n (ctx.state as Record<symbol, unknown>)[ORIGINAL_PATH] = undefined;\n (ctx.state as Record<symbol, unknown>)[ROUTE_PREFIX] = undefined;\n }\n };\n\n this.middlewareStack.push(mountedMiddleware);\n return this;\n }\n\n // ===========================================================================\n // Error Handling\n // ===========================================================================\n\n /**\n * Set the application error handler.\n *\n * Replaces any previously set handler. Only one error handler is active\n * at a time. For additive error handling, compose logic within a single\n * handler or use the `errorHandler()` middleware from `@nextrush/errors`.\n *\n * @param handler - Error handler function\n * @returns this for chaining\n *\n * @example\n * ```typescript\n * app.setErrorHandler((error, ctx) => {\n * console.error('Request failed:', error);\n *\n * if (error instanceof ValidationError) {\n * ctx.status = 400;\n * ctx.json({ error: error.message, details: error.details });\n * return;\n * }\n *\n * ctx.status = 500;\n * ctx.json({ error: 'Internal Server Error' });\n * });\n * ```\n */\n setErrorHandler(handler: ErrorHandler): this {\n this._errorHandler = handler;\n return this;\n }\n\n /**\n * Set custom error handler.\n *\n * @param handler - Error handler function\n * @returns this for chaining\n *\n * @deprecated Use `setErrorHandler()` instead — `onError()` implies\n * event subscription (additive), but this is a setter (replaces).\n */\n onError(handler: ErrorHandler): this {\n return this.setErrorHandler(handler);\n }\n\n // ===========================================================================\n // Plugin System\n // ===========================================================================\n\n /**\n * Install a plugin.\n *\n * Handles both sync and async `install()` methods automatically.\n * Returns `this` for sync plugins and `Promise<this>` for async ones.\n *\n * @param plugin - Plugin to install\n * @returns this (sync) or Promise<this> (async)\n *\n * @example\n * ```typescript\n * // Sync plugin\n * app.plugin(loggerPlugin({ level: 'info' }));\n *\n * // Async plugin — just await it\n * await app.plugin(databasePlugin({ uri: '...' }));\n * ```\n */\n plugin(plugin: Plugin): this | Promise<this> {\n this.assertNotRunning('plugin');\n if (this.plugins.has(plugin.name)) {\n throw new Error(`Plugin \"${plugin.name}\" is already installed`);\n }\n\n const result = plugin.install(this);\n\n // If install() returned a promise, handle it asynchronously\n if (result instanceof Promise) {\n return result.then(() => {\n this.plugins.set(plugin.name, plugin);\n return this;\n });\n }\n\n this.plugins.set(plugin.name, plugin);\n return this;\n }\n\n /**\n * Install a plugin asynchronously.\n *\n * @param plugin - Plugin to install\n * @returns Promise that resolves when plugin is installed\n *\n * @deprecated Use `plugin()` instead — it handles both sync and async\n * plugins automatically.\n *\n * @example\n * ```typescript\n * await app.plugin(new DatabasePlugin({ connectionString: '...' }));\n * ```\n */\n async pluginAsync(plugin: Plugin): Promise<this> {\n const result = this.plugin(plugin);\n return result instanceof Promise ? result : Promise.resolve(result);\n }\n\n /**\n * Get an installed plugin by name\n *\n * @param name - Plugin name\n * @returns Plugin instance or undefined\n */\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters\n getPlugin<T extends Plugin>(name: string): T | undefined {\n return this.plugins.get(name) as T | undefined;\n }\n\n /**\n * Check if a plugin is installed\n */\n hasPlugin(name: string): boolean {\n return this.plugins.has(name);\n }\n\n // ===========================================================================\n // Request Handler\n // ===========================================================================\n\n /**\n * Create the request handler callback\n *\n * This is the function that adapters call to handle each request.\n * It composes all middleware and returns a function that processes context.\n *\n * **Important:** The middleware stack is snapshot at call time.\n * Middleware or plugins added after `callback()` will NOT take effect\n * on the returned handler. Call `callback()` again to get a\n * handler that includes subsequent registrations.\n *\n * @returns Request handler function\n */\n callback(): (ctx: Context) => Promise<void> {\n const fn = compose(this.middlewareStack);\n\n // Collect plugins that implement lifecycle hooks (once at build time)\n // Validate that hook properties are actually callable functions\n const hookPlugins = Array.from(this.plugins.values()).filter((p): p is PluginWithHooks => {\n const hasHook =\n 'onRequest' in p || 'onResponse' in p || 'onError' in p || 'extendContext' in p;\n if (!hasHook) return false;\n\n // Runtime validation: ensure hook properties are functions\n if ('onRequest' in p && typeof p.onRequest !== 'function') {\n throw new TypeError(\n `Plugin \"${p.name}\": onRequest must be a function, got ${typeof p.onRequest}`\n );\n }\n if ('onResponse' in p && typeof p.onResponse !== 'function') {\n throw new TypeError(\n `Plugin \"${p.name}\": onResponse must be a function, got ${typeof p.onResponse}`\n );\n }\n if ('onError' in p && typeof p.onError !== 'function') {\n throw new TypeError(\n `Plugin \"${p.name}\": onError must be a function, got ${typeof p.onError}`\n );\n }\n if ('extendContext' in p && typeof p.extendContext !== 'function') {\n throw new TypeError(\n `Plugin \"${p.name}\": extendContext must be a function, got ${typeof p.extendContext}`\n );\n }\n return true;\n });\n\n return async (ctx: Context): Promise<void> => {\n try {\n // Extend context and run onRequest hooks\n for (const p of hookPlugins) {\n if (p.extendContext) p.extendContext(ctx);\n if (p.onRequest) await p.onRequest(ctx);\n }\n\n await fn(ctx);\n\n // Run onResponse hooks — isolate errors so all hooks run\n for (const p of hookPlugins) {\n if (p.onResponse) {\n try {\n await p.onResponse(ctx);\n } catch (hookError) {\n this.logger.warn('Plugin onResponse hook threw:', {\n plugin: p.name,\n error: hookError,\n });\n }\n }\n }\n } catch (error) {\n // Run onError hooks\n const err = error instanceof Error ? error : new Error(String(error));\n for (const p of hookPlugins) {\n if (p.onError) {\n try {\n await p.onError(err, ctx);\n } catch (hookError) {\n this.logger.warn('Plugin onError hook threw:', {\n plugin: p.name,\n error: hookError,\n });\n }\n }\n }\n await this.handleError(error, ctx);\n }\n };\n }\n\n /**\n * Handle errors - uses custom handler if set, otherwise default\n */\n private async handleError(error: unknown, ctx: Context): Promise<void> {\n const err = error instanceof Error ? error : new Error(String(error));\n\n // Use custom error handler if set\n if (this._errorHandler) {\n try {\n await this._errorHandler(err, ctx);\n return;\n } catch (handlerError) {\n // If custom handler throws, fall through to default handling\n this.logger.error('Error handler threw:', handlerError);\n }\n }\n\n // Default error handling\n this.defaultErrorHandler(err, ctx);\n }\n\n /**\n * Default error handler\n *\n * Uses the `expose` flag on errors (set by HttpError/NextRushError)\n * to decide whether to include the error message in the response.\n * 4xx errors expose messages by default; 5xx errors never do.\n * This prevents leaking internal details (paths, SQL, stack info)\n * regardless of environment.\n */\n private defaultErrorHandler(error: Error, ctx: Context): void {\n // Always log non-production errors for DX\n if (!this.isProduction) {\n this.logger.error('Request error:', error);\n }\n\n // Determine status — clamp to valid error range (400-599)\n const errorMeta = error as Error & { status?: number; expose?: boolean };\n let status = 500;\n if (typeof errorMeta.status === 'number') {\n const raw = errorMeta.status;\n status = raw >= 400 && raw < 600 ? raw : 500;\n }\n ctx.status = status;\n\n // Use the `expose` flag to decide what message the client sees.\n // HttpError/NextRushError set expose=true for 4xx, false for 5xx.\n // Plain Error never exposes — prevents leaking internal details.\n const expose = errorMeta.expose === true;\n const message = expose ? error.message : 'Internal Server Error';\n\n ctx.json({ error: message });\n }\n\n // ===========================================================================\n // Lifecycle\n // ===========================================================================\n\n /**\n * Mark app as running and freeze configuration.\n *\n * Called by adapters when the server starts listening. After this call,\n * `use()`, `route()`, `plugin()`, and `pluginAsync()` will throw.\n * This prevents unsafe middleware mutations while requests are in flight.\n *\n * To re-enable registration (e.g. for testing), call `close()` first.\n */\n start(): void {\n this._isRunning = true;\n }\n\n /**\n * Graceful shutdown\n * Destroys all plugins that have a destroy method.\n * Uses Promise.allSettled to ensure all plugins are destroyed\n * even if some throw errors.\n *\n * @returns Array of errors from plugins that failed to destroy (empty on success)\n */\n async close(): Promise<Error[]> {\n this._isRunning = false;\n\n // Destroy plugins in reverse order using allSettled for resilience\n const pluginArray = Array.from(this.plugins.values()).reverse();\n const destroyablePlugins = pluginArray.filter(\n (p): p is Plugin & { destroy: () => void | Promise<void> } => typeof p.destroy === 'function'\n );\n\n const destroyPromises = destroyablePlugins.map((p) =>\n Promise.resolve()\n .then(() => p.destroy())\n .catch((err: unknown) => {\n throw err instanceof Error ? err : new Error(String(err));\n })\n );\n\n const results = await Promise.allSettled(destroyPromises);\n this.plugins.clear();\n\n return results\n .filter((r): r is PromiseRejectedResult => r.status === 'rejected')\n .map((r) => (r.reason instanceof Error ? r.reason : new Error(String(r.reason))));\n }\n}\n\n/**\n * Create a new Application instance\n *\n * @param options - Application options\n * @returns New Application instance\n *\n * @example\n * ```typescript\n * const app = createApp();\n * const app = createApp({ env: 'production' });\n * ```\n */\nexport function createApp(options?: ApplicationOptions): Application {\n return new Application(options);\n}\n"]}
1
+ {"version":3,"sources":["../src/middleware.ts","../src/error-handler.ts","../src/route-mount.ts","../src/application.ts"],"names":[],"mappings":";;;;;AAqBA,IAAM,qBAAA,GAAwB,8BAAA;AAU9B,SAAS,0BAA0B,KAAA,EAAqB;AACtD,EAAA,OAAA,CAAQ,IAAA;AAAA,IACN,CAAA,+BAAA,EAAkC,MAAA,CAAO,KAAK,CAAC,CAAA,2NAAA;AAAA,GAGjD;AACF;AAoDO,SAAS,OAAA,CAAQ,YAA0B,OAAA,EAA8C;AAE9F,EAAA,IAAI,CAAC,KAAA,CAAM,OAAA,CAAQ,UAAU,CAAA,EAAG;AAC9B,IAAA,MAAM,IAAI,UAAU,mCAAmC,CAAA;AAAA,EACzD;AAEA,EAAA,KAAA,MAAW,MAAM,UAAA,EAAY;AAC3B,IAAA,IAAI,OAAO,OAAO,UAAA,EAAY;AAC5B,MAAA,MAAM,IAAI,UAAU,+BAA+B,CAAA;AAAA,IACrD;AAAA,EACF;AAEA,EAAA,MAAM,kBAAA,GAAqB,SAAS,kBAAA,IAAsB,KAAA;AAG1D,EAAA,MAAM,KAAA,GAAQ,CAAC,GAAG,UAAU,CAAA;AAC5B,EAAA,MAAM,MAAM,KAAA,CAAM,MAAA;AAGlB,EAAA,IAAI,QAAQ,CAAA,EAAG;AACb,IAAA,OAAO,SAAS,kBAAA,CAAmB,IAAA,EAAe,IAAA,EAA4B;AAC5E,MAAA,OAAO,IAAA,GAAO,IAAA,EAAK,GAAI,OAAA,CAAQ,OAAA,EAAQ;AAAA,IACzC,CAAA;AAAA,EACF;AAYA,EAAA,IAAI,QAAQ,CAAA,EAAG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,EAAA,OAAO,IAAI,YAAY,OAAO,CAAA;AAChC","file":"index.js","sourcesContent":["/**\n * @nextrush/core - Middleware Composition\n *\n * Koa-style middleware composition with async/await support.\n * This is the heart of the middleware pipeline.\n *\n * @packageDocumentation\n */\n\nimport type { Context, Middleware, Next } from '@nextrush/types';\n\n/**\n * Composed middleware handler - can be called with just context\n */\nexport type ComposedMiddleware = (ctx: Context, next?: Next) => Promise<void>;\n\n/**\n * Rejection message shared by BOTH the general path and the single-middleware\n * fast path (design D4). Downstream code/tests assert on this exact string, so\n * it is defined once to prevent the two paths from drifting.\n */\nconst MULTIPLE_NEXT_MESSAGE = 'next() called multiple times';\n\n/**\n * Emit the double-response warning for the middleware at `index`.\n *\n * Shared by the general path and the fast path so the text (including the\n * index reference) cannot diverge between them (design D4). Fires only when\n * `warnDoubleResponse` is enabled AND the context has already committed a\n * response — the caller supplies both conditions.\n */\nfunction emitDoubleResponseWarning(index: number): void {\n console.warn(\n `[nextrush] Middleware at index ${String(index)} called next() after the response was already committed. ` +\n 'Downstream middleware may attempt to write to an already-finished response. ' +\n 'Either await next() to delegate downstream, or send a response without calling next().'\n );\n}\n\n/**\n * Options for middleware composition\n */\nexport interface ComposeOptions {\n /**\n * Warn when a middleware sends a response AND calls next().\n *\n * @remarks\n * Opt-in and defaults to `false` — `@nextrush/core` is a runtime-agnostic\n * package and must not read `process.env` (global-rules §2, audit C-4). The\n * `Application` enables this in non-production by passing the flag from its\n * own `env` option.\n *\n * @default false\n */\n warnDoubleResponse?: boolean;\n}\n\n/**\n * Compose multiple middleware functions into a single middleware.\n *\n * Executes middleware in order, each middleware can call `await next()`\n * to pass control to the next middleware and wait for it to complete.\n *\n * @param middleware - Array of middleware functions to compose\n * @param options - Composition options\n * @returns Single composed middleware function\n *\n * @example\n * ```typescript\n * const composed = compose([\n * async (ctx, next) => {\n * console.log('1 - before');\n * await next();\n * console.log('1 - after');\n * },\n * async (ctx, next) => {\n * console.log('2 - before');\n * await next();\n * console.log('2 - after');\n * },\n * ]);\n *\n * // Output:\n * // 1 - before\n * // 2 - before\n * // 2 - after\n * // 1 - after\n * ```\n */\nexport function compose(middleware: Middleware[], options?: ComposeOptions): ComposedMiddleware {\n // Validate middleware array\n if (!Array.isArray(middleware)) {\n throw new TypeError('Middleware stack must be an array');\n }\n\n for (const fn of middleware) {\n if (typeof fn !== 'function') {\n throw new TypeError('Middleware must be a function');\n }\n }\n\n const warnDoubleResponse = options?.warnDoubleResponse ?? false;\n\n // Snapshot middleware array at compose time\n const stack = [...middleware];\n const len = stack.length;\n\n // FAST PATH: No middleware — just call next()\n if (len === 0) {\n return function composedMiddleware(_ctx: Context, next?: Next): Promise<void> {\n return next ? next() : Promise.resolve();\n };\n }\n\n // FAST PATH: Exactly one middleware — the overwhelmingly common application\n // shape (a single mounted router). Avoids allocating the recursive `dispatch`\n // closure and the per-call index comparison of the general path while\n // preserving every observable semantic (design D2/D3/D7):\n // - a PER-INVOCATION guard (`called`) declared inside the returned function,\n // never hoisted, so concurrent requests cannot corrupt each other;\n // - the SAME guarded thunk is passed as the `next` argument AND wired to\n // `ctx.setNext`, so a double-call is caught across either surface;\n // - a synchronous throw becomes a rejected promise and non-`Error` throws\n // are wrapped, identical to the general path.\n if (len === 1) {\n const only = stack[0];\n if (only) {\n return function composedSingle(ctx: Context, next?: Next): Promise<void> {\n let called = false; // PER-INVOCATION — must never be hoisted out of here\n const nextFn = (): Promise<void> => {\n if (called) {\n return Promise.reject(new Error(MULTIPLE_NEXT_MESSAGE));\n }\n called = true;\n if (warnDoubleResponse && ctx.responded) {\n emitDoubleResponseWarning(0);\n }\n return next ? next() : Promise.resolve();\n };\n\n // Wire ctx.next() to the SAME thunk passed as the argument (design D3).\n if (ctx.setNext) {\n ctx.setNext(nextFn);\n }\n\n try {\n return Promise.resolve(only(ctx, nextFn));\n } catch (err: unknown) {\n return Promise.reject(err instanceof Error ? err : new Error(String(err)));\n }\n };\n }\n }\n\n /**\n * Composed middleware function\n * Uses index-based dispatch to avoid per-request closure chains\n * while preserving double-next detection per call.\n */\n return function composedMiddleware(ctx: Context, next?: Next): Promise<void> {\n // Per-request index tracker — only state needed\n let index = -1;\n\n function dispatch(i: number): Promise<void> {\n if (i <= index) {\n return Promise.reject(new Error(MULTIPLE_NEXT_MESSAGE));\n }\n\n index = i;\n\n let fn: Middleware | Next | undefined;\n if (i < len) {\n fn = stack[i];\n } else if (i === len) {\n fn = next;\n }\n\n if (!fn) {\n return Promise.resolve();\n }\n\n const nextFn = (): Promise<void> => {\n if (warnDoubleResponse && ctx.responded) {\n emitDoubleResponseWarning(i);\n }\n return dispatch(i + 1);\n };\n\n // Wire up ctx.next() if the context supports it\n if (ctx.setNext) {\n ctx.setNext(nextFn);\n }\n\n try {\n return Promise.resolve(fn(ctx, nextFn));\n } catch (err: unknown) {\n return Promise.reject(err instanceof Error ? err : new Error(String(err)));\n }\n }\n\n return dispatch(0);\n };\n}\n\n/**\n * Check if a function is a valid middleware\n */\nexport function isMiddleware(fn: unknown): fn is Middleware {\n return typeof fn === 'function';\n}\n\n/**\n * Flatten nested middleware arrays with type validation.\n * Uses bounded depth (10 levels) to prevent V8 deoptimization on deeply nested arrays.\n */\nexport function flattenMiddleware(arr: (Middleware | Middleware[])[]): Middleware[] {\n const flattened = arr.flat(10);\n for (const fn of flattened) {\n if (typeof fn !== 'function') {\n throw new TypeError(`Invalid middleware: expected function, got ${typeof fn}`);\n }\n }\n return flattened;\n}\n","/**\n * @nextrush/core - Default Error Response\n *\n * The framework's default error serialization, extracted from `Application`\n * (audit C-5). Produces the same JSON shape as `@nextrush/errors`'\n * `errorHandler()` so there is ONE error contract framework-wide (audit C-1):\n * a `NextRushError` serializes via its own `toJSON()`; a plain error becomes a\n * safe coded 500.\n *\n * @packageDocumentation\n */\n\nimport { getErrorStatus, getHttpStatusMessage, NextRushError } from '@nextrush/errors';\nimport type { Context, Logger } from '@nextrush/types';\n\n/** Options for {@link writeDefaultErrorResponse}. */\nexport interface DefaultErrorOptions {\n logger: Logger;\n isProduction: boolean;\n}\n\n/**\n * Write the default error response to `ctx`.\n *\n * @remarks\n * 5xx are always logged; 4xx only outside production (audit C-7). The internal\n * message of a non-exposed error is never sent to the client.\n */\nexport function writeDefaultErrorResponse(\n error: Error,\n ctx: Context,\n opts: DefaultErrorOptions\n): void {\n const status = getErrorStatus(error);\n\n if (status >= 500 || !opts.isProduction) {\n opts.logger.error('Request error:', error);\n }\n\n ctx.status = status;\n\n if (error instanceof NextRushError) {\n ctx.json(error.toJSON());\n return;\n }\n\n const expose = status < 500;\n ctx.json({\n error: expose ? error.name : getHttpStatusMessage(status),\n message: expose ? error.message : 'Internal Server Error',\n code: 'INTERNAL_ERROR',\n status,\n });\n}\n","/**\n * @nextrush/core - Router Prefix Mount\n *\n * Builds the middleware that mounts a router at a path prefix, rewriting\n * `ctx.path` for the duration of the sub-router and restoring it afterward.\n * Extracted from `Application.route()` (audit C-5).\n *\n * @packageDocumentation\n */\n\nimport type { Context, Middleware } from '@nextrush/types';\n\n/** @internal Symbol keys for mount state — avoids polluting the user's ctx.state namespace */\nconst ORIGINAL_PATH = Symbol.for('nextrush.originalPath');\nconst ROUTE_PREFIX = Symbol.for('nextrush.routePrefix');\n\n/**\n * Create a middleware that mounts `routerMiddleware` at `normalizedPrefix`.\n *\n * @remarks\n * On a matching request it strips the prefix from `ctx.path`, runs the mounted\n * middleware, and restores the original path in a `finally` — including across\n * the downstream `next()` boundary, so middleware after the mount sees the\n * original path. Callers pass an already-normalized prefix (leading `/`, no\n * trailing `/`).\n *\n * @param normalizedPrefix - The mount prefix (e.g. `/api/users`).\n * @param routerMiddleware - The mounted router's `routes()` middleware.\n */\nexport function createPrefixMount(\n normalizedPrefix: string,\n routerMiddleware: Middleware\n): Middleware {\n const prefixLen = normalizedPrefix.length;\n\n return async (ctx: Context, next): Promise<void> => {\n const currentPath = ctx.path;\n\n // Fast prefix check\n if (!currentPath.startsWith(normalizedPrefix)) {\n return next();\n }\n\n // Check prefix boundary (avoid /api/usersxxx matching /api/users)\n const hasCharAfterPrefix = prefixLen < currentPath.length;\n if (hasCharAfterPrefix && currentPath.charCodeAt(prefixLen) !== 47) {\n // 47 = '/'\n return next();\n }\n\n // Direct path manipulation (no Proxy - fast!)\n const adjustedPath = currentPath.slice(prefixLen) || '/';\n (ctx as { path: string }).path = adjustedPath;\n\n // Store original for recovery (Symbol keys avoid ctx.state pollution)\n (ctx.state as Record<symbol, unknown>)[ORIGINAL_PATH] = currentPath;\n (ctx.state as Record<symbol, unknown>)[ROUTE_PREFIX] = normalizedPrefix;\n\n try {\n await routerMiddleware(ctx, async () => {\n (ctx as { path: string }).path = currentPath;\n await next();\n (ctx as { path: string }).path = adjustedPath;\n });\n } finally {\n (ctx as { path: string }).path = currentPath;\n (ctx.state as Record<symbol, unknown>)[ORIGINAL_PATH] = undefined;\n (ctx.state as Record<symbol, unknown>)[ROUTE_PREFIX] = undefined;\n }\n };\n}\n","/**\n * @nextrush/core - Application Class\n *\n * The Application class is the main entry point for NextRush.\n * It manages middleware registration and the extension lifecycle.\n *\n * See docs/RFC/class-runtime/005-plugin-system.md for the extension model.\n *\n * @packageDocumentation\n */\n\nimport type {\n Container,\n Context,\n Extension,\n ExtensionContext,\n Logger,\n Middleware,\n RouteEntry,\n Router,\n} from '@nextrush/types';\nimport { compose } from './middleware';\nimport { writeDefaultErrorResponse } from './error-handler';\nimport { createPrefixMount } from './route-mount';\n\n/**\n * Error handler function type\n */\nexport type ErrorHandler = (error: Error, ctx: Context) => void | Promise<void>;\n\n/**\n * Options for {@link Application.close}.\n *\n * @see RFC-022 (`docs/RFC/class-runtime/022-bounded-teardown-lifecycle.md`) / ADR-0012.\n */\nexport interface CloseOptions {\n /**\n * Bound, in milliseconds, on total teardown time. Every teardown unit\n * (extension `destroy()`) races against this budget independently — a\n * unit that does not finish in time is reported as a {@link TeardownTimeoutError}\n * in the returned array, and never blocks `close()` past the budget.\n *\n * @remarks Omitted = unbounded, identical to calling `close()` with no\n * arguments today (`Promise.allSettled`, no timeout).\n */\n timeout?: number;\n}\n\n/**\n * Reported when a teardown unit (extension `destroy()`) does not settle\n * within the budget passed to {@link Application.close}. Named by the unit\n * so operators can see exactly which extension leaked past the shutdown\n * window (RFC-022 §8.5).\n */\nexport class TeardownTimeoutError extends Error {\n constructor(unitName: string, timeoutMs: number) {\n super(`Teardown unit \"${unitName}\" did not complete within ${String(timeoutMs)}ms`);\n this.name = 'TeardownTimeoutError';\n }\n}\n\n/**\n * One named, independently-runnable teardown unit — the uniform shape shared\n * by extension `destroy()`, class `onShutdown()` (bridged externally), and\n * `onClose` hooks (RFC-022 §7.3: \"teardown becomes a flat list of\n * independently-isolated, budget-raced units\").\n */\ninterface TeardownUnit {\n readonly name: string;\n run(): void | Promise<void>;\n}\n\n/**\n * Run one teardown unit, isolated from every other unit's failure, optionally\n * racing it against `timeoutMs`. Resolves to `null` on success or an `Error`\n * describing the failure/timeout — never throws and never leaves the caller\n * waiting past the budget.\n */\nasync function runTeardownUnit(unit: TeardownUnit, timeoutMs?: number): Promise<Error | null> {\n const settle = Promise.resolve()\n .then(() => unit.run())\n .then((): Error | null => null)\n .catch((err: unknown): Error => (err instanceof Error ? err : new Error(String(err))));\n\n if (timeoutMs === undefined) {\n return settle;\n }\n\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timedOut = new Promise<Error>((resolve) => {\n timer = setTimeout(() => {\n resolve(new TeardownTimeoutError(unit.name, timeoutMs));\n }, timeoutMs);\n });\n\n try {\n return await Promise.race([settle, timedOut]);\n } finally {\n clearTimeout(timer);\n }\n}\n\n/** No-op logger — default when no logger is configured */\nconst NOOP_LOGGER: Logger = {\n error(..._args) {\n void _args;\n },\n warn(..._args) {\n void _args;\n },\n info(..._args) {\n void _args;\n },\n debug(..._args) {\n void _args;\n },\n};\n\n/**\n * Application options\n */\nexport interface ApplicationOptions {\n /**\n * Environment mode\n * @default 'development'\n */\n env?: 'development' | 'production' | 'test';\n\n /**\n * Whether to use proxy headers (X-Forwarded-For, etc.)\n * @default false\n */\n proxy?: boolean;\n\n /**\n * Custom logger. Defaults to no-op (silent).\n *\n * @remarks\n * Pass `console` for quick development logging. For production, provide a\n * structured logger (pino, winston, `@nextrush/logger`) implementing {@link Logger}.\n */\n logger?: Logger;\n\n /**\n * A router the app owns. Route methods (`app.get`, `app.post`, …) delegate to\n * it, and it is mounted last at `ready()`. The `nextrush` meta-package's\n * `createApp` injects one automatically; pass it explicitly when using\n * `@nextrush/core` directly.\n */\n router?: Router;\n\n /**\n * A per-app DI container. Exposed to extensions via `ExtensionContext.container`\n * and used by class-based registrars (e.g. `registerControllers`). Injected by\n * `nextrush/class`; omitted for functional, DI-free apps.\n */\n container?: Container;\n}\n\n/**\n * Listener callback type\n */\nexport type ListenCallback = () => void;\n\n/**\n * Routable interface - any object with routes() method.\n * Allows mounting Router instances without a circular dependency.\n */\nexport interface Routable {\n routes(): Middleware;\n}\n\n/**\n * The Application class\n *\n * @example\n * ```typescript\n * const app = createApp();\n *\n * app.use(async (ctx) => {\n * ctx.json({ message: 'Hello World' });\n * });\n *\n * // Extensions (rare — long-lived services) are booted at ready(), which\n * // adapters call automatically before start().\n * app.extend(events());\n *\n * listen(app, { port: 8080 });\n * ```\n */\nexport class Application {\n /** Middleware stack */\n private readonly middlewareStack: Middleware[] = [];\n\n /** Registered extensions, in registration order (setup runs at ready()) */\n private readonly extensions: Extension<unknown>[] = [];\n\n /** Registered extension names — enforces uniqueness */\n private readonly extensionNames = new Set<string>();\n\n /**\n * Combined teardown-unit registration order: extension `destroy()`s and\n * {@link onClose} hooks interleaved in the exact order they were registered,\n * so `_shutdown()` can run the whole set in one reverse-of-registration pass\n * (RFC-022 §7.3 — \"teardown becomes a flat list of independently-isolated,\n * budget-raced units\"). Populated lazily by {@link extend} (for extensions\n * declaring `destroy()`) and {@link onClose}.\n */\n private readonly teardownUnits: TeardownUnit[] = [];\n\n /** Whether {@link close} has started — {@link onClose} is a pre-shutdown-only registration point (RFC-022 §8.6). */\n private _closeStarted = false;\n\n /** Names decorated onto the app — enforces collision detection */\n private readonly decorations = new Set<string>();\n\n /** Custom error handler */\n private _errorHandler: ErrorHandler | null = null;\n\n /** Pluggable logger */\n readonly logger: Logger;\n\n /** Application options */\n readonly options: ApplicationOptions;\n\n /** Whether the app is running (server listening) */\n private _isRunning = false;\n\n /** Whether the app has been booted (extensions set up, config frozen) */\n private _isReady = false;\n\n /** Whether ready() mounted the app-owned router (so close() can undo it) */\n private _routerMounted = false;\n\n /** In-flight boot promise — memoized so concurrent ready() calls share one boot (H-1) */\n private _readyPromise: Promise<this> | null = null;\n\n /** In-flight shutdown promise — memoized so concurrent close() calls share one (H-3) */\n private _closePromise: Promise<Error[]> | null = null;\n\n /** The app-owned router (optional). Route methods delegate to it. */\n readonly router?: Router;\n\n /** The app-owned DI container (optional). Exposed to extensions and registrars. */\n readonly container?: Container;\n\n constructor(options: ApplicationOptions = {}) {\n this.options = {\n env: options.env ?? 'development',\n proxy: options.proxy ?? false,\n };\n this.logger = options.logger ?? NOOP_LOGGER;\n this.router = options.router;\n this.container = options.container;\n }\n\n /** Check if running in production */\n get isProduction(): boolean {\n return this.options.env === 'production';\n }\n\n /** Check if app is running */\n get isRunning(): boolean {\n return this._isRunning;\n }\n\n /**\n * Whether a graceful shutdown is currently in progress — `true` from the\n * moment {@link close} begins tearing down until it completes (F-12:\n * shutdown observability, RFC-022). A readiness check or operator tooling\n * can read this to reflect an in-progress drain.\n */\n get isDraining(): boolean {\n return this._closeStarted;\n }\n\n /** Check if app has been booted via ready() */\n get isReady(): boolean {\n return this._isReady;\n }\n\n /** Get middleware count */\n get middlewareCount(): number {\n return this.middlewareStack.length;\n }\n\n /** Get registered extension count */\n get extensionCount(): number {\n return this.extensions.length;\n }\n\n /**\n * Throws if the app configuration is frozen (after ready() or start()).\n * Prevents unsafe mutations once the app has booted or is serving traffic.\n */\n private assertConfigurable(method: string): void {\n if (this._isReady || this._isRunning) {\n throw new Error(\n `Cannot call ${method}() after the app has booted (ready()) or started — ` +\n `configuration is frozen`\n );\n }\n }\n\n // ===========================================================================\n // Middleware Registration\n // ===========================================================================\n\n /**\n * Register middleware function(s)\n *\n * @param middleware - Middleware function(s)\n * @returns this for chaining\n */\n use(...middleware: Middleware[]): this {\n this.assertConfigurable('use');\n for (const mw of middleware) {\n if (typeof mw !== 'function') {\n throw new TypeError('Middleware must be a function');\n }\n this.middlewareStack.push(mw);\n }\n return this;\n }\n\n // ===========================================================================\n // Router Mounting (Hono-style)\n // ===========================================================================\n\n /**\n * Mount a router at a path prefix.\n *\n * @param path - Path prefix (e.g. '/api/users')\n * @param router - Router instance to mount\n * @returns this for chaining\n */\n route(path: string, router: Routable): this {\n this.assertConfigurable('route');\n // Root mount optimization: skip all prefix processing\n if (path === '/' || path === '') {\n this.middlewareStack.push(router.routes());\n return this;\n }\n\n const routerMiddleware = router.routes();\n // Normalize prefix: ensure leading '/', strip trailing '/'\n let normalizedPrefix = path.endsWith('/') ? path.slice(0, -1) : path;\n if (!normalizedPrefix.startsWith('/')) {\n normalizedPrefix = '/' + normalizedPrefix;\n }\n\n this.middlewareStack.push(createPrefixMount(normalizedPrefix, routerMiddleware));\n return this;\n }\n\n // ===========================================================================\n // Routing (delegates to the app-owned router)\n // ===========================================================================\n\n private requireRouter(): Router {\n if (!this.router) {\n throw new Error(\n 'No router configured. Create your app with `createApp()` from `nextrush` ' +\n '(batteries-included), or pass one: `createApp({ router: createRouter() })`.'\n );\n }\n return this.router;\n }\n\n /** Register a GET route on the app-owned router. */\n get(path: string, ...entries: RouteEntry[]): this {\n this.assertConfigurable('get');\n this.requireRouter().get(path, ...entries);\n return this;\n }\n\n /** Register a POST route on the app-owned router. */\n post(path: string, ...entries: RouteEntry[]): this {\n this.assertConfigurable('post');\n this.requireRouter().post(path, ...entries);\n return this;\n }\n\n /** Register a PUT route on the app-owned router. */\n put(path: string, ...entries: RouteEntry[]): this {\n this.assertConfigurable('put');\n this.requireRouter().put(path, ...entries);\n return this;\n }\n\n /** Register a PATCH route on the app-owned router. */\n patch(path: string, ...entries: RouteEntry[]): this {\n this.assertConfigurable('patch');\n this.requireRouter().patch(path, ...entries);\n return this;\n }\n\n /** Register a DELETE route on the app-owned router. */\n delete(path: string, ...entries: RouteEntry[]): this {\n this.assertConfigurable('delete');\n this.requireRouter().delete(path, ...entries);\n return this;\n }\n\n /** Register a HEAD route on the app-owned router. */\n head(path: string, ...entries: RouteEntry[]): this {\n this.assertConfigurable('head');\n this.requireRouter().head(path, ...entries);\n return this;\n }\n\n /**\n * Register a route for all HTTP methods on the app-owned router.\n *\n * @remarks\n * There is intentionally no `app.options()` verb method — it would collide\n * with the `app.options` configuration property. Register OPTIONS routes via\n * `app.all()`, the router directly, or let CORS middleware handle preflight.\n */\n all(path: string, ...entries: RouteEntry[]): this {\n this.assertConfigurable('all');\n this.requireRouter().all(path, ...entries);\n return this;\n }\n\n // ===========================================================================\n // Error Handling\n // ===========================================================================\n\n /**\n * Set the application error handler. Replaces any previously set handler.\n *\n * @param handler - Error handler function\n * @returns this for chaining\n */\n setErrorHandler(handler: ErrorHandler): this {\n this.assertConfigurable('setErrorHandler');\n this._errorHandler = handler;\n return this;\n }\n\n // ===========================================================================\n // Extension System (see RFC-NEXTRUSH-PLUGIN-SYSTEM)\n // ===========================================================================\n\n /**\n * Register an extension. Queues it — `setup()` runs later, at `ready()`,\n * in registration order. Synchronous and chainable.\n *\n * @param extension - Extension to register. If it declares a decorated\n * shape via `Extension<TDecorated>`, the return type carries that shape —\n * `app.extend(events<MyEvents>()).events` is statically known, no\n * `declare module` augmentation required.\n * @returns this, intersected with the extension's declared decorated shape\n *\n * @example\n * ```typescript\n * const extended = app.extend(events<MyEvents>());\n * await app.ready(); // adapters call this automatically — runs setup()/decorate()\n * extended.events.emit('user:created', { id: '1' }); // available only AFTER ready()\n * ```\n */\n extend<TDecorated = Record<string, never>>(\n extension: Extension<TDecorated>\n ): this & TDecorated {\n this.assertConfigurable('extend');\n // Runtime guard for externally-supplied input: the type says non-null with a\n // required setup(), but user/plugin code can still violate that at runtime.\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- defensive validation of external input\n if (!extension || typeof extension.setup !== 'function') {\n throw new TypeError('Extension must have a setup() method');\n }\n if (this.extensionNames.has(extension.name)) {\n throw new Error(\n `Extension \"${extension.name}\" is already registered. Use a different extension ` +\n `name, or check for a duplicate app.extend() call.`\n );\n }\n this.extensionNames.add(extension.name);\n this.extensions.push(extension);\n if (typeof extension.destroy === 'function') {\n const destroyableExtension = extension as Extension<TDecorated> & {\n destroy: () => void | Promise<void>;\n };\n this.teardownUnits.push({\n name: extension.name,\n run: () => destroyableExtension.destroy(),\n });\n }\n return this as this & TDecorated;\n }\n\n /**\n * Boot the application: run every registered extension's `setup()` once, in\n * registration order, awaiting async setups. Idempotent — safe to call twice.\n * Adapters call this automatically before `start()`.\n *\n * After `ready()` resolves, the configuration is frozen (`use`/`route`/`extend`\n * throw).\n *\n * @returns this\n * @throws if an extension declares a `needs` dependency not yet registered\n */\n async ready(): Promise<this> {\n if (this._isReady) {\n return this;\n }\n\n // Memoize the in-flight boot so concurrent `await app.ready()` calls share a\n // single setup() pass (H-1). Without this, two racing callers both clear the\n // `_isReady` guard, run every extension's setup() twice, and the second\n // decorate() throws a collision. On failure, clear the memo so a retry can\n // re-attempt boot.\n this._readyPromise ??= this._boot().catch((err: unknown) => {\n this._readyPromise = null;\n throw err;\n });\n return this._readyPromise;\n }\n\n /**\n * Run the boot sequence once (extension setup + router mount). Guarded and\n * memoized by {@link ready}.\n */\n private async _boot(): Promise<this> {\n // extension SOMEWHERE (regardless of order) — catches a typo'd or\n // never-registered dependency name with a distinct message from the\n // order-sensitive check below, before running any setup().\n const allNames = new Set(this.extensions.map((e) => e.name));\n for (const extension of this.extensions) {\n if (extension.needs) {\n for (const dep of extension.needs) {\n if (!allNames.has(dep)) {\n throw new Error(\n `Extension \"${extension.name}\" needs \"${dep}\", but no extension named ` +\n `\"${dep}\" was ever registered.`\n );\n }\n }\n }\n }\n\n const setupDone = new Set<string>();\n\n for (const extension of this.extensions) {\n // Declare-and-assert dependency check (no auto-sort; registration order is the order)\n if (extension.needs) {\n for (const dep of extension.needs) {\n if (!setupDone.has(dep)) {\n throw new Error(\n `Extension \"${extension.name}\" needs \"${dep}\", but \"${dep}\" was not ` +\n `registered before it. Register the \"${dep}\" extension before \"${extension.name}\".`\n );\n }\n }\n }\n\n const ctx: ExtensionContext = {\n app: this,\n logger: this.logger,\n container: this.container,\n env: this.options.env ?? 'development',\n name: extension.name,\n decorate: (name: string, value: unknown): void => {\n this.decorate(name, value);\n },\n };\n\n await extension.setup(ctx);\n setupDone.add(extension.name);\n }\n\n // Mount the app-owned router LAST, so routes run after all middleware\n // (both user- and extension-registered).\n if (this.router) {\n this.middlewareStack.push(this.router.routes());\n this._routerMounted = true;\n }\n\n this._isReady = true;\n return this;\n }\n\n /**\n * Attach a value to the app under `name`. Extension-author primitive, invoked\n * through {@link ExtensionContext.decorate} — there is intentionally no public\n * `app.decorate()` (RFC §6.1). Throws on collision.\n *\n * @internal\n */\n private decorate(name: string, value: unknown): void {\n if (this.decorations.has(name)) {\n throw new Error(\n `Decoration \"${name}\" already exists on the application. Choose a different ` +\n `name, or check for a duplicate ctx.decorate() call across your extensions.`\n );\n }\n if (name in this) {\n throw new Error(\n `Decoration \"${name}\" collides with an existing Application member — choose another name`\n );\n }\n Object.defineProperty(this, name, {\n value,\n enumerable: true,\n writable: false,\n configurable: true, // allow close() to clean up\n });\n this.decorations.add(name);\n }\n\n /**\n * Whether a decoration already occupies `name`.\n */\n hasDecorator(name: string): boolean {\n return this.decorations.has(name);\n }\n\n // ===========================================================================\n // Request Handler\n // ===========================================================================\n\n /**\n * Create the request handler callback.\n *\n * The middleware stack is snapshot at call time — call `ready()` before\n * `callback()` so extension-registered middleware is included. Adapters do\n * this automatically.\n *\n * @returns Request handler function\n */\n callback(): (ctx: Context) => Promise<void> {\n if (!this._isReady && this.extensions.length > 0) {\n this.logger.warn(\n `callback() was called before ready(), but ${String(this.extensions.length)} extension(s) ` +\n `were registered via extend() — their setup() will NOT run, and anything they ` +\n `would decorate (e.g. app.events) will be missing. Call \\`await app.ready()\\` ` +\n `before \\`callback()\\`. Adapters (listen/serve) do this automatically.`\n );\n }\n\n const fn = compose(this.middlewareStack, {\n warnDoubleResponse: !this.isProduction,\n });\n\n return async (ctx: Context): Promise<void> => {\n try {\n await fn(ctx);\n } catch (error) {\n await this.handleError(error, ctx);\n }\n };\n }\n\n /**\n * Handle errors - uses custom handler if set, otherwise default\n */\n private async handleError(error: unknown, ctx: Context): Promise<void> {\n const err = error instanceof Error ? error : new Error(String(error));\n\n if (this._errorHandler) {\n try {\n await this._errorHandler(err, ctx);\n return;\n } catch (handlerError) {\n this.logger.error('Error handler threw:', handlerError);\n }\n }\n\n // The default handler can itself throw (e.g. ctx.json when the response is\n // already committed). Swallow-and-log so the request settles instead of\n // rejecting out of callback() into the adapter as an unhandled error (H-2).\n try {\n this.defaultErrorHandler(err, ctx);\n } catch (fatal) {\n this.logger.error('Default error handler threw:', fatal);\n }\n }\n\n /**\n * Default error handler — delegates to the shared error serializer so the\n * default response matches `@nextrush/errors`' `errorHandler()` (audit C-1).\n */\n private defaultErrorHandler(error: Error, ctx: Context): void {\n writeDefaultErrorResponse(error, ctx, {\n logger: this.logger,\n isProduction: this.isProduction,\n });\n }\n\n // ===========================================================================\n // Lifecycle\n // ===========================================================================\n\n /**\n * Mark app as running and freeze configuration.\n *\n * Called by adapters when the server starts listening (after `ready()`).\n */\n start(): void {\n this._isRunning = true;\n }\n\n /**\n * Register a teardown hook for a resource outside the extension system\n * (stateful middleware, a manually-attached service, …). Run during\n * {@link close} under the SAME bounded/isolated guarantee as extension\n * `destroy()` — one throwing/hanging hook never strands the others — in one\n * combined reverse-of-registration order together with every `extend()`ed\n * extension's `destroy()` (RFC-022 §8.1/§8.2).\n *\n * @param hook - Teardown callback. May be sync or async; a thrown/rejected\n * hook is isolated and its error collected in {@link close}'s returned array.\n *\n * @remarks Registration is pre-shutdown only: a hook registered after\n * `close()` has already started is not run in that shutdown (RFC-022 §8.6).\n *\n * @example\n * ```typescript\n * const store = new MemoryStore(options);\n * app.onClose(() => store.shutdown());\n * ```\n */\n onClose(hook: () => void | Promise<void>): void {\n if (this._closeStarted) {\n return;\n }\n this.teardownUnits.push({ name: 'onClose hook', run: hook });\n }\n\n /**\n * Graceful shutdown. Destroys extensions in reverse registration order,\n * each isolated from the others' failures — one failing/hanging `destroy()`\n * never strands the rest (RFC-022 / ADR-0012).\n *\n * @param options - Optional teardown budget. Omitted = unbounded, byte-identical\n * to today's behavior (`Promise.allSettled`, no timeout). When `timeout` is\n * given, every teardown unit races against it independently; a unit that\n * does not finish in time is reported as a {@link TeardownTimeoutError} in\n * the returned array instead of blocking `close()` past the budget.\n * @returns Array of errors from units that failed or timed out (empty on success)\n */\n async close(options?: CloseOptions): Promise<Error[]> {\n // Memoize the in-flight shutdown so concurrent close() calls (e.g. two\n // signal handlers) destroy each extension exactly once (H-3).\n this._closePromise ??= this._shutdown(options);\n return this._closePromise;\n }\n\n /** Run the shutdown sequence once. Guarded and memoized by {@link close}. */\n private async _shutdown(options?: CloseOptions): Promise<Error[]> {\n this._isRunning = false;\n this._closeStarted = true;\n // F-12: surface the draining transition so operators/readiness checks can\n // observe an in-progress shutdown instead of it being a silent black box.\n this.logger.info('Application is draining: graceful shutdown starting');\n\n if (!this._isReady && this.extensions.length > 0) {\n this.logger.warn(\n `close() was called before ready(), but ${String(this.extensions.length)} extension(s) ` +\n `were registered via extend() — their setup() never ran, yet destroy() will still ` +\n `be called on them now. If destroy() assumes setup()-established state, this may ` +\n `throw or behave incorrectly. Call \\`await app.ready()\\` before \\`close()\\`.`\n );\n }\n\n const timeoutMs = options?.timeout;\n // Reverse of registration order across BOTH extension destroy() calls and\n // onClose hooks — one uniform, combined teardown-unit list (RFC-022 §7.3),\n // so a hook registered between two extend() calls runs at the correct\n // point in the reversed sequence, not as a separate pass.\n const units = [...this.teardownUnits].reverse();\n\n const errors = (\n await Promise.all(units.map((unit) => runTeardownUnit(unit, timeoutMs)))\n ).filter((e): e is Error => e !== null);\n\n // F-12: report the teardown outcome at completion — which unit(s) failed\n // or timed out — rather than exiting silently. TeardownTimeoutError's own\n // message already names the offending unit (§8.5).\n for (const error of errors) {\n this.logger.error('Teardown unit failed during shutdown:', error);\n }\n\n // Clean up decorations so the instance can be re-booted (e.g. in tests)\n for (const name of this.decorations) {\n Reflect.deleteProperty(this, name);\n }\n this.decorations.clear();\n this.extensions.length = 0;\n this.extensionNames.clear();\n this.teardownUnits.length = 0;\n this._isReady = false;\n // Reset the boot/shutdown memos so the instance can be cleanly re-booted\n // (re-boot in tests / hot reload) — a fresh ready()/close() must re-run.\n this._readyPromise = null;\n this._closePromise = null;\n this._closeStarted = false;\n\n // Undo the router mount that ready() appended, so a subsequent ready()\n // (re-boot in tests / hot reload) does not stack a second router (audit C-2).\n if (this._routerMounted) {\n this.middlewareStack.pop();\n this._routerMounted = false;\n }\n\n return errors;\n }\n}\n\n/**\n * Create a new Application instance\n *\n * @param options - Application options\n * @returns New Application instance\n */\nexport function createApp(options?: ApplicationOptions): Application {\n return new Application(options);\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nextrush/core",
3
- "version": "3.0.6",
3
+ "version": "4.0.0-beta.0",
4
4
  "description": "Core functionality for NextRush framework - Application, Context, Middleware",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -46,14 +46,14 @@
46
46
  "access": "public"
47
47
  },
48
48
  "dependencies": {
49
- "@nextrush/errors": "3.0.6",
50
- "@nextrush/types": "3.0.6"
49
+ "@nextrush/errors": "4.0.0-beta.0",
50
+ "@nextrush/types": "4.0.0-beta.0"
51
51
  },
52
52
  "devDependencies": {
53
- "@types/node": "^25.5.2",
53
+ "@types/node": "^25.9.5",
54
54
  "tsup": "^8.5.1",
55
- "typescript": "^6.0.2",
56
- "vitest": "^4.1.4"
55
+ "typescript": "^6.0.3",
56
+ "vitest": "^4.1.10"
57
57
  },
58
58
  "sideEffects": false,
59
59
  "scripts": {