@emmett-community/emmett-expressjs-with-openapi 0.3.0 → 0.5.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/README.md +91 -0
- package/dist/chunk-FSPH5TRT.cjs +45 -0
- package/dist/chunk-FSPH5TRT.cjs.map +1 -0
- package/dist/chunk-PZBLPYJH.js +45 -0
- package/dist/chunk-PZBLPYJH.js.map +1 -0
- package/dist/{handler-importer-4BVBIZX3.cjs → handler-importer-BRJVJNST.cjs} +21 -2
- package/dist/handler-importer-BRJVJNST.cjs.map +1 -0
- package/dist/{handler-importer-OJGFQON5.js → handler-importer-V4EJZ2DG.js} +21 -2
- package/dist/handler-importer-V4EJZ2DG.js.map +1 -0
- package/dist/index.cjs +110 -36
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +142 -1
- package/dist/index.d.ts +142 -1
- package/dist/index.js +97 -23
- package/dist/index.js.map +1 -1
- package/dist/{openapi-parser-NFUD7ZGZ.cjs → openapi-parser-HMWO3IPV.cjs} +27 -8
- package/dist/openapi-parser-HMWO3IPV.cjs.map +1 -0
- package/dist/{openapi-parser-CCYU636U.js → openapi-parser-SFYDJEIN.js} +27 -7
- package/dist/openapi-parser-SFYDJEIN.js.map +1 -0
- package/package.json +2 -1
- package/dist/handler-importer-4BVBIZX3.cjs.map +0 -1
- package/dist/handler-importer-OJGFQON5.js.map +0 -1
- package/dist/openapi-parser-CCYU636U.js.map +0 -1
- package/dist/openapi-parser-NFUD7ZGZ.cjs.map +0 -1
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/runner/work/emmett-expressjs-with-openapi/emmett-expressjs-with-openapi/dist/index.cjs","../src/index.ts","../src/application.ts","../src/middlewares/problemDetailsMiddleware.ts","../src/etag.ts","../src/handler.ts","../src/openapi/firebase-auth.ts","../src/openapi/index.ts","../src/responses.ts","../src/testing/apiE2ESpecification.ts","../src/testing/apiSpecification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ViU8C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/emmett-expressjs-with-openapi/emmett-expressjs-with-openapi/dist/index.cjs","sourcesContent":[null,"import 'express-async-errors';\n\nexport * from './application';\nexport * from './etag';\nexport * from './handler';\nexport * from './openapi';\nexport * from './responses';\nexport * from './testing';\nexport { registerHandlerModule } from './internal/esm-resolver';\n","import express, {\n Router,\n type Application,\n type RequestHandler,\n} from 'express';\nimport 'express-async-errors';\nimport http from 'http';\nimport { createRequire } from 'node:module';\nimport { problemDetailsMiddleware } from './middlewares/problemDetailsMiddleware';\nimport type { OpenApiValidatorOptions } from './openapi';\nimport type { ErrorToProblemDetailsMapping } from './responses';\n\n// #region web-api-setup\nexport type WebApiSetup = (router: Router) => void;\n// #endregion web-api-setup\n\n/**\n * Options forwarded to pino-http. Typed loosely to avoid hard dependency.\n *\n * @see https://github.com/pinojs/pino-http\n */\nexport type PinoHttpOptions = Record<string, unknown>;\n\nexport type ApplicationOptions = {\n apis?: WebApiSetup[];\n mapError?: ErrorToProblemDetailsMapping;\n enableDefaultExpressEtag?: boolean;\n disableJsonMiddleware?: boolean;\n disableUrlEncodingMiddleware?: boolean;\n disableProblemDetailsMiddleware?: boolean;\n /**\n * Optional Pino HTTP logger configuration.\n * When true, enables pino-http with defaults.\n * When an object, forwards the options to pino-http.\n * Requires the 'pino-http' package to be installed.\n *\n * @see https://github.com/pinojs/pino-http\n * @example\n * ```typescript\n * const app = await getApplication({\n * pinoHttp: true,\n * });\n *\n * const app = await getApplication({\n * pinoHttp: { autoLogging: false },\n * });\n * ```\n */\n pinoHttp?: boolean | PinoHttpOptions;\n /**\n * Optional OpenAPI validator configuration.\n * When provided, enables request/response validation against an OpenAPI specification.\n * Requires the 'express-openapi-validator' package to be installed.\n *\n * @see https://github.com/cdimascio/express-openapi-validator\n * @example\n * ```typescript\n * import { getApplication, createOpenApiValidatorOptions } from '@event-driven-io/emmett-expressjs';\n *\n * type AppDeps = {\n * eventStore: EventStore;\n * messageBus: EventsPublisher;\n * };\n *\n * const app = await getApplication({\n * openApiValidator: createOpenApiValidatorOptions<AppDeps>('./openapi.yaml', {\n * validateResponses: true,\n * operationHandlers: './handlers',\n * initializeHandlers: (deps) => {\n * initializeHandlers(deps.eventStore, deps.messageBus);\n * }\n * })\n * });\n * ```\n */\n openApiValidator?: OpenApiValidatorOptions;\n};\n\nexport const getApplication = async (options: ApplicationOptions) => {\n const app: Application = express();\n\n const {\n apis,\n mapError,\n enableDefaultExpressEtag,\n disableJsonMiddleware,\n disableUrlEncodingMiddleware,\n disableProblemDetailsMiddleware,\n pinoHttp,\n openApiValidator,\n } = options;\n\n const router = Router();\n\n // disabling default etag behaviour\n // to use etags in if-match and if-not-match headers\n app.set('etag', enableDefaultExpressEtag ?? false);\n\n // add Pino HTTP logger middleware if configured\n if (pinoHttp !== undefined && pinoHttp !== false) {\n try {\n const require = createRequire(import.meta.url);\n const mod = require('pino-http') as Record<string, unknown>;\n const provider = (mod.default ?? mod) as unknown;\n\n if (typeof provider !== 'function') {\n throw new Error('Invalid pino-http module: missing default export');\n }\n\n const options = pinoHttp === true ? undefined : pinoHttp;\n const middleware = (\n provider as (opts?: PinoHttpOptions) => RequestHandler\n )(options);\n app.use(middleware);\n } catch {\n console.warn(\n 'Pino HTTP configuration provided but pino-http package is not installed. ' +\n 'Install it with: npm install pino-http',\n );\n throw new Error(\n 'pino-http package is required when pinoHttp option is used',\n );\n }\n }\n\n // add json middleware\n if (!disableJsonMiddleware) app.use(express.json());\n\n // enable url encoded urls and bodies\n if (!disableUrlEncodingMiddleware)\n app.use(\n express.urlencoded({\n extended: true,\n }),\n );\n\n // add OpenAPI validator middleware if configured\n if (openApiValidator) {\n // Activate ESM resolver if operationHandlers are configured\n // This ensures handler modules are loaded via ESM import() instead of CJS require(),\n // preventing dual module loading issues when using TypeScript runtimes (tsx, ts-node)\n if (openApiValidator.operationHandlers) {\n const { activateESMResolver } = await import(\n './internal/esm-resolver.js'\n );\n activateESMResolver();\n\n // NEW: Auto-discover and import handler modules from OpenAPI spec\n const handlersBasePath =\n typeof openApiValidator.operationHandlers === 'string'\n ? openApiValidator.operationHandlers\n : openApiValidator.operationHandlers.basePath;\n\n if (handlersBasePath) {\n const { extractHandlerModules } = await import(\n './internal/openapi-parser.js'\n );\n const { importAndRegisterHandlers } = await import(\n './internal/handler-importer.js'\n );\n\n try {\n // Parse OpenAPI spec to find handler modules\n const modules = await extractHandlerModules(\n openApiValidator.apiSpec,\n handlersBasePath,\n );\n\n // Dynamically import and register all handler modules\n const importedHandlers = await importAndRegisterHandlers(modules);\n\n // Call user's initializeHandlers callback with imported modules\n if (openApiValidator.initializeHandlers) {\n await openApiValidator.initializeHandlers(importedHandlers);\n }\n } catch (error) {\n console.error('Failed to auto-import handler modules:', error);\n throw error;\n }\n }\n } else {\n // No operationHandlers, just call initializeHandlers if provided\n if (openApiValidator.initializeHandlers) {\n await openApiValidator.initializeHandlers();\n }\n }\n\n try {\n const require = createRequire(import.meta.url);\n // express-openapi-validator exports a default with .middleware (ESM/CJS compatibility)\n const mod = require('express-openapi-validator') as Record<\n string,\n unknown\n >;\n const provider = (mod.default ?? mod) as Record<string, unknown>;\n\n if (typeof provider.middleware !== 'function') {\n throw new Error(\n 'Invalid express-openapi-validator module: missing middleware export',\n );\n }\n\n // Serve OpenAPI spec if configured\n if (openApiValidator.serveSpec) {\n if (typeof openApiValidator.apiSpec === 'string') {\n // If apiSpec is a file path, serve it as a static file\n app.use(\n openApiValidator.serveSpec,\n express.static(openApiValidator.apiSpec),\n );\n } else {\n // If apiSpec is an object, serve it as JSON\n app.get(openApiValidator.serveSpec, (_req, res) => {\n res.json(openApiValidator.apiSpec);\n });\n }\n }\n\n const factory = provider.middleware as (\n opts: OpenApiValidatorOptions,\n ) => RequestHandler | RequestHandler[];\n const middleware = factory(openApiValidator);\n if (Array.isArray(middleware)) {\n for (const m of middleware) app.use(m);\n } else {\n app.use(middleware);\n }\n } catch {\n console.warn(\n 'OpenAPI validator configuration provided but express-openapi-validator package is not installed. ' +\n 'Install it with: npm install express-openapi-validator',\n );\n throw new Error(\n 'express-openapi-validator package is required when openApiValidator option is used',\n );\n }\n }\n\n // Register API routes if provided\n if (apis) {\n for (const api of apis) {\n api(router);\n }\n app.use(router);\n }\n\n // add problem details middleware\n if (!disableProblemDetailsMiddleware)\n app.use(problemDetailsMiddleware(mapError));\n\n return app;\n};\n\nexport type StartApiOptions = {\n port?: number;\n};\n\nexport const startAPI = (\n app: Application,\n options: StartApiOptions = { port: 3000 },\n) => {\n const { port } = options;\n const server = http.createServer(app);\n\n server.on('listening', () => {\n console.info('server up listening');\n });\n\n return server.listen(port);\n};\n","import type { NextFunction, Request, Response } from 'express';\nimport { ProblemDocument } from 'http-problem-details';\nimport { sendProblem, type ErrorToProblemDetailsMapping } from '..';\n\nexport const problemDetailsMiddleware =\n (mapError?: ErrorToProblemDetailsMapping) =>\n (\n error: Error,\n request: Request,\n response: Response,\n _next: NextFunction,\n ): void => {\n let problemDetails: ProblemDocument | undefined;\n\n if (mapError) problemDetails = mapError(error, request);\n\n problemDetails =\n problemDetails ?? defaultErrorToProblemDetailsMapping(error);\n\n sendProblem(response, problemDetails.status, { problem: problemDetails });\n };\n\nexport const defaultErrorToProblemDetailsMapping = (\n error: Error,\n): ProblemDocument => {\n let statusCode = 500;\n\n // Prefer standard `status` code if present (e.g., express-openapi-validator)\n const errObj = error as unknown as Record<string, unknown>;\n const maybeStatus = errObj['status'];\n if (\n typeof maybeStatus === 'number' &&\n maybeStatus >= 100 &&\n maybeStatus < 600\n ) {\n statusCode = maybeStatus;\n }\n\n const maybeErrorCode = errObj['errorCode'];\n if (\n typeof maybeErrorCode === 'number' &&\n maybeErrorCode >= 100 &&\n maybeErrorCode < 600\n ) {\n statusCode = maybeErrorCode;\n }\n\n return new ProblemDocument({\n detail: error.message,\n status: statusCode,\n });\n};\n","import { type Brand } from '@event-driven-io/emmett';\nimport type { Request, Response } from 'express';\n\n//////////////////////////////////////\n/// ETAG\n//////////////////////////////////////\n\nexport const HeaderNames = {\n IF_MATCH: 'if-match',\n IF_NOT_MATCH: 'if-not-match',\n ETag: 'etag',\n};\n\nexport type WeakETag = Brand<`W/${string}`, 'ETag'>;\nexport type ETag = Brand<string, 'ETag'>;\n\nexport const WeakETagRegex = /W\\/\"(-?\\d+.*)\"/;\n\nexport const enum ETagErrors {\n WRONG_WEAK_ETAG_FORMAT = 'WRONG_WEAK_ETAG_FORMAT',\n MISSING_IF_MATCH_HEADER = 'MISSING_IF_MATCH_HEADER',\n MISSING_IF_NOT_MATCH_HEADER = 'MISSING_IF_NOT_MATCH_HEADER',\n}\n\nexport const isWeakETag = (etag: ETag): etag is WeakETag => {\n return WeakETagRegex.test(etag as string);\n};\n\nexport const getWeakETagValue = (etag: ETag): string => {\n const result = WeakETagRegex.exec(etag as string);\n if (result === null || result.length === 0) {\n throw new Error(ETagErrors.WRONG_WEAK_ETAG_FORMAT);\n }\n return result[1]!;\n};\n\nexport const toWeakETag = (value: number | bigint | string): WeakETag => {\n return `W/\"${value}\"` as WeakETag;\n};\n\nexport const getETagFromIfMatch = (request: Request): ETag => {\n const etag = request.headers[HeaderNames.IF_MATCH];\n\n if (etag === undefined) {\n throw new Error(ETagErrors.MISSING_IF_MATCH_HEADER);\n }\n\n return etag as ETag;\n};\n\nexport const getETagFromIfNotMatch = (request: Request): ETag => {\n const etag = request.headers[HeaderNames.IF_NOT_MATCH];\n\n if (etag === undefined) {\n throw new Error(ETagErrors.MISSING_IF_MATCH_HEADER);\n }\n\n return (Array.isArray(etag) ? etag[0] : etag) as ETag;\n};\n\nexport const setETag = (response: Response, etag: ETag): void => {\n response.setHeader(HeaderNames.ETag, etag as string);\n};\n\nexport const getETagValueFromIfMatch = (request: Request): string => {\n const eTagValue: ETag = getETagFromIfMatch(request);\n\n return isWeakETag(eTagValue)\n ? getWeakETagValue(eTagValue)\n : (eTagValue as string);\n};\n","import { type NextFunction, type Request, type Response } from 'express';\nimport {\n send,\n sendAccepted,\n sendCreated,\n sendProblem,\n type AcceptedHttpResponseOptions,\n type CreatedHttpResponseOptions,\n type HttpProblemResponseOptions,\n type HttpResponseOptions,\n type NoContentHttpResponseOptions,\n} from '.';\n\n// #region httpresponse-on\nexport type HttpResponse = (response: Response) => void;\n\nexport type HttpHandler<RequestType extends Request> = (\n request: RequestType,\n) => Promise<HttpResponse> | HttpResponse;\n\nexport const on =\n <RequestType extends Request>(handle: HttpHandler<RequestType>) =>\n async (\n request: RequestType,\n response: Response,\n _next: NextFunction,\n ): Promise<void> => {\n const setResponse = await Promise.resolve(handle(request));\n\n return setResponse(response);\n };\n// #endregion httpresponse-on\n\nexport const OK =\n (options?: HttpResponseOptions): HttpResponse =>\n (response: Response) => {\n send(response, 200, options);\n };\n\nexport const Created =\n (options: CreatedHttpResponseOptions): HttpResponse =>\n (response: Response) => {\n sendCreated(response, options);\n };\n\nexport const Accepted =\n (options: AcceptedHttpResponseOptions): HttpResponse =>\n (response: Response) => {\n sendAccepted(response, options);\n };\n\nexport const NoContent = (\n options?: NoContentHttpResponseOptions,\n): HttpResponse => HttpResponse(204, options);\n\nexport const HttpResponse =\n (statusCode: number, options?: HttpResponseOptions): HttpResponse =>\n (response: Response) => {\n send(response, statusCode, options);\n };\n\n/////////////////////\n// ERRORS\n/////////////////////\n\nexport const BadRequest = (\n options?: HttpProblemResponseOptions,\n): HttpResponse => HttpProblem(400, options);\n\nexport const Forbidden = (options?: HttpProblemResponseOptions): HttpResponse =>\n HttpProblem(403, options);\n\nexport const NotFound = (options?: HttpProblemResponseOptions): HttpResponse =>\n HttpProblem(404, options);\n\nexport const Conflict = (options?: HttpProblemResponseOptions): HttpResponse =>\n HttpProblem(409, options);\n\nexport const PreconditionFailed = (\n options: HttpProblemResponseOptions,\n): HttpResponse => HttpProblem(412, options);\n\nexport const HttpProblem =\n (statusCode: number, options?: HttpProblemResponseOptions): HttpResponse =>\n (response: Response) => {\n sendProblem(response, statusCode, options);\n };\n","import type { SecurityHandlers } from './index';\n\ntype AuthClient = {\n verifyIdToken: (token: string) => Promise<unknown>;\n};\n\nexport type FirebaseAuthSecurityOptions = {\n /**\n * Name of the OpenAPI security scheme to attach the handler to.\n * Defaults to \"bearerAuth\".\n */\n securitySchemeName?: string;\n /**\n * Custom auth client for tests or alternate Firebase auth instances.\n */\n authClient?: AuthClient;\n /**\n * Token claim used for role-based checks when scopes are defined.\n * Defaults to \"roles\".\n */\n roleClaim?: string;\n};\n\ntype FirebaseAuthModule = {\n firebaseAuthMiddleware: (options?: { authClient?: AuthClient }) => (\n req: unknown,\n res: unknown,\n next: () => void,\n ) => Promise<void> | void;\n};\n\nconst loadFirebaseAuth = async (): Promise<FirebaseAuthModule> => {\n try {\n const mod = await import('@my-f-startup/firebase-auth-express');\n const provider = (mod as unknown as Record<string, unknown>).default ?? mod;\n const firebaseAuthMiddleware =\n (provider as Record<string, unknown>).firebaseAuthMiddleware;\n\n if (typeof firebaseAuthMiddleware !== 'function') {\n throw new Error(\n 'Invalid @my-f-startup/firebase-auth-express module: missing firebaseAuthMiddleware export',\n );\n }\n\n return provider as FirebaseAuthModule;\n } catch (error) {\n const message =\n '@my-f-startup/firebase-auth-express is required for createFirebaseAuthSecurityHandlers. ' +\n 'Install it with: npm install @my-f-startup/firebase-auth-express';\n throw new Error(message, { cause: error as Error });\n }\n};\n\nconst createNullResponse = () => {\n const res: Record<string, unknown> = {};\n res.status = () => res;\n res.json = () => res;\n res.send = () => res;\n res.end = () => res;\n res.set = () => res;\n return res;\n};\n\nconst runMiddleware = async (\n middleware: (req: unknown, res: unknown, next: () => void) => Promise<void> | void,\n req: unknown,\n): Promise<boolean> => {\n return new Promise((resolve) => {\n let nextCalled = false;\n const res = createNullResponse();\n const next = () => {\n nextCalled = true;\n resolve(true);\n };\n\n Promise.resolve(middleware(req, res, next))\n .then(() => {\n if (!nextCalled) resolve(false);\n })\n .catch(() => resolve(false));\n });\n};\n\nexport const createFirebaseAuthSecurityHandlers = (\n options: FirebaseAuthSecurityOptions = {},\n): SecurityHandlers => {\n const securitySchemeName = options.securitySchemeName ?? 'bearerAuth';\n const roleClaim = options.roleClaim ?? 'roles';\n\n return {\n [securitySchemeName]: async (req, scopes, _schema) => {\n const { firebaseAuthMiddleware } = await loadFirebaseAuth();\n const middleware = firebaseAuthMiddleware({\n authClient: options.authClient,\n });\n\n const isAuthenticated = await runMiddleware(middleware, req);\n if (!isAuthenticated) return false;\n\n if (!scopes.length) return true;\n\n const roles = (req as Record<string, any>)?.auth?.token?.[roleClaim];\n if (!Array.isArray(roles)) return false;\n\n return scopes.every((scope: string) => roles.includes(scope));\n },\n };\n};\n","/**\n * OpenAPI v3 Document type (to avoid requiring express-openapi-validator types directly)\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type OpenAPIV3Document = any;\n\n/**\n * Imported handler modules, keyed by module name.\n * Automatically populated by the framework when operationHandlers is configured.\n */\nexport type ImportedHandlerModules = Record<string, any>;\n\n/**\n * Security handlers for custom authentication/authorization logic.\n * Maps security scheme names to handler functions.\n *\n * @see https://cdimascio.github.io/express-openapi-validator-documentation/usage-validate-security/\n */\n\nexport type SecurityHandlers = Record<\n string,\n (req: any, scopes: string[], schema: any) => boolean | Promise<boolean>\n>;\n\nexport * from './firebase-auth';\n\n/**\n * Configuration options for express-openapi-validator middleware.\n * This allows optional validation of API requests and responses against an OpenAPI specification.\n *\n * @see https://cdimascio.github.io/express-openapi-validator-documentation/\n */\nexport type OpenApiValidatorOptions = {\n /**\n * Path to the OpenAPI specification file (JSON or YAML)\n * or an OpenAPI specification object.\n */\n apiSpec: string | OpenAPIV3Document;\n\n /**\n * Determines whether the validator should validate requests.\n * Can be a boolean or an object with detailed request validation options.\n * @default true\n * @see https://cdimascio.github.io/express-openapi-validator-documentation/usage-validate-requests/\n */\n validateRequests?:\n | boolean\n | {\n /**\n * Allow unknown query parameters (not defined in the spec).\n * @default false\n */\n allowUnknownQueryParameters?: boolean;\n /**\n * Coerce types in request parameters.\n * @default true\n */\n coerceTypes?: boolean | 'array';\n /**\n * Remove additional properties not defined in the spec.\n * @default false\n */\n removeAdditional?: boolean | 'all' | 'failing';\n };\n\n /**\n * Determines whether the validator should validate responses.\n * Can be a boolean or an object with detailed response validation options.\n * @default false\n * @see https://cdimascio.github.io/express-openapi-validator-documentation/usage-validate-responses/\n */\n validateResponses?:\n | boolean\n | {\n /**\n * Remove additional properties from responses not defined in the spec.\n * @default false\n */\n removeAdditional?: boolean | 'all' | 'failing';\n /**\n * Coerce types in responses.\n * @default true\n */\n coerceTypes?: boolean;\n /**\n * Callback to handle response validation errors.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n onError?: (error: any, body: any, req: any) => void;\n };\n\n /**\n * Determines whether the validator should validate security.\n * Can be a boolean or an object with security handlers.\n * @default true\n * @see https://cdimascio.github.io/express-openapi-validator-documentation/usage-validate-security/\n */\n validateSecurity?:\n | boolean\n | {\n /**\n * Custom security handlers for authentication/authorization.\n */\n handlers?: SecurityHandlers;\n };\n\n /**\n * Defines how the validator should validate formats.\n * When true, uses ajv-formats for format validation.\n * When false, format validation is disabled.\n * Can also be 'fast' or 'full' for different validation modes.\n * @default true\n */\n validateFormats?: boolean | 'fast' | 'full';\n\n /**\n * The base path to the operation handlers directory.\n * When set to a path, automatically wires OpenAPI operations to handler functions\n * based on operationId or x-eov-operation-id.\n * When false, operation handlers are disabled (manual routing required).\n * @default false\n * @see https://cdimascio.github.io/express-openapi-validator-documentation/guide-operation-handlers/\n */\n operationHandlers?:\n | string\n | false\n | {\n /**\n * Base path to operation handlers directory.\n */\n basePath?: string;\n /**\n * Resolver function to map operationId to handler module path.\n */\n resolver?: (\n handlersPath: string,\n route: string,\n apiDoc: OpenAPIV3Document,\n ) => string;\n };\n\n /**\n * Paths or pattern to ignore during validation.\n * @default undefined\n */\n ignorePaths?: RegExp | ((path: string) => boolean);\n\n /**\n * Validate the OpenAPI specification itself.\n * @default true\n */\n validateApiSpec?: boolean;\n\n /**\n * $ref parser configuration for handling OpenAPI references.\n * @default undefined\n */\n $refParser?: {\n mode: 'bundle' | 'dereference';\n };\n\n /**\n * Serve the OpenAPI specification at a specific path.\n * When set to a string, the spec will be served at that path.\n * When false, the spec will not be served.\n * @default false\n * @example '/api-docs/openapi.json'\n */\n serveSpec?: string | false;\n\n /**\n * File upload configuration options.\n * @see https://cdimascio.github.io/express-openapi-validator-documentation/usage-file-uploads/\n */\n fileUploader?:\n | boolean\n | {\n /**\n * Destination directory for uploaded files.\n */\n dest?: string;\n /**\n * File size limit in bytes.\n */\n limits?: {\n fileSize?: number;\n files?: number;\n };\n };\n\n /**\n * Optional callback to initialize operation handlers with dependencies.\n * Called before the OpenAPI validator middleware is configured.\n *\n * The framework automatically imports handler modules referenced in your\n * OpenAPI spec (via x-eov-operation-handler) and passes them as the first parameter.\n *\n * @param handlers - Auto-imported handler modules, keyed by module name\n * @returns void or a Promise that resolves when initialization is complete\n *\n * @example\n * ```typescript\n * // With automatic import (recommended)\n * initializeHandlers: async (handlers) => {\n * handlers.shoppingCarts.initializeHandlers(eventStore, messageBus, getUnitPrice, getCurrentTime);\n * }\n *\n * // Manual import (still supported for backward compatibility)\n * import * as handlersModule from './handlers/shoppingCarts';\n * import { registerHandlerModule } from '@emmett-community/emmett-expressjs-with-openapi';\n * initializeHandlers: () => {\n * const handlersPath = path.join(__dirname, './handlers/shoppingCarts');\n * registerHandlerModule(handlersPath, handlersModule);\n * handlersModule.initializeHandlers(eventStore, messageBus, getUnitPrice, getCurrentTime);\n * }\n * ```\n */\n initializeHandlers?: (\n handlers?: ImportedHandlerModules,\n ) => void | Promise<void>;\n};\n\n/**\n * Helper function to create OpenAPI validator configuration with sensible defaults.\n *\n * @param apiSpec - Path to OpenAPI spec file or OpenAPI document object\n * @param options - Additional validator options\n * @returns Complete OpenApiValidatorOptions configuration\n *\n * @example\n * ```typescript\n * // Basic usage with default options\n * const validatorOptions = createOpenApiValidatorOptions('./openapi.yaml');\n *\n * // With response validation enabled\n * const validatorOptions = createOpenApiValidatorOptions('./openapi.yaml', {\n * validateResponses: true\n * });\n *\n * // With custom security handlers\n * const validatorOptions = createOpenApiValidatorOptions('./openapi.yaml', {\n * validateSecurity: {\n * handlers: {\n * bearerAuth: async (req, scopes) => {\n * // Custom authentication logic\n * return true;\n * }\n * }\n * }\n * });\n *\n * // Serving the spec at /api-docs\n * const validatorOptions = createOpenApiValidatorOptions('./openapi.yaml', {\n * serveSpec: '/api-docs/openapi.json'\n * });\n *\n * // With dependency injection for operation handlers\n * type ShoppingCartDeps = {\n * eventStore: EventStore;\n * messageBus: EventsPublisher;\n * getUnitPrice: (productId: string) => Promise<number>;\n * getCurrentTime: () => Date;\n * };\n *\n * const validatorOptions = createOpenApiValidatorOptions<ShoppingCartDeps>(\n * './openapi.yaml',\n * {\n * operationHandlers: './handlers',\n * initializeHandlers: (deps) => {\n * initializeHandlers(\n * deps.eventStore,\n * deps.messageBus,\n * deps.getUnitPrice,\n * deps.getCurrentTime\n * );\n * }\n * }\n * );\n *\n * const app = getApplication({\n * apis: [myApi],\n * openApiValidator: validatorOptions\n * });\n * ```\n */\nexport const createOpenApiValidatorOptions = (\n apiSpec: string | OpenAPIV3Document,\n options?: Partial<Omit<OpenApiValidatorOptions, 'apiSpec'>>,\n): OpenApiValidatorOptions => {\n return {\n apiSpec,\n validateRequests: options?.validateRequests ?? true,\n validateResponses: options?.validateResponses ?? false,\n validateSecurity: options?.validateSecurity ?? true,\n validateFormats: options?.validateFormats ?? true,\n operationHandlers: options?.operationHandlers,\n ignorePaths: options?.ignorePaths,\n validateApiSpec: options?.validateApiSpec ?? true,\n $refParser: options?.$refParser,\n serveSpec: options?.serveSpec ?? false,\n fileUploader: options?.fileUploader,\n initializeHandlers: options?.initializeHandlers,\n };\n};\n\n/**\n * Type guard to check if express-openapi-validator is available\n */\nexport const isOpenApiValidatorAvailable = async (): Promise<boolean> => {\n try {\n await import('express-openapi-validator');\n return true;\n } catch {\n return false;\n }\n};\n","import { type Request, type Response } from 'express';\nimport { ProblemDocument } from 'http-problem-details';\nimport { setETag, type ETag } from './etag';\n\nexport type ErrorToProblemDetailsMapping = (\n error: Error,\n request: Request,\n) => ProblemDocument | undefined;\n\nexport type HttpResponseOptions = {\n body?: unknown;\n location?: string;\n eTag?: ETag;\n};\nexport const DefaultHttpResponseOptions: HttpResponseOptions = {};\n\nexport type HttpProblemResponseOptions = {\n location?: string;\n eTag?: ETag;\n} & Omit<HttpResponseOptions, 'body'> &\n (\n | {\n problem: ProblemDocument;\n }\n | { problemDetails: string }\n );\nexport const DefaultHttpProblemResponseOptions: HttpProblemResponseOptions = {\n problemDetails: 'Error occured!',\n};\n\nexport type CreatedHttpResponseOptions = (\n | {\n createdId: string;\n }\n | {\n createdId?: string;\n url: string;\n }\n) &\n HttpResponseOptions;\n\nexport const sendCreated = (\n response: Response,\n { eTag, ...options }: CreatedHttpResponseOptions,\n): void =>\n send(response, 201, {\n location:\n 'url' in options\n ? options.url\n : `${response.req.url}/${options.createdId}`,\n body: 'createdId' in options ? { id: options.createdId } : undefined,\n eTag,\n });\n\nexport type AcceptedHttpResponseOptions = {\n location: string;\n} & HttpResponseOptions;\n\nexport const sendAccepted = (\n response: Response,\n options: AcceptedHttpResponseOptions,\n): void => send(response, 202, options);\n\nexport type NoContentHttpResponseOptions = Omit<HttpResponseOptions, 'body'>;\n\nexport const send = (\n response: Response,\n statusCode: number,\n options?: HttpResponseOptions,\n): void => {\n const { location, body, eTag } = options ?? DefaultHttpResponseOptions;\n // HEADERS\n if (eTag) setETag(response, eTag);\n if (location) response.setHeader('Location', location);\n\n if (body) {\n response.statusCode = statusCode;\n response.send(body);\n } else {\n response.sendStatus(statusCode);\n }\n};\n\nexport const sendProblem = (\n response: Response,\n statusCode: number,\n options?: HttpProblemResponseOptions,\n): void => {\n options = options ?? DefaultHttpProblemResponseOptions;\n\n const { location, eTag } = options;\n\n const problemDetails =\n 'problem' in options\n ? options.problem\n : new ProblemDocument({\n detail: options.problemDetails,\n status: statusCode,\n });\n\n // HEADERS\n if (eTag) setETag(response, eTag);\n if (location) response.setHeader('Location', location);\n\n response.setHeader('Content-Type', 'application/problem+json');\n\n response.statusCode = statusCode;\n response.json(problemDetails);\n};\n","import supertest, { type Response } from 'supertest';\n\nimport type { EventStore } from '@event-driven-io/emmett';\nimport assert from 'assert';\nimport type { Application } from 'express';\nimport type { TestRequest } from './apiSpecification';\n\nexport type E2EResponseAssert = (response: Response) => boolean | void;\n\nexport type ApiE2ESpecificationAssert = [E2EResponseAssert];\n\nexport type ApiE2ESpecification = (...givenRequests: TestRequest[]) => {\n when: (setupRequest: TestRequest) => {\n then: (verify: ApiE2ESpecificationAssert) => Promise<void>;\n };\n};\n\nexport const ApiE2ESpecification = {\n for: <Store extends EventStore = EventStore>(\n getEventStore: () => Store,\n getApplication: (eventStore: Store) => Application | Promise<Application>,\n ): ApiE2ESpecification => {\n {\n return (...givenRequests: TestRequest[]) => {\n const eventStore = getEventStore();\n\n return {\n when: (setupRequest: TestRequest) => {\n const handle = async () => {\n const application = await Promise.resolve(getApplication(eventStore));\n\n for (const requestFn of givenRequests) {\n await requestFn(supertest(application));\n }\n\n return setupRequest(supertest(application));\n };\n\n return {\n then: async (\n verify: ApiE2ESpecificationAssert,\n ): Promise<void> => {\n const response = await handle();\n\n verify.forEach((assertion) => {\n const succeeded = assertion(response);\n\n if (succeeded === false) assert.fail();\n });\n },\n };\n },\n };\n };\n }\n },\n};\n","import {\n WrapEventStore,\n assertEqual,\n assertFails,\n assertMatches,\n type Event,\n type EventStore,\n type TestEventStream,\n} from '@event-driven-io/emmett';\nimport { type Application } from 'express';\nimport type { ProblemDocument } from 'http-problem-details';\nimport type { Response, Test } from 'supertest';\nimport supertest from 'supertest';\nimport type TestAgent from 'supertest/lib/agent';\n\n////////////////////////////////\n/////////// Setup\n////////////////////////////////\n\nexport type TestRequest = (request: TestAgent<supertest.Test>) => Test;\n\nexport const existingStream = <EventType extends Event = Event>(\n streamId: string,\n events: EventType[],\n): TestEventStream<EventType> => {\n return [streamId, events];\n};\n\n////////////////////////////////\n/////////// Asserts\n////////////////////////////////\n\nexport type ResponseAssert = (response: Response) => boolean | void;\n\nexport type ApiSpecificationAssert<EventType extends Event = Event> =\n | TestEventStream<EventType>[]\n | ResponseAssert\n | [ResponseAssert, ...TestEventStream<EventType>[]];\n\nexport const expect = <EventType extends Event = Event>(\n streamId: string,\n events: EventType[],\n): TestEventStream<EventType> => {\n return [streamId, events];\n};\n\nexport const expectNewEvents = <EventType extends Event = Event>(\n streamId: string,\n events: EventType[],\n): TestEventStream<EventType> => {\n return [streamId, events];\n};\n\nexport const expectResponse =\n <Body = unknown>(\n statusCode: number,\n options?: { body?: Body; headers?: { [index: string]: string } },\n ) =>\n (response: Response): void => {\n const { body, headers } = options ?? {};\n assertEqual(statusCode, response.statusCode, \"Response code doesn't match\");\n if (body) assertMatches(response.body, body);\n if (headers) assertMatches(response.headers, headers);\n };\n\nexport const expectError = (\n errorCode: number,\n problemDetails?: Partial<ProblemDocument>,\n) =>\n expectResponse(\n errorCode,\n problemDetails ? { body: problemDetails } : undefined,\n );\n\n////////////////////////////////\n/////////// Api Specification\n////////////////////////////////\n\nexport type ApiSpecification<EventType extends Event = Event> = (\n ...givenStreams: TestEventStream<EventType>[]\n) => {\n when: (setupRequest: TestRequest) => {\n then: (verify: ApiSpecificationAssert<EventType>) => Promise<void>;\n };\n};\n\nexport const ApiSpecification = {\n for: <\n EventType extends Event = Event,\n Store extends EventStore<import('@event-driven-io/emmett').ReadEventMetadataWithGlobalPosition> = EventStore<import('@event-driven-io/emmett').ReadEventMetadataWithGlobalPosition>\n >(\n getEventStore: () => Store,\n getApplication: (eventStore: Store) => Application | Promise<Application>,\n ): ApiSpecification<EventType> => {\n {\n return (...givenStreams: TestEventStream<EventType>[]) => {\n const eventStore = WrapEventStore(getEventStore());\n\n return {\n when: (setupRequest: TestRequest) => {\n const handle = async () => {\n const application = await Promise.resolve(getApplication(eventStore));\n\n for (const [streamName, events] of givenStreams) {\n await eventStore.setup(streamName, events);\n }\n\n return setupRequest(supertest(application));\n };\n\n return {\n then: async (\n verify: ApiSpecificationAssert<EventType>,\n ): Promise<void> => {\n const response = await handle();\n\n if (typeof verify === 'function') {\n const succeeded = verify(response);\n\n if (succeeded === false) assertFails();\n } else if (Array.isArray(verify)) {\n const [first, ...rest] = verify;\n\n if (typeof first === 'function') {\n const succeeded = first(response);\n\n if (succeeded === false) assertFails();\n }\n\n const events = typeof first === 'function' ? rest : verify;\n\n assertMatches(\n Array.from(eventStore.appendedEvents.values()),\n events,\n );\n }\n },\n };\n },\n };\n };\n }\n },\n};\n"]}
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/emmett-expressjs-with-openapi/emmett-expressjs-with-openapi/dist/index.cjs","../src/index.ts","../src/application.ts","../src/middlewares/problemDetailsMiddleware.ts","../src/etag.ts","../src/handler.ts","../src/openapi/firebase-auth.ts","../src/openapi/index.ts","../src/responses.ts","../src/testing/apiE2ESpecification.ts","../src/testing/apiSpecification.ts"],"names":["require","options","ETagErrors","tracer","trace","SpanStatusCode"],"mappings":"AAAA;AACE;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACA;ACVA,gCAAO;ADYP;AACA;AEbA,yCAAsC;AACtC;AACE;AAAA,oFAGK;AACP;AACA,wEAAiB;AACjB,gCAA8B;AFa9B;AACA;AGrBA,0DAAgC;AAIzB,IAAM,yBAAA,EACX,CAAC,QAAA,EAAyC,MAAA,EAAA,GAC1C,CACE,KAAA,EACA,OAAA,EACA,QAAA,EACA,KAAA,EAAA,GACS;AACT,EAAA,yBAAA,CAAQ,KAAA,CAAM,MAAA,EAAQ,eAAA,EAAiB,KAAK,CAAA;AAE5C,EAAA,IAAI,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AAChC,YAAA;AAEO,YAAA;AAGe,cAAA;AACY,gBAAA;AAER,gBAAA;AACK,kBAAA;AAEA,kBAAA;AACF,gBAAA;AACE,kBAAA;AAEJ,kBAAA;AACK,oBAAA;AAEC,oBAAA;AAC3B,kBAAA;AAEsB,kBAAA;AAEtB,kBAAA;AACwB,oBAAA;AACtB,oBAAA;AACF,kBAAA;AACF,gBAAA;AACF,cAAA;AACF,YAAA;AACF,UAAA;AACF,QAAA;AACF,MAAA;AACF,IAAA;AACF,EAAA;AACF;AVyY8C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/emmett-expressjs-with-openapi/emmett-expressjs-with-openapi/dist/index.cjs","sourcesContent":[null,"import 'express-async-errors';\n\nexport * from './application';\nexport * from './etag';\nexport * from './handler';\nexport * from './observability';\nexport * from './openapi';\nexport * from './responses';\nexport * from './testing';\nexport { registerHandlerModule } from './internal/esm-resolver';\n","import { trace, SpanStatusCode } from '@opentelemetry/api';\nimport express, {\n Router,\n type Application,\n type RequestHandler,\n} from 'express';\nimport 'express-async-errors';\nimport http from 'http';\nimport { createRequire } from 'node:module';\nimport { problemDetailsMiddleware } from './middlewares/problemDetailsMiddleware';\nimport { type Logger, type ObservabilityOptions, safeLog } from './observability';\nimport type { OpenApiValidatorOptions } from './openapi';\nimport type { ErrorToProblemDetailsMapping } from './responses';\n\nconst tracer = trace.getTracer('@emmett-community/emmett-expressjs-with-openapi');\n\n// #region web-api-setup\nexport type WebApiSetup = (router: Router) => void;\n// #endregion web-api-setup\n\n/**\n * Options forwarded to pino-http. Typed loosely to avoid hard dependency.\n *\n * @see https://github.com/pinojs/pino-http\n */\nexport type PinoHttpOptions = Record<string, unknown>;\n\nexport type ApplicationOptions = {\n apis?: WebApiSetup[];\n mapError?: ErrorToProblemDetailsMapping;\n enableDefaultExpressEtag?: boolean;\n disableJsonMiddleware?: boolean;\n disableUrlEncodingMiddleware?: boolean;\n disableProblemDetailsMiddleware?: boolean;\n /**\n * Optional Pino HTTP logger configuration.\n * When true, enables pino-http with defaults.\n * When an object, forwards the options to pino-http.\n * Requires the 'pino-http' package to be installed.\n *\n * @see https://github.com/pinojs/pino-http\n * @example\n * ```typescript\n * const app = await getApplication({\n * pinoHttp: true,\n * });\n *\n * const app = await getApplication({\n * pinoHttp: { autoLogging: false },\n * });\n * ```\n */\n pinoHttp?: boolean | PinoHttpOptions;\n /**\n * Optional OpenAPI validator configuration.\n * When provided, enables request/response validation against an OpenAPI specification.\n * Requires the 'express-openapi-validator' package to be installed.\n *\n * @see https://github.com/cdimascio/express-openapi-validator\n * @example\n * ```typescript\n * import { getApplication, createOpenApiValidatorOptions } from '@event-driven-io/emmett-expressjs';\n *\n * type AppDeps = {\n * eventStore: EventStore;\n * messageBus: EventsPublisher;\n * };\n *\n * const app = await getApplication({\n * openApiValidator: createOpenApiValidatorOptions<AppDeps>('./openapi.yaml', {\n * validateResponses: true,\n * operationHandlers: './handlers',\n * initializeHandlers: (deps) => {\n * initializeHandlers(deps.eventStore, deps.messageBus);\n * }\n * })\n * });\n * ```\n */\n openApiValidator?: OpenApiValidatorOptions;\n /**\n * Optional observability configuration for logging.\n * When not provided, the library operates silently (no logs).\n *\n * @example\n * ```typescript\n * import pino from 'pino';\n *\n * const logger = pino();\n *\n * const app = await getApplication({\n * observability: { logger },\n * });\n * ```\n */\n observability?: ObservabilityOptions;\n};\n\nexport const getApplication = async (options: ApplicationOptions) => {\n const app: Application = express();\n\n const {\n apis,\n mapError,\n enableDefaultExpressEtag,\n disableJsonMiddleware,\n disableUrlEncodingMiddleware,\n disableProblemDetailsMiddleware,\n pinoHttp,\n openApiValidator,\n observability,\n } = options;\n\n const logger = observability?.logger;\n\n safeLog.debug(logger, 'Initializing Express application', {\n hasApis: !!apis?.length,\n hasOpenApiValidator: !!openApiValidator,\n hasPinoHttp: !!pinoHttp,\n });\n\n const router = Router();\n\n // disabling default etag behaviour\n // to use etags in if-match and if-not-match headers\n app.set('etag', enableDefaultExpressEtag ?? false);\n\n // add Pino HTTP logger middleware if configured\n if (pinoHttp !== undefined && pinoHttp !== false) {\n try {\n const require = createRequire(import.meta.url);\n const mod = require('pino-http') as Record<string, unknown>;\n const provider = (mod.default ?? mod) as unknown;\n\n if (typeof provider !== 'function') {\n throw new Error('Invalid pino-http module: missing default export');\n }\n\n const options = pinoHttp === true ? undefined : pinoHttp;\n const middleware = (\n provider as (opts?: PinoHttpOptions) => RequestHandler\n )(options);\n app.use(middleware);\n } catch (error) {\n safeLog.warn(\n logger,\n 'Pino HTTP configuration provided but pino-http package is not installed. Install it with: npm install pino-http',\n );\n throw new Error(\n 'pino-http package is required when pinoHttp option is used',\n );\n }\n }\n\n // add json middleware\n if (!disableJsonMiddleware) app.use(express.json());\n\n // enable url encoded urls and bodies\n if (!disableUrlEncodingMiddleware)\n app.use(\n express.urlencoded({\n extended: true,\n }),\n );\n\n // add OpenAPI validator middleware if configured\n if (openApiValidator) {\n // Activate ESM resolver if operationHandlers are configured\n // This ensures handler modules are loaded via ESM import() instead of CJS require(),\n // preventing dual module loading issues when using TypeScript runtimes (tsx, ts-node)\n if (openApiValidator.operationHandlers) {\n const { activateESMResolver } = await import(\n './internal/esm-resolver.js'\n );\n activateESMResolver();\n\n // NEW: Auto-discover and import handler modules from OpenAPI spec\n const handlersBasePath =\n typeof openApiValidator.operationHandlers === 'string'\n ? openApiValidator.operationHandlers\n : openApiValidator.operationHandlers.basePath;\n\n if (handlersBasePath) {\n const { extractHandlerModules } = await import(\n './internal/openapi-parser.js'\n );\n const { importAndRegisterHandlers } = await import(\n './internal/handler-importer.js'\n );\n\n // Parse OpenAPI spec to find handler modules\n const modules = await tracer.startActiveSpan(\n 'emmett.openapi.parse_spec',\n async (span) => {\n try {\n const result = await extractHandlerModules(\n openApiValidator.apiSpec,\n handlersBasePath,\n logger,\n );\n span.setAttribute('emmett.handlers.count', result.length);\n span.setStatus({ code: SpanStatusCode.OK });\n return result;\n } catch (error) {\n span.recordException(error as Error);\n span.setStatus({ code: SpanStatusCode.ERROR });\n throw error;\n } finally {\n span.end();\n }\n },\n );\n\n // Dynamically import and register all handler modules\n const importedHandlers = await tracer.startActiveSpan(\n 'emmett.http.import_handlers',\n async (span) => {\n try {\n const result = await importAndRegisterHandlers(modules, logger);\n span.setAttribute(\n 'emmett.handlers.count',\n Object.keys(result).length,\n );\n span.setStatus({ code: SpanStatusCode.OK });\n return result;\n } catch (error) {\n safeLog.error(logger, 'Failed to auto-import handler modules', error);\n span.recordException(error as Error);\n span.setStatus({ code: SpanStatusCode.ERROR });\n throw error;\n } finally {\n span.end();\n }\n },\n );\n\n // Call user's initializeHandlers callback with imported modules\n if (openApiValidator.initializeHandlers) {\n await openApiValidator.initializeHandlers(importedHandlers);\n }\n }\n } else {\n // No operationHandlers, just call initializeHandlers if provided\n if (openApiValidator.initializeHandlers) {\n await openApiValidator.initializeHandlers();\n }\n }\n\n try {\n const require = createRequire(import.meta.url);\n // express-openapi-validator exports a default with .middleware (ESM/CJS compatibility)\n const mod = require('express-openapi-validator') as Record<\n string,\n unknown\n >;\n const provider = (mod.default ?? mod) as Record<string, unknown>;\n\n if (typeof provider.middleware !== 'function') {\n throw new Error(\n 'Invalid express-openapi-validator module: missing middleware export',\n );\n }\n\n // Serve OpenAPI spec if configured\n if (openApiValidator.serveSpec) {\n if (typeof openApiValidator.apiSpec === 'string') {\n // If apiSpec is a file path, serve it as a static file\n app.use(\n openApiValidator.serveSpec,\n express.static(openApiValidator.apiSpec),\n );\n } else {\n // If apiSpec is an object, serve it as JSON\n app.get(openApiValidator.serveSpec, (_req, res) => {\n res.json(openApiValidator.apiSpec);\n });\n }\n }\n\n const factory = provider.middleware as (\n opts: OpenApiValidatorOptions,\n ) => RequestHandler | RequestHandler[];\n const middleware = factory(openApiValidator);\n if (Array.isArray(middleware)) {\n for (const m of middleware) app.use(m);\n } else {\n app.use(middleware);\n }\n } catch (error) {\n safeLog.warn(\n logger,\n 'OpenAPI validator configuration provided but express-openapi-validator package is not installed. Install it with: npm install express-openapi-validator',\n );\n throw new Error(\n 'express-openapi-validator package is required when openApiValidator option is used',\n );\n }\n }\n\n // Register API routes if provided\n if (apis) {\n for (const api of apis) {\n api(router);\n }\n app.use(router);\n }\n\n // add problem details middleware\n if (!disableProblemDetailsMiddleware)\n app.use(problemDetailsMiddleware(mapError, logger));\n\n safeLog.info(logger, 'Express application initialized');\n\n return app;\n};\n\nexport type StartApiOptions = {\n port?: number;\n /**\n * Optional logger for lifecycle events.\n */\n logger?: Logger;\n};\n\nexport const startAPI = (\n app: Application,\n options: StartApiOptions = { port: 3000 },\n) => {\n const { port, logger } = options;\n const server = http.createServer(app);\n\n server.on('listening', () => {\n safeLog.info(logger, 'Server up listening', { port });\n });\n\n return server.listen(port);\n};\n","import type { NextFunction, Request, Response } from 'express';\nimport { ProblemDocument } from 'http-problem-details';\nimport { sendProblem, type ErrorToProblemDetailsMapping } from '..';\nimport { type Logger, safeLog } from '../observability';\n\nexport const problemDetailsMiddleware =\n (mapError?: ErrorToProblemDetailsMapping, logger?: Logger) =>\n (\n error: Error,\n request: Request,\n response: Response,\n _next: NextFunction,\n ): void => {\n safeLog.error(logger, 'Request error', error);\n\n let problemDetails: ProblemDocument | undefined;\n\n if (mapError) problemDetails = mapError(error, request);\n\n problemDetails =\n problemDetails ?? defaultErrorToProblemDetailsMapping(error);\n\n sendProblem(response, problemDetails.status, { problem: problemDetails });\n };\n\nexport const defaultErrorToProblemDetailsMapping = (\n error: Error,\n): ProblemDocument => {\n let statusCode = 500;\n\n // Prefer standard `status` code if present (e.g., express-openapi-validator)\n const errObj = error as unknown as Record<string, unknown>;\n const maybeStatus = errObj['status'];\n if (\n typeof maybeStatus === 'number' &&\n maybeStatus >= 100 &&\n maybeStatus < 600\n ) {\n statusCode = maybeStatus;\n }\n\n const maybeErrorCode = errObj['errorCode'];\n if (\n typeof maybeErrorCode === 'number' &&\n maybeErrorCode >= 100 &&\n maybeErrorCode < 600\n ) {\n statusCode = maybeErrorCode;\n }\n\n return new ProblemDocument({\n detail: error.message,\n status: statusCode,\n });\n};\n","import { type Brand } from '@event-driven-io/emmett';\nimport type { Request, Response } from 'express';\n\n//////////////////////////////////////\n/// ETAG\n//////////////////////////////////////\n\nexport const HeaderNames = {\n IF_MATCH: 'if-match',\n IF_NOT_MATCH: 'if-not-match',\n ETag: 'etag',\n};\n\nexport type WeakETag = Brand<`W/${string}`, 'ETag'>;\nexport type ETag = Brand<string, 'ETag'>;\n\nexport const WeakETagRegex = /W\\/\"(-?\\d+.*)\"/;\n\nexport const enum ETagErrors {\n WRONG_WEAK_ETAG_FORMAT = 'WRONG_WEAK_ETAG_FORMAT',\n MISSING_IF_MATCH_HEADER = 'MISSING_IF_MATCH_HEADER',\n MISSING_IF_NOT_MATCH_HEADER = 'MISSING_IF_NOT_MATCH_HEADER',\n}\n\nexport const isWeakETag = (etag: ETag): etag is WeakETag => {\n return WeakETagRegex.test(etag as string);\n};\n\nexport const getWeakETagValue = (etag: ETag): string => {\n const result = WeakETagRegex.exec(etag as string);\n if (result === null || result.length === 0) {\n throw new Error(ETagErrors.WRONG_WEAK_ETAG_FORMAT);\n }\n return result[1]!;\n};\n\nexport const toWeakETag = (value: number | bigint | string): WeakETag => {\n return `W/\"${value}\"` as WeakETag;\n};\n\nexport const getETagFromIfMatch = (request: Request): ETag => {\n const etag = request.headers[HeaderNames.IF_MATCH];\n\n if (etag === undefined) {\n throw new Error(ETagErrors.MISSING_IF_MATCH_HEADER);\n }\n\n return etag as ETag;\n};\n\nexport const getETagFromIfNotMatch = (request: Request): ETag => {\n const etag = request.headers[HeaderNames.IF_NOT_MATCH];\n\n if (etag === undefined) {\n throw new Error(ETagErrors.MISSING_IF_MATCH_HEADER);\n }\n\n return (Array.isArray(etag) ? etag[0] : etag) as ETag;\n};\n\nexport const setETag = (response: Response, etag: ETag): void => {\n response.setHeader(HeaderNames.ETag, etag as string);\n};\n\nexport const getETagValueFromIfMatch = (request: Request): string => {\n const eTagValue: ETag = getETagFromIfMatch(request);\n\n return isWeakETag(eTagValue)\n ? getWeakETagValue(eTagValue)\n : (eTagValue as string);\n};\n","import { trace, SpanStatusCode } from '@opentelemetry/api';\nimport { type NextFunction, type Request, type Response } from 'express';\nimport {\n send,\n sendAccepted,\n sendCreated,\n sendProblem,\n type AcceptedHttpResponseOptions,\n type CreatedHttpResponseOptions,\n type HttpProblemResponseOptions,\n type HttpResponseOptions,\n type NoContentHttpResponseOptions,\n} from '.';\n\nconst tracer = trace.getTracer('@emmett-community/emmett-expressjs-with-openapi');\n\n// #region httpresponse-on\nexport type HttpResponse = (response: Response) => void;\n\nexport type HttpHandler<RequestType extends Request> = (\n request: RequestType,\n) => Promise<HttpResponse> | HttpResponse;\n\nexport const on =\n <RequestType extends Request>(handle: HttpHandler<RequestType>) =>\n async (\n request: RequestType,\n response: Response,\n _next: NextFunction,\n ): Promise<void> => {\n const setResponse = await Promise.resolve(handle(request));\n\n return setResponse(response);\n };\n// #endregion httpresponse-on\n\n/**\n * Options for the traced handler wrapper.\n */\nexport type TracedHandlerOptions = {\n /**\n * Custom span name. Defaults to 'emmett.http.handle_request'.\n */\n spanName?: string;\n};\n\n/**\n * Wraps an HTTP handler with OpenTelemetry tracing.\n * Creates a span that captures request method, route, and response status.\n *\n * If OpenTelemetry is not initialized by the application, spans are no-ops\n * with zero overhead.\n *\n * @example\n * ```typescript\n * router.post('/carts', tracedOn(async (req) => {\n * // Your handler logic\n * return Created({ createdId: cartId });\n * }));\n * ```\n */\nexport const tracedOn =\n <RequestType extends Request>(\n handle: HttpHandler<RequestType>,\n options?: TracedHandlerOptions,\n ) =>\n async (\n request: RequestType,\n response: Response,\n _next: NextFunction,\n ): Promise<void> => {\n const spanName = options?.spanName ?? 'emmett.http.handle_request';\n\n return tracer.startActiveSpan(spanName, async (span) => {\n try {\n span.setAttribute('http.method', request.method);\n\n const route =\n (request.baseUrl ?? '') +\n ((request.route as { path?: string })?.path ?? request.path);\n span.setAttribute('http.route', route);\n\n const setResponse = await Promise.resolve(handle(request));\n setResponse(response);\n\n span.setAttribute('http.status_code', response.statusCode);\n span.setStatus({\n code:\n response.statusCode >= 400 ? SpanStatusCode.ERROR : SpanStatusCode.OK,\n });\n } catch (error) {\n span.recordException(error as Error);\n span.setStatus({ code: SpanStatusCode.ERROR });\n throw error;\n } finally {\n span.end();\n }\n });\n };\n\nexport const OK =\n (options?: HttpResponseOptions): HttpResponse =>\n (response: Response) => {\n send(response, 200, options);\n };\n\nexport const Created =\n (options: CreatedHttpResponseOptions): HttpResponse =>\n (response: Response) => {\n sendCreated(response, options);\n };\n\nexport const Accepted =\n (options: AcceptedHttpResponseOptions): HttpResponse =>\n (response: Response) => {\n sendAccepted(response, options);\n };\n\nexport const NoContent = (\n options?: NoContentHttpResponseOptions,\n): HttpResponse => HttpResponse(204, options);\n\nexport const HttpResponse =\n (statusCode: number, options?: HttpResponseOptions): HttpResponse =>\n (response: Response) => {\n send(response, statusCode, options);\n };\n\n/////////////////////\n// ERRORS\n/////////////////////\n\nexport const BadRequest = (\n options?: HttpProblemResponseOptions,\n): HttpResponse => HttpProblem(400, options);\n\nexport const Forbidden = (options?: HttpProblemResponseOptions): HttpResponse =>\n HttpProblem(403, options);\n\nexport const NotFound = (options?: HttpProblemResponseOptions): HttpResponse =>\n HttpProblem(404, options);\n\nexport const Conflict = (options?: HttpProblemResponseOptions): HttpResponse =>\n HttpProblem(409, options);\n\nexport const PreconditionFailed = (\n options: HttpProblemResponseOptions,\n): HttpResponse => HttpProblem(412, options);\n\nexport const HttpProblem =\n (statusCode: number, options?: HttpProblemResponseOptions): HttpResponse =>\n (response: Response) => {\n sendProblem(response, statusCode, options);\n };\n","import type { SecurityHandlers } from './index';\n\ntype AuthClient = {\n verifyIdToken: (token: string) => Promise<unknown>;\n};\n\nexport type FirebaseAuthSecurityOptions = {\n /**\n * Name of the OpenAPI security scheme to attach the handler to.\n * Defaults to \"bearerAuth\".\n */\n securitySchemeName?: string;\n /**\n * Custom auth client for tests or alternate Firebase auth instances.\n */\n authClient?: AuthClient;\n /**\n * Token claim used for role-based checks when scopes are defined.\n * Defaults to \"roles\".\n */\n roleClaim?: string;\n};\n\ntype FirebaseAuthModule = {\n firebaseAuthMiddleware: (options?: { authClient?: AuthClient }) => (\n req: unknown,\n res: unknown,\n next: () => void,\n ) => Promise<void> | void;\n};\n\nconst loadFirebaseAuth = async (): Promise<FirebaseAuthModule> => {\n try {\n const mod = await import('@my-f-startup/firebase-auth-express');\n const provider = (mod as unknown as Record<string, unknown>).default ?? mod;\n const firebaseAuthMiddleware =\n (provider as Record<string, unknown>).firebaseAuthMiddleware;\n\n if (typeof firebaseAuthMiddleware !== 'function') {\n throw new Error(\n 'Invalid @my-f-startup/firebase-auth-express module: missing firebaseAuthMiddleware export',\n );\n }\n\n return provider as FirebaseAuthModule;\n } catch (error) {\n const message =\n '@my-f-startup/firebase-auth-express is required for createFirebaseAuthSecurityHandlers. ' +\n 'Install it with: npm install @my-f-startup/firebase-auth-express';\n throw new Error(message, { cause: error as Error });\n }\n};\n\nconst createNullResponse = () => {\n const res: Record<string, unknown> = {};\n res.status = () => res;\n res.json = () => res;\n res.send = () => res;\n res.end = () => res;\n res.set = () => res;\n return res;\n};\n\nconst runMiddleware = async (\n middleware: (req: unknown, res: unknown, next: () => void) => Promise<void> | void,\n req: unknown,\n): Promise<boolean> => {\n return new Promise((resolve) => {\n let nextCalled = false;\n const res = createNullResponse();\n const next = () => {\n nextCalled = true;\n resolve(true);\n };\n\n Promise.resolve(middleware(req, res, next))\n .then(() => {\n if (!nextCalled) resolve(false);\n })\n .catch(() => resolve(false));\n });\n};\n\nexport const createFirebaseAuthSecurityHandlers = (\n options: FirebaseAuthSecurityOptions = {},\n): SecurityHandlers => {\n const securitySchemeName = options.securitySchemeName ?? 'bearerAuth';\n const roleClaim = options.roleClaim ?? 'roles';\n\n return {\n [securitySchemeName]: async (req, scopes, _schema) => {\n const { firebaseAuthMiddleware } = await loadFirebaseAuth();\n const middleware = firebaseAuthMiddleware({\n authClient: options.authClient,\n });\n\n const isAuthenticated = await runMiddleware(middleware, req);\n if (!isAuthenticated) return false;\n\n if (!scopes.length) return true;\n\n const roles = (req as Record<string, any>)?.auth?.token?.[roleClaim];\n if (!Array.isArray(roles)) return false;\n\n return scopes.every((scope: string) => roles.includes(scope));\n },\n };\n};\n","/**\n * OpenAPI v3 Document type (to avoid requiring express-openapi-validator types directly)\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type OpenAPIV3Document = any;\n\n/**\n * Imported handler modules, keyed by module name.\n * Automatically populated by the framework when operationHandlers is configured.\n */\nexport type ImportedHandlerModules = Record<string, any>;\n\n/**\n * Security handlers for custom authentication/authorization logic.\n * Maps security scheme names to handler functions.\n *\n * @see https://cdimascio.github.io/express-openapi-validator-documentation/usage-validate-security/\n */\n\nexport type SecurityHandlers = Record<\n string,\n (req: any, scopes: string[], schema: any) => boolean | Promise<boolean>\n>;\n\nexport * from './firebase-auth';\n\n/**\n * Configuration options for express-openapi-validator middleware.\n * This allows optional validation of API requests and responses against an OpenAPI specification.\n *\n * @see https://cdimascio.github.io/express-openapi-validator-documentation/\n */\nexport type OpenApiValidatorOptions = {\n /**\n * Path to the OpenAPI specification file (JSON or YAML)\n * or an OpenAPI specification object.\n */\n apiSpec: string | OpenAPIV3Document;\n\n /**\n * Determines whether the validator should validate requests.\n * Can be a boolean or an object with detailed request validation options.\n * @default true\n * @see https://cdimascio.github.io/express-openapi-validator-documentation/usage-validate-requests/\n */\n validateRequests?:\n | boolean\n | {\n /**\n * Allow unknown query parameters (not defined in the spec).\n * @default false\n */\n allowUnknownQueryParameters?: boolean;\n /**\n * Coerce types in request parameters.\n * @default true\n */\n coerceTypes?: boolean | 'array';\n /**\n * Remove additional properties not defined in the spec.\n * @default false\n */\n removeAdditional?: boolean | 'all' | 'failing';\n };\n\n /**\n * Determines whether the validator should validate responses.\n * Can be a boolean or an object with detailed response validation options.\n * @default false\n * @see https://cdimascio.github.io/express-openapi-validator-documentation/usage-validate-responses/\n */\n validateResponses?:\n | boolean\n | {\n /**\n * Remove additional properties from responses not defined in the spec.\n * @default false\n */\n removeAdditional?: boolean | 'all' | 'failing';\n /**\n * Coerce types in responses.\n * @default true\n */\n coerceTypes?: boolean;\n /**\n * Callback to handle response validation errors.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n onError?: (error: any, body: any, req: any) => void;\n };\n\n /**\n * Determines whether the validator should validate security.\n * Can be a boolean or an object with security handlers.\n * @default true\n * @see https://cdimascio.github.io/express-openapi-validator-documentation/usage-validate-security/\n */\n validateSecurity?:\n | boolean\n | {\n /**\n * Custom security handlers for authentication/authorization.\n */\n handlers?: SecurityHandlers;\n };\n\n /**\n * Defines how the validator should validate formats.\n * When true, uses ajv-formats for format validation.\n * When false, format validation is disabled.\n * Can also be 'fast' or 'full' for different validation modes.\n * @default true\n */\n validateFormats?: boolean | 'fast' | 'full';\n\n /**\n * The base path to the operation handlers directory.\n * When set to a path, automatically wires OpenAPI operations to handler functions\n * based on operationId or x-eov-operation-id.\n * When false, operation handlers are disabled (manual routing required).\n * @default false\n * @see https://cdimascio.github.io/express-openapi-validator-documentation/guide-operation-handlers/\n */\n operationHandlers?:\n | string\n | false\n | {\n /**\n * Base path to operation handlers directory.\n */\n basePath?: string;\n /**\n * Resolver function to map operationId to handler module path.\n */\n resolver?: (\n handlersPath: string,\n route: string,\n apiDoc: OpenAPIV3Document,\n ) => string;\n };\n\n /**\n * Paths or pattern to ignore during validation.\n * @default undefined\n */\n ignorePaths?: RegExp | ((path: string) => boolean);\n\n /**\n * Validate the OpenAPI specification itself.\n * @default true\n */\n validateApiSpec?: boolean;\n\n /**\n * $ref parser configuration for handling OpenAPI references.\n * @default undefined\n */\n $refParser?: {\n mode: 'bundle' | 'dereference';\n };\n\n /**\n * Serve the OpenAPI specification at a specific path.\n * When set to a string, the spec will be served at that path.\n * When false, the spec will not be served.\n * @default false\n * @example '/api-docs/openapi.json'\n */\n serveSpec?: string | false;\n\n /**\n * File upload configuration options.\n * @see https://cdimascio.github.io/express-openapi-validator-documentation/usage-file-uploads/\n */\n fileUploader?:\n | boolean\n | {\n /**\n * Destination directory for uploaded files.\n */\n dest?: string;\n /**\n * File size limit in bytes.\n */\n limits?: {\n fileSize?: number;\n files?: number;\n };\n };\n\n /**\n * Optional callback to initialize operation handlers with dependencies.\n * Called before the OpenAPI validator middleware is configured.\n *\n * The framework automatically imports handler modules referenced in your\n * OpenAPI spec (via x-eov-operation-handler) and passes them as the first parameter.\n *\n * @param handlers - Auto-imported handler modules, keyed by module name\n * @returns void or a Promise that resolves when initialization is complete\n *\n * @example\n * ```typescript\n * // With automatic import (recommended)\n * initializeHandlers: async (handlers) => {\n * handlers.shoppingCarts.initializeHandlers(eventStore, messageBus, getUnitPrice, getCurrentTime);\n * }\n *\n * // Manual import (still supported for backward compatibility)\n * import * as handlersModule from './handlers/shoppingCarts';\n * import { registerHandlerModule } from '@emmett-community/emmett-expressjs-with-openapi';\n * initializeHandlers: () => {\n * const handlersPath = path.join(__dirname, './handlers/shoppingCarts');\n * registerHandlerModule(handlersPath, handlersModule);\n * handlersModule.initializeHandlers(eventStore, messageBus, getUnitPrice, getCurrentTime);\n * }\n * ```\n */\n initializeHandlers?: (\n handlers?: ImportedHandlerModules,\n ) => void | Promise<void>;\n};\n\n/**\n * Helper function to create OpenAPI validator configuration with sensible defaults.\n *\n * @param apiSpec - Path to OpenAPI spec file or OpenAPI document object\n * @param options - Additional validator options\n * @returns Complete OpenApiValidatorOptions configuration\n *\n * @example\n * ```typescript\n * // Basic usage with default options\n * const validatorOptions = createOpenApiValidatorOptions('./openapi.yaml');\n *\n * // With response validation enabled\n * const validatorOptions = createOpenApiValidatorOptions('./openapi.yaml', {\n * validateResponses: true\n * });\n *\n * // With custom security handlers\n * const validatorOptions = createOpenApiValidatorOptions('./openapi.yaml', {\n * validateSecurity: {\n * handlers: {\n * bearerAuth: async (req, scopes) => {\n * // Custom authentication logic\n * return true;\n * }\n * }\n * }\n * });\n *\n * // Serving the spec at /api-docs\n * const validatorOptions = createOpenApiValidatorOptions('./openapi.yaml', {\n * serveSpec: '/api-docs/openapi.json'\n * });\n *\n * // With dependency injection for operation handlers\n * type ShoppingCartDeps = {\n * eventStore: EventStore;\n * messageBus: EventsPublisher;\n * getUnitPrice: (productId: string) => Promise<number>;\n * getCurrentTime: () => Date;\n * };\n *\n * const validatorOptions = createOpenApiValidatorOptions<ShoppingCartDeps>(\n * './openapi.yaml',\n * {\n * operationHandlers: './handlers',\n * initializeHandlers: (deps) => {\n * initializeHandlers(\n * deps.eventStore,\n * deps.messageBus,\n * deps.getUnitPrice,\n * deps.getCurrentTime\n * );\n * }\n * }\n * );\n *\n * const app = getApplication({\n * apis: [myApi],\n * openApiValidator: validatorOptions\n * });\n * ```\n */\nexport const createOpenApiValidatorOptions = (\n apiSpec: string | OpenAPIV3Document,\n options?: Partial<Omit<OpenApiValidatorOptions, 'apiSpec'>>,\n): OpenApiValidatorOptions => {\n return {\n apiSpec,\n validateRequests: options?.validateRequests ?? true,\n validateResponses: options?.validateResponses ?? false,\n validateSecurity: options?.validateSecurity ?? true,\n validateFormats: options?.validateFormats ?? true,\n operationHandlers: options?.operationHandlers,\n ignorePaths: options?.ignorePaths,\n validateApiSpec: options?.validateApiSpec ?? true,\n $refParser: options?.$refParser,\n serveSpec: options?.serveSpec ?? false,\n fileUploader: options?.fileUploader,\n initializeHandlers: options?.initializeHandlers,\n };\n};\n\n/**\n * Type guard to check if express-openapi-validator is available\n */\nexport const isOpenApiValidatorAvailable = async (): Promise<boolean> => {\n try {\n await import('express-openapi-validator');\n return true;\n } catch {\n return false;\n }\n};\n","import { type Request, type Response } from 'express';\nimport { ProblemDocument } from 'http-problem-details';\nimport { setETag, type ETag } from './etag';\n\nexport type ErrorToProblemDetailsMapping = (\n error: Error,\n request: Request,\n) => ProblemDocument | undefined;\n\nexport type HttpResponseOptions = {\n body?: unknown;\n location?: string;\n eTag?: ETag;\n};\nexport const DefaultHttpResponseOptions: HttpResponseOptions = {};\n\nexport type HttpProblemResponseOptions = {\n location?: string;\n eTag?: ETag;\n} & Omit<HttpResponseOptions, 'body'> &\n (\n | {\n problem: ProblemDocument;\n }\n | { problemDetails: string }\n );\nexport const DefaultHttpProblemResponseOptions: HttpProblemResponseOptions = {\n problemDetails: 'Error occured!',\n};\n\nexport type CreatedHttpResponseOptions = (\n | {\n createdId: string;\n }\n | {\n createdId?: string;\n url: string;\n }\n) &\n HttpResponseOptions;\n\nexport const sendCreated = (\n response: Response,\n { eTag, ...options }: CreatedHttpResponseOptions,\n): void =>\n send(response, 201, {\n location:\n 'url' in options\n ? options.url\n : `${response.req.url}/${options.createdId}`,\n body: 'createdId' in options ? { id: options.createdId } : undefined,\n eTag,\n });\n\nexport type AcceptedHttpResponseOptions = {\n location: string;\n} & HttpResponseOptions;\n\nexport const sendAccepted = (\n response: Response,\n options: AcceptedHttpResponseOptions,\n): void => send(response, 202, options);\n\nexport type NoContentHttpResponseOptions = Omit<HttpResponseOptions, 'body'>;\n\nexport const send = (\n response: Response,\n statusCode: number,\n options?: HttpResponseOptions,\n): void => {\n const { location, body, eTag } = options ?? DefaultHttpResponseOptions;\n // HEADERS\n if (eTag) setETag(response, eTag);\n if (location) response.setHeader('Location', location);\n\n if (body) {\n response.statusCode = statusCode;\n response.send(body);\n } else {\n response.sendStatus(statusCode);\n }\n};\n\nexport const sendProblem = (\n response: Response,\n statusCode: number,\n options?: HttpProblemResponseOptions,\n): void => {\n options = options ?? DefaultHttpProblemResponseOptions;\n\n const { location, eTag } = options;\n\n const problemDetails =\n 'problem' in options\n ? options.problem\n : new ProblemDocument({\n detail: options.problemDetails,\n status: statusCode,\n });\n\n // HEADERS\n if (eTag) setETag(response, eTag);\n if (location) response.setHeader('Location', location);\n\n response.setHeader('Content-Type', 'application/problem+json');\n\n response.statusCode = statusCode;\n response.json(problemDetails);\n};\n","import supertest, { type Response } from 'supertest';\n\nimport type { EventStore } from '@event-driven-io/emmett';\nimport assert from 'assert';\nimport type { Application } from 'express';\nimport type { TestRequest } from './apiSpecification';\n\nexport type E2EResponseAssert = (response: Response) => boolean | void;\n\nexport type ApiE2ESpecificationAssert = [E2EResponseAssert];\n\nexport type ApiE2ESpecification = (...givenRequests: TestRequest[]) => {\n when: (setupRequest: TestRequest) => {\n then: (verify: ApiE2ESpecificationAssert) => Promise<void>;\n };\n};\n\nexport const ApiE2ESpecification = {\n for: <Store extends EventStore = EventStore>(\n getEventStore: () => Store,\n getApplication: (eventStore: Store) => Application | Promise<Application>,\n ): ApiE2ESpecification => {\n {\n return (...givenRequests: TestRequest[]) => {\n const eventStore = getEventStore();\n\n return {\n when: (setupRequest: TestRequest) => {\n const handle = async () => {\n const application = await Promise.resolve(getApplication(eventStore));\n\n for (const requestFn of givenRequests) {\n await requestFn(supertest(application));\n }\n\n return setupRequest(supertest(application));\n };\n\n return {\n then: async (\n verify: ApiE2ESpecificationAssert,\n ): Promise<void> => {\n const response = await handle();\n\n verify.forEach((assertion) => {\n const succeeded = assertion(response);\n\n if (succeeded === false) assert.fail();\n });\n },\n };\n },\n };\n };\n }\n },\n};\n","import {\n WrapEventStore,\n assertEqual,\n assertFails,\n assertMatches,\n type Event,\n type EventStore,\n type TestEventStream,\n} from '@event-driven-io/emmett';\nimport { type Application } from 'express';\nimport type { ProblemDocument } from 'http-problem-details';\nimport type { Response, Test } from 'supertest';\nimport supertest from 'supertest';\nimport type TestAgent from 'supertest/lib/agent';\n\n////////////////////////////////\n/////////// Setup\n////////////////////////////////\n\nexport type TestRequest = (request: TestAgent<supertest.Test>) => Test;\n\nexport const existingStream = <EventType extends Event = Event>(\n streamId: string,\n events: EventType[],\n): TestEventStream<EventType> => {\n return [streamId, events];\n};\n\n////////////////////////////////\n/////////// Asserts\n////////////////////////////////\n\nexport type ResponseAssert = (response: Response) => boolean | void;\n\nexport type ApiSpecificationAssert<EventType extends Event = Event> =\n | TestEventStream<EventType>[]\n | ResponseAssert\n | [ResponseAssert, ...TestEventStream<EventType>[]];\n\nexport const expect = <EventType extends Event = Event>(\n streamId: string,\n events: EventType[],\n): TestEventStream<EventType> => {\n return [streamId, events];\n};\n\nexport const expectNewEvents = <EventType extends Event = Event>(\n streamId: string,\n events: EventType[],\n): TestEventStream<EventType> => {\n return [streamId, events];\n};\n\nexport const expectResponse =\n <Body = unknown>(\n statusCode: number,\n options?: { body?: Body; headers?: { [index: string]: string } },\n ) =>\n (response: Response): void => {\n const { body, headers } = options ?? {};\n assertEqual(statusCode, response.statusCode, \"Response code doesn't match\");\n if (body) assertMatches(response.body, body);\n if (headers) assertMatches(response.headers, headers);\n };\n\nexport const expectError = (\n errorCode: number,\n problemDetails?: Partial<ProblemDocument>,\n) =>\n expectResponse(\n errorCode,\n problemDetails ? { body: problemDetails } : undefined,\n );\n\n////////////////////////////////\n/////////// Api Specification\n////////////////////////////////\n\nexport type ApiSpecification<EventType extends Event = Event> = (\n ...givenStreams: TestEventStream<EventType>[]\n) => {\n when: (setupRequest: TestRequest) => {\n then: (verify: ApiSpecificationAssert<EventType>) => Promise<void>;\n };\n};\n\nexport const ApiSpecification = {\n for: <\n EventType extends Event = Event,\n Store extends EventStore<import('@event-driven-io/emmett').ReadEventMetadataWithGlobalPosition> = EventStore<import('@event-driven-io/emmett').ReadEventMetadataWithGlobalPosition>\n >(\n getEventStore: () => Store,\n getApplication: (eventStore: Store) => Application | Promise<Application>,\n ): ApiSpecification<EventType> => {\n {\n return (...givenStreams: TestEventStream<EventType>[]) => {\n const eventStore = WrapEventStore(getEventStore());\n\n return {\n when: (setupRequest: TestRequest) => {\n const handle = async () => {\n const application = await Promise.resolve(getApplication(eventStore));\n\n for (const [streamName, events] of givenStreams) {\n await eventStore.setup(streamName, events);\n }\n\n return setupRequest(supertest(application));\n };\n\n return {\n then: async (\n verify: ApiSpecificationAssert<EventType>,\n ): Promise<void> => {\n const response = await handle();\n\n if (typeof verify === 'function') {\n const succeeded = verify(response);\n\n if (succeeded === false) assertFails();\n } else if (Array.isArray(verify)) {\n const [first, ...rest] = verify;\n\n if (typeof first === 'function') {\n const succeeded = first(response);\n\n if (succeeded === false) assertFails();\n }\n\n const events = typeof first === 'function' ? rest : verify;\n\n assertMatches(\n Array.from(eventStore.appendedEvents.values()),\n events,\n );\n }\n },\n };\n },\n };\n };\n }\n },\n};\n"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -6,6 +6,102 @@ import { Brand, Event, TestEventStream, EventStore } from '@event-driven-io/emme
|
|
|
6
6
|
import supertest, { Test, Response as Response$1 } from 'supertest';
|
|
7
7
|
import TestAgent from 'supertest/lib/agent';
|
|
8
8
|
|
|
9
|
+
/**
|
|
10
|
+
* Observability types for emmett-expressjs-with-openapi.
|
|
11
|
+
*
|
|
12
|
+
* This module provides optional logging integration
|
|
13
|
+
* following a "silent by default" philosophy.
|
|
14
|
+
*/
|
|
15
|
+
/**
|
|
16
|
+
* Canonical Logger contract for the Emmett ecosystem.
|
|
17
|
+
*
|
|
18
|
+
* This package defines the canonical Logger interface.
|
|
19
|
+
* Implementations (Pino, Winston, etc.) MUST adapt to this contract.
|
|
20
|
+
* This contract MUST NOT adapt to any specific implementation.
|
|
21
|
+
*
|
|
22
|
+
* Semantic Rules:
|
|
23
|
+
* - context (first parameter): ALWAYS structured data as Record<string, unknown>
|
|
24
|
+
* - message (second parameter): ALWAYS the human-readable log message
|
|
25
|
+
* - The order is NEVER inverted
|
|
26
|
+
* - The (message, data) form is NOT valid for this contract
|
|
27
|
+
*
|
|
28
|
+
* @example
|
|
29
|
+
* ```typescript
|
|
30
|
+
* // Pino - native compatibility
|
|
31
|
+
* import pino from 'pino';
|
|
32
|
+
* const logger = pino();
|
|
33
|
+
* // logger.info({ orderId }, 'Order created') matches our contract
|
|
34
|
+
* ```
|
|
35
|
+
*/
|
|
36
|
+
interface Logger {
|
|
37
|
+
/**
|
|
38
|
+
* Log debug-level message with structured context.
|
|
39
|
+
* @param context - Structured data to include in the log entry
|
|
40
|
+
* @param message - Optional human-readable message
|
|
41
|
+
*/
|
|
42
|
+
debug(context: Record<string, unknown>, message?: string): void;
|
|
43
|
+
/**
|
|
44
|
+
* Log info-level message with structured context.
|
|
45
|
+
* @param context - Structured data to include in the log entry
|
|
46
|
+
* @param message - Optional human-readable message
|
|
47
|
+
*/
|
|
48
|
+
info(context: Record<string, unknown>, message?: string): void;
|
|
49
|
+
/**
|
|
50
|
+
* Log warn-level message with structured context.
|
|
51
|
+
* @param context - Structured data to include in the log entry
|
|
52
|
+
* @param message - Optional human-readable message
|
|
53
|
+
*/
|
|
54
|
+
warn(context: Record<string, unknown>, message?: string): void;
|
|
55
|
+
/**
|
|
56
|
+
* Log error-level message with structured context.
|
|
57
|
+
* @param context - Structured data to include in the log entry (may include 'err' key)
|
|
58
|
+
* @param message - Optional human-readable message
|
|
59
|
+
*/
|
|
60
|
+
error(context: Record<string, unknown>, message?: string): void;
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Observability configuration options.
|
|
64
|
+
*/
|
|
65
|
+
type ObservabilityOptions = {
|
|
66
|
+
/**
|
|
67
|
+
* Optional logger instance for diagnostic output.
|
|
68
|
+
* When not provided, the library operates silently.
|
|
69
|
+
*
|
|
70
|
+
* @example
|
|
71
|
+
* ```typescript
|
|
72
|
+
* import pino from 'pino';
|
|
73
|
+
*
|
|
74
|
+
* const logger = pino();
|
|
75
|
+
*
|
|
76
|
+
* const app = await getApplication({
|
|
77
|
+
* observability: { logger },
|
|
78
|
+
* });
|
|
79
|
+
* ```
|
|
80
|
+
*/
|
|
81
|
+
logger?: Logger;
|
|
82
|
+
};
|
|
83
|
+
/**
|
|
84
|
+
* Internal helper to safely call logger methods.
|
|
85
|
+
*
|
|
86
|
+
* IMPORTANT: safeLog is the ONLY translation point between internal usage
|
|
87
|
+
* and the Logger contract.
|
|
88
|
+
*
|
|
89
|
+
* Internal Usage Pattern:
|
|
90
|
+
* safeLog.info(logger, 'Order created', { orderId: 123 })
|
|
91
|
+
*
|
|
92
|
+
* Translation to Logger Contract:
|
|
93
|
+
* logger.info({ orderId: 123 }, 'Order created')
|
|
94
|
+
*
|
|
95
|
+
* This allows ergonomic internal usage while ensuring all injected loggers
|
|
96
|
+
* receive calls in the canonical (context, message) format.
|
|
97
|
+
*/
|
|
98
|
+
declare const safeLog: {
|
|
99
|
+
debug: (logger: Logger | undefined, msg: string, data?: unknown) => void;
|
|
100
|
+
info: (logger: Logger | undefined, msg: string, data?: unknown) => void;
|
|
101
|
+
warn: (logger: Logger | undefined, msg: string, data?: unknown) => void;
|
|
102
|
+
error: (logger: Logger | undefined, msg: string, error?: unknown) => void;
|
|
103
|
+
};
|
|
104
|
+
|
|
9
105
|
type AuthClient = {
|
|
10
106
|
verifyIdToken: (token: string) => Promise<unknown>;
|
|
11
107
|
};
|
|
@@ -391,15 +487,60 @@ type ApplicationOptions = {
|
|
|
391
487
|
* ```
|
|
392
488
|
*/
|
|
393
489
|
openApiValidator?: OpenApiValidatorOptions;
|
|
490
|
+
/**
|
|
491
|
+
* Optional observability configuration for logging.
|
|
492
|
+
* When not provided, the library operates silently (no logs).
|
|
493
|
+
*
|
|
494
|
+
* @example
|
|
495
|
+
* ```typescript
|
|
496
|
+
* import pino from 'pino';
|
|
497
|
+
*
|
|
498
|
+
* const logger = pino();
|
|
499
|
+
*
|
|
500
|
+
* const app = await getApplication({
|
|
501
|
+
* observability: { logger },
|
|
502
|
+
* });
|
|
503
|
+
* ```
|
|
504
|
+
*/
|
|
505
|
+
observability?: ObservabilityOptions;
|
|
394
506
|
};
|
|
395
507
|
declare const getApplication: (options: ApplicationOptions) => Promise<express.Application>;
|
|
396
508
|
type StartApiOptions = {
|
|
397
509
|
port?: number;
|
|
510
|
+
/**
|
|
511
|
+
* Optional logger for lifecycle events.
|
|
512
|
+
*/
|
|
513
|
+
logger?: Logger;
|
|
398
514
|
};
|
|
399
515
|
declare const startAPI: (app: Application, options?: StartApiOptions) => http.Server<typeof http.IncomingMessage, typeof http.ServerResponse>;
|
|
400
516
|
|
|
401
517
|
type HttpHandler<RequestType extends Request> = (request: RequestType) => Promise<HttpResponse> | HttpResponse;
|
|
402
518
|
declare const on: <RequestType extends Request>(handle: HttpHandler<RequestType>) => (request: RequestType, response: Response, _next: NextFunction) => Promise<void>;
|
|
519
|
+
/**
|
|
520
|
+
* Options for the traced handler wrapper.
|
|
521
|
+
*/
|
|
522
|
+
type TracedHandlerOptions = {
|
|
523
|
+
/**
|
|
524
|
+
* Custom span name. Defaults to 'emmett.http.handle_request'.
|
|
525
|
+
*/
|
|
526
|
+
spanName?: string;
|
|
527
|
+
};
|
|
528
|
+
/**
|
|
529
|
+
* Wraps an HTTP handler with OpenTelemetry tracing.
|
|
530
|
+
* Creates a span that captures request method, route, and response status.
|
|
531
|
+
*
|
|
532
|
+
* If OpenTelemetry is not initialized by the application, spans are no-ops
|
|
533
|
+
* with zero overhead.
|
|
534
|
+
*
|
|
535
|
+
* @example
|
|
536
|
+
* ```typescript
|
|
537
|
+
* router.post('/carts', tracedOn(async (req) => {
|
|
538
|
+
* // Your handler logic
|
|
539
|
+
* return Created({ createdId: cartId });
|
|
540
|
+
* }));
|
|
541
|
+
* ```
|
|
542
|
+
*/
|
|
543
|
+
declare const tracedOn: <RequestType extends Request>(handle: HttpHandler<RequestType>, options?: TracedHandlerOptions) => (request: RequestType, response: Response, _next: NextFunction) => Promise<void>;
|
|
403
544
|
declare const OK: (options?: HttpResponseOptions) => HttpResponse;
|
|
404
545
|
declare const Created: (options: CreatedHttpResponseOptions) => HttpResponse;
|
|
405
546
|
declare const Accepted: (options: AcceptedHttpResponseOptions) => HttpResponse;
|
|
@@ -484,4 +625,4 @@ declare const ApiE2ESpecification: {
|
|
|
484
625
|
*/
|
|
485
626
|
declare const registerHandlerModule: (modulePath: string, moduleExports: any) => void;
|
|
486
627
|
|
|
487
|
-
export { Accepted, type AcceptedHttpResponseOptions, ApiE2ESpecification, type ApiE2ESpecificationAssert, ApiSpecification, type ApiSpecificationAssert, type ApplicationOptions, BadRequest, Conflict, Created, type CreatedHttpResponseOptions, DefaultHttpProblemResponseOptions, DefaultHttpResponseOptions, type E2EResponseAssert, type ETag, ETagErrors, type ErrorToProblemDetailsMapping, type FirebaseAuthSecurityOptions, Forbidden, HeaderNames, type HttpHandler, HttpProblem, type HttpProblemResponseOptions, HttpResponse, type HttpResponseOptions, type ImportedHandlerModules, NoContent, type NoContentHttpResponseOptions, NotFound, OK, type OpenAPIV3Document, type OpenApiValidatorOptions, type PinoHttpOptions, PreconditionFailed, type ResponseAssert, type SecurityHandlers, type StartApiOptions, type TestRequest, type WeakETag, WeakETagRegex, type WebApiSetup, createFirebaseAuthSecurityHandlers, createOpenApiValidatorOptions, existingStream, expect, expectError, expectNewEvents, expectResponse, getApplication, getETagFromIfMatch, getETagFromIfNotMatch, getETagValueFromIfMatch, getWeakETagValue, isOpenApiValidatorAvailable, isWeakETag, on, registerHandlerModule, send, sendAccepted, sendCreated, sendProblem, setETag, startAPI, toWeakETag };
|
|
628
|
+
export { Accepted, type AcceptedHttpResponseOptions, ApiE2ESpecification, type ApiE2ESpecificationAssert, ApiSpecification, type ApiSpecificationAssert, type ApplicationOptions, BadRequest, Conflict, Created, type CreatedHttpResponseOptions, DefaultHttpProblemResponseOptions, DefaultHttpResponseOptions, type E2EResponseAssert, type ETag, ETagErrors, type ErrorToProblemDetailsMapping, type FirebaseAuthSecurityOptions, Forbidden, HeaderNames, type HttpHandler, HttpProblem, type HttpProblemResponseOptions, HttpResponse, type HttpResponseOptions, type ImportedHandlerModules, type Logger, NoContent, type NoContentHttpResponseOptions, NotFound, OK, type ObservabilityOptions, type OpenAPIV3Document, type OpenApiValidatorOptions, type PinoHttpOptions, PreconditionFailed, type ResponseAssert, type SecurityHandlers, type StartApiOptions, type TestRequest, type TracedHandlerOptions, type WeakETag, WeakETagRegex, type WebApiSetup, createFirebaseAuthSecurityHandlers, createOpenApiValidatorOptions, existingStream, expect, expectError, expectNewEvents, expectResponse, getApplication, getETagFromIfMatch, getETagFromIfNotMatch, getETagValueFromIfMatch, getWeakETagValue, isOpenApiValidatorAvailable, isWeakETag, on, registerHandlerModule, safeLog, send, sendAccepted, sendCreated, sendProblem, setETag, startAPI, toWeakETag, tracedOn };
|
package/dist/index.d.ts
CHANGED
|
@@ -6,6 +6,102 @@ import { Brand, Event, TestEventStream, EventStore } from '@event-driven-io/emme
|
|
|
6
6
|
import supertest, { Test, Response as Response$1 } from 'supertest';
|
|
7
7
|
import TestAgent from 'supertest/lib/agent';
|
|
8
8
|
|
|
9
|
+
/**
|
|
10
|
+
* Observability types for emmett-expressjs-with-openapi.
|
|
11
|
+
*
|
|
12
|
+
* This module provides optional logging integration
|
|
13
|
+
* following a "silent by default" philosophy.
|
|
14
|
+
*/
|
|
15
|
+
/**
|
|
16
|
+
* Canonical Logger contract for the Emmett ecosystem.
|
|
17
|
+
*
|
|
18
|
+
* This package defines the canonical Logger interface.
|
|
19
|
+
* Implementations (Pino, Winston, etc.) MUST adapt to this contract.
|
|
20
|
+
* This contract MUST NOT adapt to any specific implementation.
|
|
21
|
+
*
|
|
22
|
+
* Semantic Rules:
|
|
23
|
+
* - context (first parameter): ALWAYS structured data as Record<string, unknown>
|
|
24
|
+
* - message (second parameter): ALWAYS the human-readable log message
|
|
25
|
+
* - The order is NEVER inverted
|
|
26
|
+
* - The (message, data) form is NOT valid for this contract
|
|
27
|
+
*
|
|
28
|
+
* @example
|
|
29
|
+
* ```typescript
|
|
30
|
+
* // Pino - native compatibility
|
|
31
|
+
* import pino from 'pino';
|
|
32
|
+
* const logger = pino();
|
|
33
|
+
* // logger.info({ orderId }, 'Order created') matches our contract
|
|
34
|
+
* ```
|
|
35
|
+
*/
|
|
36
|
+
interface Logger {
|
|
37
|
+
/**
|
|
38
|
+
* Log debug-level message with structured context.
|
|
39
|
+
* @param context - Structured data to include in the log entry
|
|
40
|
+
* @param message - Optional human-readable message
|
|
41
|
+
*/
|
|
42
|
+
debug(context: Record<string, unknown>, message?: string): void;
|
|
43
|
+
/**
|
|
44
|
+
* Log info-level message with structured context.
|
|
45
|
+
* @param context - Structured data to include in the log entry
|
|
46
|
+
* @param message - Optional human-readable message
|
|
47
|
+
*/
|
|
48
|
+
info(context: Record<string, unknown>, message?: string): void;
|
|
49
|
+
/**
|
|
50
|
+
* Log warn-level message with structured context.
|
|
51
|
+
* @param context - Structured data to include in the log entry
|
|
52
|
+
* @param message - Optional human-readable message
|
|
53
|
+
*/
|
|
54
|
+
warn(context: Record<string, unknown>, message?: string): void;
|
|
55
|
+
/**
|
|
56
|
+
* Log error-level message with structured context.
|
|
57
|
+
* @param context - Structured data to include in the log entry (may include 'err' key)
|
|
58
|
+
* @param message - Optional human-readable message
|
|
59
|
+
*/
|
|
60
|
+
error(context: Record<string, unknown>, message?: string): void;
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Observability configuration options.
|
|
64
|
+
*/
|
|
65
|
+
type ObservabilityOptions = {
|
|
66
|
+
/**
|
|
67
|
+
* Optional logger instance for diagnostic output.
|
|
68
|
+
* When not provided, the library operates silently.
|
|
69
|
+
*
|
|
70
|
+
* @example
|
|
71
|
+
* ```typescript
|
|
72
|
+
* import pino from 'pino';
|
|
73
|
+
*
|
|
74
|
+
* const logger = pino();
|
|
75
|
+
*
|
|
76
|
+
* const app = await getApplication({
|
|
77
|
+
* observability: { logger },
|
|
78
|
+
* });
|
|
79
|
+
* ```
|
|
80
|
+
*/
|
|
81
|
+
logger?: Logger;
|
|
82
|
+
};
|
|
83
|
+
/**
|
|
84
|
+
* Internal helper to safely call logger methods.
|
|
85
|
+
*
|
|
86
|
+
* IMPORTANT: safeLog is the ONLY translation point between internal usage
|
|
87
|
+
* and the Logger contract.
|
|
88
|
+
*
|
|
89
|
+
* Internal Usage Pattern:
|
|
90
|
+
* safeLog.info(logger, 'Order created', { orderId: 123 })
|
|
91
|
+
*
|
|
92
|
+
* Translation to Logger Contract:
|
|
93
|
+
* logger.info({ orderId: 123 }, 'Order created')
|
|
94
|
+
*
|
|
95
|
+
* This allows ergonomic internal usage while ensuring all injected loggers
|
|
96
|
+
* receive calls in the canonical (context, message) format.
|
|
97
|
+
*/
|
|
98
|
+
declare const safeLog: {
|
|
99
|
+
debug: (logger: Logger | undefined, msg: string, data?: unknown) => void;
|
|
100
|
+
info: (logger: Logger | undefined, msg: string, data?: unknown) => void;
|
|
101
|
+
warn: (logger: Logger | undefined, msg: string, data?: unknown) => void;
|
|
102
|
+
error: (logger: Logger | undefined, msg: string, error?: unknown) => void;
|
|
103
|
+
};
|
|
104
|
+
|
|
9
105
|
type AuthClient = {
|
|
10
106
|
verifyIdToken: (token: string) => Promise<unknown>;
|
|
11
107
|
};
|
|
@@ -391,15 +487,60 @@ type ApplicationOptions = {
|
|
|
391
487
|
* ```
|
|
392
488
|
*/
|
|
393
489
|
openApiValidator?: OpenApiValidatorOptions;
|
|
490
|
+
/**
|
|
491
|
+
* Optional observability configuration for logging.
|
|
492
|
+
* When not provided, the library operates silently (no logs).
|
|
493
|
+
*
|
|
494
|
+
* @example
|
|
495
|
+
* ```typescript
|
|
496
|
+
* import pino from 'pino';
|
|
497
|
+
*
|
|
498
|
+
* const logger = pino();
|
|
499
|
+
*
|
|
500
|
+
* const app = await getApplication({
|
|
501
|
+
* observability: { logger },
|
|
502
|
+
* });
|
|
503
|
+
* ```
|
|
504
|
+
*/
|
|
505
|
+
observability?: ObservabilityOptions;
|
|
394
506
|
};
|
|
395
507
|
declare const getApplication: (options: ApplicationOptions) => Promise<express.Application>;
|
|
396
508
|
type StartApiOptions = {
|
|
397
509
|
port?: number;
|
|
510
|
+
/**
|
|
511
|
+
* Optional logger for lifecycle events.
|
|
512
|
+
*/
|
|
513
|
+
logger?: Logger;
|
|
398
514
|
};
|
|
399
515
|
declare const startAPI: (app: Application, options?: StartApiOptions) => http.Server<typeof http.IncomingMessage, typeof http.ServerResponse>;
|
|
400
516
|
|
|
401
517
|
type HttpHandler<RequestType extends Request> = (request: RequestType) => Promise<HttpResponse> | HttpResponse;
|
|
402
518
|
declare const on: <RequestType extends Request>(handle: HttpHandler<RequestType>) => (request: RequestType, response: Response, _next: NextFunction) => Promise<void>;
|
|
519
|
+
/**
|
|
520
|
+
* Options for the traced handler wrapper.
|
|
521
|
+
*/
|
|
522
|
+
type TracedHandlerOptions = {
|
|
523
|
+
/**
|
|
524
|
+
* Custom span name. Defaults to 'emmett.http.handle_request'.
|
|
525
|
+
*/
|
|
526
|
+
spanName?: string;
|
|
527
|
+
};
|
|
528
|
+
/**
|
|
529
|
+
* Wraps an HTTP handler with OpenTelemetry tracing.
|
|
530
|
+
* Creates a span that captures request method, route, and response status.
|
|
531
|
+
*
|
|
532
|
+
* If OpenTelemetry is not initialized by the application, spans are no-ops
|
|
533
|
+
* with zero overhead.
|
|
534
|
+
*
|
|
535
|
+
* @example
|
|
536
|
+
* ```typescript
|
|
537
|
+
* router.post('/carts', tracedOn(async (req) => {
|
|
538
|
+
* // Your handler logic
|
|
539
|
+
* return Created({ createdId: cartId });
|
|
540
|
+
* }));
|
|
541
|
+
* ```
|
|
542
|
+
*/
|
|
543
|
+
declare const tracedOn: <RequestType extends Request>(handle: HttpHandler<RequestType>, options?: TracedHandlerOptions) => (request: RequestType, response: Response, _next: NextFunction) => Promise<void>;
|
|
403
544
|
declare const OK: (options?: HttpResponseOptions) => HttpResponse;
|
|
404
545
|
declare const Created: (options: CreatedHttpResponseOptions) => HttpResponse;
|
|
405
546
|
declare const Accepted: (options: AcceptedHttpResponseOptions) => HttpResponse;
|
|
@@ -484,4 +625,4 @@ declare const ApiE2ESpecification: {
|
|
|
484
625
|
*/
|
|
485
626
|
declare const registerHandlerModule: (modulePath: string, moduleExports: any) => void;
|
|
486
627
|
|
|
487
|
-
export { Accepted, type AcceptedHttpResponseOptions, ApiE2ESpecification, type ApiE2ESpecificationAssert, ApiSpecification, type ApiSpecificationAssert, type ApplicationOptions, BadRequest, Conflict, Created, type CreatedHttpResponseOptions, DefaultHttpProblemResponseOptions, DefaultHttpResponseOptions, type E2EResponseAssert, type ETag, ETagErrors, type ErrorToProblemDetailsMapping, type FirebaseAuthSecurityOptions, Forbidden, HeaderNames, type HttpHandler, HttpProblem, type HttpProblemResponseOptions, HttpResponse, type HttpResponseOptions, type ImportedHandlerModules, NoContent, type NoContentHttpResponseOptions, NotFound, OK, type OpenAPIV3Document, type OpenApiValidatorOptions, type PinoHttpOptions, PreconditionFailed, type ResponseAssert, type SecurityHandlers, type StartApiOptions, type TestRequest, type WeakETag, WeakETagRegex, type WebApiSetup, createFirebaseAuthSecurityHandlers, createOpenApiValidatorOptions, existingStream, expect, expectError, expectNewEvents, expectResponse, getApplication, getETagFromIfMatch, getETagFromIfNotMatch, getETagValueFromIfMatch, getWeakETagValue, isOpenApiValidatorAvailable, isWeakETag, on, registerHandlerModule, send, sendAccepted, sendCreated, sendProblem, setETag, startAPI, toWeakETag };
|
|
628
|
+
export { Accepted, type AcceptedHttpResponseOptions, ApiE2ESpecification, type ApiE2ESpecificationAssert, ApiSpecification, type ApiSpecificationAssert, type ApplicationOptions, BadRequest, Conflict, Created, type CreatedHttpResponseOptions, DefaultHttpProblemResponseOptions, DefaultHttpResponseOptions, type E2EResponseAssert, type ETag, ETagErrors, type ErrorToProblemDetailsMapping, type FirebaseAuthSecurityOptions, Forbidden, HeaderNames, type HttpHandler, HttpProblem, type HttpProblemResponseOptions, HttpResponse, type HttpResponseOptions, type ImportedHandlerModules, type Logger, NoContent, type NoContentHttpResponseOptions, NotFound, OK, type ObservabilityOptions, type OpenAPIV3Document, type OpenApiValidatorOptions, type PinoHttpOptions, PreconditionFailed, type ResponseAssert, type SecurityHandlers, type StartApiOptions, type TestRequest, type TracedHandlerOptions, type WeakETag, WeakETagRegex, type WebApiSetup, createFirebaseAuthSecurityHandlers, createOpenApiValidatorOptions, existingStream, expect, expectError, expectNewEvents, expectResponse, getApplication, getETagFromIfMatch, getETagFromIfNotMatch, getETagValueFromIfMatch, getWeakETagValue, isOpenApiValidatorAvailable, isWeakETag, on, registerHandlerModule, safeLog, send, sendAccepted, sendCreated, sendProblem, setETag, startAPI, toWeakETag, tracedOn };
|