@vvedantb/server 0.10.0 → 0.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +79 -0
- package/README.md +14 -6
- package/dist/ai/cost.d.ts +17 -0
- package/dist/ai/cost.js +20 -0
- package/dist/ai/errors.d.ts +35 -0
- package/dist/ai/errors.js +84 -0
- package/dist/ai/index.d.ts +3 -0
- package/dist/ai/index.js +3 -0
- package/dist/ai/serviceTier.d.ts +55 -0
- package/dist/ai/serviceTier.js +29 -0
- package/dist/convex/clerkBilling.d.ts +89 -0
- package/dist/convex/clerkBilling.js +130 -0
- package/dist/convex/clerkWebhook.d.ts +31 -0
- package/dist/convex/clerkWebhook.js +26 -0
- package/dist/convex/index.d.ts +4 -1
- package/dist/convex/index.js +4 -1
- package/dist/convex/vPlan.d.ts +22 -0
- package/dist/convex/vPlan.js +33 -0
- package/dist/convex/vProModule.d.ts +109 -0
- package/dist/convex/vProModule.js +87 -0
- package/docs/ai.md +135 -0
- package/docs/convex.md +225 -1
- package/package.json +17 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,84 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.12.0
|
|
4
|
+
|
|
5
|
+
Shared V Pro checks and Clerk Billing webhook helpers, so apps stop keeping their own copies, with config options so apps whose webhook copies differ from the defaults can adopt them with no change users can see. Additive; nothing in 0.11.0 changes. No new dependency: `@clerk/backend` stays an optional peer and is never imported. (These helpers were first drafted as 0.11.0; 0.11.0 shipped the AI Gateway helpers instead.)
|
|
6
|
+
|
|
7
|
+
### Added
|
|
8
|
+
|
|
9
|
+
- `hasVPro({ identity, planSlugs, compIds, clerkId })`: true when `hasVPlan(identity)` is true, a stored slug is in `V_PRO_PLAN_KEYS`, or the Clerk id (`clerkId`, else `identity.subject`) is in `compIds`. Missing or malformed fields count as no plan; it never throws. Reads no env.
|
|
10
|
+
- `parseVProCompUserIds(value)`: a comma-separated id list (for example `V_PRO_COMP_USER_IDS`), trimmed, empty ids dropped.
|
|
11
|
+
- `verifyClerkWebhook(verifyWebhook, request, options?)`: verifies a Clerk (Svix) webhook with an injected `verifyWebhook` from `@clerk/backend/webhooks`. The secret is `options.signingSecret`, else `CLERK_WEBHOOK_SIGNING_SECRET` from `options.env` (default `process.env`). Returns `{ ok: true, event }` or `{ ok: false, reason: "missing-secret" | "invalid", error }`; never throws. Map both failures to HTTP 400.
|
|
12
|
+
- `parseClerkBillingEvent(event)`: `subscription.created`, `.updated`, `.active` and `.pastDue` give `{ kind: "replace", clerkId, planSlugs }`. `subscriptionItem.updated`, `.active`, `.canceled`, `.ended`, `.abandoned`, `.incomplete` and `.pastDue` give `{ kind: "item", clerkId, status, slug }`. Returns `null` for other events, a payer with no `user_id` (an organisation), and malformed data, including a subscription event with no `items` array.
|
|
13
|
+
- `applyBillingChange(current, change)`, `applyItemToPlanSlugs(current, item)`, `activePlanSlugs(items)`, `itemGrantsPlan(item)` and `GRANTING_ITEM_STATUSES` (`active`, `past_due`, `canceled`). `canceled` still grants until the item ends. Billing period fields are not read, so monthly and yearly items of one plan store the same slug.
|
|
14
|
+
- `createVProModule<DataModel>()({ table, index, clerkIdField, planSlugsField, lookup? })`: `writeBillingChange(ctx, change)` (looks up the row and patches the slugs field; `false` with no write when there is no row), `nextPlanSlugs`, `planSlugsOf`, `planSlugsPatch` and `userHasVPro`. `planSlugsField` is configurable (for example `planSlugs` or `billingPlanSlugs`), so no data migration. Typed structurally; a Convex `MutationCtx` fits without a cast.
|
|
15
|
+
- Types `ClerkBillingChange`, `ClerkWebhookEventLike`, `PlanItem`, `HasVProInput`, `ClerkWebhookEnv`, `ClerkWebhookRejection`, `VerifyClerkWebhookOptions`, `VerifyClerkWebhookResult`, `UserHasVProOptions`, `VProModuleConfig`, `VProPlanSlugsFieldOf`, `VProWriterCtx`.
|
|
16
|
+
|
|
17
|
+
### Added: config options
|
|
18
|
+
|
|
19
|
+
Every option is optional and defaults to the behaviour above.
|
|
20
|
+
|
|
21
|
+
- `ClerkBillingOptions` (`grantingStatuses?`, `eventMatch?`) as an optional last argument to `itemGrantsPlan`, `activePlanSlugs`, `applyItemToPlanSlugs`, `applyBillingChange` and `parseClerkBillingEvent`.
|
|
22
|
+
- `grantingStatuses`: the item statuses that grant. Default `GRANTING_ITEM_STATUSES` (`active`, `past_due`, `canceled`).
|
|
23
|
+
- `eventMatch`: `"exact"` (default, the listed event types) or `"prefix"` (any `subscription.*` type gives `replace`, any `subscriptionItem.*` type gives `item`). Read only by `parseClerkBillingEvent`.
|
|
24
|
+
- `GRANTING_STATUSES_ACTIVE_PAST_DUE` (`active`, `past_due`) and `GRANTING_STATUSES_ACTIVE_ONLY` (`active`) presets.
|
|
25
|
+
- `createVProModule` config:
|
|
26
|
+
- `grantingStatuses` and `eventMatch`, used by `nextPlanSlugs`, `writeBillingChange` and the new `parseBillingEvent`.
|
|
27
|
+
- `createUser(ctx, { clerkId, planSlugs })`: called by `writeBillingChange` when there is no row, which then returns `true`. The app supplies every other field; the package invents none. `ctx.db.insert` is typed against the table.
|
|
28
|
+
- `onMissingUser`: `"noop"` (default) or `"create"` (implied by `createUser`). `"create"` without `createUser` is a type error and throws at configure time.
|
|
29
|
+
- `extraPatch(planSlugs)`: fields merged into the `writeBillingChange` patch of an existing row, typed as `Partial` of the document. The slugs field always wins.
|
|
30
|
+
- `vPro.parseBillingEvent(event)`: `parseClerkBillingEvent` with the module's `grantingStatuses` and `eventMatch`, so the parser and the writer cannot disagree.
|
|
31
|
+
- Types `ClerkBillingOptions`, `VProCreateUser`, `VProCreateUserCtx`. `VProModuleConfig` takes an optional fifth `Doc` type argument. `VProWriterCtx` gains an optional `db.insert`, which a `MutationCtx` has.
|
|
32
|
+
|
|
33
|
+
### Renamed from the app copies
|
|
34
|
+
|
|
35
|
+
- `planSlugsFromItems` is `activePlanSlugs`. `userHasVPlan(user, env)` is `hasVPro` (or `vPro.userHasVPro`) with an explicit `compIds`. `identityHasVPlan` is `hasVPlan`. The replace and apply-item writers are one `writeBillingChange`.
|
|
36
|
+
|
|
37
|
+
### Known limit
|
|
38
|
+
|
|
39
|
+
- An item event knows only its own item. When two items share a slug (for example a monthly and a yearly item of one plan), an item event with a non-granting status for one of them (`ended`, `upcoming`, `abandoned`, `incomplete`) removes the slug while the other still grants. The next subscription event or a backfill restores it. The app copy these helpers came from behaves the same.
|
|
40
|
+
|
|
41
|
+
### Unchanged
|
|
42
|
+
|
|
43
|
+
- Stored slugs stay unique and sorted. Apps that stored them unsorted get the same members in a different order.
|
|
44
|
+
- Webhook runtime (V8 or Node), the HTTP status for a missing secret, refetching the subscription on each event, custom JWT plan claims and backfill paging stay in the apps. See `docs/convex.md`.
|
|
45
|
+
|
|
46
|
+
### Tests
|
|
47
|
+
|
|
48
|
+
- `tests/convex/clerkBilling.test.ts`: every handled event type, granting and removing statuses, monthly against yearly items, free plan and empty items, organisation payers, ignored and malformed events, and out-of-order event sequences.
|
|
49
|
+
- `tests/convex/clerkWebhook.test.ts`: secret from options, env and `process.env`; missing and empty secrets; `verifyWebhook` rejecting, throwing synchronously and throwing a non-`Error`.
|
|
50
|
+
- `tests/convex/vProModule.test.ts` and `tests/convex/vProModule.types.ts`: `planSlugs` against `billingPlanSlugs`, missing rows, `lookup`, `userHasVPro`, a webhook handler built from the helpers, and real Convex ctx and validator types.
|
|
51
|
+
- `tests/convex/vPlan.test.ts`: `hasVPro` and `parseVProCompUserIds`. `tests-node/esm-exports.mjs` checks the new exports with no peer installed; `tests-node/bundle.mjs` bundles the webhook helpers for Convex V8.
|
|
52
|
+
- `tests/convex/clerkBilling.test.ts`: each `grantingStatuses` preset across every helper, `eventMatch` exact against prefix, and prefix giving the same change as exact for every listed type.
|
|
53
|
+
- `tests/convex/vProModule.test.ts`: module `grantingStatuses`, `parseBillingEvent`, `extraPatch`, `createUser` (insert, then patch), `onMissingUser` and a ctx with no `insert`. `tests/convex/vProModule.types.ts`: `createUser` and `extraPatch` against a real Convex schema, and rejected configs.
|
|
54
|
+
- `tests-node/esm-exports.mjs` and `tests-node/bundle.mjs`: the presets and options with no peer installed and in a Convex V8 bundle.
|
|
55
|
+
|
|
56
|
+
## 0.11.0
|
|
57
|
+
|
|
58
|
+
Additive: Vercel AI Gateway helpers on a new subpath, `@vvedantb/server/ai`, taken from three apps' local copies. The root is unchanged and does not re-export them. No new dependency: `ai` (`>=5`) and `@ai-sdk/gateway` (`>=1`) are new optional peers, needed only by the subpath. See `docs/ai.md`.
|
|
59
|
+
|
|
60
|
+
### Added
|
|
61
|
+
|
|
62
|
+
- Export `./ai` (`dist/ai/index.js`). Works in the Convex default runtime: no Node built-ins, no `"use node"`.
|
|
63
|
+
- `GatewayServiceTier` (`"flex" | "default" | "ultrafast"`), `gatewayServiceTier(tier)` and its alias `gatewayTier`: `{}` for `"default"`, else `{ gateway: { serviceTier: tier } }`.
|
|
64
|
+
- `FLEX_GATEWAY_PROVIDER_OPTIONS` (replaces inline `{ gateway: { serviceTier: "flex" } }` literals) and its alias `FLEX_PROVIDER_OPTIONS`, frozen.
|
|
65
|
+
- `withFlexGatewayOptions(extra?)`: flex with the caller's provider options on top. Unlike the local `buildChatProviderOptions` it replaces, a caller `gateway` key is merged over flex instead of replacing it.
|
|
66
|
+
- `readGatewayCost(metadata)`: `gateway.cost`, else `gateway.marketCost`, as a number or numeric string. Takes a structural type that the SDK's `ProviderMetadata` fits; no SDK import.
|
|
67
|
+
- `classifyGatewayError(error)`, `errorMessageOf(error)`, `GatewayErrorKind` and `GatewayFailure` (from a local `gatewayErrors.ts`). Changes from that copy:
|
|
68
|
+
- New kind `quota`: status 402, a billing message, or "quota" on a Gateway error that is not a rate limit. Not retryable. A rate-limit error that only says "quota" stays `rate_limit`.
|
|
69
|
+
- `auth` also matches the error that `generateText` and the other `ai` calls put in place of `GatewayAuthenticationError` (a plain `Error` named `GatewayAuthenticationError`, or in production an `AISDKError` named `GatewayError`). The local copy returned `other` for both.
|
|
70
|
+
- The Gateway's `GatewayTimeoutError` is `timeout` (retryable), not `gateway`.
|
|
71
|
+
- `statusCode` is set for every Gateway error; `message` has ANSI colour codes removed.
|
|
72
|
+
- Types `GatewayServiceTierOptions`, `GatewayProviderOptions`, `GatewayJsonObject`, `GatewayJsonValue`, `GatewayCostMetadata`.
|
|
73
|
+
- `docs/ai.md`, with which app files can be deleted once each app adopts it.
|
|
74
|
+
|
|
75
|
+
### Tests
|
|
76
|
+
|
|
77
|
+
- `tests/ai/`: tier builder, flex merge, cost parsing, every classifier branch with real SDK error instances, marker matching for a foreign copy, and errors built by `generateText` through `createGateway` with a fake `fetch` (429, 402, 401, 404, 400, 503). Types are checked against the SDK's `providerOptions` and `ProviderMetadata`.
|
|
78
|
+
- `tests-node/esm-exports.mjs`: the exports map has `./ai`; the root has no AI exports; `./ai` fails with a missing package when the peers are absent and runs when they are installed; the published `./ai` types check alone and fit the SDK.
|
|
79
|
+
- `tests-node/bundle.mjs`: a Convex V8 bundle of an action that uses `./ai` has no Node built-in with the SDK external, and imports no Node built-in with the SDK bundled. The SDK itself carries guarded `process.getBuiltinModule("node:…")` calls; the test allows those and nothing else.
|
|
80
|
+
- `ai` and `@ai-sdk/gateway` are dev dependencies.
|
|
81
|
+
|
|
3
82
|
## 0.10.0
|
|
4
83
|
|
|
5
84
|
Retires the per-app `vibot_pro` plan. Only the shared `v_pro` plan counts as V Pro. No new dependency.
|
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @vvedantb/server
|
|
2
2
|
|
|
3
|
-
Server-side helpers for Convex backends, Convex optimistic updates, Node-side MCP OAuth client helpers, a QuickJS code sandbox and an artifacts core, from one root import.
|
|
3
|
+
Server-side helpers for Convex backends, Convex optimistic updates, Node-side MCP OAuth client helpers, a QuickJS code sandbox and an artifacts core, from one root import. Vercel AI Gateway helpers are on the `@vvedantb/server/ai` subpath.
|
|
4
4
|
|
|
5
5
|
```sh
|
|
6
6
|
npm install @vvedantb/server
|
|
@@ -10,16 +10,21 @@ npm install @vvedantb/server
|
|
|
10
10
|
import { createMcpHttpHandler, extractBearerToken, registerMcpRoutes, sha256Hex } from "@vvedantb/server";
|
|
11
11
|
```
|
|
12
12
|
|
|
13
|
-
|
|
13
|
+
```ts
|
|
14
|
+
import { classifyGatewayError, FLEX_GATEWAY_PROVIDER_OPTIONS, readGatewayCost } from "@vvedantb/server/ai";
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
The one subpath export is `./ai` (0.11.0). The root does not re-export it, so a root import never loads the AI SDK. 0.2.0 removed `/convex` and `/mcp`; see [CHANGELOG.md](CHANGELOG.md).
|
|
14
18
|
|
|
15
19
|
| Area | What it holds | Docs |
|
|
16
20
|
| --- | --- | --- |
|
|
17
|
-
| Convex helpers | Query-limit errors, Clerk auth config and client, Clerk token verification (Node `verifyClerkAccessToken`, V8 `authenticateClerkBearer` for OAuth access token JWTs, with `verifyFallback` for opaque tokens and session JWTs; the MCP token cache is deprecated), Clerk-user lookups and `ensureUser` (`createClerkUserAuth`), bearer tokens, env, MCP CORS, origin-allowlist CORS, `jsonResponse`, server info, test helpers. | [docs/convex.md](docs/convex.md) |
|
|
21
|
+
| Convex helpers | Query-limit errors, Clerk auth config and client, Clerk token verification (Node `verifyClerkAccessToken`, V8 `authenticateClerkBearer` for OAuth access token JWTs, with `verifyFallback` for opaque tokens and session JWTs; the MCP token cache is deprecated), Clerk-user lookups and `ensureUser` (`createClerkUserAuth`), V Pro checks and configurable Clerk Billing webhook helpers (`hasVPro`, `verifyClerkWebhook`, `parseClerkBillingEvent`, `createVProModule` with granting statuses, prefix event matching, `createUser` and `extraPatch`), bearer tokens, env, MCP CORS, origin-allowlist CORS, `jsonResponse`, server info, test helpers. | [docs/convex.md](docs/convex.md) |
|
|
18
22
|
| MCP scaffolding | For Convex `httpAction`s: bearer-auth handler, OAuth metadata, route registration, a pure JSON-RPC dispatcher, tool helpers and explorer tools. | [docs/mcp.md](docs/mcp.md) |
|
|
19
23
|
| Crypto | WebCrypto-only base64/base64url/hex, SHA-256, random tokens, `timingSafeEqual`, AES-GCM. Convex default runtime and Node 20+. | [docs/crypto.md](docs/crypto.md) |
|
|
20
24
|
| Optimistic updates | `mapLoadedQuery` (also `forEachLoadedQuery`, `updateAllCachedQueries`), `patchLoadedQuery`, `tempId`, `createMemoryOptimisticStore`. Client-side, no React. | [docs/convex.md](docs/convex.md#optimistic-updates-client-side) |
|
|
21
25
|
| MCP OAuth client | Node only (Electron main): OAuth provider over injected storage, sign-in, refresh, revocation, loopback redirect server. Node built-ins and the MCP SDK load on first use, so Convex V8 bundles of the root stay clean. | [docs/mcp-oauth-client.md](docs/mcp-oauth-client.md) |
|
|
22
26
|
| Artifacts core | Pure, no DOM: Zod contract for artifact rows and typed bodies (`createArtifactSchemas`, `validateArtifactBody`), state limits and ops, the host's save debounce, built-in quiz and flashcards pages, and `wrapArtifactDocument` (CSP plus a guest state bridge with host-given global aliases). | [docs/artifacts.md](docs/artifacts.md) |
|
|
27
|
+
| AI Gateway (`@vvedantb/server/ai`) | Service tier provider options (`gatewayServiceTier`, `FLEX_GATEWAY_PROVIDER_OPTIONS`, `withFlexGatewayOptions`), `readGatewayCost` from provider metadata, and `classifyGatewayError` (AI SDK and Gateway errors to `invalid_request`, `auth`, `model_not_found`, `rate_limit`, `quota`, `gateway`, `malformed_response`, `timeout` or `other`). Convex default runtime safe. | [docs/ai.md](docs/ai.md) |
|
|
23
28
|
| Code sandbox | Node only: `runSandboxedScript` runs untrusted JavaScript in QuickJS (WASM) with a `tools` proxy to host handlers, time, heap, stack, call and log limits, injected `globals`, and an `onCall` hook for allow-lists and dry runs. QuickJS loads on first call. | [docs/sandbox.md](docs/sandbox.md) |
|
|
24
29
|
|
|
25
30
|
Migration steps per app: [docs/migration.md](docs/migration.md).
|
|
@@ -28,7 +33,8 @@ Migration steps per app: [docs/migration.md](docs/migration.md).
|
|
|
28
33
|
|
|
29
34
|
All are optional. None is imported when the root loads.
|
|
30
35
|
|
|
31
|
-
- `@
|
|
36
|
+
- `ai` `>=5` and `@ai-sdk/gateway` `>=1`: only for `@vvedantb/server/ai`, which imports their error classes statically, so that subpath needs both installed. The root never imports them.
|
|
37
|
+
- `@clerk/backend` `>=1`: only for `getClerkClient`, `verifyClerkAccessToken` and `verifyClerkWebhook`, which take its factory, client or `verifyWebhook` as an argument.
|
|
32
38
|
- `zod` `^3.25.0 || ^4.0.0`: only if you pass zod schemas to `defineTool`, or your `z` to `createMcpOAuthStateSchema` or `createArtifactSchemas`.
|
|
33
39
|
- `convex` `^1.24.0`: types only, for the optimistic-update helpers. The package never imports `convex` at runtime: `registerMcpRoutes` and `createClerkUserAuth` type the router and ctx structurally, and `createMemoryOptimisticStore` carries its own copy of `getFunctionName` (`convex` is a dev dependency, used to check that real Convex types fit).
|
|
34
40
|
- `@modelcontextprotocol/sdk` `^1.29.0`: only for the MCP client OAuth calls, which import it on first use.
|
|
@@ -39,13 +45,15 @@ No React, no web dependencies. `"sideEffects": false`. Compiled ESM with types i
|
|
|
39
45
|
## Layout
|
|
40
46
|
|
|
41
47
|
```
|
|
42
|
-
src/index.ts the
|
|
48
|
+
src/index.ts the root export: re-exports the six folders below (not ai/)
|
|
49
|
+
src/ai/ the ./ai subpath: AI Gateway tier, cost and error helpers (static ai and @ai-sdk/gateway imports)
|
|
43
50
|
src/convex/ Convex helpers and optimistic updates
|
|
44
51
|
src/mcp/ MCP scaffolding (imports ../convex by relative path)
|
|
45
52
|
src/mcp-oauth-client/ MCP OAuth client helpers (Node only; lazy node:http and SDK imports)
|
|
46
53
|
src/crypto/ WebCrypto primitives
|
|
47
54
|
src/sandbox/ QuickJS code sandbox (Node only; lazy QuickJS import)
|
|
48
55
|
src/artifacts/ artifacts core (pure strings and data; runs anywhere)
|
|
56
|
+
tests/ai/ vitest, including errors built by generateText through the Gateway provider with a fake fetch
|
|
49
57
|
tests/convex/ vitest
|
|
50
58
|
tests/mcp/ vitest, with fixtures/ (SDK captures, app references)
|
|
51
59
|
tests/mcp-oauth-client/ vitest, against fake MCP and authorization servers
|
|
@@ -54,7 +62,7 @@ tests/sandbox/ vitest, against real QuickJS
|
|
|
54
62
|
tests/artifacts/ vitest, including the guest bootstrap in a VM realm and a no-app-name check
|
|
55
63
|
tests-node/ plain Node checks of the built package: exports map and peers (esm-exports.mjs),
|
|
56
64
|
Convex V8 and Node/Electron bundles with esbuild (bundle.mjs)
|
|
57
|
-
docs/ convex.md, mcp.md, mcp-oauth-client.md, crypto.md, sandbox.md, artifacts.md, migration.md, migrated/<app>/
|
|
65
|
+
docs/ ai.md, convex.md, mcp.md, mcp-oauth-client.md, crypto.md, sandbox.md, artifacts.md, migration.md, migrated/<app>/
|
|
58
66
|
scripts/ capture-sdk-fixtures.mjs
|
|
59
67
|
```
|
|
60
68
|
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The part of AI SDK `providerMetadata` that `readGatewayCost` reads. The SDK's `ProviderMetadata` is
|
|
3
|
+
* assignable to it; no AI SDK import is needed at runtime.
|
|
4
|
+
*/
|
|
5
|
+
export type GatewayCostMetadata = {
|
|
6
|
+
readonly gateway?: {
|
|
7
|
+
readonly cost?: unknown;
|
|
8
|
+
readonly marketCost?: unknown;
|
|
9
|
+
readonly [key: string]: unknown;
|
|
10
|
+
};
|
|
11
|
+
};
|
|
12
|
+
/**
|
|
13
|
+
* AI Gateway cost in USD from a result's `providerMetadata`: `gateway.cost` (what was billed), else
|
|
14
|
+
* `gateway.marketCost` (list price), so budget guards still see a value. Each may be a number or a numeric
|
|
15
|
+
* string. Returns `undefined` when neither is a finite number.
|
|
16
|
+
*/
|
|
17
|
+
export declare function readGatewayCost(metadata: GatewayCostMetadata | null | undefined): number | undefined;
|
package/dist/ai/cost.js
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* AI Gateway cost in USD from a result's `providerMetadata`: `gateway.cost` (what was billed), else
|
|
3
|
+
* `gateway.marketCost` (list price), so budget guards still see a value. Each may be a number or a numeric
|
|
4
|
+
* string. Returns `undefined` when neither is a finite number.
|
|
5
|
+
*/
|
|
6
|
+
export function readGatewayCost(metadata) {
|
|
7
|
+
const gateway = metadata?.gateway;
|
|
8
|
+
if (typeof gateway !== "object" || gateway === null)
|
|
9
|
+
return undefined;
|
|
10
|
+
const { cost, marketCost } = gateway;
|
|
11
|
+
return parseCost(cost) ?? parseCost(marketCost);
|
|
12
|
+
}
|
|
13
|
+
function parseCost(cost) {
|
|
14
|
+
if (typeof cost === "number")
|
|
15
|
+
return Number.isFinite(cost) ? cost : undefined;
|
|
16
|
+
if (typeof cost !== "string" || cost.trim().length === 0)
|
|
17
|
+
return undefined;
|
|
18
|
+
const parsed = Number(cost);
|
|
19
|
+
return Number.isFinite(parsed) ? parsed : undefined;
|
|
20
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What went wrong with an AI SDK / AI Gateway call, in terms a caller can act on.
|
|
3
|
+
*
|
|
4
|
+
* - `invalid_request`: bad arguments or a request the Gateway rejected. Not retryable.
|
|
5
|
+
* - `auth`: missing or invalid Gateway key or OIDC token. Not retryable.
|
|
6
|
+
* - `model_not_found`: unknown model ID. Not retryable.
|
|
7
|
+
* - `rate_limit`: too many requests. Retryable after a wait.
|
|
8
|
+
* - `quota`: out of credits, spend limit or quota reached: HTTP 402, a billing message, or "quota" on a Gateway
|
|
9
|
+
* error other than a rate limit. Not retryable until someone tops up or the period resets.
|
|
10
|
+
* - `gateway`: any other Gateway error. `retryable` is the SDK's `isRetryable`.
|
|
11
|
+
* - `malformed_response`: the response did not match what the SDK expected. Retryable.
|
|
12
|
+
* - `timeout`: the call timed out or was aborted. Retryable.
|
|
13
|
+
* - `other`: anything else. Not retryable.
|
|
14
|
+
*/
|
|
15
|
+
export type GatewayErrorKind = "invalid_request" | "auth" | "model_not_found" | "rate_limit" | "quota" | "gateway" | "malformed_response" | "timeout" | "other";
|
|
16
|
+
export type GatewayFailure = {
|
|
17
|
+
kind: GatewayErrorKind;
|
|
18
|
+
/** The error's own message, without ANSI colour codes. Never the request body; the SDK does not put the key in it. */
|
|
19
|
+
message: string;
|
|
20
|
+
retryable: boolean;
|
|
21
|
+
/** HTTP status, set for every Gateway error (the SDK defaults it to 500 when the response had none). */
|
|
22
|
+
statusCode?: number;
|
|
23
|
+
};
|
|
24
|
+
/** `error.message` for an `Error`, the string itself for a string, else `"Unknown error"`. */
|
|
25
|
+
export declare function errorMessageOf(error: unknown): string;
|
|
26
|
+
/**
|
|
27
|
+
* Maps an AI SDK / AI Gateway failure to a `GatewayFailure`. A `RetryError` is unwrapped to its `lastError`.
|
|
28
|
+
* Checks use the SDK's `isInstance`, which matches by marker, so errors from another copy of `ai` or
|
|
29
|
+
* `@ai-sdk/gateway` in the bundle are still recognised; the auth error that `ai` rewraps is matched by name.
|
|
30
|
+
* The message has ANSI colour codes and outer whitespace removed. Never throws.
|
|
31
|
+
*
|
|
32
|
+
* Order matters: invalid request, auth and model-not-found win over quota; quota wins over rate limit; a Gateway
|
|
33
|
+
* timeout is `timeout`, not `gateway`.
|
|
34
|
+
*/
|
|
35
|
+
export declare function classifyGatewayError(error: unknown): GatewayFailure;
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { InvalidArgumentError, InvalidResponseDataError, NoSuchModelError, RetryError } from "ai";
|
|
2
|
+
import { GatewayAuthenticationError, GatewayError, GatewayInvalidRequestError, GatewayModelNotFoundError, GatewayRateLimitError, } from "@ai-sdk/gateway";
|
|
3
|
+
/** `error.message` for an `Error`, the string itself for a string, else `"Unknown error"`. */
|
|
4
|
+
export function errorMessageOf(error) {
|
|
5
|
+
if (error instanceof Error)
|
|
6
|
+
return error.message;
|
|
7
|
+
if (typeof error === "string")
|
|
8
|
+
return error;
|
|
9
|
+
return "Unknown error";
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* The Gateway has no quota error type: an out-of-credits or spend-limit reply arrives as a rate-limit or
|
|
13
|
+
* generic Gateway error, so the status (402) or the message is all there is to go on.
|
|
14
|
+
*
|
|
15
|
+
* Billing words (credits, funds, billing, payment, spend limit, budget) mean quota on any Gateway error. The bare
|
|
16
|
+
* word "quota" is ambiguous on a rate-limit error ("requests per minute quota"), so there it stays `rate_limit`;
|
|
17
|
+
* on any other Gateway error (for example a 403) it means quota.
|
|
18
|
+
*/
|
|
19
|
+
const BILLING_MESSAGE = /\b(?:insufficient[ _-]?(?:funds|credits?|balance)|out of credits?|credits? (?:exhausted|limit|balance)|billing|payment required|spend(?:ing)? limit|budget (?:exceeded|limit))\b/i;
|
|
20
|
+
const QUOTA_MESSAGE = /\bquota\b/i;
|
|
21
|
+
function isQuotaError(error, message) {
|
|
22
|
+
if (error.statusCode === 402 || BILLING_MESSAGE.test(message))
|
|
23
|
+
return true;
|
|
24
|
+
return !GatewayRateLimitError.isInstance(error) && QUOTA_MESSAGE.test(message);
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* `generateText`, `streamText` and the other `ai` calls replace a `GatewayAuthenticationError` before it reaches
|
|
28
|
+
* the caller (`wrapGatewayError` in `ai` 5 to 7): outside production with a plain `Error` named
|
|
29
|
+
* `GatewayAuthenticationError`, and in production (`NODE_ENV=production`) with an `AISDKError` named
|
|
30
|
+
* `GatewayError` whose message starts "Unauthenticated". Neither has the Gateway markers, so match them by name.
|
|
31
|
+
*/
|
|
32
|
+
function isWrappedAuthError(error) {
|
|
33
|
+
if (!(error instanceof Error))
|
|
34
|
+
return false;
|
|
35
|
+
return (error.name === "GatewayAuthenticationError" ||
|
|
36
|
+
(error.name === "GatewayError" && !GatewayError.isInstance(error) && /^Unauthenticated\b/.test(error.message)));
|
|
37
|
+
}
|
|
38
|
+
// ANSI colour codes, which the non-production wrapped auth error puts in its message.
|
|
39
|
+
const ANSI = /\u001b\[[0-9;]*m/g;
|
|
40
|
+
/**
|
|
41
|
+
* Maps an AI SDK / AI Gateway failure to a `GatewayFailure`. A `RetryError` is unwrapped to its `lastError`.
|
|
42
|
+
* Checks use the SDK's `isInstance`, which matches by marker, so errors from another copy of `ai` or
|
|
43
|
+
* `@ai-sdk/gateway` in the bundle are still recognised; the auth error that `ai` rewraps is matched by name.
|
|
44
|
+
* The message has ANSI colour codes and outer whitespace removed. Never throws.
|
|
45
|
+
*
|
|
46
|
+
* Order matters: invalid request, auth and model-not-found win over quota; quota wins over rate limit; a Gateway
|
|
47
|
+
* timeout is `timeout`, not `gateway`.
|
|
48
|
+
*/
|
|
49
|
+
export function classifyGatewayError(error) {
|
|
50
|
+
if (RetryError.isInstance(error)) {
|
|
51
|
+
return classifyGatewayError(error.lastError);
|
|
52
|
+
}
|
|
53
|
+
const message = errorMessageOf(error).replace(ANSI, "").trim();
|
|
54
|
+
const statusCode = GatewayError.isInstance(error) ? { statusCode: error.statusCode } : {};
|
|
55
|
+
if (InvalidArgumentError.isInstance(error) || GatewayInvalidRequestError.isInstance(error)) {
|
|
56
|
+
return { kind: "invalid_request", message, retryable: false, ...statusCode };
|
|
57
|
+
}
|
|
58
|
+
if (GatewayAuthenticationError.isInstance(error) || isWrappedAuthError(error)) {
|
|
59
|
+
return { kind: "auth", message, retryable: false, ...statusCode };
|
|
60
|
+
}
|
|
61
|
+
if (NoSuchModelError.isInstance(error) || GatewayModelNotFoundError.isInstance(error)) {
|
|
62
|
+
return { kind: "model_not_found", message, retryable: false, ...statusCode };
|
|
63
|
+
}
|
|
64
|
+
if (GatewayError.isInstance(error) && isQuotaError(error, message)) {
|
|
65
|
+
return { kind: "quota", message, retryable: false, ...statusCode };
|
|
66
|
+
}
|
|
67
|
+
if (GatewayRateLimitError.isInstance(error)) {
|
|
68
|
+
return { kind: "rate_limit", message, retryable: true, ...statusCode };
|
|
69
|
+
}
|
|
70
|
+
if (GatewayError.isInstance(error)) {
|
|
71
|
+
// GatewayTimeoutError is not exported by @ai-sdk/gateway, so match it by name.
|
|
72
|
+
if (error.name === "GatewayTimeoutError") {
|
|
73
|
+
return { kind: "timeout", message, retryable: true, ...statusCode };
|
|
74
|
+
}
|
|
75
|
+
return { kind: "gateway", message, retryable: error.isRetryable, ...statusCode };
|
|
76
|
+
}
|
|
77
|
+
if (InvalidResponseDataError.isInstance(error)) {
|
|
78
|
+
return { kind: "malformed_response", message, retryable: true };
|
|
79
|
+
}
|
|
80
|
+
if (error instanceof Error && (error.name === "TimeoutError" || error.name === "AbortError")) {
|
|
81
|
+
return { kind: "timeout", message, retryable: true };
|
|
82
|
+
}
|
|
83
|
+
return { kind: "other", message, retryable: false };
|
|
84
|
+
}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
export { readGatewayCost, type GatewayCostMetadata } from "./cost.js";
|
|
2
|
+
export { classifyGatewayError, errorMessageOf, type GatewayErrorKind, type GatewayFailure, } from "./errors.js";
|
|
3
|
+
export { FLEX_GATEWAY_PROVIDER_OPTIONS, FLEX_PROVIDER_OPTIONS, gatewayServiceTier, gatewayTier, withFlexGatewayOptions, type GatewayJsonObject, type GatewayJsonValue, type GatewayProviderOptions, type GatewayServiceTier, type GatewayServiceTierOptions, } from "./serviceTier.js";
|
package/dist/ai/index.js
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* AI Gateway service tier provider options. Pure data: no AI SDK import, so
|
|
3
|
+
* these run anywhere (Convex default runtime, Node, browsers).
|
|
4
|
+
*/
|
|
5
|
+
/** A JSON value the AI SDK accepts in `providerOptions` (mirrors `JSONValue` from `@ai-sdk/provider`). */
|
|
6
|
+
export type GatewayJsonValue = null | string | number | boolean | Readonly<GatewayJsonObject> | readonly GatewayJsonValue[];
|
|
7
|
+
/** A JSON object the AI SDK accepts in `providerOptions` (mirrors `JSONObject` from `@ai-sdk/provider`). */
|
|
8
|
+
export type GatewayJsonObject = {
|
|
9
|
+
[key: string]: GatewayJsonValue | undefined;
|
|
10
|
+
};
|
|
11
|
+
/** Per-provider options for an AI SDK call (`providerOptions`). Assignable to the SDK's `ProviderOptions`. */
|
|
12
|
+
export type GatewayProviderOptions = Record<string, GatewayJsonObject>;
|
|
13
|
+
/**
|
|
14
|
+
* AI Gateway service tier, chosen per call.
|
|
15
|
+
*
|
|
16
|
+
* - `"flex"`: cheaper, may queue and be slower. For background work.
|
|
17
|
+
* - `"default"`: the Gateway's standard tier. No `serviceTier` is sent.
|
|
18
|
+
* - `"ultrafast"`: sent as is. Not confirmed for every model; the Gateway may reject it. Read
|
|
19
|
+
* `providerMetadata.gateway.serviceTier` to see what the Gateway applied.
|
|
20
|
+
*
|
|
21
|
+
* A tier the provider or model does not support is a no-op on the Gateway side.
|
|
22
|
+
*/
|
|
23
|
+
export type GatewayServiceTier = "flex" | "default" | "ultrafast";
|
|
24
|
+
/** The provider options `gatewayServiceTier` returns: empty for `"default"`. */
|
|
25
|
+
export type GatewayServiceTierOptions = {
|
|
26
|
+
gateway?: {
|
|
27
|
+
serviceTier: Exclude<GatewayServiceTier, "default">;
|
|
28
|
+
};
|
|
29
|
+
};
|
|
30
|
+
/**
|
|
31
|
+
* Provider options for a service tier: `{}` for `"default"`, else `{ gateway: { serviceTier: tier } }`.
|
|
32
|
+
* Returns a new object on every call.
|
|
33
|
+
*/
|
|
34
|
+
export declare function gatewayServiceTier(tier: GatewayServiceTier): GatewayServiceTierOptions;
|
|
35
|
+
/** Alias of `gatewayServiceTier`. */
|
|
36
|
+
export declare const gatewayTier: typeof gatewayServiceTier;
|
|
37
|
+
/** `{ gateway: { serviceTier: "flex" } }`, frozen. Spread it into `providerOptions`; do not mutate it. */
|
|
38
|
+
export declare const FLEX_GATEWAY_PROVIDER_OPTIONS: {
|
|
39
|
+
readonly gateway: {
|
|
40
|
+
readonly serviceTier: "flex";
|
|
41
|
+
};
|
|
42
|
+
};
|
|
43
|
+
/** Alias of `FLEX_GATEWAY_PROVIDER_OPTIONS`. */
|
|
44
|
+
export declare const FLEX_PROVIDER_OPTIONS: {
|
|
45
|
+
readonly gateway: {
|
|
46
|
+
readonly serviceTier: "flex";
|
|
47
|
+
};
|
|
48
|
+
};
|
|
49
|
+
/**
|
|
50
|
+
* Flex tier plus the caller's provider options, as a new object. Caller options win: other providers' keys
|
|
51
|
+
* (for example `{ alibaba: { enableThinking: false } }`) are added as is, and caller `gateway` keys are merged
|
|
52
|
+
* over `{ serviceTier: "flex" }`, so `{ gateway: { order: ["anthropic"] } }` keeps flex and a caller
|
|
53
|
+
* `serviceTier` replaces it. Neither argument is mutated.
|
|
54
|
+
*/
|
|
55
|
+
export declare function withFlexGatewayOptions(extra?: GatewayProviderOptions): GatewayProviderOptions;
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* AI Gateway service tier provider options. Pure data: no AI SDK import, so
|
|
3
|
+
* these run anywhere (Convex default runtime, Node, browsers).
|
|
4
|
+
*/
|
|
5
|
+
/**
|
|
6
|
+
* Provider options for a service tier: `{}` for `"default"`, else `{ gateway: { serviceTier: tier } }`.
|
|
7
|
+
* Returns a new object on every call.
|
|
8
|
+
*/
|
|
9
|
+
export function gatewayServiceTier(tier) {
|
|
10
|
+
return tier === "default" ? {} : { gateway: { serviceTier: tier } };
|
|
11
|
+
}
|
|
12
|
+
/** Alias of `gatewayServiceTier`. */
|
|
13
|
+
export const gatewayTier = gatewayServiceTier;
|
|
14
|
+
/** `{ gateway: { serviceTier: "flex" } }`, frozen. Spread it into `providerOptions`; do not mutate it. */
|
|
15
|
+
export const FLEX_GATEWAY_PROVIDER_OPTIONS = Object.freeze({ gateway: Object.freeze({ serviceTier: "flex" }) });
|
|
16
|
+
/** Alias of `FLEX_GATEWAY_PROVIDER_OPTIONS`. */
|
|
17
|
+
export const FLEX_PROVIDER_OPTIONS = FLEX_GATEWAY_PROVIDER_OPTIONS;
|
|
18
|
+
/**
|
|
19
|
+
* Flex tier plus the caller's provider options, as a new object. Caller options win: other providers' keys
|
|
20
|
+
* (for example `{ alibaba: { enableThinking: false } }`) are added as is, and caller `gateway` keys are merged
|
|
21
|
+
* over `{ serviceTier: "flex" }`, so `{ gateway: { order: ["anthropic"] } }` keeps flex and a caller
|
|
22
|
+
* `serviceTier` replaces it. Neither argument is mutated.
|
|
23
|
+
*/
|
|
24
|
+
export function withFlexGatewayOptions(extra) {
|
|
25
|
+
return {
|
|
26
|
+
...extra,
|
|
27
|
+
gateway: { ...FLEX_GATEWAY_PROVIDER_OPTIONS.gateway, ...extra?.gateway },
|
|
28
|
+
};
|
|
29
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure Clerk Billing helpers: which subscription items grant their plan, and
|
|
3
|
+
* how a verified webhook event changes a user's stored plan slugs. No Convex
|
|
4
|
+
* or Clerk import; apps own the `httpAction` and `internalMutation` wrappers.
|
|
5
|
+
*/
|
|
6
|
+
/**
|
|
7
|
+
* Clerk Billing item statuses that grant the item's plan. `canceled` means
|
|
8
|
+
* cancel at period end, so it still grants until `ended`. Every other status
|
|
9
|
+
* (`ended`, `expired`, `abandoned`, `incomplete`, `upcoming`) does not.
|
|
10
|
+
*/
|
|
11
|
+
export declare const GRANTING_ITEM_STATUSES: readonly string[];
|
|
12
|
+
/** `active` and `past_due` grant; `canceled` does not. Pass as `grantingStatuses`. */
|
|
13
|
+
export declare const GRANTING_STATUSES_ACTIVE_PAST_DUE: readonly string[];
|
|
14
|
+
/** Only `active` grants. Pass as `grantingStatuses`. */
|
|
15
|
+
export declare const GRANTING_STATUSES_ACTIVE_ONLY: readonly string[];
|
|
16
|
+
/**
|
|
17
|
+
* Options for the Clerk Billing helpers. Every field is optional, and
|
|
18
|
+
* leaving them out keeps the defaults. Use the same `grantingStatuses` when
|
|
19
|
+
* parsing an event and when applying the change it gives.
|
|
20
|
+
*/
|
|
21
|
+
export type ClerkBillingOptions = {
|
|
22
|
+
/** Item statuses that grant the item's plan. Default `GRANTING_ITEM_STATUSES`. */
|
|
23
|
+
readonly grantingStatuses?: readonly string[];
|
|
24
|
+
/**
|
|
25
|
+
* How `parseClerkBillingEvent` matches event types. `"exact"` (default)
|
|
26
|
+
* handles the listed `subscription.*` and `subscriptionItem.*` types only.
|
|
27
|
+
* `"prefix"` handles any type that starts with `subscription.` or
|
|
28
|
+
* `subscriptionItem.`. Read only by `parseClerkBillingEvent`.
|
|
29
|
+
*/
|
|
30
|
+
readonly eventMatch?: "exact" | "prefix";
|
|
31
|
+
};
|
|
32
|
+
/**
|
|
33
|
+
* One subscription item. Webhook `data.items` entries and the Clerk backend
|
|
34
|
+
* client's `subscription.subscriptionItems` both fit without mapping. Billing
|
|
35
|
+
* period fields are not read: a monthly and a yearly item of one plan share
|
|
36
|
+
* its slug.
|
|
37
|
+
*/
|
|
38
|
+
export type PlanItem = {
|
|
39
|
+
readonly status: string;
|
|
40
|
+
readonly plan?: {
|
|
41
|
+
readonly slug: string;
|
|
42
|
+
} | null;
|
|
43
|
+
};
|
|
44
|
+
/** A verified Clerk webhook event, structurally. `verifyWebhook`'s result fits. */
|
|
45
|
+
export type ClerkWebhookEventLike = {
|
|
46
|
+
readonly type: string;
|
|
47
|
+
readonly data?: unknown;
|
|
48
|
+
};
|
|
49
|
+
/** How one billing event changes a user's stored plan slugs. */
|
|
50
|
+
export type ClerkBillingChange =
|
|
51
|
+
/** From a `subscription.*` event, which lists every item: overwrite the stored set. */
|
|
52
|
+
{
|
|
53
|
+
kind: "replace";
|
|
54
|
+
clerkId: string;
|
|
55
|
+
planSlugs: string[];
|
|
56
|
+
}
|
|
57
|
+
/** From a `subscriptionItem.*` event, which holds one item: merge it into the stored set. */
|
|
58
|
+
| {
|
|
59
|
+
kind: "item";
|
|
60
|
+
clerkId: string;
|
|
61
|
+
status: string;
|
|
62
|
+
slug: string;
|
|
63
|
+
};
|
|
64
|
+
/** True when the item's status is one of `options.grantingStatuses` (default `GRANTING_ITEM_STATUSES`). */
|
|
65
|
+
export declare function itemGrantsPlan(item: PlanItem, options?: ClerkBillingOptions): boolean;
|
|
66
|
+
/** Slugs of the items that grant their plan, unique and sorted. */
|
|
67
|
+
export declare function activePlanSlugs(items: readonly PlanItem[], options?: ClerkBillingOptions): string[];
|
|
68
|
+
/**
|
|
69
|
+
* Merge one item into the current slugs: add its slug when it grants, remove
|
|
70
|
+
* it when it does not. An item without a plan changes nothing. Unique and sorted.
|
|
71
|
+
*/
|
|
72
|
+
export declare function applyItemToPlanSlugs(current: readonly string[] | null | undefined, item: PlanItem, options?: ClerkBillingOptions): string[];
|
|
73
|
+
/**
|
|
74
|
+
* The slugs to store after `change`, given the slugs stored now. Unique and
|
|
75
|
+
* sorted. `options.grantingStatuses` decides an `item` change; a `replace`
|
|
76
|
+
* change was already filtered when it was parsed.
|
|
77
|
+
*/
|
|
78
|
+
export declare function applyBillingChange(current: readonly string[] | null | undefined, change: ClerkBillingChange, options?: ClerkBillingOptions): string[];
|
|
79
|
+
/**
|
|
80
|
+
* Read a verified Clerk webhook event as a billing change, or `null` when it
|
|
81
|
+
* changes nothing: another event type, a payer with no `user_id` (an
|
|
82
|
+
* organisation), an item with no status or plan slug, or a subscription with
|
|
83
|
+
* no `items` array. Reads `data` defensively and never throws.
|
|
84
|
+
*
|
|
85
|
+
* `options.eventMatch` picks exact types (default) or the `subscription.` and
|
|
86
|
+
* `subscriptionItem.` prefixes. `options.grantingStatuses` filters the slugs
|
|
87
|
+
* of a `replace` change.
|
|
88
|
+
*/
|
|
89
|
+
export declare function parseClerkBillingEvent(event: ClerkWebhookEventLike | null | undefined, options?: ClerkBillingOptions): ClerkBillingChange | null;
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure Clerk Billing helpers: which subscription items grant their plan, and
|
|
3
|
+
* how a verified webhook event changes a user's stored plan slugs. No Convex
|
|
4
|
+
* or Clerk import; apps own the `httpAction` and `internalMutation` wrappers.
|
|
5
|
+
*/
|
|
6
|
+
/**
|
|
7
|
+
* Clerk Billing item statuses that grant the item's plan. `canceled` means
|
|
8
|
+
* cancel at period end, so it still grants until `ended`. Every other status
|
|
9
|
+
* (`ended`, `expired`, `abandoned`, `incomplete`, `upcoming`) does not.
|
|
10
|
+
*/
|
|
11
|
+
export const GRANTING_ITEM_STATUSES = ["active", "past_due", "canceled"];
|
|
12
|
+
/** `active` and `past_due` grant; `canceled` does not. Pass as `grantingStatuses`. */
|
|
13
|
+
export const GRANTING_STATUSES_ACTIVE_PAST_DUE = ["active", "past_due"];
|
|
14
|
+
/** Only `active` grants. Pass as `grantingStatuses`. */
|
|
15
|
+
export const GRANTING_STATUSES_ACTIVE_ONLY = ["active"];
|
|
16
|
+
/** Subscription events whose `data.items` is the full item list. */
|
|
17
|
+
const SUBSCRIPTION_EVENTS = new Set([
|
|
18
|
+
"subscription.created",
|
|
19
|
+
"subscription.updated",
|
|
20
|
+
"subscription.active",
|
|
21
|
+
"subscription.pastDue",
|
|
22
|
+
]);
|
|
23
|
+
/** Subscription item events whose `data` is one item. */
|
|
24
|
+
const SUBSCRIPTION_ITEM_EVENTS = new Set([
|
|
25
|
+
"subscriptionItem.updated",
|
|
26
|
+
"subscriptionItem.active",
|
|
27
|
+
"subscriptionItem.canceled",
|
|
28
|
+
"subscriptionItem.ended",
|
|
29
|
+
"subscriptionItem.abandoned",
|
|
30
|
+
"subscriptionItem.incomplete",
|
|
31
|
+
"subscriptionItem.pastDue",
|
|
32
|
+
]);
|
|
33
|
+
/** True when the item's status is one of `options.grantingStatuses` (default `GRANTING_ITEM_STATUSES`). */
|
|
34
|
+
export function itemGrantsPlan(item, options = {}) {
|
|
35
|
+
return (options.grantingStatuses ?? GRANTING_ITEM_STATUSES).includes(item.status);
|
|
36
|
+
}
|
|
37
|
+
/** Slugs of the items that grant their plan, unique and sorted. */
|
|
38
|
+
export function activePlanSlugs(items, options = {}) {
|
|
39
|
+
const slugs = new Set();
|
|
40
|
+
for (const item of items) {
|
|
41
|
+
if (item.plan && itemGrantsPlan(item, options))
|
|
42
|
+
slugs.add(item.plan.slug);
|
|
43
|
+
}
|
|
44
|
+
return [...slugs].sort();
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Merge one item into the current slugs: add its slug when it grants, remove
|
|
48
|
+
* it when it does not. An item without a plan changes nothing. Unique and sorted.
|
|
49
|
+
*/
|
|
50
|
+
export function applyItemToPlanSlugs(current, item, options = {}) {
|
|
51
|
+
const slugs = new Set(current ?? []);
|
|
52
|
+
if (item.plan) {
|
|
53
|
+
if (itemGrantsPlan(item, options))
|
|
54
|
+
slugs.add(item.plan.slug);
|
|
55
|
+
else
|
|
56
|
+
slugs.delete(item.plan.slug);
|
|
57
|
+
}
|
|
58
|
+
return [...slugs].sort();
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* The slugs to store after `change`, given the slugs stored now. Unique and
|
|
62
|
+
* sorted. `options.grantingStatuses` decides an `item` change; a `replace`
|
|
63
|
+
* change was already filtered when it was parsed.
|
|
64
|
+
*/
|
|
65
|
+
export function applyBillingChange(current, change, options = {}) {
|
|
66
|
+
if (change.kind === "replace")
|
|
67
|
+
return [...new Set(change.planSlugs)].sort();
|
|
68
|
+
return applyItemToPlanSlugs(current, { status: change.status, plan: { slug: change.slug } }, options);
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Read a verified Clerk webhook event as a billing change, or `null` when it
|
|
72
|
+
* changes nothing: another event type, a payer with no `user_id` (an
|
|
73
|
+
* organisation), an item with no status or plan slug, or a subscription with
|
|
74
|
+
* no `items` array. Reads `data` defensively and never throws.
|
|
75
|
+
*
|
|
76
|
+
* `options.eventMatch` picks exact types (default) or the `subscription.` and
|
|
77
|
+
* `subscriptionItem.` prefixes. `options.grantingStatuses` filters the slugs
|
|
78
|
+
* of a `replace` change.
|
|
79
|
+
*/
|
|
80
|
+
export function parseClerkBillingEvent(event, options = {}) {
|
|
81
|
+
if (!isRecord(event) || typeof event.type !== "string")
|
|
82
|
+
return null;
|
|
83
|
+
const data = event.data;
|
|
84
|
+
if (!isRecord(data))
|
|
85
|
+
return null;
|
|
86
|
+
const clerkId = nonEmptyString(isRecord(data.payer) ? data.payer.user_id : undefined);
|
|
87
|
+
if (clerkId === undefined)
|
|
88
|
+
return null;
|
|
89
|
+
const kind = eventKind(event.type, options.eventMatch ?? "exact");
|
|
90
|
+
if (kind === "replace") {
|
|
91
|
+
if (!Array.isArray(data.items))
|
|
92
|
+
return null;
|
|
93
|
+
return { kind: "replace", clerkId, planSlugs: activePlanSlugs(data.items.flatMap(toPlanItem), options) };
|
|
94
|
+
}
|
|
95
|
+
if (kind === "item") {
|
|
96
|
+
const [item] = toPlanItem(data);
|
|
97
|
+
if (!item?.plan)
|
|
98
|
+
return null;
|
|
99
|
+
return { kind: "item", clerkId, status: item.status, slug: item.plan.slug };
|
|
100
|
+
}
|
|
101
|
+
return null;
|
|
102
|
+
}
|
|
103
|
+
function eventKind(type, match) {
|
|
104
|
+
if (match === "prefix") {
|
|
105
|
+
// "subscriptionItem.x" does not start with "subscription.", so the order does not matter.
|
|
106
|
+
if (type.startsWith("subscriptionItem."))
|
|
107
|
+
return "item";
|
|
108
|
+
if (type.startsWith("subscription."))
|
|
109
|
+
return "replace";
|
|
110
|
+
return null;
|
|
111
|
+
}
|
|
112
|
+
if (SUBSCRIPTION_EVENTS.has(type))
|
|
113
|
+
return "replace";
|
|
114
|
+
if (SUBSCRIPTION_ITEM_EVENTS.has(type))
|
|
115
|
+
return "item";
|
|
116
|
+
return null;
|
|
117
|
+
}
|
|
118
|
+
/** `[item]` when `value` has a string `status`; the plan is kept only with a non-empty slug. */
|
|
119
|
+
function toPlanItem(value) {
|
|
120
|
+
if (!isRecord(value) || typeof value.status !== "string")
|
|
121
|
+
return [];
|
|
122
|
+
const slug = nonEmptyString(isRecord(value.plan) ? value.plan.slug : undefined);
|
|
123
|
+
return [{ status: value.status, plan: slug === undefined ? null : { slug } }];
|
|
124
|
+
}
|
|
125
|
+
function isRecord(value) {
|
|
126
|
+
return typeof value === "object" && value !== null;
|
|
127
|
+
}
|
|
128
|
+
function nonEmptyString(value) {
|
|
129
|
+
return typeof value === "string" && value.length > 0 ? value : undefined;
|
|
130
|
+
}
|