@vvedantb/server 0.2.0 → 0.4.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,27 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.4.0
4
+
5
+ Additive: two packages fold in under the same export names. Nothing in 0.3.0 changes.
6
+
7
+ ### Added
8
+
9
+ - From `@vvedantb/convex-client` 0.1.0, its non-React helpers: `mapLoadedQuery` (also `forEachLoadedQuery` and `updateAllCachedQueries`), `patchLoadedQuery`, `OptimisticStore`, `tempId(table?, { format? })`, `TempIdFormat`, `TempIdOptions` and `createMemoryOptimisticStore()`. See `docs/convex.md`. The package still never imports `convex` at runtime: the memory store carries a copy of `getFunctionName`, tested against Convex's.
10
+ - From `@vvedantb/mcp-client` 0.1.0, every export: `createMcpOAuthStateSchema`, `hasMcpOAuthTokens`, `isAccessTokenExpiring`, `createMcpOAuthProvider`, `authorizeMcpServer`, `refreshMcpOAuth`, `revokeMcpOAuth`, `startLoopback`, `LOOPBACK_PATH`, `LOOPBACK_TIMEOUT_MS` and their types. See `docs/mcp-client.md`. Node only; nothing Node-only loads when the root is imported: `startLoopback` imports `node:http` when called, the SDK loads on first use, and `state()` uses WebCrypto instead of `node:crypto` (same format).
11
+ - New optional peers: `@modelcontextprotocol/sdk` `^1.29.0` (MCP client OAuth calls) and `convex` `^1.24.0` (types only). Neither is imported when the root loads.
12
+ - Tests: the convex-client and mcp-client suites are ported. `tests-node/bundle.mjs` bundles a Convex function that imports the root with Convex's own esbuild and options, with and without the SDK installed, and asserts no `node:` import or built-in `require` in any output; it also runs an Electron-style Node bundle with no `node_modules`. `tests-node/esm-exports.mjs` imports the root with no peer installed.
13
+
14
+ ### Changed (from `@vvedantb/mcp-client` 0.1.0)
15
+
16
+ - A non-interactive provider's `redirectToAuthorization` returns a promise that rejects with the SDK's `UnauthorizedError`, instead of throwing it synchronously: the class is only reachable once the SDK is loaded. The SDK awaits the call, so its sign-in, refresh and connect flows are unchanged.
17
+ - Without the SDK installed, `authorizeMcpServer` and `redirectToAuthorization` reject with "The MCP client OAuth helpers need the @modelcontextprotocol/sdk package", and `refreshMcpOAuth` and `revokeMcpOAuth` return `false`. Before, a missing SDK failed the package import.
18
+
19
+ ## 0.3.0
20
+
21
+ ### Added
22
+
23
+ - `createClerkUserAuth<DataModel>()({ table, index, field, adminField?, lookup?, unauthenticatedMessage? })`: Clerk-user helpers for Convex queries and mutations. Returns `getUserByClerkId`, `getCurrentUser`, `getCurrentUserId`, `requireCurrentUserId`, `isCurrentUserAdmin` and `ensureUser(ctx, buildFields, { patch?, unauthenticatedMessage?, missingSubjectMessage? })`. Typed structurally (no `convex` import); config keys are checked against your `DataModel`. See `docs/convex.md` for semantics and the per-app mapping.
24
+
3
25
  ## 0.2.0
4
26
 
5
27
  ### Breaking
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @vvedantb/server
2
2
 
3
- Server-side helpers for Convex backends, from one root import.
3
+ Server-side helpers for Convex backends, Convex optimistic updates and Node-side MCP client OAuth, from one root import.
4
4
 
5
5
  ```sh
6
6
  npm install @vvedantb/server
@@ -14,33 +14,40 @@ There are no subpath exports (0.2.0 removed `/convex` and `/mcp`; see [CHANGELOG
14
14
 
15
15
  | Area | What it holds | Docs |
16
16
  | --- | --- | --- |
17
- | Convex helpers | Query-limit errors, Clerk auth config and client, Clerk token verification, bearer tokens, env, MCP CORS, origin-allowlist CORS, `jsonResponse`, server info, test helpers. | [docs/convex.md](docs/convex.md) |
17
+ | Convex helpers | Query-limit errors, Clerk auth config and client, Clerk token verification, Clerk-user lookups and `ensureUser` (`createClerkUserAuth`), bearer tokens, env, MCP CORS, origin-allowlist CORS, `jsonResponse`, server info, test helpers. | [docs/convex.md](docs/convex.md) |
18
18
  | MCP scaffolding | For Convex `httpAction`s: bearer-auth handler, OAuth metadata, route registration, a pure JSON-RPC dispatcher, tool helpers and explorer tools. | [docs/mcp.md](docs/mcp.md) |
19
19
  | Crypto | WebCrypto-only base64/base64url/hex, SHA-256, random tokens, `timingSafeEqual`, AES-GCM. Convex default runtime and Node 20+. | [docs/crypto.md](docs/crypto.md) |
20
+ | Optimistic updates | `mapLoadedQuery` (also `forEachLoadedQuery`, `updateAllCachedQueries`), `patchLoadedQuery`, `tempId`, `createMemoryOptimisticStore`. Client-side, no React. From `@vvedantb/convex-client`. | [docs/convex.md](docs/convex.md#optimistic-updates-client-side) |
21
+ | MCP client OAuth | Node only (Electron main): OAuth provider over injected storage, sign-in, refresh, revocation, loopback redirect server. Node built-ins and the MCP SDK load on first use, so Convex V8 bundles of the root stay clean. From `@vvedantb/mcp-client`. | [docs/mcp-client.md](docs/mcp-client.md) |
20
22
 
21
23
  Migration steps per app: [docs/migration.md](docs/migration.md).
22
24
 
23
25
  ## Peers
24
26
 
25
- Both are optional.
27
+ All are optional. None is imported when the root loads.
26
28
 
27
29
  - `@clerk/backend` `>=1`: only for `getClerkClient` and `verifyClerkAccessToken`, which take its client or factory as an argument.
28
- - `zod` `^3.25.0 || ^4.0.0`: only if you pass zod schemas to `defineTool`.
30
+ - `zod` `^3.25.0 || ^4.0.0`: only if you pass zod schemas to `defineTool`, or your `z` to `createMcpOAuthStateSchema`.
31
+ - `convex` `^1.24.0`: types only, for the optimistic-update helpers. The package never imports `convex` at runtime: `registerMcpRoutes` and `createClerkUserAuth` type the router and ctx structurally, and `createMemoryOptimisticStore` carries its own copy of `getFunctionName` (`convex` is a dev dependency, used to check that real Convex types fit).
32
+ - `@modelcontextprotocol/sdk` `^1.29.0`: only for the MCP client OAuth calls, which import it on first use.
29
33
 
30
- `convex` is not a dependency: `registerMcpRoutes` types the router structurally. No React, no web dependencies. Compiled ESM with types in `dist`, built on pack.
34
+ No React, no web dependencies. `"sideEffects": false`. Compiled ESM with types in `dist`, built on pack.
31
35
 
32
36
  ## Layout
33
37
 
34
38
  ```
35
- src/index.ts the only export: re-exports the three folders
36
- src/convex/ Convex helpers
39
+ src/index.ts the only export: re-exports the four folders
40
+ src/convex/ Convex helpers and optimistic updates
37
41
  src/mcp/ MCP scaffolding (imports ../convex by relative path)
42
+ src/mcp-client/ MCP client OAuth (Node only; lazy node:http and SDK imports)
38
43
  src/crypto/ WebCrypto primitives
39
44
  tests/convex/ vitest
40
45
  tests/mcp/ vitest, with fixtures/ (SDK captures, app references)
46
+ tests/mcp-client/ vitest, against fake MCP and authorization servers
41
47
  tests/crypto/ vitest, with published vectors and app format parity
42
- tests-node/ plain Node ESM check of the built exports map
43
- docs/ convex.md, mcp.md, crypto.md, migration.md, migrated/<app>/
48
+ tests-node/ plain Node checks of the built package: exports map and peers (esm-exports.mjs),
49
+ Convex V8 and Electron main bundles with esbuild (bundle.mjs)
50
+ docs/ convex.md, mcp.md, mcp-client.md, crypto.md, migration.md, migrated/<app>/
44
51
  scripts/ capture-sdk-fixtures.mjs
45
52
  ```
46
53
 
@@ -0,0 +1,105 @@
1
+ /**
2
+ * Clerk-user lookups for Convex functions: the caller's identity `subject`
3
+ * resolved to a row through one index. Typed structurally, so the package
4
+ * never imports `convex`; a real `QueryCtx` or `MutationCtx` fits the ctx
5
+ * types below without a cast.
6
+ */
7
+ /** The part of a Convex table's type info this helper reads (`DataModel[table]`). */
8
+ export type ClerkUserTableInfoLike = {
9
+ document: {
10
+ _id: string;
11
+ };
12
+ indexes: Record<string, string[]>;
13
+ };
14
+ /** The part of a Convex `DataModel` this helper reads. Pass your generated `DataModel`. */
15
+ export type ClerkUserDataModelLike = Record<string, ClerkUserTableInfoLike>;
16
+ /** The part of Convex's `UserIdentity` this helper reads. */
17
+ export type ClerkUserIdentityLike = {
18
+ readonly subject: string;
19
+ };
20
+ /** The index range builder after `q`: one `eq` on the Clerk id field. */
21
+ export type ClerkUserIndexRange<Field extends string, Range> = {
22
+ eq(field: Field, value: string): Range;
23
+ };
24
+ /** `ctx.db` reads: one index lookup that ends in `.first()` or `.unique()`. */
25
+ export type ClerkUserDbReader<Table extends string, Index extends string, Field extends string, Doc, Range> = {
26
+ query(table: Table): {
27
+ withIndex(index: Index, range: (q: ClerkUserIndexRange<Field, Range>) => Range): {
28
+ first(): Promise<Doc | null>;
29
+ unique(): Promise<Doc | null>;
30
+ };
31
+ };
32
+ };
33
+ /** A Convex `QueryCtx` or `MutationCtx`, structurally. */
34
+ export type ClerkUserQueryCtx<Table extends string, Index extends string, Field extends string, Doc, Range, Identity extends ClerkUserIdentityLike = ClerkUserIdentityLike> = {
35
+ auth: {
36
+ getUserIdentity(): Promise<Identity | null>;
37
+ };
38
+ db: ClerkUserDbReader<Table, Index, Field, Doc, Range>;
39
+ };
40
+ /** A row to insert: the document without Convex's system fields. */
41
+ export type ClerkUserInsert<Doc> = Omit<Doc, "_id" | "_creationTime">;
42
+ /** A Convex `MutationCtx`, structurally. */
43
+ export type ClerkUserMutationCtx<Table extends string, Index extends string, Field extends string, Doc extends {
44
+ _id: string;
45
+ }, Range, Identity extends ClerkUserIdentityLike = ClerkUserIdentityLike> = {
46
+ auth: {
47
+ getUserIdentity(): Promise<Identity | null>;
48
+ };
49
+ db: ClerkUserDbReader<Table, Index, Field, Doc, Range> & {
50
+ insert(table: Table, value: ClerkUserInsert<Doc>): Promise<Doc["_id"]>;
51
+ patch(id: Doc["_id"], value: Partial<ClerkUserInsert<Doc>>): Promise<void>;
52
+ };
53
+ };
54
+ export type ClerkUserAuthConfig<Table extends string, Index extends string, Field extends string, AdminField extends string> = {
55
+ /** The users table, for example `"users"`. */
56
+ table: Table;
57
+ /** The index on the Clerk id field, for example `"by_clerk_id"`. */
58
+ index: Index;
59
+ /** The indexed field that holds the identity `subject`, for example `"clerkId"`. */
60
+ field: Field;
61
+ /** A boolean field; `isCurrentUserAdmin` is true only when it is `=== true`. */
62
+ adminField?: AdminField;
63
+ /** How the index lookup ends. Default `"first"`; `"unique"` throws on duplicate rows. */
64
+ lookup?: "first" | "unique";
65
+ /** Thrown by `requireCurrentUserId` and `ensureUser`. Default `"Not authenticated"`. */
66
+ unauthenticatedMessage?: string;
67
+ };
68
+ export type EnsureClerkUserOptions<Doc, Identity> = {
69
+ /**
70
+ * Fields to patch on an existing row, or `undefined` to leave it alone.
71
+ * Only called when the row exists.
72
+ */
73
+ patch?: (existing: Doc, identity: Identity) => Partial<ClerkUserInsert<Doc>> | undefined;
74
+ /** Thrown when there is no identity. Default: the config's `unauthenticatedMessage`. */
75
+ unauthenticatedMessage?: string;
76
+ /** Thrown when the identity has an empty `subject`. Default `"Clerk user ID is required"`. */
77
+ missingSubjectMessage?: string;
78
+ };
79
+ export type EnsureClerkUserResult<Id> = {
80
+ userId: Id;
81
+ wasCreated: boolean;
82
+ };
83
+ /**
84
+ * Build Clerk-user helpers for one users table. Curried so `DataModel` can be
85
+ * given while the config keys are inferred (and checked against it):
86
+ *
87
+ * ```ts
88
+ * const userAuth = createClerkUserAuth<DataModel>()({
89
+ * table: "users",
90
+ * index: "by_clerk_id",
91
+ * field: "clerkId",
92
+ * adminField: "admin",
93
+ * });
94
+ * ```
95
+ */
96
+ export declare function createClerkUserAuth<DataModel extends ClerkUserDataModelLike>(): <const Table extends keyof DataModel & string, const Index extends keyof DataModel[Table]["indexes"] & string, const Field extends DataModel[Table]["indexes"][Index][0], const AdminField extends keyof DataModel[Table]["document"] & string = never>(config: ClerkUserAuthConfig<Table, Index, Field, AdminField>) => {
97
+ getUserByClerkId: <Range>(ctx: {
98
+ db: ClerkUserDbReader<Table, Index, Field, DataModel[Table]["document"], Range>;
99
+ }, clerkId: string) => Promise<DataModel[Table]["document"] | null>;
100
+ getCurrentUser: <Range>(ctx: ClerkUserQueryCtx<Table, Index, Field, DataModel[Table]["document"], Range>) => Promise<DataModel[Table]["document"] | null>;
101
+ getCurrentUserId: <Range>(ctx: ClerkUserQueryCtx<Table, Index, Field, DataModel[Table]["document"], Range>) => Promise<DataModel[Table]["document"]["_id"] | null>;
102
+ requireCurrentUserId: <Range>(ctx: ClerkUserQueryCtx<Table, Index, Field, DataModel[Table]["document"], Range>, message?: string) => Promise<DataModel[Table]["document"]["_id"]>;
103
+ isCurrentUserAdmin: <Range>(ctx: ClerkUserQueryCtx<Table, Index, Field, DataModel[Table]["document"], Range>) => Promise<boolean>;
104
+ ensureUser: <Range, Identity extends ClerkUserIdentityLike>(ctx: ClerkUserMutationCtx<Table, Index, Field, DataModel[Table]["document"], Range, Identity>, buildFields: (identity: Identity) => ClerkUserInsert<DataModel[Table]["document"]>, options?: EnsureClerkUserOptions<DataModel[Table]["document"], Identity>) => Promise<EnsureClerkUserResult<DataModel[Table]["document"]["_id"]>>;
105
+ };
@@ -0,0 +1,89 @@
1
+ /**
2
+ * Clerk-user lookups for Convex functions: the caller's identity `subject`
3
+ * resolved to a row through one index. Typed structurally, so the package
4
+ * never imports `convex`; a real `QueryCtx` or `MutationCtx` fits the ctx
5
+ * types below without a cast.
6
+ */
7
+ const DEFAULT_UNAUTHENTICATED_MESSAGE = "Not authenticated";
8
+ const DEFAULT_MISSING_SUBJECT_MESSAGE = "Clerk user ID is required";
9
+ /**
10
+ * Build Clerk-user helpers for one users table. Curried so `DataModel` can be
11
+ * given while the config keys are inferred (and checked against it):
12
+ *
13
+ * ```ts
14
+ * const userAuth = createClerkUserAuth<DataModel>()({
15
+ * table: "users",
16
+ * index: "by_clerk_id",
17
+ * field: "clerkId",
18
+ * adminField: "admin",
19
+ * });
20
+ * ```
21
+ */
22
+ export function createClerkUserAuth() {
23
+ return function configure(config) {
24
+ const unauthenticatedMessage = config.unauthenticatedMessage ?? DEFAULT_UNAUTHENTICATED_MESSAGE;
25
+ function getUserByClerkId(ctx, clerkId) {
26
+ const query = ctx.db
27
+ .query(config.table)
28
+ .withIndex(config.index, (q) => q.eq(config.field, clerkId));
29
+ return config.lookup === "unique" ? query.unique() : query.first();
30
+ }
31
+ /** The caller's row, or `null` with no identity, an empty `subject`, or no row. */
32
+ async function getCurrentUser(ctx) {
33
+ const identity = await ctx.auth.getUserIdentity();
34
+ if (!identity?.subject)
35
+ return null;
36
+ return getUserByClerkId(ctx, identity.subject);
37
+ }
38
+ async function getCurrentUserId(ctx) {
39
+ const user = await getCurrentUser(ctx);
40
+ return user?._id ?? null;
41
+ }
42
+ /** `getCurrentUserId`, throwing `new Error(message)` where that returns `null`. */
43
+ async function requireCurrentUserId(ctx, message = unauthenticatedMessage) {
44
+ const userId = await getCurrentUserId(ctx);
45
+ if (userId === null)
46
+ throw new Error(message);
47
+ return userId;
48
+ }
49
+ async function isCurrentUserAdmin(ctx) {
50
+ const adminField = config.adminField;
51
+ if (adminField === undefined) {
52
+ throw new Error("createClerkUserAuth: set adminField to use isCurrentUserAdmin");
53
+ }
54
+ const user = await getCurrentUser(ctx);
55
+ return user !== null && user[adminField] === true;
56
+ }
57
+ /**
58
+ * The ensure-user mutation core: throws without an identity or `subject`,
59
+ * patches an existing row when `options.patch` returns fields, otherwise
60
+ * inserts `buildFields(identity)` (which must set the Clerk id field).
61
+ */
62
+ async function ensureUser(ctx, buildFields, options = {}) {
63
+ const identity = await ctx.auth.getUserIdentity();
64
+ if (!identity) {
65
+ throw new Error(options.unauthenticatedMessage ?? unauthenticatedMessage);
66
+ }
67
+ if (!identity.subject) {
68
+ throw new Error(options.missingSubjectMessage ?? DEFAULT_MISSING_SUBJECT_MESSAGE);
69
+ }
70
+ const existing = await getUserByClerkId(ctx, identity.subject);
71
+ if (existing) {
72
+ const patch = options.patch?.(existing, identity);
73
+ if (patch !== undefined)
74
+ await ctx.db.patch(existing._id, patch);
75
+ return { userId: existing._id, wasCreated: false };
76
+ }
77
+ const userId = await ctx.db.insert(config.table, buildFields(identity));
78
+ return { userId, wasCreated: true };
79
+ }
80
+ return {
81
+ getUserByClerkId,
82
+ getCurrentUser,
83
+ getCurrentUserId,
84
+ requireCurrentUserId,
85
+ isCurrentUserAdmin,
86
+ ensureUser,
87
+ };
88
+ };
89
+ }
@@ -1,11 +1,15 @@
1
1
  export { clerkAuthConfig, type ClerkAuthConfigEnv } from "./authConfig.js";
2
2
  export { extractBearerToken } from "./bearerToken.js";
3
3
  export { getClerkClient, type ClerkClientEnv } from "./clerk.js";
4
+ export { createClerkUserAuth, type ClerkUserAuthConfig, type ClerkUserDataModelLike, type ClerkUserDbReader, type ClerkUserIdentityLike, type ClerkUserIndexRange, type ClerkUserInsert, type ClerkUserMutationCtx, type ClerkUserQueryCtx, type ClerkUserTableInfoLike, type EnsureClerkUserOptions, type EnsureClerkUserResult, } from "./clerkUserAuth.js";
4
5
  export { corsPreflight, jsonWithCors, mcpCorsHeaders, type JsonWithCorsInit, } from "./cors.js";
5
6
  export { formatConvexQueryError, isConvexResourceLimitError, } from "./convexQueryLimits.js";
6
7
  export { jsonResponse } from "./jsonResponse.js";
8
+ export { createMemoryOptimisticStore } from "./memoryStore.js";
9
+ export { forEachLoadedQuery, mapLoadedQuery, patchLoadedQuery, updateAllCachedQueries, type OptimisticStore, } from "./optimistic.js";
7
10
  export { createOriginAllowlistCors, type OriginAllowlistCors, } from "./originAllowlistCors.js";
8
11
  export { requiredEnv, requiredEnvUrl, type EnvSource } from "./env.js";
9
12
  export { defineMcpServerInfo, type McpServerInfo } from "./mcpServerInfo.js";
10
13
  export { assertMcpTools, expectMcpToolCount } from "./mcpTestHelpers.js";
14
+ export { tempId, type TempIdFormat, type TempIdOptions } from "./tempId.js";
11
15
  export { consoleClerkVerifyLogger, verifyClerkAccessToken, type ClerkAuthLike, type ClerkLike, type ClerkRequestStateLike, type ClerkTokenType, type ClerkVerifyRejection, type VerifiedClerkToken, type VerifyClerkAccessTokenOptions, } from "./verifyClerkAccessToken.js";
@@ -1,11 +1,15 @@
1
1
  export { clerkAuthConfig } from "./authConfig.js";
2
2
  export { extractBearerToken } from "./bearerToken.js";
3
3
  export { getClerkClient } from "./clerk.js";
4
+ export { createClerkUserAuth, } from "./clerkUserAuth.js";
4
5
  export { corsPreflight, jsonWithCors, mcpCorsHeaders, } from "./cors.js";
5
6
  export { formatConvexQueryError, isConvexResourceLimitError, } from "./convexQueryLimits.js";
6
7
  export { jsonResponse } from "./jsonResponse.js";
8
+ export { createMemoryOptimisticStore } from "./memoryStore.js";
9
+ export { forEachLoadedQuery, mapLoadedQuery, patchLoadedQuery, updateAllCachedQueries, } from "./optimistic.js";
7
10
  export { createOriginAllowlistCors, } from "./originAllowlistCors.js";
8
11
  export { requiredEnv, requiredEnvUrl } from "./env.js";
9
12
  export { defineMcpServerInfo } from "./mcpServerInfo.js";
10
13
  export { assertMcpTools, expectMcpToolCount } from "./mcpTestHelpers.js";
14
+ export { tempId } from "./tempId.js";
11
15
  export { consoleClerkVerifyLogger, verifyClerkAccessToken, } from "./verifyClerkAccessToken.js";
@@ -0,0 +1,8 @@
1
+ import type { OptimisticLocalStore } from "convex/browser";
2
+ /**
3
+ * An in-memory `OptimisticLocalStore` for testing optimistic updates without a
4
+ * Convex client. Entries are keyed by function name and `JSON.stringify(args)`
5
+ * (missing args read as `{}`), kept in first-set order; setting `undefined`
6
+ * removes an entry.
7
+ */
8
+ export declare function createMemoryOptimisticStore(): OptimisticLocalStore;
@@ -0,0 +1,59 @@
1
+ /**
2
+ * An in-memory `OptimisticLocalStore` for testing optimistic updates without a
3
+ * Convex client. Entries are keyed by function name and `JSON.stringify(args)`
4
+ * (missing args read as `{}`), kept in first-set order; setting `undefined`
5
+ * removes an entry.
6
+ */
7
+ export function createMemoryOptimisticStore() {
8
+ const data = new Map();
9
+ return {
10
+ getQuery(query, ...args) {
11
+ const key = JSON.stringify(args[0] ?? {});
12
+ return data.get(getFunctionName(query))?.get(key)?.value;
13
+ },
14
+ getAllQueries(query) {
15
+ const slots = data.get(getFunctionName(query));
16
+ if (!slots)
17
+ return [];
18
+ return [...slots.values()];
19
+ },
20
+ setQuery(query, args, value) {
21
+ const name = getFunctionName(query);
22
+ let slots = data.get(name);
23
+ if (!slots) {
24
+ slots = new Map();
25
+ data.set(name, slots);
26
+ }
27
+ const key = JSON.stringify(args ?? {});
28
+ if (value === undefined) {
29
+ slots.delete(key);
30
+ return;
31
+ }
32
+ slots.set(key, { args, value });
33
+ },
34
+ };
35
+ }
36
+ // `getFunctionName` from `convex/server` (as of 1.47), copied so this package
37
+ // never imports `convex` at runtime: the root is also loaded where `convex` is
38
+ // not installed. For the references Convex creates (`api`/`internal` refs,
39
+ // name strings, function handles, component refs) it returns the same name or
40
+ // throws the same message; tests compare it with Convex's.
41
+ const functionName = Symbol.for("functionName");
42
+ const toReferencePath = Symbol.for("toReferencePath");
43
+ function getFunctionName(reference) {
44
+ if (typeof reference === "string") {
45
+ if (reference.startsWith("function://")) {
46
+ throw new Error(`Expected function reference like "api.file.func" or "internal.file.func", but received function handle ${reference}`);
47
+ }
48
+ return reference;
49
+ }
50
+ // Read, not `in`: `api` references are proxies that answer property reads only.
51
+ const symbols = reference;
52
+ const name = symbols[functionName];
53
+ if (name)
54
+ return name;
55
+ const path = symbols[toReferencePath] ?? null;
56
+ if (!path)
57
+ throw new Error(`${String(reference)} is not a functionReference`);
58
+ throw new Error(`Expected function reference in the current component like "api.file.func" or "internal.file.func", but received reference ${String(path)}`);
59
+ }
@@ -0,0 +1,25 @@
1
+ import type { FunctionArgs, FunctionReference, FunctionReturnType } from "convex/server";
2
+ /**
3
+ * The part of Convex's `OptimisticLocalStore` these helpers use. A real
4
+ * `OptimisticLocalStore` fits; `getAllQueries` is optional so a hand-written
5
+ * store without it works too (then `mapLoadedQuery` does nothing).
6
+ */
7
+ export type OptimisticStore = {
8
+ getQuery<Query extends FunctionReference<"query">>(query: Query, args: FunctionArgs<Query>): undefined | FunctionReturnType<Query>;
9
+ setQuery<Query extends FunctionReference<"query">>(query: Query, args: FunctionArgs<Query>, value: undefined | FunctionReturnType<Query>): void;
10
+ getAllQueries?: <Query extends FunctionReference<"query">>(query: Query) => Array<{
11
+ args: FunctionArgs<Query>;
12
+ value: undefined | FunctionReturnType<Query>;
13
+ }>;
14
+ };
15
+ /**
16
+ * Replace every loaded copy of `query` (one per args) with `update(value, args)`.
17
+ * Copies still loading (`value === undefined`) are skipped.
18
+ */
19
+ export declare function mapLoadedQuery<Query extends FunctionReference<"query">>(store: OptimisticStore, query: Query, update: (value: FunctionReturnType<Query>, args: FunctionArgs<Query>) => FunctionReturnType<Query>): void;
20
+ /** `mapLoadedQuery` under the name some apps use. Same function. */
21
+ export declare const forEachLoadedQuery: typeof mapLoadedQuery;
22
+ /** `mapLoadedQuery` under the name some apps use. Same function. */
23
+ export declare const updateAllCachedQueries: typeof mapLoadedQuery;
24
+ /** Replace the copy of `query` loaded for `args` with `update(value)`; nothing if it is not loaded. */
25
+ export declare function patchLoadedQuery<Query extends FunctionReference<"query">>(store: OptimisticStore, query: Query, args: FunctionArgs<Query>, update: (value: FunctionReturnType<Query>) => FunctionReturnType<Query>): void;
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Replace every loaded copy of `query` (one per args) with `update(value, args)`.
3
+ * Copies still loading (`value === undefined`) are skipped.
4
+ */
5
+ export function mapLoadedQuery(store, query, update) {
6
+ const entries = store.getAllQueries?.(query) ?? [];
7
+ for (const entry of entries) {
8
+ if (entry.value === undefined)
9
+ continue;
10
+ store.setQuery(query, entry.args, update(entry.value, entry.args));
11
+ }
12
+ }
13
+ /** `mapLoadedQuery` under the name some apps use. Same function. */
14
+ export const forEachLoadedQuery = mapLoadedQuery;
15
+ /** `mapLoadedQuery` under the name some apps use. Same function. */
16
+ export const updateAllCachedQueries = mapLoadedQuery;
17
+ /** Replace the copy of `query` loaded for `args` with `update(value)`; nothing if it is not loaded. */
18
+ export function patchLoadedQuery(store, query, args, update) {
19
+ const current = store.getQuery(query, args);
20
+ if (current === undefined)
21
+ return;
22
+ store.setQuery(query, args, update(current));
23
+ }
@@ -0,0 +1,15 @@
1
+ import type { GenericId } from "convex/values";
2
+ /**
3
+ * - `"uuid"` (default): `crypto.randomUUID()`.
4
+ * - `"timestamp"`: `optimistic_<Date.now()>_<Math.random() base 36>`.
5
+ */
6
+ export type TempIdFormat = "uuid" | "timestamp";
7
+ export type TempIdOptions = {
8
+ format?: TempIdFormat;
9
+ };
10
+ /**
11
+ * A placeholder id for an optimistic insert. The server's real id replaces it
12
+ * when the mutation lands. `table` only names the id type and is not used at
13
+ * runtime: `tempId("tasks")` or `tempId<"tasks">()`.
14
+ */
15
+ export declare function tempId<Table extends string>(table?: Table, options?: TempIdOptions): GenericId<Table>;
@@ -0,0 +1,19 @@
1
+ /**
2
+ * A placeholder id for an optimistic insert. The server's real id replaces it
3
+ * when the mutation lands. `table` only names the id type and is not used at
4
+ * runtime: `tempId("tasks")` or `tempId<"tasks">()`.
5
+ */
6
+ export function tempId(table, options = {}) {
7
+ const value = options.format === "timestamp"
8
+ ? `optimistic_${Date.now()}_${Math.random().toString(36).slice(2)}`
9
+ : crypto.randomUUID();
10
+ if (!isPlaceholderId(value)) {
11
+ throw new Error(`tempId: empty id for ${table ?? "table"}`);
12
+ }
13
+ return value;
14
+ }
15
+ // GenericId is a branded string with no constructor; this guard is the one
16
+ // place a placeholder string is accepted as one.
17
+ function isPlaceholderId(value) {
18
+ return value.length > 0;
19
+ }
package/dist/index.d.ts CHANGED
@@ -1,3 +1,4 @@
1
1
  export * from "./convex/index.js";
2
2
  export * from "./crypto/index.js";
3
3
  export * from "./mcp/index.js";
4
+ export * from "./mcp-client/index.js";
package/dist/index.js CHANGED
@@ -1,3 +1,4 @@
1
1
  export * from "./convex/index.js";
2
2
  export * from "./crypto/index.js";
3
3
  export * from "./mcp/index.js";
4
+ export * from "./mcp-client/index.js";
@@ -0,0 +1,3 @@
1
+ export { createMcpOAuthStateSchema, type McpOAuthClientInformation, type McpOAuthIdentity, type McpOAuthState, type McpOAuthTokens, } from "./state.js";
2
+ export { authorizeMcpServer, createMcpOAuthProvider, hasMcpOAuthTokens, isAccessTokenExpiring, refreshMcpOAuth, revokeMcpOAuth, type McpClientInfo, type McpOAuthProvider, type McpOAuthProviderOptions, type McpOAuthStorage, } from "./oauth.js";
3
+ export { LOOPBACK_PATH, LOOPBACK_TIMEOUT_MS, startLoopback, type Loopback, type LoopbackMessages, type LoopbackOptions, } from "./loopback.js";
@@ -0,0 +1,3 @@
1
+ export { createMcpOAuthStateSchema, } from "./state.js";
2
+ export { authorizeMcpServer, createMcpOAuthProvider, hasMcpOAuthTokens, isAccessTokenExpiring, refreshMcpOAuth, revokeMcpOAuth, } from "./oauth.js";
3
+ export { LOOPBACK_PATH, LOOPBACK_TIMEOUT_MS, startLoopback, } from "./loopback.js";
@@ -0,0 +1,25 @@
1
+ export declare const LOOPBACK_PATH = "/callback";
2
+ export declare const LOOPBACK_TIMEOUT_MS: number;
3
+ /** The text of the pages the browser shows. Inserted as HTML, unescaped. */
4
+ export type LoopbackMessages = {
5
+ /** 400: the request does not carry the expected `state`. */
6
+ invalid: string;
7
+ /** 200: the redirect carried `error`, or no `code`. */
8
+ incomplete: string;
9
+ /** 200: the code was received. */
10
+ success: string;
11
+ };
12
+ export type LoopbackOptions = {
13
+ /** The page `<title>`. Default `"Sign in"`. */
14
+ title?: string;
15
+ messages?: Partial<LoopbackMessages>;
16
+ };
17
+ export type Loopback = {
18
+ /** The exact redirect_uri to register and send, for example http://127.0.0.1:51234/callback. */
19
+ redirectUrl: string;
20
+ /** Resolves with the authorisation code. `expectedState` is read when the request arrives, so it may be set later. */
21
+ waitForCode: (expectedState: () => string | undefined, timeoutMs?: number) => Promise<string>;
22
+ close: () => void;
23
+ };
24
+ /** Starts listening on 127.0.0.1 with a free port. Call close when the sign-in ends. */
25
+ export declare function startLoopback(options?: LoopbackOptions): Promise<Loopback>;
@@ -0,0 +1,83 @@
1
+ // The redirect target for sign-in: a one-shot HTTP server on 127.0.0.1 with a random port.
2
+ // Node only. `node:http` is imported when the server starts, never at module
3
+ // load, so the package root stays loadable in Convex's V8 runtime.
4
+ export const LOOPBACK_PATH = "/callback";
5
+ export const LOOPBACK_TIMEOUT_MS = 5 * 60_000;
6
+ const DEFAULT_TITLE = "Sign in";
7
+ const DEFAULT_MESSAGES = {
8
+ invalid: "This sign-in link is not valid. Go back to the app and try again.",
9
+ incomplete: "Sign-in was not completed. You can close this window.",
10
+ success: "You can close this window and go back to the app.",
11
+ };
12
+ /** Starts listening on 127.0.0.1 with a free port. Call close when the sign-in ends. */
13
+ export async function startLoopback(options = {}) {
14
+ const title = options.title ?? DEFAULT_TITLE;
15
+ const messages = { ...DEFAULT_MESSAGES, ...options.messages };
16
+ const page = (text) => `<!doctype html><meta charset="utf-8"><title>${title}</title><body style="font:16px system-ui;margin:3rem"><p>${text}</p></body>`;
17
+ let deliver = () => undefined;
18
+ let expected = () => undefined;
19
+ let timer;
20
+ const html = { "content-type": "text/html; charset=utf-8" };
21
+ const { createServer } = await loadNodeHttp();
22
+ const server = createServer((req, res) => {
23
+ const url = new URL(req.url ?? "/", "http://127.0.0.1");
24
+ if (req.method !== "GET" || url.pathname !== LOOPBACK_PATH) {
25
+ res.writeHead(404).end();
26
+ return;
27
+ }
28
+ const state = expected();
29
+ const error = url.searchParams.get("error");
30
+ const code = url.searchParams.get("code");
31
+ // A request without the state we sent is not our redirect: ignore it and keep waiting.
32
+ if (!state || url.searchParams.get("state") !== state) {
33
+ res.writeHead(400, html).end(page(messages.invalid));
34
+ return;
35
+ }
36
+ if (error || !code) {
37
+ res.writeHead(200, html).end(page(messages.incomplete));
38
+ deliver({ error: error ? "Sign-in was cancelled" : "Sign-in returned no code" });
39
+ return;
40
+ }
41
+ res.writeHead(200, html).end(page(messages.success));
42
+ deliver({ code });
43
+ });
44
+ await new Promise((resolve, reject) => {
45
+ server.once("error", reject);
46
+ server.listen(0, "127.0.0.1", resolve);
47
+ });
48
+ const address = server.address();
49
+ if (address === null || typeof address === "string")
50
+ throw new Error("Loopback server has no port");
51
+ const close = () => {
52
+ clearTimeout(timer);
53
+ server.close();
54
+ server.closeAllConnections();
55
+ };
56
+ return {
57
+ redirectUrl: `http://127.0.0.1:${String(address.port)}${LOOPBACK_PATH}`,
58
+ close,
59
+ waitForCode: (expectedState, timeoutMs = LOOPBACK_TIMEOUT_MS) => {
60
+ expected = expectedState;
61
+ return new Promise((resolve, reject) => {
62
+ timer = setTimeout(() => reject(new Error("Sign-in timed out")), timeoutMs);
63
+ deliver = (result) => {
64
+ clearTimeout(timer);
65
+ if ("code" in result)
66
+ resolve(result.code);
67
+ else
68
+ reject(new Error(result.error));
69
+ };
70
+ });
71
+ },
72
+ };
73
+ }
74
+ // The import sits directly in a try block: esbuild (Convex's bundler) and Metro
75
+ // then treat `node:http` as optional instead of failing a non-Node build.
76
+ async function loadNodeHttp() {
77
+ try {
78
+ return await import("node:http");
79
+ }
80
+ catch (error) {
81
+ throw new Error("startLoopback needs Node.js (node:http)", { cause: error });
82
+ }
83
+ }