nuxt-backend 0.1.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.
Files changed (106) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +744 -0
  3. package/dist/convex/auth.config.d.ts +9 -0
  4. package/dist/convex/auth.config.d.ts.map +1 -0
  5. package/dist/convex/auth.config.js +14 -0
  6. package/dist/convex/auth.config.js.map +1 -0
  7. package/dist/convex/client/index.d.ts +12784 -0
  8. package/dist/convex/client/index.d.ts.map +1 -0
  9. package/dist/convex/client/index.js +230 -0
  10. package/dist/convex/client/index.js.map +1 -0
  11. package/dist/convex/component/_generated/api.d.ts +36 -0
  12. package/dist/convex/component/_generated/api.d.ts.map +1 -0
  13. package/dist/convex/component/_generated/api.js +31 -0
  14. package/dist/convex/component/_generated/api.js.map +1 -0
  15. package/dist/convex/component/_generated/component.d.ts +549 -0
  16. package/dist/convex/component/_generated/component.d.ts.map +1 -0
  17. package/dist/convex/component/_generated/component.js +11 -0
  18. package/dist/convex/component/_generated/component.js.map +1 -0
  19. package/dist/convex/component/_generated/dataModel.d.ts +46 -0
  20. package/dist/convex/component/_generated/dataModel.d.ts.map +1 -0
  21. package/dist/convex/component/_generated/dataModel.js +11 -0
  22. package/dist/convex/component/_generated/dataModel.js.map +1 -0
  23. package/dist/convex/component/_generated/server.d.ts +121 -0
  24. package/dist/convex/component/_generated/server.d.ts.map +1 -0
  25. package/dist/convex/component/_generated/server.js +78 -0
  26. package/dist/convex/component/_generated/server.js.map +1 -0
  27. package/dist/convex/component/adapter.d.ts +3 -0
  28. package/dist/convex/component/adapter.d.ts.map +1 -0
  29. package/dist/convex/component/adapter.js +23 -0
  30. package/dist/convex/component/adapter.js.map +1 -0
  31. package/dist/convex/component/constants.d.ts +3 -0
  32. package/dist/convex/component/constants.d.ts.map +1 -0
  33. package/dist/convex/component/constants.js +3 -0
  34. package/dist/convex/component/constants.js.map +1 -0
  35. package/dist/convex/component/convex.config.d.ts +14 -0
  36. package/dist/convex/component/convex.config.d.ts.map +1 -0
  37. package/dist/convex/component/convex.config.js +15 -0
  38. package/dist/convex/component/convex.config.js.map +1 -0
  39. package/dist/convex/component/schema.d.ts +278 -0
  40. package/dist/convex/component/schema.d.ts.map +1 -0
  41. package/dist/convex/component/schema.js +91 -0
  42. package/dist/convex/component/schema.js.map +1 -0
  43. package/dist/module.d.ts +47 -0
  44. package/dist/module.js +275 -0
  45. package/dist/module.json +9 -0
  46. package/dist/runtime/nuxt/auth/middleware.d.ts +12 -0
  47. package/dist/runtime/nuxt/auth/middleware.js +31 -0
  48. package/dist/runtime/nuxt/auth/proxy.d.ts +6 -0
  49. package/dist/runtime/nuxt/auth/proxy.js +11 -0
  50. package/dist/runtime/nuxt/auth/server.d.ts +86 -0
  51. package/dist/runtime/nuxt/auth/server.js +110 -0
  52. package/dist/runtime/nuxt/config.d.ts +7 -0
  53. package/dist/runtime/nuxt/config.js +12 -0
  54. package/dist/runtime/nuxt/index.d.ts +102 -0
  55. package/dist/runtime/nuxt/index.js +77 -0
  56. package/dist/runtime/vue/auth/client.d.ts +14 -0
  57. package/dist/runtime/vue/auth/client.js +7 -0
  58. package/dist/runtime/vue/auth/cross-domain.d.ts +8 -0
  59. package/dist/runtime/vue/auth/cross-domain.js +34 -0
  60. package/dist/runtime/vue/auth/helpers.d.ts +52 -0
  61. package/dist/runtime/vue/auth/helpers.js +35 -0
  62. package/dist/runtime/vue/auth/hydration.d.ts +14 -0
  63. package/dist/runtime/vue/auth/hydration.js +23 -0
  64. package/dist/runtime/vue/auth/index.d.ts +79 -0
  65. package/dist/runtime/vue/auth/index.js +81 -0
  66. package/dist/runtime/vue/auth/plugin.client.d.ts +6 -0
  67. package/dist/runtime/vue/auth/plugin.client.js +30 -0
  68. package/dist/runtime/vue/auth/plugin.server.d.ts +17 -0
  69. package/dist/runtime/vue/auth/plugin.server.js +29 -0
  70. package/dist/runtime/vue/auth/use-auth.d.ts +84 -0
  71. package/dist/runtime/vue/auth/use-auth.js +77 -0
  72. package/dist/runtime/vue/client.d.ts +245 -0
  73. package/dist/runtime/vue/client.js +341 -0
  74. package/dist/runtime/vue/composables/use-action.d.ts +45 -0
  75. package/dist/runtime/vue/composables/use-action.js +10 -0
  76. package/dist/runtime/vue/composables/use-connection-state.d.ts +25 -0
  77. package/dist/runtime/vue/composables/use-connection-state.js +13 -0
  78. package/dist/runtime/vue/composables/use-mutation.d.ts +60 -0
  79. package/dist/runtime/vue/composables/use-mutation.js +36 -0
  80. package/dist/runtime/vue/composables/use-paginated-query.d.ts +101 -0
  81. package/dist/runtime/vue/composables/use-paginated-query.js +508 -0
  82. package/dist/runtime/vue/composables/use-queries.d.ts +45 -0
  83. package/dist/runtime/vue/composables/use-queries.js +32 -0
  84. package/dist/runtime/vue/composables/use-query.d.ts +82 -0
  85. package/dist/runtime/vue/composables/use-query.js +63 -0
  86. package/dist/runtime/vue/composables/use-subscription.d.ts +14 -0
  87. package/dist/runtime/vue/composables/use-subscription.js +15 -0
  88. package/dist/runtime/vue/hydration.d.ts +42 -0
  89. package/dist/runtime/vue/hydration.js +18 -0
  90. package/dist/runtime/vue/index.d.ts +29 -0
  91. package/dist/runtime/vue/index.js +38 -0
  92. package/dist/runtime/vue/queries-observer.d.ts +38 -0
  93. package/dist/runtime/vue/queries-observer.js +127 -0
  94. package/dist/types.d.ts +3 -0
  95. package/package.json +157 -0
  96. package/src/convex/auth.config.ts +21 -0
  97. package/src/convex/client/index.ts +329 -0
  98. package/src/convex/component/_generated/api.ts +52 -0
  99. package/src/convex/component/_generated/component.ts +1338 -0
  100. package/src/convex/component/_generated/dataModel.ts +60 -0
  101. package/src/convex/component/_generated/server.ts +156 -0
  102. package/src/convex/component/adapter.ts +42 -0
  103. package/src/convex/component/constants.ts +2 -0
  104. package/src/convex/component/convex.config.ts +16 -0
  105. package/src/convex/component/schema.ts +93 -0
  106. package/src/convex/test.ts +34 -0
@@ -0,0 +1,77 @@
1
+ import { computed, ref } from "vue";
2
+ import { authClient } from "./client.js";
3
+ const cachedToken = ref(null);
4
+ let cachedTokenVersion = null;
5
+ let pendingToken = null;
6
+ let pendingTokenVersion = null;
7
+ let initialTokenUsed = false;
8
+ const PENDING_AUTH_VERSION = "__pending__";
9
+ const useClientSession = () => authClient.useSession();
10
+ export function useAuth(initialToken) {
11
+ if (!initialTokenUsed && initialToken) {
12
+ cachedToken.value = initialToken;
13
+ cachedTokenVersion = PENDING_AUTH_VERSION;
14
+ initialTokenUsed = true;
15
+ }
16
+ const session = useClientSession();
17
+ const client = authClient;
18
+ const authVersion = computed(() => {
19
+ const data = session.value.data;
20
+ return data?.session?.id ?? data?.user?.id ?? null;
21
+ });
22
+ const currentAuthVersion = () => authVersion.value ?? (session.value.isPending ? PENDING_AUTH_VERSION : null);
23
+ const fetchAccessToken = async ({ forceRefreshToken }) => {
24
+ const version = currentAuthVersion();
25
+ if (version === null) {
26
+ cachedToken.value = null;
27
+ cachedTokenVersion = null;
28
+ pendingToken = null;
29
+ pendingTokenVersion = null;
30
+ return null;
31
+ }
32
+ if (cachedToken.value && cachedTokenVersion === version && !forceRefreshToken) {
33
+ return cachedToken.value;
34
+ }
35
+ if (!forceRefreshToken && pendingToken && pendingTokenVersion === version) {
36
+ return pendingToken;
37
+ }
38
+ const request = (async () => {
39
+ try {
40
+ const result = await client.convex?.token({ fetchOptions: { throw: false } });
41
+ const token = result?.data?.token ?? null;
42
+ cachedToken.value = token;
43
+ cachedTokenVersion = version;
44
+ return token;
45
+ } catch {
46
+ cachedToken.value = null;
47
+ cachedTokenVersion = version;
48
+ return null;
49
+ }
50
+ })();
51
+ pendingTokenVersion = version;
52
+ pendingToken = request.finally(() => {
53
+ pendingToken = null;
54
+ pendingTokenVersion = null;
55
+ });
56
+ return pendingToken;
57
+ };
58
+ return {
59
+ client,
60
+ session,
61
+ isAuthenticated: computed(
62
+ () => !!session.value.data || session.value.isPending && cachedToken.value !== null
63
+ ),
64
+ isLoading: computed(
65
+ () => session.value.isPending && cachedToken.value === null
66
+ ),
67
+ fetchAccessToken,
68
+ authVersion
69
+ };
70
+ }
71
+ export function __resetUseAuthForTests() {
72
+ cachedToken.value = null;
73
+ cachedTokenVersion = null;
74
+ pendingToken = null;
75
+ pendingTokenVersion = null;
76
+ initialTokenUsed = false;
77
+ }
@@ -0,0 +1,245 @@
1
+ import type { InjectionKey } from 'vue';
2
+ import { BaseConvexClient } from 'convex/browser';
3
+ import type { AuthTokenFetcher, BaseConvexClientOptions, ConnectionState, MutationOptions as BaseMutationOptions, OptimisticUpdate, QueryJournal, QueryOptions, SubscribeOptions, PaginationStatus } from 'convex/browser';
4
+ import type { Watch as ConvexWatch } from 'convex/react';
5
+ import type { ArgsAndOptions, FunctionArgs, FunctionReference, FunctionReturnType, OptionalRestArgs, UserIdentityAttributes } from 'convex/server';
6
+ import type { Value } from 'convex/values';
7
+ export type { AuthTokenFetcher, ConnectionState, OptimisticUpdate, QueryJournal };
8
+ /**
9
+ * A live subscription to the output of a Convex query function.
10
+ *
11
+ * Returned by {@link ConvexVueClient.watchQuery}. Most component code should
12
+ * use the {@link useQuery} composable instead.
13
+ *
14
+ * Shape is derived from `convex/react` for API parity (see React client.ts).
15
+ * We extend to include internal `localQueryLogs` (present at runtime and in
16
+ * Convex source, omitted from some public .d.ts builds).
17
+ *
18
+ * @public
19
+ */
20
+ export interface Watch<T> extends ConvexWatch<T> {
21
+ /** @internal */
22
+ localQueryLogs(): string[] | undefined;
23
+ }
24
+ /**
25
+ * A watch on the output of a paginated Convex query function.
26
+ *
27
+ * @public
28
+ */
29
+ export interface PaginatedWatch<T> {
30
+ onUpdate(callback: () => void): () => void;
31
+ localQueryResult(): {
32
+ results: T[];
33
+ status: PaginationStatus;
34
+ loadMore: (numItems: number) => boolean;
35
+ } | undefined;
36
+ }
37
+ /**
38
+ * Options for {@link ConvexVueClient.watchQuery}.
39
+ *
40
+ * Pass a `journal` to resume a previously-saved query journal for faster
41
+ * initial hydration.
42
+ *
43
+ * @public
44
+ */
45
+ export interface WatchQueryOptions extends SubscribeOptions {
46
+ /** @internal */
47
+ componentPath?: string;
48
+ }
49
+ /**
50
+ * Options passed to {@link ConvexVueClient.mutation}.
51
+ *
52
+ * @public
53
+ */
54
+ export type VueMutationOptions<Args extends Record<string, Value>> = Omit<BaseMutationOptions, 'optimisticUpdate'> & {
55
+ optimisticUpdate?: OptimisticUpdate<Args> | undefined;
56
+ };
57
+ /**
58
+ * Construction options for {@link ConvexVueClient}.
59
+ *
60
+ * All options from `BaseConvexClientOptions` are accepted, such as
61
+ * `webSocketConstructor` (needed for testing in Node.js environments).
62
+ *
63
+ * @public
64
+ */
65
+ export interface ConvexVueClientOptions extends BaseConvexClientOptions {
66
+ }
67
+ export type ConvexLogger = Exclude<BaseConvexClientOptions['logger'], boolean | undefined>;
68
+ /**
69
+ * The primary Convex client for Vue and Nuxt applications.
70
+ *
71
+ * Manages a WebSocket connection to the Convex backend and exposes methods
72
+ * for subscribing to queries, running mutations, and executing actions.
73
+ * The underlying WebSocket is created lazily so that no connection is opened
74
+ * during server-side rendering.
75
+ *
76
+ * In a Nuxt app the client is automatically provided by the plugin and
77
+ * available via the {@link useConvex} composable or `useNuxtApp().$convex`.
78
+ *
79
+ * @public
80
+ */
81
+ export declare class ConvexVueClient {
82
+ private address;
83
+ private cachedSync?;
84
+ private listeners;
85
+ private options;
86
+ private closed;
87
+ private _logger;
88
+ private adminAuth?;
89
+ private fakeUserIdentity?;
90
+ constructor(address: string, options?: ConvexVueClientOptions);
91
+ /**
92
+ * The deployment URL this client is connected to.
93
+ */
94
+ get url(): string;
95
+ /**
96
+ * Lazily-instantiated underlying sync client.
97
+ *
98
+ * The WebSocket is not opened until this getter is first accessed, which
99
+ * prevents unnecessary connections during SSR.
100
+ *
101
+ * @internal
102
+ */
103
+ get sync(): BaseConvexClient;
104
+ /**
105
+ * Register a callback that returns the current auth token.
106
+ *
107
+ * Called by auth integrations (e.g. Better Auth) to pass tokens to the
108
+ * Convex backend. Supply an optional `onChange` to be notified when the
109
+ * server confirms the authenticated state.
110
+ */
111
+ setAuth(fetchToken: AuthTokenFetcher, onChange?: (isAuthenticated: boolean) => void): void;
112
+ /**
113
+ * Clear the current auth token and sign out from Convex.
114
+ *
115
+ * The underlying sync client is only contacted if it has already been
116
+ * instantiated; calling this before the first WebSocket connection is a
117
+ * safe no-op.
118
+ */
119
+ clearAuth(): void;
120
+ /** @internal */
121
+ setAdminAuth(token: string, identity?: UserIdentityAttributes): void;
122
+ /**
123
+ * Create a low-level {@link Watch} subscription to a Convex query.
124
+ *
125
+ * Prefer the {@link useQuery} composable for component code. Use
126
+ * `watchQuery` directly when you need fine-grained control over subscription
127
+ * lifecycle — e.g. in tests or outside a component setup context.
128
+ */
129
+ watchQuery<Query extends FunctionReference<'query'>>(query: Query, ...argsAndOptions: ArgsAndOptions<Query, WatchQueryOptions>): Watch<FunctionReturnType<Query>>;
130
+ /**
131
+ * Construct a new {@link PaginatedWatch} on a Convex paginated query function.
132
+ *
133
+ * **Not supported in the Vue port — use the {@link usePaginatedQuery}
134
+ * composable instead.**
135
+ *
136
+ * Convex's native paginated-subscription engine (`PaginatedQueryClient`,
137
+ * added in convex 1.40) is an internal module that is not part of the public
138
+ * `convex/*` exports, so a third-party package cannot instantiate it without
139
+ * reaching into Convex internals. The Vue port therefore handles pagination
140
+ * entirely in the composable layer: {@link usePaginatedQuery} walks pages via
141
+ * ordinary {@link watchQuery} subscriptions.
142
+ *
143
+ * This method is retained for structural and type parity with
144
+ * `ConvexReactClient.watchPaginatedQuery`. It is reachable only if a caller
145
+ * passes `paginationOptions` to {@link useConvexQueries} (the React-shaped
146
+ * escape hatch); doing so throws this error to fail loudly rather than
147
+ * silently mis-subscribe.
148
+ *
149
+ * @internal
150
+ */
151
+ watchPaginatedQuery<Query extends FunctionReference<'query'>>(_query: Query, _args: FunctionArgs<Query>, _options: any): PaginatedWatch<FunctionReturnType<Query>>;
152
+ /**
153
+ * Run a Convex mutation function.
154
+ *
155
+ * Returns a Promise that resolves to the mutation's return value once the
156
+ * write has been committed on the server. Accepts an optional
157
+ * `optimisticUpdate` to apply locally before the round-trip completes.
158
+ */
159
+ mutation<Mutation extends FunctionReference<'mutation'>>(mutation: Mutation, ...argsAndOptions: ArgsAndOptions<Mutation, VueMutationOptions<FunctionArgs<Mutation>>>): Promise<FunctionReturnType<Mutation>>;
160
+ /**
161
+ * Run a Convex action function.
162
+ *
163
+ * Actions run on the Convex backend and can call third-party services or
164
+ * perform work that goes beyond what mutations allow. Returns a Promise of
165
+ * the action's return value.
166
+ */
167
+ action<Action extends FunctionReference<'action'>>(action: Action, ...args: OptionalRestArgs<Action>): Promise<FunctionReturnType<Action>>;
168
+ /**
169
+ * Fetch a query result once as a Promise.
170
+ *
171
+ * Resolves immediately if a local result is already cached, otherwise waits
172
+ * for the next update. Prefer {@link useQuery} in component code where
173
+ * live reactivity is needed.
174
+ */
175
+ query<Query extends FunctionReference<'query'>>(query: Query, ...args: OptionalRestArgs<Query>): Promise<FunctionReturnType<Query>>;
176
+ /**
177
+ * Return the current WebSocket connection state.
178
+ *
179
+ * For a reactive version inside components, use
180
+ * {@link useConvexConnectionState}.
181
+ */
182
+ connectionState(): ConnectionState;
183
+ /**
184
+ * Register a callback invoked whenever the WebSocket connection state changes.
185
+ *
186
+ * Returns an unsubscribe function. In components, prefer
187
+ * {@link useConvexConnectionState} which handles cleanup automatically.
188
+ */
189
+ subscribeToConnectionState(cb: (connectionState: ConnectionState) => void): () => void;
190
+ /**
191
+ * Get the logger configured for this client.
192
+ *
193
+ * This is the same logger instance handed to the underlying
194
+ * {@link BaseConvexClient}, so client-level and SDK-level logging stay
195
+ * consistent.
196
+ */
197
+ get logger(): ConvexLogger;
198
+ /**
199
+ * Subscribe to a query briefly to warm the local cache.
200
+ *
201
+ * Useful for prefetching data before navigating to a new route. The
202
+ * subscription is automatically cancelled after `extendSubscriptionFor`
203
+ * milliseconds (default 5 000 ms).
204
+ *
205
+ * @example
206
+ * ```ts
207
+ * // Prefetch on hover before the user navigates
208
+ * convex.prewarmQuery({ query: api.tasks.list, args: {} })
209
+ * ```
210
+ */
211
+ prewarmQuery<Query extends FunctionReference<'query'>>(queryOptions: QueryOptions<Query> & {
212
+ extendSubscriptionFor?: number;
213
+ }): void;
214
+ /**
215
+ * Close the WebSocket and cancel all active subscriptions.
216
+ *
217
+ * Should be called when the client is no longer needed (e.g. during plugin
218
+ * teardown). The client cannot be reused after this call.
219
+ */
220
+ close(): Promise<void>;
221
+ private transition;
222
+ }
223
+ /**
224
+ * Vue injection key for the {@link ConvexVueClient}.
225
+ *
226
+ * Used with `provide` / `inject` to pass the client down the component tree.
227
+ * The Nuxt plugin registers the client automatically; you only need this key
228
+ * when writing manual tests or custom providers.
229
+ *
230
+ * @public
231
+ */
232
+ export declare const ConvexClientKey: InjectionKey<ConvexVueClient>;
233
+ /**
234
+ * Access the {@link ConvexVueClient} from any Vue composable or component.
235
+ *
236
+ * Reads the client that was registered by the Nuxt plugin (or a manual
237
+ * `provide` call). Throws if called outside a component tree that has a
238
+ * client provided.
239
+ *
240
+ * @returns The active {@link ConvexVueClient} instance.
241
+ * @throws If no client has been provided in the component tree.
242
+ *
243
+ * @public
244
+ */
245
+ export declare function useConvex(): ConvexVueClient;
@@ -0,0 +1,341 @@
1
+ import { inject } from "vue";
2
+ import { BaseConvexClient } from "convex/browser";
3
+ import dedent from "dedent";
4
+ import { getFunctionName } from "convex/server";
5
+ const noopLogger = {
6
+ logVerbose() {
7
+ },
8
+ log() {
9
+ },
10
+ warn() {
11
+ },
12
+ error() {
13
+ }
14
+ };
15
+ function defaultLogger(verbose) {
16
+ return {
17
+ logVerbose: (...args) => {
18
+ if (verbose) console.debug(...args);
19
+ },
20
+ log: (...args) => console.log(...args),
21
+ warn: (...args) => console.warn(...args),
22
+ error: (...args) => console.error(...args)
23
+ };
24
+ }
25
+ export class ConvexVueClient {
26
+ address;
27
+ cachedSync;
28
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
29
+ listeners;
30
+ options;
31
+ closed = false;
32
+ _logger;
33
+ adminAuth;
34
+ fakeUserIdentity;
35
+ constructor(address, options) {
36
+ if (address === void 0) {
37
+ throw new Error(dedent`
38
+ No address provided to ConvexVueClient.\n
39
+ If trying to deploy to production, make sure to follow all the instructions found at https://docs.convex.dev/production/hosting/\n
40
+ If running locally, make sure to run \`convex dev\` and ensure the .env.local file is populated.
41
+ `);
42
+ }
43
+ if (typeof address !== "string") {
44
+ throw new TypeError(
45
+ `ConvexVueClient requires a URL like 'https://happy-otter-123.convex.cloud', received ${typeof address}.`
46
+ );
47
+ }
48
+ if (!address.includes("://")) {
49
+ throw new Error("Provided address was not an absolute URL.");
50
+ }
51
+ this.address = address;
52
+ this.listeners = /* @__PURE__ */ new Map();
53
+ this._logger = options?.logger === false ? noopLogger : options?.logger !== true && options?.logger ? options.logger : defaultLogger(options?.verbose ?? false);
54
+ this.options = { ...options, logger: this._logger };
55
+ }
56
+ /**
57
+ * The deployment URL this client is connected to.
58
+ */
59
+ get url() {
60
+ return this.address;
61
+ }
62
+ /**
63
+ * Lazily-instantiated underlying sync client.
64
+ *
65
+ * The WebSocket is not opened until this getter is first accessed, which
66
+ * prevents unnecessary connections during SSR.
67
+ *
68
+ * @internal
69
+ */
70
+ get sync() {
71
+ if (this.closed) {
72
+ throw new Error("ConvexVueClient has already been closed.");
73
+ }
74
+ if (this.cachedSync) {
75
+ return this.cachedSync;
76
+ }
77
+ this.cachedSync = new BaseConvexClient(
78
+ this.address,
79
+ (updatedQueries) => this.transition(updatedQueries),
80
+ this.options
81
+ );
82
+ if (this.adminAuth) {
83
+ const sync = this.cachedSync;
84
+ sync.setAdminAuth(this.adminAuth, this.fakeUserIdentity);
85
+ }
86
+ return this.cachedSync;
87
+ }
88
+ /**
89
+ * Register a callback that returns the current auth token.
90
+ *
91
+ * Called by auth integrations (e.g. Better Auth) to pass tokens to the
92
+ * Convex backend. Supply an optional `onChange` to be notified when the
93
+ * server confirms the authenticated state.
94
+ */
95
+ setAuth(fetchToken, onChange) {
96
+ if (typeof fetchToken === "string") {
97
+ throw new TypeError(
98
+ "Passing a string to ConvexVueClient.setAuth is no longer supported, please upgrade to passing in an async function to handle reauthentication."
99
+ );
100
+ }
101
+ this.sync.setAuth(
102
+ fetchToken,
103
+ onChange ?? (() => {
104
+ })
105
+ );
106
+ }
107
+ /**
108
+ * Clear the current auth token and sign out from Convex.
109
+ *
110
+ * The underlying sync client is only contacted if it has already been
111
+ * instantiated; calling this before the first WebSocket connection is a
112
+ * safe no-op.
113
+ */
114
+ clearAuth() {
115
+ this.sync.clearAuth();
116
+ }
117
+ /** @internal */
118
+ setAdminAuth(token, identity) {
119
+ this.adminAuth = token;
120
+ this.fakeUserIdentity = identity;
121
+ if (this.closed) {
122
+ throw new Error("ConvexVueClient has already been closed.");
123
+ }
124
+ if (this.cachedSync) {
125
+ const sync = this.cachedSync;
126
+ sync.setAdminAuth(token, identity);
127
+ }
128
+ }
129
+ /**
130
+ * Create a low-level {@link Watch} subscription to a Convex query.
131
+ *
132
+ * Prefer the {@link useQuery} composable for component code. Use
133
+ * `watchQuery` directly when you need fine-grained control over subscription
134
+ * lifecycle — e.g. in tests or outside a component setup context.
135
+ */
136
+ watchQuery(query, ...argsAndOptions) {
137
+ const [args, options] = argsAndOptions;
138
+ const name = getFunctionName(query);
139
+ return {
140
+ onUpdate: (callback) => {
141
+ const { queryToken, unsubscribe } = this.sync.subscribe(
142
+ name,
143
+ args,
144
+ options
145
+ );
146
+ const currentListeners = this.listeners.get(queryToken);
147
+ if (currentListeners !== void 0) {
148
+ currentListeners.add(callback);
149
+ } else {
150
+ this.listeners.set(queryToken, /* @__PURE__ */ new Set([callback]));
151
+ }
152
+ return () => {
153
+ if (this.closed) return;
154
+ const listeners = this.listeners.get(queryToken);
155
+ listeners.delete(callback);
156
+ if (listeners.size === 0) {
157
+ this.listeners.delete(queryToken);
158
+ }
159
+ unsubscribe();
160
+ };
161
+ },
162
+ localQueryResult: () => {
163
+ if (this.cachedSync) {
164
+ return this.cachedSync.localQueryResult(name, args);
165
+ }
166
+ return void 0;
167
+ },
168
+ localQueryLogs: () => {
169
+ if (this.cachedSync) {
170
+ const sync = this.cachedSync;
171
+ return sync.localQueryLogs(name, args);
172
+ }
173
+ return void 0;
174
+ },
175
+ journal: () => {
176
+ if (this.cachedSync) {
177
+ return this.cachedSync.queryJournal(name, args);
178
+ }
179
+ return void 0;
180
+ }
181
+ };
182
+ }
183
+ /**
184
+ * Construct a new {@link PaginatedWatch} on a Convex paginated query function.
185
+ *
186
+ * **Not supported in the Vue port — use the {@link usePaginatedQuery}
187
+ * composable instead.**
188
+ *
189
+ * Convex's native paginated-subscription engine (`PaginatedQueryClient`,
190
+ * added in convex 1.40) is an internal module that is not part of the public
191
+ * `convex/*` exports, so a third-party package cannot instantiate it without
192
+ * reaching into Convex internals. The Vue port therefore handles pagination
193
+ * entirely in the composable layer: {@link usePaginatedQuery} walks pages via
194
+ * ordinary {@link watchQuery} subscriptions.
195
+ *
196
+ * This method is retained for structural and type parity with
197
+ * `ConvexReactClient.watchPaginatedQuery`. It is reachable only if a caller
198
+ * passes `paginationOptions` to {@link useConvexQueries} (the React-shaped
199
+ * escape hatch); doing so throws this error to fail loudly rather than
200
+ * silently mis-subscribe.
201
+ *
202
+ * @internal
203
+ */
204
+ watchPaginatedQuery(_query, _args, _options) {
205
+ throw new Error(
206
+ "ConvexVueClient.watchPaginatedQuery is not supported: Convex's internal PaginatedQueryClient is not part of the public API. Use the `usePaginatedQuery` composable for paginated queries."
207
+ );
208
+ }
209
+ /**
210
+ * Run a Convex mutation function.
211
+ *
212
+ * Returns a Promise that resolves to the mutation's return value once the
213
+ * write has been committed on the server. Accepts an optional
214
+ * `optimisticUpdate` to apply locally before the round-trip completes.
215
+ */
216
+ mutation(mutation, ...argsAndOptions) {
217
+ const [args, options] = argsAndOptions;
218
+ const name = getFunctionName(mutation);
219
+ return this.sync.mutation(name, args, options);
220
+ }
221
+ /**
222
+ * Run a Convex action function.
223
+ *
224
+ * Actions run on the Convex backend and can call third-party services or
225
+ * perform work that goes beyond what mutations allow. Returns a Promise of
226
+ * the action's return value.
227
+ */
228
+ action(action, ...args) {
229
+ const name = getFunctionName(action);
230
+ return this.sync.action(name, ...args);
231
+ }
232
+ /**
233
+ * Fetch a query result once as a Promise.
234
+ *
235
+ * Resolves immediately if a local result is already cached, otherwise waits
236
+ * for the next update. Prefer {@link useQuery} in component code where
237
+ * live reactivity is needed.
238
+ */
239
+ query(query, ...args) {
240
+ const watch = this.watchQuery(query, ...args);
241
+ const existingResult = watch.localQueryResult();
242
+ if (existingResult !== void 0) {
243
+ return Promise.resolve(existingResult);
244
+ }
245
+ return new Promise((resolve, reject) => {
246
+ const unsubscribe = watch.onUpdate(() => {
247
+ unsubscribe();
248
+ try {
249
+ resolve(watch.localQueryResult());
250
+ } catch (e) {
251
+ reject(e);
252
+ }
253
+ });
254
+ });
255
+ }
256
+ /**
257
+ * Return the current WebSocket connection state.
258
+ *
259
+ * For a reactive version inside components, use
260
+ * {@link useConvexConnectionState}.
261
+ */
262
+ connectionState() {
263
+ return this.sync.connectionState();
264
+ }
265
+ /**
266
+ * Register a callback invoked whenever the WebSocket connection state changes.
267
+ *
268
+ * Returns an unsubscribe function. In components, prefer
269
+ * {@link useConvexConnectionState} which handles cleanup automatically.
270
+ */
271
+ subscribeToConnectionState(cb) {
272
+ return this.sync.subscribeToConnectionState(cb);
273
+ }
274
+ /**
275
+ * Get the logger configured for this client.
276
+ *
277
+ * This is the same logger instance handed to the underlying
278
+ * {@link BaseConvexClient}, so client-level and SDK-level logging stay
279
+ * consistent.
280
+ */
281
+ get logger() {
282
+ return this._logger;
283
+ }
284
+ /**
285
+ * Subscribe to a query briefly to warm the local cache.
286
+ *
287
+ * Useful for prefetching data before navigating to a new route. The
288
+ * subscription is automatically cancelled after `extendSubscriptionFor`
289
+ * milliseconds (default 5 000 ms).
290
+ *
291
+ * @example
292
+ * ```ts
293
+ * // Prefetch on hover before the user navigates
294
+ * convex.prewarmQuery({ query: api.tasks.list, args: {} })
295
+ * ```
296
+ */
297
+ prewarmQuery(queryOptions) {
298
+ const extendSubscriptionFor = queryOptions.extendSubscriptionFor ?? 5e3;
299
+ const watch = this.watchQuery(queryOptions.query, queryOptions.args);
300
+ const unsubscribe = watch.onUpdate(() => {
301
+ });
302
+ setTimeout(unsubscribe, extendSubscriptionFor);
303
+ }
304
+ /**
305
+ * Close the WebSocket and cancel all active subscriptions.
306
+ *
307
+ * Should be called when the client is no longer needed (e.g. during plugin
308
+ * teardown). The client cannot be reused after this call.
309
+ */
310
+ async close() {
311
+ this.closed = true;
312
+ this.listeners = /* @__PURE__ */ new Map();
313
+ if (this.cachedSync) {
314
+ const sync = this.cachedSync;
315
+ this.cachedSync = void 0;
316
+ await sync.close();
317
+ }
318
+ }
319
+ transition(updatedQueries) {
320
+ for (const queryToken of updatedQueries) {
321
+ const callbacks = this.listeners.get(queryToken);
322
+ if (callbacks) {
323
+ for (const callback of callbacks) {
324
+ callback();
325
+ }
326
+ }
327
+ }
328
+ }
329
+ }
330
+ export const ConvexClientKey = Symbol("ConvexVueClient");
331
+ export function useConvex() {
332
+ const client = inject(ConvexClientKey, void 0);
333
+ if (!client) {
334
+ throw new Error(dedent`
335
+ Could not find Convex client! \`useConvex\` must be used in a component tree
336
+ where the Convex client has been provided.
337
+ In Nuxt, ensure the nuxt-backend module is installed.
338
+ `);
339
+ }
340
+ return client;
341
+ }
@@ -0,0 +1,45 @@
1
+ import type { FunctionReference, FunctionReturnType, OptionalRestArgs } from 'convex/server';
2
+ /**
3
+ * An interface to execute a Convex action on the server.
4
+ *
5
+ * @public
6
+ */
7
+ export interface VueAction<Action extends FunctionReference<'action'>> {
8
+ /** Execute the action, returning a Promise of its return value. */
9
+ (...args: OptionalRestArgs<Action>): Promise<FunctionReturnType<Action>>;
10
+ }
11
+ /**
12
+ * Construct a new {@link VueAction}.
13
+ *
14
+ * Returns a function that you can call to execute a Convex action.
15
+ * The returned function is stable (same reference) for the lifetime of the composable.
16
+ *
17
+ * Actions can call third-party APIs and perform side effects.
18
+ *
19
+ * @example
20
+ * ```vue
21
+ * <script setup lang="ts">
22
+ * import { useAction } from '#imports'
23
+ * import { api } from '#backend/api'
24
+ *
25
+ * const generate = useAction(api.ai.generateSummary)
26
+ *
27
+ * async function handleClick() {
28
+ * try {
29
+ * const summary = await generate({ text: 'Some long text...' })
30
+ * console.log(summary)
31
+ * } catch (error) {
32
+ * console.error('Action failed:', error)
33
+ * }
34
+ * }
35
+ * </script>
36
+ * ```
37
+ *
38
+ * @param action - A FunctionReference for the public action to run.
39
+ * @returns The {@link VueAction} object.
40
+ *
41
+ * @public
42
+ */
43
+ export declare function useAction<Action extends FunctionReference<'action'>>(action: Action): VueAction<Action>;
44
+ /** @public */
45
+ export declare const useConvexAction: typeof useAction;