balda 0.0.59 → 0.0.60

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/lib/index.d.cts CHANGED
@@ -2563,7 +2563,7 @@ type PolicyRouteConfig<T extends Record<string, PolicyProvider> = Record<string,
2563
2563
  };
2564
2564
 
2565
2565
  type ServerHandlerReturnType<TResponseMap extends Record<number, any> = Record<number, any>> = void | Promise<void> | ResponseBodyForStatus<TResponseMap, 200> | Promise<ResponseBodyForStatus<TResponseMap, 200>>;
2566
- type ServerPlugin = {
2566
+ type ServerPluginConfig = {
2567
2567
  bodyParser?: BodyParserOptions;
2568
2568
  cors?: CorsOptions;
2569
2569
  static?: StaticPluginOptions;
@@ -2582,6 +2582,7 @@ type ServerPlugin = {
2582
2582
  asyncLocalStorage?: AsyncLocalStorageContextSetters;
2583
2583
  cache?: CachePluginOptions;
2584
2584
  };
2585
+ type ServerPlugin = ServerPluginConfig | readonly (ServerRouteMiddleware | TypedMiddleware<any>)[];
2585
2586
  type NodeHttpClient = "http" | "http2" | "https" | "http2-secure";
2586
2587
  type ServerOptions<H extends NodeHttpClient = NodeHttpClient> = {
2587
2588
  /** Specific node client to use for nodejs, default to `http` */
@@ -2592,7 +2593,33 @@ type ServerOptions<H extends NodeHttpClient = NodeHttpClient> = {
2592
2593
  host?: string;
2593
2594
  /** Controller patterns to match, defaults to an empty array */
2594
2595
  controllerPatterns?: string[];
2595
- /** Basic plugins to apply to all requests, plugins are applied in order based on where they are defined in the `plugins` object, by default no plugins are applied */
2596
+ /**
2597
+ * Plugins configuration for the server. Accepts either:
2598
+ *
2599
+ * - An object with built-in plugin options (bodyParser, cors, helmet, etc.)
2600
+ * - An array of middlewares to apply globally
2601
+ *
2602
+ * Plugins/middlewares are applied in order. By default, no plugins are applied.
2603
+ *
2604
+ * @example
2605
+ * ```ts
2606
+ * // Object form - built-in plugins
2607
+ * const server = new Server({
2608
+ * plugins: {
2609
+ * cors: { origin: ["http://localhost:3000"] },
2610
+ * helmet: {},
2611
+ * },
2612
+ * });
2613
+ * ```
2614
+ *
2615
+ * @example
2616
+ * ```ts
2617
+ * // Array form - custom middlewares
2618
+ * const server = new Server({
2619
+ * plugins: [authMiddleware, loggingMiddleware],
2620
+ * });
2621
+ * ```
2622
+ */
2596
2623
  plugins?: ServerPlugin;
2597
2624
  /** The tap options to interact with the underlying server connector before it is used to listen for incoming requests */
2598
2625
  tapOptions?: ServerTapOptions;
@@ -4907,4 +4934,4 @@ declare enum CacheStatus {
4907
4934
  */
4908
4935
  declare const router: ClientRouter;
4909
4936
 
4910
- export { type AsyncLocalStorageContextSetters, AzureBlobStorageProvider, BaseCron, BasePlugin, type BaseStorageProviderOptions, type BlobStorageProviderOptions, type BodylessMethodOptions, BullMQConfiguration, type BullMQConfigurationOptions, BullMQPubSub, CACHE_STATUS_HEADER, type CacheKeyIncludes, type CacheMiddlewareOptions, type CachePluginOptions, type CacheProvider, type CacheRedisOptions, type CacheRouteConfig, CacheService, type CacheServiceInterface, type CacheStats, CacheStatus, Command, type CommandOptions, CommandRegistry, type CompressionOptions, type CookieMiddlewareOptions, type CorsOptions, type CronSchedule, type CronScheduleParams, CronService, type CronUIOptions, CustomAdapter, type CustomQueueConfiguration, type CustomStorageProviderOptions, CustomTypedQueue, type CustomValidationError, DEFAULT_CACHE_OPTIONS, EdgeAdapter, EjsAdapter, type ExtractParams, GraphQL, type GraphQLContext, type GraphQLOptions, type GraphQLResolverFunction, type GraphQLResolverMap, type GraphQLResolverType, type GraphQLResolvers, type GraphQLSchemaInput, type GraphQLTypeDef, type GroupRouter, HandlebarsAdapter, type HelmetOptions, type HttpMethod, type HttpsOptions, type InferMiddlewareExtension, type InferMiddlewareExtensions, type InferResponseMap, type InferSchemaType, LocalStorageProvider, type LocalStorageProviderOptions, type LockBehavior, type LogOptions, type LoggerOptions, type MailOptions, MailOptionsBuilder, MailProvider, type MailProviderInterface, Mailer, type MailerInterface, type MailerOptions, type MailerProviderOptions, MemoryCacheProvider, MemoryPubSub, type MethodOverrideOptions, MockResponse, MockServer, type MockServerOptions, type MqttConnectionOptions, type MqttHandler, type MqttPublishOptions, MqttService, type MqttSubscribeOptions, type MqttSubscription, type MqttTopics, MustacheAdapter, type NextFunction, type NodeHttpClient, type NodeServer as NodeHttpServerClient, PGBossConfiguration, type PGBossConfigurationOptions, PGBossPubSub, type PolicyDecorator, type PolicyErrorHandlerOptions, PolicyManager, type PolicyProvider, type PolicyRouteConfig, type PublishTopic, QueueManager, QueueService, type RateLimiterKeyOptions, RedisCacheProvider, Request, type RequestSchema, Response$1 as Response, type ResponseBodyForStatus, type RuntimeServer, S3StorageProvider, type S3StorageProviderOptions, SQSConfiguration, type SQSConfigurationOptions, SQSPubSub, type CacheMetrics as SchemaCacheMetrics, type SerializeOptions, type SerializedValidationError, Server, type ServerConnectInput, type ServerErrorHandler, type ServerHook, type ServerInterface, type ServerListenCallback, type ServerOptions, type ServerRouteHandler, type ServerRouteMiddleware, type ServerTapOptions, type SessionOptions, type SignalEvent, type StandardMethodOptions, type StaticPluginOptions, Storage, type StorageInterface, type StorageOptions, type StorageProviderOptions, type TemplateMailOptions, type TimeoutOptions, type TrustProxyOptions, type TypedCacheKeyIncludes, type TypedCacheRouteConfig, type TypedHandler, type TypedMiddleware, TypedQueue, type TypedRouteMetadata, type ValidatedData, type ValidationErrorHandlerOptions, type ValidationOptions, arg, asyncLocalStorage, asyncStorage, bullmqQueue, cache, cacheMiddleware, clearAllCaches as clearAllSchemaCaches, commandRegistry, compression, controller, cookie, cors, createExpressAdapter, createPolicyDecorator, createQueue, cron, cronUIInstance, cronUi, Server as default, defineMiddleware, defineQueueConfiguration, del, expressHandler, expressMiddleware, flag, get, getCacheService, getCacheMetrics as getSchemaCacheMetrics, hash, helmet, initCacheService, log, logCacheMetrics as logSchemaCacheMetrics, logger, memoryQueue, methodOverride, middleware, mountExpressRouter, mqtt, patch, pgbossQueue, post, put, rateLimiter, resetCacheService, router, serialize, serveStatic, session, setCronGlobalErrorHandler, setMqttGlobalErrorHandler, sqsQueue, timeout as timeoutMw, trustProxy, validate };
4937
+ export { type AsyncLocalStorageContextSetters, AzureBlobStorageProvider, BaseCron, BasePlugin, type BaseStorageProviderOptions, type BlobStorageProviderOptions, type BodylessMethodOptions, BullMQConfiguration, type BullMQConfigurationOptions, BullMQPubSub, CACHE_STATUS_HEADER, type CacheKeyIncludes, type CacheMiddlewareOptions, type CachePluginOptions, type CacheProvider, type CacheRedisOptions, type CacheRouteConfig, CacheService, type CacheServiceInterface, type CacheStats, CacheStatus, Command, type CommandOptions, CommandRegistry, type CompressionOptions, type CookieMiddlewareOptions, type CorsOptions, type CronSchedule, type CronScheduleParams, CronService, type CronUIOptions, CustomAdapter, type CustomQueueConfiguration, type CustomStorageProviderOptions, CustomTypedQueue, type CustomValidationError, DEFAULT_CACHE_OPTIONS, EdgeAdapter, EjsAdapter, type ExtractParams, GraphQL, type GraphQLContext, type GraphQLOptions, type GraphQLResolverFunction, type GraphQLResolverMap, type GraphQLResolverType, type GraphQLResolvers, type GraphQLSchemaInput, type GraphQLTypeDef, type GroupRouter, HandlebarsAdapter, type HelmetOptions, type HttpMethod, type HttpsOptions, type InferMiddlewareExtension, type InferMiddlewareExtensions, type InferResponseMap, type InferSchemaType, LocalStorageProvider, type LocalStorageProviderOptions, type LockBehavior, type LogOptions, type LoggerOptions, type MailOptions, MailOptionsBuilder, MailProvider, type MailProviderInterface, Mailer, type MailerInterface, type MailerOptions, type MailerProviderOptions, MemoryCacheProvider, MemoryPubSub, type MethodOverrideOptions, MockResponse, MockServer, type MockServerOptions, type MqttConnectionOptions, type MqttHandler, type MqttPublishOptions, MqttService, type MqttSubscribeOptions, type MqttSubscription, type MqttTopics, MustacheAdapter, type NextFunction, type NodeHttpClient, type NodeServer as NodeHttpServerClient, PGBossConfiguration, type PGBossConfigurationOptions, PGBossPubSub, type PolicyDecorator, type PolicyErrorHandlerOptions, PolicyManager, type PolicyProvider, type PolicyRouteConfig, type PublishTopic, QueueManager, QueueService, type RateLimiterKeyOptions, RedisCacheProvider, Request, type RequestSchema, Response$1 as Response, type ResponseBodyForStatus, type RuntimeServer, S3StorageProvider, type S3StorageProviderOptions, SQSConfiguration, type SQSConfigurationOptions, SQSPubSub, type CacheMetrics as SchemaCacheMetrics, type SerializeOptions, type SerializedValidationError, Server, type ServerConnectInput, type ServerErrorHandler, type ServerHook, type ServerInterface, type ServerListenCallback, type ServerOptions, type ServerPlugin, type ServerPluginConfig, type ServerRouteHandler, type ServerRouteMiddleware, type ServerTapOptions, type SessionOptions, type SignalEvent, type StandardMethodOptions, type StaticPluginOptions, Storage, type StorageInterface, type StorageOptions, type StorageProviderOptions, type TemplateMailOptions, type TimeoutOptions, type TrustProxyOptions, type TypedCacheKeyIncludes, type TypedCacheRouteConfig, type TypedHandler, type TypedMiddleware, TypedQueue, type TypedRouteMetadata, type ValidatedData, type ValidationErrorHandlerOptions, type ValidationOptions, arg, asyncLocalStorage, asyncStorage, bullmqQueue, cache, cacheMiddleware, clearAllCaches as clearAllSchemaCaches, commandRegistry, compression, controller, cookie, cors, createExpressAdapter, createPolicyDecorator, createQueue, cron, cronUIInstance, cronUi, Server as default, defineMiddleware, defineQueueConfiguration, del, expressHandler, expressMiddleware, flag, get, getCacheService, getCacheMetrics as getSchemaCacheMetrics, hash, helmet, initCacheService, log, logCacheMetrics as logSchemaCacheMetrics, logger, memoryQueue, methodOverride, middleware, mountExpressRouter, mqtt, patch, pgbossQueue, post, put, rateLimiter, resetCacheService, router, serialize, serveStatic, session, setCronGlobalErrorHandler, setMqttGlobalErrorHandler, sqsQueue, timeout as timeoutMw, trustProxy, validate };
package/lib/index.d.ts CHANGED
@@ -2563,7 +2563,7 @@ type PolicyRouteConfig<T extends Record<string, PolicyProvider> = Record<string,
2563
2563
  };
2564
2564
 
2565
2565
  type ServerHandlerReturnType<TResponseMap extends Record<number, any> = Record<number, any>> = void | Promise<void> | ResponseBodyForStatus<TResponseMap, 200> | Promise<ResponseBodyForStatus<TResponseMap, 200>>;
2566
- type ServerPlugin = {
2566
+ type ServerPluginConfig = {
2567
2567
  bodyParser?: BodyParserOptions;
2568
2568
  cors?: CorsOptions;
2569
2569
  static?: StaticPluginOptions;
@@ -2582,6 +2582,7 @@ type ServerPlugin = {
2582
2582
  asyncLocalStorage?: AsyncLocalStorageContextSetters;
2583
2583
  cache?: CachePluginOptions;
2584
2584
  };
2585
+ type ServerPlugin = ServerPluginConfig | readonly (ServerRouteMiddleware | TypedMiddleware<any>)[];
2585
2586
  type NodeHttpClient = "http" | "http2" | "https" | "http2-secure";
2586
2587
  type ServerOptions<H extends NodeHttpClient = NodeHttpClient> = {
2587
2588
  /** Specific node client to use for nodejs, default to `http` */
@@ -2592,7 +2593,33 @@ type ServerOptions<H extends NodeHttpClient = NodeHttpClient> = {
2592
2593
  host?: string;
2593
2594
  /** Controller patterns to match, defaults to an empty array */
2594
2595
  controllerPatterns?: string[];
2595
- /** Basic plugins to apply to all requests, plugins are applied in order based on where they are defined in the `plugins` object, by default no plugins are applied */
2596
+ /**
2597
+ * Plugins configuration for the server. Accepts either:
2598
+ *
2599
+ * - An object with built-in plugin options (bodyParser, cors, helmet, etc.)
2600
+ * - An array of middlewares to apply globally
2601
+ *
2602
+ * Plugins/middlewares are applied in order. By default, no plugins are applied.
2603
+ *
2604
+ * @example
2605
+ * ```ts
2606
+ * // Object form - built-in plugins
2607
+ * const server = new Server({
2608
+ * plugins: {
2609
+ * cors: { origin: ["http://localhost:3000"] },
2610
+ * helmet: {},
2611
+ * },
2612
+ * });
2613
+ * ```
2614
+ *
2615
+ * @example
2616
+ * ```ts
2617
+ * // Array form - custom middlewares
2618
+ * const server = new Server({
2619
+ * plugins: [authMiddleware, loggingMiddleware],
2620
+ * });
2621
+ * ```
2622
+ */
2596
2623
  plugins?: ServerPlugin;
2597
2624
  /** The tap options to interact with the underlying server connector before it is used to listen for incoming requests */
2598
2625
  tapOptions?: ServerTapOptions;
@@ -4907,4 +4934,4 @@ declare enum CacheStatus {
4907
4934
  */
4908
4935
  declare const router: ClientRouter;
4909
4936
 
4910
- export { type AsyncLocalStorageContextSetters, AzureBlobStorageProvider, BaseCron, BasePlugin, type BaseStorageProviderOptions, type BlobStorageProviderOptions, type BodylessMethodOptions, BullMQConfiguration, type BullMQConfigurationOptions, BullMQPubSub, CACHE_STATUS_HEADER, type CacheKeyIncludes, type CacheMiddlewareOptions, type CachePluginOptions, type CacheProvider, type CacheRedisOptions, type CacheRouteConfig, CacheService, type CacheServiceInterface, type CacheStats, CacheStatus, Command, type CommandOptions, CommandRegistry, type CompressionOptions, type CookieMiddlewareOptions, type CorsOptions, type CronSchedule, type CronScheduleParams, CronService, type CronUIOptions, CustomAdapter, type CustomQueueConfiguration, type CustomStorageProviderOptions, CustomTypedQueue, type CustomValidationError, DEFAULT_CACHE_OPTIONS, EdgeAdapter, EjsAdapter, type ExtractParams, GraphQL, type GraphQLContext, type GraphQLOptions, type GraphQLResolverFunction, type GraphQLResolverMap, type GraphQLResolverType, type GraphQLResolvers, type GraphQLSchemaInput, type GraphQLTypeDef, type GroupRouter, HandlebarsAdapter, type HelmetOptions, type HttpMethod, type HttpsOptions, type InferMiddlewareExtension, type InferMiddlewareExtensions, type InferResponseMap, type InferSchemaType, LocalStorageProvider, type LocalStorageProviderOptions, type LockBehavior, type LogOptions, type LoggerOptions, type MailOptions, MailOptionsBuilder, MailProvider, type MailProviderInterface, Mailer, type MailerInterface, type MailerOptions, type MailerProviderOptions, MemoryCacheProvider, MemoryPubSub, type MethodOverrideOptions, MockResponse, MockServer, type MockServerOptions, type MqttConnectionOptions, type MqttHandler, type MqttPublishOptions, MqttService, type MqttSubscribeOptions, type MqttSubscription, type MqttTopics, MustacheAdapter, type NextFunction, type NodeHttpClient, type NodeServer as NodeHttpServerClient, PGBossConfiguration, type PGBossConfigurationOptions, PGBossPubSub, type PolicyDecorator, type PolicyErrorHandlerOptions, PolicyManager, type PolicyProvider, type PolicyRouteConfig, type PublishTopic, QueueManager, QueueService, type RateLimiterKeyOptions, RedisCacheProvider, Request, type RequestSchema, Response$1 as Response, type ResponseBodyForStatus, type RuntimeServer, S3StorageProvider, type S3StorageProviderOptions, SQSConfiguration, type SQSConfigurationOptions, SQSPubSub, type CacheMetrics as SchemaCacheMetrics, type SerializeOptions, type SerializedValidationError, Server, type ServerConnectInput, type ServerErrorHandler, type ServerHook, type ServerInterface, type ServerListenCallback, type ServerOptions, type ServerRouteHandler, type ServerRouteMiddleware, type ServerTapOptions, type SessionOptions, type SignalEvent, type StandardMethodOptions, type StaticPluginOptions, Storage, type StorageInterface, type StorageOptions, type StorageProviderOptions, type TemplateMailOptions, type TimeoutOptions, type TrustProxyOptions, type TypedCacheKeyIncludes, type TypedCacheRouteConfig, type TypedHandler, type TypedMiddleware, TypedQueue, type TypedRouteMetadata, type ValidatedData, type ValidationErrorHandlerOptions, type ValidationOptions, arg, asyncLocalStorage, asyncStorage, bullmqQueue, cache, cacheMiddleware, clearAllCaches as clearAllSchemaCaches, commandRegistry, compression, controller, cookie, cors, createExpressAdapter, createPolicyDecorator, createQueue, cron, cronUIInstance, cronUi, Server as default, defineMiddleware, defineQueueConfiguration, del, expressHandler, expressMiddleware, flag, get, getCacheService, getCacheMetrics as getSchemaCacheMetrics, hash, helmet, initCacheService, log, logCacheMetrics as logSchemaCacheMetrics, logger, memoryQueue, methodOverride, middleware, mountExpressRouter, mqtt, patch, pgbossQueue, post, put, rateLimiter, resetCacheService, router, serialize, serveStatic, session, setCronGlobalErrorHandler, setMqttGlobalErrorHandler, sqsQueue, timeout as timeoutMw, trustProxy, validate };
4937
+ export { type AsyncLocalStorageContextSetters, AzureBlobStorageProvider, BaseCron, BasePlugin, type BaseStorageProviderOptions, type BlobStorageProviderOptions, type BodylessMethodOptions, BullMQConfiguration, type BullMQConfigurationOptions, BullMQPubSub, CACHE_STATUS_HEADER, type CacheKeyIncludes, type CacheMiddlewareOptions, type CachePluginOptions, type CacheProvider, type CacheRedisOptions, type CacheRouteConfig, CacheService, type CacheServiceInterface, type CacheStats, CacheStatus, Command, type CommandOptions, CommandRegistry, type CompressionOptions, type CookieMiddlewareOptions, type CorsOptions, type CronSchedule, type CronScheduleParams, CronService, type CronUIOptions, CustomAdapter, type CustomQueueConfiguration, type CustomStorageProviderOptions, CustomTypedQueue, type CustomValidationError, DEFAULT_CACHE_OPTIONS, EdgeAdapter, EjsAdapter, type ExtractParams, GraphQL, type GraphQLContext, type GraphQLOptions, type GraphQLResolverFunction, type GraphQLResolverMap, type GraphQLResolverType, type GraphQLResolvers, type GraphQLSchemaInput, type GraphQLTypeDef, type GroupRouter, HandlebarsAdapter, type HelmetOptions, type HttpMethod, type HttpsOptions, type InferMiddlewareExtension, type InferMiddlewareExtensions, type InferResponseMap, type InferSchemaType, LocalStorageProvider, type LocalStorageProviderOptions, type LockBehavior, type LogOptions, type LoggerOptions, type MailOptions, MailOptionsBuilder, MailProvider, type MailProviderInterface, Mailer, type MailerInterface, type MailerOptions, type MailerProviderOptions, MemoryCacheProvider, MemoryPubSub, type MethodOverrideOptions, MockResponse, MockServer, type MockServerOptions, type MqttConnectionOptions, type MqttHandler, type MqttPublishOptions, MqttService, type MqttSubscribeOptions, type MqttSubscription, type MqttTopics, MustacheAdapter, type NextFunction, type NodeHttpClient, type NodeServer as NodeHttpServerClient, PGBossConfiguration, type PGBossConfigurationOptions, PGBossPubSub, type PolicyDecorator, type PolicyErrorHandlerOptions, PolicyManager, type PolicyProvider, type PolicyRouteConfig, type PublishTopic, QueueManager, QueueService, type RateLimiterKeyOptions, RedisCacheProvider, Request, type RequestSchema, Response$1 as Response, type ResponseBodyForStatus, type RuntimeServer, S3StorageProvider, type S3StorageProviderOptions, SQSConfiguration, type SQSConfigurationOptions, SQSPubSub, type CacheMetrics as SchemaCacheMetrics, type SerializeOptions, type SerializedValidationError, Server, type ServerConnectInput, type ServerErrorHandler, type ServerHook, type ServerInterface, type ServerListenCallback, type ServerOptions, type ServerPlugin, type ServerPluginConfig, type ServerRouteHandler, type ServerRouteMiddleware, type ServerTapOptions, type SessionOptions, type SignalEvent, type StandardMethodOptions, type StaticPluginOptions, Storage, type StorageInterface, type StorageOptions, type StorageProviderOptions, type TemplateMailOptions, type TimeoutOptions, type TrustProxyOptions, type TypedCacheKeyIncludes, type TypedCacheRouteConfig, type TypedHandler, type TypedMiddleware, TypedQueue, type TypedRouteMetadata, type ValidatedData, type ValidationErrorHandlerOptions, type ValidationOptions, arg, asyncLocalStorage, asyncStorage, bullmqQueue, cache, cacheMiddleware, clearAllCaches as clearAllSchemaCaches, commandRegistry, compression, controller, cookie, cors, createExpressAdapter, createPolicyDecorator, createQueue, cron, cronUIInstance, cronUi, Server as default, defineMiddleware, defineQueueConfiguration, del, expressHandler, expressMiddleware, flag, get, getCacheService, getCacheMetrics as getSchemaCacheMetrics, hash, helmet, initCacheService, log, logCacheMetrics as logSchemaCacheMetrics, logger, memoryQueue, methodOverride, middleware, mountExpressRouter, mqtt, patch, pgbossQueue, post, put, rateLimiter, resetCacheService, router, serialize, serveStatic, session, setCronGlobalErrorHandler, setMqttGlobalErrorHandler, sqsQueue, timeout as timeoutMw, trustProxy, validate };
package/lib/index.js CHANGED
@@ -1226,6 +1226,6 @@ ${d}\r
1226
1226
  <script src="https://unpkg.com/@stoplight/elements@7.7.9/web-components.min.js"></script>
1227
1227
  </body>
1228
1228
  </html>
1229
- `}function zs(o,e){let t=[],r=/:([a-zA-Z0-9_]+)/g,s;for(;(s=r.exec(o))!==null;){let i=s[1],n={type:"string"};e&&e.shape&&e.shape[i]&&(n=ye(e.shape[i])||{type:"string"}),t.push({name:i,in:"path",required:true,schema:n});}return t}var Lr=o=>async(e,t,r)=>{e.timeout=false;let s=setTimeout(()=>{e.timeout=true;},o.ms);try{await r();}finally{clearTimeout(s);}};var Nr=o=>{let e=o?.header??"x-forwarded-for",t=o?.trust??true,r=o?.hop??"first";return async(s,i,n)=>{if(!t)return n();let a=s.rawHeaders.get(e);if(a&&typeof a=="string"){let l=a.split(",").map(p=>p.trim()).filter(Boolean);l.length&&(s.ip=r==="first"?l[0]:l[l.length-1]);}return n()}};var Nt=class{port;hostname;host;routes;tapOptions;graphql;ensureGraphQLHandler;constructor(e){this.routes=e?.routes??[],this.port=e?.port??80,this.hostname=e?.host??"0.0.0.0",this.host=e?.host??"0.0.0.0",this.tapOptions=e?.tapOptions,this.graphql=e?.graphql??new ie,this.ensureGraphQLHandler=ge(this.graphql);}get url(){return `http://${this.host}:${this.port}`}listen(){let e=this.tapOptions?.bun,{fetch:t,websocket:r,...s}=e??{},i=this.graphql.isEnabled,n="/graphql";this.runtimeServer=Bun.serve({port:this.port,hostname:this.hostname,fetch:async(a,l)=>{let p=a.url,c=p.indexOf("://")+3,d=p.indexOf("/",c),u=d===-1?"/":p.slice(d),h=u.indexOf("?"),m=h===-1?u:u.slice(0,h),f=h===-1?"":u.slice(h+1),g=_.find(a.method,m),y=ne.fromRequest(a);if(y.params=g?.params??{},y.setQueryString(f),y.setBunIpExtractor(a,l),await t?.call(this,y,l),i&&m.startsWith(n)){let w=await this.ensureGraphQLHandler();if(w){let b=y.toWebApi();return At(w.server,b,a.method,f,{req:y,server:l})}}if(r&&y.rawHeaders.get("upgrade")==="websocket"){let w=y.toWebApi();if(l.upgrade(w,{data:{}}))return}let P=new Q;return g?.responseSchemas&&P.setRouteResponseSchemas(g.responseSchemas),await fe(g?.middleware??[],g?.handler??((w,b)=>{b.notFound({...N(new J(w.url,w.method))});}),y,P),Q.toWebResponse(P)},...r?{websocket:r}:{},...s});}async close(){this.runtimeServer&&await this.runtimeServer.stop();}};var It=class{graphql;ensureGraphQLHandler;constructor(e){this.routes=e?.routes??[],this.port=e?.port??80,this.hostname=e?.host??"0.0.0.0",this.host=e?.host??"0.0.0.0",this.tapOptions=e?.tapOptions,this.graphql=e?.graphql??new ie,this.ensureGraphQLHandler=ge(this.graphql);}get url(){return `http://${this.host}:${this.port}`}listen(){let e=this.tapOptions?.deno,{handler:t,...r}=e??{},s=this.graphql.isEnabled,i="/graphql";this.runtimeServer=Deno.serve({port:this.port,hostname:this.hostname,handler:async(n,a)=>{let l=n.url,p=l.indexOf("://")+3,c=l.indexOf("/",p),d=c===-1?"/":l.slice(c),u=d.indexOf("?"),h=u===-1?d:d.slice(0,u),m=u===-1?"":d.slice(u+1),f=_.find(n.method,h),g=ne.fromRequest(n);if(g.params=f?.params??{},g.setQueryString(m),g.setDenoIpExtractor(n,a),await t?.(n,a))return new globalThis.Response(null,{status:426});if(s&&h.startsWith(i)){let w=await this.ensureGraphQLHandler();if(w){let b=g.toWebApi();return At(w.server,b,n.method,m,{req:g,info:a})}}if(g.rawHeaders.get("upgrade")==="websocket"&&this.tapOptions?.deno?.websocket){let w=g.toWebApi(),{socket:b,response:k}=Deno.upgradeWebSocket(w);return this.tapOptions?.deno?.websocket?.open&&(b.onopen=()=>this.tapOptions?.deno?.websocket?.open?.(b)),this.tapOptions?.deno?.websocket?.message&&(b.onmessage=A=>{this.tapOptions?.deno?.websocket?.message?.(b,A.data);}),this.tapOptions?.deno?.websocket?.close&&(b.onclose=()=>this.tapOptions?.deno?.websocket?.close?.(b)),k}let P=new Q;return f?.responseSchemas&&P.setRouteResponseSchemas(f.responseSchemas),await fe(f?.middleware??[],f?.handler??((w,b)=>{b.notFound({...N(new J(w.url,w.method))});}),g,P),Q.toWebResponse(P)},...r});}async close(){this.runtimeServer&&await this.runtimeServer.shutdown();}};var Ii=async(o,e)=>{let t=Readable.fromWeb(o);return pipeline(t,e)},Ft=class{port;host;routes;tapOptions;runtimeServer;nodeHttpClient;httpsOptions;graphql;ensureGraphQLHandler;needsHeaderFiltering;constructor(e){this.routes=e?.routes??[],this.port=e?.port??80,this.host=e?.host??"0.0.0.0",this.tapOptions=e?.tapOptions,this.nodeHttpClient=e?.nodeHttpClient??"http",this.httpsOptions=e?.nodeHttpClient==="https"||e?.nodeHttpClient==="http2-secure"?e?.httpsOptions:void 0,this.graphql=e?.graphql??new ie,this.ensureGraphQLHandler=ge(this.graphql),this.needsHeaderFiltering=this.nodeHttpClient==="http2"||this.nodeHttpClient==="http2-secure",this.createServerWithHandler();}get url(){return `${this.nodeHttpClient==="https"||this.nodeHttpClient==="http2-secure"?"https":"http"}://${this.host}:${this.port}`}createServerWithHandler(){let e=this.graphql.isEnabled,t="/graphql";this.runtimeServer=this.createServer(async(r,s)=>{if(this.tapOptions&&this.tapOptions.node){let h=this.tapOptions.node;await h?.(r);}let i=r.url,n=i.indexOf("?"),a=n===-1?i:i.slice(0,n),l=n===-1?"":i.slice(n+1);if(e&&a.startsWith(t)){let h=await this.ensureGraphQLHandler();if(h){let m=le(r.method)?await this.readRequestBody(r):"";await Ts(h.server,r.headers,r.method??"POST",m,l,{req:r},async(f,g,y)=>{for(let[P,S]of f)s.setHeader(P,S);if(s.statusCode=g,typeof y=="string")s.end(y);else {for await(let P of y)s.write(P);s.end();}});return}}let p=_.find(r.method,a),c=new ne;c.url=`${this.url}${i}`,c.method=r.method,le(r.method)&&c.setNodeRequest(r),c.setRawHeaders(r.headers,this.needsHeaderFiltering),c.setIpExtractor(r),c.setQueryString(l),c.params=p?.params??{};let d=new Q;d.nodeResponse=s,p?.responseSchemas&&d.setRouteResponseSchemas(p.responseSchemas);let u=fe(p?.middleware??[],p?.handler??((h,m)=>{m.notFound({...N(new J(h.url,h.method))});}),c,d);u instanceof Q?this.writeResponse(u,s):u.then(h=>this.writeResponse(h,s));});}listen(){this.runtimeServer.listen(this.port,this.host);}writeResponse(e,t){if(t.headersSent||t.writableEnded)return;let r=e.getBody();if(r instanceof ReadableStream){t.writeHead(e.responseStatus,e.headers),Ii(r,t);return}t.writeHead(e.responseStatus,e.headers),r instanceof Buffer||r instanceof Uint8Array||typeof r=="string"?t.end(r):e.headers["Content-Type"]==="application/json"?t.end(typeof r=="string"?r:JSON.stringify(r)):t.end(r!=null?String(r):void 0);}async close(){return new Promise((e,t)=>{this.runtimeServer.close(r=>{r&&"code"in r&&r.code!=="ERR_SERVER_NOT_RUNNING"?t(r):e();});})}processHeaders(e){let t={};if(this.needsHeaderFiltering){for(let s in e){if(s.charCodeAt(0)===58)continue;let i=e[s];i!==void 0&&(t[s]=Array.isArray(i)?i.join(", "):i);}return t}for(let r in e){let s=e[r];s!==void 0&&(t[r]=Array.isArray(s)?s.join(", "):s);}return t}extractClientIp(e){let t=e.headers["x-forwarded-for"];return t?Array.isArray(t)?t[0].trim():t.split(",")[0].trim():e.socket.remoteAddress}async readRequestBody(e){return new Promise((t,r)=>{let s=[];e.on("data",i=>s.push(Buffer.from(i))),e.on("error",r),e.on("end",()=>t(Buffer.concat(s).toString()));})}createServer(e){if(this.nodeHttpClient==="http")return createServer(e);if(this.nodeHttpClient==="http2")return createServer$1(e);if(this.nodeHttpClient==="http2-secure"){if(!this.httpsOptions)throw new Error("httpsOptions (key, cert) are required when using http2-secure client");return createSecureServer(this.httpsOptions,e)}if(!this.httpsOptions)throw new Error("httpsOptions (key, cert) are required when using https client");return createServer$2(this.httpsOptions,e)}};var Dt=class{routes;server;constructor(e){this.server=this.getRuntimeServer(e),this.routes=this.server.routes;}get url(){return this.server.url}get port(){return this.server.port}set port(e){this.server.port=e;}get host(){return this.server.host}getServer(e){return this.server.runtimeServer}listen(){return this.server.listen()}async close(){return this.server.close()}getRuntimeServer(e){if(e?.runtime==="bun")return new Nt(e);if(e?.runtime==="node")return new Ft(e);if(e?.runtime==="deno")return new It(e);throw new Error("No server implementation found for runtime: "+e?.runtime)}};V();var Qt=class{_brand="BaldaServer";#t=new Ge;serverOptions;router=_;logger;isListening;isProduction;graphql;#r;#e;#a=[];#o=["node_modules"];#i;#l;#d=[];#u=[];constructor(e){this.#r=false,this.logger=(e?.logger??E).child({scope:"Balda"}),this.serverOptions={nodeHttpClient:e?.nodeHttpClient??"http",port:(e?.port??Number(this.#t.get("PORT")||"80"))||80,host:e?.host??this.#t.get("HOST")??"0.0.0.0",controllerPatterns:e?.controllerPatterns??[],plugins:e?.plugins??{},tapOptions:e?.tapOptions??{},swagger:e?.swagger??true,graphql:e?.graphql??void 0,abortSignal:e?.abortSignal},e?.ajvInstance&&j.setGlobalInstance(e.ajvInstance),this.#l=e?.nodeHttpClient==="https"||e?.nodeHttpClient==="http2-secure"?e.httpsOptions:void 0,this.isListening=false,this.isProduction=this.#t.get("NODE_ENV")==="production",this.graphql=new ie(this.serverOptions.graphql),this.#e=new Dt({routes:[],port:this.serverOptions.port,host:this.serverOptions.host,tapOptions:this.serverOptions.tapOptions,runtime:M.type,nodeHttpClient:this.serverOptions.nodeHttpClient,httpsOptions:this.#l,graphql:this.graphql}),this.setupAbortSignalHandler();}get protectedKeys(){let e=Object.getOwnPropertyNames(this),t=Object.getPrototypeOf(this),r=t?Object.getOwnPropertyNames(t):[];return Array.from(new Set([...e,...r]))}get url(){return this.#e.url}get port(){return this.#e.port}set port(e){if(this.isListening)throw new Error("Cannot change port while server is listening, please call `.close()` before changing the port");this.#e.port=e;}get host(){return this.#e.host}get routes(){return _.getRoutes()||[]}get fs(){return v}getEnvironment(){return this.#t.getEnvironment()}tmpDir(...e){return x.join("tmp",...e)}getNodeServer(){if(M.type!=="node")throw new Error("Server is not using node runtime, you can't call `.getNodeServer()`");return this.#e.getServer("node")}getBunServer(){if(M.type!=="bun")throw new Error("Server is not using bun runtime, you can't call `.getBunServer()`");return this.#e.getServer("bun")}getDenoServer(){if(M.type!=="deno")throw new Error("Server is not using deno runtime, you can't call `.getDenoServer()`");return this.#e.getServer("deno")}embed(e,t){if(typeof e!="string"||e.trim()==="")throw new Error(`Invalid key provided to embed: ${e}. Key must be a non-empty string.`);if(this.protectedKeys.includes(e)||e==="constructor")throw new Error(`Cannot embed value with key '${e}' as it conflicts with a protected server property`);Object.defineProperty(this,e,{value:t,writable:false,configurable:true,enumerable:true});}exit(e=0){Qe.exit(e);}on(e,t){switch(M.type){case "bun":case "node":process.on(e,t);break;case "deno":Deno.addSignalListener(e,t);break;default:throw new Error(`Unsupported runtime: ${M.type}, only node, bun and deno are supported`)}}once(e,t){switch(M.type){case "bun":case "node":process.once(e,t);break;case "deno":Deno.addSignalListener(e,t);break;default:throw new Error(`Unsupported runtime: ${M.type}, only node, bun and deno are supported`)}}use(...e){this.#a.push(...e);}useExpress(e,t){kr(this).use(e,t);}expressMiddleware(e){return $e(e)}mountExpressRouter(e,t){dt(e,t);}setErrorHandler(e){this.#a.unshift(async(t,r,s)=>{try{await s();}catch(i){await e?.(t,r,s,i);}});}setNotFoundHandler(e){this.#i=e?.bind(this);}setValidationErrorHandler(e){ss(e);}setPolicyErrorHandler(e){ps(e);}beforeStart(e){this.#d.push(e);}beforeClose(e){this.#u.push(e);}listen(e,t){let r=typeof e=="function"?e:t;if(typeof e=="number"&&Number.isFinite(e)&&(this.port=e),this.isListening)throw new Error("Server is already listening, you can't call `.listen()` multiple times");let s={port:this.port,host:this.host,url:this.url};this.bootstrap().then(async()=>{for(let i of this.#d)await i();this.#e.listen(),this.isListening=true,r?.({...s,error:void 0});}).catch(i=>{r?.({...s,error:i});});}async waitUntilListening(e){return e??=this.port,new Promise((t,r)=>{try{this.listen(e,()=>{t({port:this.port,host:this.host,url:this.url});});}catch(s){r(s);}})}async close(){await this.disconnect();}async disconnect(){if(!this.isListening){this.logger.warn("Trying to disconnect the server that is not listening, ignoring");return}try{for(let e of this.#u)await e();await this.#e.close();}catch(e){throw this.logger.error({error:e},"Error closing server connector"),e}finally{this.isListening=false;}}async getMockServer(e){return await this.bootstrap(e),new Ht(this)}async importControllers(e){let t=e??this.serverOptions.controllerPatterns;if(!(!t||t.length===0))try{let r=await Promise.all(t.map(async s=>v.glob(s,{cwd:L.getCwd()}))).then(s=>s.flat());r=r.flat(),r=r.filter(s=>!this.#o.some(i=>s.includes(i))),this.logger.debug(`Found ${r.length} controllers to import`),await Promise.all(r.map(async s=>{this.logger.debug(`Importing controller ${s}`),await import(s).catch(i=>{this.logger.error(`Error importing controller ${s}: ${i}`);});}));}catch(r){this.logger.warn(`Could not auto-import controllers: ${r instanceof Error?r.message:String(r)}`);}}applyPlugins(e){Object.entries(e).forEach(([t,r])=>{switch(t){case "bodyParser":this.use(_s(r));break;case "cors":this.use(jr(r));break;case "static":this.use(Pr(r));break;case "helmet":this.use(Ar(r));break;case "cookie":this.use(Mr(r));break;case "methodOverride":this.use(Hr(r));break;case "compression":this.use(Er(r));break;case "log":this.use(_r(r));break;case "rateLimiter":let{keyOptions:s,storageOptions:i}=r;this.use($r(s,i));break;case "trustProxy":this.use(Nr(r));break;case "timeout":this.use(Lr(r));break;case "session":this.use(Br(r));break;case "asyncLocalStorage":this.use(Cr(r));break;case "cache":{let n=r,a;n.provider&&typeof n.provider=="object"&&"get"in n.provider?a=n.provider:n.provider==="redis"?a=new ct(n.redis):a=new at,this.use(xr(a,n));break}default:this.logger.warn(`Unknown plugin ${t}`);break}});}async bootstrap(e){this.#r||(await this.importControllers(e?.controllerPatterns),this.applyPlugins(this.serverOptions.plugins),this.serverOptions.swagger&&Gs(this.serverOptions.swagger),this.registerNotFoundRoutes(),this.#a.length&&_.applyGlobalMiddlewaresToAllRoutes(this.#a),this.#r=true);}handleNotFound=(e,t)=>{if(this.#i){this.#i(e,t);return}let r=new URL(e.url).pathname,s=["GET","POST","PUT","PATCH","DELETE"],i=[];for(let a of s){if(a===e.method.toUpperCase())continue;let l=_.find(a,r);l&&l.handler!==this.handleNotFound&&i.push(a);}if(i.length){t.setHeader("Allow",i.join(", "));let a=new Je(r,e.method);t.methodNotAllowed({...N(a)});return}let n=new J(r,e.method);t.notFound({...N(n)});};registerNotFoundRoutes(){let e=["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"];for(let t of e)_.addOrUpdate(t,"*",[],this.handleNotFound,{},{excludeFromSwagger:true},void 0,true);}setupAbortSignalHandler(){if(!this.serverOptions.abortSignal)return;let e=this.serverOptions.abortSignal;if(e.aborted){this.logger.warn("AbortSignal was already aborted, server will not start");return}e.addEventListener("abort",async()=>{this.logger.info("AbortSignal received, shutting down server gracefully");try{await this.disconnect(),this.logger.info("Server shutdown completed");}catch(t){this.logger.error({error:t},"Error during server shutdown from abort signal");}});}};var Ir=class{ITERATIONS=6e5;SALT_LENGTH=16;KEY_LENGTH=256;configure(e){if(e.iterations!==void 0){if(e.iterations<1)throw new Error("Iterations must be at least 1");this.ITERATIONS=e.iterations;}if(e.saltLength!==void 0){if(e.saltLength<8)throw new Error("Salt length must be at least 8 bytes");this.SALT_LENGTH=e.saltLength;}if(e.keyLength!==void 0){if(e.keyLength<128)throw new Error("Key length must be at least 128 bits");this.KEY_LENGTH=e.keyLength;}}async hash(e){if(!e)throw new Error("Data to hash cannot be empty");let r=new TextEncoder().encode(e),s=crypto.getRandomValues(new Uint8Array(this.SALT_LENGTH)),i=await crypto.subtle.importKey("raw",r,{name:"PBKDF2"},false,["deriveBits"]),n=await crypto.subtle.deriveBits({name:"PBKDF2",salt:s,iterations:this.ITERATIONS,hash:"SHA-256"},i,this.KEY_LENGTH),a=this.encodeBase64(s),l=this.encodeBase64(new Uint8Array(n));return `${a}:${l}`}async compare(e,t){if(!e||!t)return false;try{let s=new TextEncoder().encode(t),i=e.split(":");if(i.length!==2)throw new Error("Invalid hash format");let[n,a]=i,l=this.decodeBase64(n),p=this.decodeBase64(a),c=await crypto.subtle.importKey("raw",s,{name:"PBKDF2"},!1,["deriveBits"]),d=await crypto.subtle.deriveBits({name:"PBKDF2",salt:l,iterations:this.ITERATIONS,hash:"SHA-256"},c,this.KEY_LENGTH),u=new Uint8Array(d);if(u.length!==p.length)return !1;let h=0;for(let m=0;m<u.length;m++)h|=u[m]^p[m];return h===0}catch{return false}}encodeBase64(e){let t="",r=e.byteLength;for(let s=0;s<r;s++)t+=String.fromCharCode(e[s]);return btoa(t)}decodeBase64(e){let t=atob(e),r=t.length,s=new Uint8Array(r);for(let i=0;i<r;i++)s[i]=t.charCodeAt(i);return s}},Fi=new Ir;var Js=()=>{let o=j.getCacheStats(),e=o.schemaCount*3,t=e,r=s=>s<1024?`~${s}KB`:`~${(s/1024).toFixed(2)}MB`;return {validators:{size:o.schemaCount,description:"Compiled schemas stored in Ajv for validation and serialization"},totalSchemaReferences:o.totalRefsCreated,memoryEstimate:{validators:r(e),total:r(t)}}},Di=()=>{let o=Js();E.info({validators:o.validators.size,totalSchemaRefs:o.totalSchemaReferences,memoryEstimate:o.memoryEstimate.total},"Schema cache metrics");},Qi=()=>{j.clearAllCaches(),E.debug("All schema caches cleared");};var Z=class extends R{constructor(e){super(`File not found: ${e}`);}};var Fr=class{constructor(e){this.options=e;}async getDownloadUrl(e,t=3600){await this.ensureClient();let r=this.containerClient.getBlockBlobClient(e),s=new Date(Date.now()-300*1e3),i=new Date(Date.now()+t*1e3),n=this.azureBlobLib.BlobSASPermissions.parse("r"),a=this.azureBlobLib.generateBlobSASQueryParameters({containerName:this.options.containerName,blobName:e,permissions:n,startsOn:s,expiresOn:i},this.sharedKeyCredential).toString();return `${r.url}?${a}`}async getUploadUrl(e,t=3600){await this.ensureClient();let r=this.containerClient.getBlockBlobClient(e),s=new Date(Date.now()-300*1e3),i=new Date(Date.now()+t*1e3),n=this.azureBlobLib.BlobSASPermissions.parse("w"),a=this.azureBlobLib.generateBlobSASQueryParameters({containerName:this.options.containerName,blobName:e,permissions:n,startsOn:s,expiresOn:i},this.sharedKeyCredential).toString();return `${r.url}?${a}`}async getPublicUrl(e){return await this.ensureClient(),this.containerClient.getBlockBlobClient(e).url}async listObjects(e){await this.ensureClient();let t=[],r=e?e.endsWith("/")?e:`${e}/`:void 0;for await(let s of this.containerClient.listBlobsFlat({prefix:r}))t.push(s.name);return t}async getObject(e,t="raw"){await this.ensureClient();try{let s=await this.containerClient.getBlockBlobClient(e).download();if(!s.readableStreamBody)throw new Z(e);let i=t;if(i==="stream")return Readable.toWeb(s.readableStreamBody);let n=[];for await(let l of s.readableStreamBody)n.push(Buffer.isBuffer(l)?l:Buffer.from(l));let a=Buffer.concat(n);switch(i){case "raw":return new Uint8Array(a);case "text":return a.toString();default:throw new R("Invalid return type")}}catch(r){throw r&&typeof r=="object"&&"statusCode"in r&&r.statusCode===404?new Z(e):r}}async putObject(e,t,r){await this.ensureClient();let s=this.containerClient.getBlockBlobClient(e),i=t;await s.upload(i,i.length,{blobHTTPHeaders:{blobContentType:r||"application/octet-stream"}});}async deleteObject(e){await this.ensureClient();let t=this.containerClient.getBlockBlobClient(e);try{await t.delete();}catch(r){if(r&&typeof r=="object"&&"statusCode"in r&&r.statusCode===404)return;throw r}}async ensureClient(){if(this.azureBlobLib)return;this.azureBlobLib=await import('@azure/storage-blob').catch(()=>{throw new R("Library not installed: @azure/storage-blob, try run npm install @azure/storage-blob")}),this.blobServiceClient=this.azureBlobLib.BlobServiceClient.fromConnectionString(this.options.connectionString),this.containerClient=this.blobServiceClient.getContainerClient(this.options.containerName);let e=this.blobServiceClient.credential;if(!(e instanceof this.azureBlobLib.StorageSharedKeyCredential))throw new R("BlobStorage requires a shared key credential to generate SAS URLs");this.sharedKeyCredential=e;}};var Dr=class{constructor(e){this.options=e;}wasDirectoryEnsured=false;async getDownloadUrl(e,t=3600){throw new R("LocalStorageProvider does not support getDownloadUrl. Use S3 or Azure Blob storage for signed URLs.")}async getUploadUrl(e,t=3600){throw new R("LocalStorageProvider does not support getUploadUrl. Use S3 or Azure Blob storage for signed URLs.")}async getPublicUrl(e){throw new R("`getPublicUrl` is not available in local storage provider")}async listObjects(e){this.wasDirectoryEnsured||await this.ensureDirectoryExists();let t=x.resolve(this.options.directory),r=e?x.join(t,e):t;if(!await v.exists(r))return [];let i=[];return await this.listFilesRecursively(r,t,i),i}async getObject(e,t="raw"){this.wasDirectoryEnsured||await this.ensureDirectoryExists();let r=x.join(this.options.directory,e);if(!await v.exists(r))throw new Z(e);switch(t){case "raw":return await v.readFile(r);case "text":return await v.readFile(r,{encoding:"utf8"});case "stream":return await v.streamFile(r);default:throw new R("Invalid return type")}}async putObject(e,t,r){this.wasDirectoryEnsured||await this.ensureDirectoryExists();let s=x.join(this.options.directory,e),i=x.join(s,"..");await v.mkdir(i,{recursive:true}),await v.writeFile(s,t);}async deleteObject(e){this.wasDirectoryEnsured||await this.ensureDirectoryExists();let t=x.join(this.options.directory,e);await v.exists(t)&&await v.unlink(t);}async listFilesRecursively(e,t,r){let s=await v.stat(e);if(s.isFile){let n=e.replace(t,"").replace(/^\//,"");r.push(n);return}if(!s.isDirectory)return;let i=await this.readDirectory(e);for(let n of i){let a=x.join(e,n);await this.listFilesRecursively(a,t,r);}}async readDirectory(e){let{runtime:t}=await Promise.resolve().then(()=>(V(),Kr));switch(t.type){case "node":return await(await import('fs/promises')).readdir(e);case "bun":return await(await import('fs/promises')).readdir(e);case "deno":{let r=[];for await(let s of Deno.readDir(e))r.push(s.name);return r}default:throw new R("Unsupported runtime")}}async ensureDirectoryExists(){if(await v.exists(this.options.directory)){this.wasDirectoryEnsured=true;return}await v.mkdir(this.options.directory,{recursive:true}),this.wasDirectoryEnsured=true;}};V();var Qr=class{isBun;clientInitialized=false;options;constructor(e){this.options=e,this.isBun=M.type==="bun";}async getDownloadUrl(e,t=3600){if(await this.ensureClient(),this.options.cloudfrontOptions){let{domainName:r,keyPairId:s,privateKey:i}=this.options.cloudfrontOptions,n=`https://${r}/${e}`,a=new Date(Date.now()+t*1e3).toISOString();return this.cloudfrontSignerLib.getSignedUrl({url:n,keyPairId:s,privateKey:i,dateLessThan:a})}if(this.isBun)return this.bunS3Client.file(e).presign({method:"GET",expiresIn:t});throw new R("getDownloadUrl requires CloudFront configuration on Node.js/Deno")}async getUploadUrl(e,t=3600){if(await this.ensureClient(),this.isBun)return this.bunS3Client.file(e).presign({method:"PUT",expiresIn:t});let r=new this.s3Lib.PutObjectCommand({Bucket:this.options.s3ClientConfig.bucketName,Key:e});return this.s3PresignerLib.getSignedUrl(this.s3Client,r,{expiresIn:t})}async getPublicUrl(e){await this.ensureClient();let{region:t,endpoint:r}=this.options.s3ClientConfig,s=this.options.s3ClientConfig.bucketName;return r?`${typeof r=="string"?r:r.toString()}/${s}/${e}`:`https://${s}.s3.${t}.amazonaws.com/${e}`}async listObjects(e){await this.ensureAwsSdk();let t=new this.s3Lib.ListObjectsV2Command({Bucket:this.options.s3ClientConfig.bucketName,Prefix:e});return (await this.s3Client.send(t)).Contents?.map(s=>s.Key).filter(Boolean)??[]}async getObject(e,t="raw"){if(await this.ensureClient(),this.isBun)try{let s=this.bunS3Client.file(e);if(!await s.exists())throw new Z(e);switch(t){case "raw":{let a=await s.arrayBuffer();return new Uint8Array(a)}case "text":return await s.text();case "stream":return s.stream();default:throw new R("Invalid return type")}}catch(s){throw s instanceof Z?s:s&&typeof s=="object"&&"code"in s&&(s.code==="NoSuchKey"||s.code==="NotFound")?new Z(e):s}let r=new this.s3Lib.GetObjectCommand({Bucket:this.options.s3ClientConfig.bucketName,Key:e});try{let s=await this.s3Client.send(r);if(!s.Body)throw new Z(e);switch(t){case "raw":return await s.Body.transformToByteArray();case "text":return await s.Body.transformToString();case "stream":return s.Body.transformToWebStream();default:throw new R("Invalid return type")}}catch(s){throw s&&typeof s=="object"&&"name"in s&&s.name==="NoSuchKey"?new Z(e):s}}async putObject(e,t,r){if(await this.ensureClient(),this.isBun){await this.bunS3Client.file(e).write(t,{type:r});return}let s=new this.s3Lib.PutObjectCommand({Bucket:this.options.s3ClientConfig.bucketName,Key:e,Body:t,ContentType:r});await this.s3Client.send(s);}async deleteObject(e){if(await this.ensureClient(),this.isBun){await this.bunS3Client.file(e).delete();return}let t=new this.s3Lib.DeleteObjectCommand({Bucket:this.options.s3ClientConfig.bucketName,Key:e});await this.s3Client.send(t);}async ensureClient(){this.clientInitialized||(this.isBun?await this.ensureBunClient():await this.ensureAwsSdk(),this.options.cloudfrontOptions&&(this.cloudfrontSignerLib=await import('@aws-sdk/cloudfront-signer').then(e=>e.default??e).catch(()=>{throw new R("Library not installed: @aws-sdk/cloudfront-signer, try run npm install @aws-sdk/cloudfront-signer")})),this.clientInitialized=true);}async ensureBunClient(){if(this.bunS3Client)return;let e=this.options.s3ClientConfig,t=typeof e.credentials=="function"?await e.credentials():e.credentials,r=typeof e.endpoint=="string"?e.endpoint:e.endpoint?.toString(),s=globalThis.Bun.S3Client;this.bunS3Client=new s({accessKeyId:t?.accessKeyId,secretAccessKey:t?.secretAccessKey,sessionToken:t?.sessionToken,region:e.region,endpoint:r,bucket:e.bucketName});}async ensureAwsSdk(){this.s3Lib||(this.s3Lib=await import('@aws-sdk/client-s3').then(e=>e.default??e).catch(()=>{throw new R("Library not installed: @aws-sdk/client-s3, try run npm install @aws-sdk/client-s3")}),this.s3PresignerLib=await import('@aws-sdk/s3-request-presigner').then(e=>e.default??e).catch(()=>{throw new R("Library not installed: @aws-sdk/s3-request-presigner, try run npm install @aws-sdk/s3-request-presigner")}),this.s3Client=new this.s3Lib.S3Client(this.options.s3ClientConfig??{}));}};var Ur=class{providerOptions;defaultProvider;providerMap;constructor(e,t){this.providerOptions=e,this.defaultProvider=t.defaultProvider,this.providerMap=new Map(Object.entries(e).map(([r,s])=>[r,s]));}use(e){let t=this.providerMap.get(e);if(!t)throw new Error(`[Storage] Provider ${String(e)} not found`);return t}async getDownloadUrl(e,t){return this.providerOptions[this.defaultProvider].getDownloadUrl(e,t)}async getUploadUrl(e,t){return this.providerOptions[this.defaultProvider].getUploadUrl(e,t)}async getPublicUrl(e){return this.providerOptions[this.defaultProvider].getPublicUrl(e)}async listObjects(e){return this.providerOptions[this.defaultProvider].listObjects(e)}async getObject(e,t="raw"){return this.providerOptions[this.defaultProvider].getObject(e,t)}async putObject(e,t,r){return this.providerOptions[this.defaultProvider].putObject(e,t,r)}async deleteObject(e){return this.providerOptions[this.defaultProvider].deleteObject(e)}};var Ut=class{async render(e,t){return await this.ensureHandlebars(),this.handlebars.compile(e)(t)}async renderFromFile(e,t){let r=await v.readFile(e,{encoding:"utf8"});return this.render(r,t)}async registerHelper(e,t){await this.ensureHandlebars(),this.handlebars.registerHelper(e,t);}async registerPartial(e,t){await this.ensureHandlebars(),this.handlebars.registerPartial(e,t);}async ensureHandlebars(){if(this.handlebars)return;let t=await import('handlebars').catch(()=>{throw new R("Library not installed: handlebars, try run npm install handlebars @types/handlebars")});this.handlebars=t.default?.default||t.default||t;}};var zt=class{async render(e,t){return await this.ensureEdge(),this.edge.renderRaw(e,t)}async renderFromFile(e,t){return await this.ensureEdge(),this.edge.render(e,t)}async global(e,t){await this.ensureEdge(),this.edge.global(e,t);}async registerTag(e){await this.ensureEdge(),this.edge.registerTag(e);}async ensureEdge(){if(this.edge)return;let e=await import('edge.js').catch(()=>{throw new R("Library not installed: edge.js, try run npm install edge.js")}),{Edge:t}=e;this.edge=new t;}};var Gt=class{partials={};async render(e,t){return await this.ensureMustache(),this.mustache.render(e,t,this.partials)}async renderFromFile(e,t){let r=await v.readFile(e,{encoding:"utf8"});return this.render(r,t)}registerPartial(e,t){this.partials[e]=t;}async ensureMustache(){if(this.mustache)return;let e=await import('mustache').catch(()=>{throw new R("Library not installed: mustache, try run npm install mustache @types/mustache")});this.mustache=e.default||e;}};var Jt=class{options;constructor(e={}){this.options=e;}async render(e,t){return await this.ensureEjs(),this.ejs.render(e,t,this.options)}async renderFromFile(e,t){return await this.ensureEjs(),this.ejs.renderFile(e,t,this.options)}async ensureEjs(){if(this.ejs)return;let e=await import('ejs').catch(()=>{throw new R("Library not installed: ejs, try run npm install ejs @types/ejs")});this.ejs=e.default||e;}};var Vt=class{helpers=new Map;render(e,t){return e.replace(/\{\{(\w+)(?::(\w+))?\}\}/g,(r,s,i)=>{let n=t[s];return n===void 0?r:i&&this.helpers.has(i)?this.helpers.get(i)(n):String(n)})}async renderFromFile(e,t){let r=await v.readFile(e,{encoding:"utf8"});return this.render(r,t)}registerHelper(e,t){this.helpers.set(e,t);}};var Be=class{options={};templateOptions;from(e){return this.options.from=e,this}to(e){return this.options.to=e,this}cc(e){return this.options.cc=e,this}bcc(e){return this.options.bcc=e,this}subject(e){return this.options.subject=e,this}text(e){return this.options.text=e,this}html(e){return this.options.html=e,this}template(e,t){return this.templateOptions={template:e,data:t,isFilePath:false},this}templateFile(e,t){return this.templateOptions={template:e,data:t,isFilePath:true},this}attachment(e){return this.options.attachments||(this.options.attachments=[]),this.options.attachments.push(e),this}attachments(e){return this.options.attachments||(this.options.attachments=[]),this.options.attachments.push(...e),this}hasTemplate(){return !!this.templateOptions}isTemplateFile(){return !!this.templateOptions?.isFilePath}build(){if(!this.options.to)throw new Error("[MailOptionsBuilder] 'to' field is required");if(!this.options.subject)throw new Error("[MailOptionsBuilder] 'subject' field is required");if(this.templateOptions){let{text:e,html:t,...r}=this.options;return {...r,template:this.templateOptions.template,data:this.templateOptions.data,isFilePath:this.templateOptions.isFilePath}}return this.options}};var pt=class extends R{constructor(e){super(e),this.name="MailerError";}},ut=class extends pt{constructor(e){super(`[Mailer] Provider '${e}' not found`),this.name="ProviderNotFoundError";}},Wt=class extends pt{constructor(){super("[MailProvider] Template adapter not configured for this provider"),this.name="TemplateAdapterNotConfiguredError";}},Kt=class extends pt{constructor(e){super(`[Mailer] Default provider '${e}' not found in provider options`),this.name="InvalidDefaultProviderError";}};var mt=class{transporter;templateAdapter;defaultFrom;constructor(e){this.transporter=e.transporter,this.templateAdapter=e.templateAdapter,this.defaultFrom=e.from;}async send(e){let t=new Be,s=e(t)??t,i=s.build();return s.hasTemplate()?this.sendWithTemplate(i):this.sendDirect(i)}async sendDirect(e){let t={...e,from:e.from||this.defaultFrom};return this.transporter.sendMail(t)}async sendWithTemplate(e){if(!this.templateAdapter)throw new Wt;let t=e.isFilePath?await this.templateAdapter.renderFromFile(e.template,e.data):await this.templateAdapter.render(e.template,e.data),r={...e,html:t,from:e.from||this.defaultFrom};await this.sendDirect(r);}async verify(){return this.transporter.verify()}};var zr=class{defaultProvider;providerMap;emailQueue=null;queueInitialized=false;constructor(e,t){if(!e[t.defaultProvider])throw new Kt(String(t.defaultProvider));this.defaultProvider=t.defaultProvider,this.providerMap=new Map(Object.keys(e).map(r=>[r,new mt(e[r])]));}use(e){let t=this.providerMap.get(e);if(!t)throw new ut(String(e));return t}async send(e){return this.getDefaultProvider().send(e)}async later(e){await this.initializeQueue();let t=new Be,s=e(t)??t,i=s.build(),n=s.hasTemplate();await this.emailQueue.publish({options:i,isTemplate:n});}async initializeQueue(){this.queueInitialized||(this.emailQueue=wr("mailer-emails"),await this.emailQueue.subscribe(async e=>{await this.processEmail(e);}),this.queueInitialized=true);}async processEmail(e){try{await this.getDefaultProvider().send(r=>{let s=e.options;if(r.to(s.to).subject(s.subject),s.from&&r.from(s.from),s.cc&&r.cc(s.cc),s.bcc&&r.bcc(s.bcc),"text"in s&&s.text&&r.text(s.text),"html"in s&&s.html&&r.html(s.html),s.attachments&&r.attachments(s.attachments),e.isTemplate){let i=s;i.isFilePath?r.templateFile(i.template,i.data):r.template(i.template,i.data);}}),await new Promise(r=>setTimeout(r,1e3));}catch(t){console.error("[Mailer] Failed to send queued email:",t);}}async verify(){return this.getDefaultProvider().verify()}getDefaultProvider(){let e=this.providerMap.get(this.defaultProvider);if(!e)throw new ut(String(this.defaultProvider));return e}};var Gr=class{};var Jr=o=>(e,t)=>(r,s,i)=>{let n={scope:e,handler:t,manager:o};if(typeof s>"u"){let l=O.get(r.prototype,"__class__");return l||(l={policies:[]}),l.policies||(l.policies=[]),l.policies.push(n),O.set(r.prototype,"__class__",l),r}let a=O.get(r,s);return a||(a={policies:[]}),a.policies||(a.policies=[]),a.policies.push(n),O.set(r,s,a),i};var Vr=class{providers;constructor(e){this.providers=e;}createDecorator(){return Jr(this)}canAccess(e,t,...r){let s=this.providers[e];if(!s)throw new R(`Policy provider for ${String(e)} not found`);return s[t](...r)}};var Lg=_,Ng=Qt;
1229
+ `}function zs(o,e){let t=[],r=/:([a-zA-Z0-9_]+)/g,s;for(;(s=r.exec(o))!==null;){let i=s[1],n={type:"string"};e&&e.shape&&e.shape[i]&&(n=ye(e.shape[i])||{type:"string"}),t.push({name:i,in:"path",required:true,schema:n});}return t}var Lr=o=>async(e,t,r)=>{e.timeout=false;let s=setTimeout(()=>{e.timeout=true;},o.ms);try{await r();}finally{clearTimeout(s);}};var Nr=o=>{let e=o?.header??"x-forwarded-for",t=o?.trust??true,r=o?.hop??"first";return async(s,i,n)=>{if(!t)return n();let a=s.rawHeaders.get(e);if(a&&typeof a=="string"){let l=a.split(",").map(p=>p.trim()).filter(Boolean);l.length&&(s.ip=r==="first"?l[0]:l[l.length-1]);}return n()}};var Nt=class{port;hostname;host;routes;tapOptions;graphql;ensureGraphQLHandler;constructor(e){this.routes=e?.routes??[],this.port=e?.port??80,this.hostname=e?.host??"0.0.0.0",this.host=e?.host??"0.0.0.0",this.tapOptions=e?.tapOptions,this.graphql=e?.graphql??new ie,this.ensureGraphQLHandler=ge(this.graphql);}get url(){return `http://${this.host}:${this.port}`}listen(){let e=this.tapOptions?.bun,{fetch:t,websocket:r,...s}=e??{},i=this.graphql.isEnabled,n="/graphql";this.runtimeServer=Bun.serve({port:this.port,hostname:this.hostname,fetch:async(a,l)=>{let p=a.url,c=p.indexOf("://")+3,d=p.indexOf("/",c),u=d===-1?"/":p.slice(d),h=u.indexOf("?"),m=h===-1?u:u.slice(0,h),f=h===-1?"":u.slice(h+1),g=_.find(a.method,m),y=ne.fromRequest(a);if(y.params=g?.params??{},y.setQueryString(f),y.setBunIpExtractor(a,l),await t?.call(this,y,l),i&&m.startsWith(n)){let w=await this.ensureGraphQLHandler();if(w){let b=y.toWebApi();return At(w.server,b,a.method,f,{req:y,server:l})}}if(r&&y.rawHeaders.get("upgrade")==="websocket"){let w=y.toWebApi();if(l.upgrade(w,{data:{}}))return}let P=new Q;return g?.responseSchemas&&P.setRouteResponseSchemas(g.responseSchemas),await fe(g?.middleware??[],g?.handler??((w,b)=>{b.notFound({...N(new J(w.url,w.method))});}),y,P),Q.toWebResponse(P)},...r?{websocket:r}:{},...s});}async close(){this.runtimeServer&&await this.runtimeServer.stop();}};var It=class{graphql;ensureGraphQLHandler;constructor(e){this.routes=e?.routes??[],this.port=e?.port??80,this.hostname=e?.host??"0.0.0.0",this.host=e?.host??"0.0.0.0",this.tapOptions=e?.tapOptions,this.graphql=e?.graphql??new ie,this.ensureGraphQLHandler=ge(this.graphql);}get url(){return `http://${this.host}:${this.port}`}listen(){let e=this.tapOptions?.deno,{handler:t,...r}=e??{},s=this.graphql.isEnabled,i="/graphql";this.runtimeServer=Deno.serve({port:this.port,hostname:this.hostname,handler:async(n,a)=>{let l=n.url,p=l.indexOf("://")+3,c=l.indexOf("/",p),d=c===-1?"/":l.slice(c),u=d.indexOf("?"),h=u===-1?d:d.slice(0,u),m=u===-1?"":d.slice(u+1),f=_.find(n.method,h),g=ne.fromRequest(n);if(g.params=f?.params??{},g.setQueryString(m),g.setDenoIpExtractor(n,a),await t?.(n,a))return new globalThis.Response(null,{status:426});if(s&&h.startsWith(i)){let w=await this.ensureGraphQLHandler();if(w){let b=g.toWebApi();return At(w.server,b,n.method,m,{req:g,info:a})}}if(g.rawHeaders.get("upgrade")==="websocket"&&this.tapOptions?.deno?.websocket){let w=g.toWebApi(),{socket:b,response:k}=Deno.upgradeWebSocket(w);return this.tapOptions?.deno?.websocket?.open&&(b.onopen=()=>this.tapOptions?.deno?.websocket?.open?.(b)),this.tapOptions?.deno?.websocket?.message&&(b.onmessage=A=>{this.tapOptions?.deno?.websocket?.message?.(b,A.data);}),this.tapOptions?.deno?.websocket?.close&&(b.onclose=()=>this.tapOptions?.deno?.websocket?.close?.(b)),k}let P=new Q;return f?.responseSchemas&&P.setRouteResponseSchemas(f.responseSchemas),await fe(f?.middleware??[],f?.handler??((w,b)=>{b.notFound({...N(new J(w.url,w.method))});}),g,P),Q.toWebResponse(P)},...r});}async close(){this.runtimeServer&&await this.runtimeServer.shutdown();}};var Ii=async(o,e)=>{let t=Readable.fromWeb(o);return pipeline(t,e)},Ft=class{port;host;routes;tapOptions;runtimeServer;nodeHttpClient;httpsOptions;graphql;ensureGraphQLHandler;needsHeaderFiltering;constructor(e){this.routes=e?.routes??[],this.port=e?.port??80,this.host=e?.host??"0.0.0.0",this.tapOptions=e?.tapOptions,this.nodeHttpClient=e?.nodeHttpClient??"http",this.httpsOptions=e?.nodeHttpClient==="https"||e?.nodeHttpClient==="http2-secure"?e?.httpsOptions:void 0,this.graphql=e?.graphql??new ie,this.ensureGraphQLHandler=ge(this.graphql),this.needsHeaderFiltering=this.nodeHttpClient==="http2"||this.nodeHttpClient==="http2-secure",this.createServerWithHandler();}get url(){return `${this.nodeHttpClient==="https"||this.nodeHttpClient==="http2-secure"?"https":"http"}://${this.host}:${this.port}`}createServerWithHandler(){let e=this.graphql.isEnabled,t="/graphql";this.runtimeServer=this.createServer(async(r,s)=>{if(this.tapOptions&&this.tapOptions.node){let h=this.tapOptions.node;await h?.(r);}let i=r.url,n=i.indexOf("?"),a=n===-1?i:i.slice(0,n),l=n===-1?"":i.slice(n+1);if(e&&a.startsWith(t)){let h=await this.ensureGraphQLHandler();if(h){let m=le(r.method)?await this.readRequestBody(r):"";await Ts(h.server,r.headers,r.method??"POST",m,l,{req:r},async(f,g,y)=>{for(let[P,S]of f)s.setHeader(P,S);if(s.statusCode=g,typeof y=="string")s.end(y);else {for await(let P of y)s.write(P);s.end();}});return}}let p=_.find(r.method,a),c=new ne;c.url=`${this.url}${i}`,c.method=r.method,le(r.method)&&c.setNodeRequest(r),c.setRawHeaders(r.headers,this.needsHeaderFiltering),c.setIpExtractor(r),c.setQueryString(l),c.params=p?.params??{};let d=new Q;d.nodeResponse=s,p?.responseSchemas&&d.setRouteResponseSchemas(p.responseSchemas);let u=fe(p?.middleware??[],p?.handler??((h,m)=>{m.notFound({...N(new J(h.url,h.method))});}),c,d);u instanceof Q?this.writeResponse(u,s):u.then(h=>this.writeResponse(h,s));});}listen(){this.runtimeServer.listen(this.port,this.host);}writeResponse(e,t){if(t.headersSent||t.writableEnded)return;let r=e.getBody();if(r instanceof ReadableStream){t.writeHead(e.responseStatus,e.headers),Ii(r,t);return}t.writeHead(e.responseStatus,e.headers),r instanceof Buffer||r instanceof Uint8Array||typeof r=="string"?t.end(r):e.headers["Content-Type"]==="application/json"?t.end(typeof r=="string"?r:JSON.stringify(r)):t.end(r!=null?String(r):void 0);}async close(){return new Promise((e,t)=>{this.runtimeServer.close(r=>{r&&"code"in r&&r.code!=="ERR_SERVER_NOT_RUNNING"?t(r):e();});})}processHeaders(e){let t={};if(this.needsHeaderFiltering){for(let s in e){if(s.charCodeAt(0)===58)continue;let i=e[s];i!==void 0&&(t[s]=Array.isArray(i)?i.join(", "):i);}return t}for(let r in e){let s=e[r];s!==void 0&&(t[r]=Array.isArray(s)?s.join(", "):s);}return t}extractClientIp(e){let t=e.headers["x-forwarded-for"];return t?Array.isArray(t)?t[0].trim():t.split(",")[0].trim():e.socket.remoteAddress}async readRequestBody(e){return new Promise((t,r)=>{let s=[];e.on("data",i=>s.push(Buffer.from(i))),e.on("error",r),e.on("end",()=>t(Buffer.concat(s).toString()));})}createServer(e){if(this.nodeHttpClient==="http")return createServer(e);if(this.nodeHttpClient==="http2")return createServer$1(e);if(this.nodeHttpClient==="http2-secure"){if(!this.httpsOptions)throw new Error("httpsOptions (key, cert) are required when using http2-secure client");return createSecureServer(this.httpsOptions,e)}if(!this.httpsOptions)throw new Error("httpsOptions (key, cert) are required when using https client");return createServer$2(this.httpsOptions,e)}};var Dt=class{routes;server;constructor(e){this.server=this.getRuntimeServer(e),this.routes=this.server.routes;}get url(){return this.server.url}get port(){return this.server.port}set port(e){this.server.port=e;}get host(){return this.server.host}getServer(e){return this.server.runtimeServer}listen(){return this.server.listen()}async close(){return this.server.close()}getRuntimeServer(e){if(e?.runtime==="bun")return new Nt(e);if(e?.runtime==="node")return new Ft(e);if(e?.runtime==="deno")return new It(e);throw new Error("No server implementation found for runtime: "+e?.runtime)}};V();var Qt=class{_brand="BaldaServer";#t=new Ge;serverOptions;router=_;logger;isListening;isProduction;graphql;#r;#e;#a=[];#o=["node_modules"];#i;#l;#d=[];#u=[];constructor(e){this.#r=false,this.logger=(e?.logger??E).child({scope:"Balda"}),this.serverOptions={nodeHttpClient:e?.nodeHttpClient??"http",port:(e?.port??Number(this.#t.get("PORT")||"80"))||80,host:e?.host??this.#t.get("HOST")??"0.0.0.0",controllerPatterns:e?.controllerPatterns??[],plugins:e?.plugins??{},tapOptions:e?.tapOptions??{},swagger:e?.swagger??true,graphql:e?.graphql??void 0,abortSignal:e?.abortSignal},e?.ajvInstance&&j.setGlobalInstance(e.ajvInstance),this.#l=e?.nodeHttpClient==="https"||e?.nodeHttpClient==="http2-secure"?e.httpsOptions:void 0,this.isListening=false,this.isProduction=this.#t.get("NODE_ENV")==="production",this.graphql=new ie(this.serverOptions.graphql),this.#e=new Dt({routes:[],port:this.serverOptions.port,host:this.serverOptions.host,tapOptions:this.serverOptions.tapOptions,runtime:M.type,nodeHttpClient:this.serverOptions.nodeHttpClient,httpsOptions:this.#l,graphql:this.graphql}),this.setupAbortSignalHandler();}get protectedKeys(){let e=Object.getOwnPropertyNames(this),t=Object.getPrototypeOf(this),r=t?Object.getOwnPropertyNames(t):[];return Array.from(new Set([...e,...r]))}get url(){return this.#e.url}get port(){return this.#e.port}set port(e){if(this.isListening)throw new Error("Cannot change port while server is listening, please call `.close()` before changing the port");this.#e.port=e;}get host(){return this.#e.host}get routes(){return _.getRoutes()||[]}get fs(){return v}getEnvironment(){return this.#t.getEnvironment()}tmpDir(...e){return x.join("tmp",...e)}getNodeServer(){if(M.type!=="node")throw new Error("Server is not using node runtime, you can't call `.getNodeServer()`");return this.#e.getServer("node")}getBunServer(){if(M.type!=="bun")throw new Error("Server is not using bun runtime, you can't call `.getBunServer()`");return this.#e.getServer("bun")}getDenoServer(){if(M.type!=="deno")throw new Error("Server is not using deno runtime, you can't call `.getDenoServer()`");return this.#e.getServer("deno")}embed(e,t){if(typeof e!="string"||e.trim()==="")throw new Error(`Invalid key provided to embed: ${e}. Key must be a non-empty string.`);if(this.protectedKeys.includes(e)||e==="constructor")throw new Error(`Cannot embed value with key '${e}' as it conflicts with a protected server property`);Object.defineProperty(this,e,{value:t,writable:false,configurable:true,enumerable:true});}exit(e=0){Qe.exit(e);}on(e,t){switch(M.type){case "bun":case "node":process.on(e,t);break;case "deno":Deno.addSignalListener(e,t);break;default:throw new Error(`Unsupported runtime: ${M.type}, only node, bun and deno are supported`)}}once(e,t){switch(M.type){case "bun":case "node":process.once(e,t);break;case "deno":Deno.addSignalListener(e,t);break;default:throw new Error(`Unsupported runtime: ${M.type}, only node, bun and deno are supported`)}}use(...e){this.#a.push(...e);}useExpress(e,t){kr(this).use(e,t);}expressMiddleware(e){return $e(e)}mountExpressRouter(e,t){dt(e,t);}setErrorHandler(e){this.#a.unshift(async(t,r,s)=>{try{await s();}catch(i){await e?.(t,r,s,i);}});}setNotFoundHandler(e){this.#i=e?.bind(this);}setValidationErrorHandler(e){ss(e);}setPolicyErrorHandler(e){ps(e);}beforeStart(e){this.#d.push(e);}beforeClose(e){this.#u.push(e);}listen(e,t){let r=typeof e=="function"?e:t;if(typeof e=="number"&&Number.isFinite(e)&&(this.port=e),this.isListening)throw new Error("Server is already listening, you can't call `.listen()` multiple times");let s={port:this.port,host:this.host,url:this.url};this.bootstrap().then(async()=>{for(let i of this.#d)await i();this.#e.listen(),this.isListening=true,r?.({...s,error:void 0});}).catch(i=>{r?.({...s,error:i});});}async waitUntilListening(e){return e??=this.port,new Promise((t,r)=>{try{this.listen(e,()=>{t({port:this.port,host:this.host,url:this.url});});}catch(s){r(s);}})}async close(){await this.disconnect();}async disconnect(){if(!this.isListening){this.logger.warn("Trying to disconnect the server that is not listening, ignoring");return}try{for(let e of this.#u)await e();await this.#e.close();}catch(e){throw this.logger.error({error:e},"Error closing server connector"),e}finally{this.isListening=false;}}async getMockServer(e){return await this.bootstrap(e),new Ht(this)}async importControllers(e){let t=e??this.serverOptions.controllerPatterns;if(!(!t||t.length===0))try{let r=await Promise.all(t.map(async s=>v.glob(s,{cwd:L.getCwd()}))).then(s=>s.flat());r=r.flat(),r=r.filter(s=>!this.#o.some(i=>s.includes(i))),this.logger.debug(`Found ${r.length} controllers to import`),await Promise.all(r.map(async s=>{this.logger.debug(`Importing controller ${s}`),await import(s).catch(i=>{this.logger.error(`Error importing controller ${s}: ${i}`);});}));}catch(r){this.logger.warn(`Could not auto-import controllers: ${r instanceof Error?r.message:String(r)}`);}}applyPlugins(e){if(Array.isArray(e)){this.use(...e);return}Object.entries(e).forEach(([t,r])=>{switch(t){case "bodyParser":this.use(_s(r));break;case "cors":this.use(jr(r));break;case "static":this.use(Pr(r));break;case "helmet":this.use(Ar(r));break;case "cookie":this.use(Mr(r));break;case "methodOverride":this.use(Hr(r));break;case "compression":this.use(Er(r));break;case "log":this.use(_r(r));break;case "rateLimiter":let{keyOptions:s,storageOptions:i}=r;this.use($r(s,i));break;case "trustProxy":this.use(Nr(r));break;case "timeout":this.use(Lr(r));break;case "session":this.use(Br(r));break;case "asyncLocalStorage":this.use(Cr(r));break;case "cache":{let n=r,a;n.provider&&typeof n.provider=="object"&&"get"in n.provider?a=n.provider:n.provider==="redis"?a=new ct(n.redis):a=new at,this.use(xr(a,n));break}default:this.logger.warn(`Unknown plugin ${t}`);break}});}async bootstrap(e){this.#r||(await this.importControllers(e?.controllerPatterns),this.applyPlugins(this.serverOptions.plugins),this.serverOptions.swagger&&Gs(this.serverOptions.swagger),this.registerNotFoundRoutes(),this.#a.length&&_.applyGlobalMiddlewaresToAllRoutes(this.#a),this.#r=true);}handleNotFound=(e,t)=>{if(this.#i){this.#i(e,t);return}let r=new URL(e.url).pathname,s=["GET","POST","PUT","PATCH","DELETE"],i=[];for(let a of s){if(a===e.method.toUpperCase())continue;let l=_.find(a,r);l&&l.handler!==this.handleNotFound&&i.push(a);}if(i.length){t.setHeader("Allow",i.join(", "));let a=new Je(r,e.method);t.methodNotAllowed({...N(a)});return}let n=new J(r,e.method);t.notFound({...N(n)});};registerNotFoundRoutes(){let e=["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"];for(let t of e)_.addOrUpdate(t,"*",[],this.handleNotFound,{},{excludeFromSwagger:true},void 0,true);}setupAbortSignalHandler(){if(!this.serverOptions.abortSignal)return;let e=this.serverOptions.abortSignal;if(e.aborted){this.logger.warn("AbortSignal was already aborted, server will not start");return}e.addEventListener("abort",async()=>{this.logger.info("AbortSignal received, shutting down server gracefully");try{await this.disconnect(),this.logger.info("Server shutdown completed");}catch(t){this.logger.error({error:t},"Error during server shutdown from abort signal");}});}};var Ir=class{ITERATIONS=6e5;SALT_LENGTH=16;KEY_LENGTH=256;configure(e){if(e.iterations!==void 0){if(e.iterations<1)throw new Error("Iterations must be at least 1");this.ITERATIONS=e.iterations;}if(e.saltLength!==void 0){if(e.saltLength<8)throw new Error("Salt length must be at least 8 bytes");this.SALT_LENGTH=e.saltLength;}if(e.keyLength!==void 0){if(e.keyLength<128)throw new Error("Key length must be at least 128 bits");this.KEY_LENGTH=e.keyLength;}}async hash(e){if(!e)throw new Error("Data to hash cannot be empty");let r=new TextEncoder().encode(e),s=crypto.getRandomValues(new Uint8Array(this.SALT_LENGTH)),i=await crypto.subtle.importKey("raw",r,{name:"PBKDF2"},false,["deriveBits"]),n=await crypto.subtle.deriveBits({name:"PBKDF2",salt:s,iterations:this.ITERATIONS,hash:"SHA-256"},i,this.KEY_LENGTH),a=this.encodeBase64(s),l=this.encodeBase64(new Uint8Array(n));return `${a}:${l}`}async compare(e,t){if(!e||!t)return false;try{let s=new TextEncoder().encode(t),i=e.split(":");if(i.length!==2)throw new Error("Invalid hash format");let[n,a]=i,l=this.decodeBase64(n),p=this.decodeBase64(a),c=await crypto.subtle.importKey("raw",s,{name:"PBKDF2"},!1,["deriveBits"]),d=await crypto.subtle.deriveBits({name:"PBKDF2",salt:l,iterations:this.ITERATIONS,hash:"SHA-256"},c,this.KEY_LENGTH),u=new Uint8Array(d);if(u.length!==p.length)return !1;let h=0;for(let m=0;m<u.length;m++)h|=u[m]^p[m];return h===0}catch{return false}}encodeBase64(e){let t="",r=e.byteLength;for(let s=0;s<r;s++)t+=String.fromCharCode(e[s]);return btoa(t)}decodeBase64(e){let t=atob(e),r=t.length,s=new Uint8Array(r);for(let i=0;i<r;i++)s[i]=t.charCodeAt(i);return s}},Fi=new Ir;var Js=()=>{let o=j.getCacheStats(),e=o.schemaCount*3,t=e,r=s=>s<1024?`~${s}KB`:`~${(s/1024).toFixed(2)}MB`;return {validators:{size:o.schemaCount,description:"Compiled schemas stored in Ajv for validation and serialization"},totalSchemaReferences:o.totalRefsCreated,memoryEstimate:{validators:r(e),total:r(t)}}},Di=()=>{let o=Js();E.info({validators:o.validators.size,totalSchemaRefs:o.totalSchemaReferences,memoryEstimate:o.memoryEstimate.total},"Schema cache metrics");},Qi=()=>{j.clearAllCaches(),E.debug("All schema caches cleared");};var Z=class extends R{constructor(e){super(`File not found: ${e}`);}};var Fr=class{constructor(e){this.options=e;}async getDownloadUrl(e,t=3600){await this.ensureClient();let r=this.containerClient.getBlockBlobClient(e),s=new Date(Date.now()-300*1e3),i=new Date(Date.now()+t*1e3),n=this.azureBlobLib.BlobSASPermissions.parse("r"),a=this.azureBlobLib.generateBlobSASQueryParameters({containerName:this.options.containerName,blobName:e,permissions:n,startsOn:s,expiresOn:i},this.sharedKeyCredential).toString();return `${r.url}?${a}`}async getUploadUrl(e,t=3600){await this.ensureClient();let r=this.containerClient.getBlockBlobClient(e),s=new Date(Date.now()-300*1e3),i=new Date(Date.now()+t*1e3),n=this.azureBlobLib.BlobSASPermissions.parse("w"),a=this.azureBlobLib.generateBlobSASQueryParameters({containerName:this.options.containerName,blobName:e,permissions:n,startsOn:s,expiresOn:i},this.sharedKeyCredential).toString();return `${r.url}?${a}`}async getPublicUrl(e){return await this.ensureClient(),this.containerClient.getBlockBlobClient(e).url}async listObjects(e){await this.ensureClient();let t=[],r=e?e.endsWith("/")?e:`${e}/`:void 0;for await(let s of this.containerClient.listBlobsFlat({prefix:r}))t.push(s.name);return t}async getObject(e,t="raw"){await this.ensureClient();try{let s=await this.containerClient.getBlockBlobClient(e).download();if(!s.readableStreamBody)throw new Z(e);let i=t;if(i==="stream")return Readable.toWeb(s.readableStreamBody);let n=[];for await(let l of s.readableStreamBody)n.push(Buffer.isBuffer(l)?l:Buffer.from(l));let a=Buffer.concat(n);switch(i){case "raw":return new Uint8Array(a);case "text":return a.toString();default:throw new R("Invalid return type")}}catch(r){throw r&&typeof r=="object"&&"statusCode"in r&&r.statusCode===404?new Z(e):r}}async putObject(e,t,r){await this.ensureClient();let s=this.containerClient.getBlockBlobClient(e),i=t;await s.upload(i,i.length,{blobHTTPHeaders:{blobContentType:r||"application/octet-stream"}});}async deleteObject(e){await this.ensureClient();let t=this.containerClient.getBlockBlobClient(e);try{await t.delete();}catch(r){if(r&&typeof r=="object"&&"statusCode"in r&&r.statusCode===404)return;throw r}}async ensureClient(){if(this.azureBlobLib)return;this.azureBlobLib=await import('@azure/storage-blob').catch(()=>{throw new R("Library not installed: @azure/storage-blob, try run npm install @azure/storage-blob")}),this.blobServiceClient=this.azureBlobLib.BlobServiceClient.fromConnectionString(this.options.connectionString),this.containerClient=this.blobServiceClient.getContainerClient(this.options.containerName);let e=this.blobServiceClient.credential;if(!(e instanceof this.azureBlobLib.StorageSharedKeyCredential))throw new R("BlobStorage requires a shared key credential to generate SAS URLs");this.sharedKeyCredential=e;}};var Dr=class{constructor(e){this.options=e;}wasDirectoryEnsured=false;async getDownloadUrl(e,t=3600){throw new R("LocalStorageProvider does not support getDownloadUrl. Use S3 or Azure Blob storage for signed URLs.")}async getUploadUrl(e,t=3600){throw new R("LocalStorageProvider does not support getUploadUrl. Use S3 or Azure Blob storage for signed URLs.")}async getPublicUrl(e){throw new R("`getPublicUrl` is not available in local storage provider")}async listObjects(e){this.wasDirectoryEnsured||await this.ensureDirectoryExists();let t=x.resolve(this.options.directory),r=e?x.join(t,e):t;if(!await v.exists(r))return [];let i=[];return await this.listFilesRecursively(r,t,i),i}async getObject(e,t="raw"){this.wasDirectoryEnsured||await this.ensureDirectoryExists();let r=x.join(this.options.directory,e);if(!await v.exists(r))throw new Z(e);switch(t){case "raw":return await v.readFile(r);case "text":return await v.readFile(r,{encoding:"utf8"});case "stream":return await v.streamFile(r);default:throw new R("Invalid return type")}}async putObject(e,t,r){this.wasDirectoryEnsured||await this.ensureDirectoryExists();let s=x.join(this.options.directory,e),i=x.join(s,"..");await v.mkdir(i,{recursive:true}),await v.writeFile(s,t);}async deleteObject(e){this.wasDirectoryEnsured||await this.ensureDirectoryExists();let t=x.join(this.options.directory,e);await v.exists(t)&&await v.unlink(t);}async listFilesRecursively(e,t,r){let s=await v.stat(e);if(s.isFile){let n=e.replace(t,"").replace(/^\//,"");r.push(n);return}if(!s.isDirectory)return;let i=await this.readDirectory(e);for(let n of i){let a=x.join(e,n);await this.listFilesRecursively(a,t,r);}}async readDirectory(e){let{runtime:t}=await Promise.resolve().then(()=>(V(),Kr));switch(t.type){case "node":return await(await import('fs/promises')).readdir(e);case "bun":return await(await import('fs/promises')).readdir(e);case "deno":{let r=[];for await(let s of Deno.readDir(e))r.push(s.name);return r}default:throw new R("Unsupported runtime")}}async ensureDirectoryExists(){if(await v.exists(this.options.directory)){this.wasDirectoryEnsured=true;return}await v.mkdir(this.options.directory,{recursive:true}),this.wasDirectoryEnsured=true;}};V();var Qr=class{isBun;clientInitialized=false;options;constructor(e){this.options=e,this.isBun=M.type==="bun";}async getDownloadUrl(e,t=3600){if(await this.ensureClient(),this.options.cloudfrontOptions){let{domainName:r,keyPairId:s,privateKey:i}=this.options.cloudfrontOptions,n=`https://${r}/${e}`,a=new Date(Date.now()+t*1e3).toISOString();return this.cloudfrontSignerLib.getSignedUrl({url:n,keyPairId:s,privateKey:i,dateLessThan:a})}if(this.isBun)return this.bunS3Client.file(e).presign({method:"GET",expiresIn:t});throw new R("getDownloadUrl requires CloudFront configuration on Node.js/Deno")}async getUploadUrl(e,t=3600){if(await this.ensureClient(),this.isBun)return this.bunS3Client.file(e).presign({method:"PUT",expiresIn:t});let r=new this.s3Lib.PutObjectCommand({Bucket:this.options.s3ClientConfig.bucketName,Key:e});return this.s3PresignerLib.getSignedUrl(this.s3Client,r,{expiresIn:t})}async getPublicUrl(e){await this.ensureClient();let{region:t,endpoint:r}=this.options.s3ClientConfig,s=this.options.s3ClientConfig.bucketName;return r?`${typeof r=="string"?r:r.toString()}/${s}/${e}`:`https://${s}.s3.${t}.amazonaws.com/${e}`}async listObjects(e){await this.ensureAwsSdk();let t=new this.s3Lib.ListObjectsV2Command({Bucket:this.options.s3ClientConfig.bucketName,Prefix:e});return (await this.s3Client.send(t)).Contents?.map(s=>s.Key).filter(Boolean)??[]}async getObject(e,t="raw"){if(await this.ensureClient(),this.isBun)try{let s=this.bunS3Client.file(e);if(!await s.exists())throw new Z(e);switch(t){case "raw":{let a=await s.arrayBuffer();return new Uint8Array(a)}case "text":return await s.text();case "stream":return s.stream();default:throw new R("Invalid return type")}}catch(s){throw s instanceof Z?s:s&&typeof s=="object"&&"code"in s&&(s.code==="NoSuchKey"||s.code==="NotFound")?new Z(e):s}let r=new this.s3Lib.GetObjectCommand({Bucket:this.options.s3ClientConfig.bucketName,Key:e});try{let s=await this.s3Client.send(r);if(!s.Body)throw new Z(e);switch(t){case "raw":return await s.Body.transformToByteArray();case "text":return await s.Body.transformToString();case "stream":return s.Body.transformToWebStream();default:throw new R("Invalid return type")}}catch(s){throw s&&typeof s=="object"&&"name"in s&&s.name==="NoSuchKey"?new Z(e):s}}async putObject(e,t,r){if(await this.ensureClient(),this.isBun){await this.bunS3Client.file(e).write(t,{type:r});return}let s=new this.s3Lib.PutObjectCommand({Bucket:this.options.s3ClientConfig.bucketName,Key:e,Body:t,ContentType:r});await this.s3Client.send(s);}async deleteObject(e){if(await this.ensureClient(),this.isBun){await this.bunS3Client.file(e).delete();return}let t=new this.s3Lib.DeleteObjectCommand({Bucket:this.options.s3ClientConfig.bucketName,Key:e});await this.s3Client.send(t);}async ensureClient(){this.clientInitialized||(this.isBun?await this.ensureBunClient():await this.ensureAwsSdk(),this.options.cloudfrontOptions&&(this.cloudfrontSignerLib=await import('@aws-sdk/cloudfront-signer').then(e=>e.default??e).catch(()=>{throw new R("Library not installed: @aws-sdk/cloudfront-signer, try run npm install @aws-sdk/cloudfront-signer")})),this.clientInitialized=true);}async ensureBunClient(){if(this.bunS3Client)return;let e=this.options.s3ClientConfig,t=typeof e.credentials=="function"?await e.credentials():e.credentials,r=typeof e.endpoint=="string"?e.endpoint:e.endpoint?.toString(),s=globalThis.Bun.S3Client;this.bunS3Client=new s({accessKeyId:t?.accessKeyId,secretAccessKey:t?.secretAccessKey,sessionToken:t?.sessionToken,region:e.region,endpoint:r,bucket:e.bucketName});}async ensureAwsSdk(){this.s3Lib||(this.s3Lib=await import('@aws-sdk/client-s3').then(e=>e.default??e).catch(()=>{throw new R("Library not installed: @aws-sdk/client-s3, try run npm install @aws-sdk/client-s3")}),this.s3PresignerLib=await import('@aws-sdk/s3-request-presigner').then(e=>e.default??e).catch(()=>{throw new R("Library not installed: @aws-sdk/s3-request-presigner, try run npm install @aws-sdk/s3-request-presigner")}),this.s3Client=new this.s3Lib.S3Client(this.options.s3ClientConfig??{}));}};var Ur=class{providerOptions;defaultProvider;providerMap;constructor(e,t){this.providerOptions=e,this.defaultProvider=t.defaultProvider,this.providerMap=new Map(Object.entries(e).map(([r,s])=>[r,s]));}use(e){let t=this.providerMap.get(e);if(!t)throw new Error(`[Storage] Provider ${String(e)} not found`);return t}async getDownloadUrl(e,t){return this.providerOptions[this.defaultProvider].getDownloadUrl(e,t)}async getUploadUrl(e,t){return this.providerOptions[this.defaultProvider].getUploadUrl(e,t)}async getPublicUrl(e){return this.providerOptions[this.defaultProvider].getPublicUrl(e)}async listObjects(e){return this.providerOptions[this.defaultProvider].listObjects(e)}async getObject(e,t="raw"){return this.providerOptions[this.defaultProvider].getObject(e,t)}async putObject(e,t,r){return this.providerOptions[this.defaultProvider].putObject(e,t,r)}async deleteObject(e){return this.providerOptions[this.defaultProvider].deleteObject(e)}};var Ut=class{async render(e,t){return await this.ensureHandlebars(),this.handlebars.compile(e)(t)}async renderFromFile(e,t){let r=await v.readFile(e,{encoding:"utf8"});return this.render(r,t)}async registerHelper(e,t){await this.ensureHandlebars(),this.handlebars.registerHelper(e,t);}async registerPartial(e,t){await this.ensureHandlebars(),this.handlebars.registerPartial(e,t);}async ensureHandlebars(){if(this.handlebars)return;let t=await import('handlebars').catch(()=>{throw new R("Library not installed: handlebars, try run npm install handlebars @types/handlebars")});this.handlebars=t.default?.default||t.default||t;}};var zt=class{async render(e,t){return await this.ensureEdge(),this.edge.renderRaw(e,t)}async renderFromFile(e,t){return await this.ensureEdge(),this.edge.render(e,t)}async global(e,t){await this.ensureEdge(),this.edge.global(e,t);}async registerTag(e){await this.ensureEdge(),this.edge.registerTag(e);}async ensureEdge(){if(this.edge)return;let e=await import('edge.js').catch(()=>{throw new R("Library not installed: edge.js, try run npm install edge.js")}),{Edge:t}=e;this.edge=new t;}};var Gt=class{partials={};async render(e,t){return await this.ensureMustache(),this.mustache.render(e,t,this.partials)}async renderFromFile(e,t){let r=await v.readFile(e,{encoding:"utf8"});return this.render(r,t)}registerPartial(e,t){this.partials[e]=t;}async ensureMustache(){if(this.mustache)return;let e=await import('mustache').catch(()=>{throw new R("Library not installed: mustache, try run npm install mustache @types/mustache")});this.mustache=e.default||e;}};var Jt=class{options;constructor(e={}){this.options=e;}async render(e,t){return await this.ensureEjs(),this.ejs.render(e,t,this.options)}async renderFromFile(e,t){return await this.ensureEjs(),this.ejs.renderFile(e,t,this.options)}async ensureEjs(){if(this.ejs)return;let e=await import('ejs').catch(()=>{throw new R("Library not installed: ejs, try run npm install ejs @types/ejs")});this.ejs=e.default||e;}};var Vt=class{helpers=new Map;render(e,t){return e.replace(/\{\{(\w+)(?::(\w+))?\}\}/g,(r,s,i)=>{let n=t[s];return n===void 0?r:i&&this.helpers.has(i)?this.helpers.get(i)(n):String(n)})}async renderFromFile(e,t){let r=await v.readFile(e,{encoding:"utf8"});return this.render(r,t)}registerHelper(e,t){this.helpers.set(e,t);}};var Be=class{options={};templateOptions;from(e){return this.options.from=e,this}to(e){return this.options.to=e,this}cc(e){return this.options.cc=e,this}bcc(e){return this.options.bcc=e,this}subject(e){return this.options.subject=e,this}text(e){return this.options.text=e,this}html(e){return this.options.html=e,this}template(e,t){return this.templateOptions={template:e,data:t,isFilePath:false},this}templateFile(e,t){return this.templateOptions={template:e,data:t,isFilePath:true},this}attachment(e){return this.options.attachments||(this.options.attachments=[]),this.options.attachments.push(e),this}attachments(e){return this.options.attachments||(this.options.attachments=[]),this.options.attachments.push(...e),this}hasTemplate(){return !!this.templateOptions}isTemplateFile(){return !!this.templateOptions?.isFilePath}build(){if(!this.options.to)throw new Error("[MailOptionsBuilder] 'to' field is required");if(!this.options.subject)throw new Error("[MailOptionsBuilder] 'subject' field is required");if(this.templateOptions){let{text:e,html:t,...r}=this.options;return {...r,template:this.templateOptions.template,data:this.templateOptions.data,isFilePath:this.templateOptions.isFilePath}}return this.options}};var pt=class extends R{constructor(e){super(e),this.name="MailerError";}},ut=class extends pt{constructor(e){super(`[Mailer] Provider '${e}' not found`),this.name="ProviderNotFoundError";}},Wt=class extends pt{constructor(){super("[MailProvider] Template adapter not configured for this provider"),this.name="TemplateAdapterNotConfiguredError";}},Kt=class extends pt{constructor(e){super(`[Mailer] Default provider '${e}' not found in provider options`),this.name="InvalidDefaultProviderError";}};var mt=class{transporter;templateAdapter;defaultFrom;constructor(e){this.transporter=e.transporter,this.templateAdapter=e.templateAdapter,this.defaultFrom=e.from;}async send(e){let t=new Be,s=e(t)??t,i=s.build();return s.hasTemplate()?this.sendWithTemplate(i):this.sendDirect(i)}async sendDirect(e){let t={...e,from:e.from||this.defaultFrom};return this.transporter.sendMail(t)}async sendWithTemplate(e){if(!this.templateAdapter)throw new Wt;let t=e.isFilePath?await this.templateAdapter.renderFromFile(e.template,e.data):await this.templateAdapter.render(e.template,e.data),r={...e,html:t,from:e.from||this.defaultFrom};await this.sendDirect(r);}async verify(){return this.transporter.verify()}};var zr=class{defaultProvider;providerMap;emailQueue=null;queueInitialized=false;constructor(e,t){if(!e[t.defaultProvider])throw new Kt(String(t.defaultProvider));this.defaultProvider=t.defaultProvider,this.providerMap=new Map(Object.keys(e).map(r=>[r,new mt(e[r])]));}use(e){let t=this.providerMap.get(e);if(!t)throw new ut(String(e));return t}async send(e){return this.getDefaultProvider().send(e)}async later(e){await this.initializeQueue();let t=new Be,s=e(t)??t,i=s.build(),n=s.hasTemplate();await this.emailQueue.publish({options:i,isTemplate:n});}async initializeQueue(){this.queueInitialized||(this.emailQueue=wr("mailer-emails"),await this.emailQueue.subscribe(async e=>{await this.processEmail(e);}),this.queueInitialized=true);}async processEmail(e){try{await this.getDefaultProvider().send(r=>{let s=e.options;if(r.to(s.to).subject(s.subject),s.from&&r.from(s.from),s.cc&&r.cc(s.cc),s.bcc&&r.bcc(s.bcc),"text"in s&&s.text&&r.text(s.text),"html"in s&&s.html&&r.html(s.html),s.attachments&&r.attachments(s.attachments),e.isTemplate){let i=s;i.isFilePath?r.templateFile(i.template,i.data):r.template(i.template,i.data);}}),await new Promise(r=>setTimeout(r,1e3));}catch(t){console.error("[Mailer] Failed to send queued email:",t);}}async verify(){return this.getDefaultProvider().verify()}getDefaultProvider(){let e=this.providerMap.get(this.defaultProvider);if(!e)throw new ut(String(this.defaultProvider));return e}};var Gr=class{};var Jr=o=>(e,t)=>(r,s,i)=>{let n={scope:e,handler:t,manager:o};if(typeof s>"u"){let l=O.get(r.prototype,"__class__");return l||(l={policies:[]}),l.policies||(l.policies=[]),l.policies.push(n),O.set(r.prototype,"__class__",l),r}let a=O.get(r,s);return a||(a={policies:[]}),a.policies||(a.policies=[]),a.policies.push(n),O.set(r,s,a),i};var Vr=class{providers;constructor(e){this.providers=e;}createDecorator(){return Jr(this)}canAccess(e,t,...r){let s=this.providers[e];if(!s)throw new R(`Policy provider for ${String(e)} not found`);return s[t](...r)}};var Lg=_,Ng=Qt;
1230
1230
  export{Fr as AzureBlobStorageProvider,yr as BaseCron,Gr as BasePlugin,tt as BullMQPubSub,ue as CACHE_STATUS_HEADER,Ze as CacheService,cr as CacheStatus,q as Command,kt as CommandRegistry,W as CronService,Vt as CustomAdapter,Ie as DEFAULT_CACHE_OPTIONS,zt as EdgeAdapter,Jt as EjsAdapter,ie as GraphQL,Ut as HandlebarsAdapter,Dr as LocalStorageProvider,Be as MailOptionsBuilder,mt as MailProvider,zr as Mailer,at as MemoryCacheProvider,rt as MemoryPubSub,De as MqttService,Gt as MustacheAdapter,st as PGBossPubSub,Vr as PolicyManager,oe as QueueManager,K as QueueService,ct as RedisCacheProvider,Qr as S3StorageProvider,ot as SQSPubSub,Qt as Server,Ur as Storage,$ as arg,Cr as asyncLocalStorage,Ve as asyncStorage,Io as bullmqQueue,oo as cache,xr as cacheMiddleware,Qi as clearAllSchemaCaches,Re as commandRegistry,Er as compression,Po as controller,Mr as cookie,jr as cors,kr as createExpressAdapter,Jr as createPolicyDecorator,Do as createQueue,xo as cron,hr as cronUIInstance,So as cronUi,Ng as default,Wo as defineMiddleware,Qo as defineQueueConfiguration,Ro as del,Fs as expressHandler,$e as expressMiddleware,C as flag,Co as get,Ye as getCacheService,Js as getSchemaCacheMetrics,Fi as hash,Ar as helmet,dr as initCacheService,_r as log,Di as logSchemaCacheMetrics,E as logger,wr as memoryQueue,Hr as methodOverride,jo as middleware,dt as mountExpressRouter,Lo as mqtt,Oo as patch,Fo as pgbossQueue,Eo as post,Mo as put,$r as rateLimiter,vo as resetCacheService,Lg as router,Ao as serialize,Pr as serveStatic,Br as session,bo as setCronGlobalErrorHandler,Bo as setMqttGlobalErrorHandler,No as sqsQueue,Lr as timeoutMw,Nr as trustProxy,Ho as validate};//# sourceMappingURL=index.js.map
1231
1231
  //# sourceMappingURL=index.js.map