@zonastery/bursar 1.0.1 → 2.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 +86 -3
- package/dist/billing/auto-recharge-port.d.ts +3 -3
- package/dist/billing/auto-recharge-port.d.ts.map +1 -1
- package/dist/billing/auto-recharge-port.js.map +1 -1
- package/dist/billing/auto-recharge-service.d.ts +5 -4
- package/dist/billing/auto-recharge-service.d.ts.map +1 -1
- package/dist/billing/auto-recharge-service.js +64 -34
- package/dist/billing/auto-recharge-service.js.map +1 -1
- package/dist/billing/billing-service.d.ts +5 -5
- package/dist/billing/billing-service.d.ts.map +1 -1
- package/dist/billing/billing-service.js +2 -2
- package/dist/billing/billing-service.js.map +1 -1
- package/dist/billing/billing-store.d.ts +8 -7
- 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 +31 -31
- package/dist/billing/contracts.d.ts.map +1 -1
- package/dist/billing/contracts.js.map +1 -1
- package/dist/billing/event-handlers.d.ts.map +1 -1
- package/dist/billing/event-handlers.js +31 -9
- package/dist/billing/event-handlers.js.map +1 -1
- package/dist/billing/event-processor.d.ts.map +1 -1
- package/dist/billing/event-processor.js +2 -1
- package/dist/billing/event-processor.js.map +1 -1
- package/dist/billing/financial-event-handlers.d.ts.map +1 -1
- package/dist/billing/financial-event-handlers.js +69 -72
- package/dist/billing/financial-event-handlers.js.map +1 -1
- package/dist/billing/index.d.ts +1 -1
- package/dist/billing/index.d.ts.map +1 -1
- package/dist/billing/index.js.map +1 -1
- package/dist/billing/management.d.ts +5 -5
- package/dist/billing/management.d.ts.map +1 -1
- package/dist/billing/management.js +2 -2
- package/dist/billing/management.js.map +1 -1
- package/dist/billing/postgres/repositories/auto-recharge.d.ts +3 -3
- package/dist/billing/postgres/repositories/auto-recharge.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/auto-recharge.js +202 -59
- package/dist/billing/postgres/repositories/auto-recharge.js.map +1 -1
- package/dist/billing/postgres/repositories/customer.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/customer.js +19 -11
- package/dist/billing/postgres/repositories/customer.js.map +1 -1
- package/dist/billing/postgres/repositories/dispute.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/dispute.js +3 -1
- package/dist/billing/postgres/repositories/dispute.js.map +1 -1
- package/dist/billing/postgres/repositories/event.d.ts +12 -5
- package/dist/billing/postgres/repositories/event.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/event.js +18 -15
- package/dist/billing/postgres/repositories/event.js.map +1 -1
- package/dist/billing/postgres/repositories/invoice.d.ts +3 -3
- package/dist/billing/postgres/repositories/invoice.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/invoice.js +53 -11
- package/dist/billing/postgres/repositories/invoice.js.map +1 -1
- package/dist/billing/postgres/repositories/offer.d.ts +20 -17
- package/dist/billing/postgres/repositories/offer.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/offer.js +123 -57
- package/dist/billing/postgres/repositories/offer.js.map +1 -1
- package/dist/billing/postgres/repositories/payment.d.ts +23 -20
- package/dist/billing/postgres/repositories/payment.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/payment.js +43 -37
- package/dist/billing/postgres/repositories/payment.js.map +1 -1
- package/dist/billing/postgres/repositories/preferences.d.ts +3 -9
- package/dist/billing/postgres/repositories/preferences.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/preferences.js +45 -7
- package/dist/billing/postgres/repositories/preferences.js.map +1 -1
- package/dist/billing/postgres/repositories/refund.d.ts +1 -1
- package/dist/billing/postgres/repositories/refund.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/refund.js +13 -9
- package/dist/billing/postgres/repositories/refund.js.map +1 -1
- package/dist/billing/postgres/repositories/subscription-change.d.ts +15 -0
- package/dist/billing/postgres/repositories/subscription-change.d.ts.map +1 -0
- package/dist/billing/postgres/repositories/subscription-change.js +234 -0
- package/dist/billing/postgres/repositories/subscription-change.js.map +1 -0
- package/dist/billing/postgres/repositories/subscription.d.ts +38 -17
- package/dist/billing/postgres/repositories/subscription.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/subscription.js +199 -91
- package/dist/billing/postgres/repositories/subscription.js.map +1 -1
- package/dist/billing/postgres/repositories/topup.d.ts +13 -15
- package/dist/billing/postgres/repositories/topup.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/topup.js +65 -34
- package/dist/billing/postgres/repositories/topup.js.map +1 -1
- package/dist/billing/postgres/store.d.ts +18 -11
- package/dist/billing/postgres/store.d.ts.map +1 -1
- package/dist/billing/postgres/store.js +260 -238
- package/dist/billing/postgres/store.js.map +1 -1
- package/dist/billing/service-types.d.ts +6 -5
- package/dist/billing/service-types.d.ts.map +1 -1
- package/dist/billing/service-types.js.map +1 -1
- package/dist/billing/types/auto-recharge.d.ts +6 -4
- package/dist/billing/types/auto-recharge.d.ts.map +1 -1
- package/dist/billing/types/auto-recharge.js.map +1 -1
- package/dist/billing/types/catalog.d.ts +18 -35
- package/dist/billing/types/catalog.d.ts.map +1 -1
- package/dist/billing/types/catalog.js.map +1 -1
- package/dist/billing/types/common.d.ts +0 -1
- package/dist/billing/types/common.d.ts.map +1 -1
- package/dist/billing/types/common.js.map +1 -1
- package/dist/billing/types/documents.d.ts +38 -12
- package/dist/billing/types/documents.d.ts.map +1 -1
- package/dist/billing/types/documents.js.map +1 -1
- package/dist/billing/types/events.d.ts +2 -0
- package/dist/billing/types/events.d.ts.map +1 -1
- package/dist/billing/types/events.js +238 -0
- package/dist/billing/types/events.js.map +1 -1
- package/dist/billing/types/subscriptions.d.ts +8 -8
- package/dist/billing/types/subscriptions.d.ts.map +1 -1
- package/dist/billing/types/subscriptions.js.map +1 -1
- package/dist/bursar.d.ts +27 -9
- package/dist/bursar.d.ts.map +1 -1
- package/dist/bursar.js +48 -20
- package/dist/bursar.js.map +1 -1
- package/dist/catalog.d.ts +1 -1
- package/dist/catalog.d.ts.map +1 -1
- package/dist/catalog.js +1 -1
- package/dist/catalog.js.map +1 -1
- package/dist/commerce/errors.d.ts +1 -10
- package/dist/commerce/errors.d.ts.map +1 -1
- package/dist/commerce/errors.js +1 -16
- package/dist/commerce/errors.js.map +1 -1
- package/dist/commerce/index.d.ts +1 -0
- package/dist/commerce/index.d.ts.map +1 -1
- package/dist/commerce/index.js.map +1 -1
- package/dist/commerce/provider-registry.d.ts.map +1 -1
- package/dist/commerce/provider-registry.js +27 -2
- package/dist/commerce/provider-registry.js.map +1 -1
- package/dist/commerce/service.d.ts +15 -7
- package/dist/commerce/service.d.ts.map +1 -1
- package/dist/commerce/service.js +85 -67
- package/dist/commerce/service.js.map +1 -1
- package/dist/commerce/types.d.ts +27 -15
- package/dist/commerce/types.d.ts.map +1 -1
- package/dist/commerce/types.js.map +1 -1
- package/dist/config/parse-plans.d.ts.map +1 -1
- package/dist/config/parse-plans.js +16 -15
- package/dist/config/parse-plans.js.map +1 -1
- package/dist/config/parse-pricing.d.ts.map +1 -1
- package/dist/config/parse-pricing.js +16 -5
- package/dist/config/parse-pricing.js.map +1 -1
- package/dist/config/types.d.ts +2 -2
- package/dist/config/types.d.ts.map +1 -1
- package/dist/config/types.js.map +1 -1
- package/dist/credits/{pricing-runtime.d.ts → catalog-runtime.d.ts} +8 -8
- package/dist/credits/catalog-runtime.d.ts.map +1 -0
- package/dist/credits/{pricing-runtime.js → catalog-runtime.js} +58 -38
- package/dist/credits/catalog-runtime.js.map +1 -0
- package/dist/credits/events.d.ts +4 -4
- package/dist/credits/events.d.ts.map +1 -1
- package/dist/credits/events.js +1 -1
- package/dist/credits/events.js.map +1 -1
- package/dist/credits/lease-workflow.d.ts +14 -14
- package/dist/credits/lease-workflow.d.ts.map +1 -1
- package/dist/credits/lease-workflow.js +18 -17
- package/dist/credits/lease-workflow.js.map +1 -1
- package/dist/credits/low-balance-monitor.d.ts +2 -2
- package/dist/credits/low-balance-monitor.d.ts.map +1 -1
- package/dist/credits/low-balance-monitor.js.map +1 -1
- package/dist/credits/postgres/repositories/analytics.d.ts +34 -34
- package/dist/credits/postgres/repositories/analytics.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/analytics.js +52 -52
- package/dist/credits/postgres/repositories/analytics.js.map +1 -1
- package/dist/credits/postgres/repositories/balance.d.ts +28 -30
- package/dist/credits/postgres/repositories/balance.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/balance.js +100 -59
- package/dist/credits/postgres/repositories/balance.js.map +1 -1
- package/dist/credits/postgres/repositories/bucket.d.ts +14 -8
- package/dist/credits/postgres/repositories/bucket.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/bucket.js +22 -21
- package/dist/credits/postgres/repositories/bucket.js.map +1 -1
- package/dist/credits/postgres/repositories/catalog.d.ts +31 -0
- package/dist/credits/postgres/repositories/catalog.d.ts.map +1 -0
- package/dist/credits/postgres/repositories/catalog.js +90 -0
- package/dist/credits/postgres/repositories/catalog.js.map +1 -0
- package/dist/credits/postgres/repositories/deduction.d.ts +28 -26
- package/dist/credits/postgres/repositories/deduction.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/deduction.js +153 -68
- package/dist/credits/postgres/repositories/deduction.js.map +1 -1
- package/dist/credits/postgres/repositories/lease.d.ts +21 -18
- package/dist/credits/postgres/repositories/lease.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/lease.js +157 -65
- package/dist/credits/postgres/repositories/lease.js.map +1 -1
- package/dist/credits/postgres/repositories/plan.d.ts +90 -43
- package/dist/credits/postgres/repositories/plan.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/plan.js +126 -108
- package/dist/credits/postgres/repositories/plan.js.map +1 -1
- package/dist/credits/postgres/repositories/team.d.ts +36 -27
- package/dist/credits/postgres/repositories/team.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/team.js +96 -52
- package/dist/credits/postgres/repositories/team.js.map +1 -1
- package/dist/credits/postgres/store.d.ts +23 -18
- package/dist/credits/postgres/store.d.ts.map +1 -1
- package/dist/credits/postgres/store.js +282 -265
- package/dist/credits/postgres/store.js.map +1 -1
- package/dist/credits/postgres/value-mappers.d.ts +7 -9
- package/dist/credits/postgres/value-mappers.d.ts.map +1 -1
- package/dist/credits/postgres/value-mappers.js +36 -61
- package/dist/credits/postgres/value-mappers.js.map +1 -1
- package/dist/credits/queries.d.ts +5 -5
- package/dist/credits/queries.d.ts.map +1 -1
- package/dist/credits/queries.js +4 -4
- package/dist/credits/queries.js.map +1 -1
- package/dist/credits/service-types.d.ts +42 -7
- package/dist/credits/service-types.d.ts.map +1 -1
- package/dist/credits/service-types.js.map +1 -1
- package/dist/credits/service.d.ts +42 -62
- package/dist/credits/service.d.ts.map +1 -1
- package/dist/credits/service.js +140 -121
- package/dist/credits/service.js.map +1 -1
- package/dist/credits/store.d.ts +20 -22
- package/dist/credits/store.d.ts.map +1 -1
- package/dist/credits/store.js +5 -5
- package/dist/credits/store.js.map +1 -1
- package/dist/credits/types/account.d.ts +49 -11
- package/dist/credits/types/account.d.ts.map +1 -1
- package/dist/credits/types/account.js.map +1 -1
- package/dist/credits/types/admission.d.ts +17 -6
- package/dist/credits/types/admission.d.ts.map +1 -1
- package/dist/credits/types/admission.js.map +1 -1
- package/dist/credits/types/analytics.d.ts +2 -2
- package/dist/credits/types/analytics.d.ts.map +1 -1
- package/dist/credits/types/analytics.js.map +1 -1
- package/dist/credits/types/catalog.d.ts +20 -15
- package/dist/credits/types/catalog.d.ts.map +1 -1
- package/dist/credits/types/catalog.js.map +1 -1
- package/dist/credits/types/grants.d.ts +22 -8
- package/dist/credits/types/grants.d.ts.map +1 -1
- package/dist/credits/types/grants.js.map +1 -1
- package/dist/credits/types/ledger.d.ts +12 -3
- package/dist/credits/types/ledger.d.ts.map +1 -1
- package/dist/credits/types/ledger.js.map +1 -1
- package/dist/credits/types/teams.d.ts +18 -6
- package/dist/credits/types/teams.d.ts.map +1 -1
- package/dist/credits/types/teams.js.map +1 -1
- package/dist/engine.d.ts.map +1 -1
- package/dist/engine.js +24 -10
- package/dist/engine.js.map +1 -1
- package/dist/errors.d.ts +52 -4
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +76 -4
- package/dist/errors.js.map +1 -1
- package/dist/expr/ast.d.ts.map +1 -1
- package/dist/expr/ast.js.map +1 -1
- package/dist/expr/evaluator.d.ts.map +1 -1
- package/dist/expr/evaluator.js +29 -17
- package/dist/expr/evaluator.js.map +1 -1
- package/dist/expr/parser.d.ts.map +1 -1
- package/dist/expr/parser.js +11 -4
- package/dist/expr/parser.js.map +1 -1
- package/dist/expr/tokenizer.d.ts.map +1 -1
- package/dist/expr/tokenizer.js +17 -13
- package/dist/expr/tokenizer.js.map +1 -1
- package/dist/expr.d.ts +2 -2
- package/dist/expr.d.ts.map +1 -1
- package/dist/expr.js +5 -7
- package/dist/expr.js.map +1 -1
- package/dist/generated/pricing-config.schema.json +5 -12
- package/dist/generated/pricing-config.types.d.ts +3 -3
- package/dist/generated/pricing-config.types.d.ts.map +1 -1
- package/dist/generated/pricing-config.types.js.map +1 -1
- package/dist/index.d.ts +6 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/integrations/better-auth.d.ts +23 -0
- package/dist/integrations/better-auth.d.ts.map +1 -0
- package/dist/integrations/better-auth.js +54 -0
- package/dist/integrations/better-auth.js.map +1 -0
- package/dist/{load-pricing-file.d.ts → load-config-file.d.ts} +4 -4
- package/dist/load-config-file.d.ts.map +1 -0
- package/dist/{load-pricing-file.js → load-config-file.js} +15 -10
- package/dist/load-config-file.js.map +1 -0
- package/dist/node.d.ts +3 -3
- package/dist/node.d.ts.map +1 -1
- package/dist/node.js +2 -2
- package/dist/node.js.map +1 -1
- package/dist/providers/_shared.d.ts +5 -0
- package/dist/providers/_shared.d.ts.map +1 -1
- package/dist/providers/_shared.js +36 -0
- package/dist/providers/_shared.js.map +1 -1
- package/dist/providers/dodo/better-auth.d.ts +29 -0
- package/dist/providers/dodo/better-auth.d.ts.map +1 -0
- package/dist/providers/dodo/better-auth.js +23 -0
- package/dist/providers/dodo/better-auth.js.map +1 -0
- package/dist/providers/dodo/client-contract.d.ts +32 -70
- package/dist/providers/dodo/client-contract.d.ts.map +1 -1
- package/dist/providers/dodo/client-contract.js.map +1 -1
- package/dist/providers/dodo/event-mapper.d.ts +3 -1
- package/dist/providers/dodo/event-mapper.d.ts.map +1 -1
- package/dist/providers/dodo/event-mapper.js +219 -148
- package/dist/providers/dodo/event-mapper.js.map +1 -1
- package/dist/providers/dodo/index.d.ts +5 -2
- package/dist/providers/dodo/index.d.ts.map +1 -1
- package/dist/providers/dodo/index.js +2 -1
- package/dist/providers/dodo/index.js.map +1 -1
- package/dist/providers/dodo/nextjs.d.ts +16 -0
- package/dist/providers/dodo/nextjs.d.ts.map +1 -0
- package/dist/providers/dodo/nextjs.js +16 -0
- package/dist/providers/dodo/nextjs.js.map +1 -0
- package/dist/providers/dodo/provider.d.ts +30 -11
- package/dist/providers/dodo/provider.d.ts.map +1 -1
- package/dist/providers/dodo/provider.js +192 -122
- package/dist/providers/dodo/provider.js.map +1 -1
- package/dist/providers/dodo/react-native.d.ts +56 -0
- package/dist/providers/dodo/react-native.d.ts.map +1 -0
- package/dist/providers/dodo/react-native.js +57 -0
- package/dist/providers/dodo/react-native.js.map +1 -0
- package/dist/providers/dodo/webhook-bridge.d.ts +17 -0
- package/dist/providers/dodo/webhook-bridge.d.ts.map +1 -0
- package/dist/providers/dodo/webhook-bridge.js +21 -0
- package/dist/providers/dodo/webhook-bridge.js.map +1 -0
- package/dist/providers/index.d.ts +1 -1
- package/dist/providers/index.d.ts.map +1 -1
- package/dist/providers/index.js.map +1 -1
- package/dist/providers/mock/index.d.ts +1 -0
- package/dist/providers/mock/index.d.ts.map +1 -1
- package/dist/providers/mock/index.js.map +1 -1
- package/dist/providers/mock/provider.d.ts +8 -8
- package/dist/providers/mock/provider.d.ts.map +1 -1
- package/dist/providers/mock/provider.js +26 -19
- package/dist/providers/mock/provider.js.map +1 -1
- package/dist/providers/stripe/event-mapper.d.ts.map +1 -1
- package/dist/providers/stripe/event-mapper.js +214 -173
- package/dist/providers/stripe/event-mapper.js.map +1 -1
- package/dist/providers/stripe/index.d.ts +1 -0
- package/dist/providers/stripe/index.d.ts.map +1 -1
- package/dist/providers/stripe/index.js.map +1 -1
- package/dist/providers/stripe/provider.d.ts +13 -11
- package/dist/providers/stripe/provider.d.ts.map +1 -1
- package/dist/providers/stripe/provider.js +287 -107
- package/dist/providers/stripe/provider.js.map +1 -1
- package/dist/providers/types.d.ts +1 -2
- package/dist/providers/types.d.ts.map +1 -1
- package/dist/providers/types.js.map +1 -1
- package/dist/shared/postgres-client.d.ts +5 -0
- package/dist/shared/postgres-client.d.ts.map +1 -1
- package/dist/shared/postgres-client.js +23 -7
- package/dist/shared/postgres-client.js.map +1 -1
- package/dist/shared/postgres-validation.d.ts +15 -3
- package/dist/shared/postgres-validation.d.ts.map +1 -1
- package/dist/shared/postgres-validation.js +58 -14
- package/dist/shared/postgres-validation.js.map +1 -1
- package/dist/storage/adapters/clickhouse.d.ts.map +1 -1
- package/dist/storage/adapters/clickhouse.js +2 -5
- package/dist/storage/adapters/clickhouse.js.map +1 -1
- package/dist/storage/adapters/s3.d.ts +0 -6
- package/dist/storage/adapters/s3.d.ts.map +1 -1
- package/dist/storage/adapters/s3.js +0 -2
- package/dist/storage/adapters/s3.js.map +1 -1
- package/dist/storage/ports.d.ts +0 -1
- package/dist/storage/ports.d.ts.map +1 -1
- package/dist/storage/ports.js.map +1 -1
- package/dist/storage/postgres-repository.d.ts +1 -1
- package/dist/storage/postgres-repository.d.ts.map +1 -1
- package/dist/storage/postgres-repository.js +2 -2
- package/dist/storage/postgres-repository.js.map +1 -1
- package/dist/storage/runtime.d.ts +24 -6
- package/dist/storage/runtime.d.ts.map +1 -1
- package/dist/storage/runtime.js +87 -30
- package/dist/storage/runtime.js.map +1 -1
- package/package.json +56 -7
- package/dist/credits/postgres/repositories/pricing.d.ts +0 -28
- package/dist/credits/postgres/repositories/pricing.d.ts.map +0 -1
- package/dist/credits/postgres/repositories/pricing.js +0 -76
- package/dist/credits/postgres/repositories/pricing.js.map +0 -1
- package/dist/credits/pricing-runtime.d.ts.map +0 -1
- package/dist/credits/pricing-runtime.js.map +0 -1
- package/dist/load-pricing-file.d.ts.map +0 -1
- package/dist/load-pricing-file.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime.d.ts","sourceRoot":"","sources":["../../src/storage/runtime.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,
|
|
1
|
+
{"version":3,"file":"runtime.d.ts","sourceRoot":"","sources":["../../src/storage/runtime.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAStC,OAAO,EAAE,oBAAoB,EAAE,MAAM,8BAA8B,CAAC;AACpE,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,+BAA+B,CAAC;AAC3E,OAAO,EAAE,aAAa,EAAE,MAAM,8BAA8B,CAAC;AAC7D,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,uBAAuB,CAAC;AACnE,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAC/D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAC5D,OAAO,KAAK,EAAE,mBAAmB,EAAoB,MAAM,2BAA2B,CAAC;AACvF,OAAO,EAIL,KAAK,yBAAyB,EAC9B,KAAK,YAAY,EAClB,MAAM,8BAA8B,CAAC;AAEtC,OAAO,EAAwB,KAAK,2BAA2B,EAAE,MAAM,0BAA0B,CAAC;AAClG,OAAO,EAAoB,KAAK,uBAAuB,EAAE,MAAM,kBAAkB,CAAC;AAClF,OAAO,EAAE,YAAY,EAAE,KAAK,eAAe,EAAE,KAAK,mBAAmB,EAAE,MAAM,oBAAoB,CAAC;AAClG,OAAO,KAAK,EAEV,qBAAqB,EAGrB,cAAc,EACf,MAAM,YAAY,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ist/storage/runtime.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { Bursar } from "../bursar.js";
|
|
2
|
-
import { ImportError as BursarImportError, isRetryableBursarError,
|
|
2
|
+
import { ConfigError, ImportError as BursarImportError, isRetryableBursarError, CatalogNotLoadedError, StoreClosedError, } from "../errors.js";
|
|
3
3
|
import { retryBursarOperation } from "../retry.js";
|
|
4
4
|
import { PostgresBillingStore } from "../billing/postgres/store.js";
|
|
5
5
|
import { PostgresStore } from "../credits/postgres/store.js";
|
|
6
|
-
import { PostgresClient, postgresPoolConfig, } from "../shared/postgres-client.js";
|
|
6
|
+
import { normalizeTenantId, PostgresClient, postgresPoolConfig, } from "../shared/postgres-client.js";
|
|
7
7
|
import { ClickHouseUsageStore } from "./adapters/clickhouse.js";
|
|
8
8
|
import { S3BillingArchive } from "./adapters/s3.js";
|
|
9
9
|
import { OutboxWorker } from "./outbox-worker.js";
|
|
@@ -23,33 +23,75 @@ export class BursarRuntime {
|
|
|
23
23
|
s3;
|
|
24
24
|
pool;
|
|
25
25
|
ownsPool;
|
|
26
|
+
postgres;
|
|
27
|
+
query;
|
|
28
|
+
tenantId;
|
|
29
|
+
tenantSlug;
|
|
26
30
|
startPromise = null;
|
|
27
31
|
closePromise = null;
|
|
28
32
|
started = false;
|
|
29
33
|
closed = false;
|
|
34
|
+
/** Construct a runtime while keeping pool ownership inside the SDK. */
|
|
35
|
+
static async create(options) {
|
|
36
|
+
if (typeof options.postgres !== "string") {
|
|
37
|
+
return new BursarRuntime(options.postgres, false, options);
|
|
38
|
+
}
|
|
39
|
+
if (!options.postgres.trim()) {
|
|
40
|
+
throw new TypeError("postgres connection string must not be empty");
|
|
41
|
+
}
|
|
42
|
+
let pg;
|
|
43
|
+
try {
|
|
44
|
+
pg = await import("pg");
|
|
45
|
+
}
|
|
46
|
+
catch (cause) {
|
|
47
|
+
throw new BursarImportError("pg is required for the Bursar runtime: npm install pg", {
|
|
48
|
+
cause,
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
const pool = new pg.Pool(postgresPoolConfig(options.postgres, options.postgresOptions));
|
|
52
|
+
try {
|
|
53
|
+
return new BursarRuntime(pool, true, options);
|
|
54
|
+
}
|
|
55
|
+
catch (error) {
|
|
56
|
+
try {
|
|
57
|
+
await pool.end();
|
|
58
|
+
}
|
|
59
|
+
catch {
|
|
60
|
+
// Preserve the composition error; no runtime exists to report cleanup.
|
|
61
|
+
}
|
|
62
|
+
throw error;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
30
65
|
constructor(pool, ownsPool, options) {
|
|
31
66
|
this.pool = pool;
|
|
32
67
|
this.ownsPool = ownsPool;
|
|
68
|
+
this.tenantId = normalizeTenantId(options.tenantId);
|
|
69
|
+
this.tenantSlug =
|
|
70
|
+
options.tenantSlug === undefined ? null : normalizeTenantSlug(options.tenantSlug);
|
|
33
71
|
if (options.clickhouse &&
|
|
34
72
|
!("writeUsage" in options.clickhouse) &&
|
|
35
|
-
options.clickhouse.tenantId !==
|
|
73
|
+
normalizeTenantId(options.clickhouse.tenantId) !== this.tenantId) {
|
|
36
74
|
throw new TypeError("ClickHouse tenantId must match runtime tenantId");
|
|
37
75
|
}
|
|
38
76
|
this.clickhouse = options.clickhouse
|
|
39
77
|
? "writeUsage" in options.clickhouse
|
|
40
78
|
? options.clickhouse
|
|
41
|
-
: new ClickHouseUsageStore(options.clickhouse)
|
|
79
|
+
: new ClickHouseUsageStore({ ...options.clickhouse, tenantId: this.tenantId })
|
|
42
80
|
: null;
|
|
43
81
|
this.s3 = options.s3
|
|
44
82
|
? "archive" in options.s3
|
|
45
83
|
? options.s3
|
|
46
84
|
: new S3BillingArchive(options.s3)
|
|
47
85
|
: null;
|
|
48
|
-
this.creditStore = new PostgresStore(
|
|
86
|
+
this.creditStore = new PostgresStore({
|
|
87
|
+
postgres: pool,
|
|
88
|
+
tenantId: this.tenantId,
|
|
49
89
|
...(options.postgresOptions ?? {}),
|
|
50
90
|
usageBackend: this.clickhouse ? "clickhouse" : "postgres",
|
|
51
91
|
});
|
|
52
|
-
this.billingStore = new PostgresBillingStore(
|
|
92
|
+
this.billingStore = new PostgresBillingStore({
|
|
93
|
+
postgres: pool,
|
|
94
|
+
tenantId: this.tenantId,
|
|
53
95
|
...(options.postgresOptions ?? {}),
|
|
54
96
|
billingPayloadBackend: this.s3 ? "s3" : "postgres",
|
|
55
97
|
});
|
|
@@ -57,7 +99,7 @@ export class BursarRuntime {
|
|
|
57
99
|
const commerceOptions = bursarOptions.commerceOptions
|
|
58
100
|
? {
|
|
59
101
|
...bursarOptions.commerceOptions,
|
|
60
|
-
tenantId:
|
|
102
|
+
tenantId: this.tenantId,
|
|
61
103
|
}
|
|
62
104
|
: undefined;
|
|
63
105
|
this.bursar = new Bursar({
|
|
@@ -73,13 +115,15 @@ export class BursarRuntime {
|
|
|
73
115
|
: undefined,
|
|
74
116
|
},
|
|
75
117
|
});
|
|
76
|
-
|
|
118
|
+
this.postgres = new PostgresClient(pool, {
|
|
77
119
|
...(options.postgresOptions ?? {}),
|
|
78
|
-
tenantId:
|
|
120
|
+
tenantId: this.tenantId,
|
|
121
|
+
accessRole: "bursar_operator",
|
|
79
122
|
usageBackend: this.clickhouse ? "clickhouse" : "postgres",
|
|
80
123
|
billingPayloadBackend: this.s3 ? "s3" : "postgres",
|
|
81
|
-
})
|
|
82
|
-
|
|
124
|
+
});
|
|
125
|
+
this.query = this.postgres.query;
|
|
126
|
+
const repository = new PostgresStorageRepository(this.query, this.tenantId);
|
|
83
127
|
const handlers = this.createHandlers(repository);
|
|
84
128
|
this.worker =
|
|
85
129
|
handlers.length > 0 && options.outbox !== false
|
|
@@ -87,11 +131,11 @@ export class BursarRuntime {
|
|
|
87
131
|
: null;
|
|
88
132
|
}
|
|
89
133
|
start(options = {}) {
|
|
90
|
-
if (this.started)
|
|
91
|
-
return Promise.resolve();
|
|
92
134
|
if (this.closed) {
|
|
93
135
|
return Promise.reject(new StoreClosedError("BursarRuntime has been closed"));
|
|
94
136
|
}
|
|
137
|
+
if (this.started)
|
|
138
|
+
return Promise.resolve();
|
|
95
139
|
if (!this.startPromise) {
|
|
96
140
|
this.startPromise = this.startRuntime(options).catch((error) => {
|
|
97
141
|
this.startPromise = null;
|
|
@@ -101,10 +145,12 @@ export class BursarRuntime {
|
|
|
101
145
|
return this.startPromise;
|
|
102
146
|
}
|
|
103
147
|
async startRuntime(options) {
|
|
104
|
-
if (
|
|
148
|
+
if (this.tenantSlug)
|
|
149
|
+
await this.verifyTenantIdentity();
|
|
150
|
+
if (options.loadCatalog ?? true) {
|
|
105
151
|
const maxAttempts = options.maxAttempts ?? 1;
|
|
106
152
|
const shouldRetry = options.shouldRetry ??
|
|
107
|
-
((error) => error instanceof
|
|
153
|
+
((error) => error instanceof CatalogNotLoadedError || isRetryableBursarError(error));
|
|
108
154
|
await retryBursarOperation(() => this.bursar.loadCatalog(), {
|
|
109
155
|
maxAttempts,
|
|
110
156
|
baseDelayMs: options.retryDelayMs ?? 250,
|
|
@@ -119,7 +165,7 @@ export class BursarRuntime {
|
|
|
119
165
|
this.started = true;
|
|
120
166
|
}
|
|
121
167
|
health() {
|
|
122
|
-
const catalogLoaded = this.bursar.
|
|
168
|
+
const catalogLoaded = this.bursar.catalog.isLoaded;
|
|
123
169
|
return {
|
|
124
170
|
ready: this.started && !this.closed && catalogLoaded,
|
|
125
171
|
started: this.started,
|
|
@@ -160,6 +206,7 @@ export class BursarRuntime {
|
|
|
160
206
|
Promise.resolve().then(() => this.s3?.close?.()),
|
|
161
207
|
Promise.resolve().then(() => this.creditStore.close()),
|
|
162
208
|
Promise.resolve().then(() => this.billingStore.close()),
|
|
209
|
+
Promise.resolve().then(() => this.postgres.close()),
|
|
163
210
|
]);
|
|
164
211
|
for (const result of resources) {
|
|
165
212
|
if (result.status === "rejected")
|
|
@@ -228,7 +275,7 @@ export class BursarRuntime {
|
|
|
228
275
|
const archived = await this.s3?.archive(event);
|
|
229
276
|
if (!archived)
|
|
230
277
|
throw new Error("S3 archive is not configured");
|
|
231
|
-
const recorded = await repository.archiveBillingEventPayload(event.eventId, archived.key, archived.versionId
|
|
278
|
+
const recorded = await repository.archiveBillingEventPayload(event.eventId, archived.key, archived.versionId);
|
|
232
279
|
if (!recorded) {
|
|
233
280
|
throw new Error(`Could not record archive pointer for billing event ${event.eventId}`);
|
|
234
281
|
}
|
|
@@ -237,22 +284,32 @@ export class BursarRuntime {
|
|
|
237
284
|
}
|
|
238
285
|
return handlers;
|
|
239
286
|
}
|
|
287
|
+
async verifyTenantIdentity() {
|
|
288
|
+
if (!this.tenantSlug)
|
|
289
|
+
return;
|
|
290
|
+
const rows = await this.query("SELECT bursar.resolve_active_tenant_for_trigger($1)::text AS tenant_id", [this.tenantSlug]);
|
|
291
|
+
const resolved = rows[0];
|
|
292
|
+
const tenantId = resolved && typeof resolved === "object" && "tenant_id" in resolved
|
|
293
|
+
? resolved.tenant_id
|
|
294
|
+
: undefined;
|
|
295
|
+
if (tenantId !== this.tenantId) {
|
|
296
|
+
throw new ConfigError(`Bursar tenant slug '${this.tenantSlug}' resolves to a different tenant ID`);
|
|
297
|
+
}
|
|
298
|
+
}
|
|
240
299
|
}
|
|
241
300
|
export async function createBursarRuntime(options) {
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
if (
|
|
246
|
-
throw new TypeError("
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
throw new BursarImportError("pg is required for the Bursar runtime: npm install pg", { cause });
|
|
301
|
+
return BursarRuntime.create(options);
|
|
302
|
+
}
|
|
303
|
+
function normalizeTenantSlug(value) {
|
|
304
|
+
if (typeof value !== "string")
|
|
305
|
+
throw new TypeError("tenantSlug must be a string");
|
|
306
|
+
const normalized = value.trim().toLowerCase();
|
|
307
|
+
if (normalized.length < 1 ||
|
|
308
|
+
normalized.length > 100 ||
|
|
309
|
+
!/^[a-z0-9]+(?:[a-z0-9-]*[a-z0-9])?$/.test(normalized)) {
|
|
310
|
+
throw new TypeError("tenantSlug must be a valid Bursar tenant slug");
|
|
253
311
|
}
|
|
254
|
-
|
|
255
|
-
return new BursarRuntime(pool, true, options);
|
|
312
|
+
return normalized;
|
|
256
313
|
}
|
|
257
314
|
function usageExportFromOutbox(payload) {
|
|
258
315
|
const requiredStrings = [
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime.js","sourceRoot":"","sources":["../../src/storage/runtime.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAsB,MAAM,cAAc,CAAC;AAC1D,OAAO,EACL,WAAW,IAAI,iBAAiB,EAChC,sBAAsB,EACtB,qBAAqB,EACrB,gBAAgB,GACjB,MAAM,cAAc,CAAC;AACtB,OAAO,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AACnD,OAAO,EAAE,oBAAoB,EAAE,MAAM,8BAA8B,CAAC;AACpE,OAAO,EAAE,aAAa,EAAE,MAAM,8BAA8B,CAAC;AAG7D,OAAO,EACL,cAAc,EACd,kBAAkB,GAGnB,MAAM,8BAA8B,CAAC;AAEtC,OAAO,EAAE,oBAAoB,EAAoC,MAAM,0BAA0B,CAAC;AAClG,OAAO,EAAE,gBAAgB,EAAgC,MAAM,kBAAkB,CAAC;AAClF,OAAO,EAAE,YAAY,EAAkD,MAAM,oBAAoB,CAAC;AAQlG,OAAO,EAAE,yBAAyB,EAAE,MAAM,0BAA0B,CAAC;AA6CrE;;;;;GAKG;AACH,MAAM,OAAO,aAAa;IACf,MAAM,CAAS;IACf,WAAW,CAAgB;IAC3B,YAAY,CAAuB;IACnC,MAAM,CAAsB;IAC5B,UAAU,CAAgD;IAC1D,EAAE,CAA+B;IAEzB,IAAI,CAAe;IACnB,QAAQ,CAAU;IAC3B,YAAY,GAAyB,IAAI,CAAC;IAC1C,YAAY,GAAyB,IAAI,CAAC;IAC1C,OAAO,GAAG,KAAK,CAAC;IAChB,MAAM,GAAG,KAAK,CAAC;IAEvB,YACE,IAAkB,EACl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AI,CAAC;IACzD,OAAO;QACL,QAAQ,EAAE,OAAO,CAAC,SAAmB;QACrC,OAAO,EAAE,OAAO,CAAC,QAAkB;QACnC,QAAQ,EAAE,OAAO,CAAC,QAAkB;QACpC,mBAAmB,EAAE,OAAO,CAAC,oBAA8B;QAC3D,eAAe,EAAE,OAAO,CAAC,iBAA2B;QACpD,SAAS,EAAE,OAAO,CAAC,UAAoB;QACvC,MAAM,EAAE,OAAO,CAAC,MAAgB;QAChC,UAAU,EAAE,OAAO,CAAC,WAAqB;QACzC,WAAW,EAAE,OAAO,CAAC,YAAY,CAAC,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,IAAI;QACvE,QAAQ,EAAE,OAAO,CAAC,QAAQ;QAC1B,SAAS,EAAG,OAAO,CAAC,UAA4B,IAAI,IAAI;QACxD,aAAa,EAAG,OAAO,CAAC,cAAgC,IAAI,IAAI;QAChE,UAAU,EAAG,OAAO,CAAC,WAA6B,IAAI,IAAI;KAC3D,CAAC;AACJ,CAAC;AAED,SAAS,gBAAgB,CAAC,KAAc;IACtC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC;AACvD,CAAC;AAED,SAAS,gBAAgB,CAAC,KAAc;IACtC,OAAO,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,SAAS,IAAI,OAAO,KAAK,KAAK,QAAQ,CAAC;AAC5E,CAAC;AAED,SAAS,YAAY,CAAC,KAAc;IAClC,OAAO,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC9E,CAAC","sourcesContent":["import { Bursar, type BursarOptions } from \"../bursar.js\";\nimport {\n ImportError as BursarImportError,\n isRetryableBursarError,\n PricingNotLoadedError,\n StoreClosedError,\n} from \"../errors.js\";\nimport { retryBursarOperation } from \"../retry.js\";\nimport { PostgresBillingStore } from \"../billing/postgres/store.js\";\nimport { PostgresStore } from \"../credits/postgres/store.js\";\nimport type { CreditsServiceOptions } from \"../credits/service.js\";\nimport type { UsageAnalyticsStore, UsageChargeStore } from \"../credits/types/index.js\";\nimport {\n PostgresClient,\n postgresPoolConfig,\n type PostgresConnectionOptions,\n type PostgresPool,\n} from \"../shared/postgres-client.js\";\nimport type { QueryFn } from \"../shared/postgres-types.js\";\nimport { ClickHouseUsageStore, type ClickHouseUsageStoreOptions } from \"./adapters/clickhouse.js\";\nimport { S3BillingArchive, type S3BillingArchiveOptions } from \"./adapters/s3.js\";\nimport { OutboxWorker, type OutboxRunResult, type OutboxWorkerOptions } from \"./outbox-worker.js\";\nimport type {\n BillingEventPayloadExport,\n BillingPayloadArchive,\n OutboxHandler,\n UsageChargeExport,\n UsageEventSink,\n} from \"./ports.js\";\nimport { PostgresStorageRepository } from \"./postgres-repository.js\";\n\ntype RuntimeBursarOptions = Omit<\n BursarOptions,\n \"creditStore\" | \"billingStore\" | \"credits\" | \"creditsOptions\"\n> & {\n creditsOptions?: Omit<CreditsServiceOptions, \"analytics\"> | null;\n};\n\nexport interface BursarRuntimeOptions {\n postgres: string | PostgresPool;\n /** Applied to SDK-owned pools and per-transaction statement deadlines. */\n postgresOptions?: PostgresConnectionOptions;\n tenantId: string;\n s3?: BillingPayloadArchive | S3BillingArchiveOptions | null;\n clickhouse?: (UsageEventSink & UsageAnalyticsStore) | ClickHouseUsageStoreOptions | null;\n /**\n * Background delivery configuration. Set false only when another process\n * consumes Bursar's outbox.\n */\n outbox?: OutboxWorkerOptions | false;\n bursar?: RuntimeBursarOptions;\n}\n\nexport interface BursarRuntimeStartOptions {\n /** Load the active catalog before starting background workers. */\n loadCatalog?: boolean;\n /** Total catalog-load attempts, including the first. Defaults to 1. */\n maxAttempts?: number;\n /** Initial retry delay. Each retry doubles up to 5 seconds. */\n retryDelayMs?: number;\n shouldRetry?: (error: unknown) => boolean;\n /** Maximum elapsed catalog-load retry budget. Defaults to 30 seconds. */\n maxElapsedMs?: number;\n /** Abort startup retries and pending backoff. */\n signal?: AbortSignal;\n}\n\nexport interface BursarRuntimeHealth {\n ready: boolean;\n started: boolean;\n closed: boolean;\n catalogLoaded: boolean;\n}\n\n/**\n * Node composition root for Bursar's stores and optional data infrastructure.\n *\n * Without S3 or ClickHouse it constructs the same PostgreSQL-only Bursar and\n * no outbox polling loop. All components share one PostgreSQL pool.\n */\nexport class BursarRuntime {\n readonly bursar: Bursar;\n readonly creditStore: PostgresStore;\n readonly billingStore: PostgresBillingStore;\n readonly worker: OutboxWorker | null;\n readonly clickhouse: (UsageEventSink & UsageAnalyticsStore) | null;\n readonly s3: BillingPayloadArchive | null;\n\n private readonly pool: PostgresPool;\n private readonly ownsPool: boolean;\n private startPromise: Promise<void> | null = null;\n private closePromise: Promise<void> | null = null;\n private started = false;\n private closed = false;\n\n constructor(\n pool: PostgresPool,\n ownsPool: boolean,\n options: Omit<BursarRuntimeOptions, \"postgres\">,\n ) {\n this.pool = pool;\n this.ownsPool = ownsPool;\n if (\n options.clickhouse &&\n !(\"writeUsage\" in options.clickhouse) &&\n options.clickhouse.tenantId !== options.tenantId\n ) {\n throw new TypeError(\"ClickHouse tenantId must match runtime tenantId\");\n }\n this.clickhouse = options.clickhouse\n ? \"writeUsage\" in options.clickhouse\n ? options.clickhouse\n : new ClickHouseUsageStore(options.clickhouse)\n : null;\n this.s3 = options.s3\n ? \"archive\" in options.s3\n ? options.s3\n : new S3BillingArchive(options.s3)\n : null;\n\n this.creditStore = new PostgresStore(\"\", options.tenantId, pool, {\n ...(options.postgresOptions ?? {}),\n usageBackend: this.clickhouse ? \"clickhouse\" : \"postgres\",\n });\n this.billingStore = new PostgresBillingStore(pool, options.tenantId, {\n ...(options.postgresOptions ?? {}),\n billingPayloadBackend: this.s3 ? \"s3\" : \"postgres\",\n });\n const bursarOptions = options.bursar ?? {};\n const commerceOptions = bursarOptions.commerceOptions\n ? {\n ...bursarOptions.commerceOptions,\n tenantId: options.tenantId,\n }\n : undefined;\n this.bursar = new Bursar({\n ...bursarOptions,\n commerceOptions,\n creditStore: this.creditStore,\n billingStore: this.billingStore,\n creditsOptions: {\n ...(bursarOptions.creditsOptions ?? {}),\n analytics: this.clickhouse ?? undefined,\n usageStore:\n this.clickhouse && \"listUsageCharges\" in this.clickhouse\n ? (this.clickhouse as UsageChargeStore)\n : undefined,\n },\n });\n\n const query: QueryFn = new PostgresClient(pool, {\n ...(options.postgresOptions ?? {}),\n tenantId: options.tenantId,\n usageBackend: this.clickhouse ? \"clickhouse\" : \"postgres\",\n billingPayloadBackend: this.s3 ? \"s3\" : \"postgres\",\n }).query;\n const repository = new PostgresStorageRepository(query, options.tenantId);\n const handlers = this.createHandlers(repository);\n this.worker =\n handlers.length > 0 && options.outbox !== false\n ? new OutboxWorker(repository, handlers, options.outbox)\n : null;\n }\n\n start(options: BursarRuntimeStartOptions = {}): Promise<void> {\n if (this.started) return Promise.resolve();\n if (this.closed) {\n return Promise.reject(new StoreClosedError(\"BursarRuntime has been closed\"));\n }\n if (!this.startPromise) {\n this.startPromise = this.startRuntime(options).catch((error: unknown) => {\n this.startPromise = null;\n throw error;\n });\n }\n return this.startPromise;\n }\n\n private async startRuntime(options: BursarRuntimeStartOptions): Promise<void> {\n if (options.loadCatalog) {\n const maxAttempts = options.maxAttempts ?? 1;\n const shouldRetry =\n options.shouldRetry ??\n ((error: unknown) =>\n error instanceof PricingNotLoadedError || isRetryableBursarError(error));\n await retryBursarOperation(() => this.bursar.loadCatalog(), {\n maxAttempts,\n baseDelayMs: options.retryDelayMs ?? 250,\n maxDelayMs: 5_000,\n maxElapsedMs: options.maxElapsedMs,\n signal: options.signal,\n shouldRetry,\n });\n }\n await this.clickhouse?.initialize?.();\n await this.worker?.start();\n this.started = true;\n }\n\n health(): BursarRuntimeHealth {\n const catalogLoaded = this.bursar.credits.pricingEngine != null;\n return {\n ready: this.started && !this.closed && catalogLoaded,\n started: this.started,\n closed: this.closed,\n catalogLoaded,\n };\n }\n\n async flush(): Promise<OutboxRunResult> {\n if (this.closed) throw new StoreClosedError(\"BursarRuntime has been closed\");\n return this.worker?.runOnce() ?? { claimed: 0, delivered: 0, failed: 0 };\n }\n\n close(): Promise<void> {\n if (this.closePromise) return this.closePromise;\n this.closed = true;\n this.closePromise = this.closeRuntime();\n return this.closePromise;\n }\n\n private async closeRuntime(): Promise<void> {\n const failures: unknown[] = [];\n const pendingStart = this.startPromise;\n if (pendingStart && !this.started) {\n try {\n await pendingStart;\n } catch {\n // Startup callers receive their own failure; shutdown must still clean up.\n }\n }\n\n try {\n await this.worker?.stop();\n } catch (error) {\n failures.push(error);\n }\n\n const resources = await Promise.allSettled([\n Promise.resolve().then(() => this.s3?.close?.()),\n Promise.resolve().then(() => this.creditStore.close()),\n Promise.resolve().then(() => this.billingStore.close()),\n ]);\n for (const result of resources) {\n if (result.status === \"rejected\") failures.push(result.reason);\n }\n\n if (this.ownsPool) {\n try {\n await this.pool.end();\n } catch (error) {\n failures.push(error);\n }\n }\n\n if (failures.length === 1) throw failures[0];\n if (failures.length > 1) {\n throw new AggregateError(failures, \"BursarRuntime failed to close all resources\");\n }\n }\n\n private createHandlers(repository: PostgresStorageRepository): OutboxHandler[] {\n const handlers: OutboxHandler[] = [];\n if (this.clickhouse) {\n handlers.push({\n topics: [\"usage.charge_recorded\"],\n handle: async (outboxEvent) => {\n if (outboxEvent.payloadVersion !== 1) {\n throw new Error(\n `Unsupported usage outbox payload version ${outboxEvent.payloadVersion}`,\n );\n }\n let usage = usageExportFromOutbox(outboxEvent.payload);\n usage ??= await repository.getUsageCharge(outboxEvent.aggregateId);\n if (!usage) {\n throw new Error(`Usage charge ${outboxEvent.aggregateId} is unavailable for export`);\n }\n if (usage.tenantId !== outboxEvent.tenantId) {\n throw new Error(\"Usage export tenant does not match its outbox event\");\n }\n if (usage.chargeId !== outboxEvent.aggregateId) {\n throw new Error(\"Usage export charge does not match its outbox event\");\n }\n await this.clickhouse?.writeUsage(usage, outboxEvent.eventId);\n },\n });\n }\n if (this.s3) {\n handlers.push({\n topics: [\"billing.webhook_received\", \"billing.webhook_completed\"],\n handle: async (outboxEvent) => {\n if (outboxEvent.payloadVersion !== 1) {\n throw new Error(\n `Unsupported billing outbox payload version ${outboxEvent.payloadVersion}`,\n );\n }\n const stored = await repository.getBillingEventPayload(outboxEvent.aggregateId);\n if (stored?.objectKey) return;\n const event =\n outboxEvent.topic === \"billing.webhook_received\"\n ? billingExportFromOutbox(outboxEvent.payload)\n : stored;\n if (!event) {\n throw new Error(`Billing event ${outboxEvent.aggregateId} is unavailable for archive`);\n }\n if (event.tenantId !== outboxEvent.tenantId) {\n throw new Error(\"Billing export tenant does not match its outbox event\");\n }\n if (event.eventId !== outboxEvent.aggregateId) {\n throw new Error(\"Billing export event does not match its outbox event\");\n }\n const archived = await this.s3?.archive(event);\n if (!archived) throw new Error(\"S3 archive is not configured\");\n const recorded = await repository.archiveBillingEventPayload(\n event.eventId,\n archived.key,\n archived.versionId,\n this.s3?.purgePostgresPayload ?? true,\n );\n if (!recorded) {\n throw new Error(`Could not record archive pointer for billing event ${event.eventId}`);\n }\n },\n });\n }\n return handlers;\n }\n}\n\nexport async function createBursarRuntime(options: BursarRuntimeOptions): Promise<BursarRuntime> {\n if (typeof options.postgres !== \"string\") {\n return new BursarRuntime(options.postgres, false, options);\n }\n if (!options.postgres.trim()) throw new TypeError(\"postgres connection string must not be empty\");\n let pg: typeof import(\"pg\");\n try {\n pg = await import(\"pg\");\n } catch (cause) {\n throw new BursarImportError(\"pg is required for the Bursar runtime: npm install pg\", { cause });\n }\n const pool = new pg.Pool(\n postgresPoolConfig(options.postgres, options.postgresOptions),\n ) as unknown as PostgresPool;\n return new BursarRuntime(pool, true, options);\n}\n\nfunction usageExportFromOutbox(payload: Record<string, unknown>): UsageChargeExport | null {\n const requiredStrings = [\n \"tenant_id\",\n \"charge_id\",\n \"account_id\",\n \"subject_id\",\n \"operation\",\n \"requested\",\n \"charged\",\n \"allowance_requested\",\n \"allowance_covered\",\n \"idempotency_key\",\n \"request_digest\",\n \"event_at\",\n \"created_at\",\n ] as const;\n if (requiredStrings.some((key) => !isNonEmptyString(payload[key]))) return null;\n if (\n !isJsonObject(payload.measures) ||\n !isJsonObject(payload.dimensions) ||\n !isJsonObject(payload.metadata) ||\n !isJsonObject(payload.pricing_snapshot)\n ) {\n return null;\n }\n const optionalStrings = [\n \"feature\",\n \"model\",\n \"region\",\n \"catalog_revision_id\",\n \"plan_id\",\n \"rate_card_key\",\n \"ledger_entry_id\",\n \"correction_of_charge_id\",\n ] as const;\n if (optionalStrings.some((key) => !isOptionalString(payload[key]))) return null;\n if (\n payload.billing_disposition !== undefined &&\n payload.billing_disposition !== \"billable\" &&\n payload.billing_disposition !== \"record_only\"\n ) {\n return null;\n }\n return {\n tenantId: payload.tenant_id as string,\n chargeId: payload.charge_id as string,\n accountId: payload.account_id as string,\n subjectId: payload.subject_id as string,\n operation: payload.operation as string,\n feature: (payload.feature as string | null) ?? null,\n model: (payload.model as string | null) ?? null,\n region: (payload.region as string | null) ?? null,\n measures: payload.measures,\n dimensions: payload.dimensions,\n metadata: payload.metadata,\n requested: payload.requested as string,\n charged: payload.charged as string,\n allowanceRequested: payload.allowance_requested as string,\n allowanceCovered: payload.allowance_covered as string,\n billingDisposition: payload.billing_disposition === \"record_only\" ? \"record_only\" : \"billable\",\n catalogRevisionId: (payload.catalog_revision_id as string | null) ?? null,\n planId: (payload.plan_id as string | null) ?? null,\n rateCardKey: (payload.rate_card_key as string | null) ?? null,\n pricingSnapshot: payload.pricing_snapshot,\n ledgerEntryId: (payload.ledger_entry_id as string | null) ?? null,\n correctionOfChargeId: (payload.correction_of_charge_id as string | null) ?? null,\n idempotencyKey: payload.idempotency_key as string,\n requestDigest: payload.request_digest as string,\n eventAt: payload.event_at as string,\n createdAt: payload.created_at as string,\n };\n}\n\nfunction billingExportFromOutbox(\n payload: Record<string, unknown>,\n): BillingEventPayloadExport | null {\n const requiredStrings = [\n \"tenant_id\",\n \"event_id\",\n \"provider\",\n \"provider_environment\",\n \"provider_event_id\",\n \"event_type\",\n \"status\",\n \"received_at\",\n ] as const;\n if (requiredStrings.some((key) => !isNonEmptyString(payload[key]))) return null;\n if (!isJsonObject(payload.envelope)) return null;\n if (!isOptionalString(payload.completed_at)) return null;\n return {\n tenantId: payload.tenant_id as string,\n eventId: payload.event_id as string,\n provider: payload.provider as string,\n providerEnvironment: payload.provider_environment as string,\n providerEventId: payload.provider_event_id as string,\n eventType: payload.event_type as string,\n status: payload.status as string,\n receivedAt: payload.received_at as string,\n completedAt: payload.completed_at ? String(payload.completed_at) : null,\n envelope: payload.envelope,\n objectKey: (payload.object_key as string | null) ?? null,\n objectVersion: (payload.object_version as string | null) ?? null,\n archivedAt: (payload.archived_at as string | null) ?? null,\n };\n}\n\nfunction isNonEmptyString(value: unknown): value is string {\n return typeof value === \"string\" && value.length > 0;\n}\n\nfunction isOptionalString(value: unknown): value is string | null | undefined {\n return value === null || value === undefined || typeof value === \"string\";\n}\n\nfunction isJsonObject(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"runtime.js","sourceRoot":"","sources":["../../src/storage/runtime.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AACtC,OAAO,EACL,WAAW,EACX,WAAW,IAAI,iBAAiB,EAChC,sBAAsB,EACtB,qBAAqB,EACrB,gBAAgB,GACjB,MAAM,cAAc,CAAC;AACtB,OAAO,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AACnD,OAAO,EAAE,oBAAoB,EAAE,MAAM,8BAA8B,CAAC;AAEpE,OAAO,EAAE,aAAa,EAAE,MAAM,8BAA8B,CAAC;AAK7D,OAAO,EACL,iBAAiB,EACjB,cAAc,EACd,kBAAkB,GAGnB,MAAM,8BAA8B,CAAC;AAEtC,OAAO,EAAE,oBAAoB,EAAoC,MAAM,0BAA0B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C,OAAO,CAAC,YAAY,CAAC;QAAE,OAAO,IAAI,CAAC;IACzD,OAAO;QACL,QAAQ,EAAE,OAAO,CAAC,SAAmB;QACrC,OAAO,EAAE,OAAO,CAAC,QAAkB;QACnC,QAAQ,EAAE,OAAO,CAAC,QAAkB;QACpC,mBAAmB,EAAE,OAAO,CAAC,oBAA8B;QAC3D,eAAe,EAAE,OAAO,CAAC,iBAA2B;QACpD,SAAS,EAAE,OAAO,CAAC,UAAoB;QACvC,MAAM,EAAE,OAAO,CAAC,MAAgB;QAChC,UAAU,EAAE,OAAO,CAAC,WAAqB;QACzC,WAAW,EAAE,OAAO,CAAC,YAAY,CAAC,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,IAAI;QACvE,QAAQ,EAAE,OAAO,CAAC,QAAQ;QAC1B,SAAS,EAAG,OAAO,CAAC,UAA4B,IAAI,IAAI;QACxD,aAAa,EAAG,OAAO,CAAC,cAAgC,IAAI,IAAI;QAChE,UAAU,EAAG,OAAO,CAAC,WAA6B,IAAI,IAAI;KAC3D,CAAC;AACJ,CAAC;AAED,SAAS,gBAAgB,CAAC,KAAc;IACtC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC;AACvD,CAAC;AAED,SAAS,gBAAgB,CAAC,KAAc;IACtC,OAAO,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,SAAS,IAAI,OAAO,KAAK,KAAK,QAAQ,CAAC;AAC5E,CAAC;AAED,SAAS,YAAY,CAAC,KAAc;IAClC,OAAO,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC9E,CAAC","sourcesContent":["import { Bursar } from \"../bursar.js\";\nimport {\n ConfigError,\n ImportError as BursarImportError,\n isRetryableBursarError,\n CatalogNotLoadedError,\n StoreClosedError,\n} from \"../errors.js\";\nimport { retryBursarOperation } from \"../retry.js\";\nimport { PostgresBillingStore } from \"../billing/postgres/store.js\";\nimport type { BillingServiceOptions } from \"../billing/billing-service.js\";\nimport { PostgresStore } from \"../credits/postgres/store.js\";\nimport type { CreditsServiceOptions } from \"../credits/service.js\";\nimport type { CreditEventEmitter } from \"../credits/events.js\";\nimport type { CommerceOptions } from \"../commerce/types.js\";\nimport type { UsageAnalyticsStore, UsageChargeStore } from \"../credits/types/index.js\";\nimport {\n normalizeTenantId,\n PostgresClient,\n postgresPoolConfig,\n type PostgresConnectionOptions,\n type PostgresPool,\n} from \"../shared/postgres-client.js\";\nimport type { QueryFn } from \"../shared/postgres-types.js\";\nimport { ClickHouseUsageStore, type ClickHouseUsageStoreOptions } from \"./adapters/clickhouse.js\";\nimport { S3BillingArchive, type S3BillingArchiveOptions } from \"./adapters/s3.js\";\nimport { OutboxWorker, type OutboxRunResult, type OutboxWorkerOptions } from \"./outbox-worker.js\";\nimport type {\n BillingEventPayloadExport,\n BillingPayloadArchive,\n OutboxHandler,\n UsageChargeExport,\n UsageEventSink,\n} from \"./ports.js\";\nimport { PostgresStorageRepository } from \"./postgres-repository.js\";\n\n/** Facade configuration accepted by the composed Node.js runtime. */\nexport interface BursarRuntimeBursarOptions {\n creditsOptions?: Omit<CreditsServiceOptions, \"analytics\"> | null;\n billingOptions?: BillingServiceOptions | null;\n commerceOptions?: CommerceOptions | null;\n emitter?: CreditEventEmitter | null;\n}\n\nexport interface BursarRuntimeOptions {\n postgres: string | PostgresPool;\n /** Applied to SDK-owned pools and per-transaction statement deadlines. */\n postgresOptions?: PostgresConnectionOptions;\n tenantId: string;\n /**\n * Optional provisioned tenant slug. When supplied, startup verifies that it\n * resolves to `tenantId` before any worker or catalog lifecycle begins.\n */\n tenantSlug?: string;\n s3?: BillingPayloadArchive | S3BillingArchiveOptions | null;\n clickhouse?: (UsageEventSink & UsageAnalyticsStore) | ClickHouseUsageStoreOptions | null;\n /**\n * Background delivery configuration. Set false only when another process\n * consumes Bursar's outbox.\n */\n outbox?: OutboxWorkerOptions | false;\n bursar?: BursarRuntimeBursarOptions;\n}\n\nexport interface BursarRuntimeStartOptions {\n /** Load the active catalog before starting background workers. */\n loadCatalog?: boolean;\n /** Total catalog-load attempts, including the first. Defaults to 1. */\n maxAttempts?: number;\n /** Initial retry delay. Each retry doubles up to 5 seconds. */\n retryDelayMs?: number;\n shouldRetry?: (error: unknown) => boolean;\n /** Maximum elapsed catalog-load retry budget. Defaults to 30 seconds. */\n maxElapsedMs?: number;\n /** Abort startup retries and pending backoff. */\n signal?: AbortSignal;\n}\n\nexport interface BursarRuntimeHealth {\n ready: boolean;\n started: boolean;\n closed: boolean;\n catalogLoaded: boolean;\n}\n\n/**\n * Node composition root for Bursar's stores and optional data infrastructure.\n *\n * Without S3 or ClickHouse it constructs the same PostgreSQL-only Bursar and\n * no outbox polling loop. All components share one PostgreSQL pool.\n */\nexport class BursarRuntime {\n readonly bursar: Bursar;\n readonly creditStore: PostgresStore;\n readonly billingStore: PostgresBillingStore;\n readonly worker: OutboxWorker | null;\n readonly clickhouse: (UsageEventSink & UsageAnalyticsStore) | null;\n readonly s3: BillingPayloadArchive | null;\n\n private readonly pool: PostgresPool;\n private readonly ownsPool: boolean;\n private readonly postgres: PostgresClient;\n private readonly query: QueryFn;\n private readonly tenantId: string;\n private readonly tenantSlug: string | null;\n private startPromise: Promise<void> | null = null;\n private closePromise: Promise<void> | null = null;\n private started = false;\n private closed = false;\n\n /** Construct a runtime while keeping pool ownership inside the SDK. */\n static async create(options: BursarRuntimeOptions): Promise<BursarRuntime> {\n if (typeof options.postgres !== \"string\") {\n return new BursarRuntime(options.postgres, false, options);\n }\n if (!options.postgres.trim()) {\n throw new TypeError(\"postgres connection string must not be empty\");\n }\n let pg: typeof import(\"pg\");\n try {\n pg = await import(\"pg\");\n } catch (cause) {\n throw new BursarImportError(\"pg is required for the Bursar runtime: npm install pg\", {\n cause,\n });\n }\n const pool = new pg.Pool(\n postgresPoolConfig(options.postgres, options.postgresOptions),\n ) as PostgresPool;\n try {\n return new BursarRuntime(pool, true, options);\n } catch (error) {\n try {\n await pool.end();\n } catch {\n // Preserve the composition error; no runtime exists to report cleanup.\n }\n throw error;\n }\n }\n\n private constructor(\n pool: PostgresPool,\n ownsPool: boolean,\n options: Omit<BursarRuntimeOptions, \"postgres\">,\n ) {\n this.pool = pool;\n this.ownsPool = ownsPool;\n this.tenantId = normalizeTenantId(options.tenantId);\n this.tenantSlug =\n options.tenantSlug === undefined ? null : normalizeTenantSlug(options.tenantSlug);\n if (\n options.clickhouse &&\n !(\"writeUsage\" in options.clickhouse) &&\n normalizeTenantId(options.clickhouse.tenantId) !== this.tenantId\n ) {\n throw new TypeError(\"ClickHouse tenantId must match runtime tenantId\");\n }\n this.clickhouse = options.clickhouse\n ? \"writeUsage\" in options.clickhouse\n ? options.clickhouse\n : new ClickHouseUsageStore({ ...options.clickhouse, tenantId: this.tenantId })\n : null;\n this.s3 = options.s3\n ? \"archive\" in options.s3\n ? options.s3\n : new S3BillingArchive(options.s3)\n : null;\n\n this.creditStore = new PostgresStore({\n postgres: pool,\n tenantId: this.tenantId,\n ...(options.postgresOptions ?? {}),\n usageBackend: this.clickhouse ? \"clickhouse\" : \"postgres\",\n });\n this.billingStore = new PostgresBillingStore({\n postgres: pool,\n tenantId: this.tenantId,\n ...(options.postgresOptions ?? {}),\n billingPayloadBackend: this.s3 ? \"s3\" : \"postgres\",\n });\n const bursarOptions = options.bursar ?? {};\n const commerceOptions = bursarOptions.commerceOptions\n ? {\n ...bursarOptions.commerceOptions,\n tenantId: this.tenantId,\n }\n : undefined;\n this.bursar = new Bursar({\n ...bursarOptions,\n commerceOptions,\n creditStore: this.creditStore,\n billingStore: this.billingStore,\n creditsOptions: {\n ...(bursarOptions.creditsOptions ?? {}),\n analytics: this.clickhouse ?? undefined,\n usageStore:\n this.clickhouse && \"listUsageCharges\" in this.clickhouse\n ? (this.clickhouse as UsageChargeStore)\n : undefined,\n },\n });\n\n this.postgres = new PostgresClient(pool, {\n ...(options.postgresOptions ?? {}),\n tenantId: this.tenantId,\n accessRole: \"bursar_operator\",\n usageBackend: this.clickhouse ? \"clickhouse\" : \"postgres\",\n billingPayloadBackend: this.s3 ? \"s3\" : \"postgres\",\n });\n this.query = this.postgres.query;\n const repository = new PostgresStorageRepository(this.query, this.tenantId);\n const handlers = this.createHandlers(repository);\n this.worker =\n handlers.length > 0 && options.outbox !== false\n ? new OutboxWorker(repository, handlers, options.outbox)\n : null;\n }\n\n start(options: BursarRuntimeStartOptions = {}): Promise<void> {\n if (this.closed) {\n return Promise.reject(new StoreClosedError(\"BursarRuntime has been closed\"));\n }\n if (this.started) return Promise.resolve();\n if (!this.startPromise) {\n this.startPromise = this.startRuntime(options).catch((error: unknown) => {\n this.startPromise = null;\n throw error;\n });\n }\n return this.startPromise;\n }\n\n private async startRuntime(options: BursarRuntimeStartOptions): Promise<void> {\n if (this.tenantSlug) await this.verifyTenantIdentity();\n if (options.loadCatalog ?? true) {\n const maxAttempts = options.maxAttempts ?? 1;\n const shouldRetry =\n options.shouldRetry ??\n ((error: unknown) =>\n error instanceof CatalogNotLoadedError || isRetryableBursarError(error));\n await retryBursarOperation(() => this.bursar.loadCatalog(), {\n maxAttempts,\n baseDelayMs: options.retryDelayMs ?? 250,\n maxDelayMs: 5_000,\n maxElapsedMs: options.maxElapsedMs,\n signal: options.signal,\n shouldRetry,\n });\n }\n await this.clickhouse?.initialize?.();\n await this.worker?.start();\n this.started = true;\n }\n\n health(): BursarRuntimeHealth {\n const catalogLoaded = this.bursar.catalog.isLoaded;\n return {\n ready: this.started && !this.closed && catalogLoaded,\n started: this.started,\n closed: this.closed,\n catalogLoaded,\n };\n }\n\n async flush(): Promise<OutboxRunResult> {\n if (this.closed) throw new StoreClosedError(\"BursarRuntime has been closed\");\n return this.worker?.runOnce() ?? { claimed: 0, delivered: 0, failed: 0 };\n }\n\n close(): Promise<void> {\n if (this.closePromise) return this.closePromise;\n this.closed = true;\n this.closePromise = this.closeRuntime();\n return this.closePromise;\n }\n\n private async closeRuntime(): Promise<void> {\n const failures: unknown[] = [];\n const pendingStart = this.startPromise;\n if (pendingStart && !this.started) {\n try {\n await pendingStart;\n } catch {\n // Startup callers receive their own failure; shutdown must still clean up.\n }\n }\n\n try {\n await this.worker?.stop();\n } catch (error) {\n failures.push(error);\n }\n\n const resources = await Promise.allSettled([\n Promise.resolve().then(() => this.s3?.close?.()),\n Promise.resolve().then(() => this.creditStore.close()),\n Promise.resolve().then(() => this.billingStore.close()),\n Promise.resolve().then(() => this.postgres.close()),\n ]);\n for (const result of resources) {\n if (result.status === \"rejected\") failures.push(result.reason);\n }\n\n if (this.ownsPool) {\n try {\n await this.pool.end();\n } catch (error) {\n failures.push(error);\n }\n }\n\n if (failures.length === 1) throw failures[0];\n if (failures.length > 1) {\n throw new AggregateError(failures, \"BursarRuntime failed to close all resources\");\n }\n }\n\n private createHandlers(repository: PostgresStorageRepository): OutboxHandler[] {\n const handlers: OutboxHandler[] = [];\n if (this.clickhouse) {\n handlers.push({\n topics: [\"usage.charge_recorded\"],\n handle: async (outboxEvent) => {\n if (outboxEvent.payloadVersion !== 1) {\n throw new Error(\n `Unsupported usage outbox payload version ${outboxEvent.payloadVersion}`,\n );\n }\n let usage = usageExportFromOutbox(outboxEvent.payload);\n usage ??= await repository.getUsageCharge(outboxEvent.aggregateId);\n if (!usage) {\n throw new Error(`Usage charge ${outboxEvent.aggregateId} is unavailable for export`);\n }\n if (usage.tenantId !== outboxEvent.tenantId) {\n throw new Error(\"Usage export tenant does not match its outbox event\");\n }\n if (usage.chargeId !== outboxEvent.aggregateId) {\n throw new Error(\"Usage export charge does not match its outbox event\");\n }\n await this.clickhouse?.writeUsage(usage, outboxEvent.eventId);\n },\n });\n }\n if (this.s3) {\n handlers.push({\n topics: [\"billing.webhook_received\", \"billing.webhook_completed\"],\n handle: async (outboxEvent) => {\n if (outboxEvent.payloadVersion !== 1) {\n throw new Error(\n `Unsupported billing outbox payload version ${outboxEvent.payloadVersion}`,\n );\n }\n const stored = await repository.getBillingEventPayload(outboxEvent.aggregateId);\n if (stored?.objectKey) return;\n const event =\n outboxEvent.topic === \"billing.webhook_received\"\n ? billingExportFromOutbox(outboxEvent.payload)\n : stored;\n if (!event) {\n throw new Error(`Billing event ${outboxEvent.aggregateId} is unavailable for archive`);\n }\n if (event.tenantId !== outboxEvent.tenantId) {\n throw new Error(\"Billing export tenant does not match its outbox event\");\n }\n if (event.eventId !== outboxEvent.aggregateId) {\n throw new Error(\"Billing export event does not match its outbox event\");\n }\n const archived = await this.s3?.archive(event);\n if (!archived) throw new Error(\"S3 archive is not configured\");\n const recorded = await repository.archiveBillingEventPayload(\n event.eventId,\n archived.key,\n archived.versionId,\n );\n if (!recorded) {\n throw new Error(`Could not record archive pointer for billing event ${event.eventId}`);\n }\n },\n });\n }\n return handlers;\n }\n\n private async verifyTenantIdentity(): Promise<void> {\n if (!this.tenantSlug) return;\n const rows = await this.query(\n \"SELECT bursar.resolve_active_tenant_for_trigger($1)::text AS tenant_id\",\n [this.tenantSlug],\n );\n const resolved = rows[0];\n const tenantId =\n resolved && typeof resolved === \"object\" && \"tenant_id\" in resolved\n ? (resolved as { tenant_id?: unknown }).tenant_id\n : undefined;\n if (tenantId !== this.tenantId) {\n throw new ConfigError(\n `Bursar tenant slug '${this.tenantSlug}' resolves to a different tenant ID`,\n );\n }\n }\n}\n\nexport async function createBursarRuntime(options: BursarRuntimeOptions): Promise<BursarRuntime> {\n return BursarRuntime.create(options);\n}\n\nfunction normalizeTenantSlug(value: string): string {\n if (typeof value !== \"string\") throw new TypeError(\"tenantSlug must be a string\");\n const normalized = value.trim().toLowerCase();\n if (\n normalized.length < 1 ||\n normalized.length > 100 ||\n !/^[a-z0-9]+(?:[a-z0-9-]*[a-z0-9])?$/.test(normalized)\n ) {\n throw new TypeError(\"tenantSlug must be a valid Bursar tenant slug\");\n }\n return normalized;\n}\n\nfunction usageExportFromOutbox(payload: Record<string, unknown>): UsageChargeExport | null {\n const requiredStrings = [\n \"tenant_id\",\n \"charge_id\",\n \"account_id\",\n \"subject_id\",\n \"operation\",\n \"requested\",\n \"charged\",\n \"allowance_requested\",\n \"allowance_covered\",\n \"idempotency_key\",\n \"request_digest\",\n \"event_at\",\n \"created_at\",\n ] as const;\n if (requiredStrings.some((key) => !isNonEmptyString(payload[key]))) return null;\n if (\n !isJsonObject(payload.measures) ||\n !isJsonObject(payload.dimensions) ||\n !isJsonObject(payload.metadata) ||\n !isJsonObject(payload.pricing_snapshot)\n ) {\n return null;\n }\n const optionalStrings = [\n \"feature\",\n \"model\",\n \"region\",\n \"catalog_revision_id\",\n \"plan_id\",\n \"rate_card_key\",\n \"ledger_entry_id\",\n \"correction_of_charge_id\",\n ] as const;\n if (optionalStrings.some((key) => !isOptionalString(payload[key]))) return null;\n if (\n payload.billing_disposition !== undefined &&\n payload.billing_disposition !== \"billable\" &&\n payload.billing_disposition !== \"record_only\"\n ) {\n return null;\n }\n return {\n tenantId: payload.tenant_id as string,\n chargeId: payload.charge_id as string,\n accountId: payload.account_id as string,\n subjectId: payload.subject_id as string,\n operation: payload.operation as string,\n feature: (payload.feature as string | null) ?? null,\n model: (payload.model as string | null) ?? null,\n region: (payload.region as string | null) ?? null,\n measures: payload.measures,\n dimensions: payload.dimensions,\n metadata: payload.metadata,\n requested: payload.requested as string,\n charged: payload.charged as string,\n allowanceRequested: payload.allowance_requested as string,\n allowanceCovered: payload.allowance_covered as string,\n billingDisposition: payload.billing_disposition === \"record_only\" ? \"record_only\" : \"billable\",\n catalogRevisionId: (payload.catalog_revision_id as string | null) ?? null,\n planId: (payload.plan_id as string | null) ?? null,\n rateCardKey: (payload.rate_card_key as string | null) ?? null,\n pricingSnapshot: payload.pricing_snapshot,\n ledgerEntryId: (payload.ledger_entry_id as string | null) ?? null,\n correctionOfChargeId: (payload.correction_of_charge_id as string | null) ?? null,\n idempotencyKey: payload.idempotency_key as string,\n requestDigest: payload.request_digest as string,\n eventAt: payload.event_at as string,\n createdAt: payload.created_at as string,\n };\n}\n\nfunction billingExportFromOutbox(\n payload: Record<string, unknown>,\n): BillingEventPayloadExport | null {\n const requiredStrings = [\n \"tenant_id\",\n \"event_id\",\n \"provider\",\n \"provider_environment\",\n \"provider_event_id\",\n \"event_type\",\n \"status\",\n \"received_at\",\n ] as const;\n if (requiredStrings.some((key) => !isNonEmptyString(payload[key]))) return null;\n if (!isJsonObject(payload.envelope)) return null;\n if (!isOptionalString(payload.completed_at)) return null;\n return {\n tenantId: payload.tenant_id as string,\n eventId: payload.event_id as string,\n provider: payload.provider as string,\n providerEnvironment: payload.provider_environment as string,\n providerEventId: payload.provider_event_id as string,\n eventType: payload.event_type as string,\n status: payload.status as string,\n receivedAt: payload.received_at as string,\n completedAt: payload.completed_at ? String(payload.completed_at) : null,\n envelope: payload.envelope,\n objectKey: (payload.object_key as string | null) ?? null,\n objectVersion: (payload.object_version as string | null) ?? null,\n archivedAt: (payload.archived_at as string | null) ?? null,\n };\n}\n\nfunction isNonEmptyString(value: unknown): value is string {\n return typeof value === \"string\" && value.length > 0;\n}\n\nfunction isOptionalString(value: unknown): value is string | null | undefined {\n return value === null || value === undefined || typeof value === \"string\";\n}\n\nfunction isJsonObject(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zonastery/bursar",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "2.0.1",
|
|
4
4
|
"packageManager": "bun@1.3.14",
|
|
5
|
-
"description": "
|
|
5
|
+
"description": "Usage metering, credits, subscriptions, and payments for AI applications",
|
|
6
6
|
"type": "module",
|
|
7
|
+
"sideEffects": false,
|
|
7
8
|
"main": "./dist/index.js",
|
|
8
9
|
"types": "./dist/index.d.ts",
|
|
9
10
|
"exports": {
|
|
@@ -32,6 +33,21 @@
|
|
|
32
33
|
"import": "./dist/providers/dodo/index.js",
|
|
33
34
|
"default": "./dist/providers/dodo/index.js"
|
|
34
35
|
},
|
|
36
|
+
"./providers/dodo/nextjs": {
|
|
37
|
+
"types": "./dist/providers/dodo/nextjs.d.ts",
|
|
38
|
+
"import": "./dist/providers/dodo/nextjs.js",
|
|
39
|
+
"default": "./dist/providers/dodo/nextjs.js"
|
|
40
|
+
},
|
|
41
|
+
"./providers/dodo/better-auth": {
|
|
42
|
+
"types": "./dist/providers/dodo/better-auth.d.ts",
|
|
43
|
+
"import": "./dist/providers/dodo/better-auth.js",
|
|
44
|
+
"default": "./dist/providers/dodo/better-auth.js"
|
|
45
|
+
},
|
|
46
|
+
"./providers/dodo/react-native": {
|
|
47
|
+
"types": "./dist/providers/dodo/react-native.d.ts",
|
|
48
|
+
"import": "./dist/providers/dodo/react-native.js",
|
|
49
|
+
"default": "./dist/providers/dodo/react-native.js"
|
|
50
|
+
},
|
|
35
51
|
"./providers/stripe": {
|
|
36
52
|
"types": "./dist/providers/stripe/index.d.ts",
|
|
37
53
|
"import": "./dist/providers/stripe/index.js",
|
|
@@ -42,6 +58,11 @@
|
|
|
42
58
|
"import": "./dist/providers/mock/index.js",
|
|
43
59
|
"default": "./dist/providers/mock/index.js"
|
|
44
60
|
},
|
|
61
|
+
"./integrations/better-auth": {
|
|
62
|
+
"types": "./dist/integrations/better-auth.d.ts",
|
|
63
|
+
"import": "./dist/integrations/better-auth.js",
|
|
64
|
+
"default": "./dist/integrations/better-auth.js"
|
|
65
|
+
},
|
|
45
66
|
"./package.json": "./package.json"
|
|
46
67
|
},
|
|
47
68
|
"engines": {
|
|
@@ -54,7 +75,7 @@
|
|
|
54
75
|
"clean": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\"",
|
|
55
76
|
"build": "bun run clean && tsc",
|
|
56
77
|
"generate:config-types": "json2ts -i src/generated/pricing-config.schema.json -o src/generated/pricing-config.types.ts --unknownAny && prettier --write src/generated/pricing-config.types.ts",
|
|
57
|
-
"typecheck": "tsc --noEmit",
|
|
78
|
+
"typecheck": "tsc --noEmit && tsc -p tsconfig.test.json",
|
|
58
79
|
"test": "vitest run --maxWorkers=1",
|
|
59
80
|
"test:providers": "vitest --config vitest.providers.config.ts run --coverage",
|
|
60
81
|
"test:concurrency": "vitest run tests/store-integration.test.ts tests/billing-integration.test.ts -t concurrent",
|
|
@@ -82,8 +103,10 @@
|
|
|
82
103
|
},
|
|
83
104
|
"homepage": "https://zonastery.github.io/bursar/",
|
|
84
105
|
"license": "AGPL-3.0-only",
|
|
106
|
+
"publishConfig": {
|
|
107
|
+
"access": "public"
|
|
108
|
+
},
|
|
85
109
|
"dependencies": {
|
|
86
|
-
"@aws-sdk/client-s3": "^3.1097.0",
|
|
87
110
|
"@js-temporal/polyfill": "^0.5.1",
|
|
88
111
|
"ajv": "^8.17.1",
|
|
89
112
|
"ajv-formats": "^3.0.1",
|
|
@@ -93,19 +116,39 @@
|
|
|
93
116
|
"zod": "^4.4.3"
|
|
94
117
|
},
|
|
95
118
|
"peerDependencies": {
|
|
96
|
-
"@dodopayments/
|
|
119
|
+
"@dodopayments/better-auth": "^1.6.4",
|
|
120
|
+
"@dodopayments/nextjs": "^0.3.7",
|
|
121
|
+
"@dodopayments/react-native-checkout": "^1.1.2",
|
|
122
|
+
"@aws-sdk/client-s3": "^3.1097.0",
|
|
123
|
+
"better-auth": "^1.4.0",
|
|
97
124
|
"dodopayments": "^2.40.1",
|
|
98
125
|
"js-yaml": "^4.0.0",
|
|
126
|
+
"next": "^14.0.0 || ^15.0.0 || ^16.0.0",
|
|
99
127
|
"pg": "^8.0.0",
|
|
100
128
|
"stripe": "^22.2.0"
|
|
101
129
|
},
|
|
102
130
|
"peerDependenciesMeta": {
|
|
103
|
-
"@dodopayments/
|
|
131
|
+
"@dodopayments/better-auth": {
|
|
132
|
+
"optional": true
|
|
133
|
+
},
|
|
134
|
+
"@dodopayments/nextjs": {
|
|
135
|
+
"optional": true
|
|
136
|
+
},
|
|
137
|
+
"@dodopayments/react-native-checkout": {
|
|
138
|
+
"optional": true
|
|
139
|
+
},
|
|
140
|
+
"@aws-sdk/client-s3": {
|
|
141
|
+
"optional": true
|
|
142
|
+
},
|
|
143
|
+
"better-auth": {
|
|
104
144
|
"optional": true
|
|
105
145
|
},
|
|
106
146
|
"js-yaml": {
|
|
107
147
|
"optional": true
|
|
108
148
|
},
|
|
149
|
+
"next": {
|
|
150
|
+
"optional": true
|
|
151
|
+
},
|
|
109
152
|
"pg": {
|
|
110
153
|
"optional": true
|
|
111
154
|
},
|
|
@@ -117,13 +160,17 @@
|
|
|
117
160
|
}
|
|
118
161
|
},
|
|
119
162
|
"devDependencies": {
|
|
120
|
-
"@dodopayments/
|
|
163
|
+
"@dodopayments/better-auth": "^1.6.4",
|
|
164
|
+
"@dodopayments/nextjs": "^0.3.7",
|
|
165
|
+
"@dodopayments/react-native-checkout": "^1.1.2",
|
|
166
|
+
"@aws-sdk/client-s3": "^3.1097.0",
|
|
121
167
|
"@eslint/js": "^10.0.1",
|
|
122
168
|
"@testcontainers/postgresql": "^12.0.4",
|
|
123
169
|
"@types/js-yaml": "^4.0.9",
|
|
124
170
|
"@types/node": "^22.0.0",
|
|
125
171
|
"@types/pg": "^8.20.0",
|
|
126
172
|
"@vitest/coverage-v8": "^3.2.6",
|
|
173
|
+
"better-auth": "^1.6.25",
|
|
127
174
|
"dodopayments": "^2.40.1",
|
|
128
175
|
"eslint": "^10.5.0",
|
|
129
176
|
"globals": "^14.0.0",
|
|
@@ -131,9 +178,11 @@
|
|
|
131
178
|
"json-schema-to-typescript": "^15.0.4",
|
|
132
179
|
"knip": "^6.18.0",
|
|
133
180
|
"lefthook": "^1.11.12",
|
|
181
|
+
"next": "^16.3.0",
|
|
134
182
|
"pg": "^8.22.0",
|
|
135
183
|
"prettier": "^3.8.4",
|
|
136
184
|
"stripe": "^22.2.0",
|
|
185
|
+
"testcontainers": "^12.0.4",
|
|
137
186
|
"typescript": "^5.7.0",
|
|
138
187
|
"typescript-eslint": "^8.62.0",
|
|
139
188
|
"vitest": "^3.2.6"
|
|
@@ -1,28 +0,0 @@
|
|
|
1
|
-
import { z } from "zod";
|
|
2
|
-
import type { CallProc } from "../../../shared/postgres-types.js";
|
|
3
|
-
declare const ActivePricingRowSchema: z.ZodObject<{
|
|
4
|
-
id: z.ZodOptional<z.ZodString>;
|
|
5
|
-
config: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
|
|
6
|
-
source_document: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
|
|
7
|
-
version: z.ZodOptional<z.ZodCoercedNumber<unknown>>;
|
|
8
|
-
revision_no: z.ZodOptional<z.ZodCoercedNumber<unknown>>;
|
|
9
|
-
label: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
10
|
-
active: z.ZodOptional<z.ZodNullable<z.ZodPipe<z.ZodUnion<readonly [z.ZodBoolean, z.ZodString, z.ZodNumber]>, z.ZodTransform<boolean, string | number | boolean>>>>;
|
|
11
|
-
status: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
12
|
-
created_at: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodPipe<z.ZodDate, z.ZodTransform<string, Date>>]>>;
|
|
13
|
-
}, z.core.$loose>;
|
|
14
|
-
export type ActivePricingRow = z.infer<typeof ActivePricingRowSchema>;
|
|
15
|
-
export type PricingHistoryRow = ActivePricingRow;
|
|
16
|
-
export declare class PricingRepository {
|
|
17
|
-
private readonly callproc;
|
|
18
|
-
constructor(callproc: CallProc);
|
|
19
|
-
private parseRevision;
|
|
20
|
-
getActivePricing(): Promise<ActivePricingRow | null>;
|
|
21
|
-
setActivePricing(config: string, label: string | null, rollout: Record<string, unknown>): Promise<ActivePricingRow>;
|
|
22
|
-
publishPricing(config: string, label: string | null, activate?: boolean, rollout?: Record<string, unknown>): Promise<ActivePricingRow>;
|
|
23
|
-
getPricingHistory(): Promise<PricingHistoryRow[]>;
|
|
24
|
-
getBursarConfig(version: number): Promise<ActivePricingRow | null>;
|
|
25
|
-
activatePricing(version: number, rollout: Record<string, unknown>): Promise<ActivePricingRow>;
|
|
26
|
-
}
|
|
27
|
-
export {};
|
|
28
|
-
//# sourceMappingURL=pricing.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"pricing.d.ts","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/pricing.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,mCAAmC,CAAC;AAGlE,QAAA,MAAM,sBAAsB;;;;;;;;;;iBAYZ,CAAC;AACjB,MAAM,MAAM,gBAAgB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,sBAAsB,CAAC,CAAC;AACtE,MAAM,MAAM,iBAAiB,GAAG,gBAAgB,CAAC;AAEjD,qBAAa,iBAAiB;IAChB,OAAO,CAAC,QAAQ,CAAC,QAAQ;gBAAR,QAAQ,EAAE,QAAQ;IAE/C,OAAO,CAAC,aAAa;IAaf,gBAAgB,IAAI,OAAO,CAAC,gBAAgB,GAAG,IAAI,CAAC;IAOpD,gBAAgB,CACpB,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,MAAM,GAAG,IAAI,EACpB,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAC/B,OAAO,CAAC,gBAAgB,CAAC;IAItB,cAAc,CAClB,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,MAAM,GAAG,IAAI,EACpB,QAAQ,UAAQ,EAChB,OAAO,GAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAiB,GAC/C,OAAO,CAAC,gBAAgB,CAAC;IA6BtB,iBAAiB,IAAI,OAAO,CAAC,iBAAiB,EAAE,CAAC;IAOjD,eAAe,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,gBAAgB,GAAG,IAAI,CAAC;IASlE,eAAe,CACnB,OAAO,EAAE,MAAM,EACf,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAC/B,OAAO,CAAC,gBAAgB,CAAC;CAQ7B"}
|
|
@@ -1,76 +0,0 @@
|
|
|
1
|
-
import { z } from "zod";
|
|
2
|
-
import { pgBoolean, safeParse } from "../../../shared/postgres-validation.js";
|
|
3
|
-
const ActivePricingRowSchema = z
|
|
4
|
-
.object({
|
|
5
|
-
id: z.string().optional(),
|
|
6
|
-
config: z.record(z.string(), z.unknown()).optional(),
|
|
7
|
-
source_document: z.record(z.string(), z.unknown()).optional(),
|
|
8
|
-
version: z.coerce.number().optional(),
|
|
9
|
-
revision_no: z.coerce.number().optional(),
|
|
10
|
-
label: z.string().nullable().optional(),
|
|
11
|
-
active: pgBoolean.nullable().optional(),
|
|
12
|
-
status: z.string().nullable().optional(),
|
|
13
|
-
created_at: z.union([z.string(), z.date().transform((v) => v.toISOString())]).optional(),
|
|
14
|
-
})
|
|
15
|
-
.passthrough();
|
|
16
|
-
export class PricingRepository {
|
|
17
|
-
callproc;
|
|
18
|
-
constructor(callproc) {
|
|
19
|
-
this.callproc = callproc;
|
|
20
|
-
}
|
|
21
|
-
parseRevision(row, context) {
|
|
22
|
-
return safeParse(ActivePricingRowSchema, {
|
|
23
|
-
...row,
|
|
24
|
-
config: row.source_document,
|
|
25
|
-
version: row.revision_no,
|
|
26
|
-
active: row.status === "active",
|
|
27
|
-
}, context);
|
|
28
|
-
}
|
|
29
|
-
async getActivePricing() {
|
|
30
|
-
const rows = await this.callproc("active_catalog_revision", []);
|
|
31
|
-
if (!rows?.length)
|
|
32
|
-
return null;
|
|
33
|
-
const row = rows[0];
|
|
34
|
-
return this.parseRevision(row, "PricingRepository.getActivePricing");
|
|
35
|
-
}
|
|
36
|
-
async setActivePricing(config, label, rollout) {
|
|
37
|
-
return this.publishPricing(config, label, true, rollout);
|
|
38
|
-
}
|
|
39
|
-
async publishPricing(config, label, activate = false, rollout = { plans: {} }) {
|
|
40
|
-
const published = (await this.callproc("publish_and_activate_catalog", [
|
|
41
|
-
1,
|
|
42
|
-
JSON.parse(config),
|
|
43
|
-
label,
|
|
44
|
-
activate,
|
|
45
|
-
rollout,
|
|
46
|
-
]))[0];
|
|
47
|
-
if (published?.revision_no == null) {
|
|
48
|
-
return safeParse(ActivePricingRowSchema, {}, "PricingRepository.publishPricing");
|
|
49
|
-
}
|
|
50
|
-
const revision = await this.getBursarConfig(Number(published.revision_no));
|
|
51
|
-
return (revision ??
|
|
52
|
-
safeParse(ActivePricingRowSchema, {
|
|
53
|
-
id: published.revision_id,
|
|
54
|
-
version: published.revision_no,
|
|
55
|
-
status: published.status,
|
|
56
|
-
active: published.status === "active",
|
|
57
|
-
}, "PricingRepository.publishPricing"));
|
|
58
|
-
}
|
|
59
|
-
async getPricingHistory() {
|
|
60
|
-
const rows = await this.callproc("list_catalog_revisions", [500]);
|
|
61
|
-
return (rows ?? []).map((row) => this.parseRevision(row, "PricingRepository.getPricingHistory"));
|
|
62
|
-
}
|
|
63
|
-
async getBursarConfig(version) {
|
|
64
|
-
const rows = await this.callproc("catalog_revision_by_number", [version]);
|
|
65
|
-
if (!rows?.length)
|
|
66
|
-
return null;
|
|
67
|
-
return this.parseRevision(rows[0], "PricingRepository.getBursarConfig");
|
|
68
|
-
}
|
|
69
|
-
async activatePricing(version, rollout) {
|
|
70
|
-
const rows = await this.callproc("activate_catalog_revision", [version, rollout]);
|
|
71
|
-
if (!rows?.length)
|
|
72
|
-
throw new Error(`Catalog revision ${version} was not found`);
|
|
73
|
-
return this.parseRevision(rows[0], "PricingRepository.activatePricing");
|
|
74
|
-
}
|
|
75
|
-
}
|
|
76
|
-
//# sourceMappingURL=pricing.js.map
|