@pithy-sh/payments 0.4.0 → 0.6.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 (180) hide show
  1. package/README.md +10 -3
  2. package/dist/admin/coverage.d.ts.map +1 -1
  3. package/dist/admin/coverage.js +26 -2
  4. package/dist/admin/read.d.ts +48 -1
  5. package/dist/admin/read.d.ts.map +1 -1
  6. package/dist/admin/read.js +89 -2
  7. package/dist/audit/actions.d.ts +13 -0
  8. package/dist/audit/actions.d.ts.map +1 -1
  9. package/dist/audit/actions.js +14 -1
  10. package/dist/capability.d.ts +33 -2
  11. package/dist/capability.d.ts.map +1 -1
  12. package/dist/capability.js +52 -9
  13. package/dist/client/api.d.ts +19 -0
  14. package/dist/client/api.d.ts.map +1 -1
  15. package/dist/client/api.js +34 -1
  16. package/dist/client/hooks.d.ts +20 -1
  17. package/dist/client/hooks.d.ts.map +1 -1
  18. package/dist/client/hooks.js +40 -2
  19. package/dist/client/projection.d.ts +29 -0
  20. package/dist/client/projection.d.ts.map +1 -1
  21. package/dist/config/allowances.d.ts +71 -0
  22. package/dist/config/allowances.d.ts.map +1 -0
  23. package/dist/config/allowances.js +115 -0
  24. package/dist/config/config.d.ts +155 -9
  25. package/dist/config/config.d.ts.map +1 -1
  26. package/dist/config/config.js +164 -14
  27. package/dist/data/meterCounter.d.ts +34 -0
  28. package/dist/data/meterCounter.d.ts.map +1 -0
  29. package/dist/data/meterCounter.js +33 -0
  30. package/dist/data/override.d.ts +56 -0
  31. package/dist/data/override.d.ts.map +1 -0
  32. package/dist/data/override.js +58 -0
  33. package/dist/data/period.d.ts +10 -0
  34. package/dist/data/period.d.ts.map +1 -0
  35. package/dist/data/period.js +37 -0
  36. package/dist/data/purchase.d.ts +2 -1
  37. package/dist/data/purchase.d.ts.map +1 -1
  38. package/dist/data/purchase.js +1 -0
  39. package/dist/data/tables.d.ts +17 -1
  40. package/dist/data/tables.d.ts.map +1 -1
  41. package/dist/data/tables.js +24 -4
  42. package/dist/data/usageReport.d.ts +68 -0
  43. package/dist/data/usageReport.d.ts.map +1 -0
  44. package/dist/data/usageReport.js +55 -0
  45. package/dist/data/usageRun.d.ts +77 -0
  46. package/dist/data/usageRun.d.ts.map +1 -0
  47. package/dist/data/usageRun.js +50 -0
  48. package/dist/data/webhookEvent.d.ts +1 -1
  49. package/dist/entitlement/allowance.d.ts +100 -0
  50. package/dist/entitlement/allowance.d.ts.map +1 -0
  51. package/dist/entitlement/allowance.js +171 -0
  52. package/dist/entitlement/manual.d.ts +5 -5
  53. package/dist/entitlement/manual.js +3 -3
  54. package/dist/entitlement/meter.d.ts +98 -0
  55. package/dist/entitlement/meter.d.ts.map +1 -0
  56. package/dist/entitlement/meter.js +177 -0
  57. package/dist/entitlement/override.d.ts +119 -0
  58. package/dist/entitlement/override.d.ts.map +1 -0
  59. package/dist/entitlement/override.js +256 -0
  60. package/dist/entitlement/resolver.d.ts +2 -1
  61. package/dist/entitlement/resolver.d.ts.map +1 -1
  62. package/dist/entitlement/resolver.js +32 -1
  63. package/dist/error/errors.d.ts +23 -3
  64. package/dist/error/errors.d.ts.map +1 -1
  65. package/dist/error/errors.js +35 -2
  66. package/dist/http/responses.d.ts +367 -0
  67. package/dist/http/responses.d.ts.map +1 -1
  68. package/dist/http/responses.js +146 -7
  69. package/dist/http/routes.d.ts.map +1 -1
  70. package/dist/http/routes.js +270 -16
  71. package/dist/http/schemas.d.ts +54 -0
  72. package/dist/http/schemas.d.ts.map +1 -1
  73. package/dist/http/schemas.js +61 -2
  74. package/dist/http/scopes.d.ts +25 -0
  75. package/dist/http/scopes.d.ts.map +1 -1
  76. package/dist/http/scopes.js +60 -1
  77. package/dist/http/view.d.ts +22 -4
  78. package/dist/http/view.d.ts.map +1 -1
  79. package/dist/http/view.js +88 -7
  80. package/dist/index.d.ts +2 -1
  81. package/dist/index.d.ts.map +1 -1
  82. package/dist/index.js +3 -2
  83. package/dist/migrations/0002_allowances.d.ts +26 -0
  84. package/dist/migrations/0002_allowances.d.ts.map +1 -0
  85. package/dist/migrations/0002_allowances.js +62 -0
  86. package/dist/peer.d.ts +2 -1
  87. package/dist/peer.d.ts.map +1 -1
  88. package/dist/projection/event.d.ts +1 -0
  89. package/dist/projection/event.d.ts.map +1 -1
  90. package/dist/projection/event.js +1 -0
  91. package/dist/projection/writer.d.ts.map +1 -1
  92. package/dist/projection/writer.js +3 -1
  93. package/dist/rails/contract.d.ts +6 -0
  94. package/dist/rails/contract.d.ts.map +1 -1
  95. package/dist/rails/google/playApi.d.ts.map +1 -1
  96. package/dist/rails/google/playApi.js +2 -0
  97. package/dist/rails/paddle/objects.d.ts +2 -0
  98. package/dist/rails/paddle/objects.d.ts.map +1 -1
  99. package/dist/rails/paddle/objects.js +7 -2
  100. package/dist/rails/paddle/usage.d.ts +11 -0
  101. package/dist/rails/paddle/usage.d.ts.map +1 -0
  102. package/dist/rails/paddle/usage.js +49 -0
  103. package/dist/rails/quantity.d.ts +12 -0
  104. package/dist/rails/quantity.d.ts.map +1 -0
  105. package/dist/rails/quantity.js +16 -0
  106. package/dist/rails/stripe/checkout.d.ts.map +1 -1
  107. package/dist/rails/stripe/checkout.js +1 -1
  108. package/dist/rails/stripe/objects.d.ts.map +1 -1
  109. package/dist/rails/stripe/objects.js +3 -0
  110. package/dist/rails/stripe/usage.d.ts +10 -0
  111. package/dist/rails/stripe/usage.d.ts.map +1 -0
  112. package/dist/rails/stripe/usage.js +49 -0
  113. package/dist/usage/pass.d.ts +120 -0
  114. package/dist/usage/pass.d.ts.map +1 -0
  115. package/dist/usage/pass.js +363 -0
  116. package/dist/usage/reporter.d.ts +36 -0
  117. package/dist/usage/reporter.d.ts.map +1 -0
  118. package/dist/usage/reporter.js +2 -0
  119. package/dist/version.generated.d.ts +1 -1
  120. package/dist/version.generated.js +1 -1
  121. package/dist/workflows/report.d.ts.map +1 -1
  122. package/dist/workflows/specs.d.ts +28 -0
  123. package/dist/workflows/specs.d.ts.map +1 -1
  124. package/dist/workflows/specs.js +26 -1
  125. package/dist/workflows/usage.d.ts +38 -0
  126. package/dist/workflows/usage.d.ts.map +1 -0
  127. package/dist/workflows/usage.js +77 -0
  128. package/dist/workflows/worker.js +2 -2
  129. package/docs/entitlements.md +249 -0
  130. package/docs/lemon-squeezy.md +1 -0
  131. package/docs/paddle.md +1 -0
  132. package/package.json +5 -5
  133. package/pithy.manifest.json +3 -8
  134. package/src/admin/coverage.ts +28 -0
  135. package/src/admin/read.ts +173 -1
  136. package/src/audit/actions.ts +13 -0
  137. package/src/capability.ts +87 -9
  138. package/src/client/api.ts +44 -0
  139. package/src/client/hooks.ts +44 -0
  140. package/src/client/projection.ts +31 -0
  141. package/src/config/allowances.ts +211 -0
  142. package/src/config/config.ts +283 -15
  143. package/src/data/meterCounter.ts +38 -0
  144. package/src/data/override.ts +74 -0
  145. package/src/data/period.ts +53 -0
  146. package/src/data/purchase.ts +9 -0
  147. package/src/data/tables.ts +25 -1
  148. package/src/data/usageReport.ts +64 -0
  149. package/src/data/usageRun.ts +66 -0
  150. package/src/entitlement/allowance.ts +213 -0
  151. package/src/entitlement/manual.ts +6 -6
  152. package/src/entitlement/meter.ts +252 -0
  153. package/src/entitlement/override.ts +381 -0
  154. package/src/entitlement/resolver.ts +43 -2
  155. package/src/error/errors.ts +48 -4
  156. package/src/http/responses.ts +305 -4
  157. package/src/http/routes.ts +365 -11
  158. package/src/http/schemas.ts +139 -1
  159. package/src/http/scopes.ts +68 -0
  160. package/src/http/view.ts +112 -7
  161. package/src/index.ts +18 -0
  162. package/src/migrations/0002_allowances.ts +149 -0
  163. package/src/projection/event.ts +9 -0
  164. package/src/projection/writer.ts +4 -0
  165. package/src/rails/contract.ts +6 -0
  166. package/src/rails/google/playApi.ts +2 -0
  167. package/src/rails/paddle/fixtures/subscription-charge.json +19 -0
  168. package/src/rails/paddle/objects.ts +6 -0
  169. package/src/rails/paddle/usage.ts +66 -0
  170. package/src/rails/quantity.ts +14 -0
  171. package/src/rails/stripe/checkout.ts +3 -1
  172. package/src/rails/stripe/fixtures/meter-event-created.json +12 -0
  173. package/src/rails/stripe/objects.ts +4 -0
  174. package/src/rails/stripe/usage.ts +61 -0
  175. package/src/usage/pass.ts +539 -0
  176. package/src/usage/reporter.ts +38 -0
  177. package/src/version.generated.ts +1 -1
  178. package/src/workflows/report.ts +4 -2
  179. package/src/workflows/specs.ts +34 -0
  180. package/src/workflows/usage.ts +97 -0
@@ -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 };
@@ -0,0 +1,77 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { z } from "zod";
4
+ /**
5
+ * Why a subject was not reported on one run. Each is counted and named, and none is ever turned into a
6
+ * number: a skip bills last period's number and leaves a line an operator can act on, where a guess bills a
7
+ * wrong one silently.
8
+ */
9
+ export declare const UsageFindingReason: z.ZodEnum<{
10
+ above_max: "above_max";
11
+ below_min: "below_min";
12
+ negative: "negative";
13
+ not_integer: "not_integer";
14
+ report_failed: "report_failed";
15
+ resolver_failed: "resolver_failed";
16
+ unanswered: "unanswered";
17
+ }>;
18
+ export type UsageFindingReason = z.infer<typeof UsageFindingReason>;
19
+ /** One subject a run did not report, and why. */
20
+ export declare const UsageFinding: z.ZodObject<{
21
+ subjectType: z.ZodEnum<{
22
+ organization: "organization";
23
+ user: "user";
24
+ }>;
25
+ subjectId: z.ZodString;
26
+ productId: z.ZodString;
27
+ reason: z.ZodEnum<{
28
+ above_max: "above_max";
29
+ below_min: "below_min";
30
+ negative: "negative";
31
+ not_integer: "not_integer";
32
+ report_failed: "report_failed";
33
+ resolver_failed: "resolver_failed";
34
+ unanswered: "unanswered";
35
+ }>;
36
+ }, z.core.$strip>;
37
+ export type UsageFinding = z.infer<typeof UsageFinding>;
38
+ /** The most findings one run keeps by name. The counts are always whole; the names are a sample past this. */
39
+ export declare const MAX_USAGE_FINDINGS = 100;
40
+ /**
41
+ * One usage-reporting pass, kept — the row in `pithy_payments_usage_runs`. The same shape and the same
42
+ * reason as `pithy_payments_reconcile_runs`: a silent job and a job that is not running look identical, and
43
+ * a run that reported nothing is the answer to "is it healthy".
44
+ */
45
+ export declare const PaymentsUsageRun: z.ZodObject<{
46
+ id: z.ZodString;
47
+ startedAt: z.ZodCodec<z.ZodUnion<readonly [z.ZodNumber, z.ZodString, z.ZodDate]>, z.ZodDate>;
48
+ finishedAt: z.ZodCodec<z.ZodUnion<readonly [z.ZodNumber, z.ZodString, z.ZodDate]>, z.ZodDate>;
49
+ scanned: z.ZodNumber;
50
+ reported: z.ZodNumber;
51
+ sampled: z.ZodNumber;
52
+ alreadyReported: z.ZodNumber;
53
+ skipped: z.ZodNumber;
54
+ invalid: z.ZodNumber;
55
+ failed: z.ZodNumber;
56
+ findings: import("@pithy-sh/core/src/data/codecs").SqliteJson<z.ZodArray<z.ZodObject<{
57
+ subjectType: z.ZodEnum<{
58
+ organization: "organization";
59
+ user: "user";
60
+ }>;
61
+ subjectId: z.ZodString;
62
+ productId: z.ZodString;
63
+ reason: z.ZodEnum<{
64
+ above_max: "above_max";
65
+ below_min: "below_min";
66
+ negative: "negative";
67
+ not_integer: "not_integer";
68
+ report_failed: "report_failed";
69
+ resolver_failed: "resolver_failed";
70
+ unanswered: "unanswered";
71
+ }>;
72
+ }, z.core.$strip>>>;
73
+ createdAt: z.ZodCodec<z.ZodUnion<readonly [z.ZodNumber, z.ZodString, z.ZodDate]>, z.ZodDate>;
74
+ }, z.core.$strip>;
75
+ export type PaymentsUsageRun = z.output<typeof PaymentsUsageRun>;
76
+ export type PaymentsUsageRunRow = z.input<typeof PaymentsUsageRun>;
77
+ //# sourceMappingURL=usageRun.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"usageRun.d.ts","sourceRoot":"","sources":["../../src/data/usageRun.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAGxB;;;;GAIG;AACH,eAAO,MAAM,kBAAkB;;;;;;;;EAI5B,CAAC;AACJ,MAAM,MAAM,kBAAkB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,kBAAkB,CAAC,CAAC;AAEpE,iDAAiD;AACjD,eAAO,MAAM,YAAY;;;;;;;;;;;;;;;;iBAOsC,CAAC;AAChE,MAAM,MAAM,YAAY,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,YAAY,CAAC,CAAC;AAExD,8GAA8G;AAC9G,eAAO,MAAM,kBAAkB,MAAM,CAAC;AAEtC;;;;GAIG;AACH,eAAO,MAAM,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAyBgF,CAAC;AAC9G,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"}
@@ -0,0 +1,50 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { PaymentsSubject } from "./subject.js";
4
+ import { z } from "zod";
5
+ import { SQLiteDate, sqliteJson } from "@pithy-sh/core/src/data/codecs";
6
+ //#region src/data/usageRun.ts
7
+ /**
8
+ * Why a subject was not reported on one run. Each is counted and named, and none is ever turned into a
9
+ * number: a skip bills last period's number and leaves a line an operator can act on, where a guess bills a
10
+ * wrong one silently.
11
+ */
12
+ const UsageFindingReason = z.enum([
13
+ "unanswered",
14
+ "not_integer",
15
+ "negative",
16
+ "below_min",
17
+ "above_max",
18
+ "resolver_failed",
19
+ "report_failed"
20
+ ]).describe("Why a subject was not reported: the resolver answered nothing, answered a non-integer, a negative, a count outside the product's min or max, or threw — or the store refused the report.");
21
+ /** One subject a run did not report, and why. */
22
+ const UsageFinding = z.object({
23
+ subjectType: PaymentsSubject.shape.subjectType.describe("Whether `subjectId` names a user or an organization."),
24
+ subjectId: PaymentsSubject.shape.subjectId.describe("The subject."),
25
+ productId: z.string().describe("The product whose count was not reported."),
26
+ reason: UsageFindingReason.describe("Why.")
27
+ }).describe("One subject a usage run did not report, and why.");
28
+ /** The most findings one run keeps by name. The counts are always whole; the names are a sample past this. */
29
+ const MAX_USAGE_FINDINGS = 100;
30
+ /**
31
+ * One usage-reporting pass, kept — the row in `pithy_payments_usage_runs`. The same shape and the same
32
+ * reason as `pithy_payments_reconcile_runs`: a silent job and a job that is not running look identical, and
33
+ * a run that reported nothing is the answer to "is it healthy".
34
+ */
35
+ const PaymentsUsageRun = z.object({
36
+ id: z.string().describe("The run's UUID."),
37
+ startedAt: SQLiteDate.describe("When the pass began."),
38
+ finishedAt: SQLiteDate.describe("When the pass finished."),
39
+ scanned: z.number().int().nonnegative().describe("Subscriptions examined."),
40
+ reported: z.number().int().nonnegative().describe("Periods a store accepted a report for on this run."),
41
+ sampled: z.number().int().nonnegative().describe("Daily-peak samples taken for a day still open."),
42
+ alreadyReported: z.number().int().nonnegative().describe("Periods found already reported or claimed, so nothing was sent. The replay count."),
43
+ skipped: z.number().int().nonnegative().describe("Subjects whose resolver answered nothing."),
44
+ invalid: z.number().int().nonnegative().describe("Subjects whose resolver answered a non-integer, a negative, or a count outside min and max."),
45
+ failed: z.number().int().nonnegative().describe("Subjects whose resolver threw, or whose report a store refused."),
46
+ findings: sqliteJson(z.array(UsageFinding)).describe(`The subjects not reported, and why — up to 100. The counts above are whole either way.`),
47
+ createdAt: SQLiteDate.describe("When this row was written.")
48
+ }).describe("One usage-reporting pass — when it ran and its tally — the row in `pithy_payments_usage_runs`.");
49
+ //#endregion
50
+ export { MAX_USAGE_FINDINGS, PaymentsUsageRun, UsageFinding, UsageFindingReason };
@@ -45,7 +45,7 @@ export declare const PaymentsWebhookEvent: z.ZodObject<{
45
45
  stripe: "stripe";
46
46
  }>;
47
47
  providerEventId: z.ZodString;
48
- payload: z.ZodCodec<z.ZodUnion<readonly [z.ZodString, z.ZodRecord<z.ZodString, z.ZodUnknown>]>, z.ZodRecord<z.ZodString, z.ZodUnknown>>;
48
+ payload: import("@pithy-sh/core/src/data/codecs").SqliteJson<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
49
49
  receivedAt: z.ZodCodec<z.ZodUnion<readonly [z.ZodNumber, z.ZodString, z.ZodDate]>, z.ZodDate>;
50
50
  processedAt: z.ZodNullable<z.ZodCodec<z.ZodUnion<readonly [z.ZodNumber, z.ZodString, z.ZodDate]>, z.ZodDate>>;
51
51
  abandonedAt: z.ZodOptional<z.ZodNullable<z.ZodCodec<z.ZodUnion<readonly [z.ZodNumber, z.ZodString, z.ZodDate]>, z.ZodDate>>>;
@@ -0,0 +1,100 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { type AllowanceDeclarations, type FeatureMap, type QuotaMap, type QuotaValue } from "../config/allowances";
4
+ /**
5
+ * How much a subject may have, resolved — the one implementation of the order every reader shares.
6
+ *
7
+ * **The order, and it fails closed:**
8
+ *
9
+ * 1. The subject's **override**, when it names this allowance. A pin beats everything, `unrestricted`
10
+ * included, so `unrestricted` with `emails: 20000` is unlimited everywhere except email.
11
+ * 2. **`unrestricted`**, when the override carries it: unlimited and on, for every name — including one
12
+ * declared after the override was written, which is why it is a mode and not a list.
13
+ * 3. The **highest** value among every key the subject holds that speaks to this name. `null` (unlimited)
14
+ * beats every number, and a feature is on when any held key turns it on. A customer holding two products
15
+ * is owed the larger of what they bought, and an upgrade overlapping an old subscription's tail must
16
+ * never read as a downgrade for those weeks.
17
+ * 4. **`defaults`**, the free floor, for a name no held key speaks to.
18
+ * 5. **`0` for a quota, `false` for a feature.** Never unlimited. A name that resolved to unlimited because
19
+ * nothing declared it is a paywall that silently does not exist.
20
+ *
21
+ * **The reader takes no key, and that is the point.** A caller does not know which tier the subject is on,
22
+ * and during an upgrade overlap it holds two. Resolving across every held key is what makes a tier ladder
23
+ * unnecessary: an adopter compares numbers, never ranks, and the kit stays without an opinion on whether
24
+ * `growth` outranks `start`.
25
+ *
26
+ * Pure: the caller hands in the held keys and the override row, so the order is testable without a
27
+ * database, and the gate's middleware, the admin read and the meters all reach the same answer.
28
+ */
29
+ /** Where an allowance's value came from. `none` is the hard floor: nothing declared spoke to it. */
30
+ export type AllowanceSource = "unrestricted" | "override" | "plan" | "default" | "none";
31
+ /** What a subject's override says. Sparse: a name it does not carry resolves normally. */
32
+ export interface AllowanceOverride {
33
+ /** Unlimited and on, for every name present and future, except the names the patch pins. */
34
+ unrestricted: boolean;
35
+ /** Pinned quotas, by name. */
36
+ quotas: QuotaMap;
37
+ /** Pinned features, by name. */
38
+ features: FeatureMap;
39
+ }
40
+ /** One resolved value and where it came from. */
41
+ export interface ResolvedValue<T> {
42
+ /** The value. */
43
+ value: T;
44
+ /** Where it came from. */
45
+ source: AllowanceSource;
46
+ /** The entitlement key that supplied it, when `source` is `plan`. Null otherwise. */
47
+ key: string | null;
48
+ }
49
+ /** One quota, resolved: what applies now, and what would apply with the override removed. */
50
+ export interface ResolvedQuota {
51
+ /** The quota name. */
52
+ name: string;
53
+ /** What applies now. */
54
+ effective: ResolvedValue<QuotaValue>;
55
+ /** What would apply with no override — the plan's own number, for a pane to show and revert to. */
56
+ inherited: ResolvedValue<QuotaValue>;
57
+ }
58
+ /** One feature, resolved. */
59
+ export interface ResolvedFeature {
60
+ /** The feature name. */
61
+ name: string;
62
+ /** What applies now. */
63
+ effective: ResolvedValue<boolean>;
64
+ /** What would apply with no override. */
65
+ inherited: ResolvedValue<boolean>;
66
+ }
67
+ /** Every declared allowance for one subject, resolved. */
68
+ export interface ResolvedAllowances {
69
+ /** Every declared quota, by name order. */
70
+ quotas: ResolvedQuota[];
71
+ /** Every declared feature, by name order. */
72
+ features: ResolvedFeature[];
73
+ }
74
+ /** What resolution reads: the declarations, the keys granting now, and the override row if there is one. */
75
+ export interface AllowanceInput {
76
+ /** The project's declarations. */
77
+ declarations: AllowanceDeclarations;
78
+ /** Every entitlement key the subject holds that grants access now. */
79
+ held: ReadonlySet<string>;
80
+ /** The subject's override, or null. */
81
+ override: AllowanceOverride | null;
82
+ }
83
+ /** One quota, resolved through the whole order. */
84
+ export declare function resolveQuota(input: AllowanceInput, name: string): ResolvedQuota;
85
+ /** One feature, resolved through the whole order. */
86
+ export declare function resolveFeature(input: AllowanceInput, name: string): ResolvedFeature;
87
+ /** Every declared quota and feature for one subject. What the admin read projects. */
88
+ export declare function resolveAllowances(input: AllowanceInput): ResolvedAllowances;
89
+ /**
90
+ * Refuse a read of a quota nobody declared, naming it and listing what is declared.
91
+ *
92
+ * **A hard failure, never a default.** `quota(c, "emals")` resolving to `0` would deny quietly, and
93
+ * resolving to unlimited would be a paywall that does not exist — and a typo in a name is exactly the bug
94
+ * that reads as either. `core/internal`, because it is the adopter's code that is wrong, and an operator
95
+ * reading the log is who fixes it.
96
+ */
97
+ export declare function requireDeclaredQuota(declarations: AllowanceDeclarations, name: string): void;
98
+ /** The same refusal for a feature. */
99
+ export declare function requireDeclaredFeature(declarations: AllowanceDeclarations, name: string): void;
100
+ //# sourceMappingURL=allowance.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"allowance.d.ts","sourceRoot":"","sources":["../../src/entitlement/allowance.ts"],"names":[],"mappings":"AAIA,OAAO,EACL,KAAK,qBAAqB,EAG1B,KAAK,UAAU,EACf,KAAK,QAAQ,EACb,KAAK,UAAU,EAChB,MAAM,sBAAsB,CAAC;AAE9B;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAEH,oGAAoG;AACpG,MAAM,MAAM,eAAe,GAAG,cAAc,GAAG,UAAU,GAAG,MAAM,GAAG,SAAS,GAAG,MAAM,CAAC;AAExF,0FAA0F;AAC1F,MAAM,WAAW,iBAAiB;IAChC,4FAA4F;IAC5F,YAAY,EAAE,OAAO,CAAC;IACtB,8BAA8B;IAC9B,MAAM,EAAE,QAAQ,CAAC;IACjB,gCAAgC;IAChC,QAAQ,EAAE,UAAU,CAAC;CACtB;AAED,iDAAiD;AACjD,MAAM,WAAW,aAAa,CAAC,CAAC;IAC9B,iBAAiB;IACjB,KAAK,EAAE,CAAC,CAAC;IACT,0BAA0B;IAC1B,MAAM,EAAE,eAAe,CAAC;IACxB,qFAAqF;IACrF,GAAG,EAAE,MAAM,GAAG,IAAI,CAAC;CACpB;AAED,6FAA6F;AAC7F,MAAM,WAAW,aAAa;IAC5B,sBAAsB;IACtB,IAAI,EAAE,MAAM,CAAC;IACb,wBAAwB;IACxB,SAAS,EAAE,aAAa,CAAC,UAAU,CAAC,CAAC;IACrC,mGAAmG;IACnG,SAAS,EAAE,aAAa,CAAC,UAAU,CAAC,CAAC;CACtC;AAED,6BAA6B;AAC7B,MAAM,WAAW,eAAe;IAC9B,wBAAwB;IACxB,IAAI,EAAE,MAAM,CAAC;IACb,wBAAwB;IACxB,SAAS,EAAE,aAAa,CAAC,OAAO,CAAC,CAAC;IAClC,yCAAyC;IACzC,SAAS,EAAE,aAAa,CAAC,OAAO,CAAC,CAAC;CACnC;AAED,0DAA0D;AAC1D,MAAM,WAAW,kBAAkB;IACjC,2CAA2C;IAC3C,MAAM,EAAE,aAAa,EAAE,CAAC;IACxB,6CAA6C;IAC7C,QAAQ,EAAE,eAAe,EAAE,CAAC;CAC7B;AAED,4GAA4G;AAC5G,MAAM,WAAW,cAAc;IAC7B,kCAAkC;IAClC,YAAY,EAAE,qBAAqB,CAAC;IACpC,sEAAsE;IACtE,IAAI,EAAE,WAAW,CAAC,MAAM,CAAC,CAAC;IAC1B,uCAAuC;IACvC,QAAQ,EAAE,iBAAiB,GAAG,IAAI,CAAC;CACpC;AAqDD,mDAAmD;AACnD,wBAAgB,YAAY,CAAC,KAAK,EAAE,cAAc,EAAE,IAAI,EAAE,MAAM,GAAG,aAAa,CAQ/E;AAED,qDAAqD;AACrD,wBAAgB,cAAc,CAAC,KAAK,EAAE,cAAc,EAAE,IAAI,EAAE,MAAM,GAAG,eAAe,CAYnF;AAED,sFAAsF;AACtF,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,cAAc,GAAG,kBAAkB,CAK3E;AAED;;;;;;;GAOG;AACH,wBAAgB,oBAAoB,CAAC,YAAY,EAAE,qBAAqB,EAAE,IAAI,EAAE,MAAM,GAAG,IAAI,CAQ5F;AAED,sCAAsC;AACtC,wBAAgB,sBAAsB,CAAC,YAAY,EAAE,qBAAqB,EAAE,IAAI,EAAE,MAAM,GAAG,IAAI,CAQ9F"}
@@ -0,0 +1,171 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { declaredFeatureNames, declaredQuotaNames } from "../config/allowances.js";
4
+ import { InternalError } from "@pithy-sh/core/src/error/pithyError";
5
+ //#region src/entitlement/allowance.ts
6
+ /** Whether `candidate` is more than `current` — `null` is unlimited and beats every number. */
7
+ function larger(candidate, current) {
8
+ if (current === null) return false;
9
+ if (candidate === null) return true;
10
+ return candidate > current;
11
+ }
12
+ /**
13
+ * A quota map's value for a name the caller has already checked is present. `?? 0` would be wrong here and
14
+ * dangerously so: `null` is unlimited, and a nullish fallback reads it as nothing.
15
+ */
16
+ function quotaAt(map, name) {
17
+ const value = map[name];
18
+ return value === void 0 ? 0 : value;
19
+ }
20
+ /** Held keys in a stable order, so the key named as a value's source does not depend on set order. */
21
+ function heldInOrder(held) {
22
+ return [...held].sort();
23
+ }
24
+ /** The value a quota has with no override: highest held, then the floor, then zero. */
25
+ function inheritedQuota(input, name) {
26
+ let best;
27
+ for (const key of heldInOrder(input.held)) {
28
+ const declaration = input.declarations.entitlements[key];
29
+ if (declaration === void 0 || !(name in declaration.quotas)) continue;
30
+ const value = quotaAt(declaration.quotas, name);
31
+ if (best === void 0 || larger(value, best.value)) best = {
32
+ value,
33
+ source: "plan",
34
+ key
35
+ };
36
+ }
37
+ if (best !== void 0) return best;
38
+ const floor = input.declarations.defaults?.quotas;
39
+ if (floor !== void 0 && name in floor) return {
40
+ value: quotaAt(floor, name),
41
+ source: "default",
42
+ key: null
43
+ };
44
+ return {
45
+ value: 0,
46
+ source: "none",
47
+ key: null
48
+ };
49
+ }
50
+ /** The value a feature has with no override: on if any held key says on, then the floor, then off. */
51
+ function inheritedFeature(input, name) {
52
+ let spoke;
53
+ for (const key of heldInOrder(input.held)) {
54
+ const declaration = input.declarations.entitlements[key];
55
+ if (declaration === void 0 || !(name in declaration.features)) continue;
56
+ if (declaration.features[name] === true) return {
57
+ value: true,
58
+ source: "plan",
59
+ key
60
+ };
61
+ spoke ??= {
62
+ value: false,
63
+ source: "plan",
64
+ key
65
+ };
66
+ }
67
+ if (spoke !== void 0) return spoke;
68
+ const floor = input.declarations.defaults?.features;
69
+ if (floor !== void 0 && name in floor) return {
70
+ value: floor[name] === true,
71
+ source: "default",
72
+ key: null
73
+ };
74
+ return {
75
+ value: false,
76
+ source: "none",
77
+ key: null
78
+ };
79
+ }
80
+ /** One quota, resolved through the whole order. */
81
+ function resolveQuota(input, name) {
82
+ const inherited = inheritedQuota(input, name);
83
+ const override = input.override;
84
+ if (override !== null && name in override.quotas) return {
85
+ name,
86
+ effective: {
87
+ value: quotaAt(override.quotas, name),
88
+ source: "override",
89
+ key: null
90
+ },
91
+ inherited
92
+ };
93
+ if (override?.unrestricted) return {
94
+ name,
95
+ effective: {
96
+ value: null,
97
+ source: "unrestricted",
98
+ key: null
99
+ },
100
+ inherited
101
+ };
102
+ return {
103
+ name,
104
+ effective: inherited,
105
+ inherited
106
+ };
107
+ }
108
+ /** One feature, resolved through the whole order. */
109
+ function resolveFeature(input, name) {
110
+ const inherited = inheritedFeature(input, name);
111
+ const override = input.override;
112
+ if (override !== null && name in override.features) return {
113
+ name,
114
+ effective: {
115
+ value: override.features[name] === true,
116
+ source: "override",
117
+ key: null
118
+ },
119
+ inherited
120
+ };
121
+ if (override?.unrestricted) return {
122
+ name,
123
+ effective: {
124
+ value: true,
125
+ source: "unrestricted",
126
+ key: null
127
+ },
128
+ inherited
129
+ };
130
+ return {
131
+ name,
132
+ effective: inherited,
133
+ inherited
134
+ };
135
+ }
136
+ /** Every declared quota and feature for one subject. What the admin read projects. */
137
+ function resolveAllowances(input) {
138
+ return {
139
+ quotas: declaredQuotaNames(input.declarations).map((name) => resolveQuota(input, name)),
140
+ features: declaredFeatureNames(input.declarations).map((name) => resolveFeature(input, name))
141
+ };
142
+ }
143
+ /**
144
+ * Refuse a read of a quota nobody declared, naming it and listing what is declared.
145
+ *
146
+ * **A hard failure, never a default.** `quota(c, "emals")` resolving to `0` would deny quietly, and
147
+ * resolving to unlimited would be a paywall that does not exist — and a typo in a name is exactly the bug
148
+ * that reads as either. `core/internal`, because it is the adopter's code that is wrong, and an operator
149
+ * reading the log is who fixes it.
150
+ */
151
+ function requireDeclaredQuota(declarations, name) {
152
+ const declared = declaredQuotaNames(declarations);
153
+ if (declared.includes(name)) return;
154
+ throw new InternalError({
155
+ message: `No quota "${name}" is declared.`,
156
+ action: "Declare it under `quotas` on an entitlement or in `defaults` in pithy.config.ts, or correct the name.",
157
+ detail: `quota("${name}") names nothing the payments declarations mention. Declared quotas: ${declared.join(", ") || "none"}.`
158
+ });
159
+ }
160
+ /** The same refusal for a feature. */
161
+ function requireDeclaredFeature(declarations, name) {
162
+ const declared = declaredFeatureNames(declarations);
163
+ if (declared.includes(name)) return;
164
+ throw new InternalError({
165
+ message: `No feature "${name}" is declared.`,
166
+ action: "Declare it under `features` on an entitlement or in `defaults` in pithy.config.ts, or correct the name.",
167
+ detail: `feature("${name}") names nothing the payments declarations mention. Declared features: ${declared.join(", ") || "none"}.`
168
+ });
169
+ }
170
+ //#endregion
171
+ export { requireDeclaredFeature, requireDeclaredQuota, resolveAllowances, resolveFeature, resolveQuota };
@@ -36,9 +36,9 @@ import { type PaymentsSubject } from "../data/subject";
36
36
  * exported, and the exported grant takes a {@link PaymentsConfig} it cannot be called without. A caller
37
37
  * cannot reach the unchecked half from outside this module, and the type says why.
38
38
  *
39
- * Comping a key nothing sells is therefore **declared** rather than achieved by nobody checking:
40
- * `manualEntitlements` in `pithy.config.ts` is where an adopter names the keys they comp but do not sell,
41
- * and those keys are grantable and are published on the catalog read beside the products. The check reads
39
+ * Comping a key nothing sells is therefore **declared** rather than achieved by nobody checking: a key the
40
+ * `entitlements` map in `pithy.config.ts` declares and no product sells is comp-only, grantable, and
41
+ * published on the catalog read beside the products. The check reads
42
42
  * `grantableEntitlements`, so that escape travels with it. Only grants are constrained. A revoke is not, or
43
43
  * dropping a product from the catalog would be irreversible for every account still holding its key — which
44
44
  * is why {@link revokeEntitlement} takes no config, and must never grow one.
@@ -87,8 +87,8 @@ export interface ManualEntitlementOptions {
87
87
  * Grant an entitlement by hand, and hold it against the projection. Idempotent; overwrites whatever the
88
88
  * projection last derived for this key, and survives every later purchase event for it.
89
89
  *
90
- * Refuses a key this project does not define — no product grants it and `manualEntitlements` does not
91
- * declare it — before any row is written. The config is a parameter rather than a closure because a grant
90
+ * Refuses a key this project does not define — the `entitlements` map does not declare it — before any row
91
+ * is written. The config is a parameter rather than a closure because a grant
92
92
  * without one is the defect: see the module doc.
93
93
  */
94
94
  export declare function grantEntitlement(d1: D1Database, config: PaymentsConfig, input: ManualEntitlementInput, options?: ManualEntitlementOptions): Promise<PaymentsEntitlement>;
@@ -12,15 +12,15 @@ import { withD1Retry } from "@pithy-sh/core/src/data/withD1Retry";
12
12
  * Grant an entitlement by hand, and hold it against the projection. Idempotent; overwrites whatever the
13
13
  * projection last derived for this key, and survives every later purchase event for it.
14
14
  *
15
- * Refuses a key this project does not define — no product grants it and `manualEntitlements` does not
16
- * declare it — before any row is written. The config is a parameter rather than a closure because a grant
15
+ * Refuses a key this project does not define — the `entitlements` map does not declare it — before any row
16
+ * is written. The config is a parameter rather than a closure because a grant
17
17
  * without one is the defect: see the module doc.
18
18
  */
19
19
  async function grantEntitlement(d1, config, input, options = {}) {
20
20
  const grantable = grantableEntitlements(config);
21
21
  if (!grantable.has(input.entitlement)) throw new PaymentsEntitlementNotInCatalogError({
22
22
  message: `No entitlement "${input.entitlement}" is defined here.`,
23
- detail: `No product grants "${input.entitlement}" and \`manualEntitlements\` does not declare it. Defined: ${[...grantable].sort().join(", ") || "nothing"}.`
23
+ detail: `\`entitlements\` declares no "${input.entitlement}". Declared: ${[...grantable].sort().join(", ") || "nothing"}.`
24
24
  });
25
25
  return writeEntitlement(d1, input, true, options);
26
26
  }