@vvedantb/server 0.13.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 +17 -0
- package/README.md +1 -1
- package/dist/convex/expoPush.d.ts +349 -0
- package/dist/convex/expoPush.js +354 -0
- package/dist/convex/index.d.ts +1 -0
- package/dist/convex/index.js +1 -0
- package/docs/convex.md +84 -0
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,22 @@
|
|
|
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
|
+
|
|
3
20
|
## 0.13.0
|
|
4
21
|
|
|
5
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.
|
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
|
+
}
|
package/dist/convex/index.d.ts
CHANGED
|
@@ -8,6 +8,7 @@ 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";
|
package/dist/convex/index.js
CHANGED
|
@@ -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";
|
package/docs/convex.md
CHANGED
|
@@ -350,6 +350,90 @@ crons.hourly("purge MCP token cache", { minuteUTC: 0 }, internal.mcp.tokenCache.
|
|
|
350
350
|
|
|
351
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.
|
|
352
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
|
+
|
|
353
437
|
## Optimistic updates (client side)
|
|
354
438
|
|
|
355
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/package.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vvedantb/server",
|
|
3
|
-
"version": "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"
|