@burdenoff/be-sdk 2026.512.99 → 2026.512.100
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/EventQueueFactory-36WGFZ5V.js +8 -0
- package/dist/{EventQueueFactory-6NMSGECR.js.map → EventQueueFactory-36WGFZ5V.js.map} +1 -1
- package/dist/auth/index.d.ts +2 -2
- package/dist/auth/index.js +2 -2
- package/dist/cache/index.js +1 -1
- package/dist/{chunk-FEPHVLZ5.js → chunk-4B43DZIS.js} +3 -3
- package/dist/{chunk-FEPHVLZ5.js.map → chunk-4B43DZIS.js.map} +1 -1
- package/dist/{chunk-NKA7EWZC.js → chunk-4XGGWW36.js} +3 -18
- package/dist/chunk-4XGGWW36.js.map +1 -0
- package/dist/{chunk-2SD5L2F2.js → chunk-536VI7HQ.js} +3 -3
- package/dist/{chunk-2SD5L2F2.js.map → chunk-536VI7HQ.js.map} +1 -1
- package/dist/{chunk-JG2FTZPI.js → chunk-5CAA3JST.js} +3 -3
- package/dist/{chunk-JG2FTZPI.js.map → chunk-5CAA3JST.js.map} +1 -1
- package/dist/{chunk-M5IMU3US.js → chunk-BWSB5HJE.js} +5 -5
- package/dist/{chunk-M5IMU3US.js.map → chunk-BWSB5HJE.js.map} +1 -1
- package/dist/{chunk-OVSYMNCI.js → chunk-COSUYUCB.js} +45 -12
- package/dist/chunk-COSUYUCB.js.map +1 -0
- package/dist/{chunk-J26YGR2U.js → chunk-ER77ZA7C.js} +3 -3
- package/dist/{chunk-J26YGR2U.js.map → chunk-ER77ZA7C.js.map} +1 -1
- package/dist/{chunk-NUWVGPWO.js → chunk-FNZEQOJY.js} +3 -3
- package/dist/{chunk-NUWVGPWO.js.map → chunk-FNZEQOJY.js.map} +1 -1
- package/dist/{chunk-XC2YD6CF.js → chunk-I43B35CP.js} +3 -3
- package/dist/{chunk-XC2YD6CF.js.map → chunk-I43B35CP.js.map} +1 -1
- package/dist/{chunk-ELLX3K54.js → chunk-MLFKAPWK.js} +3 -3
- package/dist/{chunk-ELLX3K54.js.map → chunk-MLFKAPWK.js.map} +1 -1
- package/dist/{chunk-IPYA5X67.js → chunk-MLW2HPS5.js} +2 -2
- package/dist/{chunk-IPYA5X67.js.map → chunk-MLW2HPS5.js.map} +1 -1
- package/dist/{chunk-MNCGUYLJ.js → chunk-NUZZRJNN.js} +6 -3
- package/dist/chunk-NUZZRJNN.js.map +1 -0
- package/dist/{chunk-NIEEQWFB.js → chunk-QQQP5ITO.js} +12 -6
- package/dist/chunk-QQQP5ITO.js.map +1 -0
- package/dist/{chunk-3O2RQOPV.js → chunk-R7Y5I4NN.js} +12 -4
- package/dist/chunk-R7Y5I4NN.js.map +1 -0
- package/dist/{chunk-SAG6ZYWQ.js → chunk-RTQIRGVB.js} +2 -2
- package/dist/{chunk-SAG6ZYWQ.js.map → chunk-RTQIRGVB.js.map} +1 -1
- package/dist/{chunk-YN6NTFJK.js → chunk-VGMFFO6N.js} +5 -5
- package/dist/{chunk-YN6NTFJK.js.map → chunk-VGMFFO6N.js.map} +1 -1
- package/dist/{chunk-L7ZMN2FJ.js → chunk-VOFKF27Q.js} +2 -2
- package/dist/chunk-VOFKF27Q.js.map +1 -0
- package/dist/{chunk-SAK2JCA7.js → chunk-WBWM7UY7.js} +3 -3
- package/dist/{chunk-SAK2JCA7.js.map → chunk-WBWM7UY7.js.map} +1 -1
- package/dist/{chunk-F5XEAGHQ.js → chunk-ZUCYUSLC.js} +4 -4
- package/dist/{chunk-F5XEAGHQ.js.map → chunk-ZUCYUSLC.js.map} +1 -1
- package/dist/config-7U7J3QXQ.js +4 -0
- package/dist/{config-UKE2E3BW.js.map → config-7U7J3QXQ.js.map} +1 -1
- package/dist/database/index.js +2 -2
- package/dist/event-queue/index.d.ts +3 -3
- package/dist/event-queue/index.js +5 -5
- package/dist/export/index.js +3 -3
- package/dist/gateway/index.js +2 -2
- package/dist/gateway/security/index.js +1 -1
- package/dist/graph/index.d.ts +3 -3
- package/dist/graph/index.js +7 -7
- package/dist/graphql/index.d.ts +1 -1
- package/dist/graphql/index.js +2 -2
- package/dist/{graphql-BAVrUgBF.d.ts → graphql-0_hoaeUf.d.ts} +1 -1
- package/dist/{index-Cq_xNjcv.d.ts → index-BF2uh_h9.d.ts} +4 -2
- package/dist/{index-CHbVw5M7.d.ts → index-CSPbpywb.d.ts} +2 -0
- package/dist/{index-KVWGHMbS.d.ts → index-DJq060D-.d.ts} +3 -3
- package/dist/{index-CrQgidpx.d.ts → index-DYEts1R8.d.ts} +1 -1
- package/dist/{index-BS2idbnr.d.ts → index-DZO2nvC9.d.ts} +2 -2
- package/dist/{index-B18rrFru.d.ts → index-HkD7NBED.d.ts} +2 -0
- package/dist/{index-DoK0bjhH.d.ts → index-TKcu5LDR.d.ts} +1 -1
- package/dist/{index-DOcBnmMe.d.ts → index-XY9x2I6b.d.ts} +2 -0
- package/dist/{index-CyVEg86m.d.ts → index-zzKCairW.d.ts} +2 -2
- package/dist/index.d.ts +15 -15
- package/dist/index.js +28 -26
- package/dist/index.js.map +1 -1
- package/dist/init/index.d.ts +1 -1
- package/dist/init/index.js +6 -6
- package/dist/instrumentation/index.d.ts +3 -3
- package/dist/logger/index.d.ts +2 -2
- package/dist/notifications/index.d.ts +3 -3
- package/dist/notifications/index.js +2 -2
- package/dist/prisma/index.js +5 -5
- package/dist/rbac/index.d.ts +2 -2
- package/dist/rbac/index.js +2 -2
- package/dist/telemetry/index.d.ts +4 -4
- package/dist/tracker/index.d.ts +4 -4
- package/dist/tracker/index.js +4 -4
- package/package.json +1 -1
- package/dist/EventQueueFactory-6NMSGECR.js +0 -8
- package/dist/chunk-3O2RQOPV.js.map +0 -1
- package/dist/chunk-L7ZMN2FJ.js.map +0 -1
- package/dist/chunk-MNCGUYLJ.js.map +0 -1
- package/dist/chunk-NIEEQWFB.js.map +0 -1
- package/dist/chunk-NKA7EWZC.js.map +0 -1
- package/dist/chunk-OVSYMNCI.js.map +0 -1
- package/dist/config-UKE2E3BW.js +0 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/export/index.ts","../src/export/base-exporter.ts","../src/export/pagination.ts","../src/export/csv.ts","../src/export/gateway-client.ts"],"names":["BaseModuleExporter","moduleKey","displayName","description","defaultExcludeFields","supportedProducts","modelName","filterFields","entity","excludeFields","fieldsToExclude","length","filtered","record","key","value","Object","entries","includes","filterFieldsMany","entities","map","paginate","queryFn","page","pageSize","skip","take","items","total","data","hasMore","nextCursor","String","undefined","fetchAll","fetchBatch","batchSize","allItems","cursor","batch","push","lastItem","id","transformForExport","validateOptions","options","validFormats","format","Error","join","getSupportedFormats","getMetadata","supportedFormats","PaginationService","params","start","end","paginatedItems","slice","totalCount","pageInfo","hasNextPage","hasPreviousPage","startCursor","endCursor","Math","min","calculatePagination","totalPages","ceil","startIndex","endIndex","currentPage","paginatedQuery","fetchFn","limit","initialCursor","totalYielded","item","collectPaginatedQuery","createPrismaFetchFn","_batchSize","calculateOffset","max","parseCursor","decoded","Buffer","from","toString","JSON","parse","createCursor","stringify","FORMULA_PREFIX_RE","sanitizeCSVCell","test","convertToCSV","delimiter","includeHeaders","flattenFields","maxFlattenDepth","flattenObject","obj","prefix","depth","result","newKey","Date","toISOString","Array","isArray","assign","flattenedRecords","allKeys","Set","keys","add","headers","sort","a","b","localeCompare","escapeCSV","sanitizedValue","replace","lines","row","header","parseCSV","csv","hasHeaders","split","filter","line","trim","parseLine","values","current","inQuotes","i","char","nextChar","dataLines","firstLine","firstRow","_","forEach","csvToJSON","pretty","parseOptions","getCSVHeaders","collectKeys","fullKey","estimateCSVSize","sampleSize","sample","sampleCSV","averageRowSize","headerSize","CREATE_EXPORT_JOB_MUTATION","triggerExportJob","serviceName","layer","actorId","actorType","workspaceId","name","entityTypes","includeMetadata","dateRangeStart","dateRangeEnd","client","GatewayClient","input","response","internalQuery","query","variables","job","createExportJob"],"mappings":";;;;AAAA,IAAA,cAAA,GAAA;;;;;;;;;;;;;ACoCO,IAAeA,qBAAf,MAAe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A,EAAA,MAAMa,GAAAA,GAAMJ,SAASjJ,IAAAA,EAAMsJ,eAAAA;AAC3B,EAAA,IAAI,CAACD,GAAAA,EAAK;AACR,IAAA,MAAM,IAAIlI,MAAM,qCAAA,CAAA;AAClB,EAAA;AACA,EAAA,OAAOkI,GAAAA;AACT;AA1CsBlB,MAAAA,CAAAA,gBAAAA,EAAAA,kBAAAA,CAAAA","file":"chunk-NUWVGPWO.js","sourcesContent":["/**\n * Export Module\n *\n * Provides common utilities for data export operations across all Burdenoff microservices.\n * Includes pagination services, base exporter classes, CSV utilities, and type definitions.\n *\n * @module export\n *\n * @example\n * ```typescript\n * // Import from the export module\n * import {\n * BaseModuleExporter,\n * PaginationService,\n * convertToCSV,\n * } from '@burdenoff/be-sdk/export';\n *\n * // Create a custom exporter\n * class UserExporter extends BaseModuleExporter<User> {\n * moduleKey = 'users';\n * displayName = 'Users';\n *\n * async export(options: ExportOptions): Promise<ExportResult> {\n * const data = await this.fetchAll(\n * (cursor) => db.user.findMany({\n * where: cursor ? { id: { gt: cursor } } : {},\n * take: 100,\n * })\n * );\n *\n * const csv = convertToCSV(data);\n * return { data, format: 'csv' };\n * }\n * }\n *\n * // Use pagination utilities\n * const result = PaginationService.paginate(items, { page: 1, pageSize: 20 });\n * ```\n */\n\n// ============================================================================\n// Type Exports\n// ============================================================================\n\nexport type {\n // Export format types\n ExportFormat,\n ExportFormatEnum,\n\n // Configuration types\n ExportConfig,\n ExportOptions,\n\n // Job types\n ExportJobStatus,\n ExportJob,\n ExportProgress,\n ExportResult,\n\n // Fetch types\n ExportFetchOptions,\n ExportFetchResult,\n\n // Pagination types\n PaginationParams,\n PaginatedResult,\n PaginatedQueryOptions,\n PaginateResult,\n PaginateQueryFn,\n\n // Module interface\n ExportableModule,\n\n // CSV types\n CSVConversionOptions,\n} from './types.js';\n\n// ============================================================================\n// Class Exports\n// ============================================================================\n\nexport { BaseModuleExporter } from './base-exporter.js';\nexport { PaginationService } from './pagination.js';\n\n// ============================================================================\n// Function Exports\n// ============================================================================\n\nexport { convertToCSV, parseCSV, csvToJSON, getCSVHeaders, estimateCSVSize } from './csv.js';\n\n// ============================================================================\n// Gateway Helper Exports\n// ============================================================================\n\nexport { triggerExportJob } from './gateway-client.js';\nexport type { TriggerExportJobParams, ExportJobResult, ExportActorType, ExportFormatGql } from './gateway-client.js';\n","/**\n * Base Module Exporter\n *\n * Abstract base class for module exporters across all Burdenoff microservices.\n * Provides common functionality for exporting data from different modules.\n *\n * @module export/base-exporter\n *\n * @example\n * ```typescript\n * import { BaseModuleExporter } from '@burdenoff/be-sdk/export';\n *\n * class UserExporter extends BaseModuleExporter<User> {\n * moduleKey = 'users';\n * displayName = 'Users';\n * description = 'Export user data';\n *\n * async export(options: ExportOptions): Promise<ExportResult> {\n * // Implementation\n * }\n * }\n * ```\n */\n\nimport type { ExportOptions, ExportResult, PaginateQueryFn, PaginateResult } from './types.js';\n\n/**\n * Abstract base class for module exporters\n *\n * Provides common functionality that all module exporters can inherit:\n * - Field filtering\n * - Pagination helpers\n * - Module metadata\n *\n * @typeParam T - The type of entity this exporter handles\n */\nexport abstract class BaseModuleExporter<T = unknown> {\n /** Unique key identifying this module (e.g., 'users', 'tags', 'orders') */\n moduleKey?: string;\n\n /** Human-readable display name for the module */\n displayName?: string;\n\n /** Description of what this module exports */\n description?: string;\n\n /** Default fields to exclude from export (e.g., sensitive data) */\n defaultExcludeFields?: string[];\n\n /** List of product IDs this exporter supports */\n supportedProducts?: string[];\n\n /** Model name for database operations */\n protected modelName?: string;\n\n /**\n * Export data from this module\n *\n * Subclasses should implement this method to perform the actual export.\n * The method is optional to allow for gradual implementation.\n *\n * @param options - Export options including format, filters, and pagination\n * @returns Export result with data or download URL\n */\n export?(options: ExportOptions): Promise<ExportResult>;\n\n /**\n * Filter fields from an entity based on exclude list\n *\n * Use this to remove sensitive or unnecessary fields from exported data.\n *\n * @param entity - Entity to filter\n * @param excludeFields - Fields to exclude (uses defaultExcludeFields if not provided)\n * @returns Filtered entity as a plain object\n *\n * @example\n * ```typescript\n * const user = { id: '1', name: 'John', password: 'secret', ssn: '123' };\n * const filtered = this.filterFields(user, ['password', 'ssn']);\n * // Result: { id: '1', name: 'John' }\n * ```\n */\n protected filterFields(entity: T | Record<string, unknown>, excludeFields?: string[]): Record<string, unknown> {\n const fieldsToExclude = excludeFields || this.defaultExcludeFields || [];\n\n if (fieldsToExclude.length === 0) {\n return entity as Record<string, unknown>;\n }\n\n const filtered: Record<string, unknown> = {};\n const record = entity as Record<string, unknown>;\n\n for (const [key, value] of Object.entries(record)) {\n if (!fieldsToExclude.includes(key)) {\n filtered[key] = value;\n }\n }\n\n return filtered;\n }\n\n /**\n * Filter multiple entities\n *\n * @param entities - Array of entities to filter\n * @param excludeFields - Fields to exclude\n * @returns Array of filtered entities\n */\n protected filterFieldsMany(\n entities: (T | Record<string, unknown>)[],\n excludeFields?: string[]\n ): Record<string, unknown>[] {\n return entities.map((entity) => this.filterFields(entity, excludeFields));\n }\n\n /**\n * Paginate helper for database queries\n *\n * Use this to implement paginated data fetching in your export method.\n *\n * @param queryFn - Function that executes the paginated query\n * @param page - Page number (1-indexed)\n * @param pageSize - Number of items per page\n * @returns Paginated result with data and metadata\n *\n * @example\n * ```typescript\n * const result = await this.paginate(\n * async ({ skip, take }) => {\n * const items = await db.user.findMany({ skip, take });\n * const total = await db.user.count();\n * return { items, total };\n * },\n * 1,\n * 100\n * );\n * ```\n */\n protected async paginate(\n queryFn: PaginateQueryFn<T>,\n page: number = 1,\n pageSize: number = 100\n ): Promise<PaginateResult<T>> {\n const skip = (page - 1) * pageSize;\n const take = pageSize;\n\n const { items, total } = await queryFn({ skip, take });\n\n return {\n data: items,\n total,\n hasMore: skip + items.length < total,\n nextCursor: items.length > 0 && skip + items.length < total ? String(page + 1) : undefined,\n };\n }\n\n /**\n * Fetch all data using cursor-based pagination\n *\n * Use this for exporting large datasets efficiently.\n *\n * @param fetchBatch - Function to fetch a batch of data\n * @param batchSize - Number of items per batch\n * @returns All fetched items\n *\n * @example\n * ```typescript\n * const allUsers = await this.fetchAll(\n * async (cursor) => db.user.findMany({\n * where: cursor ? { id: { gt: cursor } } : undefined,\n * orderBy: { id: 'asc' },\n * take: 100,\n * }),\n * 100\n * );\n * ```\n */\n protected async fetchAll(\n fetchBatch: (cursor?: string) => Promise<(T & { id: string })[]>,\n batchSize: number = 100\n ): Promise<T[]> {\n const allItems: T[] = [];\n let cursor: string | undefined;\n\n while (true) {\n const batch = await fetchBatch(cursor);\n\n if (batch.length === 0) {\n break;\n }\n\n allItems.push(...batch);\n\n // Get cursor from last item\n const lastItem = batch[batch.length - 1];\n if (lastItem) {\n cursor = lastItem.id;\n }\n\n // If we got fewer items than batch size, we're done\n if (batch.length < batchSize) {\n break;\n }\n }\n\n return allItems;\n }\n\n /**\n * Transform entity for export\n *\n * Override this method to customize how entities are transformed before export.\n * Default implementation returns the entity as-is after field filtering.\n *\n * @param entity - Entity to transform\n * @param excludeFields - Fields to exclude\n * @returns Transformed entity\n */\n protected transformForExport(entity: T, excludeFields?: string[]): Record<string, unknown> {\n return this.filterFields(entity, excludeFields);\n }\n\n /**\n * Validate export options\n *\n * Override this to add custom validation for export options.\n *\n * @param options - Export options to validate\n * @throws Error if options are invalid\n */\n protected validateOptions(options: ExportOptions): void {\n const validFormats = ['csv', 'json', 'xlsx'];\n if (!validFormats.includes(options.format)) {\n throw new Error(`Invalid export format: ${options.format}. Valid formats: ${validFormats.join(', ')}`);\n }\n }\n\n /**\n * Get supported export formats\n *\n * @returns Array of supported format strings\n */\n getSupportedFormats(): string[] {\n return ['csv', 'json', 'xlsx'];\n }\n\n /**\n * Get module metadata\n *\n * @returns Module metadata object\n */\n getMetadata(): {\n moduleKey?: string;\n displayName?: string;\n description?: string;\n supportedProducts?: string[];\n supportedFormats: string[];\n } {\n return {\n moduleKey: this.moduleKey,\n displayName: this.displayName,\n description: this.description,\n supportedProducts: this.supportedProducts,\n supportedFormats: this.getSupportedFormats(),\n };\n }\n}\n","/**\n * Pagination Service\n *\n * Provides pagination utilities for export operations across all Burdenoff microservices.\n * Supports both offset-based and cursor-based pagination strategies.\n *\n * @module export/pagination\n *\n * @example\n * ```typescript\n * import { PaginationService } from '@burdenoff/be-sdk/export';\n *\n * // Offset-based pagination\n * const result = PaginationService.paginate(items, { page: 2, pageSize: 20 });\n *\n * // Cursor-based pagination with async generator\n * for await (const item of PaginationService.paginatedQuery(fetchFn, { limit: 100 })) {\n * console.log(item);\n * }\n * ```\n */\n\nimport type { PaginatedQueryOptions, PaginatedResult, PaginationParams } from './types.js';\n\n/**\n * Service providing pagination utilities for export and data fetching operations\n */\nexport class PaginationService {\n /**\n * Paginate an array of items using offset-based pagination\n *\n * @param items - Array of items to paginate\n * @param params - Pagination parameters\n * @returns Paginated result with items and metadata\n *\n * @example\n * ```typescript\n * const allUsers = await db.user.findMany();\n * const page = PaginationService.paginate(allUsers, { page: 1, pageSize: 10 });\n * console.log(page.items); // First 10 users\n * console.log(page.pageInfo.hasNextPage); // true if more pages exist\n * ```\n */\n static paginate<T>(items: T[], params: PaginationParams): PaginatedResult<T> {\n const page = params.page ?? 1;\n const pageSize = params.pageSize ?? 20;\n const start = (page - 1) * pageSize;\n const end = start + pageSize;\n\n const paginatedItems = items.slice(start, end);\n\n return {\n items: paginatedItems,\n totalCount: items.length,\n pageInfo: {\n hasNextPage: end < items.length,\n hasPreviousPage: page > 1,\n startCursor: paginatedItems.length > 0 ? String(start) : undefined,\n endCursor: paginatedItems.length > 0 ? String(Math.min(end, items.length) - 1) : undefined,\n },\n };\n }\n\n /**\n * Calculate pagination metadata without slicing data\n *\n * @param totalCount - Total number of items\n * @param page - Current page number (1-indexed)\n * @param pageSize - Items per page\n * @returns Pagination metadata\n *\n * @example\n * ```typescript\n * const meta = PaginationService.calculatePagination(150, 3, 20);\n * // meta.hasNextPage = true (page 4 exists)\n * // meta.hasPreviousPage = true (page 2 exists)\n * // meta.totalPages = 8\n * ```\n */\n static calculatePagination(\n totalCount: number,\n page: number,\n pageSize: number\n ): {\n hasNextPage: boolean;\n hasPreviousPage: boolean;\n totalPages: number;\n currentPage: number;\n pageSize: number;\n startIndex: number;\n endIndex: number;\n } {\n const totalPages = Math.ceil(totalCount / pageSize);\n const startIndex = (page - 1) * pageSize;\n const endIndex = Math.min(startIndex + pageSize - 1, totalCount - 1);\n\n return {\n hasNextPage: page < totalPages,\n hasPreviousPage: page > 1,\n totalPages,\n currentPage: page,\n pageSize,\n startIndex,\n endIndex,\n };\n }\n\n /**\n * Async generator for paginated database queries using cursor-based pagination\n *\n * This is ideal for processing large datasets without loading everything into memory.\n * The generator yields items one at a time, fetching new batches as needed.\n *\n * @param fetchFn - Function to fetch data given a cursor\n * @param options - Pagination options\n * @returns Async generator of items\n *\n * @example\n * ```typescript\n * // Define fetch function that queries the database\n * const fetchUsers = async (cursor?: string) => {\n * return db.user.findMany({\n * where: cursor ? { id: { gt: cursor } } : undefined,\n * orderBy: { id: 'asc' },\n * take: 100,\n * });\n * };\n *\n * // Process all users without loading all into memory\n * for await (const user of PaginationService.paginatedQuery(fetchUsers)) {\n * await processUser(user);\n * }\n * ```\n */\n static async *paginatedQuery<T extends { id: string }>(\n fetchFn: (cursor?: string) => Promise<T[]>,\n options: PaginatedQueryOptions = {}\n ): AsyncGenerator<T, void, unknown> {\n const { limit, initialCursor } = options;\n let cursor = initialCursor;\n let hasMore = true;\n let totalYielded = 0;\n\n while (hasMore) {\n const items = await fetchFn(cursor);\n\n if (items.length === 0) {\n break;\n }\n\n for (const item of items) {\n yield item;\n totalYielded++;\n\n if (limit && totalYielded >= limit) {\n return;\n }\n }\n\n // Get next cursor from last item\n const lastItem = items[items.length - 1];\n if (lastItem) {\n cursor = lastItem.id;\n }\n\n // If we got fewer items than expected batch size, we're done\n // Note: This assumes fetchFn respects a consistent batch size internally\n hasMore = items.length > 0;\n }\n }\n\n /**\n * Collect all items from a paginated query into an array\n *\n * @param fetchFn - Function to fetch data given a cursor\n * @param options - Pagination options\n * @returns Array of all items\n *\n * @example\n * ```typescript\n * const allUsers = await PaginationService.collectPaginatedQuery(fetchUsers, { limit: 1000 });\n * ```\n */\n static async collectPaginatedQuery<T extends { id: string }>(\n fetchFn: (cursor?: string) => Promise<T[]>,\n options: PaginatedQueryOptions = {}\n ): Promise<T[]> {\n const items: T[] = [];\n\n for await (const item of PaginationService.paginatedQuery(fetchFn, options)) {\n items.push(item);\n }\n\n return items;\n }\n\n /**\n * Create a cursor-based paginated fetch function from a Prisma-style query\n *\n * @param queryFn - Prisma-style query function\n * @param batchSize - Number of items to fetch per batch\n * @returns Fetch function compatible with paginatedQuery\n *\n * @example\n * ```typescript\n * const fetchFn = PaginationService.createPrismaFetchFn(\n * (cursor) => db.user.findMany({\n * where: { isActive: true, ...(cursor ? { id: { gt: cursor } } : {}) },\n * orderBy: { id: 'asc' },\n * take: 100,\n * }),\n * 100\n * );\n *\n * for await (const user of PaginationService.paginatedQuery(fetchFn)) {\n * console.log(user);\n * }\n * ```\n */\n static createPrismaFetchFn<T extends { id: string }>(\n queryFn: (cursor?: string) => Promise<T[]>,\n _batchSize: number = 100\n ): (cursor?: string) => Promise<T[]> {\n return queryFn;\n }\n\n /**\n * Calculate offset for skip-based pagination\n *\n * @param page - Page number (1-indexed)\n * @param pageSize - Items per page\n * @returns Offset value for skip\n */\n static calculateOffset(page: number, pageSize: number): number {\n return (Math.max(1, page) - 1) * pageSize;\n }\n\n /**\n * Parse cursor string to extract pagination state\n *\n * @param cursor - Base64-encoded cursor string\n * @returns Decoded cursor data or null if invalid\n */\n static parseCursor<T = Record<string, unknown>>(cursor: string): T | null {\n try {\n const decoded = Buffer.from(cursor, 'base64').toString('utf-8');\n return JSON.parse(decoded) as T;\n } catch {\n return null;\n }\n }\n\n /**\n * Create cursor string from pagination state\n *\n * @param data - Data to encode in cursor\n * @returns Base64-encoded cursor string\n */\n static createCursor(data: Record<string, unknown>): string {\n return Buffer.from(JSON.stringify(data)).toString('base64');\n }\n}\n","/**\n * CSV Utilities\n *\n * Utilities for converting data to CSV format for export operations.\n *\n * @module export/csv\n *\n * @example\n * ```typescript\n * import { convertToCSV, parseCSV } from '@burdenoff/be-sdk/export';\n *\n * const csv = convertToCSV(users, { includeHeaders: true });\n * console.log(csv);\n * ```\n */\n\nimport type { CSVConversionOptions } from './types.js';\n\nconst FORMULA_PREFIX_RE = /^[=+\\-@]/;\n\nexport function sanitizeCSVCell(value: string): string {\n return FORMULA_PREFIX_RE.test(value) ? `'${value}` : value;\n}\n\n/**\n * Convert an array of objects to CSV format\n *\n * Handles nested objects by flattening them with dot notation.\n * Arrays are JSON stringified.\n * Dates are converted to ISO strings.\n *\n * @param data - Array of objects to convert\n * @param options - CSV conversion options\n * @returns CSV string\n *\n * @example\n * ```typescript\n * const users = [\n * { id: 1, name: 'John', address: { city: 'NYC' } },\n * { id: 2, name: 'Jane', address: { city: 'LA' } },\n * ];\n *\n * const csv = convertToCSV(users);\n * // Output:\n * // id,name,address.city\n * // 1,John,NYC\n * // 2,Jane,LA\n * ```\n */\nexport function convertToCSV(data: unknown[], options: CSVConversionOptions = {}): string {\n const { delimiter = ',', includeHeaders = true, flattenFields = true, maxFlattenDepth = 3 } = options;\n\n if (data.length === 0) {\n return '';\n }\n\n // Flatten objects and get all keys\n const flattenObject = (obj: unknown, prefix = '', depth = 0): Record<string, string> => {\n const result: Record<string, string> = {};\n\n if (obj === null || obj === undefined) {\n return result;\n }\n\n if (typeof obj !== 'object') {\n return { [prefix || 'value']: String(obj) };\n }\n\n for (const [key, value] of Object.entries(obj as Record<string, unknown>)) {\n const newKey = prefix ? `${prefix}.${key}` : key;\n\n if (value === null || value === undefined) {\n result[newKey] = '';\n } else if (value instanceof Date) {\n result[newKey] = value.toISOString();\n } else if (Array.isArray(value)) {\n result[newKey] = JSON.stringify(value);\n } else if (typeof value === 'object' && flattenFields && depth < maxFlattenDepth) {\n Object.assign(result, flattenObject(value, newKey, depth + 1));\n } else if (typeof value === 'object') {\n result[newKey] = JSON.stringify(value);\n } else {\n result[newKey] = String(value);\n }\n }\n\n return result;\n };\n\n // Flatten all records and collect all keys\n const flattenedRecords = data.map((item) => flattenObject(item));\n const allKeys = new Set<string>();\n for (const record of flattenedRecords) {\n for (const key of Object.keys(record)) {\n allKeys.add(key);\n }\n }\n\n const headers = Array.from(allKeys).sort((a, b) => a.localeCompare(b));\n\n // Escape CSV values\n const escapeCSV = (value: string): string => {\n const sanitizedValue = sanitizeCSVCell(value);\n\n if (\n sanitizedValue.includes(delimiter) ||\n sanitizedValue.includes('\"') ||\n sanitizedValue.includes('\\n') ||\n sanitizedValue.includes('\\r')\n ) {\n return `\"${sanitizedValue.replace(/\"/g, '\"\"')}\"`;\n }\n return sanitizedValue;\n };\n\n // Build CSV\n const lines: string[] = [];\n\n if (includeHeaders) {\n lines.push(headers.map(escapeCSV).join(delimiter));\n }\n\n for (const record of flattenedRecords) {\n const row = headers.map((header) => escapeCSV(record[header] || ''));\n lines.push(row.join(delimiter));\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Parse a CSV string into an array of objects\n *\n * @param csv - CSV string to parse\n * @param options - Parse options\n * @returns Array of parsed objects\n *\n * @example\n * ```typescript\n * const csv = 'id,name\\n1,John\\n2,Jane';\n * const data = parseCSV(csv);\n * // [{ id: '1', name: 'John' }, { id: '2', name: 'Jane' }]\n * ```\n */\nexport function parseCSV(\n csv: string,\n options: { delimiter?: string; hasHeaders?: boolean } = {}\n): Record<string, string>[] {\n const { delimiter = ',', hasHeaders = true } = options;\n\n const lines = csv.split(/\\r?\\n/).filter((line) => line.trim());\n\n if (lines.length === 0) {\n return [];\n }\n\n // Parse a single CSV line, handling quoted values\n const parseLine = (line: string): string[] => {\n const values: string[] = [];\n let current = '';\n let inQuotes = false;\n\n let i = 0;\n while (i < line.length) {\n const char = line[i];\n const nextChar = line[i + 1];\n\n if (char === '\"' && inQuotes && nextChar === '\"') {\n current += '\"';\n i += 2; // Skip next quote\n } else if (char === '\"') {\n inQuotes = !inQuotes;\n i++;\n } else if (char === delimiter && !inQuotes) {\n values.push(current);\n current = '';\n i++;\n } else {\n current += char;\n i++;\n }\n }\n\n values.push(current);\n return values;\n };\n\n let headers: string[];\n let dataLines: string[];\n\n // We've already checked that lines.length > 0, so lines[0] is guaranteed to exist\n const firstLine = lines[0] as string;\n\n if (hasHeaders) {\n headers = parseLine(firstLine);\n dataLines = lines.slice(1);\n } else {\n // Generate numeric headers if no header row\n const firstRow = parseLine(firstLine);\n headers = firstRow.map((_, i) => `col${i}`);\n dataLines = lines;\n }\n\n return dataLines.map((line) => {\n const values = parseLine(line);\n const obj: Record<string, string> = {};\n\n headers.forEach((header, i) => {\n obj[header] = values[i] || '';\n });\n\n return obj;\n });\n}\n\n/**\n * Convert CSV to JSON string\n *\n * @param csv - CSV string\n * @param options - Parse options\n * @returns JSON string\n */\nexport function csvToJSON(\n csv: string,\n options: { delimiter?: string; hasHeaders?: boolean; pretty?: boolean } = {}\n): string {\n const { pretty = false, ...parseOptions } = options;\n const data = parseCSV(csv, parseOptions);\n return pretty ? JSON.stringify(data, null, 2) : JSON.stringify(data);\n}\n\n/**\n * Get CSV headers from data\n *\n * @param data - Array of objects\n * @param flattenFields - Whether to flatten nested objects\n * @returns Array of header strings\n */\nexport function getCSVHeaders(data: unknown[], flattenFields: boolean = true): string[] {\n if (data.length === 0) {\n return [];\n }\n\n const collectKeys = (obj: unknown, prefix = '', depth = 0): string[] => {\n const keys: string[] = [];\n\n if (obj === null || obj === undefined || typeof obj !== 'object') {\n return prefix ? [prefix] : [];\n }\n\n for (const [key, value] of Object.entries(obj as Record<string, unknown>)) {\n const fullKey = prefix ? `${prefix}.${key}` : key;\n\n if (\n value !== null &&\n typeof value === 'object' &&\n !Array.isArray(value) &&\n !(value instanceof Date) &&\n flattenFields &&\n depth < 3\n ) {\n keys.push(...collectKeys(value, fullKey, depth + 1));\n } else {\n keys.push(fullKey);\n }\n }\n\n return keys;\n };\n\n const allKeys = new Set<string>();\n for (const item of data) {\n for (const key of collectKeys(item)) {\n allKeys.add(key);\n }\n }\n\n return Array.from(allKeys).sort((a, b) => a.localeCompare(b));\n}\n\n/**\n * Estimate CSV file size for a dataset\n *\n * @param data - Array of objects\n * @param sampleSize - Number of records to sample for estimation\n * @returns Estimated size in bytes\n */\nexport function estimateCSVSize(data: unknown[], sampleSize: number = 100): number {\n if (data.length === 0) {\n return 0;\n }\n\n // Take a sample to estimate average row size\n const sample = data.slice(0, Math.min(sampleSize, data.length));\n const sampleCSV = convertToCSV(sample);\n const averageRowSize = sampleCSV.length / sample.length;\n\n // Estimate total size (headers + data rows)\n const headers = getCSVHeaders(data);\n const headerSize = headers.join(',').length + 1; // +1 for newline\n\n return Math.ceil(headerSize + averageRowSize * data.length);\n}\n","/**\n * Export Gateway Helper\n *\n * Centralised wrapper around the workspace internal gateway's\n * `createExportJob` mutation, used by per-svc convenience resolvers\n * (e.g. `createTagsExportJob`, `createGroupsExportJob`).\n *\n * Replaces the duplicated `src/clients/export-gateway.ts` files that\n * existed in 19+ workspace svcs.\n *\n * @module export/gateway-client\n *\n * @example\n * ```typescript\n * import { triggerExportJob } from '@burdenoff/be-sdk/export';\n *\n * const result = await triggerExportJob({\n * serviceName: 'wspace-tags-svc',\n * workspaceId: ctx.workspaceId,\n * name: input.name,\n * entityTypes: ['tags', 'vocabularies'],\n * format: input.format,\n * actorId: ctx.actorId,\n * actorType: ctx.actorType,\n * });\n * ```\n */\n\nimport { GatewayClient } from '../gateway/index.js';\nimport type { ServiceLayer } from '../types/layer.js';\n\nconst CREATE_EXPORT_JOB_MUTATION = `mutation CreateExportJob($input: CreateExportJobInput!) {\n createExportJob(input: $input) {\n id\n status\n workspaceId\n entityTypes\n format\n createdAt\n }\n}`;\n\nexport type ExportActorType = 'user' | 'app' | 'service' | 'super_admin';\nexport type ExportFormatGql = 'JSON' | 'CSV';\n\nexport interface TriggerExportJobParams {\n /** Caller service name, used by gateway client telemetry/auth */\n serviceName: string;\n /** Layer for the gateway. Defaults to `wspace`. */\n layer?: ServiceLayer;\n /** Workspace context (required for wspace exports). */\n workspaceId: string;\n /** Human-readable name for the export job. */\n name: string;\n /** Entity types registered in `wspace-export-svc` to include. */\n entityTypes: string[];\n /** Output format. */\n format: ExportFormatGql;\n /** Actor making the request (forwarded to RBAC). */\n actorId: string;\n actorType: ExportActorType;\n /** Whether to include extended metadata in the export ZIP. */\n includeMetadata?: boolean;\n /** Optional ISO date-range bounds. */\n dateRangeStart?: string;\n dateRangeEnd?: string;\n}\n\nexport interface ExportJobResult {\n id: string;\n status: string;\n workspaceId: string;\n entityTypes: string[];\n format: string;\n createdAt: string;\n}\n\ninterface CreateExportJobResponse {\n createExportJob?: ExportJobResult;\n}\n\n/**\n * Submit a `createExportJob` mutation to the workspace internal gateway.\n *\n * The caller is expected to map the returned `ExportJobResult` to its\n * own GraphQL output type (the per-svc `ExportJobResponse`).\n */\nexport async function triggerExportJob(params: TriggerExportJobParams): Promise<ExportJobResult> {\n const {\n serviceName,\n layer = 'wspace',\n actorId,\n actorType,\n workspaceId,\n name,\n entityTypes,\n format,\n includeMetadata,\n dateRangeStart,\n dateRangeEnd,\n } = params;\n\n const client = new GatewayClient({ layer, serviceName });\n\n const input = {\n workspaceId,\n name,\n entityTypes,\n format,\n ...(includeMetadata !== undefined ? { includeMetadata } : {}),\n ...(dateRangeStart !== undefined ? { dateRangeStart } : {}),\n ...(dateRangeEnd !== undefined ? { dateRangeEnd } : {}),\n };\n\n const response = await client.internalQuery<CreateExportJobResponse>({\n query: CREATE_EXPORT_JOB_MUTATION,\n variables: { input },\n headers: {\n 'x-actor-id': actorId,\n 'x-actor-type': actorType,\n 'x-workspace-id': workspaceId,\n },\n });\n\n const job = response.data?.createExportJob;\n if (!job) {\n throw new Error('Export service did not return a job');\n }\n return job;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/export/index.ts","../src/export/base-exporter.ts","../src/export/pagination.ts","../src/export/csv.ts","../src/export/gateway-client.ts"],"names":["BaseModuleExporter","moduleKey","displayName","description","defaultExcludeFields","supportedProducts","modelName","filterFields","entity","excludeFields","fieldsToExclude","length","filtered","record","key","value","Object","entries","includes","filterFieldsMany","entities","map","paginate","queryFn","page","pageSize","skip","take","items","total","data","hasMore","nextCursor","String","undefined","fetchAll","fetchBatch","batchSize","allItems","cursor","batch","push","lastItem","id","transformForExport","validateOptions","options","validFormats","format","Error","join","getSupportedFormats","getMetadata","supportedFormats","PaginationService","params","start","end","paginatedItems","slice","totalCount","pageInfo","hasNextPage","hasPreviousPage","startCursor","endCursor","Math","min","calculatePagination","totalPages","ceil","startIndex","endIndex","currentPage","paginatedQuery","fetchFn","limit","initialCursor","totalYielded","item","collectPaginatedQuery","createPrismaFetchFn","_batchSize","calculateOffset","max","parseCursor","decoded","Buffer","from","toString","JSON","parse","createCursor","stringify","FORMULA_PREFIX_RE","sanitizeCSVCell","test","convertToCSV","delimiter","includeHeaders","flattenFields","maxFlattenDepth","flattenObject","obj","prefix","depth","result","newKey","Date","toISOString","Array","isArray","assign","flattenedRecords","allKeys","Set","keys","add","headers","sort","a","b","localeCompare","escapeCSV","sanitizedValue","replace","lines","row","header","parseCSV","csv","hasHeaders","split","filter","line","trim","parseLine","values","current","inQuotes","i","char","nextChar","dataLines","firstLine","firstRow","_","forEach","csvToJSON","pretty","parseOptions","getCSVHeaders","collectKeys","fullKey","estimateCSVSize","sampleSize","sample","sampleCSV","averageRowSize","headerSize","CREATE_EXPORT_JOB_MUTATION","triggerExportJob","serviceName","layer","actorId","actorType","workspaceId","name","entityTypes","includeMetadata","dateRangeStart","dateRangeEnd","client","GatewayClient","input","response","internalQuery","query","variables","job","createExportJob"],"mappings":";;;;AAAA,IAAA,cAAA,GAAA;;;;;;;;;;;;;ACoCO,IAAeA,qBAAf,MAAeA;EApCtB;;;;AAsCEC,EAAAA,SAAAA;;AAGAC,EAAAA,WAAAA;;AAGAC,EAAAA,WAAAA;;AAGAC,EAAAA,oBAAAA;;AAGAC,EAAAA,iBAAAA;;AAGUC,EAAAA,SAAAA;;;;;;;;;;;;;;;;;AA6BAC,E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AA;AACT;AA1CsBlB,MAAAA,CAAAA,gBAAAA,EAAAA,kBAAAA,CAAAA","file":"chunk-FNZEQOJY.js","sourcesContent":["/**\n * Export Module\n *\n * Provides common utilities for data export operations across all Burdenoff microservices.\n * Includes pagination services, base exporter classes, CSV utilities, and type definitions.\n *\n * @module export\n *\n * @example\n * ```typescript\n * // Import from the export module\n * import {\n * BaseModuleExporter,\n * PaginationService,\n * convertToCSV,\n * } from '@burdenoff/be-sdk/export';\n *\n * // Create a custom exporter\n * class UserExporter extends BaseModuleExporter<User> {\n * moduleKey = 'users';\n * displayName = 'Users';\n *\n * async export(options: ExportOptions): Promise<ExportResult> {\n * const data = await this.fetchAll(\n * (cursor) => db.user.findMany({\n * where: cursor ? { id: { gt: cursor } } : {},\n * take: 100,\n * })\n * );\n *\n * const csv = convertToCSV(data);\n * return { data, format: 'csv' };\n * }\n * }\n *\n * // Use pagination utilities\n * const result = PaginationService.paginate(items, { page: 1, pageSize: 20 });\n * ```\n */\n\n// ============================================================================\n// Type Exports\n// ============================================================================\n\nexport type {\n // Export format types\n ExportFormat,\n ExportFormatEnum,\n\n // Configuration types\n ExportConfig,\n ExportOptions,\n\n // Job types\n ExportJobStatus,\n ExportJob,\n ExportProgress,\n ExportResult,\n\n // Fetch types\n ExportFetchOptions,\n ExportFetchResult,\n\n // Pagination types\n PaginationParams,\n PaginatedResult,\n PaginatedQueryOptions,\n PaginateResult,\n PaginateQueryFn,\n\n // Module interface\n ExportableModule,\n\n // CSV types\n CSVConversionOptions,\n} from './types.js';\n\n// ============================================================================\n// Class Exports\n// ============================================================================\n\nexport { BaseModuleExporter } from './base-exporter.js';\nexport { PaginationService } from './pagination.js';\n\n// ============================================================================\n// Function Exports\n// ============================================================================\n\nexport { convertToCSV, parseCSV, csvToJSON, getCSVHeaders, estimateCSVSize } from './csv.js';\n\n// ============================================================================\n// Gateway Helper Exports\n// ============================================================================\n\nexport { triggerExportJob } from './gateway-client.js';\nexport type { TriggerExportJobParams, ExportJobResult, ExportActorType, ExportFormatGql } from './gateway-client.js';\n","/**\n * Base Module Exporter\n *\n * Abstract base class for module exporters across all Burdenoff microservices.\n * Provides common functionality for exporting data from different modules.\n *\n * @module export/base-exporter\n *\n * @example\n * ```typescript\n * import { BaseModuleExporter } from '@burdenoff/be-sdk/export';\n *\n * class UserExporter extends BaseModuleExporter<User> {\n * moduleKey = 'users';\n * displayName = 'Users';\n * description = 'Export user data';\n *\n * async export(options: ExportOptions): Promise<ExportResult> {\n * // Implementation\n * }\n * }\n * ```\n */\n\nimport type { ExportOptions, ExportResult, PaginateQueryFn, PaginateResult } from './types.js';\n\n/**\n * Abstract base class for module exporters\n *\n * Provides common functionality that all module exporters can inherit:\n * - Field filtering\n * - Pagination helpers\n * - Module metadata\n *\n * @typeParam T - The type of entity this exporter handles\n */\nexport abstract class BaseModuleExporter<T = unknown> {\n /** Unique key identifying this module (e.g., 'users', 'tags', 'orders') */\n moduleKey?: string;\n\n /** Human-readable display name for the module */\n displayName?: string;\n\n /** Description of what this module exports */\n description?: string;\n\n /** Default fields to exclude from export (e.g., sensitive data) */\n defaultExcludeFields?: string[];\n\n /** List of product IDs this exporter supports */\n supportedProducts?: string[];\n\n /** Model name for database operations */\n protected modelName?: string;\n\n /**\n * Export data from this module\n *\n * Subclasses should implement this method to perform the actual export.\n * The method is optional to allow for gradual implementation.\n *\n * @param options - Export options including format, filters, and pagination\n * @returns Export result with data or download URL\n */\n export?(options: ExportOptions): Promise<ExportResult>;\n\n /**\n * Filter fields from an entity based on exclude list\n *\n * Use this to remove sensitive or unnecessary fields from exported data.\n *\n * @param entity - Entity to filter\n * @param excludeFields - Fields to exclude (uses defaultExcludeFields if not provided)\n * @returns Filtered entity as a plain object\n *\n * @example\n * ```typescript\n * const user = { id: '1', name: 'John', password: 'secret', ssn: '123' };\n * const filtered = this.filterFields(user, ['password', 'ssn']);\n * // Result: { id: '1', name: 'John' }\n * ```\n */\n protected filterFields(entity: T | Record<string, unknown>, excludeFields?: string[]): Record<string, unknown> {\n const fieldsToExclude = excludeFields || this.defaultExcludeFields || [];\n\n if (fieldsToExclude.length === 0) {\n return entity as Record<string, unknown>;\n }\n\n const filtered: Record<string, unknown> = {};\n const record = entity as Record<string, unknown>;\n\n for (const [key, value] of Object.entries(record)) {\n if (!fieldsToExclude.includes(key)) {\n filtered[key] = value;\n }\n }\n\n return filtered;\n }\n\n /**\n * Filter multiple entities\n *\n * @param entities - Array of entities to filter\n * @param excludeFields - Fields to exclude\n * @returns Array of filtered entities\n */\n protected filterFieldsMany(\n entities: (T | Record<string, unknown>)[],\n excludeFields?: string[]\n ): Record<string, unknown>[] {\n return entities.map((entity) => this.filterFields(entity, excludeFields));\n }\n\n /**\n * Paginate helper for database queries\n *\n * Use this to implement paginated data fetching in your export method.\n *\n * @param queryFn - Function that executes the paginated query\n * @param page - Page number (1-indexed)\n * @param pageSize - Number of items per page\n * @returns Paginated result with data and metadata\n *\n * @example\n * ```typescript\n * const result = await this.paginate(\n * async ({ skip, take }) => {\n * const items = await db.user.findMany({ skip, take });\n * const total = await db.user.count();\n * return { items, total };\n * },\n * 1,\n * 100\n * );\n * ```\n */\n protected async paginate(\n queryFn: PaginateQueryFn<T>,\n page: number = 1,\n pageSize: number = 100\n ): Promise<PaginateResult<T>> {\n const skip = (page - 1) * pageSize;\n const take = pageSize;\n\n const { items, total } = await queryFn({ skip, take });\n\n return {\n data: items,\n total,\n hasMore: skip + items.length < total,\n nextCursor: items.length > 0 && skip + items.length < total ? String(page + 1) : undefined,\n };\n }\n\n /**\n * Fetch all data using cursor-based pagination\n *\n * Use this for exporting large datasets efficiently.\n *\n * @param fetchBatch - Function to fetch a batch of data\n * @param batchSize - Number of items per batch\n * @returns All fetched items\n *\n * @example\n * ```typescript\n * const allUsers = await this.fetchAll(\n * async (cursor) => db.user.findMany({\n * where: cursor ? { id: { gt: cursor } } : undefined,\n * orderBy: { id: 'asc' },\n * take: 100,\n * }),\n * 100\n * );\n * ```\n */\n protected async fetchAll(\n fetchBatch: (cursor?: string) => Promise<(T & { id: string })[]>,\n batchSize: number = 100\n ): Promise<T[]> {\n const allItems: T[] = [];\n let cursor: string | undefined;\n\n while (true) {\n const batch = await fetchBatch(cursor);\n\n if (batch.length === 0) {\n break;\n }\n\n allItems.push(...batch);\n\n // Get cursor from last item\n const lastItem = batch[batch.length - 1];\n if (lastItem) {\n cursor = lastItem.id;\n }\n\n // If we got fewer items than batch size, we're done\n if (batch.length < batchSize) {\n break;\n }\n }\n\n return allItems;\n }\n\n /**\n * Transform entity for export\n *\n * Override this method to customize how entities are transformed before export.\n * Default implementation returns the entity as-is after field filtering.\n *\n * @param entity - Entity to transform\n * @param excludeFields - Fields to exclude\n * @returns Transformed entity\n */\n protected transformForExport(entity: T, excludeFields?: string[]): Record<string, unknown> {\n return this.filterFields(entity, excludeFields);\n }\n\n /**\n * Validate export options\n *\n * Override this to add custom validation for export options.\n *\n * @param options - Export options to validate\n * @throws Error if options are invalid\n */\n protected validateOptions(options: ExportOptions): void {\n const validFormats = ['csv', 'json', 'xlsx'];\n if (!validFormats.includes(options.format)) {\n throw new Error(`Invalid export format: ${options.format}. Valid formats: ${validFormats.join(', ')}`);\n }\n }\n\n /**\n * Get supported export formats\n *\n * @returns Array of supported format strings\n */\n getSupportedFormats(): string[] {\n return ['csv', 'json', 'xlsx'];\n }\n\n /**\n * Get module metadata\n *\n * @returns Module metadata object\n */\n getMetadata(): {\n moduleKey?: string;\n displayName?: string;\n description?: string;\n supportedProducts?: string[];\n supportedFormats: string[];\n } {\n return {\n moduleKey: this.moduleKey,\n displayName: this.displayName,\n description: this.description,\n supportedProducts: this.supportedProducts,\n supportedFormats: this.getSupportedFormats(),\n };\n }\n}\n","/**\n * Pagination Service\n *\n * Provides pagination utilities for export operations across all Burdenoff microservices.\n * Supports both offset-based and cursor-based pagination strategies.\n *\n * @module export/pagination\n *\n * @example\n * ```typescript\n * import { PaginationService } from '@burdenoff/be-sdk/export';\n *\n * // Offset-based pagination\n * const result = PaginationService.paginate(items, { page: 2, pageSize: 20 });\n *\n * // Cursor-based pagination with async generator\n * for await (const item of PaginationService.paginatedQuery(fetchFn, { limit: 100 })) {\n * console.log(item);\n * }\n * ```\n */\n\nimport type { PaginatedQueryOptions, PaginatedResult, PaginationParams } from './types.js';\n\n/**\n * Service providing pagination utilities for export and data fetching operations\n */\nexport class PaginationService {\n /**\n * Paginate an array of items using offset-based pagination\n *\n * @param items - Array of items to paginate\n * @param params - Pagination parameters\n * @returns Paginated result with items and metadata\n *\n * @example\n * ```typescript\n * const allUsers = await db.user.findMany();\n * const page = PaginationService.paginate(allUsers, { page: 1, pageSize: 10 });\n * console.log(page.items); // First 10 users\n * console.log(page.pageInfo.hasNextPage); // true if more pages exist\n * ```\n */\n static paginate<T>(items: T[], params: PaginationParams): PaginatedResult<T> {\n const page = params.page ?? 1;\n const pageSize = params.pageSize ?? 20;\n const start = (page - 1) * pageSize;\n const end = start + pageSize;\n\n const paginatedItems = items.slice(start, end);\n\n return {\n items: paginatedItems,\n totalCount: items.length,\n pageInfo: {\n hasNextPage: end < items.length,\n hasPreviousPage: page > 1,\n startCursor: paginatedItems.length > 0 ? String(start) : undefined,\n endCursor: paginatedItems.length > 0 ? String(Math.min(end, items.length) - 1) : undefined,\n },\n };\n }\n\n /**\n * Calculate pagination metadata without slicing data\n *\n * @param totalCount - Total number of items\n * @param page - Current page number (1-indexed)\n * @param pageSize - Items per page\n * @returns Pagination metadata\n *\n * @example\n * ```typescript\n * const meta = PaginationService.calculatePagination(150, 3, 20);\n * // meta.hasNextPage = true (page 4 exists)\n * // meta.hasPreviousPage = true (page 2 exists)\n * // meta.totalPages = 8\n * ```\n */\n static calculatePagination(\n totalCount: number,\n page: number,\n pageSize: number\n ): {\n hasNextPage: boolean;\n hasPreviousPage: boolean;\n totalPages: number;\n currentPage: number;\n pageSize: number;\n startIndex: number;\n endIndex: number;\n } {\n const totalPages = Math.ceil(totalCount / pageSize);\n const startIndex = (page - 1) * pageSize;\n const endIndex = Math.min(startIndex + pageSize - 1, totalCount - 1);\n\n return {\n hasNextPage: page < totalPages,\n hasPreviousPage: page > 1,\n totalPages,\n currentPage: page,\n pageSize,\n startIndex,\n endIndex,\n };\n }\n\n /**\n * Async generator for paginated database queries using cursor-based pagination\n *\n * This is ideal for processing large datasets without loading everything into memory.\n * The generator yields items one at a time, fetching new batches as needed.\n *\n * @param fetchFn - Function to fetch data given a cursor\n * @param options - Pagination options\n * @returns Async generator of items\n *\n * @example\n * ```typescript\n * // Define fetch function that queries the database\n * const fetchUsers = async (cursor?: string) => {\n * return db.user.findMany({\n * where: cursor ? { id: { gt: cursor } } : undefined,\n * orderBy: { id: 'asc' },\n * take: 100,\n * });\n * };\n *\n * // Process all users without loading all into memory\n * for await (const user of PaginationService.paginatedQuery(fetchUsers)) {\n * await processUser(user);\n * }\n * ```\n */\n static async *paginatedQuery<T extends { id: string }>(\n fetchFn: (cursor?: string) => Promise<T[]>,\n options: PaginatedQueryOptions = {}\n ): AsyncGenerator<T, void, unknown> {\n const { limit, initialCursor } = options;\n let cursor = initialCursor;\n let hasMore = true;\n let totalYielded = 0;\n\n while (hasMore) {\n const items = await fetchFn(cursor);\n\n if (items.length === 0) {\n break;\n }\n\n for (const item of items) {\n yield item;\n totalYielded++;\n\n if (limit && totalYielded >= limit) {\n return;\n }\n }\n\n // Get next cursor from last item\n const lastItem = items[items.length - 1];\n if (lastItem) {\n cursor = lastItem.id;\n }\n\n // If we got fewer items than expected batch size, we're done\n // Note: This assumes fetchFn respects a consistent batch size internally\n hasMore = items.length > 0;\n }\n }\n\n /**\n * Collect all items from a paginated query into an array\n *\n * @param fetchFn - Function to fetch data given a cursor\n * @param options - Pagination options\n * @returns Array of all items\n *\n * @example\n * ```typescript\n * const allUsers = await PaginationService.collectPaginatedQuery(fetchUsers, { limit: 1000 });\n * ```\n */\n static async collectPaginatedQuery<T extends { id: string }>(\n fetchFn: (cursor?: string) => Promise<T[]>,\n options: PaginatedQueryOptions = {}\n ): Promise<T[]> {\n const items: T[] = [];\n\n for await (const item of PaginationService.paginatedQuery(fetchFn, options)) {\n items.push(item);\n }\n\n return items;\n }\n\n /**\n * Create a cursor-based paginated fetch function from a Prisma-style query\n *\n * @param queryFn - Prisma-style query function\n * @param batchSize - Number of items to fetch per batch\n * @returns Fetch function compatible with paginatedQuery\n *\n * @example\n * ```typescript\n * const fetchFn = PaginationService.createPrismaFetchFn(\n * (cursor) => db.user.findMany({\n * where: { isActive: true, ...(cursor ? { id: { gt: cursor } } : {}) },\n * orderBy: { id: 'asc' },\n * take: 100,\n * }),\n * 100\n * );\n *\n * for await (const user of PaginationService.paginatedQuery(fetchFn)) {\n * console.log(user);\n * }\n * ```\n */\n static createPrismaFetchFn<T extends { id: string }>(\n queryFn: (cursor?: string) => Promise<T[]>,\n _batchSize: number = 100\n ): (cursor?: string) => Promise<T[]> {\n return queryFn;\n }\n\n /**\n * Calculate offset for skip-based pagination\n *\n * @param page - Page number (1-indexed)\n * @param pageSize - Items per page\n * @returns Offset value for skip\n */\n static calculateOffset(page: number, pageSize: number): number {\n return (Math.max(1, page) - 1) * pageSize;\n }\n\n /**\n * Parse cursor string to extract pagination state\n *\n * @param cursor - Base64-encoded cursor string\n * @returns Decoded cursor data or null if invalid\n */\n static parseCursor<T = Record<string, unknown>>(cursor: string): T | null {\n try {\n const decoded = Buffer.from(cursor, 'base64').toString('utf-8');\n return JSON.parse(decoded) as T;\n } catch {\n return null;\n }\n }\n\n /**\n * Create cursor string from pagination state\n *\n * @param data - Data to encode in cursor\n * @returns Base64-encoded cursor string\n */\n static createCursor(data: Record<string, unknown>): string {\n return Buffer.from(JSON.stringify(data)).toString('base64');\n }\n}\n","/**\n * CSV Utilities\n *\n * Utilities for converting data to CSV format for export operations.\n *\n * @module export/csv\n *\n * @example\n * ```typescript\n * import { convertToCSV, parseCSV } from '@burdenoff/be-sdk/export';\n *\n * const csv = convertToCSV(users, { includeHeaders: true });\n * console.log(csv);\n * ```\n */\n\nimport type { CSVConversionOptions } from './types.js';\n\nconst FORMULA_PREFIX_RE = /^[=+\\-@]/;\n\nexport function sanitizeCSVCell(value: string): string {\n return FORMULA_PREFIX_RE.test(value) ? `'${value}` : value;\n}\n\n/**\n * Convert an array of objects to CSV format\n *\n * Handles nested objects by flattening them with dot notation.\n * Arrays are JSON stringified.\n * Dates are converted to ISO strings.\n *\n * @param data - Array of objects to convert\n * @param options - CSV conversion options\n * @returns CSV string\n *\n * @example\n * ```typescript\n * const users = [\n * { id: 1, name: 'John', address: { city: 'NYC' } },\n * { id: 2, name: 'Jane', address: { city: 'LA' } },\n * ];\n *\n * const csv = convertToCSV(users);\n * // Output:\n * // id,name,address.city\n * // 1,John,NYC\n * // 2,Jane,LA\n * ```\n */\nexport function convertToCSV(data: unknown[], options: CSVConversionOptions = {}): string {\n const { delimiter = ',', includeHeaders = true, flattenFields = true, maxFlattenDepth = 3 } = options;\n\n if (data.length === 0) {\n return '';\n }\n\n // Flatten objects and get all keys\n const flattenObject = (obj: unknown, prefix = '', depth = 0): Record<string, string> => {\n const result: Record<string, string> = {};\n\n if (obj === null || obj === undefined) {\n return result;\n }\n\n if (typeof obj !== 'object') {\n return { [prefix || 'value']: String(obj) };\n }\n\n for (const [key, value] of Object.entries(obj as Record<string, unknown>)) {\n const newKey = prefix ? `${prefix}.${key}` : key;\n\n if (value === null || value === undefined) {\n result[newKey] = '';\n } else if (value instanceof Date) {\n result[newKey] = value.toISOString();\n } else if (Array.isArray(value)) {\n result[newKey] = JSON.stringify(value);\n } else if (typeof value === 'object' && flattenFields && depth < maxFlattenDepth) {\n Object.assign(result, flattenObject(value, newKey, depth + 1));\n } else if (typeof value === 'object') {\n result[newKey] = JSON.stringify(value);\n } else {\n result[newKey] = String(value);\n }\n }\n\n return result;\n };\n\n // Flatten all records and collect all keys\n const flattenedRecords = data.map((item) => flattenObject(item));\n const allKeys = new Set<string>();\n for (const record of flattenedRecords) {\n for (const key of Object.keys(record)) {\n allKeys.add(key);\n }\n }\n\n const headers = Array.from(allKeys).sort((a, b) => a.localeCompare(b));\n\n // Escape CSV values\n const escapeCSV = (value: string): string => {\n const sanitizedValue = sanitizeCSVCell(value);\n\n if (\n sanitizedValue.includes(delimiter) ||\n sanitizedValue.includes('\"') ||\n sanitizedValue.includes('\\n') ||\n sanitizedValue.includes('\\r')\n ) {\n return `\"${sanitizedValue.replace(/\"/g, '\"\"')}\"`;\n }\n return sanitizedValue;\n };\n\n // Build CSV\n const lines: string[] = [];\n\n if (includeHeaders) {\n lines.push(headers.map(escapeCSV).join(delimiter));\n }\n\n for (const record of flattenedRecords) {\n const row = headers.map((header) => escapeCSV(record[header] || ''));\n lines.push(row.join(delimiter));\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Parse a CSV string into an array of objects\n *\n * @param csv - CSV string to parse\n * @param options - Parse options\n * @returns Array of parsed objects\n *\n * @example\n * ```typescript\n * const csv = 'id,name\\n1,John\\n2,Jane';\n * const data = parseCSV(csv);\n * // [{ id: '1', name: 'John' }, { id: '2', name: 'Jane' }]\n * ```\n */\nexport function parseCSV(\n csv: string,\n options: { delimiter?: string; hasHeaders?: boolean } = {}\n): Record<string, string>[] {\n const { delimiter = ',', hasHeaders = true } = options;\n\n const lines = csv.split(/\\r?\\n/).filter((line) => line.trim());\n\n if (lines.length === 0) {\n return [];\n }\n\n // Parse a single CSV line, handling quoted values\n const parseLine = (line: string): string[] => {\n const values: string[] = [];\n let current = '';\n let inQuotes = false;\n\n let i = 0;\n while (i < line.length) {\n const char = line[i];\n const nextChar = line[i + 1];\n\n if (char === '\"' && inQuotes && nextChar === '\"') {\n current += '\"';\n i += 2; // Skip next quote\n } else if (char === '\"') {\n inQuotes = !inQuotes;\n i++;\n } else if (char === delimiter && !inQuotes) {\n values.push(current);\n current = '';\n i++;\n } else {\n current += char;\n i++;\n }\n }\n\n values.push(current);\n return values;\n };\n\n let headers: string[];\n let dataLines: string[];\n\n // We've already checked that lines.length > 0, so lines[0] is guaranteed to exist\n const firstLine = lines[0] as string;\n\n if (hasHeaders) {\n headers = parseLine(firstLine);\n dataLines = lines.slice(1);\n } else {\n // Generate numeric headers if no header row\n const firstRow = parseLine(firstLine);\n headers = firstRow.map((_, i) => `col${i}`);\n dataLines = lines;\n }\n\n return dataLines.map((line) => {\n const values = parseLine(line);\n const obj: Record<string, string> = {};\n\n headers.forEach((header, i) => {\n obj[header] = values[i] || '';\n });\n\n return obj;\n });\n}\n\n/**\n * Convert CSV to JSON string\n *\n * @param csv - CSV string\n * @param options - Parse options\n * @returns JSON string\n */\nexport function csvToJSON(\n csv: string,\n options: { delimiter?: string; hasHeaders?: boolean; pretty?: boolean } = {}\n): string {\n const { pretty = false, ...parseOptions } = options;\n const data = parseCSV(csv, parseOptions);\n return pretty ? JSON.stringify(data, null, 2) : JSON.stringify(data);\n}\n\n/**\n * Get CSV headers from data\n *\n * @param data - Array of objects\n * @param flattenFields - Whether to flatten nested objects\n * @returns Array of header strings\n */\nexport function getCSVHeaders(data: unknown[], flattenFields: boolean = true): string[] {\n if (data.length === 0) {\n return [];\n }\n\n const collectKeys = (obj: unknown, prefix = '', depth = 0): string[] => {\n const keys: string[] = [];\n\n if (obj === null || obj === undefined || typeof obj !== 'object') {\n return prefix ? [prefix] : [];\n }\n\n for (const [key, value] of Object.entries(obj as Record<string, unknown>)) {\n const fullKey = prefix ? `${prefix}.${key}` : key;\n\n if (\n value !== null &&\n typeof value === 'object' &&\n !Array.isArray(value) &&\n !(value instanceof Date) &&\n flattenFields &&\n depth < 3\n ) {\n keys.push(...collectKeys(value, fullKey, depth + 1));\n } else {\n keys.push(fullKey);\n }\n }\n\n return keys;\n };\n\n const allKeys = new Set<string>();\n for (const item of data) {\n for (const key of collectKeys(item)) {\n allKeys.add(key);\n }\n }\n\n return Array.from(allKeys).sort((a, b) => a.localeCompare(b));\n}\n\n/**\n * Estimate CSV file size for a dataset\n *\n * @param data - Array of objects\n * @param sampleSize - Number of records to sample for estimation\n * @returns Estimated size in bytes\n */\nexport function estimateCSVSize(data: unknown[], sampleSize: number = 100): number {\n if (data.length === 0) {\n return 0;\n }\n\n // Take a sample to estimate average row size\n const sample = data.slice(0, Math.min(sampleSize, data.length));\n const sampleCSV = convertToCSV(sample);\n const averageRowSize = sampleCSV.length / sample.length;\n\n // Estimate total size (headers + data rows)\n const headers = getCSVHeaders(data);\n const headerSize = headers.join(',').length + 1; // +1 for newline\n\n return Math.ceil(headerSize + averageRowSize * data.length);\n}\n","/**\n * Export Gateway Helper\n *\n * Centralised wrapper around the workspace internal gateway's\n * `createExportJob` mutation, used by per-svc convenience resolvers\n * (e.g. `createTagsExportJob`, `createGroupsExportJob`).\n *\n * Replaces the duplicated `src/clients/export-gateway.ts` files that\n * existed in 19+ workspace svcs.\n *\n * @module export/gateway-client\n *\n * @example\n * ```typescript\n * import { triggerExportJob } from '@burdenoff/be-sdk/export';\n *\n * const result = await triggerExportJob({\n * serviceName: 'wspace-tags-svc',\n * workspaceId: ctx.workspaceId,\n * name: input.name,\n * entityTypes: ['tags', 'vocabularies'],\n * format: input.format,\n * actorId: ctx.actorId,\n * actorType: ctx.actorType,\n * });\n * ```\n */\n\nimport { GatewayClient } from '../gateway/index.js';\nimport type { ServiceLayer } from '../types/layer.js';\n\nconst CREATE_EXPORT_JOB_MUTATION = `mutation CreateExportJob($input: CreateExportJobInput!) {\n createExportJob(input: $input) {\n id\n status\n workspaceId\n entityTypes\n format\n createdAt\n }\n}`;\n\nexport type ExportActorType = 'user' | 'app' | 'service' | 'super_admin';\nexport type ExportFormatGql = 'JSON' | 'CSV';\n\nexport interface TriggerExportJobParams {\n /** Caller service name, used by gateway client telemetry/auth */\n serviceName: string;\n /** Layer for the gateway. Defaults to `wspace`. */\n layer?: ServiceLayer;\n /** Workspace context (required for wspace exports). */\n workspaceId: string;\n /** Human-readable name for the export job. */\n name: string;\n /** Entity types registered in `wspace-export-svc` to include. */\n entityTypes: string[];\n /** Output format. */\n format: ExportFormatGql;\n /** Actor making the request (forwarded to RBAC). */\n actorId: string;\n actorType: ExportActorType;\n /** Whether to include extended metadata in the export ZIP. */\n includeMetadata?: boolean;\n /** Optional ISO date-range bounds. */\n dateRangeStart?: string;\n dateRangeEnd?: string;\n}\n\nexport interface ExportJobResult {\n id: string;\n status: string;\n workspaceId: string;\n entityTypes: string[];\n format: string;\n createdAt: string;\n}\n\ninterface CreateExportJobResponse {\n createExportJob?: ExportJobResult;\n}\n\n/**\n * Submit a `createExportJob` mutation to the workspace internal gateway.\n *\n * The caller is expected to map the returned `ExportJobResult` to its\n * own GraphQL output type (the per-svc `ExportJobResponse`).\n */\nexport async function triggerExportJob(params: TriggerExportJobParams): Promise<ExportJobResult> {\n const {\n serviceName,\n layer = 'wspace',\n actorId,\n actorType,\n workspaceId,\n name,\n entityTypes,\n format,\n includeMetadata,\n dateRangeStart,\n dateRangeEnd,\n } = params;\n\n const client = new GatewayClient({ layer, serviceName });\n\n const input = {\n workspaceId,\n name,\n entityTypes,\n format,\n ...(includeMetadata !== undefined ? { includeMetadata } : {}),\n ...(dateRangeStart !== undefined ? { dateRangeStart } : {}),\n ...(dateRangeEnd !== undefined ? { dateRangeEnd } : {}),\n };\n\n const response = await client.internalQuery<CreateExportJobResponse>({\n query: CREATE_EXPORT_JOB_MUTATION,\n variables: { input },\n headers: {\n 'x-actor-id': actorId,\n 'x-actor-type': actorType,\n 'x-workspace-id': workspaceId,\n },\n });\n\n const job = response.data?.createExportJob;\n if (!job) {\n throw new Error('Export service did not return a job');\n }\n return job;\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ValidationError } from './chunk-
|
|
1
|
+
import { ValidationError } from './chunk-RTQIRGVB.js';
|
|
2
2
|
import { logger } from './chunk-CBZNP6RF.js';
|
|
3
3
|
import { __export, __name } from './chunk-XE4OXN2W.js';
|
|
4
4
|
|
|
@@ -909,5 +909,5 @@ var NotificationsModule = class {
|
|
|
909
909
|
};
|
|
910
910
|
|
|
911
911
|
export { NotificationChannel2 as NotificationChannel, NotificationPriority, NotificationType2 as NotificationType, NotificationsModule, TenantNotificationsModule, tenant_notifications_exports };
|
|
912
|
-
//# sourceMappingURL=chunk-
|
|
913
|
-
//# sourceMappingURL=chunk-
|
|
912
|
+
//# sourceMappingURL=chunk-I43B35CP.js.map
|
|
913
|
+
//# sourceMappingURL=chunk-I43B35CP.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/notifications/tenant-notifications.ts","../src/notifications/index.ts"],"names":["NotificationChannel","NotificationPriority","NotificationType","TenantNotificationsModule","client","context","send","input","validateSendInput","logger","info","channel","type","priority","mutation","variables","recipient","subject","body","htmlBody","data","metadata","scheduledFor","toISOString","expiresAt","trackOpens","trackClicks","response","tenantQuery","notificationId","sendNotification","sendWithTemplate","templateSlug","trim","length","ValidationError","Object","keys","email","userId","channelId","platform","timezone","triggerNotificationWithTemplate","id","status","sendBatch","notifications","count","batchSize","map","n","delayBetweenBatches","batchId","sendBatchNotifications","queued","totalQueued","failed","totalFailed","getNotification","query","notification","getNotifications","filter","startDate","endDate","undefined","limit","offset","getTemplate","slug","locale","notificationTemplate","getTemplates","notificationTemplates","getStats","notificationStats","markAsRead","notificationIds","markAllAsRead","deleteNotifications","deleteAllReadNotifications","phoneNumber","pushToken","NotificationsModule","options","title","message","userIds","userCount","redirectUrl","appName","sms","result","successCount","createNotification","failureCount","errors","sendToUser","debug","search","markMultipleAsRead","markNotificationsAsRead","markAllMyNotificationsAsRead","deleteNotification","deleteMultiple","getUnreadCount","unreadCount","sendChannelNotification","recipients","includeInApp","recipientCount","inAppUserCount","results","Promise","allSettled","forEach","index","value","push","triggerNotification","reason","Error","error","sendTemplateNotification"],"mappings":";;;;;AAAA,IAAA,4BAAA,GAAA;;;;;;;AAcO,IAAKA,mBAAAA,6BAAAA,oBAAAA,EAAAA;;;;;;;;;;;AAAAA,EAAAA,OAAAA,oBAAAA;;AAaL,IAAKC,oBAAAA,6BAAAA,qBAAAA,EAAAA;;;;;AAAAA,EAAAA,OAAAA,qBAAAA;;AAOL,IAAKC,gBAAAA,6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["/**\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 { 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 queued: number;\n processing: 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): Promise<string> {\n // Validate inputs\n this.validateSendInput(input);\n\n logger.info('[TenantNotifications] Sending notification', {\n channel: input.channel,\n type: input.type || NotificationType.TRANSACTIONAL,\n priority: input.priority || NotificationPriority.MEDIUM,\n });\n\n const mutation = `\n mutation SendNotification($input: SendNotificationInput!) {\n sendNotification(input: $input)\n }\n `;\n\n const variables = {\n input: {\n recipient: input.recipient,\n channel: input.channel,\n type: input.type || NotificationType.TRANSACTIONAL,\n priority: input.priority || NotificationPriority.MEDIUM,\n subject: input.subject,\n body: input.body,\n htmlBody: input.htmlBody,\n data: input.data,\n metadata: input.metadata,\n scheduledFor: input.scheduledFor?.toISOString(),\n expiresAt: input.expiresAt?.toISOString(),\n trackOpens: input.trackOpens,\n trackClicks: input.trackClicks,\n },\n };\n\n const response = await this.client.tenantQuery<{\n sendNotification: string;\n }>(mutation, variables, this.context);\n\n logger.info('[TenantNotifications] Notification sent', {\n notificationId: response.sendNotification,\n });\n\n return response.sendNotification;\n }\n\n /**\n * Send notification using a template\n */\n public async sendWithTemplate(input: SendWithTemplateInput): 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 || Object.keys(input.variables).length === 0) {\n throw new ValidationError('Template variables are required');\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 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 id\n status\n deliveryStatus\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: { id: string; status: string; deliveryStatus?: string };\n }>(mutation, variables, this.context);\n\n logger.info('[TenantNotifications] Notification sent with template', {\n notificationId: response.triggerNotificationWithTemplate.id,\n status: response.triggerNotificationWithTemplate.status,\n });\n\n return response.triggerNotificationWithTemplate.id;\n }\n\n /**\n * Send batch notifications\n */\n public async sendBatch(input: BatchNotificationInput): Promise<{\n totalRequested: number;\n totalQueued: number;\n totalFailed: number;\n batchId: string;\n }> {\n if (!input.notifications || input.notifications.length === 0) {\n throw new ValidationError('At least one notification is required');\n }\n\n logger.info('[TenantNotifications] Sending batch notifications', {\n count: input.notifications.length,\n batchSize: input.batchSize,\n });\n\n const mutation = `\n mutation SendBatchNotifications($input: BatchNotificationInput!) {\n sendBatchNotifications(input: $input) {\n totalRequested\n totalQueued\n totalFailed\n batchId\n }\n }\n `;\n\n const variables = {\n input: {\n notifications: input.notifications.map((n) => ({\n recipient: n.recipient,\n channel: n.channel,\n type: n.type || NotificationType.TRANSACTIONAL,\n priority: n.priority || NotificationPriority.MEDIUM,\n subject: n.subject,\n body: n.body,\n htmlBody: n.htmlBody,\n data: n.data,\n metadata: n.metadata,\n scheduledFor: n.scheduledFor?.toISOString(),\n expiresAt: n.expiresAt?.toISOString(),\n trackOpens: n.trackOpens,\n trackClicks: n.trackClicks,\n })),\n batchSize: input.batchSize,\n delayBetweenBatches: input.delayBetweenBatches,\n priority: input.priority,\n },\n };\n\n const response = await this.client.tenantQuery<{\n sendBatchNotifications: {\n totalRequested: number;\n totalQueued: number;\n totalFailed: number;\n batchId: string;\n };\n }>(mutation, variables, this.context);\n\n logger.info('[TenantNotifications] Batch notifications sent', {\n batchId: response.sendBatchNotifications.batchId,\n queued: response.sendBatchNotifications.totalQueued,\n failed: response.sendBatchNotifications.totalFailed,\n });\n\n return response.sendBatchNotifications;\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 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 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: Notification[];\n }>(query, variables, this.context);\n\n return response.notifications;\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 = `\n query GetNotificationTemplates($filter: TemplateFilterInput) {\n notificationTemplates(filter: $filter) {\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 notificationTemplates: NotificationTemplate[];\n }>(query, { filter }, this.context);\n\n return response.notificationTemplates;\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 queued\n processing\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)\n }\n `;\n\n await this.client.tenantQuery(mutation, { notificationIds }, this.context);\n\n logger.info('[TenantNotifications] Notifications marked as read', {\n count: notificationIds.length,\n });\n\n return true;\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\n }\n `;\n\n await this.client.tenantQuery(mutation, {}, this.context);\n\n logger.info('[TenantNotifications] All notifications marked as read');\n\n return true;\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 await this.client.tenantQuery(mutation, { notificationIds }, this.context);\n\n logger.info('[TenantNotifications] Notifications deleted', {\n count: notificationIds.length,\n });\n\n return true;\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 await this.client.tenantQuery(mutation, {}, this.context);\n\n logger.info('[TenantNotifications] All read notifications deleted');\n\n return true;\n }\n\n /**\n * Validate send notification input\n */\n private validateSendInput(input: SendNotificationInput): void {\n if (!input.recipient || (!input.recipient.email && !input.recipient.userId && !input.recipient.phoneNumber)) {\n throw new ValidationError('Recipient email, userId, or phoneNumber is required');\n }\n\n if (!input.channel) {\n throw new ValidationError('Notification channel is required');\n }\n\n if (!input.body || input.body.trim().length === 0) {\n throw new ValidationError('Notification body is required');\n }\n\n // Channel-specific validation\n if (input.channel === NotificationChannel.EMAIL && !input.recipient.email) {\n throw new ValidationError('Recipient email is required for EMAIL channel');\n }\n\n if (input.channel === NotificationChannel.SMS && !input.recipient.phoneNumber) {\n throw new ValidationError('Recipient phone number is required for SMS channel');\n }\n\n if (input.channel === NotificationChannel.PUSH && !input.recipient.pushToken && !input.recipient.userId) {\n throw new ValidationError('Recipient push token or userId is required for PUSH channel');\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 { NotificationPriority, TenantNotificationsModule } 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}\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 * 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\n logger.info('[Notifications] Sending notification', {\n title: options.title,\n userCount: options.userIds.length,\n type: options.type || NotificationType.INFO,\n });\n\n const mutation = `\n mutation CreateNotification($input: CreateNotificationInput!) {\n createNotification(input: $input) {\n successCount\n failureCount\n errors\n notifications {\n id\n }\n }\n }\n `;\n\n const variables = {\n input: {\n title: options.title,\n message: options.message,\n type: options.type || NotificationType.INFO,\n userIds: options.userIds,\n redirectUrl: options.redirectUrl || '',\n appName: options.appName,\n email: options.email || false,\n sms: options.sms || false,\n },\n };\n\n const response = await this.client.query<{\n createNotification: NotificationResponse & { notifications: Array<{ id: string }> };\n }>(mutation, variables, this.context);\n\n const result = {\n successCount: response.createNotification.successCount,\n failureCount: response.createNotification.failureCount,\n errors: response.createNotification.errors,\n notificationIds: response.createNotification.notifications.map((n) => n.id),\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.query(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.query(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.query(\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 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 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: { 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.triggerNotificationWithTemplate.id],\n };\n\n logger.info('[Notifications] Template notification sent', {\n notificationId: response.triggerNotificationWithTemplate.id,\n status: response.triggerNotificationWithTemplate.status,\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"]}
|
|
1
|
+
{"version":3,"sources":["../src/notifications/tenant-notifications.ts","../src/notifications/index.ts"],"names":["NotificationChannel","NotificationPriority","NotificationType","TenantNotificationsModule","client","context","send","input","validateSendInput","logger","info","channel","type","priority","mutation","variables","recipient","subject","body","htmlBody","data","metadata","scheduledFor","toISOString","expiresAt","trackOpens","trackClicks","response","tenantQuery","notificationId","sendNotification","sendWithTemplate","templateSlug","trim","length","ValidationError","Object","keys","email","userId","channelId","platform","timezone","triggerNotificationWithTemplate","id","status","sendBatch","notifications","count","batchSize","map","n","delayBetweenBatches","batchId","sendBatchNotifications","queued","totalQueued","failed","totalFailed","getNotification","query","notification","getNotifications","filter","startDate","endDate","undefined","limit","offset","getTemplate","slug","locale","notificationTemplate","getTemplates","notificationTemplates","getStats","notificationStats","markAsRead","notificationIds","markAllAsRead","deleteNotifications","deleteAllReadNotifications","phoneNumber","pushToken","NotificationsModule","options","title","message","userIds","userCount","redirectUrl","appName","sms","result","successCount","createNotification","failureCount","errors","sendToUser","debug","search","markMultipleAsRead","markNotificationsAsRead","markAllMyNotificationsAsRead","deleteNotification","deleteMultiple","getUnreadCount","unreadCount","sendChannelNotification","recipients","includeInApp","recipientCount","inAppUserCount","results","Promise","allSettled","forEach","index","value","push","triggerNotification","reason","Error","error","sendTemplateNotification"],"mappings":";;;;;AAAA,IAAA,4BAAA,GAAA;;;;;;;AAcO,IAAKA,mBAAAA,6BAAAA,oBAAAA,EAAAA;;;;;;;;;;;AAAAA,EAAAA,OAAAA,oBAAAA;;AAaL,IAAKC,oBAAAA,6BAAAA,qBAAAA,EAAAA;;;;;AAAAA,EAAAA,OAAAA,qBAAAA;;AAOL,IAAKC,gBAAAA,6BAAAA,iBAAAA,EAAAA;;;;;AAAAA,EAAAA,OAAAA,iBAAAA;;AAsIL,IAAMC,4BAAN,MAAMA;EAxKb;;;;;AAyKE,EAAA,WAAA,CACUC,QACAC,OAAAA,EACR;SAFQD,MAAAA,GAAAA,MAAAA;SACAC,OAAAA,GAAAA,OAAAA;AACP,EAAA;;;;AAKH,EAAA,MAAaC,KAAKC,KAAAA,EAA+C;AAE/D,IAAA,IAAA,CAAKC,kBAAkBD,KAAAA,CAAAA;AAEvBE,IAAAA,MAAAA,CAAOC,KAAK,4CAAA,EAA8C;AACxDC,MAAAA,OAAAA,EAASJ,KAAAA,CAAMI,OAAAA;AACfC,MAAAA,IAAAA,EAAML,MAAMK,IAAAA,IAAI,eAAA;AAChBC,MAAAA,QAAAA,EAAUN,MAAMM,QAAAA,IAAQ;KAC1B,CAAA;AAEA,IAAA,MAAMC,QAAAA,GAAW;;;;;AAMjB,IAAA,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RnB,eAAAA,EAAiB;AAACnD,UAAAA,QAAAA,CAASgB,+BAAAA,CAAgCC;;AAC7D,OAAA;AAEAnC,MAAAA,MAAAA,CAAOC,KAAK,4CAAA,EAA8C;AACxDmB,QAAAA,cAAAA,EAAgBF,SAASgB,+BAAAA,CAAgCC,EAAAA;AACzDC,QAAAA,MAAAA,EAAQlB,SAASgB,+BAAAA,CAAgCE;OACnD,CAAA;AAEA,MAAA,OAAOgD,MAAAA;AACT,IAAA,CAAA,CAAA,OAAS8B,KAAAA,EAAO;AACdlH,MAAAA,MAAAA,CAAOkH,MAAM,sDAAA,EAAwD;AAAEA,QAAAA;OAAM,CAAA;AAE7E,MAAA,OAAO;QACL7B,YAAAA,EAAc,CAAA;QACdE,YAAAA,EAAc,CAAA;QACdC,MAAAA,EAAQ;UAAC0B,KAAAA,YAAiBD,KAAAA,GAAQC,MAAMpC,OAAAA,GAAU;;AAClDT,QAAAA,eAAAA,EAAiB;AACnB,OAAA;AACF,IAAA;AACF,EAAA;AACF","file":"chunk-I43B35CP.js","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 { 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 queued: number;\n processing: 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): Promise<string> {\n // Validate inputs\n this.validateSendInput(input);\n\n logger.info('[TenantNotifications] Sending notification', {\n channel: input.channel,\n type: input.type || NotificationType.TRANSACTIONAL,\n priority: input.priority || NotificationPriority.MEDIUM,\n });\n\n const mutation = `\n mutation SendNotification($input: SendNotificationInput!) {\n sendNotification(input: $input)\n }\n `;\n\n const variables = {\n input: {\n recipient: input.recipient,\n channel: input.channel,\n type: input.type || NotificationType.TRANSACTIONAL,\n priority: input.priority || NotificationPriority.MEDIUM,\n subject: input.subject,\n body: input.body,\n htmlBody: input.htmlBody,\n data: input.data,\n metadata: input.metadata,\n scheduledFor: input.scheduledFor?.toISOString(),\n expiresAt: input.expiresAt?.toISOString(),\n trackOpens: input.trackOpens,\n trackClicks: input.trackClicks,\n },\n };\n\n const response = await this.client.tenantQuery<{\n sendNotification: string;\n }>(mutation, variables, this.context);\n\n logger.info('[TenantNotifications] Notification sent', {\n notificationId: response.sendNotification,\n });\n\n return response.sendNotification;\n }\n\n /**\n * Send notification using a template\n */\n public async sendWithTemplate(input: SendWithTemplateInput): 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 || Object.keys(input.variables).length === 0) {\n throw new ValidationError('Template variables are required');\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 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 id\n status\n deliveryStatus\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: { id: string; status: string; deliveryStatus?: string };\n }>(mutation, variables, this.context);\n\n logger.info('[TenantNotifications] Notification sent with template', {\n notificationId: response.triggerNotificationWithTemplate.id,\n status: response.triggerNotificationWithTemplate.status,\n });\n\n return response.triggerNotificationWithTemplate.id;\n }\n\n /**\n * Send batch notifications\n */\n public async sendBatch(input: BatchNotificationInput): Promise<{\n totalRequested: number;\n totalQueued: number;\n totalFailed: number;\n batchId: string;\n }> {\n if (!input.notifications || input.notifications.length === 0) {\n throw new ValidationError('At least one notification is required');\n }\n\n logger.info('[TenantNotifications] Sending batch notifications', {\n count: input.notifications.length,\n batchSize: input.batchSize,\n });\n\n const mutation = `\n mutation SendBatchNotifications($input: BatchNotificationInput!) {\n sendBatchNotifications(input: $input) {\n totalRequested\n totalQueued\n totalFailed\n batchId\n }\n }\n `;\n\n const variables = {\n input: {\n notifications: input.notifications.map((n) => ({\n recipient: n.recipient,\n channel: n.channel,\n type: n.type || NotificationType.TRANSACTIONAL,\n priority: n.priority || NotificationPriority.MEDIUM,\n subject: n.subject,\n body: n.body,\n htmlBody: n.htmlBody,\n data: n.data,\n metadata: n.metadata,\n scheduledFor: n.scheduledFor?.toISOString(),\n expiresAt: n.expiresAt?.toISOString(),\n trackOpens: n.trackOpens,\n trackClicks: n.trackClicks,\n })),\n batchSize: input.batchSize,\n delayBetweenBatches: input.delayBetweenBatches,\n priority: input.priority,\n },\n };\n\n const response = await this.client.tenantQuery<{\n sendBatchNotifications: {\n totalRequested: number;\n totalQueued: number;\n totalFailed: number;\n batchId: string;\n };\n }>(mutation, variables, this.context);\n\n logger.info('[TenantNotifications] Batch notifications sent', {\n batchId: response.sendBatchNotifications.batchId,\n queued: response.sendBatchNotifications.totalQueued,\n failed: response.sendBatchNotifications.totalFailed,\n });\n\n return response.sendBatchNotifications;\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 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 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: Notification[];\n }>(query, variables, this.context);\n\n return response.notifications;\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 = `\n query GetNotificationTemplates($filter: TemplateFilterInput) {\n notificationTemplates(filter: $filter) {\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 notificationTemplates: NotificationTemplate[];\n }>(query, { filter }, this.context);\n\n return response.notificationTemplates;\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 queued\n processing\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)\n }\n `;\n\n await this.client.tenantQuery(mutation, { notificationIds }, this.context);\n\n logger.info('[TenantNotifications] Notifications marked as read', {\n count: notificationIds.length,\n });\n\n return true;\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\n }\n `;\n\n await this.client.tenantQuery(mutation, {}, this.context);\n\n logger.info('[TenantNotifications] All notifications marked as read');\n\n return true;\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 await this.client.tenantQuery(mutation, { notificationIds }, this.context);\n\n logger.info('[TenantNotifications] Notifications deleted', {\n count: notificationIds.length,\n });\n\n return true;\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 await this.client.tenantQuery(mutation, {}, this.context);\n\n logger.info('[TenantNotifications] All read notifications deleted');\n\n return true;\n }\n\n /**\n * Validate send notification input\n */\n private validateSendInput(input: SendNotificationInput): void {\n if (!input.recipient || (!input.recipient.email && !input.recipient.userId && !input.recipient.phoneNumber)) {\n throw new ValidationError('Recipient email, userId, or phoneNumber is required');\n }\n\n if (!input.channel) {\n throw new ValidationError('Notification channel is required');\n }\n\n if (!input.body || input.body.trim().length === 0) {\n throw new ValidationError('Notification body is required');\n }\n\n // Channel-specific validation\n if (input.channel === NotificationChannel.EMAIL && !input.recipient.email) {\n throw new ValidationError('Recipient email is required for EMAIL channel');\n }\n\n if (input.channel === NotificationChannel.SMS && !input.recipient.phoneNumber) {\n throw new ValidationError('Recipient phone number is required for SMS channel');\n }\n\n if (input.channel === NotificationChannel.PUSH && !input.recipient.pushToken && !input.recipient.userId) {\n throw new ValidationError('Recipient push token or userId is required for PUSH channel');\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 { NotificationPriority, TenantNotificationsModule } 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}\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 * 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\n logger.info('[Notifications] Sending notification', {\n title: options.title,\n userCount: options.userIds.length,\n type: options.type || NotificationType.INFO,\n });\n\n const mutation = `\n mutation CreateNotification($input: CreateNotificationInput!) {\n createNotification(input: $input) {\n successCount\n failureCount\n errors\n notifications {\n id\n }\n }\n }\n `;\n\n const variables = {\n input: {\n title: options.title,\n message: options.message,\n type: options.type || NotificationType.INFO,\n userIds: options.userIds,\n redirectUrl: options.redirectUrl || '',\n appName: options.appName,\n email: options.email || false,\n sms: options.sms || false,\n },\n };\n\n const response = await this.client.query<{\n createNotification: NotificationResponse & { notifications: Array<{ id: string }> };\n }>(mutation, variables, this.context);\n\n const result = {\n successCount: response.createNotification.successCount,\n failureCount: response.createNotification.failureCount,\n errors: response.createNotification.errors,\n notificationIds: response.createNotification.notifications.map((n) => n.id),\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.query(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.query(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.query(\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 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 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: { 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.triggerNotificationWithTemplate.id],\n };\n\n logger.info('[Notifications] Template notification sent', {\n notificationId: response.triggerNotificationWithTemplate.id,\n status: response.triggerNotificationWithTemplate.status,\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"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { EventQueueFactory } from './chunk-
|
|
1
|
+
import { EventQueueFactory } from './chunk-R7Y5I4NN.js';
|
|
2
2
|
import { logger } from './chunk-CBZNP6RF.js';
|
|
3
3
|
import { __name } from './chunk-XE4OXN2W.js';
|
|
4
4
|
import { randomUUID } from 'crypto';
|
|
@@ -609,5 +609,5 @@ async function resetGraphEventEmitter() {
|
|
|
609
609
|
__name(resetGraphEventEmitter, "resetGraphEventEmitter");
|
|
610
610
|
|
|
611
611
|
export { MemoryEventBus, MemoryEventConsumer, MemoryEventPublisher, MemoryEventQueue, NatsGraphEventEmitter, createGraphEventEmitter, createGraphEventEmitter2, createMemoryConsumer, createMemoryPublisher, getGraphEventEmitter, resetGraphEventEmitter };
|
|
612
|
-
//# sourceMappingURL=chunk-
|
|
613
|
-
//# sourceMappingURL=chunk-
|
|
612
|
+
//# sourceMappingURL=chunk-MLFKAPWK.js.map
|
|
613
|
+
//# sourceMappingURL=chunk-MLFKAPWK.js.map
|