blaizejs 0.3.4 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-EE2VJ6JY.js → chunk-2LP25IUP.js} +3 -3
- package/dist/chunk-2LP25IUP.js.map +1 -0
- package/dist/{chunk-TL4GIFTB.js → chunk-6A3MHG3V.js} +3 -3
- package/dist/chunk-6A3MHG3V.js.map +1 -0
- package/dist/{chunk-HSLLYUVO.js → chunk-6XBGCGAR.js} +3 -3
- package/dist/chunk-6XBGCGAR.js.map +1 -0
- package/dist/{chunk-VLVWNGUO.js → chunk-J7KS32ZT.js} +3 -3
- package/dist/chunk-J7KS32ZT.js.map +1 -0
- package/dist/chunk-QD45PRU4.js +11 -0
- package/dist/chunk-QD45PRU4.js.map +1 -0
- package/dist/index.cjs +22 -9
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1664 -220
- package/dist/index.d.ts +1664 -220
- package/dist/index.js +22 -9
- package/dist/index.js.map +1 -1
- package/dist/{internal-server-error-GWBNT3OO.js → internal-server-error-BDHJW7WB.js} +3 -3
- package/dist/{payload-too-large-error-EBM5BNWG.js → payload-too-large-error-PX6RP7T6.js} +3 -3
- package/dist/{unsupported-media-type-error-YQ7GCZ32.js → unsupported-media-type-error-IXHPPRCO.js} +3 -3
- package/dist/{validation-error-6JDCGV2S.js → validation-error-FNJKIDG6.js} +3 -3
- package/package.json +2 -2
- package/dist/chunk-DTDGIBMA.js +0 -11
- package/dist/chunk-DTDGIBMA.js.map +0 -1
- package/dist/chunk-EE2VJ6JY.js.map +0 -1
- package/dist/chunk-HSLLYUVO.js.map +0 -1
- package/dist/chunk-TL4GIFTB.js.map +0 -1
- package/dist/chunk-VLVWNGUO.js.map +0 -1
- /package/dist/{internal-server-error-GWBNT3OO.js.map → internal-server-error-BDHJW7WB.js.map} +0 -0
- /package/dist/{payload-too-large-error-EBM5BNWG.js.map → payload-too-large-error-PX6RP7T6.js.map} +0 -0
- /package/dist/{unsupported-media-type-error-YQ7GCZ32.js.map → unsupported-media-type-error-IXHPPRCO.js.map} +0 -0
- /package/dist/{validation-error-6JDCGV2S.js.map → validation-error-FNJKIDG6.js.map} +0 -0
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
|
|
2
2
|
/**
|
|
3
|
-
* blaizejs v0.
|
|
3
|
+
* blaizejs v0.5.0
|
|
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{
|
|
11
|
-
//# sourceMappingURL=chunk-
|
|
10
|
+
import{c as r,g as o}from"./chunk-QD45PRU4.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-2LP25IUP.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/errors/payload-too-large-error.ts"],"sourcesContent":["import { BlaizeError, ErrorType } from '../../../blaize-types/src/errors';\nimport { getCorrelationId } from '../tracing/correlation';\n\nimport type { PayloadTooLargeErrorDetails } from '@blaize-types/errors';\n\nexport class PayloadTooLargeError extends BlaizeError<PayloadTooLargeErrorDetails> {\n constructor(\n title: string,\n details?: PayloadTooLargeErrorDetails | undefined,\n correlationId?: string\n ) {\n super(\n ErrorType.PAYLOAD_TOO_LARGE,\n title,\n 413,\n correlationId ?? getCorrelationId(),\n details\n );\n }\n}\n"],"mappings":";;;;;;;;;+CAKO,IAAMA,EAAN,cAAmCC,CAAyC,CACjF,YACEC,EACAC,EACAC,EACA,CACA,0BAEEF,EACA,IACAE,GAAiBC,EAAiB,EAClCF,CACF,CACF,CACF","names":["PayloadTooLargeError","BlaizeError","title","details","correlationId","getCorrelationId"]}
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
|
|
2
2
|
/**
|
|
3
|
-
* blaizejs v0.
|
|
3
|
+
* blaizejs v0.5.0
|
|
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{
|
|
11
|
-
//# sourceMappingURL=chunk-
|
|
10
|
+
import{c as r,g as e}from"./chunk-QD45PRU4.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-6A3MHG3V.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/errors/validation-error.ts"],"sourcesContent":["/**\n * ValidationError class for request validation failures\n *\n * This error is thrown when request validation fails (params, query, body, or response).\n * It provides structured information about which fields failed validation and why.\n */\n\nimport { BlaizeError, ErrorType } from '@blaize-types/errors';\n\nimport { getCorrelationId } from '../tracing/correlation';\n\nimport type { ValidationErrorDetails } from '@blaize-types/errors';\n\n/**\n * Error thrown when request validation fails\n *\n * Automatically sets HTTP status to 400 and provides structured\n * validation error information for better client debugging.\n *\n * @example Basic usage:\n * ```typescript\n * throw new ValidationError('Email is required');\n * ```\n *\n * @example With detailed field information:\n * ```typescript\n * throw new ValidationError('Validation failed', {\n * fields: [\n * {\n * field: 'email',\n * messages: ['Email is required', 'Email must be valid'],\n * rejectedValue: '',\n * expectedType: 'string'\n * }\n * ],\n * errorCount: 1,\n * section: 'body'\n * });\n * ```\n */\nexport class ValidationError extends BlaizeError<ValidationErrorDetails> {\n /**\n * Creates a new ValidationError instance\n *\n * @param title - Human-readable error message\n * @param details - Optional structured validation details\n * @param correlationId - Optional correlation ID (uses current context if not provided)\n */\n constructor(\n title: string,\n details: ValidationErrorDetails | undefined = undefined,\n correlationId: string | undefined = undefined\n ) {\n super(\n ErrorType.VALIDATION_ERROR,\n title,\n 400, // HTTP 400 Bad Request\n correlationId ?? getCorrelationId(),\n details\n );\n }\n}\n"],"mappings":";;;;;;;;;+CAwCO,IAAMA,EAAN,cAA8BC,CAAoC,CAQvE,YACEC,EACAC,EAA8C,OAC9CC,EAAoC,OACpC,CACA,yBAEEF,EACA,IACAE,GAAiBC,EAAiB,EAClCF,CACF,CACF,CACF","names":["ValidationError","BlaizeError","title","details","correlationId","getCorrelationId"]}
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
|
|
2
2
|
/**
|
|
3
|
-
* blaizejs v0.
|
|
3
|
+
* blaizejs v0.5.0
|
|
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{
|
|
11
|
-
//# sourceMappingURL=chunk-
|
|
10
|
+
import{c as r,g as e}from"./chunk-QD45PRU4.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-6XBGCGAR.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/errors/internal-server-error.ts"],"sourcesContent":["/**\n * InternalServerError class for server-side errors\n *\n * This error is thrown for unexpected server-side errors that are not\n * the client's fault. It provides debugging context while protecting\n * sensitive information in production.\n */\n\nimport { BlaizeError, ErrorType } from '@blaize-types/errors';\n\nimport { getCorrelationId } from '../tracing/correlation';\n\nimport type { InternalServerErrorDetails } from '@blaize-types/errors';\n/**\n * Error thrown for internal server errors\n *\n * Automatically sets HTTP status to 500 and provides debugging context.\n * Note: In production, sensitive details should be filtered by error boundary.\n *\n * @example Basic usage:\n * ```typescript\n * throw new InternalServerError('Something went wrong');\n * ```\n *\n * @example With debugging details:\n * ```typescript\n * throw new InternalServerError('Database error', {\n * originalError: error.message,\n * component: 'user-service',\n * operation: 'createUser',\n * retryable: true\n * });\n * ```\n *\n * @example Wrapping an existing error:\n * ```typescript\n * try {\n * await database.connect();\n * } catch (error) {\n * throw new InternalServerError('Database connection failed', {\n * originalError: error.message,\n * stackTrace: error.stack,\n * component: 'database',\n * retryable: true\n * });\n * }\n * ```\n */\nexport class InternalServerError extends BlaizeError<InternalServerErrorDetails> {\n /**\n * Creates a new InternalServerError instance\n *\n * @param title - Human-readable error message\n * @param details - Optional debugging context\n * @param correlationId - Optional correlation ID (uses current context if not provided)\n */\n constructor(\n title: string,\n details: InternalServerErrorDetails | undefined = undefined,\n correlationId: string | undefined = undefined\n ) {\n super(\n ErrorType.INTERNAL_SERVER_ERROR,\n title,\n 500, // HTTP 500 Internal Server Error\n correlationId ?? getCorrelationId(),\n details\n );\n }\n}\n"],"mappings":";;;;;;;;;+CAgDO,IAAMA,EAAN,cAAkCC,CAAwC,CAQ/E,YACEC,EACAC,EAAkD,OAClDC,EAAoC,OACpC,CACA,8BAEEF,EACA,IACAE,GAAiBC,EAAiB,EAClCF,CACF,CACF,CACF","names":["InternalServerError","BlaizeError","title","details","correlationId","getCorrelationId"]}
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
|
|
2
2
|
/**
|
|
3
|
-
* blaizejs v0.
|
|
3
|
+
* blaizejs v0.5.0
|
|
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{
|
|
11
|
-
//# sourceMappingURL=chunk-
|
|
10
|
+
import{c as r,g as o}from"./chunk-QD45PRU4.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-J7KS32ZT.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/errors/unsupported-media-type-error.ts"],"sourcesContent":["import { BlaizeError, ErrorType } from '../../../blaize-types/src/errors';\nimport { getCorrelationId } from '../tracing/correlation';\n\nexport class UnsupportedMediaTypeError extends BlaizeError {\n constructor(title: string, details?: unknown, correlationId?: string) {\n super(\n ErrorType.UNSUPPORTED_MEDIA_TYPE,\n title,\n 415,\n correlationId ?? getCorrelationId(),\n details\n );\n }\n}\n"],"mappings":";;;;;;;;;+CAGO,IAAMA,EAAN,cAAwCC,CAAY,CACzD,YAAYC,EAAeC,EAAmBC,EAAwB,CACpE,+BAEEF,EACA,IACAE,GAAiBC,EAAiB,EAClCF,CACF,CACF,CACF","names":["UnsupportedMediaTypeError","BlaizeError","title","details","correlationId","getCorrelationId"]}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
|
|
2
|
+
/**
|
|
3
|
+
* blaizejs v0.5.0
|
|
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))(u||{}),d=(o=>(o.LOW="low",o.MEDIUM="medium",o.HIGH="high",o.CRITICAL="critical",o))(d||{}),g=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},c=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 T(){return s.headerName}function E(){return s.generator()}function I(){let e=c.getStore();return e&&e.trim()?e:"unknown"}function C(e,t){return c.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,g as c,f as d,S as e,T as f,I as g,C as h,O as i};
|
|
11
|
+
//# sourceMappingURL=chunk-QD45PRU4.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\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\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":";;;;;;;;;AA2MO,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,oBA3DVA,OAAA,IAmEAC,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,CCppBA,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"]}
|
package/dist/index.cjs
CHANGED
|
@@ -1,18 +1,31 @@
|
|
|
1
1
|
|
|
2
2
|
/**
|
|
3
|
-
* blaizejs v0.
|
|
3
|
+
* blaizejs v0.5.0
|
|
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 lr=Object.create;var te=Object.defineProperty;var cr=Object.getOwnPropertyDescriptor;var dr=Object.getOwnPropertyNames;var pr=Object.getPrototypeOf,fr=Object.prototype.hasOwnProperty;var q=(e,t)=>()=>(e&&(t=e(e=0)),t);var Q=(e,t)=>{for(var r in t)te(e,r,{get:t[r],enumerable:!0})},Ye=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of dr(t))!fr.call(e,n)&&n!==r&&te(e,n,{get:()=>t[n],enumerable:!(o=cr(t,n))||o.enumerable});return e};var T=(e,t,r)=>(r=e!=null?lr(pr(e)):{},Ye(t||!e||!e.__esModule?te(r,"default",{value:e,enumerable:!0}):r,e)),mr=e=>Ye(te({},"__esModule",{value:!0}),e);function Er(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,dt,h,x=q(()=>{"use strict";P=(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))(P||{}),dt=(n=>(n.LOW="low",n.MEDIUM="medium",n.HIGH="high",n.CRITICAL="critical",n))(dt||{}),h=class extends Error{type;title;status;correlationId;timestamp;details;constructor(t,r,o,n,i){super(r),this.name=this.constructor.name,this.type=t,this.title=r,this.status=o,this.correlationId=n,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 De(){let e=Date.now().toString(36),t=Math.random().toString(36).substr(2,9);return`req_${e}_${t}`}function R(){let e=xr.getStore();return e&&e.trim()?e:"unknown"}var pt,xr,v=q(()=>{"use strict";pt=require("async_hooks"),xr=new pt.AsyncLocalStorage});var ft={};Q(ft,{InternalServerError:()=>D});var D,W=q(()=>{"use strict";x();v();D=class extends h{constructor(t,r=void 0,o=void 0){super("INTERNAL_SERVER_ERROR",t,500,o??R(),r)}}});var H={};Q(H,{ValidationError:()=>k});var k,z=q(()=>{"use strict";x();v();k=class extends h{constructor(t,r=void 0,o=void 0){super("VALIDATION_ERROR",t,400,o??R(),r)}}});var ke={};Q(ke,{PayloadTooLargeError:()=>G});var G,le=q(()=>{"use strict";v();x();G=class extends h{constructor(t,r,o){super("PAYLOAD_TOO_LARGE",t,413,o??R(),r)}}});var ze={};Q(ze,{UnsupportedMediaTypeError:()=>Z});var Z,ce=q(()=>{"use strict";v();x();Z=class extends h{constructor(t,r,o){super("UNSUPPORTED_MEDIA_TYPE",t,415,o??R(),r)}}});var Uo={};Q(Uo,{Blaize:()=>Ao,BlaizeError:()=>h,ConflictError:()=>Se,ErrorSeverity:()=>dt,ErrorType:()=>P,ForbiddenError:()=>Re,InternalServerError:()=>D,MiddlewareAPI:()=>ar,NotFoundError:()=>$,PayloadTooLargeError:()=>G,PluginsAPI:()=>ur,RateLimitError:()=>Te,RequestTimeoutError:()=>Ee,RouterAPI:()=>sr,ServerAPI:()=>ir,UnauthorizedError:()=>we,UnprocessableEntityError:()=>xe,UnsupportedMediaTypeError:()=>Z,VERSION:()=>nr,ValidationError:()=>k,compose:()=>A,createDeleteRoute:()=>Ce,createGetRoute:()=>be,createHeadRoute:()=>Me,createMiddleware:()=>re,createOptionsRoute:()=>Oe,createPatchRoute:()=>Fe,createPlugin:()=>oe,createPostRoute:()=>Pe,createPutRoute:()=>ve,createServer:()=>he,isBodyParseError:()=>Er});module.exports=mr(Uo);function Ke(e,t,r){if(!e||e.skip&&e.skip(t))return Promise.resolve(r());try{let o=e.execute(t,r);return o instanceof Promise?o:Promise.resolve(o)}catch(o){return Promise.reject(o)}}function A(e){return e.length===0?async(t,r)=>{await Promise.resolve(r())}:async function(t,r){let o=new Set,n=async i=>{if(i>=e.length)return Promise.resolve(r());let s=e[i];return Ke(s,t,()=>{if(o.has(i))throw new Error("next() called multiple times");return o.add(i),n(i+1)})};return n(0)}}function re(e){if(typeof e=="function")return{name:"anonymous",execute:e,debug:!1};let{name:t="anonymous",handler:r,skip:o,debug:n=!1}=e,i={name:t,execute:r,debug:n};return o!==void 0?{...i,skip:o}:i}function oe(e,t,r,o={}){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={...o,...i},a={name:e,version:t,register:async u=>{let c=await r(u,s);c&&typeof c=="object"&&Object.assign(a,c)}};return a}}var rt=require("url");var ne={};function Xe(e){ne={...ne,...e}}function et(){if(!ne.routesDir)throw new Error("Routes directory not configured. Make sure server is properly initialized.");return ne.routesDir}var tt=T(require("path"),1);function ie(e,t){e.startsWith("file://")&&(e=e.replace("file://","")),t.startsWith("file://")&&(t=t.replace("file://",""));let r=e.replace(/\\/g,"/"),o=t.replace(/\\/g,"/"),n=o.endsWith("/")?o:`${o}/`,i=r;r.startsWith(n)?i=r.substring(n.length):r.startsWith(o)?(i=r.substring(o.length),i.startsWith("/")&&(i=i.substring(1))):i=tt.relative(o,r).replace(/\\/g,"/"),i=i.replace(/\.[^.]+$/,"");let s=i.split("/").filter(Boolean),a=[],u=s.map(S=>{if(S.startsWith("[")&&S.endsWith("]")){let p=S.slice(1,-1);return a.push(p),`:${p}`}return S}),c=u.length>0?`/${u.join("/")}`:"/";return c.endsWith("/index")&&(c=c.slice(0,-6)||"/"),{filePath:e,routePath:c,params:a}}function gr(){let e=Error.prepareStackTrace;try{Error.prepareStackTrace=(n,i)=>i;let r=new Error().stack[3];if(!r||typeof r.getFileName!="function")throw new Error("Unable to determine caller file frame");let o=r.getFileName();if(!o)throw new Error("Unable to determine caller file name");return o.startsWith("file://")?(0,rt.fileURLToPath)(o):o}finally{Error.prepareStackTrace=e}}function U(){let e=gr(),t=et(),r=ie(e,t);return console.log(`\u{1F50E} Parsed route path: ${r.routePath} from file: ${e}`),r.routePath}var be=e=>{L("GET",e);let t=U();return{GET:e,path:t}},Pe=e=>{L("POST",e);let t=U();return{POST:e,path:t}},ve=e=>{L("PUT",e);let t=U();return{PUT:e,path:t}},Ce=e=>{L("DELETE",e);let t=U();return{DELETE:e,path:t}},Fe=e=>{L("PATCH",e);let t=U();return{PATCH:e,path:t}},Me=e=>{L("HEAD",e);let t=U();return{HEAD:e,path:t}},Oe=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&&yr(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 yr(e,t){let{params:r,query:o,body:n,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(o&&(!o._def||typeof o.parse!="function"))throw new Error(`Query schema for ${e} must be a valid Zod schema`);if(n&&(!n._def||typeof n.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`)}var rr=require("async_hooks"),or=T(require("events"),1);var Ne=T(require("fs"),1),Ft=T(require("http"),1),Mt=T(require("http2"),1);var O=T(require("fs"),1),se=T(require("path"),1),ot=T(require("selfsigned"),1);async function nt(){let e=se.join(process.cwd(),".blaizejs","certs"),t=se.join(e,"dev.key"),r=se.join(e,"dev.cert");if(O.existsSync(t)&&O.existsSync(r))return{keyFile:t,certFile:r};O.existsSync(e)||O.mkdirSync(e,{recursive:!0});let i=ot.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 O.writeFileSync(t,Buffer.from(i.private,"utf-8")),O.writeFileSync(r,Buffer.from(i.cert,"utf-8")),console.log(`
|
|
10
|
+
"use strict";var Gr=Object.create;var le=Object.defineProperty;var Zr=Object.getOwnPropertyDescriptor;var Jr=Object.getOwnPropertyNames;var Yr=Object.getPrototypeOf,Kr=Object.prototype.hasOwnProperty;var Q=(e,t)=>()=>(e&&(t=e(e=0)),t);var J=(e,t)=>{for(var r in t)le(e,r,{get:t[r],enumerable:!0})},yt=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Jr(t))!Kr.call(e,o)&&o!==r&&le(e,o,{get:()=>t[o],enumerable:!(n=Zr(t,o))||n.enumerable});return e};var P=(e,t,r)=>(r=e!=null?Gr(Yr(e)):{},yt(t||!e||!e.__esModule?le(r,"default",{value:e,enumerable:!0}):r,e)),Xr=e=>yt(le({},"__esModule",{value:!0}),e);function sn(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 _,Tt,x,C=Q(()=>{"use strict";_=(m=>(m.VALIDATION_ERROR="VALIDATION_ERROR",m.NOT_FOUND="NOT_FOUND",m.UNAUTHORIZED="UNAUTHORIZED",m.FORBIDDEN="FORBIDDEN",m.SSE_NOT_ACCEPTABLE="SSE_NOT_ACCEPTABLE",m.CONFLICT="CONFLICT",m.RATE_LIMITED="RATE_LIMITED",m.INTERNAL_SERVER_ERROR="INTERNAL_SERVER_ERROR",m.PAYLOAD_TOO_LARGE="PAYLOAD_TOO_LARGE",m.UNSUPPORTED_MEDIA_TYPE="UNSUPPORTED_MEDIA_TYPE",m.UPLOAD_TIMEOUT="UPLOAD_TIMEOUT",m.UNPROCESSABLE_ENTITY="UNPROCESSABLE_ENTITY",m.NETWORK_ERROR="NETWORK_ERROR",m.TIMEOUT_ERROR="TIMEOUT_ERROR",m.PARSE_ERROR="PARSE_ERROR",m.HTTP_ERROR="HTTP_ERROR",m.SSE_CONNECTION_ERROR="SSE_CONNECTION_ERROR",m.SSE_BUFFER_OVERFLOW="SSE_BUFFER_OVERFLOW",m.SSE_STREAM_CLOSED="SSE_STREAM_CLOSED",m))(_||{}),Tt=(o=>(o.LOW="low",o.MEDIUM="medium",o.HIGH="high",o.CRITICAL="critical",o))(Tt||{}),x=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 an(){let e=Date.now().toString(36),t=Math.random().toString(36).substr(2,9);return`req_${e}_${t}`}function Ct(e,t){he={headerName:e||je.headerName,generator:t||je.generator}}function j(){return he.headerName}function cn(){return he.generator()}function S(){let e=bt.getStore();return e&&e.trim()?e:"unknown"}function Pt(e,t){return bt.run(e,t)}function ye(e){let t=he.headerName,r=e[t],n;return Array.isArray(r)?n=r[0]:typeof r=="string"&&(n=r),n&&n.trim()?n:cn()}var Rt,je,he,bt,T=Q(()=>{"use strict";Rt=require("async_hooks"),je={headerName:"x-correlation-id",generator:an},he={...je},bt=new Rt.AsyncLocalStorage});var Ut={};J(Ut,{InternalServerError:()=>N});var N,X=Q(()=>{"use strict";C();T();N=class extends x{constructor(t,r=void 0,n=void 0){super("INTERNAL_SERVER_ERROR",t,500,n??S(),r)}}});var W={};J(W,{ValidationError:()=>O});var O,I=Q(()=>{"use strict";C();T();O=class extends x{constructor(t,r=void 0,n=void 0){super("VALIDATION_ERROR",t,400,n??S(),r)}}});var Qe={};J(Qe,{PayloadTooLargeError:()=>ee});var ee,Oe=Q(()=>{"use strict";C();T();ee=class extends x{constructor(t,r,n){super("PAYLOAD_TOO_LARGE",t,413,n??S(),r)}}});var Ge={};J(Ge,{UnsupportedMediaTypeError:()=>te});var te,Fe=Q(()=>{"use strict";C();T();te=class extends x{constructor(t,r,n){super("UNSUPPORTED_MEDIA_TYPE",t,415,n??S(),r)}}});var li={};J(li,{Blaize:()=>ci,BlaizeError:()=>x,ConflictError:()=>$e,ErrorSeverity:()=>Tt,ErrorType:()=>_,ForbiddenError:()=>G,InternalServerError:()=>N,MiddlewareAPI:()=>Vr,NotFoundError:()=>H,PayloadTooLargeError:()=>ee,PluginsAPI:()=>Wr,RateLimitError:()=>He,RequestTimeoutError:()=>Ue,RouterAPI:()=>jr,ServerAPI:()=>Lr,UnauthorizedError:()=>Be,UnprocessableEntityError:()=>qe,UnsupportedMediaTypeError:()=>te,VERSION:()=>qr,ValidationError:()=>O,asMiddlewareArray:()=>oi,asPluginArray:()=>ii,compose:()=>L,createDeleteRoute:()=>Te,createGetRoute:()=>xe,createHeadRoute:()=>be,createMiddleware:()=>$,createMiddlewareArray:()=>si,createOptionsRoute:()=>Ce,createPatchRoute:()=>Re,createPlugin:()=>pe,createPluginArray:()=>ai,createPostRoute:()=>Ee,createPutRoute:()=>ve,createRouteFactory:()=>We,createServer:()=>Ne,createServiceMiddleware:()=>de,createStateMiddleware:()=>ue,getCorrelationId:()=>S,inferContext:()=>ht,isBodyParseError:()=>sn,isMiddleware:()=>ri,isPlugin:()=>ni});module.exports=Xr(li);function St(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 St(s,t,()=>{if(n.has(i))throw new Error("next() called multiple times");return n.add(i),o(i+1)})};return o(0)}}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 ue(e){return $({name:"state-middleware",handler:e})}function de(e){return $({name:"service-middleware",handler:e})}function pe(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 u=await r(c,s);u&&typeof u=="object"&&Object.assign(a,u)}};return a}}var At=require("url");var fe={};function wt(e){fe={...fe,...e}}function xt(){if(!fe.routesDir)throw new Error("Routes directory not configured. Make sure server is properly initialized.");return fe.routesDir}var Et=P(require("path"),1);function me(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=Et.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 h=p.slice(1,-1);return a.push(h),`:${h}`}return p}),u=c.length>0?`/${c.join("/")}`:"/";return u.endsWith("/index")&&(u=u.slice(0,-6)||"/"),{filePath:e,routePath:u,params:a}}var Mt=require("events");var M=require("zod"),en=M.z.enum(["drop-oldest","drop-newest","close"]),tn=M.z.object({low:M.z.number().int().positive().describe("Resume threshold in messages"),high:M.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"]}),rn=M.z.object({maxMessages:M.z.number().int().positive().max(1e5).describe("Maximum number of messages in buffer"),maxBytes:M.z.number().int().positive().max(100*1024*1024).optional().describe("Maximum buffer size in bytes"),messageTimeout:M.z.number().int().nonnegative().max(3e5).optional().describe("Message TTL in milliseconds")}),vt=M.z.object({enabled:M.z.boolean().default(!0).describe("Enable backpressure management"),strategy:en.default("drop-oldest").describe("Strategy when buffer reaches high watermark"),watermarks:tn.default({low:100,high:1e3}).describe("Buffer watermark thresholds"),limits:rn.default({maxMessages:1e4}).describe("Buffer size constraints"),metrics:M.z.object({enabled:M.z.boolean().default(!1),interval:M.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 nn={maxConnections:1e4,maxConnectionsPerClient:100,inactiveTimeout:18e5,cleanupInterval:6e4};function on(e){let t={...nn,...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,y)=>{if(!d)return;let b=(n.get(d)||0)+y;b<=0?n.delete(d):n.set(d,b)},u=(d,y,m)=>{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(m?.clientIp&&(n.get(m.clientIp)||0)>=t.maxConnectionsPerClient)throw new Error(`Maximum connections per client reached (${t.maxConnectionsPerClient})`);let b=Date.now();r.set(d,{stream:y,connectedAt:b,lastActivity:b,clientIp:m?.clientIp,userAgent:m?.userAgent}),c(m?.clientIp,1),r.size===1&&s(i.cleanup),y.onClose(()=>{p(d)})},p=d=>{let y=r.get(d);y&&(r.delete(d),c(y.clientIp,-1),r.size===0&&a())},h=()=>r.size,w=()=>{let d=Date.now(),y=[];r.forEach((m,b)=>{let k=d-m.lastActivity>t.inactiveTimeout,Qr=!m.stream||m.stream.state==="closed"||!m.stream.isWritable;if((k||Qr)&&(y.push(b),m.stream&&typeof m.stream.close=="function"))try{m.stream.close()}catch{}}),y.forEach(m=>p(m))},E=d=>r.get(d)?.stream,l=d=>r.has(d),f=()=>Array.from(r.keys()),g=()=>{a(),r.forEach(d=>{if(d.stream&&typeof d.stream.close=="function")try{d.stream.close()}catch{}}),r.clear(),n.clear()};return i.add=u,i.remove=p,i.count=h,i.cleanup=w,i.get=E,i.has=l,i.getIds=f,i.shutdown=g,i}var Le=null;function ge(e){return Le||(Le=on(e)),Le}C();T();var Y=class extends x{constructor(t,r,n=void 0){super("SSE_BUFFER_OVERFLOW",t,503,n??S(),r)}};C();T();var Se=class extends x{constructor(t,r=void 0,n=void 0){super("SSE_STREAM_CLOSED",t,410,n??S(),r)}};T();var ln={heartbeatInterval:3e4,maxEventSize:1024*1024,autoClose:!0,maxBufferSize:1e3,bufferStrategy:"drop-oldest"};function _t(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(`
|
|
11
|
+
`);for(let a of s)o.push(`data: ${a}`);return o.push(""),o.join(`
|
|
12
|
+
`)+`
|
|
13
|
+
`}function un(){let e=Date.now().toString(36),t=Math.random().toString(36).substr(2,9);return`${e}-${t}`}function dn(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 pn(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 Ve=class{id;_state="connecting";_buffer=[];_closeCallbacks=[];_errorCallbacks=[];_emitter=new Mt.EventEmitter;_metrics;_options;_response;_request;_writable=!0;_cleanupExecuted=!1;_eventCounter=0;_lastEventId=null;_heartbeatTimer;_backpressureConfig;_disconnectHandlers=null;constructor(t,r={}){if(this.id=`sse-${un()}`,this._options={...ln,...r},this._response=t.response,this._request=t.request,r.backpressure){let o=vt.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=ge(),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
|
|
14
|
+
|
|
15
|
+
`)}_registerConnection(){try{let t=ge(),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=_t(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{ge().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 Se("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=S(),i=dn(t,r),s=this._options.maxEventSize;if(i>s)throw new Y("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 Y("Buffer overflow - stream closed",{currentSize:p,maxSize:c,strategy:"close",clientId:this.id})}let u=pn(this._buffer,this._options.bufferStrategy,a,c);this._buffer=u.buffer,this._metrics.eventsDropped+=u.dropped,u.dropped>0&&console.warn(`SSE stream ${this.id}: Dropped ${u.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(u=>{this._handleError(u)})}sendError(t){if(!this.isWritable)return;let r={message:t.message,name:t.name,correlationId:S(),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=_t("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}
|
|
16
|
+
|
|
17
|
+
`:`: ping
|
|
18
|
+
|
|
19
|
+
`;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)}
|
|
20
|
+
|
|
21
|
+
`)}}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 Ot(e,t){return new Ve(e,t)}C();T();var we=class extends x{constructor(t,r,n){super("SSE_NOT_ACCEPTABLE",t,406,n||S(),r)}};function fn(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 mn(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 Ft=()=>e=>{fn(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 we("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=Ot(n,e.options),a=e.schema?.events&&typeof e.schema.events=="object"&&!e.schema.events._def?mn(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 gn(){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,At.fileURLToPath)(n):n}finally{Error.prepareStackTrace=e}}function D(){let e=gn(),t=xt(),r=me(e,t);return console.log(`\u{1F50E} Parsed route path: ${r.routePath} from file: ${e}`),r.routePath}var xe=()=>e=>{V("GET",e);let t=D();return{GET:e,path:t}},Ee=()=>e=>{V("POST",e);let t=D();return{POST:e,path:t}},ve=()=>e=>{V("PUT",e);let t=D();return{PUT:e,path:t}},Te=()=>e=>{V("DELETE",e);let t=D();return{DELETE:e,path:t}},Re=()=>e=>{V("PATCH",e);let t=D();return{PATCH:e,path:t}},be=()=>e=>{V("HEAD",e);let t=D();return{HEAD:e,path:t}},Ce=()=>e=>{V("OPTIONS",e);let t=D();return{OPTIONS:e,path:t}};function V(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&&hn(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 hn(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 We(){return{get:xe(),post:Ee(),put:ve(),delete:Te(),patch:Re(),head:be(),options:Ce(),sse:Ft()}}var Hr=require("async_hooks"),Ur=P(require("events"),1);var et=P(require("fs"),1),mr=P(require("http"),1),gr=P(require("http2"),1);var z=P(require("fs"),1),Pe=P(require("path"),1),kt=P(require("selfsigned"),1);async function It(){let e=Pe.join(process.cwd(),".blaizejs","certs"),t=Pe.join(e,"dev.key"),r=Pe.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=kt.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
22
|
\u{1F512} Generated self-signed certificates for development at ${e}
|
|
12
|
-
`),{keyFile:t,certFile:r}}var
|
|
13
|
-
`))&&(
|
|
23
|
+
`),{keyFile:t,certFile:r}}var F=class extends Error{constructor(t="\u274C Response has already been sent"){super(t),this.name="ResponseSentError"}},K=class extends F{constructor(t="Cannot set header after response has been sent"){super(t)}},_e=class extends F{constructor(t="Cannot set content type after response has been sent"){super(t)}},Me=class extends F{constructor(t="Invalide URL"){super(t)}};var Dt=require("async_hooks"),yn=new Dt.AsyncLocalStorage;function zt(e,t){return yn.run(e,t)}T();var qt=P(require("crypto"),1),Lt=require("fs"),jt=require("os"),Vt=require("path"),Ze=require("stream");var Sn=/boundary=([^;]+)/i,wn=/Content-Disposition:\s*form-data;\s*name="([^"]+)"(?:;[\s\r\n]*filename="([^"]*)")?/i,xn=/Content-Type:\s*([^\r\n]+)/i,En=/multipart\/form-data/i;function Nt(e){let t=e.match(Sn);if(!t||!t[1])return null;let r=t[1].trim();return r.startsWith('"')&&r.endsWith('"')&&(r=r.slice(1,-1)),r||null}function Bt(e){let t=e.match(wn);return!t||!t[1]?null:{name:t[1],filename:t[2]!==void 0?t[2]:void 0}}function $t(e){let t=e.match(xn);return t&&t[1]?.trim()?t[1].trim():"application/octet-stream"}function Ht(e){return En.test(e)}var vn={maxFileSize:10*1024*1024,maxFiles:10,maxFieldSize:1*1024*1024,allowedMimeTypes:[],allowedExtensions:[],strategy:"stream",tempDir:(0,jt.tmpdir)(),computeHash:!1};function Tn(e,t={}){return{boundary:Buffer.from(`--${e}`),options:{...vn,...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 Rn(e,t){let r=Buffer.concat([e.buffer,t]),n={...e,buffer:r};for(;n.buffer.length>0&&!n.isFinished;){let o=await bn(n);if(o===n)break;n=o}return n}async function bn(e){switch(e.stage){case"boundary":return Cn(e);case"headers":return Pn(e);case"content":return _n(e);default:{let{InternalServerError:t}=await Promise.resolve().then(()=>(X(),Ut));throw new t("Invalid parser stage",{operation:e.stage})}}}function Cn(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
|
|
24
|
+
`))&&(n=n.subarray(2)),{...e,buffer:n,hasFoundValidBoundary:r,stage:"headers",currentHeaders:""})}async function Pn(e){let t=e.buffer.indexOf(`\r
|
|
14
25
|
\r
|
|
15
|
-
`);if(t===-1)return e;let r=e.buffer.subarray(0,t).toString("utf8"),o=e.buffer.subarray(t+4),n=ut(r);if(!n){let{ValidationError:a}=await Promise.resolve().then(()=>(z(),H));throw new a("Missing or invalid Content-Disposition header")}let i=lt(r),s=n.filename!==void 0;if(s&&e.fileCount>=e.options.maxFiles){let{PayloadTooLargeError:a}=await Promise.resolve().then(()=>(le(),ke));throw new a("Too many files in upload",{fileCount:e.fileCount+1,maxFiles:e.options.maxFiles,filename:n.filename})}if(s&&e.options.allowedMimeTypes.length>0&&!e.options.allowedMimeTypes.includes(i)){let{UnsupportedMediaTypeError:a}=await Promise.resolve().then(()=>(ce(),ze));throw new a("File type not allowed",{receivedMimeType:i,allowedMimeTypes:e.options.allowedMimeTypes,filename:n.filename})}return{...e,buffer:o,stage:"content",currentHeaders:r,currentField:n.name,currentFilename:n.filename,currentMimetype:i,currentContentLength:0,fileCount:s?e.fileCount+1:e.fileCount,fieldCount:s?e.fieldCount:e.fieldCount+1,currentBufferChunks:[]}}async function Or(e){let t=e.buffer.indexOf(e.boundary),r,o=!1,n=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),n=e.buffer.subarray(s)}else{let s=Math.max(0,t-2);r=e.buffer.subarray(0,s),n=e.buffer.subarray(t),o=!0}let i={...e,buffer:n};return r.length>0&&(i=await Dr(i,r)),o&&(i=await Br(i),i={...i,stage:"boundary",hasProcessedAnyPart:!0}),i}async function Dr(e,t){let r=e.currentContentLength+t.length,o=e.currentFilename!==void 0?e.options.maxFileSize:e.options.maxFieldSize;if(r>o){let n=e.currentFilename!==void 0,{PayloadTooLargeError:i}=await Promise.resolve().then(()=>(le(),ke)),s=e.currentField?{contentType:n?"file":"field",currentSize:r,maxSize:o,field:e.currentField,filename:e.currentFilename}:{contentType:n?"file":"field",currentSize:r,maxSize:o,filename:e.currentFilename};throw new i(`${n?"File":"Field"} size exceeds limit`,s)}return e.currentFilename!==void 0?kr(e,t,r):{...e,currentContentLength:r,currentBufferChunks:[...e.currentBufferChunks,t]}}async function kr(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 Ar(e.currentWriteStream,t),{...e,currentContentLength:r};default:{let{ValidationError:o}=await Promise.resolve().then(()=>(z(),H));throw new o("Invalid parsing strategy")}}}async function zr(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:o=>{t=o}});return{...e,currentStream:r,streamController:t}}case"temp":{let t=(0,ht.join)(e.options.tempDir,`upload-${mt.randomUUID()}`),r=(0,gt.createWriteStream)(t),o=async()=>{try{let{unlink:n}=await import("fs/promises");await n(t)}catch(n){console.warn(`Failed to cleanup temp file: ${t}`,n)}};return{...e,currentTempPath:t,currentWriteStream:r,cleanupTasks:[...e.cleanupTasks,o]}}default:{let{ValidationError:t}=await Promise.resolve().then(()=>(z(),H));throw new t("Invalid file processing strategy")}}}async function Br(e){return e.currentField?e.currentFilename!==void 0?$r(e):Nr(e):J(e)}async function $r(e){if(!e.currentField||e.currentFilename===void 0)return J(e);let t,r,o;switch(e.options.strategy){case"memory":r=Buffer.concat(e.currentBufferChunks),t=Be.Readable.from(r);break;case"stream":e.streamController&&e.streamController.close(),t=e.currentStream;break;case"temp":e.currentWriteStream&&await Rt(e.currentWriteStream),o=e.currentTempPath,t=Be.Readable.from(Buffer.alloc(0));break;default:{let{ValidationError:s}=await Promise.resolve().then(()=>(z(),H));throw new s("Invalid file finalization strategy")}}let n={filename:e.currentFilename,fieldname:e.currentField,mimetype:e.currentMimetype,size:e.currentContentLength,stream:t,buffer:r,tempPath:o},i=wt(e.files,e.currentField,n);return{...J(e),files:i}}function Nr(e){if(!e.currentField)return J(e);let t=Buffer.concat(e.currentBufferChunks).toString("utf8"),r=wt(e.fields,e.currentField,t);return{...J(e),fields:r}}function J(e){return{...e,currentField:null,currentFilename:void 0,currentContentLength:0,currentBufferChunks:[],currentStream:null,streamController:null,currentTempPath:null,currentWriteStream:null}}function wt(e,t,r){let o=new Map(e),n=o.get(t)||[];return o.set(t,[...n,r]),o}async function Ir(e){if(!e.hasFoundValidBoundary){let{ValidationError:o}=await Promise.resolve().then(()=>(z(),H));throw new o("No valid multipart boundary found")}if(e.hasFoundValidBoundary&&!e.hasProcessedAnyPart){let{ValidationError:o}=await Promise.resolve().then(()=>(z(),H));throw new o("Empty multipart request")}let t={};for(let[o,n]of e.fields.entries())t[o]=n.length===1?n[0]:n;let r={};for(let[o,n]of e.files.entries())r[o]=n.length===1?n[0]:n;return{fields:t,files:r}}async function _r(e){await Promise.allSettled(e.cleanupTasks.map(t=>t())),e.streamController&&e.streamController.close(),e.currentWriteStream&&await Rt(e.currentWriteStream)}async function Ar(e,t){return new Promise((r,o)=>{e.write(t,n=>{n?o(n):r()})})}async function Rt(e){return new Promise(t=>{e.end(()=>t())})}async function St(e,t={}){let r=e.headers["content-type"]||"",o=at(r);if(!o){let{UnsupportedMediaTypeError:i}=await Promise.resolve().then(()=>(ce(),ze));throw new i("Missing boundary in multipart content-type",{receivedContentType:r,expectedFormat:"multipart/form-data; boundary=..."})}let n=Pr(o,t);n.currentFilename!==void 0&&(n=await zr(n));try{for await(let i of e)n=await vr(n,i);return Ir(n)}finally{await _r(n)}}var Y="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 Ur(e){let t=e.url||"/",r=e.headers.host||"localhost",n=`${e.socket&&e.socket.encrypted?"https":"http"}://${r}${t.startsWith("/")?"":"/"}${t}`;try{let i=new URL(n),s=i.pathname,a={};return i.searchParams.forEach((u,c)=>{a[c]!==void 0?Array.isArray(a[c])?a[c].push(u):a[c]=[a[c],u]:a[c]=u}),{path:s,url:i,query:a}}catch(i){throw console.warn(`Invalid URL: ${n}`,i),new ue(`Invalid URL: ${n}`)}}function Lr(e){return"stream"in e||"httpVersionMajor"in e&&e.httpVersionMajor===2}function Hr(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 Tt(e,t,r={}){let{path:o,url:n,query:i}=Ur(e),s=e.method||"GET",a=Lr(e),u=Hr(e),c={},S={...r.initialState||{}},p={sent:!1},g={request:qr(e,{path:o,url:n,query:i,params:c,method:s,isHttp2:a,protocol:u}),response:{},state:S};return g.response=Qr(t,p,g),r.parseBody&&await to(e,g,r),g}function qr(e,t){return{raw:e,...t,header:Et(e),headers:jr(e),body:void 0}}function Et(e){return t=>{let r=e.headers[t.toLowerCase()];return Array.isArray(r)?r.join(", "):r||void 0}}function jr(e){let t=Et(e);return r=>r&&Array.isArray(r)&&r.length>0?r.reduce((o,n)=>(o[n]=t(n),o),{}):Object.entries(e.headers).reduce((o,[n,i])=>(o[n]=Array.isArray(i)?i.join(", "):i||void 0,o),{})}function Qr(e,t,r){return{raw:e,get sent(){return t.sent},status:Vr(e,t,r),header:Wr(e,t,r),headers:Gr(e,t,r),type:Zr(e,t,r),json:Jr(e,t),text:Yr(e,t),html:Kr(e,t),redirect:Xr(e,t),stream:eo(e,t)}}function Vr(e,t,r){return function(n){if(t.sent)throw new C;return e.statusCode=n,r.response}}function Wr(e,t,r){return function(n,i){if(t.sent)throw new V;return e.setHeader(n,i),r.response}}function Gr(e,t,r){return function(n){if(t.sent)throw new V;for(let[i,s]of Object.entries(n))e.setHeader(i,s);return r.response}}function Zr(e,t,r){return function(n){if(t.sent)throw new ae;return e.setHeader(Y,n),r.response}}function Jr(e,t){return function(o,n){if(t.sent)throw new C;n!==void 0&&(e.statusCode=n),e.setHeader(Y,"application/json"),e.end(JSON.stringify(o)),t.sent=!0}}function Yr(e,t){return function(o,n){if(t.sent)throw new C;n!==void 0&&(e.statusCode=n),e.setHeader(Y,"text/plain"),e.end(o),t.sent=!0}}function Kr(e,t){return function(o,n){if(t.sent)throw new C;n!==void 0&&(e.statusCode=n),e.setHeader(Y,"text/html"),e.end(o),t.sent=!0}}function Xr(e,t){return function(o,n=302){if(t.sent)throw new C;e.statusCode=n,e.setHeader("Location",o),e.end(),t.sent=!0}}function eo(e,t){return function(o,n={}){if(t.sent)throw new C;if(n.status!==void 0&&(e.statusCode=n.status),n.contentType&&e.setHeader(Y,n.contentType),n.headers)for(let[i,s]of Object.entries(n.headers))e.setHeader(i,s);o.pipe(e),o.on("end",()=>{t.sent=!0}),o.on("error",i=>{console.error("Stream error:",i),t.sent||(e.statusCode=500,e.end("Stream error"),t.sent=!0)})}}async function to(e,t,r={}){if(ro(e.method))return;let o=e.headers["content-type"]||"",n=parseInt(e.headers["content-length"]||"0",10);if(n===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(o.includes("application/json")){if(n>i.json)throw new Error(`JSON body too large: ${n} > ${i.json} bytes`);await oo(e,t)}else if(o.includes("application/x-www-form-urlencoded")){if(n>i.form)throw new Error(`Form body too large: ${n} > ${i.form} bytes`);await no(e,t)}else if(o.includes("text/")){if(n>i.text)throw new Error(`Text body too large: ${n} > ${i.text} bytes`);await so(e,t)}else if(ct(o))await ao(e,t,i.multipart);else{if(n>i.raw)throw new Error(`Request body too large: ${n} > ${i.raw} bytes`);return}}catch(s){let a=o.includes("multipart")?"multipart_parse_error":"body_read_error";de(t,a,"Error reading request body",s)}}function ro(e){return["GET","HEAD","OPTIONS"].includes(e||"GET")}async function oo(e,t){let r=await $e(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 o=JSON.parse(r);t.request.body=o}catch(o){t.request.body=null,de(t,"json_parse_error","Invalid JSON in request body",o)}}async function no(e,t){let r=await $e(e);if(r)try{t.request.body=io(r)}catch(o){t.request.body=null,de(t,"form_parse_error","Invalid form data in request body",o)}}function io(e){let t=new URLSearchParams(e),r={};return t.forEach((o,n)=>{r[n]!==void 0?Array.isArray(r[n])?r[n].push(o):r[n]=[r[n],o]:r[n]=o}),r}async function so(e,t){let r=await $e(e);r&&(t.request.body=r)}async function ao(e,t,r){try{let o=r||B.multipart,n=await St(e,{strategy:"stream",maxFileSize:o.maxFileSize,maxFiles:o.maxFiles,maxFieldSize:o.maxFieldSize});t.request.multipart=n,t.request.files=n.files,t.request.body=n.fields}catch(o){t.request.body=null,de(t,"multipart_parse_error","Failed to parse multipart data",o)}}function de(e,t,r,o){let n={type:t,message:r,error:o};e.state._bodyError=n}async function $e(e){return new Promise((t,r)=>{let o=[];e.on("data",n=>{o.push(Buffer.isBuffer(n)?n:Buffer.from(n))}),e.on("end",()=>{t(Buffer.concat(o).toString("utf8"))}),e.on("error",n=>{r(n)})})}x();v();var $=class extends h{constructor(t,r=void 0,o=void 0){super("NOT_FOUND",t,404,o??R(),r)}};x();v();W();function uo(e){return e instanceof h}function xt(e){if(uo(e))return{type:e.type,title:e.title,status:e.status,correlationId:e.correlationId,timestamp:e.timestamp.toISOString(),details:e.details};let t=De(),r;e instanceof Error?r=e.message:e==null?r="Unknown error occurred":r=String(e);let o=new D("Internal Server Error",{originalMessage:r},t);return{type:o.type,title:o.title,status:o.status,correlationId:o.correlationId,timestamp:o.timestamp.toISOString(),details:o.details}}function bt(e){return e("x-correlation-id")??De()}function Pt(e,t){e("x-correlation-id",t)}function vt(e={}){let{debug:t=!1}=e;return{name:"ErrorBoundary",execute:async(o,n)=>{try{await n()}catch(i){if(o.response.sent){t&&console.error("Error occurred after response was sent:",i);return}t&&console.error("Error boundary caught error:",i);let s=bt(o.request.header),a=xt(i);a.correlationId=s,Pt(o.response.header,s),o.response.status(a.status).json(a)}},debug:t}}function Ct(e){return async(t,r)=>{try{let o=await Tt(t,r,{parseBody:!0}),i=[vt(),...e.middleware],s=A(i);await st(o,async()=>{await s(o,async()=>{if(!o.response.sent&&(await e.router.handleRequest(o),!o.response.sent))throw new $(`Route not found: ${o.request.method} ${o.request.path}`)})})}catch(o){console.error("Error creating context:",o),r.writeHead(500,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:"Internal Server Error",message:"Failed to process request"}))}}}async function lo(e){if(!e.enabled)return{};let{keyFile:t,certFile:r}=e,o=process.env.NODE_ENV==="development",n=!t||!r;if(n&&o)return await nt();if(n)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 co(e,t){if(!e)return Ft.createServer();let r={allowHTTP1:!0};try{t.keyFile&&(r.key=Ne.readFileSync(t.keyFile)),t.certFile&&(r.cert=Ne.readFileSync(t.certFile))}catch(o){throw new Error(`Failed to read certificate files: ${o instanceof Error?o.message:String(o)}`)}return Mt.createSecureServer(r)}function po(e,t,r,o){return new Promise((n,i)=>{e.listen(t,r,()=>{let a=`${o?"https":"http"}://${r}:${t}`;console.log(`
|
|
26
|
+
`);if(t===-1)return e;let r=e.buffer.subarray(0,t).toString("utf8"),n=e.buffer.subarray(t+4),o=Bt(r);if(!o){let{ValidationError:a}=await Promise.resolve().then(()=>(I(),W));throw new a("Missing or invalid Content-Disposition header")}let i=$t(r),s=o.filename!==void 0;if(s&&e.fileCount>=e.options.maxFiles){let{PayloadTooLargeError:a}=await Promise.resolve().then(()=>(Oe(),Qe));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(()=>(Fe(),Ge));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 _n(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 Mn(i,r)),n&&(i=await An(i),i={...i,stage:"boundary",hasProcessedAnyPart:!0}),i}async function Mn(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(()=>(Oe(),Qe)),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?On(e,t,r):{...e,currentContentLength:r,currentBufferChunks:[...e.currentBufferChunks,t]}}async function On(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 Nn(e.currentWriteStream,t),{...e,currentContentLength:r};default:{let{ValidationError:n}=await Promise.resolve().then(()=>(I(),W));throw new n("Invalid parsing strategy")}}}async function Fn(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,Vt.join)(e.options.tempDir,`upload-${qt.randomUUID()}`),r=(0,Lt.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(),W));throw new t("Invalid file processing strategy")}}}async function An(e){return e.currentField?e.currentFilename!==void 0?kn(e):In(e):re(e)}async function kn(e){if(!e.currentField||e.currentFilename===void 0)return re(e);let t,r,n;switch(e.options.strategy){case"memory":r=Buffer.concat(e.currentBufferChunks),t=Ze.Readable.from(r);break;case"stream":e.streamController&&e.streamController.close(),t=e.currentStream;break;case"temp":e.currentWriteStream&&await Qt(e.currentWriteStream),n=e.currentTempPath,t=Ze.Readable.from(Buffer.alloc(0));break;default:{let{ValidationError:s}=await Promise.resolve().then(()=>(I(),W));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=Wt(e.files,e.currentField,o);return{...re(e),files:i}}function In(e){if(!e.currentField)return re(e);let t=Buffer.concat(e.currentBufferChunks).toString("utf8"),r=Wt(e.fields,e.currentField,t);return{...re(e),fields:r}}function re(e){return{...e,currentField:null,currentFilename:void 0,currentContentLength:0,currentBufferChunks:[],currentStream:null,streamController:null,currentTempPath:null,currentWriteStream:null}}function Wt(e,t,r){let n=new Map(e),o=n.get(t)||[];return n.set(t,[...o,r]),n}async function Dn(e){if(!e.hasFoundValidBoundary){let{ValidationError:n}=await Promise.resolve().then(()=>(I(),W));throw new n("No valid multipart boundary found")}if(e.hasFoundValidBoundary&&!e.hasProcessedAnyPart){let{ValidationError:n}=await Promise.resolve().then(()=>(I(),W));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 zn(e){await Promise.allSettled(e.cleanupTasks.map(t=>t())),e.streamController&&e.streamController.close(),e.currentWriteStream&&await Qt(e.currentWriteStream)}async function Nn(e,t){return new Promise((r,n)=>{e.write(t,o=>{o?n(o):r()})})}async function Qt(e){return new Promise(t=>{e.end(()=>t())})}async function Gt(e,t={}){let r=e.headers["content-type"]||"",n=Nt(r);if(!n){let{UnsupportedMediaTypeError:i}=await Promise.resolve().then(()=>(Fe(),Ge));throw new i("Missing boundary in multipart content-type",{receivedContentType:r,expectedFormat:"multipart/form-data; boundary=..."})}let o=Tn(n,t);o.currentFilename!==void 0&&(o=await Fn(o));try{for await(let i of e)o=await Rn(o,i);return Dn(o)}finally{await zn(o)}}var ne="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 Bn(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,u)=>{a[u]!==void 0?Array.isArray(a[u])?a[u].push(c):a[u]=[a[u],c]:a[u]=c}),{path:s,url:i,query:a}}catch(i){throw console.warn(`Invalid URL: ${o}`,i),new Me(`Invalid URL: ${o}`)}}function $n(e){return"stream"in e||"httpVersionMajor"in e&&e.httpVersionMajor===2}function Hn(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 Zt(e,t,r={}){let{path:n,url:o,query:i}=Bn(e),s=e.method||"GET",a=$n(e),c=Hn(e),u={},p={...r.initialState||{}},h={...r.initialServices||{}},w={sent:!1},E={request:Un(e,{path:n,url:o,query:i,params:u,method:s,isHttp2:a,protocol:c}),response:{},state:p,services:h};return E.response=Ln(t,w,E),r.parseBody&&await Xn(e,E,r),E}function Un(e,t){return{raw:e,...t,header:Jt(e),headers:qn(e),body:void 0}}function Jt(e){return t=>{let r=e.headers[t.toLowerCase()];return Array.isArray(r)?r.join(", "):r||void 0}}function qn(e){let t=Jt(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 oe(e,t){if(t.correlationId){let r=j(),n=String(t.correlationId);e.setHeader(r,n)}}function Ln(e,t,r){return{raw:e,get statusCode(){return e.statusCode||200},get sent(){return t.sent},status:jn(e,t,r),header:Vn(e,t,r),headers:Wn(e,t,r),type:Qn(e,t,r),json:Gn(e,t,r.state),text:Zn(e,t,r.state),html:Jn(e,t,r.state),redirect:Yn(e,t,r.state),stream:Kn(e,t,r.state)}}function jn(e,t,r){return function(o){if(t.sent)throw new F;return e.statusCode=o,r.response}}function Vn(e,t,r){return function(o,i){if(t.sent)throw new K;return e.setHeader(o,i),r.response}}function Wn(e,t,r){return function(o){if(t.sent)throw new K;for(let[i,s]of Object.entries(o))e.setHeader(i,s);return r.response}}function Qn(e,t,r){return function(o){if(t.sent)throw new _e;return e.setHeader(ne,o),r.response}}function Gn(e,t,r){return function(o,i){if(t.sent)throw new F;i!==void 0&&(e.statusCode=i),oe(e,r),e.setHeader(ne,"application/json"),e.end(JSON.stringify(o)),t.sent=!0}}function Zn(e,t,r){return function(o,i){if(t.sent)throw new F;i!==void 0&&(e.statusCode=i),oe(e,r),e.setHeader(ne,"text/plain"),e.end(o),t.sent=!0}}function Jn(e,t,r){return function(o,i){if(t.sent)throw new F;i!==void 0&&(e.statusCode=i),oe(e,r),e.setHeader(ne,"text/html"),e.end(o),t.sent=!0}}function Yn(e,t,r){return function(o,i=302){if(t.sent)throw new F;oe(e,r),e.statusCode=i,e.setHeader("Location",o),e.end(),t.sent=!0}}function Kn(e,t,r){return function(o,i={}){if(t.sent)throw new F;if(i.status!==void 0&&(e.statusCode=i.status),oe(e,r),i.contentType&&e.setHeader(ne,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 Xn(e,t,r={}){if(eo(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 to(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 ro(e,t)}else if(n.includes("text/")){if(o>i.text)throw new Error(`Text body too large: ${o} > ${i.text} bytes`);await oo(e,t)}else if(Ht(n))await io(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";Ae(t,a,"Error reading request body",s)}}function eo(e){return["GET","HEAD","OPTIONS"].includes(e||"GET")}async function to(e,t){let r=await Je(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,Ae(t,"json_parse_error","Invalid JSON in request body",n)}}async function ro(e,t){let r=await Je(e);if(r)try{t.request.body=no(r)}catch(n){t.request.body=null,Ae(t,"form_parse_error","Invalid form data in request body",n)}}function no(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 oo(e,t){let r=await Je(e);r&&(t.request.body=r)}async function io(e,t,r){try{let n=r||B.multipart,o=await Gt(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,Ae(t,"multipart_parse_error","Failed to parse multipart data",n)}}function Ae(e,t,r,n){let o={type:t,message:r,error:n};e.state._bodyError=o}async function Je(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)})})}C();T();var H=class extends x{constructor(t,r=void 0,n=void 0){super("NOT_FOUND",t,404,n??S(),r)}};C();T();var G=class extends x{constructor(t,r=void 0,n=void 0){super("FORBIDDEN",t,403,n??S(),r)}};var so={origin:!0,methods:["GET","HEAD","PUT","PATCH","POST","DELETE"],credentials:!1,optionsSuccessStatus:204},ao={origin:!1,methods:["GET","HEAD"],credentials:!1,optionsSuccessStatus:204};function Yt(e){return e===void 0&&(e=process.env.NODE_ENV!=="production"),e?{...so}:{...ao}}function co(e=6e4,t=1e3){let r=new Map,n={ttl:e,maxSize:t},o=(h,w,E)=>`${h}:${w}:${E||"anonymous"}`,i=()=>{if(r.size===0)return;let h=null,w=1/0;for(let[E,l]of r.entries())l.lastAccessed<w&&(w=l.lastAccessed,h=E);h&&r.delete(h)};return{get:(h,w,E)=>{let l=o(h,w,E),f=r.get(l);if(!f)return null;let g=Date.now();return g>f.expiresAt?(r.delete(l),null):(f.lastAccessed=g,f.allowed)},set:(h,w,E,l)=>{let f=o(h,E,l),g=Date.now();if(r.has(f)){r.set(f,{allowed:w,expiresAt:g+n.ttl,lastAccessed:g});return}r.size>=n.maxSize&&i(),r.set(f,{allowed:w,expiresAt:g+n.ttl,lastAccessed:g})},clear:()=>{r.clear()},cleanExpired:()=>{let h=Date.now(),w=0;for(let[E,l]of r.entries())h>l.expiresAt&&(r.delete(E),w++);return w},getStats:()=>({size:r.size,maxSize:n.maxSize,ttl:n.ttl})}}var Kt=co();function lo(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 uo(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 po(e,t){return t==="*"?!0:e===t}async function fo(e,t){return t.test(e)}async function mo(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 Xt(e,t,r){let n=t.map(i=>Ye(e,i,r));return(await Promise.all(n)).some(i=>i===!0)}async function Ye(e,t,r){return typeof t=="string"?po(e,t):t instanceof RegExp?fo(e,t):typeof t=="function"?mo(e,t,r):(console.warn("Unknown CORS origin type:",typeof t),!1)}async function ie(e,t,r){if(t===!0)return!0;if(t===!1)return!1;if(lo(t)){let o=r?.state?.user?.id||r?.state?.userId,i=uo(t),s=Kt.get(e,i,o);if(s!==null)return s;let a;return Array.isArray(t)?a=await Xt(e,t,r):a=await Ye(e,t,r),Kt.set(e,a,i,o),a}else return Array.isArray(t)?Xt(e,t,r):Ye(e,t,r)}I();function go(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 Ke(e){return e.toUpperCase()}function ho(e,t){return t?(typeof t=="string"?t.split(",").map(n=>n.trim()):t).map(n=>Ke(n)).includes(Ke(e)):["GET","HEAD","PUT","PATCH","POST","DELETE"].includes(Ke(e))}function yo(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 So(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 er(e,t){let r=go(e);if(!r.origin||!r.requestedMethod)throw e.response.status(403),new O("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 ie(r.origin,t.origin||!1,e);if(!n)throw e.response.status(403),new O("CORS origin not allowed",{fields:[{field:"Origin",messages:[`Origin '${r.origin}' is not allowed`],rejectedValue:r.origin}],errorCount:1,section:"body"});if(!ho(r.requestedMethod,t.methods))throw e.response.status(403),new O("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(!yo(r.requestedHeaders,t.allowedHeaders)){let i=r.requestedHeaders?.filter(s=>{let a=t.allowedHeaders;return a?!(typeof a=="string"?a.split(",").map(u=>u.trim().toLowerCase()):a.map(u=>u.toLowerCase())).includes(s.toLowerCase()):!1});throw e.response.status(403),new O("CORS headers not allowed",{fields:[{field:"Access-Control-Request-Headers",messages:[`Headers not allowed: ${i?.join(", ")}`],rejectedValue:i}],errorCount:1,section:"body"})}So(e,t,r.origin,n);let o=t.optionsSuccessStatus||204;e.response.status(o),t.preflightContinue||e.response.text("")}function Xe(e){return e.request.method==="OPTIONS"&&!!(e.request.header("access-control-request-method")||e.request.header("Access-Control-Request-Method"))}var v=require("zod"),wo=v.z.enum(["GET","POST","PUT","DELETE","PATCH","HEAD","OPTIONS","CONNECT","TRACE"]),xo=v.z.union([v.z.array(wo),v.z.string().transform(e=>e.split(",").map(t=>t.trim()))]).optional(),tr=v.z.union([v.z.array(v.z.string()),v.z.string().transform(e=>e.split(",").map(t=>t.trim()))]).optional(),Eo=v.z.custom(e=>typeof e=="function"&&e.length<=2,{message:"Origin validator must be a function accepting (origin, ctx?) parameters"}),rr=v.z.union([v.z.string(),v.z.instanceof(RegExp),Eo]),vo=v.z.union([v.z.boolean(),rr,v.z.array(rr)]),nr=v.z.object({origin:vo.optional(),methods:xo,allowedHeaders:tr,exposedHeaders:tr,credentials:v.z.boolean().optional(),maxAge:v.z.number().int().optional(),preflightContinue:v.z.boolean().optional(),optionsSuccessStatus:v.z.number().int().min(200).max(299).optional()}).strict(),or=v.z.union([v.z.boolean(),nr]).optional();function ir(e){try{return typeof e=="boolean"?e===!1?{origin:!1}:{origin:!0}:nr.parse(e)}catch(t){if(t instanceof v.z.ZodError){let r=To(t);throw new Error(`Invalid CORS options:
|
|
27
|
+
${r}`)}throw new Error(`Invalid CORS options: ${String(t)}`)}}function To(e){return e.errors.map(r=>` - ${r.path.join(".")||"root"}: ${r.message}`).join(`
|
|
28
|
+
`)}function Ro(e){return Array.isArray(e)}function sr(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(Ro(e.origin)&&e.origin.some(r=>r==="*"))throw new Error("CORS security violation: Cannot include wildcard origin (*) in array when credentials are enabled.")}}function ar(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 bo(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 cr(e){let t=process.env.NODE_ENV==="development",r=Yt(t),n=ar(e,r),o=ir(n);return sr(o),$({name:"cors",handler:async(i,s)=>{let a=i.request.header("origin")||i.request.header("Origin");if(Xe(i)){if(await er(i,o),!o.preflightContinue)return}else{if(!a){await s();return}let c=await ie(a,o.origin||!1,i);if(!c)throw i.response.status(403),new G("CORS validation failed",{reason:"origin_not_allowed",origin:a,allowedOrigins:o.origin});bo(i,o,a,c)}await s()},debug:process.env.DEBUG?.includes("cors")})}C();X();T();function Co(e){return e instanceof x}function lr(e){if(Co(e))return{type:e.type,title:e.title,status:e.status,correlationId:e.correlationId,timestamp:e.timestamp.toISOString(),details:e.details};let t=S(),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 ur(e){let t=j(),r={[t]:e(t)};return ye(r)}function dr(e,t){let r=j();e(r,t)}function pr(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=ur(n.request.header),a=lr(i);a.correlationId=s,dr(n.response.header,s),n.response.status(a.status).json(a)}},debug:t}}T();function fr(e){return async(t,r)=>{let n=ye(t.headers);try{await Pt(n,async()=>{let o=await Zt(t,r,{parseBody:!0,initialState:{correlationId:n}}),s=[pr()];"corsOptions"in e&&e.corsOptions!==!1&&s.push(cr(e.corsOptions)),s.push(...e.middleware);let a=L(s);await zt(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 Po(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 It();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 _o(e,t){if(!e)return mr.createServer();let r={allowHTTP1:!0};try{t.keyFile&&(r.key=et.readFileSync(t.keyFile)),t.certFile&&(r.cert=et.readFileSync(t.certFile))}catch(n){throw new Error(`Failed to read certificate files: ${n instanceof Error?n.message:String(n)}`)}return gr.createSecureServer(r)}function Mo(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
|
-
`),n()}),e.on("error",s=>{console.error("Server error:",s),i(s)})})}async function fo(e){for(let t of e.plugins)typeof t.initialize=="function"&&await t.initialize(e)}async function Ot(e,t){if(!e.server)try{let r=t.port,o=t.host;await fo(e);let n=t.http2||{enabled:!0},i=!!n.enabled,s=await lo(n);t.http2&&s.keyFile&&s.certFile&&(t.http2.keyFile=s.keyFile,t.http2.certFile=s.certFile);let a=co(i,s);e.server=a,e.port=r,e.host=o;let u=Ct(e);a.on("request",u),await po(a,r,o,i)}catch(r){throw console.error("Failed to start server:",r),r}}var pe=!1;async function Dt(e,t={}){let r=e.server,o=e.events;if(pe){console.log("\u26A0\uFE0F Shutdown already in progress, ignoring duplicate shutdown request");return}if(!r)return;pe=!0;let n=t.timeout||5e3;try{if(t.onStopping&&await t.onStopping(),o.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(c=>{if(c)return u(c);a()})}),s=new Promise((a,u)=>{setTimeout(()=>{u(new Error("Server shutdown timeout"))},n)});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(),o.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)),o.emit("error",i),i}}function kt(e){if(process.env.NODE_ENV==="development"){let r=()=>{console.log("\u{1F4E4} SIGINT received, forcing exit for development restart..."),process.exit(0)},o=()=>{console.log("\u{1F4E4} SIGTERM received, forcing exit for development restart..."),process.exit(0)};return process.on("SIGINT",r),process.on("SIGTERM",o),{unregister:()=>{process.removeListener("SIGINT",r),process.removeListener("SIGTERM",o)}}}else{let r=()=>{console.log("\u{1F4E4} SIGINT received, starting graceful shutdown..."),e().catch(console.error)},o=()=>{console.log("\u{1F4E4} SIGTERM received, starting graceful shutdown..."),e().catch(console.error)};return process.on("SIGINT",r),process.on("SIGTERM",o),{unregister:()=>{process.removeListener("SIGINT",r),process.removeListener("SIGTERM",o)}}}}var b=require("zod"),mo=b.z.custom(e=>e!==null&&typeof e=="object"&&"execute"in e&&typeof e.execute=="function",{message:"Expected middleware to have an execute function"}),go=b.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"}),yo=b.z.object({enabled:b.z.boolean().optional().default(!0),keyFile:b.z.string().optional(),certFile:b.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"}),ho=b.z.object({port:b.z.number().int().positive().optional().default(3e3),host:b.z.string().optional().default("localhost"),routesDir:b.z.string().optional().default("./routes"),http2:yo.optional().default({enabled:!0}),middleware:b.z.array(mo).optional().default([]),plugins:b.z.array(go).optional().default([])});function zt(e){try{return ho.parse(e)}catch(t){if(t instanceof b.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 Bt(e={}){let{continueOnError:t=!0,debug:r=!1,onError:o}=e;function n(s,...a){r&&console.log(`[PluginLifecycle] ${s}`,...a)}function i(s,a,u){let c=`Plugin ${s.name} failed during ${a}: ${u.message}`;if(o?o(s,a,u):console.error(c,u),!t)throw new Error(c)}return{async initializePlugins(s){n("Initializing plugins...");for(let a of s.plugins)if(a.initialize)try{n(`Initializing plugin: ${a.name}`),await a.initialize(s)}catch(u){i(a,"initialize",u)}n(`Initialized ${s.plugins.length} plugins`)},async terminatePlugins(s){n("Terminating plugins...");let a=[...s.plugins].reverse();for(let u of a)if(u.terminate)try{n(`Terminating plugin: ${u.name}`),await u.terminate(s)}catch(c){i(u,"terminate",c)}n(`Terminated ${a.length} plugins`)},async onServerStart(s,a){n("Notifying plugins of server start...");for(let u of s.plugins)if(u.onServerStart)try{n(`Notifying plugin of server start: ${u.name}`),await u.onServerStart(a)}catch(c){i(u,"onServerStart",c)}},async onServerStop(s,a){n("Notifying plugins of server stop...");let u=[...s.plugins].reverse();for(let c of u)if(c.onServerStop)try{n(`Notifying plugin of server stop: ${c.name}`),await c.onServerStop(a)}catch(S){i(c,"onServerStop",S)}}}}var F=class extends Error{constructor(r,o){super(`Plugin validation error${r?` for "${r}"`:""}: ${o}`);this.pluginName=r;this.name="PluginValidationError"}};var wo=new Set(["core","server","router","middleware","context","blaize","blaizejs"]),Ro=/^[a-z]([a-z0-9-]*[a-z0-9])?$/,So=/^\d+\.\d+\.\d+(?:-[a-zA-Z0-9-.]+)?(?:\+[a-zA-Z0-9-.]+)?$/;function $t(e,t={}){let{requireVersion:r=!0,validateNameFormat:o=!0,checkReservedNames:n=!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(o&&!Ro.test(i.name))throw new F(i.name,"Plugin name must be lowercase letters, numbers, and hyphens only");if(n&&wo.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(!So.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 It=T(require("crypto"),1),_t=T(require("fs/promises"),1),At=require("module"),Ut=T(require("path"),1);async function To(e){let t=`?t=${Date.now()}`,r=e+t;try{let o=await import(r);return console.log("\u2705 Successfully imported module"),o}catch(o){let n=o instanceof Error?o.message:String(o);return console.log("\u26A0\uFE0F Error importing with cache buster, trying original path:",n),import(e)}}async function Nt(e,t){try{let r=ie(e,t),o=await To(e);console.log("\u{1F4E6} Module exports:",Object.keys(o));let n=[];if(o.default&&typeof o.default=="object"){let i={...o.default,path:r.routePath};n.push(i)}return Object.entries(o).forEach(([i,s])=>{if(i==="default"||!s||typeof s!="object")return;let a=s;if(Eo(a)){let u={...a,path:r.routePath};n.push(u)}}),n.length===0?(console.warn(`Route file ${e} does not export any valid route definitions`),[]):(console.log(`\u2705 Successfully Loaded ${n.length} route(s)`),n)}catch(r){return console.error(`Failed to load route module ${e}:`,r),[]}}function Eo(e){return!e||typeof e!="object"?!1:["GET","POST","PUT","DELETE","PATCH","HEAD","OPTIONS"].some(o=>e[o]&&typeof e[o]=="object"&&e[o].handler)}var bo={},K=new Map;async function X(e,t,r=!0){let n=(await _t.stat(e)).mtime.getTime(),i=K.get(e);if(r&&i&&i.timestamp===n)return i.routes;xo(e);let s=await Nt(e,t);if(r){let a=Ht(s);K.set(e,{routes:s,timestamp:n,hash:a})}return s}function Lt(e,t){let r=K.get(e);if(!r)return!0;let o=Ht(t);return r.hash!==o}function Ie(e){e?K.delete(e):K.clear()}function Ht(e){let t=e.map(n=>({path:n.path,methods:Object.keys(n).filter(i=>i!=="path").sort().map(i=>{let s=n[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 It.createHash("md5").update(r).digest("hex")}function xo(e){try{let t=Ut.resolve(e);if(typeof require<"u"){delete require.cache[t];try{let r=require.resolve(t);delete require.cache[r]}catch(r){let o=r instanceof Error?r.message:String(r);console.log(`\u26A0\uFE0F Could not resolve path: ${o}`)}}else try{let r=(0,At.createRequire)(bo.url);delete r.cache[t];try{let o=r.resolve(t);delete r.cache[o]}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 qt=T(require("os"),1);var fe=T(require("fs/promises"),1),j=T(require("path"),1);async function me(e,t={}){let r=j.isAbsolute(e)?e:j.resolve(process.cwd(),e);console.log("Creating router with routes directory:",r);try{if(!(await fe.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 o=[],n=t.ignore||["node_modules",".git"];async function i(s){let a=await fe.readdir(s,{withFileTypes:!0});for(let u of a){let c=j.join(s,u.name);u.isDirectory()&&n.includes(u.name)||(u.isDirectory()?await i(c):Po(u.name)&&o.push(c))}}return await i(r),o}function Po(e){return!e.startsWith("_")&&(e.endsWith(".ts")||e.endsWith(".js"))}async function vo(e,t,r=Math.max(1,Math.floor(qt.cpus().length/2))){let o=Co(e,r),n=[];for(let i of o){let a=(await Promise.allSettled(i.map(u=>t(u)))).filter(u=>u.status==="fulfilled").map(u=>u.value);n.push(...a)}return n}async function jt(e){let t=await me(e);return(await vo(t,o=>X(o,e))).flat()}function Co(e,t){let r=[];for(let o=0;o<e.length;o+=t)r.push(e.slice(o,o+t));return r}var N={fileChanges:0,totalReloadTime:0,averageReloadTime:0,slowReloads:[]};function Qt(e,t){let r=Date.now()-t;if(N.fileChanges++,N.totalReloadTime+=r,N.averageReloadTime=N.totalReloadTime/N.fileChanges,r>100&&(N.slowReloads.push({file:e,time:r}),N.slowReloads.length>10&&N.slowReloads.shift()),process.env.NODE_ENV==="development"){let o=r<50?"\u26A1":r<100?"\u{1F504}":"\u{1F40C}";console.log(`${o} Route reload: ${e} (${r}ms)`)}}function _e(e,t){return console.log(`Tracking performance for: ${t}`),async(...r)=>{let o=Date.now();try{let n=await e(...r);return Qt(t,o),n}catch(n){throw Qt(t,o),n}}}var Ae=T(require("path"),1),Vt=require("chokidar");function Ue(e,t={}){let r=t.debounceMs||16,o=new Map;function n(p,g){return(...y)=>{let l=o.get(g);l&&clearTimeout(l);let d=setTimeout(()=>{p(...y),o.delete(g)},r);o.set(g,d)}}let i=new Map;async function s(){try{let p=await me(e,{ignore:t.ignore});for(let g of p)await a(g)}catch(p){c(p)}}async function a(p){try{let g=i.get(p),y=await X(p,e,!1);if(!y||y.length===0||g&&!Lt(p,y))return;await X(p,e,!0);let l=Ae.normalize(p);g?(i.set(p,y),t.onRouteChanged&&t.onRouteChanged(l,y)):(i.set(p,y),t.onRouteAdded&&t.onRouteAdded(l,y))}catch(g){console.log(`\u26A0\uFE0F Error processing file ${p}:`,g),c(g)}}function u(p){let g=Ae.normalize(p),y=i.get(g);y&&y.length>0&&t.onRouteRemoved&&t.onRouteRemoved(g,y),i.delete(g)}function c(p){t.onError&&p instanceof Error?t.onError(p):console.error("\u26A0\uFE0F Route watcher error:",p)}let S=(0,Vt.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 S.on("add",p=>{n(a,p)(p)}).on("change",p=>{n(a,p)(p)}).on("unlink",p=>{n(u,p)(p)}).on("error",c),s().catch(c),{close:()=>(o.forEach(p=>clearTimeout(p)),o.clear(),S.close()),getRoutes:()=>{let p=[];for(let g of i.values())p.push(...g);return p},getRoutesByFile:()=>new Map(i)}}var Yt=require("zod");var Wt=require("zod");function Le(e,t){return t instanceof Wt.z.ZodObject?t.strict().parse(e):t.parse(e)}var Gt=require("zod");function He(e,t){return t instanceof Gt.z.ZodObject?t.strict().parse(e):t.parse(e)}var Zt=require("zod");function qe(e,t){return t instanceof Zt.z.ZodObject?t.strict().parse(e):t.parse(e)}var Jt=require("zod");function je(e,t){return t instanceof Jt.z.ZodObject?t.strict().parse(e):t.parse(e)}W();z();function Qe(e,t=!1){return{name:"RequestValidator",execute:async(o,n)=>{if(e.params&&o.request.params)try{o.request.params=He(o.request.params,e.params)}catch(i){let s=ge(i),a=s.reduce((u,c)=>u+c.messages.length,0);throw new k("Request validation failed",{fields:s,errorCount:a,section:"params"})}if(e.query&&o.request.query)try{o.request.query=qe(o.request.query,e.query)}catch(i){let s=ge(i),a=s.reduce((u,c)=>u+c.messages.length,0);throw new k("Request validation failed",{fields:s,errorCount:a,section:"query"})}if(e.body)try{o.request.body=Le(o.request.body,e.body)}catch(i){let s=ge(i),a=s.reduce((u,c)=>u+c.messages.length,0);throw new k("Request validation failed",{fields:s,errorCount:a,section:"body"})}await n()},debug:t}}function Ve(e,t=!1){return{name:"ResponseValidator",execute:async(o,n)=>{let i=o.response.json;o.response.json=(s,a)=>{try{let u=je(s,e);return o.response.json=i,i.call(o.response,u,a)}catch(u){throw o.response.json=i,new D("Response validation failed",{responseSchema:e.description||"Unknown schema",validationError:ge(u),originalResponse:s})}},await n()},debug:t}}function ge(e){if(e instanceof Yt.z.ZodError){let t=new Map;for(let r of e.issues){let o=r.path.length>0?r.path.join("."):"root";t.has(o)||t.set(o,[]),t.get(o).push(r.message)}return Array.from(t.entries()).map(([r,o])=>({field:r,messages:o}))}return e instanceof Error?[{field:"unknown",messages:[e.message]}]:[{field:"unknown",messages:[String(e)]}]}async function We(e,t,r){let o=[...t.middleware||[]];t.schema&&((t.schema.params||t.schema.query||t.schema.body)&&o.unshift(Qe(t.schema)),t.schema.response&&o.push(Ve(t.schema.response))),await A([...o])(e,async()=>{let i=await t.handler(e,r);!e.response.sent&&i!==void 0&&e.response.json(i)})}function ye(e,t,r){let o=t.exec(e);if(!o)return{};let n={};for(let i=0;i<r.length;i++)n[r[i]]=o[i+1]||"";return n}function Ge(e){let t=[];if(e==="/")return{pattern:/^\/$/,paramNames:[]};let r=e.replace(/([.+*?^$(){}|\\])/g,"\\$1");return r=r.replace(/\/:([^/]+)/g,(n,i)=>(t.push(i),"/([^/]+)")).replace(/\/\[([^\]]+)\]/g,(n,i)=>(t.push(i),"/([^/]+)")),r=`${r}(?:/)?`,{pattern:new RegExp(`^${r}$`),paramNames:t}}function Ze(){let e=[];return{add(t,r,o){let{pattern:n,paramNames:i}=Ge(t),s={path:t,method:r,pattern:n,paramNames:i,routeOptions:o},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 o=t.split("?")[0];if(!o)return null;for(let i of e){if(i.method!==r)continue;if(i.pattern.exec(o)){let a=ye(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:ye(t,r.pattern,r.paramNames)}))}}}function Kt(){return{routesByPath:new Map,routesByFile:new Map,pathToFile:new Map}}function I(e,t,r){console.log(`Updating routes from file: ${t}`);let o=e.routesByFile.get(t)||new Set,n=new Set(r.map(c=>c.path)),i=r.filter(c=>!o.has(c.path)),s=Array.from(o).filter(c=>!n.has(c)),u=r.filter(c=>o.has(c.path)).filter(c=>{let S=e.routesByPath.get(c.path);return!S||!Mo(S,c)});return Fo(e,t,{added:i,removed:s,changed:u}),{added:i,removed:s,changed:u}}function Xt(e){return Array.from(e.routesByPath.values())}function Fo(e,t,r){let{added:o,removed:n,changed:i}=r;n.forEach(a=>{e.routesByPath.delete(a),e.pathToFile.delete(a)}),[...o,...i].forEach(a=>{e.routesByPath.set(a.path,a),e.pathToFile.set(a.path,t)});let s=new Set([...o.map(a=>a.path),...i.map(a=>a.path),...Array.from(e.routesByFile.get(t)||[]).filter(a=>!n.includes(a))]);s.size>0?e.routesByFile.set(t,s):e.routesByFile.delete(t)}function Mo(e,t){if(e.path!==t.path)return!1;let r=Object.keys(e).filter(n=>n!=="path").sort(),o=Object.keys(t).filter(n=>n!=="path").sort();return r.length!==o.length?!1:r.every(n=>{let i=e[n],s=t[n];return typeof i==typeof s})}function Je(e,t){Object.entries(e).forEach(([r,o])=>{r==="path"||!o||t.add(e.path,r,o)})}function ee(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 er(e,t){ee(e.path,t),Je(e,t)}var Oo={routesDir:"./routes",basePath:"/",watchMode:process.env.NODE_ENV==="development"};function tr(e){let t={...Oo,...e};e.basePath&&!e.basePath.startsWith("/")&&console.warn("Base path does nothing");let r=Kt(),o=Ze(),n=!1,i=null,s=null,a=new Set([t.routesDir]);function u(l){console.log(`
|
|
28
|
-
\u{1F527} APPLYING MATCHER CHANGES:`),console.log(` Adding ${l.added.length} routes`),console.log(` Removing ${l.removed.length} routes`),console.log(` Updating ${l.changed.length} routes`),l.removed.forEach(
|
|
29
|
-
`)}function
|
|
30
|
-
\u{1F4E5} Handling request: ${
|
|
40
|
+
`),o()}),e.on("error",s=>{console.error("Server error:",s),i(s)})})}async function Oo(e){for(let t of e.plugins)typeof t.initialize=="function"&&await t.initialize(e)}async function hr(e,t){if(!e.server)try{let r=t.port,n=t.host;await Oo(e);let o=t.http2||{enabled:!0},i=!!o.enabled,s=await Po(o);t.http2&&s.keyFile&&s.certFile&&(t.http2.keyFile=s.keyFile,t.http2.certFile=s.certFile);let a=_o(i,s);e.server=a,e.port=r,e.host=n;let c=fr(e);a.on("request",c),await Mo(a,r,n,i)}catch(r){throw console.error("Failed to start server:",r),r}}var ke=!1;async function yr(e,t={}){let r=e.server,n=e.events;if(ke){console.log("\u26A0\uFE0F Shutdown already in progress, ignoring duplicate shutdown request");return}if(!r)return;ke=!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(u=>{if(u)return c(u);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"),ke=!1}catch(i){throw ke=!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 Sr(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 R=require("zod");var Fo=R.z.custom(e=>e!==null&&typeof e=="object"&&"execute"in e&&typeof e.execute=="function",{message:"Expected middleware to have an execute function"}),Ao=R.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"}),ko=R.z.object({enabled:R.z.boolean().optional().default(!0),keyFile:R.z.string().optional(),certFile:R.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"}),Io=R.z.object({headerName:R.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:R.z.function().args().returns(R.z.string()).optional()}).optional(),Do=R.z.object({port:R.z.number().int().positive().optional().default(3e3),host:R.z.string().optional().default("localhost"),routesDir:R.z.string().optional().default("./routes"),http2:ko.optional().default({enabled:!0}),middleware:R.z.array(Fo).optional().default([]),plugins:R.z.array(Ao).optional().default([]),correlation:Io,cors:or});function wr(e){try{return Do.parse(e)}catch(t){if(t instanceof R.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 xr(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 u=`Plugin ${s.name} failed during ${a}: ${c.message}`;if(n?n(s,a,c):console.error(u,c),!t)throw new Error(u)}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(u){i(c,"terminate",u)}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(u){i(c,"onServerStart",u)}},async onServerStop(s,a){o("Notifying plugins of server stop...");let c=[...s.plugins].reverse();for(let u of c)if(u.onServerStop)try{o(`Notifying plugin of server stop: ${u.name}`),await u.onServerStop(a)}catch(p){i(u,"onServerStop",p)}}}}var A=class extends Error{constructor(r,n){super(`Plugin validation error${r?` for "${r}"`:""}: ${n}`);this.pluginName=r;this.name="PluginValidationError"}};var zo=new Set(["core","server","router","middleware","context","blaize","blaizejs"]),No=/^[a-z]([a-z0-9-]*[a-z0-9])?$/,Bo=/^\d+\.\d+\.\d+(?:-[a-zA-Z0-9-.]+)?(?:\+[a-zA-Z0-9-.]+)?$/;function tt(e,t={}){let{requireVersion:r=!0,validateNameFormat:n=!0,checkReservedNames:o=!0}=t;if(!e||typeof e!="object")throw new A("","Plugin must be an object");let i=e;if(!i.name||typeof i.name!="string")throw new A("","Plugin must have a name (string)");if(n&&!No.test(i.name))throw new A(i.name,"Plugin name must be lowercase letters, numbers, and hyphens only");if(o&&zo.has(i.name.toLowerCase()))throw new A(i.name,`Plugin name "${i.name}" is reserved`);if(r){if(!i.version||typeof i.version!="string")throw new A(i.name,"Plugin must have a version (string)");if(!Bo.test(i.version))throw new A(i.name,'Plugin version must follow semantic versioning (e.g., "1.0.0")')}if(!i.register||typeof i.register!="function")throw new A(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 A(i.name,`Plugin ${a} must be a function if provided`)}var vr=P(require("crypto"),1),Tr=P(require("fs/promises"),1);async function $o(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 Er(e,t){try{let r=me(e,t),n=await $o(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(Ho(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 Ho(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 se=new Map;async function ae(e,t,r=!0){let o=(await Tr.stat(e)).mtime.getTime(),i=se.get(e);if(r&&i&&i.timestamp===o)return i.routes;let s=await Er(e,t);if(r){let a=br(s);se.set(e,{routes:s,timestamp:o,hash:a})}return s}function Rr(e,t){let r=se.get(e);if(!r)return!0;let n=br(t);return r.hash!==n}function rt(e){e?se.delete(e):se.clear()}function br(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 vr.createHash("md5").update(r).digest("hex")}var Pr=P(require("os"),1);var Ie=P(require("fs/promises"),1),Z=P(require("path"),1);async function Cr(e,t={}){let r=Z.isAbsolute(e)?e:Z.resolve(process.cwd(),e);console.log("Creating router with routes directory:",r);try{if(!(await Ie.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 Ie.readdir(s,{withFileTypes:!0});for(let c of a){let u=Z.join(s,c.name);c.isDirectory()&&o.includes(c.name)||(c.isDirectory()?await i(u):Uo(c.name)&&n.push(u))}}return await i(r),n}function Uo(e){return!e.startsWith("_")&&(e.endsWith(".ts")||e.endsWith(".js"))}async function qo(e,t,r=Math.max(1,Math.floor(Pr.cpus().length/2))){let n=Lo(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 _r(e){let t=await Cr(e);return(await qo(t,n=>ae(n,e))).flat()}function Lo(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 Mr(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 nt(e,t){return console.log(`Tracking performance for: ${t}`),async(...r)=>{let n=Date.now();try{let o=await e(...r);return Mr(t,n),o}catch(o){throw Mr(t,n),o}}}var ot=P(require("path"),1),Or=require("chokidar");function it(e,t={}){let r=t.debounceMs||16,n=new Map;function o(p,h){return(...w)=>{let E=n.get(h);E&&clearTimeout(E);let l=setTimeout(()=>{p(...w),n.delete(h)},r);n.set(h,l)}}let i=new Map;async function s(p){try{let h=i.get(p),w=await ae(p,e,!1);if(!w||w.length===0||h&&!Rr(p,w))return;await ae(p,e,!0);let E=ot.normalize(p);h?(i.set(p,w),t.onRouteChanged&&t.onRouteChanged(E,w)):(i.set(p,w),t.onRouteAdded&&t.onRouteAdded(E,w))}catch(h){console.log(`\u26A0\uFE0F Error processing file ${p}:`,h),c(h)}}function a(p){let h=ot.normalize(p),w=i.get(h);w&&w.length>0&&t.onRouteRemoved&&t.onRouteRemoved(h,w),i.delete(h)}function c(p){t.onError&&p instanceof Error?t.onError(p):console.error("\u26A0\uFE0F Route watcher error:",p)}let u=(0,Or.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 u.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(),u.close()),getRoutes:()=>{let p=[];for(let h of i.values())p.push(...h);return p},getRoutesByFile:()=>new Map(i)}}var Dr=require("zod");var Fr=require("zod");function st(e,t){return t instanceof Fr.z.ZodObject?t.strict().parse(e):t.parse(e)}var Ar=require("zod");function at(e,t){return t instanceof Ar.z.ZodObject?t.strict().parse(e):t.parse(e)}var kr=require("zod");function ct(e,t){return t instanceof kr.z.ZodObject?t.strict().parse(e):t.parse(e)}var Ir=require("zod");function lt(e,t){return t instanceof Ir.z.ZodObject?t.strict().parse(e):t.parse(e)}X();I();function ut(e,t=!1){return{name:"RequestValidator",execute:async(n,o)=>{if(e.params&&n.request.params)try{n.request.params=at(n.request.params,e.params)}catch(i){let s=De(i),a=s.reduce((c,u)=>c+u.messages.length,0);throw new O("Request validation failed",{fields:s,errorCount:a,section:"params"})}if(e.query&&n.request.query)try{n.request.query=ct(n.request.query,e.query)}catch(i){let s=De(i),a=s.reduce((c,u)=>c+u.messages.length,0);throw new O("Request validation failed",{fields:s,errorCount:a,section:"query"})}if(e.body)try{n.request.body=st(n.request.body,e.body)}catch(i){let s=De(i),a=s.reduce((c,u)=>c+u.messages.length,0);throw new O("Request validation failed",{fields:s,errorCount:a,section:"body"})}await o()},debug:t}}function dt(e,t=!1){return{name:"ResponseValidator",execute:async(n,o)=>{let i=n.response.json;n.response.json=(s,a)=>{try{let c=lt(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:De(c),originalResponse:s})}},await o()},debug:t}}function De(e){if(e instanceof Dr.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 pt(e,t,r){let n=[...t.middleware||[]];t.schema&&((t.schema.params||t.schema.query||t.schema.body)&&n.unshift(ut(t.schema)),t.schema.response&&n.push(dt(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 ze(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 ft(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 mt(){let e=[];return{add(t,r,n){let{pattern:o,paramNames:i}=ft(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=ze(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:ze(t,r.pattern,r.paramNames)}))}}}function zr(){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(u=>u.path)),i=r.filter(u=>!n.has(u.path)),s=Array.from(n).filter(u=>!o.has(u)),c=r.filter(u=>n.has(u.path)).filter(u=>{let p=e.routesByPath.get(u.path);return!p||!Vo(p,u)});return jo(e,t,{added:i,removed:s,changed:c}),{added:i,removed:s,changed:c}}function Nr(e){return Array.from(e.routesByPath.values())}function jo(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 Vo(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 gt(e,t){Object.entries(e).forEach(([r,n])=>{r==="path"||!n||t.add(e.path,r,n)})}function ce(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 Br(e,t){ce(e.path,t),gt(e,t)}var Wo={routesDir:"./routes",basePath:"/",watchMode:process.env.NODE_ENV==="development"};function $r(e){let t={...Wo,...e};e.basePath&&!e.basePath.startsWith("/")&&console.warn("Base path does nothing");let r=zr(),n=mt(),o=!1,i=null,s=null,a=new Set([t.routesDir]);function c(l){console.log(`
|
|
41
|
+
\u{1F527} APPLYING MATCHER CHANGES:`),console.log(` Adding ${l.added.length} routes`),console.log(` Removing ${l.removed.length} routes`),console.log(` Updating ${l.changed.length} routes`),l.removed.forEach(f=>{console.log(` \u2796 Removing: ${f}`),ce(f,n)}),l.added.forEach(f=>{let g=Object.keys(f).filter(d=>d!=="path");console.log(` \u2795 Adding: ${f.path} [${g.join(", ")}]`),gt(f,n)}),l.changed.forEach(f=>{let g=Object.keys(f).filter(d=>d!=="path");console.log(` \u{1F504} Updating: ${f.path} [${g.join(", ")}]`),Br(f,n)}),console.log(`\u2705 Matcher changes applied
|
|
42
|
+
`)}function u(l,f){try{let g=q(r,f,l);return c(g),g}catch(g){throw console.error(`\u26A0\uFE0F Route conflicts from ${f}:`,g),g}}async function p(l,f,g){try{let d=await _r(l),y=d.map(b=>g?{...b,path:`${g}${b.path}`}:b),m=u(y,f);console.log(`Loaded ${d.length} routes from ${f}${g?` with prefix ${g}`:""} (${m.added.length} added, ${m.changed.length} changed, ${m.removed.length} removed)`)}catch(d){throw console.error(`\u26A0\uFE0F Failed to load routes from ${f}:`,d),d}}async function h(){return o||i||(i=(async()=>{try{await Promise.all(Array.from(a).map(l=>p(l,l))),t.watchMode&&w(),o=!0}catch(l){throw console.error("\u26A0\uFE0F Failed to initialize router:",l),l}})()),i}function w(){s||(s=new Map);for(let l of a)if(!s.has(l)){let f=it(l,{debounceMs:16,ignore:["node_modules",".git"],onRouteAdded:(g,d)=>{try{let y=q(r,g,d);c(y)}catch(y){console.error(`Error adding routes from ${l}:`,y)}},onRouteChanged:nt(async(g,d)=>{try{console.log(`Processing changes for ${g}`);let y=q(r,g,d);console.log(`Changes detected: ${y.added.length} added, ${y.changed.length} changed, ${y.removed.length} removed`),c(y),console.log(`Route changes applied: ${y.added.length} added, ${y.changed.length} changed, ${y.removed.length} removed`)}catch(y){console.error(`\u26A0\uFE0F Error updating routes from ${l}:`,y)}},l),onRouteRemoved:(g,d)=>{console.log(`File removed: ${g} with ${d.length} routes`);try{d.forEach(y=>{ce(y.path,n)}),rt(g)}catch(y){console.error(`\u26A0\uFE0F Error removing routes from ${g}:`,y)}},onError:g=>{console.error(`\u26A0\uFE0F Route watcher error for ${l}:`,g)}});s.set(l,f)}}function E(l,f){s||(s=new Map);let g=it(l,{debounceMs:16,ignore:["node_modules",".git"],onRouteAdded:(d,y)=>{try{let m=y.map(k=>f?{...k,path:`${f}${k.path}`}:k),b=q(r,d,m);c(b)}catch(m){console.error(`\u26A0\uFE0F Error adding routes from ${l}:`,m)}},onRouteChanged:nt(async(d,y)=>{try{let m=y.map(k=>f?{...k,path:`${f}${k.path}`}:k),b=q(r,d,m);c(b)}catch(m){console.error(`\u26A0\uFE0F Error updating routes from ${l}:`,m)}},l),onRouteRemoved:(d,y)=>{try{y.forEach(m=>{let b=f?`${f}${m.path}`:m.path;ce(b,n)}),rt(d)}catch(m){console.error(`Error removing routes from ${d}:`,m)}},onError:d=>{console.error(`\u26A0\uFE0F Route watcher error for ${l}:`,d)}});return s.set(l,g),g}return h().catch(l=>{console.error("\u26A0\uFE0F Failed to initialize router on creation:",l)}),{async handleRequest(l){o||(console.log("\u{1F504} Router not initialized, initializing..."),await h());let{method:f,path:g}=l.request;console.log(`
|
|
43
|
+
\u{1F4E5} Handling request: ${f} ${g}`);let d=n.match(g,f);if(!d)throw console.log(`\u274C No match found for: ${f} ${g}`),new H("Not found");if(console.log(`\u2705 Route matched: ${f} ${g}`),console.log(` Params: ${JSON.stringify(d.params)}`),d.methodNotAllowed){l.response.status(405).json({error:"\u274C Method Not Allowed",allowed:d.allowedMethods}),d.allowedMethods&&d.allowedMethods.length>0&&l.response.header("Allow",d.allowedMethods.join(", "));return}l.request.params=d.params,await pt(l,d.route,d.params)},getRoutes(){return Nr(r)},addRoute(l){let f=q(r,"programmatic",[l]);c(f)},addRoutes(l){let f=q(r,"programmatic",l);return c(f),f},async addRouteDirectory(l,f={}){if(a.has(l)){console.warn(`Route directory ${l} already registered`);return}a.add(l),o&&(await p(l,l,f.prefix),t.watchMode&&E(l,f.prefix))},getRouteConflicts(){return[]},async close(){if(s){for(let l of s.values())await l.close();s.clear()}}}}T();var Qo={port:3e3,host:"localhost",routesDir:"./routes",http2:{enabled:!0},middleware:[],plugins:[]};function Go(e={}){let t={...Qo};return wt({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 Zo(e){e.correlation&&Ct(e.correlation.headerName,e.correlation.generator)}function Jo(e,t){return async()=>(Zo(t),await Yo(e),await e.pluginManager.initializePlugins(e),await hr(e,t),await e.pluginManager.onServerStart(e,e.server),Ko(e),e)}async function Yo(e){for(let t of e.plugins)await t.register(e)}function Ko(e){let t=Sr(()=>e.close());e._signalHandlers=t,e.events.emit("started")}function Xo(e){return async t=>{if(!e.server)return;let r={...t};e._signalHandlers&&(e._signalHandlers.unregister(),delete e._signalHandlers),await yr(e,r)}}function ei(e){return t=>{let r=Array.isArray(t)?t:[t];return e.middleware.push(...r),e}}function ti(e){return async t=>{if(Array.isArray(t))for(let r of t)tt(r),e.plugins.push(r),await r.register(e);else tt(t),e.plugins.push(t),await t.register(e);return e}}function Ne(e={}){let t=Go(e),r;try{r=wr(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]:[],u=Array.isArray(s)?[...s]:[],p=new Hr.AsyncLocalStorage,h=$r({routesDir:r.routesDir,watchMode:process.env.NODE_ENV==="development"}),w=xr({debug:process.env.NODE_ENV==="development",continueOnError:!0}),E=new Ur.default,l={server:null,port:n,host:o,context:p,events:E,plugins:[...u],middleware:[...c],corsOptions:a,_signalHandlers:{unregister:()=>{}},use:()=>l,register:async()=>l,listen:async()=>l,close:async()=>{},router:h,pluginManager:w};return l.listen=Jo(l,r),l.close=Xo(l),l.use=ei(l),l.register=ti(l),l}function ht(e){return{}}T();function ri(e){return typeof e=="object"&&e!==null&&"name"in e&&"execute"in e&&typeof e.name=="string"&&typeof e.execute=="function"}function ni(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 oi(e){return e}function ii(e){return e}function si(...e){return e}function ai(...e){return e}C();I();C();T();var Be=class extends x{constructor(t,r=void 0,n=void 0){super("UNAUTHORIZED",t,401,n??S(),r)}};C();T();var $e=class extends x{constructor(t,r=void 0,n=void 0){super("CONFLICT",t,409,n??S(),r)}};C();T();var He=class extends x{constructor(t,r=void 0,n=void 0){super("RATE_LIMITED",t,429,n??S(),r)}};X();Oe();C();T();var Ue=class extends x{constructor(t,r,n){super("UPLOAD_TIMEOUT",t,408,n??S(),r)}};Fe();C();T();var qe=class extends x{constructor(t,r,n){super("UNPROCESSABLE_ENTITY",t,422,n??S(),r)}};var qr="0.1.0",Lr={createServer:Ne,inferContext:ht},jr={createDeleteRoute:Te,createGetRoute:xe,createHeadRoute:be,createOptionsRoute:Ce,createPatchRoute:Re,createPostRoute:Ee,createPutRoute:ve,createRouteFactory:We},Vr={createMiddleware:$,createServiceMiddleware:de,createStateMiddleware:ue,compose:L},Wr={createPlugin:pe},ci={createServer:Ne,createMiddleware:$,createServiceMiddleware:de,createStateMiddleware:ue,createPlugin:pe,getCorrelationId:S,Server:Lr,Router:jr,Middleware:Vr,Plugins:Wr,VERSION:qr};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});
|
|
31
44
|
//# sourceMappingURL=index.cjs.map
|