blaizejs 0.4.0 → 0.5.1

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 (27) hide show
  1. package/dist/{chunk-LMTJAVHX.js → chunk-6G464Q37.js} +3 -3
  2. package/dist/{chunk-ORFAFXHX.js → chunk-NA2GUVHF.js} +3 -3
  3. package/dist/chunk-VAD7G4RR.js +11 -0
  4. package/dist/chunk-VAD7G4RR.js.map +1 -0
  5. package/dist/{chunk-LI53MJIF.js → chunk-XZOKQ5VF.js} +3 -3
  6. package/dist/{chunk-N7F6OHDX.js → chunk-Y7KAZMOI.js} +3 -3
  7. package/dist/index.cjs +22 -9
  8. package/dist/index.cjs.map +1 -1
  9. package/dist/index.d.cts +1046 -7
  10. package/dist/index.d.ts +1046 -7
  11. package/dist/index.js +22 -9
  12. package/dist/index.js.map +1 -1
  13. package/dist/{internal-server-error-DAEFNRNG.js → internal-server-error-4S64KATC.js} +3 -3
  14. package/dist/{payload-too-large-error-YO3MSQJF.js → payload-too-large-error-BC6YVP2R.js} +3 -3
  15. package/dist/{unsupported-media-type-error-GW2UC37Q.js → unsupported-media-type-error-FV554WCH.js} +3 -3
  16. package/dist/{validation-error-SJTLEIZZ.js → validation-error-ZLDRDHW5.js} +3 -3
  17. package/package.json +4 -4
  18. package/dist/chunk-GP5NAYQS.js +0 -11
  19. package/dist/chunk-GP5NAYQS.js.map +0 -1
  20. /package/dist/{chunk-LMTJAVHX.js.map → chunk-6G464Q37.js.map} +0 -0
  21. /package/dist/{chunk-ORFAFXHX.js.map → chunk-NA2GUVHF.js.map} +0 -0
  22. /package/dist/{chunk-LI53MJIF.js.map → chunk-XZOKQ5VF.js.map} +0 -0
  23. /package/dist/{chunk-N7F6OHDX.js.map → chunk-Y7KAZMOI.js.map} +0 -0
  24. /package/dist/{internal-server-error-DAEFNRNG.js.map → internal-server-error-4S64KATC.js.map} +0 -0
  25. /package/dist/{payload-too-large-error-YO3MSQJF.js.map → payload-too-large-error-BC6YVP2R.js.map} +0 -0
  26. /package/dist/{unsupported-media-type-error-GW2UC37Q.js.map → unsupported-media-type-error-FV554WCH.js.map} +0 -0
  27. /package/dist/{validation-error-SJTLEIZZ.js.map → validation-error-ZLDRDHW5.js.map} +0 -0
@@ -1,11 +1,11 @@
1
1
 
2
2
  /**
3
- * blaizejs v0.4.0
3
+ * blaizejs v0.5.1
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{d as r,i as e}from"./chunk-GP5NAYQS.js";var t=class extends e{constructor(n,o=void 0,i=void 0){super("INTERNAL_SERVER_ERROR",n,500,i??r(),o)}};export{t as a};
11
- //# sourceMappingURL=chunk-LMTJAVHX.js.map
10
+ import{c as r,g as e}from"./chunk-VAD7G4RR.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-6G464Q37.js.map
@@ -1,11 +1,11 @@
1
1
 
2
2
  /**
3
- * blaizejs v0.4.0
3
+ * blaizejs v0.5.1
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{d as r,i as o}from"./chunk-GP5NAYQS.js";var t=class extends o{constructor(n,s,e){super("UNSUPPORTED_MEDIA_TYPE",n,415,e??r(),s)}};export{t as a};
11
- //# sourceMappingURL=chunk-ORFAFXHX.js.map
10
+ import{c as r,g as o}from"./chunk-VAD7G4RR.js";var t=class extends r{constructor(n,s,e){super("UNSUPPORTED_MEDIA_TYPE",n,415,e??o(),s)}};export{t as a};
11
+ //# sourceMappingURL=chunk-NA2GUVHF.js.map
@@ -0,0 +1,11 @@
1
+
2
+ /**
3
+ * blaizejs v0.5.1
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 u=(r=>(r.VALIDATION_ERROR="VALIDATION_ERROR",r.NOT_FOUND="NOT_FOUND",r.UNAUTHORIZED="UNAUTHORIZED",r.FORBIDDEN="FORBIDDEN",r.SSE_NOT_ACCEPTABLE="SSE_NOT_ACCEPTABLE",r.CONFLICT="CONFLICT",r.RATE_LIMITED="RATE_LIMITED",r.INTERNAL_SERVER_ERROR="INTERNAL_SERVER_ERROR",r.PAYLOAD_TOO_LARGE="PAYLOAD_TOO_LARGE",r.UNSUPPORTED_MEDIA_TYPE="UNSUPPORTED_MEDIA_TYPE",r.UPLOAD_TIMEOUT="UPLOAD_TIMEOUT",r.UNPROCESSABLE_ENTITY="UNPROCESSABLE_ENTITY",r.NETWORK_ERROR="NETWORK_ERROR",r.TIMEOUT_ERROR="TIMEOUT_ERROR",r.PARSE_ERROR="PARSE_ERROR",r.HTTP_ERROR="HTTP_ERROR",r.SSE_CONNECTION_ERROR="SSE_CONNECTION_ERROR",r.SSE_BUFFER_OVERFLOW="SSE_BUFFER_OVERFLOW",r.SSE_STREAM_CLOSED="SSE_STREAM_CLOSED",r.SERVICE_UNAVAILABLE="SERVICE_UNAVAILABLE",r))(u||{}),d=(o=>(o.LOW="low",o.MEDIUM="medium",o.HIGH="high",o.CRITICAL="critical",o))(d||{}),c=class extends Error{type;title;status;correlationId;timestamp;details;constructor(t,n,i,o,l){super(n),this.name=this.constructor.name,this.type=t,this.title=n,this.status=i,this.correlationId=o,this.timestamp=new Date,this.details=l,Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}toJSON(){let t={type:this.type,title:this.title,status:this.status,correlationId:this.correlationId,timestamp:this.timestamp.toISOString()};return this.details!==void 0?{...t,details:this.details}:t}toString(){return`${this.name}: ${this.title} [${this.correlationId}]`}};function f(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 m}from"node:async_hooks";var a={headerName:"x-correlation-id",generator:p},s={...a},g=new m;function p(){let e=Date.now().toString(36),t=Math.random().toString(36).substr(2,9);return`req_${e}_${t}`}function S(e,t){s={headerName:e||a.headerName,generator:t||a.generator}}function I(){return s.headerName}function E(){return s.generator()}function C(){let e=g.getStore();return e&&e.trim()?e:"unknown"}function T(e,t){return g.run(e,t)}function O(e){let t=s.headerName,n=e[t],i;return Array.isArray(n)?i=n[0]:typeof n=="string"&&(i=n),i&&i.trim()?i:E()}export{u as a,d as b,c,f as d,S as e,I as f,C as g,T as h,O as i};
11
+ //# sourceMappingURL=chunk-VAD7G4RR.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../blaize-types/src/errors.ts","../src/tracing/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\nexport interface ServiceNotAvailableDetails {\n /** Service that's unavailable */\n service?: string;\n\n /** Seconds to wait before retry */\n retryAfter?: number;\n\n /** Why service is unavailable */\n reason?: 'maintenance' | 'overload' | 'circuit_breaker' | 'dependency_down';\n\n /** Additional context */\n [key: string]: unknown;\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 /** SSE Not Acceptable (406) */\n SSE_NOT_ACCEPTABLE = 'SSE_NOT_ACCEPTABLE',\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 // SSE-specific errors\n /** SSE connection failed (502) */\n SSE_CONNECTION_ERROR = 'SSE_CONNECTION_ERROR',\n\n /** SSE buffer overflow (503) */\n SSE_BUFFER_OVERFLOW = 'SSE_BUFFER_OVERFLOW',\n\n /** SSE stream closed (410) */\n SSE_STREAM_CLOSED = 'SSE_STREAM_CLOSED',\n\n /** Service temporarily unavailable (503) */\n SERVICE_UNAVAILABLE = 'SERVICE_UNAVAILABLE',\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?:\n | 'insufficient_permissions'\n | 'account_suspended'\n | 'resource_locked'\n | 'origin_not_allowed'\n | 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// TODO: Consider moving to blaize-core\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/**\n * SSE-specific error detail interfaces for BlaizeJS framework\n *\n * These interfaces define the structure of details for SSE errors.\n * The actual error classes are implemented in blaize-core.\n */\n\n/**\n * Details for SSE connection errors\n */\nexport interface SSEConnectionErrorDetails {\n /** Client identifier if available */\n clientId?: string;\n\n /** Connection attempt number */\n attemptNumber?: number;\n\n /** Maximum retry attempts configured */\n maxRetries?: number;\n\n /** The underlying error that caused connection failure */\n cause?: string;\n\n /** Suggested resolution */\n suggestion?: string;\n}\n\n/**\n * Details for SSE buffer overflow errors\n */\nexport interface SSEBufferOverflowErrorDetails {\n /** Client identifier */\n clientId?: string;\n\n /** Current buffer size when overflow occurred */\n currentSize: number;\n\n /** Maximum buffer size configured */\n maxSize: number;\n\n /** Number of events dropped */\n eventsDropped?: number;\n\n /** Buffer strategy that was applied */\n strategy: 'drop-oldest' | 'drop-newest' | 'close';\n\n /** Event that triggered the overflow */\n triggeringEvent?: string;\n}\n\n/**\n * Details for SSE stream closed errors\n */\nexport interface SSEStreamClosedErrorDetails {\n /** Client identifier */\n clientId?: string;\n\n /** When the stream was closed */\n closedAt?: string;\n\n /** Reason for closure */\n closeReason?: 'client-disconnect' | 'server-close' | 'timeout' | 'error' | 'buffer-overflow';\n\n /** Whether reconnection is possible */\n canReconnect?: boolean;\n\n /** Suggested retry interval in milliseconds */\n retryAfter?: number;\n}\n\n/**\n * Context for SSE connection errors\n */\nexport interface SSEConnectionErrorContext {\n /** The SSE endpoint URL */\n url: string;\n\n /** Correlation ID for tracing */\n correlationId: string;\n\n /** Connection state when error occurred */\n state: 'connecting' | 'connected' | 'disconnected' | 'closed';\n\n /** Number of reconnection attempts made */\n reconnectAttempts?: number;\n\n /** The original error if available */\n originalError?: Error;\n\n /** Additional SSE-specific details */\n sseDetails?: {\n /** Whether credentials were included */\n withCredentials?: boolean;\n\n /** Last received event ID */\n lastEventId?: string;\n\n /** EventSource ready state */\n readyState?: number;\n };\n}\n\n/**\n * Context for SSE stream errors (server-sent errors)\n */\nexport interface SSEStreamErrorContext {\n /** The SSE endpoint URL */\n url: string;\n\n /** Correlation ID from server or client */\n correlationId: string;\n\n /** Error message from server */\n message: string;\n\n /** Error code if provided */\n code?: string;\n\n /** Error name/type from server */\n name?: string;\n\n /** Raw error data from server */\n rawData?: any;\n}\n\n/**\n * Context for SSE heartbeat timeout errors\n */\nexport interface SSEHeartbeatErrorContext {\n /** The SSE endpoint URL */\n url: string;\n\n /** Correlation ID for tracing */\n correlationId: string;\n\n /** Configured heartbeat timeout in ms */\n heartbeatTimeout: number;\n\n /** Time since last event in ms */\n timeSinceLastEvent?: number;\n\n /** Last event ID received */\n lastEventId?: string;\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\nimport type { CorrelationConfig } from '@blaize-types/tracing';\n\n/**\n * Default configuration values\n * @internal\n */\nconst DEFAULT_CONFIG: CorrelationConfig = {\n headerName: 'x-correlation-id',\n generator: defaultCorrelationIdGenerator,\n};\n\n/**\n * Current configuration (mutable for server customization)\n * @internal\n */\nlet currentConfig: CorrelationConfig = { ...DEFAULT_CONFIG };\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 * Default correlation ID generator\n *\n * Format: req_[timestamp_base36]_[random_base36]\n * Example: req_k3x2m1_9z8y7w6v\n *\n * @internal\n */\nfunction defaultCorrelationIdGenerator(): 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 * Sets the correlation configuration (internal use only)\n *\n * This function is called by the server during initialization to configure\n * the correlation ID system. It should not be called directly by application code.\n *\n * @param headerName - The HTTP header name to use for correlation IDs\n * @param generator - Custom correlation ID generator function\n * @internal\n */\nexport function _setCorrelationConfig(headerName?: string, generator?: () => string): void {\n currentConfig = {\n headerName: headerName || DEFAULT_CONFIG.headerName,\n generator: generator || DEFAULT_CONFIG.generator,\n };\n}\n\n/**\n * Gets the configured correlation header name\n *\n * @returns The configured header name (defaults to 'x-correlation-id')\n * @internal\n */\nexport function getCorrelationHeaderName(): string {\n return currentConfig.headerName;\n}\n\n/**\n * Resets the correlation configuration to defaults\n *\n * Primarily used for testing to ensure clean state between tests\n *\n * @internal\n */\nexport function _resetCorrelationConfig(): void {\n currentConfig = { ...DEFAULT_CONFIG };\n}\n\n/**\n * Generates a new unique correlation ID\n *\n * Uses the configured generator function, which defaults to the format:\n * req_[timestamp_base36]_[random_base36]\n * Example: req_k3x2m1_9z8y7w6v\n *\n * @returns A unique correlation ID string\n */\nexport function generateCorrelationId(): string {\n return currentConfig.generator();\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 getCorrelationId(): 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 configured correlation header (default: 'x-correlation-id').\n * If not found, empty, or undefined, generates a new correlation ID.\n * Supports both string and string[] header values for compatibility.\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 createCorrelationIdFromHeaders(\n headers: Record<string, string | string[] | undefined>\n): string {\n const headerName = currentConfig.headerName;\n const headerValue = headers[headerName];\n\n // Handle both string and string[] header values\n let correlationId: string | undefined;\n\n if (Array.isArray(headerValue)) {\n // Take the first value if it's an array\n correlationId = headerValue[0];\n } else if (typeof headerValue === 'string') {\n correlationId = headerValue;\n }\n\n // Use header value if it exists and is not empty\n if (correlationId && correlationId.trim()) {\n return correlationId;\n }\n\n // Generate new correlation ID if header is missing or empty\n return generateCorrelationId();\n}\n\n// Note: Correlation middleware is not needed since we're integrating\n// at the request handler level (see Task T6). The request handler\n// will directly use getOrGenerateCorrelationId() and withCorrelationId()\n// to establish correlation context for the entire request lifecycle.\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 = getCorrelationId();\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 config: {\n headerName: currentConfig.headerName,\n generatorType:\n currentConfig.generator === defaultCorrelationIdGenerator ? 'default' : 'custom',\n },\n };\n}\n"],"mappings":";;;;;;;;;AAyNO,IAAKA,OAGVA,EAAA,iBAAmB,mBAGnBA,EAAA,UAAY,YAGZA,EAAA,aAAe,eAGfA,EAAA,UAAY,YAGZA,EAAA,mBAAqB,qBAGrBA,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,aAIbA,EAAA,qBAAuB,uBAGvBA,EAAA,oBAAsB,sBAGtBA,EAAA,kBAAoB,oBAGpBA,EAAA,oBAAsB,sBA9DZA,OAAA,IAsEAC,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,EA0PO,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,CCrqBA,OAAS,qBAAAC,MAAyB,mBAQlC,IAAMC,EAAoC,CACxC,WAAY,mBACZ,UAAWC,CACb,EAMIC,EAAmC,CAAE,GAAGF,CAAe,EAMrDG,EAAqB,IAAIJ,EAU/B,SAASE,GAAwC,CAC/C,IAAMG,EAAY,KAAK,IAAI,EAAE,SAAS,EAAE,EAClCC,EAAS,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE,OAAO,EAAG,CAAC,EACrD,MAAO,OAAOD,CAAS,IAAIC,CAAM,EACnC,CAYO,SAASC,EAAsBC,EAAqBC,EAAgC,CACzFN,EAAgB,CACd,WAAYK,GAAcP,EAAe,WACzC,UAAWQ,GAAaR,EAAe,SACzC,CACF,CAQO,SAASS,GAAmC,CACjD,OAAOP,EAAc,UACvB,CAsBO,SAASQ,GAAgC,CAC9C,OAAOC,EAAc,UAAU,CACjC,CAOO,SAASC,GAA2B,CACzC,IAAMC,EAASC,EAAmB,SAAS,EAC3C,OAAOD,GAAUA,EAAO,KAAK,EAAIA,EAAS,SAC5C,CAiCO,SAASE,EACdC,EACAC,EACgB,CAChB,OAAOC,EAAmB,IAAIF,EAAeC,CAAE,CACjD,CAuBO,SAASE,EACdC,EACQ,CACR,IAAMC,EAAaC,EAAc,WAC3BC,EAAcH,EAAQC,CAAU,EAGlCL,EAUJ,OARI,MAAM,QAAQO,CAAW,EAE3BP,EAAgBO,EAAY,CAAC,EACpB,OAAOA,GAAgB,WAChCP,EAAgBO,GAIdP,GAAiBA,EAAc,KAAK,EAC/BA,EAIFQ,EAAsB,CAC/B","names":["ErrorType","ErrorSeverity","BlaizeError","type","title","status","correlationId","details","base","isBodyParseError","error","AsyncLocalStorage","DEFAULT_CONFIG","defaultCorrelationIdGenerator","currentConfig","correlationStorage","timestamp","random","_setCorrelationConfig","headerName","generator","getCorrelationHeaderName","generateCorrelationId","currentConfig","getCorrelationId","stored","correlationStorage","withCorrelationId","correlationId","fn","correlationStorage","createCorrelationIdFromHeaders","headers","headerName","currentConfig","headerValue","generateCorrelationId"]}
@@ -1,11 +1,11 @@
1
1
 
2
2
  /**
3
- * blaizejs v0.4.0
3
+ * blaizejs v0.5.1
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{d as r,i as o}from"./chunk-GP5NAYQS.js";var e=class extends o{constructor(t,a,i){super("PAYLOAD_TOO_LARGE",t,413,i??r(),a)}};export{e as a};
11
- //# sourceMappingURL=chunk-LI53MJIF.js.map
10
+ import{c as r,g as o}from"./chunk-VAD7G4RR.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-XZOKQ5VF.js.map
@@ -1,11 +1,11 @@
1
1
 
2
2
  /**
3
- * blaizejs v0.4.0
3
+ * blaizejs v0.5.1
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{d as r,i as e}from"./chunk-GP5NAYQS.js";var i=class extends e{constructor(o,t=void 0,n=void 0){super("VALIDATION_ERROR",o,400,n??r(),t)}};export{i as a};
11
- //# sourceMappingURL=chunk-N7F6OHDX.js.map
10
+ import{c as r,g as e}from"./chunk-VAD7G4RR.js";var i=class extends r{constructor(o,t=void 0,n=void 0){super("VALIDATION_ERROR",o,400,n??e(),t)}};export{i as a};
11
+ //# sourceMappingURL=chunk-Y7KAZMOI.js.map
package/dist/index.cjs CHANGED
@@ -1,18 +1,31 @@
1
1
 
2
2
  /**
3
- * blaizejs v0.4.0
3
+ * blaizejs v0.5.1
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
- "use strict";var Tr=Object.create;var oe=Object.defineProperty;var xr=Object.getOwnPropertyDescriptor;var Rr=Object.getOwnPropertyNames;var vr=Object.getPrototypeOf,Er=Object.prototype.hasOwnProperty;var j=(e,t)=>()=>(e&&(t=e(e=0)),t);var W=(e,t)=>{for(var r in t)oe(e,r,{get:t[r],enumerable:!0})},st=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Rr(t))!Er.call(e,o)&&o!==r&&oe(e,o,{get:()=>t[o],enumerable:!(n=xr(t,o))||n.enumerable});return e};var R=(e,t,r)=>(r=e!=null?Tr(vr(e)):{},st(t||!e||!e.__esModule?oe(r,"default",{value:e,enumerable:!0}):r,e)),Pr=e=>st(oe({},"__esModule",{value:!0}),e);function Fr(){let e=Date.now().toString(36),t=Math.random().toString(36).substr(2,9);return`req_${e}_${t}`}function St(e,t){Te={headerName:e||$e.headerName,generator:t||$e.generator}}function H(){return Te.headerName}function kr(){return Te.generator()}function y(){let e=ht.getStore();return e&&e.trim()?e:"unknown"}function wt(e,t){return ht.run(e,t)}function xe(e){let t=Te.headerName,r=e[t],n;return Array.isArray(r)?n=r[0]:typeof r=="string"&&(n=r),n&&n.trim()?n:kr()}var yt,$e,Te,ht,v=j(()=>{"use strict";yt=require("async_hooks"),$e={headerName:"x-correlation-id",generator:Fr},Te={...$e},ht=new yt.AsyncLocalStorage});function zr(e){return typeof e=="object"&&e!==null&&"type"in e&&"message"in e&&"error"in e&&typeof e.type=="string"&&typeof e.message=="string"}var b,Et,h,P=j(()=>{"use strict";b=(d=>(d.VALIDATION_ERROR="VALIDATION_ERROR",d.NOT_FOUND="NOT_FOUND",d.UNAUTHORIZED="UNAUTHORIZED",d.FORBIDDEN="FORBIDDEN",d.CONFLICT="CONFLICT",d.RATE_LIMITED="RATE_LIMITED",d.INTERNAL_SERVER_ERROR="INTERNAL_SERVER_ERROR",d.PAYLOAD_TOO_LARGE="PAYLOAD_TOO_LARGE",d.UNSUPPORTED_MEDIA_TYPE="UNSUPPORTED_MEDIA_TYPE",d.UPLOAD_TIMEOUT="UPLOAD_TIMEOUT",d.UNPROCESSABLE_ENTITY="UNPROCESSABLE_ENTITY",d.NETWORK_ERROR="NETWORK_ERROR",d.TIMEOUT_ERROR="TIMEOUT_ERROR",d.PARSE_ERROR="PARSE_ERROR",d.HTTP_ERROR="HTTP_ERROR",d))(b||{}),Et=(o=>(o.LOW="low",o.MEDIUM="medium",o.HIGH="high",o.CRITICAL="critical",o))(Et||{}),h=class extends Error{type;title;status;correlationId;timestamp;details;constructor(t,r,n,o,i){super(r),this.name=this.constructor.name,this.type=t,this.title=r,this.status=n,this.correlationId=o,this.timestamp=new Date,this.details=i,Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}toJSON(){let t={type:this.type,title:this.title,status:this.status,correlationId:this.correlationId,timestamp:this.timestamp.toISOString()};return this.details!==void 0?{...t,details:this.details}:t}toString(){return`${this.name}: ${this.title} [${this.correlationId}]`}}});var Pt={};W(Pt,{InternalServerError:()=>O});var O,Z=j(()=>{"use strict";P();v();O=class extends h{constructor(t,r=void 0,n=void 0){super("INTERNAL_SERVER_ERROR",t,500,n??y(),r)}}});var q={};W(q,{ValidationError:()=>I});var I,N=j(()=>{"use strict";P();v();I=class extends h{constructor(t,r=void 0,n=void 0){super("VALIDATION_ERROR",t,400,n??y(),r)}}});var _e={};W(_e,{PayloadTooLargeError:()=>J});var J,Re=j(()=>{"use strict";P();v();J=class extends h{constructor(t,r,n){super("PAYLOAD_TOO_LARGE",t,413,n??y(),r)}}});var Ue={};W(Ue,{UnsupportedMediaTypeError:()=>Y});var Y,ve=j(()=>{"use strict";P();v();Y=class extends h{constructor(t,r,n){super("UNSUPPORTED_MEDIA_TYPE",t,415,n??y(),r)}}});var so={};W(so,{Blaize:()=>io,BlaizeError:()=>h,ConflictError:()=>Ne,ErrorSeverity:()=>Et,ErrorType:()=>b,ForbiddenError:()=>Ie,InternalServerError:()=>O,MiddlewareAPI:()=>Sr,NotFoundError:()=>z,PayloadTooLargeError:()=>J,PluginsAPI:()=>wr,RateLimitError:()=>De,RequestTimeoutError:()=>ze,RouterAPI:()=>hr,ServerAPI:()=>yr,UnauthorizedError:()=>Oe,UnprocessableEntityError:()=>Be,UnsupportedMediaTypeError:()=>Y,VERSION:()=>gr,ValidationError:()=>I,asMiddlewareArray:()=>to,asPluginArray:()=>ro,compose:()=>_,createDeleteRoute:()=>fe,createGetRoute:()=>le,createHeadRoute:()=>ge,createMiddleware:()=>V,createMiddlewareArray:()=>no,createOptionsRoute:()=>ye,createPatchRoute:()=>me,createPlugin:()=>ae,createPluginArray:()=>oo,createPostRoute:()=>de,createPutRoute:()=>pe,createRouteFactory:()=>Ae,createServer:()=>ke,createServiceMiddleware:()=>se,createStateMiddleware:()=>ie,getCorrelationId:()=>y,inferContext:()=>it,isBodyParseError:()=>zr,isMiddleware:()=>Xn,isPlugin:()=>eo});module.exports=Pr(so);function at(e,t,r){if(!e||e.skip&&e.skip(t))return Promise.resolve(r());try{let n=e.execute(t,r);return n instanceof Promise?n:Promise.resolve(n)}catch(n){return Promise.reject(n)}}function _(e){return e.length===0?async(t,r)=>{await Promise.resolve(r())}:async function(t,r){let n=new Set,o=async i=>{if(i>=e.length)return Promise.resolve(r());let s=e[i];return at(s,t,()=>{if(n.has(i))throw new Error("next() called multiple times");return n.add(i),o(i+1)})};return o(0)}}function V(e){if(typeof e=="function")return{name:"anonymous",execute:e,debug:!1};let{name:t="anonymous",handler:r,skip:n,debug:o=!1}=e;return{name:t,execute:r,debug:o,...n!==void 0&&{skip:n}}}function ie(e){return V({name:"state-middleware",handler:e})}function se(e){return V({name:"service-middleware",handler:e})}function ae(e,t,r,n={}){if(!e||typeof e!="string")throw new Error("Plugin name must be a non-empty string");if(!t||typeof t!="string")throw new Error("Plugin version must be a non-empty string");if(typeof r!="function")throw new Error("Plugin setup must be a function");return function(i){let s={...n,...i},a={name:e,version:t,register:async u=>{let l=await r(u,s);l&&typeof l=="object"&&Object.assign(a,l)}};return a}}var dt=require("url");var ue={};function ut(e){ue={...ue,...e}}function ct(){if(!ue.routesDir)throw new Error("Routes directory not configured. Make sure server is properly initialized.");return ue.routesDir}var lt=R(require("path"),1);function ce(e,t){e.startsWith("file://")&&(e=e.replace("file://","")),t.startsWith("file://")&&(t=t.replace("file://",""));let r=e.replace(/\\/g,"/"),n=t.replace(/\\/g,"/"),o=n.endsWith("/")?n:`${n}/`,i=r;r.startsWith(o)?i=r.substring(o.length):r.startsWith(n)?(i=r.substring(n.length),i.startsWith("/")&&(i=i.substring(1))):i=lt.relative(n,r).replace(/\\/g,"/"),i=i.replace(/\.[^.]+$/,"");let s=i.split("/").filter(Boolean),a=[],u=s.map(T=>{if(T.startsWith("[")&&T.endsWith("]")){let p=T.slice(1,-1);return a.push(p),`:${p}`}return T}),l=u.length>0?`/${u.join("/")}`:"/";return l.endsWith("/index")&&(l=l.slice(0,-6)||"/"),{filePath:e,routePath:l,params:a}}function br(){let e=Error.prepareStackTrace;try{Error.prepareStackTrace=(o,i)=>i;let r=new Error().stack[3];if(!r||typeof r.getFileName!="function")throw new Error("Unable to determine caller file frame");let n=r.getFileName();if(!n)throw new Error("Unable to determine caller file name");return n.startsWith("file://")?(0,dt.fileURLToPath)(n):n}finally{Error.prepareStackTrace=e}}function U(){let e=br(),t=ct(),r=ce(e,t);return console.log(`\u{1F50E} Parsed route path: ${r.routePath} from file: ${e}`),r.routePath}var le=()=>e=>{L("GET",e);let t=U();return{GET:e,path:t}},de=()=>e=>{L("POST",e);let t=U();return{POST:e,path:t}},pe=()=>e=>{L("PUT",e);let t=U();return{PUT:e,path:t}},fe=()=>e=>{L("DELETE",e);let t=U();return{DELETE:e,path:t}},me=()=>e=>{L("PATCH",e);let t=U();return{PATCH:e,path:t}},ge=()=>e=>{L("HEAD",e);let t=U();return{HEAD:e,path:t}},ye=()=>e=>{L("OPTIONS",e);let t=U();return{OPTIONS:e,path:t}};function L(e,t){if(!t.handler||typeof t.handler!="function")throw new Error(`Handler for method ${e} must be a function`);if(t.middleware&&!Array.isArray(t.middleware))throw new Error(`Middleware for method ${e} must be an array`);switch(t.schema&&Cr(e,t.schema),e){case"GET":case"HEAD":case"DELETE":t.schema?.body&&console.warn(`Warning: ${e} requests typically don't have request bodies`);break}}function Cr(e,t){let{params:r,query:n,body:o,response:i}=t;if(r&&(!r._def||typeof r.parse!="function"))throw new Error(`Params schema for ${e} must be a valid Zod schema`);if(n&&(!n._def||typeof n.parse!="function"))throw new Error(`Query schema for ${e} must be a valid Zod schema`);if(o&&(!o._def||typeof o.parse!="function"))throw new Error(`Body schema for ${e} must be a valid Zod schema`);if(i&&(!i._def||typeof i.parse!="function"))throw new Error(`Response schema for ${e} must be a valid Zod schema`)}function Ae(){return{get:le(),post:de(),put:pe(),delete:fe(),patch:me(),head:ge(),options:ye()}}var fr=require("async_hooks"),mr=R(require("events"),1);var qe=R(require("fs"),1),Ut=R(require("http"),1),Lt=R(require("http2"),1);var k=R(require("fs"),1),he=R(require("path"),1),pt=R(require("selfsigned"),1);async function ft(){let e=he.join(process.cwd(),".blaizejs","certs"),t=he.join(e,"dev.key"),r=he.join(e,"dev.cert");if(k.existsSync(t)&&k.existsSync(r))return{keyFile:t,certFile:r};k.existsSync(e)||k.mkdirSync(e,{recursive:!0});let i=pt.generate([{name:"commonName",value:"localhost"}],{days:365,algorithm:"sha256",keySize:2048,extensions:[{name:"basicConstraints",cA:!0},{name:"keyUsage",keyCertSign:!0,digitalSignature:!0,nonRepudiation:!0,keyEncipherment:!0,dataEncipherment:!0},{name:"extKeyUsage",serverAuth:!0,clientAuth:!0},{name:"subjectAltName",altNames:[{type:2,value:"localhost"},{type:7,ip:"127.0.0.1"}]}]});return k.writeFileSync(t,Buffer.from(i.private,"utf-8")),k.writeFileSync(r,Buffer.from(i.cert,"utf-8")),console.log(`
10
+ "use strict";var Yr=Object.create;var me=Object.defineProperty;var Kr=Object.getOwnPropertyDescriptor;var Xr=Object.getOwnPropertyNames;var en=Object.getPrototypeOf,tn=Object.prototype.hasOwnProperty;var G=(e,t)=>()=>(e&&(t=e(e=0)),t);var X=(e,t)=>{for(var r in t)me(e,r,{get:t[r],enumerable:!0})},Et=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Xr(t))!tn.call(e,o)&&o!==r&&me(e,o,{get:()=>t[o],enumerable:!(n=Kr(t,o))||n.enumerable});return e};var _=(e,t,r)=>(r=e!=null?Yr(en(e)):{},Et(t||!e||!e.__esModule?me(r,"default",{value:e,enumerable:!0}):r,e)),rn=e=>Et(me({},"__esModule",{value:!0}),e);function nn(e){return typeof e=="object"&&e!==null&&"type"in e&&"message"in e&&"error"in e&&typeof e.type=="string"&&typeof e.message=="string"}var P,Tt,w,b=G(()=>{"use strict";P=(h=>(h.VALIDATION_ERROR="VALIDATION_ERROR",h.NOT_FOUND="NOT_FOUND",h.UNAUTHORIZED="UNAUTHORIZED",h.FORBIDDEN="FORBIDDEN",h.SSE_NOT_ACCEPTABLE="SSE_NOT_ACCEPTABLE",h.CONFLICT="CONFLICT",h.RATE_LIMITED="RATE_LIMITED",h.INTERNAL_SERVER_ERROR="INTERNAL_SERVER_ERROR",h.PAYLOAD_TOO_LARGE="PAYLOAD_TOO_LARGE",h.UNSUPPORTED_MEDIA_TYPE="UNSUPPORTED_MEDIA_TYPE",h.UPLOAD_TIMEOUT="UPLOAD_TIMEOUT",h.UNPROCESSABLE_ENTITY="UNPROCESSABLE_ENTITY",h.NETWORK_ERROR="NETWORK_ERROR",h.TIMEOUT_ERROR="TIMEOUT_ERROR",h.PARSE_ERROR="PARSE_ERROR",h.HTTP_ERROR="HTTP_ERROR",h.SSE_CONNECTION_ERROR="SSE_CONNECTION_ERROR",h.SSE_BUFFER_OVERFLOW="SSE_BUFFER_OVERFLOW",h.SSE_STREAM_CLOSED="SSE_STREAM_CLOSED",h.SERVICE_UNAVAILABLE="SERVICE_UNAVAILABLE",h))(P||{}),Tt=(o=>(o.LOW="low",o.MEDIUM="medium",o.HIGH="high",o.CRITICAL="critical",o))(Tt||{}),w=class extends Error{type;title;status;correlationId;timestamp;details;constructor(t,r,n,o,i){super(r),this.name=this.constructor.name,this.type=t,this.title=r,this.status=n,this.correlationId=o,this.timestamp=new Date,this.details=i,Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}toJSON(){let t={type:this.type,title:this.title,status:this.status,correlationId:this.correlationId,timestamp:this.timestamp.toISOString()};return this.details!==void 0?{...t,details:this.details}:t}toString(){return`${this.name}: ${this.title} [${this.correlationId}]`}}});function on(){let e=Date.now().toString(36),t=Math.random().toString(36).substr(2,9);return`req_${e}_${t}`}function Ct(e,t){ge={headerName:e||Ze.headerName,generator:t||Ze.generator}}function j(){return ge.headerName}function sn(){return ge.generator()}function y(){let e=bt.getStore();return e&&e.trim()?e:"unknown"}function Pt(e,t){return bt.run(e,t)}function he(e){let t=ge.headerName,r=e[t],n;return Array.isArray(r)?n=r[0]:typeof r=="string"&&(n=r),n&&n.trim()?n:sn()}var Rt,Ze,ge,bt,R=G(()=>{"use strict";Rt=require("async_hooks"),Ze={headerName:"x-correlation-id",generator:on},ge={...Ze},bt=new Rt.AsyncLocalStorage});var V={};X(V,{ValidationError:()=>M});var M,I=G(()=>{"use strict";b();R();M=class extends w{constructor(t,r=void 0,n=void 0){super("VALIDATION_ERROR",t,400,n??y(),r)}}});var rr={};X(rr,{InternalServerError:()=>N});var N,ie=G(()=>{"use strict";b();R();N=class extends w{constructor(t,r=void 0,n=void 0){super("INTERNAL_SERVER_ERROR",t,500,n??y(),r)}}});var rt={};X(rt,{PayloadTooLargeError:()=>se});var se,ze=G(()=>{"use strict";b();R();se=class extends w{constructor(t,r,n){super("PAYLOAD_TOO_LARGE",t,413,n??y(),r)}}});var nt={};X(nt,{UnsupportedMediaTypeError:()=>ae});var ae,Ne=G(()=>{"use strict";b();R();ae=class extends w{constructor(t,r,n){super("UNSUPPORTED_MEDIA_TYPE",t,415,n??y(),r)}}});var pi={};X(pi,{Blaize:()=>di,BlaizeError:()=>w,ConflictError:()=>je,ErrorSeverity:()=>Tt,ErrorType:()=>P,ForbiddenError:()=>Z,InternalServerError:()=>N,MiddlewareAPI:()=>Gr,NotFoundError:()=>H,PayloadTooLargeError:()=>se,PluginsAPI:()=>Zr,RateLimitError:()=>Ve,RequestTimeoutError:()=>We,RouterAPI:()=>Qr,ServerAPI:()=>Wr,ServiceNotAvailableError:()=>Ge,UnauthorizedError:()=>Le,UnprocessableEntityError:()=>Qe,UnsupportedMediaTypeError:()=>ae,VERSION:()=>Vr,ValidationError:()=>M,asMiddlewareArray:()=>ai,asPluginArray:()=>ci,buildUrl:()=>Fe,compilePathPattern:()=>J,compose:()=>L,cors:()=>te,createDeleteRoute:()=>_e,createGetRoute:()=>be,createHeadRoute:()=>Oe,createMatcher:()=>Y,createMiddleware:()=>$,createMiddlewareArray:()=>li,createOptionsRoute:()=>Ae,createPatchRoute:()=>Me,createPlugin:()=>we,createPluginArray:()=>ui,createPostRoute:()=>Ce,createPutRoute:()=>Pe,createRouteFactory:()=>tt,createServer:()=>qe,createServiceMiddleware:()=>Se,createStateMiddleware:()=>ye,extractParams:()=>Q,getCorrelationId:()=>y,inferContext:()=>xt,isBodyParseError:()=>nn,isMiddleware:()=>ii,isPlugin:()=>si,paramsToQuery:()=>ne});module.exports=rn(pi);function vt(e,t,r){if(!e||e.skip&&e.skip(t))return Promise.resolve(r());try{let n=e.execute(t,r);return n instanceof Promise?n:Promise.resolve(n)}catch(n){return Promise.reject(n)}}function L(e){return e.length===0?async(t,r)=>{await Promise.resolve(r())}:async function(t,r){let n=new Set,o=async i=>{if(i>=e.length)return Promise.resolve(r());let s=e[i];return vt(s,t,()=>{if(n.has(i))throw new Error("next() called multiple times");return n.add(i),o(i+1)})};return o(0)}}b();R();var Z=class extends w{constructor(t,r=void 0,n=void 0){super("FORBIDDEN",t,403,n??y(),r)}};function $(e){if(typeof e=="function")return{name:"anonymous",execute:e,debug:!1};let{name:t="anonymous",handler:r,skip:n,debug:o=!1}=e;return{name:t,execute:r,debug:o,...n!==void 0&&{skip:n}}}function ye(e){return $({name:"state-middleware",handler:e})}function Se(e){return $({name:"service-middleware",handler:e})}var an={origin:!0,methods:["GET","HEAD","PUT","PATCH","POST","DELETE"],credentials:!1,optionsSuccessStatus:204},cn={origin:!1,methods:["GET","HEAD"],credentials:!1,optionsSuccessStatus:204};function _t(e){return e===void 0&&(e=process.env.NODE_ENV!=="production"),e?{...an}:{...cn}}function ln(e=6e4,t=1e3){let r=new Map,n={ttl:e,maxSize:t},o=(g,x,v)=>`${g}:${x}:${v||"anonymous"}`,i=()=>{if(r.size===0)return;let g=null,x=1/0;for(let[v,u]of r.entries())u.lastAccessed<x&&(x=u.lastAccessed,g=v);g&&r.delete(g)};return{get:(g,x,v)=>{let u=o(g,x,v),f=r.get(u);if(!f)return null;let m=Date.now();return m>f.expiresAt?(r.delete(u),null):(f.lastAccessed=m,f.allowed)},set:(g,x,v,u)=>{let f=o(g,v,u),m=Date.now();if(r.has(f)){r.set(f,{allowed:x,expiresAt:m+n.ttl,lastAccessed:m});return}r.size>=n.maxSize&&i(),r.set(f,{allowed:x,expiresAt:m+n.ttl,lastAccessed:m})},clear:()=>{r.clear()},cleanExpired:()=>{let g=Date.now(),x=0;for(let[v,u]of r.entries())g>u.expiresAt&&(r.delete(v),x++);return x},getStats:()=>({size:r.size,maxSize:n.maxSize,ttl:n.ttl})}}var Mt=ln();function un(e){return typeof e=="boolean"||typeof e=="function"?!1:Array.isArray(e)?e.every(t=>typeof t=="string"||t instanceof RegExp):typeof e=="string"||e instanceof RegExp}function dn(e){return typeof e=="string"?`str:${e}`:e instanceof RegExp?`regex:${e.source}:${e.flags}`:Array.isArray(e)?`array:[${e.map(t=>typeof t=="string"?`str:${t}`:t instanceof RegExp?`regex:${t.source}:${t.flags}`:"unknown").join(",")}]`:"unknown"}async function pn(e,t){return t==="*"?!0:e===t}async function fn(e,t){return t.test(e)}async function mn(e,t,r,n=100){let o;try{let i=new Promise(a=>{o=setTimeout(()=>{a({timedOut:!0})},n)}),s=await Promise.race([Promise.resolve(t(e,r)).then(a=>({result:a})),i]);return o&&clearTimeout(o),"timedOut"in s?(console.warn(`CORS origin validation function timed out after ${n}ms for origin: ${e}`),!1):s.result}catch(i){return o&&clearTimeout(o),console.error("CORS origin validation function error:",i),!1}}async function Ot(e,t,r){let n=t.map(i=>Je(e,i,r));return(await Promise.all(n)).some(i=>i===!0)}async function Je(e,t,r){return typeof t=="string"?pn(e,t):t instanceof RegExp?fn(e,t):typeof t=="function"?mn(e,t,r):(console.warn("Unknown CORS origin type:",typeof t),!1)}async function ee(e,t,r){if(t===!0)return!0;if(t===!1)return!1;if(un(t)){let o=r?.state?.user?.id||r?.state?.userId,i=dn(t),s=Mt.get(e,i,o);if(s!==null)return s;let a;return Array.isArray(t)?a=await Ot(e,t,r):a=await Je(e,t,r),Mt.set(e,a,i,o),a}else return Array.isArray(t)?Ot(e,t,r):Je(e,t,r)}I();function gn(e){let t=e.request.header("origin")||e.request.header("Origin"),r=e.request.header("access-control-request-method")||e.request.header("Access-Control-Request-Method"),n=e.request.header("access-control-request-headers")||e.request.header("Access-Control-Request-Headers"),o=n?n.split(",").map(i=>i.trim().toLowerCase()):void 0;return{origin:t,requestedMethod:r,requestedHeaders:o}}function Ye(e){return e.toUpperCase()}function hn(e,t){return t?(typeof t=="string"?t.split(",").map(n=>n.trim()):t).map(n=>Ye(n)).includes(Ye(e)):["GET","HEAD","PUT","PATCH","POST","DELETE"].includes(Ye(e))}function yn(e,t){if(!e||e.length===0||t===void 0)return!0;let r=typeof t=="string"?t.split(",").map(n=>n.trim().toLowerCase()):t.map(n=>n.toLowerCase());return e.every(n=>r.includes(n.toLowerCase()))}function Sn(e,t,r,n){n&&(t.origin===!0&&!t.credentials?e.response.header("Access-Control-Allow-Origin","*"):(e.response.header("Access-Control-Allow-Origin",r),e.response.header("Vary","Origin"))),t.credentials&&n&&e.response.header("Access-Control-Allow-Credentials","true");let o=t.methods||["GET","HEAD","PUT","PATCH","POST","DELETE"],i=typeof o=="string"?o:o.join(", ");if(e.response.header("Access-Control-Allow-Methods",i),t.allowedHeaders){let s=typeof t.allowedHeaders=="string"?t.allowedHeaders:t.allowedHeaders.join(", ");e.response.header("Access-Control-Allow-Headers",s)}else{let s=e.request.header("access-control-request-headers")||e.request.header("Access-Control-Request-Headers");s&&e.response.header("Access-Control-Allow-Headers",s)}t.maxAge!==void 0&&t.maxAge>=0&&e.response.header("Access-Control-Max-Age",String(t.maxAge))}async function At(e,t){let r=gn(e);if(!r.origin||!r.requestedMethod)throw e.response.status(403),new M("Invalid preflight request: missing required headers",{fields:[{field:r.origin?"Access-Control-Request-Method":"Origin",messages:["Required header is missing"]}],errorCount:1,section:"body"});let n=await ee(r.origin,t.origin||!1,e);if(!n)throw e.response.status(403),new M("CORS origin not allowed",{fields:[{field:"Origin",messages:[`Origin '${r.origin}' is not allowed`],rejectedValue:r.origin}],errorCount:1,section:"body"});if(!hn(r.requestedMethod,t.methods))throw e.response.status(403),new M("CORS method not allowed",{fields:[{field:"Access-Control-Request-Method",messages:[`Method '${r.requestedMethod}' is not allowed`],rejectedValue:r.requestedMethod,expectedType:typeof t.methods=="string"?t.methods:t.methods?.join(", ")}],errorCount:1,section:"body"});if(!yn(r.requestedHeaders,t.allowedHeaders)){let i=r.requestedHeaders?.filter(s=>{let a=t.allowedHeaders;return a?!(typeof a=="string"?a.split(",").map(l=>l.trim().toLowerCase()):a.map(l=>l.toLowerCase())).includes(s.toLowerCase()):!1});throw e.response.status(403),new M("CORS headers not allowed",{fields:[{field:"Access-Control-Request-Headers",messages:[`Headers not allowed: ${i?.join(", ")}`],rejectedValue:i}],errorCount:1,section:"body"})}Sn(e,t,r.origin,n);let o=t.optionsSuccessStatus||204;e.response.status(o),t.preflightContinue||e.response.text("")}function Ke(e){return e.request.method==="OPTIONS"&&!!(e.request.header("access-control-request-method")||e.request.header("Access-Control-Request-Method"))}var T=require("zod"),wn=T.z.enum(["GET","POST","PUT","DELETE","PATCH","HEAD","OPTIONS","CONNECT","TRACE"]),xn=T.z.union([T.z.array(wn),T.z.string().transform(e=>e.split(",").map(t=>t.trim()))]).optional(),Ft=T.z.union([T.z.array(T.z.string()),T.z.string().transform(e=>e.split(",").map(t=>t.trim()))]).optional(),En=T.z.custom(e=>typeof e=="function"&&e.length<=2,{message:"Origin validator must be a function accepting (origin, ctx?) parameters"}),kt=T.z.union([T.z.string(),T.z.instanceof(RegExp),En]),vn=T.z.union([T.z.boolean(),kt,T.z.array(kt)]),It=T.z.object({origin:vn.optional(),methods:xn,allowedHeaders:Ft,exposedHeaders:Ft,credentials:T.z.boolean().optional(),maxAge:T.z.number().int().optional(),preflightContinue:T.z.boolean().optional(),optionsSuccessStatus:T.z.number().int().min(200).max(299).optional()}).strict(),Dt=T.z.union([T.z.boolean(),It]).optional();function zt(e){try{return typeof e=="boolean"?e===!1?{origin:!1}:{origin:!0}:It.parse(e)}catch(t){if(t instanceof T.z.ZodError){let r=Tn(t);throw new Error(`Invalid CORS options:
11
+ ${r}`)}throw new Error(`Invalid CORS options: ${String(t)}`)}}function Tn(e){return e.errors.map(r=>` - ${r.path.join(".")||"root"}: ${r.message}`).join(`
12
+ `)}function Rn(e){return Array.isArray(e)}function Nt(e){if(e.credentials===!0&&e.origin!==void 0){if(e.origin===!0||e.origin==="*")throw new Error("CORS security violation: Cannot use wildcard origin (*) with credentials. When credentials are enabled, you must specify explicit origins.");if(Rn(e.origin)&&e.origin.some(r=>r==="*"))throw new Error("CORS security violation: Cannot include wildcard origin (*) in array when credentials are enabled.")}}function Bt(e,t){return e===!0?{...t,origin:!0}:e===!1?{origin:!1}:e?{...t,...e,methods:e.methods??t.methods,allowedHeaders:e.allowedHeaders??t.allowedHeaders,exposedHeaders:e.exposedHeaders??t.exposedHeaders}:t}function bn(e,t,r,n){if(!(!n||!r)&&(t.origin===!0&&!t.credentials?e.response.header("Access-Control-Allow-Origin","*"):(e.response.header("Access-Control-Allow-Origin",r),e.response.header("Vary","Origin")),t.credentials&&e.response.header("Access-Control-Allow-Credentials","true"),t.exposedHeaders)){let o=typeof t.exposedHeaders=="string"?t.exposedHeaders:t.exposedHeaders.join(", ");e.response.header("Access-Control-Expose-Headers",o)}}function te(e){let t=process.env.NODE_ENV==="development",r=_t(t),n=Bt(e,r),o=zt(n);return Nt(o),$({name:"cors",handler:async(i,s)=>{let a=i.request.header("origin")||i.request.header("Origin");if(Ke(i)){if(await At(i,o),!o.preflightContinue)return}else{if(!a){await s();return}let c=await ee(a,o.origin||!1,i);if(!c)throw i.response.status(403),new Z("CORS validation failed",{reason:"origin_not_allowed",origin:a,allowedOrigins:o.origin});bn(i,o,a,c)}await s()},debug:process.env.DEBUG?.includes("cors")})}function we(e,t,r,n={}){if(!e||typeof e!="string")throw new Error("Plugin name must be a non-empty string");if(!t||typeof t!="string")throw new Error("Plugin version must be a non-empty string");if(typeof r!="function")throw new Error("Plugin setup must be a function");return function(i){let s={...n,...i},a={name:e,version:t,register:async c=>{let l=await r(c,s);l&&typeof l=="object"&&Object.assign(a,l)}};return a}}var Qt=require("url");var xe={};function $t(e){xe={...xe,...e}}function Ht(){if(!xe.routesDir)throw new Error("Routes directory not configured. Make sure server is properly initialized.");return xe.routesDir}var Ut=_(require("path"),1);function Ee(e,t){e.startsWith("file://")&&(e=e.replace("file://","")),t.startsWith("file://")&&(t=t.replace("file://",""));let r=e.replace(/\\/g,"/"),n=t.replace(/\\/g,"/"),o=n.endsWith("/")?n:`${n}/`,i=r;r.startsWith(o)?i=r.substring(o.length):r.startsWith(n)?(i=r.substring(n.length),i.startsWith("/")&&(i=i.substring(1))):i=Ut.relative(n,r).replace(/\\/g,"/"),i=i.replace(/\.[^.]+$/,"");let s=i.split("/").filter(Boolean),a=[],c=s.map(p=>{if(p.startsWith("[")&&p.endsWith("]")){let g=p.slice(1,-1);return a.push(g),`:${g}`}return p}),l=c.length>0?`/${c.join("/")}`:"/";return l.endsWith("/index")&&(l=l.slice(0,-6)||"/"),{filePath:e,routePath:l,params:a}}var jt=require("events");var O=require("zod"),Cn=O.z.enum(["drop-oldest","drop-newest","close"]),Pn=O.z.object({low:O.z.number().int().positive().describe("Resume threshold in messages"),high:O.z.number().int().positive().describe("Trigger threshold in messages")}).refine(e=>e.low<e.high,{message:"Low watermark must be less than high watermark",path:["low"]}),_n=O.z.object({maxMessages:O.z.number().int().positive().max(1e5).describe("Maximum number of messages in buffer"),maxBytes:O.z.number().int().positive().max(100*1024*1024).optional().describe("Maximum buffer size in bytes"),messageTimeout:O.z.number().int().nonnegative().max(3e5).optional().describe("Message TTL in milliseconds")}),qt=O.z.object({enabled:O.z.boolean().default(!0).describe("Enable backpressure management"),strategy:Cn.default("drop-oldest").describe("Strategy when buffer reaches high watermark"),watermarks:Pn.default({low:100,high:1e3}).describe("Buffer watermark thresholds"),limits:_n.default({maxMessages:1e4}).describe("Buffer size constraints"),metrics:O.z.object({enabled:O.z.boolean().default(!1),interval:O.z.number().int().positive().default(5e3)}).optional().describe("Metrics collection configuration")}).refine(e=>e.watermarks.high<=e.limits.maxMessages,{message:"High watermark cannot exceed maxMessages limit",path:["watermarks","high"]});var Mn={maxConnections:1e4,maxConnectionsPerClient:100,inactiveTimeout:18e5,cleanupInterval:6e4};function On(e){let t={...Mn,...e},r=new Map,n=new Map,o=null,i={},s=d=>{!o&&t.cleanupInterval>0&&(o=setInterval(()=>{d()},t.cleanupInterval),o.unref&&o.unref())},a=()=>{o&&(clearInterval(o),o=null)},c=(d,S)=>{if(!d)return;let h=(n.get(d)||0)+S;h<=0?n.delete(d):n.set(d,h)},l=(d,S,E)=>{if(r.has(d))throw new Error(`Connection with ID ${d} already exists`);if(r.size>=t.maxConnections)throw new Error(`Maximum connection limit reached (${t.maxConnections})`);if(E?.clientIp&&(n.get(E.clientIp)||0)>=t.maxConnectionsPerClient)throw new Error(`Maximum connections per client reached (${t.maxConnectionsPerClient})`);let h=Date.now();r.set(d,{stream:S,connectedAt:h,lastActivity:h,clientIp:E?.clientIp,userAgent:E?.userAgent}),c(E?.clientIp,1),r.size===1&&s(i.cleanup),S.onClose(()=>{p(d)})},p=d=>{let S=r.get(d);S&&(r.delete(d),c(S.clientIp,-1),r.size===0&&a())},g=()=>r.size,x=()=>{let d=Date.now(),S=[];r.forEach((E,h)=>{let k=d-E.lastActivity>t.inactiveTimeout,Jr=!E.stream||E.stream.state==="closed"||!E.stream.isWritable;if((k||Jr)&&(S.push(h),E.stream&&typeof E.stream.close=="function"))try{E.stream.close()}catch{}}),S.forEach(E=>p(E))},v=d=>r.get(d)?.stream,u=d=>r.has(d),f=()=>Array.from(r.keys()),m=()=>{a(),r.forEach(d=>{if(d.stream&&typeof d.stream.close=="function")try{d.stream.close()}catch{}}),r.clear(),n.clear()};return i.add=l,i.remove=p,i.count=g,i.cleanup=x,i.get=v,i.has=u,i.getIds=f,i.shutdown=m,i}var Xe=null;function ve(e){return Xe||(Xe=On(e)),Xe}b();R();var re=class extends w{constructor(t,r,n=void 0){super("SSE_BUFFER_OVERFLOW",t,503,n??y(),r)}};b();R();var Te=class extends w{constructor(t,r=void 0,n=void 0){super("SSE_STREAM_CLOSED",t,410,n??y(),r)}};R();var An={heartbeatInterval:3e4,maxEventSize:1024*1024,autoClose:!0,maxBufferSize:1e3,bufferStrategy:"drop-oldest"};function Lt(e,t,r,n){let o=[];r&&o.push(`id: ${r}`),n!==void 0&&o.push(`retry: ${n}`),o.push(`event: ${e}`);let s=(t===null?"null":t===void 0?"undefined":typeof t=="string"?t:JSON.stringify(t)).split(`
13
+ `);for(let a of s)o.push(`data: ${a}`);return o.push(""),o.join(`
14
+ `)+`
15
+ `}function Fn(){let e=Date.now().toString(36),t=Math.random().toString(36).substr(2,9);return`${e}-${t}`}function kn(e,t){let r=t===null?"null":t===void 0?"undefined":typeof t=="string"?t:JSON.stringify(t);return e.length+r.length+50}function In(e,t,r,n){let o=0;switch(t){case"drop-oldest":{for(;e.length>=n&&e.length>0;)e.shift(),o++;e.push(r);break}case"drop-newest":{e.length>=n?o=1:e.push(r);break}case"close":break;default:for(;e.length>=n&&e.length>0;)e.shift(),o++;e.push(r)}return{buffer:e,dropped:o}}var et=class{id;_state="connecting";_buffer=[];_closeCallbacks=[];_errorCallbacks=[];_emitter=new jt.EventEmitter;_metrics;_options;_response;_request;_writable=!0;_cleanupExecuted=!1;_eventCounter=0;_lastEventId=null;_heartbeatTimer;_backpressureConfig;_disconnectHandlers=null;constructor(t,r={}){if(this.id=`sse-${Fn()}`,this._options={...An,...r},this._response=t.response,this._request=t.request,r.backpressure){let o=qt.safeParse(r.backpressure);o.success&&(this._backpressureConfig=o.data,this._options.maxBufferSize=o.data.limits.maxMessages,this._options.bufferStrategy=o.data.strategy)}let n=t.request.header("last-event-id");n&&(this._eventCounter=parseInt(n)||0,this._lastEventId=n),this._metrics={eventsSent:0,eventsDropped:0,bytesWritten:0,bufferHighWatermark:0,lastEventTime:Date.now()};try{let o=ve(),i={clientIp:this._request.header("x-forwarded-for")||this._request.header("x-real-ip")||this._request.raw.socket?.remoteAddress,userAgent:this._request.header("user-agent")};o.add(this.id,this,i)}catch(o){throw this._state="closed",this._writable=!1,console.error("[SSE] Failed to register connection:",o),o}this._setupDisconnectHandling(),this._response.status(200).header("Content-Type","text/event-stream").header("Cache-Control","no-cache").header("X-Accel-Buffering","no"),(!this._request.raw.httpVersionMajor||this._request.raw.httpVersionMajor<2)&&this._response.header("Connection","keep-alive"),this._options.heartbeatInterval&&this._options.heartbeatInterval>0&&this._setupHeartbeat(this._options.heartbeatInterval),this._state="connected",this._writeRaw(`: SSE connection established
16
+
17
+ `)}_registerConnection(){try{let t=ve(),r={clientIp:this._request.header("x-forwarded-for")||this._request.header("x-real-ip")||this._request.raw.socket?.remoteAddress,userAgent:this._request.header("user-agent")};t.add(this.id,this,r)}catch(t){throw this._state="closed",this._writable=!1,t}}_setupHeartbeat(t){this._heartbeatTimer=global.setInterval(()=>{this.isWritable&&Date.now()-this._metrics.lastEventTime>t*.9&&this.ping(`heartbeat ${new Date().toISOString()}`)},t),this._heartbeatTimer.unref&&this._heartbeatTimer.unref()}_setupDisconnectHandling(){let t=this._request.raw,r=this._response.raw,n=()=>{this._options.autoClose&&this._state!=="closed"&&this.close()};this._disconnectHandlers={req:{close:n,error:n},res:{close:n,error:n}},t.on("close",this._disconnectHandlers.req.close),t.on("error",this._disconnectHandlers.req.error),r.on("close",this._disconnectHandlers.res.close),r.on("error",this._disconnectHandlers.res.error)}_writeRaw(t){if(!this._writable||this._state==="closed")return!1;try{let r=this._response.raw,n;if("write"in r&&typeof r.write=="function")n=r.write(t);else throw new Error("Response stream does not support write operation");return n&&(this._metrics.bytesWritten+=Buffer.byteLength(t)),n}catch(r){return this._writable=!1,this._handleError(r),!1}}async _flushBuffer(){for(;this._buffer.length>0&&this._writable;){let t=this._buffer.shift();if(!t)break;let r=Lt(t.event,t.data,t.id);this._writeRaw(r)?(this._metrics.eventsSent++,this._metrics.lastEventTime=Date.now()):(this._buffer.unshift(t),await this._waitForDrain())}}_waitForDrain(){return new Promise(t=>{this._response.raw.once("drain",t)})}_handleError(t){this._errorCallbacks.forEach(r=>{try{r(t)}catch(n){console.error("Error in error callback:",n)}}),this._writable&&this.sendError(t)}_executeCleanup(){if(this._cleanupExecuted)return;if(this._cleanupExecuted=!0,this._heartbeatTimer&&(global.clearInterval(this._heartbeatTimer),this._heartbeatTimer=void 0),this._disconnectHandlers){let r=this._request.raw,n=this._response.raw;r.removeListener("close",this._disconnectHandlers.req.close),r.removeListener("error",this._disconnectHandlers.req.error),n.removeListener("close",this._disconnectHandlers.res.close),n.removeListener("error",this._disconnectHandlers.res.error),this._disconnectHandlers=null}try{ve().remove(this.id)}catch(r){console.error("Registry cleanup error:",r)}let t=[...this._closeCallbacks];for(let r of t)try{let n=r();n&&typeof n.then=="function"&&n.catch(o=>{console.error("Error in async close callback:",o)})}catch(n){console.error("Error in close callback:",n)}this._closeCallbacks=[],this._errorCallbacks=[],this._buffer=[],this._emitter.removeAllListeners()}get state(){return this._state}get bufferSize(){return this._buffer.length}get isWritable(){return this._writable&&this._state==="connected"}send(t,r){if(!this.isWritable)throw new Te("Cannot send event to closed stream",{clientId:this.id,closedAt:new Date().toISOString(),closeReason:"server-close",canReconnect:!1});let n=String(++this._eventCounter);this._lastEventId=n;let o=y(),i=kn(t,r),s=this._options.maxEventSize;if(i>s)throw new re("Event size exceeds maximum allowed",{currentSize:i,maxSize:s,strategy:"close",clientId:this.id,eventsDropped:0,triggeringEvent:t});let a={id:n,event:t,data:r,size:i,timestamp:Date.now(),correlationId:o},c=this._backpressureConfig?this._backpressureConfig.watermarks.high:this._options.maxBufferSize;if(this._buffer.length>=c){if(this._options.bufferStrategy==="close"){let p=this._buffer.length;throw this.close(),new re("Buffer overflow - stream closed",{currentSize:p,maxSize:c,strategy:"close",clientId:this.id})}let l=In(this._buffer,this._options.bufferStrategy,a,c);this._buffer=l.buffer,this._metrics.eventsDropped+=l.dropped,l.dropped>0&&console.warn(`SSE stream ${this.id}: Dropped ${l.dropped} events due to buffer overflow`)}else this._buffer.push(a);this._metrics.bufferHighWatermark=Math.max(this._metrics.bufferHighWatermark,this._buffer.length),this._emitter.emit("event"),this._flushBuffer().catch(l=>{this._handleError(l)})}sendError(t){if(!this.isWritable)return;let r={message:t.message,name:t.name,correlationId:y(),timestamp:new Date().toISOString(),stack:process.env.NODE_ENV==="development"?t.stack:void 0};try{this.send("error",r)}catch(n){console.error("Failed to send error event:",n)}}close(){if(this._state!=="closed"){this._state="closed",this._writable=!1,this._emitter.emit("close");try{let t=Lt("close",{reason:"stream-closed",reconnect:!1}),r=this._response.raw;"write"in r&&typeof r.write=="function"&&r.write(t)}catch{}try{let t=this._response.raw;!t.writableEnded&&typeof t.end=="function"&&t.end()}catch(t){console.error("Error ending response:",t)}this._executeCleanup()}}onClose(t){if(this._state==="closed")try{let r=t();r&&typeof r.then=="function"&&r.catch(n=>{console.error("Error in close callback:",n)})}catch(r){console.error("Error in close callback:",r)}else this._closeCallbacks.push(t)}ping(t){if(!this.isWritable)return;let r=t?`: ${t}
18
+
19
+ `:`: ping
20
+
21
+ `;this._writeRaw(r)}setRetry(t){if(this.isWritable){if(t<0||!Number.isFinite(t))throw new Error("Retry interval must be a positive number");this._writeRaw(`retry: ${Math.floor(t)}
22
+
23
+ `)}}flush(){this.isWritable&&this._flushBuffer().catch(t=>{this._handleError(t)})}getMetrics(){return{...this._metrics}}async*[Symbol.asyncIterator](){for(;this.isWritable;){for(;this._buffer.length>0;){let t=this._buffer.shift();t&&(yield t)}await new Promise(t=>{let r=()=>{(this._buffer.length>0||!this.isWritable)&&(this._emitter.off("event",r),this._emitter.off("close",r),t())};this._emitter.on("event",r),this._emitter.on("close",r)})}}};function Vt(e,t){return new et(e,t)}b();R();var Re=class extends w{constructor(t,r,n){super("SSE_NOT_ACCEPTABLE",t,406,n||y(),r)}};function Dn(e){if(!e.handler||typeof e.handler!="function")throw new Error("SSE route handler must be a function");if(e.middleware&&!Array.isArray(e.middleware))throw new Error("Middleware for SSE route must be an array");if(e.schema){let{params:t,query:r,events:n}=e.schema;if(t&&(!t._def||typeof t.parse!="function"))throw new Error("Params schema for SSE must be a valid Zod schema");if(r&&(!r._def||typeof r.parse!="function"))throw new Error("Query schema for SSE must be a valid Zod schema");if(n){if(typeof n=="object"&&!n._def){for(let[o,i]of Object.entries(n))if(!i||typeof i!="object"||!i._def||typeof i.parse!="function")throw new Error(`Event schema for '${o}' must be a valid Zod schema`)}else if(!(n._def&&typeof n.parse=="function"))throw new Error("Events schema for SSE must be a valid Zod schema or event map")}}}function zn(e,t){let r=Object.create(e),n=e.send.bind(e);return r.send=function(o,i){let s=t[o];if(s)try{let a=s.parse(i);n(o,a)}catch(a){e.sendError(new Error(`Event '${o}' validation failed: ${a instanceof Error?a.message:String(a)}`))}else n(o,i)},r}var Wt=()=>e=>{Dn(e);let t=D();return{GET:{handler:async(n,o)=>{let i=n.request.header("accept");if(i&&!i.includes("text/event-stream")&&!i.includes("*/*"))throw new Re("This endpoint requires Server-Sent Events support",{acceptHeader:i,requiredHeader:"text/event-stream",endpoint:n.request.path});if(e.schema)try{e.schema.params&&(o=e.schema.params.parse(o)),e.schema.query&&(n.request.query=e.schema.query.parse(n.request.query))}catch(c){throw console.error("[SSE] Validation error:",c),c}let s=Vt(n,e.options),a=e.schema?.events&&typeof e.schema.events=="object"&&!e.schema.events._def?zn(s,e.schema.events):s;n.request.raw.on("close",()=>a.close());try{await e.handler(a,n,o)}catch(c){throw console.error("[SSE] Handler error - THIS IS THE REAL ERROR:",c),console.error("[SSE] Stack trace:",c instanceof Error?c.stack:"No stack"),a.isWritable&&a.sendError(c instanceof Error?c:new Error(String(c))),a.close(),c}},schema:e.schema?.params||e.schema?.query?{params:e.schema?.params,query:e.schema?.query}:void 0,middleware:e.middleware,options:e.options},path:t}};function Nn(){let e=Error.prepareStackTrace;try{Error.prepareStackTrace=(o,i)=>i;let r=new Error().stack[3];if(!r||typeof r.getFileName!="function")throw new Error("Unable to determine caller file frame");let n=r.getFileName();if(!n)throw new Error("Unable to determine caller file name");return n.startsWith("file://")?(0,Qt.fileURLToPath)(n):n}finally{Error.prepareStackTrace=e}}function D(){let e=Nn(),t=Ht(),r=Ee(e,t);return console.log(`\u{1F50E} Parsed route path: ${r.routePath} from file: ${e}`),r.routePath}var be=()=>e=>{W("GET",e);let t=D();return{GET:e,path:t}},Ce=()=>e=>{W("POST",e);let t=D();return{POST:e,path:t}},Pe=()=>e=>{W("PUT",e);let t=D();return{PUT:e,path:t}},_e=()=>e=>{W("DELETE",e);let t=D();return{DELETE:e,path:t}},Me=()=>e=>{W("PATCH",e);let t=D();return{PATCH:e,path:t}},Oe=()=>e=>{W("HEAD",e);let t=D();return{HEAD:e,path:t}},Ae=()=>e=>{W("OPTIONS",e);let t=D();return{OPTIONS:e,path:t}};function W(e,t){if(!t.handler||typeof t.handler!="function")throw new Error(`Handler for method ${e} must be a function`);if(t.middleware&&!Array.isArray(t.middleware))throw new Error(`Middleware for method ${e} must be an array`);switch(t.schema&&Bn(e,t.schema),e){case"GET":case"HEAD":case"DELETE":t.schema?.body&&console.warn(`Warning: ${e} requests typically don't have request bodies`);break}}function Bn(e,t){let{params:r,query:n,body:o,response:i}=t;if(r&&(!r._def||typeof r.parse!="function"))throw new Error(`Params schema for ${e} must be a valid Zod schema`);if(n&&(!n._def||typeof n.parse!="function"))throw new Error(`Query schema for ${e} must be a valid Zod schema`);if(o&&(!o._def||typeof o.parse!="function"))throw new Error(`Body schema for ${e} must be a valid Zod schema`);if(i&&(!i._def||typeof i.parse!="function"))throw new Error(`Response schema for ${e} must be a valid Zod schema`)}function tt(){return{get:be(),post:Ce(),put:Pe(),delete:_e(),patch:Me(),head:Oe(),options:Ae(),sse:Wt()}}function Q(e,t,r){let n=t.exec(e);if(!n)return{};let o={};for(let i=0;i<r.length;i++)o[r[i]]=n[i+1]||"";return o}function J(e){let t=[];if(e==="/")return{pattern:/^\/$/,paramNames:[]};let r=e.replace(/([.+*?^$(){}|\\])/g,"\\$1");return r=r.replace(/\/:([^/]+)/g,(o,i)=>(t.push(i),"/([^/]+)")).replace(/\/\[([^\]]+)\]/g,(o,i)=>(t.push(i),"/([^/]+)")),r=`${r}(?:/)?`,{pattern:new RegExp(`^${r}$`),paramNames:t}}function ne(e){let t=[];for(let[r,n]of Object.entries(e))if(n!=null){let o=encodeURIComponent(r),i=encodeURIComponent(String(n));t.push(`${o}=${i}`)}return t.length>0?`?${t.join("&")}`:""}function Fe(e,t={},r={}){let n={},o={...r},i=[];e.replace(/\/:([^/]+)/g,(c,l)=>(i.push(l),"/"));for(let[c,l]of Object.entries(t))i.includes(c)?n[c]=l:o[c]=l;let s=e;for(let[c,l]of Object.entries(n))s=s.replace(`:${c}`,encodeURIComponent(String(l)));let a=ne(o);return s+a}function Y(){let e=[];return{add(t,r,n){let{pattern:o,paramNames:i}=J(t),s={path:t,method:r,pattern:o,paramNames:i,routeOptions:n},a=e.findIndex(c=>i.length<c.paramNames.length);a===-1?e.push(s):e.splice(a,0,s)},remove(t){for(let r=e.length-1;r>=0;r--)e[r].path===t&&e.splice(r,1)},clear(){e.length=0},match(t,r){let n=t.split("?")[0];if(!n)return null;for(let i of e){if(i.method!==r)continue;if(i.pattern.exec(n)){let a=Q(t,i.pattern,i.paramNames);return{route:i.routeOptions,params:a}}}return e.find(i=>i.method!==r&&i.pattern.test(t))?{route:null,params:{},methodNotAllowed:!0,allowedMethods:e.filter(i=>i.pattern.test(t)).map(i=>i.method)}:null},getRoutes(){return e.map(t=>({path:t.path,method:t.method}))},findRoutes(t){return e.filter(r=>r.pattern.test(t)).map(r=>({path:r.path,method:r.method,params:Q(t,r.pattern,r.paramNames)}))}}}var Lr=require("async_hooks"),jr=_(require("events"),1);var st=_(require("fs"),1),yr=_(require("http"),1),Sr=_(require("http2"),1);var z=_(require("fs"),1),ke=_(require("path"),1),Gt=_(require("selfsigned"),1);async function Zt(){let e=ke.join(process.cwd(),".blaizejs","certs"),t=ke.join(e,"dev.key"),r=ke.join(e,"dev.cert");if(z.existsSync(t)&&z.existsSync(r))return{keyFile:t,certFile:r};z.existsSync(e)||z.mkdirSync(e,{recursive:!0});let i=Gt.generate([{name:"commonName",value:"localhost"}],{days:365,algorithm:"sha256",keySize:2048,extensions:[{name:"basicConstraints",cA:!0},{name:"keyUsage",keyCertSign:!0,digitalSignature:!0,nonRepudiation:!0,keyEncipherment:!0,dataEncipherment:!0},{name:"extKeyUsage",serverAuth:!0,clientAuth:!0},{name:"subjectAltName",altNames:[{type:2,value:"localhost"},{type:7,ip:"127.0.0.1"}]}]});return z.writeFileSync(t,Buffer.from(i.private,"utf-8")),z.writeFileSync(r,Buffer.from(i.cert,"utf-8")),console.log(`
11
24
  \u{1F512} Generated self-signed certificates for development at ${e}
12
- `),{keyFile:t,certFile:r}}var C=class extends Error{constructor(t="\u274C Response has already been sent"){super(t),this.name="ResponseSentError"}},G=class extends C{constructor(t="Cannot set header after response has been sent"){super(t)}},Se=class extends C{constructor(t="Cannot set content type after response has been sent"){super(t)}},we=class extends C{constructor(t="Invalide URL"){super(t)}};var mt=require("async_hooks"),Mr=new mt.AsyncLocalStorage;function gt(e,t){return Mr.run(e,t)}v();var bt=R(require("crypto"),1),Ct=require("fs"),Mt=require("os"),Ft=require("path"),Le=require("stream");var Or=/boundary=([^;]+)/i,Ir=/Content-Disposition:\s*form-data;\s*name="([^"]+)"(?:;[\s\r\n]*filename="([^"]*)")?/i,Nr=/Content-Type:\s*([^\r\n]+)/i,Dr=/multipart\/form-data/i;function Tt(e){let t=e.match(Or);if(!t||!t[1])return null;let r=t[1].trim();return r.startsWith('"')&&r.endsWith('"')&&(r=r.slice(1,-1)),r||null}function xt(e){let t=e.match(Ir);return!t||!t[1]?null:{name:t[1],filename:t[2]!==void 0?t[2]:void 0}}function Rt(e){let t=e.match(Nr);return t&&t[1]?.trim()?t[1].trim():"application/octet-stream"}function vt(e){return Dr.test(e)}var Br={maxFileSize:10*1024*1024,maxFiles:10,maxFieldSize:1*1024*1024,allowedMimeTypes:[],allowedExtensions:[],strategy:"stream",tempDir:(0,Mt.tmpdir)(),computeHash:!1};function Ar(e,t={}){return{boundary:Buffer.from(`--${e}`),options:{...Br,...t},fields:new Map,files:new Map,buffer:Buffer.alloc(0),stage:"boundary",currentHeaders:"",currentField:null,currentFilename:void 0,currentMimetype:"application/octet-stream",currentContentLength:0,fileCount:0,fieldCount:0,currentBufferChunks:[],currentStream:null,currentTempPath:null,currentWriteStream:null,streamController:null,cleanupTasks:[],hasFoundValidBoundary:!1,hasProcessedAnyPart:!1,isFinished:!1}}async function $r(e,t){let r=Buffer.concat([e.buffer,t]),n={...e,buffer:r};for(;n.buffer.length>0&&!n.isFinished;){let o=await _r(n);if(o===n)break;n=o}return n}async function _r(e){switch(e.stage){case"boundary":return Ur(e);case"headers":return Lr(e);case"content":return Hr(e);default:{let{InternalServerError:t}=await Promise.resolve().then(()=>(Z(),Pt));throw new t("Invalid parser stage",{operation:e.stage})}}}function Ur(e){let t=e.buffer.indexOf(e.boundary);if(t===-1)return e;let r=!0,n=e.buffer.subarray(t+e.boundary.length);return n.length>=2&&n.subarray(0,2).equals(Buffer.from("--"))?{...e,buffer:n,hasFoundValidBoundary:r,isFinished:!0,stage:"boundary"}:(n.length>=2&&n.subarray(0,2).equals(Buffer.from(`\r
13
- `))&&(n=n.subarray(2)),{...e,buffer:n,hasFoundValidBoundary:r,stage:"headers",currentHeaders:""})}async function Lr(e){let t=e.buffer.indexOf(`\r
25
+ `),{keyFile:t,certFile:r}}var A=class extends Error{constructor(t="\u274C Response has already been sent"){super(t),this.name="ResponseSentError"}},oe=class extends A{constructor(t="Cannot set header after response has been sent"){super(t)}},Ie=class extends A{constructor(t="Cannot set content type after response has been sent"){super(t)}},De=class extends A{constructor(t="Invalide URL"){super(t)}};var Jt=require("async_hooks"),$n=new Jt.AsyncLocalStorage;function Yt(e,t){return $n.run(e,t)}R();var nr=_(require("crypto"),1),or=require("fs"),ir=require("os"),sr=require("path"),ot=require("stream");var Hn=/boundary=([^;]+)/i,Un=/Content-Disposition:\s*form-data;\s*name="([^"]+)"(?:;[\s\r\n]*filename="([^"]*)")?/i,qn=/Content-Type:\s*([^\r\n]+)/i,Ln=/multipart\/form-data/i;function Kt(e){let t=e.match(Hn);if(!t||!t[1])return null;let r=t[1].trim();return r.startsWith('"')&&r.endsWith('"')&&(r=r.slice(1,-1)),r||null}function Xt(e){let t=e.match(Un);return!t||!t[1]?null:{name:t[1],filename:t[2]!==void 0?t[2]:void 0}}function er(e){let t=e.match(qn);return t&&t[1]?.trim()?t[1].trim():"application/octet-stream"}function tr(e){return Ln.test(e)}var jn={maxFileSize:10*1024*1024,maxFiles:10,maxFieldSize:1*1024*1024,allowedMimeTypes:[],allowedExtensions:[],strategy:"stream",tempDir:(0,ir.tmpdir)(),computeHash:!1};function Vn(e,t={}){return{boundary:Buffer.from(`--${e}`),options:{...jn,...t},fields:new Map,files:new Map,buffer:Buffer.alloc(0),stage:"boundary",currentHeaders:"",currentField:null,currentFilename:void 0,currentMimetype:"application/octet-stream",currentContentLength:0,fileCount:0,fieldCount:0,currentBufferChunks:[],currentStream:null,currentTempPath:null,currentWriteStream:null,streamController:null,cleanupTasks:[],hasFoundValidBoundary:!1,hasProcessedAnyPart:!1,isFinished:!1}}async function Wn(e,t){let r=Buffer.concat([e.buffer,t]),n={...e,buffer:r};for(;n.buffer.length>0&&!n.isFinished;){let o=await Qn(n);if(o===n)break;n=o}return n}async function Qn(e){switch(e.stage){case"boundary":return Gn(e);case"headers":return Zn(e);case"content":return Jn(e);default:{let{InternalServerError:t}=await Promise.resolve().then(()=>(ie(),rr));throw new t("Invalid parser stage",{operation:e.stage})}}}function Gn(e){let t=e.buffer.indexOf(e.boundary);if(t===-1)return e;let r=!0,n=e.buffer.subarray(t+e.boundary.length);return n.length>=2&&n.subarray(0,2).equals(Buffer.from("--"))?{...e,buffer:n,hasFoundValidBoundary:r,isFinished:!0,stage:"boundary"}:(n.length>=2&&n.subarray(0,2).equals(Buffer.from(`\r
26
+ `))&&(n=n.subarray(2)),{...e,buffer:n,hasFoundValidBoundary:r,stage:"headers",currentHeaders:""})}async function Zn(e){let t=e.buffer.indexOf(`\r
14
27
  \r
15
- `);if(t===-1)return e;let r=e.buffer.subarray(0,t).toString("utf8"),n=e.buffer.subarray(t+4),o=xt(r);if(!o){let{ValidationError:a}=await Promise.resolve().then(()=>(N(),q));throw new a("Missing or invalid Content-Disposition header")}let i=Rt(r),s=o.filename!==void 0;if(s&&e.fileCount>=e.options.maxFiles){let{PayloadTooLargeError:a}=await Promise.resolve().then(()=>(Re(),_e));throw new a("Too many files in upload",{fileCount:e.fileCount+1,maxFiles:e.options.maxFiles,filename:o.filename})}if(s&&e.options.allowedMimeTypes.length>0&&!e.options.allowedMimeTypes.includes(i)){let{UnsupportedMediaTypeError:a}=await Promise.resolve().then(()=>(ve(),Ue));throw new a("File type not allowed",{receivedMimeType:i,allowedMimeTypes:e.options.allowedMimeTypes,filename:o.filename})}return{...e,buffer:n,stage:"content",currentHeaders:r,currentField:o.name,currentFilename:o.filename,currentMimetype:i,currentContentLength:0,fileCount:s?e.fileCount+1:e.fileCount,fieldCount:s?e.fieldCount:e.fieldCount+1,currentBufferChunks:[]}}async function Hr(e){let t=e.buffer.indexOf(e.boundary),r,n=!1,o=e.buffer;if(t===-1){let s=Math.max(0,e.buffer.length-e.boundary.length);if(s===0)return e;r=e.buffer.subarray(0,s),o=e.buffer.subarray(s)}else{let s=Math.max(0,t-2);r=e.buffer.subarray(0,s),o=e.buffer.subarray(t),n=!0}let i={...e,buffer:o};return r.length>0&&(i=await qr(i,r)),n&&(i=await Qr(i),i={...i,stage:"boundary",hasProcessedAnyPart:!0}),i}async function qr(e,t){let r=e.currentContentLength+t.length,n=e.currentFilename!==void 0?e.options.maxFileSize:e.options.maxFieldSize;if(r>n){let o=e.currentFilename!==void 0,{PayloadTooLargeError:i}=await Promise.resolve().then(()=>(Re(),_e)),s=e.currentField?{contentType:o?"file":"field",currentSize:r,maxSize:n,field:e.currentField,filename:e.currentFilename}:{contentType:o?"file":"field",currentSize:r,maxSize:n,filename:e.currentFilename};throw new i(`${o?"File":"Field"} size exceeds limit`,s)}return e.currentFilename!==void 0?jr(e,t,r):{...e,currentContentLength:r,currentBufferChunks:[...e.currentBufferChunks,t]}}async function jr(e,t,r){switch(e.options.strategy){case"memory":return{...e,currentContentLength:r,currentBufferChunks:[...e.currentBufferChunks,t]};case"stream":return e.streamController&&e.streamController.enqueue(t),{...e,currentContentLength:r};case"temp":return e.currentWriteStream&&await Yr(e.currentWriteStream,t),{...e,currentContentLength:r};default:{let{ValidationError:n}=await Promise.resolve().then(()=>(N(),q));throw new n("Invalid parsing strategy")}}}async function Vr(e){if(e.currentFilename===void 0)return e;switch(e.options.strategy){case"memory":return{...e,currentBufferChunks:[]};case"stream":{let t=null,r=new ReadableStream({start:n=>{t=n}});return{...e,currentStream:r,streamController:t}}case"temp":{let t=(0,Ft.join)(e.options.tempDir,`upload-${bt.randomUUID()}`),r=(0,Ct.createWriteStream)(t),n=async()=>{try{let{unlink:o}=await import("fs/promises");await o(t)}catch(o){console.warn(`Failed to cleanup temp file: ${t}`,o)}};return{...e,currentTempPath:t,currentWriteStream:r,cleanupTasks:[...e.cleanupTasks,n]}}default:{let{ValidationError:t}=await Promise.resolve().then(()=>(N(),q));throw new t("Invalid file processing strategy")}}}async function Qr(e){return e.currentField?e.currentFilename!==void 0?Wr(e):Gr(e):K(e)}async function Wr(e){if(!e.currentField||e.currentFilename===void 0)return K(e);let t,r,n;switch(e.options.strategy){case"memory":r=Buffer.concat(e.currentBufferChunks),t=Le.Readable.from(r);break;case"stream":e.streamController&&e.streamController.close(),t=e.currentStream;break;case"temp":e.currentWriteStream&&await Ot(e.currentWriteStream),n=e.currentTempPath,t=Le.Readable.from(Buffer.alloc(0));break;default:{let{ValidationError:s}=await Promise.resolve().then(()=>(N(),q));throw new s("Invalid file finalization strategy")}}let o={filename:e.currentFilename,fieldname:e.currentField,mimetype:e.currentMimetype,size:e.currentContentLength,stream:t,buffer:r,tempPath:n},i=kt(e.files,e.currentField,o);return{...K(e),files:i}}function Gr(e){if(!e.currentField)return K(e);let t=Buffer.concat(e.currentBufferChunks).toString("utf8"),r=kt(e.fields,e.currentField,t);return{...K(e),fields:r}}function K(e){return{...e,currentField:null,currentFilename:void 0,currentContentLength:0,currentBufferChunks:[],currentStream:null,streamController:null,currentTempPath:null,currentWriteStream:null}}function kt(e,t,r){let n=new Map(e),o=n.get(t)||[];return n.set(t,[...o,r]),n}async function Zr(e){if(!e.hasFoundValidBoundary){let{ValidationError:n}=await Promise.resolve().then(()=>(N(),q));throw new n("No valid multipart boundary found")}if(e.hasFoundValidBoundary&&!e.hasProcessedAnyPart){let{ValidationError:n}=await Promise.resolve().then(()=>(N(),q));throw new n("Empty multipart request")}let t={};for(let[n,o]of e.fields.entries())t[n]=o.length===1?o[0]:o;let r={};for(let[n,o]of e.files.entries())r[n]=o.length===1?o[0]:o;return{fields:t,files:r}}async function Jr(e){await Promise.allSettled(e.cleanupTasks.map(t=>t())),e.streamController&&e.streamController.close(),e.currentWriteStream&&await Ot(e.currentWriteStream)}async function Yr(e,t){return new Promise((r,n)=>{e.write(t,o=>{o?n(o):r()})})}async function Ot(e){return new Promise(t=>{e.end(()=>t())})}async function It(e,t={}){let r=e.headers["content-type"]||"",n=Tt(r);if(!n){let{UnsupportedMediaTypeError:i}=await Promise.resolve().then(()=>(ve(),Ue));throw new i("Missing boundary in multipart content-type",{receivedContentType:r,expectedFormat:"multipart/form-data; boundary=..."})}let o=Ar(n,t);o.currentFilename!==void 0&&(o=await Vr(o));try{for await(let i of e)o=await $r(o,i);return Zr(o)}finally{await Jr(o)}}var X="Content-Type",D={json:512*1024,form:1024*1024,text:5*1024*1024,multipart:{maxFileSize:50*1024*1024,maxTotalSize:100*1024*1024,maxFiles:10,maxFieldSize:1024*1024},raw:10*1024*1024};function Kr(e){let t=e.url||"/",r=e.headers.host||"localhost",o=`${e.socket&&e.socket.encrypted?"https":"http"}://${r}${t.startsWith("/")?"":"/"}${t}`;try{let i=new URL(o),s=i.pathname,a={};return i.searchParams.forEach((u,l)=>{a[l]!==void 0?Array.isArray(a[l])?a[l].push(u):a[l]=[a[l],u]:a[l]=u}),{path:s,url:i,query:a}}catch(i){throw console.warn(`Invalid URL: ${o}`,i),new we(`Invalid URL: ${o}`)}}function Xr(e){return"stream"in e||"httpVersionMajor"in e&&e.httpVersionMajor===2}function en(e){let t=e.socket&&e.socket.encrypted,r=e.headers["x-forwarded-proto"];return r?Array.isArray(r)?r[0]?.split(",")[0]?.trim()||"http":r.split(",")[0]?.trim()||"http":t?"https":"http"}async function Nt(e,t,r={}){let{path:n,url:o,query:i}=Kr(e),s=e.method||"GET",a=Xr(e),u=en(e),l={},T={...r.initialState||{}},p={...r.initialServices||{}},S={sent:!1},m={request:tn(e,{path:n,url:o,query:i,params:l,method:s,isHttp2:a,protocol:u}),response:{},state:T,services:p};return m.response=nn(t,S,m),r.parseBody&&await mn(e,m,r),m}function tn(e,t){return{raw:e,...t,header:Dt(e),headers:rn(e),body:void 0}}function Dt(e){return t=>{let r=e.headers[t.toLowerCase()];return Array.isArray(r)?r.join(", "):r||void 0}}function rn(e){let t=Dt(e);return r=>r&&Array.isArray(r)&&r.length>0?r.reduce((n,o)=>(n[o]=t(o),n),{}):Object.entries(e.headers).reduce((n,[o,i])=>(n[o]=Array.isArray(i)?i.join(", "):i||void 0,n),{})}function ee(e,t){if(t.correlationId){let r=H(),n=String(t.correlationId);e.setHeader(r,n)}}function nn(e,t,r){return{raw:e,get statusCode(){return e.statusCode||200},get sent(){return t.sent},status:on(e,t,r),header:sn(e,t,r),headers:an(e,t,r),type:un(e,t,r),json:cn(e,t,r.state),text:ln(e,t,r.state),html:dn(e,t,r.state),redirect:pn(e,t,r.state),stream:fn(e,t,r.state)}}function on(e,t,r){return function(o){if(t.sent)throw new C;return e.statusCode=o,r.response}}function sn(e,t,r){return function(o,i){if(t.sent)throw new G;return e.setHeader(o,i),r.response}}function an(e,t,r){return function(o){if(t.sent)throw new G;for(let[i,s]of Object.entries(o))e.setHeader(i,s);return r.response}}function un(e,t,r){return function(o){if(t.sent)throw new Se;return e.setHeader(X,o),r.response}}function cn(e,t,r){return function(o,i){if(t.sent)throw new C;i!==void 0&&(e.statusCode=i),ee(e,r),e.setHeader(X,"application/json"),e.end(JSON.stringify(o)),t.sent=!0}}function ln(e,t,r){return function(o,i){if(t.sent)throw new C;i!==void 0&&(e.statusCode=i),ee(e,r),e.setHeader(X,"text/plain"),e.end(o),t.sent=!0}}function dn(e,t,r){return function(o,i){if(t.sent)throw new C;i!==void 0&&(e.statusCode=i),ee(e,r),e.setHeader(X,"text/html"),e.end(o),t.sent=!0}}function pn(e,t,r){return function(o,i=302){if(t.sent)throw new C;ee(e,r),e.statusCode=i,e.setHeader("Location",o),e.end(),t.sent=!0}}function fn(e,t,r){return function(o,i={}){if(t.sent)throw new C;if(i.status!==void 0&&(e.statusCode=i.status),ee(e,r),i.contentType&&e.setHeader(X,i.contentType),i.headers)for(let[s,a]of Object.entries(i.headers))e.setHeader(s,a);o.pipe(e),o.on("end",()=>{t.sent=!0}),o.on("error",s=>{console.error("Stream error:",s),t.sent||(e.statusCode=500,e.end("Stream error"),t.sent=!0)})}}async function mn(e,t,r={}){if(gn(e.method))return;let n=e.headers["content-type"]||"",o=parseInt(e.headers["content-length"]||"0",10);if(o===0)return;let i={json:r.bodyLimits?.json??D.json,form:r.bodyLimits?.form??D.form,text:r.bodyLimits?.text??D.text,raw:r.bodyLimits?.raw??D.raw,multipart:{maxFileSize:r.bodyLimits?.multipart?.maxFileSize??D.multipart.maxFileSize,maxFiles:r.bodyLimits?.multipart?.maxFiles??D.multipart.maxFiles,maxFieldSize:r.bodyLimits?.multipart?.maxFieldSize??D.multipart.maxFieldSize,maxTotalSize:r.bodyLimits?.multipart?.maxTotalSize??D.multipart.maxTotalSize}};try{if(n.includes("application/json")){if(o>i.json)throw new Error(`JSON body too large: ${o} > ${i.json} bytes`);await yn(e,t)}else if(n.includes("application/x-www-form-urlencoded")){if(o>i.form)throw new Error(`Form body too large: ${o} > ${i.form} bytes`);await hn(e,t)}else if(n.includes("text/")){if(o>i.text)throw new Error(`Text body too large: ${o} > ${i.text} bytes`);await wn(e,t)}else if(vt(n))await Tn(e,t,i.multipart);else{if(o>i.raw)throw new Error(`Request body too large: ${o} > ${i.raw} bytes`);return}}catch(s){let a=n.includes("multipart")?"multipart_parse_error":"body_read_error";Ee(t,a,"Error reading request body",s)}}function gn(e){return["GET","HEAD","OPTIONS"].includes(e||"GET")}async function yn(e,t){let r=await He(e);if(!r){console.warn("Empty body, skipping JSON parsing");return}if(r.trim()==="null"){console.warn('Body is the string "null"'),t.request.body=null;return}try{let n=JSON.parse(r);t.request.body=n}catch(n){t.request.body=null,Ee(t,"json_parse_error","Invalid JSON in request body",n)}}async function hn(e,t){let r=await He(e);if(r)try{t.request.body=Sn(r)}catch(n){t.request.body=null,Ee(t,"form_parse_error","Invalid form data in request body",n)}}function Sn(e){let t=new URLSearchParams(e),r={};return t.forEach((n,o)=>{r[o]!==void 0?Array.isArray(r[o])?r[o].push(n):r[o]=[r[o],n]:r[o]=n}),r}async function wn(e,t){let r=await He(e);r&&(t.request.body=r)}async function Tn(e,t,r){try{let n=r||D.multipart,o=await It(e,{strategy:"stream",maxFileSize:n.maxFileSize,maxFiles:n.maxFiles,maxFieldSize:n.maxFieldSize});t.request.multipart=o,t.request.files=o.files,t.request.body=o.fields}catch(n){t.request.body=null,Ee(t,"multipart_parse_error","Failed to parse multipart data",n)}}function Ee(e,t,r,n){let o={type:t,message:r,error:n};e.state._bodyError=o}async function He(e){return new Promise((t,r)=>{let n=[];e.on("data",o=>{n.push(Buffer.isBuffer(o)?o:Buffer.from(o))}),e.on("end",()=>{t(Buffer.concat(n).toString("utf8"))}),e.on("error",o=>{r(o)})})}P();v();var z=class extends h{constructor(t,r=void 0,n=void 0){super("NOT_FOUND",t,404,n??y(),r)}};P();Z();v();function xn(e){return e instanceof h}function zt(e){if(xn(e))return{type:e.type,title:e.title,status:e.status,correlationId:e.correlationId,timestamp:e.timestamp.toISOString(),details:e.details};let t=y(),r;e instanceof Error?r=e.message:e==null?r="Unknown error occurred":r=String(e);let n=new O("Internal Server Error",{originalMessage:r},t);return{type:n.type,title:n.title,status:n.status,correlationId:n.correlationId,timestamp:n.timestamp.toISOString(),details:n.details}}function Bt(e){let t=H(),r={[t]:e(t)};return xe(r)}function At(e,t){let r=H();e(r,t)}function $t(e={}){let{debug:t=!1}=e;return{name:"ErrorBoundary",execute:async(n,o)=>{try{await o()}catch(i){if(n.response.sent){t&&console.error("Error occurred after response was sent:",i);return}t&&console.error("Error boundary caught error:",i);let s=Bt(n.request.header),a=zt(i);a.correlationId=s,At(n.response.header,s),n.response.status(a.status).json(a)}},debug:t}}v();function _t(e){return async(t,r)=>{let n=xe(t.headers);try{await wt(n,async()=>{let o=await Nt(t,r,{parseBody:!0,initialState:{correlationId:n}}),s=[$t(),...e.middleware],a=_(s);await gt(o,async()=>{await a(o,async()=>{if(!o.response.sent&&(await e.router.handleRequest(o),!o.response.sent))throw new z(`Route not found: ${o.request.method} ${o.request.path}`)})})})}catch(o){console.error("Error creating context:",o);let i=H();"stream"in r&&typeof r.stream?.respond=="function"?(r.stream.respond({":status":500,"content-type":"application/json",[i.toLowerCase()]:n}),r.stream.end(JSON.stringify({error:"Internal Server Error",message:"Failed to process request",correlationId:n}))):(r.setHeader(i,n),r.writeHead(500,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:"Internal Server Error",message:"Failed to process request",correlationId:n})))}}}async function Rn(e){if(!e.enabled)return{};let{keyFile:t,certFile:r}=e,n=process.env.NODE_ENV==="development",o=!t||!r;if(o&&n)return await ft();if(o)throw new Error("HTTP/2 requires SSL certificates. Provide keyFile and certFile in http2 options. In development, set NODE_ENV=development to generate them automatically.");return{keyFile:t,certFile:r}}function vn(e,t){if(!e)return Ut.createServer();let r={allowHTTP1:!0};try{t.keyFile&&(r.key=qe.readFileSync(t.keyFile)),t.certFile&&(r.cert=qe.readFileSync(t.certFile))}catch(n){throw new Error(`Failed to read certificate files: ${n instanceof Error?n.message:String(n)}`)}return Lt.createSecureServer(r)}function En(e,t,r,n){return new Promise((o,i)=>{e.listen(t,r,()=>{let a=`${n?"https":"http"}://${r}:${t}`;console.log(`
28
+ `);if(t===-1)return e;let r=e.buffer.subarray(0,t).toString("utf8"),n=e.buffer.subarray(t+4),o=Xt(r);if(!o){let{ValidationError:a}=await Promise.resolve().then(()=>(I(),V));throw new a("Missing or invalid Content-Disposition header")}let i=er(r),s=o.filename!==void 0;if(s&&e.fileCount>=e.options.maxFiles){let{PayloadTooLargeError:a}=await Promise.resolve().then(()=>(ze(),rt));throw new a("Too many files in upload",{fileCount:e.fileCount+1,maxFiles:e.options.maxFiles,filename:o.filename})}if(s&&e.options.allowedMimeTypes.length>0&&!e.options.allowedMimeTypes.includes(i)){let{UnsupportedMediaTypeError:a}=await Promise.resolve().then(()=>(Ne(),nt));throw new a("File type not allowed",{receivedMimeType:i,allowedMimeTypes:e.options.allowedMimeTypes,filename:o.filename})}return{...e,buffer:n,stage:"content",currentHeaders:r,currentField:o.name,currentFilename:o.filename,currentMimetype:i,currentContentLength:0,fileCount:s?e.fileCount+1:e.fileCount,fieldCount:s?e.fieldCount:e.fieldCount+1,currentBufferChunks:[]}}async function Jn(e){let t=e.buffer.indexOf(e.boundary),r,n=!1,o=e.buffer;if(t===-1){let s=Math.max(0,e.buffer.length-e.boundary.length);if(s===0)return e;r=e.buffer.subarray(0,s),o=e.buffer.subarray(s)}else{let s=Math.max(0,t-2);r=e.buffer.subarray(0,s),o=e.buffer.subarray(t),n=!0}let i={...e,buffer:o};return r.length>0&&(i=await Yn(i,r)),n&&(i=await eo(i),i={...i,stage:"boundary",hasProcessedAnyPart:!0}),i}async function Yn(e,t){let r=e.currentContentLength+t.length,n=e.currentFilename!==void 0?e.options.maxFileSize:e.options.maxFieldSize;if(r>n){let o=e.currentFilename!==void 0,{PayloadTooLargeError:i}=await Promise.resolve().then(()=>(ze(),rt)),s=e.currentField?{contentType:o?"file":"field",currentSize:r,maxSize:n,field:e.currentField,filename:e.currentFilename}:{contentType:o?"file":"field",currentSize:r,maxSize:n,filename:e.currentFilename};throw new i(`${o?"File":"Field"} size exceeds limit`,s)}return e.currentFilename!==void 0?Kn(e,t,r):{...e,currentContentLength:r,currentBufferChunks:[...e.currentBufferChunks,t]}}async function Kn(e,t,r){switch(e.options.strategy){case"memory":return{...e,currentContentLength:r,currentBufferChunks:[...e.currentBufferChunks,t]};case"stream":return e.streamController&&e.streamController.enqueue(t),{...e,currentContentLength:r};case"temp":return e.currentWriteStream&&await io(e.currentWriteStream,t),{...e,currentContentLength:r};default:{let{ValidationError:n}=await Promise.resolve().then(()=>(I(),V));throw new n("Invalid parsing strategy")}}}async function Xn(e){if(e.currentFilename===void 0)return e;switch(e.options.strategy){case"memory":return{...e,currentBufferChunks:[]};case"stream":{let t=null,r=new ReadableStream({start:n=>{t=n}});return{...e,currentStream:r,streamController:t}}case"temp":{let t=(0,sr.join)(e.options.tempDir,`upload-${nr.randomUUID()}`),r=(0,or.createWriteStream)(t),n=async()=>{try{let{unlink:o}=await import("fs/promises");await o(t)}catch(o){console.warn(`Failed to cleanup temp file: ${t}`,o)}};return{...e,currentTempPath:t,currentWriteStream:r,cleanupTasks:[...e.cleanupTasks,n]}}default:{let{ValidationError:t}=await Promise.resolve().then(()=>(I(),V));throw new t("Invalid file processing strategy")}}}async function eo(e){return e.currentField?e.currentFilename!==void 0?to(e):ro(e):ce(e)}async function to(e){if(!e.currentField||e.currentFilename===void 0)return ce(e);let t,r,n;switch(e.options.strategy){case"memory":r=Buffer.concat(e.currentBufferChunks),t=ot.Readable.from(r);break;case"stream":e.streamController&&e.streamController.close(),t=e.currentStream;break;case"temp":e.currentWriteStream&&await cr(e.currentWriteStream),n=e.currentTempPath,t=ot.Readable.from(Buffer.alloc(0));break;default:{let{ValidationError:s}=await Promise.resolve().then(()=>(I(),V));throw new s("Invalid file finalization strategy")}}let o={filename:e.currentFilename,fieldname:e.currentField,mimetype:e.currentMimetype,size:e.currentContentLength,stream:t,buffer:r,tempPath:n},i=ar(e.files,e.currentField,o);return{...ce(e),files:i}}function ro(e){if(!e.currentField)return ce(e);let t=Buffer.concat(e.currentBufferChunks).toString("utf8"),r=ar(e.fields,e.currentField,t);return{...ce(e),fields:r}}function ce(e){return{...e,currentField:null,currentFilename:void 0,currentContentLength:0,currentBufferChunks:[],currentStream:null,streamController:null,currentTempPath:null,currentWriteStream:null}}function ar(e,t,r){let n=new Map(e),o=n.get(t)||[];return n.set(t,[...o,r]),n}async function no(e){if(!e.hasFoundValidBoundary){let{ValidationError:n}=await Promise.resolve().then(()=>(I(),V));throw new n("No valid multipart boundary found")}if(e.hasFoundValidBoundary&&!e.hasProcessedAnyPart){let{ValidationError:n}=await Promise.resolve().then(()=>(I(),V));throw new n("Empty multipart request")}let t={};for(let[n,o]of e.fields.entries())t[n]=o.length===1?o[0]:o;let r={};for(let[n,o]of e.files.entries())r[n]=o.length===1?o[0]:o;return{fields:t,files:r}}async function oo(e){await Promise.allSettled(e.cleanupTasks.map(t=>t())),e.streamController&&e.streamController.close(),e.currentWriteStream&&await cr(e.currentWriteStream)}async function io(e,t){return new Promise((r,n)=>{e.write(t,o=>{o?n(o):r()})})}async function cr(e){return new Promise(t=>{e.end(()=>t())})}async function lr(e,t={}){let r=e.headers["content-type"]||"",n=Kt(r);if(!n){let{UnsupportedMediaTypeError:i}=await Promise.resolve().then(()=>(Ne(),nt));throw new i("Missing boundary in multipart content-type",{receivedContentType:r,expectedFormat:"multipart/form-data; boundary=..."})}let o=Vn(n,t);o.currentFilename!==void 0&&(o=await Xn(o));try{for await(let i of e)o=await Wn(o,i);return no(o)}finally{await oo(o)}}var le="Content-Type",B={json:512*1024,form:1024*1024,text:5*1024*1024,multipart:{maxFileSize:50*1024*1024,maxTotalSize:100*1024*1024,maxFiles:10,maxFieldSize:1024*1024},raw:10*1024*1024};function so(e){let t=e.url||"/",r=e.headers.host||"localhost",o=`${e.socket&&e.socket.encrypted?"https":"http"}://${r}${t.startsWith("/")?"":"/"}${t}`;try{let i=new URL(o),s=i.pathname,a={};return i.searchParams.forEach((c,l)=>{a[l]!==void 0?Array.isArray(a[l])?a[l].push(c):a[l]=[a[l],c]:a[l]=c}),{path:s,url:i,query:a}}catch(i){throw console.warn(`Invalid URL: ${o}`,i),new De(`Invalid URL: ${o}`)}}function ao(e){return"stream"in e||"httpVersionMajor"in e&&e.httpVersionMajor===2}function co(e){let t=e.socket&&e.socket.encrypted,r=e.headers["x-forwarded-proto"];return r?Array.isArray(r)?r[0]?.split(",")[0]?.trim()||"http":r.split(",")[0]?.trim()||"http":t?"https":"http"}async function ur(e,t,r={}){let{path:n,url:o,query:i}=so(e),s=e.method||"GET",a=ao(e),c=co(e),l={},p={...r.initialState||{}},g={...r.initialServices||{}},x={sent:!1},v={request:lo(e,{path:n,url:o,query:i,params:l,method:s,isHttp2:a,protocol:c}),response:{},state:p,services:g};return v.response=po(t,x,v),r.parseBody&&await vo(e,v,r),v}function lo(e,t){return{raw:e,...t,header:dr(e),headers:uo(e),body:void 0}}function dr(e){return t=>{let r=e.headers[t.toLowerCase()];return Array.isArray(r)?r.join(", "):r||void 0}}function uo(e){let t=dr(e);return r=>r&&Array.isArray(r)&&r.length>0?r.reduce((n,o)=>(n[o]=t(o),n),{}):Object.entries(e.headers).reduce((n,[o,i])=>(n[o]=Array.isArray(i)?i.join(", "):i||void 0,n),{})}function ue(e,t){if(t.correlationId){let r=j(),n=String(t.correlationId);e.setHeader(r,n)}}function po(e,t,r){return{raw:e,get statusCode(){return e.statusCode||200},get sent(){return t.sent},status:fo(e,t,r),header:mo(e,t,r),headers:go(e,t,r),type:ho(e,t,r),json:yo(e,t,r.state),text:So(e,t,r.state),html:wo(e,t,r.state),redirect:xo(e,t,r.state),stream:Eo(e,t,r.state)}}function fo(e,t,r){return function(o){if(t.sent)throw new A;return e.statusCode=o,r.response}}function mo(e,t,r){return function(o,i){if(t.sent)throw new oe;return e.setHeader(o,i),r.response}}function go(e,t,r){return function(o){if(t.sent)throw new oe;for(let[i,s]of Object.entries(o))e.setHeader(i,s);return r.response}}function ho(e,t,r){return function(o){if(t.sent)throw new Ie;return e.setHeader(le,o),r.response}}function yo(e,t,r){return function(o,i){if(t.sent)throw new A;i!==void 0&&(e.statusCode=i),ue(e,r),e.setHeader(le,"application/json"),e.end(JSON.stringify(o)),t.sent=!0}}function So(e,t,r){return function(o,i){if(t.sent)throw new A;i!==void 0&&(e.statusCode=i),ue(e,r),e.setHeader(le,"text/plain"),e.end(o),t.sent=!0}}function wo(e,t,r){return function(o,i){if(t.sent)throw new A;i!==void 0&&(e.statusCode=i),ue(e,r),e.setHeader(le,"text/html"),e.end(o),t.sent=!0}}function xo(e,t,r){return function(o,i=302){if(t.sent)throw new A;ue(e,r),e.statusCode=i,e.setHeader("Location",o),e.end(),t.sent=!0}}function Eo(e,t,r){return function(o,i={}){if(t.sent)throw new A;if(i.status!==void 0&&(e.statusCode=i.status),ue(e,r),i.contentType&&e.setHeader(le,i.contentType),i.headers)for(let[s,a]of Object.entries(i.headers))e.setHeader(s,a);o.pipe(e),o.on("end",()=>{t.sent=!0}),o.on("error",s=>{console.error("Stream error:",s),t.sent||(e.statusCode=500,e.end("Stream error"),t.sent=!0)})}}async function vo(e,t,r={}){if(To(e.method))return;let n=e.headers["content-type"]||"",o=parseInt(e.headers["content-length"]||"0",10);if(o===0)return;let i={json:r.bodyLimits?.json??B.json,form:r.bodyLimits?.form??B.form,text:r.bodyLimits?.text??B.text,raw:r.bodyLimits?.raw??B.raw,multipart:{maxFileSize:r.bodyLimits?.multipart?.maxFileSize??B.multipart.maxFileSize,maxFiles:r.bodyLimits?.multipart?.maxFiles??B.multipart.maxFiles,maxFieldSize:r.bodyLimits?.multipart?.maxFieldSize??B.multipart.maxFieldSize,maxTotalSize:r.bodyLimits?.multipart?.maxTotalSize??B.multipart.maxTotalSize}};try{if(n.includes("application/json")){if(o>i.json)throw new Error(`JSON body too large: ${o} > ${i.json} bytes`);await Ro(e,t)}else if(n.includes("application/x-www-form-urlencoded")){if(o>i.form)throw new Error(`Form body too large: ${o} > ${i.form} bytes`);await bo(e,t)}else if(n.includes("text/")){if(o>i.text)throw new Error(`Text body too large: ${o} > ${i.text} bytes`);await Po(e,t)}else if(tr(n))await _o(e,t,i.multipart);else{if(o>i.raw)throw new Error(`Request body too large: ${o} > ${i.raw} bytes`);return}}catch(s){let a=n.includes("multipart")?"multipart_parse_error":"body_read_error";Be(t,a,"Error reading request body",s)}}function To(e){return["GET","HEAD","OPTIONS"].includes(e||"GET")}async function Ro(e,t){let r=await it(e);if(!r){console.warn("Empty body, skipping JSON parsing");return}if(r.trim()==="null"){console.warn('Body is the string "null"'),t.request.body=null;return}try{let n=JSON.parse(r);t.request.body=n}catch(n){t.request.body=null,Be(t,"json_parse_error","Invalid JSON in request body",n)}}async function bo(e,t){let r=await it(e);if(r)try{t.request.body=Co(r)}catch(n){t.request.body=null,Be(t,"form_parse_error","Invalid form data in request body",n)}}function Co(e){let t=new URLSearchParams(e),r={};return t.forEach((n,o)=>{r[o]!==void 0?Array.isArray(r[o])?r[o].push(n):r[o]=[r[o],n]:r[o]=n}),r}async function Po(e,t){let r=await it(e);r&&(t.request.body=r)}async function _o(e,t,r){try{let n=r||B.multipart,o=await lr(e,{strategy:"stream",maxFileSize:n.maxFileSize,maxFiles:n.maxFiles,maxFieldSize:n.maxFieldSize});t.request.multipart=o,t.request.files=o.files,t.request.body=o.fields}catch(n){t.request.body=null,Be(t,"multipart_parse_error","Failed to parse multipart data",n)}}function Be(e,t,r,n){let o={type:t,message:r,error:n};e.state._bodyError=o}async function it(e){return new Promise((t,r)=>{let n=[];e.on("data",o=>{n.push(Buffer.isBuffer(o)?o:Buffer.from(o))}),e.on("end",()=>{t(Buffer.concat(n).toString("utf8"))}),e.on("error",o=>{r(o)})})}b();R();var H=class extends w{constructor(t,r=void 0,n=void 0){super("NOT_FOUND",t,404,n??y(),r)}};b();ie();R();function Mo(e){return e instanceof w}function pr(e){if(Mo(e))return{type:e.type,title:e.title,status:e.status,correlationId:e.correlationId,timestamp:e.timestamp.toISOString(),details:e.details};let t=y(),r;e instanceof Error?r=e.message:e==null?r="Unknown error occurred":r=String(e);let n=new N("Internal Server Error",{originalMessage:r},t);return{type:n.type,title:n.title,status:n.status,correlationId:n.correlationId,timestamp:n.timestamp.toISOString(),details:n.details}}function fr(e){let t=j(),r={[t]:e(t)};return he(r)}function mr(e,t){let r=j();e(r,t)}function gr(e={}){let{debug:t=!1}=e;return{name:"ErrorBoundary",execute:async(n,o)=>{try{await o()}catch(i){if(n.response.sent){t&&console.error("Error occurred after response was sent:",i);return}t&&console.error("Error boundary caught error:",i);let s=fr(n.request.header),a=pr(i);a.correlationId=s,mr(n.response.header,s),n.response.status(a.status).json(a)}},debug:t}}R();function hr(e){return async(t,r)=>{let n=he(t.headers);try{await Pt(n,async()=>{let o=await ur(t,r,{parseBody:!0,initialState:{correlationId:n}}),s=[gr()];"corsOptions"in e&&e.corsOptions!==!1&&s.push(te(e.corsOptions)),s.push(...e.middleware);let a=L(s);await Yt(o,async()=>{await a(o,async()=>{if(!o.response.sent&&(await e.router.handleRequest(o),!r.headersSent&&!o.response.sent))throw new H(`Route not found: ${o.request.method} ${o.request.path}`)})})})}catch(o){console.error("Error creating context:",o);let i=j();if(r.headersSent||r.stream?.headersSent){console.error("Headers already sent, cannot send error response");return}"stream"in r&&typeof r.stream?.respond=="function"?(r.stream.respond({":status":500,"content-type":"application/json",[i.toLowerCase()]:n}),r.stream.end(JSON.stringify({error:"Internal Server Error",message:"Failed to process request",correlationId:n}))):(r.setHeader(i,n),r.writeHead(500,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:"Internal Server Error",message:"Failed to process request",correlationId:n})))}}}async function Oo(e){if(!e.enabled)return{};let{keyFile:t,certFile:r}=e,n=process.env.NODE_ENV==="development",o=!t||!r;if(o&&n)return await Zt();if(o)throw new Error("HTTP/2 requires SSL certificates. Provide keyFile and certFile in http2 options. In development, set NODE_ENV=development to generate them automatically.");return{keyFile:t,certFile:r}}function Ao(e,t){if(!e)return yr.createServer();let r={allowHTTP1:!0};try{t.keyFile&&(r.key=st.readFileSync(t.keyFile)),t.certFile&&(r.cert=st.readFileSync(t.certFile))}catch(n){throw new Error(`Failed to read certificate files: ${n instanceof Error?n.message:String(n)}`)}return Sr.createSecureServer(r)}function Fo(e,t,r,n){return new Promise((o,i)=>{e.listen(t,r,()=>{let a=`${n?"https":"http"}://${r}:${t}`;console.log(`
16
29
  \u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}
17
30
 
18
31
  \u26A1 BlaizeJS DEVELOPMENT SERVER HOT AND READY \u26A1
@@ -24,8 +37,8 @@
24
37
  Time to build something amazing! \u{1F680}
25
38
 
26
39
  \u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}
27
- `),o()}),e.on("error",s=>{console.error("Server error:",s),i(s)})})}async function Pn(e){for(let t of e.plugins)typeof t.initialize=="function"&&await t.initialize(e)}async function Ht(e,t){if(!e.server)try{let r=t.port,n=t.host;await Pn(e);let o=t.http2||{enabled:!0},i=!!o.enabled,s=await Rn(o);t.http2&&s.keyFile&&s.certFile&&(t.http2.keyFile=s.keyFile,t.http2.certFile=s.certFile);let a=vn(i,s);e.server=a,e.port=r,e.host=n;let u=_t(e);a.on("request",u),await En(a,r,n,i)}catch(r){throw console.error("Failed to start server:",r),r}}var Pe=!1;async function qt(e,t={}){let r=e.server,n=e.events;if(Pe){console.log("\u26A0\uFE0F Shutdown already in progress, ignoring duplicate shutdown request");return}if(!r)return;Pe=!0;let o=t.timeout||5e3;try{if(t.onStopping&&await t.onStopping(),n.emit("stopping"),e.router&&typeof e.router.close=="function"){console.log("\u{1F50C} Closing router watchers...");try{await Promise.race([e.router.close(),new Promise((a,u)=>setTimeout(()=>u(new Error("Router close timeout")),2e3))]),console.log("\u2705 Router watchers closed")}catch(a){console.error("\u274C Error closing router watchers:",a)}}try{await Promise.race([e.pluginManager.onServerStop(e,r),new Promise((a,u)=>setTimeout(()=>u(new Error("Plugin stop timeout")),2e3))])}catch(a){console.error("\u274C Plugin stop timeout:",a)}let i=new Promise((a,u)=>{r.close(l=>{if(l)return u(l);a()})}),s=new Promise((a,u)=>{setTimeout(()=>{u(new Error("Server shutdown timeout"))},o)});await Promise.race([i,s]);try{await Promise.race([e.pluginManager.terminatePlugins(e),new Promise((a,u)=>setTimeout(()=>u(new Error("Plugin terminate timeout")),1e3))])}catch(a){console.error("\u274C Plugin terminate timeout:",a)}t.onStopped&&await t.onStopped(),n.emit("stopped"),e.server=null,console.log("\u2705 Graceful shutdown completed"),Pe=!1}catch(i){throw Pe=!1,console.error("\u26A0\uFE0F Shutdown error (forcing exit):",i),r&&typeof r.close=="function"&&r.close(),process.env.NODE_ENV==="development"&&(console.log("\u{1F504} Forcing exit for development restart..."),process.exit(0)),n.emit("error",i),i}}function jt(e){if(process.env.NODE_ENV==="development"){let r=()=>{console.log("\u{1F4E4} SIGINT received, forcing exit for development restart..."),process.exit(0)},n=()=>{console.log("\u{1F4E4} SIGTERM received, forcing exit for development restart..."),process.exit(0)};return process.on("SIGINT",r),process.on("SIGTERM",n),{unregister:()=>{process.removeListener("SIGINT",r),process.removeListener("SIGTERM",n)}}}else{let r=()=>{console.log("\u{1F4E4} SIGINT received, starting graceful shutdown..."),e().catch(console.error)},n=()=>{console.log("\u{1F4E4} SIGTERM received, starting graceful shutdown..."),e().catch(console.error)};return process.on("SIGINT",r),process.on("SIGTERM",n),{unregister:()=>{process.removeListener("SIGINT",r),process.removeListener("SIGTERM",n)}}}}var x=require("zod"),bn=x.z.custom(e=>e!==null&&typeof e=="object"&&"execute"in e&&typeof e.execute=="function",{message:"Expected middleware to have an execute function"}),Cn=x.z.custom(e=>e!==null&&typeof e=="object"&&"register"in e&&typeof e.register=="function",{message:"Expected a valid plugin object with a register method"}),Mn=x.z.object({enabled:x.z.boolean().optional().default(!0),keyFile:x.z.string().optional(),certFile:x.z.string().optional()}).refine(e=>e.enabled&&process.env.NODE_ENV==="production"?e.keyFile&&e.certFile:!0,{message:"When HTTP/2 is enabled (outside of development mode), both keyFile and certFile must be provided"}),Fn=x.z.object({headerName:x.z.string().regex(/^[a-z][a-z0-9-]*$/,{message:"Header name must start with a letter and contain only lowercase letters, numbers, and hyphens"}).optional(),generator:x.z.function().args().returns(x.z.string()).optional()}).optional(),kn=x.z.object({port:x.z.number().int().positive().optional().default(3e3),host:x.z.string().optional().default("localhost"),routesDir:x.z.string().optional().default("./routes"),http2:Mn.optional().default({enabled:!0}),middleware:x.z.array(bn).optional().default([]),plugins:x.z.array(Cn).optional().default([]),correlation:Fn});function Vt(e){try{return kn.parse(e)}catch(t){if(t instanceof x.z.ZodError){let r=t.format();throw new Error(`Invalid server options: ${JSON.stringify(r,null,2)}`)}throw new Error(`Invalid server options: ${String(t)}`)}}function Qt(e={}){let{continueOnError:t=!0,debug:r=!1,onError:n}=e;function o(s,...a){r&&console.log(`[PluginLifecycle] ${s}`,...a)}function i(s,a,u){let l=`Plugin ${s.name} failed during ${a}: ${u.message}`;if(n?n(s,a,u):console.error(l,u),!t)throw new Error(l)}return{async initializePlugins(s){o("Initializing plugins...");for(let a of s.plugins)if(a.initialize)try{o(`Initializing plugin: ${a.name}`),await a.initialize(s)}catch(u){i(a,"initialize",u)}o(`Initialized ${s.plugins.length} plugins`)},async terminatePlugins(s){o("Terminating plugins...");let a=[...s.plugins].reverse();for(let u of a)if(u.terminate)try{o(`Terminating plugin: ${u.name}`),await u.terminate(s)}catch(l){i(u,"terminate",l)}o(`Terminated ${a.length} plugins`)},async onServerStart(s,a){o("Notifying plugins of server start...");for(let u of s.plugins)if(u.onServerStart)try{o(`Notifying plugin of server start: ${u.name}`),await u.onServerStart(a)}catch(l){i(u,"onServerStart",l)}},async onServerStop(s,a){o("Notifying plugins of server stop...");let u=[...s.plugins].reverse();for(let l of u)if(l.onServerStop)try{o(`Notifying plugin of server stop: ${l.name}`),await l.onServerStop(a)}catch(T){i(l,"onServerStop",T)}}}}var M=class extends Error{constructor(r,n){super(`Plugin validation error${r?` for "${r}"`:""}: ${n}`);this.pluginName=r;this.name="PluginValidationError"}};var On=new Set(["core","server","router","middleware","context","blaize","blaizejs"]),In=/^[a-z]([a-z0-9-]*[a-z0-9])?$/,Nn=/^\d+\.\d+\.\d+(?:-[a-zA-Z0-9-.]+)?(?:\+[a-zA-Z0-9-.]+)?$/;function je(e,t={}){let{requireVersion:r=!0,validateNameFormat:n=!0,checkReservedNames:o=!0}=t;if(!e||typeof e!="object")throw new M("","Plugin must be an object");let i=e;if(!i.name||typeof i.name!="string")throw new M("","Plugin must have a name (string)");if(n&&!In.test(i.name))throw new M(i.name,"Plugin name must be lowercase letters, numbers, and hyphens only");if(o&&On.has(i.name.toLowerCase()))throw new M(i.name,`Plugin name "${i.name}" is reserved`);if(r){if(!i.version||typeof i.version!="string")throw new M(i.name,"Plugin must have a version (string)");if(!Nn.test(i.version))throw new M(i.name,'Plugin version must follow semantic versioning (e.g., "1.0.0")')}if(!i.register||typeof i.register!="function")throw new M(i.name,"Plugin must have a register method (function)");let s=["initialize","terminate","onServerStart","onServerStop"];for(let a of s)if(i[a]&&typeof i[a]!="function")throw new M(i.name,`Plugin ${a} must be a function if provided`)}var Gt=R(require("crypto"),1),Zt=R(require("fs/promises"),1),Jt=require("module"),Yt=R(require("path"),1);async function Dn(e){let t=`?t=${Date.now()}`,r=e+t;try{let n=await import(r);return console.log("\u2705 Successfully imported module"),n}catch(n){let o=n instanceof Error?n.message:String(n);return console.log("\u26A0\uFE0F Error importing with cache buster, trying original path:",o),import(e)}}async function Wt(e,t){try{let r=ce(e,t),n=await Dn(e);console.log("\u{1F4E6} Module exports:",Object.keys(n));let o=[];if(n.default&&typeof n.default=="object"){let i={...n.default,path:r.routePath};o.push(i)}return Object.entries(n).forEach(([i,s])=>{if(i==="default"||!s||typeof s!="object")return;let a=s;if(zn(a)){let u={...a,path:r.routePath};o.push(u)}}),o.length===0?(console.warn(`Route file ${e} does not export any valid route definitions`),[]):(console.log(`\u2705 Successfully Loaded ${o.length} route(s)`),o)}catch(r){return console.error(`Failed to load route module ${e}:`,r),[]}}function zn(e){return!e||typeof e!="object"?!1:["GET","POST","PUT","DELETE","PATCH","HEAD","OPTIONS"].some(n=>e[n]&&typeof e[n]=="object"&&e[n].handler)}var An={},te=new Map;async function re(e,t,r=!0){let o=(await Zt.stat(e)).mtime.getTime(),i=te.get(e);if(r&&i&&i.timestamp===o)return i.routes;Bn(e);let s=await Wt(e,t);if(r){let a=Xt(s);te.set(e,{routes:s,timestamp:o,hash:a})}return s}function Kt(e,t){let r=te.get(e);if(!r)return!0;let n=Xt(t);return r.hash!==n}function Ve(e){e?te.delete(e):te.clear()}function Xt(e){let t=e.map(o=>({path:o.path,methods:Object.keys(o).filter(i=>i!=="path").sort().map(i=>{let s=o[i],a=s?.handler?s.handler.toString():null;return{method:i,handler:a,middleware:s?.middleware?s.middleware.length:0,hasSchema:!!s?.schema,schemaKeys:s?.schema?Object.keys(s.schema).sort():[]}})})),r=JSON.stringify(t);return Gt.createHash("md5").update(r).digest("hex")}function Bn(e){try{let t=Yt.resolve(e);if(typeof require<"u"){delete require.cache[t];try{let r=require.resolve(t);delete require.cache[r]}catch(r){let n=r instanceof Error?r.message:String(r);console.log(`\u26A0\uFE0F Could not resolve path: ${n}`)}}else try{let r=(0,Jt.createRequire)(An.url);delete r.cache[t];try{let n=r.resolve(t);delete r.cache[n]}catch{console.log("\u26A0\uFE0F Could not resolve ESM path")}}catch{console.log("\u26A0\uFE0F createRequire not available in pure ESM")}}catch(t){console.log(`\u26A0\uFE0F Error during module cache invalidation for ${e}:`,t)}}var er=R(require("os"),1);var be=R(require("fs/promises"),1),Q=R(require("path"),1);async function Ce(e,t={}){let r=Q.isAbsolute(e)?e:Q.resolve(process.cwd(),e);console.log("Creating router with routes directory:",r);try{if(!(await be.stat(r)).isDirectory())throw new Error(`Route directory is not a directory: ${r}`)}catch(s){throw s.code==="ENOENT"?new Error(`Route directory not found: ${r}`):s}let n=[],o=t.ignore||["node_modules",".git"];async function i(s){let a=await be.readdir(s,{withFileTypes:!0});for(let u of a){let l=Q.join(s,u.name);u.isDirectory()&&o.includes(u.name)||(u.isDirectory()?await i(l):$n(u.name)&&n.push(l))}}return await i(r),n}function $n(e){return!e.startsWith("_")&&(e.endsWith(".ts")||e.endsWith(".js"))}async function _n(e,t,r=Math.max(1,Math.floor(er.cpus().length/2))){let n=Un(e,r),o=[];for(let i of n){let a=(await Promise.allSettled(i.map(u=>t(u)))).filter(u=>u.status==="fulfilled").map(u=>u.value);o.push(...a)}return o}async function tr(e){let t=await Ce(e);return(await _n(t,n=>re(n,e))).flat()}function Un(e,t){let r=[];for(let n=0;n<e.length;n+=t)r.push(e.slice(n,n+t));return r}var B={fileChanges:0,totalReloadTime:0,averageReloadTime:0,slowReloads:[]};function rr(e,t){let r=Date.now()-t;if(B.fileChanges++,B.totalReloadTime+=r,B.averageReloadTime=B.totalReloadTime/B.fileChanges,r>100&&(B.slowReloads.push({file:e,time:r}),B.slowReloads.length>10&&B.slowReloads.shift()),process.env.NODE_ENV==="development"){let n=r<50?"\u26A1":r<100?"\u{1F504}":"\u{1F40C}";console.log(`${n} Route reload: ${e} (${r}ms)`)}}function Qe(e,t){return console.log(`Tracking performance for: ${t}`),async(...r)=>{let n=Date.now();try{let o=await e(...r);return rr(t,n),o}catch(o){throw rr(t,n),o}}}var We=R(require("path"),1),nr=require("chokidar");function Ge(e,t={}){let r=t.debounceMs||16,n=new Map;function o(p,S){return(...m)=>{let c=n.get(S);c&&clearTimeout(c);let d=setTimeout(()=>{p(...m),n.delete(S)},r);n.set(S,d)}}let i=new Map;async function s(){try{let p=await Ce(e,{ignore:t.ignore});for(let S of p)await a(S)}catch(p){l(p)}}async function a(p){try{let S=i.get(p),m=await re(p,e,!1);if(!m||m.length===0||S&&!Kt(p,m))return;await re(p,e,!0);let c=We.normalize(p);S?(i.set(p,m),t.onRouteChanged&&t.onRouteChanged(c,m)):(i.set(p,m),t.onRouteAdded&&t.onRouteAdded(c,m))}catch(S){console.log(`\u26A0\uFE0F Error processing file ${p}:`,S),l(S)}}function u(p){let S=We.normalize(p),m=i.get(S);m&&m.length>0&&t.onRouteRemoved&&t.onRouteRemoved(S,m),i.delete(S)}function l(p){t.onError&&p instanceof Error?t.onError(p):console.error("\u26A0\uFE0F Route watcher error:",p)}let T=(0,nr.watch)(e,{awaitWriteFinish:{stabilityThreshold:50,pollInterval:10},usePolling:!1,atomic:!0,followSymlinks:!1,depth:10,ignored:[/(^|[/\\])\../,/node_modules/,/\.git/,/\.DS_Store/,/Thumbs\.db/,/\.(test|spec)\.(ts|js)$/,/\.d\.ts$/,/\.map$/,/~$/,...t.ignore||[]]});return T.on("add",p=>{o(a,p)(p)}).on("change",p=>{o(a,p)(p)}).on("unlink",p=>{o(u,p)(p)}).on("error",l),s().catch(l),{close:()=>(n.forEach(p=>clearTimeout(p)),n.clear(),T.close()),getRoutes:()=>{let p=[];for(let S of i.values())p.push(...S);return p},getRoutesByFile:()=>new Map(i)}}var ur=require("zod");var or=require("zod");function Ze(e,t){return t instanceof or.z.ZodObject?t.strict().parse(e):t.parse(e)}var ir=require("zod");function Je(e,t){return t instanceof ir.z.ZodObject?t.strict().parse(e):t.parse(e)}var sr=require("zod");function Ye(e,t){return t instanceof sr.z.ZodObject?t.strict().parse(e):t.parse(e)}var ar=require("zod");function Ke(e,t){return t instanceof ar.z.ZodObject?t.strict().parse(e):t.parse(e)}Z();N();function Xe(e,t=!1){return{name:"RequestValidator",execute:async(n,o)=>{if(e.params&&n.request.params)try{n.request.params=Je(n.request.params,e.params)}catch(i){let s=Me(i),a=s.reduce((u,l)=>u+l.messages.length,0);throw new I("Request validation failed",{fields:s,errorCount:a,section:"params"})}if(e.query&&n.request.query)try{n.request.query=Ye(n.request.query,e.query)}catch(i){let s=Me(i),a=s.reduce((u,l)=>u+l.messages.length,0);throw new I("Request validation failed",{fields:s,errorCount:a,section:"query"})}if(e.body)try{n.request.body=Ze(n.request.body,e.body)}catch(i){let s=Me(i),a=s.reduce((u,l)=>u+l.messages.length,0);throw new I("Request validation failed",{fields:s,errorCount:a,section:"body"})}await o()},debug:t}}function et(e,t=!1){return{name:"ResponseValidator",execute:async(n,o)=>{let i=n.response.json;n.response.json=(s,a)=>{try{let u=Ke(s,e);return n.response.json=i,i.call(n.response,u,a)}catch(u){throw n.response.json=i,new O("Response validation failed",{responseSchema:e.description||"Unknown schema",validationError:Me(u),originalResponse:s})}},await o()},debug:t}}function Me(e){if(e instanceof ur.z.ZodError){let t=new Map;for(let r of e.issues){let n=r.path.length>0?r.path.join("."):"root";t.has(n)||t.set(n,[]),t.get(n).push(r.message)}return Array.from(t.entries()).map(([r,n])=>({field:r,messages:n}))}return e instanceof Error?[{field:"unknown",messages:[e.message]}]:[{field:"unknown",messages:[String(e)]}]}async function tt(e,t,r){let n=[...t.middleware||[]];t.schema&&((t.schema.params||t.schema.query||t.schema.body)&&n.unshift(Xe(t.schema)),t.schema.response&&n.push(et(t.schema.response))),await _([...n])(e,async()=>{let i=await t.handler(e,r);!e.response.sent&&i!==void 0&&e.response.json(i)})}function Fe(e,t,r){let n=t.exec(e);if(!n)return{};let o={};for(let i=0;i<r.length;i++)o[r[i]]=n[i+1]||"";return o}function rt(e){let t=[];if(e==="/")return{pattern:/^\/$/,paramNames:[]};let r=e.replace(/([.+*?^$(){}|\\])/g,"\\$1");return r=r.replace(/\/:([^/]+)/g,(o,i)=>(t.push(i),"/([^/]+)")).replace(/\/\[([^\]]+)\]/g,(o,i)=>(t.push(i),"/([^/]+)")),r=`${r}(?:/)?`,{pattern:new RegExp(`^${r}$`),paramNames:t}}function nt(){let e=[];return{add(t,r,n){let{pattern:o,paramNames:i}=rt(t),s={path:t,method:r,pattern:o,paramNames:i,routeOptions:n},a=e.findIndex(u=>i.length<u.paramNames.length);a===-1?e.push(s):e.splice(a,0,s)},remove(t){for(let r=e.length-1;r>=0;r--)e[r].path===t&&e.splice(r,1)},clear(){e.length=0},match(t,r){let n=t.split("?")[0];if(!n)return null;for(let i of e){if(i.method!==r)continue;if(i.pattern.exec(n)){let a=Fe(t,i.pattern,i.paramNames);return{route:i.routeOptions,params:a}}}return e.find(i=>i.method!==r&&i.pattern.test(t))?{route:null,params:{},methodNotAllowed:!0,allowedMethods:e.filter(i=>i.pattern.test(t)).map(i=>i.method)}:null},getRoutes(){return e.map(t=>({path:t.path,method:t.method}))},findRoutes(t){return e.filter(r=>r.pattern.test(t)).map(r=>({path:r.path,method:r.method,params:Fe(t,r.pattern,r.paramNames)}))}}}function cr(){return{routesByPath:new Map,routesByFile:new Map,pathToFile:new Map}}function A(e,t,r){console.log(`Updating routes from file: ${t}`);let n=e.routesByFile.get(t)||new Set,o=new Set(r.map(l=>l.path)),i=r.filter(l=>!n.has(l.path)),s=Array.from(n).filter(l=>!o.has(l)),u=r.filter(l=>n.has(l.path)).filter(l=>{let T=e.routesByPath.get(l.path);return!T||!Hn(T,l)});return Ln(e,t,{added:i,removed:s,changed:u}),{added:i,removed:s,changed:u}}function lr(e){return Array.from(e.routesByPath.values())}function Ln(e,t,r){let{added:n,removed:o,changed:i}=r;o.forEach(a=>{e.routesByPath.delete(a),e.pathToFile.delete(a)}),[...n,...i].forEach(a=>{e.routesByPath.set(a.path,a),e.pathToFile.set(a.path,t)});let s=new Set([...n.map(a=>a.path),...i.map(a=>a.path),...Array.from(e.routesByFile.get(t)||[]).filter(a=>!o.includes(a))]);s.size>0?e.routesByFile.set(t,s):e.routesByFile.delete(t)}function Hn(e,t){if(e.path!==t.path)return!1;let r=Object.keys(e).filter(o=>o!=="path").sort(),n=Object.keys(t).filter(o=>o!=="path").sort();return r.length!==n.length?!1:r.every(o=>{let i=e[o],s=t[o];return typeof i==typeof s})}function ot(e,t){Object.entries(e).forEach(([r,n])=>{r==="path"||!n||t.add(e.path,r,n)})}function ne(e,t){"remove"in t&&typeof t.remove=="function"?t.remove(e):console.warn("Matcher does not support selective removal, consider adding remove() method")}function dr(e,t){ne(e.path,t),ot(e,t)}var qn={routesDir:"./routes",basePath:"/",watchMode:process.env.NODE_ENV==="development"};function pr(e){let t={...qn,...e};e.basePath&&!e.basePath.startsWith("/")&&console.warn("Base path does nothing");let r=cr(),n=nt(),o=!1,i=null,s=null,a=new Set([t.routesDir]);function u(c){console.log(`
28
- \u{1F527} APPLYING MATCHER CHANGES:`),console.log(` Adding ${c.added.length} routes`),console.log(` Removing ${c.removed.length} routes`),console.log(` Updating ${c.changed.length} routes`),c.removed.forEach(d=>{console.log(` \u2796 Removing: ${d}`),ne(d,n)}),c.added.forEach(d=>{let g=Object.keys(d).filter(f=>f!=="path");console.log(` \u2795 Adding: ${d.path} [${g.join(", ")}]`),ot(d,n)}),c.changed.forEach(d=>{let g=Object.keys(d).filter(f=>f!=="path");console.log(` \u{1F504} Updating: ${d.path} [${g.join(", ")}]`),dr(d,n)}),console.log(`\u2705 Matcher changes applied
29
- `)}function l(c,d){try{let g=A(r,d,c);return u(g),g}catch(g){throw console.error(`\u26A0\uFE0F Route conflicts from ${d}:`,g),g}}async function T(c,d,g){try{let f=await tr(c),w=f.map(F=>g?{...F,path:`${g}${F.path}`}:F),E=l(w,d);console.log(`Loaded ${f.length} routes from ${d}${g?` with prefix ${g}`:""} (${E.added.length} added, ${E.changed.length} changed, ${E.removed.length} removed)`)}catch(f){throw console.error(`\u26A0\uFE0F Failed to load routes from ${d}:`,f),f}}async function p(){return o||i||(i=(async()=>{try{await Promise.all(Array.from(a).map(c=>T(c,c))),t.watchMode&&S(),o=!0}catch(c){throw console.error("\u26A0\uFE0F Failed to initialize router:",c),c}})()),i}function S(){s||(s=new Map);for(let c of a)if(!s.has(c)){let d=Ge(c,{debounceMs:16,ignore:["node_modules",".git"],onRouteAdded:(g,f)=>{try{let w=A(r,g,f);u(w)}catch(w){console.error(`Error adding routes from ${c}:`,w)}},onRouteChanged:Qe(async(g,f)=>{try{console.log(`Processing changes for ${g}`);let w=A(r,g,f);console.log(`Changes detected: ${w.added.length} added, ${w.changed.length} changed, ${w.removed.length} removed`),u(w),console.log(`Route changes applied: ${w.added.length} added, ${w.changed.length} changed, ${w.removed.length} removed`)}catch(w){console.error(`\u26A0\uFE0F Error updating routes from ${c}:`,w)}},c),onRouteRemoved:(g,f)=>{console.log(`File removed: ${g} with ${f.length} routes`);try{f.forEach(w=>{ne(w.path,n)}),Ve(g)}catch(w){console.error(`\u26A0\uFE0F Error removing routes from ${g}:`,w)}},onError:g=>{console.error(`\u26A0\uFE0F Route watcher error for ${c}:`,g)}});s.set(c,d)}}function m(c,d){s||(s=new Map);let g=Ge(c,{debounceMs:16,ignore:["node_modules",".git"],onRouteAdded:(f,w)=>{try{let E=w.map($=>d?{...$,path:`${d}${$.path}`}:$),F=A(r,f,E);u(F)}catch(E){console.error(`\u26A0\uFE0F Error adding routes from ${c}:`,E)}},onRouteChanged:Qe(async(f,w)=>{try{let E=w.map($=>d?{...$,path:`${d}${$.path}`}:$),F=A(r,f,E);u(F)}catch(E){console.error(`\u26A0\uFE0F Error updating routes from ${c}:`,E)}},c),onRouteRemoved:(f,w)=>{try{w.forEach(E=>{let F=d?`${d}${E.path}`:E.path;ne(F,n)}),Ve(f)}catch(E){console.error(`Error removing routes from ${f}:`,E)}},onError:f=>{console.error(`\u26A0\uFE0F Route watcher error for ${c}:`,f)}});return s.set(c,g),g}return p().catch(c=>{console.error("\u26A0\uFE0F Failed to initialize router on creation:",c)}),{async handleRequest(c){o||(console.log("\u{1F504} Router not initialized, initializing..."),await p());let{method:d,path:g}=c.request;console.log(`
30
- \u{1F4E5} Handling request: ${d} ${g}`);let f=n.match(g,d);if(!f)throw console.log(`\u274C No match found for: ${d} ${g}`),new z("Not found");if(console.log(`\u2705 Route matched: ${d} ${g}`),console.log(` Params: ${JSON.stringify(f.params)}`),f.methodNotAllowed){c.response.status(405).json({error:"\u274C Method Not Allowed",allowed:f.allowedMethods}),f.allowedMethods&&f.allowedMethods.length>0&&c.response.header("Allow",f.allowedMethods.join(", "));return}c.request.params=f.params,await tt(c,f.route,f.params)},getRoutes(){return lr(r)},addRoute(c){let d=A(r,"programmatic",[c]);u(d)},addRoutes(c){let d=A(r,"programmatic",c);return u(d),d},async addRouteDirectory(c,d={}){if(a.has(c)){console.warn(`Route directory ${c} already registered`);return}a.add(c),o&&(await T(c,c,d.prefix),t.watchMode&&m(c,d.prefix))},getRouteConflicts(){return[]},async close(){if(s){for(let c of s.values())await c.close();s.clear()}}}}v();var jn={port:3e3,host:"localhost",routesDir:"./routes",http2:{enabled:!0},middleware:[],plugins:[]};function Vn(e={}){let t={...jn};return ut({routesDir:e.routesDir||t.routesDir}),{port:e.port??t.port,host:e.host??t.host,routesDir:e.routesDir??t.routesDir,http2:{enabled:e.http2?.enabled??t.http2?.enabled,keyFile:e.http2?.keyFile??t.http2?.keyFile,certFile:e.http2?.certFile??t.http2?.certFile},middleware:[...t.middleware||[],...e.middleware||[]],plugins:[...t.plugins||[],...e.plugins||[]],correlation:e.correlation}}function Qn(e){e.correlation&&St(e.correlation.headerName,e.correlation.generator)}function Wn(e,t){return async()=>(Qn(t),await Gn(e),await e.pluginManager.initializePlugins(e),await Ht(e,t),await e.pluginManager.onServerStart(e,e.server),Zn(e),e)}async function Gn(e){for(let t of e.plugins)await t.register(e)}function Zn(e){let t=jt(()=>e.close());e._signalHandlers=t,e.events.emit("started")}function Jn(e){return async t=>{if(!e.server)return;let r={...t};e._signalHandlers&&(e._signalHandlers.unregister(),delete e._signalHandlers),await qt(e,r)}}function Yn(e){return t=>{let r=Array.isArray(t)?t:[t];return e.middleware.push(...r),e}}function Kn(e){return async t=>{if(Array.isArray(t))for(let r of t)je(r),e.plugins.push(r),await r.register(e);else je(t),e.plugins.push(t),await t.register(e);return e}}function ke(e={}){let t=Vn(e),r;try{r=Vt(t)}catch(c){throw c instanceof Error?new Error(`Failed to create server: ${c.message}`):new Error(`Failed to create server: ${String(c)}`)}let{port:n,host:o,middleware:i,plugins:s}=r,a=Array.isArray(i)?[...i]:[],u=Array.isArray(s)?[...s]:[],l=new fr.AsyncLocalStorage,T=pr({routesDir:r.routesDir,watchMode:process.env.NODE_ENV==="development"}),p=Qt({debug:process.env.NODE_ENV==="development",continueOnError:!0}),S=new mr.default,m={server:null,port:n,host:o,context:l,events:S,plugins:[...u],middleware:[...a],_signalHandlers:{unregister:()=>{}},use:()=>m,register:async()=>m,listen:async()=>m,close:async()=>{},router:T,pluginManager:p};return m.listen=Wn(m,r),m.close=Jn(m),m.use=Yn(m),m.register=Kn(m),m}function it(e){return{}}v();function Xn(e){return typeof e=="object"&&e!==null&&"name"in e&&"execute"in e&&typeof e.name=="string"&&typeof e.execute=="function"}function eo(e){return typeof e=="object"&&e!==null&&"name"in e&&"version"in e&&"register"in e&&typeof e.name=="string"&&typeof e.version=="string"&&typeof e.register=="function"}function to(e){return e}function ro(e){return e}function no(...e){return e}function oo(...e){return e}P();N();P();v();var Oe=class extends h{constructor(t,r=void 0,n=void 0){super("UNAUTHORIZED",t,401,n??y(),r)}};P();v();var Ie=class extends h{constructor(t,r=void 0,n=void 0){super("FORBIDDEN",t,403,n??y(),r)}};P();v();var Ne=class extends h{constructor(t,r=void 0,n=void 0){super("CONFLICT",t,409,n??y(),r)}};P();v();var De=class extends h{constructor(t,r=void 0,n=void 0){super("RATE_LIMITED",t,429,n??y(),r)}};Z();Re();P();v();var ze=class extends h{constructor(t,r,n){super("UPLOAD_TIMEOUT",t,408,n??y(),r)}};ve();P();v();var Be=class extends h{constructor(t,r,n){super("UNPROCESSABLE_ENTITY",t,422,n??y(),r)}};var gr="0.1.0",yr={createServer:ke,inferContext:it},hr={createDeleteRoute:fe,createGetRoute:le,createHeadRoute:ge,createOptionsRoute:ye,createPatchRoute:me,createPostRoute:de,createPutRoute:pe,createRouteFactory:Ae},Sr={createMiddleware:V,createServiceMiddleware:se,createStateMiddleware:ie,compose:_},wr={createPlugin:ae},io={createServer:ke,createMiddleware:V,createServiceMiddleware:se,createStateMiddleware:ie,createPlugin:ae,getCorrelationId:y,Server:yr,Router:hr,Middleware:Sr,Plugins:wr,VERSION:gr};0&&(module.exports={Blaize,BlaizeError,ConflictError,ErrorSeverity,ErrorType,ForbiddenError,InternalServerError,MiddlewareAPI,NotFoundError,PayloadTooLargeError,PluginsAPI,RateLimitError,RequestTimeoutError,RouterAPI,ServerAPI,UnauthorizedError,UnprocessableEntityError,UnsupportedMediaTypeError,VERSION,ValidationError,asMiddlewareArray,asPluginArray,compose,createDeleteRoute,createGetRoute,createHeadRoute,createMiddleware,createMiddlewareArray,createOptionsRoute,createPatchRoute,createPlugin,createPluginArray,createPostRoute,createPutRoute,createRouteFactory,createServer,createServiceMiddleware,createStateMiddleware,getCorrelationId,inferContext,isBodyParseError,isMiddleware,isPlugin});
40
+ `),o()}),e.on("error",s=>{console.error("Server error:",s),i(s)})})}async function ko(e){for(let t of e.plugins)typeof t.initialize=="function"&&await t.initialize(e)}async function wr(e,t){if(!e.server)try{let r=t.port,n=t.host;await ko(e);let o=t.http2||{enabled:!0},i=!!o.enabled,s=await Oo(o);t.http2&&s.keyFile&&s.certFile&&(t.http2.keyFile=s.keyFile,t.http2.certFile=s.certFile);let a=Ao(i,s);e.server=a,e.port=r,e.host=n;let c=hr(e);a.on("request",c),await Fo(a,r,n,i)}catch(r){throw console.error("Failed to start server:",r),r}}var $e=!1;async function xr(e,t={}){let r=e.server,n=e.events;if($e){console.log("\u26A0\uFE0F Shutdown already in progress, ignoring duplicate shutdown request");return}if(!r)return;$e=!0;let o=t.timeout||5e3;try{if(t.onStopping&&await t.onStopping(),n.emit("stopping"),e.router&&typeof e.router.close=="function"){console.log("\u{1F50C} Closing router watchers...");try{await Promise.race([e.router.close(),new Promise((a,c)=>setTimeout(()=>c(new Error("Router close timeout")),2e3))]),console.log("\u2705 Router watchers closed")}catch(a){console.error("\u274C Error closing router watchers:",a)}}try{await Promise.race([e.pluginManager.onServerStop(e,r),new Promise((a,c)=>setTimeout(()=>c(new Error("Plugin stop timeout")),2e3))])}catch(a){console.error("\u274C Plugin stop timeout:",a)}let i=new Promise((a,c)=>{r.close(l=>{if(l)return c(l);a()})}),s=new Promise((a,c)=>{setTimeout(()=>{c(new Error("Server shutdown timeout"))},o)});await Promise.race([i,s]);try{await Promise.race([e.pluginManager.terminatePlugins(e),new Promise((a,c)=>setTimeout(()=>c(new Error("Plugin terminate timeout")),1e3))])}catch(a){console.error("\u274C Plugin terminate timeout:",a)}t.onStopped&&await t.onStopped(),n.emit("stopped"),e.server=null,console.log("\u2705 Graceful shutdown completed"),$e=!1}catch(i){throw $e=!1,console.error("\u26A0\uFE0F Shutdown error (forcing exit):",i),r&&typeof r.close=="function"&&r.close(),process.env.NODE_ENV==="development"&&(console.log("\u{1F504} Forcing exit for development restart..."),process.exit(0)),n.emit("error",i),i}}function Er(e){if(process.env.NODE_ENV==="development"){let r=()=>{console.log("\u{1F4E4} SIGINT received, forcing exit for development restart..."),process.exit(0)},n=()=>{console.log("\u{1F4E4} SIGTERM received, forcing exit for development restart..."),process.exit(0)};return process.on("SIGINT",r),process.on("SIGTERM",n),{unregister:()=>{process.removeListener("SIGINT",r),process.removeListener("SIGTERM",n)}}}else{let r=()=>{console.log("\u{1F4E4} SIGINT received, starting graceful shutdown..."),e().catch(console.error)},n=()=>{console.log("\u{1F4E4} SIGTERM received, starting graceful shutdown..."),e().catch(console.error)};return process.on("SIGINT",r),process.on("SIGTERM",n),{unregister:()=>{process.removeListener("SIGINT",r),process.removeListener("SIGTERM",n)}}}}var C=require("zod");var Io=C.z.custom(e=>e!==null&&typeof e=="object"&&"execute"in e&&typeof e.execute=="function",{message:"Expected middleware to have an execute function"}),Do=C.z.custom(e=>e!==null&&typeof e=="object"&&"register"in e&&typeof e.register=="function",{message:"Expected a valid plugin object with a register method"}),zo=C.z.object({enabled:C.z.boolean().optional().default(!0),keyFile:C.z.string().optional(),certFile:C.z.string().optional()}).refine(e=>e.enabled&&process.env.NODE_ENV==="production"?e.keyFile&&e.certFile:!0,{message:"When HTTP/2 is enabled (outside of development mode), both keyFile and certFile must be provided"}),No=C.z.object({headerName:C.z.string().regex(/^[a-z][a-z0-9-]*$/,{message:"Header name must start with a letter and contain only lowercase letters, numbers, and hyphens"}).optional(),generator:C.z.function().args().returns(C.z.string()).optional()}).optional(),Bo=C.z.object({port:C.z.number().int().positive().optional().default(3e3),host:C.z.string().optional().default("localhost"),routesDir:C.z.string().optional().default("./routes"),http2:zo.optional().default({enabled:!0}),middleware:C.z.array(Io).optional().default([]),plugins:C.z.array(Do).optional().default([]),correlation:No,cors:Dt});function vr(e){try{return Bo.parse(e)}catch(t){if(t instanceof C.z.ZodError){let r=t.format();throw new Error(`Invalid server options: ${JSON.stringify(r,null,2)}`)}throw new Error(`Invalid server options: ${String(t)}`)}}function Tr(e={}){let{continueOnError:t=!0,debug:r=!1,onError:n}=e;function o(s,...a){r&&console.log(`[PluginLifecycle] ${s}`,...a)}function i(s,a,c){let l=`Plugin ${s.name} failed during ${a}: ${c.message}`;if(n?n(s,a,c):console.error(l,c),!t)throw new Error(l)}return{async initializePlugins(s){o("Initializing plugins...");for(let a of s.plugins)if(a.initialize)try{o(`Initializing plugin: ${a.name}`),await a.initialize(s)}catch(c){i(a,"initialize",c)}o(`Initialized ${s.plugins.length} plugins`)},async terminatePlugins(s){o("Terminating plugins...");let a=[...s.plugins].reverse();for(let c of a)if(c.terminate)try{o(`Terminating plugin: ${c.name}`),await c.terminate(s)}catch(l){i(c,"terminate",l)}o(`Terminated ${a.length} plugins`)},async onServerStart(s,a){o("Notifying plugins of server start...");for(let c of s.plugins)if(c.onServerStart)try{o(`Notifying plugin of server start: ${c.name}`),await c.onServerStart(a)}catch(l){i(c,"onServerStart",l)}},async onServerStop(s,a){o("Notifying plugins of server stop...");let c=[...s.plugins].reverse();for(let l of c)if(l.onServerStop)try{o(`Notifying plugin of server stop: ${l.name}`),await l.onServerStop(a)}catch(p){i(l,"onServerStop",p)}}}}var F=class extends Error{constructor(r,n){super(`Plugin validation error${r?` for "${r}"`:""}: ${n}`);this.pluginName=r;this.name="PluginValidationError"}};var $o=new Set(["core","server","router","middleware","context","blaize","blaizejs"]),Ho=/^[a-z]([a-z0-9-]*[a-z0-9])?$/,Uo=/^\d+\.\d+\.\d+(?:-[a-zA-Z0-9-.]+)?(?:\+[a-zA-Z0-9-.]+)?$/;function at(e,t={}){let{requireVersion:r=!0,validateNameFormat:n=!0,checkReservedNames:o=!0}=t;if(!e||typeof e!="object")throw new F("","Plugin must be an object");let i=e;if(!i.name||typeof i.name!="string")throw new F("","Plugin must have a name (string)");if(n&&!Ho.test(i.name))throw new F(i.name,"Plugin name must be lowercase letters, numbers, and hyphens only");if(o&&$o.has(i.name.toLowerCase()))throw new F(i.name,`Plugin name "${i.name}" is reserved`);if(r){if(!i.version||typeof i.version!="string")throw new F(i.name,"Plugin must have a version (string)");if(!Uo.test(i.version))throw new F(i.name,'Plugin version must follow semantic versioning (e.g., "1.0.0")')}if(!i.register||typeof i.register!="function")throw new F(i.name,"Plugin must have a register method (function)");let s=["initialize","terminate","onServerStart","onServerStop"];for(let a of s)if(i[a]&&typeof i[a]!="function")throw new F(i.name,`Plugin ${a} must be a function if provided`)}var br=_(require("crypto"),1),Cr=_(require("fs/promises"),1);async function qo(e){let t=`?t=${Date.now()}`,r=e+t;try{let n=await import(r);return console.log("\u2705 Successfully imported module"),n}catch(n){let o=n instanceof Error?n.message:String(n);return console.log("\u26A0\uFE0F Error importing with cache buster, trying original path:",o),import(e)}}async function Rr(e,t){try{let r=Ee(e,t),n=await qo(e);console.log("\u{1F4E6} Module exports:",Object.keys(n));let o=[];if(n.default&&typeof n.default=="object"){let i={...n.default,path:r.routePath};o.push(i)}return Object.entries(n).forEach(([i,s])=>{if(i==="default"||!s||typeof s!="object")return;let a=s;if(Lo(a)){let c={...a,path:r.routePath};o.push(c)}}),o.length===0?(console.warn(`Route file ${e} does not export any valid route definitions`),[]):(console.log(`\u2705 Successfully Loaded ${o.length} route(s)`),o)}catch(r){return console.error(`Failed to load route module ${e}:`,r),[]}}function Lo(e){return!e||typeof e!="object"?!1:["GET","POST","PUT","DELETE","PATCH","HEAD","OPTIONS"].some(n=>e[n]&&typeof e[n]=="object"&&e[n].handler)}var de=new Map;async function pe(e,t,r=!0){let o=(await Cr.stat(e)).mtime.getTime(),i=de.get(e);if(r&&i&&i.timestamp===o)return i.routes;let s=await Rr(e,t);if(r){let a=_r(s);de.set(e,{routes:s,timestamp:o,hash:a})}return s}function Pr(e,t){let r=de.get(e);if(!r)return!0;let n=_r(t);return r.hash!==n}function ct(e){e?de.delete(e):de.clear()}function _r(e){let t=e.map(o=>({path:o.path,methods:Object.keys(o).filter(i=>i!=="path").sort().map(i=>{let s=o[i],a=s?.handler?s.handler.toString():null;return{method:i,handler:a,middleware:s?.middleware?s.middleware.length:0,hasSchema:!!s?.schema,schemaKeys:s?.schema?Object.keys(s.schema).sort():[]}})})),r=JSON.stringify(t);return br.createHash("md5").update(r).digest("hex")}var Or=_(require("os"),1);var He=_(require("fs/promises"),1),K=_(require("path"),1);async function Mr(e,t={}){let r=K.isAbsolute(e)?e:K.resolve(process.cwd(),e);console.log("Creating router with routes directory:",r);try{if(!(await He.stat(r)).isDirectory())throw new Error(`Route directory is not a directory: ${r}`)}catch(s){throw s.code==="ENOENT"?new Error(`Route directory not found: ${r}`):s}let n=[],o=t.ignore||["node_modules",".git"];async function i(s){let a=await He.readdir(s,{withFileTypes:!0});for(let c of a){let l=K.join(s,c.name);c.isDirectory()&&o.includes(c.name)||(c.isDirectory()?await i(l):jo(c.name)&&n.push(l))}}return await i(r),n}function jo(e){return!e.startsWith("_")&&(e.endsWith(".ts")||e.endsWith(".js"))}async function Vo(e,t,r=Math.max(1,Math.floor(Or.cpus().length/2))){let n=Wo(e,r),o=[];for(let i of n){let a=(await Promise.allSettled(i.map(c=>t(c)))).filter(c=>c.status==="fulfilled").map(c=>c.value);o.push(...a)}return o}async function Ar(e){let t=await Mr(e);return(await Vo(t,n=>pe(n,e))).flat()}function Wo(e,t){let r=[];for(let n=0;n<e.length;n+=t)r.push(e.slice(n,n+t));return r}var U={fileChanges:0,totalReloadTime:0,averageReloadTime:0,slowReloads:[]};function Fr(e,t){let r=Date.now()-t;if(U.fileChanges++,U.totalReloadTime+=r,U.averageReloadTime=U.totalReloadTime/U.fileChanges,r>100&&(U.slowReloads.push({file:e,time:r}),U.slowReloads.length>10&&U.slowReloads.shift()),process.env.NODE_ENV==="development"){let n=r<50?"\u26A1":r<100?"\u{1F504}":"\u{1F40C}";console.log(`${n} Route reload: ${e} (${r}ms)`)}}function lt(e,t){return console.log(`Tracking performance for: ${t}`),async(...r)=>{let n=Date.now();try{let o=await e(...r);return Fr(t,n),o}catch(o){throw Fr(t,n),o}}}var ut=_(require("path"),1),kr=require("chokidar");function dt(e,t={}){let r=t.debounceMs||16,n=new Map;function o(p,g){return(...x)=>{let v=n.get(g);v&&clearTimeout(v);let u=setTimeout(()=>{p(...x),n.delete(g)},r);n.set(g,u)}}let i=new Map;async function s(p){try{let g=i.get(p),x=await pe(p,e,!1);if(!x||x.length===0||g&&!Pr(p,x))return;await pe(p,e,!0);let v=ut.normalize(p);g?(i.set(p,x),t.onRouteChanged&&t.onRouteChanged(v,x)):(i.set(p,x),t.onRouteAdded&&t.onRouteAdded(v,x))}catch(g){console.log(`\u26A0\uFE0F Error processing file ${p}:`,g),c(g)}}function a(p){let g=ut.normalize(p),x=i.get(g);x&&x.length>0&&t.onRouteRemoved&&t.onRouteRemoved(g,x),i.delete(g)}function c(p){t.onError&&p instanceof Error?t.onError(p):console.error("\u26A0\uFE0F Route watcher error:",p)}let l=(0,kr.watch)(e,{ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:50,pollInterval:10},usePolling:!1,atomic:!0,followSymlinks:!1,depth:10,ignored:[/(^|[/\\])\../,/node_modules/,/\.git/,/\.DS_Store/,/Thumbs\.db/,/\.(test|spec)\.(ts|js)$/,/\.d\.ts$/,/\.map$/,/~$/,...t.ignore||[]]});return l.on("add",p=>{o(s,p)(p)}).on("change",p=>{o(s,p)(p)}).on("unlink",p=>{o(a,p)(p)}).on("error",c),{close:()=>(n.forEach(p=>clearTimeout(p)),n.clear(),l.close()),getRoutes:()=>{let p=[];for(let g of i.values())p.push(...g);return p},getRoutesByFile:()=>new Map(i)}}var Br=require("zod");var Ir=require("zod");function pt(e,t){return t instanceof Ir.z.ZodObject?t.strict().parse(e):t.parse(e)}var Dr=require("zod");function ft(e,t){return t instanceof Dr.z.ZodObject?t.strict().parse(e):t.parse(e)}var zr=require("zod");function mt(e,t){return t instanceof zr.z.ZodObject?t.strict().parse(e):t.parse(e)}var Nr=require("zod");function gt(e,t){return t instanceof Nr.z.ZodObject?t.strict().parse(e):t.parse(e)}ie();I();function ht(e,t=!1){return{name:"RequestValidator",execute:async(n,o)=>{if(e.params&&n.request.params)try{n.request.params=ft(n.request.params,e.params)}catch(i){let s=Ue(i),a=s.reduce((c,l)=>c+l.messages.length,0);throw new M("Request validation failed",{fields:s,errorCount:a,section:"params"})}if(e.query&&n.request.query)try{n.request.query=mt(n.request.query,e.query)}catch(i){let s=Ue(i),a=s.reduce((c,l)=>c+l.messages.length,0);throw new M("Request validation failed",{fields:s,errorCount:a,section:"query"})}if(e.body)try{n.request.body=pt(n.request.body,e.body)}catch(i){let s=Ue(i),a=s.reduce((c,l)=>c+l.messages.length,0);throw new M("Request validation failed",{fields:s,errorCount:a,section:"body"})}await o()},debug:t}}function yt(e,t=!1){return{name:"ResponseValidator",execute:async(n,o)=>{let i=n.response.json;n.response.json=(s,a)=>{try{let c=gt(s,e);return n.response.json=i,i.call(n.response,c,a)}catch(c){throw n.response.json=i,new N("Response validation failed",{responseSchema:e.description||"Unknown schema",validationError:Ue(c),originalResponse:s})}},await o()},debug:t}}function Ue(e){if(e instanceof Br.z.ZodError){let t=new Map;for(let r of e.issues){let n=r.path.length>0?r.path.join("."):"root";t.has(n)||t.set(n,[]),t.get(n).push(r.message)}return Array.from(t.entries()).map(([r,n])=>({field:r,messages:n}))}return e instanceof Error?[{field:"unknown",messages:[e.message]}]:[{field:"unknown",messages:[String(e)]}]}async function St(e,t,r){let n=[...t.middleware||[]];t.schema&&((t.schema.params||t.schema.query||t.schema.body)&&n.unshift(ht(t.schema)),t.schema.response&&n.push(yt(t.schema.response))),await L([...n])(e,async()=>{let i=await t.handler(e,r);!e.response.sent&&i!==void 0&&e.response.json(i)})}function $r(){return{routesByPath:new Map,routesByFile:new Map,pathToFile:new Map}}function q(e,t,r){console.log(`Updating routes from file: ${t}`);let n=e.routesByFile.get(t)||new Set,o=new Set(r.map(l=>l.path)),i=r.filter(l=>!n.has(l.path)),s=Array.from(n).filter(l=>!o.has(l)),c=r.filter(l=>n.has(l.path)).filter(l=>{let p=e.routesByPath.get(l.path);return!p||!Go(p,l)});return Qo(e,t,{added:i,removed:s,changed:c}),{added:i,removed:s,changed:c}}function Hr(e){return Array.from(e.routesByPath.values())}function Qo(e,t,r){let{added:n,removed:o,changed:i}=r;o.forEach(a=>{e.routesByPath.delete(a),e.pathToFile.delete(a)}),[...n,...i].forEach(a=>{e.routesByPath.set(a.path,a),e.pathToFile.set(a.path,t)});let s=new Set([...n.map(a=>a.path),...i.map(a=>a.path),...Array.from(e.routesByFile.get(t)||[]).filter(a=>!o.includes(a))]);s.size>0?e.routesByFile.set(t,s):e.routesByFile.delete(t)}function Go(e,t){if(e.path!==t.path)return!1;let r=Object.keys(e).filter(o=>o!=="path").sort(),n=Object.keys(t).filter(o=>o!=="path").sort();return r.length!==n.length?!1:r.every(o=>{let i=e[o],s=t[o];return typeof i==typeof s})}function wt(e,t){Object.entries(e).forEach(([r,n])=>{r==="path"||!n||t.add(e.path,r,n)})}function fe(e,t){"remove"in t&&typeof t.remove=="function"?t.remove(e):console.warn("Matcher does not support selective removal, consider adding remove() method")}function Ur(e,t){fe(e.path,t),wt(e,t)}var Zo={routesDir:"./routes",basePath:"/",watchMode:process.env.NODE_ENV==="development"};function qr(e){let t={...Zo,...e};e.basePath&&!e.basePath.startsWith("/")&&console.warn("Base path does nothing");let r=$r(),n=Y(),o=!1,i=null,s=null,a=new Set([t.routesDir]);function c(u){console.log(`
41
+ \u{1F527} APPLYING MATCHER CHANGES:`),console.log(` Adding ${u.added.length} routes`),console.log(` Removing ${u.removed.length} routes`),console.log(` Updating ${u.changed.length} routes`),u.removed.forEach(f=>{console.log(` \u2796 Removing: ${f}`),fe(f,n)}),u.added.forEach(f=>{let m=Object.keys(f).filter(d=>d!=="path");console.log(` \u2795 Adding: ${f.path} [${m.join(", ")}]`),wt(f,n)}),u.changed.forEach(f=>{let m=Object.keys(f).filter(d=>d!=="path");console.log(` \u{1F504} Updating: ${f.path} [${m.join(", ")}]`),Ur(f,n)}),console.log(`\u2705 Matcher changes applied
42
+ `)}function l(u,f){try{let m=q(r,f,u);return c(m),m}catch(m){throw console.error(`\u26A0\uFE0F Route conflicts from ${f}:`,m),m}}async function p(u,f,m){try{let d=await Ar(u),S=d.map(h=>m?{...h,path:`${m}${h.path}`}:h),E=l(S,f);console.log(`Loaded ${d.length} routes from ${f}${m?` with prefix ${m}`:""} (${E.added.length} added, ${E.changed.length} changed, ${E.removed.length} removed)`)}catch(d){throw console.error(`\u26A0\uFE0F Failed to load routes from ${f}:`,d),d}}async function g(){return o||i||(i=(async()=>{try{await Promise.all(Array.from(a).map(u=>p(u,u))),t.watchMode&&x(),o=!0}catch(u){throw console.error("\u26A0\uFE0F Failed to initialize router:",u),u}})()),i}function x(){s||(s=new Map);for(let u of a)if(!s.has(u)){let f=dt(u,{debounceMs:16,ignore:["node_modules",".git"],onRouteAdded:(m,d)=>{try{let S=q(r,m,d);c(S)}catch(S){console.error(`Error adding routes from ${u}:`,S)}},onRouteChanged:lt(async(m,d)=>{try{console.log(`Processing changes for ${m}`);let S=q(r,m,d);console.log(`Changes detected: ${S.added.length} added, ${S.changed.length} changed, ${S.removed.length} removed`),c(S),console.log(`Route changes applied: ${S.added.length} added, ${S.changed.length} changed, ${S.removed.length} removed`)}catch(S){console.error(`\u26A0\uFE0F Error updating routes from ${u}:`,S)}},u),onRouteRemoved:(m,d)=>{console.log(`File removed: ${m} with ${d.length} routes`);try{d.forEach(S=>{fe(S.path,n)}),ct(m)}catch(S){console.error(`\u26A0\uFE0F Error removing routes from ${m}:`,S)}},onError:m=>{console.error(`\u26A0\uFE0F Route watcher error for ${u}:`,m)}});s.set(u,f)}}function v(u,f){s||(s=new Map);let m=dt(u,{debounceMs:16,ignore:["node_modules",".git"],onRouteAdded:(d,S)=>{try{let E=S.map(k=>f?{...k,path:`${f}${k.path}`}:k),h=q(r,d,E);c(h)}catch(E){console.error(`\u26A0\uFE0F Error adding routes from ${u}:`,E)}},onRouteChanged:lt(async(d,S)=>{try{let E=S.map(k=>f?{...k,path:`${f}${k.path}`}:k),h=q(r,d,E);c(h)}catch(E){console.error(`\u26A0\uFE0F Error updating routes from ${u}:`,E)}},u),onRouteRemoved:(d,S)=>{try{S.forEach(E=>{let h=f?`${f}${E.path}`:E.path;fe(h,n)}),ct(d)}catch(E){console.error(`Error removing routes from ${d}:`,E)}},onError:d=>{console.error(`\u26A0\uFE0F Route watcher error for ${u}:`,d)}});return s.set(u,m),m}return g().catch(u=>{console.error("\u26A0\uFE0F Failed to initialize router on creation:",u)}),{async handleRequest(u){o||(console.log("\u{1F504} Router not initialized, initializing..."),await g());let{method:f,path:m}=u.request;console.log(`
43
+ \u{1F4E5} Handling request: ${f} ${m}`);let d=n.match(m,f);if(!d)throw console.log(`\u274C No match found for: ${f} ${m}`),new H("Not found");if(console.log(`\u2705 Route matched: ${f} ${m}`),console.log(` Params: ${JSON.stringify(d.params)}`),d.methodNotAllowed){u.response.status(405).json({error:"\u274C Method Not Allowed",allowed:d.allowedMethods}),d.allowedMethods&&d.allowedMethods.length>0&&u.response.header("Allow",d.allowedMethods.join(", "));return}u.request.params=d.params,await St(u,d.route,d.params)},getRoutes(){return Hr(r)},addRoute(u){let f=q(r,"programmatic",[u]);c(f)},addRoutes(u){let f=q(r,"programmatic",u);return c(f),f},async addRouteDirectory(u,f={}){if(a.has(u)){console.warn(`Route directory ${u} already registered`);return}a.add(u),o&&(await p(u,u,f.prefix),t.watchMode&&v(u,f.prefix))},getRouteConflicts(){return[]},async close(){if(s){for(let u of s.values())await u.close();s.clear()}}}}R();var Jo={port:3e3,host:"localhost",routesDir:"./routes",http2:{enabled:!0},middleware:[],plugins:[]};function Yo(e={}){let t={...Jo};return $t({routesDir:e.routesDir||t.routesDir}),{port:e.port??t.port,host:e.host??t.host,routesDir:e.routesDir??t.routesDir,http2:{enabled:e.http2?.enabled??t.http2?.enabled,keyFile:e.http2?.keyFile??t.http2?.keyFile,certFile:e.http2?.certFile??t.http2?.certFile},middleware:[...t.middleware||[],...e.middleware||[]],plugins:[...t.plugins||[],...e.plugins||[]],correlation:e.correlation,cors:e.cors}}function Ko(e){e.correlation&&Ct(e.correlation.headerName,e.correlation.generator)}function Xo(e,t){return async()=>(Ko(t),await ei(e),await e.pluginManager.initializePlugins(e),await wr(e,t),await e.pluginManager.onServerStart(e,e.server),ti(e),e)}async function ei(e){for(let t of e.plugins)await t.register(e)}function ti(e){let t=Er(()=>e.close());e._signalHandlers=t,e.events.emit("started")}function ri(e){return async t=>{if(!e.server)return;let r={...t};e._signalHandlers&&(e._signalHandlers.unregister(),delete e._signalHandlers),await xr(e,r)}}function ni(e){return t=>{let r=Array.isArray(t)?t:[t];return e.middleware.push(...r),e}}function oi(e){return async t=>{if(Array.isArray(t))for(let r of t)at(r),e.plugins.push(r),await r.register(e);else at(t),e.plugins.push(t),await t.register(e);return e}}function qe(e={}){let t=Yo(e),r;try{r=vr(t)}catch(f){throw f instanceof Error?new Error(`Failed to create server: ${f.message}`):new Error(`Failed to create server: ${String(f)}`)}let{port:n,host:o,middleware:i,plugins:s,cors:a}=r,c=Array.isArray(i)?[...i]:[],l=Array.isArray(s)?[...s]:[],p=new Lr.AsyncLocalStorage,g=qr({routesDir:r.routesDir,watchMode:process.env.NODE_ENV==="development"}),x=Tr({debug:process.env.NODE_ENV==="development",continueOnError:!0}),v=new jr.default,u={server:null,port:n,host:o,context:p,events:v,plugins:[...l],middleware:[...c],corsOptions:a,_signalHandlers:{unregister:()=>{}},use:()=>u,register:async()=>u,listen:async()=>u,close:async()=>{},router:g,pluginManager:x};return u.listen=Xo(u,r),u.close=ri(u),u.use=ni(u),u.register=oi(u),u}function xt(e){return{}}R();function ii(e){return typeof e=="object"&&e!==null&&"name"in e&&"execute"in e&&typeof e.name=="string"&&typeof e.execute=="function"}function si(e){return typeof e=="object"&&e!==null&&"name"in e&&"version"in e&&"register"in e&&typeof e.name=="string"&&typeof e.version=="string"&&typeof e.register=="function"}function ai(e){return e}function ci(e){return e}function li(...e){return e}function ui(...e){return e}b();I();b();R();var Le=class extends w{constructor(t,r=void 0,n=void 0){super("UNAUTHORIZED",t,401,n??y(),r)}};b();R();var je=class extends w{constructor(t,r=void 0,n=void 0){super("CONFLICT",t,409,n??y(),r)}};b();R();var Ve=class extends w{constructor(t,r=void 0,n=void 0){super("RATE_LIMITED",t,429,n??y(),r)}};ie();ze();b();R();var We=class extends w{constructor(t,r,n){super("UPLOAD_TIMEOUT",t,408,n??y(),r)}};b();R();var Qe=class extends w{constructor(t,r,n){super("UNPROCESSABLE_ENTITY",t,422,n??y(),r)}};Ne();b();R();var Ge=class extends w{constructor(t,r=void 0,n=void 0){super("SERVICE_UNAVAILABLE",t,503,n??y(),r)}};var Vr="0.1.0",Wr={createServer:qe,inferContext:xt},Qr={createDeleteRoute:_e,createGetRoute:be,createHeadRoute:Oe,createOptionsRoute:Ae,createPatchRoute:Me,createPostRoute:Ce,createPutRoute:Pe,createRouteFactory:tt,createMatcher:Y,extractParams:Q,compilePathPattern:J,paramsToQuery:ne,buildUrl:Fe},Gr={createMiddleware:$,createServiceMiddleware:Se,createStateMiddleware:ye,compose:L,cors:te},Zr={createPlugin:we},di={createServer:qe,createMiddleware:$,createServiceMiddleware:Se,createStateMiddleware:ye,createPlugin:we,getCorrelationId:y,Server:Wr,Router:Qr,Middleware:Gr,Plugins:Zr,VERSION:Vr};0&&(module.exports={Blaize,BlaizeError,ConflictError,ErrorSeverity,ErrorType,ForbiddenError,InternalServerError,MiddlewareAPI,NotFoundError,PayloadTooLargeError,PluginsAPI,RateLimitError,RequestTimeoutError,RouterAPI,ServerAPI,ServiceNotAvailableError,UnauthorizedError,UnprocessableEntityError,UnsupportedMediaTypeError,VERSION,ValidationError,asMiddlewareArray,asPluginArray,buildUrl,compilePathPattern,compose,cors,createDeleteRoute,createGetRoute,createHeadRoute,createMatcher,createMiddleware,createMiddlewareArray,createOptionsRoute,createPatchRoute,createPlugin,createPluginArray,createPostRoute,createPutRoute,createRouteFactory,createServer,createServiceMiddleware,createStateMiddleware,extractParams,getCorrelationId,inferContext,isBodyParseError,isMiddleware,isPlugin,paramsToQuery});
31
44
  //# sourceMappingURL=index.cjs.map