@digilogiclabs/platform-core 1.4.0 → 1.5.1

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.ts CHANGED
@@ -2,10 +2,11 @@ import { p as ILogger, q as IMetrics, I as IPlatform, P as PlatformHealthStatus,
2
2
  export { aI as AIChatChoice, br as AIConfigSchema, aO as AIError, aN as AIErrorCode, aC as AIErrorMessages, aJ as AIFinishReason, aF as AIMessage, bk as AIProviderSchema, aE as AIRole, aM as AIRouterConfig, aH as AITool, aG as AIToolCall, aK as AIUsageInfo, am as BackoffOptions, by as BulkheadConfigSchema, bI as CacheConfig, bn as CacheConfigSchema, be as CacheProviderSchema, aS as ChunkingConfig, aQ as ChunkingPresets, aR as ChunkingStrategy, bw as CircuitBreakerConfigSchema, C as ConsoleEmail, h as ConsoleLogger, aX as CryptoAlgorithm, bP as CryptoConfig, bt as CryptoConfigSchema, aW as CryptoKeyStatus, bH as DatabaseConfig, bm as DatabaseConfigSchema, bd as DatabaseProviderSchema, b7 as EmailAddress, b8 as EmailAttachment, bK as EmailConfig, bp as EmailConfigSchema, bg as EmailProviderSchema, E as EnvSecrets, aw as GetSecretOptions, as as HistogramStats, ah as ICacheOptions, r as ISecrets, b1 as ISpan, b0 as ITracing, aj as JobContext, ak as JobEvent, ai as JobResult, ap as LogEntry, an as LogLevel, bj as LogLevelSchema, ao as LogMeta, aq as LoggerConfig, bA as LoggingConfigSchema, aD as MemoryAI, a as MemoryCache, M as MemoryDatabase, c as MemoryEmail, i as MemoryMetrics, d as MemoryQueue, aP as MemoryRAG, f as MemorySecrets, b as MemoryStorage, a_ as MemoryTracing, ar as MetricTags, bB as MetricsConfigSchema, bO as MiddlewareConfig, bE as MiddlewareConfigSchema, N as NoopLogger, j as NoopMetrics, a$ as NoopTracing, bN as ObservabilityConfig, bD as ObservabilityConfigSchema, bG as PlatformConfig, bF as PlatformConfigSchema, bL as QueueConfig, bq as QueueConfigSchema, bh as QueueProviderSchema, al as QueueStats, bs as RAGConfigSchema, aU as RAGFilter, aV as RAGPipelineStep, bl as RAGProviderSchema, bM as ResilienceConfig, bz as ResilienceConfigSchema, bv as RetryConfigSchema, ay as RotateSecretOptions, az as RotationResult, aL as RoutingStrategy, aT as SearchMode, au as Secret, av as SecretMetadata, bQ as SecurityConfig, bu as SecurityConfigSchema, ax as SetSecretOptions, b2 as SpanContext, bc as SpanEvent, b5 as SpanKind, b3 as SpanOptions, b4 as SpanStatus, bb as SpanStatusCode, bJ as StorageConfig, bo as StorageConfigSchema, bf as StorageProviderSchema, bx as TimeoutConfigSchema, at as TimingStats, b6 as TracingConfig, bC as TracingConfigSchema, bi as TracingProviderSchema, b9 as calculateBackoff, aA as createAIError, g as createPlatform, aY as createPlatformAsync, aZ as createScopedMetrics, ba as generateJobId, bU as getDefaultConfig, aB as isAIError, bR as loadConfig, bT as safeValidateConfig, bS as validateConfig } from './ConsoleEmail-ubSVWgTa.js';
3
3
  export { t as IMigrationDatabase, I as IMigrator, n as Migration, o as MigrationRecord, p as MigrationResult, q as MigrationStatus, M as Migrator, r as MigratorConfig, S as SQL, f as createDomainVerificationsTable, c as createMigration, b as createSsoOidcConfigsTable, m as createSsoSessionsTable, k as createTenantInvitationsTable, j as createTenantMembersTable, l as createTenantUsageTable, i as createTenantsTable, h as createVerifiedDomainsTable, d as defineMigration, e as enterpriseMigrations, g as generateVersion, a as getEnterpriseMigrations, s as sqlMigration } from './index-CepDdu7h.js';
4
4
  export { NextHeaderEntry, SecurityHeaderPresets, SecurityHeadersConfig, generateSecurityHeaders } from './security-headers.js';
5
+ export { AllowlistConfig, ApiSecurityConfig, ApiSecurityContext, AuditRequest, AuthCookiesConfig, AuthMethod, CommonRateLimits, DateRangeInput, DateRangeSchema, DeploymentStage, EmailInput, EmailSchema, FlagDefinition, FlagDefinitions, FlagValue, KEYCLOAK_DEFAULT_ROLES, KeycloakCallbacksConfig, KeycloakConfig, KeycloakJwtFields, KeycloakTokenSet, LoginInput, LoginSchema, OpsAuditActor, OpsAuditEvent, OpsAuditLoggerOptions, OpsAuditRecord, OpsAuditResource, PaginationInput, PaginationSchema, PasswordSchema, PersonNameSchema, PhoneSchema, RateLimitCheckResult, RateLimitOptions, RateLimitPreset, RateLimitRule, RateLimitStore, RedirectCallbackConfig, ResolvedFlags, RouteAuditConfig, SearchQueryInput, SearchQuerySchema, SecuritySession, SignupInput, SignupSchema, SlugSchema, StandardAuditActionType, StandardAuditActions, StandardRateLimitPresets, TokenRefreshResult, WrapperPresets, buildAllowlist, buildAuthCookies, buildErrorBody, buildKeycloakCallbacks, buildRateLimitHeaders, buildRateLimitResponseHeaders, buildRedirectCallback, buildTokenRefreshParams, checkRateLimit, createAuditActor, createAuditLogger, createFeatureFlags, createMemoryRateLimitStore, createSafeTextSchema, detectStage, extractAuditIp, extractAuditRequestId, extractAuditUserAgent, extractClientIp, getEndSessionEndpoint, getRateLimitStatus, getTokenEndpoint, hasAllRoles, hasAnyRole, hasRole, isAllowlisted, isTokenExpired, parseKeycloakRoles, refreshKeycloakToken, resetRateLimitForKey, resolveIdentifier, resolveRateLimitIdentifier } from './auth.js';
5
6
  import { SupabaseClient } from '@supabase/supabase-js';
6
7
  import { Pool } from 'pg';
7
8
  import { Redis } from '@upstash/redis';
8
- import { Redis as Redis$1 } from 'ioredis';
9
+ import Redis$2, { Redis as Redis$1 } from 'ioredis';
9
10
  import { S3Client } from '@aws-sdk/client-s3';
10
11
  import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
11
12
  import { Resend } from 'resend';
@@ -9236,7 +9237,6 @@ declare const runWithContext: <T>(data: CorrelationData, fn: () => T) => T;
9236
9237
  declare const runWithContextAsync: <T>(data: CorrelationData, fn: () => Promise<T>) => Promise<T>;
9237
9238
  declare const getContext: () => CorrelationData | undefined;
9238
9239
  declare const getTraceId: () => string | undefined;
9239
- declare const getCorrelationId: () => string | undefined;
9240
9240
  declare const getRequestId: () => string | undefined;
9241
9241
  declare const getUserId: () => string | undefined;
9242
9242
  declare const getTenantId: () => string | undefined;
@@ -10188,8 +10188,9 @@ declare const FallbackStrategies: {
10188
10188
  /**
10189
10189
  * Security Utilities
10190
10190
  *
10191
- * HTML escaping, input detection, and sanitization helpers
10192
- * for safe rendering of user content in emails, templates, and HTML output.
10191
+ * HTML escaping, input detection, sanitization helpers,
10192
+ * timing-safe comparison, error sanitization, and request
10193
+ * correlation for safe, consistent security across all apps.
10193
10194
  */
10194
10195
  /** Regex for protocol-prefixed URLs */
10195
10196
  declare const URL_PROTOCOL_PATTERN: RegExp;
@@ -10218,6 +10219,58 @@ declare function defangUrl(str: string): string;
10218
10219
  * Escapes HTML entities AND defangs any URLs that slipped through validation.
10219
10220
  */
10220
10221
  declare function sanitizeForEmail(str: string): string;
10222
+ /**
10223
+ * Constant-time string comparison to prevent timing side-channel attacks.
10224
+ * Use for comparing secrets, tokens, API keys, HMAC signatures, etc.
10225
+ *
10226
+ * Returns false (not throws) for length mismatches — still constant-time
10227
+ * relative to the shorter string to avoid leaking length info.
10228
+ *
10229
+ * @example
10230
+ * ```typescript
10231
+ * if (!constantTimeEqual(providedToken, expectedSecret)) {
10232
+ * return { status: 401, error: 'Invalid token' }
10233
+ * }
10234
+ * ```
10235
+ */
10236
+ declare function constantTimeEqual(a: string, b: string): boolean;
10237
+ /**
10238
+ * Sanitize an error for client-facing API responses.
10239
+ *
10240
+ * - 4xx errors: returns the actual message (client needs to know what went wrong)
10241
+ * - 5xx errors: returns a generic message (never leak internals to clients)
10242
+ * - Development mode: optionally includes stack trace for debugging
10243
+ *
10244
+ * @example
10245
+ * ```typescript
10246
+ * catch (error) {
10247
+ * const { message, code } = sanitizeApiError(error, 500)
10248
+ * return Response.json({ error: message, code }, { status: 500 })
10249
+ * }
10250
+ * ```
10251
+ */
10252
+ declare function sanitizeApiError(error: unknown, statusCode: number, isDevelopment?: boolean): {
10253
+ message: string;
10254
+ code?: string;
10255
+ stack?: string;
10256
+ };
10257
+ /**
10258
+ * Extract a correlation/request ID from standard headers, or generate one.
10259
+ *
10260
+ * Checks (in order): X-Request-ID, X-Correlation-ID, then falls back to
10261
+ * crypto.randomUUID(). Works with any headers-like object (plain object,
10262
+ * Headers API, or a getter function).
10263
+ *
10264
+ * @example
10265
+ * ```typescript
10266
+ * // With Next.js request
10267
+ * const id = getCorrelationId((name) => request.headers.get(name))
10268
+ *
10269
+ * // With plain object
10270
+ * const id = getCorrelationId({ 'x-request-id': 'abc-123' })
10271
+ * ```
10272
+ */
10273
+ declare function getCorrelationId(headers: Record<string, string | string[] | undefined> | ((name: string) => string | null | undefined)): string;
10221
10274
 
10222
10275
  /**
10223
10276
  * API Utilities
@@ -13158,4 +13211,224 @@ declare class PostgresTenant implements ITenant {
13158
13211
  private mapRowToInvitation;
13159
13212
  }
13160
13213
 
13161
- export { AIChatRequest, AIChatResponse, AICompletionRequest, AICompletionResponse, AIConfig, AIEmbeddingRequest, AIEmbeddingResponse, AIModelConfig, AIModelType, AIProvider, AIStreamCallback, AIStreamChunk, type AIUsageConfig, type AccountCapabilities, type AccountLink, type AccountType, type Address, type AlertType, AnthropicAdapter, type AnthropicAdapterConfig, type ApiAuthentication, type ApiChangelog, type ApiDocumentation, type ApiEndpoint, ApiError, ApiErrorCode, type ApiErrorCodeType, type ApiExample, type ApiKey, type ApiKeyStatus, type ApiKeyType, type ApiKeyValidationResult, type ApiPaginatedResponse, type ApiParameter, type ApiResponse, type ApiSchema, type ApiSchemaProperty, type ApiSuccessResponse, type ApiUsageStats, type ApiUsageTimeSeries, AssembledContext, type AuditActor, type AuditCategory, type AuditEvent, AuditEvents, type AuditEvidence, type AuditLogConfig, type AuditOutcome, type AuditQuery, type AuditQueryResult, type AuditRetentionPolicy, type AuditStats, type AuditTarget, type AuthConfig, type AuthError, type AuthErrorCode, AuthErrorMessages, type AuthEventType, type AuthResult, type AuthSession, type AuthStateChangeCallback, type AuthStorage, type AuthUser, type Balance, type BalanceAmount, type BankAccountDetails, type BatchNotificationOptions, type BillingConfig, type BillingDetails, type BillingPeriod, type Breadcrumb, type Budget, type BudgetStatus, BulkIngestionResult, Bulkhead, type BulkheadOptions, BulkheadRegistry, BulkheadRejectedError, type BulkheadStats, type BullMQConfig, BullMQQueue, type BusinessProfile, type CancelationReason, type CaptureOptions, type CapturePaymentIntentOptions, type CardBrand, type CardDetails, type ChainExecutionResult, CircuitBreaker, type CircuitBreakerOptions, CircuitBreakerRegistry, type CircuitBreakerStats, CircuitOpenError, type CircuitState, type CommandStatus, CommonApiErrors, type ComplianceConfig, type ComplianceReport, type ConfirmPaymentIntentOptions, type ConnectedAccount, type ConnectedAccountStatus, type ConsentPreferences, type ConsentPurpose, type ConsentRecord, type ConsentStatus, ContextAssemblyConfig, type ControlFramework, type ControlStatus, type CorrelationData, type CostBreakdown, type Coupon, type CreateAccountLinkOptions, type CreateApiKeyOptions, CreateCollectionOptions, type CreateConnectedAccountOptions, type CreateCustomerOptions, type CreateDsarOptions, type CreatePaymentIntentOptions, type CreatePayoutOptions, type CreateRefundOptions, type CreateSandboxOptions, type CreateScheduleOptions, type CreateTenantOptions, type CreateTransferOptions, type CreateWebhookOptions, type CreditBalance, type CreditTransaction, type CreditType, type CronExpression, CronPresets, CryptoKeyMetadata, type Currency, type Customer, DEFAULT_BULKHEAD_OPTIONS, DEFAULT_CIRCUIT_BREAKER_OPTIONS, DEFAULT_RETRY_OPTIONS, type DataBreachRecord, type DataCategory, type DataInventoryItem, type DataMap, type DataSensitivity, type DataSubjectRequest, type DataType, DatabaseAIUsage, type DatabaseAIUsageConfig, DatabaseAuditLog, type DatabaseAuditLogConfig, DatabaseBilling, type DatabaseBillingConfig, DatabaseCompliance, DatabaseErrorReporter, type DatabaseErrorReporterConfig, DatabaseNotification, type DatabaseNotificationConfig, DatabasePromptStore, type DatabasePromptStoreConfig, DefaultTimeouts, type DeleteAccountOptions, type DeleteHookContext, type DeliveryAttempt, type DeliveryQuery, type DeliveryStatus, type DetailedHealthResponse, DeterministicEncryptedField, type DevPortalConfig, type DeveloperMetrics, type Device, type DeviceAuthMethod, type DeviceCommand, type DeviceConfig, type DeviceConnectionState, type DeviceCredentials, type DeviceGroup, type DeviceGroupQuery, type DeviceLocation, type DeviceQuery, type DeviceQueryResult, type DeviceShadow, type DeviceStatus, type DirectoryAttributeMapping, type DirectoryConfig, DocumentStatus, type DsarAttachment, type DsarNote, type DsarStatus, type DsarType, type DunningActionType, type DunningAttempt, type DunningConfig, type EmailHookContext, EmailMessage, EmailResult, EncryptOptions, EncryptedField, type EnrollMfaOptions, type EnrollMfaResult, type ErrorContext, type ErrorHookContext, type ErrorLevel, type ErrorReport, type ErrorReporterConfig, type EvidenceType, type ExperimentMetrics, type FallbackOptions, type FallbackResult, FallbackStrategies, type FirmwareStatus, type FirmwareUpdate, type FirmwareVersion, type GeneratedSdk, GenericOIDCAuthSSO, type GenericOIDCConfig, GoogleAIAdapter, type GoogleAIAdapterConfig, HTML_TAG_PATTERN, type HealthCheckResult, type HealthEndpoints, type HealthEndpointsOptions, type HealthStatus, type HookRegistry, type HttpMethod, HttpWebhook, type HttpWebhookConfig, IAI, type IAIUsage, type IAuditLog, type IAuth, type IAuthSSO, type IBilling, ICache, type ICompliance, ICrypto, IDatabase, type IDevPortal, type IDevice, IEmail, type IErrorReporter, type IHealth, type IHealthCheckable, ILogger, IMetrics, type INotification, type IPayment, IPlatform, type IPromptStore, IQueryBuilder, IQueue, IRAG, type IScheduler, IStorage, type ITenant, type IWebhook, type InboundWebhookConfig, type InboundWebhookContext, IngestionOptions, IngestionResult, type InsertHookContext, type InviteMemberOptions, type Invoice, type InvoiceLineItem, type InvoiceQuery, type InvoiceStatus, Job, JobEventHandler, JobEventType, type JobHookContext, JobOptions, JobState, KeyRotationResult, type ListTenantsOptions, type LivenessResponse, MemoryAIUsage, MemoryAuditLog, type MemoryAuditLogConfig, MemoryAuth, MemoryAuthSSO, MemoryBilling, MemoryCompliance, MemoryCrypto, MemoryDevPortal, MemoryDevice, MemoryErrorReporter, type MemoryErrorReporterConfig, MemoryNotification, type MemoryNotificationConfig, MemoryPayment, MemoryPromptStore, MemoryRateLimiterStorage, MemoryScheduler, type MemorySchedulerConfig, MemoryTenant, MemoryWebhook, type MemoryWebhookConfig, type Meter, type MetricsEndpoint, type MetricsEndpointOptions, MetricsSummary, type MfaChallenge, type MfaFactor, type MfaFactorType, type Middleware, type MiddlewareChain, type MiddlewareChainOptions, type MiddlewareContext, NodeCrypto, type NodeCryptoConfig, type NotificationAction, type NotificationCategory, type NotificationChannel, type NotificationConfig, type NotificationData, type NotificationPreferences, type NotificationPriority, type NotificationQuery, type NotificationResult, type NotificationStats, type NotificationStatus, type NotificationTarget, NotificationTemplates, type OAuthOptions, type OAuthProvider, type OAuthResult, type OidcAuthRequest, type OidcAuthResponse, type OidcClaimMapping, type OidcIdpConfig, OpenAIAdapter, type OpenAIAdapterConfig, PG_ERROR_MAP, type ParameterLocation, type PaymentConfig, type PaymentError, type PaymentErrorCode, PaymentErrorMessages, type PaymentEventType, type PaymentIntent, type PaymentMethod, type PaymentMethodType, type PaymentStatus, type PaymentWebhookEvent, type Payout, type PayoutStatus, type PiaMitigation, type PiaRisk, type PiaStatus, PineconeRAG, type PineconeRAGConfig, type PlatformHealthResult, PlatformHealthStatus, type PlatformHooks, type PostgresConfig, PostgresDatabase, PostgresTenant, type PostgresTenantConfig, type Price, type PricingModel, type PricingTier, type PrivacyImpactAssessment, type Product, type Prompt, type PromptChain, type PromptChainStep, type PromptExperiment, type PromptQuery, type PromptQueryResult, type PromptStatus, type PromptStoreConfig, type PromptType, type PromptUsageRecord, type PromptUsageStats, type PromptVariable, type PromptVariant, type PromptVersion, type ProvisioningConfig, type ProvisioningRequest, type ProvisioningResult, type ProvisioningStatus, type PushSubscription, type QueryHookContext, QueryResult, QueueScheduler, type QueueSchedulerConfig, type Quota, type QuotaStatus, type QuotaType, RAGChunk, RAGCollection, RAGConfig, RAGDocument, RAGPipeline, RAGSearchQuery, RAGSearchResponse, RAGSearchResult, type RateLimitAlgorithm, RateLimitError, type RateLimitInfo, type RateLimitOptions, RateLimitPresets, type RateLimiterStorage, type ReadinessResponse, type RecordConsentOptions, RedisCache, type RedisConfig, type Refund, type RefundReason, type RefundStatus, type RenderOptions, type RenderedPrompt, RepeatOptions, ResendEmail, type ResetPasswordOptions, type RetentionAction, type RetentionExecution, type RetentionPolicy, RetryConfigs, type RetryOptions, RetryPredicates, type RetryResult, type RevenueMetrics, type RiskLevel, S3Storage, type SamlAssertion, type SamlAttributeMapping, type SamlAuthRequest, type SamlAuthResponse, type SamlIdpConfig, type SamlNameIdFormat, type SamlSpConfig, type Sandbox, type SandboxConfig, type SandboxLimits, type SandboxStatus, type SandboxUsage, type ScheduleContext, type ScheduleExecution, type ScheduleHandler, type ScheduleQuery, type ScheduleState, type ScheduleUpdateOptions, type ScheduledJob, type SchedulerConfig, type SchedulerStats, type ScimConfig, type ScimUser, type SdkConfig, type SdkFile, type SdkLanguage, type SendCommandOptions, type SendNotificationOptions, type ServiceHealth, type ShadowDelta, type ShadowMetadata, type ShadowUpdate, type SignInWithEmailOptions, type SignInWithMagicLinkOptions, type SignInWithPhoneOptions, type SignUpWithEmailOptions, type SignatureAlgorithm, type SlidingWindowRateLimitOptions, type SmtpConfig, SmtpEmail, type SsoSession, type StartupResponse, StorageFile, type StoredAuditEvent, type StoredNotification, StripePayment, type StripePaymentConfig, type Subscription, type SubscriptionDiscount, type SubscriptionItem, type SubscriptionMetrics, type SubscriptionQuery, type SubscriptionStatus, SupabaseAuth, type SupabaseAuthConfig, SupabaseDatabase, SupabaseStorage, type SupabaseStorageConfig, type TaxBreakdown, type TelemetryMessage, type TelemetryQuery, type TelemetryResult, type Tenant, type TenantBranding, type TenantContext, type TenantDatabaseConfig, type TenantInvitation, type TenantIsolationModel, type TenantMember, type TenantMemberStatus, type TenantQuotas, type TenantResolutionOptions, type TenantResolutionStrategy, type TenantRole, type TenantSecuritySettings, type TenantSettings, type TenantStatus, type TenantUsage, TimeoutError, type TimeoutOptions, type TokenBucketOptions, type TosAcceptance, type Transfer, type TransferStatus, URL_DOMAIN_PATTERN, URL_PROTOCOL_PATTERN, type Unsubscribe, type UpdateCustomerOptions, type UpdateHookContext, type UpdatePasswordOptions, type UpdatePaymentIntentOptions, type UpdateScheduleOptions, type UpdateStatus, type UpdateTenantOptions, type UpdateUserOptions, type UpdateWebhookOptions, type UploadHookContext, UploadOptions, UpstashCache, type UsageAlert, type UsageCategory, type UsageEvent, type UsageInterval, type UsageInvoice, type UsageInvoiceItem, type UsageQuery, type UsageQueryResult, type UsageRecord, type UsageSummary, type UsageSummaryRecord, type UsageTrend, type VerificationResult, type VerifyMfaOptions, type VerifyPhoneOtpOptions, type VerifyWebhookOptions, WeaviateRAG, type WeaviateRAGConfig, type WebhookConfig, type WebhookDelivery, type WebhookEndpoint, type WebhookEvent, WebhookEventTypes, type WebhookQuery, type WebhookState, type WebhookStats, type WebhookTestEndpoint, type WebhookTestEvent, buildPagination, calculateRetryDelay, classifyError, composeHookRegistries, containsHtml, containsUrls, correlationContext, createAnthropicAdapter, createAuthError, createBulkhead, createCacheMiddleware, createCachedFallback, createCircuitBreaker, createDefaultPreferences, createErrorReport, createExpressHealthHandlers, createExpressMetricsHandler, createGoogleAIAdapter, createHealthEndpoints, createHealthServer, createHookRegistry, createIpKeyGenerator, createJobContext, createLoggingMiddleware, createMetricsEndpoint, createMetricsMiddleware, createMetricsServer, createMiddlewareChain, createMiddlewareContext, createObservabilityServer, createOpenAIAdapter, createPaymentError, createPineconeRAG, createRateLimitMiddleware, createRequestContext, createRequestIdMiddleware, createSlowQueryMiddleware, createTenantMiddleware, createTimeoutMiddleware, createUserKeyGenerator, createWeaviateRAG, defangUrl, describeCron, escapeHtml, filterChannelsByPreferences, formatAmount, generateAuditId, generateChecksum, generateDeliveryId, generateErrorId, generateEventId, generateFingerprint, generateNotificationId, generatePaymentId, generateScheduleId, generateSecureToken, generateWebhookId, generateWebhookSecret, getContext, getCorrelationId, getLogMeta, getNextCronRun, getRequestId, getTenantId, getTraceId, getUserId, isApiError, isAuthError, isInContext, isInQuietHours, isPaymentError, isValidCron, matchAction, matchEventType, raceTimeout, retryable, runWithContext, runWithContextAsync, sanitizeForEmail, stripHtml, timedHealthCheck, toHealthCheckResult, withCorrelation, withCorrelationAsync, withFallback, withFallbackChain, withFallbackResult, withRetry, withRetryResult, withTimeout, withTimeoutWrapper };
13214
+ /**
13215
+ * Environment Variable Helpers
13216
+ *
13217
+ * Type-safe, fail-fast utilities for reading environment variables.
13218
+ * Every app needs these — extracted from DLL, WIAN, and OSS patterns.
13219
+ *
13220
+ * @example
13221
+ * ```typescript
13222
+ * import { getRequiredEnv, getOptionalEnv, getBoolEnv, validateEnvVars } from '@digilogiclabs/platform-core'
13223
+ *
13224
+ * const config = {
13225
+ * stripe: { secretKey: getRequiredEnv('STRIPE_SECRET_KEY') },
13226
+ * redis: { url: getOptionalEnv('REDIS_URL', '') },
13227
+ * features: { debug: getBoolEnv('DEBUG', false) },
13228
+ * }
13229
+ *
13230
+ * // Validate at startup
13231
+ * validateEnvVars({
13232
+ * required: ['STRIPE_SECRET_KEY', 'DATABASE_URL'],
13233
+ * requireOneOf: [['DATABASE_URL', 'SUPABASE_URL']], // at least one
13234
+ * validators: {
13235
+ * DATABASE_URL: (v) => v.startsWith('postgres') || 'must start with postgres://',
13236
+ * ADMIN_SECRET: (v) => v.length >= 32 || 'must be at least 32 characters',
13237
+ * },
13238
+ * })
13239
+ * ```
13240
+ */
13241
+ /**
13242
+ * Get a required environment variable.
13243
+ * Throws immediately if not set — fail-fast at startup.
13244
+ */
13245
+ declare function getRequiredEnv(key: string): string;
13246
+ /**
13247
+ * Get an optional environment variable with a default value.
13248
+ */
13249
+ declare function getOptionalEnv(key: string, defaultValue: string): string;
13250
+ /**
13251
+ * Get a boolean environment variable.
13252
+ * Treats "true" and "1" as true, everything else as false.
13253
+ */
13254
+ declare function getBoolEnv(key: string, defaultValue?: boolean): boolean;
13255
+ /**
13256
+ * Get a numeric environment variable with a default.
13257
+ */
13258
+ declare function getIntEnv(key: string, defaultValue: number): number;
13259
+ /**
13260
+ * Configuration for environment validation.
13261
+ */
13262
+ interface EnvValidationConfig {
13263
+ /** Variables that must be set (non-empty) */
13264
+ required?: string[];
13265
+ /** Groups where at least one must be set (e.g., DATABASE_URL or SUPABASE_URL) */
13266
+ requireOneOf?: string[][];
13267
+ /** Custom validators — return true or an error message */
13268
+ validators?: Record<string, (value: string) => true | string>;
13269
+ }
13270
+ /**
13271
+ * Validation result with categorized errors.
13272
+ */
13273
+ interface EnvValidationResult {
13274
+ valid: boolean;
13275
+ missing: string[];
13276
+ invalid: {
13277
+ key: string;
13278
+ reason: string;
13279
+ }[];
13280
+ missingOneOf: string[][];
13281
+ }
13282
+ /**
13283
+ * Validate environment variables against a configuration.
13284
+ *
13285
+ * @throws Error with details about all missing/invalid variables
13286
+ */
13287
+ declare function validateEnvVars(config: EnvValidationConfig): void;
13288
+ /**
13289
+ * Check environment variables without throwing.
13290
+ * Returns a result object for custom error handling.
13291
+ */
13292
+ declare function checkEnvVars(config: EnvValidationConfig): EnvValidationResult;
13293
+ /**
13294
+ * Get a redacted config summary for debugging.
13295
+ * Shows which variables are configured without exposing values.
13296
+ */
13297
+ declare function getEnvSummary(keys: string[]): Record<string, boolean>;
13298
+
13299
+ /**
13300
+ * Application Logger
13301
+ *
13302
+ * Structured logger with child loggers, request correlation,
13303
+ * and operation timing. Builds on ConsoleLogger but adds the
13304
+ * patterns every app needs: component loggers, request loggers,
13305
+ * job loggers, and timing wrappers.
13306
+ *
13307
+ * @example
13308
+ * ```typescript
13309
+ * import { createAppLogger } from '@digilogiclabs/platform-core'
13310
+ *
13311
+ * const logger = createAppLogger({ service: 'my-app' })
13312
+ *
13313
+ * // Child loggers for components
13314
+ * const authLogger = logger.child({ component: 'auth' })
13315
+ * authLogger.info('User signed in', { userId: '123' })
13316
+ *
13317
+ * // Request-scoped logger with correlation ID
13318
+ * const reqLogger = logger.forRequest(request, 'create-server')
13319
+ * reqLogger.info('Processing request')
13320
+ *
13321
+ * // Timed operations
13322
+ * const result = await logger.timed('fetchArticles', () => fetchArticles(), { count: 10 })
13323
+ * ```
13324
+ */
13325
+ interface AppLogContext {
13326
+ [key: string]: unknown;
13327
+ }
13328
+ /**
13329
+ * Structured logger interface shared across all apps.
13330
+ */
13331
+ interface AppLogger {
13332
+ debug(message: string, context?: AppLogContext): void;
13333
+ info(message: string, context?: AppLogContext): void;
13334
+ warn(message: string, context?: AppLogContext): void;
13335
+ error(message: string, context?: AppLogContext): void;
13336
+ /** Create a child logger with additional persistent context */
13337
+ child(context: AppLogContext): AppLogger;
13338
+ /** Create a request-scoped logger with correlation ID */
13339
+ forRequest(request: Request, operation: string): AppLogger;
13340
+ /** Create a job-scoped logger */
13341
+ forJob(jobType: string, jobId: string, context?: AppLogContext): AppLogger;
13342
+ /**
13343
+ * Execute an async operation with automatic timing.
13344
+ * Logs start (debug), success with duration (info), or failure with duration (error).
13345
+ */
13346
+ timed<T>(operation: string, fn: () => Promise<T>, context?: AppLogContext): Promise<T>;
13347
+ }
13348
+ interface AppLoggerOptions {
13349
+ /** Service/app name for log context */
13350
+ service: string;
13351
+ /** Minimum log level (default: 'debug' in dev, 'info' in production) */
13352
+ minLevel?: "debug" | "info" | "warn" | "error";
13353
+ /** Custom output handler (default: console with JSON in prod, pretty in dev) */
13354
+ output?: (level: string, message: string, context: AppLogContext) => void;
13355
+ /** Error reporter callback — called on error() logs */
13356
+ onError?: (message: string, context: AppLogContext) => void;
13357
+ }
13358
+ /**
13359
+ * Create an application logger.
13360
+ *
13361
+ * @param options - Logger configuration
13362
+ * @returns Structured logger with child, request, job, and timing support
13363
+ */
13364
+ declare function createAppLogger(options: AppLoggerOptions): AppLogger;
13365
+
13366
+ /**
13367
+ * Redis Client Factory
13368
+ *
13369
+ * Shared ioredis singleton factory with retry strategy and graceful
13370
+ * degradation. All self-hosted apps need a Redis client for rate
13371
+ * limiting, caching, audit logging, webhook deduplication, etc.
13372
+ *
13373
+ * This provides a raw ioredis client — for higher-level cache
13374
+ * operations, use RedisCache from the adapters module.
13375
+ *
13376
+ * @example
13377
+ * ```typescript
13378
+ * import { createRedisClient, getSharedRedis } from '@digilogiclabs/platform-core'
13379
+ *
13380
+ * // Option 1: Shared singleton (recommended for most apps)
13381
+ * const redis = getSharedRedis() // null if REDIS_URL not set
13382
+ *
13383
+ * // Option 2: Custom client with options
13384
+ * const redis = createRedisClient({
13385
+ * url: process.env.REDIS_URL,
13386
+ * keyPrefix: 'myapp:',
13387
+ * maxRetries: 5,
13388
+ * })
13389
+ * ```
13390
+ */
13391
+
13392
+ interface RedisClientOptions {
13393
+ /** Redis connection URL (redis://...) */
13394
+ url: string;
13395
+ /** Key prefix for namespace isolation (e.g., 'dll:', 'wian:') */
13396
+ keyPrefix?: string;
13397
+ /** Max retries per request (default: 3) */
13398
+ maxRetries?: number;
13399
+ /** Use lazy connect — don't connect until first command (default: true) */
13400
+ lazyConnect?: boolean;
13401
+ /** Logger for connection events (default: console) */
13402
+ logger?: {
13403
+ error: (msg: string, meta?: Record<string, unknown>) => void;
13404
+ info?: (msg: string, meta?: Record<string, unknown>) => void;
13405
+ };
13406
+ /** Suppress connection error logs (useful for tests) */
13407
+ silent?: boolean;
13408
+ }
13409
+ /**
13410
+ * Create a new ioredis client with sensible defaults.
13411
+ *
13412
+ * Features:
13413
+ * - Exponential backoff retry strategy (200ms, 400ms, 600ms)
13414
+ * - Automatic reconnection
13415
+ * - Optional key prefix for multi-app isolation
13416
+ * - Connection error logging (suppressible)
13417
+ */
13418
+ declare function createRedisClient(options: RedisClientOptions): Redis$2;
13419
+ /**
13420
+ * Get the shared Redis client singleton.
13421
+ *
13422
+ * Returns null if REDIS_URL is not configured — callers should
13423
+ * handle this gracefully (fail-open pattern).
13424
+ *
13425
+ * Reads from `REDIS_URL` and optionally `REDIS_KEY_PREFIX`.
13426
+ */
13427
+ declare function getSharedRedis(): Redis$2 | null;
13428
+ /**
13429
+ * Close the shared Redis client.
13430
+ * Call during graceful shutdown.
13431
+ */
13432
+ declare function closeSharedRedis(): Promise<void>;
13433
+
13434
+ export { AIChatRequest, AIChatResponse, AICompletionRequest, AICompletionResponse, AIConfig, AIEmbeddingRequest, AIEmbeddingResponse, AIModelConfig, AIModelType, AIProvider, AIStreamCallback, AIStreamChunk, type AIUsageConfig, type AccountCapabilities, type AccountLink, type AccountType, type Address, type AlertType, AnthropicAdapter, type AnthropicAdapterConfig, type ApiAuthentication, type ApiChangelog, type ApiDocumentation, type ApiEndpoint, ApiError, ApiErrorCode, type ApiErrorCodeType, type ApiExample, type ApiKey, type ApiKeyStatus, type ApiKeyType, type ApiKeyValidationResult, type ApiPaginatedResponse, type ApiParameter, type ApiResponse, type ApiSchema, type ApiSchemaProperty, type ApiSuccessResponse, type ApiUsageStats, type ApiUsageTimeSeries, type AppLogContext, type AppLogger, type AppLoggerOptions, AssembledContext, type AuditActor, type AuditCategory, type AuditEvent, AuditEvents, type AuditEvidence, type AuditLogConfig, type AuditOutcome, type AuditQuery, type AuditQueryResult, type AuditRetentionPolicy, type AuditStats, type AuditTarget, type AuthConfig, type AuthError, type AuthErrorCode, AuthErrorMessages, type AuthEventType, type AuthResult, type AuthSession, type AuthStateChangeCallback, type AuthStorage, type AuthUser, type Balance, type BalanceAmount, type BankAccountDetails, type BatchNotificationOptions, type BillingConfig, type BillingDetails, type BillingPeriod, type Breadcrumb, type Budget, type BudgetStatus, BulkIngestionResult, Bulkhead, type BulkheadOptions, BulkheadRegistry, BulkheadRejectedError, type BulkheadStats, type BullMQConfig, BullMQQueue, type BusinessProfile, type CancelationReason, type CaptureOptions, type CapturePaymentIntentOptions, type CardBrand, type CardDetails, type ChainExecutionResult, CircuitBreaker, type CircuitBreakerOptions, CircuitBreakerRegistry, type CircuitBreakerStats, CircuitOpenError, type CircuitState, type CommandStatus, CommonApiErrors, type ComplianceConfig, type ComplianceReport, type ConfirmPaymentIntentOptions, type ConnectedAccount, type ConnectedAccountStatus, type ConsentPreferences, type ConsentPurpose, type ConsentRecord, type ConsentStatus, ContextAssemblyConfig, type ControlFramework, type ControlStatus, type CorrelationData, type CostBreakdown, type Coupon, type CreateAccountLinkOptions, type CreateApiKeyOptions, CreateCollectionOptions, type CreateConnectedAccountOptions, type CreateCustomerOptions, type CreateDsarOptions, type CreatePaymentIntentOptions, type CreatePayoutOptions, type CreateRefundOptions, type CreateSandboxOptions, type CreateScheduleOptions, type CreateTenantOptions, type CreateTransferOptions, type CreateWebhookOptions, type CreditBalance, type CreditTransaction, type CreditType, type CronExpression, CronPresets, CryptoKeyMetadata, type Currency, type Customer, DEFAULT_BULKHEAD_OPTIONS, DEFAULT_CIRCUIT_BREAKER_OPTIONS, DEFAULT_RETRY_OPTIONS, type DataBreachRecord, type DataCategory, type DataInventoryItem, type DataMap, type DataSensitivity, type DataSubjectRequest, type DataType, DatabaseAIUsage, type DatabaseAIUsageConfig, DatabaseAuditLog, type DatabaseAuditLogConfig, DatabaseBilling, type DatabaseBillingConfig, DatabaseCompliance, DatabaseErrorReporter, type DatabaseErrorReporterConfig, DatabaseNotification, type DatabaseNotificationConfig, DatabasePromptStore, type DatabasePromptStoreConfig, DefaultTimeouts, type DeleteAccountOptions, type DeleteHookContext, type DeliveryAttempt, type DeliveryQuery, type DeliveryStatus, type DetailedHealthResponse, DeterministicEncryptedField, type DevPortalConfig, type DeveloperMetrics, type Device, type DeviceAuthMethod, type DeviceCommand, type DeviceConfig, type DeviceConnectionState, type DeviceCredentials, type DeviceGroup, type DeviceGroupQuery, type DeviceLocation, type DeviceQuery, type DeviceQueryResult, type DeviceShadow, type DeviceStatus, type DirectoryAttributeMapping, type DirectoryConfig, DocumentStatus, type DsarAttachment, type DsarNote, type DsarStatus, type DsarType, type DunningActionType, type DunningAttempt, type DunningConfig, type EmailHookContext, EmailMessage, EmailResult, EncryptOptions, EncryptedField, type EnrollMfaOptions, type EnrollMfaResult, type EnvValidationConfig, type EnvValidationResult, type ErrorContext, type ErrorHookContext, type ErrorLevel, type ErrorReport, type ErrorReporterConfig, type EvidenceType, type ExperimentMetrics, type FallbackOptions, type FallbackResult, FallbackStrategies, type FirmwareStatus, type FirmwareUpdate, type FirmwareVersion, type GeneratedSdk, GenericOIDCAuthSSO, type GenericOIDCConfig, GoogleAIAdapter, type GoogleAIAdapterConfig, HTML_TAG_PATTERN, type HealthCheckResult, type HealthEndpoints, type HealthEndpointsOptions, type HealthStatus, type HookRegistry, type HttpMethod, HttpWebhook, type HttpWebhookConfig, IAI, type IAIUsage, type IAuditLog, type IAuth, type IAuthSSO, type IBilling, ICache, type ICompliance, ICrypto, IDatabase, type IDevPortal, type IDevice, IEmail, type IErrorReporter, type IHealth, type IHealthCheckable, ILogger, IMetrics, type INotification, type IPayment, IPlatform, type IPromptStore, IQueryBuilder, IQueue, IRAG, type IScheduler, IStorage, type ITenant, type IWebhook, type InboundWebhookConfig, type InboundWebhookContext, IngestionOptions, IngestionResult, type InsertHookContext, type InviteMemberOptions, type Invoice, type InvoiceLineItem, type InvoiceQuery, type InvoiceStatus, Job, JobEventHandler, JobEventType, type JobHookContext, JobOptions, JobState, KeyRotationResult, type ListTenantsOptions, type LivenessResponse, MemoryAIUsage, MemoryAuditLog, type MemoryAuditLogConfig, MemoryAuth, MemoryAuthSSO, MemoryBilling, MemoryCompliance, MemoryCrypto, MemoryDevPortal, MemoryDevice, MemoryErrorReporter, type MemoryErrorReporterConfig, MemoryNotification, type MemoryNotificationConfig, MemoryPayment, MemoryPromptStore, MemoryRateLimiterStorage, MemoryScheduler, type MemorySchedulerConfig, MemoryTenant, MemoryWebhook, type MemoryWebhookConfig, type Meter, type MetricsEndpoint, type MetricsEndpointOptions, MetricsSummary, type MfaChallenge, type MfaFactor, type MfaFactorType, type Middleware, type MiddlewareChain, type MiddlewareChainOptions, type MiddlewareContext, NodeCrypto, type NodeCryptoConfig, type NotificationAction, type NotificationCategory, type NotificationChannel, type NotificationConfig, type NotificationData, type NotificationPreferences, type NotificationPriority, type NotificationQuery, type NotificationResult, type NotificationStats, type NotificationStatus, type NotificationTarget, NotificationTemplates, type OAuthOptions, type OAuthProvider, type OAuthResult, type OidcAuthRequest, type OidcAuthResponse, type OidcClaimMapping, type OidcIdpConfig, OpenAIAdapter, type OpenAIAdapterConfig, PG_ERROR_MAP, type ParameterLocation, type PaymentConfig, type PaymentError, type PaymentErrorCode, PaymentErrorMessages, type PaymentEventType, type PaymentIntent, type PaymentMethod, type PaymentMethodType, type PaymentStatus, type PaymentWebhookEvent, type Payout, type PayoutStatus, type PiaMitigation, type PiaRisk, type PiaStatus, PineconeRAG, type PineconeRAGConfig, type PlatformHealthResult, PlatformHealthStatus, type PlatformHooks, type PostgresConfig, PostgresDatabase, PostgresTenant, type PostgresTenantConfig, type Price, type PricingModel, type PricingTier, type PrivacyImpactAssessment, type Product, type Prompt, type PromptChain, type PromptChainStep, type PromptExperiment, type PromptQuery, type PromptQueryResult, type PromptStatus, type PromptStoreConfig, type PromptType, type PromptUsageRecord, type PromptUsageStats, type PromptVariable, type PromptVariant, type PromptVersion, type ProvisioningConfig, type ProvisioningRequest, type ProvisioningResult, type ProvisioningStatus, type PushSubscription, type QueryHookContext, QueryResult, QueueScheduler, type QueueSchedulerConfig, type Quota, type QuotaStatus, type QuotaType, RAGChunk, RAGCollection, RAGConfig, RAGDocument, RAGPipeline, RAGSearchQuery, RAGSearchResponse, RAGSearchResult, type RateLimitAlgorithm, RateLimitError, type RateLimitInfo, RateLimitPresets, type RateLimiterStorage, type ReadinessResponse, type RecordConsentOptions, RedisCache, type RedisClientOptions, type RedisConfig, type Refund, type RefundReason, type RefundStatus, type RenderOptions, type RenderedPrompt, RepeatOptions, ResendEmail, type ResetPasswordOptions, type RetentionAction, type RetentionExecution, type RetentionPolicy, RetryConfigs, type RetryOptions, RetryPredicates, type RetryResult, type RevenueMetrics, type RiskLevel, S3Storage, type SamlAssertion, type SamlAttributeMapping, type SamlAuthRequest, type SamlAuthResponse, type SamlIdpConfig, type SamlNameIdFormat, type SamlSpConfig, type Sandbox, type SandboxConfig, type SandboxLimits, type SandboxStatus, type SandboxUsage, type ScheduleContext, type ScheduleExecution, type ScheduleHandler, type ScheduleQuery, type ScheduleState, type ScheduleUpdateOptions, type ScheduledJob, type SchedulerConfig, type SchedulerStats, type ScimConfig, type ScimUser, type SdkConfig, type SdkFile, type SdkLanguage, type SendCommandOptions, type SendNotificationOptions, type ServiceHealth, type ShadowDelta, type ShadowMetadata, type ShadowUpdate, type SignInWithEmailOptions, type SignInWithMagicLinkOptions, type SignInWithPhoneOptions, type SignUpWithEmailOptions, type SignatureAlgorithm, type SlidingWindowRateLimitOptions, type SmtpConfig, SmtpEmail, type SsoSession, type StartupResponse, StorageFile, type StoredAuditEvent, type StoredNotification, StripePayment, type StripePaymentConfig, type Subscription, type SubscriptionDiscount, type SubscriptionItem, type SubscriptionMetrics, type SubscriptionQuery, type SubscriptionStatus, SupabaseAuth, type SupabaseAuthConfig, SupabaseDatabase, SupabaseStorage, type SupabaseStorageConfig, type TaxBreakdown, type TelemetryMessage, type TelemetryQuery, type TelemetryResult, type Tenant, type TenantBranding, type TenantContext, type TenantDatabaseConfig, type TenantInvitation, type TenantIsolationModel, type TenantMember, type TenantMemberStatus, type TenantQuotas, type TenantResolutionOptions, type TenantResolutionStrategy, type TenantRole, type TenantSecuritySettings, type TenantSettings, type TenantStatus, type TenantUsage, TimeoutError, type TimeoutOptions, type TokenBucketOptions, type TosAcceptance, type Transfer, type TransferStatus, URL_DOMAIN_PATTERN, URL_PROTOCOL_PATTERN, type Unsubscribe, type UpdateCustomerOptions, type UpdateHookContext, type UpdatePasswordOptions, type UpdatePaymentIntentOptions, type UpdateScheduleOptions, type UpdateStatus, type UpdateTenantOptions, type UpdateUserOptions, type UpdateWebhookOptions, type UploadHookContext, UploadOptions, UpstashCache, type UsageAlert, type UsageCategory, type UsageEvent, type UsageInterval, type UsageInvoice, type UsageInvoiceItem, type UsageQuery, type UsageQueryResult, type UsageRecord, type UsageSummary, type UsageSummaryRecord, type UsageTrend, type VerificationResult, type VerifyMfaOptions, type VerifyPhoneOtpOptions, type VerifyWebhookOptions, WeaviateRAG, type WeaviateRAGConfig, type WebhookConfig, type WebhookDelivery, type WebhookEndpoint, type WebhookEvent, WebhookEventTypes, type WebhookQuery, type WebhookState, type WebhookStats, type WebhookTestEndpoint, type WebhookTestEvent, buildPagination, calculateRetryDelay, checkEnvVars, classifyError, closeSharedRedis, composeHookRegistries, constantTimeEqual, containsHtml, containsUrls, correlationContext, createAnthropicAdapter, createAppLogger, createAuthError, createBulkhead, createCacheMiddleware, createCachedFallback, createCircuitBreaker, createDefaultPreferences, createErrorReport, createExpressHealthHandlers, createExpressMetricsHandler, createGoogleAIAdapter, createHealthEndpoints, createHealthServer, createHookRegistry, createIpKeyGenerator, createJobContext, createLoggingMiddleware, createMetricsEndpoint, createMetricsMiddleware, createMetricsServer, createMiddlewareChain, createMiddlewareContext, createObservabilityServer, createOpenAIAdapter, createPaymentError, createPineconeRAG, createRateLimitMiddleware, createRedisClient, createRequestContext, createRequestIdMiddleware, createSlowQueryMiddleware, createTenantMiddleware, createTimeoutMiddleware, createUserKeyGenerator, createWeaviateRAG, defangUrl, describeCron, escapeHtml, filterChannelsByPreferences, formatAmount, generateAuditId, generateChecksum, generateDeliveryId, generateErrorId, generateEventId, generateFingerprint, generateNotificationId, generatePaymentId, generateScheduleId, generateSecureToken, generateWebhookId, generateWebhookSecret, getBoolEnv, getContext, getCorrelationId, getEnvSummary, getIntEnv, getLogMeta, getNextCronRun, getOptionalEnv, getRequestId, getRequiredEnv, getSharedRedis, getTenantId, getTraceId, getUserId, isApiError, isAuthError, isInContext, isInQuietHours, isPaymentError, isValidCron, matchAction, matchEventType, raceTimeout, retryable, runWithContext, runWithContextAsync, sanitizeApiError, sanitizeForEmail, stripHtml, timedHealthCheck, toHealthCheckResult, validateEnvVars, withCorrelation, withCorrelationAsync, withFallback, withFallbackChain, withFallbackResult, withRetry, withRetryResult, withTimeout, withTimeoutWrapper };