@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
@@ -3,7 +3,9 @@
3
3
 
4
4
  import { useCallback, useEffect, useRef, useState } from "react";
5
5
  import {
6
+ type AllowancesView,
6
7
  type EntitlementView,
8
+ getAllowances,
7
9
  getEntitlements,
8
10
  openBillingPortal,
9
11
  openStoreSubscriptions,
@@ -14,6 +16,7 @@ import {
14
16
  type PaymentsHostedRail,
15
17
  type PurchaseView,
16
18
  restorePurchases,
19
+ resumeCheckout,
17
20
  startCheckout,
18
21
  submitPurchase,
19
22
  } from "./api";
@@ -28,6 +31,7 @@ import {
28
31
  previewPrices,
29
32
  priceQueryKey,
30
33
  } from "./paddle";
34
+ import { readPaddleLinkTransaction } from "./paddleLink";
31
35
 
32
36
  /**
33
37
  * The headless client surface: six hooks a paywall, a pricing page, a subscription screen, and a route
@@ -141,6 +145,48 @@ export function useEntitlement(key: string, options?: PaymentsClientOptions): Us
141
145
  return { entitled, loading, readFailure, refresh };
142
146
  }
143
147
 
148
+ /** What {@link useAllowances} gives a paywall screen. */
149
+ export interface UseAllowances {
150
+ /** The caller's resolved quotas and features, or null until a read has landed. Never guessed. */
151
+ allowances: AllowancesView | null;
152
+ /** Whether a read is in flight. */
153
+ loading: boolean;
154
+ /** Why the last read could not be made, or null. `allowances` keeps its last answer while this is set. */
155
+ readFailure: PaymentsFailure | null;
156
+ /** Re-read. Call it after a purchase or an upgrade completes. */
157
+ refresh: () => void;
158
+ }
159
+
160
+ /**
161
+ * What the caller's holder may have — "3 of 10 seats", "SSO included" — for a screen to show.
162
+ *
163
+ * **Null until it knows, never zero.** A paywall that rendered `0 of 0` from a read still in flight would tell
164
+ * a paying customer they have nothing. And it is a UX affordance, never a boundary: the server's `quota()` and
165
+ * the kit's meters are what refuse.
166
+ */
167
+ export function useAllowances(options?: PaymentsClientOptions): UseAllowances {
168
+ const [allowances, setAllowances] = useState<AllowancesView | null>(null);
169
+ const [loading, setLoading] = useState(true);
170
+ const [readFailure, setReadFailure] = useState<PaymentsFailure | null>(null);
171
+ const latest = useLatest(options);
172
+ const live = useLive();
173
+ const basePath = options?.basePath;
174
+
175
+ const refresh = useCallback(() => {
176
+ setLoading(true);
177
+ void getAllowances({ ...latest.current, basePath }).then((result) => {
178
+ if (!live.current) return;
179
+ if (result.ok) setAllowances(result.value);
180
+ setReadFailure(result.ok ? null : result.failure);
181
+ setLoading(false);
182
+ });
183
+ }, [basePath, latest, live]);
184
+
185
+ useEffect(refresh, [refresh]);
186
+
187
+ return { allowances, loading, readFailure, refresh };
188
+ }
189
+
144
190
  /** What {@link useSubscription} gives a subscription screen. */
145
191
  export interface UseSubscription {
146
192
  /** Every entitlement the caller holds, as the server resolved it. */
@@ -370,6 +416,82 @@ export function usePaddleCheckout(
370
416
  return { inline: handoff?.displayMode === "inline", opening, failure };
371
417
  }
372
418
 
419
+ /** What {@link usePaddleLink} gives the screen a Paddle payment link lands on. */
420
+ export interface UsePaddleLink {
421
+ /**
422
+ * The handoff to open, or null.
423
+ *
424
+ * Null covers three different facts and deliberately reads as one: there was no `_ptxn` in the URL, there
425
+ * was one and it was not a transaction id, or the server has not answered yet. A screen renders its
426
+ * ordinary state for all three, which is what it was already rendering before this hook existed.
427
+ */
428
+ handoff: PaddleCheckoutHandoff | null;
429
+ /** Whether the resume read is in flight. A screen with nothing to show need not read it. */
430
+ loading: boolean;
431
+ /** The refusal, or null. A rail that is off, or a mode that cannot resume. */
432
+ failure: PaymentsFailure | null;
433
+ }
434
+
435
+ /**
436
+ * Resume the checkout a Paddle payment link arrived for.
437
+ *
438
+ * **The inbound half of Paddle's *Default payment link*.** Paddle appends `?_ptxn=<transaction_id>` to it
439
+ * and expects this page to open a checkout for that transaction. Those are the links Paddle sends rather
440
+ * than ones this kit opened: a past-due dunning mail, a manually-collected invoice, the payment-method
441
+ * update link minted for a subscription. `useCheckout` cannot serve them — it mints a transaction, and here
442
+ * one already exists.
443
+ *
444
+ * **Pass the result to {@link usePaddleCheckout}, which opens it.** Nothing about opening is reimplemented
445
+ * here, and that is the point: the one-open-per-transaction guard, the `StrictMode` second pass, and the
446
+ * `PADDLE_NO_CONTAINER` refusal when an inline container is missing are all inherited by going through the
447
+ * same hook the minted path goes through.
448
+ *
449
+ * **In inline mode the page must already render the container.** Paddle finds it by class name when `open`
450
+ * is called, so a Default payment link pointing at a page that does not render one produces a refusal
451
+ * rather than a checkout — which makes the choice of landing page part of configuring this, not a detail.
452
+ * `docs/paddle.md` says so where an adopter sets the link.
453
+ *
454
+ * Reads `location.search` once, on mount. A link is a navigation, so there is no later arrival to watch for.
455
+ *
456
+ * **One read per transaction, remembered rather than assumed.** The same rule {@link usePaddleCheckout}
457
+ * states and for the same reason: `StrictMode` runs every effect, cleans it up and runs it again, and that
458
+ * is the mode `pithy ui add` scaffolds. Without the ref this asked the server twice on every mount — not
459
+ * harmful, since the route only echoes config, and still two requests where the file beside it had already
460
+ * solved the problem.
461
+ */
462
+ export function usePaddleLink(options?: PaymentsClientOptions): UsePaddleLink {
463
+ const [handoff, setHandoff] = useState<PaddleCheckoutHandoff | null>(null);
464
+ const [loading, setLoading] = useState(false);
465
+ const [failure, setFailure] = useState<PaymentsFailure | null>(null);
466
+ const latest = useLatest(options);
467
+ const live = useLive();
468
+ /** The transaction this hook has already asked about, so a second effect pass asks nothing. */
469
+ const asked = useRef<string | null>(null);
470
+
471
+ useEffect(() => {
472
+ // Narrowly cast rather than read off a typed global, which is `checkout.ts`'s `documentOf` pattern and
473
+ // is forced by the same thing: the build's tsconfig gives `globalThis` no DOM index signature, so
474
+ // `globalThis.location` compiles under `typecheck` and fails the published build with TS7017.
475
+ const search = (globalThis as { location?: { search?: string } }).location?.search;
476
+ // No browser, or nothing in the URL. Both are "this page was not reached from a payment link", and a
477
+ // server render is the first of those rather than a failure worth reporting.
478
+ const transactionId = search === undefined ? null : readPaddleLinkTransaction(search);
479
+ if (transactionId === null) return;
480
+ // StrictMode's second pass, or any remount holding the same URL. One arrival is one read.
481
+ if (asked.current === transactionId) return;
482
+ asked.current = transactionId;
483
+ setLoading(true);
484
+ void resumeCheckout(transactionId, latest.current).then((outcome) => {
485
+ if (!live.current) return;
486
+ setLoading(false);
487
+ if (outcome.ok) setHandoff(outcome.value);
488
+ else setFailure(outcome.failure);
489
+ });
490
+ }, [latest, live]);
491
+
492
+ return { handoff, loading, failure };
493
+ }
494
+
373
495
  /** What {@link usePurchase} gives the screen that submits receipts. */
374
496
  export interface UsePurchase {
375
497
  /** Submit one receipt for verification. */
@@ -0,0 +1,41 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { isPaddleTransactionId } from "../data/paddleIds";
5
+
6
+ /**
7
+ * The query parameter Paddle appends to a seller's **Default payment link**.
8
+ *
9
+ * Named once, because Paddle does not document it as stable and a literal at two call sites is how one of
10
+ * them survives a rename. This is the thing to grep for if it ever moves.
11
+ */
12
+ export const PADDLE_LINK_PARAM = "_ptxn";
13
+
14
+ /**
15
+ * The transaction Paddle put in this page's URL, or null.
16
+ *
17
+ * **Paddle's own links are the ones that arrive here**, not any this kit opened: a past-due dunning mail,
18
+ * a manually-collected invoice's pay link, the payment-method-update link Paddle mints for a subscription.
19
+ * Each is the seller's *Default payment link* with `?_ptxn=<transaction_id>` on the end, and the contract
20
+ * is that the page it lands on opens a checkout for that transaction.
21
+ *
22
+ * **Null is the ordinary answer and is not a failure.** Every page this is called on is loaded without a
23
+ * `_ptxn` almost every time, so an absent parameter reads as "nothing to resume" and a screen renders
24
+ * exactly as it did before this existed. A malformed one reads the same way, which is the second half of
25
+ * the point: the value comes from outside, from a URL, from somebody who may not be signed in, and it is
26
+ * about to be sent to a route and then handed to `Paddle.Checkout.open`. The only thing that makes it safe
27
+ * to pass on is that it is shaped like a transaction id — so anything else is null rather than an error
28
+ * worth telling a buyer about, because a buyer cannot act on it and an attacker already knows.
29
+ *
30
+ * The shape check is {@link isPaddleTransactionId}, which is the rail's own and is shared rather than
31
+ * copied. Takes a search string rather than reading `location` itself, so this is a pure function and the
32
+ * hook that owns the browser is the only thing that needs one.
33
+ */
34
+ export function readPaddleLinkTransaction(search: string): string | null {
35
+ // `URLSearchParams` takes either spelling, so a caller may pass `location.search` — which carries the
36
+ // `?` — or a string it assembled without one, and neither has to be normalized first.
37
+ const value = new URLSearchParams(search).get(PADDLE_LINK_PARAM);
38
+ // Not trimmed, deliberately. A padded id is somebody's broken link or somebody's probe, and silently
39
+ // repairing it would mean this function and the route disagreed about what the id was.
40
+ return value !== null && isPaddleTransactionId(value) ? value : null;
41
+ }
@@ -40,6 +40,24 @@ export type PaymentsClientProduct = {
40
40
  };
41
41
  };
42
42
 
43
+ /** Numbered allowances and switches, as a browser reads them. */
44
+ export type PaymentsClientAllowances = {
45
+ /** Quotas by name: a whole number, or null for unlimited. */
46
+ quotas: Record<string, number | null>;
47
+ /** Features by name. */
48
+ features: Record<string, boolean>;
49
+ };
50
+
51
+ /** One declared entitlement key, browser-safe: what it is called and what it buys. */
52
+ export type PaymentsClientEntitlement = {
53
+ /** The tier's display name — `Growth`. Not translated: it is a product name. */
54
+ name: string;
55
+ /** Quotas by name: a whole number, or null for unlimited. */
56
+ quotas: Record<string, number | null>;
57
+ /** Features by name. */
58
+ features: Record<string, boolean>;
59
+ };
60
+
43
61
  /**
44
62
  * What a browser may know about this project's payments — the shape of `virtual:pithy/payments`.
45
63
  *
@@ -130,4 +148,17 @@ export type PaymentsClientProjection =
130
148
  * purchase fulfills beyond its entitlements, stay server-side.
131
149
  */
132
150
  products: PaymentsClientProduct[];
151
+ /**
152
+ * What each entitlement key buys, keyed by the key — its display name, its quotas (a whole number,
153
+ * or null for unlimited) and its features — so a paywall can lay tiers side by side. What the
154
+ * caller's own holder resolves to is `GET {basePath}/entitlements`. A UX affordance, never a
155
+ * security boundary: the server enforces every number here. The ceilings an operator's override is
156
+ * bounded by stay server-side.
157
+ */
158
+ entitlements: {
159
+ /** One declared key, by the key. */
160
+ [key: string]: PaymentsClientEntitlement;
161
+ };
162
+ /** What a caller holding no key gets — the free floor — or null when none is declared. */
163
+ defaults: PaymentsClientAllowances | null;
133
164
  };
@@ -0,0 +1,211 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { z } from "zod";
5
+
6
+ /**
7
+ * What an entitlement buys: a display name, numbered allowances, and switches. Declared once per key.
8
+ *
9
+ * A key is the thing gating code names and the thing a product mentions — `growth` — and until this
10
+ * existed it was declared nowhere. It was only ever *mentioned*, in the array a product grants and in a
11
+ * second list of comp-only keys, and those two could disagree about the same key with no answer for which
12
+ * won. There was also nowhere to write what a key buys: "up to 25 students" could gate on the key and
13
+ * could not tell 25 from 26.
14
+ *
15
+ * **The declaration hangs on the key, not on the product, because a tier is sold by more than one
16
+ * product.** `growth_monthly` and `growth_annual` are two SKUs on two rails for one tier. Writing the
17
+ * numbers on the product writes them twice and reconciles them forever.
18
+ *
19
+ * **Two maps, not one.** A single `limits: { emails: 5000, sso: true }` reads well and answers
20
+ * `number | boolean | null`, and from there no caller can tell `0` from `false` from *nothing was
21
+ * declared* without writing the same narrowing every time. `quotas` holds integers and `null`, and
22
+ * `features` holds booleans, so each reader answers one type.
23
+ *
24
+ * **`null` is unlimited, and it is written, never inferred.** A quota a key does not mention is not
25
+ * unlimited for that key — it falls to `defaults`, then to `0`. Unlimited is a decision somebody wrote
26
+ * down, because a paywall that silently does not exist is invisible until the invoice.
27
+ */
28
+
29
+ /** The longest an allowance name may be. Long enough to read, short enough to sit in an audit row. */
30
+ const MAX_ALLOWANCE_NAME_LENGTH = 64;
31
+
32
+ /** The longest a declared tier name may be — the same bound a product's display name carries. */
33
+ const MAX_TIER_NAME_LENGTH = 120;
34
+
35
+ /**
36
+ * A quota or feature name — `emails`, `seats`, `auditExport`. camelCase or snake_case, starting with a
37
+ * lowercase letter, because it is an identifier code names and never copy a screen renders.
38
+ */
39
+ export const AllowanceName = z
40
+ .string()
41
+ .min(1)
42
+ .max(MAX_ALLOWANCE_NAME_LENGTH)
43
+ .regex(
44
+ /^[a-z][A-Za-z0-9_]*$/,
45
+ "An allowance name starts with a lowercase letter and holds only letters, digits, and underscores.",
46
+ )
47
+ .describe(
48
+ "A quota or feature name — `emails`, `seats`, `auditExport`. An identifier gating code reads, never display copy, and never translated.",
49
+ );
50
+ export type AllowanceName = z.infer<typeof AllowanceName>;
51
+
52
+ /**
53
+ * One quota's value: a whole number of things, or `null` for unlimited. Never a float, never negative,
54
+ * never a string — a number that costs money to serve is not something to coerce.
55
+ */
56
+ export const QuotaValue = z
57
+ .number()
58
+ .int("A quota is a whole number, or null for unlimited.")
59
+ .min(0, "A quota is never negative. Use 0 for none and null for unlimited.")
60
+ .nullable()
61
+ .describe("How many of a thing this grants: a whole number from 0, or null for unlimited.");
62
+ export type QuotaValue = z.infer<typeof QuotaValue>;
63
+
64
+ /** A ceiling an operator's override may not pass. A whole number, and never unlimited — that is not a ceiling. */
65
+ export const OverrideCeiling = z
66
+ .number()
67
+ .int("An override ceiling is a whole number.")
68
+ .min(0, "An override ceiling is never negative.")
69
+ .describe(
70
+ "The largest number an operator's override may set for this quota. A set past it is refused naming it, never clamped.",
71
+ );
72
+ export type OverrideCeiling = z.infer<typeof OverrideCeiling>;
73
+
74
+ /** A quota map: name → whole number or unlimited. */
75
+ export const QuotaMap = z
76
+ .record(AllowanceName, QuotaValue)
77
+ .describe("Numbered allowances by name. A whole number from 0, or null for unlimited.");
78
+ export type QuotaMap = z.infer<typeof QuotaMap>;
79
+
80
+ /** A feature map: name → on or off. */
81
+ export const FeatureMap = z
82
+ .record(AllowanceName, z.boolean().describe("Whether this switch is on."))
83
+ .describe("Switches by name. A feature is read, never enforced: `false` denies nothing on its own.");
84
+ export type FeatureMap = z.infer<typeof FeatureMap>;
85
+
86
+ export const PaymentsEntitlementDeclaration = z
87
+ .object({
88
+ name: z
89
+ .string()
90
+ .min(1)
91
+ .max(MAX_TIER_NAME_LENGTH)
92
+ .describe(
93
+ "The tier's display name — `Growth`. A product name, so it is not translated, the way a product's own name is not.",
94
+ ),
95
+ quotas: QuotaMap.default({}).describe(
96
+ "What this key allows, by name — `{ emails: 5000, seats: 10 }`. A whole number from 0, or null for unlimited. Read with `quota(c, name)`, which resolves across every key the subject holds and answers the highest.",
97
+ ),
98
+ features: FeatureMap.default({}).describe(
99
+ "The switches this key turns on or off, by name — `{ sso: true }`. Read with `feature(c, name)`, which is true when any held key says true. Never enforced on its own.",
100
+ ),
101
+ overrideMax: z
102
+ .record(AllowanceName, OverrideCeiling)
103
+ .optional()
104
+ .describe(
105
+ "Optional. Per quota, the largest number an operator's override may set — so `200000000` is refused where `20000` was meant. A quota with no ceiling accepts any whole number. Must name a quota this key declares, and must not sit below that quota's own value.",
106
+ ),
107
+ })
108
+ .describe(
109
+ "What one entitlement key buys: its display name, its numbered quotas, and its switches. Declared once, however many products sell it.",
110
+ );
111
+ export type PaymentsEntitlementDeclaration = z.output<typeof PaymentsEntitlementDeclaration>;
112
+ export type PaymentsEntitlementDeclarationInput = z.input<typeof PaymentsEntitlementDeclaration>;
113
+
114
+ export const PaymentsAllowanceDefaults = z
115
+ .object({
116
+ quotas: QuotaMap.default({}).describe(
117
+ "What a subject holding no key that speaks to a quota gets — the free floor. A name absent here resolves to 0.",
118
+ ),
119
+ features: FeatureMap.default({}).describe(
120
+ "The switches a subject holding no key that speaks to them gets. A name absent here resolves to false.",
121
+ ),
122
+ })
123
+ .describe(
124
+ "The free floor: what a caller holding no key gets. Optional, and omitting it means an unentitled caller gets 0 of every quota and no feature.",
125
+ );
126
+ export type PaymentsAllowanceDefaults = z.output<typeof PaymentsAllowanceDefaults>;
127
+
128
+ /** The slice of a parsed config the derivations below read. Structural, so a test needs no full catalog. */
129
+ export interface AllowanceDeclarations {
130
+ /** Every declared entitlement key and what it buys. */
131
+ entitlements: Readonly<Record<string, PaymentsEntitlementDeclaration>>;
132
+ /** The free floor, when declared. */
133
+ defaults?: PaymentsAllowanceDefaults | undefined;
134
+ }
135
+
136
+ /**
137
+ * Every quota name this project declares, on any key or on the floor, sorted.
138
+ *
139
+ * Derived, never written down, the way the set of grantable keys is derived from the products — a second
140
+ * list of names would be a list that disagrees with the declarations the first time one is added.
141
+ */
142
+ export function declaredQuotaNames(declarations: AllowanceDeclarations): string[] {
143
+ const names = new Set<string>(Object.keys(declarations.defaults?.quotas ?? {}));
144
+ for (const declaration of Object.values(declarations.entitlements)) {
145
+ for (const name of Object.keys(declaration.quotas)) names.add(name);
146
+ }
147
+ return [...names].sort();
148
+ }
149
+
150
+ /** Every feature name this project declares, on any key or on the floor, sorted. */
151
+ export function declaredFeatureNames(declarations: AllowanceDeclarations): string[] {
152
+ const names = new Set<string>(Object.keys(declarations.defaults?.features ?? {}));
153
+ for (const declaration of Object.values(declarations.entitlements)) {
154
+ for (const name of Object.keys(declaration.features)) names.add(name);
155
+ }
156
+ return [...names].sort();
157
+ }
158
+
159
+ /**
160
+ * The problems with a set of declarations, as sentences, each with the path it belongs at.
161
+ *
162
+ * Separate from the schema so `PaymentsConfig`'s check can report every one at once, beside the catalog
163
+ * problems it already reports, and so each rule is testable on its own.
164
+ */
165
+ export interface DeclarationProblem {
166
+ /** Where in the config the problem is. */
167
+ path: (string | number)[];
168
+ /** The sentence. Names the key and the name. */
169
+ message: string;
170
+ }
171
+
172
+ /**
173
+ * Check the rules a schema cannot state field by field: a name that is a quota on one key and a feature on
174
+ * another, and an `overrideMax` that names an undeclared quota or sits below the quota it bounds.
175
+ */
176
+ export function declarationProblems(declarations: AllowanceDeclarations): DeclarationProblem[] {
177
+ const problems: DeclarationProblem[] = [];
178
+
179
+ // A name is a number or a switch, everywhere. `quota(c, "sso")` and `feature(c, "sso")` both answering
180
+ // would give one name two meanings, and an override editor could not say which input to draw.
181
+ const quotas = new Set(declaredQuotaNames(declarations));
182
+ for (const name of declaredFeatureNames(declarations)) {
183
+ if (!quotas.has(name)) continue;
184
+ problems.push({
185
+ path: ["entitlements"],
186
+ message: `"${name}" is declared as both a quota and a feature. A name is a number or a switch, never both. Rename one.`,
187
+ });
188
+ }
189
+
190
+ for (const [key, declaration] of Object.entries(declarations.entitlements)) {
191
+ for (const [name, ceiling] of Object.entries(declaration.overrideMax ?? {})) {
192
+ if (!(name in declaration.quotas)) {
193
+ problems.push({
194
+ path: ["entitlements", key, "overrideMax", name],
195
+ message: `Entitlement "${key}" sets an overrideMax for "${name}", which it declares no quota for. A ceiling bounds a quota the key declares. Declared: ${Object.keys(declaration.quotas).sort().join(", ") || "none"}.`,
196
+ });
197
+ continue;
198
+ }
199
+ const value = declaration.quotas[name];
200
+ // A ceiling under the plan's own number would refuse an override the plan already grants. Unlimited
201
+ // is above every ceiling, so a ceiling on an unlimited quota is always under it.
202
+ if (value === null || (value !== undefined && ceiling < value)) {
203
+ problems.push({
204
+ path: ["entitlements", key, "overrideMax", name],
205
+ message: `Entitlement "${key}" caps overrides of "${name}" at ${ceiling}, below the ${value === null ? "unlimited" : value} the plan itself grants. A ceiling under the plan would refuse an override the plan already allows.`,
206
+ });
207
+ }
208
+ }
209
+ }
210
+ return problems;
211
+ }