@burdenoff/be-sdk 2026.1130.2 → 2026.1201.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +6 -1
  2. package/dist/context/index.js +7 -2
  3. package/dist/context/index.js.map +1 -1
  4. package/dist/files/index.d.ts +2 -2
  5. package/dist/files/index.js +2 -2
  6. package/dist/{files-h5U-D2AF.js → files-BISdM0fh.js} +188 -28
  7. package/dist/files-BISdM0fh.js.map +1 -0
  8. package/dist/{bun-runtime-metrics-CPy5D6NT.js → incoming-request-span-DCou42Il.js} +56 -2
  9. package/dist/incoming-request-span-DCou42Il.js.map +1 -0
  10. package/dist/{index-CIgoeobA.d.ts → index-Bnz5Bqtl.d.ts} +14 -3
  11. package/dist/{index-8pUSoT85.d.ts → index-ieSQpD9r.d.ts} +26 -3
  12. package/dist/index.d.ts +2 -2
  13. package/dist/index.js +4 -4
  14. package/dist/prisma/index.js +2 -2
  15. package/dist/{prisma-Bo-C0XUv.js → prisma-D0f-THMv.js} +2 -2
  16. package/dist/{prisma-Bo-C0XUv.js.map → prisma-D0f-THMv.js.map} +1 -1
  17. package/dist/{sdk-7TBR987n.js → sdk-Oooulm2n.js} +22 -6
  18. package/dist/sdk-Oooulm2n.js.map +1 -0
  19. package/dist/server/index.js +5 -5
  20. package/dist/server/index.js.map +1 -1
  21. package/dist/{stub-DNkzpQvR.js → stub-CmVOE6ql.js} +2 -2
  22. package/dist/{stub-DNkzpQvR.js.map → stub-CmVOE6ql.js.map} +1 -1
  23. package/dist/telemetry/index.d.ts +40 -2
  24. package/dist/telemetry/index.js +3 -3
  25. package/dist/telemetry/index.js.map +1 -1
  26. package/dist/tracker/index.js +2 -2
  27. package/dist/{tracker-CDVYIoCb.js → tracker-CNF8TRpk.js} +2 -2
  28. package/dist/{tracker-CDVYIoCb.js.map → tracker-CNF8TRpk.js.map} +1 -1
  29. package/dist/validation/index.d.ts +2 -2
  30. package/dist/validation/index.js +2 -2
  31. package/dist/{validation-CPUITdMk.js → validation-bwJzOytZ.js} +66 -97
  32. package/dist/{validation-CPUITdMk.js.map → validation-bwJzOytZ.js.map} +1 -1
  33. package/dist/{workspace-extension-BcMPoGWr.js → workspace-extension-feJYFO9e.js} +41 -8
  34. package/dist/workspace-extension-feJYFO9e.js.map +1 -0
  35. package/package.json +1 -1
  36. package/dist/bun-runtime-metrics-CPy5D6NT.js.map +0 -1
  37. package/dist/files-h5U-D2AF.js.map +0 -1
  38. package/dist/sdk-7TBR987n.js.map +0 -1
  39. package/dist/workspace-extension-BcMPoGWr.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"tracker-CDVYIoCb.js","names":[],"sources":["../src/tracker/agent-activity.ts","../src/tracker/index.ts"],"sourcesContent":["/**\n * AI-agent activity (BOFF-9684)\n *\n * Platform-wide activity actions for what an AI agent does, and a helper that records them with\n * the agent as an `app` actor. The audit trail can then separate agent actions from the human\n * actions around them (ISO/IEC 42001 Annex A.9 evidence) and link each one back to the person\n * who started the run (`onBehalfOf`).\n *\n * The action names follow the platform taxonomy `<domain>.<resource>.<verb>` and are shared by\n * every product that runs agents; the product is identified by `productId`.\n *\n * @example\n * ```ts\n * import { AGENT_ACTIVITY_ACTIONS, trackAgentActivity } from '@burdenoff/be-sdk/tracker';\n *\n * await trackAgentActivity({\n * action: AGENT_ACTIVITY_ACTIONS.TOOL_CALLED,\n * agentId: agent.id,\n * workspaceId,\n * onBehalfOf: userId,\n * productId: 'botmanor',\n * metadata: { toolName: 'search' },\n * });\n * ```\n *\n * @module tracker/agent-activity\n * @category Tracking\n */\nimport { createExplicitActivityScope, runInExplicitActivityScope } from '../activity/explicit-activity-scope.js';\nimport { trackOperation } from './stub.js';\n\n/** Activity actions for AI-agent behaviour. */\nexport const AGENT_ACTIVITY_ACTIONS = Object.freeze({\n /** An agent run (one turn) finished and produced a response. */\n RUN_COMPLETED: 'agent.run.completed',\n /** An agent run failed before producing a response. */\n RUN_FAILED: 'agent.run.failed',\n /** The agent called a tool (MCP or similar). `success: false` when the call failed. */\n TOOL_CALLED: 'agent.tool.called',\n /** The agent delegated a sub-task to another agent. */\n DELEGATION_SENT: 'agent.delegation.sent',\n /** A governance policy refused something the agent run attempted (input, output, tool, model, budget, rate). */\n POLICY_BLOCKED: 'agent.policy.blocked',\n} as const);\n\nexport type AgentActivityAction = (typeof AGENT_ACTIVITY_ACTIONS)[keyof typeof AGENT_ACTIVITY_ACTIONS];\n\n/** Default `resourceType` of agent activity rows; `resourceId` defaults to the agent id. */\nexport const AGENT_ACTIVITY_RESOURCE_TYPE = 'agent';\n\nconst FAILURE_ACTIONS: ReadonlySet<AgentActivityAction> = new Set<AgentActivityAction>([\n AGENT_ACTIVITY_ACTIONS.RUN_FAILED,\n AGENT_ACTIVITY_ACTIONS.POLICY_BLOCKED,\n]);\n\nexport interface AgentActivityOptions {\n action: AgentActivityAction;\n /** The agent that acted. Recorded as the row's actor (`userId`) with `actorType: 'app'`. */\n agentId: string;\n workspaceId: string;\n /** The human who started the run, when there is one. */\n onBehalfOf?: string;\n /** Product that runs the agent, e.g. `botmanor`. */\n productId?: string;\n /** Defaults to false for RUN_FAILED and POLICY_BLOCKED, true otherwise. */\n success?: boolean;\n errorMessage?: string;\n description?: string;\n /** Defaults to `AGENT_ACTIVITY_RESOURCE_TYPE`. */\n resourceType?: string;\n /** Defaults to `agentId`. */\n resourceId?: string;\n metadata?: Record<string, unknown>;\n /** Stable idempotency key, only for callers that may replay the same event. */\n dedupeKey?: string;\n}\n\n/**\n * Record one AI-agent activity row, attributed to the agent as an `app` actor.\n *\n * Fire-and-forget like `trackOperation`: it never throws for a delivery failure and never blocks\n * on the activity service. It runs in its own explicit-activity scope, so recording what the\n * agent did does not suppress the mutation-audit row of the human request that started the run.\n */\nexport function trackAgentActivity(options: AgentActivityOptions): Promise<boolean> {\n const success = options.success ?? !FAILURE_ACTIONS.has(options.action);\n return runInExplicitActivityScope(createExplicitActivityScope(), () =>\n trackOperation({\n operationName: options.action,\n userId: options.agentId,\n actorType: 'app',\n ...(options.onBehalfOf ? { onBehalfOf: options.onBehalfOf } : {}),\n workspaceId: options.workspaceId,\n ...(options.productId ? { productId: options.productId } : {}),\n success,\n ...(options.errorMessage ? { errorMessage: options.errorMessage } : {}),\n activityOptions: {\n enabled: true,\n activityType: options.action,\n description: options.description ?? `Agent ${options.agentId}: ${options.action}`,\n workspaceId: options.workspaceId,\n resourceType: options.resourceType ?? AGENT_ACTIVITY_RESOURCE_TYPE,\n resourceId: options.resourceId ?? options.agentId,\n metadata: { ...options.metadata, agentId: options.agentId },\n ...(options.dedupeKey ? { dedupeKey: options.dedupeKey } : {}),\n },\n })\n );\n}\n","/**\n * Unified Tracker Module\n * Aggregates RBAC + Activity + Usage + Notifications in single function call\n * This is the MOST IMPORTANT module that products should use for most operations\n */\n\nimport type { BurdenoffGraphQLClient } from '../client/graphql.js';\nimport type { SDKContext } from '../types/index.js';\nimport { PermissionDeniedError, QuotaExceededError, ValidationError } from '../types/index.js';\nimport { logger } from '../logger/index.js';\nimport { RBACModule, type CheckPermissionOptions } from '../rbac/index.js';\nimport { ActivityModule, ActivityType, ActivityStatus, ActivitySeverity } from '../activity/index.js';\nimport { UsageModule, type UsageMetricType } from '../usage/index.js';\nimport { NotificationsModule, NotificationType } from '../notifications/index.js';\n\nexport interface TrackOptions {\n /** User performing the action */\n userId: string;\n /** Action being performed */\n action: string;\n /** Resource type */\n resourceType: string;\n /** Optional resource ID */\n resourceId?: string;\n /** Workspace context */\n workspaceId?: string;\n /** Organization context */\n organizationId?: string;\n /** Project context */\n projectId?: string;\n\n /** RBAC options */\n rbac?: {\n /** Check permission before executing (default: true) */\n enabled?: boolean;\n /** Custom permission action (defaults to action parameter) */\n permissionAction?: string;\n };\n\n /** Activity tracking options */\n activity?: {\n /** Enable activity tracking (default: true) */\n enabled?: boolean;\n /** Activity type (auto-inferred if not provided) */\n activityType?: ActivityType;\n /** Additional metadata */\n metadata?: Record<string, unknown>;\n /** IP address */\n ipAddress?: string;\n /** User agent */\n userAgent?: string;\n /** Severity level */\n severity?: ActivitySeverity;\n };\n\n /**\n * Usage tracking options.\n *\n * The tracker meters a workspace quota only when `quotaName` is set: it checks capacity\n * with the owner's `checkWorkspaceQuota` (for positive amounts) and records the amount\n * with `trackUsage`. Without a `quotaName` the usage step is skipped. Mutations whose\n * schema carries a gateway `@usage` directive are already metered by the gateway and\n * should not set `quotaName` here, or the quota is charged twice.\n */\n usage?: {\n /** Enable usage tracking (default: true) */\n enabled?: boolean;\n /** Workspace quota to charge, for example `platform.projects.created`. */\n quotaName?: string;\n /** Product that owns the quota. Defaults to the SDK context's `productId`. */\n productId?: string;\n /** Description stored on the usage record. Defaults to `<action> <resourceType>`. */\n description?: string;\n /**\n * Amount to record (default: 1). A negative amount releases usage, for example on\n * delete; the quota check is skipped for it.\n */\n amount?: number;\n /** Check quota before recording a positive amount (default: true) */\n checkQuota?: boolean;\n /**\n * Legacy metric name. The workspace usage owner has no metric types, so a metric type\n * without a `quotaName` is not metered by the tracker.\n */\n metricType?: UsageMetricType;\n /** Legacy entity type. Workspace quotas are always charged to the workspace. */\n entityType?: 'user' | 'workspace' | 'organization';\n };\n\n /** Notification options */\n notification?: {\n /** Send notification on success */\n onSuccess?: {\n title: string;\n message: string;\n type?: NotificationType;\n /** Additional user IDs to notify */\n additionalUserIds?: string[];\n };\n /** Send notification on failure */\n onFailure?: {\n title: string;\n message: string;\n type?: NotificationType;\n /** Additional user IDs to notify */\n additionalUserIds?: string[];\n };\n };\n}\n\n/** A usage step that meters a named workspace quota. */\ninterface ResolvedUsage {\n quotaName: string;\n amount: number;\n workspaceId: string;\n checkQuota: boolean;\n}\n\nexport interface TrackResult {\n success: boolean;\n /** Permission check result */\n permissionGranted: boolean;\n /** Quota check result (if quota checking enabled) */\n quotaAvailable?: boolean;\n quotaRemaining?: number;\n /** Activity record ID */\n activityId?: string;\n /** True when the usage step recorded the amount with the owner */\n usageTracked?: boolean;\n /**\n * @deprecated The owner's `trackUsage` returns `Boolean!` and no record id, so this is\n * never set. Read `usageTracked` instead.\n */\n usageRecordId?: string;\n /** Notification IDs sent */\n notificationIds?: string[];\n /** Error if operation failed */\n error?: {\n type: 'permission' | 'quota' | 'validation' | 'unknown';\n message: string;\n details?: Record<string, unknown>;\n };\n /** Operation duration in milliseconds */\n duration: number;\n}\n\n/**\n * Unified Tracker Module\n *\n * The primary module products should use for tracking operations.\n * Automatically handles RBAC checks, activity logging, usage tracking, and notifications.\n *\n * @example\n * ```typescript\n * const result = await sdk.tracker.track({\n * userId: 'user123',\n * action: 'create_project',\n * resourceType: 'project',\n * workspaceId: 'ws123',\n * usage: {\n * quotaName: 'myproduct.projects.count',\n * productId: 'myproduct',\n * amount: 1,\n * checkQuota: true,\n * },\n * notification: {\n * onSuccess: {\n * title: 'Project Created',\n * message: 'Your project has been created successfully',\n * },\n * },\n * });\n *\n * if (!result.success) {\n * // Handle error\n * }\n * ```\n */\nexport class TrackerModule {\n private rbac: RBACModule;\n private activity: ActivityModule;\n private usage: UsageModule;\n private notifications: NotificationsModule;\n\n constructor(\n client: BurdenoffGraphQLClient,\n private context: SDKContext = {}\n ) {\n this.rbac = new RBACModule(client, context);\n this.activity = new ActivityModule(client, context);\n this.usage = new UsageModule(client, context);\n this.notifications = new NotificationsModule(client, context);\n }\n\n /**\n * Track operation with RBAC, Activity, Usage, and Notifications\n * This is the primary method products should use\n */\n public async track(options: TrackOptions): Promise<TrackResult> {\n const startTime = Date.now();\n const result: TrackResult = {\n success: false,\n permissionGranted: false,\n duration: 0,\n };\n\n try {\n // Validate required fields\n this.validateOptions(options);\n\n // Step 1: Check RBAC permission (if enabled)\n if (options.rbac?.enabled !== false) {\n await this.checkPermission(options, result);\n if (!result.permissionGranted) {\n result.duration = Date.now() - startTime;\n await this.logFailedActivity(options, result, startTime);\n return result;\n }\n } else {\n result.permissionGranted = true;\n }\n\n // Steps 2 and 3: check quota, then record usage (only for a named workspace quota)\n const usage = this.resolveUsage(options);\n if (usage) {\n let quotaAssignmentId: string | undefined;\n if (usage.checkQuota) {\n quotaAssignmentId = await this.checkQuota(options, usage, result);\n if (result.quotaAvailable === false) {\n result.duration = Date.now() - startTime;\n await this.logFailedActivity(options, result, startTime);\n return result;\n }\n }\n await this.trackUsage(options, usage, quotaAssignmentId, result);\n }\n\n // Step 4: Log successful activity (if enabled)\n if (options.activity?.enabled !== false) {\n await this.logSuccessActivity(options, result, startTime);\n }\n\n // Step 5: Send success notification (if configured)\n if (options.notification?.onSuccess) {\n await this.sendSuccessNotification(options, result);\n }\n\n result.success = true;\n result.duration = Date.now() - startTime;\n\n logger.info('[Tracker] Operation tracked successfully', {\n action: options.action,\n duration: result.duration,\n });\n\n return result;\n } catch (error) {\n result.duration = Date.now() - startTime;\n result.success = false;\n\n // Categorize error\n if (error instanceof PermissionDeniedError) {\n result.error = {\n type: 'permission',\n message: error.message,\n details: error.details,\n };\n } else if (error instanceof QuotaExceededError) {\n result.error = {\n type: 'quota',\n message: error.message,\n details: error.details,\n };\n } else if (error instanceof ValidationError) {\n result.error = {\n type: 'validation',\n message: error.message,\n details: error.details,\n };\n } else {\n result.error = {\n type: 'unknown',\n message: error instanceof Error ? error.message : 'Unknown error',\n };\n }\n\n // Log failed activity\n await this.logFailedActivity(options, result, startTime);\n\n // Send failure notification (if configured)\n if (options.notification?.onFailure) {\n await this.sendFailureNotification(options, result);\n }\n\n logger.error('[Tracker] Operation tracking failed', {\n action: options.action,\n error: result.error,\n duration: result.duration,\n });\n\n return result;\n }\n }\n\n /**\n * Track operation and throw on failure\n * Convenience method that throws errors instead of returning them in result\n */\n public async trackOrThrow(options: TrackOptions): Promise<TrackResult> {\n const result = await this.track(options);\n\n if (!result.success && result.error) {\n const errorMessage = result.error.message;\n const errorDetails = result.error.details;\n\n switch (result.error.type) {\n case 'permission':\n throw new PermissionDeniedError(errorMessage, errorDetails);\n case 'quota':\n throw new QuotaExceededError(errorMessage, errorDetails);\n case 'validation':\n throw new ValidationError(errorMessage, errorDetails);\n default:\n throw new Error(errorMessage);\n }\n }\n\n return result;\n }\n\n /**\n * Simplified track method for common operations.\n * The trailing metric type is accepted for source compatibility and is not metered.\n */\n public async trackSimple(\n userId: string,\n action: string,\n resourceType: string,\n resourceId?: string,\n _metricType?: UsageMetricType\n ): Promise<boolean> {\n // A metric type has no workspace quota on the owner, so trackSimple never meters usage.\n // Call track() with `usage.quotaName` to charge a quota.\n const result = await this.track({\n userId,\n action,\n resourceType,\n resourceId,\n workspaceId: this.context.workspaceId,\n usage: { enabled: false },\n });\n\n return result.success;\n }\n\n /**\n * Validate tracking options\n */\n private validateOptions(options: TrackOptions): void {\n if (!options.userId) {\n throw new ValidationError('User ID is required');\n }\n\n if (!options.action) {\n throw new ValidationError('Action is required');\n }\n\n if (!options.resourceType) {\n throw new ValidationError('Resource type is required');\n }\n }\n\n /**\n * Check RBAC permission\n */\n private async checkPermission(options: TrackOptions, result: TrackResult): Promise<void> {\n const permissionOptions: CheckPermissionOptions = {\n userId: options.userId,\n action: options.rbac?.permissionAction || options.action,\n resourceType: options.resourceType,\n resourceId: options.resourceId,\n workspaceId: options.workspaceId,\n };\n\n const hasPermission = await this.rbac.checkPermission(permissionOptions);\n result.permissionGranted = hasPermission;\n\n if (!hasPermission) {\n result.error = {\n type: 'permission',\n message: 'Permission denied',\n details: permissionOptions as unknown as Record<string, unknown>,\n };\n }\n }\n\n /**\n * Resolve the usage step for an operation, or null when nothing is metered: usage is\n * disabled, or no workspace quota is named (a legacy `metricType` alone has no owner\n * quota to charge).\n */\n private resolveUsage(options: TrackOptions): ResolvedUsage | null {\n const usage = options.usage;\n if (!usage || usage.enabled === false) {\n return null;\n }\n const quotaName = usage.quotaName?.trim();\n if (!quotaName) {\n if (usage.metricType) {\n logger.debug('[Tracker] Usage step skipped: no quotaName for legacy metricType', {\n action: options.action,\n metricType: usage.metricType,\n });\n }\n return null;\n }\n const amount = usage.amount ?? 1;\n if (typeof amount !== 'number' || !Number.isFinite(amount) || amount === 0) {\n throw new ValidationError('Usage amount must be a finite, non-zero number');\n }\n const workspaceId = options.workspaceId ?? this.context.workspaceId;\n if (!workspaceId) {\n throw new ValidationError('Workspace ID is required to track workspace quota usage');\n }\n return {\n quotaName,\n amount,\n workspaceId,\n // Only consumption is gated; a release (negative amount) must always go through.\n checkQuota: usage.checkQuota !== false && amount > 0,\n };\n }\n\n /**\n * Check workspace quota capacity. Returns the assignment to charge when one exists.\n */\n private async checkQuota(\n options: TrackOptions,\n usage: ResolvedUsage,\n result: TrackResult\n ): Promise<string | undefined> {\n const quotaCheck = await this.usage.checkWorkspaceQuota({\n quotaName: usage.quotaName,\n amount: usage.amount,\n workspaceId: usage.workspaceId,\n userId: options.userId,\n });\n\n result.quotaAvailable = quotaCheck.allowed;\n result.quotaRemaining = quotaCheck.limitLeft ?? undefined;\n\n if (!quotaCheck.allowed) {\n const notProvisioned = quotaCheck.assignmentId === null;\n result.error = {\n type: 'quota',\n message: notProvisioned\n ? `Quota ${usage.quotaName} is not included in this workspace's plan`\n : 'Quota exceeded',\n details: {\n quotaName: usage.quotaName,\n requestedAmount: usage.amount,\n limitLeft: quotaCheck.limitLeft,\n notProvisioned,\n },\n };\n }\n\n return quotaCheck.assignmentId ?? undefined;\n }\n\n /**\n * Record workspace quota usage with the owner.\n */\n private async trackUsage(\n options: TrackOptions,\n usage: ResolvedUsage,\n quotaAssignmentId: string | undefined,\n result: TrackResult\n ): Promise<void> {\n result.usageTracked = await this.usage.trackUsage({\n quotaName: usage.quotaName,\n productId: options.usage?.productId,\n amount: usage.amount,\n description: options.usage?.description?.trim() || `${options.action} ${options.resourceType}`,\n workspaceId: usage.workspaceId,\n userId: options.userId,\n quotaAssignmentId,\n metadata: {\n action: options.action,\n resourceType: options.resourceType,\n ...(options.resourceId ? { resourceId: options.resourceId } : {}),\n },\n });\n }\n\n /**\n * Log successful activity\n */\n private async logSuccessActivity(options: TrackOptions, result: TrackResult, startTime: number): Promise<void> {\n const activityRecord = await this.activity.log({\n userId: options.userId,\n activityType: options.activity?.activityType || this.inferActivityType(options.action),\n resourceType: options.resourceType,\n resourceId: options.resourceId,\n action: options.action,\n status: ActivityStatus.SUCCESS,\n workspaceId: options.workspaceId,\n organizationId: options.organizationId,\n projectId: options.projectId,\n ipAddress: options.activity?.ipAddress,\n userAgent: options.activity?.userAgent,\n metadata: options.activity?.metadata,\n severity: options.activity?.severity || ActivitySeverity.LOW,\n duration: Date.now() - startTime,\n });\n\n result.activityId = activityRecord.id;\n }\n\n /**\n * Log failed activity\n */\n private async logFailedActivity(options: TrackOptions, result: TrackResult, startTime: number): Promise<void> {\n if (options.activity?.enabled === false) {\n return;\n }\n\n try {\n const activityRecord = await this.activity.log({\n userId: options.userId,\n activityType: options.activity?.activityType || this.inferActivityType(options.action),\n resourceType: options.resourceType,\n resourceId: options.resourceId,\n action: options.action,\n status: ActivityStatus.FAILURE,\n workspaceId: options.workspaceId,\n organizationId: options.organizationId,\n projectId: options.projectId,\n ipAddress: options.activity?.ipAddress,\n userAgent: options.activity?.userAgent,\n metadata: options.activity?.metadata,\n severity: ActivitySeverity.HIGH,\n errorMessage: result.error?.message,\n duration: Date.now() - startTime,\n });\n\n result.activityId = activityRecord.id;\n } catch (error) {\n logger.error('[Tracker] Failed to log activity', { error });\n }\n }\n\n /**\n * Send success notification\n */\n private async sendSuccessNotification(options: TrackOptions, result: TrackResult): Promise<void> {\n if (!options.notification?.onSuccess) {\n return;\n }\n\n try {\n const userIds = [options.userId, ...(options.notification.onSuccess.additionalUserIds || [])];\n\n const response = await this.notifications.send({\n title: options.notification.onSuccess.title,\n message: options.notification.onSuccess.message,\n type: options.notification.onSuccess.type || NotificationType.SUCCESS,\n userIds,\n });\n\n result.notificationIds = response.notificationIds;\n } catch (error) {\n logger.error('[Tracker] Failed to send success notification', { error });\n }\n }\n\n /**\n * Send failure notification\n */\n private async sendFailureNotification(options: TrackOptions, result: TrackResult): Promise<void> {\n if (!options.notification?.onFailure) {\n return;\n }\n\n try {\n const userIds = [options.userId, ...(options.notification.onFailure.additionalUserIds || [])];\n\n const response = await this.notifications.send({\n title: options.notification.onFailure.title,\n message: options.notification.onFailure.message,\n type: options.notification.onFailure.type || NotificationType.ERROR,\n userIds,\n });\n\n result.notificationIds = response.notificationIds;\n } catch (error) {\n logger.error('[Tracker] Failed to send failure notification', { error });\n }\n }\n\n /**\n * Infer activity type from action\n */\n private inferActivityType(action: string): ActivityType {\n const actionLower = action.toLowerCase();\n\n if (actionLower.includes('create') || actionLower.includes('add')) return ActivityType.CREATE;\n if (actionLower.includes('update') || actionLower.includes('edit')) return ActivityType.UPDATE;\n if (actionLower.includes('delete') || actionLower.includes('remove')) return ActivityType.DELETE;\n if (actionLower.includes('read') || actionLower.includes('view')) return ActivityType.READ;\n if (actionLower.includes('login')) return ActivityType.LOGIN;\n if (actionLower.includes('logout')) return ActivityType.LOGOUT;\n if (actionLower.includes('export')) return ActivityType.EXPORT;\n if (actionLower.includes('import')) return ActivityType.IMPORT;\n if (actionLower.includes('share')) return ActivityType.SHARE;\n if (actionLower.includes('download')) return ActivityType.DOWNLOAD;\n if (actionLower.includes('upload')) return ActivityType.UPLOAD;\n\n return ActivityType.CUSTOM;\n }\n\n /**\n * Batch track multiple operations\n */\n public async trackBatch(operations: TrackOptions[]): Promise<TrackResult[]> {\n logger.debug('[Tracker] Batch tracking operations', { count: operations.length });\n\n const results = await Promise.all(operations.map((op) => this.track(op)));\n\n logger.info('[Tracker] Batch tracking completed', {\n total: results.length,\n successful: results.filter((r) => r.success).length,\n failed: results.filter((r) => !r.success).length,\n });\n\n return results;\n }\n}\n\n// Export stub implementation for services that don't need full tracking\nexport {\n trackOperation,\n createProductTracker,\n UnifiedTrackerStub,\n trackerStub,\n UNIFIED_TRACKER_CONSTANTS,\n} from './stub.js';\nexport { isTrackedActorType, resolveAssistantSession } from './stub.js';\n// Assistant-session attribution on activity rows (BOFF-9649)\nexport { AI_ASSISTANT_ACTOR_ORIGIN } from '../activity/assistant-session.js';\nexport type { ActorOrigin, AssistantSessionAttribution } from '../activity/assistant-session.js';\nexport type {\n TrackingEvent,\n RbacCheckOptions,\n UsageTrackingOptions,\n ActivityTrackingOptions,\n UnifiedTrackingOptions,\n ProductTracker,\n TrackedActorType,\n} from './stub.js';\n\n// AI-agent activity actions and recorder (BOFF-9684)\nexport { AGENT_ACTIVITY_ACTIONS, AGENT_ACTIVITY_RESOURCE_TYPE, trackAgentActivity } from './agent-activity.js';\nexport type { AgentActivityAction, AgentActivityOptions } from './agent-activity.js';\n\n// Opt a resolver out of the mutation-audit backstop row (see server/mutation-audit.ts)\nexport { suppressMutationAudit } from '../activity/explicit-activity-scope.js';\n\n// Re-export UsageMetricType from usage module for convenience\nexport { UsageMetricType } from '../usage/index.js';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,MAAa,yBAAyB,OAAO,OAAO;;CAElD,eAAe;;CAEf,YAAY;;CAEZ,aAAa;;CAEb,iBAAiB;;CAEjB,gBAAgB;AAClB,CAAU;;AAKV,MAAa,+BAA+B;AAE5C,MAAM,kCAAoD,IAAI,IAAyB,CACrF,uBAAuB,YACvB,uBAAuB,cACzB,CAAC;;;;;;;;AA+BD,SAAgB,mBAAmB,SAAiD;CAClF,MAAM,UAAU,QAAQ,WAAW,CAAC,gBAAgB,IAAI,QAAQ,MAAM;CACtE,OAAO,2BAA2B,4BAA4B,SAC5D,eAAe;EACb,eAAe,QAAQ;EACvB,QAAQ,QAAQ;EAChB,WAAW;EACX,GAAI,QAAQ,aAAa,EAAE,YAAY,QAAQ,WAAW,IAAI,CAAC;EAC/D,aAAa,QAAQ;EACrB,GAAI,QAAQ,YAAY,EAAE,WAAW,QAAQ,UAAU,IAAI,CAAC;EAC5D;EACA,GAAI,QAAQ,eAAe,EAAE,cAAc,QAAQ,aAAa,IAAI,CAAC;EACrE,iBAAiB;GACf,SAAS;GACT,cAAc,QAAQ;GACtB,aAAa,QAAQ,eAAe,SAAS,QAAQ,QAAQ,IAAI,QAAQ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CAAuC,EAAE,OAAO,WAAW,OAAO,CAAC;EAEhF,MAAM,UAAU,MAAM,QAAQ,IAAI,WAAW,KAAK,OAAO,KAAK,MAAM,EAAE,CAAC,CAAC;EAExE,OAAO,KAAK,sCAAsC;GAChD,OAAO,QAAQ;GACf,YAAY,QAAQ,QAAQ,MAAM,EAAE,OAAO,CAAC,CAAC;GAC7C,QAAQ,QAAQ,QAAQ,MAAM,CAAC,EAAE,OAAO,CAAC,CAAC;EAC5C,CAAC;EAED,OAAO;CACT;AACF"}
1
+ {"version":3,"file":"tracker-CNF8TRpk.js","names":[],"sources":["../src/tracker/agent-activity.ts","../src/tracker/index.ts"],"sourcesContent":["/**\n * AI-agent activity (BOFF-9684)\n *\n * Platform-wide activity actions for what an AI agent does, and a helper that records them with\n * the agent as an `app` actor. The audit trail can then separate agent actions from the human\n * actions around them (ISO/IEC 42001 Annex A.9 evidence) and link each one back to the person\n * who started the run (`onBehalfOf`).\n *\n * The action names follow the platform taxonomy `<domain>.<resource>.<verb>` and are shared by\n * every product that runs agents; the product is identified by `productId`.\n *\n * @example\n * ```ts\n * import { AGENT_ACTIVITY_ACTIONS, trackAgentActivity } from '@burdenoff/be-sdk/tracker';\n *\n * await trackAgentActivity({\n * action: AGENT_ACTIVITY_ACTIONS.TOOL_CALLED,\n * agentId: agent.id,\n * workspaceId,\n * onBehalfOf: userId,\n * productId: 'botmanor',\n * metadata: { toolName: 'search' },\n * });\n * ```\n *\n * @module tracker/agent-activity\n * @category Tracking\n */\nimport { createExplicitActivityScope, runInExplicitActivityScope } from '../activity/explicit-activity-scope.js';\nimport { trackOperation } from './stub.js';\n\n/** Activity actions for AI-agent behaviour. */\nexport const AGENT_ACTIVITY_ACTIONS = Object.freeze({\n /** An agent run (one turn) finished and produced a response. */\n RUN_COMPLETED: 'agent.run.completed',\n /** An agent run failed before producing a response. */\n RUN_FAILED: 'agent.run.failed',\n /** The agent called a tool (MCP or similar). `success: false` when the call failed. */\n TOOL_CALLED: 'agent.tool.called',\n /** The agent delegated a sub-task to another agent. */\n DELEGATION_SENT: 'agent.delegation.sent',\n /** A governance policy refused something the agent run attempted (input, output, tool, model, budget, rate). */\n POLICY_BLOCKED: 'agent.policy.blocked',\n} as const);\n\nexport type AgentActivityAction = (typeof AGENT_ACTIVITY_ACTIONS)[keyof typeof AGENT_ACTIVITY_ACTIONS];\n\n/** Default `resourceType` of agent activity rows; `resourceId` defaults to the agent id. */\nexport const AGENT_ACTIVITY_RESOURCE_TYPE = 'agent';\n\nconst FAILURE_ACTIONS: ReadonlySet<AgentActivityAction> = new Set<AgentActivityAction>([\n AGENT_ACTIVITY_ACTIONS.RUN_FAILED,\n AGENT_ACTIVITY_ACTIONS.POLICY_BLOCKED,\n]);\n\nexport interface AgentActivityOptions {\n action: AgentActivityAction;\n /** The agent that acted. Recorded as the row's actor (`userId`) with `actorType: 'app'`. */\n agentId: string;\n workspaceId: string;\n /** The human who started the run, when there is one. */\n onBehalfOf?: string;\n /** Product that runs the agent, e.g. `botmanor`. */\n productId?: string;\n /** Defaults to false for RUN_FAILED and POLICY_BLOCKED, true otherwise. */\n success?: boolean;\n errorMessage?: string;\n description?: string;\n /** Defaults to `AGENT_ACTIVITY_RESOURCE_TYPE`. */\n resourceType?: string;\n /** Defaults to `agentId`. */\n resourceId?: string;\n metadata?: Record<string, unknown>;\n /** Stable idempotency key, only for callers that may replay the same event. */\n dedupeKey?: string;\n}\n\n/**\n * Record one AI-agent activity row, attributed to the agent as an `app` actor.\n *\n * Fire-and-forget like `trackOperation`: it never throws for a delivery failure and never blocks\n * on the activity service. It runs in its own explicit-activity scope, so recording what the\n * agent did does not suppress the mutation-audit row of the human request that started the run.\n */\nexport function trackAgentActivity(options: AgentActivityOptions): Promise<boolean> {\n const success = options.success ?? !FAILURE_ACTIONS.has(options.action);\n return runInExplicitActivityScope(createExplicitActivityScope(), () =>\n trackOperation({\n operationName: options.action,\n userId: options.agentId,\n actorType: 'app',\n ...(options.onBehalfOf ? { onBehalfOf: options.onBehalfOf } : {}),\n workspaceId: options.workspaceId,\n ...(options.productId ? { productId: options.productId } : {}),\n success,\n ...(options.errorMessage ? { errorMessage: options.errorMessage } : {}),\n activityOptions: {\n enabled: true,\n activityType: options.action,\n description: options.description ?? `Agent ${options.agentId}: ${options.action}`,\n workspaceId: options.workspaceId,\n resourceType: options.resourceType ?? AGENT_ACTIVITY_RESOURCE_TYPE,\n resourceId: options.resourceId ?? options.agentId,\n metadata: { ...options.metadata, agentId: options.agentId },\n ...(options.dedupeKey ? { dedupeKey: options.dedupeKey } : {}),\n },\n })\n );\n}\n","/**\n * Unified Tracker Module\n * Aggregates RBAC + Activity + Usage + Notifications in single function call\n * This is the MOST IMPORTANT module that products should use for most operations\n */\n\nimport type { BurdenoffGraphQLClient } from '../client/graphql.js';\nimport type { SDKContext } from '../types/index.js';\nimport { PermissionDeniedError, QuotaExceededError, ValidationError } from '../types/index.js';\nimport { logger } from '../logger/index.js';\nimport { RBACModule, type CheckPermissionOptions } from '../rbac/index.js';\nimport { ActivityModule, ActivityType, ActivityStatus, ActivitySeverity } from '../activity/index.js';\nimport { UsageModule, type UsageMetricType } from '../usage/index.js';\nimport { NotificationsModule, NotificationType } from '../notifications/index.js';\n\nexport interface TrackOptions {\n /** User performing the action */\n userId: string;\n /** Action being performed */\n action: string;\n /** Resource type */\n resourceType: string;\n /** Optional resource ID */\n resourceId?: string;\n /** Workspace context */\n workspaceId?: string;\n /** Organization context */\n organizationId?: string;\n /** Project context */\n projectId?: string;\n\n /** RBAC options */\n rbac?: {\n /** Check permission before executing (default: true) */\n enabled?: boolean;\n /** Custom permission action (defaults to action parameter) */\n permissionAction?: string;\n };\n\n /** Activity tracking options */\n activity?: {\n /** Enable activity tracking (default: true) */\n enabled?: boolean;\n /** Activity type (auto-inferred if not provided) */\n activityType?: ActivityType;\n /** Additional metadata */\n metadata?: Record<string, unknown>;\n /** IP address */\n ipAddress?: string;\n /** User agent */\n userAgent?: string;\n /** Severity level */\n severity?: ActivitySeverity;\n };\n\n /**\n * Usage tracking options.\n *\n * The tracker meters a workspace quota only when `quotaName` is set: it checks capacity\n * with the owner's `checkWorkspaceQuota` (for positive amounts) and records the amount\n * with `trackUsage`. Without a `quotaName` the usage step is skipped. Mutations whose\n * schema carries a gateway `@usage` directive are already metered by the gateway and\n * should not set `quotaName` here, or the quota is charged twice.\n */\n usage?: {\n /** Enable usage tracking (default: true) */\n enabled?: boolean;\n /** Workspace quota to charge, for example `platform.projects.created`. */\n quotaName?: string;\n /** Product that owns the quota. Defaults to the SDK context's `productId`. */\n productId?: string;\n /** Description stored on the usage record. Defaults to `<action> <resourceType>`. */\n description?: string;\n /**\n * Amount to record (default: 1). A negative amount releases usage, for example on\n * delete; the quota check is skipped for it.\n */\n amount?: number;\n /** Check quota before recording a positive amount (default: true) */\n checkQuota?: boolean;\n /**\n * Legacy metric name. The workspace usage owner has no metric types, so a metric type\n * without a `quotaName` is not metered by the tracker.\n */\n metricType?: UsageMetricType;\n /** Legacy entity type. Workspace quotas are always charged to the workspace. */\n entityType?: 'user' | 'workspace' | 'organization';\n };\n\n /** Notification options */\n notification?: {\n /** Send notification on success */\n onSuccess?: {\n title: string;\n message: string;\n type?: NotificationType;\n /** Additional user IDs to notify */\n additionalUserIds?: string[];\n };\n /** Send notification on failure */\n onFailure?: {\n title: string;\n message: string;\n type?: NotificationType;\n /** Additional user IDs to notify */\n additionalUserIds?: string[];\n };\n };\n}\n\n/** A usage step that meters a named workspace quota. */\ninterface ResolvedUsage {\n quotaName: string;\n amount: number;\n workspaceId: string;\n checkQuota: boolean;\n}\n\nexport interface TrackResult {\n success: boolean;\n /** Permission check result */\n permissionGranted: boolean;\n /** Quota check result (if quota checking enabled) */\n quotaAvailable?: boolean;\n quotaRemaining?: number;\n /** Activity record ID */\n activityId?: string;\n /** True when the usage step recorded the amount with the owner */\n usageTracked?: boolean;\n /**\n * @deprecated The owner's `trackUsage` returns `Boolean!` and no record id, so this is\n * never set. Read `usageTracked` instead.\n */\n usageRecordId?: string;\n /** Notification IDs sent */\n notificationIds?: string[];\n /** Error if operation failed */\n error?: {\n type: 'permission' | 'quota' | 'validation' | 'unknown';\n message: string;\n details?: Record<string, unknown>;\n };\n /** Operation duration in milliseconds */\n duration: number;\n}\n\n/**\n * Unified Tracker Module\n *\n * The primary module products should use for tracking operations.\n * Automatically handles RBAC checks, activity logging, usage tracking, and notifications.\n *\n * @example\n * ```typescript\n * const result = await sdk.tracker.track({\n * userId: 'user123',\n * action: 'create_project',\n * resourceType: 'project',\n * workspaceId: 'ws123',\n * usage: {\n * quotaName: 'myproduct.projects.count',\n * productId: 'myproduct',\n * amount: 1,\n * checkQuota: true,\n * },\n * notification: {\n * onSuccess: {\n * title: 'Project Created',\n * message: 'Your project has been created successfully',\n * },\n * },\n * });\n *\n * if (!result.success) {\n * // Handle error\n * }\n * ```\n */\nexport class TrackerModule {\n private rbac: RBACModule;\n private activity: ActivityModule;\n private usage: UsageModule;\n private notifications: NotificationsModule;\n\n constructor(\n client: BurdenoffGraphQLClient,\n private context: SDKContext = {}\n ) {\n this.rbac = new RBACModule(client, context);\n this.activity = new ActivityModule(client, context);\n this.usage = new UsageModule(client, context);\n this.notifications = new NotificationsModule(client, context);\n }\n\n /**\n * Track operation with RBAC, Activity, Usage, and Notifications\n * This is the primary method products should use\n */\n public async track(options: TrackOptions): Promise<TrackResult> {\n const startTime = Date.now();\n const result: TrackResult = {\n success: false,\n permissionGranted: false,\n duration: 0,\n };\n\n try {\n // Validate required fields\n this.validateOptions(options);\n\n // Step 1: Check RBAC permission (if enabled)\n if (options.rbac?.enabled !== false) {\n await this.checkPermission(options, result);\n if (!result.permissionGranted) {\n result.duration = Date.now() - startTime;\n await this.logFailedActivity(options, result, startTime);\n return result;\n }\n } else {\n result.permissionGranted = true;\n }\n\n // Steps 2 and 3: check quota, then record usage (only for a named workspace quota)\n const usage = this.resolveUsage(options);\n if (usage) {\n let quotaAssignmentId: string | undefined;\n if (usage.checkQuota) {\n quotaAssignmentId = await this.checkQuota(options, usage, result);\n if (result.quotaAvailable === false) {\n result.duration = Date.now() - startTime;\n await this.logFailedActivity(options, result, startTime);\n return result;\n }\n }\n await this.trackUsage(options, usage, quotaAssignmentId, result);\n }\n\n // Step 4: Log successful activity (if enabled)\n if (options.activity?.enabled !== false) {\n await this.logSuccessActivity(options, result, startTime);\n }\n\n // Step 5: Send success notification (if configured)\n if (options.notification?.onSuccess) {\n await this.sendSuccessNotification(options, result);\n }\n\n result.success = true;\n result.duration = Date.now() - startTime;\n\n logger.info('[Tracker] Operation tracked successfully', {\n action: options.action,\n duration: result.duration,\n });\n\n return result;\n } catch (error) {\n result.duration = Date.now() - startTime;\n result.success = false;\n\n // Categorize error\n if (error instanceof PermissionDeniedError) {\n result.error = {\n type: 'permission',\n message: error.message,\n details: error.details,\n };\n } else if (error instanceof QuotaExceededError) {\n result.error = {\n type: 'quota',\n message: error.message,\n details: error.details,\n };\n } else if (error instanceof ValidationError) {\n result.error = {\n type: 'validation',\n message: error.message,\n details: error.details,\n };\n } else {\n result.error = {\n type: 'unknown',\n message: error instanceof Error ? error.message : 'Unknown error',\n };\n }\n\n // Log failed activity\n await this.logFailedActivity(options, result, startTime);\n\n // Send failure notification (if configured)\n if (options.notification?.onFailure) {\n await this.sendFailureNotification(options, result);\n }\n\n logger.error('[Tracker] Operation tracking failed', {\n action: options.action,\n error: result.error,\n duration: result.duration,\n });\n\n return result;\n }\n }\n\n /**\n * Track operation and throw on failure\n * Convenience method that throws errors instead of returning them in result\n */\n public async trackOrThrow(options: TrackOptions): Promise<TrackResult> {\n const result = await this.track(options);\n\n if (!result.success && result.error) {\n const errorMessage = result.error.message;\n const errorDetails = result.error.details;\n\n switch (result.error.type) {\n case 'permission':\n throw new PermissionDeniedError(errorMessage, errorDetails);\n case 'quota':\n throw new QuotaExceededError(errorMessage, errorDetails);\n case 'validation':\n throw new ValidationError(errorMessage, errorDetails);\n default:\n throw new Error(errorMessage);\n }\n }\n\n return result;\n }\n\n /**\n * Simplified track method for common operations.\n * The trailing metric type is accepted for source compatibility and is not metered.\n */\n public async trackSimple(\n userId: string,\n action: string,\n resourceType: string,\n resourceId?: string,\n _metricType?: UsageMetricType\n ): Promise<boolean> {\n // A metric type has no workspace quota on the owner, so trackSimple never meters usage.\n // Call track() with `usage.quotaName` to charge a quota.\n const result = await this.track({\n userId,\n action,\n resourceType,\n resourceId,\n workspaceId: this.context.workspaceId,\n usage: { enabled: false },\n });\n\n return result.success;\n }\n\n /**\n * Validate tracking options\n */\n private validateOptions(options: TrackOptions): void {\n if (!options.userId) {\n throw new ValidationError('User ID is required');\n }\n\n if (!options.action) {\n throw new ValidationError('Action is required');\n }\n\n if (!options.resourceType) {\n throw new ValidationError('Resource type is required');\n }\n }\n\n /**\n * Check RBAC permission\n */\n private async checkPermission(options: TrackOptions, result: TrackResult): Promise<void> {\n const permissionOptions: CheckPermissionOptions = {\n userId: options.userId,\n action: options.rbac?.permissionAction || options.action,\n resourceType: options.resourceType,\n resourceId: options.resourceId,\n workspaceId: options.workspaceId,\n };\n\n const hasPermission = await this.rbac.checkPermission(permissionOptions);\n result.permissionGranted = hasPermission;\n\n if (!hasPermission) {\n result.error = {\n type: 'permission',\n message: 'Permission denied',\n details: permissionOptions as unknown as Record<string, unknown>,\n };\n }\n }\n\n /**\n * Resolve the usage step for an operation, or null when nothing is metered: usage is\n * disabled, or no workspace quota is named (a legacy `metricType` alone has no owner\n * quota to charge).\n */\n private resolveUsage(options: TrackOptions): ResolvedUsage | null {\n const usage = options.usage;\n if (!usage || usage.enabled === false) {\n return null;\n }\n const quotaName = usage.quotaName?.trim();\n if (!quotaName) {\n if (usage.metricType) {\n logger.debug('[Tracker] Usage step skipped: no quotaName for legacy metricType', {\n action: options.action,\n metricType: usage.metricType,\n });\n }\n return null;\n }\n const amount = usage.amount ?? 1;\n if (typeof amount !== 'number' || !Number.isFinite(amount) || amount === 0) {\n throw new ValidationError('Usage amount must be a finite, non-zero number');\n }\n const workspaceId = options.workspaceId ?? this.context.workspaceId;\n if (!workspaceId) {\n throw new ValidationError('Workspace ID is required to track workspace quota usage');\n }\n return {\n quotaName,\n amount,\n workspaceId,\n // Only consumption is gated; a release (negative amount) must always go through.\n checkQuota: usage.checkQuota !== false && amount > 0,\n };\n }\n\n /**\n * Check workspace quota capacity. Returns the assignment to charge when one exists.\n */\n private async checkQuota(\n options: TrackOptions,\n usage: ResolvedUsage,\n result: TrackResult\n ): Promise<string | undefined> {\n const quotaCheck = await this.usage.checkWorkspaceQuota({\n quotaName: usage.quotaName,\n amount: usage.amount,\n workspaceId: usage.workspaceId,\n userId: options.userId,\n });\n\n result.quotaAvailable = quotaCheck.allowed;\n result.quotaRemaining = quotaCheck.limitLeft ?? undefined;\n\n if (!quotaCheck.allowed) {\n const notProvisioned = quotaCheck.assignmentId === null;\n result.error = {\n type: 'quota',\n message: notProvisioned\n ? `Quota ${usage.quotaName} is not included in this workspace's plan`\n : 'Quota exceeded',\n details: {\n quotaName: usage.quotaName,\n requestedAmount: usage.amount,\n limitLeft: quotaCheck.limitLeft,\n notProvisioned,\n },\n };\n }\n\n return quotaCheck.assignmentId ?? undefined;\n }\n\n /**\n * Record workspace quota usage with the owner.\n */\n private async trackUsage(\n options: TrackOptions,\n usage: ResolvedUsage,\n quotaAssignmentId: string | undefined,\n result: TrackResult\n ): Promise<void> {\n result.usageTracked = await this.usage.trackUsage({\n quotaName: usage.quotaName,\n productId: options.usage?.productId,\n amount: usage.amount,\n description: options.usage?.description?.trim() || `${options.action} ${options.resourceType}`,\n workspaceId: usage.workspaceId,\n userId: options.userId,\n quotaAssignmentId,\n metadata: {\n action: options.action,\n resourceType: options.resourceType,\n ...(options.resourceId ? { resourceId: options.resourceId } : {}),\n },\n });\n }\n\n /**\n * Log successful activity\n */\n private async logSuccessActivity(options: TrackOptions, result: TrackResult, startTime: number): Promise<void> {\n const activityRecord = await this.activity.log({\n userId: options.userId,\n activityType: options.activity?.activityType || this.inferActivityType(options.action),\n resourceType: options.resourceType,\n resourceId: options.resourceId,\n action: options.action,\n status: ActivityStatus.SUCCESS,\n workspaceId: options.workspaceId,\n organizationId: options.organizationId,\n projectId: options.projectId,\n ipAddress: options.activity?.ipAddress,\n userAgent: options.activity?.userAgent,\n metadata: options.activity?.metadata,\n severity: options.activity?.severity || ActivitySeverity.LOW,\n duration: Date.now() - startTime,\n });\n\n result.activityId = activityRecord.id;\n }\n\n /**\n * Log failed activity\n */\n private async logFailedActivity(options: TrackOptions, result: TrackResult, startTime: number): Promise<void> {\n if (options.activity?.enabled === false) {\n return;\n }\n\n try {\n const activityRecord = await this.activity.log({\n userId: options.userId,\n activityType: options.activity?.activityType || this.inferActivityType(options.action),\n resourceType: options.resourceType,\n resourceId: options.resourceId,\n action: options.action,\n status: ActivityStatus.FAILURE,\n workspaceId: options.workspaceId,\n organizationId: options.organizationId,\n projectId: options.projectId,\n ipAddress: options.activity?.ipAddress,\n userAgent: options.activity?.userAgent,\n metadata: options.activity?.metadata,\n severity: ActivitySeverity.HIGH,\n errorMessage: result.error?.message,\n duration: Date.now() - startTime,\n });\n\n result.activityId = activityRecord.id;\n } catch (error) {\n logger.error('[Tracker] Failed to log activity', { error });\n }\n }\n\n /**\n * Send success notification\n */\n private async sendSuccessNotification(options: TrackOptions, result: TrackResult): Promise<void> {\n if (!options.notification?.onSuccess) {\n return;\n }\n\n try {\n const userIds = [options.userId, ...(options.notification.onSuccess.additionalUserIds || [])];\n\n const response = await this.notifications.send({\n title: options.notification.onSuccess.title,\n message: options.notification.onSuccess.message,\n type: options.notification.onSuccess.type || NotificationType.SUCCESS,\n userIds,\n });\n\n result.notificationIds = response.notificationIds;\n } catch (error) {\n logger.error('[Tracker] Failed to send success notification', { error });\n }\n }\n\n /**\n * Send failure notification\n */\n private async sendFailureNotification(options: TrackOptions, result: TrackResult): Promise<void> {\n if (!options.notification?.onFailure) {\n return;\n }\n\n try {\n const userIds = [options.userId, ...(options.notification.onFailure.additionalUserIds || [])];\n\n const response = await this.notifications.send({\n title: options.notification.onFailure.title,\n message: options.notification.onFailure.message,\n type: options.notification.onFailure.type || NotificationType.ERROR,\n userIds,\n });\n\n result.notificationIds = response.notificationIds;\n } catch (error) {\n logger.error('[Tracker] Failed to send failure notification', { error });\n }\n }\n\n /**\n * Infer activity type from action\n */\n private inferActivityType(action: string): ActivityType {\n const actionLower = action.toLowerCase();\n\n if (actionLower.includes('create') || actionLower.includes('add')) return ActivityType.CREATE;\n if (actionLower.includes('update') || actionLower.includes('edit')) return ActivityType.UPDATE;\n if (actionLower.includes('delete') || actionLower.includes('remove')) return ActivityType.DELETE;\n if (actionLower.includes('read') || actionLower.includes('view')) return ActivityType.READ;\n if (actionLower.includes('login')) return ActivityType.LOGIN;\n if (actionLower.includes('logout')) return ActivityType.LOGOUT;\n if (actionLower.includes('export')) return ActivityType.EXPORT;\n if (actionLower.includes('import')) return ActivityType.IMPORT;\n if (actionLower.includes('share')) return ActivityType.SHARE;\n if (actionLower.includes('download')) return ActivityType.DOWNLOAD;\n if (actionLower.includes('upload')) return ActivityType.UPLOAD;\n\n return ActivityType.CUSTOM;\n }\n\n /**\n * Batch track multiple operations\n */\n public async trackBatch(operations: TrackOptions[]): Promise<TrackResult[]> {\n logger.debug('[Tracker] Batch tracking operations', { count: operations.length });\n\n const results = await Promise.all(operations.map((op) => this.track(op)));\n\n logger.info('[Tracker] Batch tracking completed', {\n total: results.length,\n successful: results.filter((r) => r.success).length,\n failed: results.filter((r) => !r.success).length,\n });\n\n return results;\n }\n}\n\n// Export stub implementation for services that don't need full tracking\nexport {\n trackOperation,\n createProductTracker,\n UnifiedTrackerStub,\n trackerStub,\n UNIFIED_TRACKER_CONSTANTS,\n} from './stub.js';\nexport { isTrackedActorType, resolveAssistantSession } from './stub.js';\n// Assistant-session attribution on activity rows (BOFF-9649)\nexport { AI_ASSISTANT_ACTOR_ORIGIN } from '../activity/assistant-session.js';\nexport type { ActorOrigin, AssistantSessionAttribution } from '../activity/assistant-session.js';\nexport type {\n TrackingEvent,\n RbacCheckOptions,\n UsageTrackingOptions,\n ActivityTrackingOptions,\n UnifiedTrackingOptions,\n ProductTracker,\n TrackedActorType,\n} from './stub.js';\n\n// AI-agent activity actions and recorder (BOFF-9684)\nexport { AGENT_ACTIVITY_ACTIONS, AGENT_ACTIVITY_RESOURCE_TYPE, trackAgentActivity } from './agent-activity.js';\nexport type { AgentActivityAction, AgentActivityOptions } from './agent-activity.js';\n\n// Opt a resolver out of the mutation-audit backstop row (see server/mutation-audit.ts)\nexport { suppressMutationAudit } from '../activity/explicit-activity-scope.js';\n\n// Re-export UsageMetricType from usage module for convenience\nexport { UsageMetricType } from '../usage/index.js';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,MAAa,yBAAyB,OAAO,OAAO;;CAElD,eAAe;;CAEf,YAAY;;CAEZ,aAAa;;CAEb,iBAAiB;;CAEjB,gBAAgB;AAClB,CAAU;;AAKV,MAAa,+BAA+B;AAE5C,MAAM,kCAAoD,IAAI,IAAyB,CACrF,uBAAuB,YACvB,uBAAuB,cACzB,CAAC;;;;;;;;AA+BD,SAAgB,mBAAmB,SAAiD;CAClF,MAAM,UAAU,QAAQ,WAAW,CAAC,gBAAgB,IAAI,QAAQ,MAAM;CACtE,OAAO,2BAA2B,4BAA4B,SAC5D,eAAe;EACb,eAAe,QAAQ;EACvB,QAAQ,QAAQ;EAChB,WAAW;EACX,GAAI,QAAQ,aAAa,EAAE,YAAY,QAAQ,WAAW,IAAI,CAAC;EAC/D,aAAa,QAAQ;EACrB,GAAI,QAAQ,YAAY,EAAE,WAAW,QAAQ,UAAU,IAAI,CAAC;EAC5D;EACA,GAAI,QAAQ,eAAe,EAAE,cAAc,QAAQ,aAAa,IAAI,CAAC;EACrE,iBAAiB;GACf,SAAS;GACT,cAAc,QAAQ;GACtB,aAAa,QAAQ,eAAe,SAAS,QAAQ,QAAQ,IAAI,QAAQ;GACzE,aAAa,QAAQ;GACrB,cAAc,QAAQ;GACtB,YAAY,QAAQ,cAAc,QAAQ;G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I,WAAW,KAAK,OAAO,KAAK,MAAM,EAAE,CAAC,CAAC;EAExE,OAAO,KAAK,sCAAsC;GAChD,OAAO,QAAQ;GACf,YAAY,QAAQ,QAAQ,MAAM,EAAE,OAAO,CAAC,CAAC;GAC7C,QAAQ,QAAQ,QAAQ,MAAM,CAAC,EAAE,OAAO,CAAC,CAAC;EAC5C,CAAC;EAED,OAAO;CACT;AACF"}
@@ -1,2 +1,2 @@
1
- import { A as readRbacDirectiveArgs, B as validateUsername, C as RbacRootField, D as assertRbacCoverage, E as analyzeRbacCoverage, F as validateUserFields, G as lengthInCodePoints, H as NAME_MIN_LENGTH, I as USERNAME_MAX_LENGTH, K as validateName, L as USERNAME_MIN_LENGTH, M as UserFieldKey, N as UserFieldsValidationResult, O as loadRbacSchemaDocuments, P as ValidatedUserFields, R as UsernameErrorCode, S as RbacFieldPin, T as RbacScopeType, U as NameErrorCode, V as NAME_MAX_LENGTH, W as NameValidationResult, _ as RbacCoverageError, a as BillingMoneyValidationResult, b as RbacCoverageSource, c as SupportedBillingCurrency, d as validateBillingAmount, f as validateBillingMoney, g as RBAC_SCOPE_TYPES, h as RBAC_GATED_SCOPE_TYPES, i as BillingMoneyErrorCode, j as UserFieldError, k as rbacArgPathProblem, l as convertBillingToMinorUnits, m as DEFAULT_RBAC_ROOT_TYPES, n as BillingAmountErrorCode, o as MAX_BILLING_AMOUNT, p as DEFAULT_MAX_RBAC_ARG_PATH_SEGMENTS, r as BillingAmountValidationResult, s as SUPPORTED_BILLING_CURRENCIES, u as isSupportedBillingCurrency, v as RbacCoverageOptions, w as RbacSchemaDocument, x as RbacDirectiveArgs, y as RbacCoverageReport, z as UsernameValidationResult } from "../index-CIgoeobA.js";
2
- export { type BillingAmountErrorCode, type BillingAmountValidationResult, type BillingMoneyErrorCode, type BillingMoneyValidationResult, DEFAULT_MAX_RBAC_ARG_PATH_SEGMENTS, DEFAULT_RBAC_ROOT_TYPES, MAX_BILLING_AMOUNT, NAME_MAX_LENGTH, NAME_MIN_LENGTH, type NameErrorCode, type NameValidationResult, RBAC_GATED_SCOPE_TYPES, RBAC_SCOPE_TYPES, RbacCoverageError, type RbacCoverageOptions, type RbacCoverageReport, type RbacCoverageSource, type RbacDirectiveArgs, type RbacFieldPin, type RbacRootField, type RbacSchemaDocument, type RbacScopeType, SUPPORTED_BILLING_CURRENCIES, type SupportedBillingCurrency, USERNAME_MAX_LENGTH, USERNAME_MIN_LENGTH, type UserFieldError, type UserFieldKey, type UserFieldsValidationResult, type UsernameErrorCode, type UsernameValidationResult, type ValidatedUserFields, analyzeRbacCoverage, assertRbacCoverage, convertBillingToMinorUnits, isSupportedBillingCurrency, lengthInCodePoints, loadRbacSchemaDocuments, rbacArgPathProblem, readRbacDirectiveArgs, validateBillingAmount, validateBillingMoney, validateName, validateUserFields, validateUsername };
1
+ import { A as RbacScopeType, B as validateUserFields, C as RbacCoverageOptions, D as RbacFieldPin, E as RbacDirectiveArgs, F as readRbacDirectiveArgs, G as validateUsername, H as USERNAME_MIN_LENGTH, I as UserFieldError, J as NameErrorCode, K as NAME_MAX_LENGTH, L as UserFieldKey, M as assertRbacCoverage, N as loadRbacSchemaDocuments, O as RbacRootField, P as rbacArgPathProblem, R as UserFieldsValidationResult, S as RbacCoverageError, T as RbacCoverageSource, U as UsernameErrorCode, V as USERNAME_MAX_LENGTH, W as UsernameValidationResult, X as lengthInCodePoints, Y as NameValidationResult, Z as validateName, _ as validateBillingMoney, a as BillingMoneyErrorCode, b as RBAC_GATED_SCOPE_TYPES, c as SUPPORTED_BILLING_CURRENCIES, d as SupportedBillingCurrencyInfo, f as convertBillingToMinorUnits, g as validateBillingAmount, h as toSupportedBillingCurrency, i as BillingCurrencyPaymentProvider, j as analyzeRbacCoverage, k as RbacSchemaDocument, l as SUPPORTED_BILLING_CURRENCY_INFO, m as isSupportedBillingCurrency, n as BillingAmountErrorCode, o as BillingMoneyValidationResult, p as getSupportedBillingCurrencyInfo, q as NAME_MIN_LENGTH, r as BillingAmountValidationResult, s as MAX_BILLING_AMOUNT, u as SupportedBillingCurrency, v as DEFAULT_MAX_RBAC_ARG_PATH_SEGMENTS, w as RbacCoverageReport, x as RBAC_SCOPE_TYPES, y as DEFAULT_RBAC_ROOT_TYPES, z as ValidatedUserFields } from "../index-Bnz5Bqtl.js";
2
+ export { type BillingAmountErrorCode, type BillingAmountValidationResult, type BillingCurrencyPaymentProvider, type BillingMoneyErrorCode, type BillingMoneyValidationResult, DEFAULT_MAX_RBAC_ARG_PATH_SEGMENTS, DEFAULT_RBAC_ROOT_TYPES, MAX_BILLING_AMOUNT, NAME_MAX_LENGTH, NAME_MIN_LENGTH, type NameErrorCode, type NameValidationResult, RBAC_GATED_SCOPE_TYPES, RBAC_SCOPE_TYPES, RbacCoverageError, type RbacCoverageOptions, type RbacCoverageReport, type RbacCoverageSource, type RbacDirectiveArgs, type RbacFieldPin, type RbacRootField, type RbacSchemaDocument, type RbacScopeType, SUPPORTED_BILLING_CURRENCIES, SUPPORTED_BILLING_CURRENCY_INFO, type SupportedBillingCurrency, type SupportedBillingCurrencyInfo, USERNAME_MAX_LENGTH, USERNAME_MIN_LENGTH, type UserFieldError, type UserFieldKey, type UserFieldsValidationResult, type UsernameErrorCode, type UsernameValidationResult, type ValidatedUserFields, analyzeRbacCoverage, assertRbacCoverage, convertBillingToMinorUnits, getSupportedBillingCurrencyInfo, isSupportedBillingCurrency, lengthInCodePoints, loadRbacSchemaDocuments, rbacArgPathProblem, readRbacDirectiveArgs, toSupportedBillingCurrency, validateBillingAmount, validateBillingMoney, validateName, validateUserFields, validateUsername };
@@ -1,4 +1,4 @@
1
- import { C as NAME_MIN_LENGTH, S as NAME_MAX_LENGTH, T as validateName, _ as readRbacDirectiveArgs, a as isSupportedBillingCurrency, b as USERNAME_MIN_LENGTH, c as DEFAULT_MAX_RBAC_ARG_PATH_SEGMENTS, d as RBAC_SCOPE_TYPES, f as RbacCoverageError, g as rbacArgPathProblem, h as loadRbacSchemaDocuments, i as convertBillingToMinorUnits, l as DEFAULT_RBAC_ROOT_TYPES, m as assertRbacCoverage, n as MAX_BILLING_AMOUNT, o as validateBillingAmount, p as analyzeRbacCoverage, r as SUPPORTED_BILLING_CURRENCIES, s as validateBillingMoney, u as RBAC_GATED_SCOPE_TYPES, v as validateUserFields, w as lengthInCodePoints, x as validateUsername, y as USERNAME_MAX_LENGTH } from "../validation-CPUITdMk.js";
1
+ import { C as USERNAME_MIN_LENGTH, D as lengthInCodePoints, E as NAME_MIN_LENGTH, O as validateName, S as USERNAME_MAX_LENGTH, T as NAME_MAX_LENGTH, _ as assertRbacCoverage, a as convertBillingToMinorUnits, b as readRbacDirectiveArgs, c as toSupportedBillingCurrency, d as DEFAULT_MAX_RBAC_ARG_PATH_SEGMENTS, f as DEFAULT_RBAC_ROOT_TYPES, g as analyzeRbacCoverage, h as RbacCoverageError, i as SUPPORTED_BILLING_CURRENCY_INFO, l as validateBillingAmount, m as RBAC_SCOPE_TYPES, n as MAX_BILLING_AMOUNT, o as getSupportedBillingCurrencyInfo, p as RBAC_GATED_SCOPE_TYPES, r as SUPPORTED_BILLING_CURRENCIES, s as isSupportedBillingCurrency, u as validateBillingMoney, v as loadRbacSchemaDocuments, w as validateUsername, x as validateUserFields, y as rbacArgPathProblem } from "../validation-bwJzOytZ.js";
2
2
 
3
- export { DEFAULT_MAX_RBAC_ARG_PATH_SEGMENTS, DEFAULT_RBAC_ROOT_TYPES, MAX_BILLING_AMOUNT, NAME_MAX_LENGTH, NAME_MIN_LENGTH, RBAC_GATED_SCOPE_TYPES, RBAC_SCOPE_TYPES, RbacCoverageError, SUPPORTED_BILLING_CURRENCIES, USERNAME_MAX_LENGTH, USERNAME_MIN_LENGTH, analyzeRbacCoverage, assertRbacCoverage, convertBillingToMinorUnits, isSupportedBillingCurrency, lengthInCodePoints, loadRbacSchemaDocuments, rbacArgPathProblem, readRbacDirectiveArgs, validateBillingAmount, validateBillingMoney, validateName, validateUserFields, validateUsername };
3
+ export { DEFAULT_MAX_RBAC_ARG_PATH_SEGMENTS, DEFAULT_RBAC_ROOT_TYPES, MAX_BILLING_AMOUNT, NAME_MAX_LENGTH, NAME_MIN_LENGTH, RBAC_GATED_SCOPE_TYPES, RBAC_SCOPE_TYPES, RbacCoverageError, SUPPORTED_BILLING_CURRENCIES, SUPPORTED_BILLING_CURRENCY_INFO, USERNAME_MAX_LENGTH, USERNAME_MIN_LENGTH, analyzeRbacCoverage, assertRbacCoverage, convertBillingToMinorUnits, getSupportedBillingCurrencyInfo, isSupportedBillingCurrency, lengthInCodePoints, loadRbacSchemaDocuments, rbacArgPathProblem, readRbacDirectiveArgs, toSupportedBillingCurrency, validateBillingAmount, validateBillingMoney, validateName, validateUserFields, validateUsername };
4
4
  //# sourceMappingURL=index.js.map
@@ -547,102 +547,73 @@ function assertRbacCoverage(source, options = {}) {
547
547
 
548
548
  // src/validation/billing.ts
549
549
  /** Canonical billing policy extracted from global-billing input validation (BOFF-10764).
550
- * Currency support and the existing 1e9 ceiling are unchanged. This validates
551
- * major-unit values only; it does not round, convert FX or authorize payment.
550
+ * This validates major-unit values only; it does not round, convert FX or authorize payment.
551
+ *
552
+ * The supported currencies mirror global-billing's single list
553
+ * (`global-billing-svc/src/modules/currency/supported-currencies.ts`, BOFF-17385):
554
+ * exactly USD, INR, EUR, GBP and AUD, in that order (BOFF-17446). Any other code is
555
+ * rejected here because billing rejects it at payment. Keep both lists identical.
552
556
  */
553
557
  const SUPPORTED_BILLING_CURRENCIES = Object.freeze([
554
558
  "USD",
559
+ "INR",
555
560
  "EUR",
556
561
  "GBP",
557
- "INR",
558
- "AUD",
559
- "CAD",
560
- "SGD",
561
- "JPY",
562
- "CNY",
563
- "BRL",
564
- "MXN",
565
- "KRW",
566
- "HKD",
567
- "NOK",
568
- "SEK",
569
- "DKK",
570
- "CHF",
571
- "NZD",
572
- "ZAR",
573
- "AED",
574
- "SAR",
575
- "QAR",
576
- "OMR",
577
- "BHD",
578
- "KWD",
579
- "JOD",
580
- "EGP",
581
- "PKR",
582
- "BDT",
583
- "LKR",
584
- "THB",
585
- "MYR",
586
- "IDR",
587
- "PHP",
588
- "VND",
589
- "TWD",
590
- "CZK",
591
- "HUF",
592
- "PLN",
593
- "RON",
594
- "RUB",
595
- "TRY",
596
- "ILS",
597
- "NGN",
598
- "GHS",
599
- "KES",
600
- "TZS",
601
- "UGX",
602
- "ETB",
603
- "MAD",
604
- "DZD",
605
- "TND",
606
- "BWP",
607
- "MUR",
608
- "MVR",
609
- "BND",
610
- "KHR",
611
- "MMK",
612
- "KZT",
613
- "UZS",
614
- "AZN",
615
- "GEL",
616
- "AMD",
617
- "UAH",
618
- "BGN",
619
- "HRK",
620
- "MKD",
621
- "ALL",
622
- "RSD",
623
- "CLP",
624
- "COP",
625
- "PEN",
626
- "ARS",
627
- "BOB",
628
- "PYG",
629
- "UYU",
630
- "GTQ",
631
- "HNL",
632
- "NIO",
633
- "CRC",
634
- "DOP",
635
- "TTD",
636
- "JMD",
637
- "BBD",
638
- "HTG",
639
- "BZD",
640
- "GYD",
641
- "SRD",
642
- "XCD",
643
- "PAB"
562
+ "AUD"
644
563
  ]);
645
564
  const supportedCurrencies = new Set(SUPPORTED_BILLING_CURRENCIES);
565
+ /** Metadata for every supported currency, identical to global-billing's `SUPPORTED_CURRENCY_INFO`. */
566
+ const SUPPORTED_BILLING_CURRENCY_INFO = Object.freeze({
567
+ USD: Object.freeze({
568
+ code: "USD",
569
+ name: "US Dollar",
570
+ symbol: "$",
571
+ minorUnits: 2,
572
+ paymentProvider: "STRIPE"
573
+ }),
574
+ INR: Object.freeze({
575
+ code: "INR",
576
+ name: "Indian Rupee",
577
+ symbol: "₹",
578
+ minorUnits: 2,
579
+ paymentProvider: "RAZORPAY"
580
+ }),
581
+ EUR: Object.freeze({
582
+ code: "EUR",
583
+ name: "Euro",
584
+ symbol: "€",
585
+ minorUnits: 2,
586
+ paymentProvider: "STRIPE"
587
+ }),
588
+ GBP: Object.freeze({
589
+ code: "GBP",
590
+ name: "British Pound",
591
+ symbol: "£",
592
+ minorUnits: 2,
593
+ paymentProvider: "STRIPE"
594
+ }),
595
+ AUD: Object.freeze({
596
+ code: "AUD",
597
+ name: "Australian Dollar",
598
+ symbol: "A$",
599
+ minorUnits: 2,
600
+ paymentProvider: "STRIPE"
601
+ })
602
+ });
603
+ /**
604
+ * The canonical supported code for a value, or null. Case-insensitive, as in
605
+ * billing. Whitespace is not silently accepted.
606
+ */
607
+ function toSupportedBillingCurrency(currency) {
608
+ if (typeof currency !== "string") return null;
609
+ const normalized = currency.toUpperCase();
610
+ return SUPPORTED_BILLING_CURRENCIES.find((code) => code === normalized) ?? null;
611
+ }
612
+ /** Metadata for a supported currency, or null when the code is not supported. */
613
+ function getSupportedBillingCurrencyInfo(currency) {
614
+ const code = toSupportedBillingCurrency(currency);
615
+ return code ? SUPPORTED_BILLING_CURRENCY_INFO[code] : null;
616
+ }
646
617
  const MAX_BILLING_AMOUNT = 1e9;
647
618
  /** Case-insensitive, as in billing. Whitespace is not silently accepted. */
648
619
  function isSupportedBillingCurrency(currency) {
@@ -705,12 +676,7 @@ function convertBillingToMinorUnits(amount, currency) {
705
676
  function validateBillingMoney(amount, currency, options = {}) {
706
677
  const validated = validateBillingAmount(amount, options);
707
678
  if (!validated.valid) return validated;
708
- if (typeof currency !== "string") return {
709
- valid: false,
710
- code: "unsupported_currency"
711
- };
712
- const normalized = currency.toUpperCase();
713
- const supported = SUPPORTED_BILLING_CURRENCIES.find((code) => code === normalized);
679
+ const supported = toSupportedBillingCurrency(currency);
714
680
  if (!supported) return {
715
681
  valid: false,
716
682
  code: "unsupported_currency"
@@ -741,16 +707,19 @@ var validation_exports = /* @__PURE__ */ __exportAll({
741
707
  RBAC_SCOPE_TYPES: () => RBAC_SCOPE_TYPES,
742
708
  RbacCoverageError: () => RbacCoverageError,
743
709
  SUPPORTED_BILLING_CURRENCIES: () => SUPPORTED_BILLING_CURRENCIES,
710
+ SUPPORTED_BILLING_CURRENCY_INFO: () => SUPPORTED_BILLING_CURRENCY_INFO,
744
711
  USERNAME_MAX_LENGTH: () => 30,
745
712
  USERNAME_MIN_LENGTH: () => 3,
746
713
  analyzeRbacCoverage: () => analyzeRbacCoverage,
747
714
  assertRbacCoverage: () => assertRbacCoverage,
748
715
  convertBillingToMinorUnits: () => convertBillingToMinorUnits,
716
+ getSupportedBillingCurrencyInfo: () => getSupportedBillingCurrencyInfo,
749
717
  isSupportedBillingCurrency: () => isSupportedBillingCurrency,
750
718
  lengthInCodePoints: () => lengthInCodePoints,
751
719
  loadRbacSchemaDocuments: () => loadRbacSchemaDocuments,
752
720
  rbacArgPathProblem: () => rbacArgPathProblem,
753
721
  readRbacDirectiveArgs: () => readRbacDirectiveArgs,
722
+ toSupportedBillingCurrency: () => toSupportedBillingCurrency,
754
723
  validateBillingAmount: () => validateBillingAmount,
755
724
  validateBillingMoney: () => validateBillingMoney,
756
725
  validateName: () => validateName,
@@ -758,5 +727,5 @@ var validation_exports = /* @__PURE__ */ __exportAll({
758
727
  validateUsername: () => validateUsername
759
728
  });
760
729
 
761
- export { NAME_MIN_LENGTH as C, NAME_MAX_LENGTH as S, validateName as T, readRbacDirectiveArgs as _, isSupportedBillingCurrency as a, USERNAME_MIN_LENGTH as b, DEFAULT_MAX_RBAC_ARG_PATH_SEGMENTS as c, RBAC_SCOPE_TYPES as d, RbacCoverageError as f, rbacArgPathProblem as g, loadRbacSchemaDocuments as h, convertBillingToMinorUnits as i, DEFAULT_RBAC_ROOT_TYPES as l, assertRbacCoverage as m, MAX_BILLING_AMOUNT as n, validateBillingAmount as o, analyzeRbacCoverage as p, SUPPORTED_BILLING_CURRENCIES as r, validateBillingMoney as s, validation_exports as t, RBAC_GATED_SCOPE_TYPES as u, validateUserFields as v, lengthInCodePoints as w, validateUsername as x, USERNAME_MAX_LENGTH as y };
762
- //# sourceMappingURL=validation-CPUITdMk.js.map
730
+ export { USERNAME_MIN_LENGTH as C, lengthInCodePoints as D, NAME_MIN_LENGTH as E, validateName as O, USERNAME_MAX_LENGTH as S, NAME_MAX_LENGTH as T, assertRbacCoverage as _, convertBillingToMinorUnits as a, readRbacDirectiveArgs as b, toSupportedBillingCurrency as c, DEFAULT_MAX_RBAC_ARG_PATH_SEGMENTS as d, DEFAULT_RBAC_ROOT_TYPES as f, analyzeRbacCoverage as g, RbacCoverageError as h, SUPPORTED_BILLING_CURRENCY_INFO as i, validateBillingAmount as l, RBAC_SCOPE_TYPES as m, MAX_BILLING_AMOUNT as n, getSupportedBillingCurrencyInfo as o, RBAC_GATED_SCOPE_TYPES as p, SUPPORTED_BILLING_CURRENCIES as r, isSupportedBillingCurrency as s, validation_exports as t, validateBillingMoney as u, loadRbacSchemaDocuments as v, validateUsername as w, validateUserFields as x, rbacArgPathProblem as y };
731
+ //# sourceMappingURL=validation-bwJzOytZ.js.map