weifuwu 0.28.2 → 0.30.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +394 -0
  2. package/dist/ai/provider.d.ts +45 -0
  3. package/dist/ai/stream.d.ts +13 -0
  4. package/dist/cli.d.ts +2 -0
  5. package/dist/cli.js +178 -0
  6. package/dist/core/cookie.d.ts +36 -0
  7. package/dist/core/env.d.ts +69 -0
  8. package/dist/core/html.d.ts +34 -0
  9. package/dist/core/logger.d.ts +16 -0
  10. package/dist/core/router.d.ts +95 -0
  11. package/dist/core/serve.d.ts +36 -0
  12. package/dist/core/sse.d.ts +47 -0
  13. package/dist/core/trace.d.ts +95 -0
  14. package/dist/graphql.d.ts +16 -0
  15. package/dist/hub.d.ts +36 -0
  16. package/dist/index.d.ts +54 -0
  17. package/dist/index.js +3387 -0
  18. package/dist/middleware/compress.d.ts +20 -0
  19. package/dist/middleware/cors.d.ts +25 -0
  20. package/dist/middleware/csrf.d.ts +31 -0
  21. package/dist/middleware/flash.d.ts +44 -0
  22. package/dist/middleware/health.d.ts +24 -0
  23. package/dist/middleware/helmet.d.ts +33 -0
  24. package/dist/middleware/i18n.d.ts +39 -0
  25. package/dist/middleware/rate-limit.d.ts +44 -0
  26. package/dist/middleware/request-id.d.ts +40 -0
  27. package/dist/middleware/static.d.ts +23 -0
  28. package/dist/middleware/theme.d.ts +31 -0
  29. package/dist/middleware/upload.d.ts +55 -0
  30. package/dist/middleware/validate.d.ts +32 -0
  31. package/dist/postgres/client.d.ts +4 -0
  32. package/dist/postgres/index.d.ts +3 -0
  33. package/dist/postgres/module.d.ts +12 -0
  34. package/dist/postgres/types.d.ts +42 -0
  35. package/dist/queue/cron.d.ts +9 -0
  36. package/dist/queue/index.d.ts +2 -0
  37. package/dist/queue/types.d.ts +61 -0
  38. package/dist/react/index.js +2573 -0
  39. package/dist/redis/client.d.ts +2 -0
  40. package/dist/redis/index.d.ts +2 -0
  41. package/dist/redis/types.d.ts +17 -0
  42. package/dist/test/test-utils.d.ts +193 -0
  43. package/dist/types.d.ts +82 -0
  44. package/package.json +31 -9
  45. package/index.d.ts +0 -8
  46. package/index.js +0 -26
@@ -0,0 +1,20 @@
1
+ import type { Middleware } from '../types.ts';
2
+ /** Options for {@link compress}. */
3
+ export interface CompressOptions {
4
+ /** Compression level (1-9, default: 6). */
5
+ level?: number;
6
+ /** Minimum response body size in bytes to compress (default: 1024). */
7
+ threshold?: number;
8
+ }
9
+ /**
10
+ * Response compression middleware (brotli, gzip, deflate).
11
+ *
12
+ * Automatically selects the best encoding based on `Accept-Encoding` header.
13
+ * Skips compression for small responses, images, audio, video, and already-encoded responses.
14
+ *
15
+ * ```ts
16
+ * import { compress } from 'weifuwu'
17
+ * app.use(compress())
18
+ * ```
19
+ */
20
+ export declare function compress(options?: CompressOptions): Middleware;
@@ -0,0 +1,25 @@
1
+ import type { Middleware, Context } from '../types.ts';
2
+ /** Options for {@link cors}. */
3
+ export interface CORSOptions {
4
+ /** Allowed origin(s). Default `'*'`. If `credentials: true`, reflects the request origin. */
5
+ origin?: string | string[] | ((origin: string) => string | boolean | undefined);
6
+ /** Allowed HTTP methods. Default: `GET, HEAD, PUT, PATCH, POST, DELETE`. */
7
+ methods?: string[];
8
+ /** Allowed request headers. Default: `Content-Type, Authorization`. */
9
+ allowedHeaders?: string[];
10
+ /** Exposed response headers. */
11
+ exposedHeaders?: string[];
12
+ /** Whether to expose `Access-Control-Allow-Credentials`. */
13
+ credentials?: boolean;
14
+ /** `Access-Control-Max-Age` in seconds. */
15
+ maxAge?: number;
16
+ }
17
+ /**
18
+ * CORS middleware.
19
+ *
20
+ * ```ts
21
+ * import { cors } from 'weifuwu'
22
+ * app.use(cors({ origin: 'https://myapp.com', credentials: true }))
23
+ * ```
24
+ */
25
+ export declare function cors(options?: CORSOptions): Middleware<Context, Context>;
@@ -0,0 +1,31 @@
1
+ import type { Context, Middleware } from '../types.ts';
2
+ declare module '../types.ts' {
3
+ interface Context {
4
+ csrf: CsrfInjected;
5
+ }
6
+ }
7
+ export interface CsrfInjected {
8
+ token: string;
9
+ }
10
+ /** CSRF protection module — a {@link Middleware} that injects `ctx.csrf`. */
11
+ export type CsrfModule = Middleware<Context, Context & CsrfInjected>;
12
+ export interface CsrfOptions {
13
+ /** Cookie name for CSRF token (default: `'_csrf'`). */
14
+ cookie?: string;
15
+ /** Request header name for CSRF token (default: `'x-csrf-token'`). */
16
+ header?: string;
17
+ /** Form body key for CSRF token (default: `'_csrf'`). */
18
+ key?: string;
19
+ /** HTTP methods to exclude from CSRF protection (default: `['GET', 'HEAD', 'OPTIONS']`). */
20
+ excludeMethods?: string[];
21
+ }
22
+ /**
23
+ * CSRF protection middleware.
24
+ *
25
+ * On excluded methods (GET, HEAD, OPTIONS), generates a token and stores it
26
+ * in a cookie. On other methods, validates the token from header or body
27
+ * against the cookie.
28
+ *
29
+ * Injects `ctx.csrf.token` for use in forms.
30
+ */
31
+ export declare function csrf(options?: CsrfOptions): Middleware<Context, Context & CsrfInjected>;
@@ -0,0 +1,44 @@
1
+ import type { Context, Middleware } from '../types.ts';
2
+ declare module '../types.ts' {
3
+ interface Context {
4
+ flash: FlashInjected;
5
+ }
6
+ }
7
+ /** Flash message module — a {@link Middleware} that injects `ctx.flash`. */
8
+ export type FlashModule = Middleware<Context, Context & FlashInjected>;
9
+ /** Options for {@link flash}. */
10
+ export interface FlashOptions {
11
+ /**
12
+ * Cookie name to store the flash message.
13
+ * @default 'flash'
14
+ */
15
+ name?: string;
16
+ }
17
+ /**
18
+ * Flash message object injected into `ctx.flash`.
19
+ */
20
+ export interface FlashInjected {
21
+ /**
22
+ * The flash value read from the incoming cookie.
23
+ * `undefined` if no flash cookie is present.
24
+ * Automatically cleared after the response is sent.
25
+ */
26
+ value: unknown;
27
+ /**
28
+ * Set a flash message and return a 302 redirect response.
29
+ *
30
+ * @param data - Any JSON-serializable value to store as the flash message.
31
+ * @param location - Redirect location (defaults to the `Referer` header).
32
+ * @returns A 302 Response with a `Set-Cookie` header.
33
+ */
34
+ set: (data: unknown, location?: string) => Response;
35
+ }
36
+ /**
37
+ * Flash message middleware — injects `ctx.flash`.
38
+ *
39
+ * @param options - Cookie name configuration.
40
+ * @returns Middleware that injects `ctx.flash` (`FlashInjected`).
41
+ */
42
+ export declare function flash(options?: FlashOptions): Middleware<Context, Context & {
43
+ flash: FlashInjected;
44
+ }>;
@@ -0,0 +1,24 @@
1
+ import { Router } from '../core/router.ts';
2
+ /** Options for {@link health}. */
3
+ export interface HealthOptions {
4
+ /** Health check endpoint path (default: `'/__health'`). */
5
+ path?: string;
6
+ /** Async function that throws if the service is unhealthy. Called on each request. */
7
+ check?: () => Promise<void>;
8
+ }
9
+ /**
10
+ * Health check endpoint.
11
+ *
12
+ * Returns 200 with `'OK'` if the check passes, 503 if it fails.
13
+ *
14
+ * ```ts
15
+ * import { health } from 'weifuwu'
16
+ *
17
+ * app.use(health({
18
+ * check: async () => {
19
+ * await db.query('SELECT 1')
20
+ * },
21
+ * }))
22
+ * ```
23
+ */
24
+ export declare function health(options?: HealthOptions): Router;
@@ -0,0 +1,33 @@
1
+ import type { Middleware, Context } from '../types.ts';
2
+ /** Options for {@link helmet}. Set any header to `false` to omit it. */
3
+ export interface HelmetOptions {
4
+ /** `Content-Security-Policy` header value. */
5
+ contentSecurityPolicy?: string | false;
6
+ /** `Cross-Origin-Embedder-Policy` header value. */
7
+ crossOriginEmbedderPolicy?: string | false;
8
+ /** `Cross-Origin-Opener-Policy` header value. */
9
+ crossOriginOpenerPolicy?: string | false;
10
+ /** `Cross-Origin-Resource-Policy` header value. */
11
+ crossOriginResourcePolicy?: string | false;
12
+ /** `Origin-Agent-Cluster` header value. */
13
+ originAgentCluster?: string | false;
14
+ /** `Referrer-Policy` header value. */
15
+ referrerPolicy?: string | false;
16
+ /** `Strict-Transport-Security` header value. */
17
+ strictTransportSecurity?: string | false;
18
+ /** `X-Content-Type-Options` header value. */
19
+ xContentTypeOptions?: string | false;
20
+ /** `X-DNS-Prefetch-Control` header value. */
21
+ xDnsPrefetchControl?: string | false;
22
+ /** `X-Download-Options` header value. */
23
+ xDownloadOptions?: string | false;
24
+ /** `X-Frame-Options` header value. */
25
+ xFrameOptions?: string | false;
26
+ /** `X-Permitted-Cross-Domain-Policies` header value. */
27
+ xPermittedCrossDomainPolicies?: string | false;
28
+ /** `X-XSS-Protection` header value. */
29
+ xXssProtection?: string | false;
30
+ /** `Permissions-Policy` header value. */
31
+ permissionsPolicy?: string | false;
32
+ }
33
+ export declare function helmet(options?: HelmetOptions): Middleware<Context, Context>;
@@ -0,0 +1,39 @@
1
+ import { Router } from '../core/router.ts';
2
+ import type { Context, Middleware } from '../types.ts';
3
+ declare module '../types.ts' {
4
+ interface Context {
5
+ i18n: I18nInjected;
6
+ }
7
+ }
8
+ export interface I18nInjected {
9
+ locale: string;
10
+ messages?: Record<string, unknown>;
11
+ t: (key: string, params?: Record<string, string>, fallback?: string) => string;
12
+ set?: (value: string, loc?: string) => Response;
13
+ }
14
+ export interface I18nOptions {
15
+ /** Default locale (default: 'en'). */
16
+ default?: string;
17
+ /** Directory containing `{locale}.json` translation files. */
18
+ dir?: string;
19
+ /** Inline translation messages keyed by locale. */
20
+ messages?: Record<string, Record<string, unknown>>;
21
+ /** Cookie name for locale (default: 'locale'). Set empty to disable. */
22
+ cookie?: string;
23
+ /** Whether to detect locale from Accept-Language header (default: true). */
24
+ fromAcceptLanguage?: boolean;
25
+ }
26
+ /**
27
+ * i18n module. Returns a Router with an attached `.middleware()` method.
28
+ *
29
+ * ```ts
30
+ * const l = i18n({ dir: './locales' })
31
+ * app.use(l.middleware()) // → ctx.i18n = { locale, t, set }
32
+ * app.mount('/', l) // → GET /__lang/:locale (switch route)
33
+ * ```
34
+ */
35
+ export interface I18nModule extends Router {
36
+ /** Middleware that injects `ctx.i18n = { locale, t, set }`. */
37
+ middleware: () => Middleware<Context, Context & I18nInjected>;
38
+ }
39
+ export declare function i18n(options?: I18nOptions): I18nModule;
@@ -0,0 +1,44 @@
1
+ import type { Redis, Context, Middleware, Closeable } from '../types.ts';
2
+ /** Options for {@link rateLimit}. */
3
+ export interface RateLimitOptions {
4
+ /** Maximum requests within the window (default: 100). */
5
+ max?: number;
6
+ /** Window duration in ms (default: 60000 = 1 minute). */
7
+ window?: number;
8
+ /** Custom key function. Default: IP from `x-forwarded-for` or `x-real-ip` or `cf-connecting-ip`. */
9
+ key?: (req: Request, ctx: Context) => string;
10
+ /** Custom 429 response body." */
11
+ message?: string;
12
+ /** Store backend. `'memory'` (default) or `'redis'`. */
13
+ store?: 'memory' | 'redis';
14
+ /** Redis client (required when `store: 'redis'`). */
15
+ redis?: Redis;
16
+ /** Redis key prefix (default: `'ratelimit:'`). */
17
+ prefix?: string;
18
+ }
19
+ /** Rate limit module — middleware + stats. */
20
+ export interface RateLimitModule extends Middleware<Context, Context>, Closeable {
21
+ stats(): {
22
+ store: string;
23
+ entries?: number;
24
+ maxEntries: number;
25
+ };
26
+ }
27
+ /**
28
+ * Rate limiting middleware (in-memory or Redis-backed).
29
+ *
30
+ * Limits requests per key (default: client IP) within a rolling window.
31
+ * Returns 429 when the limit is exceeded, with `Retry-After` header.
32
+ *
33
+ * ```ts
34
+ * import { rateLimit } from 'weifuwu'
35
+ *
36
+ * // In-memory (single process)
37
+ * app.use(rateLimit({ max: 60, window: 60_000 }))
38
+ *
39
+ * // Redis-backed (multi-process)
40
+ * import { Redis } from 'ioredis'
41
+ * app.use(rateLimit({ store: 'redis', redis: new Redis(), max: 100 }))
42
+ * ```
43
+ */
44
+ export declare function rateLimit(options?: RateLimitOptions): RateLimitModule;
@@ -0,0 +1,40 @@
1
+ import type { Context, Middleware } from '../types.ts';
2
+ declare module '../types.ts' {
3
+ interface Context {
4
+ requestId: string;
5
+ }
6
+ }
7
+ /** Options for {@link requestId}. */
8
+ /** Request ID module — a {@link Middleware} that injects `ctx.requestId`. */
9
+ export type RequestIdModule = Middleware<Context, Context & {
10
+ requestId: string;
11
+ }>;
12
+ export interface RequestIdOptions {
13
+ /** Header name for request ID (default: `'X-Request-ID'`). */
14
+ header?: string;
15
+ /** Custom ID generator (default: `crypto.randomUUID`). */
16
+ generator?: () => string;
17
+ }
18
+ /**
19
+ * Request ID middleware.
20
+ *
21
+ * @deprecated Use `trace()` from 'weifuwu' instead — it injects `ctx.trace.requestId`
22
+ * along with `traceId` and `elapsed()` in a single middleware.
23
+ *
24
+ * ```ts
25
+ * // Old:
26
+ * app.use(requestId())
27
+ * ctx.requestId
28
+ *
29
+ * // New:
30
+ * app.use(trace())
31
+ * ctx.trace.requestId
32
+ * ```
33
+ *
34
+ * Reads an incoming `X-Request-ID` header (or custom header name) from the
35
+ * request. If absent, generates a new UUID. Sets the response header and
36
+ * injects `ctx.requestId`.
37
+ */
38
+ export declare function requestId(options?: RequestIdOptions): Middleware<Context, Context & {
39
+ requestId: string;
40
+ }>;
@@ -0,0 +1,23 @@
1
+ import type { Handler } from '../types.ts';
2
+ /** Options for {@link serveStatic}. */
3
+ export interface ServeStaticOptions {
4
+ /** Directory index filename (default: `'index.html'`). */
5
+ index?: string;
6
+ /** `Cache-Control max-age` in seconds. */
7
+ maxAge?: number;
8
+ /** Add `immutable` to `Cache-Control` (requires `maxAge`). */
9
+ immutable?: boolean;
10
+ }
11
+ /**
12
+ * Static file serving handler.
13
+ *
14
+ * Serves files from a root directory. Supports ETag/304, directory index,
15
+ * Content-Type detection by extension, and directory traversal protection.
16
+ *
17
+ * ```ts
18
+ * import { serveStatic, Router } from 'weifuwu'
19
+ * const app = new Router()
20
+ * app.get('/static/*', serveStatic('./public'))
21
+ * ```
22
+ */
23
+ export declare function serveStatic(root: string, options?: ServeStaticOptions): Handler;
@@ -0,0 +1,31 @@
1
+ import { Router } from '../core/router.ts';
2
+ import type { Context, Middleware } from '../types.ts';
3
+ declare module '../types.ts' {
4
+ interface Context {
5
+ theme: ThemeInjected;
6
+ }
7
+ }
8
+ export interface ThemeInjected {
9
+ value: string;
10
+ set: (value: string, loc?: string) => Response;
11
+ }
12
+ export interface ThemeOptions {
13
+ /** Default theme value (default: 'system'). */
14
+ default?: string;
15
+ /** Cookie name (default: 'theme'). Set to empty string to disable cookie. */
16
+ cookie?: string;
17
+ }
18
+ /**
19
+ * Theme module. Returns a Router with an attached `.middleware()` method.
20
+ *
21
+ * ```ts
22
+ * const t = theme()
23
+ * app.use(t.middleware()) // → ctx.theme = { value, set }
24
+ * app.mount('/', t) // → GET /__theme/dark (switch route)
25
+ * ```
26
+ */
27
+ export interface ThemeModule extends Router {
28
+ /** Middleware that injects `ctx.theme = { value, set }`. */
29
+ middleware: () => Middleware<Context, Context & ThemeInjected>;
30
+ }
31
+ export declare function theme(options?: ThemeOptions): ThemeModule;
@@ -0,0 +1,55 @@
1
+ import type { Context, Middleware } from '../types.ts';
2
+ declare module '../types.ts' {
3
+ interface Context {
4
+ parsed: Record<string, unknown>;
5
+ }
6
+ }
7
+ /** Upload middleware — a {@link Middleware} that injects `ctx.parsed` with file fields. */
8
+ export type UploadModule = Middleware<Context, Context & {
9
+ parsed: Record<string, unknown>;
10
+ }>;
11
+ /** A parsed file from a multipart upload. */
12
+ export interface UploadedFile {
13
+ /** Original filename from the client. */
14
+ name: string;
15
+ /** MIME type from the `Content-Type` part header. */
16
+ type: string;
17
+ /** File size in bytes. */
18
+ size: number;
19
+ /** Path where the file was saved (when `dir` option is set). */
20
+ path?: string;
21
+ /** File content as Buffer (when `dir` option is not set). */
22
+ buffer?: Buffer;
23
+ }
24
+ /** Options for {@link upload}. */
25
+ export interface UploadOptions {
26
+ /** Directory to save uploaded files. If not set, files stay in memory via `.buffer`. */
27
+ dir?: string;
28
+ /** Maximum file size in bytes. Default: 10 MB. Set `0` to allow unlimited. */
29
+ maxFileSize?: number;
30
+ /** Allowed MIME types (e.g. `['image/jpeg', 'image/png']`). Empty array allows all. */
31
+ allowedTypes?: string[];
32
+ }
33
+ /**
34
+ * Multipart file upload middleware.
35
+ *
36
+ * Parses `multipart/form-data` requests, extracting files and fields.
37
+ * Files can be saved to disk (`dir` option) or kept in memory as Buffers.
38
+ * Parsed fields are available in `ctx.parsed`.
39
+ *
40
+ * ```ts
41
+ * import { upload } from 'weifuwu'
42
+ *
43
+ * // Save to disk
44
+ * app.use(upload({ dir: './uploads', maxFileSize: 5_000_000 }))
45
+ *
46
+ * // In-memory
47
+ * app.post('/upload', async (req, ctx) => {
48
+ * const file = ctx.parsed?.file as UploadedFile
49
+ * console.log(file.name, file.type, file.buffer!.length)
50
+ * })
51
+ * ```
52
+ */
53
+ export declare function upload(options?: UploadOptions): Middleware<Context, Context & {
54
+ parsed: Record<string, unknown>;
55
+ }>;
@@ -0,0 +1,32 @@
1
+ import type { ZodSchema } from 'zod';
2
+ import type { Middleware } from '../types.ts';
3
+ declare module '../types.ts' {
4
+ interface Context {
5
+ parsed: Record<string, unknown>;
6
+ }
7
+ }
8
+ /** Validation middleware — a {@link Middleware} that injects `ctx.parsed` with validated data. */
9
+ export type ValidateModule = Middleware;
10
+ export interface ValidationSchemas {
11
+ body?: ZodSchema;
12
+ query?: ZodSchema;
13
+ params?: ZodSchema;
14
+ headers?: ZodSchema;
15
+ }
16
+ /**
17
+ * Request validation middleware using Zod schemas.
18
+ *
19
+ * Validates `params`, `query`, `body`, and/or `headers` against schemas.
20
+ * Returns 422 with error details on mismatch.
21
+ * Injects `ctx.parsed` with validated-and-transformed values.
22
+ *
23
+ * ```ts
24
+ * import { z } from 'zod'
25
+ *
26
+ * app.get('/users/:id', validate({
27
+ * params: z.object({ id: z.string() }),
28
+ * query: z.object({ include: z.string().optional() }),
29
+ * }), handler)
30
+ * ```
31
+ */
32
+ export declare function validate(schemas?: ValidationSchemas): Middleware;
@@ -0,0 +1,4 @@
1
+ import type { PostgresOptions, PostgresClient } from './types.ts';
2
+ /** Migration tracking table name. Created automatically on first migrate(). */
3
+ export declare const MIGRATIONS_TABLE = "_weifuwu_migrations";
4
+ export declare function postgres(opts?: string | PostgresOptions): PostgresClient;
@@ -0,0 +1,3 @@
1
+ export { postgres, MIGRATIONS_TABLE } from './client.ts';
2
+ export { PgModule } from './module.ts';
3
+ export type { PostgresOptions, PostgresClient, PostgresInjected } from './types.ts';
@@ -0,0 +1,12 @@
1
+ import type { SqlClient, Closeable } from '../types.ts';
2
+ import type { PostgresClient } from './types.ts';
3
+ export declare class PgModule implements Closeable {
4
+ protected sql: SqlClient;
5
+ protected pg: PostgresClient;
6
+ constructor(pg: PostgresClient);
7
+ transaction<T>(fn: (sql: SqlClient) => Promise<T>, retryOpts?: {
8
+ maxRetries?: number;
9
+ }): Promise<T>;
10
+ migrate(): Promise<void>;
11
+ close(): Promise<void>;
12
+ }
@@ -0,0 +1,42 @@
1
+ import type { SqlClient, Context, Middleware, Closeable } from '../types.ts';
2
+ declare module '../types.ts' {
3
+ interface Context {
4
+ sql: SqlClient;
5
+ }
6
+ }
7
+ export interface PostgresInjected {
8
+ sql: SqlClient;
9
+ }
10
+ export interface PostgresOptions {
11
+ connection?: string | Record<string, unknown>;
12
+ signal?: AbortSignal;
13
+ closeTimeout?: number;
14
+ max?: number;
15
+ ssl?: boolean | Record<string, unknown>;
16
+ idle_timeout?: number;
17
+ connect_timeout?: number;
18
+ /** Per-statement timeout in ms. Set to 0 to disable. Default: 30_000. */
19
+ statementTimeout?: number;
20
+ /** Called after every query completes. Receives query text, duration in ms, and row count. */
21
+ onQuery?: (query: string, durationMs: number, rowCount: number) => void;
22
+ }
23
+ export interface PostgresClient extends Middleware<Context, Context & PostgresInjected>, Closeable {
24
+ sql: SqlClient;
25
+ /** Creates the migration tracking table (_weifuwu_migrations). Called once at startup. */
26
+ migrate: () => Promise<void>;
27
+ /** Record that a module's migration has been applied (idempotent). */
28
+ markMigrated: (moduleName: string) => Promise<void>;
29
+ /** Check whether a module has already been migrated. */
30
+ isMigrated: (moduleName: string) => Promise<boolean>;
31
+ transaction: <T>(fn: (sql: any) => Promise<T>, retryOpts?: {
32
+ maxRetries?: number;
33
+ }) => Promise<T>;
34
+ /** Snapshot of connection pool state: active, idle, waiting, max connections. */
35
+ poolStats: () => {
36
+ active: number;
37
+ idle: number;
38
+ waiting: number;
39
+ max: number;
40
+ };
41
+ close: () => Promise<void>;
42
+ }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Cron expression parsing utilities (moved from cron-utils.ts).
3
+ * Used internally by queue for scheduled job execution.
4
+ *
5
+ * All functions operate in local timezone.
6
+ */
7
+ export declare function parsePattern(pattern: string): Set<number>[];
8
+ export declare function matches(fields: Set<number>[], date: Date): boolean;
9
+ export declare function cronNext(expr: string, from?: Date): number;
@@ -0,0 +1,2 @@
1
+ import type { Queue, QueueOptions } from './types.ts';
2
+ export declare function queue(opts?: QueueOptions): Queue;
@@ -0,0 +1,61 @@
1
+ import type { Redis, Context, Middleware, Closeable } from '../types.ts';
2
+ declare module '../types.ts' {
3
+ interface Context {
4
+ queue: Queue;
5
+ }
6
+ }
7
+ export interface QueueJob<T = unknown> {
8
+ id: string;
9
+ type: string;
10
+ payload: T;
11
+ createdAt: number;
12
+ runAt: number;
13
+ schedule?: string;
14
+ }
15
+ export interface QueueOptions {
16
+ /** Backend store. Default: 'memory'. */
17
+ store?: 'memory' | 'pg' | 'redis';
18
+ redis?: Redis;
19
+ url?: string;
20
+ prefix?: string;
21
+ pollInterval?: number;
22
+ /** PostgreSQL client (required when store: 'pg'). */
23
+ pg?: {
24
+ sql: import('../types.ts').SqlClient;
25
+ };
26
+ }
27
+ export interface QueueInjected {
28
+ queue: Queue;
29
+ }
30
+ export interface QueueJobWithError<T = unknown> extends QueueJob<T> {
31
+ error: string;
32
+ failedAt: number;
33
+ }
34
+ export interface Queue extends Middleware<Context, Context & QueueInjected>, Closeable {
35
+ /** Register a cron job. Uses queue's backend (memory/pg/redis) for execution. */
36
+ cron(pattern: string, handler: () => void | Promise<void>): {
37
+ stop: () => void;
38
+ };
39
+ add<T>(type: string, payload: T, opts?: {
40
+ delay?: number;
41
+ schedule?: string;
42
+ }): Promise<string>;
43
+ process<T>(type: string, handler: (job: QueueJob<T>) => Promise<void>): void;
44
+ run(): Promise<void>;
45
+ stats(): {
46
+ running: boolean;
47
+ inflight: number;
48
+ processed: number;
49
+ failed: number;
50
+ handlers: number;
51
+ maxConcurrent: number;
52
+ };
53
+ jobs(limit?: number): Promise<QueueJob[]>;
54
+ failedJobs(limit?: number): Promise<QueueJobWithError[]>;
55
+ retryFailed(jobId: string): Promise<boolean>;
56
+ retryAllFailed(type?: string): Promise<number>;
57
+ dashboard(): import('../core/router.ts').Router;
58
+ /** Create the jobs table (PG mode only; safe to call multiple times). */
59
+ migrate?(): Promise<void>;
60
+ close(): Promise<void>;
61
+ }