@pithy-sh/payments 0.3.10 → 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 (215) hide show
  1. package/README.md +11 -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 +38 -0
  14. package/dist/client/api.d.ts.map +1 -1
  15. package/dist/client/api.js +59 -1
  16. package/dist/client/hooks.d.ts +63 -1
  17. package/dist/client/hooks.d.ts.map +1 -1
  18. package/dist/client/hooks.js +96 -2
  19. package/dist/client/paddleLink.d.ts +31 -0
  20. package/dist/client/paddleLink.d.ts.map +1 -0
  21. package/dist/client/paddleLink.js +37 -0
  22. package/dist/client/projection.d.ts +29 -0
  23. package/dist/client/projection.d.ts.map +1 -1
  24. package/dist/config/allowances.d.ts +71 -0
  25. package/dist/config/allowances.d.ts.map +1 -0
  26. package/dist/config/allowances.js +115 -0
  27. package/dist/config/config.d.ts +155 -9
  28. package/dist/config/config.d.ts.map +1 -1
  29. package/dist/config/config.js +164 -14
  30. package/dist/data/meterCounter.d.ts +34 -0
  31. package/dist/data/meterCounter.d.ts.map +1 -0
  32. package/dist/data/meterCounter.js +33 -0
  33. package/dist/data/override.d.ts +56 -0
  34. package/dist/data/override.d.ts.map +1 -0
  35. package/dist/data/override.js +58 -0
  36. package/dist/data/paddleIds.d.ts +28 -0
  37. package/dist/data/paddleIds.d.ts.map +1 -0
  38. package/dist/data/paddleIds.js +73 -0
  39. package/dist/data/period.d.ts +10 -0
  40. package/dist/data/period.d.ts.map +1 -0
  41. package/dist/data/period.js +37 -0
  42. package/dist/data/purchase.d.ts +1 -0
  43. package/dist/data/purchase.d.ts.map +1 -1
  44. package/dist/data/purchase.js +1 -0
  45. package/dist/data/tables.d.ts +17 -1
  46. package/dist/data/tables.d.ts.map +1 -1
  47. package/dist/data/tables.js +24 -4
  48. package/dist/data/usageReport.d.ts +68 -0
  49. package/dist/data/usageReport.d.ts.map +1 -0
  50. package/dist/data/usageReport.js +55 -0
  51. package/dist/data/usageRun.d.ts +93 -0
  52. package/dist/data/usageRun.d.ts.map +1 -0
  53. package/dist/data/usageRun.js +50 -0
  54. package/dist/entitlement/allowance.d.ts +100 -0
  55. package/dist/entitlement/allowance.d.ts.map +1 -0
  56. package/dist/entitlement/allowance.js +171 -0
  57. package/dist/entitlement/manual.d.ts +5 -5
  58. package/dist/entitlement/manual.js +3 -3
  59. package/dist/entitlement/meter.d.ts +98 -0
  60. package/dist/entitlement/meter.d.ts.map +1 -0
  61. package/dist/entitlement/meter.js +177 -0
  62. package/dist/entitlement/override.d.ts +119 -0
  63. package/dist/entitlement/override.d.ts.map +1 -0
  64. package/dist/entitlement/override.js +256 -0
  65. package/dist/entitlement/resolver.d.ts +2 -1
  66. package/dist/entitlement/resolver.d.ts.map +1 -1
  67. package/dist/entitlement/resolver.js +32 -1
  68. package/dist/entitlement/unimplementedSubject.d.ts.map +1 -1
  69. package/dist/entitlement/unimplementedSubject.js +3 -2
  70. package/dist/error/errors.d.ts +19 -0
  71. package/dist/error/errors.d.ts.map +1 -1
  72. package/dist/error/errors.js +35 -2
  73. package/dist/http/responses.d.ts +390 -5
  74. package/dist/http/responses.d.ts.map +1 -1
  75. package/dist/http/responses.js +169 -13
  76. package/dist/http/routes.d.ts +6 -2
  77. package/dist/http/routes.d.ts.map +1 -1
  78. package/dist/http/routes.js +478 -52
  79. package/dist/http/schemas.d.ts +75 -1
  80. package/dist/http/schemas.d.ts.map +1 -1
  81. package/dist/http/schemas.js +80 -3
  82. package/dist/http/scopes.d.ts +25 -0
  83. package/dist/http/scopes.d.ts.map +1 -1
  84. package/dist/http/scopes.js +60 -1
  85. package/dist/http/view.d.ts +22 -4
  86. package/dist/http/view.d.ts.map +1 -1
  87. package/dist/http/view.js +88 -7
  88. package/dist/http/webhookGuard.d.ts.map +1 -1
  89. package/dist/http/webhookGuard.js +1 -1
  90. package/dist/index.d.ts +2 -1
  91. package/dist/index.d.ts.map +1 -1
  92. package/dist/index.js +3 -2
  93. package/dist/migrations/0002_allowances.d.ts +26 -0
  94. package/dist/migrations/0002_allowances.d.ts.map +1 -0
  95. package/dist/migrations/0002_allowances.js +62 -0
  96. package/dist/peer.d.ts +1 -0
  97. package/dist/peer.d.ts.map +1 -1
  98. package/dist/projection/event.d.ts +1 -0
  99. package/dist/projection/event.d.ts.map +1 -1
  100. package/dist/projection/event.js +1 -0
  101. package/dist/projection/writer.d.ts.map +1 -1
  102. package/dist/projection/writer.js +3 -1
  103. package/dist/rails/contract.d.ts +6 -0
  104. package/dist/rails/contract.d.ts.map +1 -1
  105. package/dist/rails/google/playApi.d.ts.map +1 -1
  106. package/dist/rails/google/playApi.js +2 -0
  107. package/dist/rails/paddle/events.d.ts.map +1 -1
  108. package/dist/rails/paddle/events.js +2 -1
  109. package/dist/rails/paddle/objects.d.ts +2 -0
  110. package/dist/rails/paddle/objects.d.ts.map +1 -1
  111. package/dist/rails/paddle/objects.js +7 -2
  112. package/dist/rails/paddle/refresh.d.ts +10 -5
  113. package/dist/rails/paddle/refresh.d.ts.map +1 -1
  114. package/dist/rails/paddle/refresh.js +8 -5
  115. package/dist/rails/paddle/refund.d.ts.map +1 -1
  116. package/dist/rails/paddle/refund.js +10 -2
  117. package/dist/rails/paddle/subscription.d.ts.map +1 -1
  118. package/dist/rails/paddle/subscription.js +8 -3
  119. package/dist/rails/paddle/usage.d.ts +11 -0
  120. package/dist/rails/paddle/usage.d.ts.map +1 -0
  121. package/dist/rails/paddle/usage.js +49 -0
  122. package/dist/rails/paddle/verify.d.ts.map +1 -1
  123. package/dist/rails/paddle/verify.js +2 -3
  124. package/dist/rails/quantity.d.ts +12 -0
  125. package/dist/rails/quantity.d.ts.map +1 -0
  126. package/dist/rails/quantity.js +16 -0
  127. package/dist/rails/stripe/checkout.d.ts.map +1 -1
  128. package/dist/rails/stripe/checkout.js +1 -1
  129. package/dist/rails/stripe/objects.d.ts.map +1 -1
  130. package/dist/rails/stripe/objects.js +3 -0
  131. package/dist/rails/stripe/usage.d.ts +10 -0
  132. package/dist/rails/stripe/usage.d.ts.map +1 -0
  133. package/dist/rails/stripe/usage.js +49 -0
  134. package/dist/secret/registry.d.ts.map +1 -1
  135. package/dist/secret/registry.js +3 -2
  136. package/dist/usage/pass.d.ts +120 -0
  137. package/dist/usage/pass.d.ts.map +1 -0
  138. package/dist/usage/pass.js +363 -0
  139. package/dist/usage/reporter.d.ts +36 -0
  140. package/dist/usage/reporter.d.ts.map +1 -0
  141. package/dist/usage/reporter.js +2 -0
  142. package/dist/version.generated.d.ts +1 -1
  143. package/dist/version.generated.d.ts.map +1 -1
  144. package/dist/version.generated.js +1 -1
  145. package/dist/workflows/specs.d.ts +28 -0
  146. package/dist/workflows/specs.d.ts.map +1 -1
  147. package/dist/workflows/specs.js +26 -1
  148. package/dist/workflows/usage.d.ts +38 -0
  149. package/dist/workflows/usage.d.ts.map +1 -0
  150. package/dist/workflows/usage.js +77 -0
  151. package/dist/workflows/worker.js +2 -2
  152. package/dist/workflows/workerConfig.d.ts.map +1 -1
  153. package/dist/workflows/workerConfig.js +8 -2
  154. package/docs/entitlements.md +249 -0
  155. package/docs/lemon-squeezy.md +1 -0
  156. package/docs/paddle.md +18 -2
  157. package/package.json +7 -7
  158. package/pithy.manifest.json +3 -8
  159. package/src/admin/coverage.ts +28 -0
  160. package/src/admin/read.ts +173 -1
  161. package/src/audit/actions.ts +13 -0
  162. package/src/capability.ts +87 -9
  163. package/src/client/api.ts +79 -0
  164. package/src/client/hooks.ts +122 -0
  165. package/src/client/paddleLink.ts +41 -0
  166. package/src/client/projection.ts +31 -0
  167. package/src/config/allowances.ts +211 -0
  168. package/src/config/config.ts +283 -15
  169. package/src/data/meterCounter.ts +38 -0
  170. package/src/data/override.ts +74 -0
  171. package/src/data/paddleIds.ts +74 -0
  172. package/src/data/period.ts +53 -0
  173. package/src/data/purchase.ts +9 -0
  174. package/src/data/tables.ts +25 -1
  175. package/src/data/usageReport.ts +64 -0
  176. package/src/data/usageRun.ts +66 -0
  177. package/src/entitlement/allowance.ts +213 -0
  178. package/src/entitlement/manual.ts +6 -6
  179. package/src/entitlement/meter.ts +252 -0
  180. package/src/entitlement/override.ts +381 -0
  181. package/src/entitlement/resolver.ts +43 -2
  182. package/src/entitlement/unimplementedSubject.ts +3 -4
  183. package/src/error/errors.ts +44 -1
  184. package/src/http/responses.ts +338 -10
  185. package/src/http/routes.ts +1089 -460
  186. package/src/http/schemas.ts +171 -2
  187. package/src/http/scopes.ts +68 -0
  188. package/src/http/view.ts +112 -7
  189. package/src/http/webhookGuard.ts +3 -2
  190. package/src/index.ts +18 -0
  191. package/src/migrations/0002_allowances.ts +149 -0
  192. package/src/projection/event.ts +9 -0
  193. package/src/projection/writer.ts +4 -0
  194. package/src/rails/contract.ts +6 -0
  195. package/src/rails/google/playApi.ts +2 -0
  196. package/src/rails/paddle/events.ts +2 -1
  197. package/src/rails/paddle/fixtures/subscription-charge.json +19 -0
  198. package/src/rails/paddle/objects.ts +6 -0
  199. package/src/rails/paddle/refresh.ts +17 -10
  200. package/src/rails/paddle/refund.ts +10 -2
  201. package/src/rails/paddle/subscription.ts +8 -3
  202. package/src/rails/paddle/usage.ts +66 -0
  203. package/src/rails/paddle/verify.ts +6 -4
  204. package/src/rails/quantity.ts +14 -0
  205. package/src/rails/stripe/checkout.ts +3 -1
  206. package/src/rails/stripe/fixtures/meter-event-created.json +12 -0
  207. package/src/rails/stripe/objects.ts +4 -0
  208. package/src/rails/stripe/usage.ts +61 -0
  209. package/src/secret/registry.ts +3 -2
  210. package/src/usage/pass.ts +539 -0
  211. package/src/usage/reporter.ts +38 -0
  212. package/src/version.generated.ts +1 -1
  213. package/src/workflows/specs.ts +34 -0
  214. package/src/workflows/usage.ts +97 -0
  215. package/src/workflows/workerConfig.ts +9 -3
@@ -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,28 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ /**
4
+ * Whether a value is shaped like a Paddle transaction id.
5
+ *
6
+ * Shape only. It says nothing about whether the transaction exists, who it belongs to, or what it is for —
7
+ * a caller acting on any of that has to ask Paddle, and `verify.ts` is what does. This is the cheap check
8
+ * that comes first.
9
+ *
10
+ * **`boolean`, deliberately, not `value is string`.** The predicate is the tempting signature and it makes
11
+ * the *false* branch `never` for a caller whose value is already a string — which is every caller that
12
+ * matters. `verify.ts` refuses a malformed receipt with a message naming `id.length`, and under a predicate
13
+ * that line stopped compiling. Nothing here needs the narrowing: the one caller holding `string | null` has
14
+ * already narrowed on `!== null` before asking, and Zod's `.refine` wants a boolean.
15
+ */
16
+ export declare function isPaddleTransactionId(value: unknown): boolean;
17
+ /**
18
+ * Whether a value is shaped like a Paddle subscription id.
19
+ *
20
+ * Shape only, and `boolean` rather than a type predicate, for the reasons {@link isPaddleTransactionId}
21
+ * gives — the three rail callers all hold a `string` already and want the false branch to stay reachable.
22
+ *
23
+ * The three callers read a purchase row's `providerTransactionId` and ask whether it names a subscription
24
+ * rather than one of its payments: `refresh.ts` to decide which endpoint to re-read, twice, and
25
+ * `subscription.ts` to decide whether there is a subscription to quote, change, cancel or keep at all.
26
+ */
27
+ export declare function isPaddleSubscriptionId(value: unknown): boolean;
28
+ //# sourceMappingURL=paddleIds.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"paddleIds.d.ts","sourceRoot":"","sources":["../../src/data/paddleIds.ts"],"names":[],"mappings":"AA4CA;;;;;;;;;;;;GAYG;AACH,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAE7D;AAED;;;;;;;;;GASG;AACH,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAE9D"}
@@ -0,0 +1,73 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ //#region src/data/paddleIds.ts
4
+ /**
5
+ * What a Paddle id looks like, in one place per kind of id.
6
+ *
7
+ * **Extracted because the rule had five producers and no two of them agreed.** `rails/paddle/verify.ts`
8
+ * held the transaction pattern as a module-private const, checking a receipt before spending a round trip
9
+ * on it; the `_ptxn` reader in `../client/paddleLink.ts` needs the same question answered about a value out
10
+ * of a query string (#680). Then `refund.ts`, `refresh.ts` and `subscription.ts` each answered it again
11
+ * with `startsWith`, which accepts the bare prefix and an alphabet Paddle does not issue — so one string
12
+ * was a transaction in `refund.ts` and not one in `verify.ts` (#681). A second regex is a second producer,
13
+ * and the ones that drift are always the copies nobody knew were copies.
14
+ *
15
+ * **Two kinds, two patterns, one rule.** Paddle's ids are globally prefixed and distinct, so the prefix is
16
+ * what says whether a row names a payment or the subscription it belongs to. Both predicates live here
17
+ * because that is one rule read two ways, not two rules: a caller asking "is this a transaction" is asking
18
+ * the question whose other half is "is this a subscription", and splitting them across modules is how the
19
+ * next build ends up with a tight transaction check beside a loose subscription one.
20
+ *
21
+ * **Deliberately `+` rather than `{26}`.** Paddle's API reference documents the ids as `^txn_[a-z\d]{26}$`
22
+ * and `^sub_[a-z\d]{26}$`, and every id seen from the live and sandbox accounts has been 26 characters
23
+ * after the prefix. These stay looser than the documentation on purpose: the length is Paddle's to change,
24
+ * a length that grew would make this kit reject transactions that are perfectly real, and nothing here
25
+ * depends on the count. The prefix and the alphabet are what distinguish a transaction from a
26
+ * subscription, a price or a URL, and they are what the callers actually need to know.
27
+ *
28
+ * **It lives in `data/` rather than in `rails/paddle/`, and the gate is why.** `client/sameOrigin.test.ts`
29
+ * freezes every specifier a browser module may import, and the one existing crossing out of `src/client/`
30
+ * is `wholeUnits.ts` reaching `../data/money` — permitted because that module imports nothing, so "a set of
31
+ * currency codes reaches the bundle, no graph behind it". This is the same shape and earns its place the
32
+ * same way: it imports nothing, so the browser half reaches a predicate and not a rail. Under
33
+ * `rails/paddle/` it made a browser module read the server rail, which the gate refused and was right to.
34
+ * **Nothing in this module may grow an import** — not a shared prefix constant, not a helper. The empty
35
+ * list at `sameOrigin.test.ts`'s `"src/data/paddleIds.ts"` is the whole reason the crossing is allowed.
36
+ *
37
+ * `paddleIds.test.ts` beside this file is also the sweep that keeps these two patterns the only ones:
38
+ * it fails when any other module in the package interrogates a Paddle id prefix.
39
+ */
40
+ const TRANSACTION_ID = /^txn_[a-z0-9]+$/;
41
+ /** A subscription, the other half of the same rule. See the module doc for why both live here. */
42
+ const SUBSCRIPTION_ID = /^sub_[a-z0-9]+$/;
43
+ /**
44
+ * Whether a value is shaped like a Paddle transaction id.
45
+ *
46
+ * Shape only. It says nothing about whether the transaction exists, who it belongs to, or what it is for —
47
+ * a caller acting on any of that has to ask Paddle, and `verify.ts` is what does. This is the cheap check
48
+ * that comes first.
49
+ *
50
+ * **`boolean`, deliberately, not `value is string`.** The predicate is the tempting signature and it makes
51
+ * the *false* branch `never` for a caller whose value is already a string — which is every caller that
52
+ * matters. `verify.ts` refuses a malformed receipt with a message naming `id.length`, and under a predicate
53
+ * that line stopped compiling. Nothing here needs the narrowing: the one caller holding `string | null` has
54
+ * already narrowed on `!== null` before asking, and Zod's `.refine` wants a boolean.
55
+ */
56
+ function isPaddleTransactionId(value) {
57
+ return typeof value === "string" && TRANSACTION_ID.test(value);
58
+ }
59
+ /**
60
+ * Whether a value is shaped like a Paddle subscription id.
61
+ *
62
+ * Shape only, and `boolean` rather than a type predicate, for the reasons {@link isPaddleTransactionId}
63
+ * gives — the three rail callers all hold a `string` already and want the false branch to stay reachable.
64
+ *
65
+ * The three callers read a purchase row's `providerTransactionId` and ask whether it names a subscription
66
+ * rather than one of its payments: `refresh.ts` to decide which endpoint to re-read, twice, and
67
+ * `subscription.ts` to decide whether there is a subscription to quote, change, cancel or keep at all.
68
+ */
69
+ function isPaddleSubscriptionId(value) {
70
+ return typeof value === "string" && SUBSCRIPTION_ID.test(value);
71
+ }
72
+ //#endregion
73
+ export { isPaddleSubscriptionId, isPaddleTransactionId };
@@ -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"}
@@ -1,10 +1,14 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: MIT
3
3
  import { PaymentsEntitlement } from "./entitlement.js";
4
+ import { PaymentsMeterCounter } from "./meterCounter.js";
5
+ import { PaymentsOverride } from "./override.js";
4
6
  import { PaymentsProviderAccount } from "./providerAccount.js";
5
7
  import { PaymentsPurchase } from "./purchase.js";
6
8
  import { PaymentsReconcileRun } from "./reconcileRun.js";
7
9
  import { PaymentsSyncCursor } from "./syncCursor.js";
10
+ import { PaymentsUsageReport } from "./usageReport.js";
11
+ import { PaymentsUsageRun } from "./usageRun.js";
8
12
  import { PaymentsWebhookEvent } from "./webhookEvent.js";
9
13
  import { createDatabase } from "@pithy-sh/core/src/data/db";
10
14
  //#region src/data/tables.ts
@@ -20,7 +24,15 @@ const PAYMENTS_WEBHOOK_EVENTS_TABLE = "pithyPaymentsWebhookEvents";
20
24
  const PAYMENTS_RECONCILE_RUNS_TABLE = "pithyPaymentsReconcileRuns";
21
25
  /** Where a resumable sweep of a provider's stream left off. → `pithy_payments_sync_cursors`. */
22
26
  const PAYMENTS_SYNC_CURSORS_TABLE = "pithyPaymentsSyncCursors";
23
- /** The payments tables map. All six are always present — none is behind a config flag. */
27
+ /** One subject's allowance override. → `pithy_payments_overrides`. */
28
+ const PAYMENTS_OVERRIDES_TABLE = "pithyPaymentsOverrides";
29
+ /** One subject's use of one kit meter in one period. → `pithy_payments_meter_counters`. */
30
+ const PAYMENTS_METER_COUNTERS_TABLE = "pithyPaymentsMeterCounters";
31
+ /** One reported period of one quantity-billed subscription. → `pithy_payments_usage_reports`. */
32
+ const PAYMENTS_USAGE_REPORTS_TABLE = "pithyPaymentsUsageReports";
33
+ /** One usage-reporting pass — the tally, kept. → `pithy_payments_usage_runs`. */
34
+ const PAYMENTS_USAGE_RUNS_TABLE = "pithyPaymentsUsageRuns";
35
+ /** The payments tables map. All ten are always present — none is behind a config flag. */
24
36
  function paymentsTables() {
25
37
  return {
26
38
  [PAYMENTS_PURCHASES_TABLE]: PaymentsPurchase,
@@ -28,7 +40,11 @@ function paymentsTables() {
28
40
  [PAYMENTS_PROVIDER_ACCOUNTS_TABLE]: PaymentsProviderAccount,
29
41
  [PAYMENTS_WEBHOOK_EVENTS_TABLE]: PaymentsWebhookEvent,
30
42
  [PAYMENTS_RECONCILE_RUNS_TABLE]: PaymentsReconcileRun,
31
- [PAYMENTS_SYNC_CURSORS_TABLE]: PaymentsSyncCursor
43
+ [PAYMENTS_SYNC_CURSORS_TABLE]: PaymentsSyncCursor,
44
+ [PAYMENTS_OVERRIDES_TABLE]: PaymentsOverride,
45
+ [PAYMENTS_METER_COUNTERS_TABLE]: PaymentsMeterCounter,
46
+ [PAYMENTS_USAGE_REPORTS_TABLE]: PaymentsUsageReport,
47
+ [PAYMENTS_USAGE_RUNS_TABLE]: PaymentsUsageRun
32
48
  };
33
49
  }
34
50
  /** Build the payments database from the `DB` binding (CamelCasePlugin installed). */
@@ -39,8 +55,12 @@ function paymentsDatabase(d1) {
39
55
  [PAYMENTS_PROVIDER_ACCOUNTS_TABLE]: PaymentsProviderAccount,
40
56
  [PAYMENTS_WEBHOOK_EVENTS_TABLE]: PaymentsWebhookEvent,
41
57
  [PAYMENTS_RECONCILE_RUNS_TABLE]: PaymentsReconcileRun,
42
- [PAYMENTS_SYNC_CURSORS_TABLE]: PaymentsSyncCursor
58
+ [PAYMENTS_SYNC_CURSORS_TABLE]: PaymentsSyncCursor,
59
+ [PAYMENTS_OVERRIDES_TABLE]: PaymentsOverride,
60
+ [PAYMENTS_METER_COUNTERS_TABLE]: PaymentsMeterCounter,
61
+ [PAYMENTS_USAGE_REPORTS_TABLE]: PaymentsUsageReport,
62
+ [PAYMENTS_USAGE_RUNS_TABLE]: PaymentsUsageRun
43
63
  });
44
64
  }
45
65
  //#endregion
46
- export { PAYMENTS_ENTITLEMENTS_TABLE, PAYMENTS_PROVIDER_ACCOUNTS_TABLE, PAYMENTS_PURCHASES_TABLE, PAYMENTS_RECONCILE_RUNS_TABLE, PAYMENTS_SYNC_CURSORS_TABLE, PAYMENTS_WEBHOOK_EVENTS_TABLE, paymentsDatabase, paymentsTables };
66
+ export { PAYMENTS_ENTITLEMENTS_TABLE, PAYMENTS_METER_COUNTERS_TABLE, PAYMENTS_OVERRIDES_TABLE, PAYMENTS_PROVIDER_ACCOUNTS_TABLE, PAYMENTS_PURCHASES_TABLE, PAYMENTS_RECONCILE_RUNS_TABLE, PAYMENTS_SYNC_CURSORS_TABLE, PAYMENTS_USAGE_REPORTS_TABLE, PAYMENTS_USAGE_RUNS_TABLE, PAYMENTS_WEBHOOK_EVENTS_TABLE, paymentsDatabase, paymentsTables };
@@ -0,0 +1,68 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { z } from "zod";
4
+ /**
5
+ * Where a reported period stands.
6
+ *
7
+ * - `sampling` — a `daily-peak` day. The row holds the day's high-water mark; a lower later answer never
8
+ * lowers it. A day is never sent itself: its period's report is the highest of its days, and the day rows
9
+ * are the audit of that number.
10
+ * - `claimed` — a report is being sent, or was sent and not yet confirmed. Claimed **before** the store is
11
+ * called, so a second run arriving mid-call finds the row taken. A claim whose call failed stays claimed,
12
+ * and the next run sends it again **under the same idempotency key** — the row's id — so a call that did
13
+ * land and lost only its answer is recorded once by the store rather than billed twice.
14
+ * - `reported` — the store accepted it. Nothing reports this period again.
15
+ */
16
+ export declare const UsageReportStatus: z.ZodEnum<{
17
+ claimed: "claimed";
18
+ reported: "reported";
19
+ sampling: "sampling";
20
+ }>;
21
+ export type UsageReportStatus = z.infer<typeof UsageReportStatus>;
22
+ /**
23
+ * One reported period of one subscription — the row in `pithy_payments_usage_reports`, keyed
24
+ * `UNIQUE (rail, providerSubscriptionId, period)`.
25
+ *
26
+ * **The key is the idempotency.** A replayed run, two runs racing, a Workflow step retried after the store
27
+ * answered — each finds the row and sends nothing, because the period has one row and a row is claimed
28
+ * before anything is sent.
29
+ *
30
+ * **The quantity is the adopter's, never a meter's.** It is the answer `resolveQuantity` gave, and nothing
31
+ * here reads `pithy_payments_meter_counters`: the kit does not sell overage.
32
+ */
33
+ export declare const PaymentsUsageReport: z.ZodObject<{
34
+ id: z.ZodString;
35
+ rail: z.ZodEnum<{
36
+ apple: "apple";
37
+ google: "google";
38
+ lemonSqueezy: "lemonSqueezy";
39
+ paddle: "paddle";
40
+ stripe: "stripe";
41
+ }>;
42
+ providerSubscriptionId: z.ZodString;
43
+ purchaseId: z.ZodString;
44
+ productId: z.ZodString;
45
+ subjectType: z.ZodEnum<{
46
+ organization: "organization";
47
+ user: "user";
48
+ }>;
49
+ subjectId: z.ZodString;
50
+ cadence: z.ZodEnum<{
51
+ "daily-peak": "daily-peak";
52
+ "period-end": "period-end";
53
+ }>;
54
+ period: z.ZodString;
55
+ quantity: z.ZodNumber;
56
+ status: z.ZodEnum<{
57
+ claimed: "claimed";
58
+ reported: "reported";
59
+ sampling: "sampling";
60
+ }>;
61
+ sampledAt: z.ZodCodec<z.ZodUnion<readonly [z.ZodNumber, z.ZodString, z.ZodDate]>, z.ZodDate>;
62
+ reportedAt: z.ZodNullable<z.ZodCodec<z.ZodUnion<readonly [z.ZodNumber, z.ZodString, z.ZodDate]>, z.ZodDate>>;
63
+ createdAt: z.ZodCodec<z.ZodUnion<readonly [z.ZodNumber, z.ZodString, z.ZodDate]>, z.ZodDate>;
64
+ updatedAt: z.ZodCodec<z.ZodUnion<readonly [z.ZodNumber, z.ZodString, z.ZodDate]>, z.ZodDate>;
65
+ }, z.core.$strip>;
66
+ export type PaymentsUsageReport = z.output<typeof PaymentsUsageReport>;
67
+ export type PaymentsUsageReportRow = z.input<typeof PaymentsUsageReport>;
68
+ //# sourceMappingURL=usageReport.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"usageReport.d.ts","sourceRoot":"","sources":["../../src/data/usageReport.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAKxB;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,iBAAiB;;;;EAI3B,CAAC;AACJ,MAAM,MAAM,iBAAiB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,iBAAiB,CAAC,CAAC;AAElE;;;;;;;;;;GAUG;AACH,eAAO,MAAM,mBAAmB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAsBmE,CAAC;AACpG,MAAM,MAAM,mBAAmB,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,mBAAmB,CAAC,CAAC;AACvE,MAAM,MAAM,sBAAsB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,mBAAmB,CAAC,CAAC"}
@@ -0,0 +1,55 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { PaymentsRail } from "./rail.js";
4
+ import { PaymentsSubject } from "./subject.js";
5
+ import { PaymentsReportCadence } from "../config/config.js";
6
+ import { z } from "zod";
7
+ import { SQLiteDate } from "@pithy-sh/core/src/data/codecs";
8
+ //#region src/data/usageReport.ts
9
+ /**
10
+ * Where a reported period stands.
11
+ *
12
+ * - `sampling` — a `daily-peak` day. The row holds the day's high-water mark; a lower later answer never
13
+ * lowers it. A day is never sent itself: its period's report is the highest of its days, and the day rows
14
+ * are the audit of that number.
15
+ * - `claimed` — a report is being sent, or was sent and not yet confirmed. Claimed **before** the store is
16
+ * called, so a second run arriving mid-call finds the row taken. A claim whose call failed stays claimed,
17
+ * and the next run sends it again **under the same idempotency key** — the row's id — so a call that did
18
+ * land and lost only its answer is recorded once by the store rather than billed twice.
19
+ * - `reported` — the store accepted it. Nothing reports this period again.
20
+ */
21
+ const UsageReportStatus = z.enum([
22
+ "sampling",
23
+ "claimed",
24
+ "reported"
25
+ ]).describe("Where one row stands: a daily-peak day's sample, a period's report in flight, or a period reported and final.");
26
+ /**
27
+ * One reported period of one subscription — the row in `pithy_payments_usage_reports`, keyed
28
+ * `UNIQUE (rail, providerSubscriptionId, period)`.
29
+ *
30
+ * **The key is the idempotency.** A replayed run, two runs racing, a Workflow step retried after the store
31
+ * answered — each finds the row and sends nothing, because the period has one row and a row is claimed
32
+ * before anything is sent.
33
+ *
34
+ * **The quantity is the adopter's, never a meter's.** It is the answer `resolveQuantity` gave, and nothing
35
+ * here reads `pithy_payments_meter_counters`: the kit does not sell overage.
36
+ */
37
+ const PaymentsUsageReport = z.object({
38
+ id: z.string().describe("The row's UUID."),
39
+ rail: PaymentsRail.describe("The store the count is reported to."),
40
+ providerSubscriptionId: z.string().describe("The store's own subscription id — `sub_…`."),
41
+ purchaseId: z.string().describe("The purchase row of the period this report is about."),
42
+ productId: z.string().describe("The catalog product being billed by quantity."),
43
+ subjectType: PaymentsSubject.shape.subjectType.describe("Whether `subjectId` names a user or an organization."),
44
+ subjectId: PaymentsSubject.shape.subjectId.describe("The subject the subscription belongs to."),
45
+ cadence: PaymentsReportCadence.describe("How the product reports — once per period, or each day's peak."),
46
+ period: z.string().describe("Which period this is: the billing period's end as ISO-8601 for a period's report, under either cadence; the UTC day `YYYY-MM-DD` for a `daily-peak` day's sample."),
47
+ quantity: z.number().int().nonnegative().describe("The count reported, or for a sampling day the peak so far."),
48
+ status: UsageReportStatus.describe("Where the period stands."),
49
+ sampledAt: SQLiteDate.describe("When the resolver was last asked for this period."),
50
+ reportedAt: SQLiteDate.nullable().describe("When the store accepted the report, or null until it has."),
51
+ createdAt: SQLiteDate.describe("When the period was first seen."),
52
+ updatedAt: SQLiteDate.describe("When the row last changed.")
53
+ }).describe("One reported period of one subscription — the row in `pithy_payments_usage_reports`.");
54
+ //#endregion
55
+ export { PaymentsUsageReport, UsageReportStatus };