@burdenoff/be-sdk 2026.1110.3 → 2026.1110.4
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/activity/index.d.ts +165 -0
- package/dist/activity/index.js +389 -0
- package/dist/activity/index.js.map +1 -0
- package/dist/ai-credits/index.js +1 -1
- package/dist/{ai-credits-Ca-NNcVx.js → ai-credits-xxfwGpHS.js} +2 -2
- package/dist/{ai-credits-Ca-NNcVx.js.map → ai-credits-xxfwGpHS.js.map} +1 -1
- package/dist/auth/index.d.ts +1 -1
- package/dist/auth/index.js +1 -1
- package/dist/{auth-CEuBEBQN.js → auth-C5ctwSLp.js} +2 -2
- package/dist/{auth-CEuBEBQN.js.map → auth-C5ctwSLp.js.map} +1 -1
- package/dist/bootstrap/index.d.ts +74 -0
- package/dist/bootstrap/index.js +282 -0
- package/dist/bootstrap/index.js.map +1 -0
- package/dist/{client-DcZ3iGES.js → client-sAJTrb4i.js} +2 -2
- package/dist/{client-DcZ3iGES.js.map → client-sAJTrb4i.js.map} +1 -1
- package/dist/context/index.d.ts +35 -0
- package/dist/{context-CZnXf2yb.js → context/index.js} +38 -2
- package/dist/context/index.js.map +1 -0
- package/dist/database/index.js +1 -1
- package/dist/event-queue/index.d.ts +1 -1
- package/dist/explicit-activity-scope-DikJ7NAE.js +57 -0
- package/dist/explicit-activity-scope-DikJ7NAE.js.map +1 -0
- package/dist/export/index.js +1 -1
- package/dist/{export-B6fphx8a.js → export-DJXE3Osa.js} +3 -3
- package/dist/{export-B6fphx8a.js.map → export-DJXE3Osa.js.map} +1 -1
- package/dist/feature-flags/index.js +1 -1
- package/dist/{feature-flags-71oDkrUe.js → feature-flags-CP1KRgwD.js} +2 -2
- package/dist/{feature-flags-71oDkrUe.js.map → feature-flags-CP1KRgwD.js.map} +1 -1
- package/dist/files/index.js +1 -1
- package/dist/{files-DjH0099H.js → files-h5U-D2AF.js} +2 -2
- package/dist/{files-DjH0099H.js.map → files-h5U-D2AF.js.map} +1 -1
- package/dist/gateway/index.js +2 -2
- package/dist/{gateway-DBFmxWks.js → gateway-ByVo-n37.js} +2 -2
- package/dist/{gateway-DBFmxWks.js.map → gateway-ByVo-n37.js.map} +1 -1
- package/dist/graph/index.d.ts +1 -1
- package/dist/graph/index.js +1 -1
- package/dist/{graph-DDYgIryR.js → graph-CR7u4lpl.js} +2 -2
- package/dist/{graph-DDYgIryR.js.map → graph-CR7u4lpl.js.map} +1 -1
- package/dist/{graphql-DNkMkGBZ.d.ts → graphql-CUDyhibV.d.ts} +1 -1
- package/dist/{index-bZKZUvBu.d.ts → index-ADmsX0BI.d.ts} +3 -3
- package/dist/{index-BqYfCQSP.d.ts → index-B2LCaK0R.d.ts} +1 -1
- package/dist/{index-D6UeLAye.d.ts → index-CHwMhK6v.d.ts} +2 -2
- package/dist/{index-BQDsNAMR.d.ts → index-CTTwo9av.d.ts} +22 -1
- package/dist/{index-DZC-2o9R.d.ts → index-CVCyKzhB.d.ts} +2 -2
- package/dist/{index-CkT2aUr3.d.ts → index-C_GXXF32.d.ts} +2 -2
- package/dist/{index-BKwHQtHQ.d.ts → index-Cot73bdh.d.ts} +1 -1
- package/dist/{index-CnzbJZP7.d.ts → index-FRRaa6h2.d.ts} +2 -2
- package/dist/{index-N-huORcj.d.ts → index-U_tu3zUl.d.ts} +2 -2
- package/dist/index-cmR9k9ga.d.ts +26 -0
- package/dist/{index-CZTnQIRU.d.ts → index-zd_NPGJo.d.ts} +6 -141
- package/dist/index.d.ts +19 -479
- package/dist/index.js +22 -1492
- package/dist/index.js.map +1 -1
- package/dist/init/index.js +1 -1
- package/dist/{init-Dy3KhT6Y.js → init-CQPFmOOe.js} +3 -3
- package/dist/{init-Dy3KhT6Y.js.map → init-CQPFmOOe.js.map} +1 -1
- package/dist/instrumentation/index.d.ts +2 -2
- package/dist/logger/index.d.ts +1 -1
- package/dist/notifications/index.d.ts +1 -1
- package/dist/notifications/index.js +1 -1
- package/dist/{notifications-CdETrtFK.js → notifications-DY_i37WN.js} +2 -2
- package/dist/{notifications-CdETrtFK.js.map → notifications-DY_i37WN.js.map} +1 -1
- package/dist/payments/index.d.ts +144 -0
- package/dist/payments/index.js +404 -0
- package/dist/payments/index.js.map +1 -0
- package/dist/rate-limit-CBrK_U5H.js +142 -0
- package/dist/rate-limit-CBrK_U5H.js.map +1 -0
- package/dist/rbac/index.d.ts +1 -1
- package/dist/rbac/index.js +1 -1
- package/dist/{rbac-BB9l9Xph.js → rbac-Dvz0YzEt.js} +2 -2
- package/dist/{rbac-BB9l9Xph.js.map → rbac-Dvz0YzEt.js.map} +1 -1
- package/dist/resource-caps/index.d.ts +1 -1
- package/dist/search/index.d.ts +112 -0
- package/dist/search/index.js +266 -0
- package/dist/search/index.js.map +1 -0
- package/dist/security/index.d.ts +2 -0
- package/dist/security/index.js +4 -0
- package/dist/security/index.js.map +1 -0
- package/dist/security/rate-limit/index.d.ts +2 -0
- package/dist/security/rate-limit/index.js +4 -0
- package/dist/security/rate-limit/index.js.map +1 -0
- package/dist/server/index.js +3 -2
- package/dist/server/index.js.map +1 -1
- package/dist/{stub-BqwKn4eh.js → stub-BUnfMiAS.js} +3 -56
- package/dist/stub-BUnfMiAS.js.map +1 -0
- package/dist/tags/index.js +1 -1
- package/dist/{tags-B5xpbgsk.js → tags-CbijgoqR.js} +2 -2
- package/dist/{tags-B5xpbgsk.js.map → tags-CbijgoqR.js.map} +1 -1
- package/dist/telemetry/index.d.ts +2 -2
- package/dist/tracker/index.d.ts +2 -2
- package/dist/tracker/index.js +5 -3
- package/dist/{tracker-BQVoEFUo.js → tracker-PQztSlhJ.js} +9 -390
- package/dist/tracker-PQztSlhJ.js.map +1 -0
- package/dist/translation/index.d.ts +120 -0
- package/dist/translation/index.js +573 -0
- package/dist/translation/index.js.map +1 -0
- package/dist/types/index.d.ts +3 -0
- package/dist/{types-Cj2RWXbz.js → types/index.js} +3 -3
- package/dist/types/index.js.map +1 -0
- package/dist/usage/index.d.ts +1 -1
- package/dist/usage/index.js +1 -1
- package/dist/{usage-BKFZiWQn.js → usage-BRqVP3CJ.js} +4 -4
- package/dist/{usage-BKFZiWQn.js.map → usage-BRqVP3CJ.js.map} +1 -1
- package/package.json +1 -1
- package/dist/context-CZnXf2yb.js.map +0 -1
- package/dist/stub-BqwKn4eh.js.map +0 -1
- package/dist/tracker-BQVoEFUo.js.map +0 -1
- package/dist/types-Cj2RWXbz.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"init-Dy3KhT6Y.js","names":[],"sources":["../src/init/index.ts"],"sourcesContent":["/**\n * Burdenoff SDK Initialization Module\n *\n * Provides a unified initialization function for all state services\n * including database, cache, analytics, event queue, and graph sync.\n *\n * @module init\n * @category Initialization\n */\n\nimport { logger } from '../logger/index.js';\nimport { LayerManager } from '../layer/index.js';\nimport { GatewayClient } from '../gateway/index.js';\nimport { configureResourceCaps } from '../resource-caps/index.js';\nimport { createCounter } from '../instrumentation/metrics-collector.js';\nimport type { BurdenoffSDKInitConfig, InitializedSDKState } from './types.js';\n\n/**\n * Global SDK state\n */\nlet sdkState: InitializedSDKState | null = null;\nlet isInitialized = false;\n\n/**\n * Initialize Burdenoff SDK with unified configuration\n *\n * This function initializes all configured state services in the correct order:\n * 1. Logging configuration\n * 2. Database (Prisma with PostgreSQL)\n * 3. Cache (Valkey)\n * 4. Event Queue (Redis Streams)\n * 5. Graph Sync (Redis Streams-based — Apache AGE writes happen inside wspace-graph-svc)\n * 6. Analytics (ClickHouse)\n * 7. Observability (Metrics, OpenTelemetry)\n *\n * @param config - SDK initialization configuration\n * @returns Initialized SDK state\n *\n * @example\n * ```typescript\n * import { initializeBurdenoffSDK } from '@burdenoff/be-sdk/init';\n *\n * const state = await initializeBurdenoffSDK({\n * database: {\n * url: process.env.DATABASE_URL!,\n * maxConnections: 20,\n * },\n * graph: {\n * enabled: true,\n * eventsEnabled: true,\n * },\n * cache: {\n * valkey: {\n * url: process.env.VALKEY_URL!,\n * },\n * },\n * });\n * ```\n */\nexport async function initializeBurdenoffSDK(config: BurdenoffSDKInitConfig): Promise<InitializedSDKState> {\n if (isInitialized && sdkState) {\n logger.warn('[SDK Init] SDK already initialized, returning existing state');\n return sdkState;\n }\n\n logger.info('[SDK Init] Starting SDK initialization...');\n const startTime = Date.now();\n\n try {\n // 1. Configure logging\n await initializeLogging(config);\n\n // 2. Initialize layer manager (if configured)\n const { layerManager, gatewayClient } = await initializeLayer(config);\n\n // 2b. Wire resource caps to billing so plan-based limits actually apply.\n // `userBillingPlan` lives in the GLOBAL layer: global services reach it\n // on their own internal gateway; wspace services go cross-layer via the\n // public global gateway (service JWT). Without this, every resource cap\n // silently collapses to the free-tier fallback regardless of the\n // customer's plan (BOFF-4805). Primes the process-wide singleton so all\n // existing `getResourceCaps()` call sites resolve real plans unchanged.\n if (gatewayClient && config.layer) {\n const layerType = config.layer.type;\n const fallbackCounter = createCounter(\n 'resource_caps.clientless_fallback_total',\n 'Total number of times resource caps fell back because no billing source was configured at bootstrap'\n );\n configureResourceCaps({\n transport: async (query, variables) => {\n // Cap checks run on entity-create paths and ALWAYS fall back to the\n // configured billing-failure tier on failure, so a billing outage\n // must degrade fast rather than stall writes. Bound the lookup with a\n // short timeout and no retries instead of the gateway defaults\n // (~30s × 3 ≈ 90s). Results are cached 60s, so healthy lookups rarely\n // hit the gateway anyway. `skipCircuitBreaker` keeps this best-effort\n // probe OUT of the shared gateway circuit: its failures already\n // degrade to the fallback here, so they must not count toward opening\n // the internal/cross-layer circuit and fail-fast unrelated M2M calls\n // during a billing outage.\n const options = { query, variables, timeout: 8000, skipRetry: true, skipCircuitBreaker: true };\n const response =\n layerType === 'global'\n ? await gatewayClient.internalQuery(options)\n : await gatewayClient.crossLayerQuery(options);\n return response?.data ?? null;\n },\n // Emitting a dedicated clientless-fallback counter at bootstrap means\n // a service that somehow starts without a billing transport is\n // immediately visible in metrics (BOFF-4809). The resource-caps module\n // itself also emits `resource_caps.plan_resolution_total`, but that\n // only fires on the first cap check; this counter fires at bootstrap.\n onFallback: () => fallbackCounter.inc(),\n });\n logger.info('[SDK Init] Resource caps wired to billing', { layer: layerType });\n } else {\n logger.warn('[SDK Init] No layer/gateway configured — resource caps will use free-tier fallbacks (BOFF-4805)');\n }\n\n // 3. Initialize database (required)\n const prisma = await initializeDatabase(config);\n\n // 4. Initialize cache (optional)\n const valkey = await initializeCache(config);\n\n // 5. Initialize event queue (optional) — Redis Streams via REDIS_URL\n const eventPublisher = await initializeEventQueue(config);\n\n // 6. Initialize layer streams (if layer configured)\n if (config.layer?.autoCreateStreams !== false && config.layer) {\n await initializeLayerStreams(config);\n }\n\n // 7. Initialize graph sync (optional) — publisher emits to Redis Streams,\n // never opens a graph-DB connection\n const graphSync = await initializeGraphSync(config);\n\n // 8. Initialize analytics (optional)\n const clickhouse = await initializeAnalytics(config);\n\n // 9. Initialize observability (optional)\n await initializeObservability(config);\n\n // Create SDK state\n // graphSync is a publisher-side placeholder; services emit Redis Streams\n // events and wspace-graph-svc owns the sole Apache AGE connection.\n void graphSync;\n sdkState = {\n prisma,\n valkey,\n clickhouse,\n eventPublisher,\n layerManager,\n gatewayClient,\n graphSyncEnabled: config.graph?.enabled ?? false,\n analyticsEnabled: !!config.analytics?.clickhouse,\n observabilityEnabled: config.observability?.metrics?.enabled ?? false,\n layerAwareEnabled: !!config.layer,\n };\n\n isInitialized = true;\n\n const duration = Date.now() - startTime;\n // sdkState is guaranteed non-null here since we just assigned it above\n const initializedState = sdkState;\n logger.info(`[SDK Init] SDK initialized successfully in ${duration}ms`, {\n graphSyncEnabled: initializedState.graphSyncEnabled,\n analyticsEnabled: initializedState.analyticsEnabled,\n observabilityEnabled: initializedState.observabilityEnabled,\n layerAwareEnabled: initializedState.layerAwareEnabled,\n layer: config.layer?.type,\n serviceName: config.layer?.serviceName,\n });\n\n return initializedState;\n } catch (error) {\n logger.error('[SDK Init] Failed to initialize SDK:', error);\n throw error;\n }\n}\n\n/**\n * Get current SDK state\n * @throws Error if SDK is not initialized\n */\nexport function getSDKState(): InitializedSDKState {\n if (!isInitialized || !sdkState) {\n throw new Error('SDK not initialized. Call initializeBurdenoffSDK() first.');\n }\n return sdkState;\n}\n\n/**\n * Check if SDK is initialized\n */\nexport function isSDKInitialized(): boolean {\n return isInitialized;\n}\n\n/**\n * Reset SDK state (useful for testing)\n */\nexport async function resetSDK(): Promise<void> {\n logger.info('[SDK Init] Resetting SDK state...');\n\n if (sdkState) {\n // Cleanup resources\n // Note: Individual cleanup will be handled by service-specific shutdown handlers\n sdkState = null;\n }\n\n isInitialized = false;\n logger.info('[SDK Init] SDK state reset');\n}\n\n/**\n * Initialize logging configuration\n */\nasync function initializeLogging(config: BurdenoffSDKInitConfig): Promise<void> {\n logger.info('[SDK Init] Configuring logging...');\n\n const loggingConfig = config.logging ?? {};\n const isDevelopment = config.app?.nodeEnv === 'development';\n\n // Set log level\n const level = loggingConfig.level ?? 'info';\n logger.setLevel(level);\n\n // Set console logging\n const console = loggingConfig.console ?? true;\n logger.setConsoleEnabled(console);\n\n logger.info('[SDK Init] Logging configured', {\n level,\n console,\n format: loggingConfig.format ?? (isDevelopment ? 'pretty' : 'json'),\n });\n}\n\n/**\n * Initialize database (Prisma with PostgreSQL)\n */\nasync function initializeDatabase(config: BurdenoffSDKInitConfig): Promise<unknown> {\n logger.info('[SDK Init] Initializing database...');\n\n // Note: Database initialization is handled by createPrismaClient in prisma/client.ts\n // This is called by the application (e.g., workspaces-backend)\n // We just validate the config here\n if (!config.database?.url) {\n throw new Error('Database URL is required');\n }\n\n logger.info('[SDK Init] Database configuration validated', {\n maxConnections: config.database.maxConnections ?? 20,\n enableQueryLogging: config.database.enableQueryLogging ?? false,\n });\n\n // Return undefined as database client is created separately\n return undefined;\n}\n\n/**\n * Initialize cache (Valkey)\n */\nasync function initializeCache(config: BurdenoffSDKInitConfig): Promise<unknown> {\n const cacheConfig = config.cache?.valkey;\n\n if (!cacheConfig) {\n logger.info('[SDK Init] Cache not configured, skipping');\n return undefined;\n }\n\n logger.info('[SDK Init] Initializing Valkey cache...');\n\n // Note: Valkey initialization is handled by cache module\n // This is a placeholder for future implementation\n logger.info('[SDK Init] Valkey cache configuration validated', {\n url: cacheConfig.url ? '***' : undefined,\n defaultTTL: cacheConfig.defaultTTL ?? 3600,\n });\n\n return undefined;\n}\n\n/**\n * Initialize event queue (Redis Streams).\n *\n * NATS was retired on 2026-05-16. The publisher is created from\n * `REDIS_STREAMS_URL` when set, else `REDIS_URL` (set in every SM bundle). Legacy `config.eventQueue.nats`\n * values are ignored — kept on the type only as a back-compat shim.\n */\nasync function initializeEventQueue(_config: BurdenoffSDKInitConfig): Promise<unknown> {\n const { resolveEventStreamsUrl } = await import('../event-queue/env.js');\n if (!resolveEventStreamsUrl()) {\n logger.info('[SDK Init] REDIS_STREAMS_URL / REDIS_URL not set, skipping event queue init');\n return undefined;\n }\n\n try {\n const { EventQueueFactory } = await import('../event-queue/factory/EventQueueFactory.js');\n const publisher = EventQueueFactory.createPublisherFromEnv();\n await publisher.connect();\n\n logger.info('[SDK Init] Redis Streams event publisher connected');\n\n return publisher;\n } catch (error) {\n logger.warn('[SDK Init] Failed to connect Redis Streams event publisher (non-fatal)', {\n error: error instanceof Error ? error.message : String(error),\n note: 'Service will continue without event publishing. Use direct API calls as fallback.',\n });\n return undefined;\n }\n}\n\n/**\n * Initialize graph sync (Redis Streams publisher side).\n *\n * Services publish entity events to Redis Streams; the `wspace-graph-svc`\n * consumer (and only it) persists them into Apache AGE via Azure PG\n * sidecar. This SDK function does no DB work — it just validates that the\n * publisher-side config is sensible and logs it.\n */\nasync function initializeGraphSync(config: BurdenoffSDKInitConfig): Promise<unknown> {\n if (!config.graph?.enabled) {\n logger.info('[SDK Init] Graph sync not enabled, skipping');\n return undefined;\n }\n\n logger.info('[SDK Init] Graph sync enabled (publisher-only mode)', {\n eventsEnabled: config.graph.eventsEnabled ?? true,\n productSource: config.graph.productSource,\n streamName: config.graph.streamName ?? 'graph_events',\n syncInterval: config.graph.syncInterval ?? 1000,\n batchSize: config.graph.batchSize ?? 10,\n });\n\n return undefined;\n}\n\n/**\n * Initialize analytics (ClickHouse)\n */\nasync function initializeAnalytics(config: BurdenoffSDKInitConfig): Promise<unknown> {\n if (!config.analytics?.clickhouse) {\n logger.info('[SDK Init] Analytics not configured, skipping');\n return undefined;\n }\n\n logger.info('[SDK Init] Initializing ClickHouse for analytics...');\n\n // Note: ClickHouse initialization is handled by analytics module\n // This is a placeholder for future implementation\n logger.info('[SDK Init] ClickHouse configuration validated', {\n url: config.analytics.clickhouse.url,\n database: config.analytics.clickhouse.database,\n requestTimeout: config.analytics.clickhouse.requestTimeout ?? 60000,\n });\n\n return undefined;\n}\n\n/**\n * Initialize observability (metrics, tracing)\n */\nasync function initializeObservability(config: BurdenoffSDKInitConfig): Promise<void> {\n if (!config.observability?.metrics?.enabled && !config.observability?.openTelemetry?.enabled) {\n logger.info('[SDK Init] Observability not configured, skipping');\n return;\n }\n\n logger.info('[SDK Init] Initializing observability...');\n\n // Note: Observability initialization is handled by observability module\n // This is a placeholder for future implementation\n if (config.observability.metrics?.enabled) {\n logger.info('[SDK Init] Metrics configuration validated', {\n port: config.observability.metrics.port ?? 9090,\n endpoint: config.observability.metrics.endpoint ?? '/metrics',\n });\n }\n\n if (config.observability.openTelemetry?.enabled) {\n logger.info('[SDK Init] OpenTelemetry configuration validated', {\n serviceName: config.observability.openTelemetry.serviceName,\n samplingRate: config.observability.openTelemetry.samplingRate ?? 1.0,\n });\n }\n}\n\n/**\n * Initialize layer manager and gateway client\n */\nasync function initializeLayer(\n config: BurdenoffSDKInitConfig\n): Promise<{ layerManager?: LayerManager; gatewayClient?: GatewayClient }> {\n if (!config.layer) {\n logger.info('[SDK Init] Layer configuration not provided, skipping layer initialization');\n return {};\n }\n\n logger.info('[SDK Init] Initializing layer manager...', {\n layer: config.layer.type,\n serviceName: config.layer.serviceName,\n });\n\n // Create layer manager\n const layerManager = new LayerManager({\n layer: config.layer.type,\n serviceName: config.layer.serviceName,\n serviceIdentity: config.layer.serviceIdentity,\n });\n\n // Create gateway client\n const gatewayClient = new GatewayClient({\n layer: config.layer.type,\n serviceName: config.layer.serviceName,\n serviceIdentity: config.layer.serviceIdentity,\n internalGatewayUrl: layerManager.getInternalGatewayUrl(),\n crossLayerGatewayUrl: layerManager.getCrossLayerGatewayUrl(),\n });\n\n logger.info('[SDK Init] Layer manager initialized', {\n layer: config.layer.type,\n serviceName: config.layer.serviceName,\n internalGatewayUrl: layerManager.getInternalGatewayUrl(),\n crossLayerGatewayUrl: layerManager.getCrossLayerGatewayUrl(),\n });\n\n return { layerManager, gatewayClient };\n}\n\n/**\n * Initialize layer-specific Redis streams.\n *\n * No-op since the 2026-05-16 NATS retirement: Redis Streams are created\n * on demand by `XGROUP CREATE ... MKSTREAM` inside the consumer, so no\n * upfront connect-and-provision step is needed.\n */\nasync function initializeLayerStreams(config: BurdenoffSDKInitConfig): Promise<void> {\n if (!config.layer) {\n return;\n }\n logger.debug('[SDK Init] Layer streams init is a no-op for Redis Streams (auto-created on first XADD/XGROUP)', {\n layer: config.layer.type,\n });\n}\n\n// Export types\nexport type * from './types.js';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAoBA,IAAI,WAAuC;AAC3C,IAAI,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCpB,eAAsB,uBAAuB,QAA8D;CACzG,IAAI,iBAAiB,UAAU;EAC7B,OAAO,KAAK,8DAA8D;EAC1E,OAAO;CACT;CAEA,OAAO,KAAK,2CAA2C;CACvD,MAAM,YAAY,KAAK,IAAI;CAE3B,IAAI;EAEF,MAAM,kBAAkB,MAAM;EAG9B,MAAM,EAAE,cAAc,kBAAkB,MAAM,gBAAgB,MAAM;EASpE,IAAI,iBAAiB,OAAO,OAAO;GACjC,MAAM,YAAY,OAAO,MAAM;GAC/B,MAAM,kBAAkB,cACtB,2CACA,qGACF;GACA,sBAAsB;IACpB,WAAW,OAAO,OAAO,cAAc;KAWrC,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cAAc,cAAc,gBAAgB;CACnE,CAAC;AAEL;;;;AAKA,eAAe,gBACb,QACyE;CACzE,IAAI,CAAC,OAAO,OAAO;EACjB,OAAO,KAAK,4EAA4E;EACxF,OAAO,CAAC;CACV;CAEA,OAAO,KAAK,4CAA4C;EACtD,OAAO,OAAO,MAAM;EACpB,aAAa,OAAO,MAAM;CAC5B,CAAC;CAGD,MAAM,eAAe,IAAI,aAAa;EACpC,OAAO,OAAO,MAAM;EACpB,aAAa,OAAO,MAAM;EAC1B,iBAAiB,OAAO,MAAM;CAChC,CAAC;CAGD,MAAM,gBAAgB,IAAI,cAAc;EACtC,OAAO,OAAO,MAAM;EACpB,aAAa,OAAO,MAAM;EAC1B,iBAAiB,OAAO,MAAM;EAC9B,oBAAoB,aAAa,sBAAsB;EACvD,sBAAsB,aAAa,wBAAwB;CAC7D,CAAC;CAED,OAAO,KAAK,wCAAwC;EAClD,OAAO,OAAO,MAAM;EACpB,aAAa,OAAO,MAAM;EAC1B,oBAAoB,aAAa,sBAAsB;EACvD,sBAAsB,aAAa,wBAAwB;CAC7D,CAAC;CAED,OAAO;EAAE;EAAc;CAAc;AACvC;;;;;;;;AASA,eAAe,uBAAuB,QAA+C;CACnF,IAAI,CAAC,OAAO,OACV;CAEF,OAAO,MAAM,kGAAkG,EAC7G,OAAO,OAAO,MAAM,KACtB,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"init-CQPFmOOe.js","names":[],"sources":["../src/init/index.ts"],"sourcesContent":["/**\n * Burdenoff SDK Initialization Module\n *\n * Provides a unified initialization function for all state services\n * including database, cache, analytics, event queue, and graph sync.\n *\n * @module init\n * @category Initialization\n */\n\nimport { logger } from '../logger/index.js';\nimport { LayerManager } from '../layer/index.js';\nimport { GatewayClient } from '../gateway/index.js';\nimport { configureResourceCaps } from '../resource-caps/index.js';\nimport { createCounter } from '../instrumentation/metrics-collector.js';\nimport type { BurdenoffSDKInitConfig, InitializedSDKState } from './types.js';\n\n/**\n * Global SDK state\n */\nlet sdkState: InitializedSDKState | null = null;\nlet isInitialized = false;\n\n/**\n * Initialize Burdenoff SDK with unified configuration\n *\n * This function initializes all configured state services in the correct order:\n * 1. Logging configuration\n * 2. Database (Prisma with PostgreSQL)\n * 3. Cache (Valkey)\n * 4. Event Queue (Redis Streams)\n * 5. Graph Sync (Redis Streams-based — Apache AGE writes happen inside wspace-graph-svc)\n * 6. Analytics (ClickHouse)\n * 7. Observability (Metrics, OpenTelemetry)\n *\n * @param config - SDK initialization configuration\n * @returns Initialized SDK state\n *\n * @example\n * ```typescript\n * import { initializeBurdenoffSDK } from '@burdenoff/be-sdk/init';\n *\n * const state = await initializeBurdenoffSDK({\n * database: {\n * url: process.env.DATABASE_URL!,\n * maxConnections: 20,\n * },\n * graph: {\n * enabled: true,\n * eventsEnabled: true,\n * },\n * cache: {\n * valkey: {\n * url: process.env.VALKEY_URL!,\n * },\n * },\n * });\n * ```\n */\nexport async function initializeBurdenoffSDK(config: BurdenoffSDKInitConfig): Promise<InitializedSDKState> {\n if (isInitialized && sdkState) {\n logger.warn('[SDK Init] SDK already initialized, returning existing state');\n return sdkState;\n }\n\n logger.info('[SDK Init] Starting SDK initialization...');\n const startTime = Date.now();\n\n try {\n // 1. Configure logging\n await initializeLogging(config);\n\n // 2. Initialize layer manager (if configured)\n const { layerManager, gatewayClient } = await initializeLayer(config);\n\n // 2b. Wire resource caps to billing so plan-based limits actually apply.\n // `userBillingPlan` lives in the GLOBAL layer: global services reach it\n // on their own internal gateway; wspace services go cross-layer via the\n // public global gateway (service JWT). Without this, every resource cap\n // silently collapses to the free-tier fallback regardless of the\n // customer's plan (BOFF-4805). Primes the process-wide singleton so all\n // existing `getResourceCaps()` call sites resolve real plans unchanged.\n if (gatewayClient && config.layer) {\n const layerType = config.layer.type;\n const fallbackCounter = createCounter(\n 'resource_caps.clientless_fallback_total',\n 'Total number of times resource caps fell back because no billing source was configured at bootstrap'\n );\n configureResourceCaps({\n transport: async (query, variables) => {\n // Cap checks run on entity-create paths and ALWAYS fall back to the\n // configured billing-failure tier on failure, so a billing outage\n // must degrade fast rather than stall writes. Bound the lookup with a\n // short timeout and no retries instead of the gateway defaults\n // (~30s × 3 ≈ 90s). Results are cached 60s, so healthy lookups rarely\n // hit the gateway anyway. `skipCircuitBreaker` keeps this best-effort\n // probe OUT of the shared gateway circuit: its failures already\n // degrade to the fallback here, so they must not count toward opening\n // the internal/cross-layer circuit and fail-fast unrelated M2M calls\n // during a billing outage.\n const options = { query, variables, timeout: 8000, skipRetry: true, skipCircuitBreaker: true };\n const response =\n layerType === 'global'\n ? await gatewayClient.internalQuery(options)\n : await gatewayClient.crossLayerQuery(options);\n return response?.data ?? null;\n },\n // Emitting a dedicated clientless-fallback counter at bootstrap means\n // a service that somehow starts without a billing transport is\n // immediately visible in metrics (BOFF-4809). The resource-caps module\n // itself also emits `resource_caps.plan_resolution_total`, but that\n // only fires on the first cap check; this counter fires at bootstrap.\n onFallback: () => fallbackCounter.inc(),\n });\n logger.info('[SDK Init] Resource caps wired to billing', { layer: layerType });\n } else {\n logger.warn('[SDK Init] No layer/gateway configured — resource caps will use free-tier fallbacks (BOFF-4805)');\n }\n\n // 3. Initialize database (required)\n const prisma = await initializeDatabase(config);\n\n // 4. Initialize cache (optional)\n const valkey = await initializeCache(config);\n\n // 5. Initialize event queue (optional) — Redis Streams via REDIS_URL\n const eventPublisher = await initializeEventQueue(config);\n\n // 6. Initialize layer streams (if layer configured)\n if (config.layer?.autoCreateStreams !== false && config.layer) {\n await initializeLayerStreams(config);\n }\n\n // 7. Initialize graph sync (optional) — publisher emits to Redis Streams,\n // never opens a graph-DB connection\n const graphSync = await initializeGraphSync(config);\n\n // 8. Initialize analytics (optional)\n const clickhouse = await initializeAnalytics(config);\n\n // 9. Initialize observability (optional)\n await initializeObservability(config);\n\n // Create SDK state\n // graphSync is a publisher-side placeholder; services emit Redis Streams\n // events and wspace-graph-svc owns the sole Apache AGE connection.\n void graphSync;\n sdkState = {\n prisma,\n valkey,\n clickhouse,\n eventPublisher,\n layerManager,\n gatewayClient,\n graphSyncEnabled: config.graph?.enabled ?? false,\n analyticsEnabled: !!config.analytics?.clickhouse,\n observabilityEnabled: config.observability?.metrics?.enabled ?? false,\n layerAwareEnabled: !!config.layer,\n };\n\n isInitialized = true;\n\n const duration = Date.now() - startTime;\n // sdkState is guaranteed non-null here since we just assigned it above\n const initializedState = sdkState;\n logger.info(`[SDK Init] SDK initialized successfully in ${duration}ms`, {\n graphSyncEnabled: initializedState.graphSyncEnabled,\n analyticsEnabled: initializedState.analyticsEnabled,\n observabilityEnabled: initializedState.observabilityEnabled,\n layerAwareEnabled: initializedState.layerAwareEnabled,\n layer: config.layer?.type,\n serviceName: config.layer?.serviceName,\n });\n\n return initializedState;\n } catch (error) {\n logger.error('[SDK Init] Failed to initialize SDK:', error);\n throw error;\n }\n}\n\n/**\n * Get current SDK state\n * @throws Error if SDK is not initialized\n */\nexport function getSDKState(): InitializedSDKState {\n if (!isInitialized || !sdkState) {\n throw new Error('SDK not initialized. Call initializeBurdenoffSDK() first.');\n }\n return sdkState;\n}\n\n/**\n * Check if SDK is initialized\n */\nexport function isSDKInitialized(): boolean {\n return isInitialized;\n}\n\n/**\n * Reset SDK state (useful for testing)\n */\nexport async function resetSDK(): Promise<void> {\n logger.info('[SDK Init] Resetting SDK state...');\n\n if (sdkState) {\n // Cleanup resources\n // Note: Individual cleanup will be handled by service-specific shutdown handlers\n sdkState = null;\n }\n\n isInitialized = false;\n logger.info('[SDK Init] SDK state reset');\n}\n\n/**\n * Initialize logging configuration\n */\nasync function initializeLogging(config: BurdenoffSDKInitConfig): Promise<void> {\n logger.info('[SDK Init] Configuring logging...');\n\n const loggingConfig = config.logging ?? {};\n const isDevelopment = config.app?.nodeEnv === 'development';\n\n // Set log level\n const level = loggingConfig.level ?? 'info';\n logger.setLevel(level);\n\n // Set console logging\n const console = loggingConfig.console ?? true;\n logger.setConsoleEnabled(console);\n\n logger.info('[SDK Init] Logging configured', {\n level,\n console,\n format: loggingConfig.format ?? (isDevelopment ? 'pretty' : 'json'),\n });\n}\n\n/**\n * Initialize database (Prisma with PostgreSQL)\n */\nasync function initializeDatabase(config: BurdenoffSDKInitConfig): Promise<unknown> {\n logger.info('[SDK Init] Initializing database...');\n\n // Note: Database initialization is handled by createPrismaClient in prisma/client.ts\n // This is called by the application (e.g., workspaces-backend)\n // We just validate the config here\n if (!config.database?.url) {\n throw new Error('Database URL is required');\n }\n\n logger.info('[SDK Init] Database configuration validated', {\n maxConnections: config.database.maxConnections ?? 20,\n enableQueryLogging: config.database.enableQueryLogging ?? false,\n });\n\n // Return undefined as database client is created separately\n return undefined;\n}\n\n/**\n * Initialize cache (Valkey)\n */\nasync function initializeCache(config: BurdenoffSDKInitConfig): Promise<unknown> {\n const cacheConfig = config.cache?.valkey;\n\n if (!cacheConfig) {\n logger.info('[SDK Init] Cache not configured, skipping');\n return undefined;\n }\n\n logger.info('[SDK Init] Initializing Valkey cache...');\n\n // Note: Valkey initialization is handled by cache module\n // This is a placeholder for future implementation\n logger.info('[SDK Init] Valkey cache configuration validated', {\n url: cacheConfig.url ? '***' : undefined,\n defaultTTL: cacheConfig.defaultTTL ?? 3600,\n });\n\n return undefined;\n}\n\n/**\n * Initialize event queue (Redis Streams).\n *\n * NATS was retired on 2026-05-16. The publisher is created from\n * `REDIS_STREAMS_URL` when set, else `REDIS_URL` (set in every SM bundle). Legacy `config.eventQueue.nats`\n * values are ignored — kept on the type only as a back-compat shim.\n */\nasync function initializeEventQueue(_config: BurdenoffSDKInitConfig): Promise<unknown> {\n const { resolveEventStreamsUrl } = await import('../event-queue/env.js');\n if (!resolveEventStreamsUrl()) {\n logger.info('[SDK Init] REDIS_STREAMS_URL / REDIS_URL not set, skipping event queue init');\n return undefined;\n }\n\n try {\n const { EventQueueFactory } = await import('../event-queue/factory/EventQueueFactory.js');\n const publisher = EventQueueFactory.createPublisherFromEnv();\n await publisher.connect();\n\n logger.info('[SDK Init] Redis Streams event publisher connected');\n\n return publisher;\n } catch (error) {\n logger.warn('[SDK Init] Failed to connect Redis Streams event publisher (non-fatal)', {\n error: error instanceof Error ? error.message : String(error),\n note: 'Service will continue without event publishing. Use direct API calls as fallback.',\n });\n return undefined;\n }\n}\n\n/**\n * Initialize graph sync (Redis Streams publisher side).\n *\n * Services publish entity events to Redis Streams; the `wspace-graph-svc`\n * consumer (and only it) persists them into Apache AGE via Azure PG\n * sidecar. This SDK function does no DB work — it just validates that the\n * publisher-side config is sensible and logs it.\n */\nasync function initializeGraphSync(config: BurdenoffSDKInitConfig): Promise<unknown> {\n if (!config.graph?.enabled) {\n logger.info('[SDK Init] Graph sync not enabled, skipping');\n return undefined;\n }\n\n logger.info('[SDK Init] Graph sync enabled (publisher-only mode)', {\n eventsEnabled: config.graph.eventsEnabled ?? true,\n productSource: config.graph.productSource,\n streamName: config.graph.streamName ?? 'graph_events',\n syncInterval: config.graph.syncInterval ?? 1000,\n batchSize: config.graph.batchSize ?? 10,\n });\n\n return undefined;\n}\n\n/**\n * Initialize analytics (ClickHouse)\n */\nasync function initializeAnalytics(config: BurdenoffSDKInitConfig): Promise<unknown> {\n if (!config.analytics?.clickhouse) {\n logger.info('[SDK Init] Analytics not configured, skipping');\n return undefined;\n }\n\n logger.info('[SDK Init] Initializing ClickHouse for analytics...');\n\n // Note: ClickHouse initialization is handled by analytics module\n // This is a placeholder for future implementation\n logger.info('[SDK Init] ClickHouse configuration validated', {\n url: config.analytics.clickhouse.url,\n database: config.analytics.clickhouse.database,\n requestTimeout: config.analytics.clickhouse.requestTimeout ?? 60000,\n });\n\n return undefined;\n}\n\n/**\n * Initialize observability (metrics, tracing)\n */\nasync function initializeObservability(config: BurdenoffSDKInitConfig): Promise<void> {\n if (!config.observability?.metrics?.enabled && !config.observability?.openTelemetry?.enabled) {\n logger.info('[SDK Init] Observability not configured, skipping');\n return;\n }\n\n logger.info('[SDK Init] Initializing observability...');\n\n // Note: Observability initialization is handled by observability module\n // This is a placeholder for future implementation\n if (config.observability.metrics?.enabled) {\n logger.info('[SDK Init] Metrics configuration validated', {\n port: config.observability.metrics.port ?? 9090,\n endpoint: config.observability.metrics.endpoint ?? '/metrics',\n });\n }\n\n if (config.observability.openTelemetry?.enabled) {\n logger.info('[SDK Init] OpenTelemetry configuration validated', {\n serviceName: config.observability.openTelemetry.serviceName,\n samplingRate: config.observability.openTelemetry.samplingRate ?? 1.0,\n });\n }\n}\n\n/**\n * Initialize layer manager and gateway client\n */\nasync function initializeLayer(\n config: BurdenoffSDKInitConfig\n): Promise<{ layerManager?: LayerManager; gatewayClient?: GatewayClient }> {\n if (!config.layer) {\n logger.info('[SDK Init] Layer configuration not provided, skipping layer initialization');\n return {};\n }\n\n logger.info('[SDK Init] Initializing layer manager...', {\n layer: config.layer.type,\n serviceName: config.layer.serviceName,\n });\n\n // Create layer manager\n const layerManager = new LayerManager({\n layer: config.layer.type,\n serviceName: config.layer.serviceName,\n serviceIdentity: config.layer.serviceIdentity,\n });\n\n // Create gateway client\n const gatewayClient = new GatewayClient({\n layer: config.layer.type,\n serviceName: config.layer.serviceName,\n serviceIdentity: config.layer.serviceIdentity,\n internalGatewayUrl: layerManager.getInternalGatewayUrl(),\n crossLayerGatewayUrl: layerManager.getCrossLayerGatewayUrl(),\n });\n\n logger.info('[SDK Init] Layer manager initialized', {\n layer: config.layer.type,\n serviceName: config.layer.serviceName,\n internalGatewayUrl: layerManager.getInternalGatewayUrl(),\n crossLayerGatewayUrl: layerManager.getCrossLayerGatewayUrl(),\n });\n\n return { layerManager, gatewayClient };\n}\n\n/**\n * Initialize layer-specific Redis streams.\n *\n * No-op since the 2026-05-16 NATS retirement: Redis Streams are created\n * on demand by `XGROUP CREATE ... MKSTREAM` inside the consumer, so no\n * upfront connect-and-provision step is needed.\n */\nasync function initializeLayerStreams(config: BurdenoffSDKInitConfig): Promise<void> {\n if (!config.layer) {\n return;\n }\n logger.debug('[SDK Init] Layer streams init is a no-op for Redis Streams (auto-created on first XADD/XGROUP)', {\n layer: config.layer.type,\n });\n}\n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C;CAED,OAAO;EAAE;EAAc;CAAc;AACvC;;;;;;;;AASA,eAAe,uBAAuB,QAA+C;CACnF,IAAI,CAAC,OAAO,OACV;CAEF,OAAO,MAAM,kGAAkG,EAC7G,OAAO,OAAO,MAAM,KACtB,CAAC;AACH"}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { u as logger } from "../index-
|
|
2
|
-
import { $ as Counter, A as buildMetricsConfig, At as HTTPInstrumentationConfig, B as GraphQLOperationType, Bt as TraceContext, C as DEFAULT_METRICS_CONFIG, Ct as isTracerInitialized, D as buildFeatureFlags, Dt as DatabaseInstrumentationConfig, E as buildDatabaseConfig, Et as CacheInstrumentationConfig, F as isInstrumentationConfigInitialized, Ft as MetricsConfig, G as createPrometheusPlugin, H as PrometheusPluginOptions, I as resetInstrumentationConfig, It as OperationContext, J as getGraphQLSpanFromContext, K as extractOperationInfo, L as updateInstrumentationConfig, Lt as STANDARD_METRICS, M as getInstrumentationConfig, Mt as InstrumentationFeatureFlags, N as initializeInstrumentationConfig, Nt as LoggingConfig, O as buildGraphQLConfig, Ot as EventQueueInstrumentationConfig, P as isFeatureEnabled, Pt as MetricDefinition, Q as isPrometheusAvailable, R as ApolloInlineTraceOptions, Rt as SpanAttributes, S as DEFAULT_LOGGING_CONFIG, St as injectTraceContext, T as ENV_VARS, Tt as withSpan, U as createApolloInlineTracePlugin, V as InstrumentationContextExtension, Vt as TracingConfig, W as createGraphQLInstrumentationPlugin, X as instrumentResolverMap, Y as instrumentResolver, Z as isApolloInlineTraceAvailable, _ as DEFAULT_DATABASE_CONFIG, _t as Tracer, at as createCounter, b as DEFAULT_GRAPHQL_CONFIG, bt as getTracer, c as resetInstrumentation, ct as createUpDownCounter, d as Log, dt as isMetricsRegistryInitialized, et as Gauge, f as Metric, ft as resetMetricsRegistry, g as DEFAULT_CACHE_CONFIG, gt as SpanStatus, h as traced, ht as SpanKind, i as getLogger, it as UpDownCounter, j as buildTracingConfig, jt as InstrumentationConfig, k as buildInstrumentationConfig, kt as GraphQLInstrumentationConfig, l as setupInstrumentation, lt as getMetricsRegistry, m as instrumented, mt as SpanEvent, n as InstrumentationSetupResult, nt as MetricLabels, o as initializeInstrumentation, ot as createGauge, p as Trace, pt as Span, q as getGraphQLOperationFromContext, r as SetupInstrumentationOptions, rt as MetricsRegistry, s as isInstrumentationInitialized, st as createHistogram, t as InitializeInstrumentationOptions, tt as Histogram, u as Instrument, ut as initializeMetricsRegistry, v as DEFAULT_EVENT_QUEUE_CONFIG, vt as extractTraceContext, w as DEFAULT_TRACING_CONFIG, wt as startSpan, x as DEFAULT_HTTP_CONFIG, xt as initializeTracer, y as DEFAULT_FEATURE_FLAGS, yt as getTraceContext, z as GraphQLOperationInfo, zt as SpanContext } from "../index-
|
|
1
|
+
import { u as logger } from "../index-Cot73bdh.js";
|
|
2
|
+
import { $ as Counter, A as buildMetricsConfig, At as HTTPInstrumentationConfig, B as GraphQLOperationType, Bt as TraceContext, C as DEFAULT_METRICS_CONFIG, Ct as isTracerInitialized, D as buildFeatureFlags, Dt as DatabaseInstrumentationConfig, E as buildDatabaseConfig, Et as CacheInstrumentationConfig, F as isInstrumentationConfigInitialized, Ft as MetricsConfig, G as createPrometheusPlugin, H as PrometheusPluginOptions, I as resetInstrumentationConfig, It as OperationContext, J as getGraphQLSpanFromContext, K as extractOperationInfo, L as updateInstrumentationConfig, Lt as STANDARD_METRICS, M as getInstrumentationConfig, Mt as InstrumentationFeatureFlags, N as initializeInstrumentationConfig, Nt as LoggingConfig, O as buildGraphQLConfig, Ot as EventQueueInstrumentationConfig, P as isFeatureEnabled, Pt as MetricDefinition, Q as isPrometheusAvailable, R as ApolloInlineTraceOptions, Rt as SpanAttributes, S as DEFAULT_LOGGING_CONFIG, St as injectTraceContext, T as ENV_VARS, Tt as withSpan, U as createApolloInlineTracePlugin, V as InstrumentationContextExtension, Vt as TracingConfig, W as createGraphQLInstrumentationPlugin, X as instrumentResolverMap, Y as instrumentResolver, Z as isApolloInlineTraceAvailable, _ as DEFAULT_DATABASE_CONFIG, _t as Tracer, at as createCounter, b as DEFAULT_GRAPHQL_CONFIG, bt as getTracer, c as resetInstrumentation, ct as createUpDownCounter, d as Log, dt as isMetricsRegistryInitialized, et as Gauge, f as Metric, ft as resetMetricsRegistry, g as DEFAULT_CACHE_CONFIG, gt as SpanStatus, h as traced, ht as SpanKind, i as getLogger, it as UpDownCounter, j as buildTracingConfig, jt as InstrumentationConfig, k as buildInstrumentationConfig, kt as GraphQLInstrumentationConfig, l as setupInstrumentation, lt as getMetricsRegistry, m as instrumented, mt as SpanEvent, n as InstrumentationSetupResult, nt as MetricLabels, o as initializeInstrumentation, ot as createGauge, p as Trace, pt as Span, q as getGraphQLOperationFromContext, r as SetupInstrumentationOptions, rt as MetricsRegistry, s as isInstrumentationInitialized, st as createHistogram, t as InitializeInstrumentationOptions, tt as Histogram, u as Instrument, ut as initializeMetricsRegistry, v as DEFAULT_EVENT_QUEUE_CONFIG, vt as extractTraceContext, w as DEFAULT_TRACING_CONFIG, wt as startSpan, x as DEFAULT_HTTP_CONFIG, xt as initializeTracer, y as DEFAULT_FEATURE_FLAGS, yt as getTraceContext, z as GraphQLOperationInfo, zt as SpanContext } from "../index-B2LCaK0R.js";
|
|
3
3
|
export { type ApolloInlineTraceOptions, type CacheInstrumentationConfig, type Counter, DEFAULT_CACHE_CONFIG, DEFAULT_DATABASE_CONFIG, DEFAULT_EVENT_QUEUE_CONFIG, DEFAULT_FEATURE_FLAGS, DEFAULT_GRAPHQL_CONFIG, DEFAULT_HTTP_CONFIG, DEFAULT_LOGGING_CONFIG, DEFAULT_METRICS_CONFIG, DEFAULT_TRACING_CONFIG, type DatabaseInstrumentationConfig, ENV_VARS, type EventQueueInstrumentationConfig, type Gauge, type GraphQLInstrumentationConfig, type GraphQLOperationInfo, type GraphQLOperationType, type HTTPInstrumentationConfig, type Histogram, InitializeInstrumentationOptions, Instrument, type InstrumentationConfig, type InstrumentationContextExtension, type InstrumentationFeatureFlags, InstrumentationSetupResult, Log, type LoggingConfig, Metric, type MetricDefinition, type MetricLabels, type MetricsConfig, MetricsRegistry, type OperationContext, type PrometheusPluginOptions, STANDARD_METRICS, SetupInstrumentationOptions, type Span, type SpanAttributes, type SpanContext, type SpanEvent, SpanKind, SpanStatus, Trace, type TraceContext, Tracer, type TracingConfig, type UpDownCounter, buildDatabaseConfig, buildFeatureFlags, buildGraphQLConfig, buildInstrumentationConfig, buildMetricsConfig, buildTracingConfig, createApolloInlineTracePlugin, createCounter, createGauge, createGraphQLInstrumentationPlugin, createHistogram, createPrometheusPlugin, createUpDownCounter, extractOperationInfo, extractTraceContext, getGraphQLOperationFromContext, getGraphQLSpanFromContext, getInstrumentationConfig, getLogger, getMetricsRegistry, getTraceContext, getTracer, initializeInstrumentation, initializeInstrumentationConfig, initializeMetricsRegistry, initializeTracer, injectTraceContext, instrumentResolver, instrumentResolverMap, instrumented, isApolloInlineTraceAvailable, isFeatureEnabled, isInstrumentationConfigInitialized, isInstrumentationInitialized, isMetricsRegistryInitialized, isPrometheusAvailable, isTracerInitialized, logger, resetInstrumentation, resetInstrumentationConfig, resetMetricsRegistry, setupInstrumentation, startSpan, traced, updateInstrumentationConfig, withSpan };
|
package/dist/logger/index.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as LoggerTransport, d as redactSensitiveFields, f as redactSensitiveString, i as LoggerConfig, l as log, n as LogMeta, o as debug, p as warn, r as Logger, s as error, t as LogLevel, u as logger } from "../index-
|
|
1
|
+
import { a as LoggerTransport, d as redactSensitiveFields, f as redactSensitiveString, i as LoggerConfig, l as log, n as LogMeta, o as debug, p as warn, r as Logger, s as error, t as LogLevel, u as logger } from "../index-Cot73bdh.js";
|
|
2
2
|
export { LogLevel, LogMeta, Logger, LoggerConfig, LoggerTransport, debug, error, log, logger, redactSensitiveFields, redactSensitiveString, warn };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { _ as TenantNotificationsModule, a as NotificationType, c as SendChannelNotificationOptions, d as BatchNotificationInput, f as NotificationChannel$1, g as SendWithTemplateInput, h as SendNotificationInput, i as NotificationResponse, l as SendNotificationOptions, m as NotificationType$1, n as Notification, o as NotificationsModule, p as NotificationPriority, r as NotificationChannel, s as RecipientInput, t as GetNotificationsOptions, u as SendTemplateNotificationOptions } from "../index-
|
|
1
|
+
import { _ as TenantNotificationsModule, a as NotificationType, c as SendChannelNotificationOptions, d as BatchNotificationInput, f as NotificationChannel$1, g as SendWithTemplateInput, h as SendNotificationInput, i as NotificationResponse, l as SendNotificationOptions, m as NotificationType$1, n as Notification, o as NotificationsModule, p as NotificationPriority, r as NotificationChannel, s as RecipientInput, t as GetNotificationsOptions, u as SendTemplateNotificationOptions } from "../index-U_tu3zUl.js";
|
|
2
2
|
export { GetNotificationsOptions, Notification, NotificationChannel, NotificationPriority, NotificationResponse, NotificationType, NotificationsModule, RecipientInput, SendChannelNotificationOptions, SendNotificationOptions, SendTemplateNotificationOptions, type BatchNotificationInput as TenantBatchNotificationInput, NotificationChannel$1 as TenantNotificationChannel, NotificationType$1 as TenantNotificationType, TenantNotificationsModule, type SendNotificationInput as TenantSendNotificationInput, type SendWithTemplateInput as TenantSendWithTemplateInput };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as NotificationPriority, i as NotificationChannel$1, n as NotificationType, o as NotificationType$1, r as NotificationsModule, s as TenantNotificationsModule, t as NotificationChannel } from "../notifications-
|
|
1
|
+
import { a as NotificationPriority, i as NotificationChannel$1, n as NotificationType, o as NotificationType$1, r as NotificationsModule, s as TenantNotificationsModule, t as NotificationChannel } from "../notifications-DY_i37WN.js";
|
|
2
2
|
|
|
3
3
|
export { NotificationChannel, NotificationPriority, NotificationType, NotificationsModule, NotificationChannel$1 as TenantNotificationChannel, NotificationType$1 as TenantNotificationType, TenantNotificationsModule };
|
|
4
4
|
//# sourceMappingURL=index.js.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { t as __exportAll } from "./rolldown-runtime-ad2WFvuA.js";
|
|
2
|
-
import {
|
|
2
|
+
import { APIError, ValidationError } from "./types/index.js";
|
|
3
3
|
import { a as logger } from "./logger-B6rCpb7D.js";
|
|
4
4
|
|
|
5
5
|
// src/notifications/tenant-notifications.ts
|
|
@@ -866,4 +866,4 @@ var NotificationsModule = class {
|
|
|
866
866
|
};
|
|
867
867
|
|
|
868
868
|
export { NotificationPriority as a, tenant_notifications_exports as c, NotificationChannel$1 as i, NotificationType as n, NotificationType$1 as o, NotificationsModule as r, TenantNotificationsModule as s, NotificationChannel as t };
|
|
869
|
-
//# sourceMappingURL=notifications-
|
|
869
|
+
//# sourceMappingURL=notifications-DY_i37WN.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"notifications-CdETrtFK.js","names":["NotificationChannel","NotificationType"],"sources":["../src/notifications/tenant-notifications.ts","../src/notifications/index.ts"],"sourcesContent":["/**\n * Tenant-Backend Notifications Module\n * Comprehensive notification system supporting 10+ channels via tenant-backend\n */\n\nimport type { BurdenoffGraphQLClient } from '../client/graphql.js';\nimport type { SDKContext } from '../types/index.js';\nimport { APIError, ValidationError } from '../types/index.js';\nimport { logger } from '../logger/index.js';\n\n// ========================================\n// Enums\n// ========================================\n\nexport enum NotificationChannel {\n EMAIL = 'EMAIL',\n SMS = 'SMS',\n PUSH = 'PUSH',\n IN_APP = 'IN_APP',\n WEBHOOK = 'WEBHOOK',\n WHATSAPP = 'WHATSAPP',\n TEAMS = 'TEAMS',\n SLACK = 'SLACK',\n TELEGRAM = 'TELEGRAM',\n DISCORD = 'DISCORD',\n}\n\nexport enum NotificationPriority {\n LOW = 'LOW',\n MEDIUM = 'MEDIUM',\n HIGH = 'HIGH',\n URGENT = 'URGENT',\n}\n\nexport enum NotificationType {\n TRANSACTIONAL = 'TRANSACTIONAL',\n MARKETING = 'MARKETING',\n SYSTEM = 'SYSTEM',\n ALERT = 'ALERT',\n}\n\n// ========================================\n// Types & Interfaces\n// ========================================\n\nexport interface RecipientInput {\n userId?: string;\n email?: string;\n phoneNumber?: string;\n pushToken?: string;\n whatsappNumber?: string;\n teamsUserId?: string;\n slackUserId?: string;\n webhookUrl?: string;\n name?: string;\n locale?: string;\n timezone?: string;\n}\n\nexport interface SendNotificationInput {\n recipient: RecipientInput;\n channel: NotificationChannel;\n type?: NotificationType;\n priority?: NotificationPriority;\n subject?: string;\n body: string;\n htmlBody?: string;\n data?: Record<string, unknown>;\n metadata?: Record<string, unknown>;\n scheduledFor?: Date;\n expiresAt?: Date;\n trackOpens?: boolean;\n trackClicks?: boolean;\n}\n\nexport interface SendWithTemplateInput {\n templateSlug: string;\n variables: Record<string, unknown>;\n recipient: RecipientInput;\n priority?: NotificationPriority;\n scheduledFor?: Date;\n expiresAt?: Date;\n trackOpens?: boolean;\n trackClicks?: boolean;\n /** Specific channel instance ID from channel service (takes precedence) */\n channelId?: string;\n /** Platform type for auto-failover (EMAIL, SMS, etc.) - used if channelId not provided */\n platform?: NotificationChannel;\n /** Timezone for scheduling */\n timezone?: string;\n}\n\nexport interface BatchNotificationInput {\n notifications: SendNotificationInput[];\n batchSize?: number;\n delayBetweenBatches?: number;\n priority?: NotificationPriority;\n}\n\nexport interface Notification {\n id: string;\n userId: string;\n channel: NotificationChannel;\n type: NotificationType;\n priority: NotificationPriority;\n status: string;\n deliveryStatus?: string;\n title: string;\n message: string;\n htmlMessage?: string;\n subject?: string;\n recipientEmail?: string;\n recipientPhone?: string;\n trackOpens: boolean;\n trackClicks: boolean;\n openedAt?: string;\n clickedAt?: string;\n sentAt?: string;\n deliveredAt?: string;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface NotificationTemplate {\n id: string;\n name: string;\n slug: string;\n description?: string;\n channel: NotificationChannel;\n type: NotificationType;\n locale: string;\n subject?: string;\n bodyTemplate: string;\n htmlTemplate?: string;\n variables: Array<{\n name: string;\n type: string;\n required: boolean;\n defaultValue?: unknown;\n description?: string;\n example?: unknown;\n }>;\n enabled: boolean;\n version: number;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface NotificationStats {\n total: number;\n pending: number;\n /** @deprecated The owner does not publish a queued counter. */\n queued?: number;\n /** @deprecated The owner does not publish a processing counter. */\n processing?: number;\n triggered: number;\n scheduled: number;\n cancelled: number;\n sent: number;\n delivered: number;\n failed: number;\n byChannel: Record<string, number>;\n byType: Record<string, number>;\n}\n\n// ========================================\n// Tenant Notifications Module\n// ========================================\n\n/**\n * Tenant-Backend Notifications Module\n * Provides access to the centralized notification system\n */\nexport class TenantNotificationsModule {\n constructor(\n private client: BurdenoffGraphQLClient,\n private context: SDKContext\n ) {}\n\n /**\n * Send a single notification\n */\n public async send(input: SendNotificationInput, context?: SDKContext): Promise<string> {\n this.validateSendInput(input);\n const notification = this.createNotificationInput(input);\n const callContext = { ...this.context, ...context };\n\n if (input.scheduledFor) {\n const response = await this.client.tenantQuery<{\n scheduleNotification: { notificationId: string; status: string };\n }>(\n `mutation ScheduleTenantNotification($input: ScheduleNotificationInput!) {\n scheduleNotification(input: $input) { notificationId status }\n }`,\n { input: { notification, scheduledFor: input.scheduledFor.toISOString(), timezone: input.recipient.timezone } },\n callContext\n );\n const result = response.scheduleNotification;\n if (!result?.notificationId || result.status !== 'PENDING') {\n throw new APIError('Notification scheduling was not acknowledged', { operation: 'scheduleNotification' });\n }\n return result.notificationId;\n }\n\n const response = await this.client.tenantQuery<{\n triggerNotification: { id: string; status: string; channel: NotificationChannel };\n }>(\n `mutation TriggerTenantNotification($input: TriggerNotificationInput!) {\n triggerNotification(input: $input) { id status channel }\n }`,\n { input: { notification, platform: input.channel, includeInApp: false } },\n callContext\n );\n const result = response.triggerNotification;\n if (\n !result?.id ||\n result.channel !== input.channel ||\n !['TRIGGERED', 'SENT', 'DELIVERED'].includes(result.status)\n ) {\n throw new APIError('Notification trigger was not acknowledged', {\n operation: 'triggerNotification',\n notificationId: result?.id,\n });\n }\n logger.info('[TenantNotifications] Notification accepted', {\n notificationId: result.id,\n channel: result.channel,\n status: result.status,\n });\n return result.id;\n }\n\n /** Owner input deliberately excludes scheduling, which has a separate API. */\n private createNotificationInput(input: SendNotificationInput, priority?: NotificationPriority) {\n return {\n recipient: input.recipient,\n channel: input.channel,\n type: input.type ?? NotificationType.TRANSACTIONAL,\n priority: input.priority ?? priority ?? NotificationPriority.MEDIUM,\n subject: input.subject,\n body: input.body,\n htmlBody: input.htmlBody,\n data: input.data,\n metadata: input.metadata,\n expiresAt: input.expiresAt?.toISOString(),\n trackOpens: input.trackOpens,\n trackClicks: input.trackClicks,\n };\n }\n\n /**\n * Send notification using a template\n */\n public async sendWithTemplate(input: SendWithTemplateInput, context?: SDKContext): Promise<string> {\n // Validate inputs\n if (!input.templateSlug || input.templateSlug.trim().length === 0) {\n throw new ValidationError('Template slug is required');\n }\n\n if (!input.variables || typeof input.variables !== 'object' || Array.isArray(input.variables)) {\n throw new ValidationError('Template variables must be an object');\n }\n\n if (!input.recipient || (!input.recipient.email && !input.recipient.userId)) {\n throw new ValidationError('Recipient email or userId is required');\n }\n\n this.validateDates(input);\n\n logger.info('[TenantNotifications] Sending notification with template', {\n templateSlug: input.templateSlug,\n priority: input.priority || NotificationPriority.MEDIUM,\n });\n\n const mutation = `\n mutation TriggerNotificationWithTemplate($input: TriggerNotificationWithTemplateInput!) {\n triggerNotificationWithTemplate(input: $input) {\n totalRequested\n totalTriggered\n totalFailed\n notifications {\n id\n status\n deliveryStatus\n }\n }\n }\n `;\n\n const variables = {\n input: {\n templateSlug: input.templateSlug,\n variables: input.variables,\n recipient: input.recipient,\n priority: input.priority || NotificationPriority.MEDIUM,\n scheduledFor: input.scheduledFor?.toISOString(),\n expiresAt: input.expiresAt?.toISOString(),\n trackOpens: input.trackOpens,\n trackClicks: input.trackClicks,\n // Platform is required for notification delivery routing\n // If channelId is specified, it takes precedence; otherwise platform determines delivery\n channelId: input.channelId,\n platform: input.platform || NotificationChannel.EMAIL,\n timezone: input.timezone,\n },\n };\n\n const response = await this.client.tenantQuery<{\n triggerNotificationWithTemplate: {\n totalRequested: number;\n totalTriggered: number;\n totalFailed: number;\n notifications: Array<{ id: string; status: string; deliveryStatus?: string }>;\n };\n }>(mutation, variables, { ...this.context, ...context });\n\n const result = response.triggerNotificationWithTemplate;\n const firstNotification = result.notifications[0];\n\n if (result.totalTriggered === 0 || !firstNotification) {\n throw new ValidationError(\n `Notification trigger failed: requested=${result.totalRequested}, triggered=${result.totalTriggered}, failed=${result.totalFailed}`\n );\n }\n\n logger.info('[TenantNotifications] Notification sent with template', {\n notificationId: firstNotification.id,\n status: firstNotification.status,\n totalTriggered: result.totalTriggered,\n totalFailed: result.totalFailed,\n });\n\n return firstNotification.id;\n }\n\n /**\n * Send batch notifications\n */\n public async sendBatch(\n input: BatchNotificationInput,\n context?: SDKContext\n ): Promise<{\n totalRequested: number;\n /** Legacy name for the owner's accepted totalTriggered counter, not final delivery. */\n totalQueued: number;\n totalFailed: number;\n batchId: string;\n }> {\n if (!input.notifications?.length) throw new ValidationError('At least one notification is required');\n for (const notification of input.notifications) this.validateSendInput(notification);\n const schedules = new Set(\n input.notifications.map((notification) => notification.scheduledFor?.toISOString() ?? '')\n );\n if (schedules.size > 1) {\n throw new ValidationError('Batch notifications must share a schedule; use send() for distinct schedules');\n }\n if (input.batchSize !== undefined && (!Number.isInteger(input.batchSize) || input.batchSize <= 0)) {\n throw new ValidationError('Batch size must be a positive integer');\n }\n if (\n input.delayBetweenBatches !== undefined &&\n (!Number.isInteger(input.delayBetweenBatches) || input.delayBetweenBatches < 0)\n ) {\n throw new ValidationError('Batch delay must be a nonnegative integer');\n }\n const response = await this.client.tenantQuery<{\n triggerBatchNotifications: { totalRequested: number; totalQueued: number; totalFailed: number; batchId: string };\n }>(\n `mutation TriggerTenantBatchNotifications($input: TriggerBatchNotificationsInput!) {\n triggerBatchNotifications(input: $input) { totalRequested totalQueued: totalTriggered totalFailed batchId }\n }`,\n {\n input: {\n notifications: input.notifications.map((notification) =>\n this.createNotificationInput(notification, input.priority)\n ),\n priority: input.priority,\n scheduledFor: input.notifications[0]?.scheduledFor?.toISOString(),\n batchSize: input.batchSize,\n delayBetweenBatches: input.delayBetweenBatches,\n },\n },\n { ...this.context, ...context }\n );\n const result = response.triggerBatchNotifications;\n if (!result?.batchId)\n throw new APIError('Notification batch was not acknowledged', { operation: 'triggerBatchNotifications' });\n return result;\n }\n\n /**\n * Get a notification by ID\n */\n public async getNotification(id: string): Promise<Notification | null> {\n const query = `\n query GetNotification($id: ID!) {\n notification(id: $id) {\n id\n userId\n channel\n type\n priority\n status\n deliveryStatus\n title\n message\n htmlMessage\n subject\n recipientEmail\n recipientPhone\n trackOpens\n trackClicks\n openedAt\n clickedAt\n sentAt\n deliveredAt\n createdAt\n updatedAt\n }\n }\n `;\n\n const response = await this.client.tenantQuery<{\n notification: Notification | null;\n }>(query, { id }, this.context);\n\n return response.notification;\n }\n\n /**\n * Get notifications with filters\n */\n public async getNotifications(filter?: {\n userId?: string;\n channel?: NotificationChannel;\n type?: NotificationType;\n status?: string;\n priority?: NotificationPriority;\n startDate?: Date;\n endDate?: Date;\n limit?: number;\n offset?: number;\n }): Promise<Notification[]> {\n const query = `\n query GetNotifications($filter: NotificationFilterInput, $limit: Int, $offset: Int) {\n notifications(filter: $filter, limit: $limit, offset: $offset) {\n items {\n id\n userId\n channel\n type\n priority\n status\n deliveryStatus\n title\n message\n subject\n recipientEmail\n trackOpens\n trackClicks\n openedAt\n clickedAt\n sentAt\n deliveredAt\n createdAt\n updatedAt\n }\n }\n }\n `;\n\n const variables = {\n filter: filter\n ? {\n userId: filter.userId,\n channel: filter.channel,\n type: filter.type,\n status: filter.status,\n priority: filter.priority,\n startDate: filter.startDate?.toISOString(),\n endDate: filter.endDate?.toISOString(),\n }\n : undefined,\n limit: filter?.limit ?? 50,\n offset: filter?.offset ?? 0,\n };\n\n const response = await this.client.tenantQuery<{\n notifications: { items: Notification[] };\n }>(query, variables, this.context);\n\n return response.notifications.items;\n }\n\n /**\n * Get notification template\n */\n public async getTemplate(slug: string, locale?: string): Promise<NotificationTemplate | null> {\n const query = `\n query GetNotificationTemplate($slug: String!, $locale: String) {\n notificationTemplate(slug: $slug, locale: $locale) {\n id\n name\n slug\n description\n channel\n type\n locale\n subject\n bodyTemplate\n htmlTemplate\n variables\n enabled\n version\n createdAt\n updatedAt\n }\n }\n `;\n\n const response = await this.client.tenantQuery<{\n notificationTemplate: NotificationTemplate | null;\n }>(query, { slug, locale }, this.context);\n\n return response.notificationTemplate;\n }\n\n /**\n * Get all notification templates\n */\n public async getTemplates(filter?: {\n channel?: NotificationChannel;\n type?: NotificationType;\n enabled?: boolean;\n }): Promise<NotificationTemplate[]> {\n const query = `query GetNotificationTemplates($filter: TemplateFilterInput, $limit: Int!, $offset: Int!) {\n notificationTemplates(filter: $filter, limit: $limit, offset: $offset) {\n items { id name slug description channel type locale subject bodyTemplate htmlTemplate variables enabled version createdAt updatedAt }\n hasMore\n }\n }`;\n const templates: NotificationTemplate[] = [];\n const seen = new Set<string>();\n for (let page = 0; page < 100; page++) {\n const response = await this.client.tenantQuery<{\n notificationTemplates: { items: NotificationTemplate[]; hasMore: boolean };\n }>(query, { filter, limit: 100, offset: templates.length }, this.context);\n const result = response.notificationTemplates;\n if (!result || !Array.isArray(result.items) || typeof result.hasMore !== 'boolean') {\n throw new APIError('Notification template page was invalid', { operation: 'notificationTemplates' });\n }\n for (const template of result.items) {\n if (!template.id || seen.has(template.id)) {\n throw new APIError('Notification template pagination did not progress', {\n operation: 'notificationTemplates',\n });\n }\n seen.add(template.id);\n templates.push(template);\n }\n if (!result.hasMore) return templates;\n if (!result.items.length) {\n throw new APIError('Notification template pagination did not progress', { operation: 'notificationTemplates' });\n }\n }\n throw new APIError('Notification template pagination exceeded its bounded limit', {\n operation: 'notificationTemplates',\n });\n }\n\n /**\n * Get notification statistics\n */\n public async getStats(filter?: { userId?: string; startDate?: Date; endDate?: Date }): Promise<NotificationStats> {\n const query = `\n query GetNotificationStats($filter: NotificationFilterInput) {\n notificationStats(filter: $filter) {\n total\n pending\n triggered\n scheduled\n cancelled\n sent\n delivered\n failed\n byChannel\n byType\n }\n }\n `;\n\n const variables = {\n filter: filter\n ? {\n userId: filter.userId,\n startDate: filter.startDate?.toISOString(),\n endDate: filter.endDate?.toISOString(),\n }\n : undefined,\n };\n\n const response = await this.client.tenantQuery<{\n notificationStats: NotificationStats;\n }>(query, variables, this.context);\n\n return response.notificationStats;\n }\n\n /**\n * Mark notifications as read\n */\n public async markAsRead(notificationIds: string[]): Promise<boolean> {\n const mutation = `\n mutation MarkNotificationsAsRead($notificationIds: [ID!]!) {\n markNotificationsAsRead(notificationIds: $notificationIds) { success count failedIds }\n }\n `;\n\n const result = await this.client.tenantQuery<{ markNotificationsAsRead: { success: boolean } }>(\n mutation,\n { notificationIds },\n this.context\n );\n\n logger.info('[TenantNotifications] Read request completed', {\n success: result.markNotificationsAsRead.success,\n count: notificationIds.length,\n });\n\n return result.markNotificationsAsRead.success;\n }\n\n /**\n * Mark all notifications as read for the current user\n */\n public async markAllAsRead(): Promise<boolean> {\n const mutation = `\n mutation MarkAllMyNotificationsAsRead {\n markAllMyNotificationsAsRead { success count failedIds }\n }\n `;\n\n const result = await this.client.tenantQuery<{ markAllMyNotificationsAsRead: { success: boolean } }>(\n mutation,\n {},\n this.context\n );\n\n logger.info('[TenantNotifications] Read-all request completed', {\n success: result.markAllMyNotificationsAsRead.success,\n });\n\n return result.markAllMyNotificationsAsRead.success;\n }\n\n /**\n * Delete notifications\n */\n public async deleteNotifications(notificationIds: string[]): Promise<boolean> {\n const mutation = `\n mutation DeleteNotifications($notificationIds: [ID!]!) {\n deleteNotifications(notificationIds: $notificationIds)\n }\n `;\n\n const result = await this.client.tenantQuery<{ deleteNotifications: boolean }>(\n mutation,\n { notificationIds },\n this.context\n );\n\n logger.info('[TenantNotifications] Delete request completed', {\n success: result.deleteNotifications,\n count: notificationIds.length,\n });\n\n return result.deleteNotifications;\n }\n\n /**\n * Delete all read notifications for the current user\n */\n public async deleteAllReadNotifications(): Promise<boolean> {\n const mutation = `\n mutation DeleteMyReadNotifications {\n deleteMyReadNotifications\n }\n `;\n\n const result = await this.client.tenantQuery<{ deleteMyReadNotifications: boolean }>(mutation, {}, this.context);\n\n logger.info('[TenantNotifications] Delete-read request completed', { success: result.deleteMyReadNotifications });\n\n return result.deleteMyReadNotifications;\n }\n\n /**\n * Validate send notification input\n */\n private validateSendInput(input: SendNotificationInput): void {\n if (!Object.values(NotificationChannel).includes(input.channel)) {\n throw new ValidationError('A supported notification channel is required');\n }\n const recipientKeys: Record<NotificationChannel, Array<keyof RecipientInput>> = {\n EMAIL: ['email', 'userId'],\n SMS: ['phoneNumber', 'userId'],\n PUSH: ['pushToken', 'userId'],\n IN_APP: ['userId'],\n WEBHOOK: ['webhookUrl', 'userId'],\n WHATSAPP: ['whatsappNumber', 'phoneNumber', 'userId'],\n TEAMS: ['teamsUserId', 'userId'],\n SLACK: ['slackUserId', 'userId'],\n TELEGRAM: ['userId'],\n DISCORD: ['userId'],\n };\n if (\n !input.recipient ||\n !recipientKeys[input.channel].some((key) => {\n const value = input.recipient[key];\n return typeof value === 'string' && value.trim().length > 0;\n })\n )\n throw new ValidationError('A recipient address or userId appropriate for the channel is required');\n if (typeof input.body !== 'string' || input.body.trim().length === 0) {\n throw new ValidationError('Notification body is required');\n }\n this.validateDates(input);\n }\n\n private validateDates(input: { scheduledFor?: Date; expiresAt?: Date }): void {\n for (const value of [input.scheduledFor, input.expiresAt]) {\n if (value != null && (!(value instanceof Date) || !Number.isFinite(value.getTime()))) {\n throw new ValidationError('Notification dates must be valid Date values');\n }\n }\n if (input.scheduledFor && input.expiresAt && input.expiresAt <= input.scheduledFor) {\n throw new ValidationError('Notification expiry must follow its scheduled delivery');\n }\n }\n}\n","/**\n * Notifications Module\n * Send in-app, email, SMS, and push notifications via workspaces-backend\n */\n\nimport type { BurdenoffGraphQLClient } from '../client/graphql.js';\nimport type { SDKContext } from '../types/index.js';\nimport { ValidationError } from '../types/index.js';\nimport { logger } from '../logger/index.js';\n\nexport enum NotificationType {\n INFO = 'info',\n SUCCESS = 'success',\n WARNING = 'warning',\n ERROR = 'error',\n}\n\nexport enum NotificationChannel {\n EMAIL = 'EMAIL',\n SMS = 'SMS',\n WHATSAPP = 'WHATSAPP',\n PUSH = 'PUSH',\n SLACK = 'SLACK',\n TEAMS = 'TEAMS',\n WEBHOOK = 'WEBHOOK',\n}\n\n// Re-export from tenant-notifications\nexport {\n NotificationChannel as TenantNotificationChannel,\n NotificationType as TenantNotificationType,\n NotificationPriority,\n TenantNotificationsModule,\n} from './tenant-notifications.js';\nexport type {\n SendNotificationInput as TenantSendNotificationInput,\n SendWithTemplateInput as TenantSendWithTemplateInput,\n BatchNotificationInput as TenantBatchNotificationInput,\n} from './tenant-notifications.js';\n\nexport interface SendNotificationOptions {\n /** Notification title */\n title: string;\n /** Notification message */\n message: string;\n /** Notification type */\n type?: NotificationType;\n /** Target user IDs */\n userIds: string[];\n /** Optional redirect URL */\n redirectUrl?: string;\n /** Application name */\n appName?: string;\n /** Send email notification */\n email?: boolean;\n /** Send SMS notification */\n sms?: boolean;\n /** Structured event metadata retained by the notification owner. */\n metadata?: Record<string, unknown>;\n /** Additional application data retained by the notification owner. */\n data?: Record<string, unknown>;\n /** Optional absolute expiration time. */\n expiresAt?: Date;\n}\n\nexport interface NotificationResponse {\n /** Number of successful notifications */\n successCount: number;\n /** Number of failed notifications */\n failureCount: number;\n /** Error messages if any */\n errors: string[];\n /** Created notification IDs */\n notificationIds?: string[];\n}\n\nexport interface GetNotificationsOptions {\n /** User ID to get notifications for */\n userId: string;\n /** Filter by status */\n status?: 'unread' | 'read' | 'all';\n /** Filter by type */\n type?: NotificationType;\n /** Filter by app name */\n appName?: string;\n /** Search term */\n search?: string;\n /** Limit number of results */\n limit?: number;\n /** Offset for pagination */\n offset?: number;\n}\n\nexport interface Notification {\n id: string;\n userId: string;\n title: string;\n message: string;\n type: NotificationType;\n status: 'unread' | 'read';\n redirectUrl?: string;\n appName?: string;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface RecipientInput {\n email?: string;\n locale?: string;\n name?: string;\n phoneNumber?: string;\n pushToken?: string;\n slackUserId?: string;\n teamsUserId?: string;\n timezone?: string;\n userId?: string;\n webhookUrl?: string;\n whatsappNumber?: string;\n}\n\nexport interface SendChannelNotificationOptions {\n /** Primary delivery channel (EMAIL, SMS, WHATSAPP, etc.) */\n platform: NotificationChannel;\n /** Recipient information for primary channel */\n recipient: RecipientInput;\n /** Multiple recipients for bulk delivery */\n recipients?: RecipientInput[];\n /** Notification subject (for EMAIL) */\n subject?: string;\n /** Notification body/message */\n body: string;\n /** HTML body (for EMAIL) */\n htmlBody?: string;\n /** Notification type */\n type?: NotificationType;\n /** Application name */\n appName?: string;\n /** Redirect URL */\n redirectUrl?: string;\n /** Also send as in-app notification */\n includeInApp?: boolean;\n /** User IDs for in-app notifications (required when includeInApp is true) */\n userIds?: string[];\n /** Additional metadata */\n metadata?: Record<string, unknown>;\n /** Track email opens */\n trackOpens?: boolean;\n /** Track link clicks */\n trackClicks?: boolean;\n /** Expiration time */\n expiresAt?: Date;\n /** Specific channel instance ID (overrides platform) */\n channelId?: string;\n}\n\nexport interface SendTemplateNotificationOptions {\n /** Primary delivery channel (EMAIL, SMS, WHATSAPP, etc.) */\n platform: NotificationChannel;\n /** Template slug to use */\n templateSlug: string;\n /** Template variables */\n variables: Record<string, unknown>;\n /** Recipient information for primary channel */\n recipient?: RecipientInput;\n /** Multiple recipients for bulk delivery */\n recipients?: RecipientInput[];\n /** Also send as in-app notification */\n includeInApp?: boolean;\n /** User IDs for in-app notifications (required when includeInApp is true) */\n userIds?: string[];\n /** Application name */\n appName?: string;\n /** Track email opens */\n trackOpens?: boolean;\n /** Track link clicks */\n trackClicks?: boolean;\n /** Expiration time */\n expiresAt?: Date;\n /** Scheduled delivery time */\n scheduledFor?: Date;\n /** Timezone for scheduling */\n timezone?: string;\n /** Specific channel instance ID (overrides platform) */\n channelId?: string;\n}\n\n/**\n * Map the SDK's severity-flavoured `NotificationType` (info/success/warning/error) onto\n * global-notification-svc's delivery-intent `NotificationType`\n * (ALERT | MARKETING | SYSTEM | TRANSACTIONAL).\n *\n * The two enums describe different things and share no values, so an unmapped value would be\n * rejected by the owner. Warnings and errors are alerts; everything else is transactional.\n */\nfunction mapNotificationType(type?: NotificationType): 'ALERT' | 'TRANSACTIONAL' {\n return type === NotificationType.WARNING || type === NotificationType.ERROR ? 'ALERT' : 'TRANSACTIONAL';\n}\n\n/**\n * Choose the delivery channel required by `CreateNotificationInput.channel` (non-nullable).\n *\n * `SendNotificationOptions` expresses channel intent as the legacy `email`/`sms` booleans; the\n * owner expects a single `NotificationChannel`. In-app is the default so a caller that sets\n * neither flag still gets a delivered, visible notification.\n */\nfunction resolveChannel(options: SendNotificationOptions): 'EMAIL' | 'SMS' | 'IN_APP' {\n if (options.email) return 'EMAIL';\n if (options.sms) return 'SMS';\n return 'IN_APP';\n}\n\n/**\n * Notifications Module\n */\nexport class NotificationsModule {\n constructor(\n private client: BurdenoffGraphQLClient,\n private context: SDKContext\n ) {}\n\n /**\n * Send notification to users\n */\n public async send(options: SendNotificationOptions): Promise<NotificationResponse> {\n // Validate inputs\n if (!options.title || options.title.trim().length === 0) {\n throw new ValidationError('Notification title is required');\n }\n\n if (!options.message || options.message.trim().length === 0) {\n throw new ValidationError('Notification message is required');\n }\n\n if (!options.userIds || options.userIds.length === 0) {\n throw new ValidationError('At least one user ID is required');\n }\n if (options.expiresAt && (!(options.expiresAt instanceof Date) || !Number.isFinite(options.expiresAt.getTime()))) {\n throw new ValidationError('Notification expiry must be a valid Date');\n }\n\n logger.info('[Notifications] Sending notification', {\n userCount: options.userIds.length,\n type: options.type || NotificationType.INFO,\n });\n\n // `triggerNotification` both creates AND delivers. `createNotification` only persists —\n // its own schema doc says \"without triggering - use triggerNotification to send\" — so sending\n // through it would silently never deliver.\n const mutation = `\n mutation TriggerNotification($input: TriggerNotificationInput!) {\n triggerNotification(input: $input) {\n id\n status\n }\n }\n `;\n\n // global-notification-svc addresses ONE recipient per notification, so a multi-user send fans\n // out into one mutation per user rather than passing a `userIds` array (which the input does\n // not have). Failures are collected per recipient instead of rejecting the whole batch.\n const channel = resolveChannel(options);\n const notificationIds: string[] = [];\n const errors: string[] = [];\n\n const results = await Promise.allSettled(\n options.userIds.map(async (userId) => {\n const variables = {\n input: {\n notification: {\n recipient: { userId },\n channel,\n type: mapNotificationType(options.type),\n subject: options.title,\n body: options.message,\n metadata: options.metadata,\n data: options.data,\n expiresAt: options.expiresAt?.toISOString(),\n ...(options.redirectUrl ? { redirectUrl: options.redirectUrl } : {}),\n ...(options.appName ? { appName: options.appName } : {}),\n },\n platform: channel,\n // Always leave an in-app trace when the primary channel is external, so the\n // notification is visible in the product even if email/SMS delivery fails.\n includeInApp: channel !== 'IN_APP',\n },\n };\n\n const response = await this.client.tenantQuery<{\n triggerNotification: { id: string; status?: string };\n }>(mutation, variables, this.context);\n\n const id = response.triggerNotification?.id;\n if (!id) {\n throw new Error(`notification service returned no id for user ${userId}`);\n }\n return id;\n })\n );\n\n for (const [index, settled] of results.entries()) {\n if (settled.status === 'fulfilled') {\n notificationIds.push(settled.value);\n } else {\n const reason = settled.reason instanceof Error ? settled.reason.message : String(settled.reason);\n errors.push(`${options.userIds[index] ?? 'unknown user'}: ${reason}`);\n }\n }\n\n const result: NotificationResponse = {\n successCount: notificationIds.length,\n failureCount: errors.length,\n errors,\n notificationIds,\n };\n\n logger.info('[Notifications] Notification sent', {\n successCount: result.successCount,\n failureCount: result.failureCount,\n });\n\n return result;\n }\n\n /**\n * Send notification to a single user (convenience method)\n */\n public async sendToUser(\n userId: string,\n title: string,\n message: string,\n options?: Omit<SendNotificationOptions, 'userIds' | 'title' | 'message'>\n ): Promise<NotificationResponse> {\n return this.send({\n title,\n message,\n userIds: [userId],\n ...options,\n });\n }\n\n /**\n * Get notifications for a user\n */\n public async getNotifications(options: GetNotificationsOptions): Promise<{\n notifications: Notification[];\n total: number;\n unreadCount: number;\n }> {\n logger.debug('[Notifications] Getting notifications', { userId: options.userId });\n\n const query = `\n query GetNotifications(\n $userId: ID!\n $status: NotificationStatus\n $type: NotificationType\n $appName: String\n $search: String\n $limit: Int\n $offset: Int\n ) {\n getNotifications(\n userId: $userId\n status: $status\n type: $type\n appName: $appName\n search: $search\n limit: $limit\n offset: $offset\n ) {\n notifications {\n id\n userId\n title\n message\n type\n status\n redirectUrl\n appName\n createdAt\n updatedAt\n }\n total\n unreadCount\n }\n }\n `;\n\n const variables = {\n userId: options.userId,\n status: options.status,\n type: options.type,\n appName: options.appName,\n search: options.search,\n limit: options.limit || 20,\n offset: options.offset || 0,\n };\n\n const response = await this.client.query<{\n getNotifications: {\n notifications: Notification[];\n total: number;\n unreadCount: number;\n };\n }>(query, variables, this.context);\n\n return response.getNotifications;\n }\n\n /**\n * Mark notification as read\n */\n public async markAsRead(notificationId: string): Promise<boolean> {\n logger.debug('[Notifications] Marking notification as read', { notificationId });\n\n const mutation = `\n mutation MarkNotificationAsRead($notificationId: ID!) {\n markNotificationAsRead(notificationId: $notificationId) {\n id\n status\n }\n }\n `;\n\n await this.client.tenantQuery(mutation, { notificationId }, this.context);\n\n logger.info('[Notifications] Notification marked as read', { notificationId });\n\n return true;\n }\n\n /**\n * Mark multiple notifications as read\n */\n public async markMultipleAsRead(notificationIds: string[]): Promise<number> {\n logger.debug('[Notifications] Marking multiple notifications as read', {\n count: notificationIds.length,\n });\n\n const mutation = `\n mutation MarkNotificationsAsRead($notificationIds: [ID!]!) {\n markNotificationsAsRead(notificationIds: $notificationIds) {\n count\n }\n }\n `;\n\n const response = await this.client.query<{\n markNotificationsAsRead: { count: number };\n }>(mutation, { notificationIds }, this.context);\n\n logger.info('[Notifications] Notifications marked as read', {\n count: response.markNotificationsAsRead.count,\n });\n\n return response.markNotificationsAsRead.count;\n }\n\n /**\n * Mark all notifications as read for the current user\n */\n public async markAllAsRead(): Promise<number> {\n logger.debug('[Notifications] Marking all notifications as read');\n\n const mutation = `\n mutation MarkAllMyNotificationsAsRead {\n markAllMyNotificationsAsRead {\n count\n }\n }\n `;\n\n const response = await this.client.query<{\n markAllMyNotificationsAsRead: { count: number };\n }>(mutation, {}, this.context);\n\n logger.info('[Notifications] All notifications marked as read', {\n count: response.markAllMyNotificationsAsRead.count,\n });\n\n return response.markAllMyNotificationsAsRead.count;\n }\n\n /**\n * Delete notification\n */\n public async deleteNotification(notificationId: string): Promise<boolean> {\n logger.debug('[Notifications] Deleting notification', { notificationId });\n\n const mutation = `\n mutation DeleteNotification($notificationId: ID!) {\n deleteNotification(notificationId: $notificationId) {\n success\n }\n }\n `;\n\n await this.client.tenantQuery(mutation, { notificationId }, this.context);\n\n logger.info('[Notifications] Notification deleted', { notificationId });\n\n return true;\n }\n\n /**\n * Delete multiple notifications\n */\n public async deleteMultiple(notificationIds: string[]): Promise<number> {\n logger.debug('[Notifications] Deleting multiple notifications', {\n count: notificationIds.length,\n });\n\n const mutation = `\n mutation DeleteNotifications($notificationIds: [ID!]!) {\n deleteNotifications(notificationIds: $notificationIds) {\n count\n }\n }\n `;\n\n const response = await this.client.query<{\n deleteNotifications: { count: number };\n }>(mutation, { notificationIds }, this.context);\n\n logger.info('[Notifications] Notifications deleted', {\n count: response.deleteNotifications.count,\n });\n\n return response.deleteNotifications.count;\n }\n\n /**\n * Get unread notification count for a user\n */\n public async getUnreadCount(userId: string): Promise<number> {\n const result = await this.getNotifications({\n userId,\n status: 'unread',\n limit: 0,\n });\n\n return result.unreadCount;\n }\n\n /**\n * Send notification via specific channel (EMAIL, SMS, WHATSAPP, etc.)\n * with optional in-app notification\n */\n public async sendChannelNotification(options: SendChannelNotificationOptions): Promise<NotificationResponse> {\n // Validate inputs\n if (!options.body || options.body.trim().length === 0) {\n throw new ValidationError('Notification body is required');\n }\n\n if (!options.recipient && !options.recipients) {\n throw new ValidationError('At least one recipient is required');\n }\n\n if (options.includeInApp && (!options.userIds || options.userIds.length === 0)) {\n throw new ValidationError('User IDs are required when includeInApp is true');\n }\n\n logger.info('[Notifications] Sending channel notification', {\n platform: options.platform,\n recipientCount: options.recipients ? options.recipients.length : 1,\n includeInApp: options.includeInApp,\n inAppUserCount: options.userIds ? options.userIds.length : 0,\n });\n\n const mutation = `\n mutation TriggerNotification($input: TriggerNotificationInput!) {\n triggerNotification(input: $input) {\n id\n status\n deliveryStatus\n }\n }\n `;\n\n const variables = {\n input: {\n platform: options.platform,\n channelId: options.channelId,\n includeInApp: options.includeInApp || false,\n userIds: options.userIds || [],\n notification: {\n subject: options.subject || '',\n body: options.body,\n htmlBody: options.htmlBody || '',\n channel: options.platform,\n type: options.type || NotificationType.INFO,\n recipient: options.recipient,\n appName: options.appName,\n redirectUrl: options.redirectUrl || '',\n metadata: options.metadata || {},\n trackOpens: options.trackOpens || false,\n trackClicks: options.trackClicks || false,\n expiresAt: options.expiresAt?.toISOString(),\n },\n },\n };\n\n // Handle bulk recipients\n if (options.recipients && options.recipients.length > 1) {\n const results = await Promise.allSettled(\n options.recipients.map((recipient) =>\n this.client.tenantQuery(\n mutation,\n {\n input: {\n ...variables.input,\n notification: {\n ...variables.input.notification,\n recipient,\n },\n },\n },\n this.context\n )\n )\n );\n\n let successCount = 0;\n let failureCount = 0;\n const errors: string[] = [];\n const notificationIds: string[] = [];\n\n results.forEach((result, index) => {\n if (result.status === 'fulfilled') {\n successCount++;\n const response = result.value as { triggerNotification: { id: string } };\n notificationIds.push(response.triggerNotification.id);\n } else {\n failureCount++;\n errors.push(\n `Recipient ${index + 1}: ${result.reason instanceof Error ? result.reason.message : 'Unknown error'}`\n );\n }\n });\n\n const response: NotificationResponse = {\n successCount,\n failureCount,\n errors,\n notificationIds,\n };\n\n logger.info('[Notifications] Channel notification sent (bulk)', {\n successCount,\n failureCount,\n });\n\n return response;\n } else {\n // Single recipient\n try {\n const response = await this.client.query<{\n triggerNotification: { id: string; status: string; deliveryStatus: string };\n }>(mutation, variables, this.context);\n\n const result: NotificationResponse = {\n successCount: 1,\n failureCount: 0,\n errors: [],\n notificationIds: [response.triggerNotification.id],\n };\n\n logger.info('[Notifications] Channel notification sent', {\n notificationId: response.triggerNotification.id,\n status: response.triggerNotification.status,\n });\n\n return result;\n } catch (error) {\n logger.error('[Notifications] Failed to send channel notification', { error });\n\n return {\n successCount: 0,\n failureCount: 1,\n errors: [error instanceof Error ? error.message : 'Unknown error'],\n notificationIds: [],\n };\n }\n }\n }\n\n /**\n * Send notification using a template with optional in-app notification\n */\n public async sendTemplateNotification(options: SendTemplateNotificationOptions): Promise<NotificationResponse> {\n // Validate inputs\n if (!options.templateSlug || options.templateSlug.trim().length === 0) {\n throw new ValidationError('Template slug is required');\n }\n\n if (!options.variables || typeof options.variables !== 'object') {\n throw new ValidationError('Template variables are required');\n }\n\n if (!options.recipient && !options.recipients) {\n throw new ValidationError('At least one recipient is required');\n }\n\n if (options.includeInApp && (!options.userIds || options.userIds.length === 0)) {\n throw new ValidationError('User IDs are required when includeInApp is true');\n }\n\n logger.info('[Notifications] Sending template notification', {\n templateSlug: options.templateSlug,\n platform: options.platform,\n recipientCount: options.recipients ? options.recipients.length : 1,\n includeInApp: options.includeInApp,\n inAppUserCount: options.userIds ? options.userIds.length : 0,\n });\n\n const mutation = `\n mutation TriggerNotificationWithTemplate($input: TriggerNotificationWithTemplateInput!) {\n triggerNotificationWithTemplate(input: $input) {\n totalRequested\n totalTriggered\n totalFailed\n notifications {\n id\n status\n deliveryStatus\n }\n }\n }\n `;\n\n const variables = {\n input: {\n platform: options.platform,\n channelId: options.channelId,\n includeInApp: options.includeInApp || false,\n userIds: options.userIds || [],\n templateSlug: options.templateSlug,\n variables: options.variables,\n recipient: options.recipient,\n recipients: options.recipients,\n trackOpens: options.trackOpens || false,\n trackClicks: options.trackClicks || false,\n expiresAt: options.expiresAt?.toISOString(),\n scheduledFor: options.scheduledFor?.toISOString(),\n timezone: options.timezone,\n },\n };\n\n try {\n const response = await this.client.query<{\n triggerNotificationWithTemplate: {\n totalRequested: number;\n totalTriggered: number;\n totalFailed: number;\n notifications: Array<{ id: string; status: string; deliveryStatus?: string }>;\n };\n }>(mutation, variables, this.context);\n\n const data = response.triggerNotificationWithTemplate;\n\n const result: NotificationResponse = {\n successCount: data.totalTriggered,\n failureCount: data.totalFailed,\n errors: [],\n notificationIds: data.notifications.map((n) => n.id),\n };\n\n logger.info('[Notifications] Template notification sent', {\n templateSlug: options.templateSlug,\n totalTriggered: data.totalTriggered,\n totalFailed: data.totalFailed,\n notificationIds: result.notificationIds,\n });\n\n return result;\n } catch (error) {\n logger.error('[Notifications] Failed to send template notification', { error });\n\n return {\n successCount: 0,\n failureCount: 1,\n errors: [error instanceof Error ? error.message : 'Unknown error'],\n notificationIds: [],\n };\n }\n }\n}\n"],"mappings":";;;;;;;;;;;AAcA,IAAYA,wBAAL;CACL;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;;AACF;AAEA,IAAY,uBAAL;CACL;CACA;CACA;CACA;;AACF;AAEA,IAAYC,qBAAL;CACL;CACA;CACA;CACA;;AACF;;;;;AAsIA,IAAa,4BAAb,MAAuC;CAE3B;CACA;CAFV,YACE,AAAQ,QACR,AAAQ,SACR;EAFQ;EACA;CACP;;;;CAKH,MAAa,KAAK,OAA8B,SAAuC;EACrF,KAAK,kBAAkB,KAAK;EAC5B,MAAM,eAAe,KAAK,wBAAwB,KAAK;EACvD,MAAM,cAAc;GAAE,GAAG,KAAK;GAAS,GAAG;EAAQ;EAElD,IAAI,MAAM,cAAc;GAUtB,MAAM,UAAS,MATQ,KAAK,OAAO,YAGjC;;YAGA,EAAE,OAAO;IAAE;IAAc,cAAc,MAAM,aAAa,YAAY;IAAG,UAAU,MAAM,UAAU;GAAS,EAAE,GAC9G,WACF,EACuB,CAAC;GACxB,IAAI,CAAC,QAAQ,kBAAkB,OAAO,WAAW,WAC/C,MAAM,IAAI,SAAS,gDAAgD,EAAE,WAAW,uBAAuB,CAAC;GAE1G,OAAO,OAAO;EAChB;EAWA,MAAM,UAAS,MATQ,KAAK,OAAO,YAGjC;;UAGA,EAAE,OAAO;GAAE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;GACnB,YAAY,QAAQ;GACpB,YAAY,QAAQ,cAAc;GAClC,aAAa,QAAQ,eAAe;GACpC,WAAW,QAAQ,WAAW,YAAY;GAC1C,cAAc,QAAQ,cAAc,YAAY;GAChD,UAAU,QAAQ;EACpB,EACF;EAEA,IAAI;GAUF,MAAM,QAAO,MATU,KAAK,OAAO,MAOhC,UAAU,WAAW,KAAK,OAAO,EAEf,CAAC;GAEtB,MAAM,SAA+B;IACnC,cAAc,KAAK;IACnB,cAAc,KAAK;IACnB,QAAQ,CAAC;IACT,iBAAiB,KAAK,cAAc,KAAK,MAAM,EAAE,EAAE;GACrD;GAEA,OAAO,KAAK,8CAA8C;IACxD,cAAc,QAAQ;IACtB,gBAAgB,KAAK;IACrB,aAAa,KAAK;IAClB,iBAAiB,OAAO;GAC1B,CAAC;GAED,OAAO;EACT,SAAS,OAAO;GACd,OAAO,MAAM,wDAAwD,EAAE,MAAM,CAAC;GAE9E,OAAO;IACL,cAAc;IACd,cAAc;IACd,QAAQ,CAAC,iBAAiB,QAAQ,MAAM,UAAU,eAAe;IACjE,iBAAiB,CAAC;GACpB;EACF;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"notifications-DY_i37WN.js","names":["NotificationChannel","NotificationType"],"sources":["../src/notifications/tenant-notifications.ts","../src/notifications/index.ts"],"sourcesContent":["/**\n * Tenant-Backend Notifications Module\n * Comprehensive notification system supporting 10+ channels via tenant-backend\n */\n\nimport type { BurdenoffGraphQLClient } from '../client/graphql.js';\nimport type { SDKContext } from '../types/index.js';\nimport { APIError, ValidationError } from '../types/index.js';\nimport { logger } from '../logger/index.js';\n\n// ========================================\n// Enums\n// ========================================\n\nexport enum NotificationChannel {\n EMAIL = 'EMAIL',\n SMS = 'SMS',\n PUSH = 'PUSH',\n IN_APP = 'IN_APP',\n WEBHOOK = 'WEBHOOK',\n WHATSAPP = 'WHATSAPP',\n TEAMS = 'TEAMS',\n SLACK = 'SLACK',\n TELEGRAM = 'TELEGRAM',\n DISCORD = 'DISCORD',\n}\n\nexport enum NotificationPriority {\n LOW = 'LOW',\n MEDIUM = 'MEDIUM',\n HIGH = 'HIGH',\n URGENT = 'URGENT',\n}\n\nexport enum NotificationType {\n TRANSACTIONAL = 'TRANSACTIONAL',\n MARKETING = 'MARKETING',\n SYSTEM = 'SYSTEM',\n ALERT = 'ALERT',\n}\n\n// ========================================\n// Types & Interfaces\n// ========================================\n\nexport interface RecipientInput {\n userId?: string;\n email?: string;\n phoneNumber?: string;\n pushToken?: string;\n whatsappNumber?: string;\n teamsUserId?: string;\n slackUserId?: string;\n webhookUrl?: string;\n name?: string;\n locale?: string;\n timezone?: string;\n}\n\nexport interface SendNotificationInput {\n recipient: RecipientInput;\n channel: NotificationChannel;\n type?: NotificationType;\n priority?: NotificationPriority;\n subject?: string;\n body: string;\n htmlBody?: string;\n data?: Record<string, unknown>;\n metadata?: Record<string, unknown>;\n scheduledFor?: Date;\n expiresAt?: Date;\n trackOpens?: boolean;\n trackClicks?: boolean;\n}\n\nexport interface SendWithTemplateInput {\n templateSlug: string;\n variables: Record<string, unknown>;\n recipient: RecipientInput;\n priority?: NotificationPriority;\n scheduledFor?: Date;\n expiresAt?: Date;\n trackOpens?: boolean;\n trackClicks?: boolean;\n /** Specific channel instance ID from channel service (takes precedence) */\n channelId?: string;\n /** Platform type for auto-failover (EMAIL, SMS, etc.) - used if channelId not provided */\n platform?: NotificationChannel;\n /** Timezone for scheduling */\n timezone?: string;\n}\n\nexport interface BatchNotificationInput {\n notifications: SendNotificationInput[];\n batchSize?: number;\n delayBetweenBatches?: number;\n priority?: NotificationPriority;\n}\n\nexport interface Notification {\n id: string;\n userId: string;\n channel: NotificationChannel;\n type: NotificationType;\n priority: NotificationPriority;\n status: string;\n deliveryStatus?: string;\n title: string;\n message: string;\n htmlMessage?: string;\n subject?: string;\n recipientEmail?: string;\n recipientPhone?: string;\n trackOpens: boolean;\n trackClicks: boolean;\n openedAt?: string;\n clickedAt?: string;\n sentAt?: string;\n deliveredAt?: string;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface NotificationTemplate {\n id: string;\n name: string;\n slug: string;\n description?: string;\n channel: NotificationChannel;\n type: NotificationType;\n locale: string;\n subject?: string;\n bodyTemplate: string;\n htmlTemplate?: string;\n variables: Array<{\n name: string;\n type: string;\n required: boolean;\n defaultValue?: unknown;\n description?: string;\n example?: unknown;\n }>;\n enabled: boolean;\n version: number;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface NotificationStats {\n total: number;\n pending: number;\n /** @deprecated The owner does not publish a queued counter. */\n queued?: number;\n /** @deprecated The owner does not publish a processing counter. */\n processing?: number;\n triggered: number;\n scheduled: number;\n cancelled: number;\n sent: number;\n delivered: number;\n failed: number;\n byChannel: Record<string, number>;\n byType: Record<string, number>;\n}\n\n// ========================================\n// Tenant Notifications Module\n// ========================================\n\n/**\n * Tenant-Backend Notifications Module\n * Provides access to the centralized notification system\n */\nexport class TenantNotificationsModule {\n constructor(\n private client: BurdenoffGraphQLClient,\n private context: SDKContext\n ) {}\n\n /**\n * Send a single notification\n */\n public async send(input: SendNotificationInput, context?: SDKContext): Promise<string> {\n this.validateSendInput(input);\n const notification = this.createNotificationInput(input);\n const callContext = { ...this.context, ...context };\n\n if (input.scheduledFor) {\n const response = await this.client.tenantQuery<{\n scheduleNotification: { notificationId: string; status: string };\n }>(\n `mutation ScheduleTenantNotification($input: ScheduleNotificationInput!) {\n scheduleNotification(input: $input) { notificationId status }\n }`,\n { input: { notification, scheduledFor: input.scheduledFor.toISOString(), timezone: input.recipient.timezone } },\n callContext\n );\n const result = response.scheduleNotification;\n if (!result?.notificationId || result.status !== 'PENDING') {\n throw new APIError('Notification scheduling was not acknowledged', { operation: 'scheduleNotification' });\n }\n return result.notificationId;\n }\n\n const response = await this.client.tenantQuery<{\n triggerNotification: { id: string; status: string; channel: NotificationChannel };\n }>(\n `mutation TriggerTenantNotification($input: TriggerNotificationInput!) {\n triggerNotification(input: $input) { id status channel }\n }`,\n { input: { notification, platform: input.channel, includeInApp: false } },\n callContext\n );\n const result = response.triggerNotification;\n if (\n !result?.id ||\n result.channel !== input.channel ||\n !['TRIGGERED', 'SENT', 'DELIVERED'].includes(result.status)\n ) {\n throw new APIError('Notification trigger was not acknowledged', {\n operation: 'triggerNotification',\n notificationId: result?.id,\n });\n }\n logger.info('[TenantNotifications] Notification accepted', {\n notificationId: result.id,\n channel: result.channel,\n status: result.status,\n });\n return result.id;\n }\n\n /** Owner input deliberately excludes scheduling, which has a separate API. */\n private createNotificationInput(input: SendNotificationInput, priority?: NotificationPriority) {\n return {\n recipient: input.recipient,\n channel: input.channel,\n type: input.type ?? NotificationType.TRANSACTIONAL,\n priority: input.priority ?? priority ?? NotificationPriority.MEDIUM,\n subject: input.subject,\n body: input.body,\n htmlBody: input.htmlBody,\n data: input.data,\n metadata: input.metadata,\n expiresAt: input.expiresAt?.toISOString(),\n trackOpens: input.trackOpens,\n trackClicks: input.trackClicks,\n };\n }\n\n /**\n * Send notification using a template\n */\n public async sendWithTemplate(input: SendWithTemplateInput, context?: SDKContext): Promise<string> {\n // Validate inputs\n if (!input.templateSlug || input.templateSlug.trim().length === 0) {\n throw new ValidationError('Template slug is required');\n }\n\n if (!input.variables || typeof input.variables !== 'object' || Array.isArray(input.variables)) {\n throw new ValidationError('Template variables must be an object');\n }\n\n if (!input.recipient || (!input.recipient.email && !input.recipient.userId)) {\n throw new ValidationError('Recipient email or userId is required');\n }\n\n this.validateDates(input);\n\n logger.info('[TenantNotifications] Sending notification with template', {\n templateSlug: input.templateSlug,\n priority: input.priority || NotificationPriority.MEDIUM,\n });\n\n const mutation = `\n mutation TriggerNotificationWithTemplate($input: TriggerNotificationWithTemplateInput!) {\n triggerNotificationWithTemplate(input: $input) {\n totalRequested\n totalTriggered\n totalFailed\n notifications {\n id\n status\n deliveryStatus\n }\n }\n }\n `;\n\n const variables = {\n input: {\n templateSlug: input.templateSlug,\n variables: input.variables,\n recipient: input.recipient,\n priority: input.priority || NotificationPriority.MEDIUM,\n scheduledFor: input.scheduledFor?.toISOString(),\n expiresAt: input.expiresAt?.toISOString(),\n trackOpens: input.trackOpens,\n trackClicks: input.trackClicks,\n // Platform is required for notification delivery routing\n // If channelId is specified, it takes precedence; otherwise platform determines delivery\n channelId: input.channelId,\n platform: input.platform || NotificationChannel.EMAIL,\n timezone: input.timezone,\n },\n };\n\n const response = await this.client.tenantQuery<{\n triggerNotificationWithTemplate: {\n totalRequested: number;\n totalTriggered: number;\n totalFailed: number;\n notifications: Array<{ id: string; status: string; deliveryStatus?: string }>;\n };\n }>(mutation, variables, { ...this.context, ...context });\n\n const result = response.triggerNotificationWithTemplate;\n const firstNotification = result.notifications[0];\n\n if (result.totalTriggered === 0 || !firstNotification) {\n throw new ValidationError(\n `Notification trigger failed: requested=${result.totalRequested}, triggered=${result.totalTriggered}, failed=${result.totalFailed}`\n );\n }\n\n logger.info('[TenantNotifications] Notification sent with template', {\n notificationId: firstNotification.id,\n status: firstNotification.status,\n totalTriggered: result.totalTriggered,\n totalFailed: result.totalFailed,\n });\n\n return firstNotification.id;\n }\n\n /**\n * Send batch notifications\n */\n public async sendBatch(\n input: BatchNotificationInput,\n context?: SDKContext\n ): Promise<{\n totalRequested: number;\n /** Legacy name for the owner's accepted totalTriggered counter, not final delivery. */\n totalQueued: number;\n totalFailed: number;\n batchId: string;\n }> {\n if (!input.notifications?.length) throw new ValidationError('At least one notification is required');\n for (const notification of input.notifications) this.validateSendInput(notification);\n const schedules = new Set(\n input.notifications.map((notification) => notification.scheduledFor?.toISOString() ?? '')\n );\n if (schedules.size > 1) {\n throw new ValidationError('Batch notifications must share a schedule; use send() for distinct schedules');\n }\n if (input.batchSize !== undefined && (!Number.isInteger(input.batchSize) || input.batchSize <= 0)) {\n throw new ValidationError('Batch size must be a positive integer');\n }\n if (\n input.delayBetweenBatches !== undefined &&\n (!Number.isInteger(input.delayBetweenBatches) || input.delayBetweenBatches < 0)\n ) {\n throw new ValidationError('Batch delay must be a nonnegative integer');\n }\n const response = await this.client.tenantQuery<{\n triggerBatchNotifications: { totalRequested: number; totalQueued: number; totalFailed: number; batchId: string };\n }>(\n `mutation TriggerTenantBatchNotifications($input: TriggerBatchNotificationsInput!) {\n triggerBatchNotifications(input: $input) { totalRequested totalQueued: totalTriggered totalFailed batchId }\n }`,\n {\n input: {\n notifications: input.notifications.map((notification) =>\n this.createNotificationInput(notification, input.priority)\n ),\n priority: input.priority,\n scheduledFor: input.notifications[0]?.scheduledFor?.toISOString(),\n batchSize: input.batchSize,\n delayBetweenBatches: input.delayBetweenBatches,\n },\n },\n { ...this.context, ...context }\n );\n const result = response.triggerBatchNotifications;\n if (!result?.batchId)\n throw new APIError('Notification batch was not acknowledged', { operation: 'triggerBatchNotifications' });\n return result;\n }\n\n /**\n * Get a notification by ID\n */\n public async getNotification(id: string): Promise<Notification | null> {\n const query = `\n query GetNotification($id: ID!) {\n notification(id: $id) {\n id\n userId\n channel\n type\n priority\n status\n deliveryStatus\n title\n message\n htmlMessage\n subject\n recipientEmail\n recipientPhone\n trackOpens\n trackClicks\n openedAt\n clickedAt\n sentAt\n deliveredAt\n createdAt\n updatedAt\n }\n }\n `;\n\n const response = await this.client.tenantQuery<{\n notification: Notification | null;\n }>(query, { id }, this.context);\n\n return response.notification;\n }\n\n /**\n * Get notifications with filters\n */\n public async getNotifications(filter?: {\n userId?: string;\n channel?: NotificationChannel;\n type?: NotificationType;\n status?: string;\n priority?: NotificationPriority;\n startDate?: Date;\n endDate?: Date;\n limit?: number;\n offset?: number;\n }): Promise<Notification[]> {\n const query = `\n query GetNotifications($filter: NotificationFilterInput, $limit: Int, $offset: Int) {\n notifications(filter: $filter, limit: $limit, offset: $offset) {\n items {\n id\n userId\n channel\n type\n priority\n status\n deliveryStatus\n title\n message\n subject\n recipientEmail\n trackOpens\n trackClicks\n openedAt\n clickedAt\n sentAt\n deliveredAt\n createdAt\n updatedAt\n }\n }\n }\n `;\n\n const variables = {\n filter: filter\n ? {\n userId: filter.userId,\n channel: filter.channel,\n type: filter.type,\n status: filter.status,\n priority: filter.priority,\n startDate: filter.startDate?.toISOString(),\n endDate: filter.endDate?.toISOString(),\n }\n : undefined,\n limit: filter?.limit ?? 50,\n offset: filter?.offset ?? 0,\n };\n\n const response = await this.client.tenantQuery<{\n notifications: { items: Notification[] };\n }>(query, variables, this.context);\n\n return response.notifications.items;\n }\n\n /**\n * Get notification template\n */\n public async getTemplate(slug: string, locale?: string): Promise<NotificationTemplate | null> {\n const query = `\n query GetNotificationTemplate($slug: String!, $locale: String) {\n notificationTemplate(slug: $slug, locale: $locale) {\n id\n name\n slug\n description\n channel\n type\n locale\n subject\n bodyTemplate\n htmlTemplate\n variables\n enabled\n version\n createdAt\n updatedAt\n }\n }\n `;\n\n const response = await this.client.tenantQuery<{\n notificationTemplate: NotificationTemplate | null;\n }>(query, { slug, locale }, this.context);\n\n return response.notificationTemplate;\n }\n\n /**\n * Get all notification templates\n */\n public async getTemplates(filter?: {\n channel?: NotificationChannel;\n type?: NotificationType;\n enabled?: boolean;\n }): Promise<NotificationTemplate[]> {\n const query = `query GetNotificationTemplates($filter: TemplateFilterInput, $limit: Int!, $offset: Int!) {\n notificationTemplates(filter: $filter, limit: $limit, offset: $offset) {\n items { id name slug description channel type locale subject bodyTemplate htmlTemplate variables enabled version createdAt updatedAt }\n hasMore\n }\n }`;\n const templates: NotificationTemplate[] = [];\n const seen = new Set<string>();\n for (let page = 0; page < 100; page++) {\n const response = await this.client.tenantQuery<{\n notificationTemplates: { items: NotificationTemplate[]; hasMore: boolean };\n }>(query, { filter, limit: 100, offset: templates.length }, this.context);\n const result = response.notificationTemplates;\n if (!result || !Array.isArray(result.items) || typeof result.hasMore !== 'boolean') {\n throw new APIError('Notification template page was invalid', { operation: 'notificationTemplates' });\n }\n for (const template of result.items) {\n if (!template.id || seen.has(template.id)) {\n throw new APIError('Notification template pagination did not progress', {\n operation: 'notificationTemplates',\n });\n }\n seen.add(template.id);\n templates.push(template);\n }\n if (!result.hasMore) return templates;\n if (!result.items.length) {\n throw new APIError('Notification template pagination did not progress', { operation: 'notificationTemplates' });\n }\n }\n throw new APIError('Notification template pagination exceeded its bounded limit', {\n operation: 'notificationTemplates',\n });\n }\n\n /**\n * Get notification statistics\n */\n public async getStats(filter?: { userId?: string; startDate?: Date; endDate?: Date }): Promise<NotificationStats> {\n const query = `\n query GetNotificationStats($filter: NotificationFilterInput) {\n notificationStats(filter: $filter) {\n total\n pending\n triggered\n scheduled\n cancelled\n sent\n delivered\n failed\n byChannel\n byType\n }\n }\n `;\n\n const variables = {\n filter: filter\n ? {\n userId: filter.userId,\n startDate: filter.startDate?.toISOString(),\n endDate: filter.endDate?.toISOString(),\n }\n : undefined,\n };\n\n const response = await this.client.tenantQuery<{\n notificationStats: NotificationStats;\n }>(query, variables, this.context);\n\n return response.notificationStats;\n }\n\n /**\n * Mark notifications as read\n */\n public async markAsRead(notificationIds: string[]): Promise<boolean> {\n const mutation = `\n mutation MarkNotificationsAsRead($notificationIds: [ID!]!) {\n markNotificationsAsRead(notificationIds: $notificationIds) { success count failedIds }\n }\n `;\n\n const result = await this.client.tenantQuery<{ markNotificationsAsRead: { success: boolean } }>(\n mutation,\n { notificationIds },\n this.context\n );\n\n logger.info('[TenantNotifications] Read request completed', {\n success: result.markNotificationsAsRead.success,\n count: notificationIds.length,\n });\n\n return result.markNotificationsAsRead.success;\n }\n\n /**\n * Mark all notifications as read for the current user\n */\n public async markAllAsRead(): Promise<boolean> {\n const mutation = `\n mutation MarkAllMyNotificationsAsRead {\n markAllMyNotificationsAsRead { success count failedIds }\n }\n `;\n\n const result = await this.client.tenantQuery<{ markAllMyNotificationsAsRead: { success: boolean } }>(\n mutation,\n {},\n this.context\n );\n\n logger.info('[TenantNotifications] Read-all request completed', {\n success: result.markAllMyNotificationsAsRead.success,\n });\n\n return result.markAllMyNotificationsAsRead.success;\n }\n\n /**\n * Delete notifications\n */\n public async deleteNotifications(notificationIds: string[]): Promise<boolean> {\n const mutation = `\n mutation DeleteNotifications($notificationIds: [ID!]!) {\n deleteNotifications(notificationIds: $notificationIds)\n }\n `;\n\n const result = await this.client.tenantQuery<{ deleteNotifications: boolean }>(\n mutation,\n { notificationIds },\n this.context\n );\n\n logger.info('[TenantNotifications] Delete request completed', {\n success: result.deleteNotifications,\n count: notificationIds.length,\n });\n\n return result.deleteNotifications;\n }\n\n /**\n * Delete all read notifications for the current user\n */\n public async deleteAllReadNotifications(): Promise<boolean> {\n const mutation = `\n mutation DeleteMyReadNotifications {\n deleteMyReadNotifications\n }\n `;\n\n const result = await this.client.tenantQuery<{ deleteMyReadNotifications: boolean }>(mutation, {}, this.context);\n\n logger.info('[TenantNotifications] Delete-read request completed', { success: result.deleteMyReadNotifications });\n\n return result.deleteMyReadNotifications;\n }\n\n /**\n * Validate send notification input\n */\n private validateSendInput(input: SendNotificationInput): void {\n if (!Object.values(NotificationChannel).includes(input.channel)) {\n throw new ValidationError('A supported notification channel is required');\n }\n const recipientKeys: Record<NotificationChannel, Array<keyof RecipientInput>> = {\n EMAIL: ['email', 'userId'],\n SMS: ['phoneNumber', 'userId'],\n PUSH: ['pushToken', 'userId'],\n IN_APP: ['userId'],\n WEBHOOK: ['webhookUrl', 'userId'],\n WHATSAPP: ['whatsappNumber', 'phoneNumber', 'userId'],\n TEAMS: ['teamsUserId', 'userId'],\n SLACK: ['slackUserId', 'userId'],\n TELEGRAM: ['userId'],\n DISCORD: ['userId'],\n };\n if (\n !input.recipient ||\n !recipientKeys[input.channel].some((key) => {\n const value = input.recipient[key];\n return typeof value === 'string' && value.trim().length > 0;\n })\n )\n throw new ValidationError('A recipient address or userId appropriate for the channel is required');\n if (typeof input.body !== 'string' || input.body.trim().length === 0) {\n throw new ValidationError('Notification body is required');\n }\n this.validateDates(input);\n }\n\n private validateDates(input: { scheduledFor?: Date; expiresAt?: Date }): void {\n for (const value of [input.scheduledFor, input.expiresAt]) {\n if (value != null && (!(value instanceof Date) || !Number.isFinite(value.getTime()))) {\n throw new ValidationError('Notification dates must be valid Date values');\n }\n }\n if (input.scheduledFor && input.expiresAt && input.expiresAt <= input.scheduledFor) {\n throw new ValidationError('Notification expiry must follow its scheduled delivery');\n }\n }\n}\n","/**\n * Notifications Module\n * Send in-app, email, SMS, and push notifications via workspaces-backend\n */\n\nimport type { BurdenoffGraphQLClient } from '../client/graphql.js';\nimport type { SDKContext } from '../types/index.js';\nimport { ValidationError } from '../types/index.js';\nimport { logger } from '../logger/index.js';\n\nexport enum NotificationType {\n INFO = 'info',\n SUCCESS = 'success',\n WARNING = 'warning',\n ERROR = 'error',\n}\n\nexport enum NotificationChannel {\n EMAIL = 'EMAIL',\n SMS = 'SMS',\n WHATSAPP = 'WHATSAPP',\n PUSH = 'PUSH',\n SLACK = 'SLACK',\n TEAMS = 'TEAMS',\n WEBHOOK = 'WEBHOOK',\n}\n\n// Re-export from tenant-notifications\nexport {\n NotificationChannel as TenantNotificationChannel,\n NotificationType as TenantNotificationType,\n NotificationPriority,\n TenantNotificationsModule,\n} from './tenant-notifications.js';\nexport type {\n SendNotificationInput as TenantSendNotificationInput,\n SendWithTemplateInput as TenantSendWithTemplateInput,\n BatchNotificationInput as TenantBatchNotificationInput,\n} from './tenant-notifications.js';\n\nexport interface SendNotificationOptions {\n /** Notification title */\n title: string;\n /** Notification message */\n message: string;\n /** Notification type */\n type?: NotificationType;\n /** Target user IDs */\n userIds: string[];\n /** Optional redirect URL */\n redirectUrl?: string;\n /** Application name */\n appName?: string;\n /** Send email notification */\n email?: boolean;\n /** Send SMS notification */\n sms?: boolean;\n /** Structured event metadata retained by the notification owner. */\n metadata?: Record<string, unknown>;\n /** Additional application data retained by the notification owner. */\n data?: Record<string, unknown>;\n /** Optional absolute expiration time. */\n expiresAt?: Date;\n}\n\nexport interface NotificationResponse {\n /** Number of successful notifications */\n successCount: number;\n /** Number of failed notifications */\n failureCount: number;\n /** Error messages if any */\n errors: string[];\n /** Created notification IDs */\n notificationIds?: string[];\n}\n\nexport interface GetNotificationsOptions {\n /** User ID to get notifications for */\n userId: string;\n /** Filter by status */\n status?: 'unread' | 'read' | 'all';\n /** Filter by type */\n type?: NotificationType;\n /** Filter by app name */\n appName?: string;\n /** Search term */\n search?: string;\n /** Limit number of results */\n limit?: number;\n /** Offset for pagination */\n offset?: number;\n}\n\nexport interface Notification {\n id: string;\n userId: string;\n title: string;\n message: string;\n type: NotificationType;\n status: 'unread' | 'read';\n redirectUrl?: string;\n appName?: string;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface RecipientInput {\n email?: string;\n locale?: string;\n name?: string;\n phoneNumber?: string;\n pushToken?: string;\n slackUserId?: string;\n teamsUserId?: string;\n timezone?: string;\n userId?: string;\n webhookUrl?: string;\n whatsappNumber?: string;\n}\n\nexport interface SendChannelNotificationOptions {\n /** Primary delivery channel (EMAIL, SMS, WHATSAPP, etc.) */\n platform: NotificationChannel;\n /** Recipient information for primary channel */\n recipient: RecipientInput;\n /** Multiple recipients for bulk delivery */\n recipients?: RecipientInput[];\n /** Notification subject (for EMAIL) */\n subject?: string;\n /** Notification body/message */\n body: string;\n /** HTML body (for EMAIL) */\n htmlBody?: string;\n /** Notification type */\n type?: NotificationType;\n /** Application name */\n appName?: string;\n /** Redirect URL */\n redirectUrl?: string;\n /** Also send as in-app notification */\n includeInApp?: boolean;\n /** User IDs for in-app notifications (required when includeInApp is true) */\n userIds?: string[];\n /** Additional metadata */\n metadata?: Record<string, unknown>;\n /** Track email opens */\n trackOpens?: boolean;\n /** Track link clicks */\n trackClicks?: boolean;\n /** Expiration time */\n expiresAt?: Date;\n /** Specific channel instance ID (overrides platform) */\n channelId?: string;\n}\n\nexport interface SendTemplateNotificationOptions {\n /** Primary delivery channel (EMAIL, SMS, WHATSAPP, etc.) */\n platform: NotificationChannel;\n /** Template slug to use */\n templateSlug: string;\n /** Template variables */\n variables: Record<string, unknown>;\n /** Recipient information for primary channel */\n recipient?: RecipientInput;\n /** Multiple recipients for bulk delivery */\n recipients?: RecipientInput[];\n /** Also send as in-app notification */\n includeInApp?: boolean;\n /** User IDs for in-app notifications (required when includeInApp is true) */\n userIds?: string[];\n /** Application name */\n appName?: string;\n /** Track email opens */\n trackOpens?: boolean;\n /** Track link clicks */\n trackClicks?: boolean;\n /** Expiration time */\n expiresAt?: Date;\n /** Scheduled delivery time */\n scheduledFor?: Date;\n /** Timezone for scheduling */\n timezone?: string;\n /** Specific channel instance ID (overrides platform) */\n channelId?: string;\n}\n\n/**\n * Map the SDK's severity-flavoured `NotificationType` (info/success/warning/error) onto\n * global-notification-svc's delivery-intent `NotificationType`\n * (ALERT | MARKETING | SYSTEM | TRANSACTIONAL).\n *\n * The two enums describe different things and share no values, so an unmapped value would be\n * rejected by the owner. Warnings and errors are alerts; everything else is transactional.\n */\nfunction mapNotificationType(type?: NotificationType): 'ALERT' | 'TRANSACTIONAL' {\n return type === NotificationType.WARNING || type === NotificationType.ERROR ? 'ALERT' : 'TRANSACTIONAL';\n}\n\n/**\n * Choose the delivery channel required by `CreateNotificationInput.channel` (non-nullable).\n *\n * `SendNotificationOptions` expresses channel intent as the legacy `email`/`sms` booleans; the\n * owner expects a single `NotificationChannel`. In-app is the default so a caller that sets\n * neither flag still gets a delivered, visible notification.\n */\nfunction resolveChannel(options: SendNotificationOptions): 'EMAIL' | 'SMS' | 'IN_APP' {\n if (options.email) return 'EMAIL';\n if (options.sms) return 'SMS';\n return 'IN_APP';\n}\n\n/**\n * Notifications Module\n */\nexport class NotificationsModule {\n constructor(\n private client: BurdenoffGraphQLClient,\n private context: SDKContext\n ) {}\n\n /**\n * Send notification to users\n */\n public async send(options: SendNotificationOptions): Promise<NotificationResponse> {\n // Validate inputs\n if (!options.title || options.title.trim().length === 0) {\n throw new ValidationError('Notification title is required');\n }\n\n if (!options.message || options.message.trim().length === 0) {\n throw new ValidationError('Notification message is required');\n }\n\n if (!options.userIds || options.userIds.length === 0) {\n throw new ValidationError('At least one user ID is required');\n }\n if (options.expiresAt && (!(options.expiresAt instanceof Date) || !Number.isFinite(options.expiresAt.getTime()))) {\n throw new ValidationError('Notification expiry must be a valid Date');\n }\n\n logger.info('[Notifications] Sending notification', {\n userCount: options.userIds.length,\n type: options.type || NotificationType.INFO,\n });\n\n // `triggerNotification` both creates AND delivers. `createNotification` only persists —\n // its own schema doc says \"without triggering - use triggerNotification to send\" — so sending\n // through it would silently never deliver.\n const mutation = `\n mutation TriggerNotification($input: TriggerNotificationInput!) {\n triggerNotification(input: $input) {\n id\n status\n }\n }\n `;\n\n // global-notification-svc addresses ONE recipient per notification, so a multi-user send fans\n // out into one mutation per user rather than passing a `userIds` array (which the input does\n // not have). Failures are collected per recipient instead of rejecting the whole batch.\n const channel = resolveChannel(options);\n const notificationIds: string[] = [];\n const errors: string[] = [];\n\n const results = await Promise.allSettled(\n options.userIds.map(async (userId) => {\n const variables = {\n input: {\n notification: {\n recipient: { userId },\n channel,\n type: mapNotificationType(options.type),\n subject: options.title,\n body: options.message,\n metadata: options.metadata,\n data: options.data,\n expiresAt: options.expiresAt?.toISOString(),\n ...(options.redirectUrl ? { redirectUrl: options.redirectUrl } : {}),\n ...(options.appName ? { appName: options.appName } : {}),\n },\n platform: channel,\n // Always leave an in-app trace when the primary channel is external, so the\n // notification is visible in the product even if email/SMS delivery fails.\n includeInApp: channel !== 'IN_APP',\n },\n };\n\n const response = await this.client.tenantQuery<{\n triggerNotification: { id: string; status?: string };\n }>(mutation, variables, this.context);\n\n const id = response.triggerNotification?.id;\n if (!id) {\n throw new Error(`notification service returned no id for user ${userId}`);\n }\n return id;\n })\n );\n\n for (const [index, settled] of results.entries()) {\n if (settled.status === 'fulfilled') {\n notificationIds.push(settled.value);\n } else {\n const reason = settled.reason instanceof Error ? settled.reason.message : String(settled.reason);\n errors.push(`${options.userIds[index] ?? 'unknown user'}: ${reason}`);\n }\n }\n\n const result: NotificationResponse = {\n successCount: notificationIds.length,\n failureCount: errors.length,\n errors,\n notificationIds,\n };\n\n logger.info('[Notifications] Notification sent', {\n successCount: result.successCount,\n failureCount: result.failureCount,\n });\n\n return result;\n }\n\n /**\n * Send notification to a single user (convenience method)\n */\n public async sendToUser(\n userId: string,\n title: string,\n message: string,\n options?: Omit<SendNotificationOptions, 'userIds' | 'title' | 'message'>\n ): Promise<NotificationResponse> {\n return this.send({\n title,\n message,\n userIds: [userId],\n ...options,\n });\n }\n\n /**\n * Get notifications for a user\n */\n public async getNotifications(options: GetNotificationsOptions): Promise<{\n notifications: Notification[];\n total: number;\n unreadCount: number;\n }> {\n logger.debug('[Notifications] Getting notifications', { userId: options.userId });\n\n const query = `\n query GetNotifications(\n $userId: ID!\n $status: NotificationStatus\n $type: NotificationType\n $appName: String\n $search: String\n $limit: Int\n $offset: Int\n ) {\n getNotifications(\n userId: $userId\n status: $status\n type: $type\n appName: $appName\n search: $search\n limit: $limit\n offset: $offset\n ) {\n notifications {\n id\n userId\n title\n message\n type\n status\n redirectUrl\n appName\n createdAt\n updatedAt\n }\n total\n unreadCount\n }\n }\n `;\n\n const variables = {\n userId: options.userId,\n status: options.status,\n type: options.type,\n appName: options.appName,\n search: options.search,\n limit: options.limit || 20,\n offset: options.offset || 0,\n };\n\n const response = await this.client.query<{\n getNotifications: {\n notifications: Notification[];\n total: number;\n unreadCount: number;\n };\n }>(query, variables, this.context);\n\n return response.getNotifications;\n }\n\n /**\n * Mark notification as read\n */\n public async markAsRead(notificationId: string): Promise<boolean> {\n logger.debug('[Notifications] Marking notification as read', { notificationId });\n\n const mutation = `\n mutation MarkNotificationAsRead($notificationId: ID!) {\n markNotificationAsRead(notificationId: $notificationId) {\n id\n status\n }\n }\n `;\n\n await this.client.tenantQuery(mutation, { notificationId }, this.context);\n\n logger.info('[Notifications] Notification marked as read', { notificationId });\n\n return true;\n }\n\n /**\n * Mark multiple notifications as read\n */\n public async markMultipleAsRead(notificationIds: string[]): Promise<number> {\n logger.debug('[Notifications] Marking multiple notifications as read', {\n count: notificationIds.length,\n });\n\n const mutation = `\n mutation MarkNotificationsAsRead($notificationIds: [ID!]!) {\n markNotificationsAsRead(notificationIds: $notificationIds) {\n count\n }\n }\n `;\n\n const response = await this.client.query<{\n markNotificationsAsRead: { count: number };\n }>(mutation, { notificationIds }, this.context);\n\n logger.info('[Notifications] Notifications marked as read', {\n count: response.markNotificationsAsRead.count,\n });\n\n return response.markNotificationsAsRead.count;\n }\n\n /**\n * Mark all notifications as read for the current user\n */\n public async markAllAsRead(): Promise<number> {\n logger.debug('[Notifications] Marking all notifications as read');\n\n const mutation = `\n mutation MarkAllMyNotificationsAsRead {\n markAllMyNotificationsAsRead {\n count\n }\n }\n `;\n\n const response = await this.client.query<{\n markAllMyNotificationsAsRead: { count: number };\n }>(mutation, {}, this.context);\n\n logger.info('[Notifications] All notifications marked as read', {\n count: response.markAllMyNotificationsAsRead.count,\n });\n\n return response.markAllMyNotificationsAsRead.count;\n }\n\n /**\n * Delete notification\n */\n public async deleteNotification(notificationId: string): Promise<boolean> {\n logger.debug('[Notifications] Deleting notification', { notificationId });\n\n const mutation = `\n mutation DeleteNotification($notificationId: ID!) {\n deleteNotification(notificationId: $notificationId) {\n success\n }\n }\n `;\n\n await this.client.tenantQuery(mutation, { notificationId }, this.context);\n\n logger.info('[Notifications] Notification deleted', { notificationId });\n\n return true;\n }\n\n /**\n * Delete multiple notifications\n */\n public async deleteMultiple(notificationIds: string[]): Promise<number> {\n logger.debug('[Notifications] Deleting multiple notifications', {\n count: notificationIds.length,\n });\n\n const mutation = `\n mutation DeleteNotifications($notificationIds: [ID!]!) {\n deleteNotifications(notificationIds: $notificationIds) {\n count\n }\n }\n `;\n\n const response = await this.client.query<{\n deleteNotifications: { count: number };\n }>(mutation, { notificationIds }, this.context);\n\n logger.info('[Notifications] Notifications deleted', {\n count: response.deleteNotifications.count,\n });\n\n return response.deleteNotifications.count;\n }\n\n /**\n * Get unread notification count for a user\n */\n public async getUnreadCount(userId: string): Promise<number> {\n const result = await this.getNotifications({\n userId,\n status: 'unread',\n limit: 0,\n });\n\n return result.unreadCount;\n }\n\n /**\n * Send notification via specific channel (EMAIL, SMS, WHATSAPP, etc.)\n * with optional in-app notification\n */\n public async sendChannelNotification(options: SendChannelNotificationOptions): Promise<NotificationResponse> {\n // Validate inputs\n if (!options.body || options.body.trim().length === 0) {\n throw new ValidationError('Notification body is required');\n }\n\n if (!options.recipient && !options.recipients) {\n throw new ValidationError('At least one recipient is required');\n }\n\n if (options.includeInApp && (!options.userIds || options.userIds.length === 0)) {\n throw new ValidationError('User IDs are required when includeInApp is true');\n }\n\n logger.info('[Notifications] Sending channel notification', {\n platform: options.platform,\n recipientCount: options.recipients ? options.recipients.length : 1,\n includeInApp: options.includeInApp,\n inAppUserCount: options.userIds ? options.userIds.length : 0,\n });\n\n const mutation = `\n mutation TriggerNotification($input: TriggerNotificationInput!) {\n triggerNotification(input: $input) {\n id\n status\n deliveryStatus\n }\n }\n `;\n\n const variables = {\n input: {\n platform: options.platform,\n channelId: options.channelId,\n includeInApp: options.includeInApp || false,\n userIds: options.userIds || [],\n notification: {\n subject: options.subject || '',\n body: options.body,\n htmlBody: options.htmlBody || '',\n channel: options.platform,\n type: options.type || NotificationType.INFO,\n recipient: options.recipient,\n appName: options.appName,\n redirectUrl: options.redirectUrl || '',\n metadata: options.metadata || {},\n trackOpens: options.trackOpens || false,\n trackClicks: options.trackClicks || false,\n expiresAt: options.expiresAt?.toISOString(),\n },\n },\n };\n\n // Handle bulk recipients\n if (options.recipients && options.recipients.length > 1) {\n const results = await Promise.allSettled(\n options.recipients.map((recipient) =>\n this.client.tenantQuery(\n mutation,\n {\n input: {\n ...variables.input,\n notification: {\n ...variables.input.notification,\n recipient,\n },\n },\n },\n this.context\n )\n )\n );\n\n let successCount = 0;\n let failureCount = 0;\n const errors: string[] = [];\n const notificationIds: string[] = [];\n\n results.forEach((result, index) => {\n if (result.status === 'fulfilled') {\n successCount++;\n const response = result.value as { triggerNotification: { id: string } };\n notificationIds.push(response.triggerNotification.id);\n } else {\n failureCount++;\n errors.push(\n `Recipient ${index + 1}: ${result.reason instanceof Error ? result.reason.message : 'Unknown error'}`\n );\n }\n });\n\n const response: NotificationResponse = {\n successCount,\n failureCount,\n errors,\n notificationIds,\n };\n\n logger.info('[Notifications] Channel notification sent (bulk)', {\n successCount,\n failureCount,\n });\n\n return response;\n } else {\n // Single recipient\n try {\n const response = await this.client.query<{\n triggerNotification: { id: string; status: string; deliveryStatus: string };\n }>(mutation, variables, this.context);\n\n const result: NotificationResponse = {\n successCount: 1,\n failureCount: 0,\n errors: [],\n notificationIds: [response.triggerNotification.id],\n };\n\n logger.info('[Notifications] Channel notification sent', {\n notificationId: response.triggerNotification.id,\n status: response.triggerNotification.status,\n });\n\n return result;\n } catch (error) {\n logger.error('[Notifications] Failed to send channel notification', { error });\n\n return {\n successCount: 0,\n failureCount: 1,\n errors: [error instanceof Error ? error.message : 'Unknown error'],\n notificationIds: [],\n };\n }\n }\n }\n\n /**\n * Send notification using a template with optional in-app notification\n */\n public async sendTemplateNotification(options: SendTemplateNotificationOptions): Promise<NotificationResponse> {\n // Validate inputs\n if (!options.templateSlug || options.templateSlug.trim().length === 0) {\n throw new ValidationError('Template slug is required');\n }\n\n if (!options.variables || typeof options.variables !== 'object') {\n throw new ValidationError('Template variables are required');\n }\n\n if (!options.recipient && !options.recipients) {\n throw new ValidationError('At least one recipient is required');\n }\n\n if (options.includeInApp && (!options.userIds || options.userIds.length === 0)) {\n throw new ValidationError('User IDs are required when includeInApp is true');\n }\n\n logger.info('[Notifications] Sending template notification', {\n templateSlug: options.templateSlug,\n platform: options.platform,\n recipientCount: options.recipients ? options.recipients.length : 1,\n includeInApp: options.includeInApp,\n inAppUserCount: options.userIds ? options.userIds.length : 0,\n });\n\n const mutation = `\n mutation TriggerNotificationWithTemplate($input: TriggerNotificationWithTemplateInput!) {\n triggerNotificationWithTemplate(input: $input) {\n totalRequested\n totalTriggered\n totalFailed\n notifications {\n id\n status\n deliveryStatus\n }\n }\n }\n `;\n\n const variables = {\n input: {\n platform: options.platform,\n channelId: options.channelId,\n includeInApp: options.includeInApp || false,\n userIds: options.userIds || [],\n templateSlug: options.templateSlug,\n variables: options.variables,\n recipient: options.recipient,\n recipients: options.recipients,\n trackOpens: options.trackOpens || false,\n trackClicks: options.trackClicks || false,\n expiresAt: options.expiresAt?.toISOString(),\n scheduledFor: options.scheduledFor?.toISOString(),\n timezone: options.timezone,\n },\n };\n\n try {\n const response = await this.client.query<{\n triggerNotificationWithTemplate: {\n totalRequested: number;\n totalTriggered: number;\n totalFailed: number;\n notifications: Array<{ id: string; status: string; deliveryStatus?: string }>;\n };\n }>(mutation, variables, this.context);\n\n const data = response.triggerNotificationWithTemplate;\n\n const result: NotificationResponse = {\n successCount: data.totalTriggered,\n failureCount: data.totalFailed,\n errors: [],\n notificationIds: data.notifications.map((n) => n.id),\n };\n\n logger.info('[Notifications] Template notification sent', {\n templateSlug: options.templateSlug,\n totalTriggered: data.totalTriggered,\n totalFailed: data.totalFailed,\n notificationIds: result.notificationIds,\n });\n\n return result;\n } catch (error) {\n logger.error('[Notifications] Failed to send template notification', { error });\n\n return {\n successCount: 0,\n failureCount: 1,\n errors: [error instanceof Error ? error.message : 'Unknown error'],\n notificationIds: [],\n };\n }\n }\n}\n"],"mappings":";;;;;;;;;;;AAcA,IAAYA,wBAAL;CACL;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;;AACF;AAEA,IAAY,uBAAL;CACL;CACA;CACA;CACA;;AACF;AAEA,IAAYC,qBAAL;CACL;CACA;CACA;CACA;;AACF;;;;;AAsIA,IAAa,4BAAb,MAAuC;CAE3B;CACA;CAFV,YACE,AAAQ,QACR,AAAQ,SACR;EAFQ;EACA;CACP;;;;CAKH,MAAa,KAAK,OAA8B,SAAuC;EACrF,KAAK,kBAAkB,KAAK;EAC5B,MAAM,eAAe,KAAK,wBAAwB,KAAK;EACvD,MAAM,cAAc;GAAE,GAAG,KAAK;GAAS,GAAG;EAAQ;EAElD,IAAI,MAAM,cAAc;GAUtB,MAAM,UAAS,MATQ,KAAK,OAAO,YAGjC;;YAGA,EAAE,OAAO;IAAE;IAAc,cAAc,MAAM,a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BAAgB,QAAQ,UAAU,QAAQ,QAAQ,SAAS;EAC7D,CAAC;EAED,MAAM,WAAW;;;;;;;;;;;;;;EAejB,MAAM,YAAY,EAChB,OAAO;GACL,UAAU,QAAQ;GAClB,WAAW,QAAQ;GACnB,cAAc,QAAQ,gBAAgB;GACtC,SAAS,QAAQ,WAAW,CAAC;GAC7B,cAAc,QAAQ;GACtB,WAAW,QAAQ;GACnB,WAAW,QAAQ;GACnB,YAAY,QAAQ;GACpB,YAAY,QAAQ,cAAc;GAClC,aAAa,QAAQ,eAAe;GACpC,WAAW,QAAQ,WAAW,YAAY;GAC1C,cAAc,QAAQ,cAAc,YAAY;GAChD,UAAU,QAAQ;EACpB,EACF;EAEA,IAAI;GAUF,MAAM,QAAO,MATU,KAAK,OAAO,MAOhC,UAAU,WAAW,KAAK,OAAO,EAEf,CAAC;GAEtB,MAAM,SAA+B;IACnC,cAAc,KAAK;IACnB,cAAc,KAAK;IACnB,QAAQ,CAAC;IACT,iBAAiB,KAAK,cAAc,KAAK,MAAM,EAAE,EAAE;GACrD;GAEA,OAAO,KAAK,8CAA8C;IACxD,cAAc,QAAQ;IACtB,gBAAgB,KAAK;IACrB,aAAa,KAAK;IAClB,iBAAiB,OAAO;GAC1B,CAAC;GAED,OAAO;EACT,SAAS,OAAO;GACd,OAAO,MAAM,wDAAwD,EAAE,MAAM,CAAC;GAE9E,OAAO;IACL,cAAc;IACd,cAAc;IACd,QAAQ,CAAC,iBAAiB,QAAQ,MAAM,UAAU,eAAe;IACjE,iBAAiB,CAAC;GACpB;EACF;CACF;AACF"}
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import { t as BurdenoffGraphQLClient } from "../graphql-CUDyhibV.js";
|
|
2
|
+
import { p as SDKContext } from "../index-CTTwo9av.js";
|
|
3
|
+
export declare enum PaymentStatus {
|
|
4
|
+
PENDING = "pending",
|
|
5
|
+
PROCESSING = "processing",
|
|
6
|
+
SUCCEEDED = "succeeded",
|
|
7
|
+
FAILED = "failed",
|
|
8
|
+
CANCELLED = "cancelled",
|
|
9
|
+
REFUNDED = "refunded"
|
|
10
|
+
}
|
|
11
|
+
export declare enum PaymentMethod {
|
|
12
|
+
CREDIT_CARD = "credit_card",
|
|
13
|
+
DEBIT_CARD = "debit_card",
|
|
14
|
+
BANK_TRANSFER = "bank_transfer",
|
|
15
|
+
UPI = "upi",
|
|
16
|
+
WALLET = "wallet",
|
|
17
|
+
PAYPAL = "paypal",
|
|
18
|
+
STRIPE = "stripe"
|
|
19
|
+
}
|
|
20
|
+
export declare enum SubscriptionStatus {
|
|
21
|
+
ACTIVE = "active",
|
|
22
|
+
INACTIVE = "inactive",
|
|
23
|
+
CANCELLED = "cancelled",
|
|
24
|
+
EXPIRED = "expired",
|
|
25
|
+
PAST_DUE = "past_due",
|
|
26
|
+
TRIALING = "trialing"
|
|
27
|
+
}
|
|
28
|
+
export interface CreatePaymentOptions {
|
|
29
|
+
amount: number;
|
|
30
|
+
currency: string;
|
|
31
|
+
paymentMethod: PaymentMethod;
|
|
32
|
+
customerId: string;
|
|
33
|
+
description?: string;
|
|
34
|
+
metadata?: Record<string, unknown>;
|
|
35
|
+
workspaceId?: string;
|
|
36
|
+
organizationId?: string;
|
|
37
|
+
}
|
|
38
|
+
export interface Payment {
|
|
39
|
+
id: string;
|
|
40
|
+
amount: number;
|
|
41
|
+
currency: string;
|
|
42
|
+
status: PaymentStatus;
|
|
43
|
+
paymentMethod: PaymentMethod;
|
|
44
|
+
customerId: string;
|
|
45
|
+
description?: string;
|
|
46
|
+
metadata?: Record<string, unknown>;
|
|
47
|
+
workspaceId?: string;
|
|
48
|
+
organizationId?: string;
|
|
49
|
+
transactionId?: string;
|
|
50
|
+
failureReason?: string;
|
|
51
|
+
createdAt: string;
|
|
52
|
+
updatedAt: string;
|
|
53
|
+
}
|
|
54
|
+
export interface CreateSubscriptionOptions {
|
|
55
|
+
customerId: string;
|
|
56
|
+
planId: string;
|
|
57
|
+
paymentMethod: PaymentMethod;
|
|
58
|
+
trialDays?: number;
|
|
59
|
+
metadata?: Record<string, unknown>;
|
|
60
|
+
workspaceId?: string;
|
|
61
|
+
organizationId?: string;
|
|
62
|
+
}
|
|
63
|
+
export interface Subscription {
|
|
64
|
+
id: string;
|
|
65
|
+
customerId: string;
|
|
66
|
+
planId: string;
|
|
67
|
+
status: SubscriptionStatus;
|
|
68
|
+
currentPeriodStart: string;
|
|
69
|
+
currentPeriodEnd: string;
|
|
70
|
+
trialEnd?: string;
|
|
71
|
+
cancelledAt?: string;
|
|
72
|
+
endedAt?: string;
|
|
73
|
+
metadata?: Record<string, unknown>;
|
|
74
|
+
workspaceId?: string;
|
|
75
|
+
organizationId?: string;
|
|
76
|
+
createdAt: string;
|
|
77
|
+
updatedAt: string;
|
|
78
|
+
}
|
|
79
|
+
export interface Plan {
|
|
80
|
+
id: string;
|
|
81
|
+
name: string;
|
|
82
|
+
description?: string;
|
|
83
|
+
amount: number;
|
|
84
|
+
currency: string;
|
|
85
|
+
interval: 'day' | 'week' | 'month' | 'year';
|
|
86
|
+
intervalCount: number;
|
|
87
|
+
features?: string[];
|
|
88
|
+
metadata?: Record<string, unknown>;
|
|
89
|
+
active: boolean;
|
|
90
|
+
createdAt: string;
|
|
91
|
+
}
|
|
92
|
+
export interface GetPaymentsOptions {
|
|
93
|
+
customerId?: string;
|
|
94
|
+
status?: PaymentStatus;
|
|
95
|
+
workspaceId?: string;
|
|
96
|
+
organizationId?: string;
|
|
97
|
+
startDate?: string;
|
|
98
|
+
endDate?: string;
|
|
99
|
+
limit?: number;
|
|
100
|
+
offset?: number;
|
|
101
|
+
}
|
|
102
|
+
export declare class PaymentsModule {
|
|
103
|
+
private client;
|
|
104
|
+
private context;
|
|
105
|
+
constructor(client: BurdenoffGraphQLClient, context: SDKContext);
|
|
106
|
+
createPayment(options: CreatePaymentOptions): Promise<Payment>;
|
|
107
|
+
getPayment(paymentId: string): Promise<Payment>;
|
|
108
|
+
getPayments(options: GetPaymentsOptions): Promise<{
|
|
109
|
+
payments: Payment[];
|
|
110
|
+
total: number;
|
|
111
|
+
}>;
|
|
112
|
+
refundPayment(paymentId: string, amount?: number, reason?: string): Promise<Payment>;
|
|
113
|
+
verifyPayment(paymentId: string, verificationData: Record<string, unknown>): Promise<{
|
|
114
|
+
verified: boolean;
|
|
115
|
+
status: PaymentStatus;
|
|
116
|
+
}>;
|
|
117
|
+
createSubscription(options: CreateSubscriptionOptions): Promise<Subscription>;
|
|
118
|
+
getSubscription(subscriptionId: string): Promise<Subscription>;
|
|
119
|
+
cancelSubscription(subscriptionId: string, cancelAtPeriodEnd?: boolean): Promise<Subscription>;
|
|
120
|
+
getCustomerSubscriptions(customerId: string): Promise<Subscription[]>;
|
|
121
|
+
getPlans(activeOnly?: boolean): Promise<Plan[]>;
|
|
122
|
+
createPaymentIntent(options: {
|
|
123
|
+
amount: number;
|
|
124
|
+
currency: string;
|
|
125
|
+
customerId: string;
|
|
126
|
+
paymentMethod?: PaymentMethod;
|
|
127
|
+
metadata?: Record<string, unknown>;
|
|
128
|
+
}): Promise<{
|
|
129
|
+
clientSecret: string;
|
|
130
|
+
paymentIntentId: string;
|
|
131
|
+
}>;
|
|
132
|
+
getPaymentStats(options?: {
|
|
133
|
+
startDate?: string;
|
|
134
|
+
endDate?: string;
|
|
135
|
+
workspaceId?: string;
|
|
136
|
+
}): Promise<{
|
|
137
|
+
totalRevenue: number;
|
|
138
|
+
totalPayments: number;
|
|
139
|
+
successfulPayments: number;
|
|
140
|
+
failedPayments: number;
|
|
141
|
+
refundedAmount: number;
|
|
142
|
+
averagePaymentAmount: number;
|
|
143
|
+
}>;
|
|
144
|
+
}
|