balda 0.0.41 → 0.0.43

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
@@ -1,4 +1,5 @@
1
1
  import { TSchema, Static } from '@sinclair/typebox';
2
+ import { JSONSchema as JSONSchema$1, FromSchema } from 'json-schema-to-ts';
2
3
  import { ZodType, z } from 'zod';
3
4
  import { Ajv } from 'ajv';
4
5
  import { IncomingMessage, ServerResponse, Server as Server$2 } from 'node:http';
@@ -11,6 +12,7 @@ import { RequestHandler, Router as Router$1, IRouter } from 'express';
11
12
  import * as pino from 'pino';
12
13
  import pino__default, { pino as pino$1, Logger } from 'pino';
13
14
  import { glob } from 'node:fs/promises';
15
+ import cronstrueType from 'cronstrue';
14
16
  import { IClientSubscribeOptions, IClientOptions, IClientPublishOptions, MqttClient } from 'mqtt';
15
17
  import { SQSClientConfig, SendMessageCommandInput } from '@aws-sdk/client-sqs';
16
18
  import { Queue, JobsOptions, Job } from 'bullmq';
@@ -23,7 +25,7 @@ type AjvInstance = InstanceType<typeof Ajv>;
23
25
  type AjvCompileParams = Parameters<AjvInstance["compile"]>;
24
26
 
25
27
  type RequestSchema = ZodType | TSchema | AjvCompileParams[0];
26
- type ValidatedData<T extends RequestSchema> = T extends ZodType ? z.infer<T> : T extends TSchema ? Static<T> : T extends AjvCompileParams[0] ? unknown : unknown;
28
+ type ValidatedData<T extends RequestSchema> = T extends ZodType ? z.infer<T> : T extends TSchema ? Static<T> : T extends JSONSchema$1 ? JSONSchema$1 extends T ? Record<string, unknown> : FromSchema<T> : unknown;
27
29
  interface CustomValidationError {
28
30
  status?: number;
29
31
  message?: string;
@@ -60,7 +62,7 @@ type ExtractParams<T extends string> = T extends `${infer _Start}:${infer Param}
60
62
  /**
61
63
  * Helper type to infer the output type from a Zod schema, TypeBox schema, or any schema with _output
62
64
  */
63
- type InferSchemaType<T> = T extends ZodType ? z.infer<T> : T extends TSchema ? Static<T> : any;
65
+ type InferSchemaType<T> = T extends ZodType ? z.infer<T> : T extends TSchema ? Static<T> : T extends JSONSchema$1 ? JSONSchema$1 extends T ? Record<string, unknown> : FromSchema<T> : any;
64
66
  /**
65
67
  * Maps a responses object (e.g. { 200: ZodSchema, 404: TypeBoxSchema }) to
66
68
  * an inferred type map (e.g. { 200: InferredType200, 404: InferredType404 }).
@@ -249,11 +251,27 @@ declare class Request<Params extends Record<string, string> = any, TBody = unkno
249
251
  * If body parser middleware is not used, this will be undefined.
250
252
  *
251
253
  * Type is `unknown` by default to enforce validation or casting before use.
254
+ * The body type is automatically inferred from the schema provided in the route options or decorator,
255
+ * supporting Zod (`z.infer<T>`), TypeBox (`Static<T>`), and plain JSON schemas (`FromSchema<T>` — requires `as const`).
252
256
  * @imperative while using router directly, when using body property, the type is inferred from the schema provided in the route options.
253
- * @example
257
+ * @example Zod schema
254
258
  * ```typescript
255
259
  * router.post("/", { body: z.object({ name: z.string() }) }, async (req, res) => {
256
- * return res.json({ name: req.body.name });
260
+ * return res.json({ name: req.body.name }); // req.body typed as { name: string }
261
+ * });
262
+ * ```
263
+ * @example TypeBox schema
264
+ * ```typescript
265
+ * import { Type } from "@sinclair/typebox";
266
+ * router.post("/", { body: Type.Object({ name: Type.String() }) }, async (req, res) => {
267
+ * return res.json({ name: req.body.name }); // req.body typed as { name: string }
268
+ * });
269
+ * ```
270
+ * @example Plain JSON schema — `as const` is required for type inference
271
+ * ```typescript
272
+ * const bodySchema = { type: "object", properties: { name: { type: "string" } }, required: ["name"] } as const;
273
+ * router.post("/", { body: bodySchema }, async (req, res) => {
274
+ * return res.json({ name: req.body.name }); // req.body typed as { name: string }
257
275
  * });
258
276
  * ```
259
277
  * @decorator When using the validate decorator, the validated data is appended to the function parameters.
@@ -1579,37 +1597,37 @@ declare class Router {
1579
1597
  * Register a GET route under this router's base path with type-safe path parameters.
1580
1598
  */
1581
1599
  get<TPath extends string = string>(path: TPath, handler: ControllerHandler<TPath>): void;
1582
- get<TPath extends string = string, TResponses extends Record<number, RequestSchema> = Record<number, RequestSchema>, TBody extends RequestSchema | undefined = undefined, TQuery extends RequestSchema | undefined = undefined>(path: TPath, options: StandardMethodOptions<TResponses, TBody, TQuery, TPath>, handler: ControllerHandler<TPath, TResponses, TBody, TQuery>): void;
1600
+ get<TPath extends string = string, TResponses extends Record<number, RequestSchema> = Record<number, RequestSchema>, TBody extends RequestSchema | undefined = undefined, TQuery extends RequestSchema | undefined = undefined, TAll extends RequestSchema | undefined = undefined>(path: TPath, options: StandardMethodOptions<TResponses, TBody, TQuery, TPath, TAll>, handler: ControllerHandler<TPath, TResponses, TBody, TQuery, TAll>): void;
1583
1601
  /**
1584
1602
  * Register a POST route under this router's base path with type-safe path parameters.
1585
1603
  */
1586
1604
  post<TPath extends string = string>(path: TPath, handler: ControllerHandler<TPath>): void;
1587
- post<TPath extends string = string, TResponses extends Record<number, RequestSchema> = Record<number, RequestSchema>, TBody extends RequestSchema | undefined = undefined, TQuery extends RequestSchema | undefined = undefined>(path: TPath, options: StandardMethodOptions<TResponses, TBody, TQuery, TPath>, handler: ControllerHandler<TPath, TResponses, TBody, TQuery>): void;
1605
+ post<TPath extends string = string, TResponses extends Record<number, RequestSchema> = Record<number, RequestSchema>, TBody extends RequestSchema | undefined = undefined, TQuery extends RequestSchema | undefined = undefined, TAll extends RequestSchema | undefined = undefined>(path: TPath, options: StandardMethodOptions<TResponses, TBody, TQuery, TPath, TAll>, handler: ControllerHandler<TPath, TResponses, TBody, TQuery, TAll>): void;
1588
1606
  /**
1589
1607
  * Register a PATCH route under this router's base path with type-safe path parameters.
1590
1608
  */
1591
1609
  patch<TPath extends string = string>(path: TPath, handler: ControllerHandler<TPath>): void;
1592
- patch<TPath extends string = string, TResponses extends Record<number, RequestSchema> = Record<number, RequestSchema>, TBody extends RequestSchema | undefined = undefined, TQuery extends RequestSchema | undefined = undefined>(path: TPath, options: StandardMethodOptions<TResponses, TBody, TQuery, TPath>, handler: ControllerHandler<TPath, TResponses, TBody, TQuery>): void;
1610
+ patch<TPath extends string = string, TResponses extends Record<number, RequestSchema> = Record<number, RequestSchema>, TBody extends RequestSchema | undefined = undefined, TQuery extends RequestSchema | undefined = undefined, TAll extends RequestSchema | undefined = undefined>(path: TPath, options: StandardMethodOptions<TResponses, TBody, TQuery, TPath, TAll>, handler: ControllerHandler<TPath, TResponses, TBody, TQuery, TAll>): void;
1593
1611
  /**
1594
1612
  * Register a PUT route under this router's base path with type-safe path parameters.
1595
1613
  */
1596
1614
  put<TPath extends string = string>(path: TPath, handler: ControllerHandler<TPath>): void;
1597
- put<TPath extends string = string, TResponses extends Record<number, RequestSchema> = Record<number, RequestSchema>, TBody extends RequestSchema | undefined = undefined, TQuery extends RequestSchema | undefined = undefined>(path: TPath, options: StandardMethodOptions<TResponses, TBody, TQuery, TPath>, handler: ControllerHandler<TPath, TResponses, TBody, TQuery>): void;
1615
+ put<TPath extends string = string, TResponses extends Record<number, RequestSchema> = Record<number, RequestSchema>, TBody extends RequestSchema | undefined = undefined, TQuery extends RequestSchema | undefined = undefined, TAll extends RequestSchema | undefined = undefined>(path: TPath, options: StandardMethodOptions<TResponses, TBody, TQuery, TPath, TAll>, handler: ControllerHandler<TPath, TResponses, TBody, TQuery, TAll>): void;
1598
1616
  /**
1599
1617
  * Register a DELETE route under this router's base path with type-safe path parameters.
1600
1618
  */
1601
1619
  delete<TPath extends string = string>(path: TPath, handler: ControllerHandler<TPath>): void;
1602
- delete<TPath extends string = string, TResponses extends Record<number, RequestSchema> = Record<number, RequestSchema>, TBody extends RequestSchema | undefined = undefined, TQuery extends RequestSchema | undefined = undefined>(path: TPath, options: StandardMethodOptions<TResponses, TBody, TQuery, TPath>, handler: ControllerHandler<TPath, TResponses, TBody, TQuery>): void;
1620
+ delete<TPath extends string = string, TResponses extends Record<number, RequestSchema> = Record<number, RequestSchema>, TBody extends RequestSchema | undefined = undefined, TQuery extends RequestSchema | undefined = undefined, TAll extends RequestSchema | undefined = undefined>(path: TPath, options: StandardMethodOptions<TResponses, TBody, TQuery, TPath, TAll>, handler: ControllerHandler<TPath, TResponses, TBody, TQuery, TAll>): void;
1603
1621
  /**
1604
1622
  * Register an OPTIONS route under this router's base path with type-safe path parameters.
1605
1623
  */
1606
1624
  options<TPath extends string = string>(path: TPath, handler: ControllerHandler<TPath>): void;
1607
- options<TPath extends string = string, TResponses extends Record<number, RequestSchema> = Record<number, RequestSchema>, TBody extends RequestSchema | undefined = undefined, TQuery extends RequestSchema | undefined = undefined>(path: TPath, options: StandardMethodOptions<TResponses, TBody, TQuery, TPath>, handler: ControllerHandler<TPath, TResponses, TBody, TQuery>): void;
1625
+ options<TPath extends string = string, TResponses extends Record<number, RequestSchema> = Record<number, RequestSchema>, TBody extends RequestSchema | undefined = undefined, TQuery extends RequestSchema | undefined = undefined, TAll extends RequestSchema | undefined = undefined>(path: TPath, options: StandardMethodOptions<TResponses, TBody, TQuery, TPath, TAll>, handler: ControllerHandler<TPath, TResponses, TBody, TQuery, TAll>): void;
1608
1626
  /**
1609
1627
  * Register an HEAD route under this router's base path with type-safe path parameters.
1610
1628
  */
1611
1629
  head<TPath extends string = string>(path: TPath, handler: ControllerHandler<TPath>): void;
1612
- head<TPath extends string = string, TResponses extends Record<number, RequestSchema> = Record<number, RequestSchema>, TBody extends RequestSchema | undefined = undefined, TQuery extends RequestSchema | undefined = undefined>(path: TPath, options: StandardMethodOptions<TResponses, TBody, TQuery, TPath>, handler: ControllerHandler<TPath, TResponses, TBody, TQuery>): void;
1630
+ head<TPath extends string = string, TResponses extends Record<number, RequestSchema> = Record<number, RequestSchema>, TBody extends RequestSchema | undefined = undefined, TQuery extends RequestSchema | undefined = undefined, TAll extends RequestSchema | undefined = undefined>(path: TPath, options: StandardMethodOptions<TResponses, TBody, TQuery, TPath, TAll>, handler: ControllerHandler<TPath, TResponses, TBody, TQuery, TAll>): void;
1613
1631
  /**
1614
1632
  * Create a grouped router that shares a base path and middlewares.
1615
1633
  * The callback receives a child router where routes are defined; routes
@@ -1669,74 +1687,6 @@ interface Route {
1669
1687
  */
1670
1688
  type ClientRouter = Omit<Router, "applyGlobalMiddlewaresToAllRoutes" | "addOrUpdate">;
1671
1689
 
1672
- /**
1673
- * Core cache service implementation wrapping a CacheProvider.
1674
- *
1675
- * Handles all cache operations including:
1676
- * - Get/Set with optional compression
1677
- * - Tag-based invalidation
1678
- * - Pattern-based invalidation
1679
- * - Thundering herd protection (lock acquisition)
1680
- * - Statistics tracking
1681
- */
1682
- declare class CacheService implements CacheServiceInterface {
1683
- private readonly log;
1684
- private readonly provider;
1685
- private readonly options;
1686
- private stats;
1687
- constructor(provider: CacheProvider, options: CachePluginOptionsResolved);
1688
- /**
1689
- * Get a cached value by key.
1690
- * Handles decompression if the entry was stored compressed.
1691
- */
1692
- get<T = unknown>(key: string): Promise<T | null>;
1693
- /**
1694
- * Set a cached value with optional compression and tag registration.
1695
- */
1696
- set(key: string, value: unknown, ttl: number, opts?: {
1697
- compressed?: boolean;
1698
- tags?: string[];
1699
- }): Promise<void>;
1700
- /**
1701
- * Invalidate all cache entries with any of the given tags.
1702
- */
1703
- invalidate(tags: string[]): Promise<number>;
1704
- /**
1705
- * Invalidate a specific cache key.
1706
- */
1707
- invalidateKey(key: string): Promise<boolean>;
1708
- /**
1709
- * Invalidate all keys matching a pattern.
1710
- */
1711
- invalidatePattern(pattern: string): Promise<number>;
1712
- /**
1713
- * Acquire a lock for thundering herd protection.
1714
- * @returns true if lock was acquired, false if already held
1715
- */
1716
- acquireLock(key: string): Promise<boolean>;
1717
- /**
1718
- * Release a lock after cache population.
1719
- */
1720
- releaseLock(key: string): Promise<void>;
1721
- /**
1722
- * Wait for cache to be populated by another request.
1723
- */
1724
- waitForCache<T>(key: string, timeoutMs: number): Promise<T | null>;
1725
- /**
1726
- * Get current cache statistics.
1727
- */
1728
- getStats(): CacheStats;
1729
- /**
1730
- * Get the underlying cache provider.
1731
- */
1732
- getProvider(): CacheProvider;
1733
- /**
1734
- * Disconnect the underlying provider.
1735
- */
1736
- disconnect(): Promise<void>;
1737
- private updateHitRate;
1738
- }
1739
-
1740
1690
  /**
1741
1691
  * The server class that is used to create and manage the server
1742
1692
  */
@@ -1768,9 +1718,6 @@ declare class Server<H extends NodeHttpClient = NodeHttpClient> implements Serve
1768
1718
  get host(): string;
1769
1719
  get routes(): Route[];
1770
1720
  get fs(): typeof nativeFs;
1771
- get cache(): CacheService;
1772
- hash(data: string): Promise<string>;
1773
- compareHash(hash: string, data: string): Promise<boolean>;
1774
1721
  getEnvironment(): Record<string, string>;
1775
1722
  tmpDir(...append: string[]): string;
1776
1723
  getNodeServer(): RuntimeServerMap<"node", H>;
@@ -1804,11 +1751,6 @@ declare class Server<H extends NodeHttpClient = NodeHttpClient> implements Serve
1804
1751
  * @returns A promise that resolves when the server is disconnected
1805
1752
  */
1806
1753
  disconnect(): Promise<void>;
1807
- configureHash(options: {
1808
- iterations?: number;
1809
- saltLength?: number;
1810
- keyLength?: number;
1811
- }): void;
1812
1754
  getMockServer(options?: Pick<ServerOptions, "controllerPatterns">): Promise<MockServer>;
1813
1755
  private importControllers;
1814
1756
  private applyPlugins;
@@ -1817,11 +1759,6 @@ declare class Server<H extends NodeHttpClient = NodeHttpClient> implements Serve
1817
1759
  * @internal
1818
1760
  */
1819
1761
  private bootstrap;
1820
- /**
1821
- * Initialize the cache service and embed it on the server instance.
1822
- * @internal
1823
- */
1824
- private initializeCache;
1825
1762
  /**
1826
1763
  * Handles not found routes by delegating to custom handler or default error response
1827
1764
  * Checks if the path exists for other methods and returns 405 if so
@@ -2324,6 +2261,7 @@ type ServerPlugin = {
2324
2261
  methodOverride?: MethodOverrideOptions;
2325
2262
  compression?: CompressionOptions;
2326
2263
  asyncLocalStorage?: AsyncLocalStorageContextSetters;
2264
+ cache?: CachePluginOptions;
2327
2265
  };
2328
2266
  type NodeHttpClient = "http" | "http2" | "https" | "http2-secure";
2329
2267
  type ServerOptions<H extends NodeHttpClient = NodeHttpClient> = {
@@ -2404,27 +2342,6 @@ type ServerOptions<H extends NodeHttpClient = NodeHttpClient> = {
2404
2342
  * ```
2405
2343
  */
2406
2344
  abortSignal?: AbortSignal;
2407
- /**
2408
- * The cronUI options to apply to the server.
2409
- * By passing the "path" option, the UI will be enabled at the given path.
2410
- */
2411
- cronUI?: CronUIOptions;
2412
- /**
2413
- * Cache configuration for the server.
2414
- * When provided, enables the cache system and exposes it via `server.cache`.
2415
- *
2416
- * @example
2417
- * ```ts
2418
- * const server = new Server({
2419
- * cache: { provider: 'memory', defaultTtl: 300 }
2420
- * });
2421
- * // or with Redis
2422
- * const server = new Server({
2423
- * cache: { provider: 'redis', redis: { host: 'localhost', port: 6379 } }
2424
- * });
2425
- * ```
2426
- */
2427
- cache?: CachePluginOptions;
2428
2345
  } & (H extends "https" | "http2-secure" ? HttpsOptions<H> : {});
2429
2346
  /** Internal resolved server options with all required properties */
2430
2347
  type ResolvedServerOptions = {
@@ -2437,8 +2354,6 @@ type ResolvedServerOptions = {
2437
2354
  swagger: Parameters<typeof swagger>[0] | boolean;
2438
2355
  graphql?: GraphQLOptions;
2439
2356
  abortSignal?: AbortSignal;
2440
- cronUI?: CronUIOptions;
2441
- cache?: CachePluginOptions;
2442
2357
  };
2443
2358
  type ServerErrorHandler = (req: Request, res: Response$1, next: NextFunction, error: Error) => SyncOrAsync;
2444
2359
  interface ServerInterface {
@@ -2479,19 +2394,6 @@ interface ServerInterface {
2479
2394
  * Main singleton router instance of the server
2480
2395
  */
2481
2396
  router: ClientRouter;
2482
- /**
2483
- * Hash the given data using the native hash function of the current runtime
2484
- * @param data - The data to hash
2485
- * @returns The hashed data
2486
- */
2487
- hash: (data: string) => Promise<string>;
2488
- /**
2489
- * Compare the given data with the given hash using the native hash function of the current runtime
2490
- * @param hash - The hash to compare the data with
2491
- * @param data - The data to compare with the hash
2492
- * @returns Whether the data matches the hash
2493
- */
2494
- compareHash: (hash: string, data: string) => Promise<boolean>;
2495
2397
  /**
2496
2398
  * Get the environment variables of the server using the native environment variables of the current runtime
2497
2399
  */
@@ -2632,18 +2534,6 @@ interface ServerInterface {
2632
2534
  * Subsequent calls after the first will have no effect
2633
2535
  */
2634
2536
  disconnect: () => Promise<void>;
2635
- /**
2636
- * Configure hash settings for password hashing
2637
- * @param options - Hash configuration options
2638
- * @param options.iterations - Number of PBKDF2 iterations (default: 600,000)
2639
- * @param options.saltLength - Salt length in bytes (default: 16)
2640
- * @param options.keyLength - Key length in bits (default: 256)
2641
- */
2642
- configureHash: (options: {
2643
- iterations?: number;
2644
- saltLength?: number;
2645
- keyLength?: number;
2646
- }) => void;
2647
2537
  /**
2648
2538
  * Returns a mock server instance that can be used to test the server without starting it
2649
2539
  * It will import the controllers and apply the plugins to the mock server
@@ -2662,19 +2552,19 @@ interface ServerInterface {
2662
2552
  */
2663
2553
  exit: (code?: number) => void;
2664
2554
  }
2665
- type StandardMethodOptions<TResponses extends Record<number, RequestSchema> = Record<number, RequestSchema>, TBody extends RequestSchema | unknown = unknown, TQuery extends RequestSchema | unknown = unknown, TPath extends string = string> = {
2555
+ type StandardMethodOptions<TResponses extends Record<number, RequestSchema> = Record<number, RequestSchema>, TBody extends RequestSchema | unknown = unknown, TQuery extends RequestSchema | unknown = unknown, TPath extends string = string, TAll extends RequestSchema | unknown = unknown> = {
2666
2556
  middlewares?: ServerRouteMiddleware[] | ServerRouteMiddleware;
2667
2557
  body?: TBody;
2668
2558
  query?: TQuery;
2669
- all?: RequestSchema;
2559
+ all?: TAll;
2670
2560
  responses?: TResponses;
2671
2561
  swagger?: SwaggerRouteOptions;
2672
- /** Cache configuration for this route. Requires cache to be configured in ServerOptions. */
2562
+ /** Cache configuration for this route. Requires cache to be initialized via initCacheService(). */
2673
2563
  cache?: TypedCacheRouteConfig<TBody, TQuery, TPath>;
2674
2564
  };
2675
2565
  type ServerHook = () => SyncOrAsync;
2676
2566
  type SignalEvent = Deno.Signal | NodeJS.Signals;
2677
- type ControllerHandler<TPath extends string = string, TResponses extends Record<number, RequestSchema> = Record<number, RequestSchema>, TBody extends RequestSchema | unknown = unknown, TQuery extends RequestSchema | unknown = unknown> = (req: Request<ExtractParams<TPath>, InferBodyType<TBody>, InferQueryType<TQuery> extends Record<string, any> ? InferQueryType<TQuery> : Record<string, unknown>>, res: Response$1<InferResponseMap<TResponses>>) => ServerHandlerReturnType;
2567
+ type ControllerHandler<TPath extends string = string, TResponses extends Record<number, RequestSchema> = Record<number, RequestSchema>, TBody extends RequestSchema | unknown = unknown, TQuery extends RequestSchema | unknown = unknown, TAll extends RequestSchema | unknown = unknown> = (req: Request<ExtractParams<TPath>, TBody extends RequestSchema ? InferBodyType<TBody> : InferBodyType<TAll>, InferQueryType<TQuery> extends Record<string, any> ? InferQueryType<TQuery> : Record<string, unknown>>, res: Response$1<InferResponseMap<TResponses>>) => ServerHandlerReturnType;
2678
2568
 
2679
2569
  type RunTimeType = "bun" | "node" | "deno";
2680
2570
 
@@ -2833,6 +2723,22 @@ declare class CronService {
2833
2723
  static massiveImportCronJobs(cronJobPatterns: string[]): Promise<void>;
2834
2724
  }
2835
2725
  declare const setCronGlobalErrorHandler: (globalErrorHandler: (...args: Parameters<(typeof CronService)["globalErrorHandler"]>) => void) => void;
2726
+ declare const cronUi: (cronUIOptions?: CronUIOptions) => Promise<void>;
2727
+
2728
+ declare class CronUI {
2729
+ static cronstrue: {
2730
+ default: typeof cronstrueType;
2731
+ } | null;
2732
+ static getCronstrue(): Promise<{
2733
+ default: typeof cronstrueType;
2734
+ }>;
2735
+ /**
2736
+ * Generates an HTML UI displaying cron jobs in a modern dashboard style
2737
+ */
2738
+ generate(): Promise<string>;
2739
+ private escapeHtml;
2740
+ }
2741
+ declare const cronUIInstance: CronUI;
2836
2742
 
2837
2743
  interface MqttTopics {
2838
2744
  }
@@ -4396,6 +4302,128 @@ declare class PolicyManager<T extends Record<string, PolicyProvider>> {
4396
4302
 
4397
4303
  declare const createPolicyDecorator: <T extends Record<string, PolicyProvider>>(manager: PolicyManager<T>) => PolicyDecorator<T>;
4398
4304
 
4305
+ /**
4306
+ * Core cache service implementation wrapping a CacheProvider.
4307
+ *
4308
+ * Handles all cache operations including:
4309
+ * - Get/Set with optional compression
4310
+ * - Tag-based invalidation
4311
+ * - Pattern-based invalidation
4312
+ * - Thundering herd protection (lock acquisition)
4313
+ * - Statistics tracking
4314
+ */
4315
+ declare class CacheService implements CacheServiceInterface {
4316
+ private readonly log;
4317
+ private readonly provider;
4318
+ private readonly options;
4319
+ private stats;
4320
+ constructor(provider: CacheProvider, options: CachePluginOptionsResolved);
4321
+ /**
4322
+ * Get a cached value by key.
4323
+ * Handles decompression if the entry was stored compressed.
4324
+ */
4325
+ get<T = unknown>(key: string): Promise<T | null>;
4326
+ /**
4327
+ * Set a cached value with optional compression and tag registration.
4328
+ */
4329
+ set(key: string, value: unknown, ttl: number, opts?: {
4330
+ compressed?: boolean;
4331
+ tags?: string[];
4332
+ }): Promise<void>;
4333
+ /**
4334
+ * Invalidate all cache entries with any of the given tags.
4335
+ */
4336
+ invalidate(tags: string[]): Promise<number>;
4337
+ /**
4338
+ * Invalidate a specific cache key.
4339
+ */
4340
+ invalidateKey(key: string): Promise<boolean>;
4341
+ /**
4342
+ * Invalidate all keys matching a pattern.
4343
+ */
4344
+ invalidatePattern(pattern: string): Promise<number>;
4345
+ /**
4346
+ * Acquire a lock for thundering herd protection.
4347
+ * @returns true if lock was acquired, false if already held
4348
+ */
4349
+ acquireLock(key: string): Promise<boolean>;
4350
+ /**
4351
+ * Release a lock after cache population.
4352
+ */
4353
+ releaseLock(key: string): Promise<void>;
4354
+ /**
4355
+ * Wait for cache to be populated by another request.
4356
+ */
4357
+ waitForCache<T>(key: string, timeoutMs: number): Promise<T | null>;
4358
+ /**
4359
+ * Get current cache statistics.
4360
+ */
4361
+ getStats(): CacheStats;
4362
+ /**
4363
+ * Get the underlying cache provider.
4364
+ */
4365
+ getProvider(): CacheProvider;
4366
+ /**
4367
+ * Disconnect the underlying provider.
4368
+ */
4369
+ disconnect(): Promise<void>;
4370
+ private updateHitRate;
4371
+ }
4372
+
4373
+ /**
4374
+ * Initialize the global cache service with a provider and options.
4375
+ * Called during server bootstrap when `cache` is configured in ServerOptions.
4376
+ * @internal
4377
+ */
4378
+ declare function initCacheService(provider: CacheProvider, options: CachePluginOptionsResolved): CacheService;
4379
+ /**
4380
+ * Get the global cache service instance.
4381
+ * Returns null if cache has not been configured.
4382
+ */
4383
+ declare function getCacheService(): CacheService | null;
4384
+ /**
4385
+ * Reset the global cache service (for testing).
4386
+ * @internal
4387
+ */
4388
+ declare function resetCacheService(): void;
4389
+
4390
+ /**
4391
+ * Options for the cache middleware.
4392
+ * Accepts the same configuration as CachePluginOptions but without provider/redis
4393
+ * since the provider is passed directly as the first argument.
4394
+ */
4395
+ type CacheMiddlewareOptions = Omit<CachePluginOptions, "provider" | "redis">;
4396
+ /**
4397
+ * Creates a cache middleware that initializes the global CacheService.
4398
+ *
4399
+ * Use with `server.use()` to enable caching across your application.
4400
+ * The `@cache()` decorator and `getCacheService()` will use the initialized service.
4401
+ *
4402
+ * @param provider - The cache provider instance (e.g. `new MemoryCacheProvider()` or `new RedisCacheProvider(...)`)
4403
+ * @param options - Optional cache configuration (defaults are applied automatically)
4404
+ * @returns A middleware compatible with `server.use()`
4405
+ *
4406
+ * @example
4407
+ * ```typescript
4408
+ * import { Server, cacheMiddleware, MemoryCacheProvider } from 'balda';
4409
+ *
4410
+ * const server = new Server({ port: 3000 });
4411
+ * server.use(cacheMiddleware(new MemoryCacheProvider()));
4412
+ * ```
4413
+ *
4414
+ * @example
4415
+ * ```typescript
4416
+ * import { Server, cacheMiddleware, RedisCacheProvider } from 'balda';
4417
+ *
4418
+ * const server = new Server({ port: 3000 });
4419
+ * server.use(cacheMiddleware(new RedisCacheProvider({ host: 'localhost' }), {
4420
+ * defaultTtl: 600,
4421
+ * enableStats: true,
4422
+ * }));
4423
+ * ```
4424
+ */
4425
+ declare function cacheMiddleware(provider: CacheProvider, options?: CacheMiddlewareOptions): ServerRouteMiddleware;
4426
+
4399
4427
  /**
4400
4428
  * In-memory cache provider using Map with TTL expiration.
4401
4429
  * Suitable for development, testing, and single-instance deployments.
@@ -4438,6 +4466,10 @@ declare class RedisCacheProvider implements CacheProvider {
4438
4466
  disconnect(): Promise<void>;
4439
4467
  }
4440
4468
 
4469
+ /**
4470
+ * Default cache plugin options.
4471
+ */
4472
+ declare const DEFAULT_CACHE_OPTIONS: CachePluginOptionsResolved;
4441
4473
  /**
4442
4474
  * Response header name for cache status.
4443
4475
  */
@@ -4457,4 +4489,4 @@ declare enum CacheStatus {
4457
4489
  */
4458
4490
  declare const router: ClientRouter;
4459
4491
 
4460
- export { type AsyncLocalStorageContextSetters, AzureBlobStorageProvider, BaseCron, BasePlugin, type BaseStorageProviderOptions, type BlobStorageProviderOptions, BullMQConfiguration, type BullMQConfigurationOptions, BullMQPubSub, CACHE_STATUS_HEADER, type CacheKeyIncludes, 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, EdgeAdapter, EjsAdapter, type ExtractParams, GraphQL, type GraphQLContext, type GraphQLOptions, type GraphQLResolverFunction, type GraphQLResolverMap, type GraphQLResolverType, type GraphQLResolvers, type GraphQLSchemaInput, type GraphQLTypeDef, HandlebarsAdapter, type HelmetOptions, type HttpMethod, type HttpsOptions, 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, PolicyManager, type PolicyProvider, 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, Server, type ServerConnectInput, type ServerErrorHandler, type ServerHook, type ServerInterface, type ServerListenCallback, type ServerOptions, type ServerRouteHandler, type ServerRouteMiddleware, type ServerTapOptions, type SessionOptions, type SignalEvent, type StaticPluginOptions, Storage, type StorageInterface, type StorageOptions, type StorageProviderOptions, type TemplateMailOptions, type TimeoutOptions, type TrustProxyOptions, type TypedCacheKeyIncludes, type TypedCacheRouteConfig, type TypedHandler, TypedQueue, type TypedRouteMetadata, type ValidatedData, type ValidationOptions, arg, asyncLocalStorage, asyncStorage, bullmqQueue, cache, clearAllCaches as clearAllSchemaCaches, commandRegistry, compression, controller, cookie, cors, createExpressAdapter, createPolicyDecorator, createQueue, cron, Server as default, defineQueueConfiguration, del, expressHandler, expressMiddleware, flag, get, getCacheMetrics as getSchemaCacheMetrics, hash, helmet, log, logCacheMetrics as logSchemaCacheMetrics, logger, memoryQueue, methodOverride, middleware, mountExpressRouter, mqtt, patch, pgbossQueue, post, put, rateLimiter, router, serialize, serveStatic, session, setCronGlobalErrorHandler, setMqttGlobalErrorHandler, sqsQueue, timeout as timeoutMw, trustProxy, validate };
4492
+ export { type AsyncLocalStorageContextSetters, AzureBlobStorageProvider, BaseCron, BasePlugin, type BaseStorageProviderOptions, type BlobStorageProviderOptions, 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, HandlebarsAdapter, type HelmetOptions, type HttpMethod, type HttpsOptions, 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, PolicyManager, type PolicyProvider, 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, Server, type ServerConnectInput, type ServerErrorHandler, type ServerHook, type ServerInterface, type ServerListenCallback, type ServerOptions, type ServerRouteHandler, type ServerRouteMiddleware, type ServerTapOptions, type SessionOptions, type SignalEvent, type StaticPluginOptions, Storage, type StorageInterface, type StorageOptions, type StorageProviderOptions, type TemplateMailOptions, type TimeoutOptions, type TrustProxyOptions, type TypedCacheKeyIncludes, type TypedCacheRouteConfig, type TypedHandler, TypedQueue, type TypedRouteMetadata, type ValidatedData, 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, 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 };