blaizejs 0.3.3 → 0.3.4

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.
Files changed (24) hide show
  1. package/dist/chunk-DTDGIBMA.js +11 -0
  2. package/dist/{chunk-KE2IOPV4.js.map → chunk-DTDGIBMA.js.map} +1 -1
  3. package/dist/{chunk-LY65OJH4.js → chunk-EE2VJ6JY.js} +3 -3
  4. package/dist/{chunk-VM3QGHVO.js → chunk-HSLLYUVO.js} +3 -3
  5. package/dist/{chunk-337RPHG5.js → chunk-TL4GIFTB.js} +3 -3
  6. package/dist/{chunk-HX7XLEO3.js → chunk-VLVWNGUO.js} +3 -3
  7. package/dist/index.cjs +10 -36
  8. package/dist/index.cjs.map +1 -1
  9. package/dist/index.js +10 -36
  10. package/dist/index.js.map +1 -1
  11. package/dist/{internal-server-error-JHHSKW5B.js → internal-server-error-GWBNT3OO.js} +3 -3
  12. package/dist/{payload-too-large-error-SOQINKUL.js → payload-too-large-error-EBM5BNWG.js} +3 -3
  13. package/dist/{unsupported-media-type-error-KJMHH5CY.js → unsupported-media-type-error-YQ7GCZ32.js} +3 -3
  14. package/dist/{validation-error-Q6IOTN4C.js → validation-error-6JDCGV2S.js} +3 -3
  15. package/package.json +2 -2
  16. package/dist/chunk-KE2IOPV4.js +0 -11
  17. /package/dist/{chunk-LY65OJH4.js.map → chunk-EE2VJ6JY.js.map} +0 -0
  18. /package/dist/{chunk-VM3QGHVO.js.map → chunk-HSLLYUVO.js.map} +0 -0
  19. /package/dist/{chunk-337RPHG5.js.map → chunk-TL4GIFTB.js.map} +0 -0
  20. /package/dist/{chunk-HX7XLEO3.js.map → chunk-VLVWNGUO.js.map} +0 -0
  21. /package/dist/{internal-server-error-JHHSKW5B.js.map → internal-server-error-GWBNT3OO.js.map} +0 -0
  22. /package/dist/{payload-too-large-error-SOQINKUL.js.map → payload-too-large-error-EBM5BNWG.js.map} +0 -0
  23. /package/dist/{unsupported-media-type-error-KJMHH5CY.js.map → unsupported-media-type-error-YQ7GCZ32.js.map} +0 -0
  24. /package/dist/{validation-error-Q6IOTN4C.js.map → validation-error-6JDCGV2S.js.map} +0 -0
@@ -0,0 +1,11 @@
1
+
2
+ /**
3
+ * blaizejs v0.3.4
4
+ * A blazing-fast, TypeScript-first Node.js framework with HTTP/2 support, file-based routing, powerful middleware system, and end-to-end type safety for building modern APIs.
5
+ *
6
+ * Copyright (c) 2025 BlaizeJS Contributors
7
+ * @license MIT
8
+ */
9
+
10
+ var g=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(r,i)=>(typeof require<"u"?require:r)[i]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var u=(t=>(t.VALIDATION_ERROR="VALIDATION_ERROR",t.NOT_FOUND="NOT_FOUND",t.UNAUTHORIZED="UNAUTHORIZED",t.FORBIDDEN="FORBIDDEN",t.CONFLICT="CONFLICT",t.RATE_LIMITED="RATE_LIMITED",t.INTERNAL_SERVER_ERROR="INTERNAL_SERVER_ERROR",t.PAYLOAD_TOO_LARGE="PAYLOAD_TOO_LARGE",t.UNSUPPORTED_MEDIA_TYPE="UNSUPPORTED_MEDIA_TYPE",t.UPLOAD_TIMEOUT="UPLOAD_TIMEOUT",t.UNPROCESSABLE_ENTITY="UNPROCESSABLE_ENTITY",t.NETWORK_ERROR="NETWORK_ERROR",t.TIMEOUT_ERROR="TIMEOUT_ERROR",t.PARSE_ERROR="PARSE_ERROR",t.HTTP_ERROR="HTTP_ERROR",t))(u||{}),c=(n=>(n.LOW="low",n.MEDIUM="medium",n.HIGH="high",n.CRITICAL="critical",n))(c||{}),o=class extends Error{type;title;status;correlationId;timestamp;details;constructor(r,i,s,n,a){super(i),this.name=this.constructor.name,this.type=r,this.title=i,this.status=s,this.correlationId=n,this.timestamp=new Date,this.details=a,Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}toJSON(){let r={type:this.type,title:this.title,status:this.status,correlationId:this.correlationId,timestamp:this.timestamp.toISOString()};return this.details!==void 0?{...r,details:this.details}:r}toString(){return`${this.name}: ${this.title} [${this.correlationId}]`}};function p(e){return typeof e=="object"&&e!==null&&"type"in e&&"message"in e&&"error"in e&&typeof e.type=="string"&&typeof e.message=="string"}import{AsyncLocalStorage as l}from"node:async_hooks";var d=new l;function f(){let e=Date.now().toString(36),r=Math.random().toString(36).substr(2,9);return`req_${e}_${r}`}function T(){let e=d.getStore();return e&&e.trim()?e:"unknown"}export{g as a,u as b,c,o as d,p as e,f,T as g};
11
+ //# sourceMappingURL=chunk-DTDGIBMA.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../blaize-types/src/errors.ts","../src/errors/correlation.ts"],"sourcesContent":["/**\n * Error type definitions and interfaces for the BlaizeJS framework\n *\n * This module contains all the type definitions used for error handling\n * across the BlaizeJS framework, including server-side errors, client-side\n * errors, and HTTP response formats.\n */\n\n/**\n * Structure of error responses sent over HTTP\n *\n * This interface defines the JSON format used for all error responses\n * from BlaizeJS servers. It matches the structure returned by BlaizeError.toJSON()\n *\n * @example\n * ```json\n * {\n * \"type\": \"VALIDATION_ERROR\",\n * \"title\": \"Request validation failed\",\n * \"status\": 400,\n * \"correlationId\": \"req_abc123\",\n * \"timestamp\": \"2024-01-15T10:30:00.000Z\",\n * \"details\": {\n * \"fields\": [\"email\", \"password\"]\n * }\n * }\n * ```\n */\nexport interface BlaizeErrorResponse {\n /** Error type from the ErrorType enum */\n type: ErrorType;\n\n /** Human-readable error message */\n title: string;\n\n /** HTTP status code */\n status: number;\n\n /** Correlation ID for request tracing */\n correlationId: string;\n\n /** ISO timestamp when error occurred */\n timestamp: string;\n\n /** Optional error-specific details */\n details?: unknown;\n}\n\n/**\n * Context information for network-related errors\n *\n * Used by client-side error classes to provide additional context\n * about network failures, timeouts, and connection issues.\n */\nexport interface NetworkErrorContext {\n /** The URL that failed */\n url: string;\n\n /** HTTP method being attempted */\n method: string;\n\n /** Correlation ID for tracing */\n correlationId: string;\n\n /** Timeout value if applicable */\n timeout?: number;\n\n /** The original error that caused the network failure */\n originalError: Error;\n\n /** Additional network-specific details */\n networkDetails?: {\n /** Whether this was a connection timeout */\n isTimeout?: boolean;\n\n /** Whether this was a DNS resolution failure */\n isDnsFailure?: boolean;\n\n /** Whether this was a connection refused error */\n isConnectionRefused?: boolean;\n\n /** HTTP status code if received before failure */\n statusCode?: number;\n };\n}\n\n/**\n * Context information for request timeout errors\n *\n * Specialized context for timeout-specific errors with timing information.\n */\nexport interface TimeoutErrorContext {\n /** The URL that timed out */\n url: string;\n\n /** HTTP method being attempted */\n method: string;\n\n /** Correlation ID for tracing */\n correlationId: string;\n\n /** Configured timeout value in milliseconds */\n timeoutMs: number;\n\n /** Actual duration before timeout in milliseconds */\n elapsedMs: number;\n\n /** Type of timeout (request, connection, etc.) */\n timeoutType: 'request' | 'connection' | 'response' | 'idle';\n}\n\n/**\n * Context information for response parsing errors\n *\n * Used when the client receives a response but cannot parse it properly.\n */\nexport interface ParseErrorContext {\n /** The URL that returned unparseable content */\n url: string;\n\n /** HTTP method used */\n method: string;\n\n /** Correlation ID for tracing */\n correlationId: string;\n\n /** HTTP status code received */\n statusCode: number;\n\n /** Content-Type header if available */\n contentType?: string;\n\n /** Expected response format */\n expectedFormat: 'json' | 'text' | 'binary';\n\n /** Sample of the actual response content (truncated for safety) */\n responseSample?: string;\n\n /** The original parsing error */\n originalError: Error;\n}\n\n/**\n * Validation error field details\n *\n * Structure for field-level validation errors with multiple error messages\n * per field.\n */\nexport interface ValidationFieldError {\n /** Field name or path (e.g., \"email\", \"user.profile.name\") */\n field: string;\n\n /** Array of error messages for this field */\n messages: string[];\n\n /** The invalid value that caused the error */\n rejectedValue?: unknown;\n\n /** Expected type or format */\n expectedType?: string;\n}\n\n/**\n * Validation error details structure\n *\n * Used by ValidationError to provide structured information about\n * what fields failed validation and why.\n */\nexport interface ValidationErrorDetails {\n /** Array of field-level errors */\n fields: ValidationFieldError[];\n\n /** Total number of validation errors */\n errorCount: number;\n\n /** The section that failed validation */\n section: 'params' | 'query' | 'body' | 'response';\n\n /** Schema name if available */\n schemaName?: string;\n}\n\n/**\n * All available error types in the BlaizeJS framework\n *\n * This enum provides both compile-time type safety and runtime values\n * for error type identification across server and client packages.\n *\n * @example Type-safe error handling:\n * ```typescript\n * function handleError(errorType: ErrorType) {\n * switch (errorType) {\n * case ErrorType.VALIDATION_ERROR:\n * // Handle validation error\n * break;\n * case ErrorType.NOT_FOUND:\n * // Handle not found error\n * break;\n * // TypeScript ensures all cases are covered\n * }\n * }\n * ```\n */\nexport enum ErrorType {\n // Server-side business logic errors\n /** Request validation failed (400) */\n VALIDATION_ERROR = 'VALIDATION_ERROR',\n\n /** Resource not found (404) */\n NOT_FOUND = 'NOT_FOUND',\n\n /** Authentication required (401) */\n UNAUTHORIZED = 'UNAUTHORIZED',\n\n /** Access forbidden (403) */\n FORBIDDEN = 'FORBIDDEN',\n\n /** Resource conflict (409) */\n CONFLICT = 'CONFLICT',\n\n /** Rate limit exceeded (429) */\n RATE_LIMITED = 'RATE_LIMITED',\n\n /** Internal server error (500) */\n INTERNAL_SERVER_ERROR = 'INTERNAL_SERVER_ERROR',\n\n /** File/Request Too Large (413) */\n PAYLOAD_TOO_LARGE = 'PAYLOAD_TOO_LARGE',\n\n /** Wrong Content Type (415) */\n UNSUPPORTED_MEDIA_TYPE = 'UNSUPPORTED_MEDIA_TYPE',\n\n /** Upload Timeout (408) */\n UPLOAD_TIMEOUT = 'UPLOAD_TIMEOUT',\n\n /** Valid Format Invalid Semantics (422) */\n UNPROCESSABLE_ENTITY = 'UNPROCESSABLE_ENTITY',\n\n // Client-side errors\n /** Network connectivity failure (0) */\n NETWORK_ERROR = 'NETWORK_ERROR',\n\n /** Request or response timeout (0) */\n TIMEOUT_ERROR = 'TIMEOUT_ERROR',\n\n /** Response parsing failure (0) */\n PARSE_ERROR = 'PARSE_ERROR',\n\n /** Generic HTTP error (varies) */\n HTTP_ERROR = 'HTTP_ERROR',\n}\n\n/**\n * Error severity levels for logging and monitoring\n *\n * Provides a way to categorize errors by their impact and urgency.\n */\nexport enum ErrorSeverity {\n /** Low impact, often user errors */\n LOW = 'low',\n\n /** Medium impact, application errors */\n MEDIUM = 'medium',\n\n /** High impact, system errors */\n HIGH = 'high',\n\n /** Critical impact, service disruption */\n CRITICAL = 'critical',\n}\n\n/**\n * Abstract base class for all BlaizeJS errors\n *\n * This class provides the foundation for all error types in the BlaizeJS framework.\n * It extends JavaScript's built-in Error class and adds framework-specific properties\n * for consistent error handling across server and client.\n *\n * @example\n * ```typescript\n * import { ErrorType } from './types';\n *\n * class NotFoundError extends BlaizeError<{ resourceId: string }> {\n * constructor(message = 'Resource not found', details?: { resourceId: string }) {\n * super(ErrorType.NOT_FOUND, message, 404, getCurrentCorrelationId(), details);\n * }\n * }\n * ```\n *\n * @template TDetails - Type for error-specific details object\n */\nexport abstract class BlaizeError<TDetails = unknown> extends Error {\n /**\n * Error type identifier from the ErrorType enum\n * Used for programmatic error handling and client-side error routing\n */\n readonly type: ErrorType;\n\n /**\n * Human-readable error title/message\n * Should be descriptive enough for debugging but safe for end users\n */\n readonly title: string;\n\n /**\n * HTTP status code associated with this error\n * Used by the error boundary to set appropriate response status\n */\n readonly status: number;\n\n /**\n * Correlation ID for request tracing\n * Links this error to the specific request that generated it\n */\n readonly correlationId: string;\n\n /**\n * Timestamp when the error occurred\n * Useful for debugging and log correlation\n */\n readonly timestamp: Date;\n\n /**\n * Additional error-specific details\n * Type-safe error context that varies by error type\n */\n readonly details?: TDetails | undefined;\n\n /**\n * Creates a new BlaizeError instance\n *\n * @param type - Error type from the ErrorType enum\n * @param title - Human-readable error message\n * @param status - HTTP status code\n * @param correlationId - Request correlation ID for tracing\n * @param details - Optional error-specific details\n */\n protected constructor(\n type: ErrorType,\n title: string,\n status: number,\n correlationId: string,\n details?: TDetails | undefined\n ) {\n super(title);\n\n // Set the error name to the class name for better stack traces\n this.name = this.constructor.name;\n\n // Framework-specific properties\n this.type = type;\n this.title = title;\n this.status = status;\n this.correlationId = correlationId;\n this.timestamp = new Date();\n this.details = details;\n\n // Maintain proper prototype chain for instanceof checks\n Object.setPrototypeOf(this, new.target.prototype);\n\n // Capture stack trace if available (V8 feature)\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n }\n\n /**\n * Serializes the error to a plain object suitable for HTTP responses\n *\n * @returns Object representation of the error\n */\n toJSON() {\n const base = {\n type: this.type,\n title: this.title,\n status: this.status,\n correlationId: this.correlationId,\n timestamp: this.timestamp.toISOString(),\n };\n\n // Only include details if they are not undefined\n if (this.details !== undefined) {\n return { ...base, details: this.details };\n }\n\n return base;\n }\n\n /**\n * Returns a string representation of the error\n * Includes correlation ID for easier debugging\n */\n toString(): string {\n return `${this.name}: ${this.title} [${this.correlationId}]`;\n }\n}\n\n/**\n * Interface for payload too large error details\n */\nexport interface PayloadTooLargeErrorDetails {\n fileCount?: number;\n maxFiles?: number;\n filename?: string;\n field?: string;\n contentType?: string;\n currentSize?: number;\n maxSize?: number;\n}\n\n/**\n * Interface for unsupported media type error details\n */\nexport interface UnsupportedMediaTypeErrorDetails {\n receivedMimeType?: string;\n allowedMimeTypes?: string[];\n filename?: string;\n}\n\n/**\n * Interface for authentication error details\n */\nexport interface UnauthorizedErrorDetails {\n /** Reason for authentication failure */\n reason?:\n | 'missing_token'\n | 'invalid_token'\n | 'expired_token'\n | 'malformed_token'\n | 'insufficient_scope'\n | string;\n\n /** Authentication scheme (Bearer, Basic, etc.) */\n authScheme?: string;\n\n /** Authentication realm */\n realm?: string;\n\n /** Detailed error description */\n error_description?: string;\n\n /** Required scopes or permissions */\n requiredScopes?: string[];\n\n /** Login URL for interactive authentication */\n loginUrl?: string;\n\n /** Additional context */\n [key: string]: unknown;\n}\n\n/**\n * Interface for authorization/permission error details\n */\nexport interface ForbiddenErrorDetails {\n /** Required permission or role */\n requiredPermission?: string;\n\n /** User's current permissions */\n userPermissions?: string[];\n\n /** Resource being accessed */\n resource?: string;\n\n /** Action being attempted */\n action?: string;\n\n /** Reason for access denial */\n reason?: 'insufficient_permissions' | 'account_suspended' | 'resource_locked' | string;\n\n /** Additional context */\n [key: string]: unknown;\n}\n\n/**\n * Interface for resource conflict error details\n */\nexport interface ConflictErrorDetails {\n /** Type of conflict */\n conflictType?:\n | 'duplicate_key'\n | 'version_mismatch'\n | 'concurrent_modification'\n | 'business_rule'\n | string;\n\n /** Field that caused the conflict */\n field?: string;\n\n /** Existing value that conflicts */\n existingValue?: unknown;\n\n /** Provided value that conflicts */\n providedValue?: unknown;\n\n /** Resource that has the conflicting value */\n conflictingResource?: string;\n\n /** Current version/etag of the resource */\n currentVersion?: string;\n\n /** Expected version/etag */\n expectedVersion?: string;\n\n /** Suggested resolution */\n resolution?: string;\n\n /** Additional context */\n [key: string]: unknown;\n}\n\n/**\n * Interface for rate limiting error details\n */\nexport interface RateLimitErrorDetails {\n /** Maximum requests allowed in the time window */\n limit?: number;\n\n /** Remaining requests in current window */\n remaining?: number;\n\n /** When the rate limit resets */\n resetTime?: Date;\n\n /** Seconds until the rate limit resets */\n retryAfter?: number;\n\n /** Time window for the rate limit */\n window?: string;\n\n /** Identifier used for rate limiting (IP, user ID, etc.) */\n identifier?: string;\n\n /** Type of rate limit hit */\n limitType?: 'global' | 'per_user' | 'per_ip' | 'per_endpoint' | string;\n\n /** Additional context */\n [key: string]: unknown;\n}\n\n/**\n * Interface for internal server error details\n */\nexport interface InternalServerErrorDetails {\n /** Original error message (for debugging) */\n originalError?: string;\n\n /** Stack trace (for debugging) */\n stackTrace?: string;\n\n /** Component where the error occurred */\n component?: string;\n\n /** Operation being performed */\n operation?: string;\n\n /** Internal error code */\n internalErrorCode?: string;\n\n /** When the error occurred */\n timestamp?: Date;\n\n /** Whether this error should be retryable */\n retryable?: boolean;\n\n /** Additional debugging context */\n [key: string]: unknown;\n}\n\n/**\n * Interface for NotFound error details\n * Provides context about the missing resource\n */\nexport interface NotFoundErrorDetails {\n /** Type of resource that was not found */\n resourceType?: string;\n\n /** ID or identifier of the resource */\n resourceId?: string;\n\n /** Collection or table where the resource was searched */\n collection?: string;\n\n /** Search criteria that was used */\n query?: Record<string, unknown>;\n\n /** Search criteria that was used (for backward compatibility) */\n searchCriteria?: Record<string, unknown>;\n\n /** The path that was attempted */\n path?: string;\n\n /** HTTP method used (for API endpoints) */\n method?: string;\n\n /** The path that was attempted (for backward compatibility) */\n attemptedPath?: string;\n\n /** Parent resource information for nested resources */\n parentResource?: {\n type: string;\n id: string;\n };\n\n /** Helpful suggestion for the user */\n suggestion?: string;\n\n /** Additional context */\n [key: string]: unknown;\n}\n\n// TODO: This can potentiall be removed\n/**\n * Interface for body parsing errors stored in context state\n */\nexport interface BodyParseError {\n /**\n * Type of parsing error that occurred\n */\n readonly type:\n | 'json_parse_error'\n | 'form_parse_error'\n | 'multipart_parse_error'\n | 'body_read_error';\n\n /**\n * Human-readable error message\n */\n readonly message: string;\n\n /**\n * Original error object or details\n */\n readonly error: unknown;\n}\n\n/**\n * Type guard to check if an object is a BodyParseError\n */\nexport function isBodyParseError(error: unknown): error is BodyParseError {\n return (\n typeof error === 'object' &&\n error !== null &&\n 'type' in error &&\n 'message' in error &&\n 'error' in error &&\n typeof (error as any).type === 'string' &&\n typeof (error as any).message === 'string'\n );\n}\n\n/**\n * Context information for error transformation\n */\nexport interface ErrorTransformContext {\n url: string;\n method: string;\n correlationId: string;\n timeoutMs?: number;\n elapsedMs?: number;\n statusCode?: number;\n contentType?: string;\n responseSample?: string;\n [key: string]: unknown;\n}\n","/**\n * Correlation ID system for request tracing across async operations\n *\n * This module provides utilities for generating, storing, and accessing\n * correlation IDs that follow requests through the entire application stack.\n * Uses AsyncLocalStorage for automatic context propagation.\n */\n\nimport { AsyncLocalStorage } from 'node:async_hooks';\n\n/**\n * AsyncLocalStorage instance for storing correlation IDs\n * Separate from the main context storage to allow independent lifecycle management\n */\nconst correlationStorage = new AsyncLocalStorage<string>();\n\n/**\n * Generates a new unique correlation ID\n *\n * Format: req_[timestamp_base36]_[random_base36]\n * Example: req_k3x2m1_9z8y7w6v\n *\n * @returns A unique correlation ID string\n */\nexport function generateCorrelationId(): string {\n const timestamp = Date.now().toString(36); // Base36 encoded timestamp\n const random = Math.random().toString(36).substr(2, 9); // Base36 random string\n return `req_${timestamp}_${random}`;\n}\n\n/**\n * Gets the current correlation ID from AsyncLocalStorage\n *\n * @returns The current correlation ID, or 'unknown' if none is set\n */\nexport function getCurrentCorrelationId(): string {\n const stored = correlationStorage.getStore();\n return stored && stored.trim() ? stored : 'unknown';\n}\n\n/**\n * Sets the correlation ID in the current AsyncLocalStorage context\n *\n * This will affect the current execution context and any subsequent\n * async operations that inherit from it.\n *\n * @param correlationId - The correlation ID to set\n */\nexport function setCorrelationId(correlationId: string): void {\n correlationStorage.enterWith(correlationId);\n}\n\n/**\n * Runs a function with a specific correlation ID\n *\n * Creates a new AsyncLocalStorage context with the provided correlation ID.\n * The correlation ID will be available to the function and any async operations\n * it spawns, but will not affect the parent context.\n *\n * @param correlationId - The correlation ID to use for this context\n * @param fn - The function to run with the correlation ID\n * @returns The result of the function\n *\n * @example\n * ```typescript\n * const result = await withCorrelationId('req_123', async () => {\n * console.log(getCurrentCorrelationId()); // 'req_123'\n * return await processRequest();\n * });\n * ```\n */\nexport function withCorrelationId<T>(\n correlationId: string,\n fn: () => T | Promise<T>\n): T | Promise<T> {\n return correlationStorage.run(correlationId, fn);\n}\n\n/**\n * Extracts correlation ID from headers or generates a new one\n *\n * Looks for the 'x-correlation-id' header and uses it if present.\n * If not found, empty, or undefined, generates a new correlation ID.\n *\n * @param headers - HTTP headers object\n * @returns A correlation ID (either from headers or newly generated)\n *\n * @example\n * ```typescript\n * // From incoming request headers\n * const correlationId = getOrGenerateCorrelationId(request.headers);\n *\n * // Use in request processing\n * await withCorrelationId(correlationId, async () => {\n * // Process request with correlation tracking\n * });\n * ```\n */\nexport function getOrGenerateCorrelationId(headers: Record<string, string | undefined>): string {\n const headerCorrelationId = headers['x-correlation-id'];\n\n // Use header value if it exists and is not empty\n if (headerCorrelationId && headerCorrelationId.trim()) {\n return headerCorrelationId;\n }\n\n // Generate new correlation ID if header is missing or empty\n return generateCorrelationId();\n}\n\n/**\n * Creates a middleware function for setting correlation ID from request headers\n *\n * This is a utility for integrating correlation ID handling into the middleware stack.\n * It extracts or generates a correlation ID and sets it for the request processing.\n *\n * @returns Middleware function that sets correlation ID\n *\n * @example\n * ```typescript\n * import { createServer } from 'blaizejs';\n * import { createCorrelationMiddleware } from './correlation';\n *\n * const server = createServer({\n * middleware: [\n * createCorrelationMiddleware(),\n * // ... other middleware\n * ]\n * });\n * ```\n */\nexport function createCorrelationMiddleware() {\n return {\n name: 'correlation',\n execute: async (context: any, next: () => Promise<void>) => {\n // Extract headers from context (adapting to BlaizeJS context structure)\n const headers = context.request.headers();\n const correlationId = getOrGenerateCorrelationId(headers);\n\n // Set correlation ID and process request\n await withCorrelationId(correlationId, next);\n },\n debug: () => ({ stage: 'correlation-id-setup' }),\n };\n}\n\n/**\n * Type-safe wrapper for functions that need correlation ID context\n *\n * Ensures that a function always has access to a correlation ID,\n * either from the current context or by generating a new one.\n *\n * @param fn - Function that requires correlation ID context\n * @returns Wrapped function that guarantees correlation ID availability\n */\nexport function withEnsuredCorrelation<T extends any[], R>(\n fn: (...args: T) => R | Promise<R>\n): (...args: T) => R | Promise<R> {\n return (...args: T): R | Promise<R> => {\n const currentCorrelationId = getCurrentCorrelationId();\n\n // If we already have a correlation ID, just run the function\n if (currentCorrelationId !== 'unknown') {\n return fn(...args);\n }\n\n // Generate new correlation ID and run function in that context\n const newCorrelationId = generateCorrelationId();\n return withCorrelationId(newCorrelationId, () => fn(...args));\n };\n}\n\n/**\n * Debugging utility to get correlation storage information\n *\n * @internal This is for debugging purposes only\n */\nexport function _getCorrelationStorageInfo() {\n return {\n hasActiveStore: correlationStorage.getStore() !== undefined,\n currentCorrelationId: correlationStorage.getStore() ?? null,\n };\n}\n"],"mappings":";;;;;;;;;kwBA2MO,IAAKA,OAGVA,EAAA,iBAAmB,mBAGnBA,EAAA,UAAY,YAGZA,EAAA,aAAe,eAGfA,EAAA,UAAY,YAGZA,EAAA,SAAW,WAGXA,EAAA,aAAe,eAGfA,EAAA,sBAAwB,wBAGxBA,EAAA,kBAAoB,oBAGpBA,EAAA,uBAAyB,yBAGzBA,EAAA,eAAiB,iBAGjBA,EAAA,qBAAuB,uBAIvBA,EAAA,cAAgB,gBAGhBA,EAAA,cAAgB,gBAGhBA,EAAA,YAAc,cAGdA,EAAA,WAAa,aA9CHA,OAAA,IAsDAC,OAEVA,EAAA,IAAM,MAGNA,EAAA,OAAS,SAGTA,EAAA,KAAO,OAGPA,EAAA,SAAW,WAXDA,OAAA,IAkCUC,EAAf,cAAuD,KAAM,CAKzD,KAMA,MAMA,OAMA,cAMA,UAMA,QAWC,YACRC,EACAC,EACAC,EACAC,EACAC,EACA,CACA,MAAMH,CAAK,EAGX,KAAK,KAAO,KAAK,YAAY,KAG7B,KAAK,KAAOD,EACZ,KAAK,MAAQC,EACb,KAAK,OAASC,EACd,KAAK,cAAgBC,EACrB,KAAK,UAAY,IAAI,KACrB,KAAK,QAAUC,EAGf,OAAO,eAAe,KAAM,WAAW,SAAS,EAG5C,MAAM,mBACR,MAAM,kBAAkB,KAAM,KAAK,WAAW,CAElD,CAOA,QAAS,CACP,IAAMC,EAAO,CACX,KAAM,KAAK,KACX,MAAO,KAAK,MACZ,OAAQ,KAAK,OACb,cAAe,KAAK,cACpB,UAAW,KAAK,UAAU,YAAY,CACxC,EAGA,OAAI,KAAK,UAAY,OACZ,CAAE,GAAGA,EAAM,QAAS,KAAK,OAAQ,EAGnCA,CACT,CAMA,UAAmB,CACjB,MAAO,GAAG,KAAK,IAAI,KAAK,KAAK,KAAK,KAAK,KAAK,aAAa,GAC3D,CACF,EAoPO,SAASC,EAAiBC,EAAyC,CACxE,OACE,OAAOA,GAAU,UACjBA,IAAU,MACV,SAAUA,GACV,YAAaA,GACb,UAAWA,GACX,OAAQA,EAAc,MAAS,UAC/B,OAAQA,EAAc,SAAY,QAEtC,CCjoBA,OAAS,qBAAAC,MAAyB,mBAMlC,IAAMC,EAAqB,IAAID,EAUxB,SAASE,GAAgC,CAC9C,IAAMC,EAAY,KAAK,IAAI,EAAE,SAAS,EAAE,EAClCC,EAAS,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE,OAAO,EAAG,CAAC,EACrD,MAAO,OAAOD,CAAS,IAAIC,CAAM,EACnC,CAOO,SAASC,GAAkC,CAChD,IAAMC,EAASL,EAAmB,SAAS,EAC3C,OAAOK,GAAUA,EAAO,KAAK,EAAIA,EAAS,SAC5C","names":["ErrorType","ErrorSeverity","BlaizeError","type","title","status","correlationId","details","base","isBodyParseError","error","AsyncLocalStorage","correlationStorage","generateCorrelationId","timestamp","random","getCurrentCorrelationId","stored"]}
1
+ {"version":3,"sources":["../../blaize-types/src/errors.ts","../src/errors/correlation.ts"],"sourcesContent":["/**\n * Error type definitions and interfaces for the BlaizeJS framework\n *\n * This module contains all the type definitions used for error handling\n * across the BlaizeJS framework, including server-side errors, client-side\n * errors, and HTTP response formats.\n */\n\n/**\n * Structure of error responses sent over HTTP\n *\n * This interface defines the JSON format used for all error responses\n * from BlaizeJS servers. It matches the structure returned by BlaizeError.toJSON()\n *\n * @example\n * ```json\n * {\n * \"type\": \"VALIDATION_ERROR\",\n * \"title\": \"Request validation failed\",\n * \"status\": 400,\n * \"correlationId\": \"req_abc123\",\n * \"timestamp\": \"2024-01-15T10:30:00.000Z\",\n * \"details\": {\n * \"fields\": [\"email\", \"password\"]\n * }\n * }\n * ```\n */\nexport interface BlaizeErrorResponse {\n /** Error type from the ErrorType enum */\n type: ErrorType;\n\n /** Human-readable error message */\n title: string;\n\n /** HTTP status code */\n status: number;\n\n /** Correlation ID for request tracing */\n correlationId: string;\n\n /** ISO timestamp when error occurred */\n timestamp: string;\n\n /** Optional error-specific details */\n details?: unknown;\n}\n\n/**\n * Context information for network-related errors\n *\n * Used by client-side error classes to provide additional context\n * about network failures, timeouts, and connection issues.\n */\nexport interface NetworkErrorContext {\n /** The URL that failed */\n url: string;\n\n /** HTTP method being attempted */\n method: string;\n\n /** Correlation ID for tracing */\n correlationId: string;\n\n /** Timeout value if applicable */\n timeout?: number;\n\n /** The original error that caused the network failure */\n originalError: Error;\n\n /** Additional network-specific details */\n networkDetails?: {\n /** Whether this was a connection timeout */\n isTimeout?: boolean;\n\n /** Whether this was a DNS resolution failure */\n isDnsFailure?: boolean;\n\n /** Whether this was a connection refused error */\n isConnectionRefused?: boolean;\n\n /** HTTP status code if received before failure */\n statusCode?: number;\n };\n}\n\n/**\n * Context information for request timeout errors\n *\n * Specialized context for timeout-specific errors with timing information.\n */\nexport interface TimeoutErrorContext {\n /** The URL that timed out */\n url: string;\n\n /** HTTP method being attempted */\n method: string;\n\n /** Correlation ID for tracing */\n correlationId: string;\n\n /** Configured timeout value in milliseconds */\n timeoutMs: number;\n\n /** Actual duration before timeout in milliseconds */\n elapsedMs: number;\n\n /** Type of timeout (request, connection, etc.) */\n timeoutType: 'request' | 'connection' | 'response' | 'idle';\n}\n\n/**\n * Context information for response parsing errors\n *\n * Used when the client receives a response but cannot parse it properly.\n */\nexport interface ParseErrorContext {\n /** The URL that returned unparseable content */\n url: string;\n\n /** HTTP method used */\n method: string;\n\n /** Correlation ID for tracing */\n correlationId: string;\n\n /** HTTP status code received */\n statusCode: number;\n\n /** Content-Type header if available */\n contentType?: string;\n\n /** Expected response format */\n expectedFormat: 'json' | 'text' | 'binary';\n\n /** Sample of the actual response content (truncated for safety) */\n responseSample?: string;\n\n /** The original parsing error */\n originalError: Error;\n}\n\n/**\n * Validation error field details\n *\n * Structure for field-level validation errors with multiple error messages\n * per field.\n */\nexport interface ValidationFieldError {\n /** Field name or path (e.g., \"email\", \"user.profile.name\") */\n field: string;\n\n /** Array of error messages for this field */\n messages: string[];\n\n /** The invalid value that caused the error */\n rejectedValue?: unknown;\n\n /** Expected type or format */\n expectedType?: string;\n}\n\n/**\n * Validation error details structure\n *\n * Used by ValidationError to provide structured information about\n * what fields failed validation and why.\n */\nexport interface ValidationErrorDetails {\n /** Array of field-level errors */\n fields: ValidationFieldError[];\n\n /** Total number of validation errors */\n errorCount: number;\n\n /** The section that failed validation */\n section: 'params' | 'query' | 'body' | 'response';\n\n /** Schema name if available */\n schemaName?: string;\n}\n\n/**\n * All available error types in the BlaizeJS framework\n *\n * This enum provides both compile-time type safety and runtime values\n * for error type identification across server and client packages.\n *\n * @example Type-safe error handling:\n * ```typescript\n * function handleError(errorType: ErrorType) {\n * switch (errorType) {\n * case ErrorType.VALIDATION_ERROR:\n * // Handle validation error\n * break;\n * case ErrorType.NOT_FOUND:\n * // Handle not found error\n * break;\n * // TypeScript ensures all cases are covered\n * }\n * }\n * ```\n */\nexport enum ErrorType {\n // Server-side business logic errors\n /** Request validation failed (400) */\n VALIDATION_ERROR = 'VALIDATION_ERROR',\n\n /** Resource not found (404) */\n NOT_FOUND = 'NOT_FOUND',\n\n /** Authentication required (401) */\n UNAUTHORIZED = 'UNAUTHORIZED',\n\n /** Access forbidden (403) */\n FORBIDDEN = 'FORBIDDEN',\n\n /** Resource conflict (409) */\n CONFLICT = 'CONFLICT',\n\n /** Rate limit exceeded (429) */\n RATE_LIMITED = 'RATE_LIMITED',\n\n /** Internal server error (500) */\n INTERNAL_SERVER_ERROR = 'INTERNAL_SERVER_ERROR',\n\n /** File/Request Too Large (413) */\n PAYLOAD_TOO_LARGE = 'PAYLOAD_TOO_LARGE',\n\n /** Wrong Content Type (415) */\n UNSUPPORTED_MEDIA_TYPE = 'UNSUPPORTED_MEDIA_TYPE',\n\n /** Upload Timeout (408) */\n UPLOAD_TIMEOUT = 'UPLOAD_TIMEOUT',\n\n /** Valid Format Invalid Semantics (422) */\n UNPROCESSABLE_ENTITY = 'UNPROCESSABLE_ENTITY',\n\n // Client-side errors\n /** Network connectivity failure (0) */\n NETWORK_ERROR = 'NETWORK_ERROR',\n\n /** Request or response timeout (0) */\n TIMEOUT_ERROR = 'TIMEOUT_ERROR',\n\n /** Response parsing failure (0) */\n PARSE_ERROR = 'PARSE_ERROR',\n\n /** Generic HTTP error (varies) */\n HTTP_ERROR = 'HTTP_ERROR',\n}\n\n/**\n * Error severity levels for logging and monitoring\n *\n * Provides a way to categorize errors by their impact and urgency.\n */\nexport enum ErrorSeverity {\n /** Low impact, often user errors */\n LOW = 'low',\n\n /** Medium impact, application errors */\n MEDIUM = 'medium',\n\n /** High impact, system errors */\n HIGH = 'high',\n\n /** Critical impact, service disruption */\n CRITICAL = 'critical',\n}\n\n/**\n * Abstract base class for all BlaizeJS errors\n *\n * This class provides the foundation for all error types in the BlaizeJS framework.\n * It extends JavaScript's built-in Error class and adds framework-specific properties\n * for consistent error handling across server and client.\n *\n * @example\n * ```typescript\n * import { ErrorType } from './types';\n *\n * class NotFoundError extends BlaizeError<{ resourceId: string }> {\n * constructor(message = 'Resource not found', details?: { resourceId: string }) {\n * super(ErrorType.NOT_FOUND, message, 404, getCurrentCorrelationId(), details);\n * }\n * }\n * ```\n *\n * @template TDetails - Type for error-specific details object\n */\nexport abstract class BlaizeError<TDetails = unknown> extends Error {\n /**\n * Error type identifier from the ErrorType enum\n * Used for programmatic error handling and client-side error routing\n */\n readonly type: ErrorType;\n\n /**\n * Human-readable error title/message\n * Should be descriptive enough for debugging but safe for end users\n */\n readonly title: string;\n\n /**\n * HTTP status code associated with this error\n * Used by the error boundary to set appropriate response status\n */\n readonly status: number;\n\n /**\n * Correlation ID for request tracing\n * Links this error to the specific request that generated it\n */\n readonly correlationId: string;\n\n /**\n * Timestamp when the error occurred\n * Useful for debugging and log correlation\n */\n readonly timestamp: Date;\n\n /**\n * Additional error-specific details\n * Type-safe error context that varies by error type\n */\n readonly details?: TDetails | undefined;\n\n /**\n * Creates a new BlaizeError instance\n *\n * @param type - Error type from the ErrorType enum\n * @param title - Human-readable error message\n * @param status - HTTP status code\n * @param correlationId - Request correlation ID for tracing\n * @param details - Optional error-specific details\n */\n protected constructor(\n type: ErrorType,\n title: string,\n status: number,\n correlationId: string,\n details?: TDetails | undefined\n ) {\n super(title);\n\n // Set the error name to the class name for better stack traces\n this.name = this.constructor.name;\n\n // Framework-specific properties\n this.type = type;\n this.title = title;\n this.status = status;\n this.correlationId = correlationId;\n this.timestamp = new Date();\n this.details = details;\n\n // Maintain proper prototype chain for instanceof checks\n Object.setPrototypeOf(this, new.target.prototype);\n\n // Capture stack trace if available (V8 feature)\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n }\n\n /**\n * Serializes the error to a plain object suitable for HTTP responses\n *\n * @returns Object representation of the error\n */\n toJSON() {\n const base = {\n type: this.type,\n title: this.title,\n status: this.status,\n correlationId: this.correlationId,\n timestamp: this.timestamp.toISOString(),\n };\n\n // Only include details if they are not undefined\n if (this.details !== undefined) {\n return { ...base, details: this.details };\n }\n\n return base;\n }\n\n /**\n * Returns a string representation of the error\n * Includes correlation ID for easier debugging\n */\n toString(): string {\n return `${this.name}: ${this.title} [${this.correlationId}]`;\n }\n}\n\n/**\n * Interface for payload too large error details\n */\nexport interface PayloadTooLargeErrorDetails {\n fileCount?: number;\n maxFiles?: number;\n filename?: string;\n field?: string;\n contentType?: string;\n currentSize?: number;\n maxSize?: number;\n}\n\n/**\n * Interface for unsupported media type error details\n */\nexport interface UnsupportedMediaTypeErrorDetails {\n receivedMimeType?: string;\n allowedMimeTypes?: string[];\n filename?: string;\n}\n\n/**\n * Interface for authentication error details\n */\nexport interface UnauthorizedErrorDetails {\n /** Reason for authentication failure */\n reason?:\n | 'missing_token'\n | 'invalid_token'\n | 'expired_token'\n | 'malformed_token'\n | 'insufficient_scope'\n | string;\n\n /** Authentication scheme (Bearer, Basic, etc.) */\n authScheme?: string;\n\n /** Authentication realm */\n realm?: string;\n\n /** Detailed error description */\n error_description?: string;\n\n /** Required scopes or permissions */\n requiredScopes?: string[];\n\n /** Login URL for interactive authentication */\n loginUrl?: string;\n\n /** Additional context */\n [key: string]: unknown;\n}\n\n/**\n * Interface for authorization/permission error details\n */\nexport interface ForbiddenErrorDetails {\n /** Required permission or role */\n requiredPermission?: string;\n\n /** User's current permissions */\n userPermissions?: string[];\n\n /** Resource being accessed */\n resource?: string;\n\n /** Action being attempted */\n action?: string;\n\n /** Reason for access denial */\n reason?: 'insufficient_permissions' | 'account_suspended' | 'resource_locked' | string;\n\n /** Additional context */\n [key: string]: unknown;\n}\n\n/**\n * Interface for resource conflict error details\n */\nexport interface ConflictErrorDetails {\n /** Type of conflict */\n conflictType?:\n | 'duplicate_key'\n | 'version_mismatch'\n | 'concurrent_modification'\n | 'business_rule'\n | string;\n\n /** Field that caused the conflict */\n field?: string;\n\n /** Existing value that conflicts */\n existingValue?: unknown;\n\n /** Provided value that conflicts */\n providedValue?: unknown;\n\n /** Resource that has the conflicting value */\n conflictingResource?: string;\n\n /** Current version/etag of the resource */\n currentVersion?: string;\n\n /** Expected version/etag */\n expectedVersion?: string;\n\n /** Suggested resolution */\n resolution?: string;\n\n /** Additional context */\n [key: string]: unknown;\n}\n\n/**\n * Interface for rate limiting error details\n */\nexport interface RateLimitErrorDetails {\n /** Maximum requests allowed in the time window */\n limit?: number;\n\n /** Remaining requests in current window */\n remaining?: number;\n\n /** When the rate limit resets */\n resetTime?: Date;\n\n /** Seconds until the rate limit resets */\n retryAfter?: number;\n\n /** Time window for the rate limit */\n window?: string;\n\n /** Identifier used for rate limiting (IP, user ID, etc.) */\n identifier?: string;\n\n /** Type of rate limit hit */\n limitType?: 'global' | 'per_user' | 'per_ip' | 'per_endpoint' | string;\n\n /** Additional context */\n [key: string]: unknown;\n}\n\n/**\n * Interface for internal server error details\n */\nexport interface InternalServerErrorDetails {\n /** Original error message (for debugging) */\n originalError?: string;\n\n /** Stack trace (for debugging) */\n stackTrace?: string;\n\n /** Component where the error occurred */\n component?: string;\n\n /** Operation being performed */\n operation?: string;\n\n /** Internal error code */\n internalErrorCode?: string;\n\n /** When the error occurred */\n timestamp?: Date;\n\n /** Whether this error should be retryable */\n retryable?: boolean;\n\n /** Additional debugging context */\n [key: string]: unknown;\n}\n\n/**\n * Interface for NotFound error details\n * Provides context about the missing resource\n */\nexport interface NotFoundErrorDetails {\n /** Type of resource that was not found */\n resourceType?: string;\n\n /** ID or identifier of the resource */\n resourceId?: string;\n\n /** Collection or table where the resource was searched */\n collection?: string;\n\n /** Search criteria that was used */\n query?: Record<string, unknown>;\n\n /** Search criteria that was used (for backward compatibility) */\n searchCriteria?: Record<string, unknown>;\n\n /** The path that was attempted */\n path?: string;\n\n /** HTTP method used (for API endpoints) */\n method?: string;\n\n /** The path that was attempted (for backward compatibility) */\n attemptedPath?: string;\n\n /** Parent resource information for nested resources */\n parentResource?: {\n type: string;\n id: string;\n };\n\n /** Helpful suggestion for the user */\n suggestion?: string;\n\n /** Additional context */\n [key: string]: unknown;\n}\n\n// TODO: This can potentiall be removed\n/**\n * Interface for body parsing errors stored in context state\n */\nexport interface BodyParseError {\n /**\n * Type of parsing error that occurred\n */\n readonly type:\n | 'json_parse_error'\n | 'form_parse_error'\n | 'multipart_parse_error'\n | 'body_read_error';\n\n /**\n * Human-readable error message\n */\n readonly message: string;\n\n /**\n * Original error object or details\n */\n readonly error: unknown;\n}\n\n/**\n * Type guard to check if an object is a BodyParseError\n */\nexport function isBodyParseError(error: unknown): error is BodyParseError {\n return (\n typeof error === 'object' &&\n error !== null &&\n 'type' in error &&\n 'message' in error &&\n 'error' in error &&\n typeof (error as any).type === 'string' &&\n typeof (error as any).message === 'string'\n );\n}\n\n/**\n * Context information for error transformation\n */\nexport interface ErrorTransformContext {\n url: string;\n method: string;\n correlationId: string;\n timeoutMs?: number;\n elapsedMs?: number;\n statusCode?: number;\n contentType?: string;\n responseSample?: string;\n [key: string]: unknown;\n}\n","/**\n * Correlation ID system for request tracing across async operations\n *\n * This module provides utilities for generating, storing, and accessing\n * correlation IDs that follow requests through the entire application stack.\n * Uses AsyncLocalStorage for automatic context propagation.\n */\n\nimport { AsyncLocalStorage } from 'node:async_hooks';\n\n/**\n * AsyncLocalStorage instance for storing correlation IDs\n * Separate from the main context storage to allow independent lifecycle management\n */\nconst correlationStorage = new AsyncLocalStorage<string>();\n\n/**\n * Generates a new unique correlation ID\n *\n * Format: req_[timestamp_base36]_[random_base36]\n * Example: req_k3x2m1_9z8y7w6v\n *\n * @returns A unique correlation ID string\n */\nexport function generateCorrelationId(): string {\n const timestamp = Date.now().toString(36); // Base36 encoded timestamp\n const random = Math.random().toString(36).substr(2, 9); // Base36 random string\n return `req_${timestamp}_${random}`;\n}\n\n/**\n * Gets the current correlation ID from AsyncLocalStorage\n *\n * @returns The current correlation ID, or 'unknown' if none is set\n */\nexport function getCurrentCorrelationId(): string {\n const stored = correlationStorage.getStore();\n return stored && stored.trim() ? stored : 'unknown';\n}\n\n/**\n * Sets the correlation ID in the current AsyncLocalStorage context\n *\n * This will affect the current execution context and any subsequent\n * async operations that inherit from it.\n *\n * @param correlationId - The correlation ID to set\n */\nexport function setCorrelationId(correlationId: string): void {\n correlationStorage.enterWith(correlationId);\n}\n\n/**\n * Runs a function with a specific correlation ID\n *\n * Creates a new AsyncLocalStorage context with the provided correlation ID.\n * The correlation ID will be available to the function and any async operations\n * it spawns, but will not affect the parent context.\n *\n * @param correlationId - The correlation ID to use for this context\n * @param fn - The function to run with the correlation ID\n * @returns The result of the function\n *\n * @example\n * ```typescript\n * const result = await withCorrelationId('req_123', async () => {\n * console.log(getCurrentCorrelationId()); // 'req_123'\n * return await processRequest();\n * });\n * ```\n */\nexport function withCorrelationId<T>(\n correlationId: string,\n fn: () => T | Promise<T>\n): T | Promise<T> {\n return correlationStorage.run(correlationId, fn);\n}\n\n/**\n * Extracts correlation ID from headers or generates a new one\n *\n * Looks for the 'x-correlation-id' header and uses it if present.\n * If not found, empty, or undefined, generates a new correlation ID.\n *\n * @param headers - HTTP headers object\n * @returns A correlation ID (either from headers or newly generated)\n *\n * @example\n * ```typescript\n * // From incoming request headers\n * const correlationId = getOrGenerateCorrelationId(request.headers);\n *\n * // Use in request processing\n * await withCorrelationId(correlationId, async () => {\n * // Process request with correlation tracking\n * });\n * ```\n */\nexport function getOrGenerateCorrelationId(headers: Record<string, string | undefined>): string {\n const headerCorrelationId = headers['x-correlation-id'];\n\n // Use header value if it exists and is not empty\n if (headerCorrelationId && headerCorrelationId.trim()) {\n return headerCorrelationId;\n }\n\n // Generate new correlation ID if header is missing or empty\n return generateCorrelationId();\n}\n\n/**\n * Creates a middleware function for setting correlation ID from request headers\n *\n * This is a utility for integrating correlation ID handling into the middleware stack.\n * It extracts or generates a correlation ID and sets it for the request processing.\n *\n * @returns Middleware function that sets correlation ID\n *\n * @example\n * ```typescript\n * import { createServer } from 'blaizejs';\n * import { createCorrelationMiddleware } from './correlation';\n *\n * const server = createServer({\n * middleware: [\n * createCorrelationMiddleware(),\n * // ... other middleware\n * ]\n * });\n * ```\n */\nexport function createCorrelationMiddleware() {\n return {\n name: 'correlation',\n execute: async (context: any, next: () => Promise<void>) => {\n // Extract headers from context (adapting to BlaizeJS context structure)\n const headers = context.request.headers();\n const correlationId = getOrGenerateCorrelationId(headers);\n\n // Set correlation ID and process request\n await withCorrelationId(correlationId, next);\n },\n debug: () => ({ stage: 'correlation-id-setup' }),\n };\n}\n\n/**\n * Type-safe wrapper for functions that need correlation ID context\n *\n * Ensures that a function always has access to a correlation ID,\n * either from the current context or by generating a new one.\n *\n * @param fn - Function that requires correlation ID context\n * @returns Wrapped function that guarantees correlation ID availability\n */\nexport function withEnsuredCorrelation<T extends any[], R>(\n fn: (...args: T) => R | Promise<R>\n): (...args: T) => R | Promise<R> {\n return (...args: T): R | Promise<R> => {\n const currentCorrelationId = getCurrentCorrelationId();\n\n // If we already have a correlation ID, just run the function\n if (currentCorrelationId !== 'unknown') {\n return fn(...args);\n }\n\n // Generate new correlation ID and run function in that context\n const newCorrelationId = generateCorrelationId();\n return withCorrelationId(newCorrelationId, () => fn(...args));\n };\n}\n\n/**\n * Debugging utility to get correlation storage information\n *\n * @internal This is for debugging purposes only\n */\nexport function _getCorrelationStorageInfo() {\n return {\n hasActiveStore: correlationStorage.getStore() !== undefined,\n currentCorrelationId: correlationStorage.getStore() ?? null,\n };\n}\n"],"mappings":";;;;;;;;;yPA2MO,IAAKA,OAGVA,EAAA,iBAAmB,mBAGnBA,EAAA,UAAY,YAGZA,EAAA,aAAe,eAGfA,EAAA,UAAY,YAGZA,EAAA,SAAW,WAGXA,EAAA,aAAe,eAGfA,EAAA,sBAAwB,wBAGxBA,EAAA,kBAAoB,oBAGpBA,EAAA,uBAAyB,yBAGzBA,EAAA,eAAiB,iBAGjBA,EAAA,qBAAuB,uBAIvBA,EAAA,cAAgB,gBAGhBA,EAAA,cAAgB,gBAGhBA,EAAA,YAAc,cAGdA,EAAA,WAAa,aA9CHA,OAAA,IAsDAC,OAEVA,EAAA,IAAM,MAGNA,EAAA,OAAS,SAGTA,EAAA,KAAO,OAGPA,EAAA,SAAW,WAXDA,OAAA,IAkCUC,EAAf,cAAuD,KAAM,CAKzD,KAMA,MAMA,OAMA,cAMA,UAMA,QAWC,YACRC,EACAC,EACAC,EACAC,EACAC,EACA,CACA,MAAMH,CAAK,EAGX,KAAK,KAAO,KAAK,YAAY,KAG7B,KAAK,KAAOD,EACZ,KAAK,MAAQC,EACb,KAAK,OAASC,EACd,KAAK,cAAgBC,EACrB,KAAK,UAAY,IAAI,KACrB,KAAK,QAAUC,EAGf,OAAO,eAAe,KAAM,WAAW,SAAS,EAG5C,MAAM,mBACR,MAAM,kBAAkB,KAAM,KAAK,WAAW,CAElD,CAOA,QAAS,CACP,IAAMC,EAAO,CACX,KAAM,KAAK,KACX,MAAO,KAAK,MACZ,OAAQ,KAAK,OACb,cAAe,KAAK,cACpB,UAAW,KAAK,UAAU,YAAY,CACxC,EAGA,OAAI,KAAK,UAAY,OACZ,CAAE,GAAGA,EAAM,QAAS,KAAK,OAAQ,EAGnCA,CACT,CAMA,UAAmB,CACjB,MAAO,GAAG,KAAK,IAAI,KAAK,KAAK,KAAK,KAAK,KAAK,aAAa,GAC3D,CACF,EAoPO,SAASC,EAAiBC,EAAyC,CACxE,OACE,OAAOA,GAAU,UACjBA,IAAU,MACV,SAAUA,GACV,YAAaA,GACb,UAAWA,GACX,OAAQA,EAAc,MAAS,UAC/B,OAAQA,EAAc,SAAY,QAEtC,CCjoBA,OAAS,qBAAAC,MAAyB,mBAMlC,IAAMC,EAAqB,IAAID,EAUxB,SAASE,GAAgC,CAC9C,IAAMC,EAAY,KAAK,IAAI,EAAE,SAAS,EAAE,EAClCC,EAAS,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE,OAAO,EAAG,CAAC,EACrD,MAAO,OAAOD,CAAS,IAAIC,CAAM,EACnC,CAOO,SAASC,GAAkC,CAChD,IAAMC,EAASL,EAAmB,SAAS,EAC3C,OAAOK,GAAUA,EAAO,KAAK,EAAIA,EAAS,SAC5C","names":["ErrorType","ErrorSeverity","BlaizeError","type","title","status","correlationId","details","base","isBodyParseError","error","AsyncLocalStorage","correlationStorage","generateCorrelationId","timestamp","random","getCurrentCorrelationId","stored"]}
@@ -1,11 +1,11 @@
1
1
 
2
2
  /**
3
- * blaizejs v0.3.3
3
+ * blaizejs v0.3.4
4
4
  * A blazing-fast, TypeScript-first Node.js framework with HTTP/2 support, file-based routing, powerful middleware system, and end-to-end type safety for building modern APIs.
5
5
  *
6
6
  * Copyright (c) 2025 BlaizeJS Contributors
7
7
  * @license MIT
8
8
  */
9
9
 
10
- import{f as r,i as o}from"./chunk-KE2IOPV4.js";var e=class extends r{constructor(t,a,i){super("PAYLOAD_TOO_LARGE",t,413,i??o(),a)}};export{e as a};
11
- //# sourceMappingURL=chunk-LY65OJH4.js.map
10
+ import{d as r,g as o}from"./chunk-DTDGIBMA.js";var e=class extends r{constructor(t,a,i){super("PAYLOAD_TOO_LARGE",t,413,i??o(),a)}};export{e as a};
11
+ //# sourceMappingURL=chunk-EE2VJ6JY.js.map
@@ -1,11 +1,11 @@
1
1
 
2
2
  /**
3
- * blaizejs v0.3.3
3
+ * blaizejs v0.3.4
4
4
  * A blazing-fast, TypeScript-first Node.js framework with HTTP/2 support, file-based routing, powerful middleware system, and end-to-end type safety for building modern APIs.
5
5
  *
6
6
  * Copyright (c) 2025 BlaizeJS Contributors
7
7
  * @license MIT
8
8
  */
9
9
 
10
- import{f as r,i as e}from"./chunk-KE2IOPV4.js";var t=class extends r{constructor(n,o=void 0,i=void 0){super("INTERNAL_SERVER_ERROR",n,500,i??e(),o)}};export{t as a};
11
- //# sourceMappingURL=chunk-VM3QGHVO.js.map
10
+ import{d as r,g as e}from"./chunk-DTDGIBMA.js";var t=class extends r{constructor(n,o=void 0,i=void 0){super("INTERNAL_SERVER_ERROR",n,500,i??e(),o)}};export{t as a};
11
+ //# sourceMappingURL=chunk-HSLLYUVO.js.map
@@ -1,11 +1,11 @@
1
1
 
2
2
  /**
3
- * blaizejs v0.3.3
3
+ * blaizejs v0.3.4
4
4
  * A blazing-fast, TypeScript-first Node.js framework with HTTP/2 support, file-based routing, powerful middleware system, and end-to-end type safety for building modern APIs.
5
5
  *
6
6
  * Copyright (c) 2025 BlaizeJS Contributors
7
7
  * @license MIT
8
8
  */
9
9
 
10
- import{f as r,i as e}from"./chunk-KE2IOPV4.js";var i=class extends r{constructor(t,o=void 0,n=void 0){super("VALIDATION_ERROR",t,400,n??e(),o)}};export{i as a};
11
- //# sourceMappingURL=chunk-337RPHG5.js.map
10
+ import{d as r,g as e}from"./chunk-DTDGIBMA.js";var i=class extends r{constructor(t,o=void 0,n=void 0){super("VALIDATION_ERROR",t,400,n??e(),o)}};export{i as a};
11
+ //# sourceMappingURL=chunk-TL4GIFTB.js.map
@@ -1,11 +1,11 @@
1
1
 
2
2
  /**
3
- * blaizejs v0.3.3
3
+ * blaizejs v0.3.4
4
4
  * A blazing-fast, TypeScript-first Node.js framework with HTTP/2 support, file-based routing, powerful middleware system, and end-to-end type safety for building modern APIs.
5
5
  *
6
6
  * Copyright (c) 2025 BlaizeJS Contributors
7
7
  * @license MIT
8
8
  */
9
9
 
10
- import{f as r,i as o}from"./chunk-KE2IOPV4.js";var t=class extends r{constructor(n,e,s){super("UNSUPPORTED_MEDIA_TYPE",n,415,s??o(),e)}};export{t as a};
11
- //# sourceMappingURL=chunk-HX7XLEO3.js.map
10
+ import{d as r,g as o}from"./chunk-DTDGIBMA.js";var t=class extends r{constructor(n,e,s){super("UNSUPPORTED_MEDIA_TYPE",n,415,s??o(),e)}};export{t as a};
11
+ //# sourceMappingURL=chunk-VLVWNGUO.js.map