@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
@@ -2,11 +2,18 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
4
  import type { PithyMiddleware } from "@pithy-sh/core/src/capability/capability";
5
- import type { Entitlement, EntitlementHolder, EntitlementResolver } from "@pithy-sh/core/src/entitlement/entitlement";
5
+ import type {
6
+ Entitlement,
7
+ EntitlementHolder,
8
+ EntitlementResolver,
9
+ MeterLimit,
10
+ } from "@pithy-sh/core/src/entitlement/entitlement";
6
11
  import { InternalError } from "@pithy-sh/core/src/error/pithyError";
7
12
  import { encodeSubjectReference, type PaymentsSubject } from "../data/subject";
8
13
  import type { PaymentsDatabase } from "../data/tables";
9
14
  import { resolveEntitlements } from "../projection/resolve";
15
+ import { requireDeclaredFeature, requireDeclaredQuota, resolveFeature, resolveQuota } from "./allowance";
16
+ import { allowanceInputFor, meterLimitFor, type PaymentsAllowances } from "./meter";
10
17
  import { type PaymentsSubjectSeam, resolvePaymentsSubject } from "./subjectSeam";
11
18
 
12
19
  /**
@@ -81,7 +88,11 @@ export function createPaymentsEntitlementResolver(
81
88
  * neither is a composition problem, and reporting `null` here would send an operator looking for a missing
82
89
  * capability.
83
90
  */
84
- export function installEntitlementResolver(database: string, seam: PaymentsSubjectSeam): PithyMiddleware {
91
+ export function installEntitlementResolver(
92
+ database: string,
93
+ seam: PaymentsSubjectSeam,
94
+ allowances: PaymentsAllowances = { declarations: { entitlements: {} }, meters: {} },
95
+ ): PithyMiddleware {
85
96
  return (app) => {
86
97
  app.use("*", async (c, next) => {
87
98
  // **One resolution per request, shared by `list()` and `holder()`.** The seam is the adopter's and
@@ -93,8 +104,38 @@ export function installEntitlementResolver(database: string, seam: PaymentsSubje
93
104
  resolving ??= resolvePaymentsSubject(c, seam);
94
105
  return resolving;
95
106
  };
107
+ /** The database, or the wiring fault — checked only once a read actually needs one. */
108
+ const appDatabase = (): PaymentsDatabase => {
109
+ const db = (c.var.db as Record<string, PaymentsDatabase>)[database];
110
+ if (!db) {
111
+ throw new InternalError({
112
+ message: "Payments is not configured.",
113
+ action: "Bind a D1 database named DB in wrangler.jsonc.",
114
+ detail: `No \`${database}\` database on c.var.db; payments cannot resolve allowances.`,
115
+ });
116
+ }
117
+ return db;
118
+ };
96
119
  c.set("entitlements", {
97
120
  provider: PAYMENTS_ENTITLEMENT_PROVIDER,
121
+ // **The name is checked before anything is read**, so a typo is a hard failure on every request
122
+ // rather than only on the ones that reach D1 — and never a 0 or an unlimited.
123
+ quota: async (name: string): Promise<number | null> => {
124
+ requireDeclaredQuota(allowances.declarations, name);
125
+ const subject = await subjectOnce();
126
+ const input = await allowanceInputFor(subject && appDatabase(), allowances.declarations, subject, new Date());
127
+ return resolveQuota(input, name).effective.value;
128
+ },
129
+ feature: async (name: string): Promise<boolean> => {
130
+ requireDeclaredFeature(allowances.declarations, name);
131
+ const subject = await subjectOnce();
132
+ const input = await allowanceInputFor(subject && appDatabase(), allowances.declarations, subject, new Date());
133
+ return resolveFeature(input, name).effective.value;
134
+ },
135
+ meterLimit: async (meter: string): Promise<MeterLimit> => {
136
+ const subject = await subjectOnce();
137
+ return meterLimitFor(appDatabase(), allowances, subject, meter, new Date());
138
+ },
98
139
  // Who the read answered for, for the log and the trail alone. `undefined` is a real answer and a
99
140
  // different one from "holds nothing": it is a caller acting for no organization, which is what
100
141
  // lets core's denial say so instead of reporting an empty list twice over.
@@ -1,6 +1,7 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
+ import { commandName } from "@pithy-sh/core/src/cli/command";
4
5
  import { InternalError, ValidationError } from "@pithy-sh/core/src/error/pithyError";
5
6
  import type { PaymentsSubjectResolver } from "./subjectSeam";
6
7
 
@@ -57,8 +58,7 @@ export const unimplementedSubject: PaymentsSubjectResolver = Object.defineProper
57
58
  throw new InternalError({
58
59
  message: "The subject resolver for this project has not been written.",
59
60
  action: "Implement resolveSubject in this Worker's src/billing/subject.ts.",
60
- detail:
61
- 'pithy add scaffolded an unimplemented resolveSubject and it is still the one composed. Under billingSubject: "organization" only the application can say which organization a caller is acting for.',
61
+ detail: `The resolveSubject that ${commandName("add")} scaffolded is unimplemented, and it is still the one composed. Under billingSubject: "organization" only the application can say which organization a caller is acting for.`,
62
62
  });
63
63
  },
64
64
  UNIMPLEMENTED_SUBJECT,
@@ -83,7 +83,6 @@ export function requireImplementedSubject(resolver: PaymentsSubjectResolver | un
83
83
  message: "This project bills organizations, and its subject resolver is still the scaffolded placeholder.",
84
84
  action:
85
85
  'Implement resolveSubject in this Worker\'s src/billing/subject.ts, or set `billingSubject: "user"` in pithy.config.ts.',
86
- detail:
87
- "pithy add wrote src/billing/subject.ts exporting an unimplemented resolveSubject, and it is unchanged. Payments has no members table and never guesses a holder, so booting on it would deny every entitlement gate and raise payments/subject_unresolved on every write, for every caller, forever.",
86
+ detail: `src/billing/subject.ts, as ${commandName("add")} wrote it, exports an unimplemented resolveSubject, and it is unchanged. Payments has no members table and never guesses a holder, so booting on it would deny every entitlement gate and raise payments/subject_unresolved on every write, for every caller, forever.`,
88
87
  });
89
88
  }
@@ -256,7 +256,7 @@ export class PaymentsEntitlementNotInCatalogError extends PithyError {
256
256
  message: args.message ?? "That entitlement is not one this project defines.",
257
257
  action:
258
258
  args.action ??
259
- "Grant a key one of the catalog's products lists, or declare it in `manualEntitlements` in pithy.config.ts.",
259
+ "Grant a key the `entitlements` map in pithy.config.ts declares, or declare it there — a declared key no product sells is grantable by hand.",
260
260
  detail: args.detail,
261
261
  params: args.params,
262
262
  },
@@ -419,3 +419,46 @@ export class PaymentsSubscriptionChangeRefusedError extends PithyError {
419
419
  );
420
420
  }
421
421
  }
422
+
423
+ /**
424
+ * An override set named a version behind the row it would change. Two operators share one customer: both
425
+ * opened `emails`, and the second would silently win while the first believes they succeeded. So the set is
426
+ * refused and nothing is written, and the caller re-reads before it tries again.
427
+ */
428
+ export class PaymentsOverrideStaleError extends PithyError {
429
+ constructor(args: PaymentsErrorArgs = {}, options?: { cause?: unknown }) {
430
+ super(
431
+ {
432
+ code: "payments/override_stale",
433
+ status: 409,
434
+ message: args.message ?? "That override changed since it was read.",
435
+ action: args.action ?? "Read the subject's entitlements again, then set the override against the new version.",
436
+ detail: args.detail,
437
+ params: args.params,
438
+ },
439
+ options,
440
+ );
441
+ }
442
+ }
443
+
444
+ /**
445
+ * An enforced meter refused: the subject's effective quota for this period does not allow more. 402, because
446
+ * the caller's plan does not allow it and the remedy is a purchase — a bigger tier, or a pinned number.
447
+ */
448
+ export class PaymentsQuotaExceededError extends PithyError {
449
+ constructor(args: PaymentsErrorArgs = {}, options?: { cause?: unknown }) {
450
+ super(
451
+ {
452
+ code: "payments/quota_exceeded",
453
+ status: 402,
454
+ message: args.message ?? "This plan's allowance is used up for this period.",
455
+ action:
456
+ args.action ??
457
+ "Upgrade the plan, or pin a larger allowance for this subject from the control plane. The meter resets when the period does.",
458
+ detail: args.detail,
459
+ params: args.params,
460
+ },
461
+ options,
462
+ );
463
+ }
464
+ }
@@ -24,8 +24,9 @@ import { RefundRequestStatus, ScheduledSubscriptionChangeAction } from "../data/
24
24
  *
25
25
  * **Nothing here is a receipt.** `PaymentsPurchase.payload` is the whole verified provider response,
26
26
  * and a bearer artifact; the purchase view is the normalized projection of it, and there is no field
27
- * that carries the original. The webhook responses are deliberately absent from this file too — they
28
- * are acknowledgements addressed to Apple, Google and Stripe, not a contract offered to any client.
27
+ * that carries the original. The webhook acknowledgement is here only so the OpenAPI contract can say
28
+ * what a store receives — it is addressed to Apple, Google and the hosted stores, not a contract offered
29
+ * to any client.
29
30
  *
30
31
  * **A client's own views name no subject; the management views name both halves of one.** A player reads
31
32
  * its own rows, and who holds them is the answer the request already carried — echoing it back teaches a
@@ -90,8 +91,22 @@ export type PaymentsPurchaseResponse = z.output<typeof PaymentsPurchaseResponse>
90
91
 
91
92
  /** `GET {base}/entitlements` — always the caller's own. */
92
93
  export const PaymentsEntitlementsResponse = z
93
- .object({ entitlements: z.array(PaymentsEntitlementView).describe("The caller's entitlements, resolved now.") })
94
- .describe("Every entitlement the caller holds.");
94
+ .object({
95
+ entitlements: z.array(PaymentsEntitlementView).describe("The caller's entitlements, resolved now."),
96
+ quotas: z
97
+ .record(z.string(), z.number().int().nonnegative().nullable().describe("A whole number, or null for unlimited."))
98
+ .optional()
99
+ .describe(
100
+ "Every declared quota, resolved for the caller's holder now — what `quota(c, name)` answers on the server, for a paywall screen to show. A UX affordance, never a security boundary: the server enforces. Absent from a Worker that predates declarations.",
101
+ ),
102
+ features: z
103
+ .record(z.string(), z.boolean().describe("Whether it is on."))
104
+ .optional()
105
+ .describe(
106
+ "Every declared feature, resolved for the caller's holder now. A UX affordance, never a security boundary. Absent from a Worker that predates declarations.",
107
+ ),
108
+ })
109
+ .describe("Every entitlement the caller holds, and the allowances they resolve to.");
95
110
  export type PaymentsEntitlementsResponse = z.output<typeof PaymentsEntitlementsResponse>;
96
111
 
97
112
  /** `POST {base}/restore`. */
@@ -601,6 +616,22 @@ export const PaymentsSubscriptionView = z
601
616
  nextEvent: PaymentsSubscriptionNextEvent.describe(
602
617
  "What happens next and when, already resolved — the scheduled change ahead of the billing date. The sentence a screen prints.",
603
618
  ),
619
+ reportedQuantity: z
620
+ .number()
621
+ .int()
622
+ .nonnegative()
623
+ .nullable()
624
+ .optional()
625
+ .describe(
626
+ "For a quantity-billed product, the last count reported to the store — null when nothing has been reported yet. Absent from a Worker that predates reported billing.",
627
+ ),
628
+ reportedAt: z.iso
629
+ .datetime()
630
+ .nullable()
631
+ .optional()
632
+ .describe(
633
+ "When that count was reported, ISO-8601, or null when nothing has been. Absent from a Worker that predates reported billing.",
634
+ ),
604
635
  })
605
636
  .describe("One subscription as the person paying for it reads it: which plan, where it stands, and what is next.");
606
637
  export type PaymentsSubscriptionView = z.output<typeof PaymentsSubscriptionView>;
@@ -807,6 +838,30 @@ export const PaymentsDiscountResponse = z
807
838
  .describe("One discount code, as the store minted it.");
808
839
  export type PaymentsDiscountResponse = z.output<typeof PaymentsDiscountResponse>;
809
840
 
841
+ /**
842
+ * What every webhook route answers a store once authenticity is established: always a 200, so the store
843
+ * stops redelivering. Three shapes share it — a redelivery of a finished event (`duplicate`), a delivery
844
+ * that projected nothing (`projected: false`), and one that projected a purchase (`projected: true` with
845
+ * the projection's `outcome`).
846
+ */
847
+ export const PaymentsWebhookAck = z
848
+ .object({
849
+ received: z.literal(true).describe("Always true. The delivery was authentic and is recorded."),
850
+ duplicate: z
851
+ .literal(true)
852
+ .optional()
853
+ .describe("Present when this event was already finished, so the delivery changed nothing."),
854
+ projected: z.boolean().optional().describe("Whether the delivery projected a purchase. Absent on a duplicate."),
855
+ outcome: z
856
+ .enum(["created", "updated", "ignored"])
857
+ .optional()
858
+ .describe(
859
+ "What the projection did, when one ran: a new purchase, a newer event applied, or an event no newer than the stored row.",
860
+ ),
861
+ })
862
+ .describe("The acknowledgement a store receives for an authentic webhook delivery.");
863
+ export type PaymentsWebhookAck = z.output<typeof PaymentsWebhookAck>;
864
+
810
865
  /**
811
866
  * ## The management read surface
812
867
  *
@@ -853,6 +908,52 @@ export const PaymentsAdminCatalogProduct = z
853
908
  .describe("One catalog product as a management client sees it: what it is, and what it grants.");
854
909
  export type PaymentsAdminCatalogProduct = z.output<typeof PaymentsAdminCatalogProduct>;
855
910
 
911
+ /** A quota's value on the wire: a whole number from 0, or null for unlimited. */
912
+ const WireQuota = z.number().int().nonnegative().nullable().describe("A whole number from 0, or null for unlimited.");
913
+
914
+ /**
915
+ * One declared entitlement key, as a management client sees it: what it is called, and what it buys.
916
+ *
917
+ * **What an override editor is built from.** An override names a quota or a feature, and without this a pane
918
+ * could not say which names exist, which are numbers and which are switches, what the plan's value is, or
919
+ * what ceiling an operator may type up to. `quotas` holds numbers and `features` holds booleans, so the map a
920
+ * name sits in *is* its kind.
921
+ */
922
+ export const PaymentsAdminCatalogEntitlement = z
923
+ .object({
924
+ key: z.string().describe("The entitlement key — what gating code names, and what a comp grants."),
925
+ name: z.string().describe("The tier's display name, as the adopter wrote it — `Growth`."),
926
+ quotas: z
927
+ .record(z.string(), WireQuota)
928
+ .describe("What this key allows, by quota name. A whole number, or null for unlimited."),
929
+ features: z
930
+ .record(z.string(), z.boolean().describe("Whether the switch is on."))
931
+ .describe("Its switches, by name."),
932
+ overrideMax: z
933
+ .record(z.string(), z.number().int().nonnegative().describe("The ceiling."))
934
+ .describe(
935
+ "Per quota, the largest number an override may set. A quota absent here accepts any whole number. `unrestricted` is never bounded by it.",
936
+ ),
937
+ sold: z
938
+ .boolean()
939
+ .describe(
940
+ "Whether a product in this catalog grants the key. False is comp-only: grantable by hand, sold by nothing.",
941
+ ),
942
+ })
943
+ .describe("One declared entitlement key: its name, its quotas, its features, and the ceilings on overriding them.");
944
+ export type PaymentsAdminCatalogEntitlement = z.output<typeof PaymentsAdminCatalogEntitlement>;
945
+
946
+ /** The free floor, as a management client sees it. */
947
+ export const PaymentsAdminCatalogDefaults = z
948
+ .object({
949
+ quotas: z.record(z.string(), WireQuota).describe("What a subject holding no key gets, by quota name."),
950
+ features: z
951
+ .record(z.string(), z.boolean().describe("Whether the switch is on."))
952
+ .describe("The switches a subject holding no key gets."),
953
+ })
954
+ .describe("What a caller holding no key gets — the free floor.");
955
+ export type PaymentsAdminCatalogDefaults = z.output<typeof PaymentsAdminCatalogDefaults>;
956
+
856
957
  /**
857
958
  * `GET {base}/admin/catalog` — what this project sells.
858
959
  *
@@ -873,7 +974,7 @@ export const PaymentsAdminCatalogResponse = z
873
974
  enabled: z
874
975
  .literal(false)
875
976
  .describe(
876
- "This project defines nothing — no product is configured and no key was declared grantable, so there is no entitlement a comp control could offer and no grant that would succeed.",
977
+ "This project defines nothing — no product is configured and no key is declared, so there is no entitlement a comp control could offer and no grant that would succeed.",
877
978
  ),
878
979
  })
879
980
  .describe("A project composing payments with an empty catalog. The same answer as not composing it at all."),
@@ -886,8 +987,17 @@ export const PaymentsAdminCatalogResponse = z
886
987
  manualEntitlements: z
887
988
  .array(z.string())
888
989
  .describe(
889
- "Entitlement keys the adopter declared grantable with no product behind them. Offered beside the products because a comp control that omitted them would refuse the grants it then submitted.",
990
+ "The comp-only keys — declared, and sold by no product. Offered beside the products because a comp control that omitted them would refuse the grants it then submitted. Kept under its first name so a client reading an older Worker and a newer one reads one field.",
991
+ ),
992
+ entitlements: z
993
+ .array(PaymentsAdminCatalogEntitlement)
994
+ .optional()
995
+ .describe(
996
+ "Every declared key and what it buys, in the order the adopter wrote them. Absent from a Worker that predates declarations. What an override editor is built from: every editable name, and whether it is a number or a switch.",
890
997
  ),
998
+ defaults: PaymentsAdminCatalogDefaults.nullable()
999
+ .optional()
1000
+ .describe("The free floor, or null when none is declared. Absent from a Worker that predates declarations."),
891
1001
  })
892
1002
  .describe("The catalog, as a management client reads it."),
893
1003
  ])
@@ -915,6 +1025,31 @@ const NextCursor = z
915
1025
  */
916
1026
  export const PaymentsAdminPurchaseView = z
917
1027
  .object({
1028
+ quantity: z
1029
+ .number()
1030
+ .int()
1031
+ .positive()
1032
+ .nullable()
1033
+ .optional()
1034
+ .describe(
1035
+ "How many were bought, as the store stated it, or null where it did not. Absent from a Worker that predates the column.",
1036
+ ),
1037
+ reportedQuantity: z
1038
+ .number()
1039
+ .int()
1040
+ .nonnegative()
1041
+ .nullable()
1042
+ .optional()
1043
+ .describe(
1044
+ "For a quantity-billed subscription, the last count reported to the store, or null when none has been. Absent from a Worker that predates reported billing.",
1045
+ ),
1046
+ reportedAt: z.iso
1047
+ .datetime()
1048
+ .nullable()
1049
+ .optional()
1050
+ .describe(
1051
+ "When that count was reported, ISO-8601, or null. Absent from a Worker that predates reported billing.",
1052
+ ),
918
1053
  id: z.string().describe("The purchase's UUID — its stable identifier on this Worker."),
919
1054
  subjectType: PaymentsSubject.shape.subjectType.describe(
920
1055
  "Whether `subjectId` names a user or an organization. Half the owner: read the two together or a row is attributed to whoever else holds that id.",
@@ -1004,10 +1139,136 @@ export const PaymentsAdminEntitlementView = z
1004
1139
  .describe(
1005
1140
  "The purchase currently granting this entitlement, or null when nothing does — a comp, or a grant whose purchase has lapsed.",
1006
1141
  ),
1142
+ unrestricted: z
1143
+ .boolean()
1144
+ .optional()
1145
+ .describe(
1146
+ "Whether this row's subject is `unrestricted` — every quota unlimited and every feature on, whatever it holds. On every row, because a privilege this large must not be inferable only from a row nobody opens. Absent from a Worker that predates overrides.",
1147
+ ),
1007
1148
  })
1008
1149
  .describe("One entitlement as a management client sees it: whose it is, whether it grants, and why.");
1009
1150
  export type PaymentsAdminEntitlementView = z.output<typeof PaymentsAdminEntitlementView>;
1010
1151
 
1152
+ /** Where an allowance's value came from. */
1153
+ export const PaymentsAllowanceSource = z
1154
+ .enum(["unrestricted", "override", "plan", "default", "none"])
1155
+ .describe(
1156
+ "Where the value came from: the subject's `unrestricted` override, a pin on its override, a key it holds (`key` names it), the free floor, or `none` — nothing declared spoke to it, so it is 0 or false.",
1157
+ );
1158
+ export type PaymentsAllowanceSource = z.output<typeof PaymentsAllowanceSource>;
1159
+
1160
+ /**
1161
+ * One quota for one subject: what applies now, where it came from, and what it would be with the override
1162
+ * removed. **Three facts, because a pane that lets an operator pin one field needs all three** — projecting only
1163
+ * the effective value loses the plan's number the instant an override exists, and the pane can no longer draw
1164
+ * the row it is editing or offer to revert it.
1165
+ */
1166
+ export const PaymentsAdminQuotaView = z
1167
+ .object({
1168
+ name: z.string().describe("The quota name."),
1169
+ effective: WireQuota.describe("What applies now. A whole number, or null for unlimited."),
1170
+ source: PaymentsAllowanceSource,
1171
+ key: z.string().nullable().describe("The entitlement key that supplied `effective`, when `source` is `plan`."),
1172
+ inherited: WireQuota.describe(
1173
+ "What it would be with the override removed — the plan's own number, to show beside a pin and to revert to.",
1174
+ ),
1175
+ inheritedSource: PaymentsAllowanceSource.describe("Where `inherited` came from."),
1176
+ inheritedKey: z.string().nullable().describe("The key that supplied `inherited`, when it is a plan's."),
1177
+ overrideMax: z
1178
+ .number()
1179
+ .int()
1180
+ .nonnegative()
1181
+ .nullable()
1182
+ .describe("The largest number an override may set here for this subject, or null for no ceiling."),
1183
+ })
1184
+ .describe("One quota for one subject: effective, provenance, and inherited.");
1185
+ export type PaymentsAdminQuotaView = z.output<typeof PaymentsAdminQuotaView>;
1186
+
1187
+ /** One feature for one subject, the same three facts. */
1188
+ export const PaymentsAdminFeatureView = z
1189
+ .object({
1190
+ name: z.string().describe("The feature name."),
1191
+ effective: z.boolean().describe("Whether it is on now."),
1192
+ source: PaymentsAllowanceSource,
1193
+ key: z.string().nullable().describe("The entitlement key that supplied `effective`, when `source` is `plan`."),
1194
+ inherited: z.boolean().describe("Whether it would be on with the override removed."),
1195
+ inheritedSource: PaymentsAllowanceSource.describe("Where `inherited` came from."),
1196
+ inheritedKey: z.string().nullable().describe("The key that supplied `inherited`, when it is a plan's."),
1197
+ })
1198
+ .describe("One feature for one subject: effective, provenance, and inherited.");
1199
+ export type PaymentsAdminFeatureView = z.output<typeof PaymentsAdminFeatureView>;
1200
+
1201
+ /** Every declared allowance for one subject. */
1202
+ export const PaymentsAdminAllowancesView = z
1203
+ .object({
1204
+ quotas: z.array(PaymentsAdminQuotaView).describe("Every declared quota, by name."),
1205
+ features: z.array(PaymentsAdminFeatureView).describe("Every declared feature, by name."),
1206
+ })
1207
+ .describe("Every declared allowance for one subject, resolved now.");
1208
+ export type PaymentsAdminAllowancesView = z.output<typeof PaymentsAdminAllowancesView>;
1209
+
1210
+ /** One subject's override row, as a management client sees it. */
1211
+ export const PaymentsAdminOverrideView = z
1212
+ .object({
1213
+ version: z
1214
+ .number()
1215
+ .int()
1216
+ .positive()
1217
+ .describe("The version a set must send back. A set naming an older one is refused as stale."),
1218
+ unrestricted: z
1219
+ .boolean()
1220
+ .describe(
1221
+ "Whether every quota is unlimited and every feature on, except the pins, for every name present and future.",
1222
+ ),
1223
+ quotas: z.record(z.string(), WireQuota).describe("The pinned quotas."),
1224
+ features: z.record(z.string(), z.boolean().describe("Whether the switch is on.")).describe("The pinned features."),
1225
+ reason: z.string().describe("The reason the last write gave."),
1226
+ updatedAt: z.iso.datetime().describe("When it last changed, ISO-8601."),
1227
+ })
1228
+ .describe("One subject's override: its version, its mode, its pins, and why.");
1229
+ export type PaymentsAdminOverrideView = z.output<typeof PaymentsAdminOverrideView>;
1230
+
1231
+ /** One subject's override in the listing: whose it is, and the override. */
1232
+ export const PaymentsAdminOverrideListItem = z
1233
+ .object({
1234
+ subjectType: PaymentsSubject.shape.subjectType.describe("Whether `subjectId` names a user or an organization."),
1235
+ subjectId: PaymentsSubject.shape.subjectId.describe("The subject the override shades."),
1236
+ override: PaymentsAdminOverrideView,
1237
+ })
1238
+ .describe("One subject's override, as the listing pages it.");
1239
+ export type PaymentsAdminOverrideListItem = z.output<typeof PaymentsAdminOverrideListItem>;
1240
+
1241
+ /** `GET {base}/admin/overrides`. */
1242
+ export const PaymentsAdminOverridesResponse = z
1243
+ .object({
1244
+ overrides: z.array(PaymentsAdminOverrideListItem).describe("The page, most recently changed first."),
1245
+ nextCursor: z
1246
+ .string()
1247
+ .nullable()
1248
+ .describe("Where the next page resumes. Null at the end of the list. Opaque — pass it back verbatim."),
1249
+ })
1250
+ .describe("A page of every subject's override — the negotiated numbers, and who is unrestricted.");
1251
+ export type PaymentsAdminOverridesResponse = z.output<typeof PaymentsAdminOverridesResponse>;
1252
+
1253
+ /** What every override write answers: the subject, and its override as it now stands. */
1254
+ export const PaymentsOverrideResponse = z
1255
+ .object({
1256
+ subjectType: PaymentsSubject.shape.subjectType.describe("Which kind of holder, echoed."),
1257
+ subjectId: PaymentsSubject.shape.subjectId.describe("The subject, echoed."),
1258
+ override: PaymentsAdminOverrideView.nullable().describe(
1259
+ "The override after the write, or null when the subject now has none — a whole clear, or a clear of nothing.",
1260
+ ),
1261
+ version: z
1262
+ .number()
1263
+ .int()
1264
+ .nonnegative()
1265
+ .describe(
1266
+ "The version the next write must name. 0 when the subject has never had an override; a cleared one keeps its version, so a stale writer stays stale.",
1267
+ ),
1268
+ })
1269
+ .describe("An override write's result: the subject, its override now, and the version to write against next.");
1270
+ export type PaymentsOverrideResponse = z.output<typeof PaymentsOverrideResponse>;
1271
+
1011
1272
  /**
1012
1273
  * One reconciliation pass, as a management client sees it.
1013
1274
  *
@@ -1070,9 +1331,9 @@ export type PaymentsAdminReconcileRunsResponse = z.output<typeof PaymentsAdminRe
1070
1331
  * job designed not to be blocked on, or invent the answer — and the answer is the one thing an operator pressed
1071
1332
  * the button to find out. So this says *started, here is its id*, and the run log is where the tally lands.
1072
1333
  *
1073
- * **`started: false` is a real answer rather than an error.** The pass is idempotent and the trigger is too: a
1074
- * second press while a run is in flight starts nothing and says so, which is a true sentence about somebody's
1075
- * catalog. Turning that into a 409 would make a nervous operator's second click look like a fault.
1334
+ * **`started` is `true` on every answer today.** A press either starts a pass or is refused with an error;
1335
+ * a second press while a run is in flight starts a second, and the pass is idempotent, so the two converge.
1336
+ * The field stays so a later trigger that declines a duplicate can say so without changing the shape.
1076
1337
  *
1077
1338
  * No count, no duration, no "queued position". Every one of those is a number a screen would print and nobody
1078
1339
  * could stand behind.
@@ -1081,7 +1342,9 @@ export const PaymentsAdminReconcileRunStarted = z
1081
1342
  .object({
1082
1343
  started: z
1083
1344
  .boolean()
1084
- .describe("Whether this request began a pass. False when one was already running, which is not a failure."),
1345
+ .describe(
1346
+ "Whether this request began a pass. Always true today: a press that starts nothing is refused with an error instead.",
1347
+ ),
1085
1348
  runId: z
1086
1349
  .string()
1087
1350
  .nullable()
@@ -1092,6 +1355,53 @@ export const PaymentsAdminReconcileRunStarted = z
1092
1355
  .describe("What a press on the reconciliation trigger produced: whether a pass began, and which one.");
1093
1356
  export type PaymentsAdminReconcileRunStarted = z.output<typeof PaymentsAdminReconcileRunStarted>;
1094
1357
 
1358
+ /** One subject a usage run did not report, and why. */
1359
+ export const PaymentsAdminUsageFindingView = z
1360
+ .object({
1361
+ subjectType: PaymentsSubject.shape.subjectType.describe("Whether `subjectId` names a user or an organization."),
1362
+ subjectId: PaymentsSubject.shape.subjectId.describe("The subject."),
1363
+ productId: z.string().describe("The product whose count was not reported."),
1364
+ reason: z
1365
+ .enum(["unanswered", "not_integer", "negative", "below_min", "above_max", "resolver_failed", "report_failed"])
1366
+ .describe(
1367
+ "Why: the resolver answered nothing, a non-integer, a negative, a count outside min or max, or threw — or the store refused the report.",
1368
+ ),
1369
+ })
1370
+ .describe("One subject a usage run did not report.");
1371
+ export type PaymentsAdminUsageFindingView = z.output<typeof PaymentsAdminUsageFindingView>;
1372
+
1373
+ /** One usage-reporting pass, as a management client sees it. */
1374
+ export const PaymentsAdminUsageRunView = z
1375
+ .object({
1376
+ id: z.string().describe("The run's id."),
1377
+ startedAt: z.iso.datetime().describe("When the pass began, ISO-8601."),
1378
+ finishedAt: z.iso.datetime().describe("When it finished, ISO-8601."),
1379
+ scanned: z.number().int().describe("Subscriptions examined."),
1380
+ reported: z.number().int().describe("Periods a store accepted."),
1381
+ sampled: z.number().int().describe("Daily-peak samples taken for a day still open."),
1382
+ alreadyReported: z.number().int().describe("Periods already reported, so nothing was sent."),
1383
+ skipped: z.number().int().describe("Subjects whose resolver answered nothing. Never reported as zero."),
1384
+ invalid: z
1385
+ .number()
1386
+ .int()
1387
+ .describe("Subjects whose resolver answered a number that may not be billed. Never clamped."),
1388
+ failed: z.number().int().describe("Subjects whose resolver threw, or whose report a store refused."),
1389
+ findings: z
1390
+ .array(PaymentsAdminUsageFindingView)
1391
+ .describe("The subjects not reported and why, up to a hundred. The counts are whole either way."),
1392
+ })
1393
+ .describe("One usage-reporting pass: when it ran, its tally, and who it did not report.");
1394
+ export type PaymentsAdminUsageRunView = z.output<typeof PaymentsAdminUsageRunView>;
1395
+
1396
+ /** `GET {base}/admin/usage-runs`. */
1397
+ export const PaymentsAdminUsageRunsResponse = z
1398
+ .object({
1399
+ runs: z.array(PaymentsAdminUsageRunView).describe("The page, most recently started first."),
1400
+ nextCursor: NextCursor,
1401
+ })
1402
+ .describe("A page of the usage-reporting run log.");
1403
+ export type PaymentsAdminUsageRunsResponse = z.output<typeof PaymentsAdminUsageRunsResponse>;
1404
+
1095
1405
  /** `GET {base}/admin/purchases`. */
1096
1406
  export const PaymentsAdminPurchasesResponse = z
1097
1407
  .object({
@@ -1142,6 +1452,24 @@ export const PaymentsAdminSubjectEntitlementsResponse = z
1142
1452
  entitlements: z
1143
1453
  .array(PaymentsAdminEntitlementView)
1144
1454
  .describe("Every entitlement this subject holds, by key. Empty when it holds none."),
1455
+ unrestricted: z
1456
+ .boolean()
1457
+ .optional()
1458
+ .describe("Whether the subject is `unrestricted`. Absent from a Worker that predates overrides."),
1459
+ overrideVersion: z
1460
+ .number()
1461
+ .int()
1462
+ .nonnegative()
1463
+ .optional()
1464
+ .describe(
1465
+ "The version an override write for this subject must name — 0 when it has none. Absent from a Worker that predates overrides.",
1466
+ ),
1467
+ override: PaymentsAdminOverrideView.nullable()
1468
+ .optional()
1469
+ .describe("The subject's override, or null when it has none. Absent from a Worker that predates overrides."),
1470
+ allowances: PaymentsAdminAllowancesView.optional().describe(
1471
+ "Every declared quota and feature, resolved for this subject now — effective, provenance, inherited. Absent from a Worker that predates declarations.",
1472
+ ),
1145
1473
  })
1146
1474
  .describe("One subject's entitlements, resolved now.");
1147
1475
  export type PaymentsAdminSubjectEntitlementsResponse = z.output<typeof PaymentsAdminSubjectEntitlementsResponse>;