@vvedantb/server 0.17.1 → 0.18.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 CHANGED
@@ -1,5 +1,19 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.18.0
4
+
5
+ ### Minor Changes
6
+
7
+ - [#70](https://github.com/vvedantb/v/pull/70) [`6c35be7`](https://github.com/vvedantb/v/commit/6c35be7466f5ecfca3a553351496684394d0ca9d) Thanks [@vvedantb](https://github.com/vvedantb)! - Require AI SDK 7: peer `ai` is now `^7` (was `>=5`). `@vvedantb/server` also requires `@ai-sdk/gateway` `^4`. Apps must depend on `ai@7` (and matching `@ai-sdk/*`).
8
+
9
+ - [`67ca6d5`](https://github.com/vvedantb/v/commit/67ca6d508ce54bd0703cc130ef59723cf9e4664b) Thanks [@cursoragent](https://github.com/cursoragent)! - Add `createClerkBillingFunctions` (and Node companion) so apps share Clerk Billing Convex wiring without schema changes.
10
+
11
+ - [`7aff75e`](https://github.com/vvedantb/v/commit/7aff75ed225e3abb1191aac6caf250cafd687177) Thanks [@cursoragent](https://github.com/cursoragent)! - Add `createMcpAuthActions`, a factory for an app's `verifyAccessToken` internal action. It wraps `verifyClerkAccessToken` and takes `v` and `internalAction` from the app. Options: `getClerk` or `getClerks` (tried in order), `acceptsToken`, `logger`, `tryBeforeClerk` (for example a legacy JWT), `mapPrincipal` and `returns`. The action returns `{ clerkUserId }` by default, and `null` for a rejected token or a throw. Nothing existing changes.
12
+
13
+ ### Patch Changes
14
+
15
+ - [`0cdac42`](https://github.com/vvedantb/v/commit/0cdac42c42d7ffce4e54c14e7670a3f6985fbc54) Thanks [@cursoragent](https://github.com/cursoragent)! - Export `V_PRO_CLERK_PLAN_ID`, `V_PRO_CLERK_PLAN_ID_STAGING` and `vProClerkPlanId` for the V Pro Clerk Billing plan id.
16
+
3
17
  ## 0.17.1
4
18
 
5
19
  ### Patch Changes
@@ -17,11 +31,11 @@
17
31
  ### Minor Changes
18
32
 
19
33
  - [#236](https://github.com/vvedantb/packages/pull/236) [`7db4f19`](https://github.com/vvedantb/packages/commit/7db4f194aeaa25b5352ce5524cd236d6f386f404) Thanks [@agenteva1](https://github.com/apps/agenteva1)! - Generative UI in the kits: agent-composed panels from one shared catalog.
20
-
34
+
21
35
  - `@vvedantb/server/generative-ui`: the 16 component definitions (zod props), the `reply` and `open_url` actions, tones and styles, `parseGenerativeUiSpec` and `isHttpUrl`. No json-render runtime: pass `generativeUiCatalogDefinition` to json-render's `defineCatalog`.
22
36
  - `@vvedantb/ui/generative-ui`: `GenerativeUiPanel` (stored spec, `onReply`, `onOpenUrl`), `GenerativeUiRenderer` and `generativeUiCatalog` on `@json-render/react`.
23
37
  - `@vvedantb/native-ui/generative-ui`: `GenerativeUiPanel` (plus `onCopy` and `renderUnsupported`) and `generativeUiNativeCatalog` on `@json-render/react-native`, drawn as the web panel on the native tokens.
24
-
38
+
25
39
  New optional peers: `@json-render/core`, `@json-render/react` (ui), `@json-render/react-native` (native-ui), `>=0.21.0`.
26
40
 
27
41
  ### Patch Changes
@@ -33,11 +47,11 @@
33
47
  ### Minor Changes
34
48
 
35
49
  - [#223](https://github.com/vvedantb/packages/pull/223) [`9e1f80d`](https://github.com/vvedantb/packages/commit/9e1f80db6d5c6af6419989194ab999d56e807a9a) Thanks [@vvedantb](https://github.com/vvedantb)! - Add three shared backend helpers.
36
-
50
+
37
51
  HMAC and webhook signatures (`@vvedantb/server`, crypto area): `hmacSha256`, `hmacSha256Hex`, `githubStyleSignature` and `verifyGithubStyleSignature`. WebCrypto only, so they run in the Convex default runtime. Each takes a string or `Uint8Array` message (type `HmacMessage`), so a verifier can read raw request bytes or decoded text. `verifyGithubStyleSignature` compares a `sha256=<hex>` header in constant time, trims the header, and returns `false` for a `null` header.
38
-
52
+
39
53
  Convex admin API client (`createConvexAdminClient`, `convexSiteToCloudUrl`, `parseConvexApiResponse`) for each app's MCP "run query" tool. The deployment URL and admin key are arguments; it reads no env vars, imports no convex or zod, and takes an injectable `fetch`. The client runs an ad-hoc query (`runTestFunction`), a system query (`runSystemQuery`), reads inferred shapes (`getShapes`) and lists tables merged with the declared schema (`listTables`).
40
-
54
+
41
55
  Auth function builders (`createAuthFunctions`) on convex-helpers `customFunctions`: `authQuery`, `authMutation` and `authAction` whose handlers receive `ctx.userId` and reject an unauthenticated caller. The app injects the four convex-helpers functions and its generated builders, so convex-helpers is an optional peer for types only. An optional `beforeEach` gate (for a maintenance check) runs before the user is resolved; internal variants come from a second call with the internal builders and no gate.
42
56
 
43
57
  ## 0.14.0
@@ -0,0 +1,185 @@
1
+ /**
2
+ * Clerk Billing Convex functions for apps that keep plan slugs on their own
3
+ * users table: an `applyBillingChange` mutation, a paged `listClerkIds` query
4
+ * and a `setPlanSlugs` mutation, plus `runClerkBillingWebhook` for the
5
+ * `POST /clerk/webhooks` route.
6
+ *
7
+ * Like `createExpoPushFunctions`, the package never imports `convex` at
8
+ * runtime. The app passes in `v` and its own function builders, and its bound
9
+ * `createVProModule` writer (`vPro.writeBillingChange`) does the write, so
10
+ * the table, index, field names and granting statuses stay with the app.
11
+ * Backfill actions need Node and live in `clerkBillingNodeFunctions.ts`.
12
+ */
13
+ import type { FunctionReference, PaginationOptions, RegisteredMutation, RegisteredQuery } from "convex/server";
14
+ import type { v as convexV, Validator } from "convex/values";
15
+ import type { ClerkBillingChange, ClerkWebhookEventLike } from "./clerkBilling.js";
16
+ import { type VerifyClerkWebhookOptions } from "./clerkWebhook.js";
17
+ type ConvexV = typeof convexV;
18
+ type Req<T> = Validator<T, "required", string>;
19
+ type Cursor = string | null;
20
+ /** The default table the list query pages through. */
21
+ export declare const CLERK_BILLING_USERS_TABLE = "users";
22
+ /** The default page size for list styles that do not take `numItems` from the caller. */
23
+ export declare const CLERK_BILLING_PAGE_SIZE = 100;
24
+ /**
25
+ * Argument and return shape of the list query. Each app keeps the shape its
26
+ * callers already use:
27
+ *
28
+ * - `"cursor"`: args `{ cursor }`, returns `{ clerkIds, isDone, continueCursor }`.
29
+ * - `"cursorAndNumItems"`: args `{ cursor, numItems }`, same return.
30
+ * - `"paginationOpts"`: args `{ paginationOpts }`, returns `{ clerkUserIds, continueCursor, isDone }`.
31
+ * - `"cursorNull"`: args `{ cursor }`, returns `{ clerkUserIds, cursor }`, where `cursor` is `null` when done.
32
+ */
33
+ export type ClerkBillingListStyle = "cursor" | "cursorAndNumItems" | "paginationOpts" | "cursorNull";
34
+ export type ClerkBillingListArgs<Style extends ClerkBillingListStyle> = Style extends "cursorAndNumItems" ? {
35
+ cursor: Cursor;
36
+ numItems: number;
37
+ } : Style extends "paginationOpts" ? {
38
+ paginationOpts: PaginationOptions;
39
+ } : {
40
+ cursor: Cursor;
41
+ };
42
+ export type ClerkBillingListResult<Style extends ClerkBillingListStyle> = Style extends "paginationOpts" ? {
43
+ clerkUserIds: string[];
44
+ continueCursor: string;
45
+ isDone: boolean;
46
+ } : Style extends "cursorNull" ? {
47
+ clerkUserIds: string[];
48
+ cursor: Cursor;
49
+ } : {
50
+ clerkIds: string[];
51
+ isDone: boolean;
52
+ continueCursor: string;
53
+ };
54
+ /** `internal.<module>.listClerkIds`. Annotate the thunk with it: an unannotated thunk makes `internal` refer to itself (TS7022). */
55
+ export type ClerkBillingListRef<Style extends ClerkBillingListStyle> = FunctionReference<"query", "internal", ClerkBillingListArgs<Style>, ClerkBillingListResult<Style>>;
56
+ /** `internal.<module>.applyBillingChange`. */
57
+ export type ClerkBillingApplyChangeRef = FunctionReference<"mutation", "internal", {
58
+ change: ClerkBillingChange;
59
+ }, boolean>;
60
+ /** `internal.<module>.setPlanSlugs`, the `{ clerkUserId, planSlugs }` mutation. */
61
+ export type ClerkBillingSetPlanSlugsRef = FunctionReference<"mutation", "internal", {
62
+ clerkUserId: string;
63
+ planSlugs: string[];
64
+ }, boolean>;
65
+ /** What the list query needs of a query ctx: `ctx.db.query(table).paginate(...)`. A Convex `QueryCtx` fits. */
66
+ export type ClerkBillingQueryCtx = {
67
+ db: {
68
+ query(table: string): {
69
+ paginate(opts: PaginationOptions): Promise<{
70
+ page: ReadonlyArray<Record<string, unknown>>;
71
+ isDone: boolean;
72
+ continueCursor: string;
73
+ }>;
74
+ };
75
+ };
76
+ };
77
+ type ValidatorsOf<T> = {
78
+ [K in keyof T]-?: Req<T[K]>;
79
+ };
80
+ type ApplyDef<Ctx> = {
81
+ args: {
82
+ change: Req<ClerkBillingChange>;
83
+ };
84
+ returns: Req<boolean>;
85
+ handler: (ctx: Ctx, args: {
86
+ change: ClerkBillingChange;
87
+ }) => Promise<boolean>;
88
+ };
89
+ type SetPlanSlugsArgs = {
90
+ clerkUserId: string;
91
+ planSlugs: string[];
92
+ };
93
+ type SetPlanSlugsDef<Ctx> = {
94
+ args: ValidatorsOf<SetPlanSlugsArgs>;
95
+ returns: Req<boolean>;
96
+ handler: (ctx: Ctx, args: SetPlanSlugsArgs) => Promise<boolean>;
97
+ };
98
+ type ListDef<Style extends ClerkBillingListStyle> = {
99
+ args: ValidatorsOf<ClerkBillingListArgs<Style>>;
100
+ returns: Req<ClerkBillingListResult<Style>>;
101
+ handler: (ctx: ClerkBillingQueryCtx, args: ClerkBillingListArgs<Style>) => Promise<ClerkBillingListResult<Style>>;
102
+ };
103
+ export type ClerkBillingFunctionsConfig<MutationCtx, Style extends ClerkBillingListStyle> = {
104
+ v: ConvexV;
105
+ /** The app's `internalMutation`, narrowed to the two calls made here. */
106
+ internalMutation: ((def: ApplyDef<MutationCtx>) => RegisteredMutation<"internal", {
107
+ change: ClerkBillingChange;
108
+ }, Promise<boolean>>) & ((def: SetPlanSlugsDef<MutationCtx>) => RegisteredMutation<"internal", SetPlanSlugsArgs, Promise<boolean>>);
109
+ internalQuery: (def: ListDef<Style>) => RegisteredQuery<"internal", ClerkBillingListArgs<Style>, Promise<ClerkBillingListResult<Style>>>;
110
+ /**
111
+ * The app's `vPro.writeBillingChange`. Annotate the ctx with your
112
+ * `MutationCtx`: `(ctx: MutationCtx, change) => vPro.writeBillingChange(ctx, change)`.
113
+ */
114
+ writeBillingChange: (ctx: MutationCtx, change: ClerkBillingChange) => Promise<boolean>;
115
+ /** Argument and return shape of `listClerkIds`. */
116
+ listStyle: Style;
117
+ /** The users table. Default `"users"`. */
118
+ table?: string;
119
+ /** The field that holds the Clerk user id, for example `"clerkId"` or `"clerkUserId"`. */
120
+ clerkIdField: string;
121
+ /**
122
+ * Skip rows whose id is missing or empty. Default `true`. Pass `false` when
123
+ * the field is required: a non-string value then throws.
124
+ */
125
+ skipFalsyClerkId?: boolean;
126
+ /** Rows per page for `"cursor"` and `"cursorNull"`. Default 100. The other styles take the size from the caller. */
127
+ pageSize?: number;
128
+ /** `paginationOptsValidator` from `convex/server`. Required for the `"paginationOpts"` style. */
129
+ paginationOptsValidator?: Req<PaginationOptions>;
130
+ };
131
+ /**
132
+ * The Clerk Billing functions. Export them from one module and rename on the way
133
+ * out to keep your function paths:
134
+ *
135
+ * ```ts
136
+ * export const { applyBillingChange, listClerkIds } = createClerkBillingFunctions({
137
+ * v,
138
+ * internalMutation,
139
+ * internalQuery,
140
+ * writeBillingChange: (ctx: MutationCtx, change) => vPro.writeBillingChange(ctx, change),
141
+ * listStyle: "cursor",
142
+ * clerkIdField: "clerkId",
143
+ * });
144
+ * ```
145
+ *
146
+ * `setPlanSlugs` is returned too. Export it only where callers need the
147
+ * `{ clerkUserId, planSlugs }` shape; a function that is not exported is not registered.
148
+ */
149
+ export declare function createClerkBillingFunctions<MutationCtx, Style extends ClerkBillingListStyle>(config: ClerkBillingFunctionsConfig<MutationCtx, Style>): {
150
+ applyBillingChange: RegisteredMutation<"internal", {
151
+ change: ClerkBillingChange;
152
+ }, Promise<boolean>>;
153
+ setPlanSlugs: RegisteredMutation<"internal", SetPlanSlugsArgs, Promise<boolean>>;
154
+ listClerkIds: RegisteredQuery<"internal", ClerkBillingListArgs<Style>, Promise<ClerkBillingListResult<Style>>>;
155
+ };
156
+ export type RunClerkBillingWebhookOptions<Event> = {
157
+ /** `verifyWebhook` from `@clerk/backend/webhooks`. Injected so this package does not import it. */
158
+ verifyWebhook: (request: Request, options: {
159
+ signingSecret: string;
160
+ }) => Promise<Event>;
161
+ /** `vPro.parseBillingEvent`. Return `null` for events that change no plan. */
162
+ parseBillingEvent: (event: Event) => ClerkBillingChange | null;
163
+ /** Writes the change, for example `(change) => ctx.runMutation(internal.billing.applyBillingChange, { change })`. */
164
+ applyChange: (change: ClerkBillingChange) => Promise<unknown>;
165
+ /** Status for a missing signing secret. Default 400, so Clerk retries. */
166
+ missingSecretStatus?: number;
167
+ /** Status for a failed signature check. Default 400. */
168
+ invalidStatus?: number;
169
+ /** Body for a failed signature check. Default `"Invalid webhook"`. */
170
+ invalidBody?: string;
171
+ /** Body for a missing secret. Default: `invalidBody`. */
172
+ missingSecretBody?: string;
173
+ /** When set, a rejection is logged with `console.error(logPrefix, reason, error)`. */
174
+ logPrefix?: string;
175
+ /** Passed to `verifyClerkWebhook`: a test `env` or `signingSecret`. */
176
+ verifyOptions?: VerifyClerkWebhookOptions;
177
+ };
178
+ /**
179
+ * Verify, parse and apply one Clerk Billing webhook. Answers 400 for a missing
180
+ * secret or a bad signature, 200 with no body when the event changes nothing
181
+ * or the change is applied. A throw from `applyChange` is not caught, so Clerk
182
+ * gets a 500 and retries.
183
+ */
184
+ export declare function runClerkBillingWebhook<Event extends ClerkWebhookEventLike>(request: Request, options: RunClerkBillingWebhookOptions<Event>): Promise<Response>;
185
+ export {};
@@ -0,0 +1,135 @@
1
+ import { verifyClerkWebhook } from "./clerkWebhook.js";
2
+ /** The default table the list query pages through. */
3
+ export const CLERK_BILLING_USERS_TABLE = "users";
4
+ /** The default page size for list styles that do not take `numItems` from the caller. */
5
+ export const CLERK_BILLING_PAGE_SIZE = 100;
6
+ /**
7
+ * The Clerk Billing functions. Export them from one module and rename on the way
8
+ * out to keep your function paths:
9
+ *
10
+ * ```ts
11
+ * export const { applyBillingChange, listClerkIds } = createClerkBillingFunctions({
12
+ * v,
13
+ * internalMutation,
14
+ * internalQuery,
15
+ * writeBillingChange: (ctx: MutationCtx, change) => vPro.writeBillingChange(ctx, change),
16
+ * listStyle: "cursor",
17
+ * clerkIdField: "clerkId",
18
+ * });
19
+ * ```
20
+ *
21
+ * `setPlanSlugs` is returned too. Export it only where callers need the
22
+ * `{ clerkUserId, planSlugs }` shape; a function that is not exported is not registered.
23
+ */
24
+ export function createClerkBillingFunctions(config) {
25
+ const { v, writeBillingChange } = config;
26
+ const table = config.table ?? CLERK_BILLING_USERS_TABLE;
27
+ const skipFalsy = config.skipFalsyClerkId ?? true;
28
+ const pageSize = config.pageSize ?? CLERK_BILLING_PAGE_SIZE;
29
+ const cursor = v.union(v.string(), v.null());
30
+ const applyBillingChange = config.internalMutation({
31
+ args: { change: changeValidator(v) },
32
+ returns: v.boolean(),
33
+ handler: (ctx, { change }) => writeBillingChange(ctx, change),
34
+ });
35
+ const setPlanSlugs = config.internalMutation({
36
+ args: { clerkUserId: v.string(), planSlugs: v.array(v.string()) },
37
+ returns: v.boolean(),
38
+ handler: (ctx, { clerkUserId, planSlugs }) => writeBillingChange(ctx, { kind: "replace", clerkId: clerkUserId, planSlugs }),
39
+ });
40
+ const clerkIdsOf = (rows) => rows.flatMap((row) => {
41
+ const id = row[config.clerkIdField];
42
+ if (typeof id === "string" && (id !== "" || !skipFalsy))
43
+ return [id];
44
+ if (skipFalsy)
45
+ return [];
46
+ throw new Error(`${table}.${config.clerkIdField} is not a string`);
47
+ });
48
+ const listClerkIds = config.internalQuery(listDef(config.listStyle, {
49
+ v,
50
+ cursor,
51
+ pageSize,
52
+ paginationOptsValidator: config.paginationOptsValidator,
53
+ read: async (ctx, opts) => {
54
+ const page = await ctx.db.query(table).paginate(opts);
55
+ return { ids: clerkIdsOf(page.page), isDone: page.isDone, continueCursor: page.continueCursor };
56
+ },
57
+ }));
58
+ return { applyBillingChange, setPlanSlugs, listClerkIds };
59
+ }
60
+ /** Validator for `ClerkBillingChange`. */
61
+ function changeValidator(v) {
62
+ // `v.union` of objects infers a type that is structurally `ClerkBillingChange`.
63
+ return v.union(v.object({ kind: v.literal("replace"), clerkId: v.string(), planSlugs: v.array(v.string()) }), v.object({ kind: v.literal("item"), clerkId: v.string(), status: v.string(), slug: v.string() }));
64
+ }
65
+ /**
66
+ * One definition per list style. The style decides the args, the page options
67
+ * and the return shape, so the table below is the whole list of differences.
68
+ */
69
+ function listDef(style, io) {
70
+ const { v, cursor, pageSize, read } = io;
71
+ // Each entry is a thunk, so only the requested style is built.
72
+ const defs = {
73
+ cursor: () => ({
74
+ args: { cursor },
75
+ returns: v.object({ clerkIds: v.array(v.string()), isDone: v.boolean(), continueCursor: v.string() }),
76
+ handler: async (ctx, args) => {
77
+ const page = await read(ctx, { numItems: pageSize, cursor: args.cursor });
78
+ return { clerkIds: page.ids, isDone: page.isDone, continueCursor: page.continueCursor };
79
+ },
80
+ }),
81
+ cursorAndNumItems: () => ({
82
+ args: { cursor, numItems: v.number() },
83
+ returns: v.object({ clerkIds: v.array(v.string()), continueCursor: v.string(), isDone: v.boolean() }),
84
+ handler: async (ctx, args) => {
85
+ const page = await read(ctx, { numItems: args.numItems, cursor: args.cursor });
86
+ return { clerkIds: page.ids, continueCursor: page.continueCursor, isDone: page.isDone };
87
+ },
88
+ }),
89
+ paginationOpts: () => ({
90
+ args: { paginationOpts: requirePaginationOptsValidator(io.paginationOptsValidator) },
91
+ returns: v.object({ clerkUserIds: v.array(v.string()), continueCursor: v.string(), isDone: v.boolean() }),
92
+ handler: async (ctx, args) => {
93
+ const page = await read(ctx, args.paginationOpts);
94
+ return { clerkUserIds: page.ids, continueCursor: page.continueCursor, isDone: page.isDone };
95
+ },
96
+ }),
97
+ cursorNull: () => ({
98
+ args: { cursor },
99
+ returns: v.object({ clerkUserIds: v.array(v.string()), cursor }),
100
+ handler: async (ctx, args) => {
101
+ const page = await read(ctx, { numItems: pageSize, cursor: args.cursor });
102
+ return { clerkUserIds: page.ids, cursor: page.isDone ? null : page.continueCursor };
103
+ },
104
+ }),
105
+ };
106
+ // `defs[style]()` is `ListDef<Style>`, but TypeScript widens the index to the union.
107
+ return defs[style]();
108
+ }
109
+ function requirePaginationOptsValidator(validator) {
110
+ if (!validator)
111
+ throw new Error('createClerkBillingFunctions: listStyle "paginationOpts" needs paginationOptsValidator');
112
+ return validator;
113
+ }
114
+ /**
115
+ * Verify, parse and apply one Clerk Billing webhook. Answers 400 for a missing
116
+ * secret or a bad signature, 200 with no body when the event changes nothing
117
+ * or the change is applied. A throw from `applyChange` is not caught, so Clerk
118
+ * gets a 500 and retries.
119
+ */
120
+ export async function runClerkBillingWebhook(request, options) {
121
+ const verified = await verifyClerkWebhook(options.verifyWebhook, request, options.verifyOptions);
122
+ if (!verified.ok) {
123
+ if (options.logPrefix)
124
+ console.error(options.logPrefix, verified.reason, verified.error);
125
+ const invalidBody = options.invalidBody ?? "Invalid webhook";
126
+ if (verified.reason === "missing-secret") {
127
+ return new Response(options.missingSecretBody ?? invalidBody, { status: options.missingSecretStatus ?? 400 });
128
+ }
129
+ return new Response(invalidBody, { status: options.invalidStatus ?? 400 });
130
+ }
131
+ const change = options.parseBillingEvent(verified.event);
132
+ if (change)
133
+ await options.applyChange(change);
134
+ return new Response(null, { status: 200 });
135
+ }
@@ -0,0 +1,169 @@
1
+ /**
2
+ * Node side of the Clerk Billing wiring: the `backfillPlanSlugs` action and
3
+ * the webhook action. They need `@clerk/backend` and Node APIs, so
4
+ * an app exports them from a `"use node"` file, apart from the V8 functions in
5
+ * `clerkBillingFunctions.ts`. The Clerk client and `verifyWebhook` are
6
+ * injected, so this package imports neither `convex` nor `@clerk/backend`.
7
+ */
8
+ import type { FunctionReference, RegisteredAction } from "convex/server";
9
+ import type { v as convexV, Validator } from "convex/values";
10
+ import { type ClerkBillingChange, type ClerkWebhookEventLike, type PlanItem } from "./clerkBilling.js";
11
+ import type { ClerkBillingApplyChangeRef, ClerkBillingListArgs, ClerkBillingListRef, ClerkBillingListResult, ClerkBillingListStyle, ClerkBillingSetPlanSlugsRef } from "./clerkBillingFunctions.js";
12
+ type ConvexV = typeof convexV;
13
+ type Req<T> = Validator<T, "required", string>;
14
+ type Cursor = string | null;
15
+ /** The part of the Clerk backend client that backfill reads. `createClerkClient(...)` fits. */
16
+ export type ClerkBillingClerkLike = {
17
+ billing: {
18
+ getUserBillingSubscription(userId: string): Promise<{
19
+ subscriptionItems: readonly PlanItem[];
20
+ }>;
21
+ };
22
+ };
23
+ /**
24
+ * What the backfill action returns, and so how it runs:
25
+ *
26
+ * - `"usersUpdated"`: one run walks every page. Returns `{ users, updated }`: ids seen, and rows the writer found.
27
+ * - `"syncedSkippedFailed"`: one run walks every page. Returns `{ synced, skipped, failed }`.
28
+ * - `"updatedSkipped"`: one run walks every page. Returns `{ updated, skipped }`.
29
+ * - `"null"`: one run handles one page, then schedules itself for the next (`backfillSelfRef`). Returns `null`.
30
+ */
31
+ export type ClerkBillingBackfillReturnStyle = "usersUpdated" | "syncedSkippedFailed" | "updatedSkipped" | "null";
32
+ export type ClerkBillingBackfillResult<Return extends ClerkBillingBackfillReturnStyle> = Return extends "usersUpdated" ? {
33
+ users: number;
34
+ updated: number;
35
+ } : Return extends "syncedSkippedFailed" ? {
36
+ synced: number;
37
+ skipped: number;
38
+ failed: number;
39
+ } : Return extends "updatedSkipped" ? {
40
+ updated: number;
41
+ skipped: number;
42
+ } : null;
43
+ /** Args of the backfill action: none for the walking styles, an optional `cursor` for `"null"`. */
44
+ export type ClerkBillingBackfillArgs<Return extends ClerkBillingBackfillReturnStyle> = Return extends "null" ? {
45
+ cursor?: Cursor | undefined;
46
+ } : Record<string, never>;
47
+ /** `internal.<module>.backfillPlanSlugs`, for the self-schedule of the `"null"` style. */
48
+ export type ClerkBillingBackfillSelfRef = FunctionReference<"action", "internal", {
49
+ cursor?: Cursor | undefined;
50
+ }, null>;
51
+ /** What the backfill needs of an action ctx. A Convex `ActionCtx` fits. */
52
+ export type ClerkBillingBackfillCtx<Style extends ClerkBillingListStyle> = {
53
+ runQuery(ref: ClerkBillingListRef<Style>, args: ClerkBillingListArgs<Style>): Promise<ClerkBillingListResult<Style>>;
54
+ runMutation(ref: ClerkBillingApplyChangeRef, args: {
55
+ change: ClerkBillingChange;
56
+ }): Promise<boolean>;
57
+ runMutation(ref: ClerkBillingSetPlanSlugsRef, args: {
58
+ clerkUserId: string;
59
+ planSlugs: string[];
60
+ }): Promise<boolean>;
61
+ scheduler: {
62
+ runAfter(delayMs: number, ref: ClerkBillingBackfillSelfRef, args: {
63
+ cursor: Cursor;
64
+ }): Promise<unknown>;
65
+ };
66
+ };
67
+ type BackfillDef<Style extends ClerkBillingListStyle, Return extends ClerkBillingBackfillReturnStyle> = {
68
+ args: {
69
+ [K in keyof ClerkBillingBackfillArgs<Return>]-?: Validator<ClerkBillingBackfillArgs<Return>[K], "optional", string>;
70
+ };
71
+ returns: Req<ClerkBillingBackfillResult<Return>>;
72
+ handler: (ctx: ClerkBillingBackfillCtx<Style>, args: ClerkBillingBackfillArgs<Return>) => Promise<ClerkBillingBackfillResult<Return>>;
73
+ };
74
+ type BackfillBuilder<Style extends ClerkBillingListStyle, Return extends ClerkBillingBackfillReturnStyle> = (def: BackfillDef<Style, Return>) => RegisteredAction<"internal", ClerkBillingBackfillArgs<Return>, Promise<ClerkBillingBackfillResult<Return>>>;
75
+ type ApplyConfig = {
76
+ /** Write through `applyBillingChange` with a `replace` change. Default. */
77
+ applyStyle?: "change";
78
+ applyBillingChangeRef: () => ClerkBillingApplyChangeRef;
79
+ } | {
80
+ /** Write through a `setPlanSlugs({ clerkUserId, planSlugs })`. */
81
+ applyStyle: "setPlanSlugs";
82
+ setPlanSlugsRef: () => ClerkBillingSetPlanSlugsRef;
83
+ };
84
+ type SelfConfig<Return extends ClerkBillingBackfillReturnStyle> = Return extends "null" ? {
85
+ backfillSelfRef: () => ClerkBillingBackfillSelfRef;
86
+ } : {
87
+ backfillSelfRef?: undefined;
88
+ };
89
+ export type ClerkBillingNodeFunctionsConfig<Style extends ClerkBillingListStyle, Return extends ClerkBillingBackfillReturnStyle> = {
90
+ v: ConvexV;
91
+ internalAction: BackfillBuilder<Style, Return>;
92
+ /** The list style the app gave `createClerkBillingFunctions`. It decides the page args and how the result is read. */
93
+ listStyle: Style;
94
+ /** Result shape and run mode. See `ClerkBillingBackfillReturnStyle`. */
95
+ returnStyle: Return;
96
+ /** `(): ClerkBillingListRef<"cursor"> => internal.billing.listClerkIds`. */
97
+ listClerkIdsRef: () => ClerkBillingListRef<Style>;
98
+ /** Builds the Clerk client when the action starts. */
99
+ getClerkClient: () => ClerkBillingClerkLike;
100
+ /** Rows per page for the list styles that do not take `numItems` from the caller. Default 100. */
101
+ pageSize?: number;
102
+ /** Item statuses that grant a plan. Default: the package default (`GRANTING_ITEM_STATUSES`). */
103
+ grantingStatuses?: readonly string[];
104
+ /**
105
+ * A user Clerk answers 404 for (never subscribed). `"emptySlugs"` writes an
106
+ * empty set; `"skip"` leaves the row alone and counts it as skipped. Default `"emptySlugs"`.
107
+ */
108
+ onNotFound?: "emptySlugs" | "skip";
109
+ /**
110
+ * A user whose Clerk call or write fails with something other than a 404.
111
+ * `"throw"` stops the run. `"log"` calls `onUserError` and counts it as failed.
112
+ * `"skip"` counts it as skipped with no log. Default `"throw"`.
113
+ */
114
+ onError?: "throw" | "log" | "skip";
115
+ /** Called for each `"log"` failure. Default `console.error("[backfillPlanSlugs]", clerkId, error)`. */
116
+ onUserError?: (clerkId: string, error: unknown) => void;
117
+ /** Called with the result when a walking run ends, for a summary log. */
118
+ onFinished?: (result: ClerkBillingBackfillResult<Return>) => void;
119
+ } & ApplyConfig & SelfConfig<Return>;
120
+ /**
121
+ * The backfill action.
122
+ *
123
+ * ```ts
124
+ * export const { backfillPlanSlugs } = createClerkBillingNodeFunctions({
125
+ * v,
126
+ * internalAction,
127
+ * listStyle: "cursor",
128
+ * returnStyle: "usersUpdated",
129
+ * listClerkIdsRef: (): ClerkBillingListRef<"cursor"> => internal.billing.listClerkIds,
130
+ * applyBillingChangeRef: (): ClerkBillingApplyChangeRef => internal.billing.applyBillingChange,
131
+ * getClerkClient: () => createClerkClient({ secretKey: process.env.CLERK_SECRET_KEY }),
132
+ * });
133
+ * ```
134
+ */
135
+ export declare function createClerkBillingNodeFunctions<Style extends ClerkBillingListStyle, Return extends ClerkBillingBackfillReturnStyle>(config: ClerkBillingNodeFunctionsConfig<Style, Return>): {
136
+ backfillPlanSlugs: RegisteredAction<"internal", ClerkBillingBackfillArgs<Return>, Promise<ClerkBillingBackfillResult<Return>>>;
137
+ };
138
+ type WebhookArgs = {
139
+ body: string;
140
+ id: string;
141
+ timestamp: string;
142
+ signature: string;
143
+ };
144
+ export type ClerkBillingWebhookNodeActionConfig<Event extends ClerkWebhookEventLike, Ctx> = {
145
+ v: ConvexV;
146
+ internalAction: (def: {
147
+ args: {
148
+ [K in keyof WebhookArgs]: Req<string>;
149
+ };
150
+ returns: Req<boolean>;
151
+ handler: (ctx: Ctx, args: WebhookArgs) => Promise<boolean>;
152
+ }) => RegisteredAction<"internal", WebhookArgs, Promise<boolean>>;
153
+ /** `verifyWebhook` from `@clerk/backend/webhooks`. */
154
+ verifyWebhook: (request: Request, options: {
155
+ signingSecret: string;
156
+ }) => Promise<Event>;
157
+ /** `vPro.parseBillingEvent`. */
158
+ parseBillingEvent: (event: Event) => ClerkBillingChange | null;
159
+ /** Writes the change: `(ctx: ActionCtx, change) => ctx.runMutation(internal.clerk.billing.applyBillingChange, { change })`. */
160
+ applyChange: (ctx: Ctx, change: ClerkBillingChange) => Promise<unknown>;
161
+ /** The URL of the rebuilt request. Verification ignores it. Default `"https://convex.invalid/clerk/webhooks"`. */
162
+ url?: string;
163
+ };
164
+ /**
165
+ * `verifyAndApplyWebhook`: returns `false` when the secret is missing or the
166
+ * signature check fails, and `true` once the event is handled.
167
+ */
168
+ export declare function createClerkBillingWebhookNodeAction<Event extends ClerkWebhookEventLike, Ctx>(config: ClerkBillingWebhookNodeActionConfig<Event, Ctx>): RegisteredAction<"internal", WebhookArgs, Promise<boolean>>;
169
+ export {};