@klappay/types 1.1.2 → 2.0.1

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.
package/dist/index.mjs CHANGED
@@ -3,7 +3,7 @@ import { z } from "zod";
3
3
  var ErrorPayloadSchema = z.object({
4
4
  error: z.object({
5
5
  code: z.string().describe(
6
- "A stable, machine-readable error identifier (e.g. `validation_error`, `invalid_credentials`)."
6
+ "A stable, machine-readable error identifier (e.g. `validation_error`, `charge_not_found`)."
7
7
  ),
8
8
  message: z.string().describe(
9
9
  "Human-readable explanation, safe to log or show a developer \u2014 not meant for end users."
@@ -18,9 +18,27 @@ var EnvironmentSchema = z2.enum(["live", "test"]).describe(
18
18
  "`live` or `test`, matching the `klap_live_.../klap_test_...` prefix of the API key that created or is scoped to this resource. `live` settles on Base mainnet with real funds; `test` settles on Base Sepolia, a separate testnet \u2014 real on-chain activity, but never real money."
19
19
  );
20
20
 
21
- // src/networks.ts
21
+ // src/api-key-scopes.ts
22
22
  import { z as z3 } from "zod";
23
- var NetworkSchema = z3.enum(["base", "optimism", "polygon", "ethereum", "arbitrum", "avalanche", "bnb"]).describe("The blockchain a charge/payment is on.");
23
+ var ApiKeyScopeSchema = z3.enum([
24
+ "charges:read",
25
+ "charges:write",
26
+ "webhooks:read",
27
+ "webhooks:write",
28
+ "webhooks:manage_secret",
29
+ "metrics:read",
30
+ "metrics:charges:read",
31
+ "metrics:transactions:read",
32
+ "metrics:distributions:read",
33
+ "sandbox:trigger"
34
+ ]).describe(
35
+ "What an API key is allowed to do, independent of `tenantId`/`environment` (which scope *whose* data, not *what actions*). A key with none of these can still authenticate but every scoped route rejects it with `403 insufficient_scope`. `metrics:read` alone grants every metrics resource; `metrics:{resource}:read` grants only that one \u2014 a key can hold either or both."
36
+ );
37
+ var API_KEY_SCOPES = ApiKeyScopeSchema.options;
38
+
39
+ // src/networks.ts
40
+ import { z as z4 } from "zod";
41
+ var NetworkSchema = z4.enum(["base", "optimism", "polygon", "ethereum", "arbitrum", "avalanche", "bnb"]).describe("The blockchain a charge/payment is on.");
24
42
  var NETWORK_LABELS = {
25
43
  base: "Base",
26
44
  optimism: "Optimism",
@@ -59,29 +77,29 @@ var OPERATIONAL_NETWORKS = [
59
77
  ];
60
78
 
61
79
  // src/pagination.ts
62
- import { z as z4 } from "zod";
80
+ import { z as z5 } from "zod";
63
81
  var PAGINATION_LIMIT_MIN = 1;
64
82
  var PAGINATION_LIMIT_MAX = 100;
65
83
  var PAGINATION_LIMIT_DEFAULT = 20;
66
- var PaginationQuerySchema = z4.object({
67
- limit: z4.coerce.number().min(PAGINATION_LIMIT_MIN).max(PAGINATION_LIMIT_MAX).default(PAGINATION_LIMIT_DEFAULT).describe(
84
+ var PaginationQuerySchema = z5.object({
85
+ limit: z5.coerce.number().min(PAGINATION_LIMIT_MIN).max(PAGINATION_LIMIT_MAX).default(PAGINATION_LIMIT_DEFAULT).describe(
68
86
  `Max items to return per page (${PAGINATION_LIMIT_MIN}\u2013${PAGINATION_LIMIT_MAX}, default ${PAGINATION_LIMIT_DEFAULT}).`
69
87
  ),
70
- cursor: z4.string().max(500).optional().describe(
88
+ cursor: z5.string().max(500).optional().describe(
71
89
  "Opaque \u2014 pass the previous response's `nextCursor` verbatim to fetch the next page. Never construct or parse this value yourself; its shape is not part of the public contract and may change."
72
90
  )
73
91
  });
74
92
  function paginatedSchema(itemSchema) {
75
- return z4.object({
76
- data: z4.array(itemSchema),
77
- nextCursor: z4.string().nullable().describe("Pass as `cursor` to fetch the next page. `null` when there are no more results."),
78
- hasMore: z4.boolean()
93
+ return z5.object({
94
+ data: z5.array(itemSchema),
95
+ nextCursor: z5.string().nullable().describe("Pass as `cursor` to fetch the next page. `null` when there are no more results."),
96
+ hasMore: z5.boolean()
79
97
  });
80
98
  }
81
99
 
82
100
  // src/tokens.ts
83
- import { z as z5 } from "zod";
84
- var TokenSchema = z5.enum(["USDC", "USDT"]).describe(
101
+ import { z as z6 } from "zod";
102
+ var TokenSchema = z6.enum(["USDC", "USDT"]).describe(
85
103
  `Which stablecoin the payer will send. Support depends on both \`network\` and \`environment\` \u2014 not every token/network/environment combination is deployed; today, both \`USDC\` and \`USDT\` are deployed on every operational network's \`live\` side except BNB Chain (\`${OPERATIONAL_NETWORKS.join(", ")}\`), but \`test\` coverage varies per network \u2014 Base, Optimism, and Ethereum each have a \`test\` environment (\`USDC\` only; none has an official Sepolia USDT), Arbitrum, Polygon, Avalanche, and BNB Chain have none yet (0xSplits hasn't deployed on Arbitrum Sepolia and has no Polygon, Avalanche Fuji, or BNB testnet support at all). An unconfigured combination is rejected with \`422 token_not_supported\`, not silently accepted. **BNB Chain's \`USDC\` address is Binance-Peg USDC, not an official Circle deployment** \u2014 Circle does not issue native USDC on BNB Chain at all; this is a Binance-custodied, 1:1-pegged BEP-20 token, a materially different trust model than every other \`TOKEN_ADDRESSES\` entry (all verified directly against their real issuer). Accepted at the payer's own risk \u2014 Klappay does not verify or guarantee Binance's collateral backing it. \`USDT\` on BNB Chain is Tether's own official issuance, same trust model as everywhere else. More tokens/networks are expected to be added over time \u2014 check \`TOKEN_ADDRESSES\` in \`@klappay/types\` (or a future \`GET /v1/networks\` capabilities endpoint) for the exact current matrix rather than assuming full coverage.`
86
104
  );
87
105
  var TOKEN_DECIMALS = 6;
@@ -116,30 +134,27 @@ var TOKEN_ADDRESSES = {
116
134
  };
117
135
 
118
136
  // src/charges.ts
119
- import { z as z6 } from "zod";
120
- var ChargeStatusSchema = z6.enum(["pending", "partially_paid", "confirmed", "expired", "underpaid", "canceled"]).describe(
121
- "Payment progress, from the payer side. `pending`: created, nothing received yet. `partially_paid`: some funds received, less than `amount`. `confirmed`: full amount received (or more \u2014 see `isOverpaid`). `expired`: `expiresAt` passed with zero funds received. `underpaid`: `expiresAt` passed while `partially_paid`. `canceled`: the merchant explicitly canceled it via `POST /v1/charges/{id}/cancel` before it resolved on its own \u2014 unlike every other terminal status, this one is never reached automatically. This never reflects whether funds actually reached the merchant \u2014 see `settlementStatus` for that."
137
+ import { z as z7 } from "zod";
138
+ var ChargeStatusSchema = z7.enum(["pending", "partially_paid", "confirmed", "expired", "underpaid"]).describe(
139
+ "Payment progress, from the payer side. `pending`: created, nothing received yet. `partially_paid`: some funds received, less than `amount`. `confirmed`: full amount received (or more \u2014 see `isOverpaid`). `expired`: `expiresAt` passed with zero funds received. `underpaid`: `expiresAt` passed while `partially_paid`. Every status is reached automatically, on its own timeline \u2014 there is no merchant-initiated cancellation. This never reflects whether funds actually reached the merchant \u2014 see `settlementStatus` for that."
122
140
  );
123
- var SettlementStatusSchema = z6.enum(["pending", "completed", "failed"]).describe(
141
+ var SettlementStatusSchema = z7.enum(["pending", "completed", "failed"]).describe(
124
142
  "Progress of the payout to the merchant's wallet, a separate step from `status` \u2014 `status: confirmed` only means the payment was detected on-chain, not that the merchant has been paid yet. `pending`: payment detected, payout not yet attempted. `completed`: the merchant's wallet has the funds. `failed`: the payout attempt failed and retries were exhausted (rare; contact support). `null` on the parent `Charge` means no payout has been attempted yet \u2014 nothing has been received, or the charge is still in progress."
125
143
  );
126
- var ChargeModeSchema = z6.enum(["standard", "continuous"]).describe(
127
- "`standard` (default): the usual lifecycle \u2014 accumulates transfers toward one resolution (`confirmed`/`expired`/`underpaid`), settles once. `continuous`: never resolves \u2014 `status` stays `pending` for the charge's entire life, and every credited transfer settles independently instead of accumulating toward one confirmation (see `charge.contribution_received`/`charge.contribution_settled`). Requires both `amount` and `expiresIn` to be omitted \u2014 there's no goal to accumulate toward and no deadline for something meant to run indefinitely (a link in a creator's bio, a permanent collection address). Not inferred from omitting those two fields \u2014 an explicit, deliberate choice, since silently changing a charge's entire settlement lifecycle based on which optional fields happened to be left out would be a footgun."
128
- );
129
144
  var CHARGE_EXPIRES_IN_MIN_SECONDS = 60;
130
- var CHARGE_EXPIRES_IN_MAX_SECONDS = 365 * 24 * 60 * 60;
145
+ var CHARGE_EXPIRES_IN_MAX_SECONDS = 3600;
131
146
  var CHARGE_ACCEPTED_PAYMENTS_MAX = 14;
132
- var AcceptedPaymentSchema = z6.object({
147
+ var AcceptedPaymentSchema = z7.object({
133
148
  token: TokenSchema,
134
149
  network: NetworkSchema
135
150
  });
136
- var AcceptedPaymentsSchema = z6.array(AcceptedPaymentSchema).min(1, "At least one accepted payment is required.").max(CHARGE_ACCEPTED_PAYMENTS_MAX).superRefine((pairs, ctx) => {
151
+ var AcceptedPaymentsSchema = z7.array(AcceptedPaymentSchema).min(1, "At least one accepted payment is required.").max(CHARGE_ACCEPTED_PAYMENTS_MAX).superRefine((pairs, ctx) => {
137
152
  const seen = /* @__PURE__ */ new Set();
138
153
  pairs.forEach((pair, index) => {
139
154
  const key = `${pair.token}:${pair.network}`;
140
155
  if (seen.has(key)) {
141
156
  ctx.addIssue({
142
- code: z6.ZodIssueCode.custom,
157
+ code: z7.ZodIssueCode.custom,
143
158
  message: `Duplicate accepted payment: ${pair.token} on ${pair.network}.`,
144
159
  path: [index]
145
160
  });
@@ -147,7 +162,7 @@ var AcceptedPaymentsSchema = z6.array(AcceptedPaymentSchema).min(1, "At least on
147
162
  seen.add(key);
148
163
  if (!OPERATIONAL_NETWORKS.includes(pair.network)) {
149
164
  ctx.addIssue({
150
- code: z6.ZodIssueCode.custom,
165
+ code: z7.ZodIssueCode.custom,
151
166
  message: `Network "${pair.network}" isn't live yet \u2014 only ${OPERATIONAL_NETWORKS.join(", ")} today.`,
152
167
  path: [index, "network"]
153
168
  });
@@ -157,88 +172,77 @@ var AcceptedPaymentsSchema = z6.array(AcceptedPaymentSchema).min(1, "At least on
157
172
  `Every \`(token, network)\` pair the payer is allowed to pay with \u2014 at least one, up to ${CHARGE_ACCEPTED_PAYMENTS_MAX}. This list is also the only restriction knob: the payer can use any combination of the pairs listed here, and every transfer on one of them is credited and sums toward the charge total (see \`paidWith\`) \u2014 e.g. a charge accepting USDC and USDT can be confirmed by $9 in USDC plus $1 in USDT, or by USDC arriving on two different accepted networks. To require payment in one specific token on one specific network, list only that single pair \u2014 a transfer on any pair not in this list is still recorded (for audit) but never credited. Each network must be live (see \`GET /v1/networks\` for the current matrix) \u2014 an unconfigured \`(token, network)\` combination for your environment is rejected with \`422 token_not_supported\`.`
158
173
  );
159
174
  var CHARGE_AMOUNT_MAX = 999999999999;
160
- var CreateChargeSchema = z6.object({
161
- mode: ChargeModeSchema.default("standard"),
162
- amount: z6.number().positive().max(CHARGE_AMOUNT_MAX).optional().describe(
163
- "Amount to charge, in `currency` units (e.g. `49.9` = $49.90) \u2014 up to 6 decimal places; anything more precise is silently truncated. Omit entirely for a charge that accepts any amount \u2014 the first credited transfer of any size confirms it, and `isOverpaid` never applies (there is no target to exceed)."
175
+ var CreateChargeSchema = z7.object({
176
+ amount: z7.number().positive().max(CHARGE_AMOUNT_MAX).describe(
177
+ "Amount to charge, in `currency` units (e.g. `49.9` = $49.90) \u2014 up to 6 decimal places; anything more precise is silently truncated. Required \u2014 every charge has a target amount, the first credited transfer that reaches it confirms the charge."
164
178
  ),
165
- currency: z6.literal("USD").default("USD").describe("Always `USD` today \u2014 the only supported currency."),
179
+ currency: z7.literal("USD").default("USD").describe("Always `USD` today \u2014 the only supported currency."),
166
180
  acceptedPayments: AcceptedPaymentsSchema,
167
- expiresIn: z6.number().int().min(CHARGE_EXPIRES_IN_MIN_SECONDS).max(CHARGE_EXPIRES_IN_MAX_SECONDS).optional().describe(
168
- "Seconds, not minutes or milliseconds \u2014 how long the charge stays open, min 60, max 31,536,000 = 365 days. Omit entirely for a charge that never expires (`expiresAt` is `null`) \u2014 useful for donations, investments, or any charge with no natural deadline. Cannot be extended or shortened after creation either way."
181
+ expiresIn: z7.number().int().min(CHARGE_EXPIRES_IN_MIN_SECONDS).max(CHARGE_EXPIRES_IN_MAX_SECONDS).describe(
182
+ "Seconds, not minutes or milliseconds \u2014 how long the charge stays open before it expires. Required, min 60, max 3600 (60 minutes) \u2014 sized off the slowest chain Klappay supports today (Ethereum mainnet, where a safely-confirmed transfer takes up to ~15 minutes), leaving real margin for payer-side delay (gas spikes, wallet friction) on top of that. Cannot be extended or shortened after creation."
169
183
  ),
170
- idempotencyKey: z6.string().min(1).max(255).optional().describe(
171
- "Scoped to your organization. Replaying the same key returns the original charge unchanged instead of creating a duplicate \u2014 safe to retry a request after a timeout without double-charging."
184
+ idempotencyKey: z7.string().min(1).max(255).optional().describe(
185
+ "Scoped to your tenant. Replaying the same key returns the original charge unchanged instead of creating a duplicate \u2014 safe to retry a request after a timeout without double-charging."
172
186
  ),
173
- externalRef: z6.string().min(1).max(255).optional().describe(
187
+ externalRef: z7.string().min(1).max(255).optional().describe(
174
188
  "An opaque correlation id from your own system (e.g. an order id) \u2014 echoed back on the charge and in every webhook payload. Not interpreted or validated by Klappay."
175
189
  ),
176
- source: z6.string().min(1).max(64).optional().describe(
190
+ source: z7.string().min(1).max(64).optional().describe(
177
191
  'Free-form label for what created this charge (e.g. `"checkout"`, `"invoice"`) \u2014 useful if you create charges from more than one flow and want to tell them apart later. Not a fixed enum; use whatever values make sense to you.'
178
192
  ),
179
- metadata: z6.record(z6.string(), z6.unknown()).optional().describe("Arbitrary key/value data to attach to the charge, returned as-is on every read.")
180
- }).superRefine((input, ctx) => {
181
- if (input.mode === "continuous" && (input.amount !== void 0 || input.expiresIn !== void 0)) {
182
- ctx.addIssue({
183
- code: z6.ZodIssueCode.custom,
184
- message: 'mode: "continuous" requires both amount and expiresIn to be omitted.',
185
- path: ["mode"]
186
- });
187
- }
193
+ metadata: z7.record(z7.string(), z7.unknown()).optional().describe("Arbitrary key/value data to attach to the charge, returned as-is on every read."),
194
+ redirectUrl: z7.string().url().refine((value) => /^https?:\/\//.test(value), "must use http or https").optional().describe(
195
+ "Where to send the payer once this charge resolves, if you use Klappay's hosted checkout page (see `checkoutUrl` on the read shape) \u2014 ignored otherwise. Must be `http(s)` \u2014 a browser will navigate here, so `javascript:`/`data:` and other non-navigational schemes are rejected. Otherwise not validated beyond being well-formed; what happens at that destination is yours to build."
196
+ )
188
197
  });
189
- var ChargeSchema = z6.object({
190
- id: z6.string().describe("Klappay-generated id, e.g. `ch_...`. Use this to look up the charge later."),
191
- mode: ChargeModeSchema,
192
- amount: z6.number().nullable().describe(
193
- "The amount originally requested, in `currency` units (up to 6 decimal places). `null` if `amount` was omitted at creation \u2014 this charge accepts any amount, and the first credited transfer confirms it."
194
- ),
195
- amountReceived: z6.number().nullable().describe(
196
- "Cumulative amount actually received on-chain so far, in `currency` units (up to 6 decimal places). `null` until the first transfer arrives. Can exceed `amount` \u2014 see `isOverpaid` \u2014 unless `amount` itself is `null`, in which case `isOverpaid` never applies."
198
+ var ChargeSchema = z7.object({
199
+ id: z7.string().describe("Klappay-generated id, e.g. `ch_...`. Use this to look up the charge later."),
200
+ amount: z7.number().describe("The amount originally requested, in `currency` units (up to 6 decimal places)."),
201
+ amountReceived: z7.number().nullable().describe(
202
+ "Cumulative amount actually received on-chain so far, in `currency` units (up to 6 decimal places). `null` until the first transfer arrives. Can exceed `amount` \u2014 see `isOverpaid`."
197
203
  ),
198
- isOverpaid: z6.boolean().describe(
204
+ isOverpaid: z7.boolean().describe(
199
205
  "`true` if `amountReceived` ended up greater than `amount`. Klappay never refunds the difference automatically \u2014 see the docs for why."
200
206
  ),
201
- currency: z6.string().describe("Always `USD` today \u2014 the only supported currency."),
202
- acceptedPayments: z6.array(AcceptedPaymentSchema).describe(
207
+ currency: z7.string().describe("Always `USD` today \u2014 the only supported currency."),
208
+ acceptedPayments: z7.array(AcceptedPaymentSchema).describe(
203
209
  "Every `(token, network)` pair this charge was configured to accept, unchanged after creation."
204
210
  ),
205
- paidWith: z6.array(AcceptedPaymentSchema).describe(
211
+ paidWith: z7.array(AcceptedPaymentSchema).describe(
206
212
  "Every distinct `(token, network)` pair that has actually contributed a credited transfer so far \u2014 empty until the first one arrives. Can hold more than one entry: a charge accepting several pairs can be paid across a combination of them, and every entry here sums toward `amountReceived`."
207
213
  ),
208
- address: z6.string().describe(
214
+ address: z7.string().describe(
209
215
  "The on-chain address the payer must send funds to \u2014 identical across every accepted network (0xSplits addresses are chain-agnostic). Unique per charge, predicted at creation time \u2014 funds sent here go directly to the merchant, Klappay never custodies them."
210
216
  ),
211
217
  status: ChargeStatusSchema,
212
218
  settlementStatus: SettlementStatusSchema.nullable(),
213
219
  environment: EnvironmentSchema,
214
- apiKeyId: z6.string().nullable().describe(
220
+ apiKeyId: z7.string().nullable().describe(
215
221
  "Which of your API keys created this charge. `null` for a charge created before this field existed."
216
222
  ),
217
- txHash: z6.string().nullable().describe(
223
+ txHash: z7.string().nullable().describe(
218
224
  "Transaction hash of the most recent transfer detected for this charge. `null` until a payment is detected."
219
225
  ),
220
- externalRef: z6.string().nullable(),
221
- source: z6.string().nullable(),
222
- metadata: z6.record(z6.string(), z6.unknown()).nullable(),
223
- createdAt: z6.string().datetime(),
224
- expiresAt: z6.string().datetime().nullable().describe(
225
- "When this charge stops accepting payment, if still `pending`/`partially_paid` by then. `null` if `expiresIn` was omitted at creation \u2014 the charge never expires on its own and must be dealt with manually (or left open indefinitely)."
226
+ externalRef: z7.string().nullable(),
227
+ source: z7.string().nullable(),
228
+ metadata: z7.record(z7.string(), z7.unknown()).nullable(),
229
+ redirectUrl: z7.string().nullable().describe("Echoes the `redirectUrl` set at creation, if any. `null` if none was set."),
230
+ checkoutUrl: z7.string().nullable().describe(
231
+ "Link to Klappay's hosted checkout page for this charge. `null` if this deployment has no hosted checkout configured \u2014 build your own payment UI from `address`/`acceptedPayments` instead."
226
232
  ),
227
- confirmedAt: z6.string().datetime().nullable().describe("When `status` first reached `confirmed`. `null` until then."),
228
- settledAt: z6.string().datetime().nullable().describe(
229
- "When `settlementStatus` first reached `completed` \u2014 the merchant's wallet actually has the funds. `null` until then, including while `settlementStatus` is `pending`/`failed`."
230
- ),
231
- lastActivityAt: z6.string().datetime().describe(
232
- "When a transfer was last credited toward this charge, or `createdAt` if none has arrived yet. Only meaningful for a charge with no `expiresAt` \u2014 see `pausedAt`."
233
+ createdAt: z7.string().datetime(),
234
+ expiresAt: z7.string().datetime().describe(
235
+ "When this charge stops accepting payment, if still `pending`/`partially_paid` by then."
233
236
  ),
234
- pausedAt: z6.string().datetime().nullable().describe(
235
- "Only ever set for a charge with no `expiresAt`: `null` means Klappay is actively watching this address in real time (the normal case). A timestamp means no contribution arrived for longer than the inactivity window (90 days for a charge with a goal `amount`, 365 days for one without), so real-time watching was stopped \u2014 the charge itself is never closed, a transfer can still arrive and land, just detected on a much slower fallback poll instead of instantly. Clears automatically (and real-time watching resumes) the moment that happens."
237
+ confirmedAt: z7.string().datetime().nullable().describe("When `status` first reached `confirmed`. `null` until then."),
238
+ settledAt: z7.string().datetime().nullable().describe(
239
+ "When `settlementStatus` first reached `completed` \u2014 the merchant's wallet actually has the funds. `null` until then, including while `settlementStatus` is `pending`/`failed`."
236
240
  ),
237
- canceledAt: z6.string().datetime().nullable().describe(
238
- "When `POST /v1/charges/{id}/cancel` was called. `null` unless `status` is `canceled`. Unlike `pausedAt`, this never clears automatically \u2014 real-time watching is stopped the same way, but a transfer landing afterward doesn't revert the charge to `pending`; it fires `charge.paid_after_cancel` instead, since resuming silently would contradict the merchant's explicit cancellation."
241
+ lastActivityAt: z7.string().datetime().describe(
242
+ "When a transfer was last credited toward this charge, or `createdAt` if none has arrived yet."
239
243
  )
240
244
  });
241
- var ListChargesSchema = z6.object({
245
+ var ListChargesSchema = z7.object({
242
246
  status: ChargeStatusSchema.optional(),
243
247
  token: TokenSchema.optional().describe(
244
248
  "Filters on `paidWith.token` \u2014 the pair actually paid, not accepted."
@@ -247,47 +251,19 @@ var ListChargesSchema = z6.object({
247
251
  "Filters on `paidWith.network` \u2014 the pair actually paid, not accepted."
248
252
  ),
249
253
  environment: EnvironmentSchema.optional(),
250
- since: z6.string().datetime().optional().describe(
254
+ since: z7.string().datetime().optional().describe(
251
255
  "Only return charges created at or after this timestamp (filters on `createdAt`, not on when the status last changed). If polling as a fallback for missed webhooks, use a window at least as wide as the longest `expiresIn` your charges use, or you can miss a long-lived charge that changed status outside a narrower window."
252
256
  ),
253
- isOverpaid: z6.enum(["true", "false"]).transform((v) => v === "true").optional()
257
+ isOverpaid: z7.enum(["true", "false"]).transform((v) => v === "true").optional()
254
258
  }).extend(PaginationQuerySchema.shape);
255
259
  var PaginatedChargesSchema = paginatedSchema(ChargeSchema);
256
- var GetChargeQrCodeQuerySchema = z6.object({
260
+ var GetChargeQrCodeQuerySchema = z7.object({
257
261
  token: TokenSchema.optional().describe(
258
262
  "Which accepted `(token, network)` pair to encode in the QR \u2014 required if `acceptedPayments` has more than one pair, since there is no single unambiguous default to fall back to. Ignored (and unnecessary) when the charge accepts exactly one pair."
259
263
  ),
260
264
  network: NetworkSchema.optional()
261
265
  });
262
266
 
263
- // src/public-charges.ts
264
- import { z as z7 } from "zod";
265
- var PublicChargeSchema = z7.object({
266
- id: z7.string(),
267
- mode: ChargeModeSchema,
268
- status: ChargeStatusSchema,
269
- settlementStatus: SettlementStatusSchema.nullable(),
270
- amount: z7.number().nullable(),
271
- amountReceived: z7.number().nullable(),
272
- isOverpaid: z7.boolean(),
273
- currency: z7.string(),
274
- acceptedPayments: z7.array(AcceptedPaymentSchema),
275
- paidWith: z7.array(AcceptedPaymentSchema),
276
- address: z7.string(),
277
- environment: EnvironmentSchema,
278
- txHash: z7.string().nullable(),
279
- metadata: z7.record(z7.unknown()).nullable().describe(
280
- "Redacted \u2014 everything the merchant put in `Charge.metadata` is stripped except the reserved `klappay` key (for Klappay-internal product integrations, e.g. this endpoint's own checkout consumer), if present. `null` if there's no `klappay` key, even when the merchant's own metadata is otherwise non-empty."
281
- ),
282
- createdAt: z7.string().datetime(),
283
- expiresAt: z7.string().datetime().nullable(),
284
- confirmedAt: z7.string().datetime().nullable(),
285
- settledAt: z7.string().datetime().nullable(),
286
- lastActivityAt: z7.string().datetime(),
287
- pausedAt: z7.string().datetime().nullable(),
288
- canceledAt: z7.string().datetime().nullable()
289
- });
290
-
291
267
  // src/distributions.ts
292
268
  import { z as z8 } from "zod";
293
269
  var SplitDistributionStatusSchema = z8.enum(["pending", "processing", "completed", "failed"]).describe(
@@ -343,11 +319,11 @@ var MetricsAggregationSchema = z9.enum(["count", "sum", "avg", "min", "max"]).de
343
319
  var MetricsFilterOperatorSchema = z9.enum(["eq", "neq", "in", "gt", "gte", "lt", "lte"]).describe(
344
320
  "`in` expects an array value (max 50 entries); every other operator expects a single scalar."
345
321
  );
346
- var MetricsDateGranularitySchema = z9.enum(["day", "week", "month"]).describe(
322
+ var MetricsDateGranularitySchema = z9.enum(["day", "week", "month", "year"]).describe(
347
323
  "Bucket width for a `date_bucket` `groupBy` entry \u2014 Postgres `date_trunc` semantics (UTC)."
348
324
  );
349
325
  var metricsQueryEnvironmentSchema = EnvironmentSchema.describe(
350
- "Which environment's data to query \u2014 `live` or `test`. Independent of your session (a dashboard user isn't scoped to one environment the way an API key is) \u2014 scopes the query to charges/transactions/distributions created under a `live` or `test` API key respectively."
326
+ "Which environment's data to query \u2014 `live` or `test`. Must match the environment of the API key used to authenticate \u2014 scopes the query to charges/transactions/distributions created under a `live` or `test` API key respectively."
351
327
  );
352
328
  var MAX_METRICS_QUERY_DATE_RANGE_DAYS = 366;
353
329
  var METRICS_QUERY_MAX_ROW_LIMIT = 1e3;
@@ -380,14 +356,14 @@ var orderBySchema = z9.object({
380
356
  var limitSchema = z9.number().int().min(1).max(METRICS_QUERY_MAX_ROW_LIMIT).default(METRICS_QUERY_DEFAULT_ROW_LIMIT).describe(
381
357
  `Max rows to return, ${1}\u2013${METRICS_QUERY_MAX_ROW_LIMIT}, default ${METRICS_QUERY_DEFAULT_ROW_LIMIT}. If more rows matched, \`meta.truncated\` is \`true\` on the response \u2014 narrow the query instead of just raising this.`
382
358
  );
383
- var ChargesQueryFieldSchema = z9.enum(["status", "mode", "source", "apiKeyId", "currency", "isOverpaid", "externalRef"]).describe(
384
- "A `Charge` field to filter or group by \u2014 see `ChargeStatusSchema`/`ChargeModeSchema` for `status`/`mode`'s own possible values (charges.md). `source`/`externalRef` are free-form strings your own integration set at creation, not a fixed enum."
359
+ var ChargesQueryFieldSchema = z9.enum(["status", "source", "apiKeyId", "currency", "isOverpaid", "externalRef"]).describe(
360
+ "A `Charge` field to filter or group by \u2014 see `ChargeStatusSchema` for `status`'s own possible values (charges.md). `source`/`externalRef` are free-form strings your own integration set at creation, not a fixed enum."
385
361
  );
386
362
  var ChargesMetricFieldSchema = z9.enum(["amount", "amountReceived", "feePercent"]).describe(
387
363
  "A `Charge` numeric field to aggregate. `amount`/`amountReceived` are decimal currency amounts (requested vs. actually received \u2014 see `charges.md`). `feePercent` is the platform fee frozen on the charge at creation, e.g. `1.5` means 1.5%."
388
364
  );
389
- var ChargesDateFieldSchema = z9.enum(["createdAt", "confirmedAt", "lastActivityAt"]).describe(
390
- "A `Charge` timestamp to filter/bucket by. `confirmedAt` is `null` until the charge reaches `confirmed` \u2014 a `dateRange`/`date_bucket` on it implicitly excludes every charge that never confirmed."
365
+ var ChargesDateFieldSchema = z9.enum(["createdAt", "confirmedAt", "lastActivityAt", "expiresAt"]).describe(
366
+ "A `Charge` timestamp to filter/bucket by. `confirmedAt` is `null` until the charge reaches `confirmed` \u2014 a `dateRange`/`date_bucket` on it implicitly excludes every charge that never confirmed. `expiresAt` is always present (set at creation), useful for e.g. finding charges expiring soon or measuring how close to expiry charges typically resolve."
391
367
  );
392
368
  var ChargesFilterSchema = z9.object({
393
369
  field: ChargesQueryFieldSchema,
@@ -458,14 +434,14 @@ var TransactionsMetricsQuerySchema = z9.object({
458
434
  orderBy: orderBySchema.optional(),
459
435
  limit: limitSchema
460
436
  });
461
- var DistributionsQueryFieldSchema = z9.enum(["status", "network", "token"]).describe(
462
- "A `SplitDistribution` field to filter or group by \u2014 see `SplitDistributionStatusSchema`/`NetworkSchema`/`TokenSchema` for their possible values."
437
+ var DistributionsQueryFieldSchema = z9.enum(["status", "network", "token", "distributorAddress"]).describe(
438
+ "A `SplitDistribution` field to filter or group by \u2014 see `SplitDistributionStatusSchema`/`NetworkSchema`/`TokenSchema` for their possible values. `distributorAddress` is the public on-chain address that actually called `distribute()` for a `completed` distribution \u2014 Klappay's own operator address if settled by Klappay's own worker, a community keeper's address if settled externally (or `null` on the rare case that lookup failed), `null` for every non-`completed` status."
463
439
  );
464
440
  var DistributionsMetricFieldSchema = z9.enum(["attempts"]).describe(
465
441
  "How many times a payout was attempted for this settlement so far \u2014 incremented on every attempt, whether it succeeded or is being retried after failing. A high `attempts` alongside `status: 'failed'` means every automatic retry was exhausted."
466
442
  );
467
- var DistributionsDateFieldSchema = z9.enum(["createdAt", "completedAt"]).describe(
468
- "`createdAt`: when this settlement was queued. `completedAt`: when it actually paid out \u2014 `null` until `status` reaches `completed`, so a `dateRange`/`date_bucket` on it implicitly excludes every distribution still pending/processing/failed."
443
+ var DistributionsDateFieldSchema = z9.enum(["createdAt", "processingStartedAt", "completedAt"]).describe(
444
+ "`createdAt`: when this settlement was queued. `processingStartedAt`: when a worker began its most recent attempt at the payout \u2014 `null` until the first attempt, then overwritten on every subsequent retry, so it reflects the *latest* attempt's start, not the first. `completedAt`: when it actually paid out \u2014 `null` until `status` reaches `completed`, so a `dateRange`/`date_bucket` on it implicitly excludes every distribution still pending/processing/failed."
469
445
  );
470
446
  var DistributionsFilterSchema = z9.object({
471
447
  field: DistributionsQueryFieldSchema,
@@ -562,15 +538,11 @@ var MetricsQueryResultRowSchema = z9.record(
562
538
  z9.string(),
563
539
  z9.union([z9.string(), z9.number(), z9.boolean(), z9.null()])
564
540
  );
565
- var MetricsQueryScopeSchema = z9.enum(["owner_admin", "member"]).describe(
566
- "`member`: results were automatically restricted to data tied to API keys you personally created \u2014 rows with no resolvable creator were excluded, not counted, and not surfaced any other way. `owner_admin`: the full organization\u2019s data was queried, no restriction applied."
567
- );
568
541
  var MetricsQueryResultSchema = z9.object({
569
542
  data: z9.array(MetricsQueryResultRowSchema),
570
543
  meta: z9.object({
571
544
  resource: MetricsResourceSchema,
572
545
  environment: EnvironmentSchema,
573
- scope: MetricsQueryScopeSchema,
574
546
  rowCount: z9.number().int().describe("Number of rows in `data`."),
575
547
  truncated: z9.boolean().describe(
576
548
  "`true` if more rows matched than `limit` allowed \u2014 `data` holds only the first `limit`."
@@ -588,86 +560,43 @@ var ChargeWebhookEventTypeSchema = z10.enum([
588
560
  "charge.underpaid",
589
561
  "charge.settled",
590
562
  "charge.settlement_failed",
591
- "charge.overpaid",
592
- "charge.paused",
593
- "charge.reactivated",
594
- "charge.contribution_received",
595
- "charge.contribution_settled",
596
- "charge.canceled",
597
- "charge.paid_after_cancel"
598
- ]).describe(
599
- 'Note the distinction between `charge.confirmed` and `charge.settled`: `confirmed` means the payment was detected on-chain; `settled` means the merchant\'s wallet actually received the funds \u2014 a separate, later step. Subscribe to `confirmed` if you only need "will I get paid," or `settled` if you need "has the money actually arrived." `charge.overpaid` fires alongside `charge.confirmed`/`charge.partially_paid` whenever the cumulative amount received ends up above `amount` (see `Charge.isOverpaid`). Every event in this category carries the full `Charge` object as `data`, except `charge.paused`/`charge.reactivated`/`charge.contribution_received`/`charge.contribution_settled`/`charge.paid_after_cancel` (see below). `charge.paused` fires when a charge with no `expiresAt` has had no contribution for longer than its inactivity window (90 days for a charge with a goal `amount`, 365 days for one without) \u2014 Klappay stops watching its address in real time, but the charge itself is never closed; `charge.reactivated` fires the moment a transfer lands on a paused charge, detected by the same fallback poller used for missed webhooks (so with much higher latency than normal \u2014 pausing trades that away deliberately, see `docs/payments.md`). `charge.contribution_received`/`charge.contribution_settled` are exclusive to `mode: continuous` charges (see `Charge.mode`) \u2014 a continuous charge never fires `charge.confirmed`/`charge.settled` at all, since `status` never leaves `pending`; instead every individual transfer fires `contribution_received` on detection and `contribution_settled` once its payout completes, one pair-scoped event per contribution instead of one event for the whole charge. `charge.canceled` fires when a merchant explicitly cancels a `pending`/`partially_paid` charge via `POST /v1/charges/{id}/cancel` \u2014 unlike every other terminal status, this one is never reached automatically. `charge.paid_after_cancel` is an anomaly signal: a transfer still landed on a canceled charge\'s address (nothing on-chain can prevent that) \u2014 `status` stays `canceled`, it is never silently resumed, and this event is your cue to manually refund the payer or honor the charge anyway. `data` for `charge.paused`: `{ chargeId, lastActivityAt, pausedAt }`; for `charge.reactivated`: `{ chargeId, reactivatedAt }`; for `charge.contribution_received`: `{ chargeId, token, network, amount, txHash, payerAddress }`; for `charge.contribution_settled`: `{ chargeId, token, network, amount, txHash, distributorAddress }`; for `charge.paid_after_cancel`: `{ chargeId, token, network, amount, txHash, payerAddress }`.'
600
- );
601
- var AccountWebhookEventTypeSchema = z10.enum([
602
- "payout_address.changed",
603
- "api_key.created",
604
- "api_key.revoked",
605
- "webhook.created",
606
- "webhook.deleted",
607
- "webhook.secret_rotated",
608
- "fee_tier.updated",
609
- "member.removed",
610
- "member.role_changed",
611
- "member.invited"
563
+ "charge.overpaid"
612
564
  ]).describe(
613
- "Account and configuration changes \u2014 not tied to any single charge. `data` per event: `payout_address.changed`: `{ organizationId, from, to }` (`from` nullable); `api_key.created`/`api_key.revoked`: `{ apiKeyId, name, environment, hint }`; `webhook.created`/`webhook.deleted`/`webhook.secret_rotated`: `{ webhookId, url }`; `fee_tier.updated`: `{ organizationId, previousFeePercent, newFeePercent }`; `member.removed`: `{ userId, email, role }`; `member.role_changed`: `{ userId, email, role, previousRole }`; `member.invited`: `{ organizationId, email, role, invitedByUserId }`."
565
+ 'Note the distinction between `charge.confirmed` and `charge.settled`: `confirmed` means the payment was detected on-chain; `settled` means the merchant\'s wallet actually received the funds \u2014 a separate, later step. Subscribe to `confirmed` if you only need "will I get paid," or `settled` if you need "has the money actually arrived." `charge.overpaid` fires alongside `charge.confirmed`/`charge.partially_paid` whenever the cumulative amount received ends up above `amount` (see `Charge.isOverpaid`). Every event in this category carries the full `Charge` object as `data`.'
614
566
  );
615
567
  var WebhookDeliveryEventTypeSchema = z10.enum(["webhook.delivery_failed", "webhook.delivery_recovered", "webhook.endpoint_unhealthy"]).describe(
616
568
  "Meta-events about the health of your own webhook endpoints \u2014 useful for monitoring without polling `GET /v1/webhooks/{id}/deliveries`. `webhook.endpoint_unhealthy` fires once when a webhook's failure rate over the trailing 24h crosses 20%, and `webhook.delivery_recovered` fires once when a delivery to that webhook next succeeds. `data` for every event in this category: `{ webhookId, url, failureRatio? }` (`failureRatio` only present on `webhook.endpoint_unhealthy`)."
617
569
  );
618
- var SecurityWebhookEventTypeSchema = z10.enum([
619
- "auth.login",
620
- "auth.login_failed",
621
- "auth.suspicious_activity",
622
- "auth.email_verified",
623
- "auth.password_reset_requested",
624
- "auth.password_reset_completed",
625
- "auth.password_changed",
626
- "auth.email_change_requested",
627
- "auth.email_changed"
628
- ]).describe(
629
- "Account security signals. `auth.suspicious_activity` is a soft heuristic (login from an IP not seen on this account before), not a block \u2014 evaluate it, not enforce against it. `auth.password_reset_requested` only ever dispatches when the requested email actually matches an account (there is nowhere to notify otherwise) \u2014 `POST /v1/auth/forgot-password` itself always returns the same generic response either way, so this event never becomes a second channel for the same enumeration question the endpoint response deliberately avoids answering. `auth.password_changed` is the self-service counterpart to `auth.password_reset_completed` \u2014 fires from `POST /v1/auth/change-password` (requires the current password) instead of the unauthenticated forgot-password flow. `auth.email_change_requested`/`auth.email_changed` are the request/complete pair for `POST /v1/auth/change-email` \u2192 `POST /v1/auth/confirm-email-change` \u2014 the change only takes effect, and `email_changed` only fires, once the confirmation link sent to the *current* address is used. `data` per event: `auth.login`: `{ userId, ipAddress }`; `auth.login_failed`: `{ email, ipAddress }`; `auth.suspicious_activity`: `{ userId, ipAddress, previousIpAddress }`; `auth.email_verified`/`auth.password_reset_requested`/`auth.password_reset_completed`/`auth.password_changed`: `{ userId, email }`; `auth.email_change_requested`: `{ userId, email, newEmail }`; `auth.email_changed`: `{ userId, previousEmail, newEmail }`."
630
- );
631
570
  var WebhookEventTypeSchema = z10.union([
632
571
  ChargeWebhookEventTypeSchema,
633
- AccountWebhookEventTypeSchema,
634
- WebhookDeliveryEventTypeSchema,
635
- SecurityWebhookEventTypeSchema
572
+ WebhookDeliveryEventTypeSchema
636
573
  ]);
637
- var WebhookCategorySchema = z10.enum(["payments", "account", "webhooks", "security"]).describe(
574
+ var WebhookCategorySchema = z10.enum(["payments", "webhooks"]).describe(
638
575
  "Subscribe to every event in a category via `eventCategories` instead of listing events one by one \u2014 new events added to a category later arrive automatically, no subscription update needed."
639
576
  );
640
577
  function buildCategoryMap() {
641
578
  const map = {};
642
579
  for (const event of ChargeWebhookEventTypeSchema.options) map[event] = "payments";
643
- for (const event of AccountWebhookEventTypeSchema.options) map[event] = "account";
644
580
  for (const event of WebhookDeliveryEventTypeSchema.options) map[event] = "webhooks";
645
- for (const event of SecurityWebhookEventTypeSchema.options) map[event] = "security";
581
+ for (const event of WebhookEventTypeSchema.options.flatMap((schema) => schema.options)) {
582
+ if (!(event in map)) {
583
+ throw new Error(
584
+ `buildCategoryMap: "${event}" has no category \u2014 a new event sub-schema was unioned into WebhookEventTypeSchema without a matching loop added here.`
585
+ );
586
+ }
587
+ }
646
588
  return map;
647
589
  }
648
590
  var EVENT_CATEGORY_MAP = buildCategoryMap();
649
591
  var WEBHOOK_EVENT_CATEGORIES = {
650
592
  payments: ChargeWebhookEventTypeSchema.options,
651
- account: AccountWebhookEventTypeSchema.options,
652
- webhooks: WebhookDeliveryEventTypeSchema.options,
653
- security: SecurityWebhookEventTypeSchema.options
593
+ webhooks: WebhookDeliveryEventTypeSchema.options
654
594
  };
655
595
  var TriggerableChargeEventSchema = ChargeWebhookEventTypeSchema.exclude([
656
- "charge.created",
657
- "charge.paused",
658
- "charge.reactivated",
659
- "charge.contribution_received",
660
- "charge.contribution_settled",
661
- "charge.canceled",
662
- "charge.paid_after_cancel"
596
+ "charge.created"
663
597
  ]).describe(
664
- "Every charge event that represents a payment-progress state transition a sandbox charge can be pushed into \u2014 everything except `charge.created` (a charge already exists by the time you have an id to trigger against), `charge.paused`/`charge.reactivated` (driven by a background worker on real inactivity, not a payment state \u2014 nothing meaningful to simulate or wait for on a fresh sandbox charge), `charge.contribution_received`/`charge.contribution_settled` (exclusive to `mode: continuous` charges, which this trigger endpoint does not support simulating today \u2014 see `POST /v1/charges/{id}/trigger`'s own description), and `charge.canceled` (already a real, immediate action in `test` mode via `POST /v1/charges/{id}/cancel` itself \u2014 nothing to simulate) along with `charge.paid_after_cancel` (not simulatable without a real transfer to an already-canceled charge)."
598
+ "Every charge event that represents a payment-progress state transition a sandbox charge can be pushed into \u2014 everything except `charge.created` (a charge already exists by the time you have an id to trigger against)."
665
599
  );
666
- var NonChargeTriggerableEventSchema = z10.union([
667
- AccountWebhookEventTypeSchema,
668
- WebhookDeliveryEventTypeSchema,
669
- SecurityWebhookEventTypeSchema
670
- ]);
671
600
 
672
601
  // src/webhooks.ts
673
602
  import { z as z11 } from "zod";
@@ -692,7 +621,7 @@ var CreateWebhookSchema = z11.object({
692
621
  var WebhookSchema = z11.object({
693
622
  id: z11.string(),
694
623
  environment: EnvironmentSchema.nullable().describe(
695
- "Which environment's API key created this webhook \u2014 `live` or `test`. Charge/webhook-delivery-health events are only ever delivered to a webhook whose `environment` matches the event's own (or to a webhook with `environment: null`, which receives every environment \u2014 the case for every webhook created before this field existed). Account/security events (`payout_address.changed`, `member.*`, `auth.*`, `fee_tier.updated`) have no environment concept and are delivered regardless."
624
+ "Which environment's API key created this webhook \u2014 `live` or `test`. Every event is only ever delivered to a webhook whose `environment` matches the event's own (or to a webhook with `environment: null`, which receives every environment \u2014 the case for every webhook created before this field existed)."
696
625
  ),
697
626
  url: z11.string(),
698
627
  events: z11.array(WebhookEventTypeSchema),
@@ -714,7 +643,7 @@ var WebhookPayloadSchema = z11.object({
714
643
  event: WebhookEventTypeSchema,
715
644
  createdAt: z11.string().datetime(),
716
645
  data: z11.unknown().describe(
717
- "Event-specific data. Charge events (`charge.*`) carry the full `Charge` object; account/security/webhook-delivery events carry a smaller, event-specific object \u2014 see `WebhookEventDataMap`/`TypedWebhookPayload` for the exact shape per event, or docs/webhooks.md."
646
+ "Event-specific data. Charge events (`charge.*`) carry the full `Charge` object; webhook-delivery events carry a smaller, event-specific object \u2014 see `WebhookEventDataMap`/`TypedWebhookPayload` for the exact shape per event, or docs/webhooks.md."
718
647
  )
719
648
  });
720
649
  var WebhookDeliveryStatusSchema = z11.enum(["pending", "delivered", "failed"]);
@@ -736,178 +665,27 @@ var WebhookDeliverySchema = z11.object({
736
665
  var ListWebhookDeliveriesSchema = PaginationQuerySchema;
737
666
  var PaginatedWebhookDeliveriesSchema = paginatedSchema(WebhookDeliverySchema);
738
667
 
739
- // src/api-keys.ts
740
- import { z as z12 } from "zod";
741
- var CreateApiKeySchema = z12.object({
742
- name: z12.string().min(1).max(64).describe(
743
- 'A label to help you tell keys apart (e.g. `"production backend"`). Not used for anything functional.'
744
- ),
745
- environment: EnvironmentSchema.describe(
746
- "`live` keys move real funds on Base mainnet; `test` keys settle on Base Sepolia (a real testnet, no real money) and additionally unlock `POST /v1/sandbox/*` for simulating events with zero on-chain activity at all."
747
- )
748
- });
749
- var ApiKeySchema = z12.object({
750
- id: z12.string(),
751
- name: z12.string(),
752
- environment: EnvironmentSchema.describe(
753
- "`live` keys authenticate real charges on Base mainnet; `test` keys authenticate the same charge lifecycle on Base Sepolia (a real testnet) and additionally unlock `/v1/sandbox/*` for synthetic event simulation."
754
- ),
755
- key: z12.string().optional().describe(
756
- "The full secret key (`klap_live_...` / `klap_test_...`), used as the `Authorization: Bearer` value on `/v1/charges`, `/v1/webhooks`, and `/v1/sandbox` requests. Present only in the response to `POST /v1/api-keys` \u2014 never returned again afterward, so store it immediately."
757
- ),
758
- hint: z12.string().describe(
759
- "A truncated, always-safe-to-display form of the key (e.g. `klap_live_...ab12`), returned everywhere the full key isn't."
760
- ),
761
- createdAt: z12.string().datetime(),
762
- lastUsedAt: z12.string().datetime().nullable().describe("Updated on every successful authenticated request. `null` if never used."),
763
- createdByUserId: z12.string().nullable().describe(
764
- "Which member of the organization created this key. `null` for a key created before this field existed."
765
- )
766
- });
767
- var ListApiKeysSchema = PaginationQuerySchema;
768
- var PaginatedApiKeysSchema = paginatedSchema(ApiKeySchema);
769
-
770
- // src/users.ts
771
- import { z as z13 } from "zod";
772
- var UserRoleSchema = z13.enum(["owner", "admin", "member"]).describe(
773
- "`owner`: full access, and the organization must always keep at least one. `admin`: can manage `member`s but not other `admin`s. `member`: no management permissions. You can only manage a member with a strictly lower role than your own, unless you're an `owner`."
774
- );
775
- var UpdateUserRoleSchema = z13.object({
776
- role: UserRoleSchema
777
- });
778
- var UserSchema = z13.object({
779
- id: z13.string(),
780
- email: z13.string(),
781
- name: z13.string().nullable(),
782
- role: UserRoleSchema.describe("Your role within the organization this user was fetched from."),
783
- emailVerifiedAt: z13.string().datetime().nullable().describe(
784
- "When this address was confirmed via the emailed verification link. `null` until then. Required (non-null) for two specific actions: creating a `live` API key (`POST /v1/api-keys`) and changing `Organization.payoutAddress` (`PATCH /v1/organization`) \u2014 everything else works regardless of verification status."
785
- ),
786
- createdAt: z13.string().datetime()
787
- });
788
- var ListUsersSchema = PaginationQuerySchema;
789
- var PaginatedUsersSchema = paginatedSchema(UserSchema);
790
-
791
- // src/auth.ts
792
- import { z as z14 } from "zod";
793
- var NormalizedEmailSchema = z14.string().trim().max(255).toLowerCase().email().transform((email) => email.normalize("NFC")).describe(
794
- "Trimmed, lowercased, and NFC-normalized server-side before use \u2014 case/whitespace don't matter."
795
- );
796
- var SignupSchema = z14.object({
797
- email: NormalizedEmailSchema,
798
- password: z14.string().min(8).max(128).describe("8-128 characters. No other complexity rule.")
799
- });
800
- var LoginSchema = z14.object({
801
- email: NormalizedEmailSchema,
802
- password: z14.string().min(1).max(128)
803
- });
804
- var VerifyEmailSchema = z14.object({
805
- token: z14.string().min(1).describe("The token from the verification email \u2014 passed as-is, not the account email.")
806
- });
807
- var ForgotPasswordSchema = z14.object({
808
- email: NormalizedEmailSchema
809
- });
810
- var ResetPasswordSchema = z14.object({
811
- token: z14.string().min(1).describe("The token from the password reset email."),
812
- newPassword: z14.string().min(8).max(128)
813
- });
814
- var MessageResponseSchema = z14.object({
815
- message: z14.string().describe("Human-readable confirmation, safe to show a user directly.")
816
- });
817
- var SelfUserSchema = UserSchema.omit({ createdAt: true, role: true });
818
- var AuthResponseSchema = z14.object({
819
- token: z14.string().describe(
820
- "Session JWT, valid 7 days \u2014 use as `Authorization: Bearer <token>` on every `/v1/organizations/*` request (which nests API keys, members, and invitations \u2014 see `GET /v1/organizations`). This token identifies only you; it carries no organization or role \u2014 every `/v1/organizations/{id}/*` request is authorized fresh against your actual membership in that specific organization. This is a separate credential from an API key: it authenticates a human/dashboard session, not payment operations. Create an API key with it before you can create charges."
821
- ),
822
- user: SelfUserSchema
823
- });
824
- var ChangeNameSchema = z14.object({
825
- name: z14.string().min(1).max(255).describe("Your display name.")
826
- });
827
- var ChangePasswordSchema = z14.object({
828
- currentPassword: z14.string().min(1).max(128),
829
- newPassword: z14.string().min(8).max(128)
830
- });
831
- var ChangeEmailSchema = z14.object({
832
- currentPassword: z14.string().min(1).max(128),
833
- newEmail: NormalizedEmailSchema
834
- });
835
- var ConfirmEmailChangeSchema = z14.object({
836
- token: z14.string().min(1).describe("The token from the confirmation email sent to your current address.")
837
- });
838
-
839
- // src/organization.ts
840
- import { z as z15 } from "zod";
841
- var UpdateOrganizationSchema = z15.object({
842
- name: z15.string().min(1).max(255).optional().describe("The organization's display name."),
843
- payoutAddress: z15.string().regex(/^0x[a-fA-F0-9]{40}$/, "must be a valid EVM address").optional().describe(
844
- "The wallet that receives the merchant's share of every future charge. Changing this only affects charges created after the change \u2014 an already-created charge's payout split is frozen from creation and is never retroactively affected. Required before you can create any charge. Any casing is accepted \u2014 EIP-55 checksum casing is not required or verified."
845
- )
846
- });
847
- var OrganizationSchema = z15.object({
848
- id: z15.string(),
849
- name: z15.string(),
850
- payoutAddress: z15.string().nullable().describe("`null` until configured \u2014 `POST /v1/charges` fails until this is set."),
851
- currentFeePercent: z15.number().describe(
852
- "Your current platform fee percentage \u2014 `1.5` means 1.5%, not a 0\u20131 fraction. Funds the infrastructure Klappay runs on your behalf (on-chain monitoring, settlement, webhook delivery, support) the same way any payment processor's fee does; this is not optional or removable. Dynamic, not fixed: it's based on your trailing monthly volume, with lower volume paying a higher percentage \u2014 higher-volume organizations, or ones with a specific negotiated arrangement, can be assigned a different rate at Klappay's discretion. Frozen onto each charge at creation, so a rate change never retroactively affects a charge already created; see `feeUpdatedAt` for when it last changed. Contact Klappay if you'd like your rate reviewed."
853
- ),
854
- feeUpdatedAt: z15.string().datetime().nullable().describe(
855
- "When `currentFeePercent` last changed. `null` if it has never changed since this organization signed up."
856
- ),
857
- createdAt: z15.string().datetime()
858
- });
859
- var OrganizationWithRoleSchema = OrganizationSchema.extend({
860
- role: UserRoleSchema.describe("Your own role within this specific organization.")
861
- });
862
- var PaginatedOrganizationsSchema = paginatedSchema(OrganizationWithRoleSchema);
863
- var ListOrganizationsSchema = PaginationQuerySchema;
864
-
865
- // src/invitations.ts
866
- import { z as z16 } from "zod";
867
- var InviteUserSchema = z16.object({
868
- email: NormalizedEmailSchema,
869
- role: UserRoleSchema.default("member").describe(
870
- "The role the invitee will hold once they accept \u2014 subject to the same management-hierarchy rule as `PATCH /v1/organizations/{id}/users/{userId}`: an `admin` inviter cannot invite an `admin` or `owner`."
871
- )
872
- });
873
- var AcceptInvitationSchema = z16.object({
874
- token: z16.string().min(1).describe("The token from the invitation email."),
875
- password: z16.string().min(8).max(128).optional().describe(
876
- "Required only if the invited email has no existing Klappay account \u2014 a new account is created along with the membership. Ignored if the account already exists."
877
- )
878
- });
879
- var InvitationSchema = z16.object({
880
- id: z16.string(),
881
- organizationId: z16.string(),
882
- email: z16.string(),
883
- role: UserRoleSchema,
884
- invitedByUserId: z16.string().describe("Which member of the organization sent this invitation."),
885
- expiresAt: z16.string().datetime(),
886
- createdAt: z16.string().datetime()
887
- });
888
-
889
668
  // src/timeline.ts
890
- import { z as z17 } from "zod";
891
- var TransactionSourceSchema = z17.enum(["moralis_webhook", "reconciliation_job", "sandbox"]).describe(
669
+ import { z as z12 } from "zod";
670
+ var TransactionSourceSchema = z12.enum(["moralis_webhook", "reconciliation_job", "sandbox"]).describe(
892
671
  "How this transfer was detected: `moralis_webhook` (the normal path), `reconciliation_job` (a fallback poller caught it after the webhook was missed or delayed), or `sandbox` (simulated via `POST /v1/sandbox/charges/{id}/trigger`, no real on-chain transfer)."
893
672
  );
894
- var TimelineEventTypeSchema = z17.enum([
673
+ var TimelineEventTypeSchema = z12.enum([
895
674
  "charge.created",
896
675
  "charge.expired",
897
- "charge.canceled",
898
676
  "transaction.detected",
899
677
  "split.distributed",
900
678
  "webhook.dispatched",
901
679
  "webhook.delivered",
902
680
  "webhook.failed"
903
681
  ]).describe(
904
- "`charge.created`: the charge was created. `charge.expired`: `expiresAt` passed with no full payment. `charge.canceled`: the merchant explicitly canceled it via `POST /v1/charges/{id}/cancel`. `transaction.detected`: a raw on-chain transfer was seen (see the `event`-shaped fields below for details \u2014 a charge can have more than one, e.g. a partial payment followed by the rest). `split.distributed`: a payout to the merchant completed on-chain, for one contributing `(token, network)` pair \u2014 a charge settled across more than one pair emits one of these per pair (see the `token`/`network` fields below). `webhook.dispatched`/`webhook.delivered`/`webhook.failed`: one specific delivery *attempt* for one webhook subscription \u2014 `failed` here means this single attempt failed, not that all retries were exhausted (see `WebhookDeliveryStatusSchema` for the exhausted-all-retries state)."
682
+ "`charge.created`: the charge was created. `charge.expired`: `expiresAt` passed with no full payment. `transaction.detected`: a raw on-chain transfer was seen (see the `event`-shaped fields below for details \u2014 a charge can have more than one, e.g. a partial payment followed by the rest). `split.distributed`: a payout to the merchant completed on-chain, for one contributing `(token, network)` pair \u2014 a charge settled across more than one pair emits one of these per pair (see the `token`/`network` fields below). `webhook.dispatched`/`webhook.delivered`/`webhook.failed`: one specific delivery *attempt* for one webhook subscription \u2014 `failed` here means this single attempt failed, not that all retries were exhausted (see `WebhookDeliveryStatusSchema` for the exhausted-all-retries state)."
905
683
  );
906
- var TimelineEventSchema = z17.object({
684
+ var TimelineEventSchema = z12.object({
907
685
  type: TimelineEventTypeSchema,
908
- at: z17.string().datetime(),
909
- txHash: z17.string().optional().describe("Present for `transaction.detected` and `split.distributed` events only."),
910
- amount: z17.number().optional().describe(
686
+ at: z12.string().datetime(),
687
+ txHash: z12.string().optional().describe("Present for `transaction.detected` and `split.distributed` events only."),
688
+ amount: z12.number().optional().describe(
911
689
  "Present for `transaction.detected` events only \u2014 the amount that specific transfer carried."
912
690
  ),
913
691
  source: TransactionSourceSchema.optional().describe(
@@ -919,80 +697,67 @@ var TimelineEventSchema = z17.object({
919
697
  network: NetworkSchema.optional().describe(
920
698
  "Present for `transaction.detected` and `split.distributed` events \u2014 which network this specific transfer, or settlement, used."
921
699
  ),
922
- causedTransition: z17.boolean().optional().describe(
700
+ causedTransition: z12.boolean().optional().describe(
923
701
  "Present for `transaction.detected` events only. `true` if this specific transfer changed the charge's status (e.g. PENDING\u2192CONFIRMED) \u2014 a charge paid in installments can have more than one such event."
924
702
  ),
925
703
  event: WebhookEventTypeSchema.optional().describe(
926
704
  "Present for `webhook.*` events only \u2014 which event type this delivery was for."
927
705
  ),
928
- responseCode: z17.number().nullable().optional().describe(
706
+ responseCode: z12.number().nullable().optional().describe(
929
707
  "Present for `webhook.*` events only \u2014 HTTP status your endpoint returned, or `null` if the request never connected."
930
708
  ),
931
- attempts: z17.number().optional().describe(
709
+ attempts: z12.number().optional().describe(
932
710
  "Present for `webhook.*` events only \u2014 how many delivery attempts have been made so far."
933
711
  )
934
712
  });
935
713
 
936
714
  // src/health.ts
937
- import { z as z18 } from "zod";
938
- var HealthSchema = z18.object({
939
- status: z18.enum(["ok", "error"]).describe(
715
+ import { z as z13 } from "zod";
716
+ var HealthSchema = z13.object({
717
+ status: z13.enum(["ok", "error"]).describe(
940
718
  "`error` when the database connectivity check fails \u2014 the HTTP status code mirrors this (503 instead of 200), so a plain uptime check (not just a JSON-aware one) still catches a DB outage."
941
719
  ),
942
- version: z18.string(),
943
- timestamp: z18.string().datetime(),
944
- db: z18.enum(["ok", "error"]).describe("Result of a real database connectivity check, not just a process-alive check."),
945
- pendingWebhooks: z18.number().describe("Count of webhook deliveries still awaiting a successful attempt."),
946
- oldestPendingChargeAgeSeconds: z18.number().nullable().describe("Age of the oldest still-unpaid charge, in seconds. `null` if there are none."),
947
- lastMoralisEventAgeSeconds: z18.number().nullable().describe(
720
+ version: z13.string(),
721
+ timestamp: z13.string().datetime(),
722
+ db: z13.enum(["ok", "error"]).describe("Result of a real database connectivity check, not just a process-alive check."),
723
+ pendingWebhooks: z13.number().describe("Count of webhook deliveries still awaiting a successful attempt."),
724
+ oldestPendingChargeAgeSeconds: z13.number().nullable().describe("Age of the oldest still-unpaid charge, in seconds. `null` if there are none."),
725
+ lastMoralisEventAgeSeconds: z13.number().nullable().describe(
948
726
  "Seconds since the last on-chain payment notification was received \u2014 a cheap signal for whether payment detection is currently working. `null` if none have ever been received."
949
727
  )
950
728
  });
951
729
 
952
730
  // src/sandbox.ts
953
- import { z as z19 } from "zod";
954
- var SandboxTriggerSchema = z19.object({
731
+ import { z as z14 } from "zod";
732
+ var SandboxTriggerSchema = z14.object({
955
733
  event: TriggerableChargeEventSchema,
956
- amount: z19.number().positive().max(CHARGE_AMOUNT_MAX).optional().describe(
734
+ amount: z14.number().positive().max(CHARGE_AMOUNT_MAX).optional().describe(
957
735
  "Used with `charge.partially_paid` (amount to simulate as received so far \u2014 must be less than the charge amount, defaults to half of it if omitted) and with `charge.overpaid` (amount received \u2014 must be greater than the charge amount, defaults to 1.5x it if omitted). Ignored for every other event."
958
736
  )
959
737
  });
960
- var SandboxEventTriggerSchema = z19.object({
961
- event: NonChargeTriggerableEventSchema.describe(
962
- "Any account, security, or webhook-delivery event \u2014 simulates it with synthetic data against your own webhooks, no real state change or precondition required (unlike `POST /v1/sandbox/charges/{id}/trigger`, which acts on a real charge)."
963
- )
964
- });
965
738
 
966
739
  // src/capabilities.ts
967
- import { z as z20 } from "zod";
968
- var CapabilitiesSchema = z20.object({
969
- acceptedPayments: z20.array(AcceptedPaymentSchema).describe(
740
+ import { z as z15 } from "zod";
741
+ var CapabilitiesSchema = z15.object({
742
+ acceptedPayments: z15.array(AcceptedPaymentSchema).describe(
970
743
  "Every `(token, network)` pair actually configured for your environment right now \u2014 read straight from the same lookup `POST /v1/charges` validates `acceptedPayments` against, so it can never list a pair that charge creation would then reject. Use this to build a picker UI instead of hardcoding the matrix client-side."
971
744
  )
972
745
  });
973
746
  export {
974
- AcceptInvitationSchema,
747
+ API_KEY_SCOPES,
975
748
  AcceptedPaymentSchema,
976
- AccountWebhookEventTypeSchema,
977
- ApiKeySchema,
978
- AuthResponseSchema,
749
+ ApiKeyScopeSchema,
979
750
  CHARGE_ACCEPTED_PAYMENTS_MAX,
980
751
  CHARGE_AMOUNT_MAX,
981
752
  CHARGE_EXPIRES_IN_MAX_SECONDS,
982
753
  CHARGE_EXPIRES_IN_MIN_SECONDS,
983
754
  CapabilitiesSchema,
984
- ChangeEmailSchema,
985
- ChangeNameSchema,
986
- ChangePasswordSchema,
987
- ChargeModeSchema,
988
755
  ChargeSchema,
989
756
  ChargeStatusSchema,
990
757
  ChargeWebhookEventTypeSchema,
991
758
  ChargesDateFieldSchema,
992
759
  ChargesMetricFieldSchema,
993
760
  ChargesQueryFieldSchema,
994
- ConfirmEmailChangeSchema,
995
- CreateApiKeySchema,
996
761
  CreateChargeSchema,
997
762
  CreateWebhookSchema,
998
763
  DistributionsDateFieldSchema,
@@ -1002,62 +767,40 @@ export {
1002
767
  EVM_NETWORKS,
1003
768
  EnvironmentSchema,
1004
769
  ErrorPayloadSchema,
1005
- ForgotPasswordSchema,
1006
770
  GetChargeQrCodeQuerySchema,
1007
771
  HealthSchema,
1008
- InvitationSchema,
1009
- InviteUserSchema,
1010
- ListApiKeysSchema,
1011
772
  ListChargesSchema,
1012
- ListOrganizationsSchema,
1013
- ListUsersSchema,
1014
773
  ListWebhookDeliveriesSchema,
1015
774
  ListenPendingDistributionsQuerySchema,
1016
- LoginSchema,
1017
775
  MAX_METRICS_QUERY_DATE_RANGE_DAYS,
1018
776
  METRICS_QUERY_DEFAULT_ROW_LIMIT,
1019
777
  METRICS_QUERY_MAX_FILTERS,
1020
778
  METRICS_QUERY_MAX_GROUP_BY,
1021
779
  METRICS_QUERY_MAX_METRICS,
1022
780
  METRICS_QUERY_MAX_ROW_LIMIT,
1023
- MessageResponseSchema,
1024
781
  MetricsAggregationSchema,
1025
782
  MetricsDateGranularitySchema,
1026
783
  MetricsFilterOperatorSchema,
1027
784
  MetricsQueryResultRowSchema,
1028
785
  MetricsQueryResultSchema,
1029
786
  MetricsQuerySchema,
1030
- MetricsQueryScopeSchema,
1031
787
  MetricsResourceSchema,
1032
788
  NETWORK_EXPLORERS,
1033
789
  NETWORK_LABELS,
1034
790
  NetworkSchema,
1035
- NonChargeTriggerableEventSchema,
1036
- NormalizedEmailSchema,
1037
791
  OPERATIONAL_NETWORKS,
1038
- OrganizationSchema,
1039
- OrganizationWithRoleSchema,
1040
792
  PAGINATION_LIMIT_DEFAULT,
1041
793
  PAGINATION_LIMIT_MAX,
1042
794
  PAGINATION_LIMIT_MIN,
1043
- PaginatedApiKeysSchema,
1044
795
  PaginatedChargesSchema,
1045
- PaginatedOrganizationsSchema,
1046
796
  PaginatedPendingDistributionsSchema,
1047
- PaginatedUsersSchema,
1048
797
  PaginatedWebhookDeliveriesSchema,
1049
798
  PaginationQuerySchema,
1050
799
  PendingDistributionEventSchema,
1051
800
  PendingDistributionRecipientSchema,
1052
801
  PendingDistributionSchema,
1053
- PublicChargeSchema,
1054
- ResetPasswordSchema,
1055
- SandboxEventTriggerSchema,
1056
802
  SandboxTriggerSchema,
1057
- SecurityWebhookEventTypeSchema,
1058
- SelfUserSchema,
1059
803
  SettlementStatusSchema,
1060
- SignupSchema,
1061
804
  SplitDistributionStatusSchema,
1062
805
  TOKEN_ADDRESSES,
1063
806
  TOKEN_DECIMALS,
@@ -1069,11 +812,6 @@ export {
1069
812
  TransactionsMetricFieldSchema,
1070
813
  TransactionsQueryFieldSchema,
1071
814
  TriggerableChargeEventSchema,
1072
- UpdateOrganizationSchema,
1073
- UpdateUserRoleSchema,
1074
- UserRoleSchema,
1075
- UserSchema,
1076
- VerifyEmailSchema,
1077
815
  WEBHOOK_EVENTS_WILDCARD,
1078
816
  WEBHOOK_EVENT_CATEGORIES,
1079
817
  WebhookCategorySchema,