@tofound/billing 0.1.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/CHANGELOG.md +136 -1
  2. package/README.md +73 -13
  3. package/dist/catalog/catalog.d.ts +115 -0
  4. package/dist/catalog/catalog.js +201 -0
  5. package/dist/domain/types.d.ts +3 -1
  6. package/dist/drizzle/index.d.ts +2 -0
  7. package/dist/drizzle/index.js +2 -0
  8. package/dist/entitlement/resolve.d.ts +76 -0
  9. package/dist/entitlement/resolve.js +122 -0
  10. package/dist/hostkit/adjustments.d.ts +65 -0
  11. package/dist/hostkit/adjustments.js +84 -0
  12. package/dist/hostkit/index.d.ts +9 -0
  13. package/dist/hostkit/index.js +9 -0
  14. package/dist/hostkit/legacy-ledger.d.ts +87 -0
  15. package/dist/hostkit/legacy-ledger.js +111 -0
  16. package/dist/hostkit/quote-wire.d.ts +73 -0
  17. package/dist/hostkit/quote-wire.js +50 -0
  18. package/dist/index.d.ts +10 -0
  19. package/dist/index.js +9 -0
  20. package/dist/providers/apple/events.d.ts +24 -0
  21. package/dist/providers/apple/events.js +232 -0
  22. package/dist/providers/apple/index.d.ts +54 -0
  23. package/dist/providers/apple/index.js +231 -0
  24. package/dist/providers/apple/jws.d.ts +50 -0
  25. package/dist/providers/apple/jws.js +206 -0
  26. package/dist/providers/google/api.d.ts +57 -0
  27. package/dist/providers/google/api.js +226 -0
  28. package/dist/providers/google/events.d.ts +46 -0
  29. package/dist/providers/google/events.js +135 -0
  30. package/dist/providers/google/index.d.ts +37 -0
  31. package/dist/providers/google/index.js +228 -0
  32. package/dist/providers/polar/events.d.ts +17 -0
  33. package/dist/providers/polar/events.js +213 -0
  34. package/dist/providers/polar/index.d.ts +50 -0
  35. package/dist/providers/polar/index.js +271 -0
  36. package/dist/providers/polar/signature.d.ts +23 -0
  37. package/dist/providers/polar/signature.js +52 -0
  38. package/dist/providers/port.d.ts +6 -0
  39. package/dist/providers/sepay/index.js +29 -0
  40. package/dist/renewal/renewal.d.ts +69 -0
  41. package/dist/renewal/renewal.js +198 -0
  42. package/dist/stores/testing.d.ts +4 -2
  43. package/dist/stores/testing.js +4 -2
  44. package/dist/terms/conformance.d.ts +17 -0
  45. package/dist/terms/conformance.js +198 -0
  46. package/dist/terms/decide.d.ts +97 -0
  47. package/dist/terms/decide.js +176 -0
  48. package/dist/terms/drizzle.d.ts +12 -0
  49. package/dist/terms/drizzle.js +131 -0
  50. package/dist/terms/memory.d.ts +23 -0
  51. package/dist/terms/memory.js +126 -0
  52. package/dist/terms/plans.d.ts +85 -0
  53. package/dist/terms/plans.js +331 -0
  54. package/dist/terms/ports.d.ts +55 -0
  55. package/dist/terms/ports.js +1 -0
  56. package/dist/terms/rules.d.ts +11 -0
  57. package/dist/terms/rules.js +36 -0
  58. package/dist/terms/schema.d.ts +711 -0
  59. package/dist/terms/schema.js +70 -0
  60. package/dist/terms/snapshot.d.ts +20 -0
  61. package/dist/terms/snapshot.js +134 -0
  62. package/dist/terms/types.d.ts +85 -0
  63. package/dist/terms/types.js +4 -0
  64. package/docs/API.md +415 -6
  65. package/docs/MIGRATION-LOHI.md +237 -0
  66. package/docs/SCHEMA.md +57 -2
  67. package/package.json +22 -1
package/CHANGELOG.md CHANGED
@@ -1,7 +1,142 @@
1
1
  # Changelog
2
2
 
3
3
  All notable changes to `@tofound/billing`. Versions follow semver; 0.x minors
4
- are additive.
4
+ were additive. From 1.0.0 the public API is frozen: removing or narrowing
5
+ anything in the declaration snapshot is a major version.
6
+
7
+ ## 1.0.0 — 2026-10-24
8
+
9
+ The 1.0 API freeze. Every 0.2 export is unchanged (changes since 0.2.0 are
10
+ the host kit, the Apple and Google adapters, the SePay tightening and the
11
+ API snapshot below); from here on any breaking API change is a major version.
12
+
13
+ To adopt: pin `@tofound/billing@1.0.0`. No schema change: no factory table
14
+ gained a column.
15
+
16
+ - **API freeze:** the public-api contract test snapshots the export names and
17
+ emitted declarations of every entry point. 1.0.0 is that snapshot.
18
+ - **Host kit** (`@tofound/billing/hostkit`, new entry point) for hosts that
19
+ keep their own tables and wire. Lohi first; see `docs/MIGRATION-LOHI.md`.
20
+ - `createLegacyLedgerStore(driver, codec)` builds a full `LedgerStore` over
21
+ a host's legacy wallet tables from a small driver of row I/O:
22
+ - seq is derived from `(createdAt, id)` order, and new rows are kept
23
+ strictly after the newest one;
24
+ - key-less pre-adapter rows read as `legacy:<id>`;
25
+ - the host reason column is written by `reasonOf`, and the kind of an old
26
+ row is read by `kindOf`.
27
+
28
+ A Lohi-shaped driver passes the full ledger store conformance suite on
29
+ memory and Postgres.
30
+ - `createAdminAdjustments({ store, overdraft })` handles operator balance
31
+ adjustments: one `adjustment` entry per request id, posted under the
32
+ account lock. A stale `expectedBalance` answers `balance_changed` and
33
+ posts nothing. Overdraft policy is `reject` (`insufficient_credits`) or
34
+ `clamp` (take what is there and report the `shortfall`). It runs in its
35
+ own transaction or in the host's.
36
+ - `serializeQuote` / `serializePlanQuote` produce the served quote:
37
+ - Lohi's key order, with unset optionals left out;
38
+ - labels only from a host labeler, so a host serving codes alone passes
39
+ none;
40
+ - the legacy `subscriptionCovered` key on request;
41
+ - plan periods as ISO strings.
42
+ - **Apple** (`@tofound/billing/providers/apple`, new entry point):
43
+ `createAppleAdapter`. Covers App Store Server Notifications v2 and
44
+ StoreKit 2 client proofs, verified through the JWS `x5c` chain to the pinned
45
+ Apple Root CA G3. One-time (consumable) purchases are keyed by transaction.
46
+ Refunds, refund reversals and revokes apply once, ordered by `signedDate`.
47
+ Auto-renewable notifications become subscription snapshots. Consumption
48
+ reporting goes through the App Store Server API.
49
+ - **Google** (`@tofound/billing/providers/google`, new entry point):
50
+ `createGoogleAdapter`. Covers Play RTDN over Pub/Sub push, with the OIDC
51
+ token verified. A purchase is trusted only as Play's own `products.get`
52
+ answer. A voided purchase, from RTDN or from `voidedpurchases.list`
53
+ (`listChangesSince`), is clawed back once. Subscription notifications are
54
+ acknowledged as ignored.
55
+ - **SePay:**
56
+ - `order.user_agent` (any `user_agent` key) is dropped from stored inbox
57
+ payloads, on top of the generic redaction.
58
+ - An IPN whose `transaction.transaction_amount` disagrees with
59
+ `order.order_amount` goes to `needs_review` with reason
60
+ `amount_mismatch` and credits (or reverses) nothing. The comparison uses
61
+ the magnitude, so a void reported as a negative movement still matches.
62
+ - Public types are unchanged.
63
+ - **Package:** ships `docs/MIGRATION-LOHI.md`.
64
+
65
+ ## 0.2.0 — 2026-10-18
66
+
67
+ Additive to 0.1: every 0.1 export is unchanged (public-api declaration
68
+ snapshot only grows). One type widens: `BillingErrorCode` gains five members
69
+ (below), so an exhaustive `switch` over it in a consumer needs the new cases
70
+ (or a `default`) to typecheck.
71
+
72
+ To adopt: pin `@tofound/billing@0.2.0`. If you use terms, export the tables
73
+ `createTermTables` returns from your drizzle schema and run `db:generate`.
74
+
75
+ - Catalog as config (`defineCatalog`): plans with strict ranks and one free
76
+ plan, N-month credit offers per market, provider offers by `productRef`,
77
+ credit packs and policies (`termDays`, `upgradeProration`, `graceDays`,
78
+ `renewalLeadSec`). Validated and frozen at boot (`invalid_catalog`).
79
+ - Terms (`Term`, `TermStore`): one shape for credit, Polar, Apple and Google
80
+ subscriptions; memory store and Drizzle tables/store (`createTermTables`,
81
+ `createDrizzleTermStore`, `termTableNames` in `/drizzle`); term store
82
+ conformance cases in `/testing`. **Schema:** two new tables,
83
+ `<prefix>terms` and the per-account lock row `<prefix>term_accounts` —
84
+ add `createTermTables(...)` to your drizzle schema and run `db:generate`
85
+ (additive: new tables and indexes only).
86
+ - Entitlement (`resolveEntitlement`): stacking S1–S5 across sources —
87
+ highest rank wins, then the later end; credit terms carry no included pool;
88
+ warnings `two_subscriptions`, `past_due`, `renewal_shortfall`,
89
+ `scheduled_downgrade`; nothing entitled → the free plan.
90
+ - Plans (`createPlans`): quote and buy N months with credits through one
91
+ waterfall — new, extend (S2), upgrade with host-policy proration
92
+ (`remaining_time`: ceil(remaining/total × (offerNew − paid)), end date kept;
93
+ or `none`), renew a past_due term, downgrade scheduled with no money moved
94
+ (S3b), blocked when a renewing subscription of ≥ rank covers it (S3,
95
+ `plan_blocked`); idempotent purchase keys; auto-renew on/off, cancel,
96
+ cancel now.
97
+ - Renewal (`createRenewal`): charges the live catalog price at period end
98
+ (`renew:<termId>:<periodEnd>`, a double run debits once); a short balance →
99
+ `past_due` with `graceDays` of entitlement; `retryPastDue` after a top-up
100
+ renews from the old end; grace passed → expired → free; scheduled terms
101
+ activate when they start; a failed early attempt (`renewalLeadSec`) keeps
102
+ the paid period active and is retried by the next run.
103
+ - Provider subscriptions (`createSnapshotHandler` for the ingest
104
+ `subscription.snapshot` slot): upserts the provider term under a watermark;
105
+ an entitled subscription of ≥ rank supersedes the credit term and refunds
106
+ its unused share pro rata (`plan_refund`, `supersede:<termId>`, rounded up);
107
+ an account `resolveAccount` does not know is ignored as unmatched and
108
+ relayed through `onUnmatched`.
109
+ - Polar adapter (`@tofound/billing/providers/polar`, new entry point):
110
+ `createPolarAdapter` for the ingest inbox, with Standard Webhooks
111
+ verification before any parse (both secret derivations, a rotation list,
112
+ a 300 s replay window). It normalizes three kinds of event:
113
+ - subscriptions → `subscription.snapshot`, for `createSnapshotHandler`;
114
+ - one-time **credit-pack orders** bound to a checkout session →
115
+ `purchase.completed`, credited once;
116
+ - **full refunds** → `purchase.reversed` (a ledger reversal). A partial
117
+ refund goes to `needs_review`.
118
+
119
+ An order's amount is the catalog price, `subtotal_amount −
120
+ discount_amount`, so tax-inclusive (EU buyers under tax behaviour
121
+ `location`), tax-exclusive and untaxed orders all credit the full pack;
122
+ refunds use the same basis. Polar's same-instant subscription events (one
123
+ revoke as `updated`, `canceled`, `revoked`) are ordered by type through the
124
+ new optional `SubscriptionSnapshotEvent.tieBreak`, which the snapshot handler
125
+ compares before the event id, and the period ends at `ended_at`.
126
+ `redactPolarPayload` also scrubs Polar secrets inside values, such as the
127
+ checkout client secret in a checkout `url`.
128
+
129
+ `createCheckout` opens one-time checkouts and `createPortalSession` opens
130
+ customer portal sessions. `resolvePolarEnvironment` makes the environment
131
+ explicit and refuses an unarmed production. Also exported:
132
+ `respondPolar`, `redactPolarPayload`, `signPolarWebhook` (test
133
+ deliveries), `PolarApiError` and the webhook header constants.
134
+ - Error codes: `invalid_catalog`, `plan_not_found`, `offer_not_found`,
135
+ `term_not_found`, `plan_blocked`. They widen the `BillingErrorCode` union,
136
+ so check exhaustive switches.
137
+ - Docs: the README describes 0.2 and links only to files shipped in the
138
+ package (no private-repo links). `docs/SCHEMA.md` names the tables each
139
+ factory returns. `docs/API.md` documents the `walletDelta` sign.
5
140
 
6
141
  ## 0.1.0 — 2026-10-17
7
142
 
package/README.md CHANGED
@@ -4,15 +4,26 @@
4
4
  products (2Novel first, the Lohi reader api last). Each host API embeds it on
5
5
  its own database; there is no billing service.
6
6
 
7
- 0.1 ships the money core: an idempotent, no-overdraft credit ledger behind
8
- store ports, memory and Drizzle/Postgres stores, a Drizzle schema factory the
9
- host re-exports and migrates itself, one quote/charge waterfall, a payment
10
- webhook inbox (verify → persist → apply exactly once) and the SePay adapter
11
- (`@tofound/billing/providers/sepay`). Terms, entitlement and the Polar, Apple
12
- and Google adapters land in later versions.
7
+ 1.0 ships (the public API is frozen from 1.0.0 on):
8
+
9
+ - **The money core** (since 0.1): an idempotent, no-overdraft credit ledger
10
+ behind store ports, memory and Drizzle/Postgres stores, a Drizzle schema
11
+ factory the host re-exports and migrates itself, one quote/charge waterfall
12
+ and a payment webhook inbox (verify → persist → apply exactly once).
13
+ - **Catalog, terms and entitlement** (0.2): the catalog as host config
14
+ (`defineCatalog`), subscription terms from credits, Polar, Apple and Google in
15
+ one shape, `resolveEntitlement` (stacking rules S1–S5), buying N months with
16
+ credits (`createPlans`: extend, prorated upgrade, scheduled downgrade),
17
+ renewal at the live price with `past_due` + grace (`createRenewal`), and
18
+ provider snapshots that supersede a credit term with a pro-rata refund
19
+ (`createSnapshotHandler`).
20
+ - **Providers**: SePay (`@tofound/billing/providers/sepay`), Polar
21
+ (`@tofound/billing/providers/polar`, 0.2), and, new in 1.0, the App Store
22
+ (`@tofound/billing/providers/apple`) and Google Play
23
+ (`@tofound/billing/providers/google`) adapters.
13
24
 
14
25
  ```sh
15
- bun add @tofound/billing@0.1.0 --exact # peer: drizzle-orm ^0.45 for /drizzle
26
+ bun add @tofound/billing@1.0.0 --exact # peer: drizzle-orm ^0.45 for /drizzle
16
27
  ```
17
28
 
18
29
  ```ts
@@ -26,10 +37,59 @@ const ledger = createLedger({ store: createDrizzleLedgerStore({ db, tables: { bi
26
37
  await db.transaction((tx) => ledger.in(tx).debit({ accountId, kind: 'spend', amount, idempotencyKey: `job:${id}:charge` }))
27
38
  ```
28
39
 
29
- - [docs/API.md](docs/API.md) — ledger, ports, waterfall, error codes
30
- - [docs/SCHEMA.md](docs/SCHEMA.md) — schema factory and the additive migration rules
31
- - [RELEASE.md](RELEASE.md) — how a version is checked, packed and published
32
- - Contracts other work builds against: [.babysit/contracts.yaml](.babysit/contracts.yaml)
40
+ Plans, terms and entitlement run on the same `db`:
41
+
42
+ ```ts
43
+ import { createPlans, createRenewal, defineCatalog, resolveEntitlement } from '@tofound/billing'
44
+ import { createDrizzleTermStore, createTermTables } from '@tofound/billing/drizzle'
45
+
46
+ export const { billingTerms, billingTermAccounts } = createTermTables({ accountId: (n) => uuid(n).notNull() })
47
+ const catalog = defineCatalog(hostCatalogConfig) // plans, prices, policies: the host's data, never the library's
48
+ const terms = createDrizzleTermStore({ db, tables: { billingTerms, billingTermAccounts } })
49
+ const plans = createPlans({ ledger, terms, catalog })
50
+ const renewal = createRenewal({ ledger, terms, catalog })
51
+ const ent = resolveEntitlement(await terms.reader().listTerms(accountId), new Date(), catalog)
52
+ ```
53
+
54
+ ## Polar
55
+
56
+ `@tofound/billing/providers/polar` is a webhook and checkout adapter for the
57
+ ingest inbox. `createPolarAdapter({ environment, webhookSecrets, products,
58
+ accessToken })` verifies Standard Webhooks signatures (secret rotation, 300 s
59
+ replay window) before parsing. It normalizes Polar subscriptions to
60
+ `subscription.snapshot` (applied by `createSnapshotHandler`), one-time credit
61
+ pack orders to `purchase.completed` and full refunds to `purchase.reversed`.
62
+ It also opens checkouts (`createCheckout`) and customer portal sessions.
63
+ `resolvePolarEnvironment` turns the host's environment and production-arming
64
+ switches into one required value. `signPolarWebhook` signs test deliveries.
65
+ The full entry is in `docs/API.md`.
66
+
67
+ ## Host kit
68
+
69
+ `@tofound/billing/hostkit` (new in 1.0) is for hosts that keep their own
70
+ tables and wire. It provides:
71
+ - `createLegacyLedgerStore`, a full `LedgerStore` over legacy wallet tables
72
+ built from a small driver of row I/O;
73
+ - `createAdminAdjustments`, for operator balance adjustments on the ledger;
74
+ - `serializeQuote` / `serializePlanQuote`, which turn a `Quote` into the
75
+ served JSON.
76
+
77
+ `docs/MIGRATION-LOHI.md` walks the Lohi reader API through it.
78
+
79
+ ## Documentation
80
+
81
+ These files ship inside the package (`node_modules/@tofound/billing/…`):
82
+
83
+ - `docs/API.md`: ledger, ports, waterfall, inbox, providers, catalog, terms,
84
+ entitlement, renewal and error codes.
85
+ - `docs/MIGRATION-LOHI.md`: moving the Lohi reader API onto the library with
86
+ the host kit.
87
+ - `docs/SCHEMA.md`: the schema factory, the tables each factory returns and the
88
+ additive migration rules.
89
+ - `CHANGELOG.md`: what each version adds, and what a host must do to adopt it.
33
90
 
34
- Develop with bun ≥ 1.3.14: `bun install`, then `bun run check` (needs a local
35
- Postgres `initdb`, see RELEASE.md).
91
+ Develop with bun ≥ 1.3.14: `bun install`, then `bun run check` (typecheck,
92
+ build, tests on memory and Postgres, pack smoke). It needs a local Postgres
93
+ `initdb` (`PG_BIN` or a Homebrew `postgresql@17`), or
94
+ `BILLING_TEST_DATABASE_URL`, in which it creates a throwaway schema. Never
95
+ point it at a shared or production database.
@@ -0,0 +1,115 @@
1
+ import type { CreditUnit, Currency, Money } from '../domain/types.js';
2
+ /** A market the host prices in; the API sets it per account, the user never picks it (D11). */
3
+ export interface MarketSpec {
4
+ key: string;
5
+ currency: Currency;
6
+ }
7
+ /** N months of a plan bought with credits (the VN path). */
8
+ export interface CreditOffer {
9
+ source: 'credit';
10
+ market: string;
11
+ months: number;
12
+ /** Credit minor units for the whole `months`. */
13
+ credits: number;
14
+ }
15
+ /** A provider-billed offer; `productRef` maps to the provider's product id in host config. */
16
+ export interface ProviderOffer {
17
+ source: 'polar' | 'apple' | 'google';
18
+ productRef: string;
19
+ market?: string;
20
+ interval?: 'month' | 'year';
21
+ price?: Money;
22
+ /** Google base plan id. */
23
+ basePlan?: string;
24
+ }
25
+ export type PlanOffer = CreditOffer | ProviderOffer;
26
+ export interface PlanSpec {
27
+ key: string;
28
+ /** Strictly ordered across plans; higher wins (S1). */
29
+ rank: number;
30
+ /** The plan an account without an entitled term resolves to. Exactly one, the lowest rank, with no offers. */
31
+ free?: boolean;
32
+ permissions?: readonly string[];
33
+ quotas?: Readonly<Record<string, number>>;
34
+ /** Per-period credit pool of provider-funded terms only (A1). */
35
+ includedCredits?: number;
36
+ offers?: readonly PlanOffer[];
37
+ }
38
+ export type PackProvider = 'sepay' | 'polar' | 'apple' | 'google';
39
+ export interface CreditPackSpec {
40
+ key: string;
41
+ market: string;
42
+ provider: PackProvider;
43
+ price: Money;
44
+ credits: number;
45
+ bonusCredits?: number;
46
+ productRef?: string;
47
+ }
48
+ export type UpgradeProration = 'remaining_time' | 'none';
49
+ export type ReversalShortfallPolicy = 'lapse_credit_terms' | 'record';
50
+ export interface CatalogPolicies {
51
+ /** Days in one catalog month; a term of N months lasts N × termDays. */
52
+ termDays: number;
53
+ /** 2Novel `remaining_time`, Lohi `none` (D8). */
54
+ upgradeProration: UpgradeProration;
55
+ /** Days a failed renewal stays entitled as `past_due` (D9). */
56
+ graceDays: number;
57
+ reversalShortfall: ReversalShortfallPolicy;
58
+ /** How early `renewDue` may renew before the period end. */
59
+ renewalLeadSec: number;
60
+ }
61
+ export declare const DEFAULT_POLICIES: Readonly<CatalogPolicies>;
62
+ export interface CatalogSpec {
63
+ version: string | number;
64
+ creditUnit: CreditUnit;
65
+ markets: readonly MarketSpec[];
66
+ plans: readonly PlanSpec[];
67
+ creditPacks?: readonly CreditPackSpec[];
68
+ policies?: Partial<CatalogPolicies>;
69
+ /** Longest plan/pack key the host can store (Lohi `user_subscriptions.tier` is 16). Default 64. */
70
+ maxKeyLength?: number;
71
+ }
72
+ export interface Plan {
73
+ key: string;
74
+ rank: number;
75
+ free: boolean;
76
+ permissions: readonly string[];
77
+ quotas: Readonly<Record<string, number>>;
78
+ includedCredits: number | null;
79
+ offers: readonly PlanOffer[];
80
+ }
81
+ export type CreditPack = Readonly<Required<Omit<CreditPackSpec, 'productRef'>>> & {
82
+ readonly productRef: string | null;
83
+ };
84
+ export type ProductMatch = {
85
+ kind: 'plan';
86
+ plan: Plan;
87
+ offer: ProviderOffer;
88
+ } | {
89
+ kind: 'pack';
90
+ pack: CreditPack;
91
+ };
92
+ export interface Catalog {
93
+ readonly version: string | number;
94
+ readonly creditUnit: CreditUnit;
95
+ readonly markets: readonly MarketSpec[];
96
+ readonly policies: Readonly<CatalogPolicies>;
97
+ /** Every plan, lowest rank first. */
98
+ readonly plans: readonly Plan[];
99
+ readonly creditPacks: readonly CreditPack[];
100
+ readonly freePlan: Plan;
101
+ /** Throws `plan_not_found`. */
102
+ plan(key: string): Plan;
103
+ findPlan(key: string): Plan | undefined;
104
+ plansWithPermission(permission: string): Plan[];
105
+ market(key: string): MarketSpec | undefined;
106
+ creditOffer(plan: string, market: string, months: number): CreditOffer | undefined;
107
+ /** Credit offers of a plan in a market, fewest months first. */
108
+ creditOffers(plan: string, market: string): CreditOffer[];
109
+ pack(key: string): CreditPack | undefined;
110
+ packsFor(market: string, provider?: PackProvider): CreditPack[];
111
+ /** The plan offer or credit pack a provider product ref names. */
112
+ offerByProductRef(productRef: string): ProductMatch | undefined;
113
+ }
114
+ /** Validate and freeze a host catalog. */
115
+ export declare function defineCatalog(spec: CatalogSpec): Catalog;
@@ -0,0 +1,201 @@
1
+ /**
2
+ * Catalog as config (design §4.4). The library ships no plan, price or tier
3
+ * literal: a host passes its own catalog values to `defineCatalog`, which
4
+ * validates and freezes them and answers the lookups the terms, renewal and
5
+ * entitlement code need. Errors are `BillingError('invalid_catalog')` at
6
+ * definition time, so a broken catalog fails at boot, not at checkout.
7
+ */
8
+ import { BillingError } from '../domain/errors.js';
9
+ import { CURRENCY_EXPONENT } from '../domain/money.js';
10
+ export const DEFAULT_POLICIES = Object.freeze({
11
+ termDays: 30,
12
+ upgradeProration: 'remaining_time',
13
+ graceDays: 3,
14
+ reversalShortfall: 'record',
15
+ renewalLeadSec: 0,
16
+ });
17
+ const KEY = /^[a-z0-9][a-z0-9_.-]*$/;
18
+ function fail(message, details = {}) {
19
+ throw new BillingError('invalid_catalog', message, details);
20
+ }
21
+ function safeInt(value, what, min) {
22
+ if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < min)
23
+ fail(`${what} must be a safe integer ≥ ${min}, got ${String(value)}`);
24
+ return value;
25
+ }
26
+ /** Validate and freeze a host catalog. */
27
+ export function defineCatalog(spec) {
28
+ const maxKeyLength = spec.maxKeyLength ?? 64;
29
+ safeInt(maxKeyLength, 'maxKeyLength', 1);
30
+ const checkKey = (key, what) => {
31
+ if (typeof key !== 'string' || !KEY.test(key))
32
+ fail(`${what} key must be lower-case [a-z0-9_.-], got ${JSON.stringify(key)}`);
33
+ if (key.length > maxKeyLength)
34
+ fail(`${what} key ${key} is longer than ${maxKeyLength}`, { key });
35
+ return key;
36
+ };
37
+ const unit = spec.creditUnit;
38
+ if (!unit?.code || !Number.isInteger(unit.exponent) || unit.exponent < 0 || unit.exponent > 6)
39
+ fail('creditUnit needs a code and an exponent 0..6');
40
+ const policies = { ...DEFAULT_POLICIES, ...(spec.policies ?? {}) };
41
+ safeInt(policies.termDays, 'policies.termDays', 1);
42
+ safeInt(policies.graceDays, 'policies.graceDays', 0);
43
+ safeInt(policies.renewalLeadSec, 'policies.renewalLeadSec', 0);
44
+ if (!['remaining_time', 'none'].includes(policies.upgradeProration))
45
+ fail(`unknown upgradeProration ${policies.upgradeProration}`);
46
+ if (!['lapse_credit_terms', 'record'].includes(policies.reversalShortfall))
47
+ fail(`unknown reversalShortfall ${policies.reversalShortfall}`);
48
+ if (!spec.markets?.length)
49
+ fail('a catalog needs at least one market');
50
+ const markets = new Map();
51
+ for (const m of spec.markets) {
52
+ checkKey(m.key, 'market');
53
+ if (markets.has(m.key))
54
+ fail(`duplicate market ${m.key}`);
55
+ if (!Object.hasOwn(CURRENCY_EXPONENT, m.currency))
56
+ fail(`market ${m.key}: unknown currency ${m.currency}`);
57
+ markets.set(m.key, Object.freeze({ key: m.key, currency: m.currency }));
58
+ }
59
+ const checkMoney = (price, market, what) => {
60
+ if (!price)
61
+ return;
62
+ if (!Object.hasOwn(CURRENCY_EXPONENT, price.currency))
63
+ fail(`${what}: unknown currency ${price.currency}`);
64
+ safeInt(price.amountMinor, `${what} price`, 1);
65
+ const m = market === undefined ? undefined : markets.get(market);
66
+ if (m && m.currency !== price.currency)
67
+ fail(`${what}: price in ${price.currency} but market ${m.key} prices in ${m.currency}`);
68
+ };
69
+ const checkMarket = (market, what) => {
70
+ if (market !== undefined && !markets.has(market))
71
+ fail(`${what}: unknown market ${market}`);
72
+ };
73
+ const productRefs = new Map();
74
+ const claimRef = (ref, match, what) => {
75
+ if (typeof ref !== 'string' || !ref)
76
+ fail(`${what}: productRef is required`);
77
+ if (productRefs.has(ref))
78
+ fail(`duplicate productRef ${ref}`, { productRef: ref });
79
+ productRefs.set(ref, match);
80
+ };
81
+ if (!spec.plans?.length)
82
+ fail('a catalog needs at least one plan');
83
+ const byKey = new Map();
84
+ const ranks = new Set();
85
+ for (const p of spec.plans) {
86
+ checkKey(p.key, 'plan');
87
+ if (byKey.has(p.key))
88
+ fail(`duplicate plan ${p.key}`);
89
+ safeInt(p.rank, `plan ${p.key} rank`, 0);
90
+ if (ranks.has(p.rank))
91
+ fail(`plan ranks must be strictly ordered; rank ${p.rank} repeats at ${p.key}`);
92
+ ranks.add(p.rank);
93
+ for (const [name, value] of Object.entries(p.quotas ?? {}))
94
+ safeInt(value, `plan ${p.key} quota ${name}`, 0);
95
+ if (p.includedCredits !== undefined)
96
+ safeInt(p.includedCredits, `plan ${p.key} includedCredits`, 0);
97
+ const offers = [];
98
+ const plan = {
99
+ key: p.key,
100
+ rank: p.rank,
101
+ free: p.free === true,
102
+ permissions: Object.freeze([...(p.permissions ?? [])]),
103
+ quotas: Object.freeze({ ...(p.quotas ?? {}) }),
104
+ includedCredits: p.includedCredits ?? null,
105
+ offers,
106
+ };
107
+ const creditMonths = new Set();
108
+ for (const o of p.offers ?? []) {
109
+ const what = `plan ${p.key} ${o.source} offer`;
110
+ if (o.source === 'credit') {
111
+ checkMarket(o.market, what);
112
+ if (o.market === undefined)
113
+ fail(`${what}: market is required`);
114
+ safeInt(o.months, `${what} months`, 1);
115
+ safeInt(o.credits, `${what} credits`, 1);
116
+ const slot = `${o.market}:${o.months}`;
117
+ if (creditMonths.has(slot))
118
+ fail(`${what}: ${o.months} months in ${o.market} is offered twice`);
119
+ creditMonths.add(slot);
120
+ offers.push(Object.freeze({ source: 'credit', market: o.market, months: o.months, credits: o.credits }));
121
+ }
122
+ else if (o.source === 'polar' || o.source === 'apple' || o.source === 'google') {
123
+ checkMarket(o.market, what);
124
+ checkMoney(o.price, o.market, what);
125
+ const offer = Object.freeze({ ...o });
126
+ claimRef(o.productRef, { kind: 'plan', plan, offer }, what);
127
+ offers.push(offer);
128
+ }
129
+ else {
130
+ fail(`${what}: unknown source`);
131
+ }
132
+ }
133
+ Object.freeze(offers);
134
+ byKey.set(p.key, Object.freeze(plan));
135
+ }
136
+ const plans = [...byKey.values()].sort((a, b) => a.rank - b.rank);
137
+ const frees = plans.filter((p) => p.free);
138
+ if (frees.length !== 1)
139
+ fail(`exactly one plan must be free, found ${frees.length}`);
140
+ const freePlan = frees[0];
141
+ if (freePlan !== plans[0])
142
+ fail(`free plan ${freePlan.key} must have the lowest rank`);
143
+ if (freePlan.offers.length)
144
+ fail(`free plan ${freePlan.key} cannot have offers`);
145
+ const packs = [];
146
+ const packKeys = new Set();
147
+ for (const k of spec.creditPacks ?? []) {
148
+ checkKey(k.key, 'pack');
149
+ if (packKeys.has(k.key))
150
+ fail(`duplicate pack ${k.key}`);
151
+ packKeys.add(k.key);
152
+ const what = `pack ${k.key}`;
153
+ checkMarket(k.market, what);
154
+ if (!['sepay', 'polar', 'apple', 'google'].includes(k.provider))
155
+ fail(`${what}: unknown provider ${k.provider}`);
156
+ checkMoney(k.price, k.market, what);
157
+ if (!k.price)
158
+ fail(`${what}: price is required`);
159
+ safeInt(k.credits, `${what} credits`, 1);
160
+ if (k.bonusCredits !== undefined)
161
+ safeInt(k.bonusCredits, `${what} bonusCredits`, 0);
162
+ const pack = Object.freeze({
163
+ key: k.key,
164
+ market: k.market,
165
+ provider: k.provider,
166
+ price: Object.freeze({ ...k.price }),
167
+ credits: k.credits,
168
+ bonusCredits: k.bonusCredits ?? 0,
169
+ productRef: k.productRef ?? null,
170
+ });
171
+ if (k.productRef !== undefined)
172
+ claimRef(k.productRef, { kind: 'pack', pack }, what);
173
+ packs.push(pack);
174
+ }
175
+ const creditOffers = (plan, market) => (byKey.get(plan)?.offers ?? [])
176
+ .filter((o) => o.source === 'credit' && o.market === market)
177
+ .sort((a, b) => a.months - b.months);
178
+ return Object.freeze({
179
+ version: spec.version,
180
+ creditUnit: Object.freeze({ code: unit.code, exponent: unit.exponent }),
181
+ markets: Object.freeze([...markets.values()]),
182
+ policies: Object.freeze(policies),
183
+ plans: Object.freeze(plans),
184
+ creditPacks: Object.freeze(packs),
185
+ freePlan,
186
+ plan(key) {
187
+ const p = byKey.get(key);
188
+ if (!p)
189
+ throw new BillingError('plan_not_found', `unknown plan ${key}`, { plan: key });
190
+ return p;
191
+ },
192
+ findPlan: (key) => byKey.get(key),
193
+ plansWithPermission: (permission) => plans.filter((p) => p.permissions.includes(permission)),
194
+ market: (key) => markets.get(key),
195
+ creditOffer: (plan, market, months) => creditOffers(plan, market).find((o) => o.months === months),
196
+ creditOffers,
197
+ pack: (key) => packs.find((p) => p.key === key),
198
+ packsFor: (market, provider) => packs.filter((p) => p.market === market && (!provider || p.provider === provider)),
199
+ offerByProductRef: (productRef) => productRefs.get(productRef),
200
+ });
201
+ }
@@ -112,7 +112,9 @@ export interface EntryPage {
112
112
  /** Pass as `beforeSeq` for the next (older) page; null when exhausted. */
113
113
  nextBeforeSeq: number | null;
114
114
  }
115
- export type BillingErrorCode = 'insufficient_credits' | 'idempotency_mismatch' | 'invalid_amount' | 'invalid_input' | 'entry_not_found' | 'reversal_exceeds_original' | 'already_reversed' | 'balance_overflow';
115
+ export type BillingErrorCode = 'insufficient_credits' | 'idempotency_mismatch' | 'invalid_amount' | 'invalid_input' | 'entry_not_found' | 'reversal_exceeds_original' | 'already_reversed' | 'balance_overflow' | 'invalid_catalog' | 'plan_not_found' | 'offer_not_found' | 'term_not_found'
116
+ /** A plan purchase the quote refuses (`details.reason`, e.g. `covered_by_subscription`). */
117
+ | 'plan_blocked';
116
118
  /** Details carried by `insufficient_credits`. */
117
119
  export interface InsufficientCredits {
118
120
  balance: number;
@@ -1,3 +1,5 @@
1
1
  export { billingTableBuilder, checkAdditiveDdl, createBillingTables, DEFAULT_PREFIX, type BillingSchemaConfig, type BillingTables, type CheckAdditiveDdlOptions, type DdlRule, type DdlViolation, } from './schema-factory.js';
2
2
  export { createDrizzleLedgerStore, type AnyPgDatabase, type AnyPgTransaction, type DrizzleLedgerStoreOptions, } from './store.js';
3
3
  export { createDrizzleIngestStore, createIngestTables, ingestTableNames, type DrizzleIngestStoreOptions, type IngestTables, } from '../inbox/drizzle.js';
4
+ export { createTermTables, termTableNames, type TermTables } from '../terms/schema.js';
5
+ export { createDrizzleTermStore, type DrizzleTermStoreOptions } from '../terms/drizzle.js';
@@ -1,3 +1,5 @@
1
1
  export { billingTableBuilder, checkAdditiveDdl, createBillingTables, DEFAULT_PREFIX, } from './schema-factory.js';
2
2
  export { createDrizzleLedgerStore, } from './store.js';
3
3
  export { createDrizzleIngestStore, createIngestTables, ingestTableNames, } from '../inbox/drizzle.js';
4
+ export { createTermTables, termTableNames } from '../terms/schema.js';
5
+ export { createDrizzleTermStore } from '../terms/drizzle.js';
@@ -0,0 +1,76 @@
1
+ /**
2
+ * The one entitlement resolver (design §4.7): "what plan and permissions does
3
+ * this account have now", from every term of every source. Pure — the host
4
+ * reads the account's terms (`termStore.reader().listTerms`) and the result
5
+ * is a function of those terms, the clock and the catalog.
6
+ */
7
+ import type { Catalog } from '../catalog/catalog.js';
8
+ import type { Term, TermSource } from '../terms/types.js';
9
+ export type EntitlementStatus = 'active' | 'grace' | 'free';
10
+ export type EntitlementWarningCode =
11
+ /** S5: two auto-renewing provider subscriptions bill the account. */
12
+ 'two_subscriptions'
13
+ /** The winning term's renewal failed; it is entitled until `graceUntil`. */
14
+ | 'past_due'
15
+ /** The winning credit term renews soon and the balance does not cover the live price (needs `balance`). */
16
+ | 'renewal_shortfall'
17
+ /** A lower plan takes over at renewal or at the end of the term (S3b). */
18
+ | 'scheduled_downgrade';
19
+ export interface EntitlementWarning {
20
+ code: EntitlementWarningCode;
21
+ termIds: string[];
22
+ }
23
+ export interface EntitlementRenewal {
24
+ auto: boolean;
25
+ at: Date;
26
+ /** The plan the renewal buys (`nextPlanKey ?? planKey`). */
27
+ plan: string;
28
+ /** Credit terms: the live credit price; provider terms: the provider's price snapshot. `null` when unknown. */
29
+ price: {
30
+ amountMinor: number;
31
+ unit: string;
32
+ } | null;
33
+ }
34
+ export interface Entitlement {
35
+ plan: string;
36
+ rank: number;
37
+ permissions: readonly string[];
38
+ quotas: Readonly<Record<string, number>>;
39
+ /** Per-period pool; only provider-funded terms carry one (A1). */
40
+ includedCredits: number | null;
41
+ /** The winning term; `null` on the free plan. */
42
+ term: Term | null;
43
+ source: TermSource | null;
44
+ status: EntitlementStatus;
45
+ /** When the winning term's entitlement ends unless renewed. */
46
+ endsAt: Date | null;
47
+ graceUntil: Date | null;
48
+ renewal: EntitlementRenewal | null;
49
+ warnings: EntitlementWarning[];
50
+ }
51
+ export interface ResolveOptions {
52
+ /** Market for the live renewal price of credit terms; default the term's own market. */
53
+ market?: string;
54
+ /** Credit balance, to flag `renewal_shortfall` on an auto-renewing credit term. */
55
+ balance?: number;
56
+ }
57
+ /**
58
+ * Until when a term entitles its account, or `null` when it does not at `now`.
59
+ *
60
+ * - `active` before its period end. An auto-renewing term past its end is
61
+ * still entitled for `graceDays` while the renewal (job or provider
62
+ * webhook) catches up — the renewal itself decides past_due.
63
+ * - `grace` until `graceUntil` (the period end when the provider sent none).
64
+ * - `past_due` only while `graceUntil` is ahead (a credit term's 3-day grace,
65
+ * AC15); a provider `past_due` without one is not entitled (§4.6).
66
+ * - `scheduled` once `startsAt` passed and before its period end, in case
67
+ * activation has not run yet.
68
+ */
69
+ export declare function entitledUntil(term: Term, now: Date, graceDays: number): Date | null;
70
+ export declare function isEntitled(term: Term, now: Date, graceDays: number): boolean;
71
+ /**
72
+ * Resolve the account's entitlement (S1: highest rank wins, then the later
73
+ * end, then the older term; quotas and permissions never sum). Terms naming a
74
+ * plan the catalog no longer has are ignored. No entitled term → the free plan.
75
+ */
76
+ export declare function resolveEntitlement(terms: readonly Term[], now: Date, catalog: Catalog, options?: ResolveOptions): Entitlement;