@zonastery/bursar 2.0.1 → 2.0.3

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 (285) hide show
  1. package/README.md +22 -14
  2. package/dist/billing/auto-recharge-service.d.ts +1 -1
  3. package/dist/billing/auto-recharge-service.d.ts.map +1 -1
  4. package/dist/billing/auto-recharge-service.js +9 -6
  5. package/dist/billing/auto-recharge-service.js.map +1 -1
  6. package/dist/billing/billing-store.d.ts +4 -1
  7. package/dist/billing/billing-store.d.ts.map +1 -1
  8. package/dist/billing/billing-store.js +2 -0
  9. package/dist/billing/billing-store.js.map +1 -1
  10. package/dist/billing/contracts.d.ts +2 -1
  11. package/dist/billing/contracts.d.ts.map +1 -1
  12. package/dist/billing/contracts.js.map +1 -1
  13. package/dist/billing/event-handlers.d.ts +2 -3
  14. package/dist/billing/event-handlers.d.ts.map +1 -1
  15. package/dist/billing/event-handlers.js +38 -49
  16. package/dist/billing/event-handlers.js.map +1 -1
  17. package/dist/billing/event-processor.d.ts.map +1 -1
  18. package/dist/billing/event-processor.js +22 -10
  19. package/dist/billing/event-processor.js.map +1 -1
  20. package/dist/billing/financial-event-handlers.d.ts +2 -2
  21. package/dist/billing/financial-event-handlers.d.ts.map +1 -1
  22. package/dist/billing/financial-event-handlers.js +7 -7
  23. package/dist/billing/financial-event-handlers.js.map +1 -1
  24. package/dist/billing/postgres/repositories/auto-recharge.js +1 -1
  25. package/dist/billing/postgres/repositories/auto-recharge.js.map +1 -1
  26. package/dist/billing/postgres/repositories/event.d.ts.map +1 -1
  27. package/dist/billing/postgres/repositories/event.js +33 -1
  28. package/dist/billing/postgres/repositories/event.js.map +1 -1
  29. package/dist/billing/postgres/repositories/offer.d.ts +1 -1
  30. package/dist/billing/postgres/repositories/offer.d.ts.map +1 -1
  31. package/dist/billing/postgres/repositories/offer.js +1 -1
  32. package/dist/billing/postgres/repositories/offer.js.map +1 -1
  33. package/dist/billing/postgres/repositories/topup.d.ts +1 -1
  34. package/dist/billing/postgres/repositories/topup.d.ts.map +1 -1
  35. package/dist/billing/postgres/repositories/topup.js +1 -1
  36. package/dist/billing/postgres/repositories/topup.js.map +1 -1
  37. package/dist/billing/postgres/store.d.ts +6 -2
  38. package/dist/billing/postgres/store.d.ts.map +1 -1
  39. package/dist/billing/postgres/store.js +21 -6
  40. package/dist/billing/postgres/store.js.map +1 -1
  41. package/dist/billing/service-types.d.ts +2 -15
  42. package/dist/billing/service-types.d.ts.map +1 -1
  43. package/dist/billing/service-types.js.map +1 -1
  44. package/dist/billing/types/auto-recharge.d.ts +1 -1
  45. package/dist/billing/types/auto-recharge.d.ts.map +1 -1
  46. package/dist/billing/types/auto-recharge.js.map +1 -1
  47. package/dist/billing/types/catalog.d.ts +1 -1
  48. package/dist/billing/types/catalog.d.ts.map +1 -1
  49. package/dist/billing/types/catalog.js.map +1 -1
  50. package/dist/billing/types/documents.d.ts +1 -1
  51. package/dist/billing/types/documents.d.ts.map +1 -1
  52. package/dist/billing/types/documents.js.map +1 -1
  53. package/dist/billing/types/events.d.ts +11 -2
  54. package/dist/billing/types/events.d.ts.map +1 -1
  55. package/dist/billing/types/events.js +2 -2
  56. package/dist/billing/types/events.js.map +1 -1
  57. package/dist/billing/types/subscriptions.d.ts.map +1 -1
  58. package/dist/billing/types/subscriptions.js.map +1 -1
  59. package/dist/breakdown.d.ts +1 -1
  60. package/dist/breakdown.d.ts.map +1 -1
  61. package/dist/breakdown.js +1 -1
  62. package/dist/breakdown.js.map +1 -1
  63. package/dist/bursar.d.ts +21 -11
  64. package/dist/bursar.d.ts.map +1 -1
  65. package/dist/bursar.js +40 -4
  66. package/dist/bursar.js.map +1 -1
  67. package/dist/catalog.d.ts.map +1 -1
  68. package/dist/catalog.js +1 -1
  69. package/dist/catalog.js.map +1 -1
  70. package/dist/commerce/index.d.ts +0 -1
  71. package/dist/commerce/index.d.ts.map +1 -1
  72. package/dist/commerce/index.js +0 -1
  73. package/dist/commerce/index.js.map +1 -1
  74. package/dist/commerce/service.d.ts.map +1 -1
  75. package/dist/commerce/service.js +154 -106
  76. package/dist/commerce/service.js.map +1 -1
  77. package/dist/commerce/types.d.ts +9 -5
  78. package/dist/commerce/types.d.ts.map +1 -1
  79. package/dist/commerce/types.js.map +1 -1
  80. package/dist/config/parse-credits.d.ts.map +1 -1
  81. package/dist/config/parse-credits.js +0 -6
  82. package/dist/config/parse-credits.js.map +1 -1
  83. package/dist/config/parse-utils.d.ts +1 -1
  84. package/dist/config/parse-utils.d.ts.map +1 -1
  85. package/dist/config/parse-utils.js +1 -1
  86. package/dist/config/parse-utils.js.map +1 -1
  87. package/dist/config/types.d.ts +1 -6
  88. package/dist/config/types.d.ts.map +1 -1
  89. package/dist/config/types.js.map +1 -1
  90. package/dist/config.d.ts.map +1 -1
  91. package/dist/config.js +8 -1
  92. package/dist/config.js.map +1 -1
  93. package/dist/credits/amount.d.ts +8 -0
  94. package/dist/credits/amount.d.ts.map +1 -0
  95. package/dist/credits/amount.js +32 -0
  96. package/dist/credits/amount.js.map +1 -0
  97. package/dist/credits/catalog-runtime.d.ts +5 -7
  98. package/dist/credits/catalog-runtime.d.ts.map +1 -1
  99. package/dist/credits/catalog-runtime.js +4 -13
  100. package/dist/credits/catalog-runtime.js.map +1 -1
  101. package/dist/credits/lease-workflow.d.ts +2 -2
  102. package/dist/credits/lease-workflow.d.ts.map +1 -1
  103. package/dist/credits/lease-workflow.js +24 -21
  104. package/dist/credits/lease-workflow.js.map +1 -1
  105. package/dist/credits/low-balance-monitor.d.ts +1 -1
  106. package/dist/credits/low-balance-monitor.d.ts.map +1 -1
  107. package/dist/credits/low-balance-monitor.js +3 -4
  108. package/dist/credits/low-balance-monitor.js.map +1 -1
  109. package/dist/credits/postgres/repositories/balance.d.ts.map +1 -1
  110. package/dist/credits/postgres/repositories/balance.js +1 -1
  111. package/dist/credits/postgres/repositories/balance.js.map +1 -1
  112. package/dist/credits/postgres/repositories/bucket.js +1 -1
  113. package/dist/credits/postgres/repositories/bucket.js.map +1 -1
  114. package/dist/credits/postgres/repositories/lease.d.ts.map +1 -1
  115. package/dist/credits/postgres/repositories/lease.js +4 -2
  116. package/dist/credits/postgres/repositories/lease.js.map +1 -1
  117. package/dist/credits/postgres/repositories/team.d.ts +2 -1
  118. package/dist/credits/postgres/repositories/team.d.ts.map +1 -1
  119. package/dist/credits/postgres/repositories/team.js +19 -5
  120. package/dist/credits/postgres/repositories/team.js.map +1 -1
  121. package/dist/credits/postgres/store.d.ts +18 -14
  122. package/dist/credits/postgres/store.d.ts.map +1 -1
  123. package/dist/credits/postgres/store.js +30 -18
  124. package/dist/credits/postgres/store.js.map +1 -1
  125. package/dist/credits/postgres/value-mappers.d.ts +1 -1
  126. package/dist/credits/postgres/value-mappers.d.ts.map +1 -1
  127. package/dist/credits/postgres/value-mappers.js +1 -1
  128. package/dist/credits/postgres/value-mappers.js.map +1 -1
  129. package/dist/credits/service-errors.d.ts +1 -1
  130. package/dist/credits/service-errors.d.ts.map +1 -1
  131. package/dist/credits/service-errors.js +1 -1
  132. package/dist/credits/service-errors.js.map +1 -1
  133. package/dist/credits/service-types.d.ts +21 -16
  134. package/dist/credits/service-types.d.ts.map +1 -1
  135. package/dist/credits/service-types.js.map +1 -1
  136. package/dist/credits/service.d.ts +21 -17
  137. package/dist/credits/service.d.ts.map +1 -1
  138. package/dist/credits/service.js +81 -38
  139. package/dist/credits/service.js.map +1 -1
  140. package/dist/credits/store.d.ts +26 -23
  141. package/dist/credits/store.d.ts.map +1 -1
  142. package/dist/credits/store.js +4 -2
  143. package/dist/credits/store.js.map +1 -1
  144. package/dist/credits/types/account.d.ts +1 -1
  145. package/dist/credits/types/account.d.ts.map +1 -1
  146. package/dist/credits/types/account.js.map +1 -1
  147. package/dist/credits/types/grants.d.ts.map +1 -1
  148. package/dist/credits/types/grants.js.map +1 -1
  149. package/dist/credits/types/teams.d.ts +1 -0
  150. package/dist/credits/types/teams.d.ts.map +1 -1
  151. package/dist/credits/types/teams.js.map +1 -1
  152. package/dist/engine.js +1 -1
  153. package/dist/engine.js.map +1 -1
  154. package/dist/errors.d.ts +4 -0
  155. package/dist/errors.d.ts.map +1 -1
  156. package/dist/errors.js +34 -0
  157. package/dist/errors.js.map +1 -1
  158. package/dist/expr/ast.d.ts.map +1 -1
  159. package/dist/expr/ast.js.map +1 -1
  160. package/dist/expr/evaluator.d.ts +1 -1
  161. package/dist/expr/evaluator.d.ts.map +1 -1
  162. package/dist/expr/evaluator.js +1 -1
  163. package/dist/expr/evaluator.js.map +1 -1
  164. package/dist/expr/parser.d.ts +1 -0
  165. package/dist/expr/parser.d.ts.map +1 -1
  166. package/dist/expr/parser.js +15 -3
  167. package/dist/expr/parser.js.map +1 -1
  168. package/dist/expr.d.ts +1 -1
  169. package/dist/expr.d.ts.map +1 -1
  170. package/dist/expr.js +1 -1
  171. package/dist/expr.js.map +1 -1
  172. package/dist/generated/pricing-config.schema.json +31 -29
  173. package/dist/generated/pricing-config.types.d.ts +6 -18
  174. package/dist/generated/pricing-config.types.d.ts.map +1 -1
  175. package/dist/generated/pricing-config.types.js.map +1 -1
  176. package/dist/index.d.ts +7 -3
  177. package/dist/index.d.ts.map +1 -1
  178. package/dist/index.js +2 -0
  179. package/dist/index.js.map +1 -1
  180. package/dist/load-config-file.d.ts +2 -3
  181. package/dist/load-config-file.d.ts.map +1 -1
  182. package/dist/load-config-file.js +14 -29
  183. package/dist/load-config-file.js.map +1 -1
  184. package/dist/metrics.d.ts +1 -1
  185. package/dist/metrics.d.ts.map +1 -1
  186. package/dist/metrics.js.map +1 -1
  187. package/dist/node.d.ts +6 -3
  188. package/dist/node.d.ts.map +1 -1
  189. package/dist/node.js +1 -0
  190. package/dist/node.js.map +1 -1
  191. package/dist/providers/_shared.d.ts +3 -3
  192. package/dist/providers/_shared.d.ts.map +1 -1
  193. package/dist/providers/_shared.js +11 -6
  194. package/dist/providers/_shared.js.map +1 -1
  195. package/dist/providers/dodo/client-contract.d.ts +8 -13
  196. package/dist/providers/dodo/client-contract.d.ts.map +1 -1
  197. package/dist/providers/dodo/client-contract.js.map +1 -1
  198. package/dist/providers/dodo/event-mapper.d.ts +1 -1
  199. package/dist/providers/dodo/event-mapper.d.ts.map +1 -1
  200. package/dist/providers/dodo/event-mapper.js +23 -15
  201. package/dist/providers/dodo/event-mapper.js.map +1 -1
  202. package/dist/providers/dodo/provider.d.ts +4 -6
  203. package/dist/providers/dodo/provider.d.ts.map +1 -1
  204. package/dist/providers/dodo/provider.js +44 -82
  205. package/dist/providers/dodo/provider.js.map +1 -1
  206. package/dist/providers/dodo/webhook-bridge.d.ts +1 -2
  207. package/dist/providers/dodo/webhook-bridge.d.ts.map +1 -1
  208. package/dist/providers/dodo/webhook-bridge.js +0 -1
  209. package/dist/providers/dodo/webhook-bridge.js.map +1 -1
  210. package/dist/providers/environment.d.ts +6 -0
  211. package/dist/providers/environment.d.ts.map +1 -0
  212. package/dist/providers/environment.js +10 -0
  213. package/dist/providers/environment.js.map +1 -0
  214. package/dist/providers/index.d.ts +3 -7
  215. package/dist/providers/index.d.ts.map +1 -1
  216. package/dist/providers/index.js +1 -5
  217. package/dist/providers/index.js.map +1 -1
  218. package/dist/providers/mock/provider.d.ts +6 -8
  219. package/dist/providers/mock/provider.d.ts.map +1 -1
  220. package/dist/providers/mock/provider.js +18 -50
  221. package/dist/providers/mock/provider.js.map +1 -1
  222. package/dist/providers/stripe/event-mapper.d.ts.map +1 -1
  223. package/dist/providers/stripe/event-mapper.js +82 -14
  224. package/dist/providers/stripe/event-mapper.js.map +1 -1
  225. package/dist/providers/stripe/provider.d.ts +3 -3
  226. package/dist/providers/stripe/provider.d.ts.map +1 -1
  227. package/dist/providers/stripe/provider.js +37 -24
  228. package/dist/providers/stripe/provider.js.map +1 -1
  229. package/dist/providers/types.d.ts +9 -20
  230. package/dist/providers/types.d.ts.map +1 -1
  231. package/dist/providers/types.js.map +1 -1
  232. package/dist/shared/diagnostics.d.ts +8 -0
  233. package/dist/shared/diagnostics.d.ts.map +1 -1
  234. package/dist/shared/diagnostics.js +49 -0
  235. package/dist/shared/diagnostics.js.map +1 -1
  236. package/dist/shared/idempotency.d.ts +9 -0
  237. package/dist/shared/idempotency.d.ts.map +1 -0
  238. package/dist/shared/idempotency.js +34 -0
  239. package/dist/shared/idempotency.js.map +1 -0
  240. package/dist/shared/postgres-client.d.ts +7 -0
  241. package/dist/shared/postgres-client.d.ts.map +1 -1
  242. package/dist/shared/postgres-client.js +21 -4
  243. package/dist/shared/postgres-client.js.map +1 -1
  244. package/dist/shared/postgres-errors.d.ts.map +1 -1
  245. package/dist/shared/postgres-errors.js.map +1 -1
  246. package/dist/storage/adapters/clickhouse.d.ts +9 -2
  247. package/dist/storage/adapters/clickhouse.d.ts.map +1 -1
  248. package/dist/storage/adapters/clickhouse.js +142 -36
  249. package/dist/storage/adapters/clickhouse.js.map +1 -1
  250. package/dist/storage/adapters/s3.d.ts +44 -6
  251. package/dist/storage/adapters/s3.d.ts.map +1 -1
  252. package/dist/storage/adapters/s3.js +59 -21
  253. package/dist/storage/adapters/s3.js.map +1 -1
  254. package/dist/storage/diagnostics.d.ts +105 -0
  255. package/dist/storage/diagnostics.d.ts.map +1 -0
  256. package/dist/storage/diagnostics.js +227 -0
  257. package/dist/storage/diagnostics.js.map +1 -0
  258. package/dist/storage/maintenance.d.ts +88 -0
  259. package/dist/storage/maintenance.d.ts.map +1 -0
  260. package/dist/storage/maintenance.js +266 -0
  261. package/dist/storage/maintenance.js.map +1 -0
  262. package/dist/storage/outbox-worker.d.ts +20 -0
  263. package/dist/storage/outbox-worker.d.ts.map +1 -1
  264. package/dist/storage/outbox-worker.js +172 -42
  265. package/dist/storage/outbox-worker.js.map +1 -1
  266. package/dist/storage/ports.d.ts +43 -1
  267. package/dist/storage/ports.d.ts.map +1 -1
  268. package/dist/storage/ports.js.map +1 -1
  269. package/dist/storage/postgres-repository.d.ts +7 -2
  270. package/dist/storage/postgres-repository.d.ts.map +1 -1
  271. package/dist/storage/postgres-repository.js +155 -54
  272. package/dist/storage/postgres-repository.js.map +1 -1
  273. package/dist/storage/runtime.d.ts +30 -9
  274. package/dist/storage/runtime.d.ts.map +1 -1
  275. package/dist/storage/runtime.js +268 -37
  276. package/dist/storage/runtime.js.map +1 -1
  277. package/dist/telemetry/index.d.ts +37 -0
  278. package/dist/telemetry/index.d.ts.map +1 -0
  279. package/dist/telemetry/index.js +115 -0
  280. package/dist/telemetry/index.js.map +1 -0
  281. package/dist/telemetry/opentelemetry.d.ts +25 -0
  282. package/dist/telemetry/opentelemetry.d.ts.map +1 -0
  283. package/dist/telemetry/opentelemetry.js +74 -0
  284. package/dist/telemetry/opentelemetry.js.map +1 -0
  285. package/package.json +62 -36
@@ -1 +1 @@
1
- {"version":3,"file":"service-types.js","sourceRoot":"","sources":["../../src/credits/service-types.ts"],"names":[],"mappings":"","sourcesContent":["import type Decimal from \"decimal.js\";\n\nimport type { UsageMetrics } from \"../metrics.js\";\nimport type { Logger } from \"../shared/logger.js\";\nimport type { CreditEvent } from \"./events.js\";\nimport type {\n BillingMode,\n CreditMetadata,\n DeductionResult,\n DeductionSuccess,\n UsageAnalyticsStore,\n UsageChargeStore,\n} from \"./types/index.js\";\n\nexport type PolicyPreset = \"strict_prepaid\" | \"overdraft\";\nexport type MetricsOrAmount = UsageMetrics | Decimal | number;\n\nexport interface PostDeductionContext {\n userId: string;\n source: \"deduct\" | \"settle\" | \"raw\";\n deduction: DeductionSuccess;\n}\n\nexport interface LowBalanceConfig {\n thresholds?: (Decimal | number)[] | null;\n onTrigger?: ((event: CreditEvent) => void | Promise<void>) | null;\n /**\n * Maximum number of subjects whose breached-threshold state is retained in\n * memory. Defaults to 100,000.\n */\n maxTrackedUsers?: number;\n}\n\nexport interface CreditsServiceOptions {\n logger?: Logger | null;\n /**\n * Optional read-only analytics backend. Defaults to the credit store, which\n * keeps PostgreSQL as the zero-infrastructure behavior.\n */\n analytics?: UsageAnalyticsStore | null;\n /** Optional usage-history backend. Defaults to the credit store. */\n usageStore?: UsageChargeStore | null;\n /** Fallback credit policy for subjects without a plan assignment. */\n policy?: PolicyPreset;\n /** Planless-subject floor used with the `overdraft` fallback. */\n overdraftFloor?: Decimal | number | null;\n /** Planless-subject admission limit fallback. */\n maxConcurrent?: number | null;\n /**\n * Edge-triggered low-balance thresholds and optional non-blocking handler.\n * Defaults to zero when omitted.\n */\n lowBalance?: LowBalanceConfig | null;\n /** Default lease TTL in seconds. Defaults to 600. */\n defaultTtlSeconds?: number;\n /** Sweep a subject's expired credits before balance-sensitive operations. */\n lazyExpiry?: boolean;\n /**\n * Catalog cache TTL in milliseconds. A value of 0 disables automatic\n * reloads. Concurrent reloads are deduplicated. Defaults to 300,000.\n */\n catalogCacheTtlMs?: number;\n /**\n * Awaited after a committed, non-replayed deduction. Hook failures are\n * isolated from the committed credit charge.\n */\n postDeduction?: ((context: PostDeductionContext) => void | Promise<void>) | null;\n}\n\nexport interface AddCreditsOptions {\n type?: string;\n metadata?: CreditMetadata | null;\n expiresAt?: Date | null;\n /** Target credit bucket; omitted resolves to the catalog's default bucket. */\n bucket?: string | null;\n /** Stable replay key for the ledger mutation. */\n idempotencyKey?: string | null;\n}\n\nexport interface DeductCreditsOptions {\n entryType?: string;\n bucket?: string | null;\n metadata?: CreditMetadata | null;\n /** Stable replay key for the ledger mutation. */\n idempotencyKey?: string | null;\n}\n\nexport interface DeductOptions {\n idempotencyKey?: string | null;\n metadata?: CreditMetadata | null;\n /** Entitlement feature required for this operation. */\n feature?: string | null;\n}\n\nexport type DeductFlatJobOptions = DeductOptions;\n\nexport interface RecordUsageOptions {\n idempotencyKey?: string | null;\n metadata?: CreditMetadata | null;\n}\n\nexport interface RefundCreditsOptions {\n amount?: Decimal | number;\n reason?: string;\n metadata?: CreditMetadata | null;\n idempotencyKey?: string | null;\n}\n\nexport interface DeductTeamOptions {\n idempotencyKey?: string | null;\n metadata?: CreditMetadata | null;\n}\n\nexport interface ReserveOptions {\n /** Replay-safe acquisition key. A random key is generated when omitted. */\n idempotencyKey?: string | null;\n operationType?: string;\n billingMode?: BillingMode | null;\n ttl?: number | null;\n metadata?: CreditMetadata | null;\n feature?: string | null;\n /** Model tag used when reserving a raw amount instead of usage metrics. */\n model?: string | null;\n}\n\nexport interface SettleOptions {\n idempotencyKey?: string | null;\n metadata?: CreditMetadata | null;\n /** Entitlement key supplied at reserve time. */\n feature?: string | null;\n}\n\nexport interface CanAffordOptions {\n feature?: string | null;\n billingMode?: BillingMode | null;\n operationType?: string;\n}\n\nexport interface GrantSubscriptionCycleOptions {\n bucket?: string;\n expiresAt?: Date;\n ttlDays?: number;\n planKey?: string;\n idempotencyKey?: string;\n metadata?: CreditMetadata | null;\n}\n\nexport interface RunBilledOptions<T> {\n estimate: MetricsOrAmount;\n doWork: () => Promise<{ result: T; actual: MetricsOrAmount }>;\n operationType?: string;\n billingMode?: BillingMode | null;\n /** Stable key for the complete reserve/work/settle operation. */\n operationKey?: string | null;\n ttl?: number | null;\n feature?: string | null;\n metadata?: CreditMetadata | null;\n /** Settlement attempts for SDK-classified transient failures. Defaults to 3. */\n settlementAttempts?: number;\n}\n\nexport interface BeginBilledOperationOptions {\n estimate: MetricsOrAmount;\n /** Stable key for the complete reserve/settle operation. */\n operationKey: string;\n operationType?: string;\n billingMode?: BillingMode | null;\n ttl?: number | null;\n feature?: string | null;\n metadata?: CreditMetadata | null;\n}\n\nexport interface BilledOperation {\n readonly leaseId: string;\n readonly operationKey: string;\n settle(actual: MetricsOrAmount, metadata?: CreditMetadata | null): Promise<DeductionResult>;\n renew(ttl?: number | null): Promise<void>;\n release(): Promise<void>;\n}\n"]}
1
+ {"version":3,"file":"service-types.js","sourceRoot":"","sources":["../../src/credits/service-types.ts"],"names":[],"mappings":"","sourcesContent":["import type { Decimal } from \"decimal.js\";\n\nimport type { UsageMetrics } from \"../metrics.js\";\nimport type { Logger } from \"../shared/logger.js\";\nimport type { Instrumentation } from \"../telemetry/index.js\";\nimport type { CreditEvent } from \"./events.js\";\nimport type {\n BillingMode,\n CreditMetadata,\n DeductionResult,\n DeductionSuccess,\n UsageAnalyticsStore,\n UsageChargeStore,\n} from \"./types/index.js\";\n\nexport type PolicyPreset = \"strict_prepaid\" | \"overdraft\";\n/** Exact decimal credit input. Native numbers are intentionally excluded. */\nexport type ExactAmount = Decimal | string;\nexport type MetricsOrAmount = UsageMetrics | ExactAmount;\n\nexport interface PostDeductionContext {\n userId: string;\n source: \"deduct\" | \"settle\" | \"raw\";\n deduction: DeductionSuccess;\n}\n\nexport interface LowBalanceConfig {\n thresholds?: ExactAmount[] | null;\n onTrigger?: ((event: CreditEvent) => void | Promise<void>) | null;\n /**\n * Maximum number of subjects whose breached-threshold state is retained in\n * memory. Defaults to 100,000.\n */\n maxTrackedUsers?: number;\n}\n\nexport interface CreditsServiceOptions {\n logger?: Logger | null;\n /** Explicit telemetry implementation; falls back to Bursar's no-op registry. */\n instrumentation?: Instrumentation | null;\n /**\n * Optional read-only analytics backend. Defaults to the credit store, which\n * keeps PostgreSQL as the zero-infrastructure behavior.\n */\n analytics?: UsageAnalyticsStore | null;\n /** Optional usage-history backend. Defaults to the credit store. */\n usageStore?: UsageChargeStore | null;\n /** Fallback credit policy for subjects without a plan assignment. */\n policy?: PolicyPreset;\n /** Planless-subject floor used with the `overdraft` fallback. */\n overdraftFloor?: ExactAmount | null;\n /** Planless-subject admission limit fallback. */\n maxConcurrent?: number | null;\n /**\n * Edge-triggered low-balance thresholds and optional non-blocking handler.\n * Defaults to zero when omitted.\n */\n lowBalance?: LowBalanceConfig | null;\n /** Default lease TTL in seconds. Defaults to 600. */\n defaultTtlSeconds?: number;\n /** Sweep a subject's expired credits before balance-sensitive operations. */\n lazyExpiry?: boolean;\n /**\n * Catalog cache TTL in milliseconds. A value of 0 disables automatic\n * reloads. Concurrent reloads are deduplicated. Defaults to 300,000.\n */\n catalogCacheTtlMs?: number;\n /**\n * Awaited after a committed, non-replayed deduction. Hook failures are\n * isolated from the committed credit charge.\n */\n postDeduction?: ((context: PostDeductionContext) => void | Promise<void>) | null;\n}\n\nexport interface AddCreditsOptions {\n type?: string;\n metadata?: CreditMetadata | null;\n expiresAt?: Date | null;\n /** Target credit bucket; omitted resolves to the catalog's default bucket. */\n bucket?: string | null;\n /** Stable replay key for the ledger mutation. */\n idempotencyKey: string;\n}\n\nexport interface DeductCreditsOptions {\n entryType?: string;\n bucket?: string | null;\n metadata?: CreditMetadata | null;\n /** Stable replay key for the ledger mutation. */\n idempotencyKey: string;\n}\n\nexport interface DeductOptions {\n idempotencyKey: string;\n metadata?: CreditMetadata | null;\n /** Entitlement feature required for this operation. */\n feature?: string | null;\n}\n\nexport type DeductFlatJobOptions = DeductOptions;\n\nexport interface RecordUsageOptions {\n idempotencyKey: string;\n metadata?: CreditMetadata | null;\n}\n\nexport interface RefundCreditsOptions {\n amount?: ExactAmount;\n reason?: string;\n metadata?: CreditMetadata | null;\n idempotencyKey: string;\n}\n\nexport interface DeductTeamOptions {\n idempotencyKey: string;\n metadata?: CreditMetadata | null;\n}\n\nexport interface ReserveOptions {\n /** Caller-stable replay-safe acquisition key. */\n idempotencyKey: string;\n operationType?: string;\n billingMode?: BillingMode | null;\n ttl?: number | null;\n metadata?: CreditMetadata | null;\n feature?: string | null;\n /** Model tag used when reserving a raw amount instead of usage metrics. */\n model?: string | null;\n}\n\nexport interface SettleOptions {\n idempotencyKey?: string;\n metadata?: CreditMetadata | null;\n /** Entitlement key supplied at reserve time. */\n feature?: string | null;\n}\n\nexport interface CanAffordOptions {\n feature?: string | null;\n billingMode?: BillingMode | null;\n operationType?: string;\n}\n\nexport interface GrantSubscriptionCycleOptions {\n bucket?: string;\n expiresAt?: Date;\n ttlDays?: number;\n planKey?: string;\n idempotencyKey: string;\n metadata?: CreditMetadata | null;\n}\n\nexport interface RunBilledOptions<T> {\n estimate: MetricsOrAmount;\n doWork: () => Promise<{ result: T; actual: MetricsOrAmount }>;\n operationType?: string;\n billingMode?: BillingMode | null;\n /** Stable key for the complete reserve/work/settle operation. */\n operationKey: string;\n ttl?: number | null;\n feature?: string | null;\n metadata?: CreditMetadata | null;\n /** Settlement attempts for SDK-classified transient failures. Defaults to 3. */\n settlementAttempts?: number;\n}\n\nexport interface BeginBilledOperationOptions {\n estimate: MetricsOrAmount;\n /** Stable key for the complete reserve/settle operation. */\n operationKey: string;\n operationType?: string;\n billingMode?: BillingMode | null;\n ttl?: number | null;\n feature?: string | null;\n metadata?: CreditMetadata | null;\n}\n\nexport interface BilledOperation {\n readonly leaseId: string;\n readonly operationKey: string;\n settle(actual: MetricsOrAmount, metadata?: CreditMetadata | null): Promise<DeductionResult>;\n renew(ttl?: number | null): Promise<void>;\n release(): Promise<void>;\n}\n"]}
@@ -1,12 +1,11 @@
1
- import Decimal from "decimal.js";
2
1
  import type { PricingEngine } from "../engine.js";
3
- import type { CatalogRollout } from "../config.js";
2
+ import type { BursarConfigData, CatalogRollout } from "../config.js";
4
3
  import type { AddCreditsResult, AggregateStats, AllowanceResult, AvailableResult, BalanceResult, CatalogRevision, BucketBalancesResult, CanAffordResult, CheckFeatureResult, DailySpendRow, DeductionResult, ExecuteGrantProgramRequest, GetUserPlanResult, GrantProgramAwardResult, LedgerEntry, LedgerPage, LeaseSuccess, ListLedgerEntriesOptions, ListQuotaEventsOptions, ListUsageChargesOptions, ListUsageEntriesOptions, PlanMigrationBatchResult, PlanMigrationStartResult, QuotaEvent, QuotaState, RefundSuccess, RevokeCreditsResult, ReleaseResult, SetUserPlanResult, UnsetUserPlanResult, SpendByModelRow, SpendByUserRow, SweepResult, TeamDeductionResult, TopUserRow, UsageChargePage, UsageRecordResult } from "./types/index.js";
5
4
  import type { CreditStore } from "./store.js";
6
5
  import type { CreditEventEmitter } from "./events.js";
7
6
  import type { UsageMetrics } from "../metrics.js";
8
- import type { AddCreditsOptions, BeginBilledOperationOptions, BilledOperation, CanAffordOptions, CreditsServiceOptions, DeductCreditsOptions, DeductFlatJobOptions, DeductOptions, DeductTeamOptions, GrantSubscriptionCycleOptions, MetricsOrAmount, PostDeductionContext, RecordUsageOptions, RefundCreditsOptions, ReserveOptions, RunBilledOptions, SettleOptions } from "./service-types.js";
9
- export type { AddCreditsOptions, BeginBilledOperationOptions, BilledOperation, CanAffordOptions, CreditsServiceOptions, DeductCreditsOptions, DeductFlatJobOptions, DeductOptions, DeductTeamOptions, GrantSubscriptionCycleOptions, LowBalanceConfig, PolicyPreset, PostDeductionContext, RecordUsageOptions, RefundCreditsOptions, ReserveOptions, RunBilledOptions, SettleOptions, } from "./service-types.js";
7
+ import type { AddCreditsOptions, BeginBilledOperationOptions, BilledOperation, CanAffordOptions, CreditsServiceOptions, DeductCreditsOptions, DeductFlatJobOptions, DeductOptions, DeductTeamOptions, ExactAmount, GrantSubscriptionCycleOptions, MetricsOrAmount, PostDeductionContext, RecordUsageOptions, RefundCreditsOptions, ReserveOptions, RunBilledOptions, SettleOptions } from "./service-types.js";
8
+ export type { AddCreditsOptions, BeginBilledOperationOptions, BilledOperation, CanAffordOptions, CreditsServiceOptions, DeductCreditsOptions, DeductFlatJobOptions, DeductOptions, DeductTeamOptions, ExactAmount, GrantSubscriptionCycleOptions, LowBalanceConfig, PolicyPreset, PostDeductionContext, RecordUsageOptions, RefundCreditsOptions, ReserveOptions, RunBilledOptions, SettleOptions, } from "./service-types.js";
10
9
  /**
11
10
  * Orchestrates credit operations.
12
11
  *
@@ -29,6 +28,7 @@ export declare class CreditsService {
29
28
  private balanceMonitor;
30
29
  private lazyExpiry;
31
30
  private logger;
31
+ private readonly instrumentation;
32
32
  private readonly postDeductionHooks;
33
33
  constructor(store: CreditStore, engine?: PricingEngine | null, emitter?: CreditEventEmitter | null, options?: CreditsServiceOptions | null);
34
34
  /**
@@ -86,11 +86,11 @@ export declare class CreditsService {
86
86
  * a persistence failure surfaces to the caller instead of becoming an
87
87
  * unhandled promise rejection.
88
88
  */
89
- publishAndActivateCatalog(config: Record<string, unknown>, label?: string | null, rollout?: CatalogRollout | Record<string, unknown> | null): Promise<string>;
89
+ publishAndActivateCatalog(config: BursarConfigData, label?: string | null, rollout?: CatalogRollout | null): Promise<string>;
90
90
  /** Publish a validated, inactive catalog draft. */
91
- publishCatalogDraft(config: Record<string, unknown>, label?: string | null): Promise<string>;
91
+ publishCatalogDraft(config: BursarConfigData, label?: string | null): Promise<string>;
92
92
  /** Activate an existing catalog version and reload the local engine. */
93
- activateCatalogRevision(version: number, rollout?: CatalogRollout | Record<string, unknown> | null): Promise<string>;
93
+ activateCatalogRevision(version: number, rollout?: CatalogRollout | null): Promise<string>;
94
94
  /** The current PricingEngine, or null if not loaded. */
95
95
  get pricingEngine(): PricingEngine | null;
96
96
  /**
@@ -110,7 +110,8 @@ export declare class CreditsService {
110
110
  private maybeLazyExpire;
111
111
  getBalance(userId: string): Promise<BalanceResult>;
112
112
  /** Add credits to a user's account. */
113
- addCredits(userId: string, amount: Decimal | number, options?: AddCreditsOptions): Promise<AddCreditsResult>;
113
+ addCredits(userId: string, amount: ExactAmount, options: AddCreditsOptions): Promise<AddCreditsResult>;
114
+ private addCreditsUninstrumented;
114
115
  /**
115
116
  * Deduct a raw credit amount from a user's account.
116
117
  *
@@ -119,7 +120,7 @@ export declare class CreditsService {
119
120
  * Use this for refund clawbacks and other administrative deductions that
120
121
  * bypass the usage-based `deduct()` flow.
121
122
  */
122
- deductCredits(userId: string, amount: Decimal | number, options?: DeductCreditsOptions): Promise<AddCreditsResult>;
123
+ deductCredits(userId: string, amount: ExactAmount, options: DeductCreditsOptions): Promise<AddCreditsResult>;
123
124
  /**
124
125
  * Grant one billing-cycle's worth of credits — idempotent-safe for a
125
126
  * payment-provider webhook handler (Stripe, etc. — bursar stays
@@ -137,8 +138,9 @@ export declare class CreditsService {
137
138
  * 5. When ``planKey`` is given, assigns it via {@link setUserPlan}.
138
139
  * 6. Emits ``credits.cycle_renewed`` and returns the grant result.
139
140
  */
140
- grantSubscriptionCycle(userId: string, amount: Decimal | number, options?: GrantSubscriptionCycleOptions): Promise<AddCreditsResult>;
141
- reserve(userId: string, metricsOrAmount: MetricsOrAmount, options?: ReserveOptions): Promise<LeaseSuccess>;
141
+ grantSubscriptionCycle(userId: string, amount: ExactAmount, options: GrantSubscriptionCycleOptions): Promise<AddCreditsResult>;
142
+ private grantSubscriptionCycleUninstrumented;
143
+ reserve(userId: string, metricsOrAmount: MetricsOrAmount, options: ReserveOptions): Promise<LeaseSuccess>;
142
144
  settle(userId: string, leaseId: string, metricsOrAmount: MetricsOrAmount, options?: SettleOptions): Promise<DeductionResult>;
143
145
  release(userId: string, leaseId: string): Promise<ReleaseResult>;
144
146
  renew(userId: string, leaseId: string, ttl?: number | null): Promise<LeaseSuccess>;
@@ -161,14 +163,15 @@ export declare class CreditsService {
161
163
  * On a store ``error`` a ``credits.deduct_failed`` event is emitted and a
162
164
  * typed exception is thrown. No success event is emitted on error.
163
165
  */
164
- deduct(userId: string, metrics: UsageMetrics, options?: DeductOptions): Promise<DeductionResult>;
166
+ deduct(userId: string, metrics: UsageMetrics, options: DeductOptions): Promise<DeductionResult>;
167
+ private deductUninstrumented;
165
168
  /**
166
169
  * Record priced usage for a workflow without debiting the account again.
167
170
  *
168
171
  * This supports priced usage receipts that should be retained without
169
172
  * affecting the account balance, such as externally billed usage.
170
173
  */
171
- recordUsage(userId: string, metrics: UsageMetrics, options?: RecordUsageOptions): Promise<UsageRecordResult>;
174
+ recordUsage(userId: string, metrics: UsageMetrics, options: RecordUsageOptions): Promise<UsageRecordResult>;
172
175
  /**
173
176
  * Refund a previous credit deduction.
174
177
  *
@@ -178,16 +181,17 @@ export declare class CreditsService {
178
181
  * refund).
179
182
  */
180
183
  /** Deduct the configured fixed cost for one named job. */
181
- deductFlatJob(userId: string, jobName: string, options?: DeductFlatJobOptions): Promise<DeductionResult>;
182
- refundCredits(entryId: string, options?: RefundCreditsOptions): Promise<RefundSuccess>;
184
+ deductFlatJob(userId: string, jobName: string, options: DeductFlatJobOptions): Promise<DeductionResult>;
185
+ refundCredits(entryId: string, options: RefundCreditsOptions): Promise<RefundSuccess>;
186
+ private refundCreditsUninstrumented;
183
187
  /**
184
188
  * Deduct from a team's shared balance pool.
185
189
  *
186
190
  * Calculates the cost via the pricing engine (exact `Decimal`, no truncation),
187
- * then debits the team balance. Threads an optional ``idempotencyKey`` through
191
+ * then debits the team balance. Threads a required ``idempotencyKey`` through
188
192
  * to the store so retried team charges are not double-counted.
189
193
  */
190
- deductTeam(teamId: string, userId: string, metrics: UsageMetrics, options?: DeductTeamOptions): Promise<TeamDeductionResult>;
194
+ deductTeam(teamId: string, userId: string, metrics: UsageMetrics, options: DeductTeamOptions): Promise<TeamDeductionResult>;
191
195
  private runSweep;
192
196
  /**
193
197
  * Sweep expired credits from all users' balances.
@@ -1 +1 @@
1
- {"version":3,"file":"service.d.ts","sourceRoot":"","sources":["../../src/credits/service.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,YAAY,CAAC;AASjC,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAClD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AACnD,OAAO,KAAK,EACV,gBAAgB,EAChB,cAAc,EACd,eAAe,EACf,eAAe,EACf,aAAa,EACb,eAAe,EACf,oBAAoB,EACpB,eAAe,EACf,kBAAkB,EAElB,aAAa,EACb,eAAe,EAEf,0BAA0B,EAC1B,iBAAiB,EACjB,uBAAuB,EACvB,WAAW,EACX,UAAU,EACV,YAAY,EACZ,wBAAwB,EACxB,sBAAsB,EACtB,uBAAuB,EACvB,uBAAuB,EACvB,wBAAwB,EACxB,wBAAwB,EACxB,UAAU,EACV,UAAU,EACV,aAAa,EACb,mBAAmB,EACnB,aAAa,EACb,iBAAiB,EACjB,mBAAmB,EACnB,eAAe,EACf,cAAc,EACd,WAAW,EACX,mBAAmB,EACnB,UAAU,EACV,eAAe,EACf,iBAAiB,EAClB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAC9C,OAAO,KAAK,EAAE,kBAAkB,EAAmB,MAAM,aAAa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E,2BAA2B,GACnC,OAAO,CAAC,eAAe,CAAC;IAI3B;;;;;;;;;;OAUG;IACG,MAAM,CACV,MAAM,EAAE,MAAM,EACd,OAAO,EAAE,YAAY,EACrB,OAAO,EAAE,aAAa,GACrB,OAAO,CAAC,eAAe,CAAC;YAMb,oBAAoB;IAwFlC;;;;;OAKG;IACG,WAAW,CACf,MAAM,EAAE,MAAM,EACd,OAAO,EAAE,YAAY,EACrB,OAAO,EAAE,kBAAkB,GAC1B,OAAO,CAAC,iBAAiB,CAAC;IAgC7B;;;;;;;OAOG;IACH,0DAA0D;IACpD,aAAa,CACjB,MAAM,EAAE,MAAM,EACd,OAAO,EAAE,MAAM,EACf,OAAO,EAAE,oBAAoB,GAC5B,OAAO,CAAC,eAAe,CAAC;IAIrB,aAAa,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,oBAAoB,GAAG,OAAO,CAAC,aAAa,CAAC;YAM7E,2BAA2B;IA2CzC;;;;;;OAMG;IACG,UAAU,CACd,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,MAAM,EACd,OAAO,EAAE,YAAY,EACrB,OAAO,EAAE,iBAAiB,GACzB,OAAO,CAAC,mBAAmB,CAAC;YAoEjB,QAAQ;IAYtB;;;;;OAKG;IACG,mBAAmB,CAAC,MAAM,UAAQ,GAAG,OAAO,CAAC,WAAW,CAAC;CAGhE"}
@@ -1,11 +1,13 @@
1
- import Decimal from "decimal.js";
2
- import { randomUUID } from "node:crypto";
1
+ import { Decimal } from "decimal.js";
3
2
  import { CapReachedError, ConfigError, InsufficientCreditsError, RefundError, StoreError, } from "../errors.js";
4
3
  import { raiseDeductError } from "./service-errors.js";
5
4
  import { LowBalanceMonitor } from "./low-balance-monitor.js";
6
5
  import { CreditQueries } from "./queries.js";
7
- import { CatalogRuntime, toDecimal } from "./catalog-runtime.js";
6
+ import { CatalogRuntime } from "./catalog-runtime.js";
7
+ import { toDecimal } from "./amount.js";
8
8
  import { CreditLeaseWorkflow } from "./lease-workflow.js";
9
+ import { requireStableKey } from "../shared/idempotency.js";
10
+ import { getDefaultInstrumentation } from "../telemetry/index.js";
9
11
  /**
10
12
  * Default lease TTL (seconds) for ``reserve`` and ``runBilled``.
11
13
  * Long batch/agentic jobs call the configured lease TTL before this elapses.
@@ -45,9 +47,11 @@ export class CreditsService {
45
47
  // behaviour; explicit `sweepExpiredCredits`/cron remains required.
46
48
  lazyExpiry;
47
49
  logger;
50
+ instrumentation;
48
51
  postDeductionHooks = new Set();
49
52
  constructor(store, engine, emitter, options) {
50
53
  this.store = store;
54
+ this.instrumentation = options?.instrumentation ?? getDefaultInstrumentation();
51
55
  this.queries = new CreditQueries(store, options?.analytics ?? store, options?.usageStore ?? store);
52
56
  const policy = options?.policy ?? "strict_prepaid";
53
57
  if (!POLICY_PRESETS.has(policy)) {
@@ -120,7 +124,7 @@ export class CreditsService {
120
124
  }
121
125
  /** Execute an application-driven catalog grant program. */
122
126
  async executeGrantProgram(request) {
123
- return this.store.executeGrantProgram(request);
127
+ return this.instrumentation.run("credits.grant_program", undefined, () => this.store.executeGrantProgram(request));
124
128
  }
125
129
  async getLedgerEntry(userId, entryId) {
126
130
  return this.queries.getLedgerEntry(userId, entryId);
@@ -273,9 +277,17 @@ export class CreditsService {
273
277
  }
274
278
  /** Add credits to a user's account. */
275
279
  async addCredits(userId, amount, options) {
276
- const type = options?.type ?? "adjustment";
277
- this.logger.info("[CreditsService] addCredits", { amount, type, bucket: options?.bucket });
278
- const result = await this.store.addCredits(userId, positiveAmount(amount, "addCredits"), type, options?.metadata, options?.expiresAt, options?.bucket, options?.idempotencyKey);
280
+ return this.instrumentation.run("credits.grant", undefined, () => this.addCreditsUninstrumented(userId, amount, options));
281
+ }
282
+ async addCreditsUninstrumented(userId, amount, options) {
283
+ const idempotencyKey = requireStableKey(options?.idempotencyKey);
284
+ const type = options.type ?? "adjustment";
285
+ this.logger.info("[CreditsService] addCredits", { amount, type, bucket: options.bucket });
286
+ const result = await this.store.addCredits(userId, positiveAmount(amount, "addCredits"), {
287
+ ...options,
288
+ type,
289
+ idempotencyKey,
290
+ });
279
291
  this.emit("credits.added", userId, {
280
292
  entryId: result.entryId,
281
293
  amount: result.amount,
@@ -295,13 +307,19 @@ export class CreditsService {
295
307
  * bypass the usage-based `deduct()` flow.
296
308
  */
297
309
  async deductCredits(userId, amount, options) {
298
- const entryType = options?.entryType ?? "adjustment";
310
+ const idempotencyKey = requireStableKey(options?.idempotencyKey);
311
+ const entryType = options.entryType ?? "adjustment";
299
312
  this.logger.info("[CreditsService] deductCredits", {
300
313
  amount,
301
314
  entryType,
302
- bucket: options?.bucket,
315
+ bucket: options.bucket,
316
+ });
317
+ const result = await this.store.addCredits(userId, positiveAmount(amount, "deductCredits").neg(), {
318
+ type: entryType,
319
+ metadata: options.metadata,
320
+ bucket: options.bucket,
321
+ idempotencyKey,
303
322
  });
304
- const result = await this.store.addCredits(userId, positiveAmount(amount, "deductCredits").neg(), entryType, options?.metadata ?? null, null, options?.bucket ?? undefined, options?.idempotencyKey);
305
323
  this.emit("credits.deducted", userId, {
306
324
  entryId: result.entryId,
307
325
  amount: result.amount,
@@ -342,24 +360,34 @@ export class CreditsService {
342
360
  * 6. Emits ``credits.cycle_renewed`` and returns the grant result.
343
361
  */
344
362
  async grantSubscriptionCycle(userId, amount, options) {
363
+ return this.instrumentation.run("credits.grant_subscription_cycle", undefined, () => this.grantSubscriptionCycleUninstrumented(userId, amount, options));
364
+ }
365
+ async grantSubscriptionCycleUninstrumented(userId, amount, options) {
366
+ const idempotencyKey = requireStableKey(options?.idempotencyKey);
345
367
  this.logger.info("[CreditsService] grantSubscriptionCycle", {
346
368
  amount,
347
- bucket: options?.bucket,
348
- planKey: options?.planKey,
369
+ bucket: options.bucket,
370
+ planKey: options.planKey,
349
371
  });
350
- if (options?.expiresAt != null && options?.ttlDays != null) {
372
+ if (options.expiresAt != null && options.ttlDays != null) {
351
373
  throw new ConfigError("grantSubscriptionCycle: specify at most one of 'expiresAt' or 'ttlDays', not both");
352
374
  }
353
- const bucket = options?.bucket ?? "subscription";
354
- const expiresAt = options?.ttlDays != null
375
+ const bucket = options.bucket ?? "subscription";
376
+ const expiresAt = options.ttlDays != null
355
377
  ? new Date(Date.now() + options.ttlDays * 86_400_000)
356
- : options?.expiresAt;
378
+ : options.expiresAt;
357
379
  const amountDec = positiveAmount(amount, "grantSubscriptionCycle");
358
- const result = await this.store.addCredits(userId, amountDec, "purchase", options?.metadata, expiresAt, bucket, options?.idempotencyKey);
380
+ const result = await this.store.addCredits(userId, amountDec, {
381
+ type: "purchase",
382
+ metadata: options.metadata,
383
+ expiresAt,
384
+ bucket,
385
+ idempotencyKey,
386
+ });
359
387
  // The store contract exposes the mutation's replay result directly, avoiding
360
388
  // a racy lifetime-balance comparison and an extra database round trip.
361
389
  const isFreshGrant = !result.idempotent;
362
- if (options?.planKey) {
390
+ if (options.planKey) {
363
391
  // A fresh cycle intentionally re-anchors plan-assignment windows. On a
364
392
  // webhook replay, repair a previously interrupted grant->assignment saga
365
393
  // without re-anchoring an assignment that already succeeded.
@@ -372,21 +400,21 @@ export class CreditsService {
372
400
  amount: amountDec,
373
401
  newBalance: result.newBalance,
374
402
  bucket,
375
- planKey: options?.planKey ?? null,
376
- idempotencyKey: options?.idempotencyKey ?? null,
403
+ planKey: options.planKey ?? null,
404
+ idempotencyKey,
377
405
  idempotent: result.idempotent,
378
406
  });
379
407
  return result;
380
408
  }
381
409
  // ── Lease lifecycle: atomic admission ───────────────────────────────
382
410
  async reserve(userId, metricsOrAmount, options) {
383
- return this.leases.reserve(userId, metricsOrAmount, options);
411
+ return this.instrumentation.run("credits.reserve", undefined, () => this.leases.reserve(userId, metricsOrAmount, options));
384
412
  }
385
413
  async settle(userId, leaseId, metricsOrAmount, options) {
386
- return this.leases.settle(userId, leaseId, metricsOrAmount, options);
414
+ return this.instrumentation.run("credits.settle", undefined, () => this.leases.settle(userId, leaseId, metricsOrAmount, options));
387
415
  }
388
416
  async release(userId, leaseId) {
389
- return this.leases.release(userId, leaseId);
417
+ return this.instrumentation.run("credits.release", undefined, () => this.leases.release(userId, leaseId));
390
418
  }
391
419
  async renew(userId, leaseId, ttl) {
392
420
  return this.leases.renew(userId, leaseId, ttl);
@@ -418,21 +446,24 @@ export class CreditsService {
418
446
  * typed exception is thrown. No success event is emitted on error.
419
447
  */
420
448
  async deduct(userId, metrics, options) {
449
+ return this.instrumentation.run("credits.deduct", undefined, () => this.deductUninstrumented(userId, metrics, options));
450
+ }
451
+ async deductUninstrumented(userId, metrics, options) {
421
452
  await this.maybeLazyExpire(userId);
422
453
  this.logger.debug("[CreditsService] deduct", {
423
454
  model: metrics.dimensions?.model,
424
- feature: options?.feature,
455
+ feature: options.feature,
425
456
  });
426
457
  const engine = await this.catalogRuntime.engineForUser(userId);
427
458
  const plan = await this.store.getUserPlan(userId);
428
- const effectiveIdempotencyKey = options?.idempotencyKey ?? `usage:${randomUUID()}`;
459
+ const effectiveIdempotencyKey = requireStableKey(options?.idempotencyKey);
429
460
  // 1) Calculate cost as an exact Decimal, never truncated.
430
461
  const breakdown = engine.calculate(metrics, { rateCard: plan.rateCard ?? undefined });
431
462
  const cost = breakdown.total;
432
463
  // Build ledger metadata: caller fields FIRST, system fields LAST so the
433
464
  // protected system fields win.
434
465
  const meta = {};
435
- if (options?.metadata) {
466
+ if (options.metadata) {
436
467
  for (const [k, v] of Object.entries(options.metadata)) {
437
468
  if (v != null)
438
469
  meta[k] = v;
@@ -446,7 +477,7 @@ export class CreditsService {
446
477
  const deductionOptions = {
447
478
  idempotencyKey: effectiveIdempotencyKey,
448
479
  operation: metrics.operation,
449
- feature: options?.feature ?? null,
480
+ feature: options.feature ?? null,
450
481
  model: typeof metrics.dimensions?.model === "string" ? metrics.dimensions.model : null,
451
482
  region: typeof metrics.dimensions?.region === "string" ? metrics.dimensions.region : null,
452
483
  measures: { ...(metrics.measures ?? {}) },
@@ -464,7 +495,7 @@ export class CreditsService {
464
495
  error: result.error,
465
496
  amount: cost,
466
497
  model: metrics.dimensions?.model,
467
- feature: options?.feature,
498
+ feature: options.feature,
468
499
  });
469
500
  this.emit("credits.deduct_failed", userId, {
470
501
  error: result.error,
@@ -502,10 +533,10 @@ export class CreditsService {
502
533
  async recordUsage(userId, metrics, options) {
503
534
  const engine = await this.catalogRuntime.engineForUser(userId);
504
535
  const plan = await this.store.getUserPlan(userId);
505
- const effectiveIdempotencyKey = options?.idempotencyKey ?? `usage-record:${randomUUID()}`;
536
+ const effectiveIdempotencyKey = requireStableKey(options?.idempotencyKey);
506
537
  const breakdown = engine.calculate(metrics, { rateCard: plan.rateCard ?? undefined });
507
538
  const meta = {};
508
- if (options?.metadata) {
539
+ if (options.metadata) {
509
540
  for (const [key, value] of Object.entries(options.metadata)) {
510
541
  if (value != null)
511
542
  meta[key] = value;
@@ -543,13 +574,21 @@ export class CreditsService {
543
574
  return this.deduct(userId, { operation: jobName, measures: { jobs: 1 } }, options);
544
575
  }
545
576
  async refundCredits(entryId, options) {
546
- const refundAmount = options?.amount != null ? positiveAmount(options.amount, "refundCredits") : undefined;
577
+ return this.instrumentation.run("credits.refund", undefined, () => this.refundCreditsUninstrumented(entryId, options));
578
+ }
579
+ async refundCreditsUninstrumented(entryId, options) {
580
+ const idempotencyKey = requireStableKey(options?.idempotencyKey);
581
+ const refundAmount = options.amount != null ? positiveAmount(options.amount, "refundCredits") : undefined;
547
582
  this.logger.info("[CreditsService] refundCredits", {
548
583
  entryId,
549
584
  refundAmount,
550
- reason: options?.reason,
585
+ reason: options.reason,
586
+ });
587
+ const result = await this.store.refundCredits(entryId, {
588
+ ...options,
589
+ amount: refundAmount,
590
+ idempotencyKey,
551
591
  });
552
- const result = await this.store.refundCredits(entryId, refundAmount, options?.reason, options?.metadata, options?.idempotencyKey);
553
592
  if (result.error !== null) {
554
593
  this.logger.warn("[CreditsService] refundCredits failed", {
555
594
  entryId,
@@ -559,7 +598,7 @@ export class CreditsService {
559
598
  this.emit("credits.refund_failed", result.userId, {
560
599
  entryId,
561
600
  error: result.error,
562
- reason: options?.reason ?? null,
601
+ reason: options.reason ?? null,
563
602
  });
564
603
  }
565
604
  throw new RefundError(`Refund rejected: ${result.error}`);
@@ -569,7 +608,7 @@ export class CreditsService {
569
608
  refundEntryId: result.refundEntryId,
570
609
  amount: result.amount,
571
610
  newBalance: result.newBalance,
572
- reason: options?.reason ?? null,
611
+ reason: options.reason ?? null,
573
612
  });
574
613
  return result;
575
614
  }
@@ -577,10 +616,11 @@ export class CreditsService {
577
616
  * Deduct from a team's shared balance pool.
578
617
  *
579
618
  * Calculates the cost via the pricing engine (exact `Decimal`, no truncation),
580
- * then debits the team balance. Threads an optional ``idempotencyKey`` through
619
+ * then debits the team balance. Threads a required ``idempotencyKey`` through
581
620
  * to the store so retried team charges are not double-counted.
582
621
  */
583
622
  async deductTeam(teamId, userId, metrics, options) {
623
+ const idempotencyKey = requireStableKey(options?.idempotencyKey);
584
624
  await this.maybeLazyExpire(userId);
585
625
  // Lazy expiry is scoped to the individual member's credits, not the team's
586
626
  // shared pool — there's no per-team expiry concept.
@@ -604,13 +644,16 @@ export class CreditsService {
604
644
  };
605
645
  }
606
646
  const teamMetadata = {
607
- ...(options?.metadata ?? {}),
647
+ ...(options.metadata ?? {}),
608
648
  operation: metrics.operation,
609
649
  measures: { ...(metrics.measures ?? {}) },
610
650
  dimensions: Object.fromEntries(Object.entries(metrics.dimensions ?? {}).map(([key, value]) => [key, String(value)])),
611
651
  breakdownTotal: breakdown.total.toString(),
612
652
  };
613
- const result = await this.store.deductTeam(teamId, userId, cost, teamMetadata, options?.idempotencyKey);
653
+ const result = await this.store.deductTeam(teamId, userId, cost, {
654
+ metadata: teamMetadata,
655
+ idempotencyKey,
656
+ });
614
657
  // Surface store errors: emit credits.deduct_failed and throw,
615
658
  // mirroring the Python credit service implementation. Previously returned a silent
616
659
  // success-shaped object with an .error field, so failed charges looked OK.