@venturekit/billing 0.0.0-dev.20260825184900

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 (66) hide show
  1. package/README.md +218 -0
  2. package/dist/client.d.ts +109 -0
  3. package/dist/client.d.ts.map +1 -0
  4. package/dist/client.js +139 -0
  5. package/dist/client.js.map +1 -0
  6. package/dist/errors.d.ts +102 -0
  7. package/dist/errors.d.ts.map +1 -0
  8. package/dist/errors.js +133 -0
  9. package/dist/errors.js.map +1 -0
  10. package/dist/events.d.ts +170 -0
  11. package/dist/events.d.ts.map +1 -0
  12. package/dist/events.js +47 -0
  13. package/dist/events.js.map +1 -0
  14. package/dist/index.d.ts +48 -0
  15. package/dist/index.d.ts.map +1 -0
  16. package/dist/index.js +52 -0
  17. package/dist/index.js.map +1 -0
  18. package/dist/provider.d.ts +178 -0
  19. package/dist/provider.d.ts.map +1 -0
  20. package/dist/provider.js +93 -0
  21. package/dist/provider.js.map +1 -0
  22. package/dist/providers/index.d.ts +15 -0
  23. package/dist/providers/index.d.ts.map +1 -0
  24. package/dist/providers/index.js +15 -0
  25. package/dist/providers/index.js.map +1 -0
  26. package/dist/providers/mock.d.ts +79 -0
  27. package/dist/providers/mock.d.ts.map +1 -0
  28. package/dist/providers/mock.js +536 -0
  29. package/dist/providers/mock.js.map +1 -0
  30. package/dist/providers/zazu/adapter.d.ts +39 -0
  31. package/dist/providers/zazu/adapter.d.ts.map +1 -0
  32. package/dist/providers/zazu/adapter.js +233 -0
  33. package/dist/providers/zazu/adapter.js.map +1 -0
  34. package/dist/providers/zazu/client.d.ts +76 -0
  35. package/dist/providers/zazu/client.d.ts.map +1 -0
  36. package/dist/providers/zazu/client.js +163 -0
  37. package/dist/providers/zazu/client.js.map +1 -0
  38. package/dist/providers/zazu/config.d.ts +54 -0
  39. package/dist/providers/zazu/config.d.ts.map +1 -0
  40. package/dist/providers/zazu/config.js +55 -0
  41. package/dist/providers/zazu/config.js.map +1 -0
  42. package/dist/providers/zazu/correlation.d.ts +65 -0
  43. package/dist/providers/zazu/correlation.d.ts.map +1 -0
  44. package/dist/providers/zazu/correlation.js +178 -0
  45. package/dist/providers/zazu/correlation.js.map +1 -0
  46. package/dist/providers/zazu/index.d.ts +18 -0
  47. package/dist/providers/zazu/index.d.ts.map +1 -0
  48. package/dist/providers/zazu/index.js +21 -0
  49. package/dist/providers/zazu/index.js.map +1 -0
  50. package/dist/providers/zazu/maps.d.ts +36 -0
  51. package/dist/providers/zazu/maps.d.ts.map +1 -0
  52. package/dist/providers/zazu/maps.js +450 -0
  53. package/dist/providers/zazu/maps.js.map +1 -0
  54. package/dist/providers/zazu/types.d.ts +365 -0
  55. package/dist/providers/zazu/types.d.ts.map +1 -0
  56. package/dist/providers/zazu/types.js +13 -0
  57. package/dist/providers/zazu/types.js.map +1 -0
  58. package/dist/providers/zazu/webhooks.d.ts +73 -0
  59. package/dist/providers/zazu/webhooks.d.ts.map +1 -0
  60. package/dist/providers/zazu/webhooks.js +259 -0
  61. package/dist/providers/zazu/webhooks.js.map +1 -0
  62. package/dist/types.d.ts +512 -0
  63. package/dist/types.d.ts.map +1 -0
  64. package/dist/types.js +16 -0
  65. package/dist/types.js.map +1 -0
  66. package/package.json +66 -0
package/README.md ADDED
@@ -0,0 +1,218 @@
1
+ # @venturekit/billing
2
+
3
+ > **Warning:** This package is in active development and not production-ready. APIs may change without notice.
4
+
5
+ Multi-provider payment processing for [VentureKit](https://venturekit.dev) — a provider-agnostic abstraction over payment providers (Zazu today; Stripe and PayPal are the intended next adapters) covering hosted checkout, payment links, invoicing, transfers, and normalized webhook events.
6
+
7
+ > **Not to be confused with** [`@venturekit-pro/billing`](../pro/billing), which handles plans, subscriptions, usage metering, and invoice *generation*. That package deliberately excludes payment processing — this one provides it. They compose.
8
+
9
+ ## Installation
10
+
11
+ ```bash
12
+ npm install @venturekit/billing@dev
13
+ ```
14
+
15
+ ## Quick start
16
+
17
+ ```typescript
18
+ import { createBillingClient, createZazuAdapter } from '@venturekit/billing';
19
+
20
+ // createZazuAdapter() resolves config from ZAZU_* env vars.
21
+ const billing = createBillingClient({
22
+ providers: { zazu: createZazuAdapter() },
23
+ defaultProvider: 'zazu',
24
+ });
25
+
26
+ const session = await billing.createCheckoutSession({
27
+ amount: { amount: '1500.000', currency: 'MAD' },
28
+ successUrl: 'https://app.example.com/success',
29
+ // Your identifiers. Handed back on the webhook so you can find your
30
+ // own record — see "Correlation" below.
31
+ correlation: { reference: 'ORD-123', metadata: { user_id: 'usr_456' } },
32
+ });
33
+
34
+ // → redirect the customer to session.url
35
+ ```
36
+
37
+ The funding account comes from `ZAZU_ACCOUNT_ID`, not from every call site — it is a deployment property. Pass `accountId` explicitly only to override it (multi-account tenants).
38
+
39
+ ## Correlation
40
+
41
+ Webhook payloads are **projections**: each carries a strict subset of what the REST API returns, and the subset differs per event. So this package does not try to rebuild a full object from an event. Instead you attach your own identifiers on create, and the event hands them back:
42
+
43
+ ```typescript
44
+ // 1. Attach your reference when creating.
45
+ await billing.createCheckoutSession({
46
+ amount: { amount: '1500.000', currency: 'MAD' },
47
+ successUrl: 'https://app.example.com/success',
48
+ correlation: { reference: order.id },
49
+ });
50
+
51
+ // 2. Recover it on the webhook.
52
+ const event = await billing.handleWebhookEvent({ rawBody, headers });
53
+ const order = await orders.findByReference(event.correlation?.reference);
54
+
55
+ // 3. Verify the amount before fulfilling — correlation tells you WHICH
56
+ // order the event is for, not that the right amount was paid.
57
+ if (event.amount?.amount !== order.total) throw new Error('amount mismatch');
58
+ ```
59
+
60
+ Every event also carries `objectId` (the provider's id, for follow-up calls), `eventId` (**deduplicate on this** — Zazu retries up to 8 times over ~28 hours), and `raw` (the untouched payload).
61
+
62
+ ### Per-flow support
63
+
64
+ `reference` round-trips on every flow. `metadata` does not, because the transports genuinely differ — query it rather than assuming:
65
+
66
+ ```typescript
67
+ billing.adapter.correlationSupport('paymentLink');
68
+ // → { reference: true, metadata: false, channel: 'urlQuery' }
69
+ ```
70
+
71
+ | Flow | Zazu channel | `reference` | `metadata` |
72
+ | --- | --- | --- | --- |
73
+ | checkout session | `metadata` map in the create body | ✅ | ✅ (≤50 keys, values ≤500 chars) |
74
+ | payment link | `client_reference_id` URL query parameter | ✅ | ❌ |
75
+ | transfer | `payment_reference` in the create body | ✅ | ❌ |
76
+
77
+ Two consequences worth knowing:
78
+
79
+ - **Payment links** — the reference is appended to the returned `url`, so **share that exact URL**; a hand-built link loses it. Passing `metadata` throws `UnsupportedCorrelationError` rather than letting Zazu silently discard it (it accepts only four whitelisted query parameters and ignores the rest without erroring).
80
+ - **Transfers** — the reference travels as `payment_reference`, which is **visible on bank statements**, so use a human-meaningful value. It cannot be combined with an explicit `paymentReference`; setting both throws rather than silently picking one.
81
+
82
+ ## Configuration
83
+
84
+ Every value resolves from the environment, with explicit overrides accepted so secrets never live in source.
85
+
86
+ | Variable | Required | Default | Purpose |
87
+ | --- | --- | --- | --- |
88
+ | `BILLING_PROVIDER` | no | `zazu` | Provider selected by `createBillingClientFromEnv()` |
89
+ | `ZAZU_API_KEY` | **yes** | — | Bearer token for the Zazu API |
90
+ | `ZAZU_ACCOUNT_ID` | effectively yes | — | Default funding/destination account. Zazu requires one to create anything; a per-call `accountId` overrides it |
91
+ | `ZAZU_BASE_URL` | no | `https://staging.zazu.ma` | Point at production when going live |
92
+ | `ZAZU_WEBHOOK_SECRET` | for webhooks | — | Endpoint signing secret |
93
+ | `ZAZU_WEBHOOK_TOLERANCE_SECONDS` | no | `300` | Replay window; `0` disables the freshness check |
94
+
95
+ ## Capabilities
96
+
97
+ Core operations — checkout sessions, payment links, inbound webhooks — are always available. Everything else is an **optional capability** an adapter opts into, so a future Stripe or PayPal adapter never stubs methods it has no equivalent for.
98
+
99
+ | Capability | Operations | Zazu | Mock |
100
+ | --- | --- | --- | --- |
101
+ | core | checkout sessions, payment links, webhooks | ✅ | ✅ |
102
+ | `invoicing` | invoices + customers | ✅ | ✅ |
103
+ | `transfers` | outgoing transfers | ✅ | ✅ |
104
+ | `accounts` | funding accounts + ledger entries | ✅ | ✅ |
105
+ | `webhookEndpoints` | endpoint provisioning | ✅ | ✅ |
106
+
107
+ Feature-detect, or assert:
108
+
109
+ ```typescript
110
+ if (billing.accounts) {
111
+ const page = await billing.accounts.listAccounts();
112
+ }
113
+
114
+ const invoice = await billing.requireInvoicing().createInvoice({ /* … */ });
115
+ ```
116
+
117
+ ## Webhooks
118
+
119
+ `handleWebhookEvent` verifies the signature and returns a normalized `PaymentEvent`, ready to publish to your event bus.
120
+
121
+ ```typescript
122
+ import { WebhookPayloadError, WebhookSignatureError } from '@venturekit/billing';
123
+ import { publishEvent } from '@venturekit/runtime/patterns';
124
+
125
+ try {
126
+ const event = await billing.handleWebhookEvent({ rawBody, headers });
127
+ await publishEvent(event.type, event.data, { source: 'billing' });
128
+ return { statusCode: 200 };
129
+ } catch (err) {
130
+ if (err instanceof WebhookSignatureError) return { statusCode: 401 };
131
+ if (err instanceof WebhookPayloadError) return { statusCode: 400 };
132
+ throw err;
133
+ }
134
+ ```
135
+
136
+ Four things the caller **must** get right:
137
+
138
+ - **Pass the raw body.** Signatures are computed over the bytes the provider sent. Re-serializing the parsed JSON breaks verification.
139
+ - **Keep the two error classes apart.** `WebhookSignatureError` is an auth failure; `WebhookPayloadError` is an authentic request this adapter can't consume. Answering `401` to an unmapped-but-authentic event makes the provider redeliver it forever — Zazu retries for ~28 hours before giving up.
140
+ - **Deduplicate on `event.eventId`.** Providers deliver at-least-once. Signature verification rejects anything outside a 300-second window, which stops indefinite replay — but not a redelivery inside it.
141
+ - **Reconcile through `correlation`, not the payload.** An event carries only what its payload is documented to include — never a reconstructed REST object. Use `event.correlation` to find your own record, and check `event.amount` before fulfilling.
142
+
143
+ Each event's `data` is narrowed to that payload's documented fields:
144
+
145
+ | Event | `data` carries |
146
+ | --- | --- |
147
+ | `checkout_session.completed` | `sessionId`, `status`, `completedAt?`, `customerEmail?`, `description?`, `transaction?` |
148
+ | `payment_link.paid` | `paymentLinkId`, `status`, `slug?`, `title?`, `paidAt?`, `paymentsCount?`, customer fields |
149
+ | `transfer.executed` | `transferId`, `providerStatus`, `operation?`, `paymentReference?`, `postedAt?` |
150
+
151
+ ```typescript
152
+ if (isCheckoutSessionCompleted(event)) {
153
+ const order = await orders.findByReference(event.correlation?.reference);
154
+ if (event.amount?.amount !== order.total) throw new Error('amount mismatch');
155
+ await fulfil(order, event.data.transaction?.cardLastFour);
156
+ }
157
+ ```
158
+
159
+ Note `transfer.executed` exposes `providerStatus` verbatim (Zazu sends `"accepted"`) rather than coercing it into the transfers API's `requested|processing|completed|failed` vocabulary, which would misreport it. It carries **no `accountId`** — the payload has none, so resolve the source account from your own record via `correlation`.
160
+
161
+ ## Retries and idempotency
162
+
163
+ The Zazu HTTP client retries **reads only**. Zazu exposes no idempotency-key header, so a `POST` whose response was merely lost cannot be safely repeated — a retry creates a second resource. `maxRetries` therefore applies to `GET` requests; mutations fail fast with a `ProviderError` carrying a `transient` flag, letting callers that own an application-level idempotency key retry deliberately.
164
+
165
+ Worth knowing what the duplicate actually is: `POST /api/payments` creates a transfer **draft** in `requested` status for a human to approve in the Zazu app — an API key alone cannot move money. So a retried transfer duplicates entries in the approval queue (which an approver may authorize more than once), rather than settling twice. `POST /api/invoices` is the sharper edge: duplicates are sent to the customer.
166
+
167
+ ```typescript
168
+ try {
169
+ await billing.requireTransfers().createTransfer({ /* … */ });
170
+ } catch (err) {
171
+ if (err instanceof ProviderError && err.transient) {
172
+ // Safe to retry only if you can guarantee idempotency yourself.
173
+ }
174
+ }
175
+ ```
176
+
177
+ ## Testing
178
+
179
+ `createMockProvider()` is an in-memory provider implementing the full surface. It records every call and can be told to fail.
180
+
181
+ It is reachable **only** by subpath — deliberately not re-exported from the package barrel, so it stays out of production bundles:
182
+
183
+ ```typescript
184
+ import { createBillingClientFor } from '@venturekit/billing';
185
+ import { createMockProvider } from '@venturekit/billing/providers/mock';
186
+
187
+ const provider = createMockProvider({ failNext: 1 });
188
+ const billing = createBillingClientFor(provider);
189
+
190
+ expect(provider.calls.map((c) => c.method)).toContain('createCheckoutSession');
191
+ ```
192
+
193
+ ### The mock cannot run in a deployed environment
194
+
195
+ It accepts webhooks **without verifying any signature** and fabricates successful payments, so three things keep it out of production:
196
+
197
+ - **Not in the barrel.** Importing `@venturekit/billing` does not pull it in.
198
+ - **No self-registration.** It does not register itself on import, so `createProvider('mock')` throws `UnknownProviderError` unless you call `registerMockProvider()` yourself. This also means `BILLING_PROVIDER=mock` is not a working configuration.
199
+ - **A construction guard.** `createMockProvider()` throws `MockProviderNotAllowedError` unless `VENTURE_LOCAL=true` (set by `vk dev`) or `NODE_ENV=test` (set by vitest).
200
+
201
+ The guard asks *"is this provably local?"* rather than *"is this production?"* on purpose. The Lambda runtime does not set `NODE_ENV=production`, so a `NODE_ENV === 'production'` check reads false in production and fails **open** — the same trap that once shipped session cookies without `Secure` (see `packages/auth/src/server/cookies.ts`). Asking for positive proof of a local environment fails closed instead.
202
+
203
+ ## Adding a provider
204
+
205
+ No core file needs editing:
206
+
207
+ 1. Add `src/providers/<name>/` with `config.ts`, `client.ts`, `maps.ts`, `adapter.ts`, `correlation.ts`, and `webhooks.ts` — mirroring `providers/zazu/`.
208
+ 2. Implement `PaymentProvider`, plus any optional capability interfaces the provider genuinely supports.
209
+ 3. Implement `correlationSupport(flow)` **honestly**. If a flow cannot round-trip `metadata`, report `false` and throw `UnsupportedCorrelationError` when it is supplied — never accept data the provider will discard.
210
+ 4. Round-trip `correlation.reference` on every flow, and populate `correlation`, `objectId`, `amount`, and `raw` on every event.
211
+ 5. Map provider errors to `ProviderError` with `transient` set correctly, and throw `WebhookSignatureError` / `WebhookPayloadError` from webhook handling.
212
+ 6. Call `registerProvider('<name>', factory)` in the provider's barrel.
213
+ 7. Add a `./providers/<name>` entry to `exports` in `package.json`.
214
+ 8. Re-export from `src/providers/index.ts`.
215
+
216
+ ## License
217
+
218
+ Apache-2.0 — see [LICENSE](../../LICENSE) for details.
@@ -0,0 +1,109 @@
1
+ /**
2
+ * @venturekit/billing — billing client facade
3
+ *
4
+ * Wraps a provider adapter with a stable, provider-agnostic API.
5
+ * Providers are passed in as **instances** (like `@venturekit/notify`),
6
+ * so you only bundle the providers you construct and can mix several in
7
+ * one application:
8
+ *
9
+ * ```ts
10
+ * import { createBillingClient, createZazuAdapter } from '@venturekit/billing';
11
+ *
12
+ * // createZazuAdapter() resolves config from ZAZU_* env vars.
13
+ * const billing = createBillingClient({
14
+ * providers: { zazu: createZazuAdapter() },
15
+ * defaultProvider: 'zazu',
16
+ * });
17
+ *
18
+ * const session = await billing.createCheckoutSession({ ... });
19
+ * const event = await billing.handleWebhookEvent({ rawBody, headers });
20
+ * ```
21
+ *
22
+ * ## Capabilities
23
+ *
24
+ * Core operations (checkout sessions, payment links, webhook handling)
25
+ * are always available. Optional capabilities — invoicing, transfers,
26
+ * accounts, webhook endpoint provisioning — are exposed as nullable
27
+ * namespaces so consumers can feature-detect:
28
+ *
29
+ * ```ts
30
+ * const accounts = billing.accounts; // null if unsupported
31
+ * if (accounts) {
32
+ * const page = await accounts.listAccounts();
33
+ * }
34
+ *
35
+ * // …or assert when you know the provider supports it:
36
+ * const invoice = await billing.requireInvoicing().createInvoice({ ... });
37
+ * ```
38
+ */
39
+ import type { PaymentEvent } from './events.js';
40
+ import { BillingError } from './errors.js';
41
+ import { type AccountCapable, type InvoicingCapable, type PaymentProvider, type ProviderName, type TransferCapable, type WebhookEndpointCapable, type WebhookRequest } from './provider.js';
42
+ import type { CheckoutSession, CreateCheckoutSessionInput, CreatePaymentLinkInput, CursorPage, ListPaymentLinksParams, PaymentLink } from './types.js';
43
+ /** Thrown when a capability is required but the provider doesn't implement it. */
44
+ export declare class CapabilityNotSupportedError extends BillingError {
45
+ readonly capability: string;
46
+ readonly provider: ProviderName;
47
+ constructor(capability: string, provider: ProviderName);
48
+ }
49
+ export interface BillingClient {
50
+ /** The active provider's name. */
51
+ readonly provider: ProviderName;
52
+ /** The underlying adapter (escape hatch for provider-specific calls). */
53
+ readonly adapter: PaymentProvider;
54
+ createCheckoutSession(input: CreateCheckoutSessionInput): Promise<CheckoutSession>;
55
+ getCheckoutSession(id: string): Promise<CheckoutSession>;
56
+ createPaymentLink(input: CreatePaymentLinkInput): Promise<PaymentLink>;
57
+ getPaymentLink(id: string): Promise<PaymentLink>;
58
+ listPaymentLinks(params?: ListPaymentLinksParams): Promise<CursorPage<PaymentLink>>;
59
+ cancelPaymentLink(id: string): Promise<PaymentLink>;
60
+ handleWebhookEvent(request: WebhookRequest): Promise<PaymentEvent>;
61
+ readonly invoicing: InvoicingCapable | null;
62
+ readonly transfers: TransferCapable | null;
63
+ readonly accounts: AccountCapable | null;
64
+ readonly webhookEndpoints: WebhookEndpointCapable | null;
65
+ /** Assert invoicing support; throws {@link CapabilityNotSupportedError}. */
66
+ requireInvoicing(): InvoicingCapable;
67
+ /** Assert transfer support; throws {@link CapabilityNotSupportedError}. */
68
+ requireTransfers(): TransferCapable;
69
+ /** Assert account support; throws {@link CapabilityNotSupportedError}. */
70
+ requireAccounts(): AccountCapable;
71
+ /** Assert webhook endpoint support; throws {@link CapabilityNotSupportedError}. */
72
+ requireWebhookEndpoints(): WebhookEndpointCapable;
73
+ }
74
+ export interface CreateBillingClientOptions {
75
+ /**
76
+ * Provider instances keyed by name. Only constructed providers are
77
+ * bundled. Partial because {@link ProviderName} is an open `string` —
78
+ * a lookup can always miss, which `createBillingClient` checks.
79
+ */
80
+ providers: Partial<Record<ProviderName, PaymentProvider>>;
81
+ /** Name of the provider to use by default. */
82
+ defaultProvider: ProviderName;
83
+ }
84
+ /**
85
+ * Create a billing client from explicitly constructed provider
86
+ * instances. This is the primary, fully tree-shakeable path — you import
87
+ * and construct exactly the providers you use.
88
+ */
89
+ export declare function createBillingClient(options: CreateBillingClientOptions): BillingClient;
90
+ /**
91
+ * Create a billing client from a single provider instance. Useful for
92
+ * one-provider applications or provider-specific code paths.
93
+ */
94
+ export declare function createBillingClientFor(adapter: PaymentProvider): BillingClient;
95
+ export interface CreateBillingClientFromEnvOptions {
96
+ /** Provider to use. Defaults to `BILLING_PROVIDER` env var, then `'zazu'`. */
97
+ provider?: ProviderName;
98
+ /** Optional per-provider config overrides, keyed by provider name. */
99
+ config?: Partial<Record<ProviderName, unknown>>;
100
+ }
101
+ /**
102
+ * Create a billing client resolved entirely from environment variables.
103
+ * Reads `BILLING_PROVIDER` (default `'zazu'`), lazy-imports the matching
104
+ * built-in provider, and lets it resolve its own config from its env
105
+ * vars (`ZAZU_*`, …). Falls back to the registry for providers the host
106
+ * application registered itself.
107
+ */
108
+ export declare function createBillingClientFromEnv(options?: CreateBillingClientFromEnvOptions): Promise<BillingClient>;
109
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,EAAE,YAAY,EAAwB,MAAM,aAAa,CAAC;AACjE,OAAO,EAOL,KAAK,cAAc,EACnB,KAAK,gBAAgB,EACrB,KAAK,eAAe,EACpB,KAAK,YAAY,EACjB,KAAK,eAAe,EACpB,KAAK,sBAAsB,EAC3B,KAAK,cAAc,EACpB,MAAM,eAAe,CAAC;AACvB,OAAO,KAAK,EACV,eAAe,EACf,0BAA0B,EAC1B,sBAAsB,EACtB,UAAU,EACV,sBAAsB,EACtB,WAAW,EACZ,MAAM,YAAY,CAAC;AAEpB,kFAAkF;AAClF,qBAAa,2BAA4B,SAAQ,YAAY;IAC3D,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,QAAQ,EAAE,YAAY,CAAC;gBACpB,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,YAAY;CAMvD;AAED,MAAM,WAAW,aAAa;IAC5B,kCAAkC;IAClC,QAAQ,CAAC,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AAC;CAC/B;AAED;;;;GAIG;AACH,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,0BAA0B,GAAG,aAAa,CAMtF;AAED;;;GAGG;AACH,wBAAgB,sBAAsB,CAAC,OAAO,EAAE,eAAe,GAAG,aAAa,CAE9E;AA0BD,MAAM,WAAW,iCAAiC;IAChD,8EAA8E;IAC9E,QAAQ,CAAC,EAAE,YAAY,CAAC;IACxB,sEAAsE;IACtE,MAAM,CAAC,EAAE,OAAO,CAAC,MAAM,CAAC,YAAY,EAAE,OAAO,CAAC,CAAC,CAAC;CACjD;AAED;;;;;;GAMG;AACH,wBAAsB,0BAA0B,CAC9C,OAAO,CAAC,EAAE,iCAAiC,GAC1C,OAAO,CAAC,aAAa,CAAC,CAYxB"}
package/dist/client.js ADDED
@@ -0,0 +1,139 @@
1
+ /**
2
+ * @venturekit/billing — billing client facade
3
+ *
4
+ * Wraps a provider adapter with a stable, provider-agnostic API.
5
+ * Providers are passed in as **instances** (like `@venturekit/notify`),
6
+ * so you only bundle the providers you construct and can mix several in
7
+ * one application:
8
+ *
9
+ * ```ts
10
+ * import { createBillingClient, createZazuAdapter } from '@venturekit/billing';
11
+ *
12
+ * // createZazuAdapter() resolves config from ZAZU_* env vars.
13
+ * const billing = createBillingClient({
14
+ * providers: { zazu: createZazuAdapter() },
15
+ * defaultProvider: 'zazu',
16
+ * });
17
+ *
18
+ * const session = await billing.createCheckoutSession({ ... });
19
+ * const event = await billing.handleWebhookEvent({ rawBody, headers });
20
+ * ```
21
+ *
22
+ * ## Capabilities
23
+ *
24
+ * Core operations (checkout sessions, payment links, webhook handling)
25
+ * are always available. Optional capabilities — invoicing, transfers,
26
+ * accounts, webhook endpoint provisioning — are exposed as nullable
27
+ * namespaces so consumers can feature-detect:
28
+ *
29
+ * ```ts
30
+ * const accounts = billing.accounts; // null if unsupported
31
+ * if (accounts) {
32
+ * const page = await accounts.listAccounts();
33
+ * }
34
+ *
35
+ * // …or assert when you know the provider supports it:
36
+ * const invoice = await billing.requireInvoicing().createInvoice({ ... });
37
+ * ```
38
+ */
39
+ import { BillingError, UnknownProviderError } from './errors.js';
40
+ import { createProvider, isProviderRegistered, supportsAccounts, supportsInvoicing, supportsTransfers, supportsWebhookEndpoints, } from './provider.js';
41
+ /** Thrown when a capability is required but the provider doesn't implement it. */
42
+ export class CapabilityNotSupportedError extends BillingError {
43
+ capability;
44
+ provider;
45
+ constructor(capability, provider) {
46
+ super(`Provider "${provider}" does not support the "${capability}" capability.`);
47
+ this.name = 'CapabilityNotSupportedError';
48
+ this.capability = capability;
49
+ this.provider = provider;
50
+ }
51
+ }
52
+ function wrap(adapter) {
53
+ const invoicing = supportsInvoicing(adapter) ? adapter : null;
54
+ const transfers = supportsTransfers(adapter) ? adapter : null;
55
+ const accounts = supportsAccounts(adapter) ? adapter : null;
56
+ const webhookEndpoints = supportsWebhookEndpoints(adapter) ? adapter : null;
57
+ function require(cap, name) {
58
+ if (!cap)
59
+ throw new CapabilityNotSupportedError(name, adapter.name);
60
+ return cap;
61
+ }
62
+ return {
63
+ provider: adapter.name,
64
+ adapter,
65
+ createCheckoutSession: (i) => adapter.createCheckoutSession(i),
66
+ getCheckoutSession: (id) => adapter.getCheckoutSession(id),
67
+ createPaymentLink: (i) => adapter.createPaymentLink(i),
68
+ getPaymentLink: (id) => adapter.getPaymentLink(id),
69
+ listPaymentLinks: (p) => adapter.listPaymentLinks(p),
70
+ cancelPaymentLink: (id) => adapter.cancelPaymentLink(id),
71
+ handleWebhookEvent: (r) => adapter.handleWebhookEvent(r),
72
+ invoicing,
73
+ transfers,
74
+ accounts,
75
+ webhookEndpoints,
76
+ requireInvoicing: () => require(invoicing, 'invoicing'),
77
+ requireTransfers: () => require(transfers, 'transfers'),
78
+ requireAccounts: () => require(accounts, 'accounts'),
79
+ requireWebhookEndpoints: () => require(webhookEndpoints, 'webhookEndpoints'),
80
+ };
81
+ }
82
+ /**
83
+ * Create a billing client from explicitly constructed provider
84
+ * instances. This is the primary, fully tree-shakeable path — you import
85
+ * and construct exactly the providers you use.
86
+ */
87
+ export function createBillingClient(options) {
88
+ const adapter = options.providers[options.defaultProvider];
89
+ if (!adapter) {
90
+ throw new UnknownProviderError(options.defaultProvider);
91
+ }
92
+ return wrap(adapter);
93
+ }
94
+ /**
95
+ * Create a billing client from a single provider instance. Useful for
96
+ * one-provider applications or provider-specific code paths.
97
+ */
98
+ export function createBillingClientFor(adapter) {
99
+ return wrap(adapter);
100
+ }
101
+ // ---------------------------------------------------------------------------
102
+ // Environment-driven convenience
103
+ // ---------------------------------------------------------------------------
104
+ /**
105
+ * Built-in providers constructible purely from environment variables.
106
+ * Lazily imported so only the selected provider's code is loaded.
107
+ * Third-party providers (registered by the host app) fall through to
108
+ * the registry.
109
+ *
110
+ * The mock is deliberately **not** listed. Having it here made
111
+ * `BILLING_PROVIDER=mock` a working configuration in any deployed stage,
112
+ * silently swapping in a provider that accepts unverified webhooks. Tests
113
+ * and local dev opt in explicitly via `registerMockProvider()` from
114
+ * `@venturekit/billing/providers/mock`, which still resolves through the
115
+ * registry fallback below.
116
+ */
117
+ const envProviders = {
118
+ zazu: async (cfg) => (await import('./providers/zazu/index.js')).createZazuAdapter(cfg),
119
+ };
120
+ /**
121
+ * Create a billing client resolved entirely from environment variables.
122
+ * Reads `BILLING_PROVIDER` (default `'zazu'`), lazy-imports the matching
123
+ * built-in provider, and lets it resolve its own config from its env
124
+ * vars (`ZAZU_*`, …). Falls back to the registry for providers the host
125
+ * application registered itself.
126
+ */
127
+ export async function createBillingClientFromEnv(options) {
128
+ const name = options?.provider ?? process.env.BILLING_PROVIDER ?? 'zazu';
129
+ const config = options?.config?.[name];
130
+ const build = envProviders[name];
131
+ if (build) {
132
+ return wrap(await build(config));
133
+ }
134
+ if (isProviderRegistered(name)) {
135
+ return wrap(createProvider(name, config));
136
+ }
137
+ throw new UnknownProviderError(name);
138
+ }
139
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.js","sourceRoot":"","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CAAC;QACb,MAAM,IAAI,oBAAoB,CAAC,OAAO,CAAC,eAAe,CAAC,CAAC;IAC1D,CAAC;IACD,OAAO,IAAI,CAAC,OAAO,CAAC,CAAC;AACvB,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,sBAAsB,CAAC,OAAwB;IAC7D,OAAO,IAAI,CAAC,OAAO,CAAC,CAAC;AACvB,CAAC;AAED,8EAA8E;AAC9E,iCAAiC;AACjC,8EAA8E;AAE9E;;;;;;;;;;;;GAYG;AACH,MAAM,YAAY,GAEd;IACF,IAAI,EAAE,KAAK,EAAE,GAAG,EAAE,EAAE,CAClB,CAAC,MAAM,MAAM,CAAC,2BAA2B,CAAC,CAAC,CAAC,iBAAiB,CAAC,GAAa,CAAC;CAC/E,CAAC;AASF;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,0BAA0B,CAC9C,OAA2C;IAE3C,MAAM,IAAI,GAAG,OAAO,EAAE,QAAQ,IAAI,OAAO,CAAC,GAAG,CAAC,gBAAgB,IAAI,MAAM,CAAC;IACzE,MAAM,MAAM,GAAG,OAAO,EAAE,MAAM,EAAE,CAAC,IAAI,CAAC,CAAC;IAEvC,MAAM,KAAK,GAAG,YAAY,CAAC,IAAI,CAAC,CAAC;IACjC,IAAI,KAAK,EAAE,CAAC;QACV,OAAO,IAAI,CAAC,MAAM,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC;IACnC,CAAC;IACD,IAAI,oBAAoB,CAAC,IAAI,CAAC,EAAE,CAAC;QAC/B,OAAO,IAAI,CAAC,cAAc,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC,CAAC;IAC5C,CAAC;IACD,MAAM,IAAI,oBAAoB,CAAC,IAAI,CAAC,CAAC;AACvC,CAAC"}
@@ -0,0 +1,102 @@
1
+ /**
2
+ * @venturekit/billing — error hierarchy
3
+ *
4
+ * All provider failures surface as a {@link ProviderError} carrying a
5
+ * `transient` flag. Transient errors (5xx, 429, network) are safe to
6
+ * retry; hard errors (4xx, auth, validation) should fail immediately.
7
+ * This mirrors the `ProviderSendError` / `ProviderHardError` split in
8
+ * `@venturekit/notify` but collapses both into one class with a flag so
9
+ * adapters can classify by HTTP status without picking a subclass.
10
+ */
11
+ /** Base class for every error thrown by this package. */
12
+ export declare class BillingError extends Error {
13
+ cause?: unknown;
14
+ constructor(message: string, cause?: unknown);
15
+ }
16
+ /**
17
+ * Error returned by a payment provider. Use `transient` to decide
18
+ * whether to retry: `true` means the failure is likely temporary
19
+ * (provider 5xx, rate limit, network blip); `false` means the request
20
+ * is structurally wrong and retrying won't help (auth, validation,
21
+ * not found).
22
+ */
23
+ export declare class ProviderError extends BillingError {
24
+ /** HTTP status from the provider response, or `0` for network errors. */
25
+ readonly status: number;
26
+ /** Whether retrying the same request could succeed. */
27
+ readonly transient: boolean;
28
+ /** Raw provider response body (for diagnostics). */
29
+ readonly providerData?: unknown;
30
+ constructor(options: {
31
+ message: string;
32
+ status: number;
33
+ transient: boolean;
34
+ providerData?: unknown;
35
+ cause?: unknown;
36
+ });
37
+ }
38
+ /**
39
+ * Webhook signature verification failed — the request is not provably
40
+ * from the provider. Treat as an authentication failure (respond 401)
41
+ * and alert: a burst of these means either a rotated secret or an
42
+ * attacker probing the endpoint.
43
+ */
44
+ export declare class WebhookSignatureError extends BillingError {
45
+ constructor(message: string, cause?: unknown);
46
+ }
47
+ /**
48
+ * The signature verified but the payload could not be parsed or
49
+ * normalized — malformed JSON, a missing required header, absent event
50
+ * data, or an event type this adapter doesn't map.
51
+ *
52
+ * Deliberately distinct from {@link WebhookSignatureError}: this is an
53
+ * authentic request the adapter can't consume, so it must NOT be
54
+ * reported as an auth failure. Respond 400 (and, for an unknown event
55
+ * type, consider 200 so the provider stops redelivering it).
56
+ */
57
+ export declare class WebhookPayloadError extends BillingError {
58
+ constructor(message: string, cause?: unknown);
59
+ }
60
+ /** The requested provider is not registered in the factory. */
61
+ export declare class UnknownProviderError extends BillingError {
62
+ readonly provider: string;
63
+ constructor(provider: string);
64
+ }
65
+ /**
66
+ * A {@link CorrelationRef} carried data the target flow cannot
67
+ * round-trip, or a reference collided with a provider-visible field.
68
+ *
69
+ * This exists because the failure is otherwise **silent**: Zazu accepts
70
+ * only four whitelisted query parameters on a payment link and ignores
71
+ * everything else without error, so a dropped metadata map would only
72
+ * surface as missing data at webhook time — long after the request that
73
+ * caused it.
74
+ */
75
+ export declare class UnsupportedCorrelationError extends BillingError {
76
+ readonly flow: string;
77
+ constructor(flow: string, detail: string);
78
+ }
79
+ /**
80
+ * A {@link CorrelationRef} violated a provider's metadata constraints
81
+ * (key count, key charset, or value length). Raised locally, before the
82
+ * request, so the failure names the offending key instead of surfacing
83
+ * as an opaque provider 422.
84
+ */
85
+ export declare class InvalidCorrelationError extends BillingError {
86
+ constructor(message: string);
87
+ }
88
+ /**
89
+ * The mock provider was constructed outside a provably local
90
+ * environment. The mock accepts webhooks **without verifying any
91
+ * signature** and fabricates successful payments, so reaching it from a
92
+ * deployed stage would mean trusting forged payment events.
93
+ */
94
+ export declare class MockProviderNotAllowedError extends BillingError {
95
+ constructor();
96
+ }
97
+ /** Required configuration (API key, base URL, …) is missing. */
98
+ export declare class MissingConfigError extends BillingError {
99
+ readonly key: string;
100
+ constructor(key: string, hint?: string);
101
+ }
102
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,yDAAyD;AACzD,qBAAa,YAAa,SAAQ,KAAK;IACrC,KAAK,CAAC,EAAE,OAAO,CAAC;gBACJ,OAAO,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,OAAO;CAK7C;AAED;;;;;;GAMG;AACH,qBAAa,aAAc,SAAQ,YAAY;IAC7C,yEAAyE;IACzE,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,uDAAuD;IACvD,QAAQ,CAAC,SAAS,EAAE,OAAO,CAAC;IAC5B,oDA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