@pithy-sh/payments 0.4.0 → 0.5.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 (177) hide show
  1. package/README.md +10 -3
  2. package/dist/admin/coverage.d.ts.map +1 -1
  3. package/dist/admin/coverage.js +26 -2
  4. package/dist/admin/read.d.ts +48 -1
  5. package/dist/admin/read.d.ts.map +1 -1
  6. package/dist/admin/read.js +89 -2
  7. package/dist/audit/actions.d.ts +13 -0
  8. package/dist/audit/actions.d.ts.map +1 -1
  9. package/dist/audit/actions.js +14 -1
  10. package/dist/capability.d.ts +33 -2
  11. package/dist/capability.d.ts.map +1 -1
  12. package/dist/capability.js +52 -9
  13. package/dist/client/api.d.ts +19 -0
  14. package/dist/client/api.d.ts.map +1 -1
  15. package/dist/client/api.js +34 -1
  16. package/dist/client/hooks.d.ts +20 -1
  17. package/dist/client/hooks.d.ts.map +1 -1
  18. package/dist/client/hooks.js +40 -2
  19. package/dist/client/projection.d.ts +29 -0
  20. package/dist/client/projection.d.ts.map +1 -1
  21. package/dist/config/allowances.d.ts +71 -0
  22. package/dist/config/allowances.d.ts.map +1 -0
  23. package/dist/config/allowances.js +115 -0
  24. package/dist/config/config.d.ts +155 -9
  25. package/dist/config/config.d.ts.map +1 -1
  26. package/dist/config/config.js +164 -14
  27. package/dist/data/meterCounter.d.ts +34 -0
  28. package/dist/data/meterCounter.d.ts.map +1 -0
  29. package/dist/data/meterCounter.js +33 -0
  30. package/dist/data/override.d.ts +56 -0
  31. package/dist/data/override.d.ts.map +1 -0
  32. package/dist/data/override.js +58 -0
  33. package/dist/data/period.d.ts +10 -0
  34. package/dist/data/period.d.ts.map +1 -0
  35. package/dist/data/period.js +37 -0
  36. package/dist/data/purchase.d.ts +1 -0
  37. package/dist/data/purchase.d.ts.map +1 -1
  38. package/dist/data/purchase.js +1 -0
  39. package/dist/data/tables.d.ts +17 -1
  40. package/dist/data/tables.d.ts.map +1 -1
  41. package/dist/data/tables.js +24 -4
  42. package/dist/data/usageReport.d.ts +68 -0
  43. package/dist/data/usageReport.d.ts.map +1 -0
  44. package/dist/data/usageReport.js +55 -0
  45. package/dist/data/usageRun.d.ts +93 -0
  46. package/dist/data/usageRun.d.ts.map +1 -0
  47. package/dist/data/usageRun.js +50 -0
  48. package/dist/entitlement/allowance.d.ts +100 -0
  49. package/dist/entitlement/allowance.d.ts.map +1 -0
  50. package/dist/entitlement/allowance.js +171 -0
  51. package/dist/entitlement/manual.d.ts +5 -5
  52. package/dist/entitlement/manual.js +3 -3
  53. package/dist/entitlement/meter.d.ts +98 -0
  54. package/dist/entitlement/meter.d.ts.map +1 -0
  55. package/dist/entitlement/meter.js +177 -0
  56. package/dist/entitlement/override.d.ts +119 -0
  57. package/dist/entitlement/override.d.ts.map +1 -0
  58. package/dist/entitlement/override.js +256 -0
  59. package/dist/entitlement/resolver.d.ts +2 -1
  60. package/dist/entitlement/resolver.d.ts.map +1 -1
  61. package/dist/entitlement/resolver.js +32 -1
  62. package/dist/error/errors.d.ts +19 -0
  63. package/dist/error/errors.d.ts.map +1 -1
  64. package/dist/error/errors.js +35 -2
  65. package/dist/http/responses.d.ts +367 -0
  66. package/dist/http/responses.d.ts.map +1 -1
  67. package/dist/http/responses.js +146 -7
  68. package/dist/http/routes.d.ts.map +1 -1
  69. package/dist/http/routes.js +270 -16
  70. package/dist/http/schemas.d.ts +54 -0
  71. package/dist/http/schemas.d.ts.map +1 -1
  72. package/dist/http/schemas.js +61 -2
  73. package/dist/http/scopes.d.ts +25 -0
  74. package/dist/http/scopes.d.ts.map +1 -1
  75. package/dist/http/scopes.js +60 -1
  76. package/dist/http/view.d.ts +22 -4
  77. package/dist/http/view.d.ts.map +1 -1
  78. package/dist/http/view.js +88 -7
  79. package/dist/index.d.ts +2 -1
  80. package/dist/index.d.ts.map +1 -1
  81. package/dist/index.js +3 -2
  82. package/dist/migrations/0002_allowances.d.ts +26 -0
  83. package/dist/migrations/0002_allowances.d.ts.map +1 -0
  84. package/dist/migrations/0002_allowances.js +62 -0
  85. package/dist/peer.d.ts +1 -0
  86. package/dist/peer.d.ts.map +1 -1
  87. package/dist/projection/event.d.ts +1 -0
  88. package/dist/projection/event.d.ts.map +1 -1
  89. package/dist/projection/event.js +1 -0
  90. package/dist/projection/writer.d.ts.map +1 -1
  91. package/dist/projection/writer.js +3 -1
  92. package/dist/rails/contract.d.ts +6 -0
  93. package/dist/rails/contract.d.ts.map +1 -1
  94. package/dist/rails/google/playApi.d.ts.map +1 -1
  95. package/dist/rails/google/playApi.js +2 -0
  96. package/dist/rails/paddle/objects.d.ts +2 -0
  97. package/dist/rails/paddle/objects.d.ts.map +1 -1
  98. package/dist/rails/paddle/objects.js +7 -2
  99. package/dist/rails/paddle/usage.d.ts +11 -0
  100. package/dist/rails/paddle/usage.d.ts.map +1 -0
  101. package/dist/rails/paddle/usage.js +49 -0
  102. package/dist/rails/quantity.d.ts +12 -0
  103. package/dist/rails/quantity.d.ts.map +1 -0
  104. package/dist/rails/quantity.js +16 -0
  105. package/dist/rails/stripe/checkout.d.ts.map +1 -1
  106. package/dist/rails/stripe/checkout.js +1 -1
  107. package/dist/rails/stripe/objects.d.ts.map +1 -1
  108. package/dist/rails/stripe/objects.js +3 -0
  109. package/dist/rails/stripe/usage.d.ts +10 -0
  110. package/dist/rails/stripe/usage.d.ts.map +1 -0
  111. package/dist/rails/stripe/usage.js +49 -0
  112. package/dist/usage/pass.d.ts +120 -0
  113. package/dist/usage/pass.d.ts.map +1 -0
  114. package/dist/usage/pass.js +363 -0
  115. package/dist/usage/reporter.d.ts +36 -0
  116. package/dist/usage/reporter.d.ts.map +1 -0
  117. package/dist/usage/reporter.js +2 -0
  118. package/dist/version.generated.d.ts +1 -1
  119. package/dist/version.generated.js +1 -1
  120. package/dist/workflows/specs.d.ts +28 -0
  121. package/dist/workflows/specs.d.ts.map +1 -1
  122. package/dist/workflows/specs.js +26 -1
  123. package/dist/workflows/usage.d.ts +38 -0
  124. package/dist/workflows/usage.d.ts.map +1 -0
  125. package/dist/workflows/usage.js +77 -0
  126. package/dist/workflows/worker.js +2 -2
  127. package/docs/entitlements.md +249 -0
  128. package/docs/lemon-squeezy.md +1 -0
  129. package/docs/paddle.md +1 -0
  130. package/package.json +5 -5
  131. package/pithy.manifest.json +3 -8
  132. package/src/admin/coverage.ts +28 -0
  133. package/src/admin/read.ts +173 -1
  134. package/src/audit/actions.ts +13 -0
  135. package/src/capability.ts +87 -9
  136. package/src/client/api.ts +44 -0
  137. package/src/client/hooks.ts +44 -0
  138. package/src/client/projection.ts +31 -0
  139. package/src/config/allowances.ts +211 -0
  140. package/src/config/config.ts +283 -15
  141. package/src/data/meterCounter.ts +38 -0
  142. package/src/data/override.ts +74 -0
  143. package/src/data/period.ts +53 -0
  144. package/src/data/purchase.ts +9 -0
  145. package/src/data/tables.ts +25 -1
  146. package/src/data/usageReport.ts +64 -0
  147. package/src/data/usageRun.ts +66 -0
  148. package/src/entitlement/allowance.ts +213 -0
  149. package/src/entitlement/manual.ts +6 -6
  150. package/src/entitlement/meter.ts +252 -0
  151. package/src/entitlement/override.ts +381 -0
  152. package/src/entitlement/resolver.ts +43 -2
  153. package/src/error/errors.ts +44 -1
  154. package/src/http/responses.ts +305 -4
  155. package/src/http/routes.ts +365 -11
  156. package/src/http/schemas.ts +139 -1
  157. package/src/http/scopes.ts +68 -0
  158. package/src/http/view.ts +112 -7
  159. package/src/index.ts +18 -0
  160. package/src/migrations/0002_allowances.ts +149 -0
  161. package/src/projection/event.ts +9 -0
  162. package/src/projection/writer.ts +4 -0
  163. package/src/rails/contract.ts +6 -0
  164. package/src/rails/google/playApi.ts +2 -0
  165. package/src/rails/paddle/fixtures/subscription-charge.json +19 -0
  166. package/src/rails/paddle/objects.ts +6 -0
  167. package/src/rails/paddle/usage.ts +66 -0
  168. package/src/rails/quantity.ts +14 -0
  169. package/src/rails/stripe/checkout.ts +3 -1
  170. package/src/rails/stripe/fixtures/meter-event-created.json +12 -0
  171. package/src/rails/stripe/objects.ts +4 -0
  172. package/src/rails/stripe/usage.ts +61 -0
  173. package/src/usage/pass.ts +539 -0
  174. package/src/usage/reporter.ts +38 -0
  175. package/src/version.generated.ts +1 -1
  176. package/src/workflows/specs.ts +34 -0
  177. package/src/workflows/usage.ts +97 -0
@@ -1,7 +1,8 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: MIT
3
- import { PAYMENTS_RAILS } from "../data/rail.js";
3
+ import { PAYMENTS_RAILS, PaymentsRail } from "../data/rail.js";
4
4
  import { PaymentsSubjectType } from "../data/subject.js";
5
+ import { PaymentsAllowanceDefaults, PaymentsEntitlementDeclaration, declarationProblems, declaredQuotaNames } from "./allowances.js";
5
6
  import { EntitlementKey } from "@pithy-sh/core/src/entitlement/entitlement";
6
7
  import { SIGNED_WEBHOOK_MAX_TOLERANCE_SECONDS } from "@pithy-sh/core/src/http/webhookWindow";
7
8
  import { z } from "zod";
@@ -75,18 +76,58 @@ const PaymentsLedgerGrant = z.object({
75
76
  amount: z.number().int().positive().describe("How much to credit, as an integer in the currency's minor unit. Never a float, never zero.")
76
77
  }).describe("A balance credit performed on fulfillment, once per provider transaction.");
77
78
  const PaymentsGrants = z.object({ ledger: PaymentsLedgerGrant.optional().describe("Credit a `@pithy-sh/ledger` balance when this product is fulfilled. The only point of contact between the two capabilities, and opt-in — most products never touch a balance.") }).describe("What a purchase fulfills beyond its entitlements. Absent for the products that only unlock a feature.");
79
+ /**
80
+ * The rails a reported quantity can be billed on. Stripe takes a meter event; Paddle takes a one-time charge
81
+ * against the subscription. **Apple and Google cannot**: in-app purchase has no concept of a seat, so a
82
+ * quantity-billed product is web-rails-only and says so at boot.
83
+ *
84
+ * **Lemon Squeezy is deferred, with the reason recorded on pithy-sh/pithy#561.** Its usage records are
85
+ * written against a subscription *item*, which the projection does not store, so the same call shape does
86
+ * not fit without a new column and a refresh of every Lemon Squeezy subscription. Named here so the refusal
87
+ * can say so, rather than reading as an oversight.
88
+ */
89
+ const REPORTED_BILLING_RAILS = ["stripe", "paddle"];
90
+ /** How often a reported quantity goes to the store. */
91
+ const PaymentsReportCadence = z.enum(["period-end", "daily-peak"]).describe("How often the count is reported. `period-end` sends one count per subscription per billing period — simplest, and what a store's metering expects to be fed. `daily-peak` samples every run and keeps each day's high-water mark, then sends the period's highest day once, in its last day — the period's peak, never the sum of its days. The day rows stay as the audit a customer disputing an invoice can check.");
92
+ const PaymentsReportedBilling = z.strictObject({
93
+ kind: z.literal("reported").describe("The quantity is reported by payments, from a count the adopter's `resolveQuantity` computes. The only kind there is."),
94
+ unit: z.string().min(1).max(MAX_NAME_LENGTH).describe("What one unit is — `student`, `coach`, `seat`. For people reading the catalog and the run log."),
95
+ cadence: PaymentsReportCadence.default("period-end").describe("How often the count is reported. Defaults to `period-end`. Per product, because a project can sell two things metered differently."),
96
+ min: z.number().int().min(0).default(0).describe("The smallest count that may be reported. A resolver answering below it is skipped and logged — never clamped, because a clamped value is a wrong number billed silently."),
97
+ max: z.number().int().positive().describe("The largest count that may be reported. A resolver answering above it is skipped and logged — never clamped. A value that becomes money is bounded by somebody who meant it."),
98
+ rails: z.array(PaymentsRail).min(1).describe("Which rails report this product's count. Stripe and Paddle only — in-app purchase has no seats, and Lemon Squeezy is deferred."),
99
+ stripe: z.strictObject({ meterEventName: z.string().min(1).max(100).describe("The `event_name` of the Stripe Billing Meter this product's metered price reads — what each report is sent as.") }).optional().describe("How Stripe hears the count: the meter it is reported to. Required when `rails` lists stripe."),
100
+ paddle: z.strictObject({ priceId: z.string().min(1).max(MAX_SKU_LENGTH).describe("The one-time Paddle price charged per unit — `pri_01…`. Each report is a one-time charge of this price, at the reported quantity, on the subscription's next bill.") }).optional().describe("How Paddle hears the count: the one-time price it is charged at. Required when `rails` lists paddle.")
101
+ }).describe("Bill by a count the adopter's code owns. Payments asks `resolveQuantity` and reports the answer to the store; it never counts anybody's members itself, and never reports a number a kit meter counted.");
78
102
  const PaymentsProduct = z.object({
79
103
  type: PaymentsProductType.describe("What kind of product this is. Decides how a renewal and a restore behave."),
80
104
  name: z.string().min(1).max(MAX_NAME_LENGTH).describe("The display name a paywall renders — `Pro`, `Remove ads`. Required: it is the one product field a browser is given, and a paywall with no copy renders nothing."),
81
- entitlements: z.array(EntitlementKey).default([]).describe("The entitlement keys this product grants. Many products across many rails may grant one key, which is the whole point — gating code names the key, never this product. Empty for a product that only credits a balance."),
105
+ entitlements: z.array(EntitlementKey).default([]).describe("The entitlement keys this product grants — mentioned here, declared in the top-level `entitlements` map. Many products across many rails may grant one key, which is the whole point — gating code names the key, never this product. Every key must be declared. Empty for a product that only credits a balance."),
82
106
  apple: PaymentsAppleProduct.optional().describe("The Apple listing, if this product ships on the App Store."),
83
107
  google: PaymentsGoogleProduct.optional().describe("The Google listing, if this product ships on Google Play."),
84
108
  stripe: PaymentsStripeProduct.optional().describe("The Stripe price, if this product is sold through Stripe."),
85
109
  lemonSqueezy: PaymentsLemonSqueezyProduct.optional().describe("The Lemon Squeezy variant, if this product is sold through Lemon Squeezy."),
86
110
  paddle: PaymentsPaddleProduct.optional().describe("The Paddle price, if this product is sold through Paddle."),
87
111
  grants: PaymentsGrants.optional().describe("What this purchase fulfills beyond its entitlements. Opt-in per product; a subscription's grant fires once per billing period, since each renewal is a distinct provider transaction."),
112
+ billing: PaymentsReportedBilling.optional().describe("Bill this subscription by a reported quantity — students, coaches, seats — rather than a flat price. Requires `resolveQuantity` on `payments(...)`. Omit for a flat-priced product."),
88
113
  clawback: z.boolean().default(false).describe("Whether a refund attempts to debit back what `grants` credited. Off by default: the user may already have spent it, and a clawback that would overdraw is refused by the ledger rather than routed around. A failed clawback is recorded and queryable, not an exception.")
89
114
  }).describe("One logical catalog product — what it is, what it grants, and how each store lists it.");
115
+ /**
116
+ * The meters the kit counts itself, because the kit writes the rows they count. Everything the kit cannot
117
+ * see — seats, students, projects — is the adopter's count, read through `quota()`. Payments never counts
118
+ * members. Forever.
119
+ */
120
+ const KIT_METERS = [
121
+ "emails",
122
+ "storageBytes",
123
+ "mediaItems"
124
+ ];
125
+ const MeterPolicy = z.strictObject({ enforce: z.boolean().default(false).describe("Whether the quota of the same name binds. Off by default: declaring a quota makes it readable, and turning this on makes it refuse. Two steps, because the first is a pricing decision and the second is a production one.") }).describe("Whether one kit meter is enforced.");
126
+ const PaymentsMeters = z.strictObject({
127
+ emails: MeterPolicy.optional().describe("Emails enqueued through `@pithy-sh/email` for a subject, per billing period. Enforced at enqueue: past the quota the enqueue throws `payments/quota_exceeded` and writes no job."),
128
+ storageBytes: MeterPolicy.optional().describe("Bytes the billing subject holds in `@pithy-sh/storage`: a user's own, or under organization billing every member's bytes stored for the organization. Enforced, the quota replaces the configured `bytesPerOwner` as the ceiling, and a write past it throws `payments/quota_exceeded`."),
129
+ mediaItems: MeterPolicy.optional().describe("Media items the billing subject holds in `@pithy-sh/media`: a user's own, or under organization billing every member's records for the organization. Enforced at create: past the quota the create throws `payments/quota_exceeded`.")
130
+ }).describe("Which kit meters enforce their quota. Every meter is advisory until named here with `enforce: true`, because a cap that arrives by surprise breaks an adopter already over it. A meter refuses at its limit and never bills.");
90
131
  const PaymentsConfig = z.object({
91
132
  billingSubject: PaymentsSubjectType.describe("Who a purchase belongs to, and who its entitlements reach. `user` is one person buying for themselves: they pay, they are entitled, nobody else is. `organization` is a company buying for its people: the company is invoiced, and everybody the adopter counts as a member holds what it bought — so a colleague who joined this morning is entitled and one who left this afternoon is not, with no row rewritten either time. Required, and decided once for the project: a codebase that could grant to a user on one route and an organization on the next eventually disagrees with itself about who is entitled, and the disagreement surfaces as somebody being refused what they paid for. Changing it later is a migration of every entitlement, purchase, and store link, so it is worth the minute now."),
92
133
  rails: PaymentsRailToggles.default({
@@ -97,7 +138,10 @@ const PaymentsConfig = z.object({
97
138
  paddle: false
98
139
  }).describe("Which stores this project sells through. Every rail is off until named."),
99
140
  products: z.record(z.string(), PaymentsProduct).default({}).describe("The catalog, keyed by logical product id — the id that lands in every purchase row. Keys are yours and outlive any store's SKU, so renaming a SKU in a console never rewrites history."),
100
- manualEntitlements: z.array(EntitlementKey).default([]).describe("Entitlement keys the control plane may grant that no product sells — a beta flag, an internal tier, a key that exists only to be comped. Declared, because the alternative to declaring is not checking: with this empty, a grant of any key outside the catalog is refused, which is what turns `pr` for `pro` into a 400 instead of a row nobody notices. Only grants are constrained; a revoke of a key the catalog has since dropped stays legal, or a catalog edit would be irreversible for everyone still holding it."),
141
+ entitlements: z.record(EntitlementKey, PaymentsEntitlementDeclaration).default({}).describe("What each entitlement key means — its display name, its numbered `quotas`, its `features` — declared once, however many products sell it. A key a product mentions must be declared here. A key declared here and sold by no product is comp-only: the control plane may grant it and no checkout sells it."),
142
+ defaults: PaymentsAllowanceDefaults.optional().describe("The free floor: the quotas and features a caller holding no key gets. Optional. Without it an unentitled caller gets 0 of every quota and no feature, which is fail-closed and correct."),
143
+ meters: PaymentsMeters.default({}).describe("Which kit meters — `emails`, `storageBytes`, `mediaItems` — enforce the quota of the same name. All advisory until named."),
144
+ manualEntitlements: z.never({ error: "`manualEntitlements` is gone. Declare each comp-only key in the top-level `entitlements` map instead — a key declared there and sold by no product is grantable by hand." }).optional().describe("Removed. Declare each comp-only key in `entitlements` instead: a declared key no product sells is what this field used to mean. Refused rather than ignored, because ignoring it would drop a comp-only key and nobody would see it."),
101
145
  stripe: PaymentsStripeSettings.optional().describe("Where Stripe's hosted Checkout and Billing Portal return the browser. Required when the Stripe rail is on — the two routes cannot create a session without them."),
102
146
  lemonSqueezy: PaymentsLemonSqueezySettings.optional().describe("Where Lemon Squeezy's hosted checkout returns the browser. Required when that rail is on — the checkout route cannot create a session without it."),
103
147
  paddle: PaymentsPaddleSettings.optional().describe("How this project sells through Paddle: the account, the publishable client token, the checkout mode, and where a buyer lands. Required when the Paddle rail is on — the rail cannot initialize Paddle.js or create a transaction without it."),
@@ -142,6 +186,41 @@ const PaymentsConfig = z.object({
142
186
  path: ["paddle"],
143
187
  message: "`paddle` declares settings, but `rails.paddle` is off. Enable the rail, or drop the block."
144
188
  });
189
+ for (const [id, product] of entries) for (const key of product.entitlements) {
190
+ if (key in config.entitlements) continue;
191
+ ctx.issues.push({
192
+ code: "custom",
193
+ input: ctx.value,
194
+ path: [
195
+ "products",
196
+ id,
197
+ "entitlements"
198
+ ],
199
+ message: `Product "${id}" grants "${key}", which \`entitlements\` does not declare. Declare it — \`entitlements: { ${key}: { name: "…" } }\` — or correct the product.`
200
+ });
201
+ }
202
+ for (const problem of declarationProblems(config)) ctx.issues.push({
203
+ code: "custom",
204
+ input: ctx.value,
205
+ path: problem.path,
206
+ message: problem.message
207
+ });
208
+ const quotaNames = new Set(declaredQuotaNames(config));
209
+ for (const meter of KIT_METERS) {
210
+ if (config.meters[meter]?.enforce !== true || quotaNames.has(meter)) continue;
211
+ ctx.issues.push({
212
+ code: "custom",
213
+ input: ctx.value,
214
+ path: ["meters", meter],
215
+ message: `The ${meter} meter is enforced, and no quota named "${meter}" is declared. Declare one on an entitlement or in \`defaults\`, or leave the meter advisory — enforced with nothing declared, it would refuse everyone.`
216
+ });
217
+ }
218
+ for (const [id, product] of entries) for (const problem of reportedBillingProblems(id, product, config)) ctx.issues.push({
219
+ code: "custom",
220
+ input: ctx.value,
221
+ path: problem.path,
222
+ message: problem.message
223
+ });
145
224
  for (const [id, product] of entries) {
146
225
  for (const rail of PAYMENTS_RAILS) if (product[rail] !== void 0 && !config.rails[rail]) ctx.issues.push({
147
226
  code: "custom",
@@ -204,6 +283,69 @@ function providerProductId(product, rail) {
204
283
  case "google": return product.google?.productId;
205
284
  }
206
285
  }
286
+ /**
287
+ * What is wrong with one product's reported billing, as sentences naming the product — empty for a product
288
+ * that has none, or one that is sound.
289
+ *
290
+ * Every refusal here is at boot, because a reported product that cannot be reported is a subscription that
291
+ * bills nothing for a quantity the customer is using — invisible until somebody reads an invoice.
292
+ */
293
+ function reportedBillingProblems(id, product, config) {
294
+ const billing = product.billing;
295
+ if (billing === void 0) return [];
296
+ const problems = [];
297
+ const at = (...rest) => [
298
+ "products",
299
+ id,
300
+ "billing",
301
+ ...rest
302
+ ];
303
+ if (product.type !== "subscription") problems.push({
304
+ path: at(),
305
+ message: `Product "${id}" reports a quantity and is a ${product.type}. A reported quantity is billed per period, so only a subscription can carry one.`
306
+ });
307
+ if (billing.min > billing.max) problems.push({
308
+ path: at("min"),
309
+ message: `Product "${id}" reports between ${billing.min} and ${billing.max}. The minimum must not exceed the maximum.`
310
+ });
311
+ for (const rail of billing.rails) {
312
+ if (rail === "apple" || rail === "google") {
313
+ problems.push({
314
+ path: at("rails"),
315
+ message: `Product "${id}" reports its quantity on ${rail}. In-app purchase has no concept of a seat, so a quantity-billed product sells on the web rails only. Remove ${rail} from \`billing.rails\`.`
316
+ });
317
+ continue;
318
+ }
319
+ if (rail === "lemonSqueezy") {
320
+ problems.push({
321
+ path: at("rails"),
322
+ message: `Product "${id}" reports its quantity on lemonSqueezy, which payments does not report to yet: its usage records are written against a subscription item the projection does not store. Report on stripe or paddle.`
323
+ });
324
+ continue;
325
+ }
326
+ if (!config.rails[rail] || product[rail] === void 0) problems.push({
327
+ path: at("rails"),
328
+ message: `Product "${id}" reports its quantity on ${rail}, and is not sold there. Enable \`rails.${rail}\` and give the product a \`${rail}\` block, or remove ${rail} from \`billing.rails\`.`
329
+ });
330
+ }
331
+ if (billing.rails.includes("stripe") && billing.stripe === void 0) problems.push({
332
+ path: at("stripe"),
333
+ message: `Product "${id}" reports its quantity on stripe and names no meter. Set \`billing.stripe.meterEventName\` to the event name of the meter its price reads.`
334
+ });
335
+ if (billing.rails.includes("paddle") && billing.paddle === void 0) problems.push({
336
+ path: at("paddle"),
337
+ message: `Product "${id}" reports its quantity on paddle and names no price to charge it at. Set \`billing.paddle.priceId\` to a one-time price.`
338
+ });
339
+ return problems;
340
+ }
341
+ /** Every product billed by a reported quantity, with its id. */
342
+ function reportedProducts(config) {
343
+ return Object.entries(config.products).flatMap(([id, product]) => product.billing === void 0 ? [] : [{
344
+ id,
345
+ product,
346
+ billing: product.billing
347
+ }]);
348
+ }
207
349
  /** The product with this logical id, or undefined. Ids come from config, so an unknown one is a 404. */
208
350
  function resolveProduct(config, id) {
209
351
  const product = config.products[id];
@@ -225,20 +367,28 @@ function productForProviderSku(config, rail, sku) {
225
367
  };
226
368
  }
227
369
  /**
228
- * Every entitlement key this project defines — what the catalog's products grant, plus what the adopter
229
- * declared grantable with no sale behind it.
370
+ * Every entitlement key this project defines — the keys `entitlements` declares. Every key a product
371
+ * mentions is among them, because the config refuses a mention with no declaration.
230
372
  *
231
- * The set a manual grant is checked against, and the set the control-plane catalog read publishes the first
232
- * half of. Computed once per composition: the catalog is config, so it cannot change under a running Worker.
373
+ * The set a manual grant is checked against, and the set the control-plane catalog read publishes.
374
+ * Computed once per composition: the catalog is config, so it cannot change under a running Worker.
233
375
  *
234
- * **Empty is a real answer.** A project composing payments with nothing to sell and nothing declared defines
235
- * no keys, and every grant against it is refused — which is correct, because there is no vocabulary to grant
236
- * in. It is the same statement `clientProjection` makes as `{ enabled: false }`.
376
+ * **Empty is a real answer.** A project composing payments with nothing declared defines no keys, and every
377
+ * grant against it is refused — which is correct, because there is no vocabulary to grant in. It is the same
378
+ * statement `clientProjection` makes as `{ enabled: false }`.
237
379
  */
238
380
  function grantableEntitlements(config) {
239
- const keys = new Set(config.manualEntitlements);
240
- for (const product of Object.values(config.products)) for (const key of product.entitlements) keys.add(key);
241
- return keys;
381
+ return new Set(Object.keys(config.entitlements));
382
+ }
383
+ /**
384
+ * The declared keys no product sells — comp-only. Granted by hand through the control plane, sold by no
385
+ * checkout. What `manualEntitlements` used to list, said by the shape of the config rather than by a
386
+ * second list that could disagree with the first.
387
+ */
388
+ function compOnlyEntitlements(config) {
389
+ const sold = /* @__PURE__ */ new Set();
390
+ for (const product of Object.values(config.products)) for (const key of product.entitlements) sold.add(key);
391
+ return Object.keys(config.entitlements).filter((key) => !sold.has(key));
242
392
  }
243
393
  /** The entitlement keys a product grants, or an empty list for an unknown product or one that grants none. */
244
394
  function entitlementsForProduct(config, id) {
@@ -249,4 +399,4 @@ function railEnabled(config, rail) {
249
399
  return config.rails[rail];
250
400
  }
251
401
  //#endregion
252
- export { PaymentsAppleProduct, PaymentsConfig, PaymentsGoogleProduct, PaymentsGrants, PaymentsLedgerGrant, PaymentsLemonSqueezyProduct, PaymentsLemonSqueezySettings, PaymentsPaddleProduct, PaymentsPaddleSettings, PaymentsProduct, PaymentsProductType, PaymentsRailToggles, PaymentsStripeProduct, PaymentsStripeSettings, entitlementsForProduct, grantableEntitlements, productForProviderSku, providerProductId, railEnabled, resolveProduct };
402
+ export { KIT_METERS, PaymentsAppleProduct, PaymentsConfig, PaymentsGoogleProduct, PaymentsGrants, PaymentsLedgerGrant, PaymentsLemonSqueezyProduct, PaymentsLemonSqueezySettings, PaymentsMeters, PaymentsPaddleProduct, PaymentsPaddleSettings, PaymentsProduct, PaymentsProductType, PaymentsRailToggles, PaymentsReportCadence, PaymentsReportedBilling, PaymentsStripeProduct, PaymentsStripeSettings, REPORTED_BILLING_RAILS, compOnlyEntitlements, entitlementsForProduct, grantableEntitlements, productForProviderSku, providerProductId, railEnabled, reportedBillingProblems, reportedProducts, resolveProduct };
@@ -0,0 +1,34 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { z } from "zod";
4
+ /**
5
+ * How much of one meter one subject used in one period — the row in `pithy_payments_meter_counters`, keyed
6
+ * `UNIQUE (subjectType, subjectId, meter, periodStart)`.
7
+ *
8
+ * **A counter, not a scan.** Counting a period's emails by reading the jobs table would be a range scan on
9
+ * every send, and it would count rows the email capability prunes. One row per period, incremented in the
10
+ * same statement that checks the limit, is both cheaper and the only shape a concurrent burst cannot walk
11
+ * past.
12
+ *
13
+ * **A new period starts at zero with nothing to reset it.** The period's start is half the key, so the first
14
+ * charge of a new period lands on a row that does not exist yet. There is no cron, no sweep, no reset job.
15
+ *
16
+ * **It refuses and never bills.** Nothing reads this table to report usage to a store: the kit does not sell
17
+ * overage, and a meter joined to a bill would make every counter a money path.
18
+ */
19
+ export declare const PaymentsMeterCounter: z.ZodObject<{
20
+ id: z.ZodString;
21
+ subjectType: z.ZodEnum<{
22
+ organization: "organization";
23
+ user: "user";
24
+ }>;
25
+ subjectId: z.ZodString;
26
+ meter: z.ZodString;
27
+ periodStart: z.ZodCodec<z.ZodUnion<readonly [z.ZodNumber, z.ZodString, z.ZodDate]>, z.ZodDate>;
28
+ used: z.ZodNumber;
29
+ createdAt: z.ZodCodec<z.ZodUnion<readonly [z.ZodNumber, z.ZodString, z.ZodDate]>, z.ZodDate>;
30
+ updatedAt: z.ZodCodec<z.ZodUnion<readonly [z.ZodNumber, z.ZodString, z.ZodDate]>, z.ZodDate>;
31
+ }, z.core.$strip>;
32
+ export type PaymentsMeterCounter = z.output<typeof PaymentsMeterCounter>;
33
+ export type PaymentsMeterCounterRow = z.input<typeof PaymentsMeterCounter>;
34
+ //# sourceMappingURL=meterCounter.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"meterCounter.d.ts","sourceRoot":"","sources":["../../src/data/meterCounter.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAGxB;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,oBAAoB;;;;;;;;;;;;iBAa0E,CAAC;AAC5G,MAAM,MAAM,oBAAoB,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,oBAAoB,CAAC,CAAC;AACzE,MAAM,MAAM,uBAAuB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,oBAAoB,CAAC,CAAC"}
@@ -0,0 +1,33 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { PaymentsSubject } from "./subject.js";
4
+ import { z } from "zod";
5
+ import { SQLiteDate } from "@pithy-sh/core/src/data/codecs";
6
+ //#region src/data/meterCounter.ts
7
+ /**
8
+ * How much of one meter one subject used in one period — the row in `pithy_payments_meter_counters`, keyed
9
+ * `UNIQUE (subjectType, subjectId, meter, periodStart)`.
10
+ *
11
+ * **A counter, not a scan.** Counting a period's emails by reading the jobs table would be a range scan on
12
+ * every send, and it would count rows the email capability prunes. One row per period, incremented in the
13
+ * same statement that checks the limit, is both cheaper and the only shape a concurrent burst cannot walk
14
+ * past.
15
+ *
16
+ * **A new period starts at zero with nothing to reset it.** The period's start is half the key, so the first
17
+ * charge of a new period lands on a row that does not exist yet. There is no cron, no sweep, no reset job.
18
+ *
19
+ * **It refuses and never bills.** Nothing reads this table to report usage to a store: the kit does not sell
20
+ * overage, and a meter joined to a bill would make every counter a money path.
21
+ */
22
+ const PaymentsMeterCounter = z.object({
23
+ id: z.string().describe("The row's UUID."),
24
+ subjectType: PaymentsSubject.shape.subjectType.describe("Whether `subjectId` names a user or an organization."),
25
+ subjectId: PaymentsSubject.shape.subjectId.describe("The subject whose usage this counts."),
26
+ meter: z.string().describe("The meter counted — `emails`."),
27
+ periodStart: SQLiteDate.describe("When the period this row counts began: the subscription's billing period where payments knows one, the calendar month (UTC) where it does not."),
28
+ used: z.number().int().nonnegative().describe("How many were charged against the meter in this period."),
29
+ createdAt: SQLiteDate.describe("When the period's first charge landed."),
30
+ updatedAt: SQLiteDate.describe("When the period's last charge landed.")
31
+ }).describe("One subject's usage of one meter in one period — the row in `pithy_payments_meter_counters`.");
32
+ //#endregion
33
+ export { PaymentsMeterCounter };
@@ -0,0 +1,56 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { z } from "zod";
4
+ /**
5
+ * One subject's allowance override — the row in `pithy_payments_overrides`, keyed `UNIQUE (subjectType,
6
+ * subjectId)`.
7
+ *
8
+ * **Keyed on the subject, never on an entitlement key.** An override survives a tier change, which is the
9
+ * whole point: a negotiated email allowance must still stand the day the customer upgrades. Keyed on a key,
10
+ * it would die with the old key at the worst possible moment. Its own table, too, so the entitlement
11
+ * projection never has to preserve a column it does not own.
12
+ *
13
+ * **It grants no key.** A subject with an override and no entitlement is still refused at every gate; the
14
+ * override only shades the numbers the subject's keys resolve to. It composes with a `manual` grant rather
15
+ * than replacing one: a comped `enterprise` key and a pinned email number are two rows in two tables.
16
+ *
17
+ * **Sparse.** `quotas` and `features` carry only what was negotiated, and every name they omit keeps
18
+ * tracking the plan. A full replacement would freeze every other allowance at the day it was written, and an
19
+ * upgrade would silently do nothing for this customer until somebody rewrote it by hand.
20
+ *
21
+ * **`unrestricted` is a mode, not a list** — unlimited and on for every name, including names declared after
22
+ * the row was written. An enumeration of today's names would quietly stop covering an enterprise contract the
23
+ * first release a name was added.
24
+ *
25
+ * **`version` is what makes a write safe for two operators.** The read carries it, a set must send it back,
26
+ * and a set naming a version behind this row's is refused rather than applied, so one operator's stale pane
27
+ * cannot silently overwrite another's pin.
28
+ *
29
+ * **So a version never repeats, and a cleared row is kept, empty.** Deleting it would put the subject back at
30
+ * version 0, the next set would write version 1 again, and a pane still holding the deleted row's 1 would pass
31
+ * the check and overwrite a newer pin. An empty row — not unrestricted, nothing pinned — is no override to
32
+ * every read ({@link isEmptyOverride}); it only remembers the version.
33
+ */
34
+ export declare const PaymentsOverride: z.ZodObject<{
35
+ id: z.ZodString;
36
+ subjectType: z.ZodEnum<{
37
+ organization: "organization";
38
+ user: "user";
39
+ }>;
40
+ subjectId: z.ZodString;
41
+ unrestricted: z.ZodCodec<z.ZodUnion<readonly [z.ZodLiteral<0>, z.ZodLiteral<1>, z.ZodBoolean, z.ZodString]>, z.ZodBoolean>;
42
+ quotas: z.ZodCodec<z.ZodUnion<readonly [z.ZodString, z.ZodRecord<z.ZodString, z.ZodNullable<z.ZodNumber>>]>, z.ZodRecord<z.ZodString, z.ZodNullable<z.ZodNumber>>>;
43
+ features: z.ZodCodec<z.ZodUnion<readonly [z.ZodString, z.ZodRecord<z.ZodString, z.ZodBoolean>]>, z.ZodRecord<z.ZodString, z.ZodBoolean>>;
44
+ version: z.ZodNumber;
45
+ reason: z.ZodString;
46
+ createdAt: z.ZodCodec<z.ZodUnion<readonly [z.ZodNumber, z.ZodString, z.ZodDate]>, z.ZodDate>;
47
+ updatedAt: z.ZodCodec<z.ZodUnion<readonly [z.ZodNumber, z.ZodString, z.ZodDate]>, z.ZodDate>;
48
+ }, z.core.$strip>;
49
+ export type PaymentsOverride = z.output<typeof PaymentsOverride>;
50
+ export type PaymentsOverrideRow = z.input<typeof PaymentsOverride>;
51
+ /**
52
+ * Whether a row overrides nothing: not unrestricted, and no name pinned. What a clear leaves behind — the row
53
+ * is kept so its version never repeats — and what every read treats as no override at all.
54
+ */
55
+ export declare function isEmptyOverride(row: PaymentsOverride): boolean;
56
+ //# sourceMappingURL=override.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"override.d.ts","sourceRoot":"","sources":["../../src/data/override.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAIxB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AACH,eAAO,MAAM,gBAAgB;;;;;;;;;;;;;;iBAyB2D,CAAC;AACzF,MAAM,MAAM,gBAAgB,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,gBAAgB,CAAC,CAAC;AACjE,MAAM,MAAM,mBAAmB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,gBAAgB,CAAC,CAAC;AAEnE;;;GAGG;AACH,wBAAgB,eAAe,CAAC,GAAG,EAAE,gBAAgB,GAAG,OAAO,CAE9D"}
@@ -0,0 +1,58 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { PaymentsSubject } from "./subject.js";
4
+ import { FeatureMap, QuotaMap } from "../config/allowances.js";
5
+ import { z } from "zod";
6
+ import { SQLiteBoolean, SQLiteDate, sqliteJson } from "@pithy-sh/core/src/data/codecs";
7
+ //#region src/data/override.ts
8
+ /**
9
+ * One subject's allowance override — the row in `pithy_payments_overrides`, keyed `UNIQUE (subjectType,
10
+ * subjectId)`.
11
+ *
12
+ * **Keyed on the subject, never on an entitlement key.** An override survives a tier change, which is the
13
+ * whole point: a negotiated email allowance must still stand the day the customer upgrades. Keyed on a key,
14
+ * it would die with the old key at the worst possible moment. Its own table, too, so the entitlement
15
+ * projection never has to preserve a column it does not own.
16
+ *
17
+ * **It grants no key.** A subject with an override and no entitlement is still refused at every gate; the
18
+ * override only shades the numbers the subject's keys resolve to. It composes with a `manual` grant rather
19
+ * than replacing one: a comped `enterprise` key and a pinned email number are two rows in two tables.
20
+ *
21
+ * **Sparse.** `quotas` and `features` carry only what was negotiated, and every name they omit keeps
22
+ * tracking the plan. A full replacement would freeze every other allowance at the day it was written, and an
23
+ * upgrade would silently do nothing for this customer until somebody rewrote it by hand.
24
+ *
25
+ * **`unrestricted` is a mode, not a list** — unlimited and on for every name, including names declared after
26
+ * the row was written. An enumeration of today's names would quietly stop covering an enterprise contract the
27
+ * first release a name was added.
28
+ *
29
+ * **`version` is what makes a write safe for two operators.** The read carries it, a set must send it back,
30
+ * and a set naming a version behind this row's is refused rather than applied, so one operator's stale pane
31
+ * cannot silently overwrite another's pin.
32
+ *
33
+ * **So a version never repeats, and a cleared row is kept, empty.** Deleting it would put the subject back at
34
+ * version 0, the next set would write version 1 again, and a pane still holding the deleted row's 1 would pass
35
+ * the check and overwrite a newer pin. An empty row — not unrestricted, nothing pinned — is no override to
36
+ * every read ({@link isEmptyOverride}); it only remembers the version.
37
+ */
38
+ const PaymentsOverride = z.object({
39
+ id: z.string().describe("The row's UUID."),
40
+ subjectType: PaymentsSubject.shape.subjectType.describe("Whether `subjectId` names a user or an organization. Half the key — the id alone is ambiguous."),
41
+ subjectId: PaymentsSubject.shape.subjectId.describe("The subject whose allowances this shades."),
42
+ unrestricted: SQLiteBoolean.describe("Whether every quota is unlimited and every feature on, for every name present and future, except the names `quotas` and `features` pin."),
43
+ quotas: sqliteJson(QuotaMap).describe("Pinned quotas by name — a whole number from 0, or null for unlimited. A name absent here resolves normally."),
44
+ features: sqliteJson(FeatureMap).describe("Pinned features by name. A name absent here resolves normally."),
45
+ version: z.number().int().positive().describe("Advances on every write. A set must name the version it read, or it is refused as stale."),
46
+ reason: z.string().describe("Why the last write was made — a contract, a goodwill credit, a migration. Required on every set."),
47
+ createdAt: SQLiteDate.describe("When this subject was first given an override."),
48
+ updatedAt: SQLiteDate.describe("When the override last changed.")
49
+ }).describe("One subject's allowance override — the row in `pithy_payments_overrides`.");
50
+ /**
51
+ * Whether a row overrides nothing: not unrestricted, and no name pinned. What a clear leaves behind — the row
52
+ * is kept so its version never repeats — and what every read treats as no override at all.
53
+ */
54
+ function isEmptyOverride(row) {
55
+ return !row.unrestricted && Object.keys(row.quotas).length === 0 && Object.keys(row.features).length === 0;
56
+ }
57
+ //#endregion
58
+ export { PaymentsOverride, isEmptyOverride };
@@ -0,0 +1,10 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import type { PaymentsRail } from "./rail";
4
+ /** The current period's start for one subscription row, or undefined where the row does not state one. */
5
+ export declare function knownPeriodStart(row: {
6
+ rail: PaymentsRail;
7
+ purchasedAt: Date;
8
+ payload: Record<string, unknown>;
9
+ }): Date | undefined;
10
+ //# sourceMappingURL=period.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"period.d.ts","sourceRoot":"","sources":["../../src/data/period.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAC;AA2B3C,0GAA0G;AAC1G,wBAAgB,gBAAgB,CAAC,GAAG,EAAE;IACpC,IAAI,EAAE,YAAY,CAAC;IACnB,WAAW,EAAE,IAAI,CAAC;IAClB,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CAClC,GAAG,IAAI,GAAG,SAAS,CAgBnB"}
@@ -0,0 +1,37 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { z } from "zod";
4
+ //#region src/data/period.ts
5
+ /**
6
+ * When a subscription's current billing period began — where payments knows, and only there.
7
+ *
8
+ * **The rails disagree about what a row is.** Stripe and Apple write a row per billing period, so a row's
9
+ * `purchasedAt` is its period's start. Paddle writes one state row per subscription and moves it forward at
10
+ * each renewal, so its `purchasedAt` is when the subscription was created — and the period it is in is in the
11
+ * stored subscription's `current_billing_period`. Google and Lemon Squeezy rows carry the subscription's
12
+ * start too, and no stored field states the current period's.
13
+ *
14
+ * So this answers for the first three and says nothing for the last two. A meter keyed on a `purchasedAt`
15
+ * that never moves would never start a new period — a customer's allowance used up once, forever — which is
16
+ * why an unknown start is `undefined` and the caller falls back to the calendar month rather than guessing.
17
+ */
18
+ /** The slice of a Paddle subscription this reads. */
19
+ const PaddleBillingPeriod = z.object({ current_billing_period: z.object({ starts_at: z.string().describe("When the period began, ISO-8601.") }).nullish().describe("The period being billed.") }).loose().describe("The billing period a stored Paddle subscription is in.");
20
+ /** The current period's start for one subscription row, or undefined where the row does not state one. */
21
+ function knownPeriodStart(row) {
22
+ switch (row.rail) {
23
+ case "stripe":
24
+ case "apple": return row.purchasedAt;
25
+ case "paddle": {
26
+ const parsed = PaddleBillingPeriod.safeParse(row.payload);
27
+ const starts = parsed.success ? parsed.data.current_billing_period?.starts_at : void 0;
28
+ if (starts === void 0) return void 0;
29
+ const at = new Date(starts);
30
+ return Number.isNaN(at.getTime()) ? void 0 : at;
31
+ }
32
+ case "google":
33
+ case "lemonSqueezy": return;
34
+ }
35
+ }
36
+ //#endregion
37
+ export { knownPeriodStart };
@@ -99,6 +99,7 @@ export declare const PaymentsPurchase: z.ZodObject<{
99
99
  originalTransactionId: z.ZodNullable<z.ZodString>;
100
100
  amountMinor: z.ZodNullable<z.ZodNumber>;
101
101
  currency: z.ZodNullable<z.ZodString>;
102
+ quantity: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
102
103
  providerEventAt: z.ZodCodec<z.ZodUnion<readonly [z.ZodNumber, z.ZodString, z.ZodDate]>, z.ZodDate>;
103
104
  payload: z.ZodCodec<z.ZodUnion<readonly [z.ZodString, z.ZodRecord<z.ZodString, z.ZodUnknown>]>, z.ZodRecord<z.ZodString, z.ZodUnknown>>;
104
105
  createdAt: z.ZodCodec<z.ZodUnion<readonly [z.ZodNumber, z.ZodString, z.ZodDate]>, z.ZodDate>;
@@ -1 +1 @@
1
- {"version":3,"file":"purchase.d.ts","sourceRoot":"","sources":["../../src/data/purchase.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAMxB;;;;GAIG;AACH,eAAO,MAAM,mBAAmB;;;EAE2E,CAAC;AAC5G,MAAM,MAAM,mBAAmB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,mBAAmB,CAAC,CAAC;AAEtE;;;;;;;;;;;;;;;;;;GAkBG;AACH,eAAO,MAAM,YAAY;;;EAItB,CAAC;AACJ,MAAM,MAAM,YAAY,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,YAAY,CAAC,CAAC;AAOxD;;;;;;;;;;;;;;;GAeG;AACH,eAAO,MAAM,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA6D4D,CAAC;AAC1F,MAAM,MAAM,gBAAgB,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,gBAAgB,CAAC,CAAC;AACjE,MAAM,MAAM,mBAAmB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,gBAAgB,CAAC,CAAC"}
1
+ {"version":3,"file":"purchase.d.ts","sourceRoot":"","sources":["../../src/data/purchase.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAMxB;;;;GAIG;AACH,eAAO,MAAM,mBAAmB;;;EAE2E,CAAC;AAC5G,MAAM,MAAM,mBAAmB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,mBAAmB,CAAC,CAAC;AAEtE;;;;;;;;;;;;;;;;;;GAkBG;AACH,eAAO,MAAM,YAAY;;;EAItB,CAAC;AACJ,MAAM,MAAM,YAAY,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,YAAY,CAAC,CAAC;AAOxD;;;;;;;;;;;;;;;GAeG;AACH,eAAO,MAAM,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAsE4D,CAAC;AAC1F,MAAM,MAAM,gBAAgB,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,gBAAgB,CAAC,CAAC;AACjE,MAAM,MAAM,mBAAmB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,gBAAgB,CAAC,CAAC"}
@@ -70,6 +70,7 @@ const PaymentsPurchase = z.object({
70
70
  originalTransactionId: z.string().nullable().describe("Chains renewals back to the transaction that started the subscription. Null for a one-time purchase."),
71
71
  amountMinor: z.number().int().nullable().describe("The amount charged, in the currency's minor unit — an integer, never a float. Nullable: not every rail reports it on every event."),
72
72
  currency: z.string().nullable().describe("The ISO currency the amount is in, or null when the rail did not report one."),
73
+ quantity: z.number().int().positive().nullable().optional().describe("How many were bought, as the store states it — a seat count, a line quantity. Null or absent where the store does not say, including every row written before the column existed. Converges like every other field: the newest event's statement wins, whichever path delivered it."),
73
74
  providerEventAt: SQLiteDate.describe("The provider's own timestamp for the event that produced this row. The monotonic write rule compares against it, so out-of-order delivery cannot revoke a live subscription."),
74
75
  payload: sqliteJson(ProviderPayload).describe("The raw verified provider payload, Zod-validated on write and on read. Retained for reconciliation and audit."),
75
76
  createdAt: SQLiteDate.describe("When this row was first projected."),
@@ -5,10 +5,14 @@ import { type DatabaseSchema } from "@pithy-sh/core/src/data/db";
5
5
  import type { Kysely } from "kysely";
6
6
  import type { z } from "zod";
7
7
  import { PaymentsEntitlement } from "./entitlement";
8
+ import { PaymentsMeterCounter } from "./meterCounter";
9
+ import { PaymentsOverride } from "./override";
8
10
  import { PaymentsProviderAccount } from "./providerAccount";
9
11
  import { PaymentsPurchase } from "./purchase";
10
12
  import { PaymentsReconcileRun } from "./reconcileRun";
11
13
  import { PaymentsSyncCursor } from "./syncCursor";
14
+ import { PaymentsUsageReport } from "./usageReport";
15
+ import { PaymentsUsageRun } from "./usageRun";
12
16
  import { PaymentsWebhookEvent } from "./webhookEvent";
13
17
  /** The projection of provider truth. `CamelCasePlugin` snake-cases it to `pithy_payments_purchases`. */
14
18
  export declare const PAYMENTS_PURCHASES_TABLE = "pithyPaymentsPurchases";
@@ -22,7 +26,15 @@ export declare const PAYMENTS_WEBHOOK_EVENTS_TABLE = "pithyPaymentsWebhookEvents
22
26
  export declare const PAYMENTS_RECONCILE_RUNS_TABLE = "pithyPaymentsReconcileRuns";
23
27
  /** Where a resumable sweep of a provider's stream left off. → `pithy_payments_sync_cursors`. */
24
28
  export declare const PAYMENTS_SYNC_CURSORS_TABLE = "pithyPaymentsSyncCursors";
25
- /** The payments tables map. All six are always present — none is behind a config flag. */
29
+ /** One subject's allowance override. → `pithy_payments_overrides`. */
30
+ export declare const PAYMENTS_OVERRIDES_TABLE = "pithyPaymentsOverrides";
31
+ /** One subject's use of one kit meter in one period. → `pithy_payments_meter_counters`. */
32
+ export declare const PAYMENTS_METER_COUNTERS_TABLE = "pithyPaymentsMeterCounters";
33
+ /** One reported period of one quantity-billed subscription. → `pithy_payments_usage_reports`. */
34
+ export declare const PAYMENTS_USAGE_REPORTS_TABLE = "pithyPaymentsUsageReports";
35
+ /** One usage-reporting pass — the tally, kept. → `pithy_payments_usage_runs`. */
36
+ export declare const PAYMENTS_USAGE_RUNS_TABLE = "pithyPaymentsUsageRuns";
37
+ /** The payments tables map. All ten are always present — none is behind a config flag. */
26
38
  export declare function paymentsTables(): Record<string, z.ZodObject>;
27
39
  /** The typed Kysely database over the payments tables. */
28
40
  export type PaymentsTables = {
@@ -32,6 +44,10 @@ export type PaymentsTables = {
32
44
  [PAYMENTS_WEBHOOK_EVENTS_TABLE]: typeof PaymentsWebhookEvent;
33
45
  [PAYMENTS_RECONCILE_RUNS_TABLE]: typeof PaymentsReconcileRun;
34
46
  [PAYMENTS_SYNC_CURSORS_TABLE]: typeof PaymentsSyncCursor;
47
+ [PAYMENTS_OVERRIDES_TABLE]: typeof PaymentsOverride;
48
+ [PAYMENTS_METER_COUNTERS_TABLE]: typeof PaymentsMeterCounter;
49
+ [PAYMENTS_USAGE_REPORTS_TABLE]: typeof PaymentsUsageReport;
50
+ [PAYMENTS_USAGE_RUNS_TABLE]: typeof PaymentsUsageRun;
35
51
  };
36
52
  export type PaymentsDatabase = Kysely<DatabaseSchema<PaymentsTables>>;
37
53
  /** Build the payments database from the `DB` binding (CamelCasePlugin installed). */
@@ -1 +1 @@
1
- {"version":3,"file":"tables.d.ts","sourceRoot":"","sources":["../../src/data/tables.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,2BAA2B,CAAC;AAC5D,OAAO,EAAkB,KAAK,cAAc,EAAE,MAAM,4BAA4B,CAAC;AACjF,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AACrC,OAAO,KAAK,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAC7B,OAAO,EAAE,mBAAmB,EAAE,MAAM,eAAe,CAAC;AACpD,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAC9C,OAAO,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AACtD,OAAO,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAClD,OAAO,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AAEtD,wGAAwG;AACxG,eAAO,MAAM,wBAAwB,2BAA2B,CAAC;AACjE,gGAAgG;AAChG,eAAO,MAAM,2BAA2B,8BAA8B,CAAC;AACvE,2FAA2F;AAC3F,eAAO,MAAM,gCAAgC,kCAAkC,CAAC;AAChF,wFAAwF;AACxF,eAAO,MAAM,6BAA6B,+BAA+B,CAAC;AAC1E,4FAA4F;AAC5F,eAAO,MAAM,6BAA6B,+BAA+B,CAAC;AAC1E,gGAAgG;AAChG,eAAO,MAAM,2BAA2B,6BAA6B,CAAC;AAEtE,0FAA0F;AAC1F,wBAAgB,cAAc,IAAI,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC,SAAS,CAAC,CAS5D;AAED,0DAA0D;AAC1D,MAAM,MAAM,cAAc,GAAG;IAC3B,CAAC,wBAAwB,CAAC,EAAE,OAAO,gBAAgB,CAAC;IACpD,CAAC,2BAA2B,CAAC,EAAE,OAAO,mBAAmB,CAAC;IAC1D,CAAC,gCAAgC,CAAC,EAAE,OAAO,uBAAuB,CAAC;IACnE,CAAC,6BAA6B,CAAC,EAAE,OAAO,oBAAoB,CAAC;IAC7D,CAAC,6BAA6B,CAAC,EAAE,OAAO,oBAAoB,CAAC;IAC7D,CAAC,2BAA2B,CAAC,EAAE,OAAO,kBAAkB,CAAC;CAC1D,CAAC;AACF,MAAM,MAAM,gBAAgB,GAAG,MAAM,CAAC,cAAc,CAAC,cAAc,CAAC,CAAC,CAAC;AAEtE,qFAAqF;AACrF,wBAAgB,gBAAgB,CAAC,EAAE,EAAE,UAAU,GAAG,gBAAgB,CASjE"}
1
+ {"version":3,"file":"tables.d.ts","sourceRoot":"","sources":["../../src/data/tables.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,2BAA2B,CAAC;AAC5D,OAAO,EAAkB,KAAK,cAAc,EAAE,MAAM,4BAA4B,CAAC;AACjF,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AACrC,OAAO,KAAK,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAC7B,OAAO,EAAE,mBAAmB,EAAE,MAAM,eAAe,CAAC;AACpD,OAAO,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AACtD,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAC9C,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAC9C,OAAO,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AACtD,OAAO,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAClD,OAAO,EAAE,mBAAmB,EAAE,MAAM,eAAe,CAAC;AACpD,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAC9C,OAAO,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AAEtD,wGAAwG;AACxG,eAAO,MAAM,wBAAwB,2BAA2B,CAAC;AACjE,gGAAgG;AAChG,eAAO,MAAM,2BAA2B,8BAA8B,CAAC;AACvE,2FAA2F;AAC3F,eAAO,MAAM,gCAAgC,kCAAkC,CAAC;AAChF,wFAAwF;AACxF,eAAO,MAAM,6BAA6B,+BAA+B,CAAC;AAC1E,4FAA4F;AAC5F,eAAO,MAAM,6BAA6B,+BAA+B,CAAC;AAC1E,gGAAgG;AAChG,eAAO,MAAM,2BAA2B,6BAA6B,CAAC;AACtE,sEAAsE;AACtE,eAAO,MAAM,wBAAwB,2BAA2B,CAAC;AACjE,2FAA2F;AAC3F,eAAO,MAAM,6BAA6B,+BAA+B,CAAC;AAC1E,iGAAiG;AACjG,eAAO,MAAM,4BAA4B,8BAA8B,CAAC;AACxE,iFAAiF;AACjF,eAAO,MAAM,yBAAyB,2BAA2B,CAAC;AAElE,0FAA0F;AAC1F,wBAAgB,cAAc,IAAI,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC,SAAS,CAAC,CAa5D;AAED,0DAA0D;AAC1D,MAAM,MAAM,cAAc,GAAG;IAC3B,CAAC,wBAAwB,CAAC,EAAE,OAAO,gBAAgB,CAAC;IACpD,CAAC,2BAA2B,CAAC,EAAE,OAAO,mBAAmB,CAAC;IAC1D,CAAC,gCAAgC,CAAC,EAAE,OAAO,uBAAuB,CAAC;IACnE,CAAC,6BAA6B,CAAC,EAAE,OAAO,oBAAoB,CAAC;IAC7D,CAAC,6BAA6B,CAAC,EAAE,OAAO,oBAAoB,CAAC;IAC7D,CAAC,2BAA2B,CAAC,EAAE,OAAO,kBAAkB,CAAC;IACzD,CAAC,wBAAwB,CAAC,EAAE,OAAO,gBAAgB,CAAC;IACpD,CAAC,6BAA6B,CAAC,EAAE,OAAO,oBAAoB,CAAC;IAC7D,CAAC,4BAA4B,CAAC,EAAE,OAAO,mBAAmB,CAAC;IAC3D,CAAC,yBAAyB,CAAC,EAAE,OAAO,gBAAgB,CAAC;CACtD,CAAC;AACF,MAAM,MAAM,gBAAgB,GAAG,MAAM,CAAC,cAAc,CAAC,cAAc,CAAC,CAAC,CAAC;AAEtE,qFAAqF;AACrF,wBAAgB,gBAAgB,CAAC,EAAE,EAAE,UAAU,GAAG,gBAAgB,CAajE"}