@onflay/node 0.3.0 → 1.0.0-staging-20261206080029
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/CHANGELOG.md +74 -0
- package/README.md +211 -48
- package/dist/chunk-4RUPPDC2.mjs +121 -0
- package/dist/chunk-4RUPPDC2.mjs.map +1 -0
- package/dist/chunk-63KSRMJG.mjs +47 -0
- package/dist/chunk-63KSRMJG.mjs.map +1 -0
- package/dist/chunk-7LYAEZCT.mjs +197 -0
- package/dist/chunk-7LYAEZCT.mjs.map +1 -0
- package/dist/chunk-A3TRCKHK.mjs +60 -0
- package/dist/chunk-A3TRCKHK.mjs.map +1 -0
- package/dist/chunk-AFAU2FH2.js +47 -0
- package/dist/chunk-AFAU2FH2.js.map +1 -0
- package/dist/chunk-DBE2YZWE.mjs +38 -0
- package/dist/chunk-DBE2YZWE.mjs.map +1 -0
- package/dist/chunk-EOHFYWFQ.mjs +154 -0
- package/dist/chunk-EOHFYWFQ.mjs.map +1 -0
- package/dist/chunk-I2IVHBFA.js +197 -0
- package/dist/chunk-I2IVHBFA.js.map +1 -0
- package/dist/chunk-J4MYKTPN.mjs +37 -0
- package/dist/chunk-J4MYKTPN.mjs.map +1 -0
- package/dist/chunk-JQPANXLV.mjs +37 -0
- package/dist/chunk-JQPANXLV.mjs.map +1 -0
- package/dist/chunk-JXP6V2P2.mjs +1057 -0
- package/dist/chunk-JXP6V2P2.mjs.map +1 -0
- package/dist/chunk-M52GW7GQ.js +1057 -0
- package/dist/chunk-M52GW7GQ.js.map +1 -0
- package/dist/chunk-MMMUKAI6.js +37 -0
- package/dist/chunk-MMMUKAI6.js.map +1 -0
- package/dist/chunk-NSR4UQLV.js +87 -0
- package/dist/chunk-NSR4UQLV.js.map +1 -0
- package/dist/chunk-SUONZUVK.js +154 -0
- package/dist/chunk-SUONZUVK.js.map +1 -0
- package/dist/chunk-T26CPULH.js +121 -0
- package/dist/chunk-T26CPULH.js.map +1 -0
- package/dist/chunk-V2XJ4GZU.js +38 -0
- package/dist/chunk-V2XJ4GZU.js.map +1 -0
- package/dist/chunk-W6AEPYUG.js +37 -0
- package/dist/chunk-W6AEPYUG.js.map +1 -0
- package/dist/chunk-YHQ7XIC6.js +60 -0
- package/dist/chunk-YHQ7XIC6.js.map +1 -0
- package/dist/chunk-YSXUZYUY.mjs +87 -0
- package/dist/chunk-YSXUZYUY.mjs.map +1 -0
- package/dist/index-C1KFW_9r.d.mts +3989 -0
- package/dist/index-C1KFW_9r.d.ts +3989 -0
- package/dist/index.d.mts +918 -0
- package/dist/index.d.ts +918 -29
- package/dist/index.js +2990 -42
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +2991 -0
- package/dist/index.mjs.map +1 -0
- package/dist/lib/config.d.mts +59 -0
- package/dist/lib/config.d.ts +59 -0
- package/dist/lib/config.js +15 -0
- package/dist/lib/config.js.map +1 -0
- package/dist/lib/config.mjs +15 -0
- package/dist/lib/config.mjs.map +1 -0
- package/dist/lib/http.d.mts +51 -0
- package/dist/lib/http.d.ts +51 -0
- package/dist/lib/http.js +13 -0
- package/dist/lib/http.js.map +1 -0
- package/dist/lib/http.mjs +13 -0
- package/dist/lib/http.mjs.map +1 -0
- package/dist/lib/retries.d.mts +41 -0
- package/dist/lib/retries.d.ts +41 -0
- package/dist/lib/retries.js +16 -0
- package/dist/lib/retries.js.map +1 -0
- package/dist/lib/retries.mjs +16 -0
- package/dist/lib/retries.mjs.map +1 -0
- package/dist/lib/sdks.d.mts +61 -0
- package/dist/lib/sdks.d.ts +61 -0
- package/dist/lib/sdks.js +12 -0
- package/dist/lib/sdks.js.map +1 -0
- package/dist/lib/sdks.mjs +12 -0
- package/dist/lib/sdks.mjs.map +1 -0
- package/dist/models/components/index.d.mts +1 -0
- package/dist/models/components/index.d.ts +1 -0
- package/dist/models/components/index.js +1 -0
- package/dist/models/components/index.js.map +1 -0
- package/dist/models/components/index.mjs +1 -0
- package/dist/models/components/index.mjs.map +1 -0
- package/dist/models/errors/index.d.mts +161 -0
- package/dist/models/errors/index.d.ts +161 -0
- package/dist/models/errors/index.js +29 -0
- package/dist/models/errors/index.js.map +1 -0
- package/dist/models/errors/index.mjs +29 -0
- package/dist/models/errors/index.mjs.map +1 -0
- package/dist/models/operations/index.d.mts +769 -0
- package/dist/models/operations/index.d.ts +769 -0
- package/dist/models/operations/index.js +1 -0
- package/dist/models/operations/index.js.map +1 -0
- package/dist/models/operations/index.mjs +1 -0
- package/dist/models/operations/index.mjs.map +1 -0
- package/dist/types/index.d.mts +26 -0
- package/dist/types/index.d.ts +26 -0
- package/dist/types/index.js +1 -0
- package/dist/types/index.js.map +1 -0
- package/dist/types/index.mjs +1 -0
- package/dist/types/index.mjs.map +1 -0
- package/dist/verify-tF2BsJK6.d.mts +325 -0
- package/dist/verify-tF2BsJK6.d.ts +325 -0
- package/dist/webhooks/express.d.mts +39 -0
- package/dist/webhooks/express.d.ts +39 -0
- package/dist/webhooks/express.js +10 -0
- package/dist/webhooks/express.js.map +1 -0
- package/dist/webhooks/express.mjs +10 -0
- package/dist/webhooks/express.mjs.map +1 -0
- package/dist/webhooks/hono.d.mts +33 -0
- package/dist/webhooks/hono.d.ts +33 -0
- package/dist/webhooks/hono.js +10 -0
- package/dist/webhooks/hono.js.map +1 -0
- package/dist/webhooks/hono.mjs +10 -0
- package/dist/webhooks/hono.mjs.map +1 -0
- package/dist/webhooks/index.d.mts +34 -0
- package/dist/webhooks/index.d.ts +34 -0
- package/dist/webhooks/index.js +75 -0
- package/dist/webhooks/index.js.map +1 -0
- package/dist/webhooks/index.mjs +75 -0
- package/dist/webhooks/index.mjs.map +1 -0
- package/dist/webhooks/next.d.mts +38 -0
- package/dist/webhooks/next.d.ts +38 -0
- package/dist/webhooks/next.js +10 -0
- package/dist/webhooks/next.js.map +1 -0
- package/dist/webhooks/next.mjs +10 -0
- package/dist/webhooks/next.mjs.map +1 -0
- package/package.json +273 -14
- package/dist/client.d.ts +0 -65
- package/dist/client.d.ts.map +0 -1
- package/dist/client.js +0 -216
- package/dist/client.js.map +0 -1
- package/dist/errors.d.ts +0 -61
- package/dist/errors.d.ts.map +0 -1
- package/dist/errors.js +0 -134
- package/dist/errors.js.map +0 -1
- package/dist/index.d.ts.map +0 -1
- package/dist/onflay.d.ts +0 -44
- package/dist/onflay.d.ts.map +0 -1
- package/dist/onflay.js +0 -63
- package/dist/onflay.js.map +0 -1
- package/dist/pagination.d.ts +0 -19
- package/dist/pagination.d.ts.map +0 -1
- package/dist/pagination.js +0 -61
- package/dist/pagination.js.map +0 -1
- package/dist/resources/checkout-sessions.d.ts +0 -11
- package/dist/resources/checkout-sessions.d.ts.map +0 -1
- package/dist/resources/checkout-sessions.js +0 -20
- package/dist/resources/checkout-sessions.js.map +0 -1
- package/dist/resources/customers.d.ts +0 -17
- package/dist/resources/customers.d.ts.map +0 -1
- package/dist/resources/customers.js +0 -39
- package/dist/resources/customers.js.map +0 -1
- package/dist/resources/invoices.d.ts +0 -60
- package/dist/resources/invoices.d.ts.map +0 -1
- package/dist/resources/invoices.js +0 -69
- package/dist/resources/invoices.js.map +0 -1
- package/dist/resources/payments.d.ts +0 -11
- package/dist/resources/payments.d.ts.map +0 -1
- package/dist/resources/payments.js +0 -27
- package/dist/resources/payments.js.map +0 -1
- package/dist/resources/prices.d.ts +0 -24
- package/dist/resources/prices.d.ts.map +0 -1
- package/dist/resources/prices.js +0 -46
- package/dist/resources/prices.js.map +0 -1
- package/dist/resources/products.d.ts +0 -18
- package/dist/resources/products.d.ts.map +0 -1
- package/dist/resources/products.js +0 -40
- package/dist/resources/products.js.map +0 -1
- package/dist/resources/subscriptions.d.ts +0 -39
- package/dist/resources/subscriptions.d.ts.map +0 -1
- package/dist/resources/subscriptions.js +0 -62
- package/dist/resources/subscriptions.js.map +0 -1
- package/dist/resources/usage.d.ts +0 -26
- package/dist/resources/usage.d.ts.map +0 -1
- package/dist/resources/usage.js +0 -43
- package/dist/resources/usage.js.map +0 -1
- package/dist/resources/webhook-endpoints.d.ts +0 -20
- package/dist/resources/webhook-endpoints.d.ts.map +0 -1
- package/dist/resources/webhook-endpoints.js +0 -47
- package/dist/resources/webhook-endpoints.js.map +0 -1
- package/dist/types/checkout-sessions.d.ts +0 -67
- package/dist/types/checkout-sessions.d.ts.map +0 -1
- package/dist/types/checkout-sessions.js +0 -3
- package/dist/types/checkout-sessions.js.map +0 -1
- package/dist/types/customers.d.ts +0 -28
- package/dist/types/customers.d.ts.map +0 -1
- package/dist/types/customers.js +0 -3
- package/dist/types/customers.js.map +0 -1
- package/dist/types/events.d.ts +0 -118
- package/dist/types/events.d.ts.map +0 -1
- package/dist/types/events.js +0 -28
- package/dist/types/events.js.map +0 -1
- package/dist/types/invoices.d.ts +0 -65
- package/dist/types/invoices.d.ts.map +0 -1
- package/dist/types/invoices.js +0 -3
- package/dist/types/invoices.js.map +0 -1
- package/dist/types/payments.d.ts +0 -25
- package/dist/types/payments.d.ts.map +0 -1
- package/dist/types/payments.js +0 -3
- package/dist/types/payments.js.map +0 -1
- package/dist/types/prices.d.ts +0 -57
- package/dist/types/prices.d.ts.map +0 -1
- package/dist/types/prices.js +0 -3
- package/dist/types/prices.js.map +0 -1
- package/dist/types/products.d.ts +0 -29
- package/dist/types/products.d.ts.map +0 -1
- package/dist/types/products.js +0 -3
- package/dist/types/products.js.map +0 -1
- package/dist/types/shared.d.ts +0 -34
- package/dist/types/shared.d.ts.map +0 -1
- package/dist/types/shared.js +0 -4
- package/dist/types/shared.js.map +0 -1
- package/dist/types/subscriptions.d.ts +0 -85
- package/dist/types/subscriptions.d.ts.map +0 -1
- package/dist/types/subscriptions.js +0 -3
- package/dist/types/subscriptions.js.map +0 -1
- package/dist/types/usage.d.ts +0 -35
- package/dist/types/usage.d.ts.map +0 -1
- package/dist/types/usage.js +0 -3
- package/dist/types/usage.js.map +0 -1
- package/dist/types/webhook-endpoints.d.ts +0 -48
- package/dist/types/webhook-endpoints.d.ts.map +0 -1
- package/dist/types/webhook-endpoints.js +0 -3
- package/dist/types/webhook-endpoints.js.map +0 -1
- package/dist/version.d.ts +0 -4
- package/dist/version.d.ts.map +0 -1
- package/dist/version.js +0 -7
- package/dist/version.js.map +0 -1
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
# @onflay/node
|
|
2
|
+
|
|
3
|
+
## 1.0.0-staging-20261206080029
|
|
4
|
+
|
|
5
|
+
### Major Changes
|
|
6
|
+
|
|
7
|
+
- 504d711: `@onflay/node` 1.0: a new SDK generated from the OpenAPI spec (Hey API for the low-level layer, plus a thin runtime), covering all 72 public operations. Its public surface follows the conventions of Speakeasy-generated TypeScript SDKs:
|
|
8
|
+
- `new Onflay({ bearer, server: 'production' | 'sandbox', serverURL, retryConfig, timeoutMs, apiVersion, httpClient })`. With no `bearer` it reads `ONFLAY_BEARER`, then `ONFLAY_SECRET_KEY`; `sk_test_` keys default to the sandbox server.
|
|
9
|
+
- Resources from `x-speakeasy-group`, methods from `x-speakeasy-name-override`: `onflay.catalog.products.upsert({ key, upsertCatalogProduct })`, `onflay.customerAccess.retrieve({ externalCustomerId })`, `onflay.checkoutSessions.create({ idempotencyKey, createCheckout })`.
|
|
10
|
+
- Paginated methods return a `PageIterator`: the first page (`result.result.data`), iterable with `for await`, following `nextCursor`.
|
|
11
|
+
- Retries from the spec (backoff on 429 / 5XX and connection errors, honouring `Retry-After`), overridable per client (`retryConfig`) and per call (`{ retries, retryCodes }`).
|
|
12
|
+
- Errors from `@onflay/node/models/errors`: `OnflayError` (statusCode, body, headers), `ApiError` for the error envelope (`err.error.code`, `type`, `message`, `param`, `hint`, `docUrl`, `requestId`, `errors`), `OnflayDefaultError`, `ConnectionError`, `RequestTimeoutError`, …
|
|
13
|
+
- Timestamps are `Date` objects. Dual ESM/CommonJS build with types; subpaths `models/components`, `models/operations`, `models/errors`, `lib/http`, `lib/retries`, `types` and `webhooks` (verification, framework handlers and event types, plus `unwrap()`).
|
|
14
|
+
|
|
15
|
+
Breaking: the 0.x API (`new Onflay(key, options)`, positional ids, `listAll()`, `client.request()`, the `Onflay*Error` classes and the webhook event types) is gone. See the README's "Upgrading from 0.x" table. Webhook event types now live in `@onflay/node/webhooks`.
|
|
16
|
+
|
|
17
|
+
- deacba6: Two SDK packages instead of four.
|
|
18
|
+
- `@onflay/node` now contains webhooks. Everything from `@onflay/webhooks` moved here with the same names: `@onflay/webhooks` → `@onflay/node/webhooks`, and `@onflay/webhooks/next`, `/express`, `/hono` → `@onflay/node/webhooks/next`, `/express`, `/hono`. `@onflay/webhooks` is deprecated; uninstall it.
|
|
19
|
+
- `@onflay/checkout-js` is renamed `@onflay/js` (same API, same `onflay.iife.js` CDN file). Update the import and any jsDelivr URL to `@onflay/js@<version>`.
|
|
20
|
+
- `@onflay/react` is retired. Use a button that posts to your own server route, which creates the checkout session with `@onflay/node`; `@onflay/js` opens it as an overlay.
|
|
21
|
+
- `onflay init` installs only `@onflay/node` and writes webhook handlers that import from `@onflay/node/webhooks/*`.
|
|
22
|
+
|
|
23
|
+
### Minor Changes
|
|
24
|
+
|
|
25
|
+
- 2e6c796: New webhook event types `catalog.product.updated` and `catalog.plan.updated` (`CatalogChangedEventData`: thin `{ productKey, planKey?, change, source }`; re-fetch the product). `onflay catalog apply` marks the products it writes as `managedBy: 'code'`, so the dashboard warns before edits the file would overwrite.
|
|
26
|
+
- 6ea8b41: **Breaking:** types follow the M3 public response shapes.
|
|
27
|
+
- `subscriptions.list`, `payments.list`, `customers.list` and `invoices.list` return `CursorList<T>` (`{ object: 'list', data, hasMore, nextCursor }`) and take `limit` (1–100) + `cursor`; `page` and `offset` are gone. New `invoices.listAll`.
|
|
28
|
+
- `OnflaySubscription` is `{ id, object, status, customer, product, plan, price, currentPeriodStart, currentPeriodEnd, cancelAtPeriodEnd, canceledAt, createdAt, updatedAt }`; statuses are lowercase. `SubscriptionCancellation.cancelAt` is now `canceledAt`.
|
|
29
|
+
- `OnflayPayment` is `{ id, object, status, amountInCents, currency, amountRefundedInCents, customer, product, plan, subscriptionId, createdAt }`.
|
|
30
|
+
- `OnflayCustomer` is `{ id, object, email, name, phone, externalCustomerId, createdAt }`; `externalCustomerId` is your app's id, not the Stripe customer id. Create/update take `name` and `phone`.
|
|
31
|
+
- `OnflayBillingInvoice.object` is `'invoice'` and `externalInvoiceId` is gone.
|
|
32
|
+
- `OnflayCheckoutSession` matches the create response (now with `id` and `object`); `checkoutSessions.retrieve` returns the new `OnflayCheckoutSessionDetails`.
|
|
33
|
+
|
|
34
|
+
- 3953321: M4 grants: typed methods for credits and license keys.
|
|
35
|
+
- Credits: `onflay.credits.retrieve({ externalCustomerId })`, `onflay.credits.listLedger(…)`, `onflay.credits.consume({ consumeCredits })` (402 `insufficient_credits` throws `ApiError`) and `onflay.credits.adjust(…)`, with the `CreditBalances`, `CreditOperation` and ledger types in `@onflay/node/models/components`.
|
|
36
|
+
- License keys: `onflay.licenseKeys.list`, `retrieve`, `revoke`, `validate`, `activate` and `deactivate`.
|
|
37
|
+
- Webhook event types `credits.granted` and `license_key.created` / `license_key.revoked` (never carries the key), and `catalog.product.updated` / `catalog.plan.updated`, live in `@onflay/node/webhooks`.
|
|
38
|
+
|
|
39
|
+
- b4dc802: **Breaking:** `products.list` and `prices.list` return `CursorList<T>` (`{ object: 'list', data, hasMore, nextCursor }`) like the other list methods; the `meta` block (`total`, `nextCursor`, `hasMore`) is gone. `cursor` is the opaque `nextCursor` of the previous page (no longer a page number). `prices.list` now pages by price: `limit` (1–100) counts prices, not products, and `productId` results are paginated too. `listAll` keeps working unchanged.
|
|
40
|
+
- 11dfd4a: Standard Webhooks support in `@onflay/node/webhooks`. `verifyWebhookSignature` now also accepts the request headers (`Headers` or a plain object) and tries Standard Webhooks (`webhook-id` / `webhook-timestamp` / `webhook-signature`) before falling back to the legacy `X-Onflay-Signature` header; the framework adapters do this automatically. New `verifyStandardWebhook` export for Standard-Webhooks-only verification. `onflay listen` now forwards both header sets.
|
|
41
|
+
|
|
42
|
+
### Patch Changes
|
|
43
|
+
|
|
44
|
+
- 11dfd4a: `onflay init` now scaffolds a catalog that passes `defineCatalog` (`nickname`/`amount`), a webhook route for the recommended `customer.access_changed` (plus subscription lifecycle) events, and `onflay:sync` / `onflay:listen` package.json scripts. The CLI reads `ONFLAY_SECRET_KEY`; `ONFLAY_API_KEY` still works but prints a deprecation warning. `onflay --version` and both SDK user agents now report the real package.json version. Removed `events show --verify`, which could not check anything because deliveries don't store the signature that was sent.
|
|
45
|
+
- 622ba2d: Expiring credits: each credit balance gains `expiresSoonest` and `expiringAmount` (the next expiry of the balance; `null` when nothing expires), and `balance` never includes expired credits. The ledger reason `expiry` is documented, and `refund` also covers a lost dispute. `onflay.credits.adjust` accepts `expiresInDays` (positive adjustments only).
|
|
46
|
+
- 6b26983: `OnflayError` exposes the API's new error guidance: `hint` (one sentence saying how to fix the request), `docUrl` (the error code's reference page) and `errors` (validation errors, one `{ field, code, message }` per invalid field, typed as `OnflayFieldError`). `OnflayErrorBody` documents the same envelope members. Classification and messages are unchanged.
|
|
47
|
+
- Staging snapshot.
|
|
48
|
+
|
|
49
|
+
## 0.3.1
|
|
50
|
+
|
|
51
|
+
### Patch Changes
|
|
52
|
+
|
|
53
|
+
- 99be218: Add overlay checkout (`onflay.js`): `uiMode: "embedded"` returns a signed `embedUrl`, and `@onflay/checkout-js` opens hosted checkout in a secure iframe overlay.
|
|
54
|
+
|
|
55
|
+
## 0.2.1
|
|
56
|
+
|
|
57
|
+
### Patch Changes
|
|
58
|
+
|
|
59
|
+
- Fix `CancelSubscriptionParams` field name: `atPeriodEnd` → `cancelAtPeriodEnd` to match the public API.
|
|
60
|
+
|
|
61
|
+
## 0.2.0
|
|
62
|
+
|
|
63
|
+
### Minor Changes
|
|
64
|
+
|
|
65
|
+
- Add `customPrice` override on `checkoutSessions.create` for per-session pricing (issue #196).
|
|
66
|
+
- `resolveBaseUrlFromKey` now respects `ONFLAY_API_BASE` from the environment.
|
|
67
|
+
- Fix `PaymentEventData` webhook types to match the real API payload (`transactionId`, `grossAmountInCents`, etc.).
|
|
68
|
+
- Append `request id` to `OnflayError.message` for easier log correlation.
|
|
69
|
+
|
|
70
|
+
## 0.1.1
|
|
71
|
+
|
|
72
|
+
### Patch Changes
|
|
73
|
+
|
|
74
|
+
- 4cfa3e8: Initial public npm release with automated Changesets publishing.
|
package/README.md
CHANGED
|
@@ -1,87 +1,250 @@
|
|
|
1
1
|
# @onflay/node
|
|
2
2
|
|
|
3
|
-
Official
|
|
4
|
-
|
|
3
|
+
Official TypeScript SDK for the [Onflay](https://onflay.com) API: checkout, catalog, customer
|
|
4
|
+
access, subscriptions, credits, license keys and more. Generated from the
|
|
5
|
+
[OpenAPI spec](https://docs.onflay.com/api-reference/introduction), so every endpoint has a typed
|
|
6
|
+
method.
|
|
7
|
+
|
|
8
|
+
- Node.js 20+, Bun, Deno, edge runtimes (uses the global `fetch`).
|
|
9
|
+
- ESM and CommonJS, with types.
|
|
10
|
+
- Retries with backoff (`429`, `5XX`, network errors; honours `Retry-After`).
|
|
11
|
+
- Auto-pagination, typed errors, `Date` objects for timestamps.
|
|
5
12
|
|
|
6
13
|
## Install
|
|
7
14
|
|
|
8
15
|
```bash
|
|
9
16
|
npm install @onflay/node
|
|
10
|
-
# or
|
|
11
|
-
pnpm add @onflay/node
|
|
12
17
|
```
|
|
13
18
|
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
## Usage
|
|
19
|
+
## Quickstart
|
|
17
20
|
|
|
18
21
|
```ts
|
|
19
22
|
import { Onflay } from '@onflay/node';
|
|
20
23
|
|
|
21
|
-
const onflay = new Onflay(
|
|
24
|
+
const onflay = new Onflay({
|
|
25
|
+
bearer: process.env['ONFLAY_SECRET_KEY'] ?? '', // sk_test_… or sk_live_…
|
|
26
|
+
});
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
With no `bearer`, the client reads `ONFLAY_BEARER`, then `ONFLAY_SECRET_KEY`, from the
|
|
30
|
+
environment. `sk_test_` / `pk_test_` keys go to the sandbox API unless you pick a server.
|
|
31
|
+
|
|
32
|
+
Methods follow the API's resources: `onflay.<resource>.<method>(request, options?)`. The request is
|
|
33
|
+
one object: path, query and header parameters by name, and the JSON body under the name of its
|
|
34
|
+
schema (`createCheckout`, `upsertCatalogProduct`, …). Operations that only take a body get
|
|
35
|
+
the body itself.
|
|
22
36
|
|
|
37
|
+
### Sell a plan by catalog key
|
|
38
|
+
|
|
39
|
+
```ts
|
|
23
40
|
const session = await onflay.checkoutSessions.create({
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
41
|
+
idempotencyKey: `checkout:${user.id}:acme-saas:pro:month`,
|
|
42
|
+
createCheckout: {
|
|
43
|
+
catalog: { product: 'acme-saas', plan: 'pro', interval: 'month' },
|
|
44
|
+
externalCustomerId: user.id,
|
|
45
|
+
email: user.email,
|
|
46
|
+
successUrl: 'https://your-app.com/thanks',
|
|
47
|
+
cancelUrl: 'https://your-app.com/pricing',
|
|
48
|
+
},
|
|
27
49
|
});
|
|
28
|
-
|
|
50
|
+
|
|
51
|
+
return Response.redirect(session.checkoutUrl, 303);
|
|
29
52
|
```
|
|
30
53
|
|
|
31
|
-
|
|
54
|
+
### Check what a customer has
|
|
32
55
|
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
56
|
+
```ts
|
|
57
|
+
const access = await onflay.customerAccess.retrieve({ externalCustomerId: user.id });
|
|
58
|
+
const isPro = access?.entitlements.some((e) => e.key === 'pro_features' && e.value === true);
|
|
59
|
+
```
|
|
37
60
|
|
|
38
|
-
|
|
61
|
+
### Manage the catalog by key
|
|
39
62
|
|
|
40
|
-
|
|
63
|
+
```ts
|
|
64
|
+
await onflay.catalog.products.upsert({
|
|
65
|
+
key: 'acme-saas',
|
|
66
|
+
upsertCatalogProduct: { name: 'Acme SaaS', type: 'subscription' },
|
|
67
|
+
});
|
|
41
68
|
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
- `onflay.checkoutSessions` — `create`, `retrieve`
|
|
45
|
-
- `onflay.payments` — `retrieve`, `list`, `listAll`
|
|
46
|
-
- `onflay.subscriptions` — `create`, `retrieve`, `update` (with proration), `cancel`, `list`
|
|
47
|
-
- `onflay.customers` — full CRUD
|
|
48
|
-
- `onflay.webhookEndpoints` — manage endpoints + browse `WebhookDelivery` history
|
|
69
|
+
const product = await onflay.catalog.products.retrieve({ key: 'acme-saas' });
|
|
70
|
+
```
|
|
49
71
|
|
|
50
|
-
##
|
|
72
|
+
## Pagination
|
|
51
73
|
|
|
52
|
-
|
|
53
|
-
|
|
74
|
+
List methods resolve to the first page, which is also an async iterable over every page
|
|
75
|
+
(following `nextCursor`):
|
|
54
76
|
|
|
55
77
|
```ts
|
|
56
|
-
await onflay.
|
|
78
|
+
const result = await onflay.customers.list({ limit: 100 });
|
|
79
|
+
console.log(result.result.data); // first page
|
|
80
|
+
|
|
81
|
+
for await (const page of result) {
|
|
82
|
+
for (const customer of page.result.data) {
|
|
83
|
+
console.log(customer.email);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const next = await result.next(); // null on the last page
|
|
57
88
|
```
|
|
58
89
|
|
|
59
90
|
## Errors
|
|
60
91
|
|
|
61
|
-
|
|
62
|
-
|
|
92
|
+
Every error response throws a subclass of `OnflayError` (`statusCode`, `body`, `headers`,
|
|
93
|
+
`rawResponse`). Responses in the Onflay error envelope throw `ApiError`:
|
|
63
94
|
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
95
|
+
```ts
|
|
96
|
+
import { OnflayError, ApiError } from '@onflay/node/models/errors';
|
|
97
|
+
|
|
98
|
+
try {
|
|
99
|
+
await onflay.customers.retrieve({ id: 'cus_missing' });
|
|
100
|
+
} catch (err) {
|
|
101
|
+
if (err instanceof ApiError) {
|
|
102
|
+
// The envelope: type, code, message, param, hint, docUrl, requestId, errors
|
|
103
|
+
console.log(err.statusCode, err.error.code, err.error.hint, err.error.docUrl, err.error.requestId);
|
|
104
|
+
} else if (err instanceof OnflayError) {
|
|
105
|
+
console.log(err.statusCode, err.body); // e.g. a 502 HTML page from a proxy
|
|
106
|
+
}
|
|
68
107
|
}
|
|
69
108
|
```
|
|
70
109
|
|
|
71
|
-
|
|
110
|
+
| Class | When |
|
|
111
|
+
|---|---|
|
|
112
|
+
| `ApiError` | A documented 4XX/5XX with the error envelope. `err.error` holds the envelope (also hoisted: `err.code`, `err.hint`, …). |
|
|
113
|
+
| `OnflayDefaultError` | Any other non-2XX response. |
|
|
114
|
+
| `ResponseValidationError` | A 2XX body that is not valid JSON. |
|
|
115
|
+
| `ConnectionError`, `RequestTimeoutError`, `RequestAbortedError`, `UnexpectedClientError` | No response (subclasses of `HTTPClientError`). |
|
|
116
|
+
| `SDKValidationError` | Invalid input, e.g. a missing path parameter. Nothing was sent. |
|
|
72
117
|
|
|
73
|
-
|
|
74
|
-
- `OnflayAuthenticationError` (401, 403)
|
|
75
|
-
- `OnflayInvalidRequestError` (400, 404, 422)
|
|
76
|
-
- `OnflayIdempotencyError` (409)
|
|
77
|
-
- `OnflayRateLimitError` (429, with `retryAfterSeconds`)
|
|
78
|
-
- `OnflayApiError` (5xx)
|
|
79
|
-
- `OnflayConnectionError` (network / timeout)
|
|
118
|
+
`code` matches a page under [Error codes](https://docs.onflay.com/errors/index).
|
|
80
119
|
|
|
81
|
-
##
|
|
120
|
+
## Retries
|
|
121
|
+
|
|
122
|
+
By default the SDK retries `429`, `5XX` and connection errors with exponential backoff
|
|
123
|
+
(500 ms initial interval, factor 1.5, 60 s max wait, 5 min total), waiting `Retry-After` when the
|
|
124
|
+
API sends it. Writes are safe to retry when you pass `idempotencyKey`.
|
|
82
125
|
|
|
83
126
|
```ts
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
}
|
|
127
|
+
// Per call
|
|
128
|
+
await onflay.customers.list(
|
|
129
|
+
{},
|
|
130
|
+
{
|
|
131
|
+
retries: {
|
|
132
|
+
strategy: 'backoff',
|
|
133
|
+
backoff: { initialInterval: 1, maxInterval: 50, exponent: 1.1, maxElapsedTime: 100 },
|
|
134
|
+
retryConnectionErrors: false,
|
|
135
|
+
},
|
|
136
|
+
retryCodes: ['429', '503'],
|
|
137
|
+
},
|
|
138
|
+
);
|
|
139
|
+
|
|
140
|
+
// Per client
|
|
141
|
+
const noRetries = new Onflay({ retryConfig: { strategy: 'none' } });
|
|
87
142
|
```
|
|
143
|
+
|
|
144
|
+
## Servers
|
|
145
|
+
|
|
146
|
+
| `server` | URL |
|
|
147
|
+
|---|---|
|
|
148
|
+
| `production` | `https://api.onflay.com` |
|
|
149
|
+
| `sandbox` | `https://sandbox-api.onflay.com` |
|
|
150
|
+
|
|
151
|
+
```ts
|
|
152
|
+
const sandbox = new Onflay({ server: 'sandbox' });
|
|
153
|
+
const local = new Onflay({ serverURL: 'http://localhost:3000' });
|
|
154
|
+
await onflay.customers.list({}, { serverURL: 'http://localhost:3010' }); // per call
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
## Options
|
|
158
|
+
|
|
159
|
+
| Option | Default | |
|
|
160
|
+
|---|---|---|
|
|
161
|
+
| `bearer` | `ONFLAY_BEARER` ?? `ONFLAY_SECRET_KEY` | Secret key, or an async function returning it. |
|
|
162
|
+
| `server` | from the key prefix | `'production'` or `'sandbox'`. |
|
|
163
|
+
| `serverURL` | | Overrides `server`. |
|
|
164
|
+
| `retryConfig` | from the spec | `{ strategy: 'none' }` disables retries. |
|
|
165
|
+
| `timeoutMs` | none | Per-attempt timeout. |
|
|
166
|
+
| `apiVersion` | the spec's version (`2026-01-01`) | `X-Onflay-Api-Version`; `null` omits it. |
|
|
167
|
+
| `httpClient` | | `new HTTPClient({ fetcher })` from `@onflay/node/lib/http`, with `beforeRequest`, `response` and `requestError` hooks. |
|
|
168
|
+
| `userAgent`, `debugLogger` | | `ONFLAY_DEBUG=true` logs requests to the console. |
|
|
169
|
+
|
|
170
|
+
Per-call options (last argument of every method): `retries`, `retryCodes`, `timeoutMs`,
|
|
171
|
+
`serverURL`, plus any `fetch` option (`headers`, `signal`, …).
|
|
172
|
+
|
|
173
|
+
## Webhooks
|
|
174
|
+
|
|
175
|
+
Webhook verification (Standard Webhooks, with the legacy `X-Onflay-Signature` fallback), the
|
|
176
|
+
event types and framework handlers ship in this package. Always pass the raw request body.
|
|
177
|
+
|
|
178
|
+
```ts
|
|
179
|
+
import { unwrap } from '@onflay/node/webhooks';
|
|
180
|
+
|
|
181
|
+
const event = unwrap(rawBody, request.headers, { secret: process.env['ONFLAY_WEBHOOK_SECRET']! });
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
| Entry point | Exports |
|
|
185
|
+
|---|---|
|
|
186
|
+
| `@onflay/node/webhooks` | `unwrap`, `verifyWebhookSignature`, `verifyStandardWebhook`, `OnflaySignatureError`, header constants, all handlers, event types (`OnflayEvent`, `ONFLAY_EVENT_TYPES`, …) |
|
|
187
|
+
| `@onflay/node/webhooks/next` | `createNextWebhookHandler`, `verifyNextWebhook` |
|
|
188
|
+
| `@onflay/node/webhooks/express` | `createExpressWebhookHandler`, `verifyExpressWebhook` |
|
|
189
|
+
| `@onflay/node/webhooks/hono` | `createHonoWebhookHandler`, `verifyHonoWebhook` |
|
|
190
|
+
|
|
191
|
+
```ts
|
|
192
|
+
// app/api/webhooks/onflay/route.ts
|
|
193
|
+
import { createNextWebhookHandler } from '@onflay/node/webhooks/next';
|
|
194
|
+
|
|
195
|
+
export const POST = createNextWebhookHandler({
|
|
196
|
+
secret: process.env['ONFLAY_WEBHOOK_SECRET']!,
|
|
197
|
+
onEvent: async (event) => {
|
|
198
|
+
if (event.type === 'customer.access_changed') {
|
|
199
|
+
// re-fetch customer access
|
|
200
|
+
}
|
|
201
|
+
},
|
|
202
|
+
});
|
|
203
|
+
```
|
|
204
|
+
|
|
205
|
+
These were the separate `@onflay/webhooks` package (0.2). The imports map one to one:
|
|
206
|
+
`@onflay/webhooks` → `@onflay/node/webhooks`, `@onflay/webhooks/next` → `@onflay/node/webhooks/next`,
|
|
207
|
+
and so on.
|
|
208
|
+
|
|
209
|
+
## Types
|
|
210
|
+
|
|
211
|
+
```ts
|
|
212
|
+
import type { Customer, CreateCheckout } from '@onflay/node/models/components';
|
|
213
|
+
import type { CustomersListRequest, CustomersListResponse } from '@onflay/node/models/operations';
|
|
214
|
+
import type { PageIterator } from '@onflay/node/types';
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
## Upgrading from 0.x
|
|
218
|
+
|
|
219
|
+
1.0 is a new, generated SDK. The main changes:
|
|
220
|
+
|
|
221
|
+
| 0.x | 1.x |
|
|
222
|
+
|---|---|
|
|
223
|
+
| `new Onflay(key, { baseUrl })` | `new Onflay({ bearer: key, serverURL })` |
|
|
224
|
+
| `onflay.customers.retrieve(id)` | `onflay.customers.retrieve({ id })` |
|
|
225
|
+
| `onflay.products.update(id, params, { idempotencyKey })` | `onflay.products.update({ id, idempotencyKey, updateProduct: params })` |
|
|
226
|
+
| `listAll()` / `.toArray()` | `for await (const page of await list())` |
|
|
227
|
+
| `onflay.client.request(...)` | a typed method for every endpoint |
|
|
228
|
+
| `OnflayInvalidRequestError`, `OnflayRateLimitError`, … | `ApiError` (`err.error.type`, `err.error.code`) |
|
|
229
|
+
| `maxRetries` | `retryConfig` |
|
|
230
|
+
| `@onflay/webhooks` (event types, verification, handlers) | `@onflay/node/webhooks` |
|
|
231
|
+
|
|
232
|
+
## Development
|
|
233
|
+
|
|
234
|
+
The SDK is generated: `src/generated/` comes from `apps/docs/api-reference/openapi.json`.
|
|
235
|
+
|
|
236
|
+
```bash
|
|
237
|
+
pnpm --filter @onflay/node generate # after `pnpm openapi:sync`
|
|
238
|
+
pnpm --filter @onflay/node generate:check # CI: fails when src/generated is stale
|
|
239
|
+
pnpm --filter @onflay/node test
|
|
240
|
+
```
|
|
241
|
+
|
|
242
|
+
- `openapi-ts.config.ts` runs [Hey API](https://heyapi.dev) for the types, one function per
|
|
243
|
+
operation and the fetch client.
|
|
244
|
+
- `scripts/generate.mjs` emits the resource classes from each operation's `x-speakeasy-group` /
|
|
245
|
+
`x-speakeasy-name-override`, plus request types, retries and pagination config.
|
|
246
|
+
- `src/lib` and `src/models/errors` are the hand-written runtime (retries, errors, pagination).
|
|
247
|
+
|
|
248
|
+
The public surface copies the conventions of [Speakeasy](https://www.speakeasy.com)-generated
|
|
249
|
+
TypeScript SDKs, so the generator can be swapped later. `test/contract.test.ts` is the usage
|
|
250
|
+
contract any generator must pass; see `sdks/README-generated.md`.
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import {
|
|
2
|
+
ConnectionError,
|
|
3
|
+
RequestTimeoutError
|
|
4
|
+
} from "./chunk-DBE2YZWE.mjs";
|
|
5
|
+
|
|
6
|
+
// src/lib/retries.ts
|
|
7
|
+
var defaultBackoff = {
|
|
8
|
+
initialInterval: 500,
|
|
9
|
+
maxInterval: 6e4,
|
|
10
|
+
exponent: 1.5,
|
|
11
|
+
maxElapsedTime: 36e5
|
|
12
|
+
};
|
|
13
|
+
var PermanentError = class extends Error {
|
|
14
|
+
constructor(message, inner) {
|
|
15
|
+
super(message);
|
|
16
|
+
this.inner = inner;
|
|
17
|
+
this.name = "PermanentError";
|
|
18
|
+
}
|
|
19
|
+
inner;
|
|
20
|
+
};
|
|
21
|
+
var TemporaryError = class extends Error {
|
|
22
|
+
constructor(message, response) {
|
|
23
|
+
super(message);
|
|
24
|
+
this.response = response;
|
|
25
|
+
this.name = "TemporaryError";
|
|
26
|
+
}
|
|
27
|
+
response;
|
|
28
|
+
};
|
|
29
|
+
async function retry(fetchFn, options) {
|
|
30
|
+
switch (options.config.strategy) {
|
|
31
|
+
case "backoff":
|
|
32
|
+
return retryBackoff(
|
|
33
|
+
wrapFetcher(fetchFn, {
|
|
34
|
+
statusCodes: options.statusCodes,
|
|
35
|
+
retryConnectionErrors: !!options.config.retryConnectionErrors
|
|
36
|
+
}),
|
|
37
|
+
options.config.backoff ?? defaultBackoff
|
|
38
|
+
);
|
|
39
|
+
default:
|
|
40
|
+
return await fetchFn();
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
function wrapFetcher(fn, options) {
|
|
44
|
+
return async () => {
|
|
45
|
+
try {
|
|
46
|
+
const res = await fn();
|
|
47
|
+
if (isRetryableResponse(res, options.statusCodes)) {
|
|
48
|
+
throw new TemporaryError("Response failed with retryable status code", res);
|
|
49
|
+
}
|
|
50
|
+
return res;
|
|
51
|
+
} catch (err) {
|
|
52
|
+
if (err instanceof TemporaryError) throw err;
|
|
53
|
+
if (options.retryConnectionErrors && isRetryableNetworkError(err)) throw err;
|
|
54
|
+
throw new PermanentError("Permanent error", err);
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
function isRetryableNetworkError(err) {
|
|
59
|
+
return err instanceof ConnectionError || err instanceof RequestTimeoutError;
|
|
60
|
+
}
|
|
61
|
+
var codeRangeRE = /^[0-9]xx$/i;
|
|
62
|
+
function isRetryableResponse(res, statusCodes) {
|
|
63
|
+
const actual = `${res.status}`;
|
|
64
|
+
return statusCodes.some((code) => {
|
|
65
|
+
if (!codeRangeRE.test(code)) return code === actual;
|
|
66
|
+
const expectFamily = code.charAt(0);
|
|
67
|
+
if (!expectFamily) throw new Error("Invalid status code range");
|
|
68
|
+
const actualFamily = actual.charAt(0);
|
|
69
|
+
if (!actualFamily) throw new Error(`Invalid response status code: ${actual}`);
|
|
70
|
+
return actualFamily === expectFamily;
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
async function retryBackoff(fn, strategy) {
|
|
74
|
+
const { maxElapsedTime, initialInterval, exponent, maxInterval } = strategy;
|
|
75
|
+
const start = Date.now();
|
|
76
|
+
let x = 0;
|
|
77
|
+
while (true) {
|
|
78
|
+
try {
|
|
79
|
+
return await fn();
|
|
80
|
+
} catch (err) {
|
|
81
|
+
if (err instanceof PermanentError) throw err.inner;
|
|
82
|
+
const elapsed = Date.now() - start;
|
|
83
|
+
if (elapsed > maxElapsedTime) {
|
|
84
|
+
if (err instanceof TemporaryError) return err.response;
|
|
85
|
+
throw err;
|
|
86
|
+
}
|
|
87
|
+
let retryInterval = 0;
|
|
88
|
+
if (err instanceof TemporaryError) retryInterval = retryIntervalFromResponse(err.response);
|
|
89
|
+
if (retryInterval <= 0) {
|
|
90
|
+
retryInterval = initialInterval * Math.pow(x, exponent) + Math.random() * 1e3;
|
|
91
|
+
}
|
|
92
|
+
const d = Math.min(retryInterval, maxInterval);
|
|
93
|
+
await delay(d);
|
|
94
|
+
x++;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
function retryIntervalFromResponse(res) {
|
|
99
|
+
const retryVal = res.headers.get("retry-after") || "";
|
|
100
|
+
if (!retryVal) return 0;
|
|
101
|
+
const parsedNumber = Number(retryVal);
|
|
102
|
+
if (Number.isInteger(parsedNumber)) return parsedNumber * 1e3;
|
|
103
|
+
const parsedDate = Date.parse(retryVal);
|
|
104
|
+
if (Number.isInteger(parsedDate)) {
|
|
105
|
+
const deltaMS = parsedDate - Date.now();
|
|
106
|
+
return deltaMS > 0 ? Math.ceil(deltaMS) : 0;
|
|
107
|
+
}
|
|
108
|
+
return 0;
|
|
109
|
+
}
|
|
110
|
+
async function delay(delay2) {
|
|
111
|
+
return new Promise((resolve) => setTimeout(resolve, delay2));
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export {
|
|
115
|
+
PermanentError,
|
|
116
|
+
TemporaryError,
|
|
117
|
+
retry,
|
|
118
|
+
isRetryableResponse,
|
|
119
|
+
retryIntervalFromResponse
|
|
120
|
+
};
|
|
121
|
+
//# sourceMappingURL=chunk-4RUPPDC2.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/lib/retries.ts"],"sourcesContent":["/**\n * Retry configuration, shaped like Speakeasy's. The default comes from the spec's\n * `x-speakeasy-retries` (exponential backoff on 429 / 5XX and connection errors, honouring\n * `Retry-After`); override it per client (`retryConfig`) or per call (`{ retries }`).\n */\n\nimport { ConnectionError, RequestTimeoutError } from '../models/errors/httpclienterrors';\n\nexport type BackoffStrategy = {\n /** First wait, in ms. */\n initialInterval: number;\n /** Cap for a single wait, in ms (also caps `Retry-After`). */\n maxInterval: number;\n /** Growth factor of the wait between attempts. */\n exponent: number;\n /** Stop retrying once this many ms have passed since the first attempt. */\n maxElapsedTime: number;\n};\n\nconst defaultBackoff: BackoffStrategy = {\n initialInterval: 500,\n maxInterval: 60000,\n exponent: 1.5,\n maxElapsedTime: 3600000,\n};\n\nexport type RetryConfig =\n | { strategy: 'none' }\n | {\n strategy: 'backoff';\n backoff?: BackoffStrategy;\n retryConnectionErrors?: boolean;\n };\n\n/** Thrown inside the retry loop: stop retrying and surface `cause`. */\nexport class PermanentError extends Error {\n constructor(\n message: string,\n public readonly inner: unknown,\n ) {\n super(message);\n this.name = 'PermanentError';\n }\n}\n\n/** Thrown inside the retry loop: retry with this response unless the budget is spent. */\nexport class TemporaryError extends Error {\n constructor(\n message: string,\n public readonly response: Response,\n ) {\n super(message);\n this.name = 'TemporaryError';\n }\n}\n\nexport async function retry(\n fetchFn: () => Promise<Response>,\n options: { config: RetryConfig; statusCodes: string[] },\n): Promise<Response> {\n switch (options.config.strategy) {\n case 'backoff':\n return retryBackoff(\n wrapFetcher(fetchFn, {\n statusCodes: options.statusCodes,\n retryConnectionErrors: !!options.config.retryConnectionErrors,\n }),\n options.config.backoff ?? defaultBackoff,\n );\n default:\n return await fetchFn();\n }\n}\n\nfunction wrapFetcher(\n fn: () => Promise<Response>,\n options: { statusCodes: string[]; retryConnectionErrors: boolean },\n): () => Promise<Response> {\n return async () => {\n try {\n const res = await fn();\n if (isRetryableResponse(res, options.statusCodes)) {\n throw new TemporaryError('Response failed with retryable status code', res);\n }\n return res;\n } catch (err: unknown) {\n if (err instanceof TemporaryError) throw err;\n if (options.retryConnectionErrors && isRetryableNetworkError(err)) throw err;\n throw new PermanentError('Permanent error', err);\n }\n };\n}\n\nfunction isRetryableNetworkError(err: unknown): boolean {\n return err instanceof ConnectionError || err instanceof RequestTimeoutError;\n}\n\nconst codeRangeRE = /^[0-9]xx$/i;\n\nexport function isRetryableResponse(res: Response, statusCodes: string[]): boolean {\n const actual = `${res.status}`;\n return statusCodes.some((code) => {\n if (!codeRangeRE.test(code)) return code === actual;\n const expectFamily = code.charAt(0);\n if (!expectFamily) throw new Error('Invalid status code range');\n const actualFamily = actual.charAt(0);\n if (!actualFamily) throw new Error(`Invalid response status code: ${actual}`);\n return actualFamily === expectFamily;\n });\n}\n\nasync function retryBackoff(fn: () => Promise<Response>, strategy: BackoffStrategy): Promise<Response> {\n const { maxElapsedTime, initialInterval, exponent, maxInterval } = strategy;\n const start = Date.now();\n let x = 0;\n\n while (true) {\n try {\n return await fn();\n } catch (err: unknown) {\n if (err instanceof PermanentError) throw err.inner;\n const elapsed = Date.now() - start;\n if (elapsed > maxElapsedTime) {\n if (err instanceof TemporaryError) return err.response;\n throw err;\n }\n\n let retryInterval = 0;\n if (err instanceof TemporaryError) retryInterval = retryIntervalFromResponse(err.response);\n if (retryInterval <= 0) {\n retryInterval = initialInterval * Math.pow(x, exponent) + Math.random() * 1000;\n }\n const d = Math.min(retryInterval, maxInterval);\n await delay(d);\n x++;\n }\n }\n}\n\n/** `Retry-After` as delay-seconds or an HTTP date, in ms (0 when absent or invalid). */\nexport function retryIntervalFromResponse(res: Response): number {\n const retryVal = res.headers.get('retry-after') || '';\n if (!retryVal) return 0;\n const parsedNumber = Number(retryVal);\n if (Number.isInteger(parsedNumber)) return parsedNumber * 1000;\n const parsedDate = Date.parse(retryVal);\n if (Number.isInteger(parsedDate)) {\n const deltaMS = parsedDate - Date.now();\n return deltaMS > 0 ? Math.ceil(deltaMS) : 0;\n }\n return 0;\n}\n\nasync function delay(delay: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, delay));\n}\n"],"mappings":";;;;;;AAmBA,IAAM,iBAAkC;AAAA,EACtC,iBAAiB;AAAA,EACjB,aAAa;AAAA,EACb,UAAU;AAAA,EACV,gBAAgB;AAClB;AAWO,IAAM,iBAAN,cAA6B,MAAM;AAAA,EACxC,YACE,SACgB,OAChB;AACA,UAAM,OAAO;AAFG;AAGhB,SAAK,OAAO;AAAA,EACd;AAAA,EAJkB;AAKpB;AAGO,IAAM,iBAAN,cAA6B,MAAM;AAAA,EACxC,YACE,SACgB,UAChB;AACA,UAAM,OAAO;AAFG;AAGhB,SAAK,OAAO;AAAA,EACd;AAAA,EAJkB;AAKpB;AAEA,eAAsB,MACpB,SACA,SACmB;AACnB,UAAQ,QAAQ,OAAO,UAAU;AAAA,IAC/B,KAAK;AACH,aAAO;AAAA,QACL,YAAY,SAAS;AAAA,UACnB,aAAa,QAAQ;AAAA,UACrB,uBAAuB,CAAC,CAAC,QAAQ,OAAO;AAAA,QAC1C,CAAC;AAAA,QACD,QAAQ,OAAO,WAAW;AAAA,MAC5B;AAAA,IACF;AACE,aAAO,MAAM,QAAQ;AAAA,EACzB;AACF;AAEA,SAAS,YACP,IACA,SACyB;AACzB,SAAO,YAAY;AACjB,QAAI;AACF,YAAM,MAAM,MAAM,GAAG;AACrB,UAAI,oBAAoB,KAAK,QAAQ,WAAW,GAAG;AACjD,cAAM,IAAI,eAAe,8CAA8C,GAAG;AAAA,MAC5E;AACA,aAAO;AAAA,IACT,SAAS,KAAc;AACrB,UAAI,eAAe,eAAgB,OAAM;AACzC,UAAI,QAAQ,yBAAyB,wBAAwB,GAAG,EAAG,OAAM;AACzE,YAAM,IAAI,eAAe,mBAAmB,GAAG;AAAA,IACjD;AAAA,EACF;AACF;AAEA,SAAS,wBAAwB,KAAuB;AACtD,SAAO,eAAe,mBAAmB,eAAe;AAC1D;AAEA,IAAM,cAAc;AAEb,SAAS,oBAAoB,KAAe,aAAgC;AACjF,QAAM,SAAS,GAAG,IAAI,MAAM;AAC5B,SAAO,YAAY,KAAK,CAAC,SAAS;AAChC,QAAI,CAAC,YAAY,KAAK,IAAI,EAAG,QAAO,SAAS;AAC7C,UAAM,eAAe,KAAK,OAAO,CAAC;AAClC,QAAI,CAAC,aAAc,OAAM,IAAI,MAAM,2BAA2B;AAC9D,UAAM,eAAe,OAAO,OAAO,CAAC;AACpC,QAAI,CAAC,aAAc,OAAM,IAAI,MAAM,iCAAiC,MAAM,EAAE;AAC5E,WAAO,iBAAiB;AAAA,EAC1B,CAAC;AACH;AAEA,eAAe,aAAa,IAA6B,UAA8C;AACrG,QAAM,EAAE,gBAAgB,iBAAiB,UAAU,YAAY,IAAI;AACnE,QAAM,QAAQ,KAAK,IAAI;AACvB,MAAI,IAAI;AAER,SAAO,MAAM;AACX,QAAI;AACF,aAAO,MAAM,GAAG;AAAA,IAClB,SAAS,KAAc;AACrB,UAAI,eAAe,eAAgB,OAAM,IAAI;AAC7C,YAAM,UAAU,KAAK,IAAI,IAAI;AAC7B,UAAI,UAAU,gBAAgB;AAC5B,YAAI,eAAe,eAAgB,QAAO,IAAI;AAC9C,cAAM;AAAA,MACR;AAEA,UAAI,gBAAgB;AACpB,UAAI,eAAe,eAAgB,iBAAgB,0BAA0B,IAAI,QAAQ;AACzF,UAAI,iBAAiB,GAAG;AACtB,wBAAgB,kBAAkB,KAAK,IAAI,GAAG,QAAQ,IAAI,KAAK,OAAO,IAAI;AAAA,MAC5E;AACA,YAAM,IAAI,KAAK,IAAI,eAAe,WAAW;AAC7C,YAAM,MAAM,CAAC;AACb;AAAA,IACF;AAAA,EACF;AACF;AAGO,SAAS,0BAA0B,KAAuB;AAC/D,QAAM,WAAW,IAAI,QAAQ,IAAI,aAAa,KAAK;AACnD,MAAI,CAAC,SAAU,QAAO;AACtB,QAAM,eAAe,OAAO,QAAQ;AACpC,MAAI,OAAO,UAAU,YAAY,EAAG,QAAO,eAAe;AAC1D,QAAM,aAAa,KAAK,MAAM,QAAQ;AACtC,MAAI,OAAO,UAAU,UAAU,GAAG;AAChC,UAAM,UAAU,aAAa,KAAK,IAAI;AACtC,WAAO,UAAU,IAAI,KAAK,KAAK,OAAO,IAAI;AAAA,EAC5C;AACA,SAAO;AACT;AAEA,eAAe,MAAMA,QAA8B;AACjD,SAAO,IAAI,QAAQ,CAAC,YAAY,WAAW,SAASA,MAAK,CAAC;AAC5D;","names":["delay"]}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import {
|
|
2
|
+
OnflaySignatureError,
|
|
3
|
+
verifyWebhookSignature
|
|
4
|
+
} from "./chunk-7LYAEZCT.mjs";
|
|
5
|
+
|
|
6
|
+
// src/webhooks/adapters/express.ts
|
|
7
|
+
function verifyExpressWebhook(req, options) {
|
|
8
|
+
const raw = readRawBody(req);
|
|
9
|
+
return verifyWebhookSignature(raw, req.headers, options);
|
|
10
|
+
}
|
|
11
|
+
function createExpressWebhookHandler(opts) {
|
|
12
|
+
return async function onflayWebhookHandler(req, res, next) {
|
|
13
|
+
try {
|
|
14
|
+
const verified = verifyExpressWebhook(req, opts);
|
|
15
|
+
await opts.onEvent(verified.event, verified);
|
|
16
|
+
res.status(200).send("ok");
|
|
17
|
+
} catch (err) {
|
|
18
|
+
opts.onError?.(err);
|
|
19
|
+
if (err instanceof OnflaySignatureError) {
|
|
20
|
+
res.status(400).json({ error: { type: "invalid_request", code: err.code, message: err.message } });
|
|
21
|
+
return;
|
|
22
|
+
}
|
|
23
|
+
if (next) {
|
|
24
|
+
next(err);
|
|
25
|
+
return;
|
|
26
|
+
}
|
|
27
|
+
res.status(500).json({ error: { type: "api_error", code: "handler_failed" } });
|
|
28
|
+
}
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
function readRawBody(req) {
|
|
32
|
+
if (req.rawBody) {
|
|
33
|
+
return typeof req.rawBody === "string" ? req.rawBody : req.rawBody.toString("utf8");
|
|
34
|
+
}
|
|
35
|
+
if (Buffer.isBuffer(req.body)) return req.body.toString("utf8");
|
|
36
|
+
if (typeof req.body === "string") return req.body;
|
|
37
|
+
throw new OnflaySignatureError(
|
|
38
|
+
"missing_payload",
|
|
39
|
+
'Express adapter requires the raw request body. Mount with `express.raw({ type: "*" })` ahead of the handler.'
|
|
40
|
+
);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export {
|
|
44
|
+
verifyExpressWebhook,
|
|
45
|
+
createExpressWebhookHandler
|
|
46
|
+
};
|
|
47
|
+
//# sourceMappingURL=chunk-63KSRMJG.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/webhooks/adapters/express.ts"],"sourcesContent":["import type { OnflayEvent } from '../events';\nimport {\n OnflaySignatureError,\n verifyWebhookSignature,\n type VerifiedWebhook,\n type VerifyWebhookOptions,\n} from '../verify';\n\ninterface ExpressLikeRequest {\n headers: Record<string, string | string[] | undefined>;\n body: unknown;\n rawBody?: Buffer | string;\n}\n\ninterface ExpressLikeResponse {\n status(code: number): ExpressLikeResponse;\n send(body?: unknown): unknown;\n json(body: unknown): unknown;\n}\n\ntype NextFn = (err?: unknown) => void;\n\n/**\n * Verify the signature of an inbound Express request whose body has been\n * captured raw. Configure your route with `express.raw({ type: '*' })`\n * (or equivalent) so the request body remains a `Buffer`. Re-parsing\n * after `express.json()` will break the HMAC.\n */\nexport function verifyExpressWebhook<TEvent = OnflayEvent>(\n req: ExpressLikeRequest,\n options: VerifyWebhookOptions,\n): VerifiedWebhook<TEvent> {\n const raw = readRawBody(req);\n // Header lookup is case-insensitive; Standard Webhooks is tried first,\n // then the legacy X-Onflay-Signature header.\n return verifyWebhookSignature<TEvent>(raw, req.headers, options);\n}\n\ninterface ExpressHandlerOptions extends VerifyWebhookOptions {\n /** Called after successful verification with the parsed event. */\n onEvent: (event: OnflayEvent, raw: VerifiedWebhook<OnflayEvent>) => unknown | Promise<unknown>;\n /** Optional logger override; defaults to no-op. */\n onError?: (error: OnflaySignatureError | Error) => void;\n}\n\n/**\n * Higher-level helper that returns a ready-to-mount Express middleware:\n *\n * ```ts\n * app.post('/webhooks/onflay',\n * express.raw({ type: 'application/json' }),\n * createExpressWebhookHandler({ secret, onEvent: async (e) => {} }),\n * );\n * ```\n */\nexport function createExpressWebhookHandler(opts: ExpressHandlerOptions) {\n return async function onflayWebhookHandler(\n req: ExpressLikeRequest,\n res: ExpressLikeResponse,\n next?: NextFn,\n ): Promise<void> {\n try {\n const verified = verifyExpressWebhook<OnflayEvent>(req, opts);\n await opts.onEvent(verified.event, verified);\n res.status(200).send('ok');\n } catch (err) {\n opts.onError?.(err as Error);\n if (err instanceof OnflaySignatureError) {\n res.status(400).json({ error: { type: 'invalid_request', code: err.code, message: err.message } });\n return;\n }\n if (next) {\n next(err);\n return;\n }\n res.status(500).json({ error: { type: 'api_error', code: 'handler_failed' } });\n }\n };\n}\n\nfunction readRawBody(req: ExpressLikeRequest): string {\n if (req.rawBody) {\n return typeof req.rawBody === 'string' ? req.rawBody : req.rawBody.toString('utf8');\n }\n if (Buffer.isBuffer(req.body)) return req.body.toString('utf8');\n if (typeof req.body === 'string') return req.body;\n throw new OnflaySignatureError(\n 'missing_payload',\n 'Express adapter requires the raw request body. Mount with `express.raw({ type: \"*\" })` ahead of the handler.',\n );\n}\n"],"mappings":";;;;;;AA4BO,SAAS,qBACd,KACA,SACyB;AACzB,QAAM,MAAM,YAAY,GAAG;AAG3B,SAAO,uBAA+B,KAAK,IAAI,SAAS,OAAO;AACjE;AAmBO,SAAS,4BAA4B,MAA6B;AACvE,SAAO,eAAe,qBACpB,KACA,KACA,MACe;AACf,QAAI;AACF,YAAM,WAAW,qBAAkC,KAAK,IAAI;AAC5D,YAAM,KAAK,QAAQ,SAAS,OAAO,QAAQ;AAC3C,UAAI,OAAO,GAAG,EAAE,KAAK,IAAI;AAAA,IAC3B,SAAS,KAAK;AACZ,WAAK,UAAU,GAAY;AAC3B,UAAI,eAAe,sBAAsB;AACvC,YAAI,OAAO,GAAG,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,mBAAmB,MAAM,IAAI,MAAM,SAAS,IAAI,QAAQ,EAAE,CAAC;AACjG;AAAA,MACF;AACA,UAAI,MAAM;AACR,aAAK,GAAG;AACR;AAAA,MACF;AACA,UAAI,OAAO,GAAG,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,aAAa,MAAM,iBAAiB,EAAE,CAAC;AAAA,IAC/E;AAAA,EACF;AACF;AAEA,SAAS,YAAY,KAAiC;AACpD,MAAI,IAAI,SAAS;AACf,WAAO,OAAO,IAAI,YAAY,WAAW,IAAI,UAAU,IAAI,QAAQ,SAAS,MAAM;AAAA,EACpF;AACA,MAAI,OAAO,SAAS,IAAI,IAAI,EAAG,QAAO,IAAI,KAAK,SAAS,MAAM;AAC9D,MAAI,OAAO,IAAI,SAAS,SAAU,QAAO,IAAI;AAC7C,QAAM,IAAI;AAAA,IACR;AAAA,IACA;AAAA,EACF;AACF;","names":[]}
|