@zonastery/bursar 0.0.2 → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +118 -333
- package/dist/billing/auto-recharge-port.d.ts +27 -0
- package/dist/billing/auto-recharge-port.d.ts.map +1 -0
- package/dist/billing/auto-recharge-port.js +2 -0
- package/dist/billing/auto-recharge-port.js.map +1 -0
- package/dist/billing/auto-recharge-service.d.ts +43 -0
- package/dist/billing/auto-recharge-service.d.ts.map +1 -0
- package/dist/billing/auto-recharge-service.js +218 -0
- package/dist/billing/auto-recharge-service.js.map +1 -0
- package/dist/billing/billing-service.d.ts +71 -0
- package/dist/billing/billing-service.d.ts.map +1 -0
- package/dist/billing/billing-service.js +172 -0
- package/dist/billing/billing-service.js.map +1 -0
- package/dist/billing/billing-store.d.ts +45 -13
- package/dist/billing/billing-store.d.ts.map +1 -1
- package/dist/billing/billing-store.js.map +1 -1
- package/dist/billing/contracts.d.ts +149 -0
- package/dist/billing/contracts.d.ts.map +1 -0
- package/dist/billing/contracts.js +2 -0
- package/dist/billing/contracts.js.map +1 -0
- package/dist/billing/event-handlers.d.ts +57 -0
- package/dist/billing/event-handlers.d.ts.map +1 -0
- package/dist/billing/event-handlers.js +684 -0
- package/dist/billing/event-handlers.js.map +1 -0
- package/dist/billing/event-processor.d.ts +20 -0
- package/dist/billing/event-processor.d.ts.map +1 -0
- package/dist/billing/event-processor.js +131 -0
- package/dist/billing/event-processor.js.map +1 -0
- package/dist/billing/financial-event-handlers.d.ts +26 -0
- package/dist/billing/financial-event-handlers.d.ts.map +1 -0
- package/dist/billing/financial-event-handlers.js +241 -0
- package/dist/billing/financial-event-handlers.js.map +1 -0
- package/dist/billing/index.d.ts +9 -5
- package/dist/billing/index.d.ts.map +1 -1
- package/dist/billing/index.js +4 -4
- package/dist/billing/index.js.map +1 -1
- package/dist/billing/management.d.ts +59 -0
- package/dist/billing/management.d.ts.map +1 -0
- package/dist/billing/management.js +113 -0
- package/dist/billing/management.js.map +1 -0
- package/dist/billing/policy-window.d.ts +24 -0
- package/dist/billing/policy-window.d.ts.map +1 -0
- package/dist/billing/policy-window.js +88 -0
- package/dist/billing/policy-window.js.map +1 -0
- package/dist/billing/postgres/repositories/auto-recharge.d.ts +32 -0
- package/dist/billing/postgres/repositories/auto-recharge.d.ts.map +1 -0
- package/dist/billing/postgres/repositories/auto-recharge.js +180 -0
- package/dist/billing/postgres/repositories/auto-recharge.js.map +1 -0
- package/dist/billing/postgres/repositories/customer.d.ts +12 -0
- package/dist/billing/postgres/repositories/customer.d.ts.map +1 -0
- package/dist/billing/postgres/repositories/customer.js +33 -0
- package/dist/billing/postgres/repositories/customer.js.map +1 -0
- package/dist/billing/postgres/repositories/dispute.d.ts +7 -0
- package/dist/billing/postgres/repositories/dispute.d.ts.map +1 -0
- package/dist/billing/postgres/repositories/dispute.js +18 -0
- package/dist/billing/postgres/repositories/dispute.js.map +1 -0
- package/dist/billing/postgres/repositories/event.d.ts +21 -0
- package/dist/billing/postgres/repositories/event.d.ts.map +1 -0
- package/dist/billing/postgres/repositories/event.js +45 -0
- package/dist/billing/postgres/repositories/event.js.map +1 -0
- package/dist/billing/postgres/repositories/invoice.d.ts +9 -0
- package/dist/billing/postgres/repositories/invoice.d.ts.map +1 -0
- package/dist/billing/postgres/repositories/invoice.js +36 -0
- package/dist/billing/postgres/repositories/invoice.js.map +1 -0
- package/dist/billing/postgres/repositories/offer.d.ts +26 -0
- package/dist/billing/postgres/repositories/offer.d.ts.map +1 -0
- package/dist/billing/postgres/repositories/offer.js +73 -0
- package/dist/billing/postgres/repositories/offer.js.map +1 -0
- package/dist/billing/postgres/repositories/payment.d.ts +32 -0
- package/dist/billing/postgres/repositories/payment.d.ts.map +1 -0
- package/dist/billing/postgres/repositories/payment.js +78 -0
- package/dist/billing/postgres/repositories/payment.js.map +1 -0
- package/dist/billing/postgres/repositories/preferences.d.ts +15 -0
- package/dist/billing/postgres/repositories/preferences.d.ts.map +1 -0
- package/dist/billing/postgres/repositories/preferences.js +23 -0
- package/dist/billing/postgres/repositories/preferences.js.map +1 -0
- package/dist/billing/postgres/repositories/refund.d.ts +7 -0
- package/dist/billing/postgres/repositories/refund.d.ts.map +1 -0
- package/dist/billing/postgres/repositories/refund.js +32 -0
- package/dist/billing/postgres/repositories/refund.js.map +1 -0
- package/dist/billing/postgres/repositories/subscription.d.ts +46 -0
- package/dist/billing/postgres/repositories/subscription.d.ts.map +1 -0
- package/dist/billing/postgres/repositories/subscription.js +187 -0
- package/dist/billing/postgres/repositories/subscription.js.map +1 -0
- package/dist/billing/postgres/repositories/topup.d.ts +27 -0
- package/dist/billing/postgres/repositories/topup.d.ts.map +1 -0
- package/dist/billing/postgres/repositories/topup.js +51 -0
- package/dist/billing/postgres/repositories/topup.js.map +1 -0
- package/dist/billing/postgres/store.d.ts +89 -0
- package/dist/billing/postgres/store.d.ts.map +1 -0
- package/dist/billing/postgres/store.js +542 -0
- package/dist/billing/postgres/store.js.map +1 -0
- package/dist/billing/service-types.d.ts +37 -0
- package/dist/billing/service-types.d.ts.map +1 -0
- package/dist/billing/service-types.js +2 -0
- package/dist/billing/service-types.js.map +1 -0
- package/dist/billing/types/auto-recharge.d.ts +56 -0
- package/dist/billing/types/auto-recharge.d.ts.map +1 -0
- package/dist/billing/types/auto-recharge.js +2 -0
- package/dist/billing/types/auto-recharge.js.map +1 -0
- package/dist/billing/types/catalog.d.ts +47 -0
- package/dist/billing/types/catalog.d.ts.map +1 -0
- package/dist/billing/types/catalog.js +2 -0
- package/dist/billing/types/catalog.js.map +1 -0
- package/dist/billing/types/common.d.ts +16 -0
- package/dist/billing/types/common.d.ts.map +1 -0
- package/dist/billing/types/common.js +2 -0
- package/dist/billing/types/common.js.map +1 -0
- package/dist/billing/types/documents.d.ts +39 -0
- package/dist/billing/types/documents.d.ts.map +1 -0
- package/dist/billing/types/documents.js +2 -0
- package/dist/billing/types/documents.js.map +1 -0
- package/dist/billing/types/events.d.ts +75 -0
- package/dist/billing/types/events.d.ts.map +1 -0
- package/dist/billing/types/events.js +38 -0
- package/dist/billing/types/events.js.map +1 -0
- package/dist/billing/types/index.d.ts +8 -0
- package/dist/billing/types/index.d.ts.map +1 -0
- package/dist/billing/types/index.js +8 -0
- package/dist/billing/types/index.js.map +1 -0
- package/dist/billing/types/preferences.d.ts +13 -0
- package/dist/billing/types/preferences.d.ts.map +1 -0
- package/dist/billing/types/preferences.js +2 -0
- package/dist/billing/types/preferences.js.map +1 -0
- package/dist/billing/types/subscriptions.d.ts +97 -0
- package/dist/billing/types/subscriptions.d.ts.map +1 -0
- package/dist/billing/types/subscriptions.js +12 -0
- package/dist/billing/types/subscriptions.js.map +1 -0
- package/dist/breakdown.d.ts +3 -1
- package/dist/breakdown.d.ts.map +1 -1
- package/dist/breakdown.js +4 -1
- package/dist/breakdown.js.map +1 -1
- package/dist/browser.d.ts +8 -0
- package/dist/browser.d.ts.map +1 -0
- package/dist/browser.js +7 -0
- package/dist/browser.js.map +1 -0
- package/dist/bursar.d.ts +84 -0
- package/dist/bursar.d.ts.map +1 -0
- package/dist/bursar.js +137 -0
- package/dist/bursar.js.map +1 -0
- package/dist/catalog.d.ts +62 -0
- package/dist/catalog.d.ts.map +1 -0
- package/dist/catalog.js +96 -0
- package/dist/catalog.js.map +1 -0
- package/dist/commerce/errors.d.ts +68 -0
- package/dist/commerce/errors.d.ts.map +1 -0
- package/dist/commerce/errors.js +105 -0
- package/dist/commerce/errors.js.map +1 -0
- package/dist/commerce/index.d.ts +6 -0
- package/dist/commerce/index.d.ts.map +1 -0
- package/dist/commerce/index.js +6 -0
- package/dist/commerce/index.js.map +1 -0
- package/dist/commerce/plan-change.d.ts +10 -0
- package/dist/commerce/plan-change.d.ts.map +1 -0
- package/dist/commerce/plan-change.js +42 -0
- package/dist/commerce/plan-change.js.map +1 -0
- package/dist/commerce/provider-registry.d.ts +18 -0
- package/dist/commerce/provider-registry.d.ts.map +1 -0
- package/dist/commerce/provider-registry.js +70 -0
- package/dist/commerce/provider-registry.js.map +1 -0
- package/dist/commerce/service.d.ts +73 -0
- package/dist/commerce/service.d.ts.map +1 -0
- package/dist/commerce/service.js +1016 -0
- package/dist/commerce/service.js.map +1 -0
- package/dist/commerce/types.d.ts +225 -0
- package/dist/commerce/types.d.ts.map +1 -0
- package/dist/commerce/types.js.map +1 -0
- package/dist/config/parse-access.d.ts +6 -0
- package/dist/config/parse-access.d.ts.map +1 -0
- package/dist/config/parse-access.js +72 -0
- package/dist/config/parse-access.js.map +1 -0
- package/dist/config/parse-commerce.d.ts +3 -0
- package/dist/config/parse-commerce.d.ts.map +1 -0
- package/dist/config/parse-commerce.js +236 -0
- package/dist/config/parse-commerce.js.map +1 -0
- package/dist/config/parse-credits.d.ts +3 -0
- package/dist/config/parse-credits.d.ts.map +1 -0
- package/dist/config/parse-credits.js +99 -0
- package/dist/config/parse-credits.js.map +1 -0
- package/dist/config/parse-plans.d.ts +5 -0
- package/dist/config/parse-plans.d.ts.map +1 -0
- package/dist/config/parse-plans.js +142 -0
- package/dist/config/parse-plans.js.map +1 -0
- package/dist/config/parse-pricing.d.ts +4 -0
- package/dist/config/parse-pricing.d.ts.map +1 -0
- package/dist/config/parse-pricing.js +252 -0
- package/dist/config/parse-pricing.js.map +1 -0
- package/dist/config/parse-utils.d.ts +18 -0
- package/dist/config/parse-utils.d.ts.map +1 -0
- package/dist/config/parse-utils.js +118 -0
- package/dist/config/parse-utils.js.map +1 -0
- package/dist/config/types.d.ts +340 -0
- package/dist/config/types.d.ts.map +1 -0
- package/dist/config/types.js +2 -0
- package/dist/config/types.js.map +1 -0
- package/dist/config.d.ts +12 -23
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +141 -377
- package/dist/config.js.map +1 -1
- package/dist/{stores → credits}/events.d.ts +6 -6
- package/dist/credits/events.d.ts.map +1 -0
- package/dist/{stores → credits}/events.js +5 -5
- package/dist/credits/events.js.map +1 -0
- package/dist/credits/lease-workflow.d.ts +90 -0
- package/dist/credits/lease-workflow.d.ts.map +1 -0
- package/dist/credits/lease-workflow.js +378 -0
- package/dist/credits/lease-workflow.js.map +1 -0
- package/dist/credits/low-balance-monitor.d.ts +26 -0
- package/dist/credits/low-balance-monitor.d.ts.map +1 -0
- package/dist/credits/low-balance-monitor.js +110 -0
- package/dist/credits/low-balance-monitor.js.map +1 -0
- package/dist/credits/postgres/repositories/analytics.d.ts +81 -0
- package/dist/credits/postgres/repositories/analytics.d.ts.map +1 -0
- package/dist/credits/postgres/repositories/analytics.js +153 -0
- package/dist/credits/postgres/repositories/analytics.js.map +1 -0
- package/dist/credits/postgres/repositories/balance.d.ts +66 -0
- package/dist/credits/postgres/repositories/balance.d.ts.map +1 -0
- package/dist/credits/postgres/repositories/balance.js +139 -0
- package/dist/credits/postgres/repositories/balance.js.map +1 -0
- package/dist/credits/postgres/repositories/bucket.d.ts +25 -0
- package/dist/credits/postgres/repositories/bucket.d.ts.map +1 -0
- package/dist/credits/postgres/repositories/bucket.js +52 -0
- package/dist/credits/postgres/repositories/bucket.js.map +1 -0
- package/dist/credits/postgres/repositories/deduction.d.ts +64 -0
- package/dist/credits/postgres/repositories/deduction.d.ts.map +1 -0
- package/dist/credits/postgres/repositories/deduction.js +154 -0
- package/dist/credits/postgres/repositories/deduction.js.map +1 -0
- package/dist/credits/postgres/repositories/lease.d.ts +69 -0
- package/dist/credits/postgres/repositories/lease.d.ts.map +1 -0
- package/dist/credits/postgres/repositories/lease.js +148 -0
- package/dist/credits/postgres/repositories/lease.js.map +1 -0
- package/dist/credits/postgres/repositories/plan.d.ts +110 -0
- package/dist/credits/postgres/repositories/plan.d.ts.map +1 -0
- package/dist/credits/postgres/repositories/plan.js +194 -0
- package/dist/credits/postgres/repositories/plan.js.map +1 -0
- package/dist/credits/postgres/repositories/pricing.d.ts +28 -0
- package/dist/credits/postgres/repositories/pricing.d.ts.map +1 -0
- package/dist/credits/postgres/repositories/pricing.js +76 -0
- package/dist/credits/postgres/repositories/pricing.js.map +1 -0
- package/dist/credits/postgres/repositories/team.d.ts +63 -0
- package/dist/credits/postgres/repositories/team.d.ts.map +1 -0
- package/dist/credits/postgres/repositories/team.js +120 -0
- package/dist/credits/postgres/repositories/team.js.map +1 -0
- package/dist/credits/postgres/store.d.ts +89 -0
- package/dist/credits/postgres/store.d.ts.map +1 -0
- package/dist/credits/postgres/store.js +838 -0
- package/dist/credits/postgres/store.js.map +1 -0
- package/dist/credits/postgres/value-mappers.d.ts +17 -0
- package/dist/credits/postgres/value-mappers.d.ts.map +1 -0
- package/dist/credits/postgres/value-mappers.js +102 -0
- package/dist/credits/postgres/value-mappers.js.map +1 -0
- package/dist/credits/pricing-runtime.d.ts +35 -0
- package/dist/credits/pricing-runtime.d.ts.map +1 -0
- package/dist/credits/pricing-runtime.js +141 -0
- package/dist/credits/pricing-runtime.js.map +1 -0
- package/dist/credits/queries.d.ts +33 -0
- package/dist/credits/queries.d.ts.map +1 -0
- package/dist/credits/queries.js +71 -0
- package/dist/credits/queries.js.map +1 -0
- package/dist/credits/service-errors.d.ts +4 -0
- package/dist/credits/service-errors.d.ts.map +1 -0
- package/dist/credits/service-errors.js +57 -0
- package/dist/credits/service-errors.js.map +1 -0
- package/dist/credits/service-types.d.ts +122 -0
- package/dist/credits/service-types.d.ts.map +1 -0
- package/dist/credits/service-types.js +2 -0
- package/dist/credits/service-types.js.map +1 -0
- package/dist/credits/service.d.ts +220 -0
- package/dist/credits/service.d.ts.map +1 -0
- package/dist/credits/service.js +640 -0
- package/dist/credits/service.js.map +1 -0
- package/dist/credits/store.d.ts +172 -0
- package/dist/credits/store.d.ts.map +1 -0
- package/dist/{stores/credit-store.js → credits/store.js} +27 -43
- package/dist/credits/store.js.map +1 -0
- package/dist/credits/types/account.d.ts +82 -0
- package/dist/credits/types/account.d.ts.map +1 -0
- package/dist/credits/types/account.js +2 -0
- package/dist/credits/types/account.js.map +1 -0
- package/dist/credits/types/admission.d.ts +39 -0
- package/dist/credits/types/admission.d.ts.map +1 -0
- package/dist/credits/types/admission.js +2 -0
- package/dist/credits/types/admission.js.map +1 -0
- package/dist/credits/types/analytics.d.ts +52 -0
- package/dist/credits/types/analytics.d.ts.map +1 -0
- package/dist/credits/types/analytics.js +2 -0
- package/dist/credits/types/analytics.js.map +1 -0
- package/dist/credits/types/catalog.d.ts +71 -0
- package/dist/credits/types/catalog.d.ts.map +1 -0
- package/dist/credits/types/catalog.js +2 -0
- package/dist/credits/types/catalog.js.map +1 -0
- package/dist/credits/types/grants.d.ts +24 -0
- package/dist/credits/types/grants.d.ts.map +1 -0
- package/dist/credits/types/grants.js +2 -0
- package/dist/credits/types/grants.js.map +1 -0
- package/dist/credits/types/index.d.ts +9 -0
- package/dist/credits/types/index.d.ts.map +1 -0
- package/dist/credits/types/index.js +2 -0
- package/dist/credits/types/index.js.map +1 -0
- package/dist/credits/types/ledger.d.ts +87 -0
- package/dist/credits/types/ledger.d.ts.map +1 -0
- package/dist/credits/types/ledger.js +2 -0
- package/dist/credits/types/ledger.js.map +1 -0
- package/dist/credits/types/quotas.d.ts +40 -0
- package/dist/credits/types/quotas.d.ts.map +1 -0
- package/dist/credits/types/quotas.js +2 -0
- package/dist/credits/types/quotas.js.map +1 -0
- package/dist/credits/types/teams.d.ts +44 -0
- package/dist/credits/types/teams.d.ts.map +1 -0
- package/dist/credits/types/teams.js +2 -0
- package/dist/credits/types/teams.js.map +1 -0
- package/dist/engine.d.ts +18 -39
- package/dist/engine.d.ts.map +1 -1
- package/dist/engine.js +169 -145
- package/dist/engine.js.map +1 -1
- package/dist/errors.d.ts +133 -25
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +173 -24
- package/dist/errors.js.map +1 -1
- package/dist/expr/ast.d.ts +46 -0
- package/dist/expr/ast.d.ts.map +1 -0
- package/dist/expr/ast.js +18 -0
- package/dist/expr/ast.js.map +1 -0
- package/dist/expr/evaluator.d.ts +4 -0
- package/dist/expr/evaluator.d.ts.map +1 -0
- package/dist/expr/evaluator.js +144 -0
- package/dist/expr/evaluator.js.map +1 -0
- package/dist/expr/language.d.ts +5 -0
- package/dist/expr/language.d.ts.map +1 -0
- package/dist/expr/language.js +73 -0
- package/dist/expr/language.js.map +1 -0
- package/dist/expr/parser.d.ts +24 -0
- package/dist/expr/parser.d.ts.map +1 -0
- package/dist/expr/parser.js +175 -0
- package/dist/expr/parser.js.map +1 -0
- package/dist/expr/tokenizer.d.ts +7 -0
- package/dist/expr/tokenizer.d.ts.map +1 -0
- package/dist/expr/tokenizer.js +85 -0
- package/dist/expr/tokenizer.js.map +1 -0
- package/dist/expr.d.ts +7 -58
- package/dist/expr.d.ts.map +1 -1
- package/dist/expr.js +41 -640
- package/dist/expr.js.map +1 -1
- package/dist/generated/pricing-config.schema.json +2792 -0
- package/dist/generated/pricing-config.types.d.ts +685 -0
- package/dist/generated/pricing-config.types.d.ts.map +1 -0
- package/dist/generated/pricing-config.types.js +8 -0
- package/dist/generated/pricing-config.types.js.map +1 -0
- package/dist/index.d.ts +23 -17
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +12 -10
- package/dist/index.js.map +1 -1
- package/dist/load-pricing-file.d.ts.map +1 -1
- package/dist/load-pricing-file.js +8 -4
- package/dist/load-pricing-file.js.map +1 -1
- package/dist/metrics.d.ts +6 -16
- package/dist/metrics.d.ts.map +1 -1
- package/dist/metrics.js.map +1 -1
- package/dist/node.d.ts +9 -2
- package/dist/node.d.ts.map +1 -1
- package/dist/node.js +6 -2
- package/dist/node.js.map +1 -1
- package/dist/providers/_shared.d.ts +9 -0
- package/dist/providers/_shared.d.ts.map +1 -0
- package/dist/providers/_shared.js +52 -0
- package/dist/providers/_shared.js.map +1 -0
- package/dist/providers/dodo/client-contract.d.ts +106 -0
- package/dist/providers/dodo/client-contract.d.ts.map +1 -0
- package/dist/providers/dodo/client-contract.js +2 -0
- package/dist/providers/dodo/client-contract.js.map +1 -0
- package/dist/providers/dodo/event-mapper.d.ts +5 -3
- package/dist/providers/dodo/event-mapper.d.ts.map +1 -1
- package/dist/providers/dodo/event-mapper.js +213 -38
- package/dist/providers/dodo/event-mapper.js.map +1 -1
- package/dist/providers/dodo/index.d.ts +1 -0
- package/dist/providers/dodo/index.d.ts.map +1 -1
- package/dist/providers/dodo/index.js.map +1 -1
- package/dist/providers/dodo/provider.d.ts +24 -14
- package/dist/providers/dodo/provider.d.ts.map +1 -1
- package/dist/providers/dodo/provider.js +249 -31
- package/dist/providers/dodo/provider.js.map +1 -1
- package/dist/providers/index.d.ts +3 -1
- package/dist/providers/index.d.ts.map +1 -1
- package/dist/providers/index.js +1 -0
- package/dist/providers/index.js.map +1 -1
- package/dist/providers/mock/index.js.map +1 -1
- package/dist/providers/mock/provider.d.ts +14 -10
- package/dist/providers/mock/provider.d.ts.map +1 -1
- package/dist/providers/mock/provider.js +78 -10
- package/dist/providers/mock/provider.js.map +1 -1
- package/dist/providers/stripe/event-mapper.d.ts +3 -3
- package/dist/providers/stripe/event-mapper.d.ts.map +1 -1
- package/dist/providers/stripe/event-mapper.js +139 -30
- package/dist/providers/stripe/event-mapper.js.map +1 -1
- package/dist/providers/stripe/index.js.map +1 -1
- package/dist/providers/stripe/provider.d.ts +21 -12
- package/dist/providers/stripe/provider.d.ts.map +1 -1
- package/dist/providers/stripe/provider.js +175 -17
- package/dist/providers/stripe/provider.js.map +1 -1
- package/dist/providers/types.d.ts +128 -32
- package/dist/providers/types.d.ts.map +1 -1
- package/dist/providers/types.js +17 -1
- package/dist/providers/types.js.map +1 -1
- package/dist/retry.d.ts +35 -0
- package/dist/retry.d.ts.map +1 -0
- package/dist/retry.js +70 -0
- package/dist/retry.js.map +1 -0
- package/dist/shared/diagnostics.d.ts +7 -0
- package/dist/shared/diagnostics.d.ts.map +1 -0
- package/dist/shared/diagnostics.js +18 -0
- package/dist/shared/diagnostics.js.map +1 -0
- package/dist/shared/logger.d.ts +10 -0
- package/dist/shared/logger.d.ts.map +1 -0
- package/dist/shared/logger.js +15 -0
- package/dist/shared/logger.js.map +1 -0
- package/dist/shared/postgres-client.d.ts +84 -0
- package/dist/shared/postgres-client.d.ts.map +1 -0
- package/dist/shared/postgres-client.js +337 -0
- package/dist/shared/postgres-client.js.map +1 -0
- package/dist/shared/postgres-errors.d.ts +11 -0
- package/dist/shared/postgres-errors.d.ts.map +1 -0
- package/dist/shared/postgres-errors.js +105 -0
- package/dist/shared/postgres-errors.js.map +1 -0
- package/dist/shared/postgres-types.d.ts +7 -0
- package/dist/shared/postgres-types.d.ts.map +1 -0
- package/dist/shared/postgres-types.js +2 -0
- package/dist/shared/postgres-types.js.map +1 -0
- package/dist/shared/postgres-validation.d.ts +8 -0
- package/dist/shared/postgres-validation.d.ts.map +1 -0
- package/dist/shared/postgres-validation.js +40 -0
- package/dist/shared/postgres-validation.js.map +1 -0
- package/dist/storage/adapters/clickhouse.d.ts +61 -0
- package/dist/storage/adapters/clickhouse.d.ts.map +1 -0
- package/dist/storage/adapters/clickhouse.js +347 -0
- package/dist/storage/adapters/clickhouse.js.map +1 -0
- package/dist/storage/adapters/s3.d.ts +35 -0
- package/dist/storage/adapters/s3.d.ts.map +1 -0
- package/dist/storage/adapters/s3.js +100 -0
- package/dist/storage/adapters/s3.js.map +1 -0
- package/dist/storage/outbox-worker.d.ts +41 -0
- package/dist/storage/outbox-worker.d.ts.map +1 -0
- package/dist/storage/outbox-worker.js +146 -0
- package/dist/storage/outbox-worker.js.map +1 -0
- package/dist/storage/ports.d.ts +78 -0
- package/dist/storage/ports.d.ts.map +1 -0
- package/dist/storage/ports.js +2 -0
- package/dist/storage/ports.js.map +1 -0
- package/dist/storage/postgres-repository.d.ts +14 -0
- package/dist/storage/postgres-repository.d.ts.map +1 -0
- package/dist/storage/postgres-repository.js +140 -0
- package/dist/storage/postgres-repository.js.map +1 -0
- package/dist/storage/runtime.d.ts +77 -0
- package/dist/storage/runtime.d.ts.map +1 -0
- package/dist/storage/runtime.js +369 -0
- package/dist/storage/runtime.js.map +1 -0
- package/package.json +43 -21
- package/dist/allowance.d.ts +0 -48
- package/dist/allowance.d.ts.map +0 -1
- package/dist/allowance.js +0 -140
- package/dist/allowance.js.map +0 -1
- package/dist/billing/billing-manager.d.ts +0 -66
- package/dist/billing/billing-manager.d.ts.map +0 -1
- package/dist/billing/billing-manager.js +0 -560
- package/dist/billing/billing-manager.js.map +0 -1
- package/dist/billing/billing-types.d.ts +0 -203
- package/dist/billing/billing-types.d.ts.map +0 -1
- package/dist/billing/billing-types.js +0 -6
- package/dist/billing/billing-types.js.map +0 -1
- package/dist/billing/memory-billing-store.d.ts +0 -37
- package/dist/billing/memory-billing-store.d.ts.map +0 -1
- package/dist/billing/memory-billing-store.js +0 -197
- package/dist/billing/memory-billing-store.js.map +0 -1
- package/dist/billing/postgres-billing-store.d.ts +0 -35
- package/dist/billing/postgres-billing-store.d.ts.map +0 -1
- package/dist/billing/postgres-billing-store.js +0 -274
- package/dist/billing/postgres-billing-store.js.map +0 -1
- package/dist/billing/supabase-billing-store.d.ts +0 -29
- package/dist/billing/supabase-billing-store.d.ts.map +0 -1
- package/dist/billing/supabase-billing-store.js +0 -250
- package/dist/billing/supabase-billing-store.js.map +0 -1
- package/dist/manager.d.ts +0 -444
- package/dist/manager.d.ts.map +0 -1
- package/dist/manager.js +0 -1153
- package/dist/manager.js.map +0 -1
- package/dist/stores/credit-store.d.ts +0 -198
- package/dist/stores/credit-store.d.ts.map +0 -1
- package/dist/stores/credit-store.js.map +0 -1
- package/dist/stores/events.d.ts.map +0 -1
- package/dist/stores/events.js.map +0 -1
- package/dist/stores/memory-store.d.ts +0 -187
- package/dist/stores/memory-store.d.ts.map +0 -1
- package/dist/stores/memory-store.js +0 -1890
- package/dist/stores/memory-store.js.map +0 -1
- package/dist/stores/postgres-store.d.ts +0 -100
- package/dist/stores/postgres-store.d.ts.map +0 -1
- package/dist/stores/postgres-store.js +0 -891
- package/dist/stores/postgres-store.js.map +0 -1
- package/dist/stores/supabase-store.d.ts +0 -87
- package/dist/stores/supabase-store.d.ts.map +0 -1
- package/dist/stores/supabase-store.js +0 -948
- package/dist/stores/supabase-store.js.map +0 -1
- package/dist/types.d.ts +0 -463
- package/dist/types.d.ts.map +0 -1
- package/dist/types.js.map +0 -1
- /package/dist/{types.js → commerce/types.js} +0 -0
package/dist/manager.js
DELETED
|
@@ -1,1153 +0,0 @@
|
|
|
1
|
-
import Decimal from "decimal.js";
|
|
2
|
-
import { CapReachedError, ConcurrencyLimitError, ConfigError, FeatureLimitReachedError, FeatureNotEntitledError, InsufficientCreditsError, LeaseExpiredError, LeaseNotFoundError, PricingNotLoadedError, RefundError, } from "./errors.js";
|
|
3
|
-
import { PricingEngine as PricingEngineClass } from "./engine.js";
|
|
4
|
-
import { resolveAllowanceWindow, resolveCalendarWindow } from "./allowance.js";
|
|
5
|
-
/**
|
|
6
|
-
* Default `low_balance` threshold multiplier (contract §6 / M18). The event
|
|
7
|
-
* fires when a deduction crosses ``minBalance * LOW_BALANCE_MULTIPLIER`` from
|
|
8
|
-
* above. Override via the ``lowBalance.thresholds`` constructor option to set
|
|
9
|
-
* an absolute threshold (or multiple levels) instead.
|
|
10
|
-
*/
|
|
11
|
-
const LOW_BALANCE_MULTIPLIER = 2;
|
|
12
|
-
/**
|
|
13
|
-
* Default lease TTL (seconds) for ``reserve``/``runBilled`` (interface plan §3).
|
|
14
|
-
* Long batch/agentic jobs call {@link CreditManager.renew} before this elapses.
|
|
15
|
-
*/
|
|
16
|
-
const DEFAULT_LEASE_TTL_SECONDS = 600;
|
|
17
|
-
/**
|
|
18
|
-
* Built-in financial-safety presets (interface plan §2). ``strict_prepaid``
|
|
19
|
-
* keeps the floor ``>= 0`` (structural zero debt); ``overdraft`` permits a
|
|
20
|
-
* negative floor and bills the full actual cost at settle.
|
|
21
|
-
*/
|
|
22
|
-
const POLICY_PRESETS = new Set(["strict_prepaid", "overdraft"]);
|
|
23
|
-
/** Coerce a `Decimal | number` money input into a `Decimal`. */
|
|
24
|
-
function toDecimal(value) {
|
|
25
|
-
return value instanceof Decimal ? value : new Decimal(value);
|
|
26
|
-
}
|
|
27
|
-
/** True when `value` is a raw money amount rather than a `UsageMetrics` object. */
|
|
28
|
-
function isAmount(value) {
|
|
29
|
-
return value instanceof Decimal || typeof value === "number";
|
|
30
|
-
}
|
|
31
|
-
/**
|
|
32
|
-
* Orchestrates credit operations.
|
|
33
|
-
*
|
|
34
|
-
* The deduction path is a single atomic, idempotency-keyed store call
|
|
35
|
-
* (``deductWithAllowance``) that consumes free allowance, enforces spend caps,
|
|
36
|
-
* applies the balance floor and debits the net amount in one transaction
|
|
37
|
-
* (contract §2). The manager is a thin layer that calculates the cost, maps
|
|
38
|
-
* the store's typed ``error`` codes to exceptions, and emits lifecycle events
|
|
39
|
-
* **only after** the operation has succeeded (contract §6).
|
|
40
|
-
*
|
|
41
|
-
* Optionally accepts a ``CreditEventEmitter`` to emit lifecycle events
|
|
42
|
-
* (deducted, deduct_failed, added, refunded, refund_failed, expired,
|
|
43
|
-
* cap_reached, cap_warning, low_balance).
|
|
44
|
-
*/
|
|
45
|
-
export class CreditManager {
|
|
46
|
-
store;
|
|
47
|
-
engine = null;
|
|
48
|
-
emitter = null;
|
|
49
|
-
// Financial-safety policy (interface plan §1/§2): `policy` is the preset default
|
|
50
|
-
// used for planless users; per-plan / per-call policy layers on top.
|
|
51
|
-
policy;
|
|
52
|
-
overdraftFloor;
|
|
53
|
-
defaultMaxConcurrent;
|
|
54
|
-
defaultTtl;
|
|
55
|
-
// Multi-level low_balance thresholds (interface plan §6), sorted high→low.
|
|
56
|
-
// Populated from `options.lowBalance.thresholds` (WS7); `null` means
|
|
57
|
-
// "unconfigured" — falls back to `[minBalance * LOW_BALANCE_MULTIPLIER]` lazily.
|
|
58
|
-
lowBalanceThresholds;
|
|
59
|
-
onLowBalance;
|
|
60
|
-
// Lazy-on-read credit expiry (closes the gap with allowance windows/lease
|
|
61
|
-
// TTLs, which are already lazy-on-read). Default `false` — unchanged
|
|
62
|
-
// behaviour; explicit `sweepExpiredCredits`/cron remains required.
|
|
63
|
-
lazyExpiry;
|
|
64
|
-
// Edge-trigger state: per-user set of thresholds currently breached ("below"),
|
|
65
|
-
// keyed by `.toString()`. A level re-arms only after the balance climbs back
|
|
66
|
-
// above it (a top-up).
|
|
67
|
-
lbBelow = new Map();
|
|
68
|
-
constructor(store, engine, emitter, options) {
|
|
69
|
-
const policy = options?.policy ?? "strict_prepaid";
|
|
70
|
-
if (!POLICY_PRESETS.has(policy)) {
|
|
71
|
-
throw new ConfigError(`unknown policy preset '${policy}'; expected one of ${[...POLICY_PRESETS].sort().join(", ")}`);
|
|
72
|
-
}
|
|
73
|
-
this.store = store;
|
|
74
|
-
if (engine)
|
|
75
|
-
this.engine = engine;
|
|
76
|
-
if (emitter)
|
|
77
|
-
this.emitter = emitter;
|
|
78
|
-
this.policy = policy;
|
|
79
|
-
this.overdraftFloor =
|
|
80
|
-
options?.overdraftFloor != null ? toDecimal(options.overdraftFloor) : null;
|
|
81
|
-
this.defaultMaxConcurrent = options?.maxConcurrent ?? null;
|
|
82
|
-
this.defaultTtl = options?.defaultTtlSeconds ?? DEFAULT_LEASE_TTL_SECONDS;
|
|
83
|
-
this.lowBalanceThresholds = options?.lowBalance?.thresholds?.length
|
|
84
|
-
? options.lowBalance.thresholds.map(toDecimal).sort((a, b) => b.comparedTo(a))
|
|
85
|
-
: null;
|
|
86
|
-
this.onLowBalance = options?.lowBalance?.onTrigger ?? null;
|
|
87
|
-
this.lazyExpiry = options?.lazyExpiry ?? false;
|
|
88
|
-
}
|
|
89
|
-
/** Emit a credit lifecycle event. No-op if no emitter is configured. */
|
|
90
|
-
emit(type, userId, data) {
|
|
91
|
-
this.emitter?.emit({ type, timestamp: new Date(), userId, data });
|
|
92
|
-
}
|
|
93
|
-
/** The configured min-balance floor as a `Decimal` (defaults to 0). */
|
|
94
|
-
minBalanceDecimal() {
|
|
95
|
-
return new Decimal(this.engine?.minBalance ?? 0);
|
|
96
|
-
}
|
|
97
|
-
/**
|
|
98
|
-
* Resolve the single `low_balance` threshold used by the ``deduct`` fast path:
|
|
99
|
-
* the lowest configured level when ``lowBalance.thresholds`` is set, otherwise
|
|
100
|
-
* ``minBalance * LOW_BALANCE_MULTIPLIER`` (documented default).
|
|
101
|
-
*/
|
|
102
|
-
resolveLowBalanceThreshold() {
|
|
103
|
-
if (this.lowBalanceThresholds) {
|
|
104
|
-
// `lowBalanceThresholds` is sorted high→low; the last element is lowest.
|
|
105
|
-
return this.lowBalanceThresholds[this.lowBalanceThresholds.length - 1];
|
|
106
|
-
}
|
|
107
|
-
return this.minBalanceDecimal().times(LOW_BALANCE_MULTIPLIER);
|
|
108
|
-
}
|
|
109
|
-
/** Run bundled SQL migrations through the store. */
|
|
110
|
-
async setup() {
|
|
111
|
-
return await this.store.setup();
|
|
112
|
-
}
|
|
113
|
-
/** Load pricing from a PricingConfigData or raw dict and sync it. */
|
|
114
|
-
async publishPricingFromDict(data) {
|
|
115
|
-
const raw = data;
|
|
116
|
-
this.engine = PricingEngineClass.fromDict(raw);
|
|
117
|
-
await this.store.setActivePricing(data);
|
|
118
|
-
}
|
|
119
|
-
/** Load the active pricing config from the store. */
|
|
120
|
-
async loadPricingFromStore() {
|
|
121
|
-
const active = await this.store.getActivePricing();
|
|
122
|
-
if (!active)
|
|
123
|
-
throw new PricingNotLoadedError("no active pricing config in store");
|
|
124
|
-
const { models, tools, search, cache, fixed, minBalance, plans } = active.config;
|
|
125
|
-
const engineDict = {
|
|
126
|
-
models,
|
|
127
|
-
tools: tools ?? { _default: "tool_calls * 0" },
|
|
128
|
-
search: search ?? null,
|
|
129
|
-
cache: cache ?? null,
|
|
130
|
-
fixed: fixed ?? {},
|
|
131
|
-
minBalance: minBalance ?? 0,
|
|
132
|
-
...(plans ? { plans } : {}),
|
|
133
|
-
};
|
|
134
|
-
this.engine = PricingEngineClass.fromDict(engineDict);
|
|
135
|
-
}
|
|
136
|
-
/**
|
|
137
|
-
* Publish new pricing and update the engine in one call.
|
|
138
|
-
*
|
|
139
|
-
* H10: the store write is now **awaited** (was a fire-and-forget `void`), so
|
|
140
|
-
* a persistence failure surfaces to the caller instead of becoming an
|
|
141
|
-
* unhandled promise rejection.
|
|
142
|
-
*/
|
|
143
|
-
async publishPricing(config, label) {
|
|
144
|
-
const { models, tools, search, cache, fixed, minBalance, plans } = config;
|
|
145
|
-
const raw = {
|
|
146
|
-
models,
|
|
147
|
-
tools: tools ?? { _default: "tool_calls * 0" },
|
|
148
|
-
search: search ?? null,
|
|
149
|
-
cache: cache ?? null,
|
|
150
|
-
fixed: fixed ?? {},
|
|
151
|
-
minBalance: minBalance ?? 0,
|
|
152
|
-
...(plans ? { plans } : {}),
|
|
153
|
-
};
|
|
154
|
-
this.engine = PricingEngineClass.fromDict(raw);
|
|
155
|
-
await this.store.setActivePricing(config, label);
|
|
156
|
-
}
|
|
157
|
-
/** The current PricingEngine, or null if not loaded. */
|
|
158
|
-
get pricingEngine() {
|
|
159
|
-
return this.engine;
|
|
160
|
-
}
|
|
161
|
-
/** Fetch a user's current plan (including feature entitlements). */
|
|
162
|
-
async getUserPlan(userId) {
|
|
163
|
-
return this.store.getUserPlan(userId);
|
|
164
|
-
}
|
|
165
|
-
/**
|
|
166
|
-
* Set a user's subscription plan and emit ``credits.plan_changed``.
|
|
167
|
-
*
|
|
168
|
-
* The store call is awaited so a persistence failure surfaces to the caller.
|
|
169
|
-
* The event is emitted only after the store write succeeds (contract §6).
|
|
170
|
-
*/
|
|
171
|
-
async setUserPlan(userId, planKey, planAssignedAt) {
|
|
172
|
-
const result = await this.store.setUserPlan(userId, planKey, planAssignedAt);
|
|
173
|
-
this.emit("credits.plan_changed", userId, {
|
|
174
|
-
userId,
|
|
175
|
-
planKey,
|
|
176
|
-
planAssignedAt: result.planAssignedAt ?? null,
|
|
177
|
-
timestamp: new Date().toISOString(),
|
|
178
|
-
});
|
|
179
|
-
}
|
|
180
|
-
/**
|
|
181
|
-
* Unset a user's subscription plan. Clears `plan_id` and `plan_assigned_at`
|
|
182
|
-
* so the allowance period is effectively paused. Call {@link setUserPlan} to
|
|
183
|
-
* re-assign and re-anchor the allowance window.
|
|
184
|
-
*/
|
|
185
|
-
async unsetUserPlan(userId) {
|
|
186
|
-
await this.store.unsetUserPlan(userId);
|
|
187
|
-
this.emit("credits.plan_changed", userId, {
|
|
188
|
-
userId,
|
|
189
|
-
planKey: null,
|
|
190
|
-
timestamp: new Date().toISOString(),
|
|
191
|
-
});
|
|
192
|
-
}
|
|
193
|
-
/**
|
|
194
|
-
* Check whether a user's plan has a specific feature entitlement.
|
|
195
|
-
*
|
|
196
|
-
* Passthrough to the store, which distinguishes *presence* from *truthiness*
|
|
197
|
-
* (numeric `0` / `""` count as present; only `null`/`undefined`/`false`/absent
|
|
198
|
-
* read as missing — contract §5 / M6).
|
|
199
|
-
*/
|
|
200
|
-
async checkFeature(userId, feature) {
|
|
201
|
-
return this.store.checkFeature(userId, feature);
|
|
202
|
-
}
|
|
203
|
-
/**
|
|
204
|
-
* Advisory, non-locking read of a per-feature invocation-count limit (UI only).
|
|
205
|
-
*
|
|
206
|
-
* Resolves the `FeatureLimit` (if any) from the user's plan and the
|
|
207
|
-
* calendar-aligned window, then delegates counting to the store. Returns
|
|
208
|
-
* `limited: false` (zeroed fields, `action: null`) when no `FeatureLimit`
|
|
209
|
-
* is configured for `feature` on the user's plan — never used for
|
|
210
|
-
* admission control; that is exclusively the atomic check-and-increment
|
|
211
|
-
* inside `deduct`/`reserve`.
|
|
212
|
-
*/
|
|
213
|
-
async checkFeatureLimit(userId, feature) {
|
|
214
|
-
const { limit, periodStart, periodEnd } = await this.resolveFeatureLimit(userId, feature);
|
|
215
|
-
if (limit == null || periodStart == null || periodEnd == null) {
|
|
216
|
-
return {
|
|
217
|
-
userId,
|
|
218
|
-
feature,
|
|
219
|
-
limited: false,
|
|
220
|
-
limit: 0,
|
|
221
|
-
used: 0,
|
|
222
|
-
remaining: 0,
|
|
223
|
-
periodStart: "",
|
|
224
|
-
periodEnd: "",
|
|
225
|
-
action: null,
|
|
226
|
-
};
|
|
227
|
-
}
|
|
228
|
-
const result = await this.store.checkFeatureLimit(userId, feature, limit.maxCalls, periodStart, periodEnd);
|
|
229
|
-
// The store only counts; the manager (which owns plan lookup) overrides
|
|
230
|
-
// `limited`/`action` from the resolved FeatureLimit (mirrors how
|
|
231
|
-
// checkAllowance overrides periodEnd after the store call).
|
|
232
|
-
return { ...result, limited: true, action: limit.action };
|
|
233
|
-
}
|
|
234
|
-
/**
|
|
235
|
-
* Sweep a single user's own expired credits when ``options.lazyExpiry`` is
|
|
236
|
-
* enabled — no-op otherwise. Mirrors the fact that allowance windows and
|
|
237
|
-
* lease TTLs are already lazy-on-read; this closes the same gap for the
|
|
238
|
-
* stored aggregate expiry balance without requiring a cron job.
|
|
239
|
-
*/
|
|
240
|
-
async maybeLazyExpire(userId) {
|
|
241
|
-
if (!this.lazyExpiry)
|
|
242
|
-
return;
|
|
243
|
-
await this.runSweep(false, userId);
|
|
244
|
-
}
|
|
245
|
-
/** Get a user's current credit balance. */
|
|
246
|
-
async getBalance(userId) {
|
|
247
|
-
await this.maybeLazyExpire(userId);
|
|
248
|
-
return await this.store.getBalance(userId);
|
|
249
|
-
}
|
|
250
|
-
/** Revoke all un-revoked credits of a given type for a user. */
|
|
251
|
-
async revokeCreditsByTxType(userId, txType) {
|
|
252
|
-
return this.store.revokeCreditsByTxType(userId, txType);
|
|
253
|
-
}
|
|
254
|
-
/** Fetch a single credit transaction by ID. Returns null when not found. */
|
|
255
|
-
async getTransaction(userId, transactionId) {
|
|
256
|
-
return await this.store.getTransaction(userId, transactionId);
|
|
257
|
-
}
|
|
258
|
-
/** Add credits to a user's account. */
|
|
259
|
-
async addCredits(userId, amount, options) {
|
|
260
|
-
const type = options?.type ?? "adjustment";
|
|
261
|
-
const result = await this.store.addCredits(userId, toDecimal(amount), type, options?.metadata, options?.expiresAt, options?.tier, options?.idempotencyKey);
|
|
262
|
-
this.emit("credits.added", userId, {
|
|
263
|
-
transactionId: result.transactionId,
|
|
264
|
-
amount: result.amount,
|
|
265
|
-
newBalance: result.newBalance,
|
|
266
|
-
type,
|
|
267
|
-
idempotent: result.idempotent ?? false,
|
|
268
|
-
});
|
|
269
|
-
// Re-arm multi-level low_balance: any level the topped-up balance is now back
|
|
270
|
-
// above can fire again on the next descent (interface plan §6).
|
|
271
|
-
if (this.lowBalanceThresholds) {
|
|
272
|
-
const below = this.lbBelow.get(userId) ?? new Set();
|
|
273
|
-
this.lbBelow.set(userId, below);
|
|
274
|
-
for (const t of this.lowBalanceThresholds) {
|
|
275
|
-
if (result.newBalance.gt(t))
|
|
276
|
-
below.delete(t.toString());
|
|
277
|
-
}
|
|
278
|
-
}
|
|
279
|
-
return result;
|
|
280
|
-
}
|
|
281
|
-
/**
|
|
282
|
-
* Deduct a raw credit amount from a user's account.
|
|
283
|
-
*
|
|
284
|
-
* Uses the store's `addCredits` with `type='adjustment'` and a negated
|
|
285
|
-
* amount — the existing validation path for negative/zero adjustments.
|
|
286
|
-
* Use this for refund clawbacks and other administrative deductions that
|
|
287
|
-
* bypass the usage-based `deduct()` flow.
|
|
288
|
-
*/
|
|
289
|
-
async deductCredits(userId, amount, options) {
|
|
290
|
-
const txType = options?.txType ?? "adjustment";
|
|
291
|
-
const result = await this.store.addCredits(userId, toDecimal(amount).neg(), "adjustment", options?.metadata ?? null, null, options?.tier ?? undefined, undefined);
|
|
292
|
-
this.emit("credits.deducted", userId, {
|
|
293
|
-
transactionId: result.transactionId,
|
|
294
|
-
amount: result.amount,
|
|
295
|
-
newBalance: result.newBalance,
|
|
296
|
-
txType,
|
|
297
|
-
});
|
|
298
|
-
return result;
|
|
299
|
-
}
|
|
300
|
-
/**
|
|
301
|
-
* Grant one billing-cycle's worth of credits — idempotent-safe for a
|
|
302
|
-
* payment-provider webhook handler (Stripe, etc. — bursar stays
|
|
303
|
-
* provider-agnostic) to call even on webhook redelivery.
|
|
304
|
-
*
|
|
305
|
-
* 1. At most one of ``expiresAt``/``ttlDays`` may be given (throws
|
|
306
|
-
* ``ConfigError`` otherwise).
|
|
307
|
-
* 2. When ``ttlDays`` is given, ``expiresAt = now + ttlDays`` days.
|
|
308
|
-
* 3. When ``replacePrior`` (default ``true``), any remaining balance in
|
|
309
|
-
* ``tier`` is expired immediately via a direct ``store.addCredits``
|
|
310
|
-
* negative adjustment — naturally idempotent (a replay finds the tier
|
|
311
|
-
* already at zero and skips the call).
|
|
312
|
-
* 4. The new cycle is granted via a direct ``store.addCredits`` call
|
|
313
|
-
* (bypassing {@link addCredits} so only ``credits.cycle_renewed`` fires,
|
|
314
|
-
* not a duplicate ``credits.added``), threading ``idempotencyKey`` so a
|
|
315
|
-
* redelivered webhook replays the prior grant instead of double-crediting.
|
|
316
|
-
* 5. When ``planKey`` is given, assigns it via {@link setUserPlan}.
|
|
317
|
-
* 6. Emits ``credits.cycle_renewed`` and returns the grant result.
|
|
318
|
-
*/
|
|
319
|
-
async grantSubscriptionCycle(userId, amount, options) {
|
|
320
|
-
if (options?.expiresAt != null && options?.ttlDays != null) {
|
|
321
|
-
throw new ConfigError("grantSubscriptionCycle: specify at most one of 'expiresAt' or 'ttlDays', not both");
|
|
322
|
-
}
|
|
323
|
-
const tier = options?.tier ?? "subscription";
|
|
324
|
-
const replacePrior = options?.replacePrior ?? true;
|
|
325
|
-
const expiresAt = options?.ttlDays != null
|
|
326
|
-
? new Date(Date.now() + options.ttlDays * 86_400_000)
|
|
327
|
-
: options?.expiresAt;
|
|
328
|
-
const amountDec = toDecimal(amount);
|
|
329
|
-
// Snapshot the tier's leftover balance and lifetimePurchased BEFORE granting.
|
|
330
|
-
// A redelivered webhook must be a full no-op -- including skipping the
|
|
331
|
-
// replace-prior wipe below -- not just avoiding a double-grant. AddCreditsResult
|
|
332
|
-
// carries no reliable cross-store "was this a replay" flag (Postgres/Supabase
|
|
333
|
-
// never populate `idempotent`), so a genuine new grant is detected after the
|
|
334
|
-
// fact by checking whether lifetimePurchased actually moved by `amountDec`; an
|
|
335
|
-
// idempotent replay leaves it unchanged.
|
|
336
|
-
let priorLeftover = new Decimal(0);
|
|
337
|
-
let preLifetimePurchased = new Decimal(0);
|
|
338
|
-
if (replacePrior) {
|
|
339
|
-
const tiersBefore = await this.getCreditTiers(userId);
|
|
340
|
-
const current = tiersBefore.tiers.find((t) => t.tierKey === tier);
|
|
341
|
-
if (current)
|
|
342
|
-
priorLeftover = current.balance;
|
|
343
|
-
preLifetimePurchased = (await this.getBalance(userId)).lifetimePurchased;
|
|
344
|
-
}
|
|
345
|
-
let result = await this.store.addCredits(userId, amountDec, "purchase", options?.metadata, expiresAt, tier, options?.idempotencyKey);
|
|
346
|
-
const isFreshGrant = result.lifetimePurchased.minus(preLifetimePurchased).eq(amountDec);
|
|
347
|
-
if (replacePrior && isFreshGrant && priorLeftover.gt(0)) {
|
|
348
|
-
await this.store.addCredits(userId, priorLeftover.negated(), "adjustment", { reason: "cycle_replaced" }, undefined, tier);
|
|
349
|
-
// Reflect the post-replace balance so the returned result is accurate
|
|
350
|
-
// (the grant call above only knows the pre-replace balance).
|
|
351
|
-
result = { ...result, newBalance: (await this.getBalance(userId)).balance };
|
|
352
|
-
}
|
|
353
|
-
if (options?.planKey) {
|
|
354
|
-
await this.setUserPlan(userId, options.planKey);
|
|
355
|
-
}
|
|
356
|
-
this.emit("credits.cycle_renewed", userId, {
|
|
357
|
-
transactionId: result.transactionId,
|
|
358
|
-
amount: amountDec,
|
|
359
|
-
newBalance: result.newBalance,
|
|
360
|
-
tier,
|
|
361
|
-
planKey: options?.planKey ?? null,
|
|
362
|
-
idempotencyKey: options?.idempotencyKey ?? null,
|
|
363
|
-
});
|
|
364
|
-
return result;
|
|
365
|
-
}
|
|
366
|
-
// ── Lease lifecycle: atomic admission (interface plan §3/§4) ────────
|
|
367
|
-
/** The default {@link OperationPolicy} from the constructor preset (§2). */
|
|
368
|
-
presetPolicy() {
|
|
369
|
-
if (this.policy === "overdraft") {
|
|
370
|
-
return {
|
|
371
|
-
billingMode: "overdraft",
|
|
372
|
-
maxConcurrent: this.defaultMaxConcurrent,
|
|
373
|
-
overdraftFloor: this.overdraftFloor ?? new Decimal(0),
|
|
374
|
-
};
|
|
375
|
-
}
|
|
376
|
-
return {
|
|
377
|
-
billingMode: "strict",
|
|
378
|
-
maxConcurrent: this.defaultMaxConcurrent,
|
|
379
|
-
overdraftFloor: null,
|
|
380
|
-
};
|
|
381
|
-
}
|
|
382
|
-
/**
|
|
383
|
-
* Resolve the effective policy: explicit arg → per-op → plan → preset (§1).
|
|
384
|
-
*
|
|
385
|
-
* A planless user (``planId`` is null) always gets the constructor preset, never
|
|
386
|
-
* silently unlimited (resolves M1). A user *with* a plan gets the plan default,
|
|
387
|
-
* then any ``perOperation`` override, then the explicit per-call ``billingMode``.
|
|
388
|
-
*/
|
|
389
|
-
async resolvePolicy(userId, operationType, billingModeOverride) {
|
|
390
|
-
let policy = this.presetPolicy();
|
|
391
|
-
let plan;
|
|
392
|
-
try {
|
|
393
|
-
plan = await this.store.getUserPlan(userId);
|
|
394
|
-
}
|
|
395
|
-
catch {
|
|
396
|
-
// A store outage shouldn't crash admission — fall back to the preset.
|
|
397
|
-
plan = null;
|
|
398
|
-
}
|
|
399
|
-
if (plan && plan.planId) {
|
|
400
|
-
policy = {
|
|
401
|
-
billingMode: plan.defaultBillingMode ?? "strict",
|
|
402
|
-
maxConcurrent: plan.maxConcurrent != null ? plan.maxConcurrent : policy.maxConcurrent,
|
|
403
|
-
overdraftFloor: plan.overdraftFloor != null ? plan.overdraftFloor : policy.overdraftFloor,
|
|
404
|
-
};
|
|
405
|
-
const op = plan.perOperation?.[operationType];
|
|
406
|
-
if (op) {
|
|
407
|
-
policy = {
|
|
408
|
-
billingMode: op.billingMode,
|
|
409
|
-
maxConcurrent: op.maxConcurrent != null ? op.maxConcurrent : policy.maxConcurrent,
|
|
410
|
-
overdraftFloor: op.overdraftFloor != null ? op.overdraftFloor : policy.overdraftFloor,
|
|
411
|
-
};
|
|
412
|
-
}
|
|
413
|
-
}
|
|
414
|
-
if (billingModeOverride != null) {
|
|
415
|
-
policy = { ...policy, billingMode: billingModeOverride };
|
|
416
|
-
}
|
|
417
|
-
return policy;
|
|
418
|
-
}
|
|
419
|
-
/** Admission floor for a policy: ``overdraftFloor`` (≤0) or ``minBalance`` (≥0). */
|
|
420
|
-
resolveFloor(policy) {
|
|
421
|
-
if (policy.billingMode === "overdraft") {
|
|
422
|
-
return policy.overdraftFloor ?? new Decimal(0);
|
|
423
|
-
}
|
|
424
|
-
return this.minBalanceDecimal();
|
|
425
|
-
}
|
|
426
|
-
/**
|
|
427
|
-
* Resolve the free-allowance period start for a user (WS9c).
|
|
428
|
-
*
|
|
429
|
-
* Fast path: a ``calendar_month`` plan (the default, and the vast majority of
|
|
430
|
-
* users) needs no computation — returns ``null`` and the store falls back to
|
|
431
|
-
* its own calendar-month window, exactly matching pre-WS9 behaviour. Only
|
|
432
|
-
* ``rolling_30d``/``anniversary`` plans pay the cost of resolving a window,
|
|
433
|
-
* anchored at the plan's ``planAssignedAt``.
|
|
434
|
-
*/
|
|
435
|
-
async resolveAllowancePeriodStart(userId) {
|
|
436
|
-
let plan;
|
|
437
|
-
try {
|
|
438
|
-
plan = await this.store.getUserPlan(userId);
|
|
439
|
-
}
|
|
440
|
-
catch {
|
|
441
|
-
return null;
|
|
442
|
-
}
|
|
443
|
-
if (!plan || !plan.allowancePeriod || plan.allowancePeriod === "calendar_month") {
|
|
444
|
-
return null;
|
|
445
|
-
}
|
|
446
|
-
const { start } = resolveAllowanceWindow(new Date(), plan.allowancePeriod, plan.planAssignedAt ?? null);
|
|
447
|
-
return start;
|
|
448
|
-
}
|
|
449
|
-
/**
|
|
450
|
-
* Resolve the `FeatureLimit` (if any) configured for `feature` on the
|
|
451
|
-
* user's plan, plus the calendar-aligned `[start, end)` window it applies
|
|
452
|
-
* to (via {@link resolveCalendarWindow}).
|
|
453
|
-
*
|
|
454
|
-
* Returns `{ limit: null, periodStart: null, periodEnd: null }` when
|
|
455
|
-
* `feature` is omitted or no limit is configured for it — the store then
|
|
456
|
-
* skips enforcement entirely (mirrors `resolveAllowancePeriodStart`).
|
|
457
|
-
*/
|
|
458
|
-
async resolveFeatureLimit(userId, feature) {
|
|
459
|
-
if (feature == null)
|
|
460
|
-
return { limit: null, periodStart: null, periodEnd: null };
|
|
461
|
-
let plan;
|
|
462
|
-
try {
|
|
463
|
-
plan = await this.store.getUserPlan(userId);
|
|
464
|
-
}
|
|
465
|
-
catch {
|
|
466
|
-
return { limit: null, periodStart: null, periodEnd: null };
|
|
467
|
-
}
|
|
468
|
-
const limit = plan?.featureLimits?.[feature] ?? null;
|
|
469
|
-
if (limit == null)
|
|
470
|
-
return { limit: null, periodStart: null, periodEnd: null };
|
|
471
|
-
const { start, end } = resolveCalendarWindow(new Date(), limit.period);
|
|
472
|
-
return { limit, periodStart: start, periodEnd: end };
|
|
473
|
-
}
|
|
474
|
-
/**
|
|
475
|
-
* Compute the credit cost and model from metrics, or pass a raw amount through.
|
|
476
|
-
*
|
|
477
|
-
* For {@link UsageMetrics} the cost is ``engine.calculate(...).total`` (exact
|
|
478
|
-
* `Decimal`, no truncation); a raw amount is used as-is with no model.
|
|
479
|
-
*/
|
|
480
|
-
costOf(metricsOrAmount) {
|
|
481
|
-
if (isAmount(metricsOrAmount)) {
|
|
482
|
-
return { amount: toDecimal(metricsOrAmount), model: null };
|
|
483
|
-
}
|
|
484
|
-
if (!this.engine) {
|
|
485
|
-
throw new PricingNotLoadedError("pricing not loaded: call loadPricingFromStore or publishPricing first");
|
|
486
|
-
}
|
|
487
|
-
const breakdown = this.engine.calculate(metricsOrAmount);
|
|
488
|
-
return { amount: breakdown.total, model: metricsOrAmount.model ?? null };
|
|
489
|
-
}
|
|
490
|
-
/** Map a store business code to the coherent typed exception (M2). */
|
|
491
|
-
raiseLeaseError(error, userId, amount) {
|
|
492
|
-
switch (error) {
|
|
493
|
-
case "concurrency_limit":
|
|
494
|
-
throw new ConcurrencyLimitError(`Concurrency limit reached. user=${userId}`);
|
|
495
|
-
case "cap_reached":
|
|
496
|
-
throw new CapReachedError(`Spend cap exceeded. user=${userId}, requested=${amount}`);
|
|
497
|
-
case "feature_limit_reached":
|
|
498
|
-
throw new FeatureLimitReachedError(`Feature limit reached. user=${userId}`);
|
|
499
|
-
case "feature_not_entitled":
|
|
500
|
-
throw new FeatureNotEntitledError(`Feature not entitled. user=${userId}`);
|
|
501
|
-
case "insufficient_credits":
|
|
502
|
-
throw new InsufficientCreditsError(`Insufficient credits. user=${userId}, requested=${amount}`);
|
|
503
|
-
case "lease_expired":
|
|
504
|
-
throw new LeaseExpiredError(`Lease expired. user=${userId}`);
|
|
505
|
-
case "lease_not_found":
|
|
506
|
-
case "not_found":
|
|
507
|
-
throw new LeaseNotFoundError(`Lease not found. user=${userId}`);
|
|
508
|
-
case "invalid_amount":
|
|
509
|
-
throw new RangeError(`Invalid amount: ${amount}`);
|
|
510
|
-
default:
|
|
511
|
-
throw new InsufficientCreditsError(`Operation failed: ${error}. user=${userId}`);
|
|
512
|
-
}
|
|
513
|
-
}
|
|
514
|
-
/**
|
|
515
|
-
* Atomically acquire a lease — the only admission control (D4).
|
|
516
|
-
*
|
|
517
|
-
* Resolves the effective policy, enforces ``requiredFeature``, sizes the hold
|
|
518
|
-
* from ``metricsOrAmount`` (worst-case in strict, estimate in overdraft — the
|
|
519
|
-
* caller chooses what to pass), and calls the store's atomic ``createLease``. On
|
|
520
|
-
* any business failure throws the coherent typed exception; on success emits
|
|
521
|
-
* ``credits.reserved`` and returns the {@link LeaseResult}.
|
|
522
|
-
*/
|
|
523
|
-
async reserve(userId, metricsOrAmount, options) {
|
|
524
|
-
await this.maybeLazyExpire(userId);
|
|
525
|
-
const operationType = options?.operationType ?? "usage";
|
|
526
|
-
const requiredFeature = options?.requiredFeature ?? null;
|
|
527
|
-
if (requiredFeature != null) {
|
|
528
|
-
const check = await this.store.checkFeature(userId, requiredFeature);
|
|
529
|
-
if (!check.hasFeature) {
|
|
530
|
-
throw new FeatureNotEntitledError(`Feature '${requiredFeature}' not entitled. user=${userId}`);
|
|
531
|
-
}
|
|
532
|
-
}
|
|
533
|
-
const policy = await this.resolvePolicy(userId, operationType, options?.billingMode);
|
|
534
|
-
const floor = this.resolveFloor(policy);
|
|
535
|
-
const { amount, model } = this.costOf(metricsOrAmount);
|
|
536
|
-
const ttlSeconds = options?.ttl != null ? options.ttl : this.defaultTtl;
|
|
537
|
-
const periodStart = await this.resolveAllowancePeriodStart(userId);
|
|
538
|
-
const feature = options?.feature ?? null;
|
|
539
|
-
const { limit: featureLimit, periodStart: featurePeriodStart } = await this.resolveFeatureLimit(userId, feature);
|
|
540
|
-
const result = await this.store.createLease(userId, amount, operationType, {
|
|
541
|
-
billingMode: policy.billingMode,
|
|
542
|
-
floor,
|
|
543
|
-
maxConcurrent: policy.maxConcurrent,
|
|
544
|
-
ttlSeconds,
|
|
545
|
-
model,
|
|
546
|
-
overdraftFloor: policy.overdraftFloor,
|
|
547
|
-
metadata: options?.metadata,
|
|
548
|
-
periodStart,
|
|
549
|
-
feature,
|
|
550
|
-
featureLimit,
|
|
551
|
-
featurePeriodStart,
|
|
552
|
-
});
|
|
553
|
-
if (result.error) {
|
|
554
|
-
this.emit("credits.deduct_failed", userId, {
|
|
555
|
-
error: result.error,
|
|
556
|
-
amount,
|
|
557
|
-
stage: "reserve",
|
|
558
|
-
operationType,
|
|
559
|
-
});
|
|
560
|
-
this.raiseLeaseError(result.error, userId, amount);
|
|
561
|
-
}
|
|
562
|
-
this.emit("credits.reserved", userId, {
|
|
563
|
-
leaseId: result.leaseId,
|
|
564
|
-
amount: result.amount,
|
|
565
|
-
available: result.available,
|
|
566
|
-
billingMode: result.billingMode,
|
|
567
|
-
operationType,
|
|
568
|
-
expiresAt: result.expiresAt,
|
|
569
|
-
});
|
|
570
|
-
return result;
|
|
571
|
-
}
|
|
572
|
-
/**
|
|
573
|
-
* Charge the ACTUAL cost against a lease and finalize it (D5).
|
|
574
|
-
*
|
|
575
|
-
* De-clamped: bills the full actual cost even if it exceeds the lease hold
|
|
576
|
-
* (overdraft). Never blocks on floor/cap at settle — a cap breach surfaces as a
|
|
577
|
-
* non-blocking ``credits.cap_warning``/``credits.cap_reached`` signal. Emits
|
|
578
|
-
* ``credits.deducted``, then multi-level ``credits.low_balance`` and a
|
|
579
|
-
* ``credits.overdraft`` signal if the balance went negative.
|
|
580
|
-
*/
|
|
581
|
-
async settle(userId, leaseId, metricsOrAmount, options) {
|
|
582
|
-
await this.maybeLazyExpire(userId);
|
|
583
|
-
const idempotencyKey = options?.idempotencyKey ?? null;
|
|
584
|
-
const { amount, model } = this.costOf(metricsOrAmount);
|
|
585
|
-
// Build transaction metadata: caller fields first, system fields last (M7).
|
|
586
|
-
const txMeta = {};
|
|
587
|
-
if (isAmount(metricsOrAmount)) {
|
|
588
|
-
if (options?.metadata) {
|
|
589
|
-
for (const [k, v] of Object.entries(options.metadata)) {
|
|
590
|
-
if (v != null)
|
|
591
|
-
txMeta[k] = v;
|
|
592
|
-
}
|
|
593
|
-
}
|
|
594
|
-
if (idempotencyKey)
|
|
595
|
-
txMeta["idempotencyKey"] = idempotencyKey;
|
|
596
|
-
}
|
|
597
|
-
else {
|
|
598
|
-
if (options?.metadata) {
|
|
599
|
-
for (const [k, v] of Object.entries(options.metadata)) {
|
|
600
|
-
if (v != null)
|
|
601
|
-
txMeta[k] = v;
|
|
602
|
-
}
|
|
603
|
-
}
|
|
604
|
-
txMeta["inputTokens"] = metricsOrAmount.inputTokens ?? 0;
|
|
605
|
-
txMeta["outputTokens"] = metricsOrAmount.outputTokens ?? 0;
|
|
606
|
-
txMeta["model"] = metricsOrAmount.model ?? "unknown";
|
|
607
|
-
txMeta["breakdownTotal"] = amount.toString();
|
|
608
|
-
if (metricsOrAmount.fixedJob)
|
|
609
|
-
txMeta["fixedJob"] = metricsOrAmount.fixedJob;
|
|
610
|
-
if (idempotencyKey)
|
|
611
|
-
txMeta["idempotencyKey"] = idempotencyKey;
|
|
612
|
-
}
|
|
613
|
-
const periodStart = await this.resolveAllowancePeriodStart(userId);
|
|
614
|
-
// The caller re-supplies the same `feature` at settle as at reserve time,
|
|
615
|
-
// exactly like `model` is re-supplied for per-model spend-cap accuracy.
|
|
616
|
-
const feature = options?.feature ?? null;
|
|
617
|
-
const { limit: featureLimit, periodStart: featurePeriodStart } = await this.resolveFeatureLimit(userId, feature);
|
|
618
|
-
const result = await this.store.settleLease(userId, leaseId, amount, {
|
|
619
|
-
idempotencyKey,
|
|
620
|
-
minBalance: this.engine ? new Decimal(this.engine.minBalance) : new Decimal(0),
|
|
621
|
-
model,
|
|
622
|
-
metadata: txMeta,
|
|
623
|
-
periodStart,
|
|
624
|
-
feature,
|
|
625
|
-
featureLimit,
|
|
626
|
-
featurePeriodStart,
|
|
627
|
-
});
|
|
628
|
-
if (result.error) {
|
|
629
|
-
this.emit("credits.deduct_failed", userId, {
|
|
630
|
-
error: result.error,
|
|
631
|
-
amount,
|
|
632
|
-
stage: "settle",
|
|
633
|
-
leaseId,
|
|
634
|
-
});
|
|
635
|
-
if (result.error === "lease_expired") {
|
|
636
|
-
this.emit("credits.lease_expired", userId, { leaseId });
|
|
637
|
-
}
|
|
638
|
-
this.raiseLeaseError(result.error, userId, amount);
|
|
639
|
-
}
|
|
640
|
-
this.emit("credits.deducted", userId, {
|
|
641
|
-
transactionId: result.transactionId,
|
|
642
|
-
amount: result.amount,
|
|
643
|
-
allowanceConsumed: result.allowanceConsumed,
|
|
644
|
-
balanceAfter: result.balanceAfter,
|
|
645
|
-
model,
|
|
646
|
-
leaseId,
|
|
647
|
-
idempotent: result.idempotent,
|
|
648
|
-
});
|
|
649
|
-
// Cap signal: 'deny' breaching at settle is non-blocking (work is done) and
|
|
650
|
-
// re-emitted as cap_reached; warn/notify as cap_warning (interface plan §7).
|
|
651
|
-
if (result.capWarning === "deny") {
|
|
652
|
-
this.emit("credits.cap_reached", userId, {
|
|
653
|
-
amount: result.amount,
|
|
654
|
-
model,
|
|
655
|
-
blocking: false,
|
|
656
|
-
});
|
|
657
|
-
}
|
|
658
|
-
else if (result.capWarning === "warn" || result.capWarning === "notify") {
|
|
659
|
-
this.emit("credits.cap_warning", userId, {
|
|
660
|
-
balanceAfter: result.balanceAfter,
|
|
661
|
-
amount: result.amount,
|
|
662
|
-
model,
|
|
663
|
-
action: result.capWarning,
|
|
664
|
-
});
|
|
665
|
-
}
|
|
666
|
-
// Feature-limit signal: mirrors the cap signal above ("prefer deny" was
|
|
667
|
-
// already applied by the store when choosing featureLimitWarning).
|
|
668
|
-
if (result.featureLimitWarning === "deny") {
|
|
669
|
-
this.emit("credits.feature_limit_reached", userId, {
|
|
670
|
-
feature,
|
|
671
|
-
amount: result.amount,
|
|
672
|
-
blocking: false,
|
|
673
|
-
});
|
|
674
|
-
}
|
|
675
|
-
else if (result.featureLimitWarning === "warn" || result.featureLimitWarning === "notify") {
|
|
676
|
-
this.emit("credits.feature_limit_warning", userId, {
|
|
677
|
-
feature,
|
|
678
|
-
action: result.featureLimitWarning,
|
|
679
|
-
amount: result.amount,
|
|
680
|
-
});
|
|
681
|
-
}
|
|
682
|
-
await this.postChargeSignals(userId, result);
|
|
683
|
-
return result;
|
|
684
|
-
}
|
|
685
|
-
/** Release a lease without charging (work failed/aborted) — idempotent (H1). */
|
|
686
|
-
async release(userId, leaseId) {
|
|
687
|
-
const result = await this.store.releaseLease(userId, leaseId);
|
|
688
|
-
if (result.released) {
|
|
689
|
-
this.emit("credits.reservation_released", userId, {
|
|
690
|
-
leaseId,
|
|
691
|
-
reason: result.reason,
|
|
692
|
-
});
|
|
693
|
-
}
|
|
694
|
-
return result;
|
|
695
|
-
}
|
|
696
|
-
/** Extend a lease's TTL for long batch/agentic jobs (B4). */
|
|
697
|
-
async renew(userId, leaseId, ttl) {
|
|
698
|
-
const ttlSeconds = ttl != null ? ttl : this.defaultTtl;
|
|
699
|
-
const result = await this.store.renewLease(userId, leaseId, ttlSeconds);
|
|
700
|
-
if (result.error) {
|
|
701
|
-
if (result.error === "lease_expired") {
|
|
702
|
-
this.emit("credits.lease_expired", userId, { leaseId });
|
|
703
|
-
}
|
|
704
|
-
this.raiseLeaseError(result.error, userId, new Decimal(0));
|
|
705
|
-
}
|
|
706
|
-
return result;
|
|
707
|
-
}
|
|
708
|
-
/**
|
|
709
|
-
* Advisory affordability check — UI only, non-locking, may be stale (D4/H3).
|
|
710
|
-
*
|
|
711
|
-
* Never use this as an admission gate; only ``reserve`` is authoritative.
|
|
712
|
-
*/
|
|
713
|
-
async canAfford(userId, metricsOrAmount, options) {
|
|
714
|
-
await this.maybeLazyExpire(userId);
|
|
715
|
-
const operationType = options?.operationType ?? "usage";
|
|
716
|
-
const requiredFeature = options?.requiredFeature ?? null;
|
|
717
|
-
const { amount: worstCase } = this.costOf(metricsOrAmount);
|
|
718
|
-
const avail = await this.store.getAvailable(userId);
|
|
719
|
-
const policy = await this.resolvePolicy(userId, operationType, options?.billingMode);
|
|
720
|
-
const floor = this.resolveFloor(policy);
|
|
721
|
-
let affordable = true;
|
|
722
|
-
let reason = null;
|
|
723
|
-
if (requiredFeature != null) {
|
|
724
|
-
const check = await this.store.checkFeature(userId, requiredFeature);
|
|
725
|
-
if (!check.hasFeature) {
|
|
726
|
-
affordable = false;
|
|
727
|
-
reason = "feature_not_entitled";
|
|
728
|
-
}
|
|
729
|
-
}
|
|
730
|
-
if (affordable && avail.available.minus(worstCase).lt(floor)) {
|
|
731
|
-
affordable = false;
|
|
732
|
-
reason = "insufficient_credits";
|
|
733
|
-
}
|
|
734
|
-
return { affordable, spendable: avail.available, worstCase, reason };
|
|
735
|
-
}
|
|
736
|
-
/** Advisory ``available = balance − Σ active holds`` read (UI only, D4/H3). */
|
|
737
|
-
async getAvailable(userId) {
|
|
738
|
-
await this.maybeLazyExpire(userId);
|
|
739
|
-
return await this.store.getAvailable(userId);
|
|
740
|
-
}
|
|
741
|
-
/** Get a user's per-tier credit balances (credit tiers). Thin pass-through, no event emission. */
|
|
742
|
-
async getCreditTiers(userId) {
|
|
743
|
-
await this.maybeLazyExpire(userId);
|
|
744
|
-
return await this.store.getCreditTiers(userId);
|
|
745
|
-
}
|
|
746
|
-
/**
|
|
747
|
-
* Get remaining free allowance for the current billing period.
|
|
748
|
-
*
|
|
749
|
-
* Convenience wrapper that routes through the manager so callers never need
|
|
750
|
-
* to reach past it into the raw store. Returns a zero-allowance result for
|
|
751
|
-
* planless users (no exception).
|
|
752
|
-
*
|
|
753
|
-
* For ``rolling_30d``/``anniversary`` plans (WS9), resolves and threads
|
|
754
|
-
* ``periodStart`` so the reported window matches the one actually used by
|
|
755
|
-
* ``deduct``/``settle``/``reserve`` — a ``calendar_month`` plan (the default)
|
|
756
|
-
* takes the fast path unchanged.
|
|
757
|
-
*/
|
|
758
|
-
async checkAllowance(userId) {
|
|
759
|
-
const plan = await this.store.getUserPlan(userId);
|
|
760
|
-
if (!plan.planId || !plan.allowancePeriod || plan.allowancePeriod === "calendar_month") {
|
|
761
|
-
return await this.store.checkAllowance(userId);
|
|
762
|
-
}
|
|
763
|
-
const { start, end } = resolveAllowanceWindow(new Date(), plan.allowancePeriod, plan.planAssignedAt ?? null);
|
|
764
|
-
const result = await this.store.checkAllowance(userId, start);
|
|
765
|
-
// The store/SQL layer only knows a generic calendar-month periodEnd (see
|
|
766
|
-
// 004_plans.sql / 009_deduct_and_leases.sql); override it here with the
|
|
767
|
-
// authoritative window this manager resolved.
|
|
768
|
-
const periodEnd = new Date(end.getTime() - 86_400_000);
|
|
769
|
-
return {
|
|
770
|
-
...result,
|
|
771
|
-
periodStart: start.toISOString(),
|
|
772
|
-
periodEnd: periodEnd.toISOString(),
|
|
773
|
-
};
|
|
774
|
-
}
|
|
775
|
-
/**
|
|
776
|
-
* One-call shortcut wiring reserve → doWork → settle (interface plan §4).
|
|
777
|
-
*
|
|
778
|
-
* ``doWork`` runs the operation and returns ``{ result, actual }`` where
|
|
779
|
-
* ``actual`` is the real usage metrics (or amount) to settle. On any exception
|
|
780
|
-
* from ``doWork`` the lease is released and the error re-raised. For long jobs
|
|
781
|
-
* ``doWork`` may call {@link renew}. A crash between reserve and settle is
|
|
782
|
-
* covered by the lease TTL (and the store's reaper).
|
|
783
|
-
*/
|
|
784
|
-
async runBilled(userId, options) {
|
|
785
|
-
const lease = await this.reserve(userId, options.estimate, {
|
|
786
|
-
operationType: options.operationType,
|
|
787
|
-
billingMode: options.billingMode,
|
|
788
|
-
requiredFeature: options.requiredFeature,
|
|
789
|
-
ttl: options.ttl,
|
|
790
|
-
feature: options.feature,
|
|
791
|
-
});
|
|
792
|
-
let workResult;
|
|
793
|
-
let actual;
|
|
794
|
-
try {
|
|
795
|
-
({ result: workResult, actual } = await options.doWork());
|
|
796
|
-
}
|
|
797
|
-
catch (err) {
|
|
798
|
-
await this.release(userId, lease.leaseId);
|
|
799
|
-
throw err;
|
|
800
|
-
}
|
|
801
|
-
const deduction = await this.settle(userId, lease.leaseId, actual, {
|
|
802
|
-
idempotencyKey: options.idempotencyKey,
|
|
803
|
-
feature: options.feature,
|
|
804
|
-
});
|
|
805
|
-
return { result: workResult, deduction };
|
|
806
|
-
}
|
|
807
|
-
// ── Low-balance / overdraft signals (interface plan §6) ─────────────
|
|
808
|
-
/** Emit overdraft + multi-level low_balance after a balance-decreasing op. */
|
|
809
|
-
async postChargeSignals(userId, result) {
|
|
810
|
-
if (result.balanceAfter.lt(0)) {
|
|
811
|
-
this.emit("credits.overdraft", userId, {
|
|
812
|
-
balance: result.balanceAfter,
|
|
813
|
-
amount: result.amount,
|
|
814
|
-
});
|
|
815
|
-
}
|
|
816
|
-
if (result.idempotent)
|
|
817
|
-
return;
|
|
818
|
-
const balanceAfter = result.balanceAfter;
|
|
819
|
-
const balanceBefore = balanceAfter.plus(result.amount);
|
|
820
|
-
await this.emitLowBalance(userId, balanceBefore, balanceAfter);
|
|
821
|
-
}
|
|
822
|
-
/** Edge-triggered low_balance: multi-level if configured, else single (§6). */
|
|
823
|
-
async emitLowBalance(userId, balanceBefore, balanceAfter) {
|
|
824
|
-
if (this.lowBalanceThresholds) {
|
|
825
|
-
const below = this.lbBelow.get(userId) ?? new Set();
|
|
826
|
-
this.lbBelow.set(userId, below);
|
|
827
|
-
const newlyCrossed = [];
|
|
828
|
-
for (const t of this.lowBalanceThresholds) {
|
|
829
|
-
// high → low
|
|
830
|
-
if (balanceAfter.lte(t)) {
|
|
831
|
-
if (!below.has(t.toString())) {
|
|
832
|
-
below.add(t.toString());
|
|
833
|
-
newlyCrossed.push(t);
|
|
834
|
-
}
|
|
835
|
-
}
|
|
836
|
-
else {
|
|
837
|
-
below.delete(t.toString());
|
|
838
|
-
}
|
|
839
|
-
}
|
|
840
|
-
const fireLevel = newlyCrossed.length > 0 ? newlyCrossed.reduce((min, t) => (t.lt(min) ? t : min)) : null;
|
|
841
|
-
if (fireLevel !== null) {
|
|
842
|
-
await this.fireLowBalance(userId, balanceAfter, fireLevel);
|
|
843
|
-
}
|
|
844
|
-
return;
|
|
845
|
-
}
|
|
846
|
-
const threshold = this.resolveLowBalanceThreshold();
|
|
847
|
-
if (balanceBefore.gt(threshold) && balanceAfter.lte(threshold)) {
|
|
848
|
-
await this.fireLowBalance(userId, balanceAfter, threshold);
|
|
849
|
-
}
|
|
850
|
-
}
|
|
851
|
-
/** Emit ``credits.low_balance`` and invoke the non-blocking ``onLowBalance``. */
|
|
852
|
-
async fireLowBalance(userId, balance, threshold) {
|
|
853
|
-
const data = { balance, threshold };
|
|
854
|
-
this.emit("credits.low_balance", userId, data);
|
|
855
|
-
if (this.onLowBalance != null) {
|
|
856
|
-
const event = {
|
|
857
|
-
type: "credits.low_balance",
|
|
858
|
-
timestamp: new Date(),
|
|
859
|
-
userId,
|
|
860
|
-
data,
|
|
861
|
-
};
|
|
862
|
-
try {
|
|
863
|
-
// Never block/break the op on a handler failure (§6/H4).
|
|
864
|
-
await this.onLowBalance(event);
|
|
865
|
-
}
|
|
866
|
-
catch (err) {
|
|
867
|
-
console.error(`[CreditManager] onLowBalance handler failed for user ${userId}:`, err);
|
|
868
|
-
}
|
|
869
|
-
}
|
|
870
|
-
}
|
|
871
|
-
/**
|
|
872
|
-
* Full deduction flow as one atomic store call (contract §2).
|
|
873
|
-
*
|
|
874
|
-
* 1. ``breakdown = engine.calculate(metrics)``; ``cost = breakdown.total``
|
|
875
|
-
* (exact `Decimal`, **no truncation**).
|
|
876
|
-
* 2. If ``cost <= 0`` short-circuit with a zero-amount result.
|
|
877
|
-
* 3. Otherwise ``store.deductWithAllowance`` consumes allowance, enforces caps,
|
|
878
|
-
* applies the balance floor and debits — idempotency-keyed end-to-end.
|
|
879
|
-
*
|
|
880
|
-
* On a store ``error`` a ``credits.deduct_failed`` event is emitted and a
|
|
881
|
-
* typed exception is thrown (``insufficient_credits`` → InsufficientCreditsError,
|
|
882
|
-
* ``cap_reached`` → CapReachedError). No success event is emitted on error.
|
|
883
|
-
*/
|
|
884
|
-
async deduct(userId, metrics, idempotencyKey, metadata,
|
|
885
|
-
/** Named feature to enforce/tag a per-feature invocation-count limit for. */
|
|
886
|
-
feature) {
|
|
887
|
-
await this.maybeLazyExpire(userId);
|
|
888
|
-
if (!this.engine)
|
|
889
|
-
throw new PricingNotLoadedError("pricing not loaded: call loadPricingFromStore or publishPricing first");
|
|
890
|
-
// 1) Calculate cost — exact Decimal, never truncated (H1).
|
|
891
|
-
const breakdown = this.engine.calculate(metrics);
|
|
892
|
-
const cost = breakdown.total;
|
|
893
|
-
// 2) Zero-amount short-circuit (no balance touch, no store round-trip).
|
|
894
|
-
if (cost.lte(0)) {
|
|
895
|
-
const balance = await this.store.getBalance(userId);
|
|
896
|
-
const result = {
|
|
897
|
-
transactionId: "",
|
|
898
|
-
userId,
|
|
899
|
-
amount: new Decimal(0),
|
|
900
|
-
allowanceConsumed: new Decimal(0),
|
|
901
|
-
balanceAfter: balance.balance,
|
|
902
|
-
idempotent: false,
|
|
903
|
-
capWarning: null,
|
|
904
|
-
featureLimitWarning: null,
|
|
905
|
-
};
|
|
906
|
-
this.emit("credits.deducted", userId, {
|
|
907
|
-
amount: new Decimal(0),
|
|
908
|
-
balanceAfter: balance.balance,
|
|
909
|
-
planCovered: false,
|
|
910
|
-
});
|
|
911
|
-
return result;
|
|
912
|
-
}
|
|
913
|
-
// Build transaction metadata: caller fields FIRST, system fields LAST so the
|
|
914
|
-
// system fields win (contract §5 / M7).
|
|
915
|
-
const meta = {};
|
|
916
|
-
if (metadata) {
|
|
917
|
-
for (const [k, v] of Object.entries(metadata)) {
|
|
918
|
-
if (v != null)
|
|
919
|
-
meta[k] = v;
|
|
920
|
-
}
|
|
921
|
-
}
|
|
922
|
-
meta["inputTokens"] = metrics.inputTokens ?? 0;
|
|
923
|
-
meta["outputTokens"] = metrics.outputTokens ?? 0;
|
|
924
|
-
meta["model"] = metrics.model ?? "unknown";
|
|
925
|
-
meta["breakdownTotal"] = breakdown.total.toString();
|
|
926
|
-
if (metrics.fixedJob)
|
|
927
|
-
meta["fixedJob"] = metrics.fixedJob;
|
|
928
|
-
if (idempotencyKey)
|
|
929
|
-
meta["idempotencyKey"] = idempotencyKey;
|
|
930
|
-
const periodStart = await this.resolveAllowancePeriodStart(userId);
|
|
931
|
-
const { limit: featureLimit, periodStart: featurePeriodStart } = await this.resolveFeatureLimit(userId, feature);
|
|
932
|
-
const options = {
|
|
933
|
-
idempotencyKey: idempotencyKey ?? null,
|
|
934
|
-
minBalance: this.minBalanceDecimal(),
|
|
935
|
-
model: metrics.model ?? null,
|
|
936
|
-
metadata: meta,
|
|
937
|
-
periodStart,
|
|
938
|
-
feature: feature ?? null,
|
|
939
|
-
featureLimit,
|
|
940
|
-
featurePeriodStart,
|
|
941
|
-
};
|
|
942
|
-
// 3) Atomic charge.
|
|
943
|
-
const result = await this.store.deductWithAllowance(userId, cost, options);
|
|
944
|
-
if (result.error) {
|
|
945
|
-
this.emit("credits.deduct_failed", userId, {
|
|
946
|
-
error: result.error,
|
|
947
|
-
amount: cost,
|
|
948
|
-
model: metrics.model ?? null,
|
|
949
|
-
});
|
|
950
|
-
if (result.error === "cap_reached") {
|
|
951
|
-
throw new CapReachedError(`Spend cap exceeded for user ${userId} (requested ${cost})`);
|
|
952
|
-
}
|
|
953
|
-
if (result.error === "feature_limit_reached") {
|
|
954
|
-
this.emit("credits.feature_limit_reached", userId, {
|
|
955
|
-
feature,
|
|
956
|
-
amount: cost,
|
|
957
|
-
model: metrics.model ?? null,
|
|
958
|
-
});
|
|
959
|
-
throw new FeatureLimitReachedError(`Feature limit exceeded for '${feature}'. user=${userId}`);
|
|
960
|
-
}
|
|
961
|
-
// insufficient_credits, invalid_amount, and any other business error.
|
|
962
|
-
throw new InsufficientCreditsError(`Credit deduction failed: ${result.error}. user=${userId}, requested=${cost}`);
|
|
963
|
-
}
|
|
964
|
-
// Success — emit deducted, then any cap warning, then edge-triggered low-balance.
|
|
965
|
-
this.emit("credits.deducted", userId, {
|
|
966
|
-
transactionId: result.transactionId,
|
|
967
|
-
amount: result.amount,
|
|
968
|
-
allowanceConsumed: result.allowanceConsumed,
|
|
969
|
-
balanceAfter: result.balanceAfter,
|
|
970
|
-
model: metrics.model ?? null,
|
|
971
|
-
idempotent: result.idempotent,
|
|
972
|
-
});
|
|
973
|
-
if (result.capWarning) {
|
|
974
|
-
this.emit("credits.cap_warning", userId, {
|
|
975
|
-
action: result.capWarning,
|
|
976
|
-
amount: result.amount,
|
|
977
|
-
model: metrics.model ?? null,
|
|
978
|
-
});
|
|
979
|
-
}
|
|
980
|
-
// Non-blocking feature-limit signal surfaced by the store (parallels
|
|
981
|
-
// capWarning above). A 'deny' feature limit never reaches here — it
|
|
982
|
-
// aborts in the error path — so only warn/notify can appear here.
|
|
983
|
-
if (result.featureLimitWarning === "warn" || result.featureLimitWarning === "notify") {
|
|
984
|
-
this.emit("credits.feature_limit_warning", userId, {
|
|
985
|
-
feature,
|
|
986
|
-
balanceAfter: result.balanceAfter,
|
|
987
|
-
amount: result.amount,
|
|
988
|
-
model: metrics.model ?? null,
|
|
989
|
-
action: result.featureLimitWarning,
|
|
990
|
-
});
|
|
991
|
-
}
|
|
992
|
-
// low_balance is EDGE-triggered (M18): only fire when THIS deduction crossed
|
|
993
|
-
// the threshold. A replayed (idempotent) result did not move the balance, so
|
|
994
|
-
// it never crosses. balanceBefore = balanceAfter + amount charged.
|
|
995
|
-
if (!result.idempotent) {
|
|
996
|
-
const threshold = this.resolveLowBalanceThreshold();
|
|
997
|
-
const balanceBefore = result.balanceAfter.plus(result.amount);
|
|
998
|
-
if (result.balanceAfter.lte(threshold) && balanceBefore.gt(threshold)) {
|
|
999
|
-
this.emit("credits.low_balance", userId, {
|
|
1000
|
-
balance: result.balanceAfter,
|
|
1001
|
-
threshold,
|
|
1002
|
-
minBalance: this.minBalanceDecimal(),
|
|
1003
|
-
});
|
|
1004
|
-
}
|
|
1005
|
-
}
|
|
1006
|
-
return result;
|
|
1007
|
-
}
|
|
1008
|
-
/**
|
|
1009
|
-
* Refund a previous credit deduction.
|
|
1010
|
-
*
|
|
1011
|
-
* H3: the store's ``error`` is checked **before** emitting. A successful refund
|
|
1012
|
-
* emits ``credits.refunded``; a failed/duplicate/over-refund emits
|
|
1013
|
-
* ``credits.refund_failed`` and throws a typed ``RefundError`` (no success
|
|
1014
|
-
* event is ever emitted for a failed refund).
|
|
1015
|
-
*/
|
|
1016
|
-
async refundCredits(transactionId, amount, reason, metadata) {
|
|
1017
|
-
const refundAmount = amount != null ? toDecimal(amount) : undefined;
|
|
1018
|
-
const result = await this.store.refundCredits(transactionId, refundAmount, reason, metadata);
|
|
1019
|
-
if (result.error) {
|
|
1020
|
-
this.emit("credits.refund_failed", result.userId, {
|
|
1021
|
-
transactionId,
|
|
1022
|
-
error: result.error,
|
|
1023
|
-
reason: reason ?? null,
|
|
1024
|
-
});
|
|
1025
|
-
throw new RefundError(`Refund failed: ${result.error}. transaction=${transactionId}`);
|
|
1026
|
-
}
|
|
1027
|
-
this.emit("credits.refunded", result.userId, {
|
|
1028
|
-
transactionId,
|
|
1029
|
-
refundTransactionId: result.refundTransactionId,
|
|
1030
|
-
amount: result.amount,
|
|
1031
|
-
newBalance: result.newBalance,
|
|
1032
|
-
reason: reason ?? null,
|
|
1033
|
-
});
|
|
1034
|
-
return result;
|
|
1035
|
-
}
|
|
1036
|
-
/**
|
|
1037
|
-
* Deduct from a team's shared balance pool.
|
|
1038
|
-
*
|
|
1039
|
-
* Calculates the cost via the pricing engine (exact `Decimal`, no truncation),
|
|
1040
|
-
* then debits the team balance. Threads an optional ``idempotencyKey`` through
|
|
1041
|
-
* to the store so retried team charges are not double-counted (H12).
|
|
1042
|
-
*/
|
|
1043
|
-
async deductTeam(teamId, userId, metrics, idempotencyKey, metadata) {
|
|
1044
|
-
// Lazy expiry is scoped to the individual member's credits, not the team's
|
|
1045
|
-
// shared pool — there's no per-team expiry concept.
|
|
1046
|
-
await this.maybeLazyExpire(userId);
|
|
1047
|
-
if (!this.engine)
|
|
1048
|
-
throw new PricingNotLoadedError("pricing not loaded: call loadPricingFromStore or publishPricing first");
|
|
1049
|
-
const breakdown = this.engine.calculate(metrics);
|
|
1050
|
-
const cost = breakdown.total;
|
|
1051
|
-
if (cost.lte(0)) {
|
|
1052
|
-
const teamBal = await this.store.getTeamBalance(teamId);
|
|
1053
|
-
return {
|
|
1054
|
-
transactionId: "",
|
|
1055
|
-
teamId,
|
|
1056
|
-
userId,
|
|
1057
|
-
amount: new Decimal(0),
|
|
1058
|
-
teamBalanceAfter: teamBal.balance,
|
|
1059
|
-
};
|
|
1060
|
-
}
|
|
1061
|
-
const result = await this.store.deductTeam(teamId, userId, cost, metadata, idempotencyKey);
|
|
1062
|
-
// H2 fix: surface store errors — emit credits.deduct_failed and throw,
|
|
1063
|
-
// mirroring Python manager.py:1069-1082. Previously returned a silent
|
|
1064
|
-
// success-shaped object with an .error field, so failed charges looked OK.
|
|
1065
|
-
if (result.error) {
|
|
1066
|
-
this.emit("credits.deduct_failed", userId, {
|
|
1067
|
-
error: result.error,
|
|
1068
|
-
amount: cost,
|
|
1069
|
-
teamId,
|
|
1070
|
-
deductType: "team",
|
|
1071
|
-
});
|
|
1072
|
-
throw new InsufficientCreditsError(`Team deduction failed: ${result.error}. Team=${teamId}, user=${userId}, requested=${cost}`);
|
|
1073
|
-
}
|
|
1074
|
-
this.emit("credits.deducted", userId, {
|
|
1075
|
-
transactionId: result.transactionId,
|
|
1076
|
-
amount: result.amount,
|
|
1077
|
-
teamBalanceAfter: result.teamBalanceAfter,
|
|
1078
|
-
teamId,
|
|
1079
|
-
deductType: "team",
|
|
1080
|
-
});
|
|
1081
|
-
return result;
|
|
1082
|
-
}
|
|
1083
|
-
/**
|
|
1084
|
-
* Shortcut for fixed-cost batch jobs.
|
|
1085
|
-
*
|
|
1086
|
-
* L1: an unknown/typo'd ``jobName`` is rejected (throws) instead of silently
|
|
1087
|
-
* charging 0 credits — ``engine.getFixedCost(jobName) === null`` means the job
|
|
1088
|
-
* is not configured.
|
|
1089
|
-
*/
|
|
1090
|
-
async deductFixed(userId, jobName, idempotencyKey, metadata, feature) {
|
|
1091
|
-
await this.maybeLazyExpire(userId);
|
|
1092
|
-
if (!this.engine)
|
|
1093
|
-
throw new PricingNotLoadedError("pricing not loaded: call loadPricingFromStore or publishPricing first");
|
|
1094
|
-
if (this.engine.getFixedCost(jobName) === null) {
|
|
1095
|
-
throw new ConfigError(`unknown fixed job '${jobName}': not configured in pricing 'fixed' section`);
|
|
1096
|
-
}
|
|
1097
|
-
return await this.deduct(userId, { fixedJob: jobName }, idempotencyKey, metadata, feature);
|
|
1098
|
-
}
|
|
1099
|
-
/**
|
|
1100
|
-
* Sweep expired credits — global when ``userId`` is omitted, scoped to a
|
|
1101
|
-
* single user when given (used by ``maybeLazyExpire``). Shared by the public
|
|
1102
|
-
* ``sweepExpiredCredits`` (always global) and the lazy-on-read trigger.
|
|
1103
|
-
*/
|
|
1104
|
-
async runSweep(dryRun, userId) {
|
|
1105
|
-
const result = await this.store.sweepExpiredCredits(dryRun, userId);
|
|
1106
|
-
if (!dryRun && result.expiredCount > 0) {
|
|
1107
|
-
this.emit("credits.expired", userId ?? "system", {
|
|
1108
|
-
expiredCount: result.expiredCount,
|
|
1109
|
-
expiredAmount: result.expiredAmount,
|
|
1110
|
-
});
|
|
1111
|
-
}
|
|
1112
|
-
return result;
|
|
1113
|
-
}
|
|
1114
|
-
/**
|
|
1115
|
-
* Sweep expired credits from all users' balances.
|
|
1116
|
-
*
|
|
1117
|
-
* When ``dryRun`` is true, reports what would be expired without modifying
|
|
1118
|
-
* any balances. Unaffected by ``options.lazyExpiry`` — this always runs a
|
|
1119
|
-
* global sweep; lazy expiry only scopes *automatic* per-user sweeps.
|
|
1120
|
-
*/
|
|
1121
|
-
async sweepExpiredCredits(dryRun = false) {
|
|
1122
|
-
return await this.runSweep(dryRun, undefined);
|
|
1123
|
-
}
|
|
1124
|
-
// ── Usage analytics ──────────────────────────────────────────────────
|
|
1125
|
-
/** Aggregate statistics across all users in a time window. */
|
|
1126
|
-
async aggregateStats(start, end) {
|
|
1127
|
-
return await this.store.aggregateStats(start, end);
|
|
1128
|
-
}
|
|
1129
|
-
/** Aggregate spend by user in a time window. */
|
|
1130
|
-
async spendByUser(start, end) {
|
|
1131
|
-
return await this.store.spendByUser(start, end);
|
|
1132
|
-
}
|
|
1133
|
-
/** Aggregate spend by model in a time window. */
|
|
1134
|
-
async spendByModel(start, end) {
|
|
1135
|
-
return await this.store.spendByModel(start, end);
|
|
1136
|
-
}
|
|
1137
|
-
/** List all user credit transactions with pagination. */
|
|
1138
|
-
async listUserTransactions(userId, options) {
|
|
1139
|
-
return await this.store.listUserTransactions(userId, options);
|
|
1140
|
-
}
|
|
1141
|
-
async listUsageEvents(userId, options) {
|
|
1142
|
-
return await this.store.listUsageEvents(userId, options);
|
|
1143
|
-
}
|
|
1144
|
-
/** Top users by spend in a time window with limit. */
|
|
1145
|
-
async topUsers(limit, start, end) {
|
|
1146
|
-
return await this.store.topUsers(limit, start, end);
|
|
1147
|
-
}
|
|
1148
|
-
/** Daily spend aggregation in a time window. */
|
|
1149
|
-
async dailySpend(start, end) {
|
|
1150
|
-
return await this.store.dailySpend(start, end);
|
|
1151
|
-
}
|
|
1152
|
-
}
|
|
1153
|
-
//# sourceMappingURL=manager.js.map
|