tempest-express-sdk 0.5.0 → 0.6.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/README.md +3 -4
- package/dist/chunk-3IDD2UXU.js +6 -0
- package/dist/{chunk-ZU6W433I.js.map → chunk-3IDD2UXU.js.map} +1 -1
- package/dist/cli.cjs +1 -1
- package/dist/cli.cjs.map +1 -1
- package/dist/cli.js +1 -1
- package/dist/index.cjs +189 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +120 -6
- package/dist/index.d.ts +120 -6
- package/dist/index.js +186 -2
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-ZU6W433I.js +0 -6
package/dist/index.d.cts
CHANGED
|
@@ -2312,23 +2312,30 @@ declare const inboundMessageSchema: z.ZodObject<{
|
|
|
2312
2312
|
type InboundMessage = z.infer<typeof inboundMessageSchema>;
|
|
2313
2313
|
/** Handler invoked for each inbound message. */
|
|
2314
2314
|
type InboundHandler = (message: InboundMessage) => Promise<void> | void;
|
|
2315
|
-
/**
|
|
2315
|
+
/**
|
|
2316
|
+
* A channel-agnostic messaging provider. `sendText`/`sendMedia`/`status` are
|
|
2317
|
+
* universal; `checkNumber` and `onMessage` are optional because not every
|
|
2318
|
+
* channel supports them (e.g. SMS has no persistent subscription — its inbound
|
|
2319
|
+
* arrives via a webhook receiver instead).
|
|
2320
|
+
*/
|
|
2316
2321
|
interface MessagingProvider {
|
|
2317
2322
|
/** Send a text message. */
|
|
2318
2323
|
sendText(to: string, text: string, options?: SendOptions): Promise<OutboundResult>;
|
|
2319
2324
|
/** Send a media message. */
|
|
2320
2325
|
sendMedia(to: string, media: OutboundMedia, options?: SendOptions): Promise<OutboundResult>;
|
|
2321
|
-
/** Whether a number exists on the channel. */
|
|
2322
|
-
checkNumber(number: string): Promise<boolean>;
|
|
2323
2326
|
/** The current session/connection status. */
|
|
2324
2327
|
status(): Promise<string>;
|
|
2328
|
+
/** Whether a number/handle exists on the channel (when supported). */
|
|
2329
|
+
checkNumber?(number: string): Promise<boolean>;
|
|
2325
2330
|
/**
|
|
2326
2331
|
* Subscribe to inbound messages; resolves to an unsubscribe function.
|
|
2332
|
+
* Present only on channels with a live subscription (WhatsApp `/ws`,
|
|
2333
|
+
* Telegram long-polling).
|
|
2327
2334
|
*
|
|
2328
2335
|
* @param handler - Invoked for each inbound message.
|
|
2329
2336
|
* @param room - Conversation to scope to; `"*"` for all. Default `"*"`.
|
|
2330
2337
|
*/
|
|
2331
|
-
onMessage(handler: InboundHandler, room?: string): Promise<() => Promise<void>>;
|
|
2338
|
+
onMessage?(handler: InboundHandler, room?: string): Promise<() => Promise<void>>;
|
|
2332
2339
|
}
|
|
2333
2340
|
|
|
2334
2341
|
/**
|
|
@@ -2398,6 +2405,113 @@ interface WhatsAppWebhookOptions {
|
|
|
2398
2405
|
*/
|
|
2399
2406
|
declare function makeWhatsAppWebhookRouter(options: WhatsAppWebhookOptions): Router;
|
|
2400
2407
|
|
|
2408
|
+
/**
|
|
2409
|
+
* Telegram provider — a client for the Telegram Bot API.
|
|
2410
|
+
*
|
|
2411
|
+
* Implements {@link MessagingProvider} over the built-in {@link HTTPClient}
|
|
2412
|
+
* (no external SDK). Outbound via `sendMessage`/`sendPhoto`/…; inbound via
|
|
2413
|
+
* `getUpdates` long-polling exposed through {@link TelegramProvider.onMessage}.
|
|
2414
|
+
*/
|
|
2415
|
+
|
|
2416
|
+
/** Options for {@link TelegramProvider}. */
|
|
2417
|
+
interface TelegramProviderOptions {
|
|
2418
|
+
/** Bot token from @BotFather. */
|
|
2419
|
+
token: string;
|
|
2420
|
+
/** API base. Default `https://api.telegram.org`. */
|
|
2421
|
+
apiBase?: string;
|
|
2422
|
+
/** Long-poll timeout in seconds for `getUpdates`. Default 30. */
|
|
2423
|
+
pollTimeoutSeconds?: number;
|
|
2424
|
+
}
|
|
2425
|
+
/** A typed Telegram Bot API client. */
|
|
2426
|
+
declare class TelegramProvider implements MessagingProvider {
|
|
2427
|
+
private readonly http;
|
|
2428
|
+
private readonly pollTimeout;
|
|
2429
|
+
/**
|
|
2430
|
+
* @param options - Bot token and API options.
|
|
2431
|
+
*/
|
|
2432
|
+
constructor(options: TelegramProviderOptions);
|
|
2433
|
+
/** Call a Bot API method, returning the `result`, throwing on `ok: false`. */
|
|
2434
|
+
private call;
|
|
2435
|
+
sendText(to: string, text: string): Promise<OutboundResult>;
|
|
2436
|
+
sendMedia(to: string, media: OutboundMedia): Promise<OutboundResult>;
|
|
2437
|
+
status(): Promise<string>;
|
|
2438
|
+
/**
|
|
2439
|
+
* Subscribe to inbound messages via `getUpdates` long-polling.
|
|
2440
|
+
*
|
|
2441
|
+
* @param handler - Invoked for each inbound text message.
|
|
2442
|
+
* @returns A stop function that ends the polling loop.
|
|
2443
|
+
*/
|
|
2444
|
+
onMessage(handler: InboundHandler): Promise<() => Promise<void>>;
|
|
2445
|
+
}
|
|
2446
|
+
|
|
2447
|
+
/**
|
|
2448
|
+
* SMS provider — a Twilio client + inbound-webhook receiver.
|
|
2449
|
+
*
|
|
2450
|
+
* Implements {@link MessagingProvider} over the built-in {@link HTTPClient}
|
|
2451
|
+
* (no `twilio` SDK). SMS has no persistent subscription, so `onMessage` is
|
|
2452
|
+
* absent — inbound arrives via {@link makeTwilioWebhookRouter}, which validates
|
|
2453
|
+
* the `X-Twilio-Signature` HMAC.
|
|
2454
|
+
*/
|
|
2455
|
+
|
|
2456
|
+
/** Options for {@link TwilioSmsProvider}. */
|
|
2457
|
+
interface TwilioSmsProviderOptions {
|
|
2458
|
+
/** Twilio Account SID. */
|
|
2459
|
+
accountSid: string;
|
|
2460
|
+
/** Twilio Auth Token. */
|
|
2461
|
+
authToken: string;
|
|
2462
|
+
/** Default `From` number (E.164), e.g. `+15551234567`. */
|
|
2463
|
+
from: string;
|
|
2464
|
+
/** API base. Default `https://api.twilio.com`. */
|
|
2465
|
+
apiBase?: string;
|
|
2466
|
+
}
|
|
2467
|
+
/** A Twilio SMS client. */
|
|
2468
|
+
declare class TwilioSmsProvider implements MessagingProvider {
|
|
2469
|
+
private readonly http;
|
|
2470
|
+
private readonly from;
|
|
2471
|
+
private readonly messagesPath;
|
|
2472
|
+
private readonly accountPath;
|
|
2473
|
+
/**
|
|
2474
|
+
* @param options - Account SID, auth token and default sender.
|
|
2475
|
+
*/
|
|
2476
|
+
constructor(options: TwilioSmsProviderOptions);
|
|
2477
|
+
/** POST a form body to Twilio and parse the JSON, throwing on non-2xx. */
|
|
2478
|
+
private postForm;
|
|
2479
|
+
sendText(to: string, text: string): Promise<OutboundResult>;
|
|
2480
|
+
sendMedia(to: string, media: OutboundMedia): Promise<OutboundResult>;
|
|
2481
|
+
status(): Promise<string>;
|
|
2482
|
+
}
|
|
2483
|
+
/**
|
|
2484
|
+
* Validate a Twilio request signature (`X-Twilio-Signature`).
|
|
2485
|
+
*
|
|
2486
|
+
* @param authToken - The Twilio auth token.
|
|
2487
|
+
* @param url - The full public URL Twilio posted to (scheme + host + path).
|
|
2488
|
+
* @param params - The POST form parameters.
|
|
2489
|
+
* @param signature - The `X-Twilio-Signature` header value.
|
|
2490
|
+
* @returns `true` when the signature matches.
|
|
2491
|
+
*/
|
|
2492
|
+
declare function validateTwilioSignature(authToken: string, url: string, params: Record<string, string>, signature: string): boolean;
|
|
2493
|
+
/** Options for {@link makeTwilioWebhookRouter}. */
|
|
2494
|
+
interface TwilioWebhookOptions {
|
|
2495
|
+
/** Handler invoked for each inbound SMS. */
|
|
2496
|
+
onMessage: InboundHandler;
|
|
2497
|
+
/** Route path. Default `/sms/inbound`. */
|
|
2498
|
+
path?: string;
|
|
2499
|
+
/** Auth token; when set, `X-Twilio-Signature` is validated. */
|
|
2500
|
+
authToken?: string;
|
|
2501
|
+
/** Public URL Twilio posts to (needed for signature validation behind a proxy). */
|
|
2502
|
+
publicUrl?: string;
|
|
2503
|
+
}
|
|
2504
|
+
/**
|
|
2505
|
+
* Build the Twilio inbound-SMS webhook router.
|
|
2506
|
+
*
|
|
2507
|
+
* Twilio posts `application/x-www-form-urlencoded` (`From`, `Body`,
|
|
2508
|
+
* `MessageSid`, …). Mount after `express.urlencoded()` (included by `createApp`).
|
|
2509
|
+
*
|
|
2510
|
+
* @param options - Handler, path and signature-validation settings.
|
|
2511
|
+
* @returns An Express router with the webhook endpoint mounted.
|
|
2512
|
+
*/
|
|
2513
|
+
declare function makeTwilioWebhookRouter(options: TwilioWebhookOptions): Router;
|
|
2514
|
+
|
|
2401
2515
|
/**
|
|
2402
2516
|
* Admin site + resource registry, mirroring `admin.site` / `admin.config`.
|
|
2403
2517
|
*
|
|
@@ -3105,6 +3219,6 @@ interface RunServerOptions {
|
|
|
3105
3219
|
declare function runServer(app: Express, options?: RunServerOptions): Promise<Server>;
|
|
3106
3220
|
|
|
3107
3221
|
/** The installed SDK version. Single source of truth for the barrel + CLI. */
|
|
3108
|
-
declare const VERSION = "0.
|
|
3222
|
+
declare const VERSION = "0.6.0";
|
|
3109
3223
|
|
|
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 };
|
|
3224
|
+
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, TelegramProvider, type TelegramProviderOptions, type ThrottleBackend, type ThrottleStatus, type ToDictOptions, type TokenPair, TooManyRequestsException, type TooManyRequestsOptions, TwilioSmsProvider, type TwilioSmsProviderOptions, type TwilioWebhookOptions, 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, makeTwilioWebhookRouter, 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, validateTwilioSignature, verifyOpaqueToken, webPushKeysSchema, webPushPayloadSchema, webPushSubscriptionSchema, wsEnvelopeSchema };
|
package/dist/index.d.ts
CHANGED
|
@@ -2312,23 +2312,30 @@ declare const inboundMessageSchema: z.ZodObject<{
|
|
|
2312
2312
|
type InboundMessage = z.infer<typeof inboundMessageSchema>;
|
|
2313
2313
|
/** Handler invoked for each inbound message. */
|
|
2314
2314
|
type InboundHandler = (message: InboundMessage) => Promise<void> | void;
|
|
2315
|
-
/**
|
|
2315
|
+
/**
|
|
2316
|
+
* A channel-agnostic messaging provider. `sendText`/`sendMedia`/`status` are
|
|
2317
|
+
* universal; `checkNumber` and `onMessage` are optional because not every
|
|
2318
|
+
* channel supports them (e.g. SMS has no persistent subscription — its inbound
|
|
2319
|
+
* arrives via a webhook receiver instead).
|
|
2320
|
+
*/
|
|
2316
2321
|
interface MessagingProvider {
|
|
2317
2322
|
/** Send a text message. */
|
|
2318
2323
|
sendText(to: string, text: string, options?: SendOptions): Promise<OutboundResult>;
|
|
2319
2324
|
/** Send a media message. */
|
|
2320
2325
|
sendMedia(to: string, media: OutboundMedia, options?: SendOptions): Promise<OutboundResult>;
|
|
2321
|
-
/** Whether a number exists on the channel. */
|
|
2322
|
-
checkNumber(number: string): Promise<boolean>;
|
|
2323
2326
|
/** The current session/connection status. */
|
|
2324
2327
|
status(): Promise<string>;
|
|
2328
|
+
/** Whether a number/handle exists on the channel (when supported). */
|
|
2329
|
+
checkNumber?(number: string): Promise<boolean>;
|
|
2325
2330
|
/**
|
|
2326
2331
|
* Subscribe to inbound messages; resolves to an unsubscribe function.
|
|
2332
|
+
* Present only on channels with a live subscription (WhatsApp `/ws`,
|
|
2333
|
+
* Telegram long-polling).
|
|
2327
2334
|
*
|
|
2328
2335
|
* @param handler - Invoked for each inbound message.
|
|
2329
2336
|
* @param room - Conversation to scope to; `"*"` for all. Default `"*"`.
|
|
2330
2337
|
*/
|
|
2331
|
-
onMessage(handler: InboundHandler, room?: string): Promise<() => Promise<void>>;
|
|
2338
|
+
onMessage?(handler: InboundHandler, room?: string): Promise<() => Promise<void>>;
|
|
2332
2339
|
}
|
|
2333
2340
|
|
|
2334
2341
|
/**
|
|
@@ -2398,6 +2405,113 @@ interface WhatsAppWebhookOptions {
|
|
|
2398
2405
|
*/
|
|
2399
2406
|
declare function makeWhatsAppWebhookRouter(options: WhatsAppWebhookOptions): Router;
|
|
2400
2407
|
|
|
2408
|
+
/**
|
|
2409
|
+
* Telegram provider — a client for the Telegram Bot API.
|
|
2410
|
+
*
|
|
2411
|
+
* Implements {@link MessagingProvider} over the built-in {@link HTTPClient}
|
|
2412
|
+
* (no external SDK). Outbound via `sendMessage`/`sendPhoto`/…; inbound via
|
|
2413
|
+
* `getUpdates` long-polling exposed through {@link TelegramProvider.onMessage}.
|
|
2414
|
+
*/
|
|
2415
|
+
|
|
2416
|
+
/** Options for {@link TelegramProvider}. */
|
|
2417
|
+
interface TelegramProviderOptions {
|
|
2418
|
+
/** Bot token from @BotFather. */
|
|
2419
|
+
token: string;
|
|
2420
|
+
/** API base. Default `https://api.telegram.org`. */
|
|
2421
|
+
apiBase?: string;
|
|
2422
|
+
/** Long-poll timeout in seconds for `getUpdates`. Default 30. */
|
|
2423
|
+
pollTimeoutSeconds?: number;
|
|
2424
|
+
}
|
|
2425
|
+
/** A typed Telegram Bot API client. */
|
|
2426
|
+
declare class TelegramProvider implements MessagingProvider {
|
|
2427
|
+
private readonly http;
|
|
2428
|
+
private readonly pollTimeout;
|
|
2429
|
+
/**
|
|
2430
|
+
* @param options - Bot token and API options.
|
|
2431
|
+
*/
|
|
2432
|
+
constructor(options: TelegramProviderOptions);
|
|
2433
|
+
/** Call a Bot API method, returning the `result`, throwing on `ok: false`. */
|
|
2434
|
+
private call;
|
|
2435
|
+
sendText(to: string, text: string): Promise<OutboundResult>;
|
|
2436
|
+
sendMedia(to: string, media: OutboundMedia): Promise<OutboundResult>;
|
|
2437
|
+
status(): Promise<string>;
|
|
2438
|
+
/**
|
|
2439
|
+
* Subscribe to inbound messages via `getUpdates` long-polling.
|
|
2440
|
+
*
|
|
2441
|
+
* @param handler - Invoked for each inbound text message.
|
|
2442
|
+
* @returns A stop function that ends the polling loop.
|
|
2443
|
+
*/
|
|
2444
|
+
onMessage(handler: InboundHandler): Promise<() => Promise<void>>;
|
|
2445
|
+
}
|
|
2446
|
+
|
|
2447
|
+
/**
|
|
2448
|
+
* SMS provider — a Twilio client + inbound-webhook receiver.
|
|
2449
|
+
*
|
|
2450
|
+
* Implements {@link MessagingProvider} over the built-in {@link HTTPClient}
|
|
2451
|
+
* (no `twilio` SDK). SMS has no persistent subscription, so `onMessage` is
|
|
2452
|
+
* absent — inbound arrives via {@link makeTwilioWebhookRouter}, which validates
|
|
2453
|
+
* the `X-Twilio-Signature` HMAC.
|
|
2454
|
+
*/
|
|
2455
|
+
|
|
2456
|
+
/** Options for {@link TwilioSmsProvider}. */
|
|
2457
|
+
interface TwilioSmsProviderOptions {
|
|
2458
|
+
/** Twilio Account SID. */
|
|
2459
|
+
accountSid: string;
|
|
2460
|
+
/** Twilio Auth Token. */
|
|
2461
|
+
authToken: string;
|
|
2462
|
+
/** Default `From` number (E.164), e.g. `+15551234567`. */
|
|
2463
|
+
from: string;
|
|
2464
|
+
/** API base. Default `https://api.twilio.com`. */
|
|
2465
|
+
apiBase?: string;
|
|
2466
|
+
}
|
|
2467
|
+
/** A Twilio SMS client. */
|
|
2468
|
+
declare class TwilioSmsProvider implements MessagingProvider {
|
|
2469
|
+
private readonly http;
|
|
2470
|
+
private readonly from;
|
|
2471
|
+
private readonly messagesPath;
|
|
2472
|
+
private readonly accountPath;
|
|
2473
|
+
/**
|
|
2474
|
+
* @param options - Account SID, auth token and default sender.
|
|
2475
|
+
*/
|
|
2476
|
+
constructor(options: TwilioSmsProviderOptions);
|
|
2477
|
+
/** POST a form body to Twilio and parse the JSON, throwing on non-2xx. */
|
|
2478
|
+
private postForm;
|
|
2479
|
+
sendText(to: string, text: string): Promise<OutboundResult>;
|
|
2480
|
+
sendMedia(to: string, media: OutboundMedia): Promise<OutboundResult>;
|
|
2481
|
+
status(): Promise<string>;
|
|
2482
|
+
}
|
|
2483
|
+
/**
|
|
2484
|
+
* Validate a Twilio request signature (`X-Twilio-Signature`).
|
|
2485
|
+
*
|
|
2486
|
+
* @param authToken - The Twilio auth token.
|
|
2487
|
+
* @param url - The full public URL Twilio posted to (scheme + host + path).
|
|
2488
|
+
* @param params - The POST form parameters.
|
|
2489
|
+
* @param signature - The `X-Twilio-Signature` header value.
|
|
2490
|
+
* @returns `true` when the signature matches.
|
|
2491
|
+
*/
|
|
2492
|
+
declare function validateTwilioSignature(authToken: string, url: string, params: Record<string, string>, signature: string): boolean;
|
|
2493
|
+
/** Options for {@link makeTwilioWebhookRouter}. */
|
|
2494
|
+
interface TwilioWebhookOptions {
|
|
2495
|
+
/** Handler invoked for each inbound SMS. */
|
|
2496
|
+
onMessage: InboundHandler;
|
|
2497
|
+
/** Route path. Default `/sms/inbound`. */
|
|
2498
|
+
path?: string;
|
|
2499
|
+
/** Auth token; when set, `X-Twilio-Signature` is validated. */
|
|
2500
|
+
authToken?: string;
|
|
2501
|
+
/** Public URL Twilio posts to (needed for signature validation behind a proxy). */
|
|
2502
|
+
publicUrl?: string;
|
|
2503
|
+
}
|
|
2504
|
+
/**
|
|
2505
|
+
* Build the Twilio inbound-SMS webhook router.
|
|
2506
|
+
*
|
|
2507
|
+
* Twilio posts `application/x-www-form-urlencoded` (`From`, `Body`,
|
|
2508
|
+
* `MessageSid`, …). Mount after `express.urlencoded()` (included by `createApp`).
|
|
2509
|
+
*
|
|
2510
|
+
* @param options - Handler, path and signature-validation settings.
|
|
2511
|
+
* @returns An Express router with the webhook endpoint mounted.
|
|
2512
|
+
*/
|
|
2513
|
+
declare function makeTwilioWebhookRouter(options: TwilioWebhookOptions): Router;
|
|
2514
|
+
|
|
2401
2515
|
/**
|
|
2402
2516
|
* Admin site + resource registry, mirroring `admin.site` / `admin.config`.
|
|
2403
2517
|
*
|
|
@@ -3105,6 +3219,6 @@ interface RunServerOptions {
|
|
|
3105
3219
|
declare function runServer(app: Express, options?: RunServerOptions): Promise<Server>;
|
|
3106
3220
|
|
|
3107
3221
|
/** The installed SDK version. Single source of truth for the barrel + CLI. */
|
|
3108
|
-
declare const VERSION = "0.
|
|
3222
|
+
declare const VERSION = "0.6.0";
|
|
3109
3223
|
|
|
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 };
|
|
3224
|
+
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, TelegramProvider, type TelegramProviderOptions, type ThrottleBackend, type ThrottleStatus, type ToDictOptions, type TokenPair, TooManyRequestsException, type TooManyRequestsOptions, TwilioSmsProvider, type TwilioSmsProviderOptions, type TwilioWebhookOptions, 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, makeTwilioWebhookRouter, 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, validateTwilioSignature, verifyOpaqueToken, webPushKeysSchema, webPushPayloadSchema, webPushSubscriptionSchema, wsEnvelopeSchema };
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { VERSION } from './chunk-
|
|
1
|
+
export { VERSION } from './chunk-3IDD2UXU.js';
|
|
2
2
|
import { AsyncLocalStorage } from 'async_hooks';
|
|
3
3
|
import { extendZodWithOpenApi, OpenAPIRegistry, OpenApiGeneratorV31, OpenApiGeneratorV3 } from '@asteasolutions/zod-to-openapi';
|
|
4
4
|
export { OpenAPIRegistry } from '@asteasolutions/zod-to-openapi';
|
|
@@ -8194,6 +8194,190 @@ function makeWhatsAppWebhookRouter(options) {
|
|
|
8194
8194
|
return router;
|
|
8195
8195
|
}
|
|
8196
8196
|
|
|
8197
|
+
// src/integrations/telegram.ts
|
|
8198
|
+
var MEDIA_METHOD = {
|
|
8199
|
+
image: { method: "sendPhoto", field: "photo" },
|
|
8200
|
+
video: { method: "sendVideo", field: "video" },
|
|
8201
|
+
audio: { method: "sendAudio", field: "audio" },
|
|
8202
|
+
document: { method: "sendDocument", field: "document" }
|
|
8203
|
+
};
|
|
8204
|
+
var TelegramProvider = class {
|
|
8205
|
+
http;
|
|
8206
|
+
pollTimeout;
|
|
8207
|
+
/**
|
|
8208
|
+
* @param options - Bot token and API options.
|
|
8209
|
+
*/
|
|
8210
|
+
constructor(options) {
|
|
8211
|
+
const base = `${options.apiBase ?? "https://api.telegram.org"}/bot${options.token}`;
|
|
8212
|
+
this.pollTimeout = options.pollTimeoutSeconds ?? 30;
|
|
8213
|
+
this.http = new HTTPClient({
|
|
8214
|
+
baseUrl: base,
|
|
8215
|
+
defaultHeaders: { "content-type": "application/json" },
|
|
8216
|
+
// Timeout must exceed the long-poll window.
|
|
8217
|
+
timeoutMs: (this.pollTimeout + 10) * 1e3
|
|
8218
|
+
});
|
|
8219
|
+
}
|
|
8220
|
+
/** Call a Bot API method, returning the `result`, throwing on `ok: false`. */
|
|
8221
|
+
async call(method, body) {
|
|
8222
|
+
const res = await this.http.post(`/${method}`, { body: JSON.stringify(body) });
|
|
8223
|
+
const data = await res.json().catch(() => ({}));
|
|
8224
|
+
if (!res.ok || !data.ok) {
|
|
8225
|
+
throw new Error(`Telegram ${method} failed: ${data.description ?? res.statusText}`);
|
|
8226
|
+
}
|
|
8227
|
+
return data.result;
|
|
8228
|
+
}
|
|
8229
|
+
async sendText(to, text) {
|
|
8230
|
+
const result = await this.call("sendMessage", {
|
|
8231
|
+
chat_id: to,
|
|
8232
|
+
text
|
|
8233
|
+
});
|
|
8234
|
+
return { id: String(result.message_id), status: "sent" };
|
|
8235
|
+
}
|
|
8236
|
+
async sendMedia(to, media) {
|
|
8237
|
+
const { method, field } = MEDIA_METHOD[media.kind];
|
|
8238
|
+
const body = { chat_id: to, [field]: media.media };
|
|
8239
|
+
if (media.caption !== void 0) body.caption = media.caption;
|
|
8240
|
+
const result = await this.call(method, body);
|
|
8241
|
+
return { id: String(result.message_id), status: "sent" };
|
|
8242
|
+
}
|
|
8243
|
+
async status() {
|
|
8244
|
+
try {
|
|
8245
|
+
await this.call("getMe", {});
|
|
8246
|
+
return "connected";
|
|
8247
|
+
} catch {
|
|
8248
|
+
return "disconnected";
|
|
8249
|
+
}
|
|
8250
|
+
}
|
|
8251
|
+
/**
|
|
8252
|
+
* Subscribe to inbound messages via `getUpdates` long-polling.
|
|
8253
|
+
*
|
|
8254
|
+
* @param handler - Invoked for each inbound text message.
|
|
8255
|
+
* @returns A stop function that ends the polling loop.
|
|
8256
|
+
*/
|
|
8257
|
+
async onMessage(handler) {
|
|
8258
|
+
let running = true;
|
|
8259
|
+
let offset = 0;
|
|
8260
|
+
const loop = async () => {
|
|
8261
|
+
while (running) {
|
|
8262
|
+
let updates = [];
|
|
8263
|
+
try {
|
|
8264
|
+
updates = await this.call("getUpdates", {
|
|
8265
|
+
offset,
|
|
8266
|
+
timeout: this.pollTimeout
|
|
8267
|
+
});
|
|
8268
|
+
} catch {
|
|
8269
|
+
if (running) await new Promise((r) => setTimeout(r, 1e3));
|
|
8270
|
+
continue;
|
|
8271
|
+
}
|
|
8272
|
+
for (const update2 of updates) {
|
|
8273
|
+
offset = update2.update_id + 1;
|
|
8274
|
+
const message = update2.message;
|
|
8275
|
+
if (!message) continue;
|
|
8276
|
+
await handler({
|
|
8277
|
+
from: String(message.chat.id),
|
|
8278
|
+
messageId: String(message.message_id),
|
|
8279
|
+
...typeof message.text === "string" ? { text: message.text } : {},
|
|
8280
|
+
mediaType: null,
|
|
8281
|
+
timestamp: new Date(message.date * 1e3).toISOString(),
|
|
8282
|
+
direction: "incoming"
|
|
8283
|
+
});
|
|
8284
|
+
}
|
|
8285
|
+
}
|
|
8286
|
+
};
|
|
8287
|
+
void loop();
|
|
8288
|
+
return async () => {
|
|
8289
|
+
running = false;
|
|
8290
|
+
};
|
|
8291
|
+
}
|
|
8292
|
+
};
|
|
8293
|
+
var TwilioSmsProvider = class {
|
|
8294
|
+
http;
|
|
8295
|
+
from;
|
|
8296
|
+
messagesPath;
|
|
8297
|
+
accountPath;
|
|
8298
|
+
/**
|
|
8299
|
+
* @param options - Account SID, auth token and default sender.
|
|
8300
|
+
*/
|
|
8301
|
+
constructor(options) {
|
|
8302
|
+
this.from = options.from;
|
|
8303
|
+
this.messagesPath = `/2010-04-01/Accounts/${options.accountSid}/Messages.json`;
|
|
8304
|
+
this.accountPath = `/2010-04-01/Accounts/${options.accountSid}.json`;
|
|
8305
|
+
const basic = Buffer.from(`${options.accountSid}:${options.authToken}`).toString(
|
|
8306
|
+
"base64"
|
|
8307
|
+
);
|
|
8308
|
+
this.http = new HTTPClient({
|
|
8309
|
+
baseUrl: options.apiBase ?? "https://api.twilio.com",
|
|
8310
|
+
defaultHeaders: {
|
|
8311
|
+
Authorization: `Basic ${basic}`,
|
|
8312
|
+
"content-type": "application/x-www-form-urlencoded"
|
|
8313
|
+
}
|
|
8314
|
+
});
|
|
8315
|
+
}
|
|
8316
|
+
/** POST a form body to Twilio and parse the JSON, throwing on non-2xx. */
|
|
8317
|
+
async postForm(params) {
|
|
8318
|
+
const res = await this.http.post(this.messagesPath, {
|
|
8319
|
+
body: new URLSearchParams(params).toString()
|
|
8320
|
+
});
|
|
8321
|
+
const data = await res.json().catch(() => ({}));
|
|
8322
|
+
if (!res.ok) {
|
|
8323
|
+
throw new Error(
|
|
8324
|
+
`Twilio send failed (${res.status}): ${data.message ?? res.statusText}`
|
|
8325
|
+
);
|
|
8326
|
+
}
|
|
8327
|
+
return {
|
|
8328
|
+
status: data.status ?? "queued",
|
|
8329
|
+
...data.sid ? { id: data.sid } : {}
|
|
8330
|
+
};
|
|
8331
|
+
}
|
|
8332
|
+
async sendText(to, text) {
|
|
8333
|
+
return this.postForm({ To: to, From: this.from, Body: text });
|
|
8334
|
+
}
|
|
8335
|
+
async sendMedia(to, media) {
|
|
8336
|
+
return this.postForm({
|
|
8337
|
+
To: to,
|
|
8338
|
+
From: this.from,
|
|
8339
|
+
MediaUrl: media.media,
|
|
8340
|
+
...media.caption !== void 0 ? { Body: media.caption } : {}
|
|
8341
|
+
});
|
|
8342
|
+
}
|
|
8343
|
+
async status() {
|
|
8344
|
+
const res = await this.http.get(this.accountPath);
|
|
8345
|
+
const data = await res.json().catch(() => ({}));
|
|
8346
|
+
return data.status ?? (res.ok ? "connected" : "disconnected");
|
|
8347
|
+
}
|
|
8348
|
+
};
|
|
8349
|
+
function validateTwilioSignature(authToken, url, params, signature) {
|
|
8350
|
+
const data = url + Object.keys(params).sort().map((key) => key + params[key]).join("");
|
|
8351
|
+
const expected = createHmac("sha1", authToken).update(data, "utf8").digest("base64");
|
|
8352
|
+
const a = Buffer.from(expected);
|
|
8353
|
+
const b = Buffer.from(signature);
|
|
8354
|
+
return a.length === b.length && timingSafeEqual(a, b);
|
|
8355
|
+
}
|
|
8356
|
+
function makeTwilioWebhookRouter(options) {
|
|
8357
|
+
const path = options.path ?? "/sms/inbound";
|
|
8358
|
+
const router = Router();
|
|
8359
|
+
router.post(path, async (req, res) => {
|
|
8360
|
+
const body = req.body ?? {};
|
|
8361
|
+
if (options.authToken) {
|
|
8362
|
+
const url = options.publicUrl ?? `${req.protocol}://${req.get("host")}${req.originalUrl}`;
|
|
8363
|
+
const signature = req.header("x-twilio-signature") ?? "";
|
|
8364
|
+
if (!validateTwilioSignature(options.authToken, url, body, signature)) {
|
|
8365
|
+
throw new UnauthorizedException({ message: "Invalid Twilio signature" });
|
|
8366
|
+
}
|
|
8367
|
+
}
|
|
8368
|
+
await options.onMessage({
|
|
8369
|
+
from: String(body.From ?? ""),
|
|
8370
|
+
messageId: String(body.MessageSid ?? ""),
|
|
8371
|
+
...body.Body ? { text: body.Body } : {},
|
|
8372
|
+
mediaType: null,
|
|
8373
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
8374
|
+
direction: "incoming"
|
|
8375
|
+
});
|
|
8376
|
+
res.type("text/xml").send("<Response></Response>");
|
|
8377
|
+
});
|
|
8378
|
+
return router;
|
|
8379
|
+
}
|
|
8380
|
+
|
|
8197
8381
|
// src/admin/site.ts
|
|
8198
8382
|
var AdminSite = class {
|
|
8199
8383
|
/**
|
|
@@ -8809,6 +8993,6 @@ function runServer(app, options = {}) {
|
|
|
8809
8993
|
});
|
|
8810
8994
|
}
|
|
8811
8995
|
|
|
8812
|
-
export { AdminSite, AppException, AttemptThrottle, BaseController, BaseModel, BaseService, CEP_PATTERN, CNPJ_PATTERN, CPF_PATTERN, CircuitOpenError, CompositeFeatureFlagBackend, ConflictException, DEFAULT_LOCALE, EmailUtils, EnvFeatureFlagBackend, EventStream, ExpiredTokenException, FeatureFlags, ForbiddenException, HTTPClient, HTTP_500_MARKER, InvalidTokenException, JSONLogger, JWTUtils, LocalUploadStorage, MemoryBroker, MemoryCacheManager, MemoryFeatureFlagBackend, MemorySessionStore, MemoryThrottleBackend, MessageCatalog, MetricsUtils, NotFoundException, PHONE_BR_PATTERN, PasswordUtils, REQUEST_ID_HEADER, RabbitBroker, RedisCacheManager, Region, RetryPolicy, SSEBroker, ServerSentEvent, SessionService, TOTPHelper, TaskManager, TooManyRequestsException, UF, UnauthorizedException, UserAuthService, ValidationException, WebPushDispatcher, WebPushError, WebPushGoneError, WebSocketHub, WhatsAppProvider, attachWebSocketHub, authResponseSchema, baseAppSettingsSchema, baseAppSettingsShape, baseResponseSchema, bearerToken, buildContentDisposition, cached3 as 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 };
|
|
8996
|
+
export { AdminSite, AppException, AttemptThrottle, BaseController, BaseModel, BaseService, CEP_PATTERN, CNPJ_PATTERN, CPF_PATTERN, CircuitOpenError, CompositeFeatureFlagBackend, ConflictException, DEFAULT_LOCALE, EmailUtils, EnvFeatureFlagBackend, EventStream, ExpiredTokenException, FeatureFlags, ForbiddenException, HTTPClient, HTTP_500_MARKER, InvalidTokenException, JSONLogger, JWTUtils, LocalUploadStorage, MemoryBroker, MemoryCacheManager, MemoryFeatureFlagBackend, MemorySessionStore, MemoryThrottleBackend, MessageCatalog, MetricsUtils, NotFoundException, PHONE_BR_PATTERN, PasswordUtils, REQUEST_ID_HEADER, RabbitBroker, RedisCacheManager, Region, RetryPolicy, SSEBroker, ServerSentEvent, SessionService, TOTPHelper, TaskManager, TelegramProvider, TooManyRequestsException, TwilioSmsProvider, UF, UnauthorizedException, UserAuthService, ValidationException, WebPushDispatcher, WebPushError, WebPushGoneError, WebSocketHub, WhatsAppProvider, attachWebSocketHub, authResponseSchema, baseAppSettingsSchema, baseAppSettingsShape, baseResponseSchema, bearerToken, buildContentDisposition, cached3 as 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, makeTwilioWebhookRouter, 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, validateTwilioSignature, verifyOpaqueToken, webPushKeysSchema, webPushPayloadSchema, webPushSubscriptionSchema, wsEnvelopeSchema };
|
|
8813
8997
|
//# sourceMappingURL=index.js.map
|
|
8814
8998
|
//# sourceMappingURL=index.js.map
|