@zonastery/bursar 2.0.0 → 2.0.2
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 +21 -14
- package/dist/billing/auto-recharge-service.d.ts.map +1 -1
- package/dist/billing/auto-recharge-service.js +6 -4
- package/dist/billing/auto-recharge-service.js.map +1 -1
- package/dist/billing/billing-store.d.ts +3 -0
- package/dist/billing/billing-store.d.ts.map +1 -1
- package/dist/billing/billing-store.js +2 -0
- package/dist/billing/billing-store.js.map +1 -1
- package/dist/billing/event-handlers.d.ts +2 -3
- package/dist/billing/event-handlers.d.ts.map +1 -1
- package/dist/billing/event-handlers.js +38 -49
- package/dist/billing/event-handlers.js.map +1 -1
- package/dist/billing/event-processor.js +4 -4
- package/dist/billing/event-processor.js.map +1 -1
- package/dist/billing/financial-event-handlers.d.ts +2 -2
- package/dist/billing/financial-event-handlers.d.ts.map +1 -1
- package/dist/billing/financial-event-handlers.js +7 -7
- package/dist/billing/financial-event-handlers.js.map +1 -1
- package/dist/billing/postgres/store.d.ts +5 -1
- package/dist/billing/postgres/store.d.ts.map +1 -1
- package/dist/billing/postgres/store.js +5 -0
- package/dist/billing/postgres/store.js.map +1 -1
- package/dist/billing/service-types.d.ts +2 -15
- 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.map +1 -1
- package/dist/billing/types/auto-recharge.js.map +1 -1
- package/dist/billing/types/events.d.ts +3 -2
- package/dist/billing/types/events.d.ts.map +1 -1
- package/dist/billing/types/events.js +2 -2
- package/dist/billing/types/events.js.map +1 -1
- package/dist/billing/types/subscriptions.d.ts.map +1 -1
- package/dist/billing/types/subscriptions.js.map +1 -1
- package/dist/bursar.d.ts +21 -11
- package/dist/bursar.d.ts.map +1 -1
- package/dist/bursar.js +40 -4
- package/dist/bursar.js.map +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/index.d.ts +0 -1
- package/dist/commerce/index.d.ts.map +1 -1
- package/dist/commerce/index.js +0 -1
- package/dist/commerce/index.js.map +1 -1
- package/dist/commerce/service.d.ts.map +1 -1
- package/dist/commerce/service.js +99 -59
- package/dist/commerce/service.js.map +1 -1
- package/dist/commerce/types.d.ts +8 -4
- package/dist/commerce/types.d.ts.map +1 -1
- package/dist/commerce/types.js.map +1 -1
- package/dist/config/parse-credits.d.ts.map +1 -1
- package/dist/config/parse-credits.js +0 -6
- package/dist/config/parse-credits.js.map +1 -1
- package/dist/config/types.d.ts +0 -5
- package/dist/config/types.d.ts.map +1 -1
- package/dist/config/types.js.map +1 -1
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +7 -0
- package/dist/config.js.map +1 -1
- package/dist/credits/amount.d.ts +8 -0
- package/dist/credits/amount.d.ts.map +1 -0
- package/dist/credits/amount.js +32 -0
- package/dist/credits/amount.js.map +1 -0
- package/dist/credits/catalog-runtime.d.ts +4 -6
- package/dist/credits/catalog-runtime.d.ts.map +1 -1
- package/dist/credits/catalog-runtime.js +3 -12
- package/dist/credits/catalog-runtime.js.map +1 -1
- package/dist/credits/lease-workflow.d.ts +1 -1
- package/dist/credits/lease-workflow.d.ts.map +1 -1
- package/dist/credits/lease-workflow.js +23 -20
- package/dist/credits/lease-workflow.js.map +1 -1
- package/dist/credits/low-balance-monitor.d.ts.map +1 -1
- package/dist/credits/low-balance-monitor.js +2 -3
- package/dist/credits/low-balance-monitor.js.map +1 -1
- package/dist/credits/postgres/repositories/balance.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/balance.js.map +1 -1
- package/dist/credits/postgres/store.d.ts +15 -11
- package/dist/credits/postgres/store.d.ts.map +1 -1
- package/dist/credits/postgres/store.js +24 -15
- package/dist/credits/postgres/store.js.map +1 -1
- package/dist/credits/service-types.d.ts +17 -15
- 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 +16 -17
- package/dist/credits/service.d.ts.map +1 -1
- package/dist/credits/service.js +61 -33
- package/dist/credits/service.js.map +1 -1
- package/dist/credits/store.d.ts +16 -22
- package/dist/credits/store.d.ts.map +1 -1
- package/dist/credits/store.js +3 -1
- package/dist/credits/store.js.map +1 -1
- package/dist/credits/types/account.d.ts +1 -1
- package/dist/credits/types/account.d.ts.map +1 -1
- package/dist/credits/types/account.js.map +1 -1
- package/dist/credits/types/grants.d.ts.map +1 -1
- package/dist/credits/types/grants.js.map +1 -1
- package/dist/expr/ast.d.ts.map +1 -1
- package/dist/expr/ast.js.map +1 -1
- package/dist/expr/parser.d.ts +1 -0
- package/dist/expr/parser.d.ts.map +1 -1
- package/dist/expr/parser.js +15 -3
- package/dist/expr/parser.js.map +1 -1
- package/dist/generated/pricing-config.schema.json +31 -29
- package/dist/generated/pricing-config.types.d.ts +6 -18
- 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 +4 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/load-config-file.d.ts +2 -3
- package/dist/load-config-file.d.ts.map +1 -1
- package/dist/load-config-file.js +14 -29
- package/dist/load-config-file.js.map +1 -1
- package/dist/providers/_shared.js +1 -1
- package/dist/providers/_shared.js.map +1 -1
- package/dist/providers/dodo/client-contract.d.ts +3 -1
- 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 +1 -1
- package/dist/providers/dodo/event-mapper.d.ts.map +1 -1
- package/dist/providers/dodo/event-mapper.js +5 -13
- package/dist/providers/dodo/event-mapper.js.map +1 -1
- package/dist/providers/dodo/provider.d.ts +4 -6
- package/dist/providers/dodo/provider.d.ts.map +1 -1
- package/dist/providers/dodo/provider.js +22 -71
- package/dist/providers/dodo/provider.js.map +1 -1
- package/dist/providers/dodo/webhook-bridge.d.ts +1 -2
- package/dist/providers/dodo/webhook-bridge.d.ts.map +1 -1
- package/dist/providers/dodo/webhook-bridge.js +0 -1
- package/dist/providers/dodo/webhook-bridge.js.map +1 -1
- package/dist/providers/environment.d.ts +6 -0
- package/dist/providers/environment.d.ts.map +1 -0
- package/dist/providers/environment.js +10 -0
- package/dist/providers/environment.js.map +1 -0
- package/dist/providers/index.d.ts +3 -7
- package/dist/providers/index.d.ts.map +1 -1
- package/dist/providers/index.js +1 -5
- package/dist/providers/index.js.map +1 -1
- package/dist/providers/mock/provider.d.ts +6 -8
- package/dist/providers/mock/provider.d.ts.map +1 -1
- package/dist/providers/mock/provider.js +18 -50
- package/dist/providers/mock/provider.js.map +1 -1
- package/dist/providers/stripe/event-mapper.js +11 -11
- package/dist/providers/stripe/event-mapper.js.map +1 -1
- package/dist/providers/stripe/provider.d.ts +3 -3
- package/dist/providers/stripe/provider.d.ts.map +1 -1
- package/dist/providers/stripe/provider.js +37 -24
- package/dist/providers/stripe/provider.js.map +1 -1
- package/dist/providers/types.d.ts +9 -19
- package/dist/providers/types.d.ts.map +1 -1
- package/dist/providers/types.js.map +1 -1
- package/dist/shared/idempotency.d.ts +9 -0
- package/dist/shared/idempotency.d.ts.map +1 -0
- package/dist/shared/idempotency.js +34 -0
- package/dist/shared/idempotency.js.map +1 -0
- package/dist/shared/postgres-client.d.ts +4 -0
- package/dist/shared/postgres-client.d.ts.map +1 -1
- package/dist/shared/postgres-client.js +6 -2
- package/dist/shared/postgres-client.js.map +1 -1
- package/dist/shared/postgres-errors.d.ts.map +1 -1
- package/dist/shared/postgres-errors.js.map +1 -1
- package/dist/storage/outbox-worker.d.ts.map +1 -1
- package/dist/storage/outbox-worker.js +22 -21
- package/dist/storage/outbox-worker.js.map +1 -1
- package/dist/storage/postgres-repository.d.ts.map +1 -1
- package/dist/storage/postgres-repository.js +67 -46
- package/dist/storage/postgres-repository.js.map +1 -1
- package/dist/storage/runtime.d.ts +11 -7
- package/dist/storage/runtime.d.ts.map +1 -1
- package/dist/storage/runtime.js +52 -8
- package/dist/storage/runtime.js.map +1 -1
- package/package.json +52 -36
|
@@ -1,11 +1,8 @@
|
|
|
1
|
-
import type Decimal from "decimal.js";
|
|
2
1
|
import type { Logger } from "../shared/logger.js";
|
|
3
|
-
import type {
|
|
2
|
+
import type { SetUserPlanResult, UnsetUserPlanResult } from "../credits/types/index.js";
|
|
4
3
|
import type { BillingEventHandler, BillingEventType } from "./types/index.js";
|
|
5
|
-
export type ResolveUser = (provider: string, providerCustomerId: string | null, email: string | null) => string | null;
|
|
6
4
|
export interface BillingServiceOptions {
|
|
7
5
|
provisioning?: BillingProvisioningPort | null;
|
|
8
|
-
resolveUser?: ResolveUser | null;
|
|
9
6
|
eventHandlers?: Partial<Record<BillingEventType, BillingEventHandler>>;
|
|
10
7
|
autoSelectEntitlementSource?: boolean;
|
|
11
8
|
/** Access grace after a failed subscription payment. Defaults to seven days. */
|
|
@@ -19,20 +16,10 @@ export interface BillingServiceOptions {
|
|
|
19
16
|
* provisioning. Billing does not depend on the full credit service.
|
|
20
17
|
*/
|
|
21
18
|
export interface BillingProvisioningPort {
|
|
22
|
-
getUserPlan
|
|
19
|
+
getUserPlan(userId: string): Promise<{
|
|
23
20
|
planAssignedAt?: Date | string | null;
|
|
24
21
|
} | null>;
|
|
25
22
|
setUserPlan(userId: string, planKey: string, planAssignedAt?: Date | null): Promise<SetUserPlanResult>;
|
|
26
23
|
unsetUserPlan(userId: string): Promise<UnsetUserPlanResult>;
|
|
27
|
-
addCredits(userId: string, amount: Decimal | number, options?: {
|
|
28
|
-
type?: string;
|
|
29
|
-
bucket?: string | null;
|
|
30
|
-
idempotencyKey?: string | null;
|
|
31
|
-
}): Promise<AddCreditsResult>;
|
|
32
|
-
deductCredits(userId: string, amount: Decimal | number, options?: {
|
|
33
|
-
entryType?: string;
|
|
34
|
-
bucket?: string | null;
|
|
35
|
-
}): Promise<AddCreditsResult>;
|
|
36
|
-
revokeCreditsByEntryType(userId: string, entryType: string): Promise<RevokeCreditsResult>;
|
|
37
24
|
}
|
|
38
25
|
//# sourceMappingURL=service-types.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"service-types.d.ts","sourceRoot":"","sources":["../../src/billing/service-types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,
|
|
1
|
+
{"version":3,"file":"service-types.d.ts","sourceRoot":"","sources":["../../src/billing/service-types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAClD,OAAO,KAAK,EAAE,iBAAiB,EAAE,mBAAmB,EAAE,MAAM,2BAA2B,CAAC;AACxF,OAAO,KAAK,EAAE,mBAAmB,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AAE9E,MAAM,WAAW,qBAAqB;IACpC,YAAY,CAAC,EAAE,uBAAuB,GAAG,IAAI,CAAC;IAC9C,aAAa,CAAC,EAAE,OAAO,CAAC,MAAM,CAAC,gBAAgB,EAAE,mBAAmB,CAAC,CAAC,CAAC;IACvE,2BAA2B,CAAC,EAAE,OAAO,CAAC;IACtC,gFAAgF;IAChF,oBAAoB,CAAC,EAAE,MAAM,CAAC;IAC9B,qEAAqE;IACrE,eAAe,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAChC,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CACxB;AAED;;;GAGG;AACH,MAAM,WAAW,uBAAuB;IACtC,WAAW,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC;QAAE,cAAc,CAAC,EAAE,IAAI,GAAG,MAAM,GAAG,IAAI,CAAA;KAAE,GAAG,IAAI,CAAC,CAAC;IACvF,WAAW,CACT,MAAM,EAAE,MAAM,EACd,OAAO,EAAE,MAAM,EACf,cAAc,CAAC,EAAE,IAAI,GAAG,IAAI,GAC3B,OAAO,CAAC,iBAAiB,CAAC,CAAC;IAC9B,aAAa,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,mBAAmB,CAAC,CAAC;CAC7D"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"service-types.js","sourceRoot":"","sources":["../../src/billing/service-types.ts"],"names":[],"mappings":"","sourcesContent":["import type
|
|
1
|
+
{"version":3,"file":"service-types.js","sourceRoot":"","sources":["../../src/billing/service-types.ts"],"names":[],"mappings":"","sourcesContent":["import type { Logger } from \"../shared/logger.js\";\nimport type { SetUserPlanResult, UnsetUserPlanResult } from \"../credits/types/index.js\";\nimport type { BillingEventHandler, BillingEventType } from \"./types/index.js\";\n\nexport interface BillingServiceOptions {\n provisioning?: BillingProvisioningPort | null;\n eventHandlers?: Partial<Record<BillingEventType, BillingEventHandler>>;\n autoSelectEntitlementSource?: boolean;\n /** Access grace after a failed subscription payment. Defaults to seven days. */\n pastDueGracePeriodMs?: number;\n /** Plan assigned when a paid subscription reaches terminal state. */\n terminalPlanKey?: string | null;\n logger?: Logger | null;\n}\n\n/**\n * The narrow credit capability billing may request during subscription\n * provisioning. Billing does not depend on the full credit service.\n */\nexport interface BillingProvisioningPort {\n getUserPlan(userId: string): Promise<{ planAssignedAt?: Date | string | null } | null>;\n setUserPlan(\n userId: string,\n planKey: string,\n planAssignedAt?: Date | null,\n ): Promise<SetUserPlanResult>;\n unsetUserPlan(userId: string): Promise<UnsetUserPlanResult>;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auto-recharge.d.ts","sourceRoot":"","sources":["../../../src/billing/types/auto-recharge.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,OAAO,MAAM,YAAY,CAAC;AAEtC,eAAO,MAAM,oBAAoB,2CAA4C,CAAC;AAC9E,MAAM,MAAM,wBAAwB,GAAG,CAAC,OAAO,oBAAoB,CAAC,CAAC,MAAM,CAAC,CAAC;AAE7E,MAAM,MAAM,+BAA+B,
|
|
1
|
+
{"version":3,"file":"auto-recharge.d.ts","sourceRoot":"","sources":["../../../src/billing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AM,CAAC;IACpB,SAAS,EAAE,MAAM,CAAC;IAClB,iBAAiB,EAAE,MAAM,GAAG,IAAI,CAAC;IACjC,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,cAAc,EAAE,MAAM,GAAG,IAAI,CAAC;IAC9B,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAClC,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,WAAW,yBAAyB;IACxC,OAAO,EAAE,OAAO,CAAC;IACjB,KAAK,EAAE,wBAAwB,CAAC;IAChC,gBAAgB,EAAE,OAAO,CAAC;IAC1B,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE,MAAM,CAAC;IACjB,YAAY,EAAE,MAAM,CAAC;IACrB,WAAW,EAAE,MAAM,CAAC;IACpB,SAAS,EAAE,MAAM,CAAC;IAClB,iBAAiB,EAAE,MAAM,CAAC;IAC1B,eAAe,EAAE,MAAM,GAAG,IAAI,CAAC;IAC/B,kBAAkB,EAAE,MAAM,GAAG,IAAI,CAAC;IAClC,kBAAkB,EAAE,MAAM,GAAG,IAAI,CAAC;IAClC,eAAe,EAAE,MAAM,GAAG,IAAI,CAAC;IAC/B,gBAAgB,EAAE,MAAM,GAAG,IAAI,CAAC;IAChC,gBAAgB,EAAE,MAAM,GAAG,IAAI,CAAC;IAChC,aAAa,EAAE,MAAM,GAAG,IAAI,CAAC;CAC9B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auto-recharge.js","sourceRoot":"","sources":["../../../src/billing/types/auto-recharge.ts"],"names":[],"mappings":"AAEA,MAAM,CAAC,MAAM,oBAAoB,GAAG,CAAC,UAAU,EAAE,QAAQ,EAAE,QAAQ,CAAU,CAAC","sourcesContent":["import type Decimal from \"decimal.js\";\n\nexport const AUTO_RECHARGE_STATES = [\"disabled\", \"active\", \"paused\"] as const;\nexport type BillingAutoRechargeState = (typeof AUTO_RECHARGE_STATES)[number];\n\nexport type BillingAutoRechargeAttemptState =\n
|
|
1
|
+
{"version":3,"file":"auto-recharge.js","sourceRoot":"","sources":["../../../src/billing/types/auto-recharge.ts"],"names":[],"mappings":"AAEA,MAAM,CAAC,MAAM,oBAAoB,GAAG,CAAC,UAAU,EAAE,QAAQ,EAAE,QAAQ,CAAU,CAAC","sourcesContent":["import type Decimal from \"decimal.js\";\n\nexport const AUTO_RECHARGE_STATES = [\"disabled\", \"active\", \"paused\"] as const;\nexport type BillingAutoRechargeState = (typeof AUTO_RECHARGE_STATES)[number];\n\nexport type BillingAutoRechargeAttemptState =\n \"claimed\" | \"submitted\" | \"processing\" | \"unknown\" | \"succeeded\" | \"failed\" | \"action_required\";\n\nexport interface BillingAutoRechargeProfile {\n userId: string;\n enabled: boolean;\n state: BillingAutoRechargeState;\n armed?: boolean;\n provider: string | null;\n topupId: string | null;\n quantity: number;\n threshold: Decimal;\n maxChargesPerWindow: number | null;\n windowUnit: \"second\" | \"minute\" | \"hour\" | \"day\" | \"week\" | \"month\" | \"year\";\n windowCount: number;\n windowAnchor: \"calendar\" | \"rolling\";\n windowTimezone: string;\n updatedAt?: string | null;\n}\n\nexport interface BillingAutoRechargeAttempt {\n id: string;\n userId: string;\n provider: string;\n idempotencyKey: string;\n providerAttemptId: string | null;\n topupId: string;\n quantity: number;\n state: BillingAutoRechargeAttemptState;\n windowStart: string;\n windowEnd: string;\n quotedAmountMinor: number | null;\n currency: string | null;\n failureCode: string | null;\n failureMessage: string | null;\n metadata: Record<string, unknown>;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface BillingAutoRechargeStatus {\n enabled: boolean;\n state: BillingAutoRechargeState;\n thresholdCredits: Decimal;\n topupKey: string;\n quantity: number;\n maxRecharges: number;\n windowStart: string;\n windowEnd: string;\n rechargesInWindow: number;\n paymentMethodId: string | null;\n paymentMethodLast4: string | null;\n paymentMethodBrand: string | null;\n suspendedReason: string | null;\n pendingAttemptId: string | null;\n quoteAmountMinor: number | null;\n quoteCurrency: string | null;\n}\n"]}
|
|
@@ -43,7 +43,8 @@ export interface BillingEvent {
|
|
|
43
43
|
eventId: string;
|
|
44
44
|
eventType: BillingEventType;
|
|
45
45
|
occurredAt: string;
|
|
46
|
-
|
|
46
|
+
/** Financial subject affected by this provider event. */
|
|
47
|
+
accountId?: string | null;
|
|
47
48
|
customer?: BillingCustomerInfo | null;
|
|
48
49
|
subscription?: BillingSubscriptionInfo | null;
|
|
49
50
|
invoice?: BillingInvoiceInfo | null;
|
|
@@ -56,7 +57,7 @@ export interface BillingEvent {
|
|
|
56
57
|
}
|
|
57
58
|
/** Validate an event at the public ingestion boundary before claiming it. */
|
|
58
59
|
export declare function assertBillingEvent(value: unknown): asserts value is BillingEvent;
|
|
59
|
-
export type BillingEventHandler = (event: BillingEvent,
|
|
60
|
+
export type BillingEventHandler = (event: BillingEvent, accountId: string) => Promise<void>;
|
|
60
61
|
export interface BillingEventResult {
|
|
61
62
|
handled: boolean;
|
|
62
63
|
action?: string | null;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"events.d.ts","sourceRoot":"","sources":["../../../src/billing/types/events.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,mBAAmB,EACnB,kBAAkB,EAClB,kBAAkB,EAClB,kBAAkB,EAClB,iBAAiB,EAClB,MAAM,gBAAgB,CAAC;AACxB,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,oBAAoB,CAAC;AAElE,eAAO,MAAM,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAoCnB,CAAC;AAEX,MAAM,MAAM,gBAAgB,GAAG,CAAC,OAAO,gBAAgB,CAAC,CAAC,MAAM,OAAO,gBAAgB,CAAC,CAAC;AAExF,MAAM,WAAW,YAAY;IAC3B,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC;IAChB,S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E,OAAO,GAAG,OAAO,CAAC,KAAK,IAAI,YAAY,CAwLhF;AAED,MAAM,MAAM,mBAAmB,GAAG,CAAC,KAAK,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;AAE5F,MAAM,WAAW,kBAAkB;IACjC,OAAO,EAAE,OAAO,CAAC;IACjB,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACvB,KAAK,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACtB,cAAc,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAChC;AAED,MAAM,MAAM,iBAAiB,GACzB;IAAE,MAAM,EAAE,SAAS,CAAC;IAAC,UAAU,EAAE,MAAM,CAAC;IAAC,cAAc,EAAE,MAAM,CAAA;CAAE,GACjE;IAAE,MAAM,EAAE,WAAW,CAAA;CAAE,GACvB;IAAE,MAAM,EAAE,MAAM,CAAA;CAAE,GAClB;IAAE,MAAM,EAAE,OAAO,CAAA;CAAE,CAAC"}
|
|
@@ -129,7 +129,7 @@ export function assertBillingEvent(value) {
|
|
|
129
129
|
"eventId",
|
|
130
130
|
"eventType",
|
|
131
131
|
"occurredAt",
|
|
132
|
-
"
|
|
132
|
+
"accountId",
|
|
133
133
|
"customer",
|
|
134
134
|
"subscription",
|
|
135
135
|
"invoice",
|
|
@@ -143,7 +143,7 @@ export function assertBillingEvent(value) {
|
|
|
143
143
|
const event = record;
|
|
144
144
|
requireNonEmptyString(event.provider, "billing event provider");
|
|
145
145
|
requireNonEmptyString(event.eventId, "billing event id");
|
|
146
|
-
requireOptionalNonEmptyString(event.
|
|
146
|
+
requireOptionalNonEmptyString(event.accountId, "billing event accountId");
|
|
147
147
|
requireOptionalNonEmptyString(event.billingEventId, "billing event billingEventId");
|
|
148
148
|
if (event.metadata !== null && event.metadata !== undefined) {
|
|
149
149
|
requireObject(event.metadata, "billing event metadata");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"events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U,CAAC,SAAS,CAAC,EAAE,CAAC;QAC3C,MAAM,IAAI,SAAS,CAAC,GAAG,SAAS,uBAAuB,CAAC,CAAC;IAC3D,CAAC;IACD,IAAI,KAAK,CAAC,OAAO,KAAK,IAAI,IAAI,KAAK,CAAC,OAAO,KAAK,SAAS,EAAE,CAAC;QAC1D,MAAM,OAAO,GAAG,aAAa,CAAC,KAAK,CAAC,OAAO,EAAE,GAAG,SAAS,UAAU,CAAC,CAAC;QACrE,iBAAiB,CACf,OAAO,EACP,CAAC,mBAAmB,EAAE,mBAAmB,EAAE,QAAQ,EAAE,QAAQ,CAAC,EAC9D,GAAG,SAAS,UAAU,CACvB,CAAC;QACF,qBAAqB,CAAC,OAAO,CAAC,iBAAiB,EAAE,GAAG,SAAS,4BAA4B,CAAC,CAAC;QAC3F,qBAAqB,CAAC,OAAO,CAAC,iBAAiB,EAAE,GAAG,SAAS,4BAA4B,CAAC,CAAC;QAC3F,YAAY,CAAC,OAAO,CAAC,MAAM,EAAE,gBAAgB,EAAE,GAAG,SAAS,iBAAiB,CAAC,CAAC;QAC9E,qBAAqB,CAAC,OAAO,CAAC,MAAM,EAAE,GAAG,SAAS,iBAAiB,CAAC,CAAC;IACvE,CAAC;SAAM,IAAI,SAAS,CAAC,UAAU,CAAC,UAAU,CAAC,EAAE,CAAC;QAC5C,MAAM,IAAI,SAAS,CAAC,GAAG,SAAS,wBAAwB,CAAC,CAAC;IAC5D,CAAC;AACH,CAAC","sourcesContent":["import type {\n BillingCustomerInfo,\n BillingDisputeInfo,\n BillingInvoiceInfo,\n BillingPaymentInfo,\n BillingRefundInfo,\n} from \"./documents.js\";\nimport type { BillingSubscriptionInfo } from \"./subscriptions.js\";\n\nexport const BillingEventType = {\n CUSTOMER_CREATED: \"customer.created\",\n CUSTOMER_UPDATED: \"customer.updated\",\n CUSTOMER_DELETED: \"customer.deleted\",\n CHECKOUT_COMPLETED: \"checkout.completed\",\n CHECKOUT_EXPIRED: \"checkout.expired\",\n SUBSCRIPTION_CREATED: \"subscription.created\",\n SUBSCRIPTION_UPDATED: \"subscription.updated\",\n SUBSCRIPTION_ACTIVATED: \"subscription.activated\",\n SUBSCRIPTION_RENEWED: \"subscription.renewed\",\n SUBSCRIPTION_PLAN_CHANGED: \"subscription.plan_changed\",\n SUBSCRIPTION_CANCELLATION_SCHEDULED: \"subscription.cancellation_scheduled\",\n SUBSCRIPTION_CANCELLATION_UNSCHEDULED: \"subscription.cancellation_unscheduled\",\n SUBSCRIPTION_CANCELED: \"subscription.canceled\",\n SUBSCRIPTION_EXPIRED: \"subscription.expired\",\n SUBSCRIPTION_PAUSED: \"subscription.paused\",\n SUBSCRIPTION_RESUMED: \"subscription.resumed\",\n SUBSCRIPTION_TRIAL_WILL_END: \"subscription.trial_will_end\",\n INVOICE_CREATED: \"invoice.created\",\n INVOICE_FINALIZED: \"invoice.finalized\",\n INVOICE_FINALIZATION_FAILED: \"invoice.finalization_failed\",\n INVOICE_UPCOMING: \"invoice.upcoming\",\n INVOICE_PAID: \"invoice.paid\",\n INVOICE_PAYMENT_FAILED: \"invoice.payment_failed\",\n INVOICE_PAYMENT_ACTION_REQUIRED: \"invoice.payment_action_required\",\n INVOICE_VOIDED: \"invoice.voided\",\n PAYMENT_SUCCEEDED: \"payment.succeeded\",\n PAYMENT_FAILED: \"payment.failed\",\n REFUND_CREATED: \"refund.created\",\n REFUND_UPDATED: \"refund.updated\",\n REFUND_FAILED: \"refund.failed\",\n DISPUTE_CREATED: \"dispute.created\",\n DISPUTE_CLOSED: \"dispute.closed\",\n PAYMENT_METHOD_ATTACHED: \"payment_method.attached\",\n PAYMENT_METHOD_UPDATED: \"payment_method.updated\",\n PAYMENT_METHOD_DETACHED: \"payment_method.detached\",\n} as const;\n\nexport type BillingEventType = (typeof BillingEventType)[keyof typeof BillingEventType];\n\nexport interface BillingEvent {\n provider: string;\n eventId: string;\n eventType: BillingEventType;\n occurredAt: string;\n userId?: string | null;\n customer?: BillingCustomerInfo | null;\n subscription?: BillingSubscriptionInfo | null;\n invoice?: BillingInvoiceInfo | null;\n payment?: BillingPaymentInfo | null;\n refund?: BillingRefundInfo | null;\n dispute?: BillingDisputeInfo | null;\n metadata?: Record<string, unknown> | null;\n raw?: unknown;\n billingEventId?: string;\n}\n\nconst BILLING_EVENT_TYPES = new Set<string>(Object.values(BillingEventType));\nconst SUBSCRIPTION_STATUSES = new Set([\n \"incomplete\",\n \"incomplete_expired\",\n \"trialing\",\n \"active\",\n \"past_due\",\n \"canceled\",\n \"unpaid\",\n \"paused\",\n \"expired\",\n]);\nconst BILLING_INTERVALS = new Set([\"day\", \"week\", \"month\", \"year\"]);\nconst INVOICE_STATUSES = new Set([\"draft\", \"open\", \"paid\", \"void\", \"uncollectible\"]);\nconst PAYMENT_PURPOSES = new Set([\"subscription\", \"credit_topup\"]);\nconst PAYMENT_STATUSES = new Set([\"pending\", \"succeeded\", \"failed\", \"canceled\"]);\nconst DISPUTE_STATUSES = new Set([\"needs_response\", \"under_review\", \"won\", \"lost\", \"closed\"]);\nconst ISO_INSTANT_WITH_OFFSET = /(?:Z|[+-]\\d{2}:\\d{2})$/;\n\nfunction requireObject(value: unknown, field: string): Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new TypeError(`${field} must be an object`);\n }\n return value as Record<string, unknown>;\n}\n\nfunction rejectUnknownKeys(\n value: Record<string, unknown>,\n allowed: readonly string[],\n field: string,\n) {\n const known = new Set(allowed);\n const unknown = Object.keys(value).filter((key) => !known.has(key));\n if (unknown.length > 0) {\n throw new TypeError(\n `${field} contains unsupported field${unknown.length === 1 ? \"\" : \"s\"}: ${unknown.join(\", \")}`,\n );\n }\n}\n\nfunction requireNonEmptyString(value: unknown, field: string): void {\n if (typeof value !== \"string\" || !value.trim()) {\n throw new TypeError(`${field} must be a non-empty string`);\n }\n}\n\nfunction requireOptionalNonEmptyString(value: unknown, field: string): void {\n if (value !== null && value !== undefined) requireNonEmptyString(value, field);\n}\n\nfunction requireOptionalString(value: unknown, field: string): void {\n if (value !== null && value !== undefined && typeof value !== \"string\") {\n throw new TypeError(`${field} must be a string`);\n }\n}\n\nfunction requireOptionalBoolean(value: unknown, field: string): void {\n if (value !== null && value !== undefined && typeof value !== \"boolean\") {\n throw new TypeError(`${field} must be a boolean`);\n }\n}\n\nfunction requireOneOf(value: unknown, allowed: ReadonlySet<string>, field: string): void {\n if (typeof value !== \"string\" || !allowed.has(value)) {\n throw new TypeError(`${field} has an unsupported value`);\n }\n}\n\nfunction validateProviderRef(value: unknown, field: string): void {\n if (value === null || value === undefined) return;\n const reference = requireObject(value, field);\n const keys = [\"productId\", \"priceId\", \"variantId\", \"lookupKey\"] as const;\n rejectUnknownKeys(reference, keys, field);\n for (const key of keys) requireOptionalNonEmptyString(reference[key], `${field}.${key}`);\n if (!keys.some((key) => reference[key] !== null && reference[key] !== undefined)) {\n throw new TypeError(`${field} must contain a provider identifier`);\n }\n}\n\nfunction requireMinorUnits(value: unknown, field: string, positive = false): void {\n if (!Number.isSafeInteger(value) || (value as number) < (positive ? 1 : 0)) {\n throw new TypeError(\n `${field} must be a ${positive ? \"positive\" : \"non-negative\"} safe integer`,\n );\n }\n}\n\nfunction requireCurrency(value: unknown, field: string): void {\n if (typeof value !== \"string\" || !/^[A-Z]{3}$/.test(value)) {\n throw new TypeError(`${field} must be an uppercase three-letter currency code`);\n }\n}\n\nfunction requireOptionalInstant(value: unknown, field: string): void {\n if (value === null || value === undefined) return;\n if (\n typeof value !== \"string\" ||\n !ISO_INSTANT_WITH_OFFSET.test(value) ||\n Number.isNaN(Date.parse(value))\n ) {\n throw new TypeError(`${field} must be an ISO 8601 instant with an offset`);\n }\n}\n\n/** Validate an event at the public ingestion boundary before claiming it. */\nexport function assertBillingEvent(value: unknown): asserts value is BillingEvent {\n const record = requireObject(value, \"billing event\");\n rejectUnknownKeys(\n record,\n [\n \"provider\",\n \"eventId\",\n \"eventType\",\n \"occurredAt\",\n \"userId\",\n \"customer\",\n \"subscription\",\n \"invoice\",\n \"payment\",\n \"refund\",\n \"dispute\",\n \"metadata\",\n \"raw\",\n \"billingEventId\",\n ],\n \"billing event\",\n );\n const event = record as unknown as BillingEvent;\n requireNonEmptyString(event.provider, \"billing event provider\");\n requireNonEmptyString(event.eventId, \"billing event id\");\n requireOptionalNonEmptyString(event.userId, \"billing event userId\");\n requireOptionalNonEmptyString(event.billingEventId, \"billing event billingEventId\");\n if (event.metadata !== null && event.metadata !== undefined) {\n requireObject(event.metadata, \"billing event metadata\");\n }\n if (!BILLING_EVENT_TYPES.has(event.eventType)) {\n throw new TypeError(`unsupported billing event type: ${String(event.eventType)}`);\n }\n if (\n typeof event.occurredAt !== \"string\" ||\n !ISO_INSTANT_WITH_OFFSET.test(event.occurredAt) ||\n Number.isNaN(Date.parse(event.occurredAt))\n ) {\n throw new TypeError(\"billing event occurredAt must be an ISO 8601 instant with an offset\");\n }\n\n const eventName: string = event.eventType;\n if (event.customer !== null && event.customer !== undefined) {\n const customer = requireObject(event.customer, `${eventName} customer`);\n rejectUnknownKeys(customer, [\"providerCustomerId\", \"email\"], `${eventName} customer`);\n requireOptionalNonEmptyString(\n customer.providerCustomerId,\n `${eventName} customer.providerCustomerId`,\n );\n requireOptionalNonEmptyString(customer.email, `${eventName} customer.email`);\n if (customer.providerCustomerId == null && customer.email == null) {\n throw new TypeError(`${eventName} customer requires providerCustomerId or email`);\n }\n } else if (eventName.startsWith(\"customer.\")) {\n throw new TypeError(`${eventName} requires customer data`);\n }\n if (event.subscription !== null && event.subscription !== undefined) {\n const subscription = requireObject(event.subscription, `${eventName} subscription`);\n rejectUnknownKeys(\n subscription,\n [\n \"providerSubscriptionId\",\n \"status\",\n \"cancelAtPeriodEnd\",\n \"periodStart\",\n \"periodEnd\",\n \"trialEnd\",\n \"cancelAt\",\n \"endedAt\",\n \"refs\",\n \"interval\",\n \"intervalCount\",\n ],\n `${eventName} subscription`,\n );\n requireNonEmptyString(\n subscription.providerSubscriptionId,\n `${eventName} subscription.providerSubscriptionId`,\n );\n if (subscription.status != null) {\n requireOneOf(subscription.status, SUBSCRIPTION_STATUSES, `${eventName} subscription.status`);\n }\n requireOptionalBoolean(\n subscription.cancelAtPeriodEnd,\n `${eventName} subscription.cancelAtPeriodEnd`,\n );\n for (const [field, value] of [\n [\"periodStart\", subscription.periodStart],\n [\"periodEnd\", subscription.periodEnd],\n [\"trialEnd\", subscription.trialEnd],\n [\"cancelAt\", subscription.cancelAt],\n [\"endedAt\", subscription.endedAt],\n ] as const) {\n requireOptionalInstant(value, `${eventName} subscription.${field}`);\n }\n validateProviderRef(subscription.refs, `${eventName} subscription.refs`);\n if (subscription.interval != null) {\n requireOneOf(subscription.interval, BILLING_INTERVALS, `${eventName} subscription.interval`);\n }\n if (\n subscription.intervalCount !== null &&\n subscription.intervalCount !== undefined &&\n (!Number.isSafeInteger(subscription.intervalCount) ||\n (subscription.intervalCount as number) <= 0)\n ) {\n throw new TypeError(\n `${eventName} subscription.intervalCount must be a positive safe integer`,\n );\n }\n } else if (eventName.startsWith(\"subscription.\")) {\n throw new TypeError(`${eventName} requires subscription data`);\n }\n if (event.invoice !== null && event.invoice !== undefined) {\n const invoice = requireObject(event.invoice, `${eventName} invoice`);\n rejectUnknownKeys(\n invoice,\n [\n \"providerInvoiceId\",\n \"status\",\n \"amountPaidMinor\",\n \"amountDueMinor\",\n \"currency\",\n \"periodStart\",\n \"periodEnd\",\n ],\n `${eventName} invoice`,\n );\n requireNonEmptyString(invoice.providerInvoiceId, `${eventName} invoice.providerInvoiceId`);\n requireOneOf(invoice.status, INVOICE_STATUSES, `${eventName} invoice.status`);\n requireMinorUnits(invoice.amountPaidMinor, `${eventName} invoice.amountPaidMinor`);\n requireMinorUnits(invoice.amountDueMinor, `${eventName} invoice.amountDueMinor`);\n requireCurrency(invoice.currency, `${eventName} invoice.currency`);\n requireOptionalInstant(invoice.periodStart, `${eventName} invoice.periodStart`);\n requireOptionalInstant(invoice.periodEnd, `${eventName} invoice.periodEnd`);\n } else if (eventName.startsWith(\"invoice.\")) {\n throw new TypeError(`${eventName} requires invoice data`);\n }\n if (event.payment !== null && event.payment !== undefined) {\n const payment = requireObject(event.payment, `${eventName} payment`);\n rejectUnknownKeys(\n payment,\n [\"providerPaymentId\", \"amountMinor\", \"taxMinor\", \"currency\", \"refs\", \"purpose\", \"status\"],\n `${eventName} payment`,\n );\n requireNonEmptyString(payment.providerPaymentId, `${eventName} payment.providerPaymentId`);\n requireMinorUnits(payment.amountMinor, `${eventName} payment.amountMinor`);\n requireMinorUnits(payment.taxMinor, `${eventName} payment.taxMinor`);\n requireCurrency(payment.currency, `${eventName} payment.currency`);\n validateProviderRef(payment.refs, `${eventName} payment.refs`);\n requireOneOf(payment.purpose, PAYMENT_PURPOSES, `${eventName} payment.purpose`);\n requireOneOf(payment.status, PAYMENT_STATUSES, `${eventName} payment.status`);\n } else if (eventName.startsWith(\"payment.\")) {\n throw new TypeError(`${eventName} requires payment data`);\n }\n if (event.refund !== null && event.refund !== undefined) {\n const refund = requireObject(event.refund, `${eventName} refund`);\n rejectUnknownKeys(\n refund,\n [\"providerRefundId\", \"providerPaymentId\", \"amountMinor\", \"currency\", \"reason\", \"status\"],\n `${eventName} refund`,\n );\n requireNonEmptyString(refund.providerRefundId, `${eventName} refund.providerRefundId`);\n requireNonEmptyString(refund.providerPaymentId, `${eventName} refund.providerPaymentId`);\n requireMinorUnits(refund.amountMinor, `${eventName} refund.amountMinor`, true);\n requireCurrency(refund.currency, `${eventName} refund.currency`);\n requireOptionalString(refund.reason, `${eventName} refund.reason`);\n requireOneOf(refund.status, PAYMENT_STATUSES, `${eventName} refund.status`);\n } else if (eventName.startsWith(\"refund.\")) {\n throw new TypeError(`${eventName} requires refund data`);\n }\n if (event.dispute !== null && event.dispute !== undefined) {\n const dispute = requireObject(event.dispute, `${eventName} dispute`);\n rejectUnknownKeys(\n dispute,\n [\"providerDisputeId\", \"providerPaymentId\", \"status\", \"reason\"],\n `${eventName} dispute`,\n );\n requireNonEmptyString(dispute.providerDisputeId, `${eventName} dispute.providerDisputeId`);\n requireNonEmptyString(dispute.providerPaymentId, `${eventName} dispute.providerPaymentId`);\n requireOneOf(dispute.status, DISPUTE_STATUSES, `${eventName} dispute.status`);\n requireOptionalString(dispute.reason, `${eventName} dispute.reason`);\n } else if (eventName.startsWith(\"dispute.\")) {\n throw new TypeError(`${eventName} requires dispute data`);\n }\n}\n\nexport type BillingEventHandler = (event: BillingEvent, userId: string) => Promise<void>;\n\nexport interface BillingEventResult {\n handled: boolean;\n action?: string | null;\n error?: string | null;\n subscriptionId?: string | null;\n}\n\nexport type BillingEventClaim =\n | { status: \"claimed\"; claimToken: string; billingEventId: string }\n | { status: \"duplicate\" }\n | { status: \"busy\" }\n | { status: \"retry\" };\n"]}
|
|
1
|
+
{"version":3,"file":"events.js","sourceRoot":"","sources":["../../../src/billing/types/events.ts"],"names":[],"mappings":"AASA,MAAM,CAAC,MAAM,gBAAgB,GAAG;IAC9B,gBAAgB,EAAE,kBAAkB;IACpC,gBAAgB,EAAE,kBAAkB;IACpC,gBAAgB,EAAE,kBAAkB;IACpC,kBAAkB,EAAE,oBAAoB;IACxC,gBAAgB,EAAE,kBAAkB;IACpC,oBAAoB,EAAE,sBAAsB;IAC5C,oBAAoB,EAAE,sBAAsB;IAC5C,sBAAsB,EAAE,wBAAwB;IAChD,oBAAoB,EAAE,sBAAsB;IAC5C,yBAAyB,EAAE,2BAA2B;IACtD,mCAAmC,EAAE,qCAAqC;IAC1E,qCAAqC,EAAE,uCAAuC;IAC9E,qBAAqB,EAAE,uBAAuB;IAC9C,oBAAoB,EAAE,sBAAsB;IAC5C,mBAAmB,EAAE,qBAAqB;IAC1C,oBAAoB,EAAE,sBAAsB;IAC5C,2BAA2B,EAAE,6BAA6B;IAC1D,eAAe,EAAE,iBAAiB;IAClC,iBAAiB,EAAE,mBAAmB;IACtC,2BAA2B,EAAE,6BAA6B;IAC1D,gBAAgB,EAAE,kBAAkB;IACpC,YAAY,EAAE,cAAc;IAC5B,sBAAsB,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ACvE,CAAC;SAAM,IAAI,SAAS,CAAC,UAAU,CAAC,UAAU,CAAC,EAAE,CAAC;QAC5C,MAAM,IAAI,SAAS,CAAC,GAAG,SAAS,wBAAwB,CAAC,CAAC;IAC5D,CAAC;AACH,CAAC","sourcesContent":["import type {\n BillingCustomerInfo,\n BillingDisputeInfo,\n BillingInvoiceInfo,\n BillingPaymentInfo,\n BillingRefundInfo,\n} from \"./documents.js\";\nimport type { BillingSubscriptionInfo } from \"./subscriptions.js\";\n\nexport const BillingEventType = {\n CUSTOMER_CREATED: \"customer.created\",\n CUSTOMER_UPDATED: \"customer.updated\",\n CUSTOMER_DELETED: \"customer.deleted\",\n CHECKOUT_COMPLETED: \"checkout.completed\",\n CHECKOUT_EXPIRED: \"checkout.expired\",\n SUBSCRIPTION_CREATED: \"subscription.created\",\n SUBSCRIPTION_UPDATED: \"subscription.updated\",\n SUBSCRIPTION_ACTIVATED: \"subscription.activated\",\n SUBSCRIPTION_RENEWED: \"subscription.renewed\",\n SUBSCRIPTION_PLAN_CHANGED: \"subscription.plan_changed\",\n SUBSCRIPTION_CANCELLATION_SCHEDULED: \"subscription.cancellation_scheduled\",\n SUBSCRIPTION_CANCELLATION_UNSCHEDULED: \"subscription.cancellation_unscheduled\",\n SUBSCRIPTION_CANCELED: \"subscription.canceled\",\n SUBSCRIPTION_EXPIRED: \"subscription.expired\",\n SUBSCRIPTION_PAUSED: \"subscription.paused\",\n SUBSCRIPTION_RESUMED: \"subscription.resumed\",\n SUBSCRIPTION_TRIAL_WILL_END: \"subscription.trial_will_end\",\n INVOICE_CREATED: \"invoice.created\",\n INVOICE_FINALIZED: \"invoice.finalized\",\n INVOICE_FINALIZATION_FAILED: \"invoice.finalization_failed\",\n INVOICE_UPCOMING: \"invoice.upcoming\",\n INVOICE_PAID: \"invoice.paid\",\n INVOICE_PAYMENT_FAILED: \"invoice.payment_failed\",\n INVOICE_PAYMENT_ACTION_REQUIRED: \"invoice.payment_action_required\",\n INVOICE_VOIDED: \"invoice.voided\",\n PAYMENT_SUCCEEDED: \"payment.succeeded\",\n PAYMENT_FAILED: \"payment.failed\",\n REFUND_CREATED: \"refund.created\",\n REFUND_UPDATED: \"refund.updated\",\n REFUND_FAILED: \"refund.failed\",\n DISPUTE_CREATED: \"dispute.created\",\n DISPUTE_CLOSED: \"dispute.closed\",\n PAYMENT_METHOD_ATTACHED: \"payment_method.attached\",\n PAYMENT_METHOD_UPDATED: \"payment_method.updated\",\n PAYMENT_METHOD_DETACHED: \"payment_method.detached\",\n} as const;\n\nexport type BillingEventType = (typeof BillingEventType)[keyof typeof BillingEventType];\n\nexport interface BillingEvent {\n provider: string;\n eventId: string;\n eventType: BillingEventType;\n occurredAt: string;\n /** Financial subject affected by this provider event. */\n accountId?: string | null;\n customer?: BillingCustomerInfo | null;\n subscription?: BillingSubscriptionInfo | null;\n invoice?: BillingInvoiceInfo | null;\n payment?: BillingPaymentInfo | null;\n refund?: BillingRefundInfo | null;\n dispute?: BillingDisputeInfo | null;\n metadata?: Record<string, unknown> | null;\n raw?: unknown;\n billingEventId?: string;\n}\n\nconst BILLING_EVENT_TYPES = new Set<string>(Object.values(BillingEventType));\nconst SUBSCRIPTION_STATUSES = new Set([\n \"incomplete\",\n \"incomplete_expired\",\n \"trialing\",\n \"active\",\n \"past_due\",\n \"canceled\",\n \"unpaid\",\n \"paused\",\n \"expired\",\n]);\nconst BILLING_INTERVALS = new Set([\"day\", \"week\", \"month\", \"year\"]);\nconst INVOICE_STATUSES = new Set([\"draft\", \"open\", \"paid\", \"void\", \"uncollectible\"]);\nconst PAYMENT_PURPOSES = new Set([\"subscription\", \"credit_topup\"]);\nconst PAYMENT_STATUSES = new Set([\"pending\", \"succeeded\", \"failed\", \"canceled\"]);\nconst DISPUTE_STATUSES = new Set([\"needs_response\", \"under_review\", \"won\", \"lost\", \"closed\"]);\nconst ISO_INSTANT_WITH_OFFSET = /(?:Z|[+-]\\d{2}:\\d{2})$/;\n\nfunction requireObject(value: unknown, field: string): Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new TypeError(`${field} must be an object`);\n }\n return value as Record<string, unknown>;\n}\n\nfunction rejectUnknownKeys(\n value: Record<string, unknown>,\n allowed: readonly string[],\n field: string,\n) {\n const known = new Set(allowed);\n const unknown = Object.keys(value).filter((key) => !known.has(key));\n if (unknown.length > 0) {\n throw new TypeError(\n `${field} contains unsupported field${unknown.length === 1 ? \"\" : \"s\"}: ${unknown.join(\", \")}`,\n );\n }\n}\n\nfunction requireNonEmptyString(value: unknown, field: string): void {\n if (typeof value !== \"string\" || !value.trim()) {\n throw new TypeError(`${field} must be a non-empty string`);\n }\n}\n\nfunction requireOptionalNonEmptyString(value: unknown, field: string): void {\n if (value !== null && value !== undefined) requireNonEmptyString(value, field);\n}\n\nfunction requireOptionalString(value: unknown, field: string): void {\n if (value !== null && value !== undefined && typeof value !== \"string\") {\n throw new TypeError(`${field} must be a string`);\n }\n}\n\nfunction requireOptionalBoolean(value: unknown, field: string): void {\n if (value !== null && value !== undefined && typeof value !== \"boolean\") {\n throw new TypeError(`${field} must be a boolean`);\n }\n}\n\nfunction requireOneOf(value: unknown, allowed: ReadonlySet<string>, field: string): void {\n if (typeof value !== \"string\" || !allowed.has(value)) {\n throw new TypeError(`${field} has an unsupported value`);\n }\n}\n\nfunction validateProviderRef(value: unknown, field: string): void {\n if (value === null || value === undefined) return;\n const reference = requireObject(value, field);\n const keys = [\"productId\", \"priceId\", \"variantId\", \"lookupKey\"] as const;\n rejectUnknownKeys(reference, keys, field);\n for (const key of keys) requireOptionalNonEmptyString(reference[key], `${field}.${key}`);\n if (!keys.some((key) => reference[key] !== null && reference[key] !== undefined)) {\n throw new TypeError(`${field} must contain a provider identifier`);\n }\n}\n\nfunction requireMinorUnits(value: unknown, field: string, positive = false): void {\n if (!Number.isSafeInteger(value) || (value as number) < (positive ? 1 : 0)) {\n throw new TypeError(\n `${field} must be a ${positive ? \"positive\" : \"non-negative\"} safe integer`,\n );\n }\n}\n\nfunction requireCurrency(value: unknown, field: string): void {\n if (typeof value !== \"string\" || !/^[A-Z]{3}$/.test(value)) {\n throw new TypeError(`${field} must be an uppercase three-letter currency code`);\n }\n}\n\nfunction requireOptionalInstant(value: unknown, field: string): void {\n if (value === null || value === undefined) return;\n if (\n typeof value !== \"string\" ||\n !ISO_INSTANT_WITH_OFFSET.test(value) ||\n Number.isNaN(Date.parse(value))\n ) {\n throw new TypeError(`${field} must be an ISO 8601 instant with an offset`);\n }\n}\n\n/** Validate an event at the public ingestion boundary before claiming it. */\nexport function assertBillingEvent(value: unknown): asserts value is BillingEvent {\n const record = requireObject(value, \"billing event\");\n rejectUnknownKeys(\n record,\n [\n \"provider\",\n \"eventId\",\n \"eventType\",\n \"occurredAt\",\n \"accountId\",\n \"customer\",\n \"subscription\",\n \"invoice\",\n \"payment\",\n \"refund\",\n \"dispute\",\n \"metadata\",\n \"raw\",\n \"billingEventId\",\n ],\n \"billing event\",\n );\n const event = record as unknown as BillingEvent;\n requireNonEmptyString(event.provider, \"billing event provider\");\n requireNonEmptyString(event.eventId, \"billing event id\");\n requireOptionalNonEmptyString(event.accountId, \"billing event accountId\");\n requireOptionalNonEmptyString(event.billingEventId, \"billing event billingEventId\");\n if (event.metadata !== null && event.metadata !== undefined) {\n requireObject(event.metadata, \"billing event metadata\");\n }\n if (!BILLING_EVENT_TYPES.has(event.eventType)) {\n throw new TypeError(`unsupported billing event type: ${String(event.eventType)}`);\n }\n if (\n typeof event.occurredAt !== \"string\" ||\n !ISO_INSTANT_WITH_OFFSET.test(event.occurredAt) ||\n Number.isNaN(Date.parse(event.occurredAt))\n ) {\n throw new TypeError(\"billing event occurredAt must be an ISO 8601 instant with an offset\");\n }\n\n const eventName: string = event.eventType;\n if (event.customer !== null && event.customer !== undefined) {\n const customer = requireObject(event.customer, `${eventName} customer`);\n rejectUnknownKeys(customer, [\"providerCustomerId\", \"email\"], `${eventName} customer`);\n requireOptionalNonEmptyString(\n customer.providerCustomerId,\n `${eventName} customer.providerCustomerId`,\n );\n requireOptionalNonEmptyString(customer.email, `${eventName} customer.email`);\n if (customer.providerCustomerId == null && customer.email == null) {\n throw new TypeError(`${eventName} customer requires providerCustomerId or email`);\n }\n } else if (eventName.startsWith(\"customer.\")) {\n throw new TypeError(`${eventName} requires customer data`);\n }\n if (event.subscription !== null && event.subscription !== undefined) {\n const subscription = requireObject(event.subscription, `${eventName} subscription`);\n rejectUnknownKeys(\n subscription,\n [\n \"providerSubscriptionId\",\n \"status\",\n \"cancelAtPeriodEnd\",\n \"periodStart\",\n \"periodEnd\",\n \"trialEnd\",\n \"cancelAt\",\n \"endedAt\",\n \"refs\",\n \"interval\",\n \"intervalCount\",\n ],\n `${eventName} subscription`,\n );\n requireNonEmptyString(\n subscription.providerSubscriptionId,\n `${eventName} subscription.providerSubscriptionId`,\n );\n if (subscription.status != null) {\n requireOneOf(subscription.status, SUBSCRIPTION_STATUSES, `${eventName} subscription.status`);\n }\n requireOptionalBoolean(\n subscription.cancelAtPeriodEnd,\n `${eventName} subscription.cancelAtPeriodEnd`,\n );\n for (const [field, value] of [\n [\"periodStart\", subscription.periodStart],\n [\"periodEnd\", subscription.periodEnd],\n [\"trialEnd\", subscription.trialEnd],\n [\"cancelAt\", subscription.cancelAt],\n [\"endedAt\", subscription.endedAt],\n ] as const) {\n requireOptionalInstant(value, `${eventName} subscription.${field}`);\n }\n validateProviderRef(subscription.refs, `${eventName} subscription.refs`);\n if (subscription.interval != null) {\n requireOneOf(subscription.interval, BILLING_INTERVALS, `${eventName} subscription.interval`);\n }\n if (\n subscription.intervalCount !== null &&\n subscription.intervalCount !== undefined &&\n (!Number.isSafeInteger(subscription.intervalCount) ||\n (subscription.intervalCount as number) <= 0)\n ) {\n throw new TypeError(\n `${eventName} subscription.intervalCount must be a positive safe integer`,\n );\n }\n } else if (eventName.startsWith(\"subscription.\")) {\n throw new TypeError(`${eventName} requires subscription data`);\n }\n if (event.invoice !== null && event.invoice !== undefined) {\n const invoice = requireObject(event.invoice, `${eventName} invoice`);\n rejectUnknownKeys(\n invoice,\n [\n \"providerInvoiceId\",\n \"status\",\n \"amountPaidMinor\",\n \"amountDueMinor\",\n \"currency\",\n \"periodStart\",\n \"periodEnd\",\n ],\n `${eventName} invoice`,\n );\n requireNonEmptyString(invoice.providerInvoiceId, `${eventName} invoice.providerInvoiceId`);\n requireOneOf(invoice.status, INVOICE_STATUSES, `${eventName} invoice.status`);\n requireMinorUnits(invoice.amountPaidMinor, `${eventName} invoice.amountPaidMinor`);\n requireMinorUnits(invoice.amountDueMinor, `${eventName} invoice.amountDueMinor`);\n requireCurrency(invoice.currency, `${eventName} invoice.currency`);\n requireOptionalInstant(invoice.periodStart, `${eventName} invoice.periodStart`);\n requireOptionalInstant(invoice.periodEnd, `${eventName} invoice.periodEnd`);\n } else if (eventName.startsWith(\"invoice.\")) {\n throw new TypeError(`${eventName} requires invoice data`);\n }\n if (event.payment !== null && event.payment !== undefined) {\n const payment = requireObject(event.payment, `${eventName} payment`);\n rejectUnknownKeys(\n payment,\n [\"providerPaymentId\", \"amountMinor\", \"taxMinor\", \"currency\", \"refs\", \"purpose\", \"status\"],\n `${eventName} payment`,\n );\n requireNonEmptyString(payment.providerPaymentId, `${eventName} payment.providerPaymentId`);\n requireMinorUnits(payment.amountMinor, `${eventName} payment.amountMinor`);\n requireMinorUnits(payment.taxMinor, `${eventName} payment.taxMinor`);\n requireCurrency(payment.currency, `${eventName} payment.currency`);\n validateProviderRef(payment.refs, `${eventName} payment.refs`);\n requireOneOf(payment.purpose, PAYMENT_PURPOSES, `${eventName} payment.purpose`);\n requireOneOf(payment.status, PAYMENT_STATUSES, `${eventName} payment.status`);\n } else if (eventName.startsWith(\"payment.\")) {\n throw new TypeError(`${eventName} requires payment data`);\n }\n if (event.refund !== null && event.refund !== undefined) {\n const refund = requireObject(event.refund, `${eventName} refund`);\n rejectUnknownKeys(\n refund,\n [\"providerRefundId\", \"providerPaymentId\", \"amountMinor\", \"currency\", \"reason\", \"status\"],\n `${eventName} refund`,\n );\n requireNonEmptyString(refund.providerRefundId, `${eventName} refund.providerRefundId`);\n requireNonEmptyString(refund.providerPaymentId, `${eventName} refund.providerPaymentId`);\n requireMinorUnits(refund.amountMinor, `${eventName} refund.amountMinor`, true);\n requireCurrency(refund.currency, `${eventName} refund.currency`);\n requireOptionalString(refund.reason, `${eventName} refund.reason`);\n requireOneOf(refund.status, PAYMENT_STATUSES, `${eventName} refund.status`);\n } else if (eventName.startsWith(\"refund.\")) {\n throw new TypeError(`${eventName} requires refund data`);\n }\n if (event.dispute !== null && event.dispute !== undefined) {\n const dispute = requireObject(event.dispute, `${eventName} dispute`);\n rejectUnknownKeys(\n dispute,\n [\"providerDisputeId\", \"providerPaymentId\", \"status\", \"reason\"],\n `${eventName} dispute`,\n );\n requireNonEmptyString(dispute.providerDisputeId, `${eventName} dispute.providerDisputeId`);\n requireNonEmptyString(dispute.providerPaymentId, `${eventName} dispute.providerPaymentId`);\n requireOneOf(dispute.status, DISPUTE_STATUSES, `${eventName} dispute.status`);\n requireOptionalString(dispute.reason, `${eventName} dispute.reason`);\n } else if (eventName.startsWith(\"dispute.\")) {\n throw new TypeError(`${eventName} requires dispute data`);\n }\n}\n\nexport type BillingEventHandler = (event: BillingEvent, accountId: string) => Promise<void>;\n\nexport interface BillingEventResult {\n handled: boolean;\n action?: string | null;\n error?: string | null;\n subscriptionId?: string | null;\n}\n\nexport type BillingEventClaim =\n | { status: \"claimed\"; claimToken: string; billingEventId: string }\n | { status: \"duplicate\" }\n | { status: \"busy\" }\n | { status: \"retry\" };\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"subscriptions.d.ts","sourceRoot":"","sources":["../../../src/billing/types/subscriptions.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAErE,MAAM,MAAM,yBAAyB,GACjC,YAAY,GACZ,oBAAoB,GACpB,UAAU,GACV,QAAQ,GAC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AM,WAAW,cAAc;IAC7B,EAAE,EAAE,MAAM,CAAC;IACX,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,MAAM,CAAC;IACjB,YAAY,EAAE,cAAc,GAAG,cAAc,CAAC;IAC9C,UAAU,EAAE,MAAM,CAAC;IACnB,aAAa,EAAE,MAAM,CAAC;IACtB,MAAM,EAAE,oBAAoB,CAAC;IAC7B,iBAAiB,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAClC,WAAW,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC5B,SAAS,EAAE,MAAM,CAAC;CACnB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"subscriptions.js","sourceRoot":"","sources":["../../../src/billing/types/subscriptions.ts"],"names":[],"mappings":"AAaA,MAAM,CAAC,MAAM,mBAAmB,GAAG;IACjC,MAAM,EAAE,QAAQ;IAChB,QAAQ,EAAE,UAAU;IACpB,QAAQ,EAAE,UAAU;IACpB,UAAU,EAAE,YAAY;IACxB,QAAQ,EAAE,UAAU;IACpB,kBAAkB,EAAE,oBAAoB;IACxC,MAAM,EAAE,QAAQ;IAChB,MAAM,EAAE,QAAQ;IAChB,OAAO,EAAE,SAAS;CAC0C,CAAC","sourcesContent":["import type { BillingOfferInterval, ProviderRef } from \"./common.js\";\n\nexport type BillingSubscriptionStatus =\n | \"incomplete\"\n | \"incomplete_expired\"\n | \"trialing\"\n | \"active\"\n | \"past_due\"\n | \"canceled\"\n | \"unpaid\"\n | \"paused\"\n | \"expired\";\n\nexport const SUBSCRIPTION_STATUS = {\n ACTIVE: \"active\",\n TRIALING: \"trialing\",\n CANCELED: \"canceled\",\n INCOMPLETE: \"incomplete\",\n PAST_DUE: \"past_due\",\n INCOMPLETE_EXPIRED: \"incomplete_expired\",\n UNPAID: \"unpaid\",\n PAUSED: \"paused\",\n EXPIRED: \"expired\",\n} as const satisfies Record<string, BillingSubscriptionStatus>;\n\nexport interface BillingSubscriptionInfo {\n providerSubscriptionId: string;\n status?: BillingSubscriptionStatus | null;\n cancelAtPeriodEnd?: boolean | null;\n periodStart?: string | null;\n periodEnd?: string | null;\n trialEnd?: string | null;\n cancelAt?: string | null;\n endedAt?: string | null;\n refs?: ProviderRef | null;\n interval?: string | null;\n intervalCount?: number | null;\n}\n\nexport interface BillingSubscriptionState {\n subscriptionId?: string | null;\n userId: string;\n provider: string;\n providerSubscriptionId: string;\n providerCustomerId?: string | null;\n offerId?: string | null;\n offerKey?: string | null;\n planId?: string | null;\n plan?: string | null;\n status: BillingSubscriptionStatus;\n currentPeriodStart?: string | null;\n currentPeriodEnd?: string | null;\n trialEnd?: string | null;\n cancelAt?: string | null;\n endedAt?: string | null;\n graceEndsAt?: string | null;\n graceExpiredAt?: string | null;\n providerUpdatedAt: string;\n cancelAtPeriodEnd: boolean;\n interval?: string | null;\n intervalCount?: number | null;\n metadata?: Record<string, unknown> | null;\n}\n\nexport type BillingSubscriptionChangeState =\n
|
|
1
|
+
{"version":3,"file":"subscriptions.js","sourceRoot":"","sources":["../../../src/billing/types/subscriptions.ts"],"names":[],"mappings":"AAaA,MAAM,CAAC,MAAM,mBAAmB,GAAG;IACjC,MAAM,EAAE,QAAQ;IAChB,QAAQ,EAAE,UAAU;IACpB,QAAQ,EAAE,UAAU;IACpB,UAAU,EAAE,YAAY;IACxB,QAAQ,EAAE,UAAU;IACpB,kBAAkB,EAAE,oBAAoB;IACxC,MAAM,EAAE,QAAQ;IAChB,MAAM,EAAE,QAAQ;IAChB,OAAO,EAAE,SAAS;CAC0C,CAAC","sourcesContent":["import type { BillingOfferInterval, ProviderRef } from \"./common.js\";\n\nexport type BillingSubscriptionStatus =\n | \"incomplete\"\n | \"incomplete_expired\"\n | \"trialing\"\n | \"active\"\n | \"past_due\"\n | \"canceled\"\n | \"unpaid\"\n | \"paused\"\n | \"expired\";\n\nexport const SUBSCRIPTION_STATUS = {\n ACTIVE: \"active\",\n TRIALING: \"trialing\",\n CANCELED: \"canceled\",\n INCOMPLETE: \"incomplete\",\n PAST_DUE: \"past_due\",\n INCOMPLETE_EXPIRED: \"incomplete_expired\",\n UNPAID: \"unpaid\",\n PAUSED: \"paused\",\n EXPIRED: \"expired\",\n} as const satisfies Record<string, BillingSubscriptionStatus>;\n\nexport interface BillingSubscriptionInfo {\n providerSubscriptionId: string;\n status?: BillingSubscriptionStatus | null;\n cancelAtPeriodEnd?: boolean | null;\n periodStart?: string | null;\n periodEnd?: string | null;\n trialEnd?: string | null;\n cancelAt?: string | null;\n endedAt?: string | null;\n refs?: ProviderRef | null;\n interval?: string | null;\n intervalCount?: number | null;\n}\n\nexport interface BillingSubscriptionState {\n subscriptionId?: string | null;\n userId: string;\n provider: string;\n providerSubscriptionId: string;\n providerCustomerId?: string | null;\n offerId?: string | null;\n offerKey?: string | null;\n planId?: string | null;\n plan?: string | null;\n status: BillingSubscriptionStatus;\n currentPeriodStart?: string | null;\n currentPeriodEnd?: string | null;\n trialEnd?: string | null;\n cancelAt?: string | null;\n endedAt?: string | null;\n graceEndsAt?: string | null;\n graceExpiredAt?: string | null;\n providerUpdatedAt: string;\n cancelAtPeriodEnd: boolean;\n interval?: string | null;\n intervalCount?: number | null;\n metadata?: Record<string, unknown> | null;\n}\n\nexport type BillingSubscriptionChangeState =\n \"awaiting_payment\" | \"scheduled\" | \"applied\" | \"failed\" | \"canceled\";\n\nexport interface BillingSubscriptionOfferContext {\n offerId: string;\n offerKey: string;\n planId: string;\n plan: string;\n interval: BillingOfferInterval;\n intervalCount: number;\n}\n\nexport interface BillingSubscriptionChange {\n id: string;\n subscriptionId: string;\n fromOfferId: string;\n toOfferId: string;\n fromOffer: BillingSubscriptionOfferContext;\n toOffer: BillingSubscriptionOfferContext;\n effectiveAt: string | null;\n effective: \"immediate\" | \"renewal\";\n state: BillingSubscriptionChangeState;\n prorationBehavior: \"provider_default\" | \"invoice_immediately\" | \"none\";\n idempotencyKey: string;\n providerOperationId?: string | null;\n errorMessage?: string | null;\n}\n\nexport interface BillingSubscriptionChangeInput {\n provider: string;\n providerSubscriptionId: string;\n toOfferId: string;\n effectiveAt: string;\n effective: \"immediate\" | \"renewal\";\n idempotencyKey: string;\n prorationBehavior?: \"provider_default\" | \"invoice_immediately\" | \"none\";\n}\n\nexport type CheckoutIntentStatus = \"open\" | \"completed\" | \"failed\" | \"expired\";\n\nexport interface CheckoutIntent {\n id: string;\n subjectId: string;\n provider: string;\n checkoutKind: \"subscription\" | \"credit_topup\";\n productKey: string;\n requestDigest: string;\n status: CheckoutIntentStatus;\n providerSessionId?: string | null;\n checkoutUrl?: string | null;\n expiresAt: string;\n}\n"]}
|
package/dist/bursar.d.ts
CHANGED
|
@@ -7,7 +7,7 @@ import type { BillingEvent, BillingEventResult } from "./billing/types/index.js"
|
|
|
7
7
|
import type { BillingCapability, BillingEventSink } from "./billing/contracts.js";
|
|
8
8
|
import { CommerceService as CommerceServiceImpl } from "./commerce/service.js";
|
|
9
9
|
import type { CommerceOptions } from "./commerce/types.js";
|
|
10
|
-
import type { CatalogRollout, ParsedBursarConfig } from "./config/types.js";
|
|
10
|
+
import type { BursarConfigData, CatalogRollout, ParsedBursarConfig } from "./config/types.js";
|
|
11
11
|
import { type PublicCatalog } from "./catalog.js";
|
|
12
12
|
import type { CreditMetadata, GrantProgramAwardResult } from "./credits/types/index.js";
|
|
13
13
|
export type { BillingCapability, BillingEventSink } from "./billing/contracts.js";
|
|
@@ -20,15 +20,25 @@ export type { CommerceOptions } from "./commerce/types.js";
|
|
|
20
20
|
*/
|
|
21
21
|
export type CreditsService = Pick<CreditsServiceImpl, "getUserPlan" | "checkFeature" | "getQuotaState" | "listQuotaEvents" | "startPlanMigration" | "migratePlanBatch" | "revokeCreditsByEntryType" | "executeGrantProgram" | "getLedgerEntry" | "getAvailable" | "aggregateStats" | "spendByUser" | "spendByModel" | "listLedgerEntries" | "listUsageEntries" | "listUsageCharges" | "topUsers" | "dailySpend" | "setUserPlan" | "unsetUserPlan" | "getBalance" | "addCredits" | "deductCredits" | "grantSubscriptionCycle" | "reserve" | "settle" | "release" | "renew" | "canAfford" | "getBucketBalances" | "checkAllowance" | "runBilled" | "beginBilledOperation" | "deduct" | "recordUsage" | "deductFlatJob" | "refundCredits" | "deductTeam" | "sweepExpiredCredits">;
|
|
22
22
|
type CatalogCreditsService = Pick<CreditsServiceImpl, "getActiveCatalog" | "loadCatalogFromStore" | "refreshCatalogIfStale" | "invalidateCatalog" | "publishAndActivateCatalog" | "publishCatalogDraft" | "activateCatalogRevision" | "pricingEngine" | "setPlanRevisionPin" | "applyDuePlanChanges">;
|
|
23
|
-
|
|
24
|
-
export interface BursarOptions {
|
|
23
|
+
interface BaseBursarOptions {
|
|
25
24
|
creditStore: CreditStore;
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
25
|
+
creditsOptions?: CreditsServiceOptions;
|
|
26
|
+
emitter?: CreditEventEmitter;
|
|
27
|
+
}
|
|
28
|
+
/** Credits-only construction rejects billing options that would otherwise be ignored. */
|
|
29
|
+
export interface CreditsOnlyBursarOptions extends BaseBursarOptions {
|
|
30
|
+
billingStore?: undefined;
|
|
31
|
+
billingOptions?: never;
|
|
32
|
+
commerceOptions?: never;
|
|
31
33
|
}
|
|
34
|
+
/** Billing construction owns provisioning and may optionally enable commerce. */
|
|
35
|
+
export interface BillingBursarOptions extends BaseBursarOptions {
|
|
36
|
+
billingStore: BillingStore;
|
|
37
|
+
billingOptions?: Omit<BillingServiceOptions, "provisioning">;
|
|
38
|
+
commerceOptions?: CommerceOptions;
|
|
39
|
+
}
|
|
40
|
+
/** Options for constructing the single application-facing Bursar service. */
|
|
41
|
+
export type BursarOptions = CreditsOnlyBursarOptions | BillingBursarOptions;
|
|
32
42
|
/** Catalog operations. Configuration writes live here, never in BillingService. */
|
|
33
43
|
export declare class CatalogService {
|
|
34
44
|
private readonly credits;
|
|
@@ -45,9 +55,9 @@ export declare class CatalogService {
|
|
|
45
55
|
invalidate(): void;
|
|
46
56
|
getConfig(): Promise<ParsedBursarConfig>;
|
|
47
57
|
publicView(): Promise<PublicCatalog>;
|
|
48
|
-
publishDraft(config:
|
|
49
|
-
activate(version: number, rollout?: CatalogRollout |
|
|
50
|
-
publishAndActivate(config:
|
|
58
|
+
publishDraft(config: BursarConfigData, label?: string | null): Promise<string>;
|
|
59
|
+
activate(version: number, rollout?: CatalogRollout | null): Promise<string>;
|
|
60
|
+
publishAndActivate(config: BursarConfigData, label?: string | null, rollout?: CatalogRollout | null): Promise<string>;
|
|
51
61
|
/** Pin or unpin one current assignment from automatic catalog rollout. */
|
|
52
62
|
setRevisionPin(userId: string, pinned: boolean): Promise<boolean>;
|
|
53
63
|
/** Apply one bounded batch of renewal-effective plan changes. */
|
package/dist/bursar.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bursar.d.ts","sourceRoot":"","sources":["../src/bursar.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,KAAK,qBAAqB,EAC3B,MAAM,8BAA8B,CAAC;AACtC,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAC/D,OAAO,EACL,cAAc,IAAI,kBAAkB,EACpC,KAAK,qBAAqB,EAC3B,MAAM,sBAAsB,CAAC;AAC9B,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AACtD,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AAC9D,OAAO,KAAK,EAAE,YAAY,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AACjF,OAAO,KAAK,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAClF,OAAO,EAAE,eAAe,IAAI,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAE/E,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAE3D,OAAO,KAAK,EAAE,cAAc,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;
|
|
1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ChE,qBAAa,cAAc;IAEvB,OAAO,CAAC,QAAQ,CAAC,OAAO;IACxB,OAAO,CAAC,QAAQ,CAAC,OAAO;gBADP,OAAO,EAAE,cAAc,EACvB,OAAO,EAAE,cAAc;IAGpC,gBAAgB,CAAC,KAAK,EAAE,mBAAmB,GAAG,OAAO,CAAC,oBAAoB,CAAC;CA0ClF;AAED;;;;;;;GAOG;AACH,qBAAa,MAAO,YAAW,gBAAgB;IAC7C,QAAQ,CAAC,OAAO,EAAE,cAAc,CAAC;IACjC,QAAQ,CAAC,OAAO,EAAE,iBAAiB,GAAG,IAAI,CAAC;IAC3C,QAAQ,CAAC,QAAQ,EAAE,mBAAmB,GAAG,IAAI,CAAC;IAC9C,QAAQ,CAAC,OAAO,EAAE,cAAc,CAAC;IACjC,QAAQ,CAAC,QAAQ,EAAE,cAAc,CAAC;gBAEtB,OAAO,EAAE,aAAa;IAiElC,uDAAuD;IACjD,WAAW,IAAI,OAAO,CAAC,IAAI,CAAC;IAIlC,mEAAmE;IACnE,cAAc,IAAI,iBAAiB;IAOnC,oEAAoE;IACpE,eAAe,IAAI,mBAAmB;IAOtC;;;OAGG;IACG,kBAAkB,CAAC,KAAK,EAAE,YAAY,GAAG,OAAO,CAAC,kBAAkB,CAAC;CAG3E"}
|
package/dist/bursar.js
CHANGED
|
@@ -68,11 +68,14 @@ export class AccountService {
|
|
|
68
68
|
this.catalog = catalog;
|
|
69
69
|
}
|
|
70
70
|
async onAccountCreated(input) {
|
|
71
|
-
if (!input.
|
|
72
|
-
throw new
|
|
71
|
+
if (typeof input.accountId !== "string" || !input.accountId.trim()) {
|
|
72
|
+
throw new TypeError("accountId must be a non-empty string");
|
|
73
|
+
}
|
|
74
|
+
if (typeof input.eventKey !== "string" || !input.eventKey.trim()) {
|
|
75
|
+
throw new TypeError("eventKey must be a non-empty string");
|
|
76
|
+
}
|
|
73
77
|
const config = await retryBursarOperation(() => this.catalog.getConfig());
|
|
74
|
-
const
|
|
75
|
-
const planKey = config.catalog.defaultPlan ?? fallback;
|
|
78
|
+
const planKey = config.catalog.defaultPlan;
|
|
76
79
|
if (!planKey)
|
|
77
80
|
throw new ConfigError("The active catalog has no default account plan");
|
|
78
81
|
const current = await retryBursarOperation(() => this.credits.getUserPlan(input.accountId));
|
|
@@ -116,6 +119,39 @@ export class Bursar {
|
|
|
116
119
|
catalog;
|
|
117
120
|
accounts;
|
|
118
121
|
constructor(options) {
|
|
122
|
+
if (typeof options !== "object" || options === null) {
|
|
123
|
+
throw new TypeError("Bursar options are required");
|
|
124
|
+
}
|
|
125
|
+
if (options.billingStore === null) {
|
|
126
|
+
throw new TypeError("billingStore must be a BillingStore when provided");
|
|
127
|
+
}
|
|
128
|
+
for (const optionName of [
|
|
129
|
+
"creditsOptions",
|
|
130
|
+
"billingOptions",
|
|
131
|
+
"commerceOptions",
|
|
132
|
+
"emitter",
|
|
133
|
+
]) {
|
|
134
|
+
if (options[optionName] === null) {
|
|
135
|
+
throw new TypeError(`${optionName} must not be null`);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
if (options.billingStore === undefined &&
|
|
139
|
+
(options.billingOptions !== undefined || options.commerceOptions !== undefined)) {
|
|
140
|
+
throw new TypeError("billingOptions and commerceOptions require billingStore");
|
|
141
|
+
}
|
|
142
|
+
if (options.billingOptions && "provisioning" in options.billingOptions) {
|
|
143
|
+
throw new TypeError("billingOptions.provisioning is owned by Bursar");
|
|
144
|
+
}
|
|
145
|
+
const environments = [
|
|
146
|
+
["creditStore", options.creditStore.providerEnvironment],
|
|
147
|
+
["billingStore", options.billingStore?.providerEnvironment],
|
|
148
|
+
["commerceOptions", options.commerceOptions?.providerEnvironment],
|
|
149
|
+
].filter((entry) => entry[1] !== undefined);
|
|
150
|
+
if (new Set(environments.map(([, environment]) => environment)).size > 1) {
|
|
151
|
+
throw new TypeError(`Bursar provider environments must match: ${environments
|
|
152
|
+
.map(([name, environment]) => `${name}=${environment}`)
|
|
153
|
+
.join(", ")}`);
|
|
154
|
+
}
|
|
119
155
|
const credits = new CreditsServiceImpl(options.creditStore, undefined, options.emitter ?? undefined, options.creditsOptions ?? undefined);
|
|
120
156
|
this.credits = credits;
|
|
121
157
|
this.catalog = new CatalogService(credits);
|
package/dist/bursar.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bursar.js","sourceRoot":"","sources":["../src/bursar.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,cAAc,IAAI,mBAAmB,GAEtC,MAAM,8BAA8B,CAAC;AAEtC,OAAO,EACL,cAAc,IAAI,kBAAkB,GAErC,MAAM,sBAAsB,CAAC;AAK9B,OAAO,EAAE,eAAe,IAAI,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAC/E,OAAO,EAAE,0BAA0B,EAAE,MAAM,sBAAsB,CAAC;AAElE,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAEjD,OAAO,EAAE,4BAA4B,EAAE,WAAW,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC;AAC/F,OAAO,EAAE,oBAAoB,EAAsB,MAAM,cAAc,CAAC;AAExE,OAAO,EAAE,oBAAoB,EAAE,MAAM,YAAY,CAAC;AA6ElD,mFAAmF;AACnF,MAAM,OAAO,cAAc;IACI;IAA7B,YAA6B,OAA8B;QAA9B,YAAO,GAAP,OAAO,CAAuB;IAAG,CAAC;IAE/D,mEAAmE;IACnE,SAAS;QACP,OAAO,IAAI,CAAC,OAAO,CAAC,gBAAgB,EAAE,CAAC;IACzC,CAAC;IAED,kEAAkE;IAClE,IAAI,QAAQ;QACV,OAAO,IAAI,CAAC,OAAO,CAAC,aAAa,KAAK,IAAI,CAAC;IAC7C,CAAC;IAED,2DAA2D;IAC3D,IAAI;QACF,OAAO,IAAI,CAAC,OAAO,CAAC,oBAAoB,EAAE,CAAC;IAC7C,CAAC;IAED,iEAAiE;IACjE,OAAO;QACL,OAAO,IAAI,CAAC,OAAO,CAAC,qBAAqB,EAAE,CAAC;IAC9C,C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vB,CAAC;IAED;;;OAGG;IACH,KAAK,CAAC,kBAAkB,CAAC,KAAmB;QAC1C,OAAO,IAAI,CAAC,cAAc,EAAE,CAAC,kBAAkB,CAAC,KAAK,CAAC,CAAC;IACzD,CAAC;CACF","sourcesContent":["import {\n BillingService as BillingEventService,\n type BillingServiceOptions,\n} from \"./billing/billing-service.js\";\nimport type { BillingStore } from \"./billing/billing-store.js\";\nimport {\n CreditsService as CreditsServiceImpl,\n type CreditsServiceOptions,\n} from \"./credits/service.js\";\nimport type { CreditStore } from \"./credits/store.js\";\nimport type { CreditEventEmitter } from \"./credits/events.js\";\nimport type { BillingEvent, BillingEventResult } from \"./billing/types/index.js\";\nimport type { BillingCapability, BillingEventSink } from \"./billing/contracts.js\";\nimport { CommerceService as CommerceServiceImpl } from \"./commerce/service.js\";\nimport { CommerceNotConfiguredError } from \"./commerce/errors.js\";\nimport type { CommerceOptions } from \"./commerce/types.js\";\nimport { loadConfigFromDict } from \"./config.js\";\nimport type { CatalogRollout, ParsedBursarConfig } from \"./config/types.js\";\nimport { CapabilityNotConfiguredError, ConfigError, CatalogNotLoadedError } from \"./errors.js\";\nimport { projectPublicCatalog, type PublicCatalog } from \"./catalog.js\";\nimport type { CreditMetadata, GrantProgramAwardResult } from \"./credits/types/index.js\";\nimport { retryBursarOperation } from \"./retry.js\";\nexport type { BillingCapability, BillingEventSink } from \"./billing/contracts.js\";\nexport type { CommerceOptions } from \"./commerce/types.js\";\n\n/**\n * Stable public credit capability exposed by {@link Bursar}.\n *\n * The explicit method list prevents implementation helpers added to\n * `CreditsServiceImpl` from silently becoming public API.\n */\nexport type CreditsService = Pick<\n CreditsServiceImpl,\n | \"getUserPlan\"\n | \"checkFeature\"\n | \"getQuotaState\"\n | \"listQuotaEvents\"\n | \"startPlanMigration\"\n | \"migratePlanBatch\"\n | \"revokeCreditsByEntryType\"\n | \"executeGrantProgram\"\n | \"getLedgerEntry\"\n | \"getAvailable\"\n | \"aggregateStats\"\n | \"spendByUser\"\n | \"spendByModel\"\n | \"listLedgerEntries\"\n | \"listUsageEntries\"\n | \"listUsageCharges\"\n | \"topUsers\"\n | \"dailySpend\"\n | \"setUserPlan\"\n | \"unsetUserPlan\"\n | \"getBalance\"\n | \"addCredits\"\n | \"deductCredits\"\n | \"grantSubscriptionCycle\"\n | \"reserve\"\n | \"settle\"\n | \"release\"\n | \"renew\"\n | \"canAfford\"\n | \"getBucketBalances\"\n | \"checkAllowance\"\n | \"runBilled\"\n | \"beginBilledOperation\"\n | \"deduct\"\n | \"recordUsage\"\n | \"deductFlatJob\"\n | \"refundCredits\"\n | \"deductTeam\"\n | \"sweepExpiredCredits\"\n>;\n\ntype CatalogCreditsService = Pick<\n CreditsServiceImpl,\n | \"getActiveCatalog\"\n | \"loadCatalogFromStore\"\n | \"refreshCatalogIfStale\"\n | \"invalidateCatalog\"\n | \"publishAndActivateCatalog\"\n | \"publishCatalogDraft\"\n | \"activateCatalogRevision\"\n | \"pricingEngine\"\n | \"setPlanRevisionPin\"\n | \"applyDuePlanChanges\"\n>;\n\n/** Options for constructing the single application-facing Bursar service. */\nexport interface BursarOptions {\n creditStore: CreditStore;\n billingStore?: BillingStore | null;\n creditsOptions?: CreditsServiceOptions | null;\n billingOptions?: BillingServiceOptions | null;\n commerceOptions?: CommerceOptions | null;\n emitter?: CreditEventEmitter | null;\n}\n\n/** Catalog operations. Configuration writes live here, never in BillingService. */\nexport class CatalogService {\n constructor(private readonly credits: CatalogCreditsService) {}\n\n /** Return the active persisted catalog revision, if one exists. */\n getActive() {\n return this.credits.getActiveCatalog();\n }\n\n /** Whether this process currently has a pricing engine loaded. */\n get isLoaded(): boolean {\n return this.credits.pricingEngine !== null;\n }\n\n /** Load the active persisted catalog into this process. */\n load(): Promise<void> {\n return this.credits.loadCatalogFromStore();\n }\n\n /** Block until a stale in-process catalog has been refreshed. */\n refresh(): Promise<void> {\n return this.credits.refreshCatalogIfStale();\n }\n\n /** Force the next refresh to reload the active catalog. */\n invalidate(): void {\n this.credits.invalidateCatalog();\n }\n\n async getConfig(): Promise<ParsedBursarConfig> {\n const active = await this.getActive();\n if (!active) throw new CatalogNotLoadedError(\"No active Bursar catalog is available\");\n return loadConfigFromDict(active.config);\n }\n\n async publicView(): Promise<PublicCatalog> {\n return projectPublicCatalog(await this.getConfig());\n }\n\n publishDraft(config: Record<string, unknown>, label?: string | null): Promise<string> {\n return this.credits.publishCatalogDraft(config, label);\n }\n\n activate(\n version: number,\n rollout?: CatalogRollout | Record<string, unknown> | null,\n ): Promise<string> {\n return this.credits.activateCatalogRevision(version, rollout);\n }\n\n publishAndActivate(\n config: Record<string, unknown>,\n label?: string | null,\n rollout?: CatalogRollout | Record<string, unknown> | null,\n ): Promise<string> {\n return this.credits.publishAndActivateCatalog(config, label, rollout);\n }\n\n /** Pin or unpin one current assignment from automatic catalog rollout. */\n setRevisionPin(userId: string, pinned: boolean): Promise<boolean> {\n return this.credits.setPlanRevisionPin(userId, pinned);\n }\n\n /** Apply one bounded batch of renewal-effective plan changes. */\n applyDueChanges(limit = 100): Promise<number> {\n return this.credits.applyDuePlanChanges(limit);\n }\n}\n\nexport interface AccountCreatedInput {\n accountId: string;\n eventKey: string;\n region?: string | null;\n metadata?: CreditMetadata | null;\n}\n\nexport interface AccountCreatedResult {\n accountId: string;\n planKey: string;\n planAssigned: boolean;\n grants: GrantProgramAwardResult[];\n}\n\n/** Generic financial lifecycle operations for SaaS accounts. */\nexport class AccountService {\n constructor(\n private readonly credits: CreditsService,\n private readonly catalog: CatalogService,\n ) {}\n\n async onAccountCreated(input: AccountCreatedInput): Promise<AccountCreatedResult> {\n if (!input.eventKey.trim()) throw new ConfigError(\"eventKey must not be empty\");\n const config = await retryBursarOperation(() => this.catalog.getConfig());\n const fallback = Object.entries(config.plans).sort(\n ([aKey, a], [bKey, b]) => a.rank - b.rank || aKey.localeCompare(bKey),\n )[0]?.[0];\n const planKey = config.catalog.defaultPlan ?? fallback;\n if (!planKey) throw new ConfigError(\"The active catalog has no default account plan\");\n\n const current = await retryBursarOperation(() => this.credits.getUserPlan(input.accountId));\n const planAssigned = current.planKey == null;\n if (planAssigned) {\n await retryBursarOperation(() => this.credits.setUserPlan(input.accountId, planKey));\n }\n\n const grants: GrantProgramAwardResult[] = [];\n for (const [programKey, program] of Object.entries(config.credits.grantPrograms).sort(\n ([a], [b]) => a.localeCompare(b),\n )) {\n if (program.trigger !== \"account_created\") continue;\n grants.push(\n ...(await retryBursarOperation(() =>\n this.credits.executeGrantProgram({\n trigger: \"account_created\",\n programKey,\n subjectId: input.accountId,\n eventKey: input.eventKey,\n region: input.region,\n metadata: input.metadata,\n }),\n )),\n );\n }\n return {\n accountId: input.accountId,\n planKey: current.planKey ?? planKey,\n planAssigned,\n grants,\n };\n }\n}\n\n/**\n * The application-facing Bursar boundary.\n *\n * Credit and billing services are deliberately created together so consumers\n * cannot accidentally construct unrelated services for the same account\n * lifecycle. Provider and application integrations use this facade rather\n * than constructing lifecycle services independently.\n */\nexport class Bursar implements BillingEventSink {\n readonly credits: CreditsService;\n readonly billing: BillingCapability | null;\n readonly commerce: CommerceServiceImpl | null;\n readonly catalog: CatalogService;\n readonly accounts: AccountService;\n\n constructor(options: BursarOptions) {\n const credits = new CreditsServiceImpl(\n options.creditStore,\n undefined,\n options.emitter ?? undefined,\n options.creditsOptions ?? undefined,\n );\n this.credits = credits;\n this.catalog = new CatalogService(credits);\n this.accounts = new AccountService(credits, this.catalog);\n\n this.billing = options.billingStore\n ? new BillingEventService(options.billingStore, {\n ...(options.billingOptions ?? {}),\n provisioning: credits,\n })\n : null;\n this.commerce =\n this.billing && options.commerceOptions\n ? new CommerceServiceImpl(this.billing, credits, this, options.commerceOptions)\n : null;\n if (this.commerce) {\n credits.addPostDeductionHook(async ({ userId }) => {\n await this.commerce!.autoRecharge.processIfNeeded({ accountId: userId });\n });\n }\n }\n\n /** Load the active catalog into the pricing engine. */\n async loadCatalog(): Promise<void> {\n await this.catalog.load();\n }\n\n /** Return billing or raise the SDK's typed configuration error. */\n requireBilling(): BillingCapability {\n if (!this.billing) {\n throw new CapabilityNotConfiguredError(\"billing\");\n }\n return this.billing;\n }\n\n /** Return commerce or raise the SDK's typed configuration error. */\n requireCommerce(): CommerceServiceImpl {\n if (!this.commerce) {\n throw new CommerceNotConfiguredError(\"Bursar commerce capability is not configured\");\n }\n return this.commerce;\n }\n\n /**\n * Ingest a normalized provider event through the facade-owned billing\n * lifecycle. Providers must not depend on BillingService directly.\n */\n async ingestBillingEvent(event: BillingEvent): Promise<BillingEventResult> {\n return this.requireBilling().ingestBillingEvent(event);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"bursar.js","sourceRoot":"","sources":["../src/bursar.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,cAAc,IAAI,mBAAmB,GAEtC,MAAM,8BAA8B,CAAC;AAEtC,OAAO,EACL,cAAc,IAAI,kBAAkB,GAErC,MAAM,sBAAsB,CAAC;AAK9B,OAAO,EAAE,eAAe,IAAI,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAC/E,OAAO,EAAE,0BAA0B,EAAE,MAAM,sBAAsB,CAAC;AAElE,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAEjD,OAAO,EAAE,4BAA4B,EAAE,WAAW,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC;AAC/F,OAAO,EAAE,oBAAoB,EAAsB,MAAM,cAAc,CAAC;AAExE,OAAO,EAAE,oBAAoB,EAAE,MAAM,YAAY,CAAC;AA0FlD,mFAAmF;AACnF,MAAM,OAAO,cAAc;IACI;IAA7B,YAA6B,OAA8B;QAA9B,YAAO,GAAP,OAAO,CAAuB;IAAG,CAAC;IAE/D,mEAAmE;IACnE,SAAS;QACP,OAAO,IAAI,CAAC,OAAO,CAAC,gBAAgB,EAAE,CAAC;IACzC,CAAC;IAED,kEAAkE;IAClE,IAAI,QAAQ;QACV,OAAO,IAAI,CAAC,OAAO,CAAC,aAAa,KAAK,IAAI,CAAC;IAC7C,CAAC;IAED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,EAAE,CAAC;IAC5B,CAAC;IAED,mEAAmE;IACnE,cAAc;QACZ,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC;YAClB,MAAM,IAAI,4BAA4B,CAAC,SAAS,CAAC,CAAC;QACpD,CAAC;QACD,OAAO,IAAI,CAAC,OAAO,CAAC;IACtB,CAAC;IAED,oEAAoE;IACpE,eAAe;QACb,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,CAAC;YACnB,MAAM,IAAI,0BAA0B,CAAC,8CAA8C,CAAC,CAAC;QACvF,CAAC;QACD,OAAO,IAAI,CAAC,QAAQ,CAAC;IACvB,CAAC;IAED;;;OAGG;IACH,KAAK,CAAC,kBAAkB,CAAC,KAAmB;QAC1C,OAAO,IAAI,CAAC,cAAc,EAAE,CAAC,kBAAkB,CAAC,KAAK,CAAC,CAAC;IACzD,CAAC;CACF","sourcesContent":["import {\n BillingService as BillingEventService,\n type BillingServiceOptions,\n} from \"./billing/billing-service.js\";\nimport type { BillingStore } from \"./billing/billing-store.js\";\nimport {\n CreditsService as CreditsServiceImpl,\n type CreditsServiceOptions,\n} from \"./credits/service.js\";\nimport type { CreditStore } from \"./credits/store.js\";\nimport type { CreditEventEmitter } from \"./credits/events.js\";\nimport type { BillingEvent, BillingEventResult } from \"./billing/types/index.js\";\nimport type { BillingCapability, BillingEventSink } from \"./billing/contracts.js\";\nimport { CommerceService as CommerceServiceImpl } from \"./commerce/service.js\";\nimport { CommerceNotConfiguredError } from \"./commerce/errors.js\";\nimport type { CommerceOptions } from \"./commerce/types.js\";\nimport { loadConfigFromDict } from \"./config.js\";\nimport type { BursarConfigData, CatalogRollout, ParsedBursarConfig } from \"./config/types.js\";\nimport { CapabilityNotConfiguredError, ConfigError, CatalogNotLoadedError } from \"./errors.js\";\nimport { projectPublicCatalog, type PublicCatalog } from \"./catalog.js\";\nimport type { CreditMetadata, GrantProgramAwardResult } from \"./credits/types/index.js\";\nimport { retryBursarOperation } from \"./retry.js\";\nexport type { BillingCapability, BillingEventSink } from \"./billing/contracts.js\";\nexport type { CommerceOptions } from \"./commerce/types.js\";\n\n/**\n * Stable public credit capability exposed by {@link Bursar}.\n *\n * The explicit method list prevents implementation helpers added to\n * `CreditsServiceImpl` from silently becoming public API.\n */\nexport type CreditsService = Pick<\n CreditsServiceImpl,\n | \"getUserPlan\"\n | \"checkFeature\"\n | \"getQuotaState\"\n | \"listQuotaEvents\"\n | \"startPlanMigration\"\n | \"migratePlanBatch\"\n | \"revokeCreditsByEntryType\"\n | \"executeGrantProgram\"\n | \"getLedgerEntry\"\n | \"getAvailable\"\n | \"aggregateStats\"\n | \"spendByUser\"\n | \"spendByModel\"\n | \"listLedgerEntries\"\n | \"listUsageEntries\"\n | \"listUsageCharges\"\n | \"topUsers\"\n | \"dailySpend\"\n | \"setUserPlan\"\n | \"unsetUserPlan\"\n | \"getBalance\"\n | \"addCredits\"\n | \"deductCredits\"\n | \"grantSubscriptionCycle\"\n | \"reserve\"\n | \"settle\"\n | \"release\"\n | \"renew\"\n | \"canAfford\"\n | \"getBucketBalances\"\n | \"checkAllowance\"\n | \"runBilled\"\n | \"beginBilledOperation\"\n | \"deduct\"\n | \"recordUsage\"\n | \"deductFlatJob\"\n | \"refundCredits\"\n | \"deductTeam\"\n | \"sweepExpiredCredits\"\n>;\n\ntype CatalogCreditsService = Pick<\n CreditsServiceImpl,\n | \"getActiveCatalog\"\n | \"loadCatalogFromStore\"\n | \"refreshCatalogIfStale\"\n | \"invalidateCatalog\"\n | \"publishAndActivateCatalog\"\n | \"publishCatalogDraft\"\n | \"activateCatalogRevision\"\n | \"pricingEngine\"\n | \"setPlanRevisionPin\"\n | \"applyDuePlanChanges\"\n>;\n\ninterface BaseBursarOptions {\n creditStore: CreditStore;\n creditsOptions?: CreditsServiceOptions;\n emitter?: CreditEventEmitter;\n}\n\n/** Credits-only construction rejects billing options that would otherwise be ignored. */\nexport interface CreditsOnlyBursarOptions extends BaseBursarOptions {\n billingStore?: undefined;\n billingOptions?: never;\n commerceOptions?: never;\n}\n\n/** Billing construction owns provisioning and may optionally enable commerce. */\nexport interface BillingBursarOptions extends BaseBursarOptions {\n billingStore: BillingStore;\n billingOptions?: Omit<BillingServiceOptions, \"provisioning\">;\n commerceOptions?: CommerceOptions;\n}\n\n/** Options for constructing the single application-facing Bursar service. */\nexport type BursarOptions = CreditsOnlyBursarOptions | BillingBursarOptions;\n\n/** Catalog operations. Configuration writes live here, never in BillingService. */\nexport class CatalogService {\n constructor(private readonly credits: CatalogCreditsService) {}\n\n /** Return the active persisted catalog revision, if one exists. */\n getActive() {\n return this.credits.getActiveCatalog();\n }\n\n /** Whether this process currently has a pricing engine loaded. */\n get isLoaded(): boolean {\n return this.credits.pricingEngine !== null;\n }\n\n /** Load the active persisted catalog into this process. */\n load(): Promise<void> {\n return this.credits.loadCatalogFromStore();\n }\n\n /** Block until a stale in-process catalog has been refreshed. */\n refresh(): Promise<void> {\n return this.credits.refreshCatalogIfStale();\n }\n\n /** Force the next refresh to reload the active catalog. */\n invalidate(): void {\n this.credits.invalidateCatalog();\n }\n\n async getConfig(): Promise<ParsedBursarConfig> {\n const active = await this.getActive();\n if (!active) throw new CatalogNotLoadedError(\"No active Bursar catalog is available\");\n return loadConfigFromDict(active.config);\n }\n\n async publicView(): Promise<PublicCatalog> {\n return projectPublicCatalog(await this.getConfig());\n }\n\n publishDraft(config: BursarConfigData, label?: string | null): Promise<string> {\n return this.credits.publishCatalogDraft(config, label);\n }\n\n activate(version: number, rollout?: CatalogRollout | null): Promise<string> {\n return this.credits.activateCatalogRevision(version, rollout);\n }\n\n publishAndActivate(\n config: BursarConfigData,\n label?: string | null,\n rollout?: CatalogRollout | null,\n ): Promise<string> {\n return this.credits.publishAndActivateCatalog(config, label, rollout);\n }\n\n /** Pin or unpin one current assignment from automatic catalog rollout. */\n setRevisionPin(userId: string, pinned: boolean): Promise<boolean> {\n return this.credits.setPlanRevisionPin(userId, pinned);\n }\n\n /** Apply one bounded batch of renewal-effective plan changes. */\n applyDueChanges(limit = 100): Promise<number> {\n return this.credits.applyDuePlanChanges(limit);\n }\n}\n\nexport interface AccountCreatedInput {\n accountId: string;\n eventKey: string;\n region?: string | null;\n metadata?: CreditMetadata | null;\n}\n\nexport interface AccountCreatedResult {\n accountId: string;\n planKey: string;\n planAssigned: boolean;\n grants: GrantProgramAwardResult[];\n}\n\n/** Generic financial lifecycle operations for SaaS accounts. */\nexport class AccountService {\n constructor(\n private readonly credits: CreditsService,\n private readonly catalog: CatalogService,\n ) {}\n\n async onAccountCreated(input: AccountCreatedInput): Promise<AccountCreatedResult> {\n if (typeof input.accountId !== \"string\" || !input.accountId.trim()) {\n throw new TypeError(\"accountId must be a non-empty string\");\n }\n if (typeof input.eventKey !== \"string\" || !input.eventKey.trim()) {\n throw new TypeError(\"eventKey must be a non-empty string\");\n }\n const config = await retryBursarOperation(() => this.catalog.getConfig());\n const planKey = config.catalog.defaultPlan;\n if (!planKey) throw new ConfigError(\"The active catalog has no default account plan\");\n\n const current = await retryBursarOperation(() => this.credits.getUserPlan(input.accountId));\n const planAssigned = current.planKey == null;\n if (planAssigned) {\n await retryBursarOperation(() => this.credits.setUserPlan(input.accountId, planKey));\n }\n\n const grants: GrantProgramAwardResult[] = [];\n for (const [programKey, program] of Object.entries(config.credits.grantPrograms).sort(\n ([a], [b]) => a.localeCompare(b),\n )) {\n if (program.trigger !== \"account_created\") continue;\n grants.push(\n ...(await retryBursarOperation(() =>\n this.credits.executeGrantProgram({\n trigger: \"account_created\",\n programKey,\n subjectId: input.accountId,\n eventKey: input.eventKey,\n region: input.region,\n metadata: input.metadata,\n }),\n )),\n );\n }\n return {\n accountId: input.accountId,\n planKey: current.planKey ?? planKey,\n planAssigned,\n grants,\n };\n }\n}\n\n/**\n * The application-facing Bursar boundary.\n *\n * Credit and billing services are deliberately created together so consumers\n * cannot accidentally construct unrelated services for the same account\n * lifecycle. Provider and application integrations use this facade rather\n * than constructing lifecycle services independently.\n */\nexport class Bursar implements BillingEventSink {\n readonly credits: CreditsService;\n readonly billing: BillingCapability | null;\n readonly commerce: CommerceServiceImpl | null;\n readonly catalog: CatalogService;\n readonly accounts: AccountService;\n\n constructor(options: BursarOptions) {\n if (typeof options !== \"object\" || options === null) {\n throw new TypeError(\"Bursar options are required\");\n }\n if (options.billingStore === null) {\n throw new TypeError(\"billingStore must be a BillingStore when provided\");\n }\n for (const optionName of [\n \"creditsOptions\",\n \"billingOptions\",\n \"commerceOptions\",\n \"emitter\",\n ] as const) {\n if (options[optionName] === null) {\n throw new TypeError(`${optionName} must not be null`);\n }\n }\n if (\n options.billingStore === undefined &&\n (options.billingOptions !== undefined || options.commerceOptions !== undefined)\n ) {\n throw new TypeError(\"billingOptions and commerceOptions require billingStore\");\n }\n if (options.billingOptions && \"provisioning\" in options.billingOptions) {\n throw new TypeError(\"billingOptions.provisioning is owned by Bursar\");\n }\n const environments = [\n [\"creditStore\", options.creditStore.providerEnvironment],\n [\"billingStore\", options.billingStore?.providerEnvironment],\n [\"commerceOptions\", options.commerceOptions?.providerEnvironment],\n ].filter((entry): entry is [string, NonNullable<(typeof entry)[1]>] => entry[1] !== undefined);\n if (new Set(environments.map(([, environment]) => environment)).size > 1) {\n throw new TypeError(\n `Bursar provider environments must match: ${environments\n .map(([name, environment]) => `${name}=${environment}`)\n .join(\", \")}`,\n );\n }\n const credits = new CreditsServiceImpl(\n options.creditStore,\n undefined,\n options.emitter ?? undefined,\n options.creditsOptions ?? undefined,\n );\n this.credits = credits;\n this.catalog = new CatalogService(credits);\n this.accounts = new AccountService(credits, this.catalog);\n\n this.billing = options.billingStore\n ? new BillingEventService(options.billingStore, {\n ...(options.billingOptions ?? {}),\n provisioning: credits,\n })\n : null;\n this.commerce =\n this.billing && options.commerceOptions\n ? new CommerceServiceImpl(this.billing, credits, this, options.commerceOptions)\n : null;\n if (this.commerce) {\n credits.addPostDeductionHook(async ({ userId }) => {\n await this.commerce!.autoRecharge.processIfNeeded({ accountId: userId });\n });\n }\n }\n\n /** Load the active catalog into the pricing engine. */\n async loadCatalog(): Promise<void> {\n await this.catalog.load();\n }\n\n /** Return billing or raise the SDK's typed configuration error. */\n requireBilling(): BillingCapability {\n if (!this.billing) {\n throw new CapabilityNotConfiguredError(\"billing\");\n }\n return this.billing;\n }\n\n /** Return commerce or raise the SDK's typed configuration error. */\n requireCommerce(): CommerceServiceImpl {\n if (!this.commerce) {\n throw new CommerceNotConfiguredError(\"Bursar commerce capability is not configured\");\n }\n return this.commerce;\n }\n\n /**\n * Ingest a normalized provider event through the facade-owned billing\n * lifecycle. Providers must not depend on BillingService directly.\n */\n async ingestBillingEvent(event: BillingEvent): Promise<BillingEventResult> {\n return this.requireBilling().ingestBillingEvent(event);\n }\n}\n"]}
|
package/dist/catalog.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"catalog.d.ts","sourceRoot":"","sources":["../src/catalog.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,YAAY,EAAE,kBAAkB,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAEjG,MAAM,WAAW,mBAAmB;IAClC,IAAI,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC;IACrB,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,WAAW,kBAAkB;IACjC,GAAG,EAAE,MAAM,CAAC;IACZ,IAAI,EAAE,aAAa,CAAC,MAAM,CAAC,CAAC;IAC5B,WAAW,EAAE,MAAM,CAAC;IACpB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,SAAS,EAAE,MAAM,CAAC;IAClB,KAAK,EAAE;QACL,WAAW,EAAE,MAAM,CAAC;QACpB,QAAQ,EAAE,MAAM,CAAC;QACjB,WAAW,EAAE,WAAW,GAAG,WAAW,GAAG,aAAa,CAAC;KACxD,CAAC;IACF,eAAe,CAAC,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC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C;KAC7B,CAAC;IACF,MAAM,EAAE,MAAM,CACZ,MAAM,EACN;QACE,SAAS,EAAE,MAAM,CAAC;QAClB,OAAO,EAAE,MAAM,CAAC;QAChB,KAAK,EAAE,MAAM,CAAC;QACd,MAAM,EAAE,mBAAmB,CAAC;QAC5B,WAAW,EAAE,OAAO,GAAG,OAAO,CAAC;KAChC,CACF,CAAC;IACF,MAAM,EAAE,kBAAkB,EAAE,CAAC;CAC9B;AAED,MAAM,WAAW,aAAa;IAC5B,OAAO,EAAE,CAAC,CAAC;IACX,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,aAAa,EAAE;QACb,QAAQ,EAAE,MAAM,CAAC;QACjB,aAAa,EAAE,MAAM,CAAC;KACvB,GAAG,IAAI,CAAC;IACT,KAAK,EAAE,iBAAiB,EAAE,CAAC;IAC3B,MAAM,EAAE,kBAAkB,EAAE,CAAC;CAC9B;AAgDD,8EAA8E;AAC9E,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,kBAAkB,GAAG,aAAa,CA0D9E"}
|
package/dist/catalog.js
CHANGED
|
@@ -79,7 +79,7 @@ export function projectPublicCatalog(config) {
|
|
|
79
79
|
.sort((a, b) => a.rank - b.rank || a.key.localeCompare(b.key));
|
|
80
80
|
return {
|
|
81
81
|
version: 1,
|
|
82
|
-
defaultPlan: config.catalog.defaultPlan ??
|
|
82
|
+
defaultPlan: config.catalog.defaultPlan ?? null,
|
|
83
83
|
creditDisplay: config.credits.display
|
|
84
84
|
? {
|
|
85
85
|
currency: config.credits.display.currency,
|