tempest-express-sdk 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -2244,6 +2244,275 @@ declare class WebPushDispatcher {
2244
2244
  send(subscription: WebPushSubscription, payload: WebPushPayload): Promise<void>;
2245
2245
  }
2246
2246
 
2247
+ /**
2248
+ * Messaging integration contracts.
2249
+ *
2250
+ * A channel-agnostic {@link MessagingProvider} so WhatsApp, SMS and future
2251
+ * channels share one shape and are swappable in tests. The first implementation
2252
+ * is {@link WhatsAppProvider} (a client for the `zap-api` service).
2253
+ */
2254
+
2255
+ /** Supported media kinds for {@link MessagingProvider.sendMedia}. */
2256
+ type MediaKind = "image" | "video" | "audio" | "document";
2257
+ /** A media message to send. */
2258
+ interface OutboundMedia {
2259
+ /** The media kind (selects the underlying route). */
2260
+ kind: MediaKind;
2261
+ /** A public `http(s)://` URL or a `data:` URI. */
2262
+ media: string;
2263
+ /** Optional caption (image/video). */
2264
+ caption?: string;
2265
+ /** File name with extension (required for `document`). */
2266
+ fileName?: string;
2267
+ }
2268
+ /** The result of enqueuing an outbound message. */
2269
+ interface OutboundResult {
2270
+ /** Provider message id, when returned. */
2271
+ id?: string;
2272
+ /** Provider status string (e.g. `"queued"`, `"sent"`). */
2273
+ status: string;
2274
+ /** Whether the send was de-duplicated by an idempotency key. */
2275
+ deduped?: boolean;
2276
+ }
2277
+ /** Options accepted by send operations. */
2278
+ interface SendOptions {
2279
+ /** Idempotency key to de-duplicate retries on the provider side. */
2280
+ idempotencyKey?: string;
2281
+ }
2282
+ /** A normalized inbound (or echoed outbound) message. */
2283
+ declare const inboundMessageSchema: z.ZodObject<{
2284
+ /** Conversation JID / sender (e.g. `5511999999999@s.whatsapp.net`). */
2285
+ from: z.ZodString;
2286
+ /** Provider message id. */
2287
+ messageId: z.ZodString;
2288
+ /** Text body, when present. */
2289
+ text: z.ZodOptional<z.ZodString>;
2290
+ /** Media kind, or `null` for plain text. */
2291
+ mediaType: z.ZodNullable<z.ZodEnum<["image", "video", "audio", "document", "sticker"]>>;
2292
+ /** ISO-8601 timestamp. */
2293
+ timestamp: z.ZodString;
2294
+ /** Delivery direction. */
2295
+ direction: z.ZodOptional<z.ZodEnum<["incoming", "outgoing"]>>;
2296
+ }, "strip", z.ZodTypeAny, {
2297
+ from: string;
2298
+ messageId: string;
2299
+ mediaType: "image" | "video" | "audio" | "document" | "sticker" | null;
2300
+ timestamp: string;
2301
+ text?: string | undefined;
2302
+ direction?: "incoming" | "outgoing" | undefined;
2303
+ }, {
2304
+ from: string;
2305
+ messageId: string;
2306
+ mediaType: "image" | "video" | "audio" | "document" | "sticker" | null;
2307
+ timestamp: string;
2308
+ text?: string | undefined;
2309
+ direction?: "incoming" | "outgoing" | undefined;
2310
+ }>;
2311
+ /** A normalized inbound message. */
2312
+ type InboundMessage = z.infer<typeof inboundMessageSchema>;
2313
+ /** Handler invoked for each inbound message. */
2314
+ type InboundHandler = (message: InboundMessage) => Promise<void> | void;
2315
+ /** A channel-agnostic messaging provider. */
2316
+ interface MessagingProvider {
2317
+ /** Send a text message. */
2318
+ sendText(to: string, text: string, options?: SendOptions): Promise<OutboundResult>;
2319
+ /** Send a media message. */
2320
+ sendMedia(to: string, media: OutboundMedia, options?: SendOptions): Promise<OutboundResult>;
2321
+ /** Whether a number exists on the channel. */
2322
+ checkNumber(number: string): Promise<boolean>;
2323
+ /** The current session/connection status. */
2324
+ status(): Promise<string>;
2325
+ /**
2326
+ * Subscribe to inbound messages; resolves to an unsubscribe function.
2327
+ *
2328
+ * @param handler - Invoked for each inbound message.
2329
+ * @param room - Conversation to scope to; `"*"` for all. Default `"*"`.
2330
+ */
2331
+ onMessage(handler: InboundHandler, room?: string): Promise<() => Promise<void>>;
2332
+ }
2333
+
2334
+ /**
2335
+ * WhatsApp provider — a typed client for the `zap-api` service.
2336
+ *
2337
+ * REST for sending (`/message/send-*`, `/message/check-number`) and session
2338
+ * control (`/session/*`); the `/ws` pub/sub for receiving inbound messages in
2339
+ * real time. HTTP goes through the SDK's resilient {@link HTTPClient}; the
2340
+ * WebSocket subscription uses the optional `ws` peer (lazily imported).
2341
+ *
2342
+ * @see https://github.com/mauriciobenjamin700 (zap-api)
2343
+ */
2344
+
2345
+ /** Options for {@link WhatsAppProvider}. */
2346
+ interface WhatsAppProviderOptions {
2347
+ /** Base URL of the `zap-api` instance, e.g. `https://zap.example.com`. */
2348
+ baseUrl: string;
2349
+ /** Consumer API key (sent as `x-api-key`). */
2350
+ apiKey: string;
2351
+ /** WebSocket URL. Defaults to `baseUrl` with `http(s)`→`ws(s)` + `/ws`. */
2352
+ wsUrl?: string;
2353
+ /** Per-request timeout in ms. Default 15000. */
2354
+ timeoutMs?: number;
2355
+ }
2356
+ /** A typed client for a running `zap-api` WhatsApp gateway. */
2357
+ declare class WhatsAppProvider implements MessagingProvider {
2358
+ private readonly http;
2359
+ private readonly apiKey;
2360
+ private readonly wsUrl;
2361
+ /**
2362
+ * @param options - Base URL, API key and optional WebSocket URL.
2363
+ */
2364
+ constructor(options: WhatsAppProviderOptions);
2365
+ /** POST JSON and parse the response, throwing on a non-2xx status. */
2366
+ private postJson;
2367
+ sendText(to: string, text: string, options?: SendOptions): Promise<OutboundResult>;
2368
+ sendMedia(to: string, media: OutboundMedia, options?: SendOptions): Promise<OutboundResult>;
2369
+ checkNumber(number: string): Promise<boolean>;
2370
+ status(): Promise<string>;
2371
+ /** Start the WhatsApp session (returns the authenticated QR URL, if any). */
2372
+ startSession(): Promise<Record<string, unknown>>;
2373
+ onMessage(handler: InboundHandler, room?: string): Promise<() => Promise<void>>;
2374
+ }
2375
+
2376
+ /**
2377
+ * WhatsApp inbound-webhook receiver.
2378
+ *
2379
+ * `zap-api` POSTs every received message to a configured webhook. This builds
2380
+ * an Express router that (optionally) validates the shared `x-api-key`, parses
2381
+ * the payload into a typed {@link InboundMessage}, and hands it to your handler.
2382
+ */
2383
+
2384
+ /** Options for {@link makeWhatsAppWebhookRouter}. */
2385
+ interface WhatsAppWebhookOptions {
2386
+ /** Handler invoked for each validated inbound message. */
2387
+ onMessage: InboundHandler;
2388
+ /** Route path. Default `/whatsapp/inbound`. */
2389
+ path?: string;
2390
+ /** Shared secret expected in `x-api-key`. Omit to skip auth (dev only). */
2391
+ apiKey?: string;
2392
+ }
2393
+ /**
2394
+ * Build the inbound-webhook router.
2395
+ *
2396
+ * @param options - Handler, path and optional shared secret.
2397
+ * @returns An Express router with the webhook endpoint mounted.
2398
+ */
2399
+ declare function makeWhatsAppWebhookRouter(options: WhatsAppWebhookOptions): Router;
2400
+
2401
+ /**
2402
+ * Admin site + resource registry, mirroring `admin.site` / `admin.config`.
2403
+ *
2404
+ * The FastAPI SDK ships a server-rendered (jinja) admin UI. Here the admin is a
2405
+ * typed **JSON API**: register one {@link AdminResource} per managed entity and
2406
+ * {@link makeAdminRouter} exposes auto-derived CRUD + introspection endpoints a
2407
+ * frontend (React, etc.) renders. Resources are callback-based, so they wire to
2408
+ * a `BaseService` — or any store — in a few lines and stay ORM-agnostic.
2409
+ */
2410
+
2411
+ /** A field descriptor a frontend uses to render list columns / form inputs. */
2412
+ interface AdminField {
2413
+ /** Field name (property key). */
2414
+ name: string;
2415
+ /** Loose type hint for rendering (`string`, `number`, `boolean`, `date`, …). */
2416
+ type?: string;
2417
+ /** Whether the field is required on create. */
2418
+ required?: boolean;
2419
+ /** Whether the field is read-only (shown, never submitted). */
2420
+ readOnly?: boolean;
2421
+ }
2422
+ /** A paginated list result returned by {@link AdminResource.list}. */
2423
+ interface AdminListResult<T = unknown> {
2424
+ items: T[];
2425
+ total: number;
2426
+ page: number;
2427
+ pageSize: number;
2428
+ pages: number;
2429
+ }
2430
+ /** Query parameters passed to {@link AdminResource.list}. */
2431
+ interface AdminListQuery {
2432
+ page: number;
2433
+ pageSize: number;
2434
+ /** Remaining query-string entries (domain filters). */
2435
+ filters: Record<string, string>;
2436
+ }
2437
+ /**
2438
+ * A managed resource. Only `name`, `fields` and `list`/`get` are required;
2439
+ * omit a write callback to make that operation unavailable (405).
2440
+ */
2441
+ interface AdminResource<T = unknown> {
2442
+ /** URL-safe resource slug (e.g. `users`). */
2443
+ name: string;
2444
+ /** Field descriptors for list/detail/form rendering. */
2445
+ fields: AdminField[];
2446
+ /** Return a page of records. */
2447
+ list(query: AdminListQuery): Promise<AdminListResult<T>>;
2448
+ /** Return one record by id, or `null` when absent. */
2449
+ get(id: string): Promise<T | null>;
2450
+ /** Create a record from validated input. */
2451
+ create?(data: unknown): Promise<T>;
2452
+ /** Update a record by id from validated input. */
2453
+ update?(id: string, data: unknown): Promise<T>;
2454
+ /** Delete a record by id. */
2455
+ remove?(id: string): Promise<void>;
2456
+ /** Zod schema validating the create body. */
2457
+ createSchema?: z.ZodTypeAny;
2458
+ /** Zod schema validating the update body. */
2459
+ updateSchema?: z.ZodTypeAny;
2460
+ }
2461
+ /** A registry of admin resources. */
2462
+ declare class AdminSite {
2463
+ readonly brand: string;
2464
+ private readonly resources;
2465
+ /**
2466
+ * @param brand - Display name surfaced under `GET {prefix}/`.
2467
+ */
2468
+ constructor(brand?: string);
2469
+ /**
2470
+ * Register a resource.
2471
+ *
2472
+ * @param resource - The resource config.
2473
+ * @returns The same resource (for chaining).
2474
+ */
2475
+ register<T>(resource: AdminResource<T>): AdminResource<T>;
2476
+ /** Look up a resource by slug, or `null`. */
2477
+ get(name: string): AdminResource | null;
2478
+ /** Every registered resource. */
2479
+ list(): AdminResource[];
2480
+ }
2481
+
2482
+ /**
2483
+ * Admin JSON router, mirroring `admin.router.make_admin_router`.
2484
+ *
2485
+ * Exposes auto-derived CRUD + introspection over an {@link AdminSite}:
2486
+ *
2487
+ * ```text
2488
+ * GET {prefix}/ site brand + resource list
2489
+ * GET {prefix}/:resource/_meta resource field descriptors
2490
+ * GET {prefix}/:resource paginated list
2491
+ * GET {prefix}/:resource/:id detail (404 when absent)
2492
+ * POST {prefix}/:resource create (405 if unsupported)
2493
+ * PATCH {prefix}/:resource/:id update (405 if unsupported)
2494
+ * DELETE {prefix}/:resource/:id delete (405 if unsupported)
2495
+ * ```
2496
+ *
2497
+ * Pass a `guard` middleware (e.g. JWT + `requireRoles("admin")`) to protect it.
2498
+ */
2499
+
2500
+ /** Options for {@link makeAdminRouter}. */
2501
+ interface AdminRouterOptions {
2502
+ /** Route prefix. Default `/admin`. */
2503
+ prefix?: string;
2504
+ /** Guard middleware applied to every admin route (auth). */
2505
+ guard?: RequestHandler;
2506
+ }
2507
+ /**
2508
+ * Build the admin router.
2509
+ *
2510
+ * @param site - The registered {@link AdminSite}.
2511
+ * @param options - Prefix and guard middleware.
2512
+ * @returns An Express router with the admin endpoints mounted.
2513
+ */
2514
+ declare function makeAdminRouter(site: AdminSite, options?: AdminRouterOptions): Router;
2515
+
2247
2516
  /**
2248
2517
  * Auth DTOs (Zod), mirroring `auth.schemas`.
2249
2518
  *
@@ -2836,6 +3105,6 @@ interface RunServerOptions {
2836
3105
  declare function runServer(app: Express, options?: RunServerOptions): Promise<Server>;
2837
3106
 
2838
3107
  /** The installed SDK version. Single source of truth for the barrel + CLI. */
2839
- declare const VERSION = "0.3.0";
3108
+ declare const VERSION = "0.5.0";
2840
3109
 
2841
- export { AppException, type AppExceptionHandlerOptions, type AppExceptionOptions, type AttachWebSocketOptions, AttemptThrottle, type AttemptThrottleOptions, type AuthResponse, type AuthRouterOptions, type AuthUser, type BaseAppSettings, BaseController, BaseModel, type BaseResponse, BaseService, type BrokerManager, CEP_PATTERN, CNPJ_PATTERN, CPF_PATTERN, type CPUMetrics, type CacheManager, type CachedOptions, type CatalogData, CircuitOpenError, type ClientIpOptions, CompositeFeatureFlagBackend, ConflictException, type CreateAppOpenApi, type CreateAppOptions, type CursorPaginationFilter, DEFAULT_LOCALE, type EmailMessage, type EmailOptions, EmailUtils, type Enum, type EnumHelpers, type EnumSpec, EnvFeatureFlagBackend, EventStream, type EventStreamOptions, type ExceptionDetails, ExpiredTokenException, type FeatureFlagBackend, FeatureFlags, type FlagContext, ForbiddenException, type GenerateOpenApiOptions, HTTPClient, type HTTPClientOptions, HTTP_500_MARKER, type HandshakeInfo, type HealthCheck, type HealthRouterOptions, InvalidTokenException, type IssuedSession, JSONLogger, JWTUtils, type JWTUtilsOptions, type JwtAuthOptions, type JwtClaims, LocalUploadStorage, type LocalUploadStorageOptions, type LogExtra, type LogLevel, type LoginInput, MemoryBroker, MemoryCacheManager, MemoryFeatureFlagBackend, type MemoryMetrics, MemorySessionStore, MemoryThrottleBackend, MessageCatalog, type MessageHandler, MetricsUtils, NotFoundException, type OpenApiDocument, type OpenApiInfo, PHONE_BR_PATTERN, type PaginationFilter, PasswordUtils, REQUEST_ID_HEADER, RabbitBroker, type RabbitBrokerOptions, RedisCacheManager, type RedisLike, type RedocOptions, type RefreshInput, Region, type RegionValue, type RegisterExceptionHandlersOptions, type RequestContext, type ResponseMapper, RetryPolicy, type RunServerOptions, SSEBroker, type SaveOptions, ServerSentEvent, type ServerSentEventInit, type Session, type SessionMiddlewareOptions, SessionService, type SessionServiceOptions, type SessionStore, type SignupInput, type StateBR, type SwaggerOptions, type SystemMetrics, TOTPHelper, type TOTPOptions, type TaskHandler, TaskManager, type TaskManagerOptions, type ThrottleBackend, type ThrottleStatus, type ToDictOptions, type TokenPair, TooManyRequestsException, type TooManyRequestsOptions, UF, type UFValue, UnauthorizedException, type UnhandledExceptionHandlerOptions, type UploadResult, type UploadStorage, UserAuthService, type UserAuthServiceOptions, type UserPublic, type UserStore, VERSION, ValidationException, type WSEnvelope, WebPushDispatcher, type WebPushDispatcherOptions, WebPushError, WebPushGoneError, type WebPushKeys, type WebPushPayload, type WebPushSubscription, type WebSocketConnection, WebSocketHub, type WebSocketHubOptions, type WebSocketLike, attachWebSocketHub, authResponseSchema, baseAppSettingsSchema, baseAppSettingsShape, baseResponseSchema, bearerToken, buildContentDisposition, cached, cepField, citiesByUf, cnpjField, coerceFlag, configureLogging, corsSettingsShape, cpfField, cpfOrCnpjField, createApp, createOpenApiRegistry, createdByColumn, cursorPaginationFilterSchema, cursorPaginationSchema, databaseSettingsShape, decodeCursor, defaultMessageCatalog, defineEnum, deletedAtColumn, encodeCursor, generateOpaqueToken, generateOpenApiDocument, getAuth, getClientIp, getConditions, getPaginationConditions, getRequestId, getState, hashOpaqueToken, isValidCep, isValidCity, isValidCnpj, isValidCpf, isValidCpfCnpj, isValidPhoneBr, isValidUf, listStates, loadSettings, loginSchema, makeAppExceptionHandler, makeAuthRouter, makeFlagGuard, makeHealthRouter, makeJwtAuthMiddleware, makeSessionMiddleware, makeUnhandledExceptionHandler, modifyDict, mountOpenApiJson, mountRedoc, mountSwaggerUi, normalizeCep, normalizeCnpj, normalizeCpf, normalizeCpfCnpj, normalizePhoneBr, normalizeUf, notFoundHandler, onlyDigits, paginationFilterSchema, paginationSchema, parseAcceptLanguage, parseCookies, phoneBrField, refreshSchema, registerExceptionHandlers, requestIdMiddleware, requireRoles, runServer, runWithRequestContext, serverSettingsShape, sessionCookie, setRequestId, signupSchema, sseResponse, statesByRegion, tableNameFor, toDict, toUtc, tokenFromUrl, tokenPairSchema, ufField, updatedByColumn, userPublicSchema, utcnow, verifyOpaqueToken, webPushKeysSchema, webPushPayloadSchema, webPushSubscriptionSchema, wsEnvelopeSchema };
3110
+ export { type AdminField, type AdminListQuery, type AdminListResult, type AdminResource, type AdminRouterOptions, AdminSite, AppException, type AppExceptionHandlerOptions, type AppExceptionOptions, type AttachWebSocketOptions, AttemptThrottle, type AttemptThrottleOptions, type AuthResponse, type AuthRouterOptions, type AuthUser, type BaseAppSettings, BaseController, BaseModel, type BaseResponse, BaseService, type BrokerManager, CEP_PATTERN, CNPJ_PATTERN, CPF_PATTERN, type CPUMetrics, type CacheManager, type CachedOptions, type CatalogData, CircuitOpenError, type ClientIpOptions, CompositeFeatureFlagBackend, ConflictException, type CreateAppOpenApi, type CreateAppOptions, type CursorPaginationFilter, DEFAULT_LOCALE, type EmailMessage, type EmailOptions, EmailUtils, type Enum, type EnumHelpers, type EnumSpec, EnvFeatureFlagBackend, EventStream, type EventStreamOptions, type ExceptionDetails, ExpiredTokenException, type FeatureFlagBackend, FeatureFlags, type FlagContext, ForbiddenException, type GenerateOpenApiOptions, HTTPClient, type HTTPClientOptions, HTTP_500_MARKER, type HandshakeInfo, type HealthCheck, type HealthRouterOptions, type InboundHandler, type InboundMessage, InvalidTokenException, type IssuedSession, JSONLogger, JWTUtils, type JWTUtilsOptions, type JwtAuthOptions, type JwtClaims, LocalUploadStorage, type LocalUploadStorageOptions, type LogExtra, type LogLevel, type LoginInput, type MediaKind, MemoryBroker, MemoryCacheManager, MemoryFeatureFlagBackend, type MemoryMetrics, MemorySessionStore, MemoryThrottleBackend, MessageCatalog, type MessageHandler, type MessagingProvider, MetricsUtils, NotFoundException, type OpenApiDocument, type OpenApiInfo, type OutboundMedia, type OutboundResult, PHONE_BR_PATTERN, type PaginationFilter, PasswordUtils, REQUEST_ID_HEADER, RabbitBroker, type RabbitBrokerOptions, RedisCacheManager, type RedisLike, type RedocOptions, type RefreshInput, Region, type RegionValue, type RegisterExceptionHandlersOptions, type RequestContext, type ResponseMapper, RetryPolicy, type RunServerOptions, SSEBroker, type SaveOptions, type SendOptions, ServerSentEvent, type ServerSentEventInit, type Session, type SessionMiddlewareOptions, SessionService, type SessionServiceOptions, type SessionStore, type SignupInput, type StateBR, type SwaggerOptions, type SystemMetrics, TOTPHelper, type TOTPOptions, type TaskHandler, TaskManager, type TaskManagerOptions, type ThrottleBackend, type ThrottleStatus, type ToDictOptions, type TokenPair, TooManyRequestsException, type TooManyRequestsOptions, UF, type UFValue, UnauthorizedException, type UnhandledExceptionHandlerOptions, type UploadResult, type UploadStorage, UserAuthService, type UserAuthServiceOptions, type UserPublic, type UserStore, VERSION, ValidationException, type WSEnvelope, WebPushDispatcher, type WebPushDispatcherOptions, WebPushError, WebPushGoneError, type WebPushKeys, type WebPushPayload, type WebPushSubscription, type WebSocketConnection, WebSocketHub, type WebSocketHubOptions, type WebSocketLike, WhatsAppProvider, type WhatsAppProviderOptions, type WhatsAppWebhookOptions, attachWebSocketHub, authResponseSchema, baseAppSettingsSchema, baseAppSettingsShape, baseResponseSchema, bearerToken, buildContentDisposition, cached, cepField, citiesByUf, cnpjField, coerceFlag, configureLogging, corsSettingsShape, cpfField, cpfOrCnpjField, createApp, createOpenApiRegistry, createdByColumn, cursorPaginationFilterSchema, cursorPaginationSchema, databaseSettingsShape, decodeCursor, defaultMessageCatalog, defineEnum, deletedAtColumn, encodeCursor, generateOpaqueToken, generateOpenApiDocument, getAuth, getClientIp, getConditions, getPaginationConditions, getRequestId, getState, hashOpaqueToken, inboundMessageSchema, isValidCep, isValidCity, isValidCnpj, isValidCpf, isValidCpfCnpj, isValidPhoneBr, isValidUf, listStates, loadSettings, loginSchema, makeAdminRouter, makeAppExceptionHandler, makeAuthRouter, makeFlagGuard, makeHealthRouter, makeJwtAuthMiddleware, makeSessionMiddleware, makeUnhandledExceptionHandler, makeWhatsAppWebhookRouter, modifyDict, mountOpenApiJson, mountRedoc, mountSwaggerUi, normalizeCep, normalizeCnpj, normalizeCpf, normalizeCpfCnpj, normalizePhoneBr, normalizeUf, notFoundHandler, onlyDigits, paginationFilterSchema, paginationSchema, parseAcceptLanguage, parseCookies, phoneBrField, refreshSchema, registerExceptionHandlers, requestIdMiddleware, requireRoles, runServer, runWithRequestContext, serverSettingsShape, sessionCookie, setRequestId, signupSchema, sseResponse, statesByRegion, tableNameFor, toDict, toUtc, tokenFromUrl, tokenPairSchema, ufField, updatedByColumn, userPublicSchema, utcnow, verifyOpaqueToken, webPushKeysSchema, webPushPayloadSchema, webPushSubscriptionSchema, wsEnvelopeSchema };
package/dist/index.d.ts CHANGED
@@ -2244,6 +2244,275 @@ declare class WebPushDispatcher {
2244
2244
  send(subscription: WebPushSubscription, payload: WebPushPayload): Promise<void>;
2245
2245
  }
2246
2246
 
2247
+ /**
2248
+ * Messaging integration contracts.
2249
+ *
2250
+ * A channel-agnostic {@link MessagingProvider} so WhatsApp, SMS and future
2251
+ * channels share one shape and are swappable in tests. The first implementation
2252
+ * is {@link WhatsAppProvider} (a client for the `zap-api` service).
2253
+ */
2254
+
2255
+ /** Supported media kinds for {@link MessagingProvider.sendMedia}. */
2256
+ type MediaKind = "image" | "video" | "audio" | "document";
2257
+ /** A media message to send. */
2258
+ interface OutboundMedia {
2259
+ /** The media kind (selects the underlying route). */
2260
+ kind: MediaKind;
2261
+ /** A public `http(s)://` URL or a `data:` URI. */
2262
+ media: string;
2263
+ /** Optional caption (image/video). */
2264
+ caption?: string;
2265
+ /** File name with extension (required for `document`). */
2266
+ fileName?: string;
2267
+ }
2268
+ /** The result of enqueuing an outbound message. */
2269
+ interface OutboundResult {
2270
+ /** Provider message id, when returned. */
2271
+ id?: string;
2272
+ /** Provider status string (e.g. `"queued"`, `"sent"`). */
2273
+ status: string;
2274
+ /** Whether the send was de-duplicated by an idempotency key. */
2275
+ deduped?: boolean;
2276
+ }
2277
+ /** Options accepted by send operations. */
2278
+ interface SendOptions {
2279
+ /** Idempotency key to de-duplicate retries on the provider side. */
2280
+ idempotencyKey?: string;
2281
+ }
2282
+ /** A normalized inbound (or echoed outbound) message. */
2283
+ declare const inboundMessageSchema: z.ZodObject<{
2284
+ /** Conversation JID / sender (e.g. `5511999999999@s.whatsapp.net`). */
2285
+ from: z.ZodString;
2286
+ /** Provider message id. */
2287
+ messageId: z.ZodString;
2288
+ /** Text body, when present. */
2289
+ text: z.ZodOptional<z.ZodString>;
2290
+ /** Media kind, or `null` for plain text. */
2291
+ mediaType: z.ZodNullable<z.ZodEnum<["image", "video", "audio", "document", "sticker"]>>;
2292
+ /** ISO-8601 timestamp. */
2293
+ timestamp: z.ZodString;
2294
+ /** Delivery direction. */
2295
+ direction: z.ZodOptional<z.ZodEnum<["incoming", "outgoing"]>>;
2296
+ }, "strip", z.ZodTypeAny, {
2297
+ from: string;
2298
+ messageId: string;
2299
+ mediaType: "image" | "video" | "audio" | "document" | "sticker" | null;
2300
+ timestamp: string;
2301
+ text?: string | undefined;
2302
+ direction?: "incoming" | "outgoing" | undefined;
2303
+ }, {
2304
+ from: string;
2305
+ messageId: string;
2306
+ mediaType: "image" | "video" | "audio" | "document" | "sticker" | null;
2307
+ timestamp: string;
2308
+ text?: string | undefined;
2309
+ direction?: "incoming" | "outgoing" | undefined;
2310
+ }>;
2311
+ /** A normalized inbound message. */
2312
+ type InboundMessage = z.infer<typeof inboundMessageSchema>;
2313
+ /** Handler invoked for each inbound message. */
2314
+ type InboundHandler = (message: InboundMessage) => Promise<void> | void;
2315
+ /** A channel-agnostic messaging provider. */
2316
+ interface MessagingProvider {
2317
+ /** Send a text message. */
2318
+ sendText(to: string, text: string, options?: SendOptions): Promise<OutboundResult>;
2319
+ /** Send a media message. */
2320
+ sendMedia(to: string, media: OutboundMedia, options?: SendOptions): Promise<OutboundResult>;
2321
+ /** Whether a number exists on the channel. */
2322
+ checkNumber(number: string): Promise<boolean>;
2323
+ /** The current session/connection status. */
2324
+ status(): Promise<string>;
2325
+ /**
2326
+ * Subscribe to inbound messages; resolves to an unsubscribe function.
2327
+ *
2328
+ * @param handler - Invoked for each inbound message.
2329
+ * @param room - Conversation to scope to; `"*"` for all. Default `"*"`.
2330
+ */
2331
+ onMessage(handler: InboundHandler, room?: string): Promise<() => Promise<void>>;
2332
+ }
2333
+
2334
+ /**
2335
+ * WhatsApp provider — a typed client for the `zap-api` service.
2336
+ *
2337
+ * REST for sending (`/message/send-*`, `/message/check-number`) and session
2338
+ * control (`/session/*`); the `/ws` pub/sub for receiving inbound messages in
2339
+ * real time. HTTP goes through the SDK's resilient {@link HTTPClient}; the
2340
+ * WebSocket subscription uses the optional `ws` peer (lazily imported).
2341
+ *
2342
+ * @see https://github.com/mauriciobenjamin700 (zap-api)
2343
+ */
2344
+
2345
+ /** Options for {@link WhatsAppProvider}. */
2346
+ interface WhatsAppProviderOptions {
2347
+ /** Base URL of the `zap-api` instance, e.g. `https://zap.example.com`. */
2348
+ baseUrl: string;
2349
+ /** Consumer API key (sent as `x-api-key`). */
2350
+ apiKey: string;
2351
+ /** WebSocket URL. Defaults to `baseUrl` with `http(s)`→`ws(s)` + `/ws`. */
2352
+ wsUrl?: string;
2353
+ /** Per-request timeout in ms. Default 15000. */
2354
+ timeoutMs?: number;
2355
+ }
2356
+ /** A typed client for a running `zap-api` WhatsApp gateway. */
2357
+ declare class WhatsAppProvider implements MessagingProvider {
2358
+ private readonly http;
2359
+ private readonly apiKey;
2360
+ private readonly wsUrl;
2361
+ /**
2362
+ * @param options - Base URL, API key and optional WebSocket URL.
2363
+ */
2364
+ constructor(options: WhatsAppProviderOptions);
2365
+ /** POST JSON and parse the response, throwing on a non-2xx status. */
2366
+ private postJson;
2367
+ sendText(to: string, text: string, options?: SendOptions): Promise<OutboundResult>;
2368
+ sendMedia(to: string, media: OutboundMedia, options?: SendOptions): Promise<OutboundResult>;
2369
+ checkNumber(number: string): Promise<boolean>;
2370
+ status(): Promise<string>;
2371
+ /** Start the WhatsApp session (returns the authenticated QR URL, if any). */
2372
+ startSession(): Promise<Record<string, unknown>>;
2373
+ onMessage(handler: InboundHandler, room?: string): Promise<() => Promise<void>>;
2374
+ }
2375
+
2376
+ /**
2377
+ * WhatsApp inbound-webhook receiver.
2378
+ *
2379
+ * `zap-api` POSTs every received message to a configured webhook. This builds
2380
+ * an Express router that (optionally) validates the shared `x-api-key`, parses
2381
+ * the payload into a typed {@link InboundMessage}, and hands it to your handler.
2382
+ */
2383
+
2384
+ /** Options for {@link makeWhatsAppWebhookRouter}. */
2385
+ interface WhatsAppWebhookOptions {
2386
+ /** Handler invoked for each validated inbound message. */
2387
+ onMessage: InboundHandler;
2388
+ /** Route path. Default `/whatsapp/inbound`. */
2389
+ path?: string;
2390
+ /** Shared secret expected in `x-api-key`. Omit to skip auth (dev only). */
2391
+ apiKey?: string;
2392
+ }
2393
+ /**
2394
+ * Build the inbound-webhook router.
2395
+ *
2396
+ * @param options - Handler, path and optional shared secret.
2397
+ * @returns An Express router with the webhook endpoint mounted.
2398
+ */
2399
+ declare function makeWhatsAppWebhookRouter(options: WhatsAppWebhookOptions): Router;
2400
+
2401
+ /**
2402
+ * Admin site + resource registry, mirroring `admin.site` / `admin.config`.
2403
+ *
2404
+ * The FastAPI SDK ships a server-rendered (jinja) admin UI. Here the admin is a
2405
+ * typed **JSON API**: register one {@link AdminResource} per managed entity and
2406
+ * {@link makeAdminRouter} exposes auto-derived CRUD + introspection endpoints a
2407
+ * frontend (React, etc.) renders. Resources are callback-based, so they wire to
2408
+ * a `BaseService` — or any store — in a few lines and stay ORM-agnostic.
2409
+ */
2410
+
2411
+ /** A field descriptor a frontend uses to render list columns / form inputs. */
2412
+ interface AdminField {
2413
+ /** Field name (property key). */
2414
+ name: string;
2415
+ /** Loose type hint for rendering (`string`, `number`, `boolean`, `date`, …). */
2416
+ type?: string;
2417
+ /** Whether the field is required on create. */
2418
+ required?: boolean;
2419
+ /** Whether the field is read-only (shown, never submitted). */
2420
+ readOnly?: boolean;
2421
+ }
2422
+ /** A paginated list result returned by {@link AdminResource.list}. */
2423
+ interface AdminListResult<T = unknown> {
2424
+ items: T[];
2425
+ total: number;
2426
+ page: number;
2427
+ pageSize: number;
2428
+ pages: number;
2429
+ }
2430
+ /** Query parameters passed to {@link AdminResource.list}. */
2431
+ interface AdminListQuery {
2432
+ page: number;
2433
+ pageSize: number;
2434
+ /** Remaining query-string entries (domain filters). */
2435
+ filters: Record<string, string>;
2436
+ }
2437
+ /**
2438
+ * A managed resource. Only `name`, `fields` and `list`/`get` are required;
2439
+ * omit a write callback to make that operation unavailable (405).
2440
+ */
2441
+ interface AdminResource<T = unknown> {
2442
+ /** URL-safe resource slug (e.g. `users`). */
2443
+ name: string;
2444
+ /** Field descriptors for list/detail/form rendering. */
2445
+ fields: AdminField[];
2446
+ /** Return a page of records. */
2447
+ list(query: AdminListQuery): Promise<AdminListResult<T>>;
2448
+ /** Return one record by id, or `null` when absent. */
2449
+ get(id: string): Promise<T | null>;
2450
+ /** Create a record from validated input. */
2451
+ create?(data: unknown): Promise<T>;
2452
+ /** Update a record by id from validated input. */
2453
+ update?(id: string, data: unknown): Promise<T>;
2454
+ /** Delete a record by id. */
2455
+ remove?(id: string): Promise<void>;
2456
+ /** Zod schema validating the create body. */
2457
+ createSchema?: z.ZodTypeAny;
2458
+ /** Zod schema validating the update body. */
2459
+ updateSchema?: z.ZodTypeAny;
2460
+ }
2461
+ /** A registry of admin resources. */
2462
+ declare class AdminSite {
2463
+ readonly brand: string;
2464
+ private readonly resources;
2465
+ /**
2466
+ * @param brand - Display name surfaced under `GET {prefix}/`.
2467
+ */
2468
+ constructor(brand?: string);
2469
+ /**
2470
+ * Register a resource.
2471
+ *
2472
+ * @param resource - The resource config.
2473
+ * @returns The same resource (for chaining).
2474
+ */
2475
+ register<T>(resource: AdminResource<T>): AdminResource<T>;
2476
+ /** Look up a resource by slug, or `null`. */
2477
+ get(name: string): AdminResource | null;
2478
+ /** Every registered resource. */
2479
+ list(): AdminResource[];
2480
+ }
2481
+
2482
+ /**
2483
+ * Admin JSON router, mirroring `admin.router.make_admin_router`.
2484
+ *
2485
+ * Exposes auto-derived CRUD + introspection over an {@link AdminSite}:
2486
+ *
2487
+ * ```text
2488
+ * GET {prefix}/ site brand + resource list
2489
+ * GET {prefix}/:resource/_meta resource field descriptors
2490
+ * GET {prefix}/:resource paginated list
2491
+ * GET {prefix}/:resource/:id detail (404 when absent)
2492
+ * POST {prefix}/:resource create (405 if unsupported)
2493
+ * PATCH {prefix}/:resource/:id update (405 if unsupported)
2494
+ * DELETE {prefix}/:resource/:id delete (405 if unsupported)
2495
+ * ```
2496
+ *
2497
+ * Pass a `guard` middleware (e.g. JWT + `requireRoles("admin")`) to protect it.
2498
+ */
2499
+
2500
+ /** Options for {@link makeAdminRouter}. */
2501
+ interface AdminRouterOptions {
2502
+ /** Route prefix. Default `/admin`. */
2503
+ prefix?: string;
2504
+ /** Guard middleware applied to every admin route (auth). */
2505
+ guard?: RequestHandler;
2506
+ }
2507
+ /**
2508
+ * Build the admin router.
2509
+ *
2510
+ * @param site - The registered {@link AdminSite}.
2511
+ * @param options - Prefix and guard middleware.
2512
+ * @returns An Express router with the admin endpoints mounted.
2513
+ */
2514
+ declare function makeAdminRouter(site: AdminSite, options?: AdminRouterOptions): Router;
2515
+
2247
2516
  /**
2248
2517
  * Auth DTOs (Zod), mirroring `auth.schemas`.
2249
2518
  *
@@ -2836,6 +3105,6 @@ interface RunServerOptions {
2836
3105
  declare function runServer(app: Express, options?: RunServerOptions): Promise<Server>;
2837
3106
 
2838
3107
  /** The installed SDK version. Single source of truth for the barrel + CLI. */
2839
- declare const VERSION = "0.3.0";
3108
+ declare const VERSION = "0.5.0";
2840
3109
 
2841
- export { AppException, type AppExceptionHandlerOptions, type AppExceptionOptions, type AttachWebSocketOptions, AttemptThrottle, type AttemptThrottleOptions, type AuthResponse, type AuthRouterOptions, type AuthUser, type BaseAppSettings, BaseController, BaseModel, type BaseResponse, BaseService, type BrokerManager, CEP_PATTERN, CNPJ_PATTERN, CPF_PATTERN, type CPUMetrics, type CacheManager, type CachedOptions, type CatalogData, CircuitOpenError, type ClientIpOptions, CompositeFeatureFlagBackend, ConflictException, type CreateAppOpenApi, type CreateAppOptions, type CursorPaginationFilter, DEFAULT_LOCALE, type EmailMessage, type EmailOptions, EmailUtils, type Enum, type EnumHelpers, type EnumSpec, EnvFeatureFlagBackend, EventStream, type EventStreamOptions, type ExceptionDetails, ExpiredTokenException, type FeatureFlagBackend, FeatureFlags, type FlagContext, ForbiddenException, type GenerateOpenApiOptions, HTTPClient, type HTTPClientOptions, HTTP_500_MARKER, type HandshakeInfo, type HealthCheck, type HealthRouterOptions, InvalidTokenException, type IssuedSession, JSONLogger, JWTUtils, type JWTUtilsOptions, type JwtAuthOptions, type JwtClaims, LocalUploadStorage, type LocalUploadStorageOptions, type LogExtra, type LogLevel, type LoginInput, MemoryBroker, MemoryCacheManager, MemoryFeatureFlagBackend, type MemoryMetrics, MemorySessionStore, MemoryThrottleBackend, MessageCatalog, type MessageHandler, MetricsUtils, NotFoundException, type OpenApiDocument, type OpenApiInfo, PHONE_BR_PATTERN, type PaginationFilter, PasswordUtils, REQUEST_ID_HEADER, RabbitBroker, type RabbitBrokerOptions, RedisCacheManager, type RedisLike, type RedocOptions, type RefreshInput, Region, type RegionValue, type RegisterExceptionHandlersOptions, type RequestContext, type ResponseMapper, RetryPolicy, type RunServerOptions, SSEBroker, type SaveOptions, ServerSentEvent, type ServerSentEventInit, type Session, type SessionMiddlewareOptions, SessionService, type SessionServiceOptions, type SessionStore, type SignupInput, type StateBR, type SwaggerOptions, type SystemMetrics, TOTPHelper, type TOTPOptions, type TaskHandler, TaskManager, type TaskManagerOptions, type ThrottleBackend, type ThrottleStatus, type ToDictOptions, type TokenPair, TooManyRequestsException, type TooManyRequestsOptions, UF, type UFValue, UnauthorizedException, type UnhandledExceptionHandlerOptions, type UploadResult, type UploadStorage, UserAuthService, type UserAuthServiceOptions, type UserPublic, type UserStore, VERSION, ValidationException, type WSEnvelope, WebPushDispatcher, type WebPushDispatcherOptions, WebPushError, WebPushGoneError, type WebPushKeys, type WebPushPayload, type WebPushSubscription, type WebSocketConnection, WebSocketHub, type WebSocketHubOptions, type WebSocketLike, attachWebSocketHub, authResponseSchema, baseAppSettingsSchema, baseAppSettingsShape, baseResponseSchema, bearerToken, buildContentDisposition, cached, cepField, citiesByUf, cnpjField, coerceFlag, configureLogging, corsSettingsShape, cpfField, cpfOrCnpjField, createApp, createOpenApiRegistry, createdByColumn, cursorPaginationFilterSchema, cursorPaginationSchema, databaseSettingsShape, decodeCursor, defaultMessageCatalog, defineEnum, deletedAtColumn, encodeCursor, generateOpaqueToken, generateOpenApiDocument, getAuth, getClientIp, getConditions, getPaginationConditions, getRequestId, getState, hashOpaqueToken, isValidCep, isValidCity, isValidCnpj, isValidCpf, isValidCpfCnpj, isValidPhoneBr, isValidUf, listStates, loadSettings, loginSchema, makeAppExceptionHandler, makeAuthRouter, makeFlagGuard, makeHealthRouter, makeJwtAuthMiddleware, makeSessionMiddleware, makeUnhandledExceptionHandler, modifyDict, mountOpenApiJson, mountRedoc, mountSwaggerUi, normalizeCep, normalizeCnpj, normalizeCpf, normalizeCpfCnpj, normalizePhoneBr, normalizeUf, notFoundHandler, onlyDigits, paginationFilterSchema, paginationSchema, parseAcceptLanguage, parseCookies, phoneBrField, refreshSchema, registerExceptionHandlers, requestIdMiddleware, requireRoles, runServer, runWithRequestContext, serverSettingsShape, sessionCookie, setRequestId, signupSchema, sseResponse, statesByRegion, tableNameFor, toDict, toUtc, tokenFromUrl, tokenPairSchema, ufField, updatedByColumn, userPublicSchema, utcnow, verifyOpaqueToken, webPushKeysSchema, webPushPayloadSchema, webPushSubscriptionSchema, wsEnvelopeSchema };
3110
+ export { type AdminField, type AdminListQuery, type AdminListResult, type AdminResource, type AdminRouterOptions, AdminSite, AppException, type AppExceptionHandlerOptions, type AppExceptionOptions, type AttachWebSocketOptions, AttemptThrottle, type AttemptThrottleOptions, type AuthResponse, type AuthRouterOptions, type AuthUser, type BaseAppSettings, BaseController, BaseModel, type BaseResponse, BaseService, type BrokerManager, CEP_PATTERN, CNPJ_PATTERN, CPF_PATTERN, type CPUMetrics, type CacheManager, type CachedOptions, type CatalogData, CircuitOpenError, type ClientIpOptions, CompositeFeatureFlagBackend, ConflictException, type CreateAppOpenApi, type CreateAppOptions, type CursorPaginationFilter, DEFAULT_LOCALE, type EmailMessage, type EmailOptions, EmailUtils, type Enum, type EnumHelpers, type EnumSpec, EnvFeatureFlagBackend, EventStream, type EventStreamOptions, type ExceptionDetails, ExpiredTokenException, type FeatureFlagBackend, FeatureFlags, type FlagContext, ForbiddenException, type GenerateOpenApiOptions, HTTPClient, type HTTPClientOptions, HTTP_500_MARKER, type HandshakeInfo, type HealthCheck, type HealthRouterOptions, type InboundHandler, type InboundMessage, InvalidTokenException, type IssuedSession, JSONLogger, JWTUtils, type JWTUtilsOptions, type JwtAuthOptions, type JwtClaims, LocalUploadStorage, type LocalUploadStorageOptions, type LogExtra, type LogLevel, type LoginInput, type MediaKind, MemoryBroker, MemoryCacheManager, MemoryFeatureFlagBackend, type MemoryMetrics, MemorySessionStore, MemoryThrottleBackend, MessageCatalog, type MessageHandler, type MessagingProvider, MetricsUtils, NotFoundException, type OpenApiDocument, type OpenApiInfo, type OutboundMedia, type OutboundResult, PHONE_BR_PATTERN, type PaginationFilter, PasswordUtils, REQUEST_ID_HEADER, RabbitBroker, type RabbitBrokerOptions, RedisCacheManager, type RedisLike, type RedocOptions, type RefreshInput, Region, type RegionValue, type RegisterExceptionHandlersOptions, type RequestContext, type ResponseMapper, RetryPolicy, type RunServerOptions, SSEBroker, type SaveOptions, type SendOptions, ServerSentEvent, type ServerSentEventInit, type Session, type SessionMiddlewareOptions, SessionService, type SessionServiceOptions, type SessionStore, type SignupInput, type StateBR, type SwaggerOptions, type SystemMetrics, TOTPHelper, type TOTPOptions, type TaskHandler, TaskManager, type TaskManagerOptions, type ThrottleBackend, type ThrottleStatus, type ToDictOptions, type TokenPair, TooManyRequestsException, type TooManyRequestsOptions, UF, type UFValue, UnauthorizedException, type UnhandledExceptionHandlerOptions, type UploadResult, type UploadStorage, UserAuthService, type UserAuthServiceOptions, type UserPublic, type UserStore, VERSION, ValidationException, type WSEnvelope, WebPushDispatcher, type WebPushDispatcherOptions, WebPushError, WebPushGoneError, type WebPushKeys, type WebPushPayload, type WebPushSubscription, type WebSocketConnection, WebSocketHub, type WebSocketHubOptions, type WebSocketLike, WhatsAppProvider, type WhatsAppProviderOptions, type WhatsAppWebhookOptions, attachWebSocketHub, authResponseSchema, baseAppSettingsSchema, baseAppSettingsShape, baseResponseSchema, bearerToken, buildContentDisposition, cached, cepField, citiesByUf, cnpjField, coerceFlag, configureLogging, corsSettingsShape, cpfField, cpfOrCnpjField, createApp, createOpenApiRegistry, createdByColumn, cursorPaginationFilterSchema, cursorPaginationSchema, databaseSettingsShape, decodeCursor, defaultMessageCatalog, defineEnum, deletedAtColumn, encodeCursor, generateOpaqueToken, generateOpenApiDocument, getAuth, getClientIp, getConditions, getPaginationConditions, getRequestId, getState, hashOpaqueToken, inboundMessageSchema, isValidCep, isValidCity, isValidCnpj, isValidCpf, isValidCpfCnpj, isValidPhoneBr, isValidUf, listStates, loadSettings, loginSchema, makeAdminRouter, makeAppExceptionHandler, makeAuthRouter, makeFlagGuard, makeHealthRouter, makeJwtAuthMiddleware, makeSessionMiddleware, makeUnhandledExceptionHandler, makeWhatsAppWebhookRouter, modifyDict, mountOpenApiJson, mountRedoc, mountSwaggerUi, normalizeCep, normalizeCnpj, normalizeCpf, normalizeCpfCnpj, normalizePhoneBr, normalizeUf, notFoundHandler, onlyDigits, paginationFilterSchema, paginationSchema, parseAcceptLanguage, parseCookies, phoneBrField, refreshSchema, registerExceptionHandlers, requestIdMiddleware, requireRoles, runServer, runWithRequestContext, serverSettingsShape, sessionCookie, setRequestId, signupSchema, sseResponse, statesByRegion, tableNameFor, toDict, toUtc, tokenFromUrl, tokenPairSchema, ufField, updatedByColumn, userPublicSchema, utcnow, verifyOpaqueToken, webPushKeysSchema, webPushPayloadSchema, webPushSubscriptionSchema, wsEnvelopeSchema };