@vvedantb/server 0.12.0 → 0.14.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,37 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.14.0
4
+
5
+ Reusable Expo push notification helpers, generalised from an app's own push code. Additive; nothing in 0.13.0 changes. `convex` is used for types only and `zod` is not needed.
6
+
7
+ ### Added
8
+
9
+ - `createExpoPushFunctions({ v, userId, mutation, internalQuery, internalMutation, internalAction, requireCurrentUserId, listTokensRef, removeTokensRef, sendRef, checkReceiptsRef, tableName?, receiptDelayMs?, fetch?, accessToken? })` returns `register`, `unregister`, `listTokensForUser`, `removeTokens`, `send`, `checkReceipts` and a bound `schedulePush`. `requireCurrentUserId` takes `createClerkUserAuth(...).requireCurrentUserId`.
10
+ - Table helpers `pushTokensFields(v, userId?)` and `pushTokensTable(defineTable, v, userId?)` (deprecated for schema use, as the MCP token cache), constants `PUSH_TOKENS_TABLE` (`"pushTokens"`), `PUSH_TOKENS_USER_INDEX` (`by_user`) and `PUSH_TOKENS_TOKEN_INDEX` (`by_token`). Apps copy the table into their own schema (`NoImportModuleInSchema`).
11
+ - `register` validates tokens against `EXPO_PUSH_TOKEN_PATTERN` and upserts by token; `unregister` deletes only the caller's row.
12
+ - `send` posts to the Expo Push API in batches of `EXPO_PUSH_BATCH_SIZE` (100), removes `DeviceNotRegistered` tokens from tickets and schedules `checkReceipts` after `EXPO_RECEIPT_DELAY_MS` (15 minutes, set with `receiptDelayMs`). `checkReceipts` fetches receipts (1000 ids per request, `EXPO_RECEIPT_BATCH_SIZE`) and removes `DeviceNotRegistered` tokens. Only that error removes a token.
13
+ - Plain helpers with an injectable `fetch`: `sendExpoPushMessages`, `fetchExpoPushReceipts`, `tokensToRemoveFromTickets`, `receiptRefsFromTickets`, `tokensToRemoveFromReceipts`, `parseExpoTickets`, `parseExpoReceipts`, `isExpoPushToken`, `isDeviceNotRegistered`; constants `EXPO_PUSH_SEND_URL` and `EXPO_PUSH_RECEIPTS_URL`; a standalone `schedulePush(ctx, params, { sendRef, tableName })`.
14
+ - Docs: "Expo push notifications" in `docs/convex.md`.
15
+
16
+ ### Tests
17
+
18
+ - `tests/convex/expoPush.test.ts` (12, mocked `fetch`, fake in-memory db): schema helpers, register upsert and takeover, invalid token, unregister ownership, batching (250 tokens, 3 calls), ticket and receipt cleanup, `schedulePush` no-op. `tests/convex/expoPush.types.ts` checks the factory against real Convex builders. `tests-node/esm-exports.mjs` checks the new exports.
19
+
20
+ ## 0.13.0
21
+
22
+ Optional `title`, `websiteUrl` and `icons` in MCP `serverInfo` (MCP 2025-11-25 `Implementation`), so MCP clients can show an app's name and icon. Additive; nothing in 0.12.0 changes. `defineMcpServerInfo({ name, version })` returns the same object as before.
23
+
24
+ ### Added
25
+
26
+ - `defineMcpServerInfo` takes optional `title`, `websiteUrl` and `icons`. Each is included only when passed; no `undefined` keys. Icons are copied as given, with no `mimeType`, `sizes` or `theme` invented. An icon with an empty `src` throws. `name` and `version` checks are unchanged.
27
+ - Type `McpServerIcon` (`{ src, mimeType?, sizes?, theme? }`, `theme` is `"light"` or `"dark"`). `McpServerInfo` gains the optional fields.
28
+ - `createMcpDispatcher` already returns `serverInfo` as given, so the optional fields reach the initialize result with no dispatcher change.
29
+
30
+ ### Tests
31
+
32
+ - `defineMcpServerInfo`: title, websiteUrl and icons included when passed, omitted when not, and empty icon `src` rejected.
33
+ - Dispatcher: an initialize result carries `title`, `websiteUrl` and `icons`.
34
+
3
35
  ## 0.12.0
4
36
 
5
37
  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.)
package/README.md CHANGED
@@ -18,7 +18,7 @@ The one subpath export is `./ai` (0.11.0). The root does not re-export it, so a
18
18
 
19
19
  | Area | What it holds | Docs |
20
20
  | --- | --- | --- |
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) |
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, and Expo push notifications (`createExpoPushFunctions`: token table helpers, `register`/`unregister`, batched send, receipts, `schedulePush`). | [docs/convex.md](docs/convex.md#expo-push-notifications) |
22
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) |
23
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) |
24
24
  | Optimistic updates | `mapLoadedQuery` (also `forEachLoadedQuery`, `updateAllCachedQueries`), `patchLoadedQuery`, `tempId`, `createMemoryOptimisticStore`. Client-side, no React. | [docs/convex.md](docs/convex.md#optimistic-updates-client-side) |
@@ -0,0 +1,349 @@
1
+ /**
2
+ * Expo push notifications for Convex apps: a device-token table, `register`
3
+ * and `unregister` mutations, a batched send through the Expo Push API, and
4
+ * push receipts that drop dead tokens.
5
+ *
6
+ * The package cannot own a Convex table and never imports `convex` at
7
+ * runtime, so the app defines the table in its own schema and passes in `v`,
8
+ * its function builders and `requireCurrentUserId`. The HTTP side
9
+ * (`sendExpoPushMessages`, `fetchExpoPushReceipts` and the token-cleanup
10
+ * helpers) is plain TypeScript that runs in Node and tests with no Convex.
11
+ */
12
+ import type { defineTable as convexDefineTable, FunctionReference, IndexRange, RegisteredAction, RegisteredMutation, RegisteredQuery } from "convex/server";
13
+ import type { v as convexV, GenericId, Validator } from "convex/values";
14
+ /** The default table name. */
15
+ export declare const PUSH_TOKENS_TABLE = "pushTokens";
16
+ export declare const PUSH_TOKENS_USER_INDEX = "by_user";
17
+ export declare const PUSH_TOKENS_TOKEN_INDEX = "by_token";
18
+ export declare const EXPO_PUSH_SEND_URL = "https://exp.host/--/api/v2/push/send";
19
+ export declare const EXPO_PUSH_RECEIPTS_URL = "https://exp.host/--/api/v2/push/getReceipts";
20
+ /** Messages per send request. Expo rejects larger batches. */
21
+ export declare const EXPO_PUSH_BATCH_SIZE = 100;
22
+ /** Receipt ids per `getReceipts` request. Expo accepts up to 1000. */
23
+ export declare const EXPO_RECEIPT_BATCH_SIZE = 1000;
24
+ /** Default wait before `send` checks receipts. Expo advises about 15 minutes. */
25
+ export declare const EXPO_RECEIPT_DELAY_MS: number;
26
+ /** `ExponentPushToken[...]` or `ExpoPushToken[...]`. */
27
+ export declare const EXPO_PUSH_TOKEN_PATTERN: RegExp;
28
+ export type PushPlatform = "android" | "ios";
29
+ /** The `data` object a push carries to the app. Expo needs a JSON object. */
30
+ export type ExpoPushData = Record<string, unknown>;
31
+ type ConvexV = typeof convexV;
32
+ export declare function isExpoPushToken(token: string): boolean;
33
+ /** A row to write. `UserId` is the app's user id type, for example `Id<"users">`. */
34
+ export type PushTokenRow<UserId = string> = {
35
+ userId: UserId;
36
+ token: string;
37
+ platform: PushPlatform;
38
+ updatedAt: number;
39
+ };
40
+ /**
41
+ * The table's fields: `userId` (pass `v.id("users")` for your users table, or
42
+ * leave it as `v.string()`), `token`, `platform` (`"android"` | `"ios"`) and
43
+ * `updatedAt` (ms).
44
+ *
45
+ * Do not import in `convex/schema.ts` (NoImportModuleInSchema). Use in tests to
46
+ * check your local table matches. See `docs/convex.md`.
47
+ */
48
+ export declare function pushTokensFields(v: ConvexV, userId?: Validator<any, "required", string>): {
49
+ userId: Validator<any, "required", string>;
50
+ token: import("convex/values").VString<string, "required">;
51
+ platform: import("convex/values").VUnion<"android" | "ios", [import("convex/values").VLiteral<"android", "required">, import("convex/values").VLiteral<"ios", "required">], "required", never>;
52
+ updatedAt: import("convex/values").VFloat64<number, "required">;
53
+ };
54
+ /**
55
+ * The table with both indexes (`by_user`, `by_token`).
56
+ *
57
+ * @deprecated Do not call in `convex/schema.ts`: a schema cannot import the
58
+ * package (NoImportModuleInSchema). Define the table locally and use this in
59
+ * tests to check your local table matches. See `docs/convex.md`.
60
+ */
61
+ export declare function pushTokensTable(defineTable: typeof convexDefineTable, v: ConvexV, userId?: Validator<any, "required", string>): import("convex/server").TableDefinition<import("convex/values").VObject<{
62
+ updatedAt: number;
63
+ token: string;
64
+ userId: any;
65
+ platform: "android" | "ios";
66
+ }, {
67
+ userId: Validator<any, "required", string>;
68
+ token: import("convex/values").VString<string, "required">;
69
+ platform: import("convex/values").VUnion<"android" | "ios", [import("convex/values").VLiteral<"android", "required">, import("convex/values").VLiteral<"ios", "required">], "required", never>;
70
+ updatedAt: import("convex/values").VFloat64<number, "required">;
71
+ }, "required", "updatedAt" | "token" | "userId" | "platform" | `userId.${string}`>, {
72
+ by_user: ["userId", "_creationTime"];
73
+ by_token: ["token", "_creationTime"];
74
+ }, {}, {}>;
75
+ export type ExpoPushMessage = {
76
+ to: string;
77
+ title: string;
78
+ body?: string;
79
+ sound: "default";
80
+ priority: "high";
81
+ data?: ExpoPushData;
82
+ };
83
+ type ExpoErrorDetails = {
84
+ error?: string;
85
+ };
86
+ /** A ticket, in request order. An `ok` ticket carries the receipt `id`. */
87
+ export type ExpoPushTicket = {
88
+ status: "ok";
89
+ id?: string;
90
+ } | {
91
+ status: "error";
92
+ message?: string;
93
+ details?: ExpoErrorDetails;
94
+ };
95
+ /** A receipt, keyed by ticket id in the `getReceipts` response. */
96
+ export type ExpoPushReceipt = {
97
+ status: "ok";
98
+ } | {
99
+ status: "error";
100
+ message?: string;
101
+ details?: ExpoErrorDetails;
102
+ };
103
+ /** A token with the ticket Expo returned for it. */
104
+ export type ExpoPushSendResult = {
105
+ token: string;
106
+ ticket: ExpoPushTicket;
107
+ };
108
+ /** A receipt id with the token it was issued for. */
109
+ export type ExpoPushReceiptRef = {
110
+ id: string;
111
+ token: string;
112
+ };
113
+ export type ExpoPushHttpOptions = {
114
+ /** Default: the global `fetch`, read at call time. */
115
+ fetch?: typeof fetch;
116
+ /** Expo access token, when the project enforces enhanced push security. */
117
+ accessToken?: string;
118
+ };
119
+ export type SendExpoPushMessagesOptions = ExpoPushHttpOptions & {
120
+ tokens: readonly string[];
121
+ title: string;
122
+ body?: string;
123
+ data?: ExpoPushData;
124
+ };
125
+ /** The `data` array of a send response, or `null` when it is not one ticket per message. */
126
+ export declare function parseExpoTickets(json: unknown, expected: number): ExpoPushTicket[] | null;
127
+ /** The `data` map of a `getReceipts` response. Entries that do not parse are skipped. */
128
+ export declare function parseExpoReceipts(json: unknown): Record<string, ExpoPushReceipt> | null;
129
+ /**
130
+ * Sends one message per token, in batches of `EXPO_PUSH_BATCH_SIZE`. Returns
131
+ * a ticket for each token Expo answered for. A batch that fails (network
132
+ * error, non-2xx or an unexpected body) is logged and left out, so the other
133
+ * batches still count.
134
+ */
135
+ export declare function sendExpoPushMessages(options: SendExpoPushMessagesOptions): Promise<ExpoPushSendResult[]>;
136
+ /**
137
+ * Fetches receipts for the given ids, in batches of `EXPO_RECEIPT_BATCH_SIZE`.
138
+ * Ids Expo has no receipt for yet are missing from the result. A failed batch
139
+ * is logged and left out.
140
+ */
141
+ export declare function fetchExpoPushReceipts(ids: readonly string[], options?: ExpoPushHttpOptions): Promise<Record<string, ExpoPushReceipt>>;
142
+ /** `DeviceNotRegistered`: the app was uninstalled or the token expired, so stop sending to it. */
143
+ export declare function isDeviceNotRegistered(outcome: ExpoPushTicket | ExpoPushReceipt): boolean;
144
+ /**
145
+ * Tokens whose ticket says `DeviceNotRegistered`, without duplicates. Other
146
+ * errors (`MessageTooBig`, `MessageRateExceeded`, `InvalidCredentials`) say
147
+ * nothing about the token, so they never remove one.
148
+ */
149
+ export declare function tokensToRemoveFromTickets(results: readonly ExpoPushSendResult[]): string[];
150
+ /** The receipt ids of `ok` tickets, each with its token. */
151
+ export declare function receiptRefsFromTickets(results: readonly ExpoPushSendResult[]): ExpoPushReceiptRef[];
152
+ /** Tokens whose receipt says `DeviceNotRegistered`, without duplicates. */
153
+ export declare function tokensToRemoveFromReceipts(receipts: Record<string, ExpoPushReceipt>, refs: readonly ExpoPushReceiptRef[]): string[];
154
+ /** A push token document. */
155
+ export type PushTokenDoc<UserId, Id> = PushTokenRow<UserId> & {
156
+ _id: Id;
157
+ _creationTime: number;
158
+ };
159
+ type PushTokenPatch<UserId> = Omit<PushTokenRow<UserId>, "token">;
160
+ type PushIndexes<UserId, Doc, Range> = {
161
+ withIndex(index: typeof PUSH_TOKENS_USER_INDEX, range: (q: {
162
+ eq(field: "userId", value: UserId): Range;
163
+ }) => Range): {
164
+ first(): Promise<Doc | null>;
165
+ collect(): Promise<Doc[]>;
166
+ };
167
+ withIndex(index: typeof PUSH_TOKENS_TOKEN_INDEX, range: (q: {
168
+ eq(field: "token", value: string): Range;
169
+ }) => Range): {
170
+ first(): Promise<Doc | null>;
171
+ };
172
+ };
173
+ export type PushQueryCtx<Table extends string, UserId, Id = GenericId<Table>, Range = IndexRange> = {
174
+ db: {
175
+ query(table: Table): PushIndexes<UserId, PushTokenDoc<UserId, Id>, Range>;
176
+ };
177
+ };
178
+ export type PushMutationCtx<Table extends string, UserId, Id = GenericId<Table>, Range = IndexRange> = {
179
+ db: {
180
+ query(table: Table): PushIndexes<UserId, PushTokenDoc<UserId, Id>, Range>;
181
+ insert(table: Table, value: PushTokenRow<UserId>): Promise<Id>;
182
+ patch(id: Id, value: PushTokenPatch<UserId>): Promise<void>;
183
+ delete(id: Id): Promise<void>;
184
+ };
185
+ };
186
+ export type PushSendParams<UserId> = {
187
+ userId: UserId;
188
+ title: string;
189
+ body?: string;
190
+ data?: ExpoPushData;
191
+ };
192
+ type RegisterArgs = {
193
+ token: string;
194
+ platform: PushPlatform;
195
+ };
196
+ type UnregisterArgs = {
197
+ token: string;
198
+ };
199
+ type ListTokensArgs<UserId> = {
200
+ userId: UserId;
201
+ };
202
+ type RemoveTokensArgs = {
203
+ tokens: string[];
204
+ };
205
+ type CheckReceiptsArgs = {
206
+ receipts: ExpoPushReceiptRef[];
207
+ };
208
+ /**
209
+ * `internal.<module>.send`. Annotate the thunk with it: an unannotated thunk
210
+ * makes `internal` refer to itself (TS7022).
211
+ */
212
+ export type ExpoPushSendRef<UserId> = FunctionReference<"action", "internal", PushSendParams<UserId>>;
213
+ export type ExpoPushListTokensRef<UserId> = FunctionReference<"query", "internal", ListTokensArgs<UserId>, string[]>;
214
+ export type ExpoPushRemoveTokensRef = FunctionReference<"mutation", "internal", RemoveTokensArgs>;
215
+ export type ExpoPushCheckReceiptsRef = FunctionReference<"action", "internal", CheckReceiptsArgs>;
216
+ /** What `schedulePush` needs of a mutation ctx: `ctx.db` reads and `ctx.scheduler`. */
217
+ export type SchedulePushCtx<Table extends string, UserId, Id = GenericId<Table>, Range = IndexRange> = PushQueryCtx<Table, UserId, Id, Range> & {
218
+ scheduler: {
219
+ runAfter(delayMs: number, fn: ExpoPushSendRef<UserId>, args: PushSendParams<UserId>): Promise<unknown>;
220
+ };
221
+ };
222
+ /**
223
+ * Queues a push to every device of `params.userId`. Skips the action when the
224
+ * user has no token. Call it from a mutation; the factory also returns it
225
+ * with `sendRef` and `tableName` already bound.
226
+ */
227
+ export declare function schedulePush<Table extends string, UserId, Id, Range>(ctx: SchedulePushCtx<Table, UserId, Id, Range>, params: PushSendParams<UserId>, options: {
228
+ sendRef: ExpoPushSendRef<UserId>;
229
+ tableName: Table;
230
+ }): Promise<void>;
231
+ type ActionRunCtx<UserId> = {
232
+ runQuery(ref: ExpoPushListTokensRef<UserId>, args: ListTokensArgs<UserId>): Promise<string[]>;
233
+ runMutation(ref: ExpoPushRemoveTokensRef, args: RemoveTokensArgs): Promise<unknown>;
234
+ scheduler: {
235
+ runAfter(delayMs: number, fn: ExpoPushCheckReceiptsRef, args: CheckReceiptsArgs): Promise<unknown>;
236
+ };
237
+ };
238
+ type Req<T> = Validator<T, "required", string>;
239
+ type Opt<T> = Validator<T | undefined, "optional", string>;
240
+ type PlatformValidator = Req<PushPlatform>;
241
+ type RegisterDef<Ctx> = {
242
+ args: {
243
+ token: Req<string>;
244
+ platform: PlatformValidator;
245
+ };
246
+ returns: Req<null>;
247
+ handler: (ctx: Ctx, args: RegisterArgs) => Promise<null>;
248
+ };
249
+ type UnregisterDef<Ctx> = {
250
+ args: {
251
+ token: Req<string>;
252
+ };
253
+ returns: Req<null>;
254
+ handler: (ctx: Ctx, args: UnregisterArgs) => Promise<null>;
255
+ };
256
+ type ListTokensDef<Ctx, UserId> = {
257
+ args: {
258
+ userId: Req<UserId>;
259
+ };
260
+ returns: Req<string[]>;
261
+ handler: (ctx: Ctx, args: ListTokensArgs<UserId>) => Promise<string[]>;
262
+ };
263
+ type RemoveTokensDef<Ctx> = {
264
+ args: {
265
+ tokens: Req<string[]>;
266
+ };
267
+ returns: Req<null>;
268
+ handler: (ctx: Ctx, args: RemoveTokensArgs) => Promise<null>;
269
+ };
270
+ type SendDef<Ctx, UserId> = {
271
+ args: {
272
+ userId: Req<UserId>;
273
+ title: Req<string>;
274
+ body: Opt<string>;
275
+ data: Opt<ExpoPushData>;
276
+ };
277
+ returns: Req<null>;
278
+ handler: (ctx: Ctx, args: PushSendParams<UserId>) => Promise<null>;
279
+ };
280
+ type CheckReceiptsDef<Ctx> = {
281
+ args: {
282
+ receipts: Req<ExpoPushReceiptRef[]>;
283
+ };
284
+ returns: Req<null>;
285
+ handler: (ctx: Ctx, args: CheckReceiptsArgs) => Promise<null>;
286
+ };
287
+ export type ExpoPushFunctionsConfig<Table extends string, UserId, Id, Range, MutationCtx extends PushMutationCtx<Table, UserId, Id, Range>, ActionCtx extends ActionRunCtx<UserId>> = {
288
+ v: ConvexV;
289
+ /** The validator for user ids, for example `v.id("users")`. It sets `UserId`. */
290
+ userId: Req<UserId>;
291
+ /** The app's public `mutation`, narrowed to the two calls made here. */
292
+ mutation: ((def: RegisterDef<MutationCtx>) => RegisteredMutation<"public", RegisterArgs, Promise<null>>) & ((def: UnregisterDef<MutationCtx>) => RegisteredMutation<"public", UnregisterArgs, Promise<null>>);
293
+ internalQuery: (def: ListTokensDef<PushQueryCtx<NoInfer<Table>, UserId, Id, Range>, UserId>) => RegisteredQuery<"internal", ListTokensArgs<UserId>, Promise<string[]>>;
294
+ internalMutation: (def: RemoveTokensDef<PushMutationCtx<NoInfer<Table>, UserId, Id, Range>>) => RegisteredMutation<"internal", RemoveTokensArgs, Promise<null>>;
295
+ internalAction: ((def: SendDef<ActionCtx, UserId>) => RegisteredAction<"internal", PushSendParams<UserId>, Promise<null>>) & ((def: CheckReceiptsDef<ActionCtx>) => RegisteredAction<"internal", CheckReceiptsArgs, Promise<null>>);
296
+ /**
297
+ * The signed-in user's id, throwing when there is none. Annotate the ctx
298
+ * with your `MutationCtx`: `(ctx: MutationCtx) => userAuth.requireCurrentUserId(ctx)`.
299
+ */
300
+ requireCurrentUserId: (ctx: MutationCtx) => Promise<UserId>;
301
+ /** `(): ExpoPushListTokensRef<Id<"users">> => internal.push.listTokensForUser`. */
302
+ listTokensRef: () => ExpoPushListTokensRef<UserId>;
303
+ removeTokensRef: () => ExpoPushRemoveTokensRef;
304
+ sendRef: () => ExpoPushSendRef<UserId>;
305
+ checkReceiptsRef: () => ExpoPushCheckReceiptsRef;
306
+ /** The tokens table. Default `"pushTokens"`; it needs both indexes. */
307
+ tableName?: Table;
308
+ /** Wait before receipts are checked. Default `EXPO_RECEIPT_DELAY_MS` (15 minutes). */
309
+ receiptDelayMs?: number;
310
+ /** For `fetch` in tests. Default: the global `fetch`. */
311
+ fetch?: typeof fetch;
312
+ /** Read at send time, so it can come from `process.env`. Sent as a bearer token. */
313
+ accessToken?: () => string | undefined;
314
+ };
315
+ /**
316
+ * The push functions. Export them from one module, here `convex/push.ts`:
317
+ *
318
+ * ```ts
319
+ * export const { register, unregister, listTokensForUser, removeTokens, send, checkReceipts, schedulePush } =
320
+ * createExpoPushFunctions({
321
+ * v,
322
+ * userId: v.id("users"),
323
+ * mutation,
324
+ * internalQuery,
325
+ * internalMutation,
326
+ * internalAction,
327
+ * requireCurrentUserId: (ctx: MutationCtx) => userAuth.requireCurrentUserId(ctx),
328
+ * listTokensRef: (): ExpoPushListTokensRef<Id<"users">> => internal.push.listTokensForUser,
329
+ * removeTokensRef: (): ExpoPushRemoveTokensRef => internal.push.removeTokens,
330
+ * sendRef: (): ExpoPushSendRef<Id<"users">> => internal.push.send,
331
+ * checkReceiptsRef: (): ExpoPushCheckReceiptsRef => internal.push.checkReceipts,
332
+ * });
333
+ * ```
334
+ *
335
+ * `send` lists the user's tokens, sends in batches, removes tokens whose
336
+ * ticket says `DeviceNotRegistered`, then schedules `checkReceipts` to do the
337
+ * same for receipts. `schedulePush` is the bound helper to call from your
338
+ * mutations.
339
+ */
340
+ export declare function createExpoPushFunctions<Table extends string = typeof PUSH_TOKENS_TABLE, UserId = string, Id = GenericId<Table>, Range = IndexRange, MutationCtx extends PushMutationCtx<Table, UserId, Id, Range> = PushMutationCtx<Table, UserId, Id, Range>, ActionCtx extends ActionRunCtx<UserId> = ActionRunCtx<UserId>>(config: ExpoPushFunctionsConfig<Table, UserId, Id, Range, MutationCtx, ActionCtx>): {
341
+ schedulePush: (ctx: SchedulePushCtx<Table, UserId, Id, Range>, params: PushSendParams<UserId>) => Promise<void>;
342
+ register: RegisteredMutation<"public", RegisterArgs, Promise<null>>;
343
+ unregister: RegisteredMutation<"public", UnregisterArgs, Promise<null>>;
344
+ listTokensForUser: RegisteredQuery<"internal", ListTokensArgs<UserId>, Promise<string[]>>;
345
+ removeTokens: RegisteredMutation<"internal", RemoveTokensArgs, Promise<null>>;
346
+ send: RegisteredAction<"internal", PushSendParams<UserId>, Promise<null>>;
347
+ checkReceipts: RegisteredAction<"internal", CheckReceiptsArgs, Promise<null>>;
348
+ };
349
+ export {};
@@ -0,0 +1,354 @@
1
+ /** The default table name. */
2
+ export const PUSH_TOKENS_TABLE = "pushTokens";
3
+ export const PUSH_TOKENS_USER_INDEX = "by_user";
4
+ export const PUSH_TOKENS_TOKEN_INDEX = "by_token";
5
+ export const EXPO_PUSH_SEND_URL = "https://exp.host/--/api/v2/push/send";
6
+ export const EXPO_PUSH_RECEIPTS_URL = "https://exp.host/--/api/v2/push/getReceipts";
7
+ /** Messages per send request. Expo rejects larger batches. */
8
+ export const EXPO_PUSH_BATCH_SIZE = 100;
9
+ /** Receipt ids per `getReceipts` request. Expo accepts up to 1000. */
10
+ export const EXPO_RECEIPT_BATCH_SIZE = 1000;
11
+ /** Default wait before `send` checks receipts. Expo advises about 15 minutes. */
12
+ export const EXPO_RECEIPT_DELAY_MS = 15 * 60 * 1000;
13
+ /** `ExponentPushToken[...]` or `ExpoPushToken[...]`. */
14
+ export const EXPO_PUSH_TOKEN_PATTERN = /^Expo(nent)?PushToken\[.+\]$/;
15
+ export function isExpoPushToken(token) {
16
+ return EXPO_PUSH_TOKEN_PATTERN.test(token);
17
+ }
18
+ /**
19
+ * The table's fields: `userId` (pass `v.id("users")` for your users table, or
20
+ * leave it as `v.string()`), `token`, `platform` (`"android"` | `"ios"`) and
21
+ * `updatedAt` (ms).
22
+ *
23
+ * Do not import in `convex/schema.ts` (NoImportModuleInSchema). Use in tests to
24
+ * check your local table matches. See `docs/convex.md`.
25
+ */
26
+ export function pushTokensFields(v, userId = v.string()) {
27
+ return {
28
+ userId,
29
+ token: v.string(),
30
+ platform: v.union(v.literal("android"), v.literal("ios")),
31
+ updatedAt: v.number(),
32
+ };
33
+ }
34
+ /**
35
+ * The table with both indexes (`by_user`, `by_token`).
36
+ *
37
+ * @deprecated Do not call in `convex/schema.ts`: a schema cannot import the
38
+ * package (NoImportModuleInSchema). Define the table locally and use this in
39
+ * tests to check your local table matches. See `docs/convex.md`.
40
+ */
41
+ export function pushTokensTable(defineTable, v, userId = v.string()) {
42
+ return defineTable(pushTokensFields(v, userId))
43
+ .index(PUSH_TOKENS_USER_INDEX, ["userId"])
44
+ .index(PUSH_TOKENS_TOKEN_INDEX, ["token"]);
45
+ }
46
+ function isRecord(value) {
47
+ return typeof value === "object" && value !== null && !Array.isArray(value);
48
+ }
49
+ function parseDetails(value) {
50
+ if (!isRecord(value))
51
+ return undefined;
52
+ return typeof value.error === "string" ? { error: value.error } : {};
53
+ }
54
+ function parseOutcome(value) {
55
+ if (!isRecord(value))
56
+ return null;
57
+ if (value.status === "ok") {
58
+ return typeof value.id === "string" ? { status: "ok", id: value.id } : { status: "ok" };
59
+ }
60
+ if (value.status === "error") {
61
+ const message = typeof value.message === "string" ? value.message : undefined;
62
+ return { status: "error", message, details: parseDetails(value.details) };
63
+ }
64
+ return null;
65
+ }
66
+ /** The `data` array of a send response, or `null` when it is not one ticket per message. */
67
+ export function parseExpoTickets(json, expected) {
68
+ if (!isRecord(json) || !Array.isArray(json.data) || json.data.length !== expected)
69
+ return null;
70
+ const tickets = [];
71
+ for (const item of json.data) {
72
+ const ticket = parseOutcome(item);
73
+ if (ticket === null)
74
+ return null;
75
+ tickets.push(ticket);
76
+ }
77
+ return tickets;
78
+ }
79
+ /** The `data` map of a `getReceipts` response. Entries that do not parse are skipped. */
80
+ export function parseExpoReceipts(json) {
81
+ if (!isRecord(json) || !isRecord(json.data))
82
+ return null;
83
+ const receipts = {};
84
+ for (const [id, item] of Object.entries(json.data)) {
85
+ const receipt = parseOutcome(item);
86
+ if (receipt !== null)
87
+ receipts[id] = receipt.status === "ok" ? { status: "ok" } : receipt;
88
+ }
89
+ return receipts;
90
+ }
91
+ function headers(accessToken) {
92
+ return {
93
+ "Content-Type": "application/json",
94
+ Accept: "application/json",
95
+ ...(accessToken ? { Authorization: `Bearer ${accessToken}` } : {}),
96
+ };
97
+ }
98
+ function chunk(items, size) {
99
+ const out = [];
100
+ for (let i = 0; i < items.length; i += size)
101
+ out.push(items.slice(i, i + size));
102
+ return out;
103
+ }
104
+ async function postJson(url, payload, options) {
105
+ const doFetch = options.fetch ?? globalThis.fetch;
106
+ try {
107
+ const response = await doFetch(url, {
108
+ method: "POST",
109
+ headers: headers(options.accessToken),
110
+ body: JSON.stringify(payload),
111
+ });
112
+ if (!response.ok) {
113
+ console.error(`[expoPush] ${url} failed: ${response.status} ${await response.text()}`);
114
+ return null;
115
+ }
116
+ return await response.json();
117
+ }
118
+ catch (err) {
119
+ console.error(`[expoPush] ${url} failed:`, err instanceof Error ? err.message : "unknown error");
120
+ return null;
121
+ }
122
+ }
123
+ /**
124
+ * Sends one message per token, in batches of `EXPO_PUSH_BATCH_SIZE`. Returns
125
+ * a ticket for each token Expo answered for. A batch that fails (network
126
+ * error, non-2xx or an unexpected body) is logged and left out, so the other
127
+ * batches still count.
128
+ */
129
+ export async function sendExpoPushMessages(options) {
130
+ const { tokens, title, body, data } = options;
131
+ const results = [];
132
+ for (const batch of chunk(tokens, EXPO_PUSH_BATCH_SIZE)) {
133
+ const messages = batch.map((to) => ({
134
+ to,
135
+ title,
136
+ ...(body === undefined ? {} : { body }),
137
+ sound: "default",
138
+ priority: "high",
139
+ ...(data === undefined ? {} : { data }),
140
+ }));
141
+ const tickets = parseExpoTickets(await postJson(EXPO_PUSH_SEND_URL, messages, options), batch.length);
142
+ if (tickets === null)
143
+ continue;
144
+ // Tickets come back in request order.
145
+ tickets.forEach((ticket, index) => results.push({ token: batch[index], ticket }));
146
+ }
147
+ return results;
148
+ }
149
+ /**
150
+ * Fetches receipts for the given ids, in batches of `EXPO_RECEIPT_BATCH_SIZE`.
151
+ * Ids Expo has no receipt for yet are missing from the result. A failed batch
152
+ * is logged and left out.
153
+ */
154
+ export async function fetchExpoPushReceipts(ids, options = {}) {
155
+ const receipts = {};
156
+ for (const batch of chunk(ids, EXPO_RECEIPT_BATCH_SIZE)) {
157
+ const parsed = parseExpoReceipts(await postJson(EXPO_PUSH_RECEIPTS_URL, { ids: batch }, options));
158
+ if (parsed !== null)
159
+ Object.assign(receipts, parsed);
160
+ }
161
+ return receipts;
162
+ }
163
+ /** `DeviceNotRegistered`: the app was uninstalled or the token expired, so stop sending to it. */
164
+ export function isDeviceNotRegistered(outcome) {
165
+ return outcome.status === "error" && outcome.details?.error === "DeviceNotRegistered";
166
+ }
167
+ /**
168
+ * Tokens whose ticket says `DeviceNotRegistered`, without duplicates. Other
169
+ * errors (`MessageTooBig`, `MessageRateExceeded`, `InvalidCredentials`) say
170
+ * nothing about the token, so they never remove one.
171
+ */
172
+ export function tokensToRemoveFromTickets(results) {
173
+ return [...new Set(results.filter((r) => isDeviceNotRegistered(r.ticket)).map((r) => r.token))];
174
+ }
175
+ /** The receipt ids of `ok` tickets, each with its token. */
176
+ export function receiptRefsFromTickets(results) {
177
+ const refs = [];
178
+ for (const { token, ticket } of results) {
179
+ if (ticket.status === "ok" && ticket.id)
180
+ refs.push({ id: ticket.id, token });
181
+ }
182
+ return refs;
183
+ }
184
+ /** Tokens whose receipt says `DeviceNotRegistered`, without duplicates. */
185
+ export function tokensToRemoveFromReceipts(receipts, refs) {
186
+ const dead = refs.filter((ref) => {
187
+ const receipt = receipts[ref.id];
188
+ return receipt !== undefined && isDeviceNotRegistered(receipt);
189
+ });
190
+ return [...new Set(dead.map((ref) => ref.token))];
191
+ }
192
+ /**
193
+ * Queues a push to every device of `params.userId`. Skips the action when the
194
+ * user has no token. Call it from a mutation; the factory also returns it
195
+ * with `sendRef` and `tableName` already bound.
196
+ */
197
+ export async function schedulePush(ctx, params, options) {
198
+ const hasToken = await ctx.db
199
+ .query(options.tableName)
200
+ .withIndex(PUSH_TOKENS_USER_INDEX, (q) => q.eq("userId", params.userId))
201
+ .first();
202
+ if (hasToken === null)
203
+ return;
204
+ await ctx.scheduler.runAfter(0, options.sendRef, params);
205
+ }
206
+ /**
207
+ * The push functions. Export them from one module, here `convex/push.ts`:
208
+ *
209
+ * ```ts
210
+ * export const { register, unregister, listTokensForUser, removeTokens, send, checkReceipts, schedulePush } =
211
+ * createExpoPushFunctions({
212
+ * v,
213
+ * userId: v.id("users"),
214
+ * mutation,
215
+ * internalQuery,
216
+ * internalMutation,
217
+ * internalAction,
218
+ * requireCurrentUserId: (ctx: MutationCtx) => userAuth.requireCurrentUserId(ctx),
219
+ * listTokensRef: (): ExpoPushListTokensRef<Id<"users">> => internal.push.listTokensForUser,
220
+ * removeTokensRef: (): ExpoPushRemoveTokensRef => internal.push.removeTokens,
221
+ * sendRef: (): ExpoPushSendRef<Id<"users">> => internal.push.send,
222
+ * checkReceiptsRef: (): ExpoPushCheckReceiptsRef => internal.push.checkReceipts,
223
+ * });
224
+ * ```
225
+ *
226
+ * `send` lists the user's tokens, sends in batches, removes tokens whose
227
+ * ticket says `DeviceNotRegistered`, then schedules `checkReceipts` to do the
228
+ * same for receipts. `schedulePush` is the bound helper to call from your
229
+ * mutations.
230
+ */
231
+ export function createExpoPushFunctions(config) {
232
+ const built = buildExpoPushFunctions(config);
233
+ // The builders only check `Table` here; `schedulePush` takes the app's real ctx, so type it with `Table`.
234
+ return {
235
+ ...built,
236
+ schedulePush: built.schedulePush,
237
+ };
238
+ }
239
+ function buildExpoPushFunctions(config) {
240
+ const { v, userId, requireCurrentUserId } = config;
241
+ const table = config.tableName ?? PUSH_TOKENS_TABLE;
242
+ const platform = v.union(v.literal("android"), v.literal("ios"));
243
+ const httpOptions = () => ({ fetch: config.fetch, accessToken: config.accessToken?.() });
244
+ const register = config.mutation({
245
+ args: { token: v.string(), platform },
246
+ returns: v.null(),
247
+ handler: async (ctx, args) => {
248
+ if (!isExpoPushToken(args.token))
249
+ throw new Error("Invalid push token");
250
+ const currentUserId = await requireCurrentUserId(ctx);
251
+ const existing = await ctx.db
252
+ .query(table)
253
+ .withIndex(PUSH_TOKENS_TOKEN_INDEX, (q) => q.eq("token", args.token))
254
+ .first();
255
+ const fields = { userId: currentUserId, platform: args.platform, updatedAt: Date.now() };
256
+ if (existing) {
257
+ // A token moves with the device, so a new sign-in takes it over.
258
+ await ctx.db.patch(existing._id, fields);
259
+ }
260
+ else {
261
+ await ctx.db.insert(table, { token: args.token, ...fields });
262
+ }
263
+ return null;
264
+ },
265
+ });
266
+ const unregister = config.mutation({
267
+ args: { token: v.string() },
268
+ returns: v.null(),
269
+ handler: async (ctx, args) => {
270
+ const currentUserId = await requireCurrentUserId(ctx);
271
+ const existing = await ctx.db
272
+ .query(table)
273
+ .withIndex(PUSH_TOKENS_TOKEN_INDEX, (q) => q.eq("token", args.token))
274
+ .first();
275
+ if (existing && existing.userId === currentUserId)
276
+ await ctx.db.delete(existing._id);
277
+ return null;
278
+ },
279
+ });
280
+ const listTokensForUser = config.internalQuery({
281
+ args: { userId },
282
+ returns: v.array(v.string()),
283
+ handler: async (ctx, args) => {
284
+ const rows = await ctx.db
285
+ .query(table)
286
+ .withIndex(PUSH_TOKENS_USER_INDEX, (q) => q.eq("userId", args.userId))
287
+ .collect();
288
+ return rows.map((row) => row.token);
289
+ },
290
+ });
291
+ const removeTokens = config.internalMutation({
292
+ args: { tokens: v.array(v.string()) },
293
+ returns: v.null(),
294
+ handler: async (ctx, args) => {
295
+ for (const token of args.tokens) {
296
+ const row = await ctx.db
297
+ .query(table)
298
+ .withIndex(PUSH_TOKENS_TOKEN_INDEX, (q) => q.eq("token", token))
299
+ .first();
300
+ if (row)
301
+ await ctx.db.delete(row._id);
302
+ }
303
+ return null;
304
+ },
305
+ });
306
+ const send = config.internalAction({
307
+ args: { userId, title: v.string(), body: v.optional(v.string()), data: v.optional(v.record(v.string(), v.any())) },
308
+ returns: v.null(),
309
+ handler: async (ctx, args) => {
310
+ const tokens = await ctx.runQuery(config.listTokensRef(), { userId: args.userId });
311
+ if (tokens.length === 0)
312
+ return null;
313
+ const results = await sendExpoPushMessages({
314
+ tokens,
315
+ title: args.title,
316
+ body: args.body,
317
+ data: args.data,
318
+ ...httpOptions(),
319
+ });
320
+ const dead = tokensToRemoveFromTickets(results);
321
+ if (dead.length > 0)
322
+ await ctx.runMutation(config.removeTokensRef(), { tokens: dead });
323
+ // Dead tokens are gone already; only check receipts for the rest.
324
+ const receipts = receiptRefsFromTickets(results).filter((ref) => !dead.includes(ref.token));
325
+ if (receipts.length > 0) {
326
+ await ctx.scheduler.runAfter(config.receiptDelayMs ?? EXPO_RECEIPT_DELAY_MS, config.checkReceiptsRef(), {
327
+ receipts,
328
+ });
329
+ }
330
+ return null;
331
+ },
332
+ });
333
+ const checkReceipts = config.internalAction({
334
+ args: { receipts: v.array(v.object({ id: v.string(), token: v.string() })) },
335
+ returns: v.null(),
336
+ handler: async (ctx, args) => {
337
+ const found = await fetchExpoPushReceipts(args.receipts.map((ref) => ref.id), httpOptions());
338
+ const dead = tokensToRemoveFromReceipts(found, args.receipts);
339
+ if (dead.length > 0)
340
+ await ctx.runMutation(config.removeTokensRef(), { tokens: dead });
341
+ return null;
342
+ },
343
+ });
344
+ const boundSchedulePush = (ctx, params) => schedulePush(ctx, params, { sendRef: config.sendRef(), tableName: table });
345
+ return {
346
+ register,
347
+ unregister,
348
+ listTokensForUser,
349
+ removeTokens,
350
+ send,
351
+ checkReceipts,
352
+ schedulePush: boundSchedulePush,
353
+ };
354
+ }
@@ -8,11 +8,12 @@ export { corsPreflight, jsonWithCors, mcpCorsHeaders, type JsonWithCorsInit, } f
8
8
  export { formatConvexQueryError, isConvexResourceLimitError, } from "./convexQueryLimits.js";
9
9
  export { jsonResponse } from "./jsonResponse.js";
10
10
  export { authenticateWithTokenCache, createMcpTokenCacheFunctions, hashMcpToken, jwtExpiryMs, MCP_TOKEN_CACHE_EXPIRES_INDEX, MCP_TOKEN_CACHE_HASH_INDEX, MCP_TOKEN_CACHE_PURGE_BATCH, MCP_TOKEN_CACHE_TABLE, MCP_TOKEN_CACHE_TTL_MS, mcpTokenCacheFields, mcpTokenCacheTable, tokenCacheExpiresAt, type AuthenticateWithTokenCacheOptions, type McpTokenCacheDoc, type McpTokenCacheEntry, type McpTokenCacheFunctionsConfig, type McpTokenCacheGetDef, type McpTokenCacheMutationBuilder, type McpTokenCacheMutationCtx, type McpTokenCachePrincipal, type McpTokenCachePurgeDef, type McpTokenCachePurgeRef, type McpTokenCachePutDef, type McpTokenCacheQueryBuilder, type McpTokenCacheQueryCtx, type McpTokenCacheRow, } from "./mcpTokenCache.js";
11
+ export { createExpoPushFunctions, EXPO_PUSH_BATCH_SIZE, EXPO_PUSH_RECEIPTS_URL, EXPO_PUSH_SEND_URL, EXPO_PUSH_TOKEN_PATTERN, EXPO_RECEIPT_BATCH_SIZE, EXPO_RECEIPT_DELAY_MS, fetchExpoPushReceipts, isDeviceNotRegistered, isExpoPushToken, parseExpoReceipts, parseExpoTickets, PUSH_TOKENS_TABLE, PUSH_TOKENS_TOKEN_INDEX, PUSH_TOKENS_USER_INDEX, pushTokensFields, pushTokensTable, receiptRefsFromTickets, schedulePush, sendExpoPushMessages, tokensToRemoveFromReceipts, tokensToRemoveFromTickets, type ExpoPushCheckReceiptsRef, type ExpoPushData, type ExpoPushFunctionsConfig, type ExpoPushHttpOptions, type ExpoPushListTokensRef, type ExpoPushMessage, type ExpoPushReceipt, type ExpoPushReceiptRef, type ExpoPushRemoveTokensRef, type ExpoPushSendRef, type ExpoPushSendResult, type ExpoPushTicket, type PushMutationCtx, type PushPlatform, type PushQueryCtx, type PushSendParams, type PushTokenDoc, type PushTokenRow, type SchedulePushCtx, type SendExpoPushMessagesOptions, } from "./expoPush.js";
11
12
  export { createMemoryOptimisticStore } from "./memoryStore.js";
12
13
  export { forEachLoadedQuery, mapLoadedQuery, patchLoadedQuery, updateAllCachedQueries, type OptimisticStore, } from "./optimistic.js";
13
14
  export { createOriginAllowlistCors, type OriginAllowlistCors, } from "./originAllowlistCors.js";
14
15
  export { requiredEnv, requiredEnvUrl, type EnvSource } from "./env.js";
15
- export { defineMcpServerInfo, type McpServerInfo } from "./mcpServerInfo.js";
16
+ export { defineMcpServerInfo, type McpServerIcon, type McpServerInfo } from "./mcpServerInfo.js";
16
17
  export { assertMcpTools, expectMcpToolCount } from "./mcpTestHelpers.js";
17
18
  export { tempId, type TempIdFormat, type TempIdOptions } from "./tempId.js";
18
19
  export { consoleClerkVerifyLogger, verifyClerkAccessToken, type ClerkAuthLike, type ClerkLike, type ClerkRequestStateLike, type ClerkTokenType, type ClerkVerifyRejection, type VerifiedClerkToken, type VerifyClerkAccessTokenOptions, } from "./verifyClerkAccessToken.js";
@@ -8,6 +8,7 @@ export { corsPreflight, jsonWithCors, mcpCorsHeaders, } from "./cors.js";
8
8
  export { formatConvexQueryError, isConvexResourceLimitError, } from "./convexQueryLimits.js";
9
9
  export { jsonResponse } from "./jsonResponse.js";
10
10
  export { authenticateWithTokenCache, createMcpTokenCacheFunctions, hashMcpToken, jwtExpiryMs, MCP_TOKEN_CACHE_EXPIRES_INDEX, MCP_TOKEN_CACHE_HASH_INDEX, MCP_TOKEN_CACHE_PURGE_BATCH, MCP_TOKEN_CACHE_TABLE, MCP_TOKEN_CACHE_TTL_MS, mcpTokenCacheFields, mcpTokenCacheTable, tokenCacheExpiresAt, } from "./mcpTokenCache.js";
11
+ export { createExpoPushFunctions, EXPO_PUSH_BATCH_SIZE, EXPO_PUSH_RECEIPTS_URL, EXPO_PUSH_SEND_URL, EXPO_PUSH_TOKEN_PATTERN, EXPO_RECEIPT_BATCH_SIZE, EXPO_RECEIPT_DELAY_MS, fetchExpoPushReceipts, isDeviceNotRegistered, isExpoPushToken, parseExpoReceipts, parseExpoTickets, PUSH_TOKENS_TABLE, PUSH_TOKENS_TOKEN_INDEX, PUSH_TOKENS_USER_INDEX, pushTokensFields, pushTokensTable, receiptRefsFromTickets, schedulePush, sendExpoPushMessages, tokensToRemoveFromReceipts, tokensToRemoveFromTickets, } from "./expoPush.js";
11
12
  export { createMemoryOptimisticStore } from "./memoryStore.js";
12
13
  export { forEachLoadedQuery, mapLoadedQuery, patchLoadedQuery, updateAllCachedQueries, } from "./optimistic.js";
13
14
  export { createOriginAllowlistCors, } from "./originAllowlistCors.js";
@@ -1,6 +1,21 @@
1
+ /** An icon in MCP `serverInfo.icons` (MCP 2025-11-25 `Implementation.icons`). */
2
+ export type McpServerIcon = {
3
+ /** Icon URL, for example an absolute https URL to the app's public icon. */
4
+ src: string;
5
+ mimeType?: string;
6
+ /** For example `["48x48"]` or `["any"]`. */
7
+ sizes?: string[];
8
+ theme?: "light" | "dark";
9
+ };
1
10
  export type McpServerInfo = {
2
11
  name: string;
3
12
  version: string;
13
+ title?: string;
14
+ websiteUrl?: string;
15
+ icons?: McpServerIcon[];
4
16
  };
5
- /** Build the MCP `serverInfo` object. The caller owns the name and version. */
17
+ /**
18
+ * Build the MCP `serverInfo` object. The caller owns every value. Optional
19
+ * fields appear only when passed, so `{ name, version }` gives exactly that.
20
+ */
6
21
  export declare function defineMcpServerInfo(options: McpServerInfo): McpServerInfo;
@@ -1,8 +1,23 @@
1
- /** Build the MCP `serverInfo` object. The caller owns the name and version. */
1
+ /**
2
+ * Build the MCP `serverInfo` object. The caller owns every value. Optional
3
+ * fields appear only when passed, so `{ name, version }` gives exactly that.
4
+ */
2
5
  export function defineMcpServerInfo(options) {
3
6
  if (!options.name)
4
7
  throw new Error("MCP server name must not be empty");
5
8
  if (!options.version)
6
9
  throw new Error("MCP server version must not be empty");
7
- return { name: options.name, version: options.version };
10
+ const info = { name: options.name, version: options.version };
11
+ if (options.title !== undefined)
12
+ info.title = options.title;
13
+ if (options.websiteUrl !== undefined)
14
+ info.websiteUrl = options.websiteUrl;
15
+ if (options.icons !== undefined) {
16
+ info.icons = options.icons.map((icon, i) => {
17
+ if (!icon.src)
18
+ throw new Error(`MCP server icon ${i} src must not be empty`);
19
+ return { ...icon };
20
+ });
21
+ }
22
+ return info;
8
23
  }
package/docs/convex.md CHANGED
@@ -38,6 +38,13 @@ if (request.method === "OPTIONS") return corsPreflight();
38
38
  return jsonWithCors({ error: "Unauthorized" }, { status: 401, extraHeaders: { "WWW-Authenticate": "Bearer" } });
39
39
 
40
40
  const serverInfo = defineMcpServerInfo({ name: "my-mcp", version: "1.0.0" });
41
+ const withIcon = defineMcpServerInfo({
42
+ name: "my-mcp",
43
+ version: "1.0.0",
44
+ title: "My app",
45
+ websiteUrl: "https://my-app.example",
46
+ icons: [{ src: "https://my-app.example/icon.png", mimeType: "image/png", sizes: ["any"] }],
47
+ });
41
48
  ```
42
49
 
43
50
  ```ts
@@ -56,7 +63,7 @@ expectMcpToolCount(toolNames, 2);
56
63
  | `extractBearerToken(header)` | Token from an `Authorization` header, or `null`. |
57
64
  | `requiredEnv(name, env?)`, `requiredEnvUrl(name, env?)` | Required env value, optionally stripping a trailing slash. |
58
65
  | `mcpCorsHeaders`, `corsPreflight`, `jsonWithCors` | CORS for MCP HTTP handlers. Methods `GET,POST,DELETE,OPTIONS`; headers `Authorization,Content-Type`; credentials `false`. |
59
- | `defineMcpServerInfo({ name, version })` | MCP `serverInfo`. The caller owns both values. |
66
+ | `defineMcpServerInfo({ name, version, title?, websiteUrl?, icons? })` | MCP `serverInfo`. The caller owns every value. `name` and `version` must not be empty. Optional fields appear only when passed; each icon is `{ src, mimeType?, sizes?, theme? }` and an empty `src` throws. See [mcp.md](mcp.md). |
60
67
  | `expectMcpToolCount`, `assertMcpTools` | Test helpers. They throw plain errors, so they work with any runner. |
61
68
  | `jsonResponse(data, status, extraHeaders?)` | `JSON.stringify(data)` with `Content-Type: application/json`; `extraHeaders` spread after it. |
62
69
  | `createOriginAllowlistCors(allowedOrigins)` | `{ headers(origin), preflightHeaders(origin) }` for credentialed browser CORS on a fixed origin list. |
@@ -343,6 +350,90 @@ crons.hourly("purge MCP token cache", { minuteUTC: 0 }, internal.mcp.tokenCache.
343
350
 
344
351
  The ctx types are structural, so the factory checks that the table exists and has both indexes. `getInternal`, `putInternal` and `purgeExpired` are real registered functions, so `ctx.runQuery(internal.mcp.tokenCache.getInternal, …)` is typed. `tests/convex/mcpTokenCache.types.ts` checks this against a codegen-shaped app with `convex/server` 1.47.
345
352
 
353
+ ## Expo push notifications
354
+
355
+ Device-token storage, a batched send through the Expo Push API, and push receipts that drop dead tokens. Like the MCP token cache, the package cannot own a table: define it in your schema and wire one `convex/push.ts`. `convex` is used for types only.
356
+
357
+ Define the table locally. `convex/schema.ts` cannot import runtime code from a package (`NoImportModuleInSchema`), so do not call `pushTokensTable` or `pushTokensFields` there.
358
+
359
+ ```ts
360
+ // convex/schema.ts
361
+ pushTokens: defineTable({
362
+ userId: v.id("users"), // pushTokensFields(v) uses v.string(); pass v.id("users") as its second argument to match
363
+ token: v.string(),
364
+ platform: v.union(v.literal("android"), v.literal("ios")),
365
+ updatedAt: v.number(),
366
+ })
367
+ .index("by_user", ["userId"])
368
+ .index("by_token", ["token"]),
369
+ ```
370
+
371
+ Check it in a test outside the schema: `expect(schema.tables.pushTokens.validator).toEqual(v.object(pushTokensFields(v, v.id("users"))))`, and compare `table[" indexes"]()` with `pushTokensTable(defineTable, v, v.id("users"))[" indexes"]()`, as in the MCP token cache section.
372
+
373
+ ```ts
374
+ // convex/push.ts
375
+ import { v } from "convex/values";
376
+ import {
377
+ createClerkUserAuth,
378
+ createExpoPushFunctions,
379
+ type ExpoPushCheckReceiptsRef,
380
+ type ExpoPushListTokensRef,
381
+ type ExpoPushRemoveTokensRef,
382
+ type ExpoPushSendRef,
383
+ } from "@vvedantb/server";
384
+ import { internal } from "./_generated/api";
385
+ import type { DataModel, Id } from "./_generated/dataModel";
386
+ import { internalAction, internalMutation, internalQuery, mutation, type MutationCtx } from "./_generated/server";
387
+
388
+ const userAuth = createClerkUserAuth<DataModel>()({ table: "users", index: "by_clerk_id", field: "clerkId" });
389
+
390
+ export const { register, unregister, listTokensForUser, removeTokens, send, checkReceipts, schedulePush } =
391
+ createExpoPushFunctions({
392
+ v,
393
+ userId: v.id("users"),
394
+ mutation,
395
+ internalQuery,
396
+ internalMutation,
397
+ internalAction,
398
+ // Annotate ctx with your MutationCtx.
399
+ requireCurrentUserId: (ctx: MutationCtx) => userAuth.requireCurrentUserId(ctx),
400
+ // Keep the return annotations: without them `internal` refers to itself (TS7022).
401
+ listTokensRef: (): ExpoPushListTokensRef<Id<"users">> => internal.push.listTokensForUser,
402
+ removeTokensRef: (): ExpoPushRemoveTokensRef => internal.push.removeTokens,
403
+ sendRef: (): ExpoPushSendRef<Id<"users">> => internal.push.send,
404
+ checkReceiptsRef: (): ExpoPushCheckReceiptsRef => internal.push.checkReceipts,
405
+ // tableName: "pushTokens", receiptDelayMs: 15 * 60 * 1000, accessToken: () => process.env.EXPO_ACCESS_TOKEN,
406
+ });
407
+ ```
408
+
409
+ Send from any mutation. `schedulePush` returns at once when the user has no token, so most users cost no action:
410
+
411
+ ```ts
412
+ import { schedulePush } from "./push";
413
+
414
+ await schedulePush(ctx, { userId: task.ownerId, title: "Task done", body: task.title, data: { target: task._id } });
415
+ ```
416
+
417
+ Mobile: pass `api.push.register` to the hook from `@vvedantb/native-ui/push` (see its README), or call `register({ token, platform })` yourself with a token from `expo-notifications`.
418
+
419
+ ```tsx
420
+ const register = useMutation(api.push.register);
421
+ useExpoPushRegistration({ register, onNotificationTap: ({ data }) => router.push(`/chat/${String(data.target)}`) });
422
+ ```
423
+
424
+ | Export | Semantics |
425
+ | --- | --- |
426
+ | `register({ token, platform })` | Public mutation. Rejects tokens that do not match `/^Expo(nent)?PushToken\[.+\]$/`. Upserts by `by_token`: an existing token is patched to the caller (a token moves with the device), otherwise inserted. No duplicates. |
427
+ | `unregister({ token })` | Public mutation. Deletes the row only when it belongs to the caller. |
428
+ | `listTokensForUser({ userId })` | Internal query: the user's tokens. |
429
+ | `removeTokens({ tokens })` | Internal mutation: deletes rows by token. |
430
+ | `send({ userId, title, body?, data? })` | Internal action. Sends `{ to, title, body?, sound: "default", priority: "high", data? }` to `https://exp.host/--/api/v2/push/send` in batches of `EXPO_PUSH_BATCH_SIZE` (100). Removes tokens whose ticket has `details.error` `DeviceNotRegistered`. Schedules `checkReceipts` after `receiptDelayMs` (default 15 minutes) with each `ok` ticket id and its token. A failed batch is logged and skipped. |
431
+ | `checkReceipts({ receipts })` | Internal action. Posts the ids to `.../push/getReceipts` (1000 per request) and removes tokens whose receipt says `DeviceNotRegistered`. Ids Expo has no receipt for are ignored; receipts last 24 hours. |
432
+ | `schedulePush(ctx, { userId, title, body?, data? })` | Checks `by_user` for a token; none: returns. Otherwise `ctx.scheduler.runAfter(0, sendRef, params)`. The factory returns it bound; the standalone export takes `{ sendRef, tableName }` as a third argument. |
433
+ | `sendExpoPushMessages`, `fetchExpoPushReceipts`, `tokensToRemoveFromTickets`, `receiptRefsFromTickets`, `tokensToRemoveFromReceipts`, `parseExpoTickets`, `parseExpoReceipts` | The HTTP and cleanup logic as plain functions with an injectable `fetch`, for Node scripts and tests. |
434
+
435
+ Only `DeviceNotRegistered` removes a token. `InvalidCredentials`, `MessageTooBig` and `MessageRateExceeded` describe your credentials or the message, not the device, so the token stays. The `userId` validator sets the user id type; with `v.id("users")` it is `Id<"users">`.
436
+
346
437
  ## Optimistic updates (client side)
347
438
 
348
439
  Client-side helpers for Convex optimistic updates. They live here, not in `@vvedantb/ui`, because they have no React: a backend package's client folder, its tests and a React Native app import them, and none of those can load the `@vvedantb/ui` root.
package/docs/mcp.md CHANGED
@@ -192,6 +192,18 @@ registerMcpRoutes(http, {
192
192
 
193
193
  ### JSON-RPC dispatcher
194
194
 
195
+ `defineMcpServerInfo` requires a non-empty `name` and `version`. It also takes optional `title`, `websiteUrl` and `icons` (MCP 2025-11-25 `Implementation`). Each icon is `{ src, mimeType?, sizes?, theme? }`, where `theme` is `"light"` or `"dark"`; an empty `src` throws. Optional fields appear only when passed, so `{ name, version }` alone gives the same object as before. An absolute https URL to the app's public icon is enough for `src`; the package serves no icon files.
196
+
197
+ ```ts
198
+ defineMcpServerInfo({
199
+ name: "my-mcp",
200
+ version: "1.0.0",
201
+ title: "My app",
202
+ websiteUrl: "https://my-app.example",
203
+ icons: [{ src: "https://my-app.example/icon.png", mimeType: "image/png", sizes: ["any"] }],
204
+ });
205
+ ```
206
+
195
207
  | Export | What it does |
196
208
  | --- | --- |
197
209
  | `createMcpDispatcher(config)` | `{ handleRpc }` for stateless HTTP: `initialize`, `ping`, `tools/list`, `tools/call`, notifications (202, empty body), batches. Other methods: -32601 "Method not found". |
@@ -200,7 +212,7 @@ registerMcpRoutes(http, {
200
212
  | `parseRpcBody(text)` | Parse a body, or the SDK's 400 -32700 "Parse error: Invalid JSON" result. |
201
213
  | `rpcResult`, `rpcError`, `JSON_RPC_ERROR` | Response builders with the SDK's key order. |
202
214
 
203
- Config: `serverInfo` (or a function of the scope), `tools`, `protocol` (`versions`, `fallback`; default SDK list, fallback `"2025-11-25"` as the SDK), `capabilities` (default `{ tools: { listChanged: true } }` as `McpServer`), `instructions`, `toJsonSchema`.
215
+ Config: `serverInfo` (or a function of the scope; returned in the initialize result as given), `tools`, `protocol` (`versions`, `fallback`; default SDK list, fallback `"2025-11-25"` as the SDK), `capabilities` (default `{ tools: { listChanged: true } }` as `McpServer`), `instructions`, `toJsonSchema`.
204
216
 
205
217
  ### Tools
206
218
 
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@vvedantb/server",
3
- "version": "0.12.0",
3
+ "version": "0.14.0",
4
4
  "license": "MIT",
5
- "description": "Shared Convex backend helpers, MCP server scaffolding and Node-side MCP OAuth client helpers from one root import: query-limit errors, Clerk auth and token verification, an MCP bearer-token cache, Clerk-user lookups and ensure-user for Convex functions, V Pro plan checks and Clerk Billing webhook helpers, bearer tokens, env, CORS, JSON responses, MCP route registration, a bearer-auth MCP HTTP handler, OAuth metadata, a JSON-RPC dispatcher, explorer tools, WebCrypto primitives, Convex optimistic-update helpers, MCP OAuth client helpers (provider, sign-in, refresh, revocation, loopback redirect server) for desktop apps, a QuickJS code sandbox that bridges script tool calls to host handlers, and a pure artifacts core (Zod contract, state limits and ops, quiz and flashcards pages, a sandboxed document wrapper with CSP and a guest state bridge); and, from the `@vvedantb/server/ai` subpath, Vercel AI Gateway helpers (service tier provider options, cost from provider metadata, error classification).",
5
+ "description": "Shared Convex backend helpers, MCP server scaffolding and Node-side MCP OAuth client helpers from one root import: query-limit errors, Clerk auth and token verification, an MCP bearer-token cache, Expo push token storage, batched send and receipts, Clerk-user lookups and ensure-user for Convex functions, V Pro plan checks and Clerk Billing webhook helpers, bearer tokens, env, CORS, JSON responses, MCP route registration, a bearer-auth MCP HTTP handler, OAuth metadata, a JSON-RPC dispatcher, explorer tools, WebCrypto primitives, Convex optimistic-update helpers, MCP OAuth client helpers (provider, sign-in, refresh, revocation, loopback redirect server) for desktop apps, a QuickJS code sandbox that bridges script tool calls to host handlers, and a pure artifacts core (Zod contract, state limits and ops, quiz and flashcards pages, a sandboxed document wrapper with CSP and a guest state bridge); and, from the `@vvedantb/server/ai` subpath, Vercel AI Gateway helpers (service tier provider options, cost from provider metadata, error classification).",
6
6
  "type": "module",
7
7
  "publishConfig": {
8
8
  "access": "public"
@@ -41,12 +41,6 @@
41
41
  "quickjs-emscripten-core": false,
42
42
  "@jitl/quickjs-singlefile-cjs-release-sync": false
43
43
  },
44
- "scripts": {
45
- "build": "tsc -p tsconfig.json",
46
- "typecheck": "tsc -p tsconfig.test.json",
47
- "test": "vitest run && node --test tests-node/esm-exports.mjs tests-node/bundle.mjs",
48
- "prepack": "tsc -p tsconfig.json"
49
- },
50
44
  "peerDependencies": {
51
45
  "@ai-sdk/gateway": ">=1",
52
46
  "@clerk/backend": ">=1",
@@ -95,5 +89,10 @@
95
89
  "vitest": "^3.2.0",
96
90
  "zod": "^4.0.0",
97
91
  "zod3": "npm:zod@^3.25.76"
92
+ },
93
+ "scripts": {
94
+ "build": "tsc -p tsconfig.json",
95
+ "typecheck": "tsc -p tsconfig.test.json",
96
+ "test": "vitest run && node --test tests-node/esm-exports.mjs tests-node/bundle.mjs"
98
97
  }
99
- }
98
+ }